Skip to content
9 changes: 6 additions & 3 deletions docs/CLI.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion docs/CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` |
Expand Down
5 changes: 3 additions & 2 deletions docs/EVENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
3 changes: 2 additions & 1 deletion docs/HTTP-API.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 4 additions & 2 deletions docs/internal/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 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.
Expand Down
5 changes: 3 additions & 2 deletions docs/internal/EVENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
68 changes: 60 additions & 8 deletions e2e/event-history.test.ts
Original file line number Diff line number Diff line change
@@ -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";

Expand Down Expand Up @@ -44,7 +44,10 @@ function parseLines(contents: string): Envelope[] {

async function eventFile(env: TestEnv): Promise<Envelope[]> {
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")));
}

Expand Down Expand Up @@ -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 () => {
const rotateBytes = 8 * 1024;
const env = await withDaemon({ configOverrides: { eventLog: { rotateBytes } } });
it("keeps no more than two generations beside events.jsonl when eventLog.maxBytes is twice eventLog.rotateBytes, holding the newest event", async () => {
const rotateBytes = 2 * 1024;
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);
}
Expand All @@ -122,8 +127,55 @@ 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("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 () => {
Expand Down
115 changes: 115 additions & 0 deletions src/bus/event-file.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
type EventEnvelope,
EventHistory,
readEventFile,
readEventHistory,
} from "./index.js";

const directories: string[] = [];
Expand Down Expand Up @@ -245,6 +246,120 @@ 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({
"/data/events.jsonl": lines(envelope(7, 700), envelope(8, 800)),
"/data/events.jsonl.1": lines(envelope(5, 500), envelope(6, 600), envelope(8, 800)),
"/data/events.jsonl.2": lines(envelope(3, 300), envelope(4, 400)),
"/data/events.jsonl.3": lines(envelope(1, 100), envelope(2, 200)),
});

const read = await readEventFile(filesystem, "/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({
"/data/events.jsonl": lines(envelope(4, 400)),
"/data/events.jsonl.1": lines(envelope(3, 300)),
"/data/events.jsonl.2": lines(envelope(2, 200)),
"/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("/data/events.jsonl", lines(envelope(5, 500)));
}
return contents;
});

const result = await readEventFile(filesystem, "/data/events.jsonl", { sinceTs: 0 });

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({
"/data/events.jsonl": lines(envelope(4, 400)),
"/data/events.jsonl.2": lines(envelope(3, 300)),
"/data/events.jsonl.3": lines(envelope(2, 200)),
"/data/events.jsonl.4": lines(envelope(1, 100)),
});

const result = await readEventFile(filesystem, "/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({
"/data/events.jsonl": lines(envelope(3, 300)),
"/data/events.jsonl.1": lines(envelope(2, 200)),
"/data/events.jsonl.4": lines(envelope(1, 100)),
});

const result = await readEventFile(filesystem, "/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({
"/data/events.jsonl": lines(envelope(3, 300)),
"/data/events.jsonl.1": lines(envelope(2, 200)),
"/data/events.jsonl.2": lines(envelope(1, 100)),
});

const held = await readEventHistory(filesystem, "/data/events.jsonl", { sinceTs: 250 });
const empty = await readEventHistory(await filesystemWith({}), "/data/events.jsonl", {
sinceTs: 0,
});

expect(held.oldestTs).toBe(100);
expect(held.events.map((entry) => entry.seq)).toEqual([3]);
expect(empty.oldestTs).toBeUndefined();
});

it("returns the generations when the current file is missing", async () => {
const filesystem = await filesystemWith({
"/data/events.jsonl.1": lines(envelope(1, 100)),
"/data/events.jsonl.2": lines(envelope(0, 50)),
});

const read = await readEventFile(filesystem, "/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({
"/data/events.jsonl": lines(envelope(1, 100), envelope(2, 101)),
});

const read = await readEventFile(filesystem, "/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({
"/data/events.jsonl": `${lines(envelope(1, 100))}null\n[]\n{"seq":"2"}\n${lines(envelope(3, 300))}`,
Expand Down
Loading
Loading