Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
jobs work: wake the idle claim loop when a sync job is queued (GBRA-133 2a.4)
garrytane95c076f0ba9
diff --git a/scripts/e2e-backend-matrix.txt b/scripts/e2e-backend-matrix.txtindex cf2a0577c3..26fe1dc56c 100644--- a/scripts/e2e-backend-matrix.txt+++ b/scripts/e2e-backend-matrix.txt@@ -69,3 +69,4 @@ test/e2e/oauth-owner-consent-source-postgres.test.tstest/e2e/entity-names-parity-postgres.test.tstest/e2e/segment-gc-parity.test.tstest/e2e/doctor-entry-deadline-postgres.test.ts+test/e2e/s-sync-queue-wake-postgres.test.tsdiff --git a/src/commands/jobs/work.ts b/src/commands/jobs/work.tsindex 130460e558..2b8b1f15b3 100644--- a/src/commands/jobs/work.ts+++ b/src/commands/jobs/work.ts@@ -248,6 +248,10 @@ export async function runJobsWork({ args, engine, queue }: JobsCommandContext):// cannot exit(143) ahead of the drain and orphan in-flight jobs.const releaseSignalOwner = registerSignalOwner('jobs-work', () => worker.requestShutdown());+ // GBRA-133 2a.4: a queued sync job wakes the idle claim loop (LISTEN on a direct session, a short poll otherwise).+ const { startSyncQueueWake } = await import('../../core/minions/sync-queue-wake.ts');+ const syncQueueWake = await startSyncQueueWake(engine, worker, { queue: queueName });+try {reportWorkerStarting('worker_startup');worker.once('ready', () => reportWorkerReady(childIdentity));@@ -255,6 +259,7 @@ export async function runJobsWork({ args, engine, queue }: JobsCommandContext):} finally {unregisterWorker();releaseSignalOwner();+ await syncQueueWake.stop();if (worker.configurationError) {const releases = worker.configurationReleaseResults;const unconfirmed = releases.filter(result => result.outcome === 'unconfirmed').length;diff --git a/src/core/minions/sync-queue-wake.ts b/src/core/minions/sync-queue-wake.tsnew file mode 100644index 0000000000..8fc4b69d9c--- /dev/null+++ b/src/core/minions/sync-queue-wake.ts@@ -0,0 +1,119 @@+/**+ * GBRA-133 PR 2a.4: wake an idle `gbrain jobs work` claim loop as soon as a `sync` job is queued, instead of after the+ * worker's 5 s idle poll.+ *+ * Two modes, chosen once at worker boot:+ * - `listen`: LISTEN on the `minion_jobs` channel the schema's `notify_minion_job_change` trigger already publishes to,+ * and wake on a `sync` job turning `waiting` in this worker's queue. Only on a connection detected as a direct+ * session: the engine's direct route (dual pool), or a pool URL that is not a transaction pooler (`prepare` is not+ * off; db.ts `resolvePrepare`, read through consumer-lane.ts). Behind a transaction pooler a LISTEN outlives the+ * transaction that ran it, so its notifications reach whichever client holds that server connection next, or nobody.+ * A probe NOTIFY right after LISTEN must arrive within LISTEN_PROBE_MS, otherwise the worker polls instead.+ * - `poll`: while the claim loop is idle-waiting, one indexed `minion_jobs` read every `GBRAIN_WORKER_SYNC_WAKE_POLL_MS`+ * (default 1 s, 250 ms to 5 s); no query while a job runs.+ * `off` on PGLite (`jobs work` drains in the foreground there) and with `GBRAIN_WORKER_SYNC_WAKE=0`.+ *+ * The claim loop's own poll stays the backstop in every mode: a lost notification costs at most one poll interval.+ */+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../engine.ts';+import type { MinionWorker } from './worker.ts';+import { consumerConnectionRoute } from '../persistence/consumer-lane.ts';++export const SYNC_WAKE_CHANNEL = 'minion_jobs';+export const SYNC_WAKE_POLL_MS_DEFAULT = 1_000;+export const LISTEN_PROBE_MS = 3_000;++export type SyncQueueWakeMode = 'listen' | 'poll' | 'off';+export interface SyncQueueWakeChoice {+ mode: SyncQueueWakeMode;+ reason: 'disabled' | 'not_postgres' | 'direct_route' | 'direct_session' | 'transaction_pooler' | 'pooler_mode_unknown' | 'listen_unverified';+}+export interface SyncQueueWake extends SyncQueueWakeChoice { readonly pollMs: number; stop(): Promise<void> }++type ListenSql = { listen(channel: string, fn: (payload: string) => void): Promise<{ unlisten(): Promise<void> }> };+type RoutedEngine = BrainEngine & { connectionManager?: { isDualPoolActive(): boolean; ddl(): Promise<unknown> } | null; sql?: unknown };++/** Which wake this engine gets: LISTEN only on a detected direct session, the short poll otherwise. */+export function chooseSyncQueueWake(engine: BrainEngine, env: Record<string, string | undefined> = process.env): SyncQueueWakeChoice {+ if (env.GBRAIN_WORKER_SYNC_WAKE === '0') return { mode: 'off', reason: 'disabled' };+ if (engine.kind !== 'postgres') return { mode: 'off', reason: 'not_postgres' };+ let direct = false;+ try { direct = (engine as RoutedEngine).connectionManager?.isDualPoolActive() === true; } catch { direct = false; }+ if (direct) return { mode: 'listen', reason: 'direct_route' };+ const { pooler_mode } = consumerConnectionRoute(engine);+ if (pooler_mode === 'session_or_direct') return { mode: 'listen', reason: 'direct_session' };+ return { mode: 'poll', reason: pooler_mode === 'transaction' ? 'transaction_pooler' : 'pooler_mode_unknown' };+}++export function syncQueueWakePollMs(env: Record<string, string | undefined> = process.env): number {+ const raw = env.GBRAIN_WORKER_SYNC_WAKE_POLL_MS;+ const value = raw === undefined || raw.trim() === '' ? NaN : Number(raw);+ return Number.isFinite(value) ? Math.min(5_000, Math.max(250, Math.round(value))) : SYNC_WAKE_POLL_MS_DEFAULT;+}++/** A queued-sync notification for this worker's queue. */+export function isSyncWakePayload(payload: string, queue: string): boolean {+ try {+ const row = JSON.parse(payload) as { name?: unknown; status?: unknown; queue?: unknown };+ return row.name === 'sync' && row.status === 'waiting' && row.queue === queue;+ } catch { return false; }+}++async function listenSql(engine: BrainEngine, reason: SyncQueueWakeChoice['reason']): Promise<ListenSql> {+ const routed = engine as RoutedEngine;+ if (reason === 'direct_route' && routed.connectionManager) return await routed.connectionManager.ddl() as ListenSql;+ return routed.sql as ListenSql;+}++/** Start the wake for one worker and log one line naming the mode. Never throws: a failed or unverified LISTEN polls instead. */+export async function startSyncQueueWake(engine: BrainEngine, worker: Pick<MinionWorker, 'wake' | 'idle'>,+ opts: { queue: string; env?: Record<string, string | undefined>; log?: (line: string) => void }): Promise<SyncQueueWake> {+ const env = opts.env ?? process.env;+ const log = opts.log ?? ((line: string) => console.log(line));+ const pollMs = syncQueueWakePollMs(env);+ let choice = chooseSyncQueueWake(engine, env);+ let stopped = false;++ if (choice.mode === 'listen') {+ try {+ const sql = await listenSql(engine, choice.reason);+ const probe = `probe:${randomUUID()}`;+ let probed: () => void = () => {};+ const arrived = new Promise<boolean>(resolve => {+ probed = () => resolve(true);+ setTimeout(() => resolve(false), LISTEN_PROBE_MS).unref?.();+ });+ const listener = await sql.listen(SYNC_WAKE_CHANNEL, payload => {+ if (payload === probe) { probed(); return; }+ if (!stopped && isSyncWakePayload(payload, opts.queue)) worker.wake('sync_queue_notify');+ });+ await engine.executeRaw('SELECT pg_notify($1, $2)', [SYNC_WAKE_CHANNEL, probe]);+ if (await arrived) {+ log(`[gbrain jobs] sync-queue wake: listen (${choice.reason})`);+ return { ...choice, pollMs, stop: async () => { stopped = true; await listener.unlisten().catch(() => {}); } };+ }+ await listener.unlisten().catch(() => {});+ } catch (error) {+ log(`[gbrain jobs] sync-queue wake: LISTEN failed (${error instanceof Error ? error.message : String(error)})`);+ }+ choice = { mode: 'poll', reason: 'listen_unverified' };+ }++ if (choice.mode === 'off') {+ if (choice.reason === 'disabled') log('[gbrain jobs] sync-queue wake: off (GBRAIN_WORKER_SYNC_WAKE=0)');+ return { ...choice, pollMs, stop: async () => { stopped = true; } };+ }++ log(`[gbrain jobs] sync-queue wake: poll every ${pollMs} ms (${choice.reason})`);+ let inflight: Promise<void> | null = null;+ const timer = setInterval(() => {+ if (stopped || inflight || !worker.idle) return;+ inflight = engine.executeRaw<{ one: number }>(+ `SELECT 1 AS one FROM minion_jobs WHERE queue = $1 AND name = 'sync' AND status = 'waiting' LIMIT 1`, [opts.queue])+ .then(rows => { if (!stopped && rows.length > 0) worker.wake('sync_queue_poll'); }, () => { /* the claim loop's own poll is the backstop */ })+ .finally(() => { inflight = null; });+ }, pollMs);+ timer.unref?.();+ return { ...choice, pollMs, stop: async () => { stopped = true; clearInterval(timer); await inflight; } };+}diff --git a/src/core/minions/worker.ts b/src/core/minions/worker.tsindex 109c24fafa..2a7a763f1c 100644--- a/src/core/minions/worker.ts+++ b/src/core/minions/worker.ts@@ -190,6 +190,9 @@ interface InFlightJob {shared: boolean;}+/** One idle poll wait of the claim loop and how it ended (waiting while in progress). */+export interface IdleWait { ms: number; ended: 'waiting' | 'timer' | 'wake' | 'skipped' | 'stop'; reason?: string }+export interface ConfigurationReleaseResult {jobId: number | null;lockToken: string;@@ -218,6 +221,12 @@ export class MinionWorker extends EventEmitter {private running = false;/** Log the pause/resume transition once each, not every poll. */private pausedByMarkerAnnounced = false;+ /** The idle poll wait in progress, which wake() ends early; null while the loop is not idle-waiting. */+ private idleWaiting: { entry: IdleWait; timer: ReturnType<typeof setTimeout>; resolve: () => void } | null = null;+ /** A wake that arrived while the loop was claiming: the next idle wait is skipped so the claim runs again at once. */+ private wakePending = false;+ /** The newest idle poll waits and how each ended (bounded): the recorded decisions the sync-queue wake tests read. */+ readonly idleWaits: IdleWait[] = [];private inFlight = new Map<number, InFlightJob>();private executions = new Map<string, OwnedExecution>();private pendingClaim: { lockToken: string; promise: Promise<MinionJob | null> } | null = null;@@ -843,6 +852,7 @@ export class MinionWorker extends EventEmitter {}if (this.inFlight.size < this.opts.concurrency && ![...this.inFlight.values()].some(f => isWatchdogSuspect(f.job))) {const lockToken = `${this.workerId}:${randomUUID()}`;+ this.wakePending = false;let job: MinionJob | null;try {const claim = this.queue.claim(@@ -913,8 +923,8 @@ export class MinionWorker extends EventEmitter {this.launchJob(job, lockToken);}} else if (this.inFlight.size === 0) {- // No jobs and nothing in flight, poll- await new Promise(resolve => setTimeout(resolve, this.opts.pollInterval));+ // No jobs and nothing in flight, poll (a sync-queue wake ends the wait early)+ await this.idleWait(this.opts.pollInterval);} else {// Jobs are running but no new ones available, brief pause before re-checkingawait new Promise(resolve => setTimeout(resolve, 100));@@ -1050,12 +1060,47 @@ export class MinionWorker extends EventEmitter {requestShutdown(): void {if (this.running) console.log('Minion worker shutting down...');this.running = false;+ this.wake('stop');if (!this.shutdownAbort.signal.aborted) this.shutdownAbort.abort(new Error('shutdown'));}+ /**+ * End the idle poll wait now so the loop claims at once (GBRA-133 2a.4 sync-queue wake,+ * src/core/minions/sync-queue-wake.ts). A wake while the loop is claiming makes the next idle wait a no-op, so a job+ * inserted between an empty claim and the wait is never left for the full poll interval.+ */+ wake(reason = 'wake'): void {+ const waiting = this.idleWaiting;+ if (!waiting) { if (reason !== 'stop') this.wakePending = true; return; }+ this.idleWaiting = null;+ clearTimeout(waiting.timer);+ waiting.entry.ended = reason === 'stop' ? 'stop' : 'wake';+ waiting.entry.reason = reason;+ waiting.resolve();+ }++ /** True while the claim loop waits out an idle poll (nothing claimed, nothing in flight). */+ get idle(): boolean { return this.idleWaiting !== null; }++ private idleWait(ms: number): Promise<void> {+ if (this.idleWaits.length >= 100) this.idleWaits.shift();+ if (this.wakePending) {+ this.wakePending = false;+ this.idleWaits.push({ ms, ended: 'skipped' });+ return Promise.resolve();+ }+ const entry: IdleWait = { ms, ended: 'waiting' };+ this.idleWaits.push(entry);+ return new Promise<void>(resolve => {+ const timer = setTimeout(() => { this.idleWaiting = null; entry.ended = 'timer'; resolve(); }, ms);+ this.idleWaiting = { entry, timer, resolve };+ });+ }+/** Stop the worker gracefully. */stop(): void {this.running = false;+ this.wake('stop');try { this.eldHistogram?.disable(); } catch { /* fail-open */ }}diff --git a/test/e2e/s-sync-queue-wake-postgres.test.ts b/test/e2e/s-sync-queue-wake-postgres.test.tsnew file mode 100644index 0000000000..c03fd68220--- /dev/null+++ b/test/e2e/s-sync-queue-wake-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../pathological/s-sync-queue-wake.test.ts'));diff --git a/test/pathological/s-sync-queue-wake.test.ts b/test/pathological/s-sync-queue-wake.test.tsnew file mode 100644index 0000000000..b78be9af49--- /dev/null+++ b/test/pathological/s-sync-queue-wake.test.ts@@ -0,0 +1,99 @@+/**+ * GBRA-133 PR 2a.4: a `gbrain jobs work` worker found a queued sync job only on its next idle poll (5 s,+ * worker.ts), so Phase 1 measured a Postgres single-file commit taking 5.3 to 5.5 s to reach search through a submitted+ * sync job even though the sync itself took about 0.3 s.+ *+ * Protects: a queued `sync` job ends the worker's idle wait. On a detected direct session the worker LISTENs on the+ * `minion_jobs` channel; behind a transaction pooler (PgBouncer, prepare=false) it never LISTENs and polls the sync+ * queue every second instead; PGLite has no resident worker and gets no wake. A wake that lands while the loop is+ * claiming makes the next idle wait a no-op instead of being lost.+ * Fails when: the job waits out the idle poll (the test sets it to 10 minutes, so it never completes), LISTEN is used+ * behind a transaction pooler, or a wake during a claim is dropped. Asserts on the worker's recorded idle waits, never+ * on elapsed time. PGLite always, Postgres when DATABASE_URL is set (the E2E backend matrix also runs it through+ * PgBouncer: GBRAIN_TEST_BACKEND=pgbouncer).+ */+import { describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../../src/core/engine.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { MinionQueue } from '../../src/core/minions/queue.ts';+import { MinionWorker } from '../../src/core/minions/worker.ts';+import { resolvePrepare } from '../../src/core/db.ts';+import { pathologicalArms } from './harness.ts';++const IDLE_POLL_MS = 600_000;+const until = async (what: string, check: () => boolean | Promise<boolean>) => {+ for (let i = 0; i < 2_000; i++) { if (await check()) return; await new Promise(resolve => setTimeout(resolve, 10)); }+ throw new Error('timed out waiting for ' + what);+};++async function withEngine(databaseUrl: string | undefined, run: (engine: BrainEngine) => Promise<void>): Promise<void> {+ const engine: BrainEngine = databaseUrl ? new PostgresEngine() : new PGLiteEngine();+ await engine.connect(databaseUrl ? { database_url: databaseUrl, poolSize: 3 } : {});+ try { await engine.initSchema(); await run(engine); } finally { await engine.disconnect(); }+}++async function withIdleWorker(engine: BrainEngine, run: (w: { worker: MinionWorker; queue: MinionQueue; queueName: string; ran: number[] }) => Promise<void>) {+ const queueName = 'wake-' + randomUUID().slice(0, 8);+ const queue = new MinionQueue(engine);+ const worker = new MinionWorker(engine, { queue: queueName, pollInterval: IDLE_POLL_MS, concurrency: 1, healthCheckInterval: 0 });+ const ran: number[] = [];+ worker.register('sync', async job => { ran.push(job.id); return { ok: true }; });+ const running = worker.start();+ try {+ await until('the worker to go idle', () => (worker as unknown as { idle?: boolean }).idle === true);+ await run({ worker, queue, queueName, ran });+ } finally { worker.stop(); await running; }+}++for (const { backend, databaseUrl } of pathologicalArms()) {+ /** The E2E backend matrix's PgBouncer pass hands this arm a transaction-pooler URL (it must carry prepare=false). */+ const pooled = databaseUrl !== undefined && resolvePrepare(databaseUrl) === false;+ describe('sync-queue wake for the jobs worker (' + (pooled ? 'pgbouncer' : backend) + ')', () => {+ test('a sync job queued beside an idle worker ends its idle wait and runs (no 10-minute poll)', async () => {+ await withEngine(databaseUrl, engine => withIdleWorker(engine, async ({ worker, queue, queueName, ran }) => {+ const { startSyncQueueWake } = await import('../../src/core/minions/sync-queue-wake.ts');+ const lines: string[] = [];+ const wake = await startSyncQueueWake(engine, worker, { queue: queueName, log: line => lines.push(line) });+ try {+ const expected = backend === 'pglite' ? { mode: 'off', reason: 'not_postgres' }+ : pooled ? { mode: 'poll', reason: 'transaction_pooler' } : { mode: 'listen', reason: 'direct_session' };+ expect({ mode: wake.mode, reason: wake.reason }).toEqual(expected);+ // PGLite has no resident worker to wake; its \`jobs work\` drains in the foreground. The primitive still works there.+ const job = await queue.add('sync', { sourceId: 'acme-example', noPull: true }, { queue: queueName });+ if (backend === 'pglite') worker.wake('test');+ await until('the job to run', () => ran.includes(job.id));+ const ended = worker.idleWaits.filter(w => w.ended === 'wake').map(w => w.reason);+ expect(ended).toContain(backend === 'pglite' ? 'test' : pooled ? 'sync_queue_poll' : 'sync_queue_notify');+ expect(worker.idleWaits.every(w => w.ms === IDLE_POLL_MS)).toBe(true);+ if (wake.mode !== 'off') expect(lines).toEqual(['[gbrain jobs] sync-queue wake: ' + (wake.mode === 'listen' ? 'listen (direct_session)' : 'poll every 1000 ms (transaction_pooler)')]);+ } finally { await wake.stop(); }+ }));+ }, 120_000);++ test('a wake that lands while the loop is claiming skips the next idle wait instead of being lost', async () => {+ await withEngine(databaseUrl, engine => withIdleWorker(engine, async ({ worker }) => {+ // The next claim finds nothing, and a notification arrives while it runs (after its SELECT, before the wait).+ const queue = (worker as unknown as { queue: { claim: (...args: unknown[]) => Promise<unknown> } }).queue;+ const claim = queue.claim.bind(queue);+ let claims = 0;+ queue.claim = async (...args: unknown[]) => { const found = await claim(...args); if (claims++ === 0) worker.wake('during_claim'); return found; };+ const before = worker.idleWaits.length;+ worker.wake('first');+ await until('two more claims', () => claims >= 2 && worker.idle);+ expect(worker.idleWaits.slice(before - 1).map(w => [w.ended, w.reason ?? null])).toEqual([['wake', 'first'], ['skipped', null], ['waiting', null]]);+ }));+ }, 120_000);++ if (backend !== 'pglite') {+ test('behind a transaction pooler the wake never LISTENs; on a direct session it LISTENs (detection from the connection, not the arm)', async () => {+ const { chooseSyncQueueWake } = await import('../../src/core/minions/sync-queue-wake.ts');+ await withEngine(databaseUrl, async engine => {+ expect(chooseSyncQueueWake(engine, {}).mode).toBe(pooled ? 'poll' : 'listen');+ expect(chooseSyncQueueWake(engine, { GBRAIN_WORKER_SYNC_WAKE: '0' })).toEqual({ mode: 'off', reason: 'disabled' });+ });+ }, 60_000);+ }+ });+}