Skip to content

Keep business events on disk so the history survives a restart #168

Closed

Description

@V3RON

Request: none

Problem

Business events (lease.granted, device.crash-detected, and the rest) live
only in an in-memory ring buffer of 1000 entries. A daemon restart or crash
empties it. A busy machine or a gateway overwrites it within minutes.
daemon.log survives a restart, but it records only two events
(component.installed, device.slimmed). So "what happened to this lease or
device" has no answer after a restart, which is often when it is asked.

Who it is for

An operator or agent debugging a lease or a device after the fact: after a
daemon restart, after a crash, or more than 1000 events later. Later, anyone
who needs an audit trail.

Outcome

  • Every business event the daemon emits is also written to an event file of
    its own in the data directory: one JSON line per event, with the same
    fields simlock events shows.
  • The file survives daemon restarts and crashes. Events from before a
    restart are still there afterwards.
  • The file is separate from daemon.log. Operational log lines cannot
    rotate events out, and events cannot rotate log lines out.
  • Its size is bounded by a configurable limit. When the limit is passed, the
    oldest events are dropped and the newest are kept.
  • On a gateway the file holds the relayed fleet events as well as the
    gateway's own.
  • The file is events.jsonl, and the limit is eventLog.rotateBytes,
    default 5 MB.
  • simlock events --since and GET /v1/events?since= reach into the file,
    so they return events from before a restart and from beyond the ring
    buffer.
  • simlock events --since <d> --follow prints that history and then keeps
    streaming live events, with no event missing or printed twice at the join.
  • With no daemon running, simlock events --since reads the file directly
    and does not start one.
  • simlock events --follow without --since behaves as it does today.
  • daemon.log no longer gets its own copies of component.installed and
    device.slimmed. The event file is the durable record.
  • A failure to write the file never fails or delays a lease operation.

Non-goals

  • Turning log lines into events, or merging the logger into the event bus.
    They stay two things.
  • Recording device.exec commands. That is a different audit feature.
  • Tuning for high event volume on a large gateway. Revisit when it is seen
    failing.
  • Sending events off the machine.
  • Retention by age, or more than one rotated generation.

Completion conditions

  • Lease a device, stop the daemon, start it again: the event file still
    holds that lease's lease.granted, with its timestamp.
  • Every line of the file parses as JSON and carries seq, timestamp,
    event, payload and module.
  • With the size limit set small, the file and its rotated generation stay
    within about twice the limit, and the newest events are present.
  • Filling daemon.log past its own limit removes nothing from the event
    file.
  • With the event file unwritable, a lease is still granted and released.
  • Lease a device, restart the daemon, run simlock events --since 1h: the
    lease.granted from before the restart is printed.
  • Stop the daemon and run simlock events --since 1h: the history is
    printed and no daemon is started.
  • Run simlock events --since 1h --follow, then lease a device: the old
    events are printed once, then the new lease.granted appears.
  • CONFIGURATION.md documents the new key. CLI.md and EVENTS.md say where
    the history is kept and how far back --since reaches.

Open questions

None.

Decisions

  • ADR 0006 — Events and the daemon log are two records: every event is persisted to a file of its own, and no fact is copied into daemon.log.

Technical spec

Modules touched

  • src/bus/event-file.ts (new, exported from src/bus/index.ts): the durable half of the bus.
    • EVENT_FILE_NAME = "events.jsonl".
    • readEventFile(filesystem, path, { sinceTs }): returns the envelopes with timestamp > sinceTs, oldest first. It reads path first and path + ".1" second, then drops any envelope seen twice (same seq and timestamp). That order means a rotation between the two reads can repeat a generation but never skip one. A line that is not JSON is skipped. A missing file is empty.
    • EventHistory({ bus, sink?, filesystem, path, logger }):
      • With a sink, it subscribes with subscribeAll and writes JSON.stringify(envelope) per event: the same five fields simlock events prints, nothing added.
      • A write that throws is caught inside the handler. It logs one error line, stops writing for the rest of the run, and never reaches the emitter.
      • replay({ sinceTs }): without sinceTs it returns bus.replay(), as today. With sinceTs it returns readEventFile(...) while the writer is writing, and bus.replay({ sinceTs }) when there is no sink, the writer has stopped, or the read fails.
  • src/ports/logger.ts: NodeFileLogSink is reused as the sink, unchanged. Rotation and the one kept generation are its existing behaviour.
  • src/core/config.ts: eventLog: { rotateBytes: number }, default 5 * 1024 * 1024, validated as a positive integer. Add eventLog to the known top-level keys and to GATEWAY_CONFIG_KEYS.
  • src/contract/schemas.ts: configSchema gains eventLog: z.object({ rotateBytes: z.number() }).optional(). Optional because a client parses config.get output, and a newer gateway reads it from an older worker.
  • src/daemon/main.ts:
    • Right after new EventBus(...) and before the mode branch, open NodeFileLogSink({ path: <dataDirectory>/events.jsonl, maxBytes: config.eventLog.rotateBytes }) in a try. On failure log one error line and continue with no sink. Build one EventHistory and pass it to Dispatcher and, through startGatewayDaemon, to GatewayDispatcher.
    • Delete wireComponentInstallLogging, its call, and the comment above the call.
  • src/daemon/dispatcher.ts, src/gateway/dispatcher.ts: #eventsReplay calls eventHistory.replay(input). Neither reads the bus for replay any more.
  • src/cli/index.ts, runEvents:
    • No --since: replay asks for no sinceTs, as today.
    • --since without --follow: connect with { launch: false }. If nothing is listening (the same test daemon status uses for "stopped"), print environment.readEventFile(sinceTs) and exit 0. Otherwise replay through the daemon.
    • Any --follow: subscribe first and buffer pushes, then replay and print it, then print each buffered push that was not in the replay (same seq and timestamp), then stream. One code path with and without --since.
    • CliEnvironment gains readEventFile(sinceTs), built in buildCliEnvironment from the Filesystem port and the data directory.
  • src/http/app.ts: no code change. GET /v1/events?since= already dispatches events.replay.
  • Docs:
    • docs/CONFIGURATION.md: the eventLog.rotateBytes row, and eventLog.* in both lists of keys a gateway reads.
    • docs/CLI.md: simlock events (where history is kept, how far --since reaches, the daemon-stopped case), the gateway paragraph on the ring buffer, and the data-directory file list.
    • docs/HTTP-API.md: GET /v1/events?since=.
    • docs/EVENTS.md, docs/internal/EVENTS.md: the conventions recap and the gateway relay paragraphs.
    • docs/internal/agent-rules/events.md rule 7: an event is appended to the ring buffer and to the event file.
    • docs/internal/ARCHITECTURE.md: the operational-logging section (drop the wireComponentInstallLogging paragraph, describe the event file), and the gateway config-key list.
    • docs/internal/KNOWN-PITFALLS.md: the install-progress pitfall names a component.install-started log line; correct it.
    • CHANGELOG.md, Unreleased: one entry.
    • docs/internal/adr/0006-events-and-log-are-two-records.md and the ADR index: status becomes Accepted in whichever PR closes the second of Keep business events on disk so the history survives a restart #168 and Daemon log records every request and background failure, and can be followed live #169.

