Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(persistence-gate): kill the owner mid facts-absorb job, re-run it, no duplicate facts
garrytanb97961c6d9df
diff --git a/TODOS.md b/TODOS.mdindex ca8ea7108d..17abadfb75 100644--- a/TODOS.md+++ b/TODOS.md@@ -12,8 +12,6 @@ Context: `scripts/persistence/README.md` ("Crash robot"), `scripts/persistence/{**What:** report the robot's kill rate against seeded mutants (a dropped receipt update, a double-applied effect, a skipped withdrawal fence). **Effort:** M. **Priority:** P1.- [ ] **P1 — Source add/remove/refresh and writer activate/deactivate ops.****What:** the generator drives page, memory, takes, timeline, sync, connector and revocation ops; topology and writer-lifecycle ops are not in the protocol yet, so the existing `topology-clone.ts`, `topology-recovery.ts`, `worktree-refresh.ts` and `bundle-files.ts` boundary hooks are not crashed. **Effort:** M. **Priority:** P1.-- [ ] **P1 — Kill `serve` mid `facts-absorb` job.**- **What:** keyless robot brains never queue facts-backstop work, so the `effect:facts-backstop:mid` seam and the facts-absorb job lease are not crashed. **Fix:** a robot topology with facts extraction on through a deterministic chat stub; SIGKILL mid job, lease expiry, re-run; assert no duplicate facts. Builds on the Lane D drain. **Effort:** M. **Priority:** P1.- [ ] **P2 — CI check that every mutating operation is registered in the generator.****What:** `MODEL` is a `Record<OpKind, Fold>` and `EFFECT_SEAMS` a `Record<EffectKind, …>`, so a new op kind or effect kind without a fold or seam fails typecheck; a new mutating operation in `operations.ts` is not forced into `OP_KINDS`. **Fix:** a test listing every `mutating: true` operation as either a robot op or an explicit exclusion with its reason. **Effort:** S. **Priority:** P2.- [ ] **P2 — Pre-activation claim lock order.**diff --git a/docs/architecture/key-files/tooling-and-tests.md b/docs/architecture/key-files/tooling-and-tests.mdindex d30829c088..38145ddeb6 100644--- a/docs/architecture/key-files/tooling-and-tests.md+++ b/docs/architecture/key-files/tooling-and-tests.md@@ -62,7 +62,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `scripts/persistence/{harness,schedules,worker,validate,failure-diagnostics}.ts` — executable concurrency gate using real journal/coordinator APIs: 1,000 seeded schedules per engine, eight actual process-kill publication boundaries, and 10,000 writes from four producer processes. Each phase owns a temporary disk PGLite datastore or a fresh test Postgres database. Independent accounting queries verify conservation; every soak receipt is compared to its canonical snapshot and file. JSON manifests separate actual counts and latency measurements from the configured Linux/Bun CI matrix. Failed runs preserve private fixtures and collect bounded, allowlisted request/queue/owner diagnostics without changing deadlines or hiding the original error. Cleanup commands read the existing test URL from the environment. The PGLite loopback endpoint is a fixture transport, not production authentication coverage. Contract and commands: `scripts/persistence/README.md`; smoke entries: `test/persistence-chaos.slow.test.ts`, `test/e2e/persistence-chaos.test.ts`; diagnostic/retention contracts: `test/persistence-failure-diagnostics.test.ts`.-- `scripts/persistence/{ops,generator,model,crash-robot,robot-driver,shrink,lock-order,history-fixture,would-have-caught}.ts` — the crash robot, a phase of `validate.ts` (`--robot-seconds`, default 300; CI runs it as its own `persistence-validation.yml` job). `ops.ts` is the JSON op-descriptor protocol between driver and workers: each descriptor names an op kind (put/edit/delete/restore page, remember/forget, takes add/supersede, timeline add, sync, connector publish, revoke access), an actor (the local CLI principal or a remote agent whose bearer token the production `verifyAccessToken` resolves), a source, a fixed request id and arguments whose `{ $ref }` values come from earlier observations; workers run every op through its registered operation handler. `generator.ts` builds seeded schedules: the fixed cross-boundary sequences (withdrawal then stale republication, overlapping slugs across two sources, competing writers, caller-bound replay, authority revoked with effects pending, sync and connector publish racing direct writes) plus random sequences with concurrent groups. `model.ts` is the temporal oracle: receipts and revisions at the observation point, legal later transitions, late receipts against page history, withdrawal permanence on recall/get_page/facts, source isolation, caller-bound replay, takes/facts fence projections, attribution, orphans, drain and wedge bounds; `EFFECT_SEAMS` maps every `EffectKind` to its trigger op and seam (typecheck-exhaustive). `crash-robot.ts` runs a schedule in-process or as a worker role (`count`, `run` frozen at a `fault-points.ts` seam and SIGKILLed by the driver, `recover`), plus process faults (stale `index.lock`, a hung git commit holding `index.lock`, Postgres session drops). `robot-driver.ts` crashes every seam the fixed sequences reach, then fills the budget with random sequences; Postgres connects through `GBRAIN_PGBOUNCER_URL` when set and, under a budget below 300 s, skips seams that wait out a dead owner's claim lease. `shrink.ts` is dependency-preserving ddmin accepted on 3/3 reproduction; `--replay`/`--shrink` re-run a manifest's failing runs. `lock-order.ts` traces each transaction's row locks (worktrees before sources, sources by id, no exclusive brain lock in a publication). `history-fixture.ts` exports `buildHistoryFixture(engine, { pages, seed, sources, worktrees })` (a managed brain with real persistence history up to 10k pages, used by engine graduation and attribution backfill) and `prepareTopology`. `would-have-caught.ts` reverts each fix in `would-have-caught.json` in a scratch worktree and runs the pre-robot gate and the robot against it. Tests: `test/persistence-crash-robot.test.ts`, `test/persistence-crash-robot.slow.test.ts` (shrunk regressions in `test/fixtures/crash-robot/`), `test/persistence-history-fixture.test.ts`.+- `scripts/persistence/{ops,generator,model,crash-robot,robot-driver,shrink,lock-order,history-fixture,would-have-caught}.ts` — the crash robot, a phase of `validate.ts` (`--robot-seconds`, default 300; CI runs it as its own `persistence-validation.yml` job). `ops.ts` is the JSON op-descriptor protocol between driver and workers: each descriptor names an op kind (put/edit/delete/restore page, remember/forget, takes add/supersede, timeline add, sync, connector publish, revoke access), an actor (the local CLI principal or a remote agent whose bearer token the production `verifyAccessToken` resolves), a source, a fixed request id and arguments whose `{ $ref }` values come from earlier observations; workers run every op through its registered operation handler. `generator.ts` builds seeded schedules: the fixed cross-boundary sequences (withdrawal then stale republication, overlapping slugs across two sources, competing writers, caller-bound replay, authority revoked with effects pending, sync and connector publish racing direct writes) plus random sequences with concurrent groups. `model.ts` is the temporal oracle: receipts and revisions at the observation point, legal later transitions, late receipts against page history, withdrawal permanence on recall/get_page/facts, source isolation, caller-bound replay, takes/facts fence projections, attribution, orphans, drain and wedge bounds; `EFFECT_SEAMS` maps every `EffectKind` to its trigger op and seam (typecheck-exhaustive). `crash-robot.ts` runs a schedule in-process or as a worker role (`count`, `run` frozen at a `fault-points.ts` seam and SIGKILLed by the driver, `recover`), plus process faults (stale `index.lock`, a hung git commit holding `index.lock`, Postgres session drops, the owner killed after a `facts-absorb` job's extraction commits and the job re-run). `robot-driver.ts` crashes every seam the fixed sequences reach, then fills the budget with random sequences; Postgres connects through `GBRAIN_PGBOUNCER_URL` when set and, under a budget below 300 s, skips seams that wait out a dead owner's claim lease. `shrink.ts` is dependency-preserving ddmin accepted on 3/3 reproduction; `--replay`/`--shrink` re-run a manifest's failing runs. `lock-order.ts` traces each transaction's row locks (worktrees before sources, sources by id, no exclusive brain lock in a publication). `history-fixture.ts` exports `buildHistoryFixture(engine, { pages, seed, sources, worktrees })` (a managed brain with real persistence history up to 10k pages, used by engine graduation and attribution backfill) and `prepareTopology`. `would-have-caught.ts` reverts each fix in `would-have-caught.json` in a scratch worktree and runs the pre-robot gate and the robot against it. Tests: `test/persistence-crash-robot.test.ts`, `test/persistence-crash-robot.slow.test.ts` (shrunk regressions in `test/fixtures/crash-robot/`), `test/persistence-history-fixture.test.ts`.- `scripts/persistence/{matrix,matrix-cases}.ts` — required real Postgres/PgBouncer deployment matrix: 24 combinations of RLS policy enforcement, ordinary pool sizes 1/2/3 and shared/separate direct capacity. Production bulk reservations must leave short claims, renewals and reads usable; size-one publication stays queued. Fresh fixtures also verify successor manifests, stale owners, retained native lock exclusion during root replacement and source deletion/recreation. `test/e2e/persistence-runtime-matrix.test.ts` runs it when configured and refuses missing required pooler fixtures. Supplied URLs pass the test-database guard before its CREATE/DROP control connection uses the maintenance database; fresh case databases isolate it from other E2E shards.- `scripts/persistence/{performance,read-workload,read-metrics,read-admission,read-diagnostics}.ts` — required median-of-three read-workload validity check with advisory CI latency around the existing heavy query corpus (500 pages, 200 reads, four writers, writesPerWriter 25, four-connection PostgreSQL pool). Both engines use public page mutation handlers; every read/write or drained sampler error invalidates the sample, actual in-flight mutation intervals must cover at least 90% of reads, and CI reports the 50% loaded-versus-idle p99 threshold without blocking on that ratio. CI uses `--informational`, which never suppresses invalid-workload failures; the default CLI and explicit strict heavy runs still enforce the threshold. Isolated children retain runtime/source hashes, queue/admission/commit/RSS/recovery/pool metrics and bounded diagnostic records with total/dropped counts, including failed partial observations. Numeric query/corpus/write indices and monotonic timestamps correlate reads, admissions, terminal receipts and pool samples without retaining SQL, parameters, identifiers, content or raw errors. Fixed failure stages retain only allowlisted error properties; raw stacks are omitted. The root postgres.js begin observer covers lexical readers and writers, preserves the original promise/receiver/arguments, and excludes nested savepoints. Dispatch-to-callback includes BEGIN and client scheduling, not pure checkout wait; PGLite has no transaction-entry timing. Identical 20ms timers record event-loop lateness in both phases. Observers run during seed/warmup before measurement; context setup and read retention sit outside query timing where possible, but transaction/timer callbacks add unquantified overhead. No SQL or server sampling is added, and sparse pool samples cannot establish lock causes. The original `tests/heavy/read_latency_under_sync.sh` invokes this runner. The stable admission proxy requires one resolved top-level queued journal transaction per committed UUID. `test/persistence-performance.test.ts` guards validity, strict threshold semantics and advisory CLI exit behavior; `test/persistence-admission-observer.test.ts` proves rollback/publication boundaries; `test/persistence-read-diagnostics{,.serial}.test.ts` covers bounds, transparency, nested transactions, safe failure retention, tiny manifests and late sampler rejection.diff --git a/scripts/persistence/README.md b/scripts/persistence/README.mdindex 11db5d6c92..08b00d3ca6 100644--- a/scripts/persistence/README.md+++ b/scripts/persistence/README.md@@ -102,8 +102,11 @@ fresh worker checks the state left behind, drains, resubmits the interruptedrequests with their original request ids and finishes the sequence. Randomsequences fill the rest of the budget. Process faults run once per engine:a stale `index.lock`, a hung `git commit` that holds `index.lock` (it releases-the lock on SIGTERM, not on SIGKILL), and, on Postgres, every session of the-run database dropped every 400 ms.+the lock on SIGTERM, not on SIGKILL), on Postgres every session of the run+database dropped every 400 ms, and the owner killed right after a+`facts-absorb` job's extraction commits (deterministic chat and embedding+stubs); the job then runs again and every absorbed fact must be active+exactly once.The reference model (`model.ts`) checks: a committed receipt is visible atonce and later revisions move only through committed ops; a late receiptdiff --git a/scripts/persistence/crash-robot.ts b/scripts/persistence/crash-robot.tsindex 9aa03312e3..6203ac9981 100644--- a/scripts/persistence/crash-robot.ts+++ b/scripts/persistence/crash-robot.ts@@ -117,14 +117,14 @@ export async function runSchedule(world: World, schedule: Schedule): Promise<Sch/* Process-separated crash mode: the worker side. *//* ------------------------------------------------------------------------ */-export type ProcessFault = 'stale_index_lock' | 'hung_git' | 'pooler_disconnect';+export type ProcessFault = 'stale_index_lock' | 'hung_git' | 'pooler_disconnect' | 'facts_absorb_kill';export interface RobotConfig {kind: 'pglite' | 'postgres'; root: string; dataDir: string; databaseUrl?: string;/** Direct (unpooled) URL of the run database, for administrative fault injection. */directUrl?: string;schedule: Schedule; worktrees: number; statePath: string;- /** SIGKILL at the nth time this seam is reached (1-based). */- fault?: { point: FaultPoint; nth: number };+ /** SIGKILL at the nth time this seam is reached (1-based), optionally counting only one operation's requests. */+ fault?: { point: FaultPoint; nth: number; operation?: string };process?: ProcessFault;}interface RobotState {@@ -196,6 +196,39 @@ exec '${real}' "$@"return { marker, release: () => rmSync(marker, { force: true }) };}+const ABSORB_SLUG = 'meetings/robot-review';+const ABSORB_FACTS = ['Robot review ships the crash gate weekly.', 'Robot review keeps withdrawn facts out of recall.'];++/** Deterministic providers for facts extraction: a chat stub that names two facts about the review, a constant embedding. */+async function stubFactsProviders(): Promise<void> {+ const gateway = await import('../../src/core/ai/gateway.ts');+ gateway.configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: { OPENAI_API_KEY: 'synthetic-local-fixture' } } as never);+ gateway.__setChatTransportForTests((async () => ({ text: JSON.stringify({ facts: ABSORB_FACTS.map(fact => ({ fact, kind: 'fact', entity: ABSORB_SLUG, confidence: 0.9, notability: 'high' })) }),+ blocks: [], stopReason: 'end', usage: { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: 'test:stub', providerId: 'test' })) as never);+ gateway.__setEmbedTransportForTests((async ({ values }: { values: string[] }) => ({ embeddings: values.map(() => [1, ...Array(1535).fill(0)]) })) as never);+}++/** Run the queued facts-absorb job through its registered handler, as a worker does after claiming it. */+async function runAbsorbJob(engine: BrainEngine, attempts: number): Promise<unknown> {+ const [job] = await retryingRead(() => engine.executeRaw<{ id: number; data: Record<string, unknown> }>("SELECT id,data FROM minion_jobs WHERE name='facts-absorb' ORDER BY id LIMIT 1"));+ if (!job) throw new Error('facts_absorb_kill: no facts-absorb job was queued');+ const { MinionWorker } = await import('../../src/core/minions/worker.ts');+ const { registerBuiltinHandlers } = await import('../../src/commands/jobs.ts');+ const worker = new MinionWorker(engine, { queue: 'crash-robot' });+ await registerBuiltinHandlers(worker, engine, { quiet: true });+ const signal = new AbortController().signal;+ return worker.getHandler('facts-absorb')!({ id: Number(job.id), name: 'facts-absorb', data: job.data, attempts_made: attempts, signal, deadlineAtMs: null,+ shutdownSignal: signal, updateProgress: async () => {}, updateTokens: async () => {}, log: async () => {}, isActive: async () => true, readInbox: async () => [] } as never);+}++/** Every absorbed fact is active exactly once. */+async function checkAbsorbedOnce(model: ReferenceModel, stage: string): Promise<void> {+ const rows = await model.q<{ fact: string; n: number }>(`SELECT fact,count(*)::int AS n FROM facts WHERE fact = ANY($1::text[])+ AND expired_at IS NULL GROUP BY fact`, [ABSORB_FACTS]);+ for (const row of rows) if (row.n > 1) model.violate({ class: 'duplicate_apply', detail: `${stage}: "${row.fact}" is active ${row.n} times` });+ if (rows.length !== ABSORB_FACTS.length) model.violate({ class: 'lost_write', detail: `${stage}: ${rows.length}/${ABSORB_FACTS.length} absorbed facts are active` });+}+/*** Process faults SIGKILL cannot model. Each must end in a terminal state or a* typed, agent-facing error, never a wedge, and must clear once the fault does.@@ -230,6 +263,22 @@ async function processFault(config: RobotConfig, world: World, model: ReferenceM}shim.release();await engine.executeRaw("UPDATE persistence_effects SET next_attempt_at=now() WHERE kind='git' AND state='queued'");+ } else if (config.process === 'facts_absorb_kill') {+ // A substantive meeting page queues facts-backstop work; the worker runs the facts-absorb job and is+ // SIGKILLed right after its extraction commits, before the job completes (config.fault).+ await stubFactsProviders();+ const source = world.remotes[0].sourceId;+ const body = 'The robot review covered the crash gate, its seams and the withdrawal checks in detail. '.repeat(4);+ const put = await executeOp(world, { v: 1, id: 'absorb-page', kind: 'put_page', actor: 'local', source, requestId: crypto.randomUUID(),+ args: { slug: ABSORB_SLUG, content: `---\ntype: meeting\ntitle: Robot review\n---\n\n${body}\n` } });+ if (put.status !== 'committed') throw new Error(`facts_absorb_kill: the meeting page did not commit (${put.code})`);+ const deadline = Date.now() + 30_000;+ while (!(await retryingRead(() => engine.executeRaw("SELECT 1 FROM minion_jobs WHERE name='facts-absorb'"))).length) {+ if (Date.now() > deadline) throw new Error('facts_absorb_kill: the facts-backstop effect never queued a facts-absorb job');+ await Bun.sleep(100);+ }+ await runAbsorbJob(engine, 0);+ await checkAbsorbedOnce(model, 'facts_absorb_kill (no crash reached)');} else if (config.process === 'pooler_disconnect') {// Every 400 ms the server drops every other session of this database, as a pooler or failover does.const admin = postgres(config.directUrl!, { max: 1, onnotice() {} });@@ -276,7 +325,7 @@ export async function robotWorker(role: 'count' | 'run' | 'recover', config: Robif (role === 'run' && config.fault) {let seen = 0; const fault = config.fault;installFaultHook((point, detail) => {- if (point !== fault.point || ++seen !== fault.nth) return;+ if (point !== fault.point || (fault.operation && detail.operation !== fault.operation) || ++seen !== fault.nth) return;freeze({ event: 'fault', point, nth: seen, detail });});}@@ -314,6 +363,14 @@ export async function robotWorker(role: 'count' | 'run' | 'recover', config: Robawait model.settleLate(inFlight, observed);await model.checkGlobal('after resubmission');}+ if (config.process === 'facts_absorb_kill') {+ // The job's lease expired with its owner; a worker runs it again.+ await stubFactsProviders();+ await runAbsorbJob(engine, 1);+ await checkAbsorbedOnce(model, 'facts-absorb re-run after SIGKILL');+ await finish(world, model, `${config.schedule.label}+facts_absorb_kill`);+ return finalize(config, model, { crashed: true, fault: config.fault, process: config.process });+ }await runSteps(world, model, config.schedule, state!.next + inFlight.length);await finish(world, model, config.schedule.label);return finalize(config, model, { crashed: true, fault: config.fault, inFlight: state!.inFlight });diff --git a/scripts/persistence/robot-driver.ts b/scripts/persistence/robot-driver.tsindex 5f0b7eafc7..89608e3bea 100644--- a/scripts/persistence/robot-driver.ts+++ b/scripts/persistence/robot-driver.ts@@ -149,6 +149,9 @@ export async function runRobotPhase(o: RobotOptions) {if (fault === 'pooler_disconnect' && !o.admin) continue;record(await execute(fixed[1], 'run', { process: fault }));}+ // serve killed right after the facts-absorb job's extraction commits; the job then runs again.+ record(await execute({ ...fixed[1], ops: [], groups: [] }, 'run', { process: 'facts_absorb_kill',+ fault: { point: 'publication:after_commit', nth: 1, operation: 'extract_facts' } }));// Random sequences fill the rest of the budget.for (let i = 0; !over(); i++) {const schedule = randomSchedule(ROBOT_TOPOLOGY, (o.seed + 1 + i) >>> 0, 24);