Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(minions): queued freshness sync skips a source disabled after enqueue (#4399 window)

time-attackaf57c0b8d649
diff --git a/docs/architecture/key-files/core-minions-1.md b/docs/architecture/key-files/core-minions-1.md
index 649d3c5e8b..063b9e8491 100644
--- a/docs/architecture/key-files/core-minions-1.md
+++ b/docs/architecture/key-files/core-minions-1.md
@@ -4,7 +4,7 @@
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
- `src/core/minions/` — Minions job queue: BullMQ-inspired, Postgres-native (queue, worker, backoff, types, protected-names, quiet-hours, handlers/shell). Private dream-inline-* queues carry an explicit lifecycle: owner job id + owner token + a renewable lease (columns on minion_jobs; `queue.ts` `reconcilePrivateQueue` terminalizes one queue through the normal cancelJobs bookkeeping and stamps every cancellation with the machine-readable `private_queue_reconciled:` reason family; `renewPrivateQueueLease` is MONOTONIC — GREATEST — so a default-horizon renewal can never shrink a creation-time lease; `reconcileOrphanedPrivateQueues` cancels only provably-orphaned queues: no healthy child lock, owner terminal/missing or lease expired; legacy unowned rows are left to Doctor/retriage; `classifyPrivateQueueForRecovery` is PUBLIC so the doctor orphan check buckets through the same verdict). Recovery runs in `gbrain jobs work` after driver/selected-child readiness and `ensureSchema`, for bare AND supervised workers (including autopilot spawns/respawns); the standalone parent does not recover queues in `beforeSpawn`. `maybeRunWorkerStartupRecovery(queue, process.env, true)` keeps this worker-owned ordering even under `GBRAIN_SUPERVISED=1`. Dream-cycle start also recovers (cycle.ts, next to the cycle lock reap — the ONLY lane on PGLite, which inlines every child). `deriveWedgeSignal` is queue-aware: a dream-inline queue is never 'wedged' (no shared worker can claim it) — it reports `private_queue: true` so jobs stats / get_job_stats / doctor all point at reconciliation instead of the impossible worker restart.
-- `src/core/minions/handlers/sync.ts` (and the other built-in job handler modules: `embed`, `lint`, `lint-fix`, `extract`, `extract-conversation-facts`, `chronicle-extract`, `loops-extract`, `enrich`, `integrity`, `integrity-auto`, `sync-retry-failed`, `import`, `backlinks`, `facts-absorb`, `autopilot-cycle`, `autopilot-global-maintenance`, `reindex`, `repair-jsonb`, `orphans`, `purge`, `cycle-phase`, `extract-atoms-drain`, `extract-ner`, `extract-takes-from-pages`, `extract-timeline-from-meetings`, `embed-catch-up`, `unify-types`, plus `job-pull.ts`) — one module per built-in handler body, each a `make<Name>Handler(engine)` factory (or a `MinionHandler` const when it needs no engine). Registered in a fixed order by `registerBuiltinHandlers` in `src/commands/jobs.ts`, which keeps the registration kind (plain vs gateway-refreshing) and wrappers such as `withFactsAbsorbHaltCooldown`; `cycle-phase.ts` serves the six phase wrappers. Command cores are imported lazily inside each handler. `resolveJobPull` and the facts-absorb retry predicates are re-exported from `jobs.ts`. `autopilot-global-maintenance` runs one `runCycle` call per maintenance phase and keeps its pass position in config `autopilot.global_maintenance.progress`: it stops starting a phase whose last measured duration would cross the job deadline (minus a 60 s reserve), the next job resumes at that phase, and a phase still marked running when an earlier job died is skipped for the rest of the pass; last_global_at is stamped only when a pass completes with no blocking phase. The deadline comes from `GBRAIN_GLOBAL_MAINTENANCE_TIMEOUT_MS` > `autopilot.global_maintenance_timeout_ms` > the autopilot default (`autopilot-fanout.ts:resolveGlobalMaintenanceTimeoutMs`); doctor `global_maintenance_timeouts` (`doctor/checks/global-maintenance-timeouts.ts`) warns after three consecutive deaths and names `gbrain dream --phase <name>` (`autopilot-global-maintenance-resume-4578.test.ts`). The `sync` handler runs performSync under `job.signal` composed with `job.shutdownSignal`: under a signal owner (`jobs work`, the supervisor) SIGTERM skips the cleanup pass and aborts only the worker's shutdown signal, so the sync and its `git pull` (async `pullRepo` on `bounded-child-exec.ts`) stop and the job is handed back without burning an attempt.
+- `src/core/minions/handlers/sync.ts` (and the other built-in job handler modules: `embed`, `lint`, `lint-fix`, `extract`, `extract-conversation-facts`, `chronicle-extract`, `loops-extract`, `enrich`, `integrity`, `integrity-auto`, `sync-retry-failed`, `import`, `backlinks`, `facts-absorb`, `autopilot-cycle`, `autopilot-global-maintenance`, `reindex`, `repair-jsonb`, `orphans`, `purge`, `cycle-phase`, `extract-atoms-drain`, `extract-ner`, `extract-takes-from-pages`, `extract-timeline-from-meetings`, `embed-catch-up`, `unify-types`, plus `job-pull.ts`) — one module per built-in handler body, each a `make<Name>Handler(engine)` factory (or a `MinionHandler` const when it needs no engine). Registered in a fixed order by `registerBuiltinHandlers` in `src/commands/jobs.ts`, which keeps the registration kind (plain vs gateway-refreshing) and wrappers such as `withFactsAbsorbHaltCooldown`; `cycle-phase.ts` serves the six phase wrappers. Command cores are imported lazily inside each handler. `resolveJobPull` and the facts-absorb retry predicates are re-exported from `jobs.ts`. `autopilot-global-maintenance` runs one `runCycle` call per maintenance phase and keeps its pass position in config `autopilot.global_maintenance.progress`: it stops starting a phase whose last measured duration would cross the job deadline (minus a 60 s reserve), the next job resumes at that phase, and a phase still marked running when an earlier job died is skipped for the rest of the pass; last_global_at is stamped only when a pass completes with no blocking phase. The deadline comes from `GBRAIN_GLOBAL_MAINTENANCE_TIMEOUT_MS` > `autopilot.global_maintenance_timeout_ms` > the autopilot default (`autopilot-fanout.ts:resolveGlobalMaintenanceTimeoutMs`); doctor `global_maintenance_timeouts` (`doctor/checks/global-maintenance-timeouts.ts`) warns after three consecutive deaths and names `gbrain dream --phase <name>` (`autopilot-global-maintenance-resume-4578.test.ts`). The `sync` handler runs performSync under `job.signal` composed with `job.shutdownSignal`: under a signal owner (`jobs work`, the supervisor) SIGTERM skips the cleanup pass and aborts only the worker's shutdown signal, so the sync and its `git pull` (async `pullRepo` on `bounded-child-exec.ts`) stop and the job is handed back without burning an attempt. A queued `autopilot_freshness` sync job re-reads its source when it runs and returns `{skipped:true, reason:'sync_disabled'}` when the source now has `syncEnabled:false`; explicit sync jobs still run and a failed lookup falls through to syncing (`sync-handler-sync-enabled.test.ts`).
- `src/core/minions/admission.ts` — submit-side queue admission control (the drain-side pool-starvation half is the job-isolation work; claim fairness is a filed TODO, deliberately out of scope). Three primitives resolved per name via `resolveAdmissionPolicy` (config `minions.*` > per-name defaults tables, 60s in-process cache, fail-open with a once-per-process stderr warn; env kill-switch `GBRAIN_MINIONS_ADMISSION=0` disables all three): PARAM-COALESCING (`PARAM_COALESCE_DEFAULT` — on for `subagent`; `computeParamHash` = sha256 of stable-stringified payload excluding only `__param_hash` itself — `__owner_client_id` is deliberately INCLUDED so owner lanes never cross; parentless + waiting-only + age-bounded to ttl/2), WAITING-TTL (`WAITING_TTL_DEFAULT_HOURS` — 48h for `subagent`; swept by `MinionQueue.handleWaitingTTL` through `cancelJobs(ids, {reason, rootStatuses:['waiting']})` so descendants cancel, child_done lands, aggregator parents resolve, and the reason stamps ROOT ids only; ≤500/tick oldest-first; warn-before-act is `runWaitingTtlTick` — first tick counts affected + stamps `TTL_NOTICE_SHOWN_KEY` with an ISO timestamp, sweeping starts only after `ttlNoticeGraceMs()` (1h default, env `GBRAIN_MINIONS_TTL_NOTICE_GRACE_MS`) elapses; `gbrain upgrade` prints the same one-shot notice and starts the same clock; legacy `'true'` flag values sweep immediately), and NAME-GLOBAL QUOTA (`QUOTA_MAX_WAITING_DEFAULT` EMPTY by operator decision — activates only via `minions.quota_max_waiting.<name>`; counts the name across ALL queues so per-run `dream-inline-*` fanout queues can't dodge it, EXACT under concurrency via a `minion_quota:<name>` advisory xact lock taken only when a quota is configured; throws typed `QueueQuotaExceededError`, checked everywhere via `isQueueQuotaExceededError` — dream submitters record a phase skip, synthesize rolls back the current transcript's fresh chunks, agent fanout cancels the whole tree, `submit_agent` maps to a structured `rate_limited` OperationError). `TTL_REASON_PREFIX` is the single source for the sweep's error_text prefix and the stats/doctor LIKE patterns; `safeConfigSegment` gates untrusted job names out of copy-pasteable config hints. Alerting rides `getStats` (`drained_completed/failed/dead/cancelled` keyed on finished_at + `waiting_now` + `oldest_waiting_minutes`), the `jobs stats` DIVERGENT-QUEUE / waiting-TTL screams (`GBRAIN_QUEUE_DIVERGENCE_RATIO`=2, `GBRAIN_QUEUE_DIVERGENCE_MIN_WAITING`=50; divergence compares intake vs COMPLETED so TTL-cancel storms can't masquerade as throughput) + `--json`, and doctor `checkQueueHealth`. Pinned by `test/minions-admission.test.ts` + `test/jobs-stats-divergence.serial.test.ts`.
diff --git a/src/core/minions/handlers/sync.ts b/src/core/minions/handlers/sync.ts
index e7b4bd9a01..aee5c81b14 100644
--- a/src/core/minions/handlers/sync.ts
+++ b/src/core/minions/handlers/sync.ts
@@ -34,6 +34,23 @@ export function makeSyncHandler(engine: BrainEngine): MinionHandler {
// global config.sync.* anchor in performSync.
}
}
+ // #4399: a queued automatic freshness sync re-reads the source when it runs, so a source
+ // disabled after enqueue is not synced. Explicit jobs still run; a failed lookup falls through.
+ if (job.data.embed_reason === 'autopilot_freshness') {
+ const id = sourceId ?? 'default';
+ const { isSyncDisabledConfig } = await import('../../sync-policy.ts');
+ let disabled = false;
+ try {
+ const [row] = await engine.executeRaw<{ config: unknown }>('SELECT config FROM sources WHERE id = $1', [id]);
+ disabled = row !== undefined && isSyncDisabledConfig(row.config);
+ } catch {
+ disabled = false;
+ }
+ if (disabled) {
+ console.error(`[sync] skipped: source ${id} has syncEnabled:false; queued freshness sync not run.`);
+ return { skipped: true, reason: 'sync_disabled', source_id: id };
+ }
+ }
// v0.22.13 (PR #490 CODEX-4): route concurrency through the shared
// autoConcurrency helper instead of hardcoded 4. PGLite engines stay
// serial (forced 1); explicit job param wins; auto path defaults are
diff --git a/test/sync-handler-sync-enabled.test.ts b/test/sync-handler-sync-enabled.test.ts
new file mode 100644
index 0000000000..1389c0253a
--- /dev/null
+++ b/test/sync-handler-sync-enabled.test.ts
@@ -0,0 +1,72 @@
+/**
+ * A queued automatic freshness sync honours `syncEnabled:false` set after it was enqueued (#4399 window).
+ *
+ * Protects: `autopilot_freshness` jobs re-read the source when they run and skip a disabled source;
+ * explicitly requested sync jobs still run; a failed source lookup falls through to syncing.
+ * Diagnosis and case matrix contributed by @Masashi-Ono0611 (PR #6407).
+ */
+import { afterAll, beforeAll, beforeEach, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { makeSyncHandler } from '../src/core/minions/handlers/sync.ts';
+import type { MinionJobContext } from '../src/core/minions/types.ts';
+import { makeGitFixture } from './helpers/git-fixture.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+
+const workdir = mkdtempSync(join(tmpdir(), 'gbrain-sync-enabled-'));
+const brain = join(workdir, 'brain');
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();
+ mkdirSync(brain, { recursive: true });
+ const repo = await makeGitFixture(brain);
+ writeFileSync(join(brain, 'note.md'), '---\ntitle: Note\ntype: note\n---\n\nA short note.\n');
+ repo.commitAll('add note');
+}, 60_000);
+afterAll(async () => { await engine.disconnect(); rmSync(workdir, { recursive: true, force: true }); });
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ await engine.executeRaw("UPDATE sources SET local_path=$1, config=jsonb_set(COALESCE(config,'{}'::jsonb),'{syncEnabled}','false'::jsonb) WHERE id='default'", [brain]);
+});
+
+const job = (data: Record<string, unknown>) => ({ id: 1, name: 'sync', data, signal: new AbortController().signal } as unknown as MinionJobContext);
+const freshness = { sourceId: 'default', repoPath: brain, pull: false, auto_embed_backfill: false, embed_reason: 'autopilot_freshness' };
+const pages = async () => (await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM pages WHERE slug='note'"))[0].n;
+
+test('a queued freshness sync of a source disabled after enqueue is skipped and imports nothing', async () => {
+ const result = await makeSyncHandler(engine)(job(freshness));
+ expect(result).toMatchObject({ skipped: true, reason: 'sync_disabled', source_id: 'default' });
+ expect(await pages()).toBe(0);
+});
+
+test('a freshness job that names only repoPath resolves the source and is skipped too', async () => {
+ const { sourceId: _omit, ...byPath } = freshness;
+ expect(await makeSyncHandler(engine)(job(byPath))).toMatchObject({ skipped: true, reason: 'sync_disabled', source_id: 'default' });
+});
+
+test('an explicit sync job of a disabled source still runs', async () => {
+ const { embed_reason: _omit, ...explicit } = freshness;
+ const result = await makeSyncHandler(engine)(job(explicit));
+ expect(result).not.toMatchObject({ skipped: true });
+ expect(await pages()).toBe(1);
+});
+
+test('an enabled source still syncs on a freshness job', async () => {
+ await engine.executeRaw("UPDATE sources SET config=config - 'syncEnabled' WHERE id='default'");
+ await makeSyncHandler(engine)(job(freshness));
+ expect(await pages()).toBe(1);
+});
+
+test('a failed source lookup falls through to syncing', async () => {
+ const original = engine.executeRaw.bind(engine);
+ const failing = Object.create(engine) as PGLiteEngine;
+ failing.executeRaw = (async (sql: string, params?: unknown[]) => {
+ if (/FROM sources WHERE id = \$1/.test(sql) && /config/.test(sql)) throw new Error('lookup failed');
+ return original(sql, params);
+ }) as PGLiteEngine['executeRaw'];
+ const result = await makeSyncHandler(failing)(job(freshness)).catch((error: unknown) => ({ threw: String(error) }));
+ expect(result).not.toMatchObject({ skipped: true, reason: 'sync_disabled' });
+});