diff --git a/hooks/codex/codex-session-mapping.cjs b/hooks/codex/codex-session-mapping.cjs index ffb46eef9..adf8a0396 100644 --- a/hooks/codex/codex-session-mapping.cjs +++ b/hooks/codex/codex-session-mapping.cjs @@ -96,21 +96,122 @@ function firstValue(keys, getValue) { return undefined; } -function readRegistry(registryFile) { - let existing; +const STALE_LOCK_MS = 30_000; +const LOCK_RETRY_MS = 50; +const LOCK_WAIT_MS = Number(process.env.AI_DEVKIT_SESSION_REGISTRY_LOCK_WAIT_MS) || 10_000; +function registryWarn(message) { + console.warn(message); +} + +function sleepMs(ms) { + const end = Date.now() + ms; + while (Date.now() < end) { + /* spin */ + } +} + +function tryAcquireLock(lockPath, staleMs) { try { - existing = JSON.parse(fs.readFileSync(registryFile, 'utf8')); + fs.closeSync(fs.openSync(lockPath, 'wx', 0o600)); + return true; } catch { - return {}; + try { + const age = Date.now() - fs.statSync(lockPath).mtimeMs; + if (age > staleMs) { + fs.unlinkSync(lockPath); + fs.closeSync(fs.openSync(lockPath, 'wx', 0o600)); + return true; + } + } catch { + /* races with the holder are fine — losing means we wait */ + } + return false; } +} - return existing && typeof existing === 'object' && !Array.isArray(existing) ? existing : {}; +function releaseLock(lockPath) { + try { + fs.unlinkSync(lockPath); + } catch { + /* already gone */ + } +} + +function withRegistryLock(registryFile, fn) { + fs.mkdirSync(path.dirname(registryFile), { recursive: true }); + const lockPath = `${registryFile}.lock`; + const deadline = Date.now() + LOCK_WAIT_MS; + while (Date.now() < deadline) { + if (tryAcquireLock(lockPath, STALE_LOCK_MS)) { + try { + fn(); + return true; + } finally { + releaseLock(lockPath); + } + } + sleepMs(LOCK_RETRY_MS); + } + registryWarn( + `ai-devkit: timed out acquiring lock for ${registryFile}; skipping this registry update`, + ); + return false; +} + +function readRegistryForUpdate(registryFile) { + let raw; + + try { + raw = fs.readFileSync(registryFile, 'utf8'); + } catch (e) { + if (e && e.code === 'ENOENT') return {}; + throw e; + } + + try { + const existing = JSON.parse(raw); + if (existing && typeof existing === 'object' && !Array.isArray(existing)) return existing; + throw new Error('sessions.json is not a JSON object'); + } catch (e) { + if (e.message === 'sessions.json is not a JSON object') throw e; + throw new Error('sessions.json is not valid JSON'); + } +} + +function loadRegistryForUpdate(registryFile) { + try { + return readRegistryForUpdate(registryFile); + } catch (e) { + if ( + e.message !== 'sessions.json is not valid JSON' && + e.message !== 'sessions.json is not a JSON object' + ) { + throw e; + } + if (!fs.existsSync(registryFile)) return {}; + const corruptPath = `${registryFile}.corrupt-${Date.now()}`; + fs.renameSync(registryFile, corruptPath); + registryWarn( + `ai-devkit: sessions registry at ${registryFile} was unreadable; renamed to ${corruptPath} and starting fresh`, + ); + return {}; + } } function writeRegistry(registryFile, registry) { fs.mkdirSync(path.dirname(registryFile), { recursive: true }); - fs.writeFileSync(registryFile, JSON.stringify(registry, null, 2), 'utf8'); + const tmp = `${registryFile}.${process.pid}.${Date.now()}.tmp`; + fs.writeFileSync(tmp, JSON.stringify(registry, null, 2), 'utf8'); + fs.renameSync(tmp, registryFile); +} + +function updateRegistry(registryFile, mutator) { + return withRegistryLock(registryFile, () => { + const registry = loadRegistryForUpdate(registryFile); + mutator(registry); + writeRegistry(registryFile, registry); + }); } function findSessionFileById(homeDir, sessionId) { @@ -159,7 +260,9 @@ function resolveCodexPid(input) { const input = readHookInput(); const homeDir = os.homedir(); const registryFile = path.join(homeDir, '.codex', 'ai-devkit', 'sessions.json'); -const registry = readRegistry(registryFile); +const codexPid = resolveCodexPid(input); +const sessionFile = resolveSessionFile(homeDir, input) || 'ephemeral'; -registry[resolveCodexPid(input)] = resolveSessionFile(homeDir, input) || 'ephemeral'; -writeRegistry(registryFile, registry); +updateRegistry(registryFile, (registry) => { + registry[codexPid] = sessionFile; +}); diff --git a/packages/cli/assets/codex/codex-session-mapping.cjs b/packages/cli/assets/codex/codex-session-mapping.cjs index 047bc9f7d..adf8a0396 100644 --- a/packages/cli/assets/codex/codex-session-mapping.cjs +++ b/packages/cli/assets/codex/codex-session-mapping.cjs @@ -1,61 +1,61 @@ -const fs = require("node:fs"); -const os = require("node:os"); -const path = require("node:path"); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); const SESSION_FILE_ENV_KEYS = [ - "CODEX_SESSION_FILE", - "CODEX_SESSION_FILE_PATH", - "CODEX_TRANSCRIPT_PATH", - "OPENAI_CODEX_SESSION_FILE", - "OPENAI_CODEX_SESSION_FILE_PATH", + 'CODEX_SESSION_FILE', + 'CODEX_SESSION_FILE_PATH', + 'CODEX_TRANSCRIPT_PATH', + 'OPENAI_CODEX_SESSION_FILE', + 'OPENAI_CODEX_SESSION_FILE_PATH', ]; const SESSION_FILE_INPUT_KEYS = [ - "session_file", - "sessionFile", - "session_file_path", - "sessionFilePath", - "transcript_path", - "transcriptPath", + 'session_file', + 'sessionFile', + 'session_file_path', + 'sessionFilePath', + 'transcript_path', + 'transcriptPath', ]; const SESSION_ID_ENV_KEYS = [ - "CODEX_THREAD_ID", - "CODEX_SESSION_ID", - "OPENAI_CODEX_THREAD_ID", - "OPENAI_CODEX_SESSION_ID", + 'CODEX_THREAD_ID', + 'CODEX_SESSION_ID', + 'OPENAI_CODEX_THREAD_ID', + 'OPENAI_CODEX_SESSION_ID', ]; const SESSION_ID_INPUT_KEYS = [ - "session_id", - "sessionId", - "thread_id", - "threadId", - "conversation_id", - "conversationId", + 'session_id', + 'sessionId', + 'thread_id', + 'threadId', + 'conversation_id', + 'conversationId', ]; const CODEX_PID_ENV_KEYS = [ - "CODEX_PID", - "CODEX_PROCESS_PID", - "OPENAI_CODEX_PID", - "OPENAI_CODEX_PROCESS_PID", - "AI_DEVKIT_CODEX_PID", + 'CODEX_PID', + 'CODEX_PROCESS_PID', + 'OPENAI_CODEX_PID', + 'OPENAI_CODEX_PROCESS_PID', + 'AI_DEVKIT_CODEX_PID', ]; const CODEX_PID_INPUT_KEYS = [ - "codex_pid", - "codexPid", - "codex_process_pid", - "codexProcessPid", - "pid", + 'codex_pid', + 'codexPid', + 'codex_process_pid', + 'codexProcessPid', + 'pid', ]; function readHookInput() { if (process.stdin.isTTY) return {}; try { - const raw = fs.readFileSync(0, "utf8").trim(); + const raw = fs.readFileSync(0, 'utf8').trim(); return raw ? JSON.parse(raw) : {}; } catch { return {}; @@ -63,14 +63,14 @@ function readHookInput() { } function normalizeValue(value) { - if (typeof value === "string" && value.trim()) return value.trim(); - if (typeof value === "number" && Number.isSafeInteger(value) && value > 0) return String(value); + if (typeof value === 'string' && value.trim()) return value.trim(); + if (typeof value === 'number' && Number.isSafeInteger(value) && value > 0) return String(value); return undefined; } function inputSources(input) { return [input, input?.payload, input?.session, input?.thread].filter( - (source) => source && typeof source === "object", + (source) => source && typeof source === 'object', ); } @@ -96,25 +96,126 @@ function firstValue(keys, getValue) { return undefined; } -function readRegistry(registryFile) { - let existing; +const STALE_LOCK_MS = 30_000; +const LOCK_RETRY_MS = 50; +const LOCK_WAIT_MS = Number(process.env.AI_DEVKIT_SESSION_REGISTRY_LOCK_WAIT_MS) || 10_000; +function registryWarn(message) { + console.warn(message); +} + +function sleepMs(ms) { + const end = Date.now() + ms; + while (Date.now() < end) { + /* spin */ + } +} + +function tryAcquireLock(lockPath, staleMs) { try { - existing = JSON.parse(fs.readFileSync(registryFile, "utf8")); + fs.closeSync(fs.openSync(lockPath, 'wx', 0o600)); + return true; } catch { - return {}; + try { + const age = Date.now() - fs.statSync(lockPath).mtimeMs; + if (age > staleMs) { + fs.unlinkSync(lockPath); + fs.closeSync(fs.openSync(lockPath, 'wx', 0o600)); + return true; + } + } catch { + /* races with the holder are fine — losing means we wait */ + } + return false; } +} - return existing && typeof existing === "object" && !Array.isArray(existing) ? existing : {}; +function releaseLock(lockPath) { + try { + fs.unlinkSync(lockPath); + } catch { + /* already gone */ + } +} + +function withRegistryLock(registryFile, fn) { + fs.mkdirSync(path.dirname(registryFile), { recursive: true }); + const lockPath = `${registryFile}.lock`; + const deadline = Date.now() + LOCK_WAIT_MS; + while (Date.now() < deadline) { + if (tryAcquireLock(lockPath, STALE_LOCK_MS)) { + try { + fn(); + return true; + } finally { + releaseLock(lockPath); + } + } + sleepMs(LOCK_RETRY_MS); + } + registryWarn( + `ai-devkit: timed out acquiring lock for ${registryFile}; skipping this registry update`, + ); + return false; +} + +function readRegistryForUpdate(registryFile) { + let raw; + + try { + raw = fs.readFileSync(registryFile, 'utf8'); + } catch (e) { + if (e && e.code === 'ENOENT') return {}; + throw e; + } + + try { + const existing = JSON.parse(raw); + if (existing && typeof existing === 'object' && !Array.isArray(existing)) return existing; + throw new Error('sessions.json is not a JSON object'); + } catch (e) { + if (e.message === 'sessions.json is not a JSON object') throw e; + throw new Error('sessions.json is not valid JSON'); + } +} + +function loadRegistryForUpdate(registryFile) { + try { + return readRegistryForUpdate(registryFile); + } catch (e) { + if ( + e.message !== 'sessions.json is not valid JSON' && + e.message !== 'sessions.json is not a JSON object' + ) { + throw e; + } + if (!fs.existsSync(registryFile)) return {}; + const corruptPath = `${registryFile}.corrupt-${Date.now()}`; + fs.renameSync(registryFile, corruptPath); + registryWarn( + `ai-devkit: sessions registry at ${registryFile} was unreadable; renamed to ${corruptPath} and starting fresh`, + ); + return {}; + } } function writeRegistry(registryFile, registry) { fs.mkdirSync(path.dirname(registryFile), { recursive: true }); - fs.writeFileSync(registryFile, JSON.stringify(registry, null, 2), "utf8"); + const tmp = `${registryFile}.${process.pid}.${Date.now()}.tmp`; + fs.writeFileSync(tmp, JSON.stringify(registry, null, 2), 'utf8'); + fs.renameSync(tmp, registryFile); +} + +function updateRegistry(registryFile, mutator) { + return withRegistryLock(registryFile, () => { + const registry = loadRegistryForUpdate(registryFile); + mutator(registry); + writeRegistry(registryFile, registry); + }); } function findSessionFileById(homeDir, sessionId) { - const codexSessionsDir = path.join(homeDir, ".codex", "sessions"); + const codexSessionsDir = path.join(homeDir, '.codex', 'sessions'); const pendingDirs = [codexSessionsDir]; while (pendingDirs.length > 0) { @@ -131,11 +232,7 @@ function findSessionFileById(homeDir, sessionId) { const entryPath = path.join(dir, entry.name); if (entry.isDirectory()) { pendingDirs.push(entryPath); - } else if ( - entry.isFile() && - entry.name.endsWith(".jsonl") && - entry.name.includes(sessionId) - ) { + } else if (entry.isFile() && entry.name.endsWith('.jsonl') && entry.name.includes(sessionId)) { return entryPath; } } @@ -145,8 +242,7 @@ function findSessionFileById(homeDir, sessionId) { } function resolveSessionFile(homeDir, input) { - const explicitPath = - envValue(SESSION_FILE_ENV_KEYS) || inputValue(input, SESSION_FILE_INPUT_KEYS); + const explicitPath = envValue(SESSION_FILE_ENV_KEYS) || inputValue(input, SESSION_FILE_INPUT_KEYS); if (explicitPath) return explicitPath; @@ -163,8 +259,10 @@ function resolveCodexPid(input) { const input = readHookInput(); const homeDir = os.homedir(); -const registryFile = path.join(homeDir, ".codex", "ai-devkit", "sessions.json"); -const registry = readRegistry(registryFile); +const registryFile = path.join(homeDir, '.codex', 'ai-devkit', 'sessions.json'); +const codexPid = resolveCodexPid(input); +const sessionFile = resolveSessionFile(homeDir, input) || 'ephemeral'; -registry[resolveCodexPid(input)] = resolveSessionFile(homeDir, input) || "ephemeral"; -writeRegistry(registryFile, registry); +updateRegistry(registryFile, (registry) => { + registry[codexPid] = sessionFile; +}); diff --git a/packages/cli/tests/assets/codex/codex-session-mapping-registry.test.ts b/packages/cli/tests/assets/codex/codex-session-mapping-registry.test.ts new file mode 100644 index 000000000..dee472e93 --- /dev/null +++ b/packages/cli/tests/assets/codex/codex-session-mapping-registry.test.ts @@ -0,0 +1,94 @@ +import * as fs from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; +import { spawn } from "node:child_process"; +import { fileURLToPath } from "node:url"; + +const hookPath = fileURLToPath( + new URL("../../../assets/codex/codex-session-mapping.cjs", import.meta.url), +); + +function runHook( + home: string, + pid: string, + sessionFile: string, + extraEnv: Record = {}, +): Promise { + return new Promise((resolve, reject) => { + let stderr = ""; + const child = spawn(process.execPath, [hookPath], { + env: { + ...process.env, + HOME: home, + CODEX_PID: pid, + CODEX_SESSION_FILE: sessionFile, + ...extraEnv, + }, + stdio: ["pipe", "ignore", "pipe"], + }); + child.stderr?.on("data", (chunk) => { + stderr += chunk.toString(); + }); + child.stdin?.end("{}"); + child.on("error", reject); + child.on("exit", (code) => { + if (code === 0) resolve(); + else reject(new Error(`hook exited ${code}: ${stderr}`)); + }); + }); +} + +describe("codex-session-mapping registry", () => { + let home: string; + let registryPath: string; + + beforeEach(() => { + home = fs.mkdtempSync(path.join(os.tmpdir(), "codex-registry-")); + registryPath = path.join(home, ".codex", "ai-devkit", "sessions.json"); + }); + + afterEach(() => { + fs.rmSync(home, { recursive: true, force: true }); + }); + + it("merges concurrent hook runs without dropping pid entries", async () => { + await Promise.all([ + runHook(home, "4242", "/tmp/a.jsonl"), + runHook(home, "4343", "/tmp/b.jsonl"), + runHook(home, "4444", "/tmp/c.jsonl"), + ]); + + expect(JSON.parse(fs.readFileSync(registryPath, "utf8"))).toEqual({ + "4242": "/tmp/a.jsonl", + "4343": "/tmp/b.jsonl", + "4444": "/tmp/c.jsonl", + }); + }); + + it("quarantines a corrupt registry and records the pid on exit 0", async () => { + fs.mkdirSync(path.dirname(registryPath), { recursive: true }); + fs.writeFileSync(registryPath, "{not json"); + + await runHook(home, "5151", "/tmp/live.jsonl"); + + expect(JSON.parse(fs.readFileSync(registryPath, "utf8"))).toEqual({ + "5151": "/tmp/live.jsonl", + }); + expect( + fs + .readdirSync(path.dirname(registryPath)) + .some((name) => name.startsWith("sessions.json.corrupt-")), + ).toBe(true); + }); + + it("exits 0 when the lock wait times out without writing", async () => { + fs.mkdirSync(path.dirname(registryPath), { recursive: true }); + fs.closeSync(fs.openSync(`${registryPath}.lock`, "wx", 0o600)); + + await runHook(home, "5252", "/tmp/skipped.jsonl", { + AI_DEVKIT_SESSION_REGISTRY_LOCK_WAIT_MS: "100", + }); + + expect(fs.existsSync(registryPath)).toBe(false); + }); +}); diff --git a/packages/pi-session-tracker/extensions/index.ts b/packages/pi-session-tracker/extensions/index.ts index d90c8f9eb..52822621f 100644 --- a/packages/pi-session-tracker/extensions/index.ts +++ b/packages/pi-session-tracker/extensions/index.ts @@ -1,51 +1,24 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; -import * as fs from "node:fs"; -import * as path from "node:path"; import * as os from "node:os"; +import * as path from "node:path"; +import { updateRegistry } from "./session-registry.js"; -type SessionRegistry = Record; - -// pid → session file map that ai-devkit (CLI adapters and devkitd's sweep) -// reads to resolve which session a running pi process is on. Plain -// read-modify-write, the same model as the codex session-mapping hook: there -// is no daemon RPC path, so an entry can never be silently dropped by a -// daemon that does not implement it. function registryFile(): string { return path.join(os.homedir(), ".pi", "agent", "sessions.json"); } -function readRegistry(file: string): SessionRegistry { - try { - const parsed: unknown = JSON.parse(fs.readFileSync(file, "utf8")); - return parsed && typeof parsed === "object" && !Array.isArray(parsed) - ? (parsed as SessionRegistry) - : {}; - } catch { - return {}; - } -} - -// Write to a sibling temp file and rename so concurrent readers never see a -// truncated JSON document. -function writeRegistry(file: string, data: SessionRegistry): void { - fs.mkdirSync(path.dirname(file), { recursive: true }); - const tmp = `${file}.${process.pid}.tmp`; - fs.writeFileSync(tmp, JSON.stringify(data, null, 2), "utf8"); - fs.renameSync(tmp, file); -} - export default function (pi: ExtensionAPI) { pi.on("session_start", async (_event, ctx) => { const file = registryFile(); - const registry = readRegistry(file); - registry[String(process.pid)] = ctx.sessionManager.getSessionFile() ?? "ephemeral"; - writeRegistry(file, registry); + updateRegistry(file, (registry) => { + registry[String(process.pid)] = ctx.sessionManager.getSessionFile() ?? "ephemeral"; + }); }); pi.on("session_shutdown", async (_event, _ctx) => { const file = registryFile(); - const registry = readRegistry(file); - delete registry[String(process.pid)]; - writeRegistry(file, registry); + updateRegistry(file, (registry) => { + delete registry[String(process.pid)]; + }); }); } diff --git a/packages/pi-session-tracker/extensions/session-registry.ts b/packages/pi-session-tracker/extensions/session-registry.ts new file mode 100644 index 000000000..c8f61488e --- /dev/null +++ b/packages/pi-session-tracker/extensions/session-registry.ts @@ -0,0 +1,131 @@ +import * as fs from "node:fs"; +import * as path from "node:path"; + +export type SessionRegistry = Record; + +const STALE_LOCK_MS = 30_000; +const LOCK_RETRY_MS = 50; +const LOCK_WAIT_MS = Number(process.env.AI_DEVKIT_SESSION_REGISTRY_LOCK_WAIT_MS) || 10_000; + +export class RegistryUnreadableError extends Error { + constructor(message: string) { + super(message); + this.name = "RegistryUnreadableError"; + } +} + +function warn(message: string): void { + console.warn(message); +} + +function sleepMs(ms: number): void { + const end = Date.now() + ms; + while (Date.now() < end) { + /* spin */ + } +} + +function tryAcquireLock(lockPath: string, staleMs: number): boolean { + try { + fs.closeSync(fs.openSync(lockPath, "wx", 0o600)); + return true; + } catch { + try { + const age = Date.now() - fs.statSync(lockPath).mtimeMs; + if (age > staleMs) { + fs.unlinkSync(lockPath); + fs.closeSync(fs.openSync(lockPath, "wx", 0o600)); + return true; + } + } catch { + /* races with the holder are fine — losing means we wait */ + } + return false; + } +} + +function releaseLock(lockPath: string): void { + try { + fs.unlinkSync(lockPath); + } catch { + /* already gone */ + } +} + +/** Returns whether the lock was acquired and `fn` ran. On timeout, logs and returns false. */ +export function withRegistryLock(registryFile: string, fn: () => void): boolean { + fs.mkdirSync(path.dirname(registryFile), { recursive: true }); + const lockPath = `${registryFile}.lock`; + const deadline = Date.now() + LOCK_WAIT_MS; + while (Date.now() < deadline) { + if (tryAcquireLock(lockPath, STALE_LOCK_MS)) { + try { + fn(); + return true; + } finally { + releaseLock(lockPath); + } + } + sleepMs(LOCK_RETRY_MS); + } + warn(`ai-devkit: timed out acquiring lock for ${registryFile}; skipping this registry update`); + return false; +} + +/** Read the registry for an update. Missing file → empty object; corrupt file → error. */ +export function readRegistryForUpdate(file: string): SessionRegistry { + let raw: string; + try { + raw = fs.readFileSync(file, "utf8"); + } catch (e) { + if ((e as NodeJS.ErrnoException).code === "ENOENT") return {}; + throw e; + } + + try { + const parsed: unknown = JSON.parse(raw); + if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) { + return parsed as SessionRegistry; + } + throw new RegistryUnreadableError("sessions.json is not a JSON object"); + } catch (e) { + if (e instanceof RegistryUnreadableError) throw e; + throw new RegistryUnreadableError("sessions.json is not valid JSON"); + } +} + +function loadRegistryForUpdate(file: string): SessionRegistry { + try { + return readRegistryForUpdate(file); + } catch (e) { + if (!(e instanceof RegistryUnreadableError) || !fs.existsSync(file)) throw e; + const corruptPath = `${file}.corrupt-${Date.now()}`; + fs.renameSync(file, corruptPath); + warn( + `ai-devkit: sessions registry at ${file} was unreadable; renamed to ${corruptPath} and starting fresh`, + ); + return {}; + } +} + +export function writeRegistry(file: string, data: SessionRegistry): void { + fs.mkdirSync(path.dirname(file), { recursive: true }); + const tmp = `${file}.${process.pid}.${Date.now()}.tmp`; + fs.writeFileSync(tmp, JSON.stringify(data, null, 2), "utf8"); + fs.renameSync(tmp, file); +} + +/** + * Locked read-modify-write. Returns false when the lock could not be acquired in time. + * Never throws for registry parse or lock errors. + */ +export function updateRegistry( + file: string, + mutator: (registry: SessionRegistry) => void, +): boolean { + return withRegistryLock(file, () => { + const registry = loadRegistryForUpdate(file); + mutator(registry); + writeRegistry(file, registry); + }); +} diff --git a/packages/pi-session-tracker/tests/extension.test.ts b/packages/pi-session-tracker/tests/extension.test.ts index 81bb91e0c..311503b0b 100644 --- a/packages/pi-session-tracker/tests/extension.test.ts +++ b/packages/pi-session-tracker/tests/extension.test.ts @@ -85,7 +85,7 @@ describe("pi-session-tracker extension", () => { }); }); - it("recovers from an invalid registry file", async () => { + it("quarantines an invalid registry file and records the new session", async () => { fs.mkdirSync(path.dirname(registryPath), { recursive: true }); fs.writeFileSync(registryPath, "{not json"); @@ -93,6 +93,10 @@ describe("pi-session-tracker extension", () => { await handlers.session_start({}, ctxFor("/sessions/a.jsonl")); expect(readRegistry()).toEqual({ [String(process.pid)]: "/sessions/a.jsonl" }); + const dir = path.dirname(registryPath); + expect(fs.readdirSync(dir).some((name) => name.startsWith("sessions.json.corrupt-"))).toBe( + true, + ); }); it("removes only its own entry on session_shutdown without socket calls", async () => { diff --git a/packages/pi-session-tracker/tests/fixtures/registry-lock-timeout.worker.ts b/packages/pi-session-tracker/tests/fixtures/registry-lock-timeout.worker.ts new file mode 100644 index 000000000..0eb039fcf --- /dev/null +++ b/packages/pi-session-tracker/tests/fixtures/registry-lock-timeout.worker.ts @@ -0,0 +1,9 @@ +import { parentPort, workerData } from "node:worker_threads"; + +process.env.AI_DEVKIT_SESSION_REGISTRY_LOCK_WAIT_MS = "100"; + +const { updateRegistry } = await import("../../extensions/session-registry.ts"); +const { file } = workerData as { file: string }; + +const ok = updateRegistry(file, () => {}); +parentPort?.postMessage(ok); diff --git a/packages/pi-session-tracker/tests/fixtures/registry-writer.worker.ts b/packages/pi-session-tracker/tests/fixtures/registry-writer.worker.ts new file mode 100644 index 000000000..0926c6a2d --- /dev/null +++ b/packages/pi-session-tracker/tests/fixtures/registry-writer.worker.ts @@ -0,0 +1,14 @@ +import { parentPort, workerData } from "node:worker_threads"; +import { updateRegistry } from "../../extensions/session-registry.ts"; + +const { file, pid, sessionPath } = workerData as { + file: string; + pid: string; + sessionPath: string; +}; + +updateRegistry(file, (registry) => { + registry[pid] = sessionPath; +}); + +parentPort?.postMessage("done"); diff --git a/packages/pi-session-tracker/tests/session-registry.test.ts b/packages/pi-session-tracker/tests/session-registry.test.ts new file mode 100644 index 000000000..bdbcfda17 --- /dev/null +++ b/packages/pi-session-tracker/tests/session-registry.test.ts @@ -0,0 +1,103 @@ +import * as fs from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; +import { Worker } from "node:worker_threads"; +import { + readRegistryForUpdate, + RegistryUnreadableError, + updateRegistry, +} from "../extensions/session-registry.js"; + +describe("session-registry", () => { + let tmpDir: string; + let registryPath: string; + let lockWaitMs: string | undefined; + + beforeEach(() => { + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "pi-registry-")); + registryPath = path.join(tmpDir, "sessions.json"); + lockWaitMs = process.env.AI_DEVKIT_SESSION_REGISTRY_LOCK_WAIT_MS; + }); + + afterEach(() => { + process.env.AI_DEVKIT_SESSION_REGISTRY_LOCK_WAIT_MS = lockWaitMs; + fs.rmSync(tmpDir, { recursive: true, force: true }); + }); + + it("quarantines a corrupt file under the lock and writes a fresh registry", () => { + fs.mkdirSync(path.dirname(registryPath), { recursive: true }); + fs.writeFileSync(registryPath, "{not json"); + + expect(() => readRegistryForUpdate(registryPath)).toThrow(RegistryUnreadableError); + expect( + updateRegistry(registryPath, (r) => { + r["42"] = "/sessions/a.jsonl"; + }), + ).toBe(true); + + expect(JSON.parse(fs.readFileSync(registryPath, "utf8"))).toEqual({ + "42": "/sessions/a.jsonl", + }); + const corruptBackup = fs + .readdirSync(path.dirname(registryPath)) + .find((name) => name.startsWith("sessions.json.corrupt-")); + expect(corruptBackup).toBeDefined(); + expect(fs.readFileSync(path.join(path.dirname(registryPath), corruptBackup!), "utf8")).toBe( + "{not json", + ); + }); + + it("skips the update after the lock wait times out", () => { + process.env.AI_DEVKIT_SESSION_REGISTRY_LOCK_WAIT_MS = "100"; + // Re-import would be needed to pick up env in module init; constants are read at load time. + // Use a fresh dynamic import in a child process instead — see lock-timeout.worker.ts. + const lockPath = `${registryPath}.lock`; + fs.mkdirSync(path.dirname(registryPath), { recursive: true }); + fs.closeSync(fs.openSync(lockPath, "wx", 0o600)); + + return new Promise((resolve, reject) => { + const worker = new Worker( + new URL("./fixtures/registry-lock-timeout.worker.ts", import.meta.url), + { + workerData: { file: registryPath }, + }, + ); + worker.once("message", (ok: boolean) => { + try { + expect(ok).toBe(false); + expect(fs.existsSync(registryPath)).toBe(false); + resolve(); + } catch (e) { + reject(e); + } + }); + worker.once("error", reject); + }); + }); + + it("keeps every pid when workers update the registry concurrently", async () => { + const writers = Array.from({ length: 8 }, (_, i) => { + const pid = String(10_000 + i); + return new Worker(new URL("./fixtures/registry-writer.worker.ts", import.meta.url), { + workerData: { file: registryPath, pid, sessionPath: `/sessions/${pid}.jsonl` }, + }); + }); + + await Promise.all( + writers.map( + (worker) => + new Promise((resolve, reject) => { + worker.once("message", () => resolve()); + worker.once("error", reject); + }), + ), + ); + await Promise.all(writers.map((worker) => worker.terminate())); + + const registry = JSON.parse(fs.readFileSync(registryPath, "utf8")) as Record; + for (let i = 0; i < 8; i++) { + const pid = String(10_000 + i); + expect(registry[pid]).toBe(`/sessions/${pid}.jsonl`); + } + }); +});