Skip to content

Commit b548ddf

Browse files
committed
fix(objectql): a committed or rolled-back trio handle reads as closed
The ScopedContext trio now marks the handles it opened closed on commit and rollback, and isClosedUnitHandle answers true for them, so late work carrying one runs unenrolled, as late work carrying a closed transaction() unit handle does. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Utp6Ca1jJvsA1dHsPwMiQb
1 parent 9212119 commit b548ddf

5 files changed

Lines changed: 133 additions & 12 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@objectstack/objectql': patch
3+
---
4+
5+
fix(objectql): a trio transaction handle that committed or rolled back reads as closed, as a closed `transaction()` unit handle does
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
`ScopedContext`'s discrete `beginTransaction` / `commitTransaction` / `rollbackTransaction` trio (the sandbox runner's `ctx.api.transaction`) now marks its handle closed when it commits or rolls it back, instead of only dropping the handle's owner record. The engine's closed-handle check answers `true` for it, so work that still carries the handle afterwards runs outside any transaction, on its own connection, exactly as late work carrying a closed `transaction()` unit handle already did. Before, such a handle read as an unattributed one: a late write routed to another datasource was handed the dead foreign handle, and a late write on the same datasource was handed the finished handle. `openTransactionKind` answers `'none'` for a closed trio handle, where it answered `'separate'`. A driver that hands out the same handle object on a later `beginTransaction` gets it back open.

‎packages/objectql/src/engine-execute-transactions.ts‎

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -77,20 +77,38 @@ import type { ObjectQL } from './engine.js';
7777
*/
7878
const trioTransactionScopes = new WeakMap<object, TransactionScope>();
7979

80+
/**
81+
* [#35149] The handles the trio opened and has since committed or rolled back.
82+
* The engine's `isClosedUnitHandle` answers `true` for them, as it does for a
83+
* `transaction()` unit whose callback settled (#22855), so every reader of a
84+
* threaded handle treats one as absent: work that still carries it runs
85+
* unenrolled. Dropping the owner record alone left such a handle unattributed,
86+
* and a late write routed to another datasource was handed the dead handle.
87+
* Weak, for the reason the owner record is.
88+
*/
89+
const closedTrioHandles = new WeakSet<object>();
90+
8091
/** [#35028] Record the owner of a handle the trio just opened. A primitive handle cannot key it and stays unattributed. */
8192
export function recordTrioTransactionScope(handle: unknown, scope: TransactionScope): void {
8293
if (handle !== null && (typeof handle === 'object' || typeof handle === 'function')) {
8394
trioTransactionScopes.set(handle, scope);
95+
// [#35149] A driver that hands the same object out again opened it again.
96+
closedTrioHandles.delete(handle);
8497
}
8598
}
8699