Contract and event changes

  • No operation is added and no operation's shape changes. events.replay with sinceTs now answers from the event file.
  • config.get output gains optional eventLog.rotateBytes. No protocol version bump.
  • Events are written as emitted. Redacting gateway.token from daemon.started is The worker's gateway join token is written in plaintext to the daemon log and the event stream #170, not this PR.
  • No event is added, renamed, or reshaped. The catalog tables in both EVENTS.md files stay as they are; only the prose named above changes.

Rules in play

  • architecture.md 4: the bus module's public surface grows by EventHistory, readEventFile and EVENT_FILE_NAME; nothing reaches into the ring.
  • architecture.md 8: the CLI reads the file only when no daemon answers. It decides nothing else.
  • architecture.md 9: file access through Filesystem and LogSink. The Node sink is built in main.ts only.
  • architecture.md 10: one replay implementation for both dispatchers, one join path in the CLI.
  • architecture.md 13: the comments in main.ts, bus/index.ts and logger.ts that say events are memory-only or that component installs are kept in daemon.log.
  • events.md 5, 7, 8: the writer is an observer and never throws into emit; rule 7's text changes in this PR.
  • safety.md, wire input is a claim: a gateway writes relayed worker payloads to disk. JSON.stringify keeps one event on one line whatever the payload holds.
  • documentation.md: end-user docs name ~/.simlock/events.jsonl, never a path in this repo and never an ADR.
  • testing.md: every title below is a claim; break the code and watch each fail.

Tests

Unit, src/bus/event-file.test.ts:

  • Every emitted event is written as one JSON line equal to its envelope.
  • A sink that throws is logged once, and later events still reach the ring and other subscribers.
  • Replay with sinceTs returns events written by an earlier bus on the same file.
  • Replay with sinceTs returns events the ring has already overwritten.
  • Replay without sinceTs returns the ring and reads no file.
  • Replay with sinceTs answers from the ring when there is no sink, and when the writer has stopped.
  • The rotated generation is returned before the current file.
  • A generation that shows up in both reads is returned once.
  • A line that is not JSON is skipped and the lines around it are returned.

Unit, src/core/config.test.ts:

  • eventLog.rotateBytes defaults to 5 MiB and rejects zero and negative values.
  • A gateway config with eventLog.rotateBytes raises no unknown-key warning.

Unit, src/daemon/dispatcher.test.ts, src/gateway/dispatcher.test.ts:

  • events.replay with sinceTs returns what the event history returns.

Unit, src/daemon/main.test.ts (the wireComponentInstallLogging tests are deleted):

  • A daemon whose event file cannot be opened starts, and logs one error line.
  • component.installed and device.slimmed write no line to the daemon log.

Unit, src/cli/index.test.ts:

  • events --since with nothing listening prints the file's events and launches no daemon.
  • events --since with a daemon listening replays through the daemon.
  • events --follow prints an event emitted between the subscribe and the replay exactly once.
  • events --follow without --since asks for no sinceTs.

E2e, fast lane, e2e/event-history.test.ts:

  • A lease granted before a daemon restart is printed by simlock events --since 1h after it.
  • With the daemon stopped, simlock events --since 1h prints the history and the daemon stays stopped.
  • With eventLog.rotateBytes small, events.jsonl plus events.jsonl.1 stay under twice the limit and hold the newest event.
  • With log.rotateBytes small and daemon.log rotated, every event emitted is still in the event file.
  • With a directory at the event file's path, a lease is granted and released.

E2e, fast lane, e2e/http-api.test.ts:

  • GET /v1/events?since=1h returns an event from before a daemon restart.

Written by an agent.

Activity

  1. added
    feature:spec
    on Oct 1, 2026
  2. V3RON commented on Oct 1, 2026

    @V3RON
    ContributorAuthor

    Spec updated: Decisions and Technical spec added.

    Written by an agent.

  3. added
    feature:ready
    and removed
    feature:spec
    on Oct 1, 2026
  4. self-assigned this
    on Oct 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

feature:ready

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions