Repository navigation
Expand file tree
/
Copy pathengine-transaction-same-origin.test.ts
More file actions
865 lines (754 loc) · 40.3 KB
/
Copy pathengine-transaction-same-origin.test.ts
File metadata and controls
865 lines (754 loc) · 40.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
//
// #5351 + #5696 point 2 — the SAME-ORIGIN transaction gate, and the two answers
// the 2026-08-06 maintainer ruling gave it.
//
// The defect (#5351, reproduced independently in PR #5724): `buildDriverOptions`
// lifted the ambient transaction handle onto EVERY driver call with no idea
// which driver was about to receive it. A write routed elsewhere — by
// `setDatasourceMapping`, by an explicit `datasource:` binding, or by ADR-0057
// §3.6 lifecycle-class separation — was handed the DEFAULT driver's handle and
// executed on the wrong connection. On knex/SQLite that is `no such table`
// against a database that never held the object, which is how every compliance
// audit row written inside a transaction was being lost: 52 insert attempts, 50
// successes, and the 2 failures were exactly the 2 with a `trxClient.query`
// frame in their stack.
//
// The ruling is two answers, because the two kinds of write fail in opposite
// directions:
//
// BUSINESS writes are REFUSED (#5696 point 2) — no two-phase commit exists,
// so the honest move is to make the caller choose instead of committing part
// of a "unit of work" they can neither see nor undo.
//
// APPEND-ONLY SYSTEM LEDGERS are CARVED OUT (#5351 plan A) — audit /
// telemetry / event rows execute OUTSIDE the transaction, on their own
// connection, and therefore SURVIVE a rollback. The orphan row is the
// deliberate cost: for an append-only ledger a spurious row is reconcilable,
// while a missing row for a write that DID commit is an unrecoverable
// compliance hole.
//
// Why they had to land together: refusal alone would be "loud but not fixed".
// An audit hook's try/catch eats the refusal and logs it, and the compliance
// row is lost exactly as before — only now with a different log line.
import { describe, it, expect } from 'vitest';
import type { Hook } from '@objectstack/spec/data';
import { ObjectQL, ScopedContext } from './engine.js';
import { bindHooksToEngine } from './hook-binder.js';
import { CrossDatasourceTransactionWriteError } from './transaction-errors.js';
import { openTransactionKind } from './open-transaction.js';
interface Recorded {
level: 'debug' | 'info' | 'warn' | 'error';
message: string;
args: unknown[];
}
function recordingLogger() {
const records: Recorded[] = [];
const push = (level: Recorded['level']) => (message: string, ...args: unknown[]) =>
void records.push({ level, message: String(message), args });
return {
records,
logger: { debug: push('debug'), info: push('info'), warn: push('warn'), error: push('error') },
at(level: Recorded['level']) {
return records.filter((r) => r.level === level);
},
};
}
/**
* The error a call rejected with, typed as `E`.
*
* `promise.catch((e) => e as E)` types the result as `E | <resolved type>`, so
* every property read on it is a type error. This narrows to the rejection and
* fails loudly if the call did NOT reject — which a bare `.catch()` would
* silently let through as a passing test.
*/
async function rejection<E>(p: Promise<unknown>): Promise<E> {
try {
await p;
} catch (e) {
return e as E;
}
throw new Error('expected the call to reject, but it resolved');
}
function meta(r: Recorded): Record<string, unknown> {
return (r.args.find((a) => a !== undefined && typeof a === 'object' && !(a instanceof Error)) ??
{}) as Record<string, unknown>;
}
/** One write the driver double saw — the shape its `writes` array carries. */
type RecordedWrite = { object: string; op: 'create' | 'update' | 'delete'; transaction: unknown };
function makeDriver(name: string) {
const writes: RecordedWrite[] = [];
const reads: Array<{ object: string; transaction: unknown }> = [];
const rows = new Map<string, Record<string, unknown>>();
let nextId = 0;
const driver: any = {
name,
version: '0.0.0',
supports: {},
writes,
reads,
rows,
async connect() {},
async disconnect() {},
async checkHealth() { return true; },
async execute() { return null; },
async find(object: string, _ast: any, options: any) {
reads.push({ object, transaction: options?.transaction });
return Array.from(rows.values());
},
async findOne(object: string, ast: any, options: any) {
reads.push({ object, transaction: options?.transaction });
const id = ast?.where?.find?.((c: any) => c?.field === 'id')?.value;
if (id !== undefined) return rows.get(String(id)) ?? null;
for (const r of rows.values()) return r;
return null;
},
async create(object: string, data: Record<string, unknown>, options: any) {
writes.push({ object, op: 'create', transaction: options?.transaction });
nextId += 1;
const id = (data.id as string) ?? `${name}_${nextId}`;
const row = { ...data, id };
rows.set(id, row);
return row;
},
async update(object: string, id: string, data: Record<string, unknown>, options: any) {
writes.push({ object, op: 'update', transaction: options?.transaction });
const row = { ...rows.get(String(id)), ...data, id };
rows.set(String(id), row);
return row;
},
async delete(object: string, id: string, options: any) {
writes.push({ object, op: 'delete', transaction: options?.transaction });
return rows.delete(String(id));
},
async count() { return 0; },
async bulkCreate(object: string, batch: Record<string, unknown>[]) {
return Promise.all(batch.map((r) => this.create(object, r, undefined)));
},
async bulkUpdate() { return []; },
async bulkDelete() {},
async syncSchema() {},
// A transaction handle is a per-connection object. The double names its
// driver so a handle arriving at the WRONG driver is visible in one glance —
// which is precisely the defect #5351 measured.
beginTransaction: async () => ({ __trx: name }),
commit: async () => {},
rollback: async () => {},
};
return driver;
}
/**
* The real #5351 topology: a primary business datasource plus the dedicated
* `telemetry` datasource ADR-0057 §3.6 routes lifecycle-classed system data to,
* plus a plain business object routed away by an ordinary mapping rule.
*/
async function splitEngine() {
const rec = recordingLogger();
const engine = new ObjectQL({ logger: rec.logger } as any);
const primary = makeDriver('primary');
const telemetry = makeDriver(ObjectQL.LIFECYCLE_DATASOURCE);
const ledgerDb = makeDriver('ledger_db');
engine.registerDriver(telemetry);
engine.registerDriver(ledgerDb);
engine.registerDriver(primary, true); // default
await engine.init();
// `ledger` is an ordinary BUSINESS object that a mapping rule routes away.
engine.setDatasourceMapping([{ objectPattern: 'ledger', datasource: 'ledger_db' }]);
engine.registry.registerObject({ name: 'thing', fields: { name: { type: 'text' } } }, '__test__');
engine.registry.registerObject({ name: 'ledger', fields: { name: { type: 'text' } } }, '__test__');
// The three append-only system ledgers, routed by lifecycle class alone.
engine.registry.registerObject({
name: 'sys_audit_log',
lifecycle: { class: 'audit', retention: { maxAge: '90d' } },
fields: { action: { type: 'text' } },
} as any, '__test__');
engine.registry.registerObject({
name: 'sys_activity',
lifecycle: { class: 'telemetry', retention: { maxAge: '14d' } },
fields: { action: { type: 'text' } },
} as any, '__test__');
engine.registry.registerObject({
name: 'sys_bus_event',
lifecycle: { class: 'event', ttl: { field: 'created_at', expireAfter: '6h' } },
fields: { action: { type: 'text' } },
} as any, '__test__');
const carveOutNotes = () =>
rec.at('debug').filter((r) => r.message.includes('executing it OUTSIDE the transaction'));
return { rec, engine, primary, telemetry, ledgerDb, carveOutNotes };
}
// ---------------------------------------------------------------------------
// (a) The system-ledger carve-out — the compliance row actually lands
// ---------------------------------------------------------------------------
describe('an audit-shaped write inside a cross-origin transaction LANDS, outside it (#5351)', () => {
it('reaches the telemetry datasource with NO foreign transaction handle', async () => {
const { engine, telemetry, primary } = await splitEngine();
await engine.transaction(async () => {
await engine.insert('thing', { name: 'business row' });
// The shape of an `afterInsert` audit hook: an ordinary insert of an
// audit-class object, made by an author who knows nothing about routing.
await engine.insert('sys_audit_log', { action: 'insert thing' });
});
// It landed — this is the whole point. Before #5351 this write was handed
// `primary`'s handle and, on a real SQL driver, never reached this store.
expect(telemetry.writes).toHaveLength(1);
expect(telemetry.writes[0]).toMatchObject({ object: 'sys_audit_log', op: 'create' });
// And it landed WITHOUT another driver's connection. Asserting `undefined`
// rather than "not primary's": there is no handle this driver could
// legitimately have been given, since the engine opened no transaction here.
expect(telemetry.writes[0].transaction).toBeUndefined();
// The business write is unaffected and still rides its own transaction.
expect(primary.writes).toHaveLength(1);
expect(primary.writes[0].transaction).toEqual({ __trx: 'primary' });
});
it('covers all three system-ledger classes, not just audit', async () => {
const { engine, telemetry } = await splitEngine();
await engine.transaction(async () => {
await engine.insert('sys_audit_log', { action: 'a' });
await engine.insert('sys_activity', { action: 'b' });
await engine.insert('sys_bus_event', { action: 'c' });
});
expect(telemetry.writes.map((w: RecordedWrite) => w.object)).toEqual(['sys_audit_log', 'sys_activity', 'sys_bus_event']);
expect(telemetry.writes.every((w: RecordedWrite) => w.transaction === undefined)).toBe(true);
});
it('SURVIVES the rollback of the business transaction — the orphan row, pinned', async () => {
const { engine, telemetry, primary } = await splitEngine();
let rolledBack = false;
primary.rollback = async () => { rolledBack = true; };
await expect(
engine.transaction(async () => {
await engine.insert('thing', { name: 'doomed' });
await engine.insert('sys_audit_log', { action: 'insert thing' });
throw new Error('business failure');
}),
).rejects.toThrow('business failure');
expect(rolledBack).toBe(true);
// The decided cost of plan A, asserted rather than left implicit: an audit
// row describing a write that was undone. For an append-only compliance
// ledger this is the correct direction of error — a spurious row can be
// reconciled against the business data, a MISSING row for a write that did
// commit cannot be recovered at all. ADR-0067/ADR-0119 record it.
expect(telemetry.writes).toHaveLength(1);
expect(telemetry.writes[0]).toMatchObject({ object: 'sys_audit_log' });
});
it('notes the carve-out at debug — once per transaction per datasource', async () => {
const { engine, carveOutNotes, rec } = await splitEngine();
await engine.transaction(async () => {
await engine.insert('sys_audit_log', { action: 'a' });
await engine.insert('sys_audit_log', { action: 'b' });
await engine.insert('sys_activity', { action: 'c' });
});
const notes = carveOutNotes();
expect(notes).toHaveLength(1);
expect(notes[0].message).toContain("insert of 'sys_audit_log'");
expect(notes[0].message).toContain('SURVIVE a rollback');
expect(meta(notes[0])).toMatchObject({
object: 'sys_audit_log',
operation: 'insert',
datasource: ObjectQL.LIFECYCLE_DATASOURCE,
transactionDatasource: 'primary',
});
// NOT `warn`, NOT `error`. This is now DECLARED behaviour that fires on
// every audited write of every transaction in a lifecycle-split deployment;
// AGENTS.md's judgment question asks whether something claimed persisted
// has failed to land, and here it lands. Escalating it would train readers
// to skim the levels that carry real durability failures.
expect(rec.at('error')).toHaveLength(0);
expect(rec.at('warn')).toHaveLength(0);
});
it('re-notes in a NEW transaction — the budget is per transaction', async () => {
const { engine, carveOutNotes } = await splitEngine();
await engine.transaction(async () => { await engine.insert('sys_audit_log', { action: 'a' }); });
await engine.transaction(async () => { await engine.insert('sys_audit_log', { action: 'b' }); });
expect(carveOutNotes()).toHaveLength(2);
});
it('carves out update and delete of a system ledger too, not just insert', async () => {
const { engine, telemetry } = await splitEngine();
const seeded = await engine.insert('sys_audit_log', { action: 'seed' });
await engine.transaction(async () => {
await engine.update('sys_audit_log', { id: seeded.id, action: 'amended' });
await engine.delete('sys_audit_log', { where: { id: seeded.id } } as any);
});
const inTxn = telemetry.writes.slice(1) as RecordedWrite[];
expect(inTxn.map((w) => w.op)).toEqual(['update', 'delete']);
expect(inTxn.every((w) => w.transaction === undefined)).toBe(true);
});
});
// ---------------------------------------------------------------------------
// (b) Business writes across drivers — refused, by name
// ---------------------------------------------------------------------------
describe('a BUSINESS write across drivers inside a transaction is refused (#5696 point 2)', () => {
it('throws CrossDatasourceTransactionWriteError naming both datasources and the fix', async () => {
const { engine } = await splitEngine();
const err = await rejection<CrossDatasourceTransactionWriteError>(
engine.transaction(async () => { await engine.insert('ledger', { name: 'NOT covered' }); }),
);
expect(err).toBeInstanceOf(CrossDatasourceTransactionWriteError);
expect(err.code).toBe('ERR_CROSS_DATASOURCE_TRANSACTION_WRITE');
expect(err).toMatchObject({
object: 'ledger',
operation: 'insert',
datasource: 'ledger_db',
transactionDatasource: 'primary',
});
// A refusal owes the caller the remedy — both routes out, concretely.
expect(err.message).toContain('datasourceMapping');
expect(err.message).toContain('split the work into per-datasource units');
expect(err.message).toContain('Nothing was written.');
});
it('writes nothing, on either datasource, and rolls the transaction back', async () => {
const { engine, primary, ledgerDb } = await splitEngine();
let rolledBack = false;
primary.rollback = async () => { rolledBack = true; };
await expect(
engine.transaction(async () => {
await engine.insert('thing', { name: 'first' });
await engine.insert('ledger', { name: 'refused' });
}),
).rejects.toBeInstanceOf(CrossDatasourceTransactionWriteError);
// Refused before any hook, default or validation ran — so the cross-driver
// store is untouched, and the covered write is undone by the rollback the
// rejection triggers. This is the difference from the pre-v17 behaviour:
// the caller now learns before a partial commit exists, not after.
expect(ledgerDb.writes).toHaveLength(0);
expect(rolledBack).toBe(true);
});
it('refuses update and delete too', async () => {
const { engine } = await splitEngine();
const seeded = await engine.insert('ledger', { name: 'seed' });
await expect(
engine.transaction(async () => { await engine.update('ledger', { id: seeded.id, name: 'x' }); }),
).rejects.toMatchObject({ operation: 'update', code: 'ERR_CROSS_DATASOURCE_TRANSACTION_WRITE' });
await expect(
engine.transaction(async () => { await engine.delete('ledger', { where: { id: seeded.id } } as any); }),
).rejects.toMatchObject({ operation: 'delete', code: 'ERR_CROSS_DATASOURCE_TRANSACTION_WRITE' });
});
it('refuses from a nested transaction() that JOINED the outer one (ADR-0067 D2)', async () => {
const { engine } = await splitEngine();
// A joined nested call opens nothing — it runs in the outer scope, so the
// OUTER owner is what the write is measured against. Just as uncovered as
// at the top level, and refused the same way.
await expect(
engine.transaction(async () => {
await engine.transaction(async () => { await engine.insert('ledger', { name: 'nested' }); });
}),
).rejects.toMatchObject({ transactionDatasource: 'primary' });
});
it('refuses from ScopedContext.transaction too (ctx.api.transaction in a hook body)', async () => {
const { engine } = await splitEngine();
const scoped = (engine as any).createContext({ userId: 'u1' }) as ScopedContext;
await expect(
scoped.transaction(async () => { await engine.insert('ledger', { name: 'from sandbox' }); }),
).rejects.toBeInstanceOf(CrossDatasourceTransactionWriteError);
});
it('refuses from a ScopedContext.transaction that JOINED the outer one, against the OUTER owner (#6168)', async () => {
const { engine } = await splitEngine();
// #6168 made `ctx.api.transaction` join an ambient transaction instead of
// opening a second one. The joined callback is handed the OUTER handle, so
// the same-origin gate attributes it to the outer scope by identity
// (`transactionCoversDriverFor`) and judges the write exactly as it judges
// a write made directly in the outer call: refused, and refused naming the
// OUTER datasource. The join changes which transaction the write is in, not
// how #5351 measures it — there is no new interaction between the two.
const err = await rejection<CrossDatasourceTransactionWriteError>(
engine.transaction(async (outerCtx: any) => {
const scoped = (engine as any).createContext({
userId: 'u1',
transaction: outerCtx.transaction,
}) as ScopedContext;
await scoped.transaction(async (trxCtx: any) => {
await trxCtx.object('ledger').insert({ name: 'joined' });
});
}),
);
expect(err).toBeInstanceOf(CrossDatasourceTransactionWriteError);
expect(err.transactionDatasource).toBe('primary');
expect(err.operation).toBe('insert');
});
it('carves an audit row out of a JOINED ScopedContext.transaction the same way (#6168)', async () => {
const { engine, telemetry, carveOutNotes } = await splitEngine();
// The carve-out half of the same ruling, measured through the joined
// surface: a system ledger still executes OUTSIDE the transaction, on its
// own connection, with no foreign handle.
await engine.transaction(async (outerCtx: any) => {
const scoped = (engine as any).createContext({
userId: 'u1',
transaction: outerCtx.transaction,
}) as ScopedContext;
await scoped.transaction(async (trxCtx: any) => {
await trxCtx.object('sys_audit_log').insert({ action: 'joined audit' });
});
});
expect(telemetry.writes).toHaveLength(1);
expect(telemetry.writes[0].transaction).toBeUndefined();
expect(carveOutNotes()).toHaveLength(1);
});
it('does NOT refuse a mapped write made outside any transaction — no false positive', async () => {
const { engine, ledgerDb } = await splitEngine();
// Routing a business object to another datasource is normal and supported.
// It is only a problem while a transaction is open and claiming to cover
// the work.
const seeded = await engine.insert('ledger', { name: 'plain write' });
await engine.update('ledger', { id: seeded.id, name: 'renamed' });
await engine.delete('ledger', { where: { id: seeded.id } } as any);
expect(ledgerDb.writes.map((w: RecordedWrite) => w.op)).toEqual(['create', 'update', 'delete']);
});
it('stays quiet after the transaction closes — the scope does not leak', async () => {
const { engine, ledgerDb } = await splitEngine();
await engine.transaction(async () => { await engine.insert('thing', { name: 'covered' }); });
await expect(engine.insert('ledger', { name: 'after' })).resolves.toBeTruthy();
expect(ledgerDb.writes).toHaveLength(1);
});
});
// ---------------------------------------------------------------------------
// Reads: never the wrong connection, never refused
// ---------------------------------------------------------------------------
describe('a cross-driver READ inside a transaction loses the handle but is not refused (#5351)', () => {
it('does not hand the other driver the transaction handle', async () => {
const { engine, ledgerDb, primary } = await splitEngine();
await engine.transaction(async () => {
await engine.find('thing', {});
await engine.find('ledger', {});
});
// A read has no atomicity claim to break, so refusing it would only break
// legitimate work (reference checks against a routed object, expand reads).
// But it must not run on a connection its driver does not own — that was
// the same wrong-connection defect, one verb over.
//
// Both lengths asserted first: `reads.at(-1)?.transaction` on an EMPTY
// array is `undefined`, so the handle assertion alone would pass for the
// reason "no read happened" rather than "the read was clean".
expect(ledgerDb.reads).toHaveLength(1);
expect(primary.reads).toHaveLength(1);
expect(ledgerDb.reads[0].transaction).toBeUndefined();
expect(primary.reads[0].transaction).toEqual({ __trx: 'primary' });
});
});
// ---------------------------------------------------------------------------
// (e) Single-datasource deployments: nothing changes at all
// ---------------------------------------------------------------------------
describe('a same-origin (single datasource) transaction is untouched (#5351 regression guard)', () => {
async function singleEngine() {
const rec = recordingLogger();
const engine = new ObjectQL({ logger: rec.logger } as any);
const primary = makeDriver('primary');
engine.registerDriver(primary, true);
await engine.init();
engine.registry.registerObject({ name: 'thing', fields: { name: { type: 'text' } } }, '__test__');
// Audit-classed, but with NO telemetry datasource registered it resolves to
// the default driver like everything else — ADR-0057 §3.6 is opt-in by the
// datasource's existence. The carve-out must not fire on it.
engine.registry.registerObject({
name: 'sys_audit_log',
lifecycle: { class: 'audit', retention: { maxAge: '90d' } },
fields: { action: { type: 'text' } },
} as any, '__test__');
return { rec, engine, primary };
}
it('every write still rides the one transaction, audit rows included', async () => {
const { engine, primary, rec } = await singleEngine();
await engine.transaction(async () => {
await engine.insert('thing', { name: 'a' });
await engine.insert('sys_audit_log', { action: 'insert thing' });
});
expect(primary.writes).toHaveLength(2);
expect(primary.writes.every((w: RecordedWrite) => JSON.stringify(w.transaction) === JSON.stringify({ __trx: 'primary' }))).toBe(true);
// No carve-out, no refusal, and nothing said: the gate is invisible to the
// deployments that make up the overwhelming majority.
expect(rec.at('error')).toHaveLength(0);
expect(rec.at('warn')).toHaveLength(0);
expect(rec.at('debug').filter((r) => r.message.includes('OUTSIDE the transaction'))).toHaveLength(0);
});
it('rolls audit rows back with the business rows, exactly as before', async () => {
const { engine, primary } = await singleEngine();
let rolledBack = false;
primary.rollback = async () => { rolledBack = true; };
await expect(
engine.transaction(async () => {
await engine.insert('sys_audit_log', { action: 'doomed' });
throw new Error('boom');
}),
).rejects.toThrow('boom');
// No orphan-row semantics here — there is nothing to be orphaned FROM. The
// carve-out's cost is paid only by deployments that actually split.
expect(rolledBack).toBe(true);
});
});
// ---------------------------------------------------------------------------
// The gate's declared limit — handles the engine cannot attribute
// ---------------------------------------------------------------------------
describe('the same-origin gate declines to judge a handle it cannot attribute (#5351 boundary)', () => {
it('covers an explicitly-threaded handle when it IS the ambient one', async () => {
const { engine, ledgerDb } = await splitEngine();
// The dominant explicit path: `transaction()` hands the caller `trxCtx` and
// the caller threads it back as `{ context: trxCtx }`. Identity-matching
// that handle against the store entry is what keeps this path covered — a
// caller cannot escape the gate by passing the context the engine gave it.
await expect(
engine.transaction(async (trxCtx) => {
await engine.insert('ledger', { name: 'threaded' }, { context: trxCtx } as any);
}),
).rejects.toBeInstanceOf(CrossDatasourceTransactionWriteError);
expect(ledgerDb.writes).toHaveLength(0);
});
it('does NOT cover a foreign handle passed in from outside — declared, not overlooked', async () => {
const { engine, ledgerDb } = await splitEngine();
// A handle the engine never opened — not through `transaction()`, and not
// through `ScopedContext`'s discrete trio, whose handles it attributes by
// the owner recorded at `beginTransaction` (#35028, the describe below) —
// is an opaque driver object with no back-reference to its owner. There is
// no honest comparison to make, and guessing would refuse legitimate
// single-datasource work. So the pre-#5351 behaviour stands on this path —
// pinned here so the limit is a recorded decision rather than a gap
// someone discovers. Closing it needs handle ownership to become
// discoverable on `IDataDriver`; filed separately.
const foreign = { __trx: 'somebody elses handle' };
await engine.insert('ledger', { name: 'unattributed' }, { context: { transaction: foreign } } as any);
expect(ledgerDb.writes).toHaveLength(1);
expect(ledgerDb.writes[0].transaction).toBe(foreign);
});
});
// ---------------------------------------------------------------------------
// (f) The discrete trio — a handle the engine opened, attributed (#35028)
// ---------------------------------------------------------------------------
describe('a handle the ScopedContext trio opened is attributed to its owner (#35028)', () => {
/**
* The sandbox runner's `ctx.api.transaction` drives `beginTransaction` /
* `commitTransaction` / `rollbackTransaction` and threads the handle into
* every op explicitly; it never reaches `txStore`. The owner is known at
* `beginTransaction`, so the gate judges the handle as it judges one
* `transaction()` opened.
*/
async function openTrio(engine: ObjectQL) {
const scoped = (engine as any).createContext({ userId: 'u1' }) as ScopedContext;
const opened = await scoped.beginTransaction();
expect(opened, 'precondition: the default driver opens transactions').not.toBeNull();
return { scoped, ctx: opened!.ctx as any, handle: opened!.handle };
}
/** The platform audit writer's shape: an `afterInsert` hook writing the ledger through `ctx.api.sudo()`. */
function auditHook(engine: ObjectQL) {
const outcomes: string[] = [];
engine.registerHook('afterInsert', async (ctx: any) => {
if (ctx.object !== 'thing') return;
try {
await ctx.api.sudo().object('sys_audit_log').create({ action: 'create thing' });
await ctx.api.sudo().object('sys_activity').create({ action: 'created' });
outcomes.push('ok');
} catch (e) {
outcomes.push(`FAILED ${String((e as Error)?.message)}`);
}
}, { packageId: '__test__' } as any);
return outcomes;
}
it('lands the audit and activity rows on telemetry, outside the transaction, with no foreign handle', async () => {
const { engine, primary, telemetry } = await splitEngine();
const outcomes = auditHook(engine);
const { scoped, ctx, handle } = await openTrio(engine);
await ctx.object('thing').insert({ name: 'business row' });
await scoped.commitTransaction(handle);
expect(outcomes).toEqual(['ok']);
expect(telemetry.writes.map((w: RecordedWrite) => w.object)).toEqual(['sys_audit_log', 'sys_activity']);
// Before #35028 both rows were handed `primary`'s handle — on a real SQL
// driver, a statement on the primary connection that has no such table.
expect(telemetry.writes.every((w: RecordedWrite) => w.transaction === undefined)).toBe(true);
// The business write still rides the trio's own handle.
expect(primary.writes).toHaveLength(1);
expect(primary.writes[0]).toMatchObject({ object: 'thing', op: 'create' });
expect(primary.writes[0].transaction).toBe(handle);
});
it('keeps the ledger rows when the trio rolls back — the decided orphan row', async () => {
const { engine, telemetry, primary } = await splitEngine();
let rolledBack: unknown;
primary.rollback = async (h: unknown) => { rolledBack = h; };
auditHook(engine);
const { scoped, ctx, handle } = await openTrio(engine);
await ctx.object('thing').insert({ name: 'doomed' });
await scoped.rollbackTransaction(handle);
expect(rolledBack).toBe(handle);
expect(telemetry.writes.map((w: RecordedWrite) => w.object)).toEqual(['sys_audit_log', 'sys_activity']);
expect(telemetry.writes.every((w: RecordedWrite) => w.transaction === undefined)).toBe(true);
});
it('notes the carve-out at debug, once per trio transaction per datasource', async () => {
const { engine, carveOutNotes } = await splitEngine();
auditHook(engine);
const { scoped, ctx, handle } = await openTrio(engine);
await ctx.object('thing').insert({ name: 'a' });
await ctx.object('thing').insert({ name: 'b' });
await scoped.commitTransaction(handle);
const notes = carveOutNotes();
expect(notes).toHaveLength(1);
expect(meta(notes[0])).toMatchObject({ datasource: 'telemetry', transactionDatasource: 'primary' });
});
it('refuses a cross-datasource business write under the trio handle, naming both datasources', async () => {
const { engine, ledgerDb } = await splitEngine();
const { scoped, ctx, handle } = await openTrio(engine);
const err = await rejection<CrossDatasourceTransactionWriteError>(ctx.object('ledger').insert({ name: 'NOT covered' }));
await scoped.rollbackTransaction(handle);
expect(err).toBeInstanceOf(CrossDatasourceTransactionWriteError);
expect(err.code).toBe('ERR_CROSS_DATASOURCE_TRANSACTION_WRITE');
expect(err).toMatchObject({ object: 'ledger', operation: 'insert', datasource: 'ledger_db', transactionDatasource: 'primary' });
// Refused before any driver ran: nothing on the other datasource, and no
// statement on the wrong connection.
expect(ledgerDb.writes).toHaveLength(0);
});
it('refuses update and delete under the trio handle too', async () => {
const { engine, ledgerDb } = await splitEngine();
const seeded = await engine.insert('ledger', { name: 'outside' });
const { scoped, ctx, handle } = await openTrio(engine);
await expect(ctx.object('ledger').update(seeded.id, { name: 'x' })).rejects.toBeInstanceOf(CrossDatasourceTransactionWriteError);
await expect(ctx.object('ledger').delete(seeded.id)).rejects.toBeInstanceOf(CrossDatasourceTransactionWriteError);
await scoped.rollbackTransaction(handle);
expect(ledgerDb.writes.map((w: RecordedWrite) => w.op)).toEqual(['create']);
});
it('treats the handle as closed once the trio commits — a late cross-datasource write runs unenrolled', async () => {
const { engine, ledgerDb } = await splitEngine();
const { scoped, handle } = await openTrio(engine);
await scoped.commitTransaction(handle);
// [#35149] A closed handle threaded back in is no handle, as a closed
// `transaction()` unit's is (#22855): the write is not refused, and it
// runs outside any transaction. Before #35149 the commit only dropped the
// owner record, so the handle read as an unattributed one and the dead
// `primary` handle was handed to `ledger_db`.
await engine.insert('ledger', { name: 'after commit' }, { context: { transaction: handle } } as any);
expect(ledgerDb.writes).toHaveLength(1);
expect(ledgerDb.writes[0].transaction).toBeUndefined();
});
it('treats the handle as closed once the trio rolls back, too', async () => {
const { engine, ledgerDb } = await splitEngine();
const { scoped, handle } = await openTrio(engine);
await scoped.rollbackTransaction(handle);
await engine.insert('ledger', { name: 'after rollback' }, { context: { transaction: handle } } as any);
expect(ledgerDb.writes).toHaveLength(1);
expect(ledgerDb.writes[0].transaction).toBeUndefined();
});
it('lets an async afterFind run, detached from the open trio handle, write a business object on another datasource', async () => {
const { engine, ledgerDb } = await splitEngine();
// An `async: true` `afterFind` run starts at dispatch, outside every unit
// open then (`unit-detach.ts`): its `ctx.api` still carries the trio
// handle, and the engine treats that handle as closed for the run
// (`isClosedUnitHandle`). So its write is outside any transaction, as
// under `transaction(cb)`: it lands, on its own connection, and the gate
// does not judge it against the trio record.
let report!: (outcome: string) => void;
const outcome = new Promise<string>((r) => { report = r; });
bindHooksToEngine(engine, [{
name: 'mirror_read', object: 'thing', events: ['afterFind'], async: true, onError: 'log',
handler: async (ctx: any) => {
try {
await ctx.api.object('ledger').insert({ name: 'from a detached read hook' });
report('stored');
} catch (e) {
report(`FAILED ${(e as Error)?.name}: ${(e as Error)?.message}`);
}
},
} as unknown as Hook], { packageId: 'app:t' });
const { scoped, ctx, handle } = await openTrio(engine);
await ctx.object('thing').find({});
// The trio is still open while the detached run writes.
expect(await outcome).toBe('stored');
await scoped.commitTransaction(handle);
expect(ledgerDb.writes).toHaveLength(1);
expect(ledgerDb.writes[0]).toMatchObject({ object: 'ledger', op: 'create' });
expect(ledgerDb.writes[0].transaction).toBeUndefined();
});
describe('single datasource: the trio still rides one handle (#35028 regression guard)', () => {
async function singleEngine() {
const engine = new ObjectQL({ logger: recordingLogger().logger } as any);
const primary = makeDriver('primary');
engine.registerDriver(primary, true);
await engine.init();
engine.registry.registerObject({ name: 'thing', fields: { name: { type: 'text' } } }, '__test__');
for (const [name, cls] of [['sys_audit_log', 'audit'], ['sys_activity', 'telemetry']] as const) {
engine.registry.registerObject({
name,
lifecycle: { class: cls, retention: { maxAge: '90d' } },
fields: { action: { type: 'text' } },
} as any, '__test__');
}
return { engine, primary };
}
it('writes the business and ledger rows on the trio handle, and rolls them back together', async () => {
const { engine, primary } = await singleEngine();
const outcomes = auditHook(engine);
let rolledBack: unknown;
primary.rollback = async (h: unknown) => { rolledBack = h; };
const { scoped, ctx, handle } = await openTrio(engine);
await ctx.object('thing').insert({ name: 'a' });
await scoped.rollbackTransaction(handle);
expect(outcomes).toEqual(['ok']);
expect(primary.writes.map((w: RecordedWrite) => w.object)).toEqual(['thing', 'sys_audit_log', 'sys_activity']);
expect(primary.writes.every((w: RecordedWrite) => w.transaction === handle)).toBe(true);
expect(rolledBack).toBe(handle);
});
});
});
// ---------------------------------------------------------------------------
// (g) A closed trio handle is no handle — as a closed transaction() unit's is (#35149)
// ---------------------------------------------------------------------------
describe('a trio handle closes as a transaction() unit handle does (#35149)', () => {
/** The engine's own reading of a threaded handle (`isClosedUnitHandle`), the one every write and read path acts on. */
const isClosed = (engine: ObjectQL, handle: unknown): boolean => (engine as any).isClosedUnitHandle(handle);
async function openTrio(engine: ObjectQL) {
const scoped = (engine as any).createContext({ userId: 'u1' }) as ScopedContext;
const opened = await scoped.beginTransaction();
expect(opened, 'precondition: the default driver opens transactions').not.toBeNull();
expect(opened!.owned, 'precondition: the trio opened this handle, it did not join one').toBe(true);
return { scoped, ctx: opened!.ctx as any, handle: opened!.handle };
}
it('gives a late cross-datasource write the same answer under a committed trio handle as under a closed unit handle', async () => {
const { engine, ledgerDb } = await splitEngine();
let unitHandle: unknown;
await engine.transaction(async (trxCtx: any) => { unitHandle = trxCtx?.transaction; });
expect(unitHandle, 'precondition: transaction() threads its handle into the callback').toBeDefined();
const { scoped, handle } = await openTrio(engine);
await scoped.commitTransaction(handle);
expect(isClosed(engine, unitHandle)).toBe(true);
expect(isClosed(engine, handle)).toBe(true);
await engine.insert('ledger', { name: 'late, closed unit' }, { context: { transaction: unitHandle } } as any);
await engine.insert('ledger', { name: 'late, committed trio' }, { context: { transaction: handle } } as any);
expect(ledgerDb.writes.map((w: RecordedWrite) => w.transaction)).toEqual([undefined, undefined]);
});
it('runs a late same-datasource write unenrolled too, never on the dead handle', async () => {
const { engine, primary } = await splitEngine();
const { scoped, handle } = await openTrio(engine);
await scoped.rollbackTransaction(handle);
expect(isClosed(engine, handle)).toBe(true);
await engine.insert('thing', { name: 'after rollback' }, { context: { transaction: handle } } as any);
expect(primary.writes).toHaveLength(1);
expect(primary.writes[0].transaction).toBeUndefined();
});
it('CONTROL: an open trio handle still enrolls, and a cross-datasource business write under it is still refused', async () => {
const { engine, primary, ledgerDb } = await splitEngine();
const { scoped, handle } = await openTrio(engine);
expect(isClosed(engine, handle)).toBe(false);
await engine.insert('thing', { name: 'in the trio' }, { context: { transaction: handle } } as any);
expect(primary.writes[0].transaction).toBe(handle);
const err = await rejection<CrossDatasourceTransactionWriteError>(
engine.insert('ledger', { name: 'refused' }, { context: { transaction: handle } } as any),
);
expect(err.code).toBe('ERR_CROSS_DATASOURCE_TRANSACTION_WRITE');
expect(ledgerDb.writes).toHaveLength(0);
await scoped.commitTransaction(handle);
expect(isClosed(engine, handle)).toBe(true);
});
it('answers the body doors\' question the same way: separate while open, none once committed', async () => {
const { engine } = await splitEngine();
const { scoped, handle } = await openTrio(engine);
expect(openTransactionKind(engine, handle)).toBe('separate');
await scoped.commitTransaction(handle);
expect(openTransactionKind(engine, handle)).toBe('none');
});
it('reads a handle the driver hands out again as open on its next begin', async () => {
const { engine, primary } = await splitEngine();
const shared = { __trx: 'primary, reused' };
primary.beginTransaction = async () => shared;
const first = await openTrio(engine);
await first.scoped.commitTransaction(first.handle);
expect(isClosed(engine, shared)).toBe(true);
const second = await openTrio(engine);
expect(second.handle).toBe(shared);
expect(isClosed(engine, shared)).toBe(false);
await second.ctx.object('thing').insert({ name: 'on the reopened handle' });
expect(primary.writes[0].transaction).toBe(shared);
await second.scoped.commitTransaction(shared);
});
});