Skip to content

Commit 8071f35

Browse files
fix(automation): a record-change flow's run history and notification deliveries land when the triggering write runs in a unit of work (#37742)
<!-- claude-projects-attribution: {"github_login":"os-sales"} --> _Requested by **Sales** · [project thread](https://claude.ai/code/project/chan_01D5bWFY3rFzgJcytD5gD4Uu?thread=cmsg_01D5bWFY3rFzgJcytD5gD4UuT6upE7mQVRYxkhAeA5UjwM)_ Fixes #37705 Clause-②: yes (widening) — `ObjectQL` is exported from the `@objectstack/objectql` entry, and it gains two public methods, `runOutsideOpenUnits(body)` and `runAfterOpenUnitsCommit(body)`; `@objectstack/core` gains the root export `wakeAfterOpenUnitsCommit(engine, wake)`; the `@objectstack/service-automation` interface `SuspendedRunStoreEngine` gains the matching optional member `runOutsideOpenUnits`, so an engine that does not supply it still satisfies the interface. No existing signature or accepted input narrows. `DispatchLoop`'s change is to the async context its ticks run in, and the dispatchers' change is to when a wake is sent, not to any API. The level stays `patch` because nothing a metadata author can write changes (`Metadata-protocol: none`). Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:记录变更触发的流程(例如 hotcrm 的线索分配)跑完后,运行历史和通知投递、活动记录不再丢失;运行历史会在保存返回后片刻落库,而不是和那次保存同时落库。 - 为什么做:hotcrm 移植到框架 19 被这个问题挡住,6 个线索分配测试失败;任何在保存时带钩子的对象上跑流程的应用都会丢运行历史。 - 出错会怎样:最坏是运行历史晚一点出现或重新丢失,业务数据本身不受影响;改动可直接回滚。 - 要你做什么:无。 ## What changes On 19.0.0-next.0 (and on `main` at `0f8e13b0`), a record-change flow fired by a write whose object carries a metadata `before*` hook, or a blocking `after*` hook that can abort, runs inside the unit of work the write door opens for that write (`inAfterAbortUnit`). Two pieces of work the run starts and does not await then took that unit's transaction handle while it was still open, and ran their statements after it had committed, so knex answered "Transaction query already complete": 1. **The terminal run-history write** (`ObjectStoreSuspendedRunStore.recordTerminal`, fired and forgotten from `run-history.ts`). Its first `find` on `sys_automation_run` failed, so the run's history row never landed. 2. **The notification dispatcher's tick**, started by the `notify` node's outbox wake (`DispatchLoop.wake()`) in the same async context. Its delivery updates failed, and so did the `sys_activity` audit rows they fire; the timer each tick sets inherited the same context, so later ticks did too. The fix, one mechanism per producer: - `packages/objectql/src/engine.ts`: new public `ObjectQL.runOutsideOpenUnits(body)`. It runs work its caller starts and does not await outside every unit open at the call, through the same `runOutsideOpenUnits` exit an `async: true` hook's run already takes (`unit-detach.ts`): out of the ambient entry, with that entry's handle recorded as detached. - `packages/services/service-automation/src/suspended-run-store.ts`: `recordTerminal` runs its whole write (the read, the insert or update, the retention prune) through the engine's `runOutsideOpenUnits`. `SuspendedRunStoreEngine` gains it as an optional member, so a double without units keeps running the write where it is. - `packages/core/src/dispatch-loop.ts`: `DispatchLoop` (the notification, HTTP-delivery, database-queue and audit-seal loops) runs every tick, its due-time read and the timer for the next tick in the async context it was constructed in, never the context of the caller of `start()`, `wake()` or `wakeAt()`. Its docblock now states that a loop is constructed at boot, and names `DbQueueAdapter.start()` reached from `subscribe()` under `autoStart` (review F-5). - **The wake waits for the commit (review F-2, option a).** A tick woken inside a unit now runs outside it, and on a pooled driver (Postgres, MySQL) it cannot see the outbox or queue row the unit has not committed yet, so that row would wait for a backed-off tick (up to `maxIdleIntervalMs`, 30 s, under `soleWriter`). New public `ObjectQL.runAfterOpenUnitsCommit(body)` (`unit-detach.ts`) runs `body` outside the units once the ambient unit commits, never when it rolls back, at once when no unit is open, on the same `UnitCommitQueue` the write events' `async` runs wait on (#33760). `wakeAfterOpenUnitsCommit(engine, wake)` (new, `@objectstack/core`) sends a wake through it, or at once on an engine without it. Wired at the notification and HTTP outboxes' `onEnqueued` (`messaging-service-plugin.ts`) and at the DB queue's due `publish` and `replay` (`db-queue-adapter.ts`). A deferred `publish` keeps `wakeAt` (a timer hint, no read now). A `ScopedContext` `beginTransaction` trio unit holds the wake back while an engine call carrying its handle runs (`publishTrioHandleFor` publishes the handle with the trio's queue); a wake made outside such a call, by code that holds the trio handle only explicitly, goes at once and on a pooled driver waits one backed-off tick (review F-6, accepted). `engine.ts` stays within its line ceiling (6856 of 6857): the `[DETACHED_HOOK_RUN]` docblock lost one line, wording only. Behaviour a reader can see: a run's history row is written beside the run, not inside the triggering write's unit. It is not rolled back with that write, and it can land a moment after the write has returned, as it already could for any run outside a unit (the run-history write was never awaited). A test that reads a run's history once, straight after the write that fired it, has to wait for it to land instead. Branch: `claude/project-thread-a7kaf6`, the name the harness assigned this card thread, not `claude/issue-37705-*`. ## Tests - `packages/objectql/src/engine-scoped-transaction-late-write.test.ts`, new top-level describe `#37705`: a driver that refuses a finished handle as knex does, and holds a read until after the commit. CONTROL: a read started bare inside `engine.transaction()` took the unit's handle and fails with "Transaction query already complete". The same read through `runOutsideOpenUnits` reaches the driver with no handle and answers. A unit the detached body opens is its own. - `packages/services/service-automation/src/suspended-run-store.test.ts`, new describe `#37705`: every statement of the terminal write (find, insert, update, the prune's delete) runs inside `runOutsideOpenUnits`; an engine without it still gets the row. - `packages/core/src/dispatch-loop.test.ts`, new describe `#37705`: a tick, its due-time read and the next timer tick see none of an `AsyncLocalStorage` store the caller of `wake()`, `start()` or `wakeAt()` was in. A second describe: `wakeAfterOpenUnitsCommit` hands the wake to the engine's `runAfterOpenUnitsCommit`, and wakes at once without it. - `packages/objectql/src/engine-scoped-transaction-late-write.test.ts`, second `#37705` describe: inside a unit the signal runs after the commit (`body done`, `commit`, `signal`); a read it starts reaches the driver with no handle; a rolled-back unit sends none; with no unit it runs before the call returns. - `packages/services/service-queue/src/db-queue-idle-backoff.test.ts`, new describe `#37705`: under an engine that holds the signal as an open unit does, a due `publish` runs no tick until the commit and then delivers within the base interval; a `replay` hands its wake over too. - `packages/services/service-messaging/src/plugin-enqueue-wakes-dispatcher.test.ts`, new describe `#37705` on the composed plugin and a real engine: an `emit()` inside `objectql.transaction()` hands its wake to `runAfterOpenUnitsCommit` once, nothing is sent while the unit is open, and the delivery goes out after the commit. Reverse verification (fix committed first, then each source file put back to its `main` body, `engine.ts` by making the method `return body()`): the two `#37705` cases in each of the three files go red (6 of 6), the control stays green, and restoring HEAD gives `git diff HEAD` empty. Round 2 at 92c84c3, the same way: `runAfterOpenUnitsCommit` running at once (2 red: commit order, rollback), `wakeAfterOpenUnitsCommit` never deferring (1 red), the queue's two wakes back to `this.wake()` (2 red), the notification outbox's `onEnqueued` back to a bare wake (1 red); 6 of 6, `git diff HEAD` empty after each. <details><summary>Local runs (tree: objectstack-ai/objectstack, head f94bcab; 62064b5 below)</summary> - `pnpm --filter @objectstack/core test`: Tests 3797 passed (3797); `typecheck` exit 0. - `pnpm --filter @objectstack/objectql test`: Tests 14435 passed (14435); `typecheck` exit 0. - `pnpm --filter @objectstack/service-messaging test`: Tests 1108 passed (1108); `typecheck` exit 0. - `pnpm --filter @objectstack/service-queue test`: Tests 93 passed (93); `typecheck` exit 0. - `pnpm --filter @objectstack/service-automation test`: Tests 4322 passed (4322); `typecheck` exit 0. - All under `os-verify-lock.sh` (VERDICT command-exit 0), after a `turbo run build` of the five packages with declarations. - `dispatch-gates.mjs --commands` at f94bcab derived 79 families; `--ran` reconciles 79: 78 run, all exit 0 (`check:facade-delegation-only`, `check:query-options-erasure`, `check:dts-closure` and `check:dual-build-cjs-loads` included), 1 NOT MEASURED (exit 3, prerequisite not met in this shallow tree: `check-plugin-teardown-shape --self-test`). - `check-adr-0087-registration`, `check-changeset-no-major`, `check-empty-changeset` green. - At 62064b5 (docs and comment wording only: `webhooks.mdx`, the `unit-detach.ts` docblock, the changeset): `dispatch-gates --commands` derives 110 families, the 31 the docs page adds all run and exit 0, `check:facade-delegation-only` and `check:query-options-erasure` re-ran green, and `engine-scoped-transaction-late-write.test.ts` re-ran green. - Full dogfood battery: not owed (no `!` in the title, no `(narrowing)` arm). Round 1's sweep files were run at aed7894 (table above); round 2 changes when a wake is sent, not what the swept tests read. </details> ## Read-after-write sweep (seat ask) What moved: only a run's terminal history row in `sys_automation_run`, and only for a run fired inside a unit. `listRuns`, `listRunsPage` and `getRun` answer from the in-memory run log first (`run-history.ts`), so an in-process read through them sees the run as soon as it finishes, as before. Delivery rows (and the `sys_activity` rows their updates fire) for a wake made inside a unit go out once the unit commits, through the commit-time wake above, on every driver, except a wake made outside an engine call that carries a trio handle (review F-6); before review F-2 this sentence held only on a single-connection pool. What can now miss is a test that reads the durable row itself (`ql.find('sys_automation_run')`, `/data/sys_automation_run`, `loadTerminal`) once, straight after the write. Checked against this branch's build (every file green, no edit needed): | File | Reads | Verdict | |---|---|---| | `packages/qa/dogfood/test/install-local-uninstall-flows-withdrawn.dogfood.test.ts` | durable rows | already a bounded wait (`settledRunCounts`, 10 s) | | `packages/plugins/plugin-approvals/src/save-notice-approval-round-trip.integration.test.ts` | durable terminal row | already a bounded wait (100 × 20 ms) | | `packages/qa/dogfood/test/flow-shipped-name-stored-row-boot.dogfood.test.ts` | `listRuns` | already a bounded wait (50 × 100 ms) | | `packages/qa/dogfood/test/flow-trigger-record-credential-mask.dogfood.test.ts`, `flow-durable-suspend.dogfood.test.ts` | durable `paused` rows | the pause write is awaited, unchanged | | `packages/qa/dogfood/test/flow-name-per-namespace.dogfood.test.ts`, `automation-stored-reference-package-column.dogfood.test.ts` | rows the test seeds itself; `getRun` | not a run's terminal write | | `packages/qa/dogfood/test/flow-condition-scope-keys`, `flow-door-elevated-start`, `seed-ownership-claim-dispatch` (`.dogfood.test.ts`) | `listRuns` / resume door | in-memory log | | `packages/verify/src/action-flow-elevated-door`, `automation-trigger-elevated-door`, `handle.flows-system-start`, `handle.public-form-door`, `handle.system-insert-delete`, `handle.update-doors` (`.test.ts`) | `listRuns` | in-memory log | | `packages/plugins/plugin-approvals/src/batch-item-recall-resumes-batch.test.ts` | `getRun` | in-memory log | | `packages/runtime/src/domains/automation-run-detail-passthrough`, `automation-screen-read-gate`, `automation-resume-caller-gate`, `automation-run-read-permission-gate`, `automation-write-capability-gate` (`.test.ts`) | stubbed engine | no store | | `packages/plugins/organizations/src/elevated-organization-wall.postures.wall.test.ts` | flow side effects | green | | `examples/app-todo/test/task-completion-trigger.test.ts`, `task-recurrence.test.ts`; `examples/app-showcase/test/approver-bindings-specimen-unarmed.test.ts` | `listRuns` | in-memory log | | `packages/services/service-automation/**` | all | full package suite green (4322) | Runs: dogfood 51 + 26, verify 70, runtime 25, organizations 10, plugin-approvals 3 + 10, example-todo 27, example-showcase 4, all passed. Found by grepping `packages/` and `examples/` test files for `sys_automation_run`, `listRuns`, `getRun`, `loadTerminal`, `/runs` and `sys_activity` next to a record-change trigger. **hotcrm** (not in this PR): in PR #2820's `test/flow-record-change.test.ts`, the three `case_escalation` cases at lines 205, 263 and 787 read the durable row once and must switch to the file's own `landedRuns` wait (details under Acceptance notes). ## Acceptance notes - **hotcrm.** hotcrm PR #2820's head `03a2647`, with every `@objectstack/*` package except `console` swapped for this branch's build: `test/flow-record-change.test.ts` answers 6 failed / 50 passed on `main` (`0f8e13b0`, the same 6 as on `19.0.0-next.0`) and 0 "Transaction query already complete" lines with the fix. Three `case_escalation` cases (lines 205, 263 and 787 there) then read the run's history once, straight after the write, and find nothing yet: on `main` the row was written inside the triggering write's unit and was visible when the write returned. With those three reads switched to the file's own `landedRuns` (wait for the row), the file is 56 / 56. That three-line change belongs to the hotcrm port, not to this PR. - A framework end-to-end twin of the hotcrm run was not kept: a booted fixture (record-after-create flow, `update_record`, a metadata `before*` and blocking `after*` hook, `AuditPlugin`) did not reproduce the race on SQLite, because nothing there held the history read between its handle and its statement. The engine-level pin holds that step by construction instead. - Accepted deviations from review: F-1, the terminal history row outlives a rolled-back triggering write. F-7, an outbox or queue table on a datasource the open unit does not cover commits its row on its own connection while the wake rides the unit's queue, so a rollback drops that wake and the row goes out on the next backed-off tick (at most `maxIdleIntervalMs`); no in-tree composition was measured that way. - Docs: `content/docs/automation/webhooks.mdx` now says a delivery `enqueueHttp()` or `redeliverHttp()` writes inside a transaction goes out at its commit, and not at all on a rollback (review F-9). - Same class elsewhere: any other work a run or a hook starts inside a unit and does not await can take the unit's handle the same way. This PR fixes the two producers the hotcrm run measured; `ObjectQL.runOutsideOpenUnits` is the exit for the next one. ## Verification Two-minute check: `pnpm --filter @objectstack/objectql exec vitest run src/engine-scoped-transaction-late-write.test.ts -t 37705`, which shows the control failing with "Transaction query already complete" and the detached read answering. Read first: 1. `packages/services/service-automation/src/suspended-run-store.ts` `recordTerminal`: the write leaves the caller's units; it no longer commits or rolls back with the triggering write. 2. `packages/core/src/dispatch-loop.ts` `loopTickAtHome` / `wakeAt`: every loop's ticks now run in the context the loop was constructed in; `wakeAfterOpenUnitsCommit` and the `unit-detach.ts` `runAfterOpenUnitsCommit` it reaches: a wake made in a unit goes at its commit. 3. `packages/objectql/src/engine.ts` `runOutsideOpenUnits`: the new public engine member. --- _Generated by [Claude Code](https://claude.ai/code/session_01L6bhgX3p4cHBBQ11Sjokrq)_ 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01L6bhgX3p4cHBBQ11Sjokrq <!-- signed: repo:objectstack#2 · os-sales · session_01L6bhgX3p4cHBBQ11Sjokrq --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 3ed97b7 commit 8071f35

13 files changed

Lines changed: 543 additions & 18 deletions
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
---
2+
'@objectstack/objectql': patch
3+
'@objectstack/service-automation': patch
4+
'@objectstack/core': patch
5+
'@objectstack/service-messaging': patch
6+
'@objectstack/service-queue': patch
7+
---
8+
9+
fix(automation): a record-change flow's run history and its notification deliveries land again when the triggering write runs in a unit of work
10+
11+
Clause-②: yes (widening) — `ObjectQL` is exported from the `@objectstack/objectql` entry, and it gains two public methods, `runOutsideOpenUnits(body)` and `runAfterOpenUnitsCommit(body)`; `@objectstack/core` gains the root export `wakeAfterOpenUnitsCommit(engine, wake)`; the `@objectstack/service-automation` interface `SuspendedRunStoreEngine` gains the matching optional member `runOutsideOpenUnits`, so an engine that does not supply it still satisfies the interface. No existing signature or accepted input narrows. `DispatchLoop`'s change is to the async context its ticks run in, and the dispatchers' change is to when a wake is sent, not to any API. The level stays `patch` because nothing a metadata author can write changes (`Metadata-protocol: none`).
12+
Metadata-protocol: none
13+
14+
On 19.0.0-next.0 a record-change flow fired by a write whose object carries a metadata `before*` hook, or a blocking `after*` hook that can abort, finished inside the unit of work the write door opens for that write. Two pieces of work the run starts and does not await then ran on that unit's transaction after it had committed, and the database answered "Transaction query already complete":
15+
16+
- the run's terminal history row (`sys_automation_run`) never landed, so the run was missing from the Runs surfaces and from every read of its history, with an `error` line naming the persist;
17+
- a `notify` node's outbox wake started the notification dispatcher's tick in the same unit, so the tick's delivery updates failed, and with them the audit rows (`sys_activity`) those updates write.
18+
19+
Both now run outside the unit:
20+
21+
- `ObjectQL.runOutsideOpenUnits(body)` is new: it runs work its caller starts and does not await outside every unit of work open at the call, the same exit an `async: true` hook's run takes. Its calls run on their own connection, and a rollback of the unit open at the call does not undo them.
22+
- The durable run-history store writes a finished run's row through it.
23+
- `DispatchLoop` (the notification, HTTP-delivery, database-queue and audit-seal loops) runs every tick in the async context it was constructed in, never in the context of the caller of `start()`, `wake()` or `wakeAt()`.
24+
- A wake for a row the open unit just wrote is sent at that unit's commit, and not at all when it rolls back: `ObjectQL.runAfterOpenUnitsCommit(body)` is new, and the notification and HTTP outboxes' wake and the database queue's `publish` and `replay` wake go through it (`wakeAfterOpenUnitsCommit` in `@objectstack/core`). A tick woken inside the unit runs outside it, and on a pooled driver (Postgres, MySQL) it could not see the row yet, so the row would have waited for a later, backed-off tick. A unit opened by `ScopedContext`'s `beginTransaction` trio holds the wake back while an engine call carrying its handle runs; a wake made outside such a call, by code that holds the trio handle only explicitly, goes at once, and on a pooled driver waits one backed-off tick.
25+
- A loop's home is the context it is constructed in, so a loop is constructed at boot; `DbQueueAdapter`'s first `subscribe()` under `autoStart` starts it too and belongs at boot.
26+
27+
What a reader sees change: a run's history row is written beside the run, not inside the triggering write's unit, so it is not rolled back with that write, and it can land a moment after the write has returned. Read it the way you read any history row written by a run that is not awaited: wait for it to land rather than reading it once straight after the write.

‎content/docs/automation/webhooks.mdx‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -495,7 +495,9 @@ delay to the next, from `intervalMs` (default 500 ms) up to `maxIdleIntervalMs`
495495
(default 30 s; `dispatchMaxIdleIntervalMs` on `MessagingServicePlugin`), and a
496496
tick that claims work snaps it back. `messaging.enqueueHttp()` and
497497
`messaging.redeliverHttp()` wake the dispatcher running in the same process, so
498-
a delivery written there goes out at once.
498+
a delivery written there goes out at once. Written inside a transaction, it goes
499+
out when that transaction commits, and not at all when it rolls back: until the
500+
commit the dispatcher could not see the row.
499501

500502
The loop also **wakes at the next due time**. After the first empty tick of an
501503
idle stretch it reads, once, the earliest instant a row becomes claimable

‎packages/core/src/dispatch-loop.test.ts‎

Lines changed: 76 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,9 @@
1515
* exact reading rather than a sleep-and-hope.
1616
*/
1717

18+
import { AsyncLocalStorage } from 'node:async_hooks';
1819
import { describe, it, expect, afterEach, vi } from 'vitest';
19-
import { DispatchLoop, type DispatchLoopOptions } from './dispatch-loop.js';
20+
import { DispatchLoop, wakeAfterOpenUnitsCommit, type DispatchLoopOptions } from './dispatch-loop.js';
2021

2122
const BASE = 500;
2223
const MINUTE = 60_000;
@@ -292,3 +293,77 @@ describe('#29919 DispatchLoop — nothing it reads can make it spin', () => {
292293
expect(h.tickStarts).toEqual([0]);
293294
});
294295
});
296+
297+
/**
298+
* #37705 — every tick runs in the loop's own async context, never the waker's.
299+
* The waker is typically a write that just enqueued work inside a unit of work;
300+
* a tick started in its context carried the unit's ambient handle into the
301+
* store it drains, and failed with "Transaction query already complete" once
302+
* the unit committed. The store here stands in for any ambient one (the
303+
* engine's unit entry, a request's identity): a tick and the due-time read it
304+
* makes must not see the waker's, and nor must the ticks its timer sets.
305+
*/
306+
describe('#37705 DispatchLoop — a tick runs in the loop\'s own context, not the waker\'s', () => {
307+
const ambient = new AsyncLocalStorage<string>();
308+
309+
function seeing() {
310+
const seen: Array<[string, string | undefined]> = [];
311+
const h = harness({
312+
runTick: async () => { seen.push(['tick', ambient.getStore()]); return 0; },
313+
nextDueAt: async () => { seen.push(['due', ambient.getStore()]); return null; },
314+
});
315+
return { ...h, seen };
316+
}
317+
318+
it('a wake() made inside a caller\'s store: the tick, its due read and the next timer tick see none of it', async () => {
319+
useClockAtZero();
320+
const h = seeing();
321+
h.loop.start();
322+
await vi.advanceTimersByTimeAsync(0);
323+
h.seen.length = 0;
324+
ambient.run('unit-of-the-waker', () => h.loop.wake());
325+
await vi.advanceTimersByTimeAsync(0);
326+
await vi.advanceTimersByTimeAsync(BASE * 4);
327+
await h.loop.stop();
328+
expect(h.seen.length, 'the wake ticked, and so did its timer').toBeGreaterThan(2);
329+
expect(h.seen.filter(([, store]) => store !== undefined)).toEqual([]);
330+
});
331+
332+
it('a start() and a wakeAt() made inside a caller\'s store: no tick sees it', async () => {
333+
useClockAtZero();
334+
const h = seeing();
335+
ambient.run('unit-of-the-starter', () => h.loop.start());
336+
await vi.advanceTimersByTimeAsync(0);
337+
ambient.run('unit-of-the-hinter', () => h.loop.wakeAt(BASE / 2));
338+
await vi.advanceTimersByTimeAsync(BASE);
339+
ambient.run('unit-of-the-hinter', () => h.loop.wakeAt(0));
340+
await vi.advanceTimersByTimeAsync(0);
341+
await h.loop.stop();
342+
expect(h.seen.filter(([what]) => what === 'tick').length, 'start, the hinted due time and the past hint each ticked').toBeGreaterThanOrEqual(3);
343+
expect(h.seen.filter(([, store]) => store !== undefined)).toEqual([]);
344+
});
345+
346+
it('CONTROL: the store the waker is in is real — a body run inside it sees it', () => {
347+
expect(ambient.run('unit-of-the-waker', () => ambient.getStore())).toBe('unit-of-the-waker');
348+
});
349+
});
350+
351+
describe('#37705 wakeAfterOpenUnitsCommit — a wake for a row a unit just wrote goes at its commit', () => {
352+
it('hands the wake to the engine\'s runAfterOpenUnitsCommit, which decides when it runs', () => {
353+
const held: Array<() => void> = [];
354+
const engine = { runAfterOpenUnitsCommit(body: () => void) { held.push(body); } };
355+
const woke: string[] = [];
356+
wakeAfterOpenUnitsCommit(engine, () => woke.push('wake'));
357+
expect(woke, 'not sent while the engine holds it').toEqual([]);
358+
expect(held).toHaveLength(1);
359+
held[0]!();
360+
expect(woke).toEqual(['wake']);
361+
});
362+
363+
it('an engine without it, or none, wakes at once', () => {
364+
const woke: string[] = [];
365+
wakeAfterOpenUnitsCommit({ find: async () => [] }, () => woke.push('plain'));
366+
wakeAfterOpenUnitsCommit(undefined, () => woke.push('none'));
367+
expect(woke).toEqual(['plain', 'none']);
368+
});
369+
});

