Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

W-C5: define the loops_extract/extract staleness bound and test convergence within one cycle

garrytanea28f23d7784
diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.md
index 403bfdea3d..a5d95a81ca 100644
--- a/docs/architecture/key-files/google-and-loops-continued.md
+++ b/docs/architecture/key-files/google-and-loops-continued.md
@@ -33,3 +33,4 @@
- `src/core/google/loop-catchup.ts` — open-loop recovery passes the Gmail sweep runs (#5867, #5868). Grace holds: `recordGraceVerdict` keeps each thread `detectThreadLoop` grace-held (and `loopExtractionEligibility` passes) in connector state `loop_grace_holds` (cap `GRACE_HOLDS_CAP` 2,000, oldest pruned and logged; prose sanitized for jsonb), separate from connector item holds, so `connector_held_items` and `waiting` coverage never count them. `settleDueGraceHolds` opens a due hold from its stored spec when the page still carries the newest message id it was computed from (no Gmail read), otherwise re-fetches through `processThread` (at most `GRACE_REFETCH_PER_SWEEP` 100 per sweep; a 404 drops the hold, a failure keeps it due). `seedGraceBackfill` seeds holds once for email pages active in the last 14 days with no open deterministic loop, from stored pages only; the sweep sets `loop_grace_backfill_done` after a non-aborted sweep. Catch-up (managed sources only): `runLoopsCatchup` re-candidates email pages whose newest message is in the last 30 days; a page is settled by a revision-bound outcome (`recordLoopsExtractOutcome`, written by the `loops_extract` handler into `op_checkpoints` op `loops-extract-outcomes`, one statement, pruned past the window), not by job completion. It skips pages this sweep or a pending sweep job already queues, checks eligibility on the live thread, enqueues under its own key `loops-catchup:<source>:<slug>:<rev>` inside the waiting-depth ceiling, retries a dead-lettered job once (`:retry`) then settles it, honors the kill switch and chat availability, and sets `loops_catchup.done` only when every candidate is settled. Tests: `test/google-loops-recovery.serial.test.ts` (+ Postgres twin).
- `src/core/cycle/connector-extract.ts` — the extract phase of a cycle with no on-disk checkout (connector sources, Postgres brains without `--dir`; #5875): `runPhaseExtractDatabaseOnly` runs the bounded, source-scoped `extractStaleFromDB` drain (`CYCLE_STALE_DRAIN_BUDGET_MS`; brain-wide when the cycle has no source id; managed brains route to `extractManagedStaleLinks`) and reports `extract: ok` with `database_only: true` and the stale counters; a dry run reports `skipped`. Tests: `test/connector-cycle-extract.test.ts` (+ Postgres twin), no `runCycle` mock.
+- `test/helpers/managed-connector-job-contract.ts` (+ `test/managed-connector-job-contract.test.ts`, its PostgreSQL twin `test/e2e/managed-connector-job-contract.test.ts`) — the managed connector-source job contract: every automatic maintenance job on an unbound Google connector source runs its real handler on a real queue and worker, and one detector checks guard refusals, committed-row receipts and dead letters. Staleness bound between the extract phase and a queued `loops_extract` (#5961): the two jobs share no lock, so a `loops_extract` the Gmail sweep queued can commit its commitment fact and republish a page (`people/alice-example` in the fixture) after the cycle's extract phase stamped `links_extracted_at`, and that page reads stale again. The product behavior is eventual consistency with a maximum staleness of one cycle: the next cycle's extract phase re-extracts every page republished since its stamp. `cycle_extract_loops_race` runs that worst-case order (cycle, then the competing `loops_extract`, then one more cycle) and asserts the page reads stale after the competing job and zero stale pages after the next cycle; `cycle_extract` cancels the queued job before its single cycle so it measures one phase run alone.
diff --git a/test/helpers/managed-connector-job-contract.ts b/test/helpers/managed-connector-job-contract.ts
index f5f55fb1db..71f60e1ccc 100644
--- a/test/helpers/managed-connector-job-contract.ts
+++ b/test/helpers/managed-connector-job-contract.ts
@@ -66,6 +66,7 @@ export const contractCases = [
'loops_extract_run',
'loops_close',
'cycle_extract',
+ 'cycle_extract_loops_race',
'cycle_extract_facts',
'extract_conversation_facts',
'facts_absorb',
@@ -565,6 +566,34 @@ const cases: Record<ContractCase, (state: CaseState) => Promise<void>> = {
expect(links).toHaveLength(1);
},
+ /**
+ * #5961 bound: a loops_extract the sweep queued can republish a page after
+ * the extract phase stamped it (eventual consistency, no lock between the
+ * two). Worst-case order: the cycle stamps every page, then the competing
+ * job republishes people/alice-example, which reads stale again; the next
+ * cycle re-extracts it, so staleness is bounded by one cycle.
+ */
+ async cycle_extract_loops_race(state) {
+ await gmailSweep(state);
+ const { engine } = state.brain;
+ await engine.executeRaw("UPDATE minion_jobs SET status='cancelled' WHERE id > $1 AND status IN ('waiting','delayed')", [state.detector.jobsFrom]);
+ await engine.executeRaw("UPDATE pages SET links_extracted_at=NULL WHERE source_id=$1", [state.sourceId]);
+ const cycle = async () => {
+ const [job] = await runJobs(engine, [{ name: 'autopilot-cycle', data: { source_id: state.sourceId, phases: ['extract'] } }], 120_000);
+ requireCompleted([job]);
+ const extract = (job.result as { report?: { phases?: Array<{ phase: string; status: string }> } }).report?.phases?.find(p => p.phase === 'extract');
+ expect(extract?.status).toBe('ok');
+ };
+ await cycle();
+ expect(await staleCount(state)).toBe(0);
+ const competing = await extractLoops(state);
+ expect(competing.result).toMatchObject({ status: 'extracted', commitments: 1 });
+ expect(await staleCount(state)).toBeGreaterThan(0);
+ await engine.executeRaw("UPDATE minion_jobs SET status='cancelled' WHERE id > $1 AND status IN ('waiting','delayed')", [state.detector.jobsFrom]);
+ await cycle();
+ expect(await staleCount(state)).toBe(0);
+ },
+
async cycle_extract_facts(state) {
await gmailSweep(state);
const [job] = await runJobs(state.brain.engine, [{ name: 'autopilot-cycle', data: { source_id: state.sourceId, phases: ['extract_facts'] } }], 120_000);