Repository navigation
Description
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
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-orphansremoves 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.dbfor a worker,~/.simlock/gateway/state.dbfor a gateway. - owner: the module that creates and changes a set of tables, e.g. core's registry owns
devicesandleases; the iOS driver ownsios_device_data. - schema version: one number per owner, kept in
state.db, raised by each migration. - old file:
state.json,tokens.jsonorworkers.json, the JSON files this feature replaces. - replay: a repeat of a
lease.requestwith the sameIdempotency-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.logorhistory.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, andsimlock statusprints the reason at once, exit 1. docs/CLI.mdhas the upgrade and downgrade steps, and no user doc namesstate.json,tokens.jsonorworkers.jsonas a live file.
Open questions
Decisions
- ADR 0036 — Daemon state is a SQLite database, and each owner keeps its own tables (PR docs(adr): 0036 daemon state is a SQLite database, and each owner keeps its own tables #755): one
state.dbper daemon, real columns, per-driver device tables, one transaction per change, refuse on old files, damage and newer versions.
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"]
"Task 1" to "task 5" in the bodies and in Shared values are, in order: #761, #757, #758, #759, #760.
- state.db opens and checks at start, and the worker's registry lives in it #761 state.db opens and checks at start, and the worker's registry lives in it — a worker keeps devices, leases, requests and components in
state.db, and refuses an oldstate.json, a damaged file or a newer version. Risk: a worker forgets or changes a record after a restart. - iOS and Android device data in their own state.db tables #757 iOS and Android device data in their own state.db tables — real simulators and emulators keep their driver data across a restart. Risk: a device comes back unreachable or slimmed again.
- Tokens live in state.db on both daemon kinds #758 Tokens live in state.db on both daemon kinds — tokens survive in
state.db;tokens.jsonrefuses start. Risk: a token stops working, or a revoked one still works. - The gateway's drained workers live in state.db #759 The gateway's drained workers live in state.db — a drain survives a gateway restart;
workers.jsonrefuses start. Risk: a drained worker takes requests again. - The CLI and MCP show why an auto-started daemon did not start #760 The CLI and MCP show why an auto-started daemon did not start — the refusal shows at once. Risk: a stale error, or a failure although a daemon came up.
Completion conditions:
- Worker keeps its state across a restart: state.db opens and checks at start, and the worker's registry lives in it #761 (restart tests), iOS and Android device data in their own state.db tables #757 (real tables), Tokens live in state.db on both daemon kinds #758 (tokens).
- Gateway keeps tokens and drains: Tokens live in state.db on both daemon kinds #758, The gateway's drained workers live in state.db #759.
- A renew changes one row: state.db opens and checks at start, and the worker's registry lives in it #761.
- Refusals and
simlock statusprinting them at once: state.db opens and checks at start, and the worker's registry lives in it #761, Tokens live in state.db on both daemon kinds #758, The gateway's drained workers live in state.db #759 (each old file, damage, version), The CLI and MCP show why an auto-started daemon did not start #760 (the CLI, with an e2e run of the real CLI against a worker folder holdingstate.json). docs/CLI.mdupgrade and downgrade steps, no live JSON file named: state.db opens and checks at start, and the worker's registry lives in it #761 (section), Tokens live in state.db on both daemon kinds #758, The gateway's drained workers live in state.db #759 (their files).
Open work in the same area:
- Every device shape says when the device entered its state #318 / draft PR feat(core): every device shape says when the device entered its state #324 (feature Events have an identity, and a device transition is an event #314) adds a device field in
src/core/registry.ts. No Depends on: it istask:blocked. Whichever lands second adds the field as adevicescolumn. - Every device state change is one device.state-changed event #320 (task:draft, feature Events have an identity, and a device transition is an event #314) adds a step to the registry's
#commit"after the state file is written", the function state.db opens and checks at start, and the worker's registry lives in it #761 rewrites. No Depends on: it waits on Every device shape says when the device entered its state #318. Whichever lands second puts that step after the transaction returns, where memory is updated. - Every action leaves a trace of who did it #703 (request, audit trail) and Review fleet reconciliation: what breaks while a gateway rebuilds its view #412 (feature:spec, fleet reconciliation) touch neither these tables nor these files yet. None.
- Operational metrics kept over hours and shown in the console #623's history (merged):
src/history/database.tshelpers move tosrc/ports/sqlite.tsin state.db opens and checks at start, and the worker's registry lives in it #761. No open task of Operational metrics kept over hours and shown in the console #623 touches them.
Written by an agent.
Activity
V3RON commentedon Oct 20, 2026
Spec updated: all business sections, Decisions, Shared values and Tasks (#761, #757, #758, #759, #760) added.
Written by an agent.
V3RON commentedon Oct 20, 2026
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.
github-actions commentedon Oct 20, 2026
All 5 sub-issues are closed. If the completion conditions hold on
main, close this feature and flip its ADRs to Accepted.github-actions commentedon Oct 20, 2026
All 5 sub-issues are closed. If the completion conditions hold on
main, close this feature and flip its ADRs to Accepted.docs(adr): 0036 daemon state is a SQLite database, and each owner kee…
github-actions commentedon Oct 20, 2026
All 5 sub-issues are closed. If the completion conditions hold on
main, close this feature and flip its ADRs to Accepted.github-actions commentedon Oct 20, 2026
All 5 sub-issues are closed. If the completion conditions hold on
main, close this feature and flip its ADRs to Accepted.github-actions commentedon Oct 20, 2026
All 5 sub-issues are closed. If the completion conditions hold on
main, close this feature and flip its ADRs to Accepted.feat(gateway): the gateway's drained workers live in state.db (#786)