‎packages/core/src/dispatch-loop.ts‎

Lines changed: 54 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,28 @@
3232
* request, then waits out the running tick; a `wake()` after it is a no-op.
3333
* The timer is `unref()`ed, so the loop never keeps a process alive by
3434
* itself.
35+
* - **Every tick runs in the loop's own async context** (#37705), the one it
36+
* was constructed in, never the context of whoever called `start()`,
37+
* `wake()` or `wakeAt()`. A wake is a request, not a hand-over: the caller
38+
* is typically a write that just enqueued work, often inside a unit of work
39+
* (the triggering write's, or a flow's), and a tick started in its context
40+
* carried that unit's ambient handle into the store it drains. The unit
41+
* then committed under the tick, which failed with "Transaction query
42+
* already complete", and so did the audit writes the tick's updates fired;
43+
* the timer a tick sets inherited the same context, so every later tick did
44+
* too. The same holds for any other ambient store (a request's identity, a
45+
* grants memo): a tick is the loop's work, not the waker's. ⛔ So construct
46+
* a loop at boot (a plugin's `start()` or `kernel:ready`, a service
47+
* constructor), never lazily inside a request or a unit: the context it is
48+
* constructed in is the one every tick runs in for good. `DbQueueAdapter`
49+
* builds its loop in `start()`, which `subscribe()` also reaches under
50+
* `autoStart`, so a first `subscribe()` belongs at boot too.
51+
* - **A wake for a row a unit of work just wrote goes at that unit's
52+
* commit** (#37705, {@link wakeAfterOpenUnitsCommit}). The tick runs outside
53+
* the unit, so on a pooled driver it cannot see the uncommitted row: woken
54+
* inside the unit, it finds nothing and the row waits for a backed-off
55+
* tick (up to `maxIdleIntervalMs` under `soleWriter`). A unit that rolls
56+
* back sends no wake, and has no row to wake for.
3557
*
3658
* The price of the backoff is paid in latency by work nobody wakes the loop
3759
* for — a deferred row coming due, a row another process wrote, a crashed
@@ -60,6 +82,8 @@
6082
* stores: five ticks in the first minute per loop, every one of them idle.
6183
*/
6284

85+
import { AsyncResource } from 'node:async_hooks';
86+
6387
/** Default ceiling of the idle backoff, in ms — see {@link DispatchLoopOptions.maxIdleIntervalMs}. */
6488
export const DEFAULT_MAX_IDLE_INTERVAL_MS = 30_000;
6589

@@ -102,6 +126,8 @@ export interface DispatchLoopOptions {
102126
}
103127

104128
export class DispatchLoop {
129+
/** The async context every tick runs in: the one this loop was constructed in. */
130+
private readonly home = new AsyncResource('DispatchLoop');
105131
private readonly intervalMs: number;
106132
private readonly maxIdleIntervalMs: number;
107133
private readonly runTick: () => Promise<number>;
@@ -144,7 +170,7 @@ export class DispatchLoop {
144170
this.idleTicks = 0;
145171
this.knownDueAt = null;
146172
this.dueReadOwed = true;
147-
this.loopTick();
173+
this.loopTickAtHome();
148174
}
149175

150176
/** Stop the loop and drain the in-flight tick. */
@@ -166,7 +192,7 @@ export class DispatchLoop {
166192
if (!this.running) return;
167193
this.idleTicks = 0;
168194
this.dueReadOwed = true;
169-
this.loopTick();
195+
this.loopTickAtHome();
170196
}
171197

172198
/**
@@ -186,10 +212,21 @@ export class DispatchLoop {
186212
const delayMs = dueAtMs - Date.now();
187213
if (delayMs <= 0) {
188214
this.dueReadOwed = true;
189-
this.loopTick();
215+
this.loopTickAtHome();
190216
return;
191217
}
192-
this.schedule(delayMs, true);
218+
// Set from the loop's own context, so the timer's tick runs there.
219+
this.home.runInAsyncScope(() => this.schedule(delayMs, true));
220+
}
221+
222+
/**
223+
* [#37705] {@link loopTick}, entered from the loop's own async context
224+
* ({@link home}) rather than the caller's: the tick, the due-time read and
225+
* the timer for the next tick are all set up there, so none of them carries
226+
* a store the caller had entered (a unit of work's handle, above all).
227+
*/
228+
private loopTickAtHome(): void {
229+
this.home.runInAsyncScope(() => this.loopTick());
193230
}
194231

195232
/**
@@ -305,6 +342,19 @@ export class DispatchLoop {
305342
}
306343
}
307344

345+
/**
346+
* [#37705] Send `wake` (a {@link DispatchLoop.wake} after an outbox or queue
347+
* insert) once the unit of work open at the call commits, through the
348+
* engine's `runAfterOpenUnitsCommit` (`@objectstack/objectql`): at once when no
349+
* unit is open, never when it rolls back. An engine without that member (a
350+
* double, a driver-level store) sends it at once, as before.
351+
*/
352+
export function wakeAfterOpenUnitsCommit(engine: unknown, wake: () => void): void {
353+
const defer = (engine as { runAfterOpenUnitsCommit?: (body: () => void) => void } | null | undefined)?.runAfterOpenUnitsCommit;
354+
if (typeof defer === 'function') defer.call(engine, wake);
355+
else wake();
356+
}
357+
308358
/** The earlier of two optional instants. */
309359
function earliest(a: number | null, b: number | null): number | null {
310360
if (a === null) return b;

0 commit comments

Comments
 (0)