Skip to content

Commit c122a90

Browse files
committed
fix(objectql): an async afterFind run starts at dispatch, not on its unit's commit
A rollback undoes a write, not a read: the rows afterFind saw were already returned. Only the after* events of a write wait for the unit's commit and are dropped on its rollback; any other event starts outside the units at dispatch, as before. Pins: afterFind in a unit that commits and one that rolls back, the outside-unit control, and a deferred run that throws after the commit; the dogfood twin repeats the afterFind set on SQLite. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QsR2jTEivi2wogPpeo3xd5
1 parent 1621f1e commit c122a90

6 files changed

Lines changed: 194 additions & 23 deletions

File tree

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

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ import { rolledBackRefusal } from './summary-errors.js';
4646
import { TransactionUnsupportedError } from './transaction-errors.js';
4747
import { redactPropagatedDriverFault } from '@objectstack/types';
4848
import { UnscopedHookApi } from './hook-run-as.js';
49-
import { newUnitCommitQueue, openTrioCommitQueue, runOutsideOpenUnitsOnCommit, settleTrioCommitQueue, settleUnitCommitQueue, type UNIT_ROLLED_BACK } from './unit-detach.js';
49+
import { newUnitCommitQueue, openTrioCommitQueue, runOutsideOpenUnits, runOutsideOpenUnitsOnCommit, settleTrioCommitQueue, settleUnitCommitQueue, type UNIT_ROLLED_BACK } from './unit-detach.js';
5050
import { refuseAppAuthoredPermanentDelete } from './recycle-bin/app-authored-delete.js';
5151
import type { HookRunAs, HookRunAsRef } from './hook-run-as.js';
5252
import { scopedContextHost } from './engine-scoped-hosts.js';
@@ -168,11 +168,14 @@ export class ScopedContextFacet {
168168
}
169169

