Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test(contract): one quiesce step before every connector-contract drain (#6102)
time-attack2fc54064f459
diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.mdindex e1296dc922..7ac9b65b1f 100644--- a/docs/architecture/key-files/google-and-loops-continued.md+++ b/docs/architecture/key-files/google-and-loops-continued.md@@ -34,4 +34,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.+- `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` measures one phase run alone. Every case runs its asserted jobs through `drainQueue`, which first cancels every other claimable (`waiting`/`delayed`) job, so a follow-up queued earlier in the case (the sweep's `loops_extract`) cannot run after the asserted job and land its writes or embedding effects after the case's check.diff --git a/test/helpers/managed-connector-job-contract.ts b/test/helpers/managed-connector-job-contract.tsindex a45b481199..c2f0d795bf 100644--- a/test/helpers/managed-connector-job-contract.ts+++ b/test/helpers/managed-connector-job-contract.ts@@ -403,7 +403,16 @@ async function runJobs(engine: BrainEngine, jobs: Array<{ name: string; data: Rereturn drainQueue(engine, ids, timeoutMs);}+/**+ * Runs `ids` on a real worker until every one is terminal. Every other+ * claimable (`waiting`/`delayed`) job is cancelled first: a follow-up queued+ * earlier in the case (the sweep's loops_extract) would otherwise be claimed+ * by this worker once `ids` finish, and its writes and embedding effects land+ * after the case's check. Active and claimed jobs are left alone. The brain is+ * this file's own, and runCase cancels each case's leftovers.+ */async function drainQueue(engine: BrainEngine, ids: number[], timeoutMs = 60_000) {+ await engine.executeRaw("UPDATE minion_jobs SET status='cancelled' WHERE status IN ('waiting','delayed') AND NOT (id = ANY($1::int[]))", [ids]);const worker = new MinionWorker(engine, { pollInterval: 20, healthCheckInterval: 0, stalledInterval: 600_000 });await registerBuiltinHandlers(worker, engine, { quiet: true });const running = worker.start();@@ -548,19 +557,11 @@ const cases: Record<ContractCase, (state: CaseState) => Promise<void>> = {async cycle_extract(state) {await gmailSweep(state);const { engine } = state.brain;- // Settle the jobs the sweep queued (loops_extract) first: the cycle's worker would- // otherwise run them beside the extract phase and leave a page rewritten after it.- const queued = await engine.executeRaw<{ id: number }>("SELECT id FROM minion_jobs WHERE status IN ('waiting','delayed')");- if (queued.length) await drainQueue(engine, queued.map(row => Number(row.id)));await submitPageMutation(state.ctx, { operation: 'put_page', params: { slug: 'notes/plan-review', request_id: randomUUID(),content: '---\ntitle: Plan review\ntype: note\n---\nReviewed with [[people/alice-example]].\n' } });await engine.executeRaw("DELETE FROM links WHERE from_page_id IN (SELECT id FROM pages WHERE source_id=$1 AND slug='notes/plan-review')", [state.sourceId]);await engine.executeRaw("UPDATE pages SET links_extracted_at=NULL WHERE source_id=$1", [state.sourceId]);expect(await staleCount(state)).toBeGreaterThan(0);- // The sweep queued loops_extract (priority 5). Left waiting, the cycle's worker can- // claim it once the cycle job finishes; its commitment fact then republishes- // people/alice-example after the extract phase stamped it, and that page reads stale.- await engine.executeRaw("UPDATE minion_jobs SET status='cancelled' WHERE id > $1 AND status IN ('waiting','delayed')", [state.detector.jobsFrom]);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; details?: Record<string, unknown> }> } }).report?.phases?.find(p => p.phase === 'extract');@@ -582,7 +583,6 @@ const cases: Record<ContractCase, (state: CaseState) => Promise<void>> = {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);@@ -595,7 +595,6 @@ const cases: Record<ContractCase, (state: CaseState) => Promise<void>> = {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);},