// Every hook on the machine reads, extends and rewrites ~/.node9/loop-state.json. // Without a lock, two hooks finishing at the same instant each wrote back what // they had read, and one call's record was gone: a missing repeat hides a loop, // a missing new call leaves another agent's count one step closer to a block. // // Real processes, because the failure only exists between processes. Four // writers start on the same clock tick and record 60 distinct calls each. // What must hold: every call a writer reports as recorded is in the file // afterwards. On the code before the lock this lost records on every run // (measured three times: the first writer kept 11, 25 and 36 of its 60). // // A writer that cannot get the lock in time judges its call and writes nothing // (recorded: false); it must never write without the lock. Writing anyway is // what lost a record on Windows CI: there a sleeping waiter wakes on a ~15 ms // timer, the holder takes the lock again first, and a writer that gave up // waiting overwrote the holder's records (1 and 2 of 60 lost, 2026-11-29). import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import { spawn } from 'child_process'; import fs from 'fs'; import os from 'os'; import path from 'path'; let home: string; beforeEach(() => { home = fs.mkdtempSync(path.join(os.tmpdir(), 'node9-loop-concurrency-')); fs.mkdirSync(path.join(home, '.node9'), { recursive: true }); }); afterEach(() => { try { fs.rmSync(home, { recursive: true, force: true }); } catch { /* best effort */ } }); const WRITERS = 4; const CALLS = 60; interface WriterStats { recorded: number; skipped: number; failedOpen: number; } function runWriter( id: number, startAt: number ): Promise<{ code: number | null; stats?: WriterStats }> { const driver = path.join(home, `driver-${id}.ts`); const statsFile = path.join(home, `stats-${id}.json`); fs.writeFileSync( driver, `import fs from 'fs'; import { recordAndCheck } from ${JSON.stringify(path.resolve('src/loop-detector.ts'))}; while (Date.now() < ${startAt}) { /* every writer starts on the same tick */ } const stats = { recorded: 0, skipped: 0, failedOpen: 0 }; for (let i = 0; i < ${CALLS}; i++) { const r = recordAndCheck('Bash', { command: 'writer ${id} call ' + i }, 5, 600_000, 'session-${id}'); if (r.recorded) stats.recorded++; else if (r.count === 0) stats.failedOpen++; // a read or write threw else stats.skipped++; // lock not taken in time: judged, not written } fs.writeFileSync(${JSON.stringify(statsFile)}, JSON.stringify(stats)); ` ); return new Promise((resolve) => { const child = spawn(process.execPath, [require.resolve('tsx/cli'), driver], { env: { ...process.env, HOME: home, USERPROFILE: home }, stdio: 'ignore', }); const done = (code: number | null) => { let stats: WriterStats | undefined; try { stats = JSON.parse(fs.readFileSync(statsFile, 'utf-8')) as WriterStats; } catch { /* the writer died before it wrote them */ } resolve({ code, stats }); }; child.on('exit', done); child.on('error', () => done(null)); }); } describe('loop-state.json under concurrent hooks', () => { it('keeps every record a writer recorded when four processes write at once', async () => { // Late enough for every tsx child to be loaded and waiting. const startAt = Date.now() + 6000; const results = await Promise.all( Array.from({ length: WRITERS }, (_, id) => runWriter(id, startAt)) ); expect(results.map((r) => r.code)).toEqual(Array(WRITERS).fill(0)); const stats = results.map((r) => r.stats!); for (const s of stats) { expect(s).toBeDefined(); expect(s.recorded + s.skipped + s.failedOpen).toBe(CALLS); } // No call failed open (a read or write that threw). expect(stats.map((s) => s.failedOpen)).toEqual(Array(WRITERS).fill(0)); const stateFile = path.join(home, '.node9', 'loop-state.json'); const records = JSON.parse(fs.readFileSync(stateFile, 'utf-8')) as Array<{ s?: string }>; // The property: a recorded call is never lost to another writer. const inFile = Array.from( { length: WRITERS }, (_, id) => records.filter((r) => r.s === `session-${id}`).length ); expect(inFile).toEqual(stats.map((s) => s.recorded)); expect(records).toHaveLength(stats.reduce((n, s) => n + s.recorded, 0)); // The lock is not just refusing everyone: most calls get through it. expect(stats.reduce((n, s) => n + s.recorded, 0)).toBeGreaterThanOrEqual(CALLS); // Nothing left behind: no lock, no temp file. expect(fs.readdirSync(path.join(home, '.node9'))).toEqual(['loop-state.json']); }, 60_000); });