Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(crash-robot): keep later chunks of a level read as fault slots, cut at fixed offsets (#7124)
garrytan844346e99d92
diff --git a/scripts/persistence/crash-robot.ts b/scripts/persistence/crash-robot.tsindex f1b1bcc893..974e24d728 100644--- a/scripts/persistence/crash-robot.ts+++ b/scripts/persistence/crash-robot.ts@@ -17,6 +17,8 @@ import { PostgresEngine } from '../../src/core/postgres-engine.ts';import { disposePersistenceConsumer, startPersistenceConsumer } from '../../src/core/persistence/service.ts';import { installFaultHook, type FaultDetail, type FaultPoint } from '../../src/core/persistence/fault-points.ts';import { bigintToStringReplacer } from '../../src/core/utils.ts';+import { hardenedGitStream } from '../../src/core/hardened-git.ts';+import { __setSyncGitStreamForTests } from '../../src/core/persistence/sync-git-stream.ts';import { assertSafeE2eDatabaseUrl } from '../../test/helpers/db-guard.ts';import postgres from '#postgres';import { prepareTopology } from './history-fixture.ts';@@ -211,21 +213,26 @@ const PER_REQUEST_SEAMS: ReadonlySet<FaultPoint> = new Set<FaultPoint>(['consume* #7124: a sync pass makes as many rounds as the schedule's races dictate: a direct write still in flight when round 1* reads its level defers that page to a round of its own, so the same schedule makes 2 or 3 rounds per pass (a count role* saw 7 `sync:level_chunk`, a cold run made 6 and its fault at #7 went unreached). These seams count in round slots: in- * each pass, the first time a seam (a chunk: of each Git read) is reached in round 1, and the first time in a later- * round. Every pass that made a round 1 with work makes a later round, its confirm round at least, so every slot comes- * again; `sync:batch_entries` counts in round 1 alone, since a later round has entries only when the race deferred one.+ * each pass, the first time a seam is reached in round 1, and the first time in a later round; a `sync:level_chunk`+ * slot is one chunk ordinal of one Git read (`LEVEL_CHUNK_BYTES` makes the ordinals the same in every run). Every pass+ * that made a round 1 with work makes a later round, its confirm round at least, so every slot comes again;+ * `sync:batch_entries` counts in round 1 alone, since a later round has entries only when the race deferred one.*/const ROUND_SEAMS: ReadonlySet<FaultPoint> = new Set<FaultPoint>(['sync:round_start', 'sync:level_chunk', 'sync:level_result', 'sync:level_take','sync:level_read', 'sync:confirm_parallel', 'sync:level_narrow', 'sync:batch_entries']);/** How far this pass advances the seam's count: 1, 0 for a repeat of the same request at a per-request seam or of a round slot, the epochs passed at the claim seam. */export function seamCounter(): (point: FaultPoint, detail: FaultDetail) => number {const seen = new Set<string>(), prepared = new Set<string>();+ const chunks = new Map<string, number>();let claimSlots = 0, pass = 0, round = 0;return (point, detail) => {if (point === 'sync:round_start') { round = Number(detail.round); if (round === 1) pass++; }if (ROUND_SEAMS.has(point)) {if (point === 'sync:batch_entries' && round > 1) return 0;- const key = `${point}\u0000${pass}\u0000${round > 1 ? 'later' : 'first'}\u0000${detail.read ?? ''}`;+ const read = `${pass}\u0000${round}\u0000${detail.read ?? ''}`;+ const ordinal = point === 'sync:level_chunk' ? (chunks.get(read) ?? 0) + 1 : 0;+ if (ordinal) chunks.set(read, ordinal);+ const key = `${point}\u0000${pass}\u0000${round > 1 ? 'later' : 'first'}\u0000${detail.read ?? ''}\u0000${ordinal}`;if (seen.has(key)) return 0;seen.add(key);return 1;@@ -245,6 +252,30 @@ export function seamCounter(): (point: FaultPoint, detail: FaultDetail) => numbe};}+/**+ * #7124: how many chunks a Git level read arrives in follows the pipe's timing, not the bytes read, so a count role and a+ * run could see a read in different chunk counts. Robot workers re-cut every level read's stdout at fixed offsets of+ * this many bytes (the last piece holds the rest): a read's chunk ordinals are then a function of what Git printed, and a+ * robot tree of a few dozen paths reads in several chunks, so a crash between two chunks of one read is a slot like any.+ */+export const LEVEL_CHUNK_BYTES = 512;+export function fixedChunks(runner: typeof hardenedGitStream = hardenedGitStream): typeof hardenedGitStream {+ return async (root, args, opts) => {+ const deliver = opts.onChunk;+ if (!deliver) return await runner(root, args, opts);+ let rest = Buffer.alloc(0), chain = Promise.resolve();+ const emit = (piece: Buffer) => { chain = chain.then(() => deliver(piece)); };+ const result = await runner(root, args, { ...opts, onChunk: chunk => {+ rest = Buffer.concat([rest, chunk]);+ for (; rest.length >= LEVEL_CHUNK_BYTES; rest = rest.subarray(LEVEL_CHUNK_BYTES)) emit(Buffer.from(rest.subarray(0, LEVEL_CHUNK_BYTES)));+ return chain;+ } });+ if (rest.length) emit(Buffer.from(rest));+ await chain;+ return result;+ };+}+/*** The `run` role's hook: freeze at the nth matching seam. A hook that throws* would unwind into the code under test, which then keeps running as if no@@ -428,6 +459,7 @@ export async function robotWorker(role: 'count' | 'run' | 'recover', config: Rob}world.descriptors = new Map(config.schedule.ops.map(d => [d.id, d]));installLockOrderTrace();+ __setSyncGitStreamForTests(fixedChunks());const counts: Record<string, number> = {};const counted = seamCounter();const hook = role === 'count' ? (point: FaultPoint, detail: FaultDetail) => { const advanced = counted(point, detail); if (advanced) counts[point] = (counts[point] ?? 0) + advanced; }@@ -485,6 +517,7 @@ export async function robotWorker(role: 'count' | 'run' | 'recover', config: Robreturn finalize(config, model, { crashed: true, fault: config.fault, inFlight: state!.inFlight });} finally {installFaultHook(undefined);+ __setSyncGitStreamForTests();await disposePersistenceConsumer(engine).catch(() => {});await engine.disconnect();}diff --git a/test/persistence-crash-robot.test.ts b/test/persistence-crash-robot.test.tsindex a4af2fd110..33f1ed9030 100644--- a/test/persistence-crash-robot.test.ts+++ b/test/persistence-crash-robot.test.ts@@ -24,7 +24,8 @@ import { FULL_ROBOT_SECONDS, ROBOT_TOPOLOGY, restrict, runRobotPhase, type Robotimport { robotFailure, robotFullGate, runValidation, spawnWorker } from '../scripts/persistence/validate.ts';import { faultPoint, installFaultHook, type FaultDetail, type FaultPoint } from '../src/core/persistence/fault-points.ts';import { shrinkRun } from '../scripts/persistence/shrink.ts';-import { finish, runSchedule, runSteps, seamCounter } from '../scripts/persistence/crash-robot.ts';+import { finish, fixedChunks, LEVEL_CHUNK_BYTES, runSchedule, runSteps, seamCounter } from '../scripts/persistence/crash-robot.ts';+import type { hardenedGitStream } from '../src/core/hardened-git.ts';import { installLockOrderTrace, lockOrderReport } from '../scripts/persistence/lock-order.ts';import { prepareTopology } from '../scripts/persistence/history-fixture.ts';import { claimPersistenceEffect, releaseAbandonedClaims } from '../src/core/persistence/effect-journal.ts';@@ -469,12 +470,28 @@ process.stdout.write('{"event":"continued"}\\n');}reader.releaseLock();expect(lines).toEqual([- { event: 'counts', counts: { 'sync:round_start': 4, 'sync:level_chunk': 6, 'sync:level_read': 4, 'sync:batch_entries': 2 } },- { event: 'fault', point: 'sync:level_chunk', nth: 6, detail: { read: 'ls-files' } },+ { event: 'counts', counts: { 'sync:round_start': 4, 'sync:level_chunk': 8, 'sync:level_read': 4, 'sync:batch_entries': 2 } },+ { event: 'fault', point: 'sync:level_chunk', nth: 8, detail: { read: 'ls-files' } },]);} finally { child.kill('SIGKILL'); await child.exited; rmSync(dir, { recursive: true, force: true }); }}, 90_000);+ test('#7124: robot workers cut a Git level read at fixed offsets, so its chunk ordinals do not follow the pipe', async () => {+ const bytes = Buffer.from(Array.from({ length: 1300 }, (_, i) => i % 251));+ const cut = async (sizes: number[]) => {+ const pieces: Buffer[] = [];+ const runner = (async (_root: string, _args: string[], opts: { onChunk?: (chunk: Buffer) => void | Promise<void> }) => {+ let at = 0;+ for (const size of sizes) { await opts.onChunk!(bytes.subarray(at, at + size)); at += size; }+ return { ok: true, bytes: at, endsWithNul: false } as never;+ }) as unknown as typeof hardenedGitStream;+ await fixedChunks(runner)('/', ['ls-tree'], { timeoutMs: 1000, onChunk: async chunk => { await Bun.sleep(1); pieces.push(chunk); } });+ return pieces.map(piece => piece.length);+ };+ expect(await cut([1300])).toEqual([LEVEL_CHUNK_BYTES, LEVEL_CHUNK_BYTES, 1300 - 2 * LEVEL_CHUNK_BYTES]);+ expect(await cut([7, 600, 1, 692])).toEqual(await cut([1300]));+ });+test('#6957: finish waits for the claim pass after its probe, so the last claim epoch a count role sees is reached in every run', async () => {await robotBrain(async ({ world }) => {const counted = seamCounter(); const prepared = new Set<string>(); let slots = 0;