Skip to content

Daemon state stores in SQLite (state.db) #754

Closed
5 of 5 issues completed
Closed

Description

@V3RON

Request: #624

Problem

The daemon keeps its state in JSON files: state.json (devices, leases, lease requests), tokens.json, workers.json and the gateway's drain list. Every registry change rewrites the whole state.json. Stores that are read, changed and written back can lose a concurrent change (#616 was one).

Who it is for

An operator who runs a Simlock worker or gateway, and the agents that lease through it. A busy worker keeps up to 10,000 lease-request records, and today every renew rewrites all of them.

Outcome

  • A change writes only what changed. A renew writes one lease, whatever the number of records.
  • No change is lost when two arrive at once.
  • After a restart, a worker still has its devices, leases, lease requests, components and tokens, and a gateway still has its tokens and drained workers.
  • A daemon whose state file is damaged, or was written by a newer Simlock, refuses to start and says why. So does a daemon that finds a JSON state file from an older Simlock.
  • When the CLI or MCP server started that daemon, it prints the reason at once, in place of a 20 s timeout.

How it works for the user

flowchart TD
  S[simlock command auto-starts the daemon] --> O{old JSON file in the folder?}
  O -->|yes| R[daemon refuses: names the file and the upgrade step]
  O -->|no| D{state.db opens and checks ok?}
  D -->|damaged| R2[daemon refuses: names the file]
  D -->|newer version| R3[daemon refuses: names the version]
  D -->|ok| U[daemon starts with its state]
  R --> C[CLI prints the reason, exit 1]
  R2 --> C
  R3 --> C
Loading

Upgrading a worker that still has state.json. The CLI prints errors as one JSON line on stderr, as today:

# before (today): the new version reads state.json and starts
$ simlock status
Daemon: running (worker)

# after
$ simlock status
{"error":{"code":"DAEMON_STARTUP_FAILED","message":"The daemon could not start: Found /Users/me/.simlock/state.json, which this Simlock no longer reads. To upgrade: with the older Simlock, release every lease and run `simlock nuke --delete-devices`; then remove /Users/me/.simlock/state.json and start again. See \"Breaking: state moves to state.db\" in docs/CLI.md."}}
$ echo $?
1

Any start refusal, e.g. a damaged state.db:

# today, after 20 s (any start failure)
{"error":{"code":"DAEMON_STARTUP_FAILED","message":"Timed out starting simlock daemon: <socket error>"}}
# after, as soon as the daemon exits
{"error":{"code":"DAEMON_STARTUP_FAILED","message":"The daemon could not start: /Users/me/.simlock/state.db is damaged (quick_check: <first row>). Move it away to start with empty state; every device and lease it held is forgotten."}}

Examples

Folder holds at start Today After
nothing starts empty starts empty, creates state.db
state.db only, healthy — starts with its state
state.json (worker) loads it refuses: names state.json
tokens.json (worker or gateway) reads it per request refuses: names tokens.json
workers.json (gateway) loads drains refuses: names workers.json
state.json with bad JSON refuses (Invalid JSON in registry state) refuses: names state.json (old file)
state.db failing quick_check — refuses: damaged
state.db written by a newer Simlock — refuses: names the owner and the version
state.db locked by another process past 5 s — refuses: locked

What could go wrong

  • An operator upgrades without the upgrade step and loses track of devices on disk: the daemon refuses until the old file is removed, and the message says what to run first. Likely once per host.
  • Someone downgrades without the documented step: the older Simlock starts empty and leaves devices behind (simlock doctor --purge-orphans removes them). Unlikely.
  • A bug in a table mapping drops a field on restart: a lease or device comes back changed. Each field has a restart test.

Words used

  • state.db: the daemon's own SQLite file, in its folder: ~/.simlock/state.db for a worker, ~/.simlock/gateway/state.db for a gateway.
  • owner: the module that creates and changes a set of tables, e.g. core's registry owns devices and leases; the iOS driver owns ios_device_data.
  • schema version: one number per owner, kept in state.db, raised by each migration.
  • old file: state.json, tokens.json or workers.json, the JSON files this feature replaces.
  • replay: a repeat of a lease.request with the same Idempotency-Key, answered with the first answer.

Non-goals

  • Importing the old JSON files. The operator runs the upgrade step.
  • Protecting a downgrade in code. It is documented only.
  • Moving instance.json, adb-server.json, config.json, admin.token, daemon.log or history.db.
  • The gateway's in-memory lease requests and lease index: they stay in memory.
  • Any change to the contract or to events.

Completion conditions

  • A worker restarted with fake drivers keeps its devices, leases, lease requests, components and tokens, field for field.
  • A gateway restarted keeps its tokens and drained workers.
  • A renew changes one row of state.db, with 1,000 lease-request records stored.
  • A worker or gateway refuses to start with each old file present, with a damaged state.db, and with a newer schema version, and simlock status prints the reason at once, exit 1.
  • docs/CLI.md has the upgrade and downgrade steps, and no user doc names state.json, tokens.json or workers.json as a live file.

Open questions

Decisions

Shared values

