Skip to content

Commit 1621f1e

Browse files
committed
fix(objectql): an async after-hook waits for its unit through the engine-built api, also under a user pin on a user-less trigger
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QsR2jTEivi2wogPpeo3xd5
1 parent 709b3ae commit 1621f1e

3 files changed

Lines changed: 64 additions & 6 deletions

File tree

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

Lines changed: 46 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -402,11 +402,30 @@ async function makeCommitEngine() {
402402
if (String(ctx.input.name).startsWith('veto')) throw new Error('refused by the gate');
403403
},
404404
} as unknown as Hook;
405-
const bind = (withGate: boolean) => bindHooksToEngine(engine, withGate ? [asyncNote, gate] : [asyncNote], { packageId: 'app:t', logger: logger as any });
405+
// [#33760 review] A `'user'` pin on a trigger that carries no user: the
406+
// handler's `ctx.api` is the unscoped api (`UnscopedHookApi`), which has no
407+
// engine and no detach of its own. It records the api it got, and touches no
408+
// data (that api refuses every data door).
409+
const apiKinds: string[] = [];
410+
const userPin = {
411+
name: 'user_pin', object: 'rec', events: ['afterInsert'], async: true, runAs: 'user', onError: 'log',
412+
handler: (ctx: any) => {
413+
const name = String(ctx.input.name);
414+
events.push(`user-pin started:${name}`);
415+
apiKinds.push(ctx.api?.constructor?.name);
416+
runOf(name);
417+
settle[name]!(0);
418+
},
419+
} as unknown as Hook;
420+
const bind = (withGate: boolean, opts: { userPin?: boolean } = {}) => bindHooksToEngine(
421+
engine,
422+
opts.userPin ? [userPin] : withGate ? [asyncNote, gate] : [asyncNote],
423+
{ packageId: 'app:t', logger: logger as any },
424+
);
406425
const api = new ScopedContext({ isSystem: true } as any, engine as any);
407426
const droppedRun = () => new Promise<string>((r) => { dropped = r; });
408427
const notes = () => driver.rowsOf('note').map((r: any) => r.name);
409-
return { engine, driver, api, events, drops, bind, runOf, droppedRun, notes };
428+
return { engine, driver, api, events, drops, bind, runOf, droppedRun, notes, apiKinds };
410429
}
411430

412431
describe('#33760 — an async after-hook fired inside a unit runs on its commit, never on its rollback', () => {
@@ -531,6 +550,31 @@ describe('#33760 — an async after-hook fired inside a unit runs on its commit,
531550
expect(notes()).toEqual([]);
532551
});
533552

553+
it('runAs \'user\' on a user-less system write in engine.transaction(): the unscoped api still waits for the commit', async () => {
554+
const { engine, events, bind, runOf, apiKinds } = await makeCommitEngine();
555+
bind(false, { userPin: true });
556+
await engine.transaction(async (trx: any) => {
557+
await engine.insert('rec', { name: 'r1' }, { context: { ...trx, isSystem: true } });
558+
events.push('callback returns');
559+
});
560+
await runOf('r1');
561+
expect(events).toEqual(['callback returns', 'commit', 'user-pin started:r1']);
562+
expect(apiKinds).toEqual(['UnscopedHookApi']);
563+
});
564+
565+
it('runAs \'user\' on a user-less system write in engine.transaction() that rolls back: the hook never starts', async () => {
566+
const { engine, events, drops, bind, droppedRun } = await makeCommitEngine();
567+
bind(false, { userPin: true });
568+
const drop = droppedRun();
569+
await expect(engine.transaction(async (trx: any) => {
570+
await engine.insert('rec', { name: 'r1' }, { context: { ...trx, isSystem: true } });
571+
throw new Error('the caller rolls back');
572+
})).rejects.toThrow('the caller rolls back');
573+
expect(await drop).toBe('user_pin');
574+
expect(events).toEqual(['rollback']);
575+
expect(drops).toEqual(['user_pin']);
576+
});
577+
534578
it('CONTROL outside any unit: the hook starts at dispatch, before the write returns, unchanged', async () => {
535579
const { driver, api, events, bind, runOf } = await makeCommitEngine();
536580
bind(false);

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

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -475,6 +475,13 @@ export function wrapDeclarativeHook(
475475
}
476476

477477
const restore = installFlatInput(ctx);
478+
// [#33760] The engine-built api, held before a `runAs` install replaces it:
479+
// the unit an `async` run waits for is the one the TRIGGERING write is in,
480+
// and only this api knows it. A derived api need not — the unscoped one a
481+
// `'user'` pin gets on a user-less trigger (`UnscopedHookApi`) carries no
482+
// engine and no detach at all, so asking it would start the run at once,
483+
// inside the unit, and after a rollback too.
484+
const engineApi = ctx.api;
478485
// [#14010] `runAs` is applied to `ctx.api` ONLY, and only for the handler
479486
// call — the same install/restore shape as the flat input above, so the
480487
// engine's own context object is never touched (the condition gate above
@@ -526,8 +533,9 @@ export function wrapDeclarativeHook(
526533
// the door's own unit for a blocking `after*` beside it (#22782), or a
527534
// caller's: nothing awaits it, so a unit it joined would commit under
528535
// its writes ("Transaction query already complete"). [#33760] Once
529-
// that unit commits, and not at all when it rolls back. `unit-detach.ts`.
530-
void runDetachedHook(detached.api, () => runWithErrorPolicy(dispatching ? detached : atDispatch))
536+
// 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))
531539
.then((ran) => {
532540
if (ran !== UNIT_ROLLED_BACK) { recordOutcome(); return; }
533541
logger.debug('[hook] async handler not run: the unit of work it was fired in rolled back', {

‎packages/spec/src/data/hook.zod.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -493,7 +493,11 @@ export type HookRefusal = z.input<typeof HookRefusalSchema>;
493493
* write happened". They are dispatched before the enclosing transaction (if
494494
* there is one) commits, so a later refusal can roll the row back after the
495495
* hook has already run. Ruled on #7477 (2026-08-11) as the declared semantics,
496-
* not an implementation detail to be re-timed later.
496+
* not an implementation detail to be re-timed later. A blocking hook RUNS at
497+
* that dispatch; an `async: true` hook is dispatched there too but runs only
498+
* once the unit commits, and never when it rolls back (#33760, see `async`
499+
* below) — so for an async hook, what this section says about a hook that
500+
* "has already run" does not apply.
497501
*
498502
* Four ordinary ways a write ends up inside such a unit:
499503
* - the write door itself, when the object has a blocking (not `async`)
@@ -521,7 +525,9 @@ export type HookRefusal = z.input<typeof HookRefusalSchema>;
521525
* file deletion, email. On a rollback the row survives and the
522526
* announcement has already gone out. Make such an effect idempotent and
523527
* reconcilable, or enqueue it for a worker that re-reads the row before
524-
* acting rather than trusting the event alone.
528+
* acting rather than trusting the event alone. This is a blocking hook's
529+
* burden: an `async: true` hook runs only after the commit, so it never
530+
* announces a write that was rolled back.
525531
*
526532
* The `before*` events carry no such caveat: they run before the write is
527533
* issued, and throwing from one refuses the operation.

0 commit comments

Comments
 (0)