Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions docs/CLI.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 4 additions & 1 deletion docs/CLIENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 9 additions & 4 deletions docs/HTTP-API.md
Original file line number Diff line number Diff line change
Expand Up @@ -210,15 +210,19 @@ 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
`stalledTransition.*` in [CONFIGURATION.md](CONFIGURATION.md)). Every other
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" } }
```

Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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=<duration>` — replay business events newer than
Expand Down
48 changes: 48 additions & 0 deletions e2e/device-state-entered.test.ts
Original file line number Diff line number Diff line change
@@ -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");
}
});
});
50 changes: 50 additions & 0 deletions src/contract/schemas.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vitest";

import { OPERATIONS } from "./operations.js";
import {
deviceRecordSchema,
fitHostFacts,
Expand Down Expand Up @@ -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]);
});
});
6 changes: 6 additions & 0 deletions src/contract/schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down Expand Up @@ -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(),
Expand Down
38 changes: 38 additions & 0 deletions src/core/doctor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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
Expand Down
9 changes: 4 additions & 5 deletions src/core/doctor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import {
type DeviceState,
mayBeGranted,
type Platform,
transitionEnteredAt,
} from "./domain.js";
import type { DeviceOperationClaims } from "./device-operation-claims.js";
import type {
Expand Down Expand Up @@ -813,8 +812,8 @@ function slowestReclaimEstimateMs(driver: Pick<Driver, "estimate">, 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
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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 ||
Expand Down
Loading
Loading