Skip to content

Commit 5cd2b54

Browse files
fix(objectql): a committed or rolled-back trio handle reads as closed (#35541)
repo:objectstack#5 · os-bill · session_01Utp6Ca1jJvsA1dHsPwMiQb Fixes #35149 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:脚本里手动开启的事务提交或回滚之后,仍带着这个旧事务的迟到写入会像普通写入一样正常落库,不再被塞进一个已经结束的事务。 - 为什么做:两种事务结束后的行为原本不一致,另一种早已按“已关闭即视为没有事务”处理,这次让两者一致。 - 出错会怎样:最坏情况是某次迟到写入没有进入它本应加入的仍在进行的事务;改动只在事务已提交或已回滚之后生效,事务进行中的行为不变。 - 要你做什么:无,席位落地。 ## 席位核对 ### What changes - `engine-execute-transactions.ts`: the trio's commit/rollback release is now `closeTrioTransactionScope`, which drops the owner record (as before) AND adds the handle to a module-level `closedTrioHandles` WeakSet, only for a handle the trio itself opened (one with an owner record). `isClosedTrioHandle` reads it. `recordTrioTransactionScope` clears the mark, so a driver that hands the same object out on a later `beginTransaction` gets it back open. - `engine-transactions-section.ts` `isClosedUnitHandle`: when `openedUnits` holds no entry for the handle, it answers `isClosedTrioHandle(handle)`. An `openedUnits` entry still decides first, so a `transaction()` unit handle reads exactly as before. - `engine-scoped-context.ts`: `commitTransaction` / `rollbackTransaction` call `closeTrioTransactionScope` in their existing `finally`. A joined (ambient) handle still returns early and is never marked. - `engine.ts` untouched: 6852 lines at `origin/main` 9212119 and at head (facade ceiling 6854). - Every reader of `isClosedUnitHandle` now treats a closed trio handle as absent, as #22855 does for a closed unit: `buildDriverOptions`, `enforceTransactionOrigin`, `opensAfterAbortUnit`, the secret-row release, the summary write transaction, and `openTransactionKind` (`'separate'` becomes `'none'` for a closed trio handle). - Clause-② measured on the diff: no caller that got an answer now gets a refusal. A late write carrying a closed trio handle was never refused (unattributed handle, the gate declined to judge), and is not refused now; it runs unenrolled instead of being handed the dead handle. ### Tests `packages/objectql/src/engine-transaction-same-origin.test.ts`: - The PR #35102 pins "forgets the owner once the trio commits / rolls back" are re-worded to "treats the handle as closed once the trio commits / rolls back — a late cross-datasource write runs unenrolled". Intent kept (the record does not outlive the handle; the late write lands, not refused); the assertion now also requires `ledgerDb.writes[0].transaction` to be `undefined`. - New top-level describe `a trio handle closes as a transaction() unit handle does (#35149)`, in the same harness file: parity with a closed `transaction()` unit handle on a late cross-datasource write; a late same-datasource write after rollback runs unenrolled; CONTROL (open trio handle reads open, enrolls, and a cross-datasource business write under it is still refused with `ERR_CROSS_DATASOURCE_TRANSACTION_WRITE`); `openTransactionKind` separate-then-none; a reused driver handle reads open on its next begin. ### Acceptance notes - A0, reproduced at `origin/main` 9212119 source with the new tests only: a late `ledger` insert carrying a committed trio handle reached `ledger_db` with `transaction: { __trx: 'primary' }` (the dead foreign handle); the same after rollback. 7 failed / 27 passed. - The ADR-0119 note (2026-11-18) says the owner record is "dropped when commitTransaction or rollbackTransaction closes it": still true, and its "a handle the engine never opened" limit now matches the code. No ADR edit. ### Verification <details><summary>Red at origin/main source, green at head, ablations</summary> - Red (tests only, source at 9212119): `vitest run src/engine-transaction-same-origin.test.ts` → `Tests 7 failed | 27 passed (34)`; first failure `expected { __trx: 'primary' } to be undefined`. - Green at b548ddf: same file plus `engine-scoped-transaction-late-write.test.ts` and `open-transaction.test.ts` → `Test Files 3 passed (3)`, `Tests 69 passed (69)`. - Ablation 1 (`scripts/ablation-replace.mjs`, anchor x1 → x0, blob abff616 → 235b522e2582): close drops the record without marking → `Tests 7 failed | 27 passed (34)`; restored, blob == HEAD, `git diff HEAD` empty. - Ablation 2 (anchor x1 → x0, blob abff616 → 99010386c306): `recordTrioTransactionScope` no longer clears the mark → `Tests 1 failed | 33 passed (34)` (the reused-handle pin); restored, blob == HEAD, `git diff HEAD` empty. - The test imports `./engine.js` from `src`, so no `dist` leg applies. </details> <details><summary>Package and gates at b548ddf</summary> - `pnpm --filter @objectstack/objectql typecheck && pnpm --filter @objectstack/objectql test` under the verify lock → `VERDICT command-exit 0`; `Test Files 615 passed (615)`, `Tests 13900 passed (13900)`; `check:test-typecheck: OK`. - `dispatch-gates.mjs --commands` derived 65 families: 59 ran locally, exit 0 each. `check:type-check-debt` exit 3 (its closure build never got a turn on the shared verify lock): NOT MEASURED. `check:dts-closure`, `check:dual-build-cjs-loads`, `check:lean-entry-closure`, `check:published-files` and `check:sourcemap-no-sources-content` read the built `dist`; the objectql build did not get a turn on the lock after more than 45 minutes in the queue, so these are NOT MEASURED locally, a declared narrowing, and left to CI. - `test:repo`, `--project integration` and the dogfood battery not run locally: not owed for this diff (no `!`, no narrowing arm), declared to CI. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01Utp6Ca1jJvsA1dHsPwMiQb)_ Co-authored-by: Claude <noreply@anthropic.com>
1 parent 3cfa5bc commit 5cd2b54

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)