Value or state Rule Written by Read by Source
state.db path <data directory>/state.db: <root>/state.db (worker), <root>/gateway/state.db (gateway) task 1 tasks 1–4 ADR 0036 §1; src/daemon/main.ts:174 (data directory today)
The state module src/state/: openStateDatabase(options) returns StateDatabase (database, transaction(work), close()); opens before createAuth, both roles task 1 tasks 2–4 ADR 0036 §1, §5; src/daemon/main.ts:222
SqliteSchemaOwner { name, version, migrations } in src/ports/sqlite.ts; migrations[i] moves version i to i+1 (0 = no tables yet) task 1 tasks 2–4 ADR 0036 §2
schema_versions table one row per owner: owner (text, key), version (integer). Written only by the state module task 1 tasks 1–4 ADR 0036 §2, §5
Owner names registry (task 1), fake-device-data (task 1, unit tests; e2e's fake module defines its own e2e-fake-device-data with the same columns, since e2e may import only dist/<module>/index.js), ios-device-data, android-device-data (task 2), tokens (task 3), drained-workers (task 4) each task its own the state module ADR 0036 §2
Owner lists worker: registry, the device-data owners, tokens; gateway: tokens, drained-workers task 1 builds both lists; tasks 2–4 add the state module ADR 0036 §1
Old-file list worker: state.json (task 1), tokens.json (task 3); gateway: tokens.json (task 3), workers.json (task 4) task 1 builds the check; tasks 3, 4 add names the state module ADR 0036 §5
DeviceDataTable core type in src/core/driver.ts: a SqliteSchemaOwner plus write(database, deviceId, driverData) and read(database, deviceId). The device-data map is a ReadonlyMap<Platform, DeviceDataTable> everywhere: StartDaemonOptions.deviceDataTables, the SIMLOCK_DRIVERS_MODULE export deviceDataTables, and productionDeviceDataTables(). One table may serve several platforms (the fake does); it is one owner. resolveDeviceDataTables picks the map once, and startDaemon passes it to the open and Registry.load task 1 task 2 ADR 0036 §2, §3
Old-file message Found <path>, which this Simlock no longer reads. To upgrade: <step> See "Breaking: state moves to state.db" in docs/CLI.md. Worker <step>: with the older Simlock, release every lease and run \simlock nuke --delete-devices`; then remove and start again.Gateway: remove and start again; then create each worker's join token again with `simlock --gateway token create --role worker`, set it as that worker's `gateway.token`, and drain workers again.(a gateway refusesnuke.run, src/gateway/dispatcher.ts:238`) task 1 (both steps, passed per role) tasks 3, 4, 5 ADR 0036 §5
Damage message <path> is damaged (<detail>). Move it away to start with empty state; every device and lease it held is forgotten. — <detail> is quick_check: <first row> or open: <error message> task 1 task 5 ADR 0036 §5
Lock message <path> is locked by another process. Stop the other Simlock daemon using it, then start again. task 1 task 5 ADR 0036 §5
Version messages <owner> in <path> is at version <stored>; this Simlock knows up to <known>. Upgrade Simlock, or move state.db away. and <owner> in <path> could not move from version <n> to <n+1>: <message>. Upgrade Simlock, or move state.db away. task 1 tasks 2–5 src/history/versions.ts:27, :38 (same wording for history.db)
No node:sqlite node:sqlite is not available; Simlock needs Node 22.13 or later. task 1 task 5 src/history/index.ts:296-298
A refusal reaches the user thrown from startDaemon → daemon.log line Daemon failed to start with fields.message, exit 1 task 1 (throws) task 5 (prints The daemon could not start: <message>) src/daemon/main.ts:1486-1488, :1503-1506
docs/CLI.md upgrade section heading ### Breaking: state moves to state.db under simlock daemon task 1 writes it; task 3 adds tokens, task 4 adds drains the old-file message docs/CLI.md:1449 (the "Breaking in 0.3.0" precedent)

Tasks

flowchart LR
  T1["#761 state.db + registry"] --> T2["#757 iOS and Android tables"]
  T1 --> T3["#758 tokens"]
  T3 --> T4["#759 drained workers"]
  T1 --> T5["#760 CLI shows start error"]
Loading

"Task 1" to "task 5" in the bodies and in Shared values are, in order: #761, #757, #758, #759, #760.

Completion conditions:

Open work in the same area:

Written by an agent.

Sub-issues

Sub-issues

5 of 5 Issues completed
Loading 5 sub-issues

Activity

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

    @V3RON
    ContributorAuthor

    Spec updated: all business sections, Decisions, Shared values and Tasks (#761, #757, #758, #759, #760) added.

    Written by an agent.

  3. added
    feature:planned
    and removed
    feature:spec
    on Oct 20, 2026
  4. V3RON commented on Oct 20, 2026

    @V3RON
    ContributorAuthor

    Delivery run

    Merged: none (the stack merges as one, and it waits on #761)
    Parked: #761: fix commit fc5076f's R15 test change is unreviewed because the round cap ran out; the stack #755 → #775 → #783 → #784 → #785 → #786 is ready otherwise
    Waiting: #757, #758, #759, #760: reviews passed, in the stack, wait on #761
    Decided: ADR 0036 (#755): replay answers the current device (narrows 0019 §4); one fake_device_data table; a socket probe before state.db opens; the docs say upgrading loses component records

    Written by an agent.

  5. github-actions commented on Oct 20, 2026

    @github-actions
    Contributor

    All 5 sub-issues are closed. If the completion conditions hold on main, close this feature and flip its ADRs to Accepted.

  6. github-actions commented on Oct 20, 2026

    @github-actions
    Contributor

    All 5 sub-issues are closed. If the completion conditions hold on main, close this feature and flip its ADRs to Accepted.

  7. github-actions commented on Oct 20, 2026

    @github-actions
    Contributor

    All 5 sub-issues are closed. If the completion conditions hold on main, close this feature and flip its ADRs to Accepted.

  8. github-actions commented on Oct 20, 2026

    @github-actions
    Contributor

    All 5 sub-issues are closed. If the completion conditions hold on main, close this feature and flip its ADRs to Accepted.

  9. github-actions commented on Oct 20, 2026

    @github-actions
    Contributor

    All 5 sub-issues are closed. If the completion conditions hold on main, close this feature and flip its ADRs to Accepted.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature:planned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions