Skip to content
4 changes: 4 additions & 0 deletions docs/CLI.md
Original file line number Diff line number Diff line change
Expand Up @@ -2637,6 +2637,10 @@ token again with `simlock --gateway token create --role worker` and set it as
that worker's `gateway.token`: a worker still holding an old token is refused
with 401 and keeps redialling.

A gateway keeps its drained workers in `state.db` too, and does not start while
a `workers.json` sits in its folder. Nothing is imported from it: remove it, and
drain the workers again with `simlock worker drain`.

A daemon also does not start when `state.db` is damaged, when another Simlock
daemon holds it locked for more than five seconds, or when it was written by a
newer Simlock (the message names the file and what to do). The reason is
Expand Down
5 changes: 2 additions & 3 deletions docs/CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -197,9 +197,8 @@ uplink upgrades from, so a gateway without it is a process nothing can reach
and no worker can join — quietly overriding the operator's value would be
worse than refusing it.

The gateway keeps one small file of its own beside `state.db`:
`workers.json`, owner-only, holding the ids of workers an operator has
drained. Drain is a decision about a machine rather than something the machine
The gateway keeps the ids of workers an operator has drained in its
`state.db`. Drain is a decision about a machine rather than something the machine
reports, so it has to survive both the worker's reconnect and a gateway
restart; every other part of a worker view is rebuilt from the worker itself.

Expand Down
2 changes: 1 addition & 1 deletion docs/internal/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ worker daemon ── uplink (WebSocket to /v1/uplink, worker dials) ──┘
works against either mode unchanged.
- State lives on the worker (`state.db`, its registry tables written only by core's
`Registry`). A gateway keeps only its tokens, its instance id and its drained-worker set on
disk; everything else is rebuilt from the workers that reconnect.
disk (`state.db`); everything else is rebuilt from the workers that reconnect.

## Modules

Expand Down
2 changes: 1 addition & 1 deletion docs/internal/flows/startup.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ platform runs the deferred reclaim (step 21.2).