87-
/** [#35028] Forget a trio handle's owner: its commit or rollback closed it. */
88-
export function forgetTrioTransactionScope(handle: unknown): void {
100+
/** [#35149] Close a handle the trio opened: its commit or rollback ended it. A handle it never opened is left as it was. */
101+
export function closeTrioTransactionScope(handle: unknown): void {
89102
if (handle !== null && (typeof handle === 'object' || typeof handle === 'function')) {
90-
trioTransactionScopes.delete(handle);
103+
if (trioTransactionScopes.delete(handle)) closedTrioHandles.add(handle);
91104
}
92105
}
93106

107+
/** [#35149] Did the trio open `handle` and since commit or roll it back? */
108+
export function isClosedTrioHandle(handle: unknown): boolean {
109+
return handle !== null && (typeof handle === 'object' || typeof handle === 'function') && closedTrioHandles.has(handle);
110+
}
111+
94112
/** [#35028] The owner of an open trio handle, or `undefined` for any other handle. */
95113
export function trioTransactionScopeOf(handle: unknown): TransactionScope | undefined {
96114
if (handle === null || (typeof handle !== 'object' && typeof handle !== 'function')) return undefined;

‎packages/objectql/src/engine-scoped-context.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ import { appAutomationElevationOf, markAppAutomationElevation, resolveUserAuthzG
4444
import type { EngineTransactionInfo, EngineTransactionOptions } from '@objectstack/core';
4545
import { rolledBackRefusal } from './summary-errors.js';
4646
import { TransactionUnsupportedError } from './transaction-errors.js';
47-
import { forgetTrioTransactionScope, recordTrioTransactionScope } from './engine-execute-transactions.js';
47+
import { closeTrioTransactionScope, recordTrioTransactionScope } from './engine-execute-transactions.js';
4848
import { redactPropagatedDriverFault } from '@objectstack/types';
4949
import { UnscopedHookApi } from './hook-run-as.js';
5050
import { newUnitCommitQueue, openTrioCommitQueue, runOutsideOpenUnits, runOutsideOpenUnitsOnCommit, settleTrioCommitQueue, settleUnitCommitQueue, type UNIT_ROLLED_BACK } from './unit-detach.js';
@@ -372,7 +372,7 @@ export class ScopedContextFacet {
372372
if (driver.commit) await driver.commit(handle);
373373
else if (driver.commitTransaction) await driver.commitTransaction(handle);
374374
} finally {
375-
forgetTrioTransactionScope(handle);
375+
closeTrioTransactionScope(handle);
376376
}
377377
settleTrioCommitQueue(handle, true);
378378
}
@@ -388,7 +388,7 @@ export class ScopedContextFacet {
388388
if (driver.rollback) await driver.rollback(handle);
389389
else if (driver.rollbackTransaction) await driver.rollbackTransaction(handle);
390390
} finally {
391-
forgetTrioTransactionScope(handle);
391+
closeTrioTransactionScope(handle);
392392
}
393393
}
394394

‎packages/objectql/src/engine-transaction-same-origin.test.ts‎

Lines changed: 94 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ import type { Hook } from '@objectstack/spec/data';
3737
import { ObjectQL, ScopedContext } from './engine.js';
3838
import { bindHooksToEngine } from './hook-binder.js';
3939
import { CrossDatasourceTransactionWriteError } from './transaction-errors.js';
40+
import { openTransactionKind } from './open-transaction.js';
4041

4142
interface Recorded {
4243
level: 'debug' | 'info' | 'warn' | 'error';
@@ -686,24 +687,29 @@ describe('a handle the ScopedContext trio opened is attributed to its owner (#35
686687
expect(ledgerDb.writes.map((w: RecordedWrite) => w.op)).toEqual(['create']);
687688
});
688689

689-
it('forgets the owner once the trio commits — the record does not outlive the handle', async () => {
690+
it('treats the handle as closed once the trio commits — a late cross-datasource write runs unenrolled', async () => {
690691
const { engine, ledgerDb } = await splitEngine();
691692
const { scoped, handle } = await openTrio(engine);
692693
await scoped.commitTransaction(handle);
693694

694-
// A closed handle threaded back in is no open trio transaction: it is
695-
// judged as any unattributed handle is (the declared limit above).
695+
// [#35149] A closed handle threaded back in is no handle, as a closed
696+
// `transaction()` unit's is (#22855): the write is not refused, and it
697+
// runs outside any transaction. Before #35149 the commit only dropped the
698+
// owner record, so the handle read as an unattributed one and the dead
699+
// `primary` handle was handed to `ledger_db`.
696700
await engine.insert('ledger', { name: 'after commit' }, { context: { transaction: handle } } as any);
697701
expect(ledgerDb.writes).toHaveLength(1);
702+
expect(ledgerDb.writes[0].transaction).toBeUndefined();
698703
});
699704

700-
it('forgets the owner once the trio rolls back, too', async () => {
705+
it('treats the handle as closed once the trio rolls back, too', async () => {
701706
const { engine, ledgerDb } = await splitEngine();
702707
const { scoped, handle } = await openTrio(engine);
703708
await scoped.rollbackTransaction(handle);
704709

705710
await engine.insert('ledger', { name: 'after rollback' }, { context: { transaction: handle } } as any);
706711
expect(ledgerDb.writes).toHaveLength(1);
712+
expect(ledgerDb.writes[0].transaction).toBeUndefined();
707713
});
708714

709715
it('lets an async afterFind run, detached from the open trio handle, write a business object on another datasource', async () => {
@@ -773,3 +779,87 @@ describe('a handle the ScopedContext trio opened is attributed to its owner (#35
773779
});
774780
});
775781
});
782+
783+
// ---------------------------------------------------------------------------
784+
// (g) A closed trio handle is no handle — as a closed transaction() unit's is (#35149)
785+
// ---------------------------------------------------------------------------
786+
787+
describe('a trio handle closes as a transaction() unit handle does (#35149)', () => {
788+
/** The engine's own reading of a threaded handle (`isClosedUnitHandle`), the one every write and read path acts on. */
789+
const isClosed = (engine: ObjectQL, handle: unknown): boolean => (engine as any).isClosedUnitHandle(handle);
790+
791+
async function openTrio(engine: ObjectQL) {
792+
const scoped = (engine as any).createContext({ userId: 'u1' }) as ScopedContext;
793+
const opened = await scoped.beginTransaction();
794+
expect(opened, 'precondition: the default driver opens transactions').not.toBeNull();
795+
expect(opened!.owned, 'precondition: the trio opened this handle, it did not join one').toBe(true);
796+
return { scoped, ctx: opened!.ctx as any, handle: opened!.handle };
797+
}
798+
799+
it('gives a late cross-datasource write the same answer under a committed trio handle as under a closed unit handle', async () => {
800+
const { engine, ledgerDb } = await splitEngine();
801+
let unitHandle: unknown;
802+
await engine.transaction(async (trxCtx: any) => { unitHandle = trxCtx?.transaction; });
803+
expect(unitHandle, 'precondition: transaction() threads its handle into the callback').toBeDefined();
804+
const { scoped, handle } = await openTrio(engine);
805+
await scoped.commitTransaction(handle);
806+
807+
expect(isClosed(engine, unitHandle)).toBe(true);
808+
expect(isClosed(engine, handle)).toBe(true);
809+
await engine.insert('ledger', { name: 'late, closed unit' }, { context: { transaction: unitHandle } } as any);
810+
await engine.insert('ledger', { name: 'late, committed trio' }, { context: { transaction: handle } } as any);
811+
expect(ledgerDb.writes.map((w: RecordedWrite) => w.transaction)).toEqual([undefined, undefined]);
812+
});
813+
814+
it('runs a late same-datasource write unenrolled too, never on the dead handle', async () => {
815+
const { engine, primary } = await splitEngine();
816+
const { scoped, handle } = await openTrio(engine);
817+
await scoped.rollbackTransaction(handle);
818+
819+
expect(isClosed(engine, handle)).toBe(true);
820+
await engine.insert('thing', { name: 'after rollback' }, { context: { transaction: handle } } as any);
821+
expect(primary.writes).toHaveLength(1);
822+
expect(primary.writes[0].transaction).toBeUndefined();
823+
});
824+
825+
it('CONTROL: an open trio handle still enrolls, and a cross-datasource business write under it is still refused', async () => {
826+
const { engine, primary, ledgerDb } = await splitEngine();
827+
const { scoped, handle } = await openTrio(engine);
828+
829+
expect(isClosed(engine, handle)).toBe(false);
830+
await engine.insert('thing', { name: 'in the trio' }, { context: { transaction: handle } } as any);
831+
expect(primary.writes[0].transaction).toBe(handle);
832+
const err = await rejection<CrossDatasourceTransactionWriteError>(
833+
engine.insert('ledger', { name: 'refused' }, { context: { transaction: handle } } as any),
834+
);
835+
expect(err.code).toBe('ERR_CROSS_DATASOURCE_TRANSACTION_WRITE');
836+
expect(ledgerDb.writes).toHaveLength(0);
837+
await scoped.commitTransaction(handle);
838+
expect(isClosed(engine, handle)).toBe(true);
839+
});
840+
841+
it('answers the body doors\' question the same way: separate while open, none once committed', async () => {
842+
const { engine } = await splitEngine();
843+
const { scoped, handle } = await openTrio(engine);
844+
845+
expect(openTransactionKind(engine, handle)).toBe('separate');
846+
await scoped.commitTransaction(handle);
847+
expect(openTransactionKind(engine, handle)).toBe('none');
848+
});
849+
850+
it('reads a handle the driver hands out again as open on its next begin', async () => {
851+
const { engine, primary } = await splitEngine();
852+
const shared = { __trx: 'primary, reused' };
853+
primary.beginTransaction = async () => shared;
854+
const first = await openTrio(engine);
855+
await first.scoped.commitTransaction(first.handle);
856+
expect(isClosed(engine, shared)).toBe(true);
857+
858+
const second = await openTrio(engine);
859+
expect(second.handle).toBe(shared);
860+
expect(isClosed(engine, shared)).toBe(false);
861+
await second.ctx.object('thing').insert({ name: 'on the reopened handle' });
862+
expect(primary.writes[0].transaction).toBe(shared);
863+
await second.scoped.commitTransaction(shared);
864+
});
865+
});

‎packages/objectql/src/engine-transactions-section.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ import type { EngineTransactionInfo, EngineTransactionOptions, IDataDriver } fro
3535
import { rollbackFailedRefusal, rolledBackRefusal } from './summary-errors.js';
3636
import { TransactionUnsupportedError } from './transaction-errors.js';
3737
import { isDetachedUnitHandle, newUnitCommitQueue, settleUnitCommitQueue, type UnitCommitQueue } from './unit-detach.js';
38+
import { isClosedTrioHandle } from './engine-execute-transactions.js';
3839
import type { TransactionScope } from './engine-top-level.js';
3940
import type { ObjectQL } from './engine.js';
4041

@@ -181,13 +182,15 @@ export class TransactionsSectionFacet {
181182
* [#22855] Is `handle` a unit {@link runOpenedUnit} published whose callback
182183
* has since settled? [#33651] Or one the current run was detached from — an
183184
* `async: true` hook's run, which starts outside every unit open at its
184-
* dispatch (`unit-detach.ts`), primitive handles included.
185+
* dispatch (`unit-detach.ts`), primitive handles included. [#35149] Or one
186+
* `ScopedContext`'s discrete trio opened and has since committed or rolled
187+
* back (`isClosedTrioHandle`), so the two kinds of handle close alike.
185188
*/
186189
static isClosedUnitHandle(this: Pick<TransactionsSectionHost, 'openedUnits'>, handle: unknown): boolean {
187190
if (isDetachedUnitHandle(handle)) return true;
188191
if (handle === null || (typeof handle !== 'object' && typeof handle !== 'function')) return false;
189192
const entry = this.openedUnits.get(handle);
190-
return entry !== undefined && entry.transaction === undefined;
193+
return entry !== undefined ? entry.transaction === undefined : isClosedTrioHandle(handle);
191194
}
192195

193196
/**

0 commit comments

Comments
 (0)