From c3d396dcd9b8de044d800edfb008d71e8e292f16 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Sun, 4 Oct 2026 16:48:58 +0200 Subject: [PATCH 1/3] test: every device shape says when the device entered its state (#318) Red: 29 failing on stateEnteredAt assertions; the tests call transition(record, to, at), which does not typecheck until the signature changes. --- e2e/device-state-entered.test.ts | 48 ++++++++++ src/contract/schemas.test.ts | 50 ++++++++++ src/core/doctor.test.ts | 38 ++++++++ src/core/domain.test.ts | 91 +++++++++++------- src/core/registry.test.ts | 157 +++++++++++++++++++++++++++++++ src/daemon/server.test.ts | 65 +++++++++++++ 6 files changed, 414 insertions(+), 35 deletions(-) create mode 100644 e2e/device-state-entered.test.ts diff --git a/e2e/device-state-entered.test.ts b/e2e/device-state-entered.test.ts new file mode 100644 index 000000000..7fa3db3b1 --- /dev/null +++ b/e2e/device-state-entered.test.ts @@ -0,0 +1,48 @@ +import { describe, expect, it } from "vitest"; + +import { waitForDeviceState, withDaemon } from "./helpers/index.js"; + +interface Device { + readonly id: string; + readonly state: string; + readonly stateEnteredAt?: number; +} + +describe("when a device entered its state", () => { + it("simlock status --json and simlock list --devices show stateEnteredAt for a ready device", async () => { + const env = await withDaemon(); + await env.driverScript.set({ + ios: { knownModels: ["iPhone 16"], availableOsVersions: ["18.4"] }, + }); + const held = env.cliBackground([ + "lease", + "--platform", + "ios", + "--device", + "iPhone 16", + "--os", + "18.4", + "--agent-id", + "state-entered", + ]); + const grant = JSON.parse(await held.firstStdoutLine()) as { + lease: { id: string }; + device: { driverDeviceId: string }; + }; + expect((await env.cli(["release", grant.lease.id])).code).toBe(0); + await waitForDeviceState(env, grant.device.driverDeviceId, "ready"); + held.kill("SIGKILL"); + await held.waitForExit(15_000).catch(() => undefined); + + const status = await env.cli(["status", "--json"]); + const list = await env.cli(["list", "--devices"]); + + expect(status.code).toBe(0); + expect(list.code).toBe(0); + for (const devices of [(status.json as { devices: Device[] }).devices, list.json as Device[]]) { + expect(devices).toHaveLength(1); + expect(devices[0]?.state).toBe("ready"); + expect(typeof devices[0]?.stateEnteredAt).toBe("number"); + } + }); +}); diff --git a/src/contract/schemas.test.ts b/src/contract/schemas.test.ts index 0a86f6bf1..debe9b668 100644 --- a/src/contract/schemas.test.ts +++ b/src/contract/schemas.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "vitest"; +import { OPERATIONS } from "./operations.js"; import { deviceRecordSchema, fitHostFacts, @@ -360,3 +361,52 @@ describe("leaseRequestRecordSchema", () => { expect(grantedDeviceSchema.safeParse(device).success).toBe(false); }); }); + +describe("stateEnteredAt on the wire", () => { + const device = { + id: "device-1", + mode: "full", + spec: { platform: "ios", model: "iPhone 17 Pro", osVersion: "26.5" }, + state: "ready", + }; + + it("the status.get and list.get output schemas keep stateEnteredAt on a device that has one and omit it on one that does not", () => { + const known = { ...device, stateEnteredAt: 1_234 }; + const status = OPERATIONS["status.get"].output; + + expect(statusDeviceSchema.parse(known)).toHaveProperty("stateEnteredAt", 1_234); + expect(statusDeviceSchema.parse(device)).not.toHaveProperty("stateEnteredAt"); + expect( + deviceRecordSchema.parse({ + ...known, + createdAt: 1, + driverData: {}, + driverDeviceId: "SIM-1", + }), + ).toHaveProperty("stateEnteredAt", 1_234); + expect(OPERATIONS["list.get"].output.parse([known])).toEqual([known]); + expect(OPERATIONS["list.get"].output.parse([device])).toEqual([device]); + expect(status.shape.devices.parse([known])).toEqual([known]); + }); + + it("a gateway's GET /v1/devices and GET /v1/workers carry a worker device's stateEnteredAt", () => { + const known = { ...device, stateEnteredAt: 1_234 }; + const list = OPERATIONS["list.get"].output.parse([{ ...known, workerId: "wrk_1" }]); + const workers = OPERATIONS["worker.list"].output.parse({ + workers: [ + { + catalog: [], + connection: "connected", + devices: [known, device], + drained: false, + id: "wrk_1", + lastSeenAt: 1, + leases: [], + }, + ], + }); + + expect(list).toEqual([{ ...known, workerId: "wrk_1" }]); + expect(workers.workers[0]?.devices).toEqual([known, device]); + }); +}); diff --git a/src/core/doctor.test.ts b/src/core/doctor.test.ts index e9ec4f6f1..a05126461 100644 --- a/src/core/doctor.test.ts +++ b/src/core/doctor.test.ts @@ -7,6 +7,7 @@ import type { Config } from "./config.js"; import { DeviceOperationClaims } from "./device-operation-claims.js"; import { Doctor, type DoctorFinding, type DoctorReport, isStalledTransition } from "./doctor.js"; import { DriverCatalog } from "./driver-catalog.js"; +import type { DeviceState } from "./domain.js"; import type { DriverRejection, PrerequisiteCheck } from "./driver.js"; import { FakeDriver } from "./fake-driver.js"; import { LeaseEngine } from "./lease-engine.js"; @@ -790,6 +791,43 @@ describe("Doctor", () => { expect(stalled()).toBe(true); }); + it("a provisioning or reclaiming device past its threshold is stalled, and a ready device that entered its state long ago is not", () => { + const clock = new FakeClock(100_000); + const driver = new FakeDriver({ + clock, + estimateMs: { boot: 2_000, provision: 1_000, reclaim: 4_000 }, + platform: "ios", + }); + // `createdAt` and `lastLeaseEndedAt` are recent; only `stateEnteredAt` is old, so a check + // that reads either of them reports no stall. + const base = { + createdAt: 99_000, + driverData: {}, + driverDeviceId: "d", + id: "dev_1", + lastLeaseEndedAt: 99_000, + mode: "full" as const, + spec: { model: "Phone", osVersion: "1", platform: "ios" as const }, + stateEnteredAt: 1_000, + }; + const stalled = (state: DeviceState, stateEnteredAt = base.stateEnteredAt) => + isStalledTransition({ + claims: undefined, + config: config().stalledTransition, + device: { ...base, state, stateEnteredAt }, + driver, + now: 100_000, + }); + + expect(stalled("provisioning")).toBe(true); + expect(stalled("reclaiming")).toBe(true); + expect(stalled("provisioning", 99_000)).toBe(false); + expect(stalled("ready")).toBe(false); + expect(stalled("leased")).toBe(false); + expect(stalled("shutdown")).toBe(false); + expect(stalled("quarantined")).toBe(false); + }); + it("the doctor's stalled-transition finding is unchanged", async () => { // The finding a stalled provisioning device and a stalled reclaiming device produced // before the stall test became `isStalledTransition`, field for field, and none a moment diff --git a/src/core/domain.test.ts b/src/core/domain.test.ts index b479d984e..99dde0894 100644 --- a/src/core/domain.test.ts +++ b/src/core/domain.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; -import { type DeviceRecord, IllegalTransition, transition, transitionEnteredAt } from "./index.js"; +import { type DeviceRecord, IllegalTransition, transition } from "./index.js"; import { type DeviceSpec, mayBeGranted, sameSpec } from "./domain.js"; const baseDevice: Omit = { @@ -19,10 +19,12 @@ describe("transition", () => { ["provisioning", "quarantined"], ["ready", "leased"], ["ready", "shutdown"], + ["ready", "deleted"], ["leased", "reclaiming"], ["reclaiming", "ready"], ["reclaiming", "shutdown"], ["reclaiming", "quarantined"], + ["reclaiming", "deleted"], ["quarantined", "ready"], ["quarantined", "shutdown"], ["quarantined", "deleted"], @@ -30,13 +32,47 @@ describe("transition", () => { ["shutdown", "deleted"], ["shutdown", "quarantined"], ] as const)("allows %s -> %s", (from, to) => { - const result = transition({ ...baseDevice, state: from }, to); + const result = transition({ ...baseDevice, state: from }, to, 5_000); + + expect(result).toEqual({ ...baseDevice, state: to, stateEnteredAt: 5_000 }); + }); - expect(result).toEqual({ ...baseDevice, state: to }); + it("transition stamps stateEnteredAt with the time it is given, on every legal edge", () => { + const states = [ + "provisioning", + "ready", + "leased", + "reclaiming", + "quarantined", + "shutdown", + "deleted", + ] as const; + let legalEdges = 0; + for (const from of states) { + for (const to of states) { + let result: DeviceRecord; + try { + result = transition({ ...baseDevice, state: from, stateEnteredAt: 1_500 }, to, 7_777); + } catch (error) { + expect(error).toBeInstanceOf(IllegalTransition); + continue; + } + legalEdges += 1; + expect(result.stateEnteredAt).toBe(7_777); + } + } + expect(legalEdges).toBe(17); + }); + + it("ready -> deleted and reclaiming -> deleted are legal, and leased -> deleted is not", () => { + expect(transition({ ...baseDevice, state: "ready" }, "deleted", 9).state).toBe("deleted"); + expect(transition({ ...baseDevice, state: "reclaiming" }, "deleted", 9).state).toBe("deleted"); + expect(() => transition({ ...baseDevice, state: "leased" }, "deleted", 9)).toThrow( + IllegalTransition, + ); }); it.each([ - ["ready", "deleted"], ["leased", "shutdown"], ["deleted", "ready"], // A leased device can only reach `quarantined` by first going through @@ -46,16 +82,16 @@ describe("transition", () => { ["leased", "quarantined"], ["quarantined", "leased"], ] as const)("rejects %s -> %s", (from, to) => { - expect(() => transition({ ...baseDevice, state: from }, to)).toThrow(IllegalTransition); + expect(() => transition({ ...baseDevice, state: from }, to, 5_000)).toThrow(IllegalTransition); }); it.each([ ["ready", "shutdown"], ["reclaiming", "shutdown"], ] as const)("drops the address on %s -> %s, since nothing listens there any more", (from, to) => { - const result = transition({ ...baseDevice, address: "emulator-5586", state: from }, to); + const result = transition({ ...baseDevice, address: "emulator-5586", state: from }, to, 5_000); - expect(result).toEqual({ ...baseDevice, state: to }); + expect(result).toEqual({ ...baseDevice, state: to, stateEnteredAt: 5_000 }); expect(result).not.toHaveProperty("address"); }); @@ -69,7 +105,7 @@ describe("transition", () => { ["reclaiming", "quarantined"], ["provisioning", "quarantined"], ] as const)("keeps the address on %s -> %s, since recovery cannot re-supply one", (from, to) => { - const result = transition({ ...baseDevice, address: "emulator-5586", state: from }, to); + const result = transition({ ...baseDevice, address: "emulator-5586", state: from }, to, 5_000); expect(result.address).toBe("emulator-5586"); }); @@ -78,54 +114,39 @@ describe("transition", () => { const quarantined = transition( { ...baseDevice, address: "emulator-5586", state: "reclaiming" }, "quarantined", + 5_000, ); // Exactly what `Registry.recoverFromQuarantine` does: no `DeviceTransitionUpdate`, because // the driver's reclaim result has no address to give it. - expect(transition(quarantined, "ready").address).toBe("emulator-5586"); + expect(transition(quarantined, "ready", 6_000).address).toBe("emulator-5586"); }); it("keeps the address across transitions between running states", () => { const leased = transition( { ...baseDevice, address: "emulator-5586", state: "ready" }, "leased", + 5_000, ); expect(leased.address).toBe("emulator-5586"); - expect(transition(leased, "reclaiming").address).toBe("emulator-5586"); + expect(transition(leased, "reclaiming", 6_000).address).toBe("emulator-5586"); }); it("takes the address a stop supplies over the one it drops", () => { - const result = transition({ ...baseDevice, address: "old", state: "ready" }, "shutdown", { - address: "new", - }); + const result = transition( + { ...baseDevice, address: "old", state: "ready" }, + "shutdown", + 5_000, + { + address: "new", + }, + ); expect(result.address).toBe("new"); }); }); -describe("transitionEnteredAt", () => { - it("reads provisioning's entry time off createdAt", () => { - expect(transitionEnteredAt({ ...baseDevice, state: "provisioning" })).toBe(1_000); - }); - - it("reads reclaiming's entry time off lastLeaseEndedAt", () => { - expect( - transitionEnteredAt({ ...baseDevice, lastLeaseEndedAt: 2_000, state: "reclaiming" }), - ).toBe(2_000); - }); - - it("is undefined for reclaiming with no recorded release (defensive, should not occur)", () => { - expect(transitionEnteredAt({ ...baseDevice, state: "reclaiming" })).toBeUndefined(); - }); - - it("is undefined for every other state", () => { - for (const state of ["ready", "leased", "quarantined", "shutdown", "deleted"] as const) { - expect(transitionEnteredAt({ ...baseDevice, state })).toBeUndefined(); - } - }); -}); - describe("mayBeGranted", () => { it("refuses only a fresh device that has ended a lease", () => { const ready = { ...baseDevice, state: "ready" as const }; diff --git a/src/core/registry.test.ts b/src/core/registry.test.ts index 96a8835f3..c77df6244 100644 --- a/src/core/registry.test.ts +++ b/src/core/registry.test.ts @@ -1436,3 +1436,160 @@ describe("Registry", () => { ).rejects.toThrow(/Invalid lease record/); }); }); + +/** A clock that moves on every read, so two reads never agree: a field that equals another + * must have come from the same read. */ +class TickingClock extends FakeClock { + #reads = 0; + + override now(): number { + this.#reads += 1; + return 1_000 + this.#reads; + } +} + +describe("Registry: stateEnteredAt", () => { + async function loadTicking(filesystem = new MemoryFilesystem()) { + const clock = new TickingClock(); + const suffixes = ["device", "lease"]; + const options = { + clock, + eventBus: new EventBus(clock), + filesystem, + idGenerator: { generate: () => suffixes.shift() ?? "unexpected" }, + statePath, + }; + return { options, registry: await Registry.load(options) }; + } + + async function registerReady(registry: Registry) { + const device = await registry.registerDevice({ + driverData: {}, + driverDeviceId: "driver_device", + provisionDuration: 0, + spec, + }); + await registry.transitionDevice(device.id, "ready", { + event: "device.ready", + payload: { bootDuration: 0, deviceId: device.id }, + }); + return device; + } + + const lease = (deviceId: string) => ({ + deviceId, + ownerId: "agent-1", + requesterId: "agent-1", + ttlDeadline: 90_000, + ttlMs: 60_000, + }); + + async function loadStored(device: Record) { + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp("/home/agent/.simlock"); + await filesystem.writeFileAtomic( + statePath, + JSON.stringify({ + devices: [ + { createdAt: 500, driverData: {}, driverDeviceId: "d", id: "dev_old", spec, ...device }, + ], + leases: [], + }), + ); + const clock = new FakeClock(1_000); + const registry = await Registry.load({ + clock, + eventBus: new EventBus(clock), + filesystem, + idGenerator: { generate: () => "x" }, + statePath, + }); + return registry.snapshot.devices[0]; + } + + it("registerDevice stamps stateEnteredAt equal to createdAt", async () => { + const { registry } = await loadTicking(); + + const device = await registry.registerDevice({ + driverData: {}, + driverDeviceId: "driver_device", + provisionDuration: 0, + spec, + }); + + expect(device.stateEnteredAt).toBeDefined(); + expect(device.stateEnteredAt).toBe(device.createdAt); + }); + + it("a grant, a release and quarantine entry stamp stateEnteredAt equal to grantedAt, lastLeaseEndedAt and quarantinedAt", async () => { + const { registry } = await loadTicking(); + const device = await registerReady(registry); + + const granted = await registry.createLease(lease(device.id)); + const leasedDevice = registry.snapshot.devices[0]; + expect(leasedDevice?.stateEnteredAt).toBeDefined(); + expect(leasedDevice?.stateEnteredAt).toBe(granted.grantedAt); + + const released = await registry.beginRelease(granted.id); + expect(released.device.stateEnteredAt).toBeDefined(); + expect(released.device.stateEnteredAt).toBe(released.device.lastLeaseEndedAt); + + const quarantined = await registry.enterQuarantine(device.id, 50_000); + expect(quarantined.stateEnteredAt).toBeDefined(); + expect(quarantined.stateEnteredAt).toBe(quarantined.quarantinedAt); + }); + + it("markDeviceMissing stamps stateEnteredAt through transition", async () => { + const { registry } = await loadTicking(); + const device = await registerReady(registry); + const before = registry.snapshot.devices[0]?.stateEnteredAt; + + const missing = await registry.markDeviceMissing(device.id, "doctor"); + + expect(missing.state).toBe("deleted"); + expect(missing.stateEnteredAt).toBeDefined(); + expect(missing.stateEnteredAt).toBeGreaterThan(before ?? Number.POSITIVE_INFINITY); + }); + + it("a record without stateEnteredAt loads it from createdAt when provisioning, lastLeaseEndedAt when reclaiming and quarantinedAt when quarantined", async () => { + expect(await loadStored({ state: "provisioning" })).toMatchObject({ stateEnteredAt: 500 }); + expect(await loadStored({ lastLeaseEndedAt: 900, state: "reclaiming" })).toMatchObject({ + stateEnteredAt: 900, + }); + expect(await loadStored({ quarantinedAt: 700, state: "quarantined" })).toMatchObject({ + stateEnteredAt: 700, + }); + }); + + it.each(["ready", "leased", "shutdown", "deleted"])( + "a record without stateEnteredAt in ready, leased, shutdown or deleted loads without it (%s)", + async (state) => { + const device = await loadStored({ lastLeaseEndedAt: 900, quarantinedAt: 700, state }); + + expect(device).toBeDefined(); + expect(device).not.toHaveProperty("stateEnteredAt"); + }, + ); + + it("a record with stateEnteredAt loads it unchanged", async () => { + const device = await loadStored({ + lastLeaseEndedAt: 900, + state: "reclaiming", + stateEnteredAt: 950, + }); + + expect(device?.stateEnteredAt).toBe(950); + }); + + it("keeps a stateEnteredAt it wrote through a save and a reload", async () => { + const { options, registry } = await loadTicking(); + await registerReady(registry); + + const reloaded = await Registry.load(options); + + expect(reloaded.snapshot.devices[0]?.stateEnteredAt).toBeDefined(); + expect(reloaded.snapshot.devices[0]?.stateEnteredAt).toBe( + registry.snapshot.devices[0]?.stateEnteredAt, + ); + }); +}); diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.ts index 1713ed35c..3eaad5d07 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -1877,6 +1877,71 @@ describe("DaemonServer decorations", () => { await observer.close(); }); + async function seededHarness(devices: readonly Record[]) { + const stateFilesystem = new MemoryFilesystem(); + await stateFilesystem.writeFileAtomic( + "/state.json", + JSON.stringify({ + devices: devices.map((device) => ({ + createdAt: 1, + driverData: {}, + driverDeviceId: `driver_${String(device.id)}`, + spec: { model: "iPhone 16", osVersion: "26.5", platform: "ios" }, + ...device, + })), + leases: [], + }), + ); + return createHarness({ stateFilesystem }); + } + + it("transitionAgeMs is now minus stateEnteredAt for a provisioning or reclaiming device and absent in every other state", async () => { + const harness = await seededHarness([ + { id: "dev_prov", state: "provisioning", stateEnteredAt: 400 }, + { id: "dev_recl", lastLeaseEndedAt: 1, state: "reclaiming", stateEnteredAt: 600 }, + { id: "dev_ready", state: "ready", stateEnteredAt: 100 }, + { id: "dev_quar", quarantinedAt: 1, state: "quarantined", stateEnteredAt: 100 }, + { id: "dev_down", state: "shutdown", stateEnteredAt: 100 }, + ]); + const observer = await createClient(harness.socketPath); + await hello(observer); + + const response = await observer.request("status.get", {}); + + const devices = (response.payload as { devices: Record[] }).devices; + const byId = new Map(devices.map((device) => [device.id, device])); + expect(byId.get("dev_prov")?.transitionAgeMs).toBe(600); + expect(byId.get("dev_recl")?.transitionAgeMs).toBe(400); + for (const id of ["dev_ready", "dev_quar", "dev_down"]) { + expect(byId.get(id)).toBeDefined(); + expect(byId.get(id)).not.toHaveProperty("transitionAgeMs"); + } + await observer.close(); + }); + + it("status.get and list.get return stateEnteredAt for a device that has one and omit it for a device that does not", async () => { + const harness = await seededHarness([ + { id: "dev_known", state: "ready", stateEnteredAt: 250 }, + { id: "dev_unknown", state: "ready" }, + ]); + const observer = await createClient(harness.socketPath); + await hello(observer); + + const status = await observer.request("status.get", {}); + const list = await observer.request("list.get", { kind: "devices" }); + + for (const devices of [ + (status.payload as { devices: Record[] }).devices, + list.payload as Record[], + ]) { + const byId = new Map(devices.map((device) => [device.id, device])); + expect(byId.get("dev_known")?.stateEnteredAt).toBe(250); + expect(byId.get("dev_unknown")).toBeDefined(); + expect(byId.get("dev_unknown")).not.toHaveProperty("stateEnteredAt"); + } + await observer.close(); + }); + describe("operational logging", () => { function logger(): { logger: Logger; sink: MemoryLogSink } { const sink = new MemoryLogSink(); From d9fe26a68f621083d68a1c669f5904ca854251dd Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Sun, 4 Oct 2026 16:56:31 +0200 Subject: [PATCH 2/3] feat(core): every device shape says when the device entered its state (#318) 2 failing -> 0 failing (the 29 red tests turn green: transition stamps stateEnteredAt, the loader fills it where an existing timestamp is exact, the stall check and transitionAgeMs read it, the wire schemas carry it). transitionEnteredAt is deleted. Two registry fixtures gain stateEnteredAt. --- docs/CLI.md | 5 +++ docs/CLIENT.md | 5 ++- docs/HTTP-API.md | 13 +++++--- src/contract/schemas.ts | 6 ++++ src/core/doctor.ts | 9 +++--- src/core/domain.ts | 42 +++++++++--------------- src/core/index.ts | 1 - src/core/registry.test.ts | 2 ++ src/core/registry.ts | 68 +++++++++++++++++++++++++++++++-------- src/daemon/dispatcher.ts | 10 ++++-- 10 files changed, 107 insertions(+), 54 deletions(-) diff --git a/docs/CLI.md b/docs/CLI.md index 4e28dc7cc..c33e1699d 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -1090,6 +1090,11 @@ threshold (see `simlock doctor` below): it stays visible in `status` and `list --devices` with that state while `QuarantineCoordinator` retries it in the background, and is never handed to a new requester. +A device in `status --json` and `list --devices` carries `stateEnteredAt`, +the moment it entered its current state, in milliseconds since the epoch. It +is absent when unknown: a `ready`, `leased` or `shutdown` device recorded by an +older daemon has none until its next change of state. + A device currently `provisioning` or `reclaiming` carries a derived `transitionAgeMs` — how long it has been in that state — visible in `status` and `list --devices` well before it crosses the threshold that would make diff --git a/docs/CLIENT.md b/docs/CLIENT.md index 0637ddf6e..4c1d9765f 100644 --- a/docs/CLIENT.md +++ b/docs/CLIENT.md @@ -51,7 +51,10 @@ device) is granted `"full"`, and a `"full"` request is never granted `"slim"`. A slim device lacks some system features — push notifications, Spotlight, StoreKit sheets, universal links, system pickers — so check it before treating such a failure as a bug. Every device in `getStatus()` and in -an admin's `list({ kind: "devices" })` carries the same `mode`. +an admin's `list({ kind: "devices" })` carries the same `mode`, and +`stateEnteredAt`, the time in milliseconds since the epoch at which the device +entered its current state. `stateEnteredAt` is absent when the daemon does not +know it. On Android, `requestLease` also takes an optional `imageTag`: the system image type to create the device from, such as `"google_apis_playstore"`, as diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index f4f23ba47..0c7ec531e 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -210,7 +210,11 @@ device, oldest first, in the shape [`GET /v1/lease-requests`](#get-v1lease-requests) answers. A worker always sends it, empty when nothing waits; an older daemon leaves it out. -A device in `devices` that is `provisioning` or `reclaiming` carries +A device in `devices` carries **`stateEnteredAt`**, the moment it entered +its current state, in milliseconds since the epoch. It is absent when the +daemon does not know: a device recorded by an older daemon that is `ready`, +`leased` or `shutdown` has none until its next change of state. A device in +`devices` that is `provisioning` or `reclaiming` also carries `transitionAgeMs`, how long it has been in that state. One that has been there past its threshold with nothing working on it also carries **`stalled: true`**: the same devices `simlock doctor` reports as stalled (see @@ -218,7 +222,7 @@ past its threshold with nothing working on it also carries device has no `stalled` field, and an older daemon sends none. ```json -{ "id": "dev_7", "state": "provisioning", "mode": "full", "transitionAgeMs": 412000, "stalled": true, +{ "id": "dev_7", "state": "provisioning", "mode": "full", "stateEnteredAt": 1790864071200, "transitionAgeMs": 412000, "stalled": true, "spec": { "platform": "ios", "model": "iPhone 16", "osVersion": "18.4" } } ``` @@ -1107,7 +1111,8 @@ the worker's and the gateway's, so you can see which side to upgrade. A worker too old to overlap is the ordinary upgrade path, not a fault, and its view carries no `host`, since the gateway asks it nothing. -`connection` is `connected`, `disconnected`, or `incompatible`. A worker view is +`connection` is `connected`, `disconnected`, or `incompatible`. Each device in a +worker view carries `stateEnteredAt` when the worker reports it. A worker view is rebuilt over the uplink and never persisted, so these are current facts, not a registry: a worker appears by connecting, and there is deliberately no route that *adds* one. @@ -1173,7 +1178,7 @@ an all-or-nothing that leaves the operator guessing. - `GET /v1/leases` — every active lease (`simlock list --leases`). - `GET /v1/lease-requests` — every request waiting for a device (`simlock list --requests`); see below. -- `GET /v1/devices` — every managed device, with state, +- `GET /v1/devices` — every managed device, with state, `stateEnteredAt`, `transitionAgeMs` and `stalled` as [`GET /v1/status`](#get-v1status) describes them (`simlock list --devices`). - `GET /v1/events?since=` — replay business events newer than diff --git a/src/contract/schemas.ts b/src/contract/schemas.ts index 06c89457a..ff9cf4f1b 100644 --- a/src/contract/schemas.ts +++ b/src/contract/schemas.ts @@ -70,6 +70,9 @@ export const deviceRecordSchema = z.object({ state: deviceStateSchema, driverData: z.unknown(), createdAt: z.number(), + /** An absolute time, not an age: when the device entered its current state. Absent when the + * record does not know. */ + stateEnteredAt: z.number().optional(), lastLeaseEndedAt: z.number().optional(), foreignStateDetectedAt: z.number().optional(), foreignProvenanceDetectedAt: z.number().optional(), @@ -129,6 +132,9 @@ export const statusDeviceSchema = z.object({ state: deviceStateSchema, /** The device mode (see `DeviceRecord.mode`) -- not the daemon's own `worker`/`gateway` mode. */ mode: deviceModeSchema, + /** An absolute time, not an age: when the device entered its current state. Absent when the + * record does not know. */ + stateEnteredAt: z.number().optional(), foreignStateDetectedAt: z.number().optional(), foreignProvenanceDetectedAt: z.number().optional(), quarantineAttempts: z.number().optional(), diff --git a/src/core/doctor.ts b/src/core/doctor.ts index a641fc4d8..6bfcf52f8 100644 --- a/src/core/doctor.ts +++ b/src/core/doctor.ts @@ -7,7 +7,6 @@ import { type DeviceState, mayBeGranted, type Platform, - transitionEnteredAt, } from "./domain.js"; import type { DeviceOperationClaims } from "./device-operation-claims.js"; import type { @@ -813,8 +812,8 @@ function slowestReclaimEstimateMs(driver: Pick, spec: Device * `minimumThresholdMs` (see `stallThresholdMs`): not `estimate` itself, because the * estimate is tuned for a routine run and real-world variance (a cold Android boot, a * loaded host) can legitimately run well past it without anything having stalled. No - * driver for the device's platform, or no recorded entry time (defensive; see - * `transitionEnteredAt`), means there is nothing to compare against, so no stall rather + * driver for the device's platform, or no recorded entry time (`stateEnteredAt`; absent + * means unknown), means there is nothing to compare against, so no stall rather * than a guess. * * A device this daemon holds an operation claim on is excluded outright, before any @@ -842,7 +841,7 @@ export function isStalledTransition(input: StallInput): boolean { if (claims?.isClaimed(device.id) === true) { return false; } - const enteredAt = transitionEnteredAt(device); + const enteredAt = device.stateEnteredAt; if (enteredAt === undefined || driver === undefined) { return false; } @@ -887,7 +886,7 @@ function stalledTransitionFinding( } // Narrowing only: `isStalledTransition` holds just for a device in one of these two states, // with an entry time and a driver. - const enteredAt = transitionEnteredAt(device); + const enteredAt = device.stateEnteredAt; if ( driver === undefined || enteredAt === undefined || diff --git a/src/core/domain.ts b/src/core/domain.ts index fea580b8a..4b2b8ca90 100644 --- a/src/core/domain.ts +++ b/src/core/domain.ts @@ -68,6 +68,13 @@ export interface DeviceRecord { readonly state: DeviceState; readonly driverData: unknown; readonly createdAt: number; + /** + * The wall-clock moment the device entered its current `state`. `transition` stamps it on every + * move and `registerDevice` on registration. Absent means unknown: a record written before this + * field loads it only where an existing timestamp is exactly the entry time (see `parseDevice` + * in `registry.ts`), and never guesses. + */ + readonly stateEnteredAt?: number; readonly lastLeaseEndedAt?: number; readonly foreignStateDetectedAt?: number; readonly foreignProvenanceDetectedAt?: number; @@ -218,13 +225,15 @@ export function isSettled(record: Pick, "state">): b * `shutdown -> quarantined` is a spent fresh device whose delete failed after its * lease-end shutdown committed -- each its own entry into the same state rather than a * second one. Exits: `ready` on a successful retry, `deleted` on a successful retried - * delete, `shutdown`/`deleted` on giving up. + * delete, `shutdown`/`deleted` on giving up. `ready -> deleted` and `reclaiming -> deleted` are + * the doctor's missing-device delete (`Registry.markDeviceMissing`); a `leased` device never + * reaches it, because the lease check refuses first. */ const legalTransitions: Readonly> = { provisioning: ["ready", "deleted", "quarantined"], - ready: ["leased", "shutdown"], + ready: ["leased", "shutdown", "deleted"], leased: ["reclaiming"], - reclaiming: ["ready", "shutdown", "quarantined"], + reclaiming: ["ready", "shutdown", "quarantined", "deleted"], quarantined: ["ready", "shutdown", "deleted"], shutdown: ["ready", "deleted", "quarantined"], deleted: [], @@ -250,6 +259,7 @@ export interface DeviceTransitionUpdate { export function transition( record: DeviceRecord, to: DeviceState, + at: number, update?: DeviceTransitionUpdate, ): DeviceRecord { if (!legalTransitions[record.state].includes(to)) { @@ -271,30 +281,8 @@ export function transition( // boot's console port in `driverData.port`, and after a daemon restart only a recovery // boot reuses it (see `ManagedDeviceLifecycle.recoverLeased`); any other takes a new one. const { address: _stale, ...stopped } = record; - return { ...stopped, ...update, state: to }; + return { ...stopped, ...update, state: to, stateEnteredAt: at }; } - return { ...record, ...update, state: to }; -} - -/** - * The wall-clock moment a `provisioning` or `reclaiming` device most recently entered - * that state -- `undefined` for every other state, which either isn't mid-transition - * or already has its own dedicated timestamp for the same purpose (`quarantinedAt`). - * No dedicated field was added for this: `createdAt` already doubles as provisioning's - * entry time, since nothing ever transitions back into `provisioning` (see - * `legalTransitions`), and `lastLeaseEndedAt` already doubles as reclaiming's, since - * `beginRelease` is reclaiming's only entry point and stamps it fresh on every entry. - * Used by Doctor to age a mid-transition device against a driver-derived stall - * threshold. - */ -export function transitionEnteredAt(record: DeviceRecord): number | undefined { - switch (record.state) { - case "provisioning": - return record.createdAt; - case "reclaiming": - return record.lastLeaseEndedAt; - default: - return undefined; - } + return { ...record, ...update, state: to, stateEnteredAt: at }; } diff --git a/src/core/index.ts b/src/core/index.ts index e35e9e131..5cf9145b4 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -18,7 +18,6 @@ export { type LeaseRequestFailure, IllegalTransition, transition, - transitionEnteredAt, } from "./domain.js"; export { type CleanupRule, type RegistryView } from "./cleanup/types.js"; export { automaticCleanupRules } from "./cleanup/rules.js"; diff --git a/src/core/registry.test.ts b/src/core/registry.test.ts index c77df6244..bb49dc863 100644 --- a/src/core/registry.test.ts +++ b/src/core/registry.test.ts @@ -147,6 +147,7 @@ describe("Registry", () => { spec, mode: "full", state: "provisioning", + stateEnteredAt: 1_000, }, ]); }); @@ -683,6 +684,7 @@ describe("Registry", () => { spec, mode: "full", state: "ready", + stateEnteredAt: 1_000, }); await expect(registry.recoverFromQuarantine(device.id, "ready")).rejects.toThrow( RegistryEventError, diff --git a/src/core/registry.ts b/src/core/registry.ts index a9ffd602b..08f7b68de 100644 --- a/src/core/registry.ts +++ b/src/core/registry.ts @@ -215,8 +215,9 @@ export class Registry implements LeaseRequestStore { provisionDuration, spec, }: RegisterDeviceInput): Promise { + const createdAt = this.options.clock.now(); const record: DeviceRecord = { - createdAt: this.options.clock.now(), + createdAt, driverData, driverDeviceId, id: `dev_${this.options.idGenerator.generate()}`, @@ -224,6 +225,7 @@ export class Registry implements LeaseRequestStore { mode: "full", spec: { ...spec }, state: "provisioning", + stateEnteredAt: createdAt, }; const devices = [...this.#devices, record]; @@ -264,7 +266,7 @@ export class Registry implements LeaseRequestStore { throw new RegistryEventError(`Device event payload does not match device: ${deviceId}`); } - const updated = transition(device, to, update); + const updated = transition(device, to, this.options.clock.now(), update); const devices = [...this.#devices]; devices[index] = updated; await this.#commit(devices, this.#leases); @@ -287,7 +289,7 @@ export class Registry implements LeaseRequestStore { if (device.state !== "reclaiming") { throw new RegistryEventError(`Device is not reclaiming: ${deviceId}`); } - const updated = transition(device, "shutdown"); + const updated = transition(device, "shutdown", this.options.clock.now()); const devices = [...this.#devices]; devices[index] = updated; await this.#commit(devices, this.#leases); @@ -313,11 +315,12 @@ export class Registry implements LeaseRequestStore { `Device is not reclaiming, provisioning, or shutdown: ${deviceId}`, ); } + const now = this.options.clock.now(); const updated: DeviceRecord = { - ...transition(device, "quarantined"), + ...transition(device, "quarantined", now), quarantineAttempts: 0, quarantineNextRetryAt: nextRetryAt, - quarantinedAt: this.options.clock.now(), + quarantinedAt: now, }; const devices = [...this.#devices]; devices[index] = updated; @@ -359,7 +362,7 @@ export class Registry implements LeaseRequestStore { quarantineNextRetryAt: _quarantineNextRetryAt, quarantinedAt: _quarantinedAt, ...updated - } = transition(device, to); + } = transition(device, to, this.options.clock.now()); const devices = [...this.#devices]; devices[index] = updated as DeviceRecord; await this.#commit(devices, this.#leases); @@ -403,7 +406,7 @@ export class Registry implements LeaseRequestStore { quarantineNextRetryAt: _quarantineNextRetryAt, quarantinedAt: _quarantinedAt, ...updated - } = transition(device, "deleted"); + } = transition(device, "deleted", this.options.clock.now()); const devices = [...this.#devices]; devices[index] = updated as DeviceRecord; await this.#commit(devices, this.#leases); @@ -496,7 +499,7 @@ export class Registry implements LeaseRequestStore { if (device.state === "deleted") { return cloneDevice(device); } - const updated = { ...device, state: "deleted" as const }; + const updated = transition(device, "deleted", this.options.clock.now()); const devices = [...this.#devices]; devices[index] = updated; await this.#commit(devices, this.#leases); @@ -524,8 +527,8 @@ export class Registry implements LeaseRequestStore { throw new RegistryEventError(`Device already has an active lease: ${deviceId}`); } - const leasedDevice = transition(device, "leased"); const grantedAt = this.options.clock.now(); + const leasedDevice = transition(device, "leased", grantedAt); const lease: LeaseRecord = { deviceId, grantedAt, @@ -562,9 +565,10 @@ export class Registry implements LeaseRequestStore { recoveryAttempts: _recoveryAttempts, ...withoutRecoveryMarkers } = device; + const endedAt = this.options.clock.now(); const reclaiming = { - ...transition(withoutRecoveryMarkers as DeviceRecord, "reclaiming"), - lastLeaseEndedAt: this.options.clock.now(), + ...transition(withoutRecoveryMarkers as DeviceRecord, "reclaiming", endedAt), + lastLeaseEndedAt: endedAt, }; const devices = [...this.#devices]; devices[deviceIndex] = reclaiming; @@ -782,6 +786,7 @@ const deviceRecordKeys = [ "state", "driverData", "createdAt", + "stateEnteredAt", "lastLeaseEndedAt", "foreignStateDetectedAt", "foreignProvenanceDetectedAt", @@ -956,8 +961,15 @@ function parseDevice(value: unknown): DeviceRecord { throw new RegistryLoadError("Invalid device record in registry state"); } + const optionalNumbers = parseOptionalDeviceNumbers(value); + const loadedState: DeviceState = state === "warm" ? "reclaiming" : state; + const stateEnteredAt = loadStateEnteredAt(value.stateEnteredAt, loadedState, { + createdAt, + ...optionalNumbers, + }); + return { - ...parseOptionalDeviceNumbers(value), + ...optionalNumbers, ...(address === undefined ? {} : { address }), createdAt, driverData, @@ -966,10 +978,40 @@ function parseDevice(value: unknown): DeviceRecord { leaseIdentity: parseLeaseIdentity(value.leaseIdentity), mode: parseDeviceMode(value.mode), spec: parseDeviceSpec(spec), - state: state === "warm" ? "reclaiming" : state, + state: loadedState, + ...(stateEnteredAt === undefined ? {} : { stateEnteredAt }), }; } +/** + * When a loaded device entered its state (ADR 0015 §5): the stored value when it is a finite + * number, else the one existing timestamp that is exactly that moment -- `createdAt` for + * `provisioning`, `lastLeaseEndedAt` for `reclaiming`, `quarantinedAt` for `quarantined` -- and + * nothing for every other state. Absent means unknown; nothing here guesses, and the next + * transition sets it. + */ +function loadStateEnteredAt( + stored: unknown, + state: DeviceState, + known: { + readonly createdAt: number; + readonly lastLeaseEndedAt?: number; + readonly quarantinedAt?: number; + }, +): number | undefined { + if (typeof stored === "number" && Number.isFinite(stored)) return stored; + switch (state) { + case "provisioning": + return known.createdAt; + case "reclaiming": + return known.lastLeaseEndedAt; + case "quarantined": + return known.quarantinedAt; + default: + return undefined; + } +} + /** * A record written before `leaseIdentity` existed was created under the only policy there was, * so it loads as `reusable`. A present-but-unknown value fails the load: guessing `reusable` for diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index 951d1c427..e4cc7556a 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -18,7 +18,6 @@ import { type StallInput, effectiveAllowDownload, RuntimeMissingError, - transitionEnteredAt, UnknownLeaseError, } from "../core/index.js"; import type { @@ -826,8 +825,13 @@ export class Dispatcher { #decorateDevice( device: DeviceRecord, ): DeviceRecord & { readonly transitionAgeMs?: number; readonly stalled?: true } { - const enteredAt = transitionEnteredAt(device); - if (enteredAt === undefined) return device; + const enteredAt = device.stateEnteredAt; + if ( + enteredAt === undefined || + (device.state !== "provisioning" && device.state !== "reclaiming") + ) { + return device; + } const now = this.options.clock.now(); return { ...device, From 41a0d5a56a89d5240414af60368bdcb9fb20907d Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Sun, 4 Oct 2026 17:02:27 +0200 Subject: [PATCH 3/3] test: kill surviving stateEnteredAt mutants (#318) Loader table replaces a switch; tests for a non-numeric stored value, a reclaiming record with no lastLeaseEndedAt, and a mid-transition device with no entry time. --- src/core/registry.test.ts | 13 +++++++++++++ src/core/registry.ts | 16 ++++++---------- src/daemon/server.test.ts | 14 ++++++++++++++ 3 files changed, 33 insertions(+), 10 deletions(-) diff --git a/src/core/registry.test.ts b/src/core/registry.test.ts index bb49dc863..c6b86df4b 100644 --- a/src/core/registry.test.ts +++ b/src/core/registry.test.ts @@ -1573,6 +1573,19 @@ describe("Registry: stateEnteredAt", () => { }, ); + it("a record whose stateEnteredAt is not a number loads as if it had none", async () => { + expect(await loadStored({ state: "provisioning", stateEnteredAt: "soon" })).toMatchObject({ + stateEnteredAt: 500, + }); + expect(await loadStored({ state: "ready", stateEnteredAt: "soon" })).not.toHaveProperty( + "stateEnteredAt", + ); + }); + + it("a reclaiming record with no lastLeaseEndedAt loads without stateEnteredAt", async () => { + expect(await loadStored({ state: "reclaiming" })).not.toHaveProperty("stateEnteredAt"); + }); + it("a record with stateEnteredAt loads it unchanged", async () => { const device = await loadStored({ lastLeaseEndedAt: 900, diff --git a/src/core/registry.ts b/src/core/registry.ts index 08f7b68de..a894b69af 100644 --- a/src/core/registry.ts +++ b/src/core/registry.ts @@ -1000,16 +1000,12 @@ function loadStateEnteredAt( }, ): number | undefined { if (typeof stored === "number" && Number.isFinite(stored)) return stored; - switch (state) { - case "provisioning": - return known.createdAt; - case "reclaiming": - return known.lastLeaseEndedAt; - case "quarantined": - return known.quarantinedAt; - default: - return undefined; - } + const exactEntryTime: Partial> = { + provisioning: known.createdAt, + quarantined: known.quarantinedAt, + reclaiming: known.lastLeaseEndedAt, + }; + return exactEntryTime[state]; } /** diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.ts index 3eaad5d07..654676b3d 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -1919,6 +1919,20 @@ describe("DaemonServer decorations", () => { await observer.close(); }); + it("a mid-transition device with no known entry time has no transitionAgeMs and is not stalled", async () => { + const harness = await seededHarness([{ id: "dev_orphan", state: "reclaiming" }]); + const observer = await createClient(harness.socketPath); + await hello(observer); + + const response = await observer.request("status.get", {}); + + const [device] = (response.payload as { devices: Record[] }).devices; + expect(device?.id).toBe("dev_orphan"); + expect(device).not.toHaveProperty("transitionAgeMs"); + expect(device).not.toHaveProperty("stalled"); + await observer.close(); + }); + it("status.get and list.get return stateEnteredAt for a device that has one and omit it for a device that does not", async () => { const harness = await seededHarness([ { id: "dev_known", state: "ready", stateEnteredAt: 250 },