1. Instance identity — `instance.json`.
2. `FleetLeaseIndex`, routing policy,
`GatewayService` (`workers.json`), `FleetLeaseCoordinator`, `DaemonServer`
`GatewayService` (drained workers in `state.db`), `FleetLeaseCoordinator`, `DaemonServer`
with `GatewayDispatcher`. No registry, drivers, reaper or health monitor.
3. `DaemonServer.start`: claim → host load → `admin.token` → converge starts →
the event history starts → HTTP starts (uplink listener on the same server).
Expand Down
20 changes: 17 additions & 3 deletions e2e/console/fixtures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,13 +117,27 @@ export async function startDaemon(
await waitFor(() => !existsSync(socketPath), { timeout: 10_000 }).catch(() => undefined);
};
const start = async () => {
const readLog = () => readFile(join(dataDirectory, "daemon.log"), "utf8").catch(() => "");
const before = (await readLog()).length;
const started = await cli([...gatewayFlag, "daemon", "start"], env, { timeout: 30_000 });
if (started.code === 0) return;
// why: `daemon start` exits 0 once the daemon answers from its socket, which can come before
// the daemon fails to bind its HTTP port and stops (#553). So a clean exit is not yet a start:
// wait for this start's own "HTTP gateway listening" or `EADDRINUSE` line (the log keeps the
// earlier starts' lines), and fail on the latter.
if (started.code === 0) {
await waitFor(
async () => {
const added = (await readLog()).slice(before);
return added.includes("EADDRINUSE") || added.includes('"HTTP gateway listening"');
},
{ label: "the daemon's HTTP listener" },
);
if (!(await readLog()).slice(before).includes("EADDRINUSE")) return;
}
// why: a failed start reports only what the CLI saw while polling the socket, and `dispose`
// deletes this home with `daemon.log` — the only record of the cause the daemon itself wrote.
// Read the tail here, before any caller's catch reaches `dispose`, and fail with both.
const log = await readFile(join(dataDirectory, "daemon.log"), "utf8").catch(() => "");
const tail = log.split("\n").slice(-20).join("\n");
const tail = (await readLog()).split("\n").slice(-20).join("\n");
expect(started.code, `daemon start failed: ${started.stderr}\n${tail}`).toBe(0);
};
const dispose = async () => {
Expand Down
15 changes: 10 additions & 5 deletions e2e/helpers/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -279,16 +279,21 @@ async function buildEnv(
expectEvents: (names, expectOptions) => expectEvents(env, names, expectOptions, gatewayFlag),
async startDaemon() {
const started = await cli([...gatewayFlag, "daemon", "start"], env);
// `daemon start` exits once the daemon answers `status.get`, which it does from its socket
// why: `daemon start` exits once the daemon answers `status.get`, which it does from its socket
// claim on, but the daemon writes `admin.token` only after that claim (ADR 0003 §5). A CLI
// that reads the file before it lands connects as agent, so an admin command run next
// (`token create`, the teardown's `daemon stop`) fails FORBIDDEN. After a first start,
// waiting for the file orders later CLI calls after the write; after a restart the previous
// run's file may still be there and passes the wait at once.
// run's file may still be there and passes the wait at once. A daemon that stops right after
// its claim (its HTTP port taken, `withHttpDaemon`) removes the file with its socket
// (`AdminSecretManager#remove`) before this poll can see it, so a gone socket ends the wait too.
if (started.code === 0) {
await waitFor(() => existsSync(join(dataDirectory, "admin.token")), {
label: "admin.token written",
});
await waitFor(
() => existsSync(join(dataDirectory, "admin.token")) || !existsSync(socketPath),
{
label: "admin.token written",
},
);
}
return started;
},
Expand Down
2 changes: 1 addition & 1 deletion src/daemon/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ The role (`StartDaemonOptions.role`; the entry reads it from `--gateway` through
when `gateway.url` and `gateway.token` are both set → `DaemonServer` with `Dispatcher`.
HTTP starts only when `http.enabled`.
- **Gateway** — instance id → `TokenStore`, `AdminSecretManager` → `FleetLeaseIndex`
(requester prefix `gw:<instanceId>:`) → `GatewayService` (uplink listener, `workers.json`)
(requester prefix `gw:<instanceId>:`) → `GatewayService` (uplink listener, drained workers in `state.db`)
→ `FleetLeaseCoordinator` → `createAlerts` when `gateway.alerts.destinations` is not empty
(before `start()`; stopped first in `stopAuxiliary`) → `DaemonServer` with `GatewayDispatcher`.
HTTP always starts; the uplink upgrades on the same listener.
Expand Down
18 changes: 13 additions & 5 deletions src/daemon/gateway-fleet.e2e.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ describe("gateway fleet smoke (ADR 0005 §35)", () => {
/**
* why: #119: a gateway that can be stopped and started again *as the same gateway* -- the same
* `SIMLOCK_HOME` directory and the same `Filesystem` instance backing it, which is what
* `instance.json`, `workers.json` and the `tokens` table of `state.db` actually persisting across the restart depends
* `instance.json` and the `tokens` and `drained_workers` tables of `state.db` actually persisting across the restart depends
* on (ADR §30, §8a). `startGateway` above deliberately hands each call a fresh
* `MemoryFilesystem`, which is right for a test that starts one gateway once; this one needs
* the state to survive the restart it is about to perform.
Expand Down Expand Up @@ -401,7 +401,7 @@ describe("gateway fleet smoke (ADR 0005 §35)", () => {
* scripted uplink `fleet-coordinator.test.ts` and `dispatcher.test.ts` already cover each
* piece of in isolation (including §27a's ownership round trip, pinned there too). What only
* this shape of test can catch: the gateway's own persisted state (`instance.json`,
* `workers.json`, and the join tokens in `state.db`) actually surviving a real `stop()`/`startDaemon()` cycle, and
* the drained workers and join tokens in `state.db`) actually surviving a real `stop()`/`startDaemon()` cycle, and
* a real worker's own `GatewayUplink` actually redialling and reconnecting on its own backoff
* once the new process is listening again.
*/
Expand Down Expand Up @@ -523,8 +523,8 @@ describe("gateway fleet smoke (ADR 0005 §35)", () => {
{ timeout: 15_000 },
);

// C1 (round 1 review, #119): this is the assertion this test's own header comment promises
// and never made -- that `workers.json` actually survived the restart. A drained-but-absent
// why: C1 (round 1 review, #119): this is the assertion this test's own header comment promises
// and never made -- that the drain actually survived the restart. A drained-but-absent
// worker has no `WorkerView` at all (a view is only ever built by `connected()`/`refresh()`,
// never synthesized from the persisted drain set on its own), so the only way to observe the
// restarted gateway's own on-disk state through the same `worker.list` the rest of this test
Expand All @@ -533,7 +533,7 @@ describe("gateway fleet smoke (ADR 0005 §35)", () => {
// had before (so its `instance.json`, and therefore its `workerId`, survives too), exactly as
// `restartedGateway` reuses the gateway's own. Its view is built from nothing but this fresh
// process's own `connected()` call plus whatever `restartedGateway` loaded from
// `workers.json` at startup -- there is no other way `drained` could come back `true` here.
// `state.db` at startup -- there is no other way `drained` could come back `true` here.
const restartedWorkerB = await startWorker({
label: "worker-b",
model: "Pixel-B",
Expand All @@ -551,6 +551,14 @@ describe("gateway fleet smoke (ADR 0005 §35)", () => {
},
{ timeout: 15_000 },
);
// why: `drained: true` is the flag; this proves the restarted gateway also keeps routing off the worker.
await expect(
restartedGateway.dispatch(
"lease.request",
{ model: "Pixel-B", platform: "android", noWait: true },
agentSession({ principal: "someone-else" }),
),
).rejects.toMatchObject({ code: "NO_CAPACITY" });
await restartedWorkerB.daemon.stop("test");
daemons.splice(daemons.indexOf(restartedWorkerB.daemon), 1);

Expand Down
15 changes: 11 additions & 4 deletions src/daemon/main.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3666,18 +3666,25 @@ describe("startDaemon state.db", () => {
it.each([
[
"worker",
"tokens.json",
"with the older Simlock, release every lease and run `simlock nuke --delete-devices`; then remove <path> and start again.",
],
[
"gateway",
"tokens.json",
"remove <path> 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.",
],
[
"gateway",
"workers.json",
"remove <path> 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.",
],
] as const)(
"a %s started with tokens.json in its folder refuses with the old-file message and its step",
async (role, step) => {
const directory = await mkdtemp(join(tmpdir(), "simlock-main-old-tokens-"));
"a %s started with %s in its folder refuses with the old-file message and its step",
async (role, file, step) => {
const directory = await mkdtemp(join(tmpdir(), "simlock-main-old-file-"));
temporaryDirectories.push(directory);
const oldFile = join(directory, "tokens.json");
const oldFile = join(directory, file);
await writeFile(oldFile, "[]", "utf8");

await expect(start({ dataDirectory: directory, role })).rejects.toMatchObject({
Expand Down
13 changes: 5 additions & 8 deletions src/daemon/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,8 @@ import {
} from "../ports/index.js";
import {
createRoutingPolicy,
FileDrainStore,
StateDrainStore,
drainedWorkersOwner,
FleetLeaseCoordinator,
FleetLeaseIndex,
GatewayDispatcher,
Expand Down Expand Up @@ -246,10 +247,10 @@ async function composeDaemon(
// why: node:sqlite writes the real disk, so the state never goes through a daemon's injected filesystem
filesystem: new NodeFilesystem(),
logger: logger.child("state"),
oldFiles: role === "gateway" ? ["tokens.json"] : ["state.json", "tokens.json"],
oldFiles: role === "gateway" ? ["tokens.json", "workers.json"] : ["state.json", "tokens.json"],
owners:
role === "gateway"
? [tokensOwner]
? [tokensOwner, drainedWorkersOwner]
: [registryOwner, tokensOwner, ...new Set(deviceDataTables.values())],
sqlite: new NodeSqliteOpener(),
upgradeStep: role === "gateway" ? GATEWAY_UPGRADE_STEP : WORKER_UPGRADE_STEP,
Expand Down Expand Up @@ -797,11 +798,7 @@ async function startGatewayDaemon(options: GatewayDaemonOptions): Promise<Daemon
// close every uplink it authorized (`GatewayService#closeLinksForToken`, wired below).
authenticate: (credential) => auth.authenticateUplink(credential),
clock,
drainStore: new FileDrainStore({
filesystem,
logger: logger.child("gateway"),
path: join(dataDirectory, "workers.json"),
}),
drainStore: new StateDrainStore({ database: state.database, logger: logger.child("gateway") }),
eventBus,
// ADR 0005 §15: this gateway's own cap, compared against every connected worker's own
// reported one so the registry can warn when a worker's is lower.
Expand Down
4 changes: 2 additions & 2 deletions src/gateway/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ Flows: [device selection](../../docs/internal/flows/device-selection.md), [devic
| `service.ts` | `GatewayService`: uplink listener, one `WorkerLink` per worker, 30 s tick |
| `worker-link.ts` | One uplink, gateway side: admin client, view reads, event relay |
| `worker-registry.ts` | `WorkerRegistry`: views, drain, retention, `worker.*` events |
| `drain-store.ts` | `FileDrainStore`: `workers.json`, the drained ids |
| `drain-store.ts` | `StateDrainStore`: the drained ids in the `drained_workers` table of `state.db`; `drainedWorkersOwner` |
| `dispatcher.ts` | `GatewayDispatcher`: the contract's handlers, answered from the fleet; `alerts.test` through the `testDestination` option |
| `fleet-coordinator.ts` | `FleetLeaseCoordinator`: admit, dispatch, retry, forward renew/release/exec |
| `queue.ts` | `FleetQueue`: leasing's `WaitQueue`, two lines |
Expand Down Expand Up @@ -119,7 +119,7 @@ views. `worker.install-component` fans out. `nuke.run`, `cleanup.run`, `doctor.r
| Link: channels per side, accept, stall | 64, 30 s, 60 s | `../link/` constants |
| Request records | 10 000, 10 min | `lease.maxRequestRecords`, `lease.requestRetentionMs` |

Persisted: `workers.json` (drained ids), the `tokens` table of `state.db`, `instance.json`. Nothing else.
Persisted: the `drained_workers` and `tokens` tables of `state.db`, `instance.json`. Nothing else.

## Rules

Expand Down
Loading
Loading