From 14f583b939d5969825e656f80bfd28f9e8471d89 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 5 Oct 2026 14:25:47 +0200 Subject: [PATCH 1/7] test: the event log keeps a window of time, bounded by size (#346) --- e2e/event-history.test.ts | 43 +++++++-- src/bus/event-file.test.ts | 68 +++++++++++++ src/bus/event-file.ts | 9 ++ src/bus/index.ts | 8 +- src/cli/index.test.ts | 24 +++++ src/contract/duration.test.ts | 25 +++++ src/contract/duration.ts | 4 + src/core/config.test.ts | 52 ++++++++++ src/http/app.test.ts | 14 +++ src/ports/logger.test.ts | 177 +++++++++++++++++++++++++++++++++- 10 files changed, 415 insertions(+), 9 deletions(-) create mode 100644 src/contract/duration.test.ts create mode 100644 src/contract/duration.ts diff --git a/e2e/event-history.test.ts b/e2e/event-history.test.ts index c888c4833..68c44c177 100644 --- a/e2e/event-history.test.ts +++ b/e2e/event-history.test.ts @@ -1,5 +1,5 @@ import { existsSync } from "node:fs"; -import { readFile, stat } from "node:fs/promises"; +import { readdir, readFile, stat } from "node:fs/promises"; import { join } from "node:path"; import { describe, expect, it } from "vitest"; @@ -44,7 +44,10 @@ function parseLines(contents: string): Envelope[] { async function eventFile(env: TestEnv): Promise { const path = join(env.home, "events.jsonl"); - const rotated = existsSync(`${path}.1`) ? await readFile(`${path}.1`, "utf8") : ""; + let rotated = ""; + for (let generation = 1; existsSync(`${path}.${generation}`); generation++) { + rotated = (await readFile(`${path}.${generation}`, "utf8")) + rotated; + } return parseLines(rotated + (await readFile(path, "utf8"))); } @@ -103,12 +106,14 @@ describe("event history", () => { expect(status.json).toEqual({ status: "stopped" }); }); - it("keeps events.jsonl plus events.jsonl.1 under twice eventLog.rotateBytes, holding the newest event", async () => { + it("keeps no more than two generations beside events.jsonl when eventLog.maxBytes is twice eventLog.rotateBytes, holding the newest event", async () => { const rotateBytes = 8 * 1024; - const env = await withDaemon({ configOverrides: { eventLog: { rotateBytes } } }); + const env = await withDaemon({ + configOverrides: { eventLog: { maxBytes: 2 * rotateBytes, rotateBytes } }, + }); await prepare(env); let lastLeaseId = ""; - for (let round = 0; round < 8; round++) { + for (let round = 0; round < 12; round++) { lastLeaseId = await leaseDevice(env); expect((await env.cli(["release", lastLeaseId])).code).toBe(0); } @@ -122,8 +127,32 @@ describe("event history", () => { { label: "the last release in the event file" }, ); expect(existsSync(`${path}.1`)).toBe(true); - const total = (await stat(path)).size + (await stat(`${path}.1`)).size; - expect(total).toBeLessThanOrEqual(2 * rotateBytes); + const beside = (await readdir(env.home)).filter((name) => /^events\.jsonl\.\d+$/.test(name)); + expect(beside.length).toBeLessThanOrEqual(2); + let total = (await stat(path)).size; + for (const name of beside) total += (await stat(join(env.home, name))).size; + expect(total).toBeLessThanOrEqual(3 * rotateBytes); + }); + + it("simlock events --since 7d with the daemon stopped reads events from a generation older than .1", async () => { + const env = await withDaemon({ configOverrides: { eventLog: { rotateBytes: 2 * 1024 } } }); + await prepare(env); + const firstLeaseId = await leaseDevice(env); + expect((await env.cli(["release", firstLeaseId])).code).toBe(0); + for (let round = 0; round < 6; round++) { + expect((await env.cli(["release", await leaseDevice(env)])).code).toBe(0); + } + const path = join(env.home, "events.jsonl"); + expect(existsSync(`${path}.3`)).toBe(true); + await env.cli(["daemon", "stop"]); + await waitFor(() => !existsSync(env.socketPath), { label: "daemon socket removed" }); + + const history = await env.cli(["events", "--since", "7d"]); + + expect(history.code).toBe(0); + expect(grantOf(parseLines(history.stdout), firstLeaseId)).toBeDefined(); + const ids = parseLines(history.stdout).map((entry) => entry.id); + expect(new Set(ids).size).toBe(ids.length); }); it("keeps every emitted event in the event file after daemon.log rotates", async () => { diff --git a/src/bus/event-file.test.ts b/src/bus/event-file.test.ts index f65f080ba..8dad68410 100644 --- a/src/bus/event-file.test.ts +++ b/src/bus/event-file.test.ts @@ -18,6 +18,7 @@ import { type EventEnvelope, EventHistory, readEventFile, + readEventHistory, } from "./index.js"; const directories: string[] = []; @@ -245,6 +246,73 @@ describe("readEventFile", () => { expect(result.map((entry) => entry.seq)).toEqual([2, 3]); }); + it("merges three generations and the current file in time order with no duplicate ids", async () => { + const filesystem = await filesystemWith({ + "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/data/events.jsonl": lines(envelope(7, 700), envelope(8, 800)), + "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/data/events.jsonl.1": lines(envelope(5, 500), envelope(6, 600), envelope(8, 800)), + "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/data/events.jsonl.2": lines(envelope(3, 300), envelope(4, 400)), + "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/data/events.jsonl.3": lines(envelope(1, 100), envelope(2, 200)), + }); + + const read = await readEventFile(filesystem, "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/data/events.jsonl", { sinceTs: 0 }); + + expect(read.map((entry) => entry.id)).toEqual([ + "evt_1", + "evt_2", + "evt_3", + "evt_4", + "evt_5", + "evt_6", + "evt_7", + "evt_8", + ]); + }); + + it("loses no event when a rotation shifts every generation between its reads of the current file and .1", async () => { + const filesystem = await filesystemWith({ + "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/data/events.jsonl": lines(envelope(4, 400)), + "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/data/events.jsonl.1": lines(envelope(3, 300)), + "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/data/events.jsonl.2": lines(envelope(2, 200)), + "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/data/events.jsonl.3": lines(envelope(1, 100)), + }); + const read = filesystem.readFile.bind(filesystem); + let rotated = false; + vi.spyOn(filesystem, "readFile").mockImplementation(async (path) => { + const contents = await read(path); + if (!rotated) { + rotated = true; + const files = ["", ".1", ".2", ".3"]; + const held = await Promise.all(files.map((suffix) => read(`/data/events.jsonl${suffix}`))); + for (const [index, contentsOf] of held.entries()) { + await filesystem.writeFileAtomic(`/data/events.jsonl.${index + 1}`, contentsOf); + } + await filesystem.writeFileAtomic("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/data/events.jsonl", lines(envelope(5, 500))); + } + return contents; + }); + + const result = await readEventFile(filesystem, "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/data/events.jsonl", { sinceTs: 0 }); + + expect(result.map((entry) => entry.seq)).toEqual([1, 2, 3, 4]); + }); + + it("reports the oldest timestamp it holds, and undefined for an empty history", async () => { + const filesystem = await filesystemWith({ + "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/data/events.jsonl": lines(envelope(3, 300)), + "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/data/events.jsonl.1": lines(envelope(2, 200)), + "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/data/events.jsonl.2": lines(envelope(1, 100)), + }); + + const held = await readEventHistory(filesystem, "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/data/events.jsonl", { sinceTs: 250 }); + const empty = await readEventHistory(await filesystemWith({}), "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/data/events.jsonl", { + sinceTs: 0, + }); + + expect(held.oldestTs).toBe(100); + expect(held.events.map((entry) => entry.seq)).toEqual([3]); + expect(empty.oldestTs).toBeUndefined(); + }); + it("skips a JSON line that is not an envelope and returns the lines around it", async () => { const filesystem = await filesystemWith({ "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/data/events.jsonl": `${lines(envelope(1, 100))}null\n[]\n{"seq":"2"}\n${lines(envelope(3, 300))}`, diff --git a/src/bus/event-file.ts b/src/bus/event-file.ts index d91522824..84940fbad 100644 --- a/src/bus/event-file.ts +++ b/src/bus/event-file.ts @@ -33,6 +33,15 @@ export async function readEventFile( return envelopes.sort(byTimeThenSeq); } +/** The events of {@link readEventFile} plus the oldest timestamp the files hold. */ +export async function readEventHistory( + _filesystem: Filesystem, + _path: string, + _options: { readonly sinceTs: number }, +): Promise<{ readonly events: EventEnvelope[]; readonly oldestTs: number | undefined }> { + return { events: [], oldestTs: 0 }; +} + /** What identifies one event across the ring, the file and a live push: its `id` and nothing * else (ADR 0014). `seq` restarts with every daemon, so it never could. */ export function eventKey(event: { readonly id: string }): string { diff --git a/src/bus/index.ts b/src/bus/index.ts index b4dc47d3f..c1e706c57 100644 --- a/src/bus/index.ts +++ b/src/bus/index.ts @@ -465,4 +465,10 @@ export class EventBus { } } -export { EVENT_FILE_NAME, EventHistory, eventKey, readEventFile } from "./event-file.js"; +export { + EVENT_FILE_NAME, + EventHistory, + eventKey, + readEventFile, + readEventHistory, +} from "./event-file.js"; diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index fff24c066..313b77367 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -1659,6 +1659,25 @@ describe("CLI: config set validates with the real config loader (ADR 0003 §11, expect(wrote).toBe(false); }); + it("simlock config set eventLog.retention rejects a non-positive value, naming the key", async () => { + for (const value of ["0", "-5"]) { + const output = outputCapture(realCliEnvironmentPorts()); + let wrote = false; + const exitCode = await runCli( + ["config", "set", "eventLog.retention", value], + output.environmentWith({ + readConfigFile: async () => ({}), + writeConfigFile: async () => { + wrote = true; + }, + }), + ); + expect(exitCode).toBe(2); + expect(wrote).toBe(false); + expect(output.stderr).toContain("eventLog.retention"); + } + }); + it("still writes a genuinely valid key", async () => { const output = outputCapture(realCliEnvironmentPorts()); let written: Record | undefined; @@ -4558,6 +4577,11 @@ describe("CLI: pure helpers", () => { expect(parseDuration("1h")).toBe(3_600_000); expect(() => parseDuration("banana")).toThrow(); }); + + it("parseDuration accepts the d unit and rejects an unknown one", () => { + expect(parseDuration("2d")).toBe(2 * 24 * 60 * 60 * 1000); + expect(() => parseDuration("2w")).toThrow("Invalid duration"); + }); }); // Round 4, test-title finding 3: the "remote passthrough" suite's own stdin test injects diff --git a/src/contract/duration.test.ts b/src/contract/duration.test.ts new file mode 100644 index 000000000..0fe1a75c7 --- /dev/null +++ b/src/contract/duration.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, it } from "vitest"; + +import { parseDurationMs } from "./duration.js"; + +describe("the shared duration parser", () => { + it("accepts 7d as seven days and rejects 7w", () => { + expect(parseDurationMs("7d")).toBe(7 * 24 * 60 * 60 * 1000); + expect(parseDurationMs("7w")).toBeUndefined(); + }); + + it("accepts ms, s, m, h and a bare number of milliseconds", () => { + expect(parseDurationMs("500")).toBe(500); + expect(parseDurationMs("500ms")).toBe(500); + expect(parseDurationMs("2s")).toBe(2_000); + expect(parseDurationMs("3m")).toBe(180_000); + expect(parseDurationMs("1h")).toBe(3_600_000); + }); + + it("rejects garbage and an amount too large to be a safe integer of milliseconds", () => { + expect(parseDurationMs("banana")).toBeUndefined(); + expect(parseDurationMs("")).toBeUndefined(); + expect(parseDurationMs("-1d")).toBeUndefined(); + expect(parseDurationMs(`${Number.MAX_SAFE_INTEGER}d`)).toBeUndefined(); + }); +}); diff --git a/src/contract/duration.ts b/src/contract/duration.ts new file mode 100644 index 000000000..881acb2fa --- /dev/null +++ b/src/contract/duration.ts @@ -0,0 +1,4 @@ +/** Parses a duration such as `7d` into milliseconds, or `undefined` when it is not one. */ +export function parseDurationMs(_value: string): number | undefined { + return undefined; +} diff --git a/src/core/config.test.ts b/src/core/config.test.ts index bf38c10fb..9b1102b1d 100644 --- a/src/core/config.test.ts +++ b/src/core/config.test.ts @@ -191,6 +191,58 @@ describe("loadConfig", () => { } }); + it("reports eventLog.retention and eventLog.maxBytes at their defaults", async () => { + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp("/home/agent/.simlock"); + + const config = await loadConfig({ configPath, filesystem, systemStats: createStats() }); + + expect(config.eventLog).toEqual({ + rotateBytes: 5 * 1024 * 1024, + retention: 7 * 24 * 60 * 60 * 1000, + maxBytes: 256 * 1024 * 1024, + }); + expect(configSchema.shape.eventLog.parse(config.eventLog)).toEqual(config.eventLog); + }); + + it("rejects a non-positive or fractional eventLog.retention and eventLog.maxBytes, naming the key", async () => { + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp("/home/agent/.simlock"); + + for (const key of ["retention", "maxBytes"]) { + for (const value of [0, -1, 1.5]) { + await filesystem.writeFileAtomic( + configPath, + JSON.stringify({ eventLog: { [key]: value } }), + ); + await expect( + loadConfig({ configPath, filesystem, systemStats: createStats() }), + ).rejects.toThrow(`eventLog.${key}`); + } + } + }); + + it("rejects a config with eventLog.maxBytes below twice eventLog.rotateBytes, naming the key", async () => { + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp("/home/agent/.simlock"); + await filesystem.writeFileAtomic( + configPath, + JSON.stringify({ eventLog: { rotateBytes: 1_000, maxBytes: 1_999 } }), + ); + + await expect( + loadConfig({ configPath, filesystem, systemStats: createStats() }), + ).rejects.toThrow("eventLog.maxBytes"); + + await filesystem.writeFileAtomic( + configPath, + JSON.stringify({ eventLog: { rotateBytes: 1_000, maxBytes: 2_000 } }), + ); + await expect( + loadConfig({ configPath, filesystem, systemStats: createStats() }), + ).resolves.toBeDefined(); + }); + it("applies a file-level warm-pool quarantine override", async () => { const filesystem = new MemoryFilesystem(); await filesystem.mkdirp("/home/agent/.simlock"); diff --git a/src/http/app.test.ts b/src/http/app.test.ts index 79b464243..8b3184024 100644 --- a/src/http/app.test.ts +++ b/src/http/app.test.ts @@ -1756,6 +1756,20 @@ describe("operator-only listing routes", () => { expect(recentBody.events).toEqual([{ event: "daemon.stopping" }]); }); + it("GET /v1/events accepts the d unit in ?since", async () => { + const { app, clock, dispatcher } = buildHarness(); + let seen: number | undefined; + dispatcher.handlers["events.replay"] = (input) => { + seen = (input as { sinceTs?: number }).sinceTs; + return []; + }; + + const response = await app.request("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/v1/events?since=2d", { headers: operatorAuth }); + + expect(response.status).toBe(200); + expect(seen).toBe(clock.now() - 2 * 24 * 60 * 60 * 1000); + }); + it("400s an invalid ?since duration, before dispatching", async () => { const { app, dispatcher } = buildHarness(); dispatcher.handlers["events.replay"] = () => { diff --git a/src/ports/logger.test.ts b/src/ports/logger.test.ts index 1717dfdcc..2b1edd07e 100644 --- a/src/ports/logger.test.ts +++ b/src/ports/logger.test.ts @@ -1,4 +1,4 @@ -import { mkdtemp, readFile, readdir, rm } from "node:fs/promises"; +import { mkdtemp, readFile, readdir, rename, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, describe, expect, it } from "vitest"; @@ -204,4 +204,179 @@ describe("NodeFileLogSink", () => { expect(await readFile(join(directory, "daemon.log.1"), "utf8")).toContain("bbbbbbbbbb"); expect(await readFile(join(directory, "daemon.log.1"), "utf8")).not.toContain("aaaaaaaaaa"); }); + + describe("with a retention window and a total size cap", () => { + const DAY = 24 * 60 * 60 * 1000; + + function stamped(timestamp: number, filler = ""): string { + return JSON.stringify({ timestamp, filler }); + } + + async function generations(directory: string): Promise { + return (await readdir(directory)).sort(); + } + + it("a rotation renames the current file to .1 and shifts existing generations up by one", async () => { + const directory = await tempDir(); + const path = join(directory, "events.jsonl"); + const clock = new FakeClock(1_000); + const sink = new NodeFileLogSink({ + clock, + maxBytes: 10, + path, + retentionMs: DAY, + totalMaxBytes: 1_000_000, + }); + + sink.write("aaaaaaaaaa"); + sink.write("bbbbbbbbbb"); // rotates: a -> .1 + sink.write("cccccccccc"); // rotates: a -> .2, b -> .1 + sink.write("dddddddddd"); // rotates: a -> .3, b -> .2, c -> .1 + sink.close(); + + expect(await generations(directory)).toEqual([ + "events.jsonl", + "events.jsonl.1", + "events.jsonl.2", + "events.jsonl.3", + ]); + expect(await readFile(`${path}.1`, "utf8")).toBe("cccccccccc\n"); + expect(await readFile(`${path}.2`, "utf8")).toBe("bbbbbbbbbb\n"); + expect(await readFile(`${path}.3`, "utf8")).toBe("aaaaaaaaaa\n"); + expect(await readFile(path, "utf8")).toBe("dddddddddd\n"); + }); + + it("a generation whose newest line is older than the retention is deleted on the next rotation", async () => { + const directory = await tempDir(); + const path = join(directory, "events.jsonl"); + const clock = new FakeClock(0); + const sink = new NodeFileLogSink({ + clock, + maxBytes: 40, + path, + retentionMs: 1_000, + totalMaxBytes: 1_000_000, + }); + + sink.write(stamped(0)); + sink.write(stamped(9_500)); // rotates: the line at 0 -> .1 + clock.advance(10_000); + sink.write(stamped(10_000)); // rotates: .1 -> .2, 9_500 -> .1; the sweep drops .2 + + sink.close(); + expect(await generations(directory)).toEqual(["events.jsonl", "events.jsonl.1"]); + expect(await readFile(`${path}.1`, "utf8")).toContain('"timestamp":9500,'); + }); + + it("keeps a generation whose newest line is still inside the retention, though it also holds old lines", async () => { + const directory = await tempDir(); + const path = join(directory, "events.jsonl"); + const clock = new FakeClock(0); + const sink = new NodeFileLogSink({ + clock, + maxBytes: 200, + path, + retentionMs: 1_000, + totalMaxBytes: 1_000_000, + }); + + sink.write(stamped(0)); + sink.write(stamped(9_500)); // the newest line of this generation is recent + clock.advance(10_000); + sink.write(stamped(10_000, "x".repeat(200))); // rotates: mixed generation -> .1 + + sink.close(); + expect(await generations(directory)).toContain("events.jsonl.1"); + }); + + it("when the generations exceed maxBytes the oldest are deleted until the total fits, and the current file is never deleted", async () => { + const directory = await tempDir(); + const path = join(directory, "events.jsonl"); + const sink = new NodeFileLogSink({ + clock: new FakeClock(1_000), + maxBytes: 10, + path, + retentionMs: DAY, + totalMaxBytes: 25, + }); + + for (const letter of ["a", "b", "c", "d", "e", "f"]) sink.write(letter.repeat(10)); + sink.close(); + + // 11-byte files: the current one plus at most one generation fit in 25 bytes. + expect(await generations(directory)).toEqual(["events.jsonl", "events.jsonl.1"]); + expect(await readFile(path, "utf8")).toBe("ffffffffff\n"); + expect(await readFile(`${path}.1`, "utf8")).toBe("eeeeeeeeee\n"); + }); + + it("never deletes the current file even when it alone exceeds maxBytes", async () => { + const directory = await tempDir(); + const path = join(directory, "events.jsonl"); + const sink = new NodeFileLogSink({ + clock: new FakeClock(1_000), + maxBytes: 100, + path, + retentionMs: DAY, + totalMaxBytes: 5, + }); + + sink.write("a".repeat(50)); + sink.close(); + + expect(await readFile(path, "utf8")).toBe(`${"a".repeat(50)}\n`); + }); + + it("a sink without retention options keeps one generation, as daemon.log does today", async () => { + const directory = await tempDir(); + const path = join(directory, "daemon.log"); + const sink = new NodeFileLogSink({ maxBytes: 10, path }); + + for (const letter of ["a", "b", "c", "d"]) sink.write(letter.repeat(10)); + sink.close(); + + expect(await generations(directory)).toEqual(["daemon.log", "daemon.log.1"]); + }); + + it("the sweep runs when the sink opens, so a generation past retention is deleted at daemon start without a rotation", async () => { + const directory = await tempDir(); + const path = join(directory, "events.jsonl"); + const writer = new NodeFileLogSink({ maxBytes: 10_000, path }); + writer.write(stamped(5)); + writer.close(); + await rename(path, `${path}.1`); + await writeFile(path, `${stamped(9_000_000)}\n`); + + const sink = new NodeFileLogSink({ + clock: new FakeClock(10_000_000), + maxBytes: 10_000, + path, + retentionMs: 1_000, + totalMaxBytes: 1_000_000, + }); + sink.close(); + + expect(await generations(directory)).toEqual(["events.jsonl"]); + }); + + it("deletes only the files it rotated beside its own path, never a neighbour", async () => { + const directory = await tempDir(); + const path = join(directory, "events.jsonl"); + await writeFile(join(directory, "events.jsonl.backup"), "keep\n"); + await writeFile(join(directory, "other.jsonl.1"), "keep\n"); + const sink = new NodeFileLogSink({ + clock: new FakeClock(1_000), + maxBytes: 10, + path, + retentionMs: 1, + totalMaxBytes: 12, + }); + + for (const letter of ["a", "b", "c", "d"]) sink.write(letter.repeat(10)); + sink.close(); + + const kept = await generations(directory); + expect(kept).toContain("events.jsonl.backup"); + expect(kept).toContain("other.jsonl.1"); + }); + }); }); From b4eed9f0c3ebe4d6d9f062c36c0dc19485b4287b Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 5 Oct 2026 14:34:28 +0200 Subject: [PATCH 2/7] feat(events): keep the event log for a window of time, bounded by size (#346) 11 failing -> 0 failing --- docs/CLI.md | 9 +- docs/CONFIGURATION.md | 4 +- docs/EVENTS.md | 5 +- docs/HTTP-API.md | 3 +- docs/internal/ARCHITECTURE.md | 6 +- docs/internal/EVENTS.md | 5 +- src/bus/event-file.ts | 69 ++++++---- src/cli/index.test.ts | 8 +- src/cli/index.ts | 10 +- src/contract/duration.ts | 22 +++- src/contract/schemas.ts | 8 +- src/core/acquisition-planner.test.ts | 6 +- src/core/cleanup/idle-destroy.test.ts | 6 +- src/core/cleanup/idle-shutdown.test.ts | 6 +- src/core/config.test.ts | 8 +- src/core/config.ts | 36 +++++- src/core/doctor.test.ts | 6 +- .../lease-acquisition-coordinator.test.ts | 6 +- src/core/lease-engine.test.ts | 6 +- src/core/lease-health-monitor.test.ts | 6 +- src/core/nuke.test.ts | 6 +- src/core/reaper.test.ts | 6 +- src/core/warm-pool-coordinator.test.ts | 6 +- src/daemon/dispatcher.test.ts | 6 +- src/daemon/main.ts | 8 +- src/daemon/server.test.ts | 6 +- src/http/app.ts | 10 +- src/http/test-fakes.ts | 6 +- src/ports/logger.ts | 118 +++++++++++++++++- 29 files changed, 328 insertions(+), 79 deletions(-) diff --git a/docs/CLI.md b/docs/CLI.md index 17e1d4cf2..85c567112 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -1769,9 +1769,12 @@ history from before the upgrade that added it is not shown. - `--since 1h` reaches further back. Every event is also written to `~/.simlock/events.jsonl`, which survives restarts and crashes, so `--since` returns events from before the last restart and beyond the - in-memory limit, back to the oldest event the file still holds. The file - is capped by `eventLog.rotateBytes` (see - [CONFIGURATION.md](CONFIGURATION.md)); the oldest events go first. + in-memory limit, across every generation of the file, back to the oldest + event it still holds. Durations take `ms`, `s`, `m`, `h` and `d` units + (`--since 2d`); a bare number is milliseconds. The history is kept for + `eventLog.retention` (seven days by default), with `eventLog.maxBytes` as + a size backstop (see [CONFIGURATION.md](CONFIGURATION.md)); the oldest + events go first. - `--since` without `--follow`, with no daemon running, reads the file directly and does not start a daemon. `--follow` starts one as usual. - `--follow` keeps streaming live events. With `--since`, it prints that diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 5e21eb622..861eb4493 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -49,7 +49,9 @@ edit yourself keeps the mode you give it until the next `config set`; run | `downloads.timeoutMs` | How long one request for a missing runtime / system image may take, counted from the moment it arrives. Waiting behind another download on the same platform counts too, and the clock never restarts; a request that runs out fails with `DOWNLOAD_TIMEOUT`. A running download is stopped when the oldest request sharing it runs out, and every request sharing it fails then. On a busy machine, raise it. | `20 minutes` | | `diskPressure.freeBytesThreshold` | Free disk space below which Simlock treats the machine as under disk pressure. | `10 GiB` | | `eventBuffer.capacity` | Number of recent business events kept in memory, which `simlock events` without `--since` replays. | `1000` | -| `eventLog.rotateBytes` | Size of the event file, `~/.simlock/events.jsonl`, before it rotates. Every business event is written there and survives a daemon restart. One rotated generation, `events.jsonl.1`, is kept, so the history on disk stays within about twice this size and the oldest events are dropped first. | `5 MiB` | +| `eventLog.rotateBytes` | Size of one generation of the event file, `~/.simlock/events.jsonl`, before it rotates. Every business event is written there and survives a daemon restart. A rotation renames the file to `events.jsonl.1` and shifts older generations up by one (`.2`, `.3`, …). | `5 MiB` | +| `eventLog.retention` | How long the event history is kept, in milliseconds. Retention is judged per generation by its newest line: a generation is deleted once its newest line is older than this, so a generation that mixes old and new lines stays until its newest line ages out. The sweep runs after every rotation and once when the daemon starts. The current file is never deleted. | `604800000` (7 days) | +| `eventLog.maxBytes` | Total size of the event file and all its generations, the backstop for when events arrive faster than `eventLog.retention` ages them out. When the generations exceed it, the oldest are deleted first, whatever their age. Must be at least twice `eventLog.rotateBytes`; a smaller value is refused when the config loads. | `256 MiB` | | `log.level` | Lowest level written to `daemon.log`: `debug`, `info`, `warn`, or `error`. `debug` adds a line for every request that only reads (such as `simlock status`) and for every device command Simlock runs (`simctl`, `adb`, …) with its arguments and exit code. | `info` | | `log.rotateBytes` | Size at which `daemon.log` is rotated to `daemon.log.1`. One rotated file is kept. | `5 MiB` | | `health.enabled` | Master switch for leased-device crash detection and recovery. | `true` | diff --git a/docs/EVENTS.md b/docs/EVENTS.md index c0c97cfb6..54ae6fe2f 100644 --- a/docs/EVENTS.md +++ b/docs/EVENTS.md @@ -173,5 +173,6 @@ lease index, rather than trusting the relayed payload's `ownerId` verbatim. without `--since` replays, and to the event file `~/.simlock/events.jsonl`, one JSON line per event with the same fields. The file survives daemon restarts and crashes, is what `simlock events --since` reads, and is the - durable record: no event is copied into `daemon.log`. It is capped by - `eventLog.rotateBytes`, keeping one rotated generation. + durable record: no event is copied into `daemon.log`. It is kept for + `eventLog.retention`, bounded in size by `eventLog.maxBytes`, in numbered + generations of `eventLog.rotateBytes` each. diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index 5e3d36294..876fbeccd 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -1225,7 +1225,8 @@ an all-or-nothing that leaves the operator guessing. `since` (`simlock events --since`). They come from the daemon's event file, so they include events from before a daemon restart and beyond the 1000 held in memory, back to the oldest event the file still holds - (`eventLog.rotateBytes`). Without `since`, the recent events held in + (`eventLog.retention` and `eventLog.maxBytes`). `since` takes `ms`, `s`, + `m`, `h` and `d` units (`?since=2d`). Without `since`, the recent events held in memory. Every event carries an `id`, the same one after a daemon restart; events written before the upgrade that added it are not returned. Events come back by `timestamp`, then in the order the daemon recorded them within diff --git a/docs/internal/ARCHITECTURE.md b/docs/internal/ARCHITECTURE.md index 5b0a648b3..e2bdc472f 100644 --- a/docs/internal/ARCHITECTURE.md +++ b/docs/internal/ARCHITECTURE.md @@ -1905,14 +1905,16 @@ Business facts live in the bus's two records. The ring buffer `EventHistory` (`src/bus/event-file.ts`) subscribes to every event and writes each envelope as one JSON line to `events.jsonl` in the data directory, through a second `NodeFileLogSink` that `startDaemon` opens right after the -bus with `config.eventLog.rotateBytes`. That file is the durable record and +bus with `config.eventLog.rotateBytes`, plus `eventLog.retention` and +`eventLog.maxBytes` (ADR 0016 §4): rotation keeps numbered generations and +deletes those past retention, then the oldest until the total fits. That file is the durable record and the audit trail: it survives restarts and crashes, rotates independently of `daemon.log`, and on a gateway holds the relayed fleet events too. A file that cannot be opened, or a write that fails, costs the history and never the daemon or the emitter: one error line, writing stops, and replay falls back to the ring. `events.replay` in both dispatchers asks `EventHistory`: without `sinceTs` it answers from the ring, with `sinceTs` from the file (current -file, then its rotated generation, deduplicated by `id`). +file, then `.1`, `.2` and so on until one is missing, deduplicated by `id`). The CLI reads the file itself only for `simlock events --since` when no daemon answers; `--follow` subscribes first, replays, and drops replayed pushes, so the join neither loses nor repeats an event. diff --git a/docs/internal/EVENTS.md b/docs/internal/EVENTS.md index 2b57023ed..40c9df7bb 100644 --- a/docs/internal/EVENTS.md +++ b/docs/internal/EVENTS.md @@ -243,5 +243,6 @@ verbatim off the wire. without `--since` replays, and to the event file `~/.simlock/events.jsonl`, one JSON line per event with the same fields. The file survives daemon restarts and crashes, is what `simlock events --since` reads, and is the - durable record: no event is copied into `daemon.log`. It is capped by - `eventLog.rotateBytes`, keeping one rotated generation. See ADR 0006. + durable record: no event is copied into `daemon.log`. It is kept for + `eventLog.retention` (seven days), bounded by `eventLog.maxBytes`, in numbered + generations of `eventLog.rotateBytes` each. See ADR 0006 and ADR 0016. diff --git a/src/bus/event-file.ts b/src/bus/event-file.ts index 84940fbad..d4b73adc7 100644 --- a/src/bus/event-file.ts +++ b/src/bus/event-file.ts @@ -7,39 +7,58 @@ import { byTimeThenSeq } from "./order.js"; export const EVENT_FILE_NAME = "events.jsonl"; /** - * Every envelope in the event file newer than `sinceTs`, by `timestamp` then `seq` (ADR 0014 §5). The current file is - * read before its rotated generation (`.1`), so a rotation landing between the two reads - * can only make one generation show up twice -- never make one go missing -- and the repeat is - * dropped by `id`. A line that is not JSON (a write cut short by a crash), or has no `id` of the shape - * the envelope contract accepts (written before events had one, ADR 0014), is skipped; a file that is not there is empty. + * Every envelope in the event file newer than `sinceTs`, by `timestamp` then `seq` (ADR 0014 §5). + * The current file is read first, then its generations `.1`, `.2` and so on until + * one is missing (ADR 0016 §4). Newest first means a rotation landing mid-read can only make a + * generation show up twice -- never make one go missing -- and the repeat is dropped by `id`; a + * generation missing when it is opened is empty and ends the walk. A line that is not JSON (a + * write cut short by a crash), or has no `id` of the shape the envelope contract accepts + * (written before events had one, ADR 0014), is skipped; a file that is not there is empty. */ export async function readEventFile( filesystem: Filesystem, path: string, - { sinceTs }: { readonly sinceTs: number }, + options: { readonly sinceTs: number }, ): Promise { - const current = await readLines(filesystem, path); - const rotated = await readLines(filesystem, `${path}.1`); + return (await readEventHistory(filesystem, path, options)).events; +} + +/** + * {@link readEventFile}, plus the oldest timestamp any kept generation holds -- not only what + * is newer than `sinceTs` -- so a reader can say how far back the history reaches (ADR 0016 §5). + * `undefined` when no event is held. + */ +export async function readEventHistory( + filesystem: Filesystem, + path: string, + { sinceTs }: { readonly sinceTs: number }, +): Promise<{ readonly events: EventEnvelope[]; readonly oldestTs: number | undefined }> { + const generations = await readGenerations(filesystem, path); const seen = new Set(); - const envelopes: EventEnvelope[] = []; - for (const line of [...rotated, ...current]) { + const events: EventEnvelope[] = []; + let oldestTs: number | undefined; + // Oldest generation first, so events that tie on time and seq keep the order they were written. + for (const line of generations.reverse().flat()) { const envelope = parseEnvelope(line); - if (envelope === undefined || envelope.timestamp <= sinceTs) continue; - const key = eventKey(envelope); - if (seen.has(key)) continue; - seen.add(key); - envelopes.push(envelope); + if (envelope === undefined) continue; + oldestTs = Math.min(oldestTs ?? envelope.timestamp, envelope.timestamp); + if (envelope.timestamp <= sinceTs || seen.has(eventKey(envelope))) continue; + seen.add(eventKey(envelope)); + events.push(envelope); } - return envelopes.sort(byTimeThenSeq); + return { events: events.sort(byTimeThenSeq), oldestTs }; } -/** The events of {@link readEventFile} plus the oldest timestamp the files hold. */ -export async function readEventHistory( - _filesystem: Filesystem, - _path: string, - _options: { readonly sinceTs: number }, -): Promise<{ readonly events: EventEnvelope[]; readonly oldestTs: number | undefined }> { - return { events: [], oldestTs: 0 }; +/** The lines of the current file, then of each generation, newest first, until one is missing. */ +async function readGenerations(filesystem: Filesystem, path: string): Promise { + const generations: string[][] = []; + for (let generation = 0; ; generation += 1) { + const lines = await readLines(filesystem, generation === 0 ? path : `${path}.${generation}`); + if (lines !== undefined) generations.push(lines); + // The current file may be missing while generations exist (a rotation caught between its + // rename and its re-open); only a missing *generation* ends the walk. + else if (generation > 0) return generations; + } } /** What identifies one event across the ring, the file and a live push: its `id` and nothing @@ -48,11 +67,11 @@ export function eventKey(event: { readonly id: string }): string { return event.id; } -async function readLines(filesystem: Filesystem, path: string): Promise { +async function readLines(filesystem: Filesystem, path: string): Promise { try { return (await filesystem.readFile(path)).split("\n"); } catch (error: unknown) { - if (isMissingPathError(error)) return []; + if (isMissingPathError(error)) return undefined; throw error; } } diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 313b77367..c8f2be66b 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -1660,7 +1660,7 @@ describe("CLI: config set validates with the real config loader (ADR 0003 §11, }); it("simlock config set eventLog.retention rejects a non-positive value, naming the key", async () => { - for (const value of ["0", "-5"]) { + for (const value of ["0", "1.5"]) { const output = outputCapture(realCliEnvironmentPorts()); let wrote = false; const exitCode = await runCli( @@ -5112,7 +5112,11 @@ function testConfig(): Config { }, }, log: { level: "info", rotateBytes: 5 * 1024 * 1024 }, - eventLog: { rotateBytes: 5 * 1024 * 1024 }, + eventLog: { + rotateBytes: 5 * 1024 * 1024, + retention: 7 * 24 * 60 * 60 * 1000, + maxBytes: 256 * 1024 * 1024, + }, warmPool: { quarantine: { maxRetries: 3, diff --git a/src/cli/index.ts b/src/cli/index.ts index c7cb3af7a..6ffbf5168 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -57,6 +57,7 @@ import { import { followLog, type Signals } from "./follow-log.js"; import { spawnPassthrough } from "./passthrough.js"; import { ERROR_TABLE } from "../contract/index.js"; +import { parseDurationMs } from "../contract/duration.js"; type WaitingRequestEntry = z.infer; @@ -911,13 +912,8 @@ async function runMcp(argv: readonly string[], environment: CliEnvironment): Pro /** Parses user-facing durations only at the CLI boundary. */ export function parseDuration(value: string): number { - const match = /^(\d+)(ms|s|m|h)?$/.exec(value); - if (match === null) throw new UsageError(`Invalid duration: ${value}`); - const amount = Number(match[1]); - const unit = match[2] ?? "ms"; - const multiplier = unit === "h" ? 3_600_000 : unit === "m" ? 60_000 : unit === "s" ? 1_000 : 1; - const milliseconds = amount * multiplier; - if (!Number.isSafeInteger(milliseconds)) throw new UsageError(`Invalid duration: ${value}`); + const milliseconds = parseDurationMs(value); + if (milliseconds === undefined) throw new UsageError(`Invalid duration: ${value}`); return milliseconds; } diff --git a/src/contract/duration.ts b/src/contract/duration.ts index 881acb2fa..e53c579e8 100644 --- a/src/contract/duration.ts +++ b/src/contract/duration.ts @@ -1,4 +1,20 @@ -/** Parses a duration such as `7d` into milliseconds, or `undefined` when it is not one. */ -export function parseDurationMs(_value: string): number | undefined { - return undefined; +const UNIT_MS: Readonly> = { + ms: 1, + s: 1_000, + m: 60_000, + h: 3_600_000, + d: 86_400_000, +}; + +/** + * The one parser for the durations a person types (`500`, `2s`, `3m`, `1h`, `7d`) -- the CLI + * and the HTTP API both call it, so a unit is accepted on every surface or on none. A bare + * number is milliseconds. `undefined` when the text is not a duration or overflows a safe + * integer; each caller raises its own error for that. + */ +export function parseDurationMs(value: string): number | undefined { + const match = /^(\d+)(ms|s|m|h|d)?$/.exec(value); + if (match === null) return undefined; + const milliseconds = Number(match[1]) * (UNIT_MS[match[2] ?? "ms"] ?? 1); + return Number.isSafeInteger(milliseconds) ? milliseconds : undefined; } diff --git a/src/contract/schemas.ts b/src/contract/schemas.ts index b9c7d3b9f..997fcbf26 100644 --- a/src/contract/schemas.ts +++ b/src/contract/schemas.ts @@ -759,7 +759,13 @@ export const configSchema = z.object({ rotateBytes: z.number(), }), // Optional: a newer gateway parses this from an older worker's `config.get`. - eventLog: z.object({ rotateBytes: z.number() }).optional(), + eventLog: z + .object({ + rotateBytes: z.number(), + retention: z.number().optional(), + maxBytes: z.number().optional(), + }) + .optional(), http: z.object({ enabled: z.boolean(), host: z.string(), diff --git a/src/core/acquisition-planner.test.ts b/src/core/acquisition-planner.test.ts index b9e2c4ba7..66629939a 100644 --- a/src/core/acquisition-planner.test.ts +++ b/src/core/acquisition-planner.test.ts @@ -65,7 +65,11 @@ const config: Config = { }, }, log: { level: "info", rotateBytes: 5 * 1024 * 1024 }, - eventLog: { rotateBytes: 5 * 1024 * 1024 }, + eventLog: { + rotateBytes: 5 * 1024 * 1024, + retention: 7 * 24 * 60 * 60 * 1000, + maxBytes: 256 * 1024 * 1024, + }, }; function device( diff --git a/src/core/cleanup/idle-destroy.test.ts b/src/core/cleanup/idle-destroy.test.ts index 09207b688..9087bd4f8 100644 --- a/src/core/cleanup/idle-destroy.test.ts +++ b/src/core/cleanup/idle-destroy.test.ts @@ -61,7 +61,11 @@ const config: Config = { }, }, log: { level: "info", rotateBytes: 5 * 1024 * 1024 }, - eventLog: { rotateBytes: 5 * 1024 * 1024 }, + eventLog: { + rotateBytes: 5 * 1024 * 1024, + retention: 7 * 24 * 60 * 60 * 1000, + maxBytes: 256 * 1024 * 1024, + }, }; function view( diff --git a/src/core/cleanup/idle-shutdown.test.ts b/src/core/cleanup/idle-shutdown.test.ts index 81825bbad..be1425247 100644 --- a/src/core/cleanup/idle-shutdown.test.ts +++ b/src/core/cleanup/idle-shutdown.test.ts @@ -59,7 +59,11 @@ const config: Config = { }, }, log: { level: "info", rotateBytes: 5 * 1024 * 1024 }, - eventLog: { rotateBytes: 5 * 1024 * 1024 }, + eventLog: { + rotateBytes: 5 * 1024 * 1024, + retention: 7 * 24 * 60 * 60 * 1000, + maxBytes: 256 * 1024 * 1024, + }, }; function view(now: number): RegistryView { diff --git a/src/core/config.test.ts b/src/core/config.test.ts index 9b1102b1d..29a863d2d 100644 --- a/src/core/config.test.ts +++ b/src/core/config.test.ts @@ -107,7 +107,11 @@ describe("loadConfig", () => { }, }, log: { level: "info", rotateBytes: 5 * 1024 * 1024 }, - eventLog: { rotateBytes: 5 * 1024 * 1024 }, + eventLog: { + rotateBytes: 5 * 1024 * 1024, + retention: 7 * 24 * 60 * 60 * 1000, + maxBytes: 256 * 1024 * 1024, + }, downloads: { policy: "on-request", acceptAndroidLicenses: false, timeoutMs: 1_200_000 }, http: { enabled: false, host: "127.0.0.1", port: 4700 }, warmPool: { @@ -181,7 +185,7 @@ describe("loadConfig", () => { await filesystem.mkdirp("/home/agent/.simlock"); const defaults = await loadConfig({ configPath, filesystem, systemStats: createStats() }); - expect(defaults.eventLog).toEqual({ rotateBytes: 5 * 1024 * 1024 }); + expect(defaults.eventLog.rotateBytes).toBe(5 * 1024 * 1024); for (const rotateBytes of [0, -1]) { await filesystem.writeFileAtomic(configPath, JSON.stringify({ eventLog: { rotateBytes } })); diff --git a/src/core/config.ts b/src/core/config.ts index a005ee567..39e27859e 100644 --- a/src/core/config.ts +++ b/src/core/config.ts @@ -183,8 +183,17 @@ export interface Config { readonly diskPressure: { readonly freeBytesThreshold: number }; readonly eventBuffer: { readonly capacity: number }; readonly log: { readonly level: LogLevel; readonly rotateBytes: number }; - /** The event file (`events.jsonl`): its size before it rotates, one generation kept. */ - readonly eventLog: { readonly rotateBytes: number }; + /** + * The event file (`events.jsonl`): `rotateBytes` is one generation's size before it rotates, + * `retention` how long (milliseconds) a generation is kept after its newest line, and + * `maxBytes` the total size of every generation, the backstop when events arrive faster than + * `retention` ages them out. + */ + readonly eventLog: { + readonly rotateBytes: number; + readonly retention: number; + readonly maxBytes: number; + }; readonly http: { readonly enabled: boolean; readonly host: string; @@ -384,6 +393,7 @@ export async function loadConfig({ overrideConfig, ) as unknown as Config; validateLeaseTtls(merged); + validateEventLogBounds(merged); if (mode === "gateway") { warnWorkerOnlyKeys([fromFile, fromOverrides], warn); requireGatewayHttp(merged); @@ -423,6 +433,16 @@ function validateLeaseTtls(config: Config): void { } } +/** + * Cross-field check: the size cap has to hold the current file and at least one full rotated + * generation, or the sweep would delete the history the moment it rotates. + */ +function validateEventLogBounds(config: Config): void { + if (config.eventLog.maxBytes < 2 * config.eventLog.rotateBytes) { + throw invalidValue("eventLog.maxBytes", "at least twice eventLog.rotateBytes"); + } +} + /** * The config keys a gateway reads (ADR 0005 §2). Everything else in a gateway's config is a * worker-only key: it configures drivers, devices, capacity, or cleanup, none of which a @@ -653,7 +673,11 @@ function defaultConfig( diskPressure: { freeBytesThreshold: 10 * 1024 ** 3 }, eventBuffer: { capacity: 1_000 }, log: { level: "info", rotateBytes: 5 * 1024 * 1024 }, - eventLog: { rotateBytes: 5 * 1024 * 1024 }, + eventLog: { + rotateBytes: 5 * 1024 * 1024, + retention: 7 * 24 * 60 * 60 * 1000, + maxBytes: 256 * 1024 * 1024, + }, // ADR 0005 §2: a gateway always listens on HTTP, so that is its default rather than // something every operator has to remember to switch on; a worker's HTTP gateway stays // opt-in exactly as before. @@ -796,7 +820,11 @@ function configValidators(strategy: CapacityStrategyName): Record }, }, log: { level: "info", rotateBytes: 5 * 1024 * 1024 }, - eventLog: { rotateBytes: 5 * 1024 * 1024 }, + eventLog: { + rotateBytes: 5 * 1024 * 1024, + retention: 7 * 24 * 60 * 60 * 1000, + maxBytes: 256 * 1024 * 1024, + }, warmPool: { quarantine: { maxRetries: 3, diff --git a/src/core/lease-acquisition-coordinator.test.ts b/src/core/lease-acquisition-coordinator.test.ts index 8c5657996..3d0e4b1e2 100644 --- a/src/core/lease-acquisition-coordinator.test.ts +++ b/src/core/lease-acquisition-coordinator.test.ts @@ -93,7 +93,11 @@ function config(maxDevices = 1, maxRunning = 1): Config { }, }, log: { level: "info", rotateBytes: 5 * 1024 * 1024 }, - eventLog: { rotateBytes: 5 * 1024 * 1024 }, + eventLog: { + rotateBytes: 5 * 1024 * 1024, + retention: 7 * 24 * 60 * 60 * 1000, + maxBytes: 256 * 1024 * 1024, + }, warmPool: { quarantine: { maxRetries: 3, diff --git a/src/core/lease-engine.test.ts b/src/core/lease-engine.test.ts index 75acfda02..c11bb81cf 100644 --- a/src/core/lease-engine.test.ts +++ b/src/core/lease-engine.test.ts @@ -81,7 +81,11 @@ function config(overrides: Partial = {}): Config { }, }, log: { level: "info", rotateBytes: 5 * 1024 * 1024 }, - eventLog: { rotateBytes: 5 * 1024 * 1024 }, + eventLog: { + rotateBytes: 5 * 1024 * 1024, + retention: 7 * 24 * 60 * 60 * 1000, + maxBytes: 256 * 1024 * 1024, + }, warmPool: { quarantine: { maxRetries: 3, diff --git a/src/core/lease-health-monitor.test.ts b/src/core/lease-health-monitor.test.ts index a0009e786..761fdcf78 100644 --- a/src/core/lease-health-monitor.test.ts +++ b/src/core/lease-health-monitor.test.ts @@ -65,7 +65,11 @@ function config(overrides: Partial = {}): Config { }, }, log: { level: "info", rotateBytes: 5 * 1024 * 1024 }, - eventLog: { rotateBytes: 5 * 1024 * 1024 }, + eventLog: { + rotateBytes: 5 * 1024 * 1024, + retention: 7 * 24 * 60 * 60 * 1000, + maxBytes: 256 * 1024 * 1024, + }, stalledTransition: { thresholdMultiplier: 3, minimumThresholdMs: 60_000 }, downloads: { policy: "on-request", acceptAndroidLicenses: false, timeoutMs: 1_200_000 }, http: { enabled: false, host: "127.0.0.1", port: 4700 }, diff --git a/src/core/nuke.test.ts b/src/core/nuke.test.ts index 7eb6b6aa3..3b70d7a37 100644 --- a/src/core/nuke.test.ts +++ b/src/core/nuke.test.ts @@ -203,7 +203,11 @@ function config(): Config { }, }, log: { level: "info", rotateBytes: 5 * 1024 * 1024 }, - eventLog: { rotateBytes: 5 * 1024 * 1024 }, + eventLog: { + rotateBytes: 5 * 1024 * 1024, + retention: 7 * 24 * 60 * 60 * 1000, + maxBytes: 256 * 1024 * 1024, + }, warmPool: { quarantine: { maxRetries: 3, diff --git a/src/core/reaper.test.ts b/src/core/reaper.test.ts index 11457ef92..bbd94d02e 100644 --- a/src/core/reaper.test.ts +++ b/src/core/reaper.test.ts @@ -99,7 +99,11 @@ function config(): Config { }, }, log: { level: "info", rotateBytes: 5 * 1024 * 1024 }, - eventLog: { rotateBytes: 5 * 1024 * 1024 }, + eventLog: { + rotateBytes: 5 * 1024 * 1024, + retention: 7 * 24 * 60 * 60 * 1000, + maxBytes: 256 * 1024 * 1024, + }, warmPool: { quarantine: { maxRetries: 3, diff --git a/src/core/warm-pool-coordinator.test.ts b/src/core/warm-pool-coordinator.test.ts index 6f72d81a6..560efd84e 100644 --- a/src/core/warm-pool-coordinator.test.ts +++ b/src/core/warm-pool-coordinator.test.ts @@ -81,7 +81,11 @@ const config: Config = { }, }, log: { level: "info", rotateBytes: 5 * 1024 * 1024 }, - eventLog: { rotateBytes: 5 * 1024 * 1024 }, + eventLog: { + rotateBytes: 5 * 1024 * 1024, + retention: 7 * 24 * 60 * 60 * 1000, + maxBytes: 256 * 1024 * 1024, + }, }; class TestRegistry { diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index d99b0c815..1b9707079 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -2952,7 +2952,11 @@ function testConfig( }, capacity, log: { level: "info", rotateBytes: 5 * 1024 * 1024 }, - eventLog: { rotateBytes: 5 * 1024 * 1024 }, + eventLog: { + rotateBytes: 5 * 1024 * 1024, + retention: 7 * 24 * 60 * 60 * 1000, + maxBytes: 256 * 1024 * 1024, + }, warmPool: { quarantine: { maxRetries: 3, diff --git a/src/daemon/main.ts b/src/daemon/main.ts index 428e11fb6..74c902a97 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -1189,7 +1189,13 @@ function openEventHistory(options: { const logger = options.logger.child("events"); let sink: NodeFileLogSink | undefined; try { - sink = new NodeFileLogSink({ maxBytes: options.config.eventLog.rotateBytes, path }); + const { maxBytes, retention, rotateBytes } = options.config.eventLog; + sink = new NodeFileLogSink({ + maxBytes: rotateBytes, + path, + retentionMs: retention, + totalMaxBytes: maxBytes, + }); } catch (error: unknown) { logger.error("Event file could not be opened; events are kept in memory only", { error: error instanceof Error ? error.message : String(error), diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.ts index 066372faf..bfc04aafd 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -3278,7 +3278,11 @@ function testConfig( }, }, log: { level: "info", rotateBytes: 5 * 1024 * 1024 }, - eventLog: { rotateBytes: 5 * 1024 * 1024 }, + eventLog: { + rotateBytes: 5 * 1024 * 1024, + retention: 7 * 24 * 60 * 60 * 1000, + maxBytes: 256 * 1024 * 1024, + }, warmPool: { quarantine: { maxRetries: 3, diff --git a/src/http/app.ts b/src/http/app.ts index 3379f9cd6..8cf2d97f7 100644 --- a/src/http/app.ts +++ b/src/http/app.ts @@ -10,6 +10,7 @@ import { deviceClassSchema, imageTagSchema, } from "../contract/index.js"; +import { parseDurationMs } from "../contract/duration.js"; import type { Config, DeviceRecord } from "../core/index.js"; import type { OwnerRoutedFacts } from "../daemon/owner-routed-facts.js"; import type { Clock, IdGenerator, Logger } from "../ports/index.js"; @@ -832,13 +833,8 @@ async function parseRenewBody(c: { * not a duplicate of any daemon-side logic (the operation itself takes an absolute timestamp), * so it is not one of the re-implementations ADR §2 says fall away with the dispatcher move. */ function parseDuration(value: string): number { - const match = /^(\d+)(ms|s|m|h)?$/.exec(value); - if (match === null) throw badRequest(`Invalid duration: ${value}`); - const amount = Number(match[1]); - const unit = match[2] ?? "ms"; - const multiplier = unit === "h" ? 3_600_000 : unit === "m" ? 60_000 : unit === "s" ? 1_000 : 1; - const milliseconds = amount * multiplier; - if (!Number.isSafeInteger(milliseconds)) throw badRequest(`Invalid duration: ${value}`); + const milliseconds = parseDurationMs(value); + if (milliseconds === undefined) throw badRequest(`Invalid duration: ${value}`); return milliseconds; } diff --git a/src/http/test-fakes.ts b/src/http/test-fakes.ts index 3e347f781..c650339c0 100644 --- a/src/http/test-fakes.ts +++ b/src/http/test-fakes.ts @@ -69,7 +69,11 @@ export function testConfig( ...overrides, }, log: { level: "info", rotateBytes: 5 * 1024 * 1024 }, - eventLog: { rotateBytes: 5 * 1024 * 1024 }, + eventLog: { + rotateBytes: 5 * 1024 * 1024, + retention: 7 * 24 * 60 * 60 * 1000, + maxBytes: 256 * 1024 * 1024, + }, stalledTransition: { minimumThresholdMs: 60_000, thresholdMultiplier: 3 }, warmPool: { quarantine: { diff --git a/src/ports/logger.ts b/src/ports/logger.ts index e75d81684..b037956fc 100644 --- a/src/ports/logger.ts +++ b/src/ports/logger.ts @@ -1,7 +1,18 @@ -import { closeSync, fstatSync, mkdirSync, openSync, renameSync, writeSync } from "node:fs"; +import { + closeSync, + existsSync, + fstatSync, + mkdirSync, + openSync, + readSync, + renameSync, + statSync, + unlinkSync, + writeSync, +} from "node:fs"; import { dirname } from "node:path"; -import type { Clock } from "./clock.js"; +import { type Clock, SystemClock } from "./clock.js"; export type LogLevel = "debug" | "info" | "warn" | "error"; @@ -117,17 +128,46 @@ export class MemoryLogSink implements LogSink { } const DEFAULT_MAX_BYTES = 5 * 1024 * 1024; +/** Enough to hold the last line of any record this tool writes; a generation is never read whole. */ +const TAIL_BYTES = 64 * 1024; + +function readTail(file: string): string { + const fd = openSync(file, "r"); + try { + const size = fstatSync(fd).size; + const length = Math.min(size, TAIL_BYTES); + const buffer = Buffer.alloc(length); + readSync(fd, buffer, 0, length, size - length); + return buffer.toString("utf8"); + } finally { + closeSync(fd); + } +} export interface NodeFileLogSinkOptions { + /** One generation: the size at which the current file rotates. */ readonly maxBytes?: number; readonly path: string; + /** + * With `retentionMs` or `totalMaxBytes`, rotation keeps numbered generations (`.1` + * newest, upward) and sweeps them; without both, exactly one generation is kept. + */ + readonly retentionMs?: number; + readonly totalMaxBytes?: number; + /** Judges a generation's age; the system clock when absent. */ + readonly clock?: Clock; } /** * Appends to `path` via a held file descriptor, tracking bytes written. Once a write * would push the file past `maxBytes`, the current file is renamed to `.1` * (replacing any existing generation) and a fresh file is opened. Exactly one rotated - * generation is kept. + * generation is kept -- unless `retentionMs` or `totalMaxBytes` is given: then existing + * generations shift up one number, and the sweep deletes (only ever `.N` beside this + * sink's own path) every generation whose newest line is older than `retentionMs`, then the + * oldest until the generations plus the current file fit `totalMaxBytes`. The current file is + * never deleted. The same sweep runs once when the sink opens. A generation's age is the + * `timestamp` of its last line when that line is JSON carrying one, else the file's mtime. * * Writes are synchronous (`writeSync`), deliberately, not by oversight: this keeps * records strictly ordered without a write queue, guarantees a line is never split @@ -147,15 +187,22 @@ export interface NodeFileLogSinkOptions { export class NodeFileLogSink implements LogSink { readonly #path: string; readonly #maxBytes: number; + readonly #retentionMs: number | undefined; + readonly #totalMaxBytes: number | undefined; + readonly #clock: Clock; #fd: number; #bytesWritten: number; constructor(options: NodeFileLogSinkOptions) { this.#path = options.path; this.#maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES; + this.#retentionMs = options.retentionMs; + this.#totalMaxBytes = options.totalMaxBytes; + this.#clock = options.clock ?? new SystemClock(); mkdirSync(dirname(this.#path), { recursive: true }); this.#fd = openSync(this.#path, "a"); this.#bytesWritten = fstatSync(this.#fd).size; + this.#sweep(); } write(line: string): void { @@ -181,8 +228,73 @@ export class NodeFileLogSink implements LogSink { #rotate(): void { closeSync(this.#fd); + if (this.#retentionMs !== undefined || this.#totalMaxBytes !== undefined) { + this.#shiftGenerations(); + } renameSync(this.#path, `${this.#path}.1`); this.#fd = openSync(this.#path, "a"); this.#bytesWritten = 0; + this.#sweep(); + } + + /** `.N` -> `.N+1`, highest first, so no generation overwrites another. */ + #shiftGenerations(): void { + let highest = 0; + while (existsSync(`${this.#path}.${highest + 1}`)) highest += 1; + for (let generation = highest; generation >= 1; generation -= 1) { + renameSync(`${this.#path}.${generation}`, `${this.#path}.${generation + 1}`); + } + } + + #sweep(): void { + if (this.#retentionMs === undefined && this.#totalMaxBytes === undefined) return; + const sizes: number[] = []; + while (existsSync(`${this.#path}.${sizes.length + 1}`)) { + sizes.push(statSync(`${this.#path}.${sizes.length + 1}`).size); + } + // Generations get older with their number, so what is past retention, or over the cap, is + // a suffix; keeping the survivors contiguous is what lets a reader stop at the first + // missing one. + const keep = this.#fitSize(sizes, this.#withinRetention(sizes.length)); + for (let generation = sizes.length; generation > keep; generation -= 1) { + unlinkSync(`${this.#path}.${generation}`); + } + } + + /** How many of the `count` generations are not past `retentionMs`. */ + #withinRetention(count: number): number { + if (this.#retentionMs === undefined) return count; + const cutoff = this.#clock.now() - this.#retentionMs; + let keep = count; + while (keep > 0 && this.#newestLine(`${this.#path}.${keep}`) < cutoff) keep -= 1; + return keep; + } + + /** How many of the first `keep` generations fit `totalMaxBytes` beside the current file. */ + #fitSize(sizes: readonly number[], keep: number): number { + if (this.#totalMaxBytes === undefined) return keep; + // The current file is counted at its full size, not what it holds now: it is about to + // fill, and the cap is a promise about the total once it has. + let total = Math.max(this.#bytesWritten, this.#maxBytes); + for (let index = 0; index < keep; index += 1) total += sizes[index] ?? 0; + let kept = keep; + while (kept > 0 && total > this.#totalMaxBytes) { + kept -= 1; + total -= sizes[kept] ?? 0; + } + return kept; + } + + /** The time of a generation's newest line: its `timestamp` field, else the file's mtime. */ + #newestLine(file: string): number { + const lines = readTail(file).trimEnd().split("\n"); + try { + const parsed: unknown = JSON.parse(lines[lines.length - 1] ?? ""); + const timestamp = (parsed as { timestamp?: unknown } | null)?.timestamp; + if (typeof timestamp === "number") return timestamp; + } catch { + // Not JSON: fall through to the file's own time. + } + return statSync(file).mtimeMs; } } From 08ef46ebddbed48504462c09e6751b201c8cb047 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 5 Oct 2026 14:44:28 +0200 Subject: [PATCH 3/7] test: kill surviving mutants in the event log sweep and reader (#346) none failing; mutants 10 -> equivalents only --- src/bus/event-file.test.ts | 21 ++++++ src/contract/duration.ts | 5 +- src/core/config.test.ts | 2 +- src/http/app.test.ts | 1 + src/http/test-fakes.ts | 6 +- src/ports/logger.test.ts | 137 ++++++++++++++++++++++++++++++++++++- src/ports/logger.ts | 14 ++-- 7 files changed, 174 insertions(+), 12 deletions(-) diff --git a/src/bus/event-file.test.ts b/src/bus/event-file.test.ts index 8dad68410..cf4309ed7 100644 --- a/src/bus/event-file.test.ts +++ b/src/bus/event-file.test.ts @@ -313,6 +313,27 @@ describe("readEventFile", () => { expect(empty.oldestTs).toBeUndefined(); }); + it("returns the generations when the current file is missing", async () => { + const filesystem = await filesystemWith({ + "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/data/events.jsonl.1": lines(envelope(1, 100)), + "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/data/events.jsonl.2": lines(envelope(0, 50)), + }); + + const read = await readEventFile(filesystem, "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/data/events.jsonl", { sinceTs: 0 }); + + expect(read.map((entry) => entry.seq)).toEqual([0, 1]); + }); + + it("leaves out an event stamped exactly sinceTs", async () => { + const filesystem = await filesystemWith({ + "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/data/events.jsonl": lines(envelope(1, 100), envelope(2, 101)), + }); + + const read = await readEventFile(filesystem, "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/data/events.jsonl", { sinceTs: 100 }); + + expect(read.map((entry) => entry.seq)).toEqual([2]); + }); + it("skips a JSON line that is not an envelope and returns the lines around it", async () => { const filesystem = await filesystemWith({ "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/data/events.jsonl": `${lines(envelope(1, 100))}null\n[]\n{"seq":"2"}\n${lines(envelope(3, 300))}`, diff --git a/src/contract/duration.ts b/src/contract/duration.ts index e53c579e8..f3d3fc54b 100644 --- a/src/contract/duration.ts +++ b/src/contract/duration.ts @@ -15,6 +15,9 @@ const UNIT_MS: Readonly> = { export function parseDurationMs(value: string): number | undefined { const match = /^(\d+)(ms|s|m|h|d)?$/.exec(value); if (match === null) return undefined; - const milliseconds = Number(match[1]) * (UNIT_MS[match[2] ?? "ms"] ?? 1); + const [, amount = "", unit = "ms"] = match; + const multiplier = UNIT_MS[unit]; + if (multiplier === undefined) return undefined; + const milliseconds = Number(amount) * multiplier; return Number.isSafeInteger(milliseconds) ? milliseconds : undefined; } diff --git a/src/core/config.test.ts b/src/core/config.test.ts index 29a863d2d..6856f3d31 100644 --- a/src/core/config.test.ts +++ b/src/core/config.test.ts @@ -236,7 +236,7 @@ describe("loadConfig", () => { await expect( loadConfig({ configPath, filesystem, systemStats: createStats() }), - ).rejects.toThrow("eventLog.maxBytes"); + ).rejects.toThrow('"eventLog.maxBytes": expected at least twice eventLog.rotateBytes'); await filesystem.writeFileAtomic( configPath, diff --git a/src/http/app.test.ts b/src/http/app.test.ts index 8b3184024..998b97a4b 100644 --- a/src/http/app.test.ts +++ b/src/http/app.test.ts @@ -1777,6 +1777,7 @@ describe("operator-only listing routes", () => { }; const response = await app.request("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/v1/events?since=nonsense", { headers: operatorAuth }); expect(response.status).toBe(400); + expect(JSON.stringify(await response.json())).toContain("Invalid duration: nonsense"); }); it("GET /v1/events/stream dispatches events.subscribe then follows the raw event bus live", async () => { diff --git a/src/http/test-fakes.ts b/src/http/test-fakes.ts index c650339c0..e1fc122c2 100644 --- a/src/http/test-fakes.ts +++ b/src/http/test-fakes.ts @@ -70,9 +70,9 @@ export function testConfig( }, log: { level: "info", rotateBytes: 5 * 1024 * 1024 }, eventLog: { - rotateBytes: 5 * 1024 * 1024, - retention: 7 * 24 * 60 * 60 * 1000, - maxBytes: 256 * 1024 * 1024, + rotateBytes: 5_242_880, + retention: 604_800_000, + maxBytes: 268_435_456, }, stalledTransition: { minimumThresholdMs: 60_000, thresholdMultiplier: 3 }, warmPool: { diff --git a/src/ports/logger.test.ts b/src/ports/logger.test.ts index 2b1edd07e..23dd65b11 100644 --- a/src/ports/logger.test.ts +++ b/src/ports/logger.test.ts @@ -1,4 +1,4 @@ -import { mkdtemp, readFile, readdir, rename, rm, writeFile } from "node:fs/promises"; +import { mkdtemp, readFile, readdir, rename, rm, utimes, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, describe, expect, it } from "vitest"; @@ -358,6 +358,141 @@ describe("NodeFileLogSink", () => { expect(await generations(directory)).toEqual(["events.jsonl"]); }); + it("keeps numbered generations with only a retention", async () => { + const directory = await tempDir(); + const path = join(directory, "events.jsonl"); + const sink = new NodeFileLogSink({ + clock: new FakeClock(1_000), + maxBytes: 10, + path, + retentionMs: DAY, + }); + + for (const letter of ["a", "b", "c", "d"]) sink.write(letter.repeat(10)); + sink.close(); + + expect(await generations(directory)).toEqual([ + "events.jsonl", + "events.jsonl.1", + "events.jsonl.2", + "events.jsonl.3", + ]); + }); + + it("keeps numbered generations with only a total size cap, and deletes the oldest to fit it", async () => { + const directory = await tempDir(); + const path = join(directory, "events.jsonl"); + const sink = new NodeFileLogSink({ maxBytes: 10, path, totalMaxBytes: 1_000_000 }); + + for (const letter of ["a", "b", "c"]) sink.write(letter.repeat(10)); + sink.close(); + + expect(await generations(directory)).toEqual([ + "events.jsonl", + "events.jsonl.1", + "events.jsonl.2", + ]); + }); + + it("keeps a generation whose newest line is exactly at the retention boundary", async () => { + const directory = await tempDir(); + const path = join(directory, "events.jsonl"); + await writeFile(`${path}.1`, `${stamped(9_000)}\n`); + await writeFile(path, ""); + + const sink = new NodeFileLogSink({ + clock: new FakeClock(10_000), + maxBytes: 10_000, + path, + retentionMs: 1_000, + }); + sink.close(); + + expect(await generations(directory)).toEqual(["events.jsonl", "events.jsonl.1"]); + }); + + it("at open deletes as many of the oldest generations as it takes to fit the total, and no more", async () => { + const directory = await tempDir(); + const path = join(directory, "events.jsonl"); + for (const generation of [1, 2, 3, 4]) { + await writeFile(`${path}.${generation}`, `${"x".repeat(9)}\n`); + } + // The current file counts as one full generation (10 bytes) plus three of 10 = exactly 40. + + const sink = new NodeFileLogSink({ maxBytes: 10, path, totalMaxBytes: 40 }); + sink.close(); + + expect(await generations(directory)).toEqual([ + "events.jsonl", + "events.jsonl.1", + "events.jsonl.2", + "events.jsonl.3", + ]); + }); + + it("at open deletes several generations when two or more do not fit", async () => { + const directory = await tempDir(); + const path = join(directory, "events.jsonl"); + for (const generation of [1, 2, 3, 4]) { + await writeFile(`${path}.${generation}`, `${"x".repeat(9)}\n`); + } + + const sink = new NodeFileLogSink({ maxBytes: 10, path, totalMaxBytes: 25 }); + sink.close(); + + expect(await generations(directory)).toEqual(["events.jsonl", "events.jsonl.1"]); + }); + + it("does not count a generation already deleted for age against the size cap", async () => { + const directory = await tempDir(); + const path = join(directory, "events.jsonl"); + // Each line is 16 bytes with its newline. The current file counts as one full 16-byte + // generation, so .1 and .2 fit a 48-byte cap exactly -- but not with .3 counted too. + await writeFile(`${path}.1`, `{"timestamp":9500}\n`); + await writeFile(`${path}.2`, `{"timestamp":9400}\n`); + await writeFile(`${path}.3`, `{"timestamp":5}\n`); + const lineBytes = Buffer.byteLength(`{"timestamp":9500}\n`); + + const sink = new NodeFileLogSink({ + clock: new FakeClock(10_000), + maxBytes: lineBytes, + path, + retentionMs: 1_000, + totalMaxBytes: 3 * lineBytes, + }); + sink.close(); + + expect(await generations(directory)).toEqual([ + "events.jsonl", + "events.jsonl.1", + "events.jsonl.2", + ]); + }); + + it("judges a generation whose last line carries no timestamp by its file time", async () => { + const directory = await tempDir(); + const path = join(directory, "events.jsonl"); + const staleFile = new Date(1_000); + for (const [generation, lastLine] of [ + [1, '{"other":1}'], + [2, "null"], + [3, "not json"], + ] as const) { + await writeFile(`${path}.${generation}`, `${lastLine}\n`); + await utimes(`${path}.${generation}`, staleFile, staleFile); + } + + const sink = new NodeFileLogSink({ + clock: new FakeClock(10_000_000), + maxBytes: 10_000, + path, + retentionMs: 1_000, + }); + sink.close(); + + expect(await generations(directory)).toEqual(["events.jsonl"]); + }); + it("deletes only the files it rotated beside its own path, never a neighbour", async () => { const directory = await tempDir(); const path = join(directory, "events.jsonl"); diff --git a/src/ports/logger.ts b/src/ports/logger.ts index b037956fc..b0c12c3b0 100644 --- a/src/ports/logger.ts +++ b/src/ports/logger.ts @@ -247,7 +247,6 @@ export class NodeFileLogSink implements LogSink { } #sweep(): void { - if (this.#retentionMs === undefined && this.#totalMaxBytes === undefined) return; const sizes: number[] = []; while (existsSync(`${this.#path}.${sizes.length + 1}`)) { sizes.push(statSync(`${this.#path}.${sizes.length + 1}`).size); @@ -263,8 +262,10 @@ export class NodeFileLogSink implements LogSink { /** How many of the `count` generations are not past `retentionMs`. */ #withinRetention(count: number): number { - if (this.#retentionMs === undefined) return count; - const cutoff = this.#clock.now() - this.#retentionMs; + const cutoff = + this.#retentionMs === undefined + ? Number.NEGATIVE_INFINITY + : this.#clock.now() - this.#retentionMs; let keep = count; while (keep > 0 && this.#newestLine(`${this.#path}.${keep}`) < cutoff) keep -= 1; return keep; @@ -275,8 +276,8 @@ export class NodeFileLogSink implements LogSink { if (this.#totalMaxBytes === undefined) return keep; // The current file is counted at its full size, not what it holds now: it is about to // fill, and the cap is a promise about the total once it has. - let total = Math.max(this.#bytesWritten, this.#maxBytes); - for (let index = 0; index < keep; index += 1) total += sizes[index] ?? 0; + let total = sizes.slice(0, keep).reduce((sum, size) => sum + size, 0); + total += Math.max(this.#bytesWritten, this.#maxBytes); let kept = keep; while (kept > 0 && total > this.#totalMaxBytes) { kept -= 1; @@ -290,7 +291,8 @@ export class NodeFileLogSink implements LogSink { const lines = readTail(file).trimEnd().split("\n"); try { const parsed: unknown = JSON.parse(lines[lines.length - 1] ?? ""); - const timestamp = (parsed as { timestamp?: unknown } | null)?.timestamp; + // A `null` line throws here and is caught, like any other line that is not an object. + const timestamp = (parsed as { timestamp?: unknown }).timestamp; if (typeof timestamp === "number") return timestamp; } catch { // Not JSON: fall through to the file's own time. From 17fe0524a3eb83ffe8afd4f0875db9bb52587459 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 5 Oct 2026 15:07:05 +0200 Subject: [PATCH 4/7] test: make the total size cap tests able to fail when the cap breaks (#346) Both tests now fail with the cap disabled; verified by mutation. --- e2e/event-history.test.ts | 2 +- src/ports/logger.test.ts | 13 ++++++------- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/e2e/event-history.test.ts b/e2e/event-history.test.ts index 68c44c177..526ada83a 100644 --- a/e2e/event-history.test.ts +++ b/e2e/event-history.test.ts @@ -107,7 +107,7 @@ describe("event history", () => { }); it("keeps no more than two generations beside events.jsonl when eventLog.maxBytes is twice eventLog.rotateBytes, holding the newest event", async () => { - const rotateBytes = 8 * 1024; + const rotateBytes = 2 * 1024; const env = await withDaemon({ configOverrides: { eventLog: { maxBytes: 2 * rotateBytes, rotateBytes } }, }); diff --git a/src/ports/logger.test.ts b/src/ports/logger.test.ts index 23dd65b11..36ac7696b 100644 --- a/src/ports/logger.test.ts +++ b/src/ports/logger.test.ts @@ -382,16 +382,15 @@ describe("NodeFileLogSink", () => { it("keeps numbered generations with only a total size cap, and deletes the oldest to fit it", async () => { const directory = await tempDir(); const path = join(directory, "events.jsonl"); - const sink = new NodeFileLogSink({ maxBytes: 10, path, totalMaxBytes: 1_000_000 }); + const sink = new NodeFileLogSink({ maxBytes: 10, path, totalMaxBytes: 30 }); - for (const letter of ["a", "b", "c"]) sink.write(letter.repeat(10)); + for (const letter of ["a", "b", "c", "d"]) sink.write(letter.repeat(10)); sink.close(); - expect(await generations(directory)).toEqual([ - "events.jsonl", - "events.jsonl.1", - "events.jsonl.2", - ]); + // Each file is 11 bytes: the current file plus one generation fit 30, a second do not. + expect(await generations(directory)).toEqual(["events.jsonl", "events.jsonl.1"]); + expect(await readFile(`${path}.1`, "utf8")).toBe("cccccccccc\n"); + expect(await readFile(path, "utf8")).toBe("dddddddddd\n"); }); it("keeps a generation whose newest line is exactly at the retention boundary", async () => { From 5e2fbc895a411cd7070a6f0a9beac187e15888e0 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 5 Oct 2026 15:25:42 +0200 Subject: [PATCH 5/7] fix: the event reader survives a rotation caught between renames, and a fresh untimestamped generation is kept by its file time (#346) 1 failing -> 0 failing per finding --- src/bus/event-file.test.ts | 26 ++++++++++++++++++++++++++ src/bus/event-file.ts | 16 ++++++++++++---- src/ports/logger.test.ts | 29 +++++++++++++++++++++++++++++ 3 files changed, 67 insertions(+), 4 deletions(-) diff --git a/src/bus/event-file.test.ts b/src/bus/event-file.test.ts index cf4309ed7..5329f1133 100644 --- a/src/bus/event-file.test.ts +++ b/src/bus/event-file.test.ts @@ -296,6 +296,32 @@ describe("readEventFile", () => { expect(result.map((entry) => entry.seq)).toEqual([1, 2, 3, 4]); }); + it("loses no generation when a rotation has renamed .1 away and not yet renamed the current file into it", async () => { + // The state between a rotation's renames: .1 -> .2 and .2 -> .3 are done, current -> .1 is not. + const filesystem = await filesystemWith({ + "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/data/events.jsonl": lines(envelope(4, 400)), + "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/data/events.jsonl.2": lines(envelope(3, 300)), + "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/data/events.jsonl.3": lines(envelope(2, 200)), + "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/data/events.jsonl.4": lines(envelope(1, 100)), + }); + + const result = await readEventFile(filesystem, "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/data/events.jsonl", { sinceTs: 0 }); + + expect(result.map((entry) => entry.seq)).toEqual([1, 2, 3, 4]); + }); + + it("ends at the first place two generations in a row are missing", async () => { + const filesystem = await filesystemWith({ + "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/data/events.jsonl": lines(envelope(3, 300)), + "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/data/events.jsonl.1": lines(envelope(2, 200)), + "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/data/events.jsonl.4": lines(envelope(1, 100)), + }); + + const result = await readEventFile(filesystem, "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/data/events.jsonl", { sinceTs: 0 }); + + expect(result.map((entry) => entry.seq)).toEqual([2, 3]); + }); + it("reports the oldest timestamp it holds, and undefined for an empty history", async () => { const filesystem = await filesystemWith({ "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/data/events.jsonl": lines(envelope(3, 300)), diff --git a/src/bus/event-file.ts b/src/bus/event-file.ts index d4b73adc7..649916742 100644 --- a/src/bus/event-file.ts +++ b/src/bus/event-file.ts @@ -10,8 +10,10 @@ export const EVENT_FILE_NAME = "events.jsonl"; * Every envelope in the event file newer than `sinceTs`, by `timestamp` then `seq` (ADR 0014 §5). * The current file is read first, then its generations `.1`, `.2` and so on until * one is missing (ADR 0016 §4). Newest first means a rotation landing mid-read can only make a - * generation show up twice -- never make one go missing -- and the repeat is dropped by `id`; a - * generation missing when it is opened is empty and ends the walk. A line that is not JSON (a + * generation show up twice -- never make one go missing -- and the repeat is dropped by `id`. + * A rotation renames the generations one at a time, so for an instant one number is missing + * with the ones above it still there: the walk ends only at a missing generation whose next + * number is missing too. A line that is not JSON (a * write cut short by a crash), or has no `id` of the shape the envelope contract accepts * (written before events had one, ADR 0014), is skipped; a file that is not there is empty. */ @@ -56,8 +58,14 @@ async function readGenerations(filesystem: Filesystem, path: string): Promise 0) return generations; + // rename and its re-open). A missing generation is one rotation step caught mid-shift when + // the next number exists; only two in a row end the walk. + else if ( + generation > 0 && + (await readLines(filesystem, `${path}.${generation + 1}`)) === undefined + ) { + return generations; + } } } diff --git a/src/ports/logger.test.ts b/src/ports/logger.test.ts index 36ac7696b..88a479d9c 100644 --- a/src/ports/logger.test.ts +++ b/src/ports/logger.test.ts @@ -492,6 +492,35 @@ describe("NodeFileLogSink", () => { expect(await generations(directory)).toEqual(["events.jsonl"]); }); + it("keeps a generation whose last line carries no timestamp while its file time is within retention", async () => { + const directory = await tempDir(); + const path = join(directory, "events.jsonl"); + const freshFile = new Date(9_999_500); + for (const [generation, lastLine] of [ + [1, '{"other":1}'], + [2, "null"], + [3, "not json"], + ] as const) { + await writeFile(`${path}.${generation}`, `${lastLine}\n`); + await utimes(`${path}.${generation}`, freshFile, freshFile); + } + + const sink = new NodeFileLogSink({ + clock: new FakeClock(10_000_000), + maxBytes: 10_000, + path, + retentionMs: 1_000, + }); + sink.close(); + + expect(await generations(directory)).toEqual([ + "events.jsonl", + "events.jsonl.1", + "events.jsonl.2", + "events.jsonl.3", + ]); + }); + it("deletes only the files it rotated beside its own path, never a neighbour", async () => { const directory = await tempDir(); const path = join(directory, "events.jsonl"); From c449c1e98a651cb5fd84cb445580f48e2d27667a Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 5 Oct 2026 15:44:15 +0200 Subject: [PATCH 6/7] test: kill surviving mutants in the sweep, the duration parser and the reader walk (#346) 12 alive -> 2 alive (both equivalent, see the PR body) --- src/bus/event-file.ts | 5 +--- src/contract/duration.ts | 15 ++++++---- src/ports/logger.test.ts | 59 ++++++++++++++++++++++++++++++++++++---- src/ports/logger.ts | 14 ++++------ 4 files changed, 69 insertions(+), 24 deletions(-) diff --git a/src/bus/event-file.ts b/src/bus/event-file.ts index 649916742..fb859089a 100644 --- a/src/bus/event-file.ts +++ b/src/bus/event-file.ts @@ -60,10 +60,7 @@ async function readGenerations(filesystem: Filesystem, path: string): Promise 0 && - (await readLines(filesystem, `${path}.${generation + 1}`)) === undefined - ) { + else if ((await readLines(filesystem, `${path}.${generation + 1}`)) === undefined) { return generations; } } diff --git a/src/contract/duration.ts b/src/contract/duration.ts index f3d3fc54b..e1ab035d8 100644 --- a/src/contract/duration.ts +++ b/src/contract/duration.ts @@ -1,10 +1,10 @@ -const UNIT_MS: Readonly> = { +const UNIT_MS = { ms: 1, s: 1_000, m: 60_000, h: 3_600_000, d: 86_400_000, -}; +} as const; /** * The one parser for the durations a person types (`500`, `2s`, `3m`, `1h`, `7d`) -- the CLI @@ -15,9 +15,12 @@ const UNIT_MS: Readonly> = { export function parseDurationMs(value: string): number | undefined { const match = /^(\d+)(ms|s|m|h|d)?$/.exec(value); if (match === null) return undefined; - const [, amount = "", unit = "ms"] = match; - const multiplier = UNIT_MS[unit]; - if (multiplier === undefined) return undefined; - const milliseconds = Number(amount) * multiplier; + // The pattern admits only the units in UNIT_MS, and only matches with an amount. + const [, amount, unit = "ms"] = match as unknown as [ + string, + string, + keyof typeof UNIT_MS | undefined, + ]; + const milliseconds = Number(amount) * UNIT_MS[unit]; return Number.isSafeInteger(milliseconds) ? milliseconds : undefined; } diff --git a/src/ports/logger.test.ts b/src/ports/logger.test.ts index 88a479d9c..9e947b193 100644 --- a/src/ports/logger.test.ts +++ b/src/ports/logger.test.ts @@ -1,3 +1,4 @@ +import { readdirSync } from "node:fs"; import { mkdtemp, readFile, readdir, rename, rm, utimes, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -289,6 +290,23 @@ describe("NodeFileLogSink", () => { expect(await generations(directory)).toContain("events.jsonl.1"); }); + it("deletes a generation by its last line's timestamp even when earlier lines are older still", async () => { + const directory = await tempDir(); + const path = join(directory, "events.jsonl"); + await writeFile(`${path}.1`, `${stamped(1)}\n${stamped(2)}\n`); + + const sink = new NodeFileLogSink({ + clock: new FakeClock(10_000_000), + maxBytes: 10_000, + path, + retentionMs: 1_000, + }); + sink.close(); + + // The file's own mtime is now; only the last line's timestamp (2) says it is expired. + expect(await generations(directory)).toEqual(["events.jsonl"]); + }); + it("when the generations exceed maxBytes the oldest are deleted until the total fits, and the current file is never deleted", async () => { const directory = await tempDir(); const path = join(directory, "events.jsonl"); @@ -358,6 +376,30 @@ describe("NodeFileLogSink", () => { expect(await generations(directory)).toEqual(["events.jsonl"]); }); + it("the sweep leaves no file descriptor open after it reads each generation's newest line", async () => { + const directory = await tempDir(); + const path = join(directory, "events.jsonl"); + for (const generation of [1, 2, 3, 4, 5]) { + await writeFile(`${path}.${generation}`, `${stamped(9_000_000)}\n`); + } + const openDescriptors = (): number => readdirSync("/dev/fd").length; + const before = openDescriptors(); + + const sink = new NodeFileLogSink({ + clock: new FakeClock(10_000_000), + maxBytes: 10_000, + path, + retentionMs: DAY, + totalMaxBytes: 1_000_000, + }); + const during = openDescriptors(); + sink.close(); + + // Only the sink's own descriptor is held; the five generations were read and closed. + expect(during - before).toBe(1); + expect(await generations(directory)).toHaveLength(6); + }); + it("keeps numbered generations with only a retention", async () => { const directory = await tempDir(); const path = join(directory, "events.jsonl"); @@ -382,15 +424,20 @@ describe("NodeFileLogSink", () => { it("keeps numbered generations with only a total size cap, and deletes the oldest to fit it", async () => { const directory = await tempDir(); const path = join(directory, "events.jsonl"); - const sink = new NodeFileLogSink({ maxBytes: 10, path, totalMaxBytes: 30 }); + const sink = new NodeFileLogSink({ maxBytes: 10, path, totalMaxBytes: 35 }); - for (const letter of ["a", "b", "c", "d"]) sink.write(letter.repeat(10)); + for (const letter of ["a", "b", "c", "d", "e"]) sink.write(letter.repeat(10)); sink.close(); - // Each file is 11 bytes: the current file plus one generation fit 30, a second do not. - expect(await generations(directory)).toEqual(["events.jsonl", "events.jsonl.1"]); - expect(await readFile(`${path}.1`, "utf8")).toBe("cccccccccc\n"); - expect(await readFile(path, "utf8")).toBe("dddddddddd\n"); + // Each file is 11 bytes: the current file plus two generations fit 35, a third does not. + expect(await generations(directory)).toEqual([ + "events.jsonl", + "events.jsonl.1", + "events.jsonl.2", + ]); + expect(await readFile(`${path}.2`, "utf8")).toBe("cccccccccc\n"); + expect(await readFile(`${path}.1`, "utf8")).toBe("dddddddddd\n"); + expect(await readFile(path, "utf8")).toBe("eeeeeeeeee\n"); }); it("keeps a generation whose newest line is exactly at the retention boundary", async () => { diff --git a/src/ports/logger.ts b/src/ports/logger.ts index b0c12c3b0..19c7b7b28 100644 --- a/src/ports/logger.ts +++ b/src/ports/logger.ts @@ -262,10 +262,8 @@ export class NodeFileLogSink implements LogSink { /** How many of the `count` generations are not past `retentionMs`. */ #withinRetention(count: number): number { - const cutoff = - this.#retentionMs === undefined - ? Number.NEGATIVE_INFINITY - : this.#clock.now() - this.#retentionMs; + // No retention: nothing is ever older than the cutoff. + const cutoff = this.#clock.now() - (this.#retentionMs ?? Number.POSITIVE_INFINITY); let keep = count; while (keep > 0 && this.#newestLine(`${this.#path}.${keep}`) < cutoff) keep -= 1; return keep; @@ -273,13 +271,13 @@ export class NodeFileLogSink implements LogSink { /** How many of the first `keep` generations fit `totalMaxBytes` beside the current file. */ #fitSize(sizes: readonly number[], keep: number): number { - if (this.#totalMaxBytes === undefined) return keep; + const cap = this.#totalMaxBytes ?? Number.POSITIVE_INFINITY; // The current file is counted at its full size, not what it holds now: it is about to // fill, and the cap is a promise about the total once it has. let total = sizes.slice(0, keep).reduce((sum, size) => sum + size, 0); total += Math.max(this.#bytesWritten, this.#maxBytes); let kept = keep; - while (kept > 0 && total > this.#totalMaxBytes) { + while (kept > 0 && total > cap) { kept -= 1; total -= sizes[kept] ?? 0; } @@ -288,9 +286,9 @@ export class NodeFileLogSink implements LogSink { /** The time of a generation's newest line: its `timestamp` field, else the file's mtime. */ #newestLine(file: string): number { - const lines = readTail(file).trimEnd().split("\n"); + const tail = readTail(file).trimEnd(); try { - const parsed: unknown = JSON.parse(lines[lines.length - 1] ?? ""); + const parsed: unknown = JSON.parse(tail.slice(tail.lastIndexOf("\n") + 1)); // A `null` line throws here and is caught, like any other line that is not an object. const timestamp = (parsed as { timestamp?: unknown }).timestamp; if (typeof timestamp === "number") return timestamp; From 5d7c1d39145a40579056729c20a48063dbbbc710 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 5 Oct 2026 16:03:49 +0200 Subject: [PATCH 7/7] fix: the event file sink uses the daemon's clock and an e2e proves retention (#346) Round-3 findings: pass the injected clock to the sink, e2e test for eventLog.retention, reader doc says two missing in a row, comment byte count fixed. --- docs/internal/ARCHITECTURE.md | 2 +- e2e/event-history.test.ts | 23 +++++++++++++++++++++++ src/bus/event-file.ts | 2 +- src/daemon/main.test.ts | 22 ++++++++++++++++++++++ src/daemon/main.ts | 11 ++++++++++- src/ports/logger.test.ts | 4 ++-- 6 files changed, 59 insertions(+), 5 deletions(-) diff --git a/docs/internal/ARCHITECTURE.md b/docs/internal/ARCHITECTURE.md index e2bdc472f..9c0f8a2a8 100644 --- a/docs/internal/ARCHITECTURE.md +++ b/docs/internal/ARCHITECTURE.md @@ -1914,7 +1914,7 @@ that cannot be opened, or a write that fails, costs the history and never the daemon or the emitter: one error line, writing stops, and replay falls back to the ring. `events.replay` in both dispatchers asks `EventHistory`: without `sinceTs` it answers from the ring, with `sinceTs` from the file (current -file, then `.1`, `.2` and so on until one is missing, deduplicated by `id`). +file, then `.1`, `.2` and so on until two in a row are missing, deduplicated by `id`). The CLI reads the file itself only for `simlock events --since` when no daemon answers; `--follow` subscribes first, replays, and drops replayed pushes, so the join neither loses nor repeats an event. diff --git a/e2e/event-history.test.ts b/e2e/event-history.test.ts index 526ada83a..1cfe7efdd 100644 --- a/e2e/event-history.test.ts +++ b/e2e/event-history.test.ts @@ -155,6 +155,29 @@ describe("event history", () => { expect(new Set(ids).size).toBe(ids.length); }); + it("deletes every generation holding only first-run events once eventLog.retention has passed and the file rotates again", async () => { + const env = await withDaemon({ + configOverrides: { eventLog: { retention: 5_000, rotateBytes: 2 * 1024 } }, + }); + await prepare(env); + const path = join(env.home, "events.jsonl"); + const firstLeaseId = await leaseDevice(env); + expect((await env.cli(["release", firstLeaseId])).code).toBe(0); + for (let round = 0; round < 6; round++) { + expect((await env.cli(["release", await leaseDevice(env)])).code).toBe(0); + } + expect(existsSync(`${path}.2`)).toBe(true); + expect(grantOf(await eventFile(env), firstLeaseId)).toBeDefined(); + + await waitFor( + async () => { + expect((await env.cli(["release", await leaseDevice(env)])).code).toBe(0); + return grantOf(await eventFile(env), firstLeaseId) === undefined; + }, + { label: "the first run's events deleted after retention", timeout: 60_000 }, + ); + }); + it("keeps every emitted event in the event file after daemon.log rotates", async () => { const env = await withDaemon({ configOverrides: { log: { rotateBytes: 1024 } } }); await prepare(env); diff --git a/src/bus/event-file.ts b/src/bus/event-file.ts index fb859089a..8f4be2ce0 100644 --- a/src/bus/event-file.ts +++ b/src/bus/event-file.ts @@ -51,7 +51,7 @@ export async function readEventHistory( return { events: events.sort(byTimeThenSeq), oldestTs }; } -/** The lines of the current file, then of each generation, newest first, until one is missing. */ +/** The lines of the current file, then of each generation, newest first, until two in a row are missing. */ async function readGenerations(filesystem: Filesystem, path: string): Promise { const generations: string[][] = []; for (let generation = 0; ; generation += 1) { diff --git a/src/daemon/main.test.ts b/src/daemon/main.test.ts index 5f6b5b5e1..5d3f0a645 100644 --- a/src/daemon/main.test.ts +++ b/src/daemon/main.test.ts @@ -76,6 +76,28 @@ async function start( return { daemon, directory, sink }; } +describe("the event file sink", () => { + it("judges retention by the injected clock, so a generation younger than the retention on that clock survives the start-up sweep", async () => { + const directory = await mkdtemp(join(tmpdir(), "simlock-main-")); + temporaryDirectories.push(directory); + // The fake clock reads 1_000; a real clock would put the 7-day cutoff far past 500. + await writeFile(join(directory, "events.jsonl.1"), `{"timestamp":500}\n`); + const clock = new FakeClock(1_000); + const daemon = await startDaemon({ + clock, + dataDirectory: directory, + drivers: [new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" })], + filesystem: new MemoryFilesystem(), + logger: new JsonLinesLogger({ clock, level: "debug", sink: new MemoryLogSink() }), + statePath: join(directory, "state.json"), + version: "1.2.3", + } as StartDaemonOptions); + runningDaemons.push(daemon); + + expect(await readFile(join(directory, "events.jsonl.1"), "utf8")).toBe(`{"timestamp":500}\n`); + }); +}); + /** A gateway URL on a port just released. Nothing listens there, so a worker's uplink dial * fails fast, and the fake clock never fires its retry. */ async function unreachableGatewayUrl(): Promise { diff --git a/src/daemon/main.ts b/src/daemon/main.ts index 74c902a97..012d3622d 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -160,7 +160,14 @@ export async function startDaemon(options: StartDaemonOptions = {}): Promise): (fact: Sli * opened costs the history, never the daemon: one error line, and replay answers from the ring. */ function openEventHistory(options: { + readonly clock: Clock; readonly config: Config; readonly dataDirectory: string; readonly eventBus: EventBus; @@ -1191,6 +1199,7 @@ function openEventHistory(options: { try { const { maxBytes, retention, rotateBytes } = options.config.eventLog; sink = new NodeFileLogSink({ + clock: options.clock, maxBytes: rotateBytes, path, retentionMs: retention, diff --git a/src/ports/logger.test.ts b/src/ports/logger.test.ts index 9e947b193..f9589b9f3 100644 --- a/src/ports/logger.test.ts +++ b/src/ports/logger.test.ts @@ -492,8 +492,8 @@ describe("NodeFileLogSink", () => { it("does not count a generation already deleted for age against the size cap", async () => { const directory = await tempDir(); const path = join(directory, "events.jsonl"); - // Each line is 16 bytes with its newline. The current file counts as one full 16-byte - // generation, so .1 and .2 fit a 48-byte cap exactly -- but not with .3 counted too. + // Each line is 19 bytes with its newline (lineBytes below). The current file counts as one + // full generation, so .1 and .2 fit a 3 * lineBytes cap exactly -- but not with .3 too. await writeFile(`${path}.1`, `{"timestamp":9500}\n`); await writeFile(`${path}.2`, `{"timestamp":9400}\n`); await writeFile(`${path}.3`, `{"timestamp":5}\n`);