170170
/** The body of `ScopedContext#[DETACHED_HOOK_RUN]`; the method's docblock there is its contract. */
171-
static detachedHookRun<T>(this: Pick<ScopedContextHost, 'engine' | 'executionContext'>, body: () => Promise<T>): Promise<T | typeof UNIT_ROLLED_BACK> {
171+
static detachedHookRun<T>(this: Pick<ScopedContextHost, 'engine' | 'executionContext'>, body: () => Promise<T>, waitForCommit: boolean): Promise<T | typeof UNIT_ROLLED_BACK> {
172172
// The engine's ambient store and its published units, reached the `as any`
173173
// way `transaction` below reaches them.
174174
const engine = this.engine as any;
175-
return runOutsideOpenUnitsOnCommit(engine?.txStore, engine?.openedUnits, this.executionContext?.transaction, body);
175+
const threaded = this.executionContext?.transaction;
176+
return waitForCommit
177+
? runOutsideOpenUnitsOnCommit(engine?.txStore, engine?.openedUnits, threaded, body)
178+
: runOutsideOpenUnits(engine?.txStore, threaded, body);
176179
}
177180

178181
/** The body of `ScopedContext#transaction`; the method's docblock there is its contract. */

‎packages/objectql/src/engine-scoped-transaction-late-write.test.ts‎

Lines changed: 90 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -364,9 +364,15 @@ async function makeCommitEngine() {
364364
let dropped!: (hook: string) => void;
365365
const drops: string[] = [];
366366
const quiet = () => {};
367+
// A deferred run's failure reaches the wrapper's error line (fire-and-forget).
368+
let errored!: (hook: string) => void;
369+
const erroredRun = new Promise<string>((r) => { errored = r; });
367370
const logger = {
368371
debug: (msg: string, meta?: any) => { if (/rolled back/.test(msg)) { drops.push(meta?.hook); dropped?.(meta?.hook); } },
369-
info: quiet, warn: quiet, error: quiet,
372+
info: quiet, warn: quiet,
373+
error: (msg: string, _err?: unknown, meta?: any) => {
374+
if (/fire-and-forget/.test(msg)) { events.push(`error logged:${meta?.hook}`); errored(meta?.hook); }
375+
},
370376
};
371377
const engine = new ObjectQL({ logger } as any);
372378
const driver = makeDriver();
@@ -417,17 +423,40 @@ async function makeCommitEngine() {
417423
settle[name]!(0);
418424
},
419425
} as unknown as Hook;
420-
const bind = (withGate: boolean, opts: { userPin?: boolean } = {}) => bindHooksToEngine(
426+
// [#33760 review#2] A read's `async` hook: a rollback does not undo the read,
427+
// so its run is not the unit's to hold or drop. It writes a note of its own.
428+
const readNote = {
429+
name: 'read_note', object: 'rec', events: ['afterFind'], async: true, onError: 'log',
430+
handler: async (ctx: any) => {
431+
events.push('read-hook started');
432+
runOf('read');
433+
await ctx.api.object('note').insert({ name: 'note:read' });
434+
settle.read!(0);
435+
},
436+
} as unknown as Hook;
437+
// A deferred run that throws once it starts, after the commit. The default
438+
// `onError` ('abort'), so the throw reaches the fire-and-forget catch.
439+
const thrower = {
440+
name: 'thrower', object: 'rec', events: ['afterInsert'], async: true,
441+
handler: async () => { events.push('thrower started'); throw new Error('the deferred run fails'); },
442+
} as unknown as Hook;
443+
const bind = (withGate: boolean, opts: { userPin?: boolean; read?: boolean; thrower?: boolean } = {}) => bindHooksToEngine(
421444
engine,
422-
opts.userPin ? [userPin] : withGate ? [asyncNote, gate] : [asyncNote],
445+
opts.read ? [readNote] : opts.thrower ? [thrower] : opts.userPin ? [userPin] : withGate ? [asyncNote, gate] : [asyncNote],
423446
{ packageId: 'app:t', logger: logger as any },
424447
);
425448
const api = new ScopedContext({ isSystem: true } as any, engine as any);
426449
const droppedRun = () => new Promise<string>((r) => { dropped = r; });
427450
const notes = () => driver.rowsOf('note').map((r: any) => r.name);
428-
return { engine, driver, api, events, drops, bind, runOf, droppedRun, notes, apiKinds };
451+
return { engine, driver, api, events, drops, bind, runOf, droppedRun, notes, apiKinds, erroredRun };
429452
}
430453

454+
/** Did the read's hook start while the unit is still open? Bounded, so a run held for the commit reads as `not started`. */
455+
const startedInUnit = (started: Promise<unknown>) => Promise.race([
456+
started.then(() => 'started in the unit'),
457+
new Promise<string>((r) => setTimeout(() => r('not started in the unit'), 200)),
458+
]);
459+
431460
describe('#33760 — an async after-hook fired inside a unit runs on its commit, never on its rollback', () => {
432461
it('engine.transaction() commits: the hook starts after the commit, sees its row, and writes outside the unit', async () => {
433462
const { engine, driver, events, bind, runOf, notes } = await makeCommitEngine();
@@ -575,6 +604,63 @@ describe('#33760 — an async after-hook fired inside a unit runs on its commit,
575604
expect(drops).toEqual(['user_pin']);
576605
});
577606

607+
it('a deferred run that throws after the commit: transaction() still resolves and the failure is logged', async () => {
608+
const { engine, events, bind, erroredRun } = await makeCommitEngine();
609+
bind(false, { thrower: true });
610+
await expect(engine.transaction(async (trx: any) => {
611+
await engine.insert('rec', { name: 'r1' }, { context: { ...trx, isSystem: true } });
612+
events.push('callback returns');
613+
return 'resolved';
614+
})).resolves.toBe('resolved');
615+
expect(await erroredRun).toBe('thrower');
616+
expect(events).toEqual(['callback returns', 'commit', 'thrower started', 'error logged:thrower']);
617+
});
618+
619+
it('afterFind inside engine.transaction() that commits: a read\'s async hook starts at dispatch, in the unit\'s lifetime, not after the commit', async () => {
620+
const { engine, driver, events, bind, runOf, notes } = await makeCommitEngine();
621+
await engine.insert('rec', { name: 'r0' }, { context: { isSystem: true } });
622+
bind(false, { read: true });
623+
await engine.transaction(async (trx: any) => {
624+
await engine.find('rec', {}, { context: { ...trx, isSystem: true } } as any);
625+
events.push(await startedInUnit(runOf('read')));
626+
});
627+
await runOf('read');
628+
expect(events).toEqual(['read-hook started', 'started in the unit', 'commit']);
629+
expect(notes()).toEqual(['note:read']);
630+
// Outside the unit, as under #33651: its write enrolled in nothing.
631+
expect(unenrolled(driver).filter(([o]) => o === 'note')).toEqual([['note', true]]);
632+
});
633+
634+
it('afterFind inside engine.transaction() that rolls back: the read\'s async hook still runs, outside the unit', async () => {
635+
const { engine, driver, events, drops, bind, runOf } = await makeCommitEngine();
636+
await engine.insert('rec', { name: 'r0' }, { context: { isSystem: true } });
637+
bind(false, { read: true });
638+
await expect(engine.transaction(async (trx: any) => {
639+
await engine.find('rec', {}, { context: { ...trx, isSystem: true } } as any);
640+
events.push(await startedInUnit(runOf('read')));
641+
throw new Error('the caller rolls back');
642+
})).rejects.toThrow('the caller rolls back');
643+
await runOf('read');
644+
expect(events).toEqual(['read-hook started', 'started in the unit', 'rollback']);
645+
expect(drops).toEqual([]);
646+
// Its write enrolled in nothing. (This double's rollback restores a whole
647+
// store snapshot, so the row itself is not read here; the dogfood twin
648+
// reads it standing on SQLite.)
649+
expect(unenrolled(driver).filter(([o]) => o === 'note')).toEqual([['note', true]]);
650+
});
651+
652+
it('CONTROL afterFind outside any unit: the read\'s async hook starts at dispatch, unchanged', async () => {
653+
const { driver, api, events, bind, runOf, notes } = await makeCommitEngine();
654+
await api.object('rec').insert({ name: 'r0' });
655+
bind(false, { read: true });
656+
await api.object('rec').find({});
657+
events.push('find returns');
658+
await runOf('read');
659+
expect(events).toEqual(['read-hook started', 'find returns']);
660+
expect(driver.begun).toHaveLength(0);
661+
expect(notes()).toEqual(['note:read']);
662+
});
663+
578664
it('CONTROL outside any unit: the hook starts at dispatch, before the write returns, unchanged', async () => {
579665
const { driver, api, events, bind, runOf } = await makeCommitEngine();
580666
bind(false);

‎packages/objectql/src/engine.ts‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6540,15 +6540,17 @@ export class ScopedContext implements IScopedContext, RunAsDerivableApi {
65406540
* and the one this api carries treated as closed for the run
65416541
* (`runOutsideOpenUnits`, `unit-detach.ts`). Called by `wrapDeclarativeHook`
65426542
* when such a hook detaches, so its writes never enrol in a unit that
6543-
* commits under them. [#33760] Started once the unit it was dispatched in
6543+
* commits under them. [#33760] With `waitForCommit` (a write event's run,
6544+
* `waitsForUnitCommit`), started once the unit it was dispatched in
65446545
* commits, and answering `UNIT_ROLLED_BACK` without running when that unit
6545-
* rolls back (`runOutsideOpenUnitsOnCommit`); at once outside any unit.
6546+
* rolls back (`runOutsideOpenUnitsOnCommit`); at once outside any unit, and
6547+
* at once for any other event (`afterFind`).
65466548
*
65476549
* Keyed on {@link DETACHED_HOOK_RUN}, a symbol the package entry does not
65486550
* export, so it is no nameable member of this class's published face.
65496551
*/
6550-
[DETACHED_HOOK_RUN]<T>(body: () => Promise<T>): Promise<T | typeof UNIT_ROLLED_BACK> {
6551-
return (ScopedContextFacet.detachedHookRun<T>).call(scopedContextHost.of(this), body);
6552+
[DETACHED_HOOK_RUN]<T>(body: () => Promise<T>, waitForCommit: boolean): Promise<T | typeof UNIT_ROLLED_BACK> {
6553+
return (ScopedContextFacet.detachedHookRun<T>).call(scopedContextHost.of(this), body, waitForCommit);
65526554
}
65536555

65546556
/**

‎packages/objectql/src/hook-wrappers.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ import { materializeDeclaredFields } from './declared-fields.js';
2424
import { describeCelFault, type CelFault } from './cel-fault.js';
2525
import { nullPreviousReadDetail, ruleScope, type PreviousBinding } from './validation/rule-validator.js';
2626
import { hookRunAs, deriveHookApi, deriveAppAuthoredHookApi, seedHookUserGrants, seedHookUnreadMembership, type HookRunAs } from './hook-run-as.js';
27-
import { runDetachedHook, UNIT_ROLLED_BACK } from './unit-detach.js';
27+
import { runDetachedHook, UNIT_ROLLED_BACK, waitsForUnitCommit } from './unit-detach.js';
2828

2929
/**
3030
* The logger the hook layer writes its diagnostics to — the `Logger` CONTRACT
@@ -534,8 +534,10 @@ export function wrapDeclarativeHook(
534534
// caller's: nothing awaits it, so a unit it joined would commit under
535535
// its writes ("Transaction query already complete"). [#33760] Once
536536
// that unit commits, and not at all when it rolls back — the unit read
537-
// off `engineApi`, whatever api the handler itself runs on. `unit-detach.ts`.
538-
void runDetachedHook(engineApi, () => runWithErrorPolicy(dispatching ? detached : atDispatch))
537+
// off `engineApi`, whatever api the handler itself runs on. Only for a
538+
// write event: a rollback does not undo a read, so an `afterFind` run
539+
// starts now. `unit-detach.ts`.
540+
void runDetachedHook(engineApi, () => runWithErrorPolicy(dispatching ? detached : atDispatch), waitsForUnitCommit(ctx.event))
539541
.then((ran) => {
540542
if (ran !== UNIT_ROLLED_BACK) { recordOutcome(); return; }
541543
logger.debug('[hook] async handler not run: the unit of work it was fired in rolled back', {

‎packages/objectql/src/unit-detach.ts‎

Lines changed: 33 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,18 @@
5353
* sandbox runner's `ctx.api.transaction(fn)` — opens one per handle it owns
5454
* ({@link openTrioCommitQueue}). Outside any unit, or where no unit opened
5555
* (a driver without transactions), the run starts at dispatch, as before.
56+
*
57+
* Only a WRITE event's run waits ({@link waitsForUnitCommit}). A rollback
58+
* undoes the write that fired `afterInsert` / `afterUpdate` / `afterDelete`,
59+
* so a run that announces it must not outlive it. It does not undo a read:
60+
* the rows `afterFind` saw were already returned to the caller, so an `async`
61+
* `afterFind` run starts at dispatch, outside the units, as under #33651,
62+
* whatever the unit it was read in does next.
63+
*
64+
* Every run a unit queued starts in one synchronous pass once it commits, in
65+
* dispatch order: a bulk write with a per-row `async` hook holds one context
66+
* copy per row until then, bounded by the per-row hook budget
67+
* (`resolveBulkPerRowHookBudget`), and then starts every handler at once.
5668
*/
5769

5870
import { AsyncLocalStorage, AsyncResource } from 'node:async_hooks';
@@ -84,6 +96,18 @@ export function runOutsideOpenUnits<T>(
8496
return typeof txStore?.exit === 'function' ? txStore.exit(run) : run();
8597
}
8698

99+
/**
100+
* The events whose `async` run waits for the commit of the unit it was
101+
* dispatched in, and is dropped when that unit rolls back: the `after*`
102+
* events of a write. Any other event (`afterFind`) starts at dispatch.
103+
*/
104+
const UNIT_SETTLED_EVENTS: ReadonlySet<string> = new Set(['afterInsert', 'afterUpdate', 'afterDelete']);
105+
106+
/** Does an `async` run dispatched for `event` wait for its unit's commit? */
107+
export function waitsForUnitCommit(event: unknown): boolean {
108+
return typeof event === 'string' && UNIT_SETTLED_EVENTS.has(event);
109+
}
110+
87111
/** What a detached run answers when the unit it waited for rolled back: the body never ran. */
88112
export const UNIT_ROLLED_BACK: unique symbol = Symbol('objectstack.objectql.unitRolledBack');
89113

@@ -193,26 +217,27 @@ export function runOutsideOpenUnitsOnCommit<T>(
193217

194218
/**
195219
* The key of `ScopedContext#[DETACHED_HOOK_RUN]`, which runs a body outside
196-
* the units open for that api, once the unit it was dispatched in commits
197-
* ({@link runOutsideOpenUnitsOnCommit}). A symbol, and ⛔
220+
* the units open for that api, at once or once the unit it was dispatched in
221+
* commits ({@link runOutsideOpenUnitsOnCommit}). A symbol, and ⛔
198222
* not re-exported from the package entry, for the reason `SEED_USER_GRANTS`
199223
* gives (`hook-run-as.ts`): it is no nameable member of the class's published
200224
* face.
201225
*/
202226
export const DETACHED_HOOK_RUN: unique symbol = Symbol('objectstack.objectql.detachedHookRun');
203227

204228
interface DetachableHookApi {
205-
[DETACHED_HOOK_RUN]<T>(body: () => Promise<T>): Promise<T | typeof UNIT_ROLLED_BACK>;
229+
[DETACHED_HOOK_RUN]<T>(body: () => Promise<T>, waitForCommit: boolean): Promise<T | typeof UNIT_ROLLED_BACK>;
206230
}
207231

208232
/**
209233
* Run an `async` hook's `body` detached from the units open for `api`, the
210-
* hook's `ctx.api`, once the unit it was dispatched in commits; answers
211-
* {@link UNIT_ROLLED_BACK} when that unit rolls back instead. An api that
212-
* cannot detach (a hook context assembled by hand) runs `body` as is.
234+
* hook's `ctx.api`. With `waitForCommit` ({@link waitsForUnitCommit}), once the
235+
* unit it was dispatched in commits, answering {@link UNIT_ROLLED_BACK} when
236+
* that unit rolls back instead; without it, at once. An api that cannot
237+
* detach (a hook context assembled by hand) runs `body` as is.
213238
*/
214-
export function runDetachedHook<T>(api: unknown, body: () => Promise<T>): Promise<T | typeof UNIT_ROLLED_BACK> {
239+
export function runDetachedHook<T>(api: unknown, body: () => Promise<T>, waitForCommit: boolean): Promise<T | typeof UNIT_ROLLED_BACK> {
215240
const detachable = api as Partial<DetachableHookApi> | undefined;
216241
if (!detachable || typeof detachable[DETACHED_HOOK_RUN] !== 'function') return body();
217-
return detachable[DETACHED_HOOK_RUN](body);
242+
return detachable[DETACHED_HOOK_RUN](body, waitForCommit);
218243
}

0 commit comments

Comments
 (0)