Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

publication-deadline: injectable scheduler on PublicationBound; the deadline test drives a manual clock (GBRA-40 flake)

garrytancac26b28e9d9
diff --git a/docs/architecture/key-files/persistence-stalls.md b/docs/architecture/key-files/persistence-stalls.md
index fd77dcfcc8..6757ec94f8 100644
--- a/docs/architecture/key-files/persistence-stalls.md
+++ b/docs/architecture/key-files/persistence-stalls.md
@@ -47,5 +47,5 @@ owner (`owner_wedged_here`), movement surfaces (`data_moving`, doctor
- `src/core/persistence/consumer-lane.ts` — #6317 (reporter ask 2): `consumerStatementEngine`, the Proxy that routes the consumer's own tick statements (idle probe, switch read, recovery and expired-claim scans, capacity, releases, floor) to `executeRawDirect` while the dual pool is active (`GBRAIN_DIRECT_DATABASE_URL` or the Supabase-derived direct URL), so the owner's round-trips avoid a transaction-mode pooler; `status().connection = { lane, pooler_mode, direct_host? }` says which lane is in use, and one `[persistence] phase=start reason=transaction_pooler` line prints when only a `prepare=false` URL exists.
- `src/core/persistence/consumer-diagnostics.ts` — #6317 (B3, I1): `hostConsumersReport` (the `host.consumers` block of `writer status --json`), `consumerOverlap` (two resident-kind full rows alive over 30 s), `ownersWithoutHeartbeat` (claim owners on running claims with no row) and `hostIdentityMismatches` (this process's `host.json` id differs from a binding owner's while the owner's checkout resolves on this filesystem or the machine id matches), read-only and shared by doctor and writer status.
- `src/core/postgres-engine/pool-stats.ts` — #6317 (C1, G1): `driverPoolStats(sql)` reads the vendored postgres.js driver's `sql.pool` getter (`vendor/postgres`, patch regenerated) for real `{checked_out, max, waiters}`; `enginePoolStats(engine)` labels the source (`driver` or `tracked_subset` from `pool-gauge.ts`). Filled into the heartbeat row, `writer status` running claims and `getPoolDiagnostics()`.
-- `src/core/persistence/publication-deadline.ts` (#6288 part 1, #6352; UC2) — what bounds a publish that neither resolves nor rejects. On Postgres the publish transaction is the real bound: `declareDurablePersistence` already sets a transaction-local `statement_timeout` (5 s) and `lock_timeout`, and `bindPublicationTimeouts` (first statement of `publishMutation`'s and `publishGroup`'s transactions, pipelined, no extra round trip) adds a transaction-local `idle_in_transaction_session_timeout` of `persistence.publication_ceiling_ms` (default 300000, 60000 to 3600000; never above the pool's own `GBRAIN_IDLE_TX_TIMEOUT`), so a publisher stuck between statements is ended by the server and commits nothing; both survive a transaction pooler that drops startup parameters. Never set on PGLite: it would enforce the bound, and a transaction it ends wedges the engine's only connection. `boundPublication` (the consumer's single path and `executeClaimedGroup`'s group publish and per-member fallback) settles only with the publish's own outcome, so nothing releases or reports a request or group while its transaction can still commit; at the ceiling the claim stamp reads `waiting_on: publication_deadline`, after `PUBLICATION_GRACE_MS` (30 s) it aborts the publication's signal (passed to `engine.transaction(fn, { signal })` through `publicationTransaction`: on Postgres the connection is discarded and nothing commits; the rejection waits for the transaction body to settle, then surfaces with the driver's `CONNECTION_CLOSED` code, so the claim is requeued for a retry; PGLite checks the signal only before BEGIN), and after `PUBLICATION_SETTLE_MS` (5 s) more the consumer lists it in `stuck_publications` and reports `restart_required` (its root stays held: restarting the owner is the recovery, never a promised reclaim). The lease keeps renewing, so a reclaim never races a publisher that may still write files. The wave 9 yield between groups is outside any one bound. Tests: `test/persistence-publication-deadline.test.ts` (barriers after the token lock, after the file rename and before commit; the server-side idle end on Postgres; the wiring probe).
+- `src/core/persistence/publication-deadline.ts` (#6288 part 1, #6352; UC2) — what bounds a publish that neither resolves nor rejects. On Postgres the publish transaction is the real bound: `declareDurablePersistence` already sets a transaction-local `statement_timeout` (5 s) and `lock_timeout`, and `bindPublicationTimeouts` (first statement of `publishMutation`'s and `publishGroup`'s transactions, pipelined, no extra round trip) adds a transaction-local `idle_in_transaction_session_timeout` of `persistence.publication_ceiling_ms` (default 300000, 60000 to 3600000; never above the pool's own `GBRAIN_IDLE_TX_TIMEOUT`), so a publisher stuck between statements is ended by the server and commits nothing; both survive a transaction pooler that drops startup parameters. Never set on PGLite: it would enforce the bound, and a transaction it ends wedges the engine's only connection. `boundPublication` (the consumer's single path and `executeClaimedGroup`'s group publish and per-member fallback) settles only with the publish's own outcome, so nothing releases or reports a request or group while its transaction can still commit; at the ceiling the claim stamp reads `waiting_on: publication_deadline`, after `PUBLICATION_GRACE_MS` (30 s) it aborts the publication's signal (passed to `engine.transaction(fn, { signal })` through `publicationTransaction`: on Postgres the connection is discarded and nothing commits; the rejection waits for the transaction body to settle, then surfaces with the driver's `CONNECTION_CLOSED` code, so the claim is requeued for a retry; PGLite checks the signal only before BEGIN), and after `PUBLICATION_SETTLE_MS` (5 s) more the consumer lists it in `stuck_publications` and reports `restart_required` (its root stays held: restarting the owner is the recovery, never a promised reclaim). The lease keeps renewing, so a reclaim never races a publisher that may still write files. The wave 9 yield between groups is outside any one bound. `PublicationBound.later` is the scheduler seam (default a real unref'd timer); the unit test drives the three phases through a manual clock so a stalled runner cannot fire a phase early (the consumer's `clock` seam is separate). Tests: `test/persistence-publication-deadline.test.ts` (barriers after the token lock, after the file rename and before commit; the server-side idle end on Postgres; the wiring probe).
- `src/core/persistence/sync-discovery.ts` (#6349 staged catch-up) — when an incremental delta (not `--full`, not company) exceeds the cursor bound (100,000 entries, 16 MiB; `_setCursorBoundForTest` lowers it), `stagedSyncTarget` gallops forward over `git rev-list --first-parent last..HEAD`, verifying every candidate's delta from the last synced commit against the bound (a net delta is not monotone, so no binary search), and discovery reruns pinned at the furthest fitting commit with no working-tree entries, recording `stagedHead`; the cursor carries it and `SyncResult.staged { target, head, stages }` reports it. One commit alone above the bound refuses `request_too_large` naming the commit. `commands/sync/perform.ts` loops a drain stage by stage to HEAD (the drain's one extra HEAD-moved pass is skipped for a staged result). Tests: `test/sync-staged-catchup.test.ts`.
diff --git a/src/core/persistence/publication-deadline.ts b/src/core/persistence/publication-deadline.ts
index 24aa94f3ba..67698d15a0 100644
--- a/src/core/persistence/publication-deadline.ts
+++ b/src/core/persistence/publication-deadline.ts
@@ -86,6 +86,14 @@ export interface PublicationBound {
onOverdue?(): void;
/** Past the ceiling, the grace and the settle window: the owner must restart. `settled` resolves when the publish finally does. */
onStuck?(settled: Promise<void>): void;
+ /** Scheduler seam: run `fn` once after `ms`, returning its cancel. Default: a real timer that does not hold the process open. Tests drive a manual clock through it. */
+ later?(ms: number, fn: () => void): () => void;
+}
+
+function realTimer(ms: number, fn: () => void): () => void {
+ const timer = setTimeout(fn, ms);
+ timer.unref?.();
+ return () => clearTimeout(timer);
}
/** Runs `publish` under the ceiling; settles only with `publish`'s own outcome. */
@@ -93,12 +101,13 @@ export function boundPublication<T>(publish: () => Promise<T>, bound: Publicatio
const controller = new AbortController();
const work = signals.run(controller.signal, publish);
const settled = work.then(() => undefined, () => undefined);
- const timers: Array<ReturnType<typeof setTimeout>> = [];
- const later = (ms: number, fn: () => void) => { const timer = setTimeout(fn, ms); timer.unref?.(); timers.push(timer); };
+ const schedule = bound.later ?? realTimer;
+ const cancels: Array<() => void> = [];
+ const later = (ms: number, fn: () => void) => { cancels.push(schedule(ms, fn)); };
const grace = bound.graceMs ?? PUBLICATION_GRACE_MS, settle = bound.settleMs ?? PUBLICATION_SETTLE_MS;
later(bound.ceilingMs, () => bound.onOverdue?.());
later(bound.ceilingMs + grace, () => controller.abort(Object.assign(new Error('publication_deadline'), { code: 'publication_deadline' })));
later(bound.ceilingMs + grace + settle, () => bound.onStuck?.(settled));
- void settled.then(() => { for (const timer of timers) clearTimeout(timer); });
+ void settled.then(() => { for (const cancel of cancels) cancel(); });
return work;
}
diff --git a/test/persistence-publication-deadline.test.ts b/test/persistence-publication-deadline.test.ts
index 35c7d7a1ab..0de87c9723 100644
--- a/test/persistence-publication-deadline.test.ts
+++ b/test/persistence-publication-deadline.test.ts
@@ -35,24 +35,44 @@ const putPage = operations.find(o => o.name === 'put_page')!;
const page = (body: string) => `---\ntitle: Example\ntype: note\n---\n\n${body}\n`;
const tick = (ms: number) => new Promise(r => setTimeout(r, ms));
+/** A manual scheduler for `PublicationBound.later`: time moves only through `advance`, so a stalled runner cannot fire a phase early. */
+function manualClock() {
+ let now = 0;
+ const pending: Array<{ at: number; fn: () => void; cancelled: boolean; fired: boolean }> = [];
+ return {
+ later: (ms: number, fn: () => void) => { const entry = { at: now + ms, fn, cancelled: false, fired: false }; pending.push(entry); return () => { entry.cancelled = true; }; },
+ async advance(ms: number) {
+ now += ms;
+ for (const entry of [...pending].sort((a, b) => a.at - b.at)) if (!entry.cancelled && !entry.fired && entry.at <= now) { entry.fired = true; entry.fn(); }
+ await Promise.resolve();
+ },
+ pending: () => pending.filter(entry => !entry.cancelled && !entry.fired).length,
+ };
+}
+
describe('boundPublication', () => {
test('never settles before the publish; overdue at the ceiling, signal aborted after the grace, stuck after the settle window', async () => {
const events: string[] = [];
let release!: (value: string) => void, seen: AbortSignal | undefined;
const fake = { transaction: (fn: (tx: unknown) => Promise<unknown>, opts?: { signal?: AbortSignal }) => { seen = opts?.signal; return fn({}); } } as unknown as BrainEngine;
let stuckSettled: Promise<void> | undefined;
+ const clock = manualClock();
const work = boundPublication(() => publicationTransaction(fake, () => new Promise<string>(resolve => { release = resolve; })),
- { ceilingMs: 20, graceMs: 20, settleMs: 20, onOverdue: () => events.push('overdue'), onStuck: settled => { events.push('stuck'); stuckSettled = settled; } });
+ { ceilingMs: 20, graceMs: 20, settleMs: 20, later: clock.later, onOverdue: () => events.push('overdue'), onStuck: settled => { events.push('stuck'); stuckSettled = settled; } });
let outcome: string | undefined;
void work.then(value => { outcome = value; });
- await tick(10); expect(events).toEqual([]); expect(seen?.aborted).toBe(false);
- await tick(20); expect(events).toEqual(['overdue']); expect(seen?.aborted).toBe(false);
- await tick(20); expect(seen?.aborted).toBe(true); expect(events).toEqual(['overdue']);
- await tick(25); expect(events).toEqual(['overdue', 'stuck']);
+ await clock.advance(10);
+ // A loaded runner stalling here used to let the wall-clock abort fire before the next assertion; the manual clock does not move.
+ { const stalled = performance.now(); while (performance.now() - stalled < 15); }
+ expect(events).toEqual([]); expect(seen?.aborted).toBe(false);
+ await clock.advance(20); expect(events).toEqual(['overdue']); expect(seen?.aborted).toBe(false);
+ await clock.advance(20); expect(seen?.aborted).toBe(true); expect(events).toEqual(['overdue']);
+ await clock.advance(25); expect(events).toEqual(['overdue', 'stuck']);
expect(outcome).toBeUndefined();
release('committed');
expect(await work).toBe('committed');
await stuckSettled;
+ expect(clock.pending()).toBe(0);
});
test('a publish that settles in time fires nothing; a rejection propagates; outside a publication no signal is passed', async () => {