Repository navigation
Description
Part of #623.
Scope
After this PR, simlock stats prints the figures for a window, as a table or as --json, on a single host and on a gateway. The programmatic admin client gets usage(window). Both call the new usage.get operation. It reads the request rows, minute rows and device fact rows #630 writes into history.db, never the events. So figures reach back as far as those rows (metrics.retention, 90 days by default), not just the 7 days of events.
In short
An operator runs simlock stats --since 24h and sees requests, grants and how each was served, wait, held time, turnaround, provisioning and boot time, rejections by reason, incidents, and use per platform, per worker and per requester. The figures are the same after a daemon restart and stay after the events they came from are pruned.
flowchart LR
CLI["simlock stats (new)"] --> C["admin client usage (new)"]
C --> D["usage.get handler (new)<br/>worker or gateway"]
D --> R[["usage reader (new)"]]
R --> P[(request, minute and device fact rows<br/>history.db, #630)]
R --> T[token store: labels]
D -->|window ends before oldest row| E[HISTORY_NOT_KEPT]
Session, before and after:
$ simlock stats --since 24h
{"error":{"code":"USAGE","message":"Unknown command: stats (run `simlock --help` for usage)"}} # today, exit 2
$ simlock stats --since 30d # a host upgraded yesterday
Usage from 2026-09-16T12:00:00.000Z to 2026-10-16T13:04:12.345Z
Figures cover from 2026-10-15T09:12:00.000Z: the history does not reach back to the start of the window.
Totals
Requests: 214 (209 granted, 5 rejected)
Granted: warm 160, booted 41, provisioned 8
Rejected: no-wait 3, timeout 2
Wait: p50 400ms, p95 38s, max 2m 10s (214 samples)
...
The header's start, 30 days before 13:04:12Z, is floored to the bucket (6 hours for 30 days); its end is the moment asked. The wait has 214 samples: 209 grants and 5 rejections.
Inputs:
| Command | Today | After |
|---|---|---|
simlock stats |
usage error, exit 2 | the last 24 hours |
simlock stats --since 1h --json |
usage error | usage.get's output as one JSON object |
simlock stats --from 2026-10-15T00:00Z --to 2026-10-16T00:00Z |
usage error | that window |
simlock stats --from 2026-10-15T00:00Z |
usage error | from then to now |
simlock stats --since 1h --from 2026-10-15T00:00Z |
usage error | usage error stats takes --since or --from, not both, exit 2 |
simlock stats --to 2026-10-16T00:00Z |
usage error | usage error --to needs --from, exit 2 |
simlock stats --from 2026-10-16T00:00Z --to 2026-10-15T00:00Z |
usage error | usage error --from must be earlier than --to, or than now when --to is left out, exit 2 |
simlock stats --since 91d |
usage error | BAD_REQUEST the window must not be longer than 90 days, exit 2 |
simlock stats --from 2026-10-15 |
usage error | usage error Invalid time: 2026-10-15 (use ISO 8601 with Z or an offset), exit 2 |
simlock stats --from <100 days ago> --to <95 days ago> |
usage error | HISTORY_NOT_KEPT, exit 12: The history does not reach back to the end of that window; its figures start at <ISO time of the oldest row>. |
Words: a bucket is one point of the series, 1 minute to 1 day wide (feature #623 Shared values, "Bucket width"). A probe is a gateway's dispatch as a worker sees it: a request row with probe set.
If this goes wrong, an operator sees figures that disagree with simlock events for the same window, or figures that vanish after 7 days.
Technical spec
Facts
| # | Fact | Source |
|---|---|---|
| F1 | events.replay is an admin, read operation over the history; a new operation copies its shape |
src/contract/operations.ts:640-646 |
| F2 | Every operation is listed in OPERATIONS; the role and effect matrices fail on a missing one |
src/contract/operations.ts:1037; src/contract/AGENTS.md "Rules" |
| F3 | The protocol is { min: 39, max: 39 } |
src/contract/protocol.ts:13 |
| F4 | Exit 12 is the "what you named does not exist" class; UNKNOWN_MODEL is 12 / 422 |
src/contract/errors.ts:264, :370 |
| F5 | MAX_DATE_MS = 8.64e15 bounds wire times |
src/contract/schemas.ts:773 |
| F6 | The worker handler for events.replay passes its input to eventHistory |
src/daemon/dispatcher.ts:289, :772-773 |
| F7 | A worker names itself with instanceId and config.gateway.label |
src/daemon/dispatcher.ts:811, :824 |
| F8 | Both dispatchers take an optional token store with list(); records carry label? |
src/daemon/dispatcher.ts:177; src/gateway/dispatcher.ts:104; src/http/token-store.ts:25, :85 |
| F9 | A gateway's requester prefix is FleetLeaseIndex.requesterPrefix (gw:<instanceId>:) |
src/gateway/lease-index.ts:98-100; src/daemon/main.ts:732 |
| F10 | The gateway dispatcher reads only project, all, isGatewayRequester of the index |
src/gateway/dispatcher.ts:139 |
| F11 | DaemonServer switches on each operation name to dispatch it |
src/daemon/server.ts:1115 |
| F12 | The admin client wraps each operation in one method; the degraded client rejects it | src/simlock-client/client.ts:248, :440, :638; types src/simlock-client/types.ts:56-57; re-export src/admin/index.ts:41-42 |
| F13 | The CLI parses durations with the contract's parser; a bad one is a UsageError |
src/cli/index.ts:659-663; src/contract/duration.ts:15 |
| F14 | A CLI error is one JSON line on stderr; a usage error exits 2, a contract error by ERROR_TABLE; an unknown command names the word and adds the simlock --help hint |
src/cli/index.ts:110-111, :493, :641-644 |
| F15 | runDispatch maps an unclassified throw to INTERNAL and logs it at error |
src/daemon/dispatch.test.ts:114 |
| F16 | An absent dependency of one operation answers its own *_UNAVAILABLE code (domain, exit 1, HTTP 503), thrown as an error class the daemon classifies |
src/contract/errors.ts:96-97, :338-344; src/daemon/dispatcher.ts:93 |
| F17 | Reused from PR #356: usageWindowSchema (integer ms, from < to, ≤ 90 days, messages from must be before to and the window must not be longer than 90 days) and usageOutputSchema |
task/347:src/contract/schemas.ts:1105-1215 |
| F18 | Reused: HISTORY_NOT_KEPT row and details { oldestTs } |
task/347:src/contract/errors.ts:100, :211, :400 |
| F19 | Reused: usageAnswer turns a reader result into the output or HISTORY_NOT_KEPT |
task/347:src/daemon/dispatch.ts:400 |
| F20 | Reused: the reader checks the oldest time against the asked to, joins labels and strips the gateway's own prefix. Not reused: its rounding of both ends (:58-63) and its memo |
task/347:src/core/usage/usage-reader.ts:71, :86-98 |
| F21 | Reused: seriesBucketMs; summarise = p50, p95, max by nearest rank, null over none; requesters by requests descending, then id, a probe that was not granted left out |
task/347:src/core/usage/compute-usage.ts:41-50, :214-221, :273-296 |
| F22 | Reused: series point ends min(from + (i+1) × bucket, to), so the last point of an unrounded to ends at to |
task/347:src/core/usage/compute-usage.ts:316-319 |
| F23 | Reused: runStats, statsWindow, parseTime, formatUsage (header Usage from <ISO> to <ISO>, partial note Figures cover from <ISO>: the history does not reach back to the start of the window., a Failures row only when there are failures) |
task/347:src/cli/index.ts:1567-1625; task/347:src/cli/stats.ts:5-10, :94-96 |
| F24 | PR #356 counted failures.byEvent for device.purge-failed, device.recovery-failed, component.install-failed and any other *-failed event |
gh issue view 347, "Contract and event changes" |
| F25 | PR #356 open finding: the worker's own label in its workers entry is reached by no test |
PR #356 body, Status; task/347:src/daemon/dispatcher.ts:253 |
| F26 | PR #356 open finding: its docs/CLI.md names "maintenance" as closing admission; only nuke does |
PR #356 body, Status; task/347:docs/CLI.md:2004-2005 |
| F27 | Not reused: PR #356's event reader (read-events.ts, timeline.ts, event-file.ts carry) |
ADR 0032 §5 |
- Slot, RAM and queue figures and the series count whole minutes only; the running minute is left out, so a stop and start gives the same output (decided in delivery, pending the maintainer).
- A boot counts in
statswhen itsdevice.readycarries abootDurationabove 0, the projection's device fact rule (decided in delivery, pending the maintainer). - The 500 ms bound on a 7-day read is for a running read thread; the thread's first start is not timed (decided in delivery, pending the maintainer).
Modules touched
Searches: usage.get, HISTORY_NOT_KEPT, HISTORY_UNAVAILABLE, history.db (0 hits on main); DOCTOR_UNAVAILABLE (the pattern: errors.ts, dispatcher.ts, error-code.ts); events.replay (22 files, the pattern for a new operation); PROTOCOL_VERSION_RANGE (10); requesterPrefix (9).
src/contract/—schemas.ts,operations.ts(usage.get),errors.ts(HISTORY_NOT_KEPT),protocol.ts(+1), andusage-window.ts(new): the window rules ofstatsWindow(F23), soGET /v1/statsand thesimlock stats --csvledger #632's route calls the same function. See "Surface".src/core/usage/(new, platform-agnostic) — figures from rows (pure);read-thread.ts, the worker-thread entry that openshistory.dbread-only, callshistory.usageand computes the figures (an entry in.fallowrc.json, loaded by path);index.ts,AGENTS.md, a row indocs/internal/ARCHITECTURE.md.src/daemon/dispatch.ts(usageAnswer),dispatcher.ts(handler),error-code.ts(HISTORY_UNAVAILABLE),server.ts(switch),main.ts(gives both modes the reader,history.statusand the data directory; terminates the read thread at stop).src/gateway/dispatcher.ts(handler; index pick gainsrequesterPrefix).src/simlock-client/client.ts,types.ts;src/admin/index.ts.src/cli/index.ts(statsroute,runStats),src/cli/stats.ts(formatUsage).- Docs:
docs/CLI.md(command, flags, exit 12 and exit 1 rows),docs/CLIENT.md(usage); manuals of contract (protocol), daemon, gateway ("Reads"), cli. - Tests:
src/contract/operations.test.ts,errors.test.ts,src/core/usage/*.test.ts,src/core/usage/usage-read.timing.test.ts(new),src/daemon/dispatcher.test.ts,server.test.ts,src/gateway/dispatcher.test.ts,src/simlock-client/client.test.ts,src/cli/index.test.ts,src/cli/stats.test.ts,e2e/usage-stats.test.ts(new).
flowchart LR
cli[cli*] --> client[simlock-client*] --> server[daemon/server*]
server --> wd[daemon/dispatcher*]
server --> gd[gateway/dispatcher*]
wd --> ur[core/usage* new]
gd --> ur
ur --> rows[history handle .usage, #630]
ur --> tok[token store]
cli --> win[contract/usage-window* new]
main[daemon/main*] --> ur
sequenceDiagram
participant C as simlock stats
participant D as daemon (worker or gateway)
participant R as usage reader (main thread)
participant T as read thread
participant H as history.db (#630 rows)
C->>D: usage.get { from, to }
D->>D: parse input (BAD_REQUEST), role (FORBIDDEN)
D->>R: get(input)
alt history.status().opened is false
R-->>D: { kind: "unavailable" }
D-->>C: HISTORY_UNAVAILABLE, exit 1
else
R->>T: post the floored window (or join the read in flight for it)
T->>H: one read transaction: oldestTs, requestRows, minuteBuckets, deviceFacts
alt oldest row later than to
T-->>R: { kind: "not-kept", oldestTs }
D-->>C: HISTORY_NOT_KEPT { oldestTs }, exit 12
else
T-->>R: figures
R->>R: labels (main thread)
D-->>C: output
end
end
Surface and extension points
src/contract/usage-window.ts:
export interface UsageWindowAsk { readonly since?: string; readonly from?: string; readonly to?: string }
export type UsageWindowRefusal =
| { readonly parameter: "from"; readonly problem: "since-and-from" } // since with from
| { readonly parameter: "to"; readonly problem: "to-without-from" }
| { readonly parameter: "from"; readonly problem: "not-before-to" }
| { readonly parameter: "since"; readonly problem: "bad-duration"; readonly value: string }
| { readonly parameter: "from" | "to"; readonly problem: "bad-time"; readonly value: string };
export function usageWindow(ask: UsageWindowAsk, now: number):
| { readonly window: { readonly from: number; readonly to: number } }
| { readonly refused: UsageWindowRefusal };- No flag → the last 24 hours to
now.since→now − sincetonow, byparseDurationMs.from→ toto, ornowwithout one. - A time is ISO 8601 with a
Zor a±HH:MMoffset, and nothing else:^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d{1,3})?)?(Z|[+-]\d{2}:\d{2})$, thenDate.parse, which must not beNaN. This is safety rule 10:Date.parsealone takes1,2026and10/15/2026. - It throws nothing and names no flag; each surface words the refusal. The CLI's words (Inputs table) use
--since,--from,--to;Invalid duration: <value>;Invalid time: <value> (use ISO 8601 with Z or an offset).
src/core/usage/index.ts exports createUsageReader(deps) → { get(input: UsageGetInput): Promise<UsageResult>; stop(): Promise<void> } and its types, where
type UsageResult =
| { readonly kind: "figures"; readonly usage: UsageGetOutput }
| { readonly kind: "not-kept"; readonly oldestTs: number }
| { readonly kind: "unavailable" };deps:
historyPath: the data directory'shistory.db, opened read-only by the read thread;opened(): boolean:history.status().opened, the read The event history is a SQLite file, history.db #629's handle givesstatus.get(feature Operational metrics kept over hours and shown in the console #623 Shared values, "status.gethistory").false→unavailablewithout posting to the thread;tokenLabels(): Promise<ReadonlyMap<string, string>>;workers(): { id, label? }[]: the worker itself, or the gateway's registry;fleet?: { requesterPrefix }: set on a gateway.
get floors from, then posts the window to one long-lived read thread (node:worker_threads, started on the first call). It keeps one promise per floored window in flight: a second get for the same { from, to } while one runs gets that promise. usageAnswer (src/daemon/dispatch.ts) maps not-kept to HISTORY_NOT_KEPT and unavailable to HISTORY_UNAVAILABLE.
What the read thread reads from the history module's handle history.usage (feature #623 Shared values, "history.usage"; #630 builds it):
| Read | Returns |
|---|---|
oldestTs(): number | undefined |
the earliest time over request rows (requestedAt), minute rows (minute start) and device fact rows (at); undefined when all are empty |
requestRows({ from, to }): RequestRow[] |
every request row with from ≤ requestedAt < to, fields as feature #623 Shared values "Request row", by requestedAt then requestId |
minuteBuckets({ from, to, bucketMs, workerId, platform }): MinuteBucket[] |
one entry per bucket with a known value for that workerId and platform, aggregated in SQL, carrying the last value across minutes with no row and stopping at a gap marker: { start, knownMs, <field>: { peak, integral } }, peak the largest minute peak, integral and knownMs the sums; a field never known in the bucket is absent |
deviceFacts({ from, to }): DeviceFactRow[] |
every device fact row with from ≤ at < to, fields as "Device fact row" |
The four run in one read transaction on the thread's read-only connection. No extension point.
Contract and event changes
This PR bumps the protocol by one.
- New operation
usage.get, roleadmin, effectread(feature Operational metrics kept over hours and shown in the console #623 Shared values, "usage.get";GET /v1/statsand thesimlock stats --csvledger #632 addsincludeLedger).- Input
{ from, to }: integers, 0 to 8.64e15 (F5),from < to,to - from≤ 90 days, checked on the asked window, before the floor. Anything else isBAD_REQUESTnaming the bound (F17). - Output: PR feat(usage): usage.get and simlock stats, the figures from the event history #356's
usageOutputSchema(F17), with these changes:- A series point is
{ at, leasesHeld, slotsUsed, slotsMax, ramUsedBytes?, queueDepth, waiting }: each the peak in its bucket,nullwhere the bucket has no row;ramUsedBytesabsent where no row has it. failures.byEventcountsdevice.recovery-failedonly.device.purge-failed,component.install-failedand the other*-failedcounts PR feat(usage): usage.get and simlock stats, the figures from the event history #356 had (F24) are dropped: no device fact row holds them.
- A series point is
- Input
- New error
HISTORY_NOT_KEPT:domain, exit 12, HTTP 422, details{ oldestTs }(F18). Message:The history does not reach back to the end of that window; its figures start at <ISO time of oldestTs>. - New error
HISTORY_UNAVAILABLE(feature Operational metrics kept over hours and shown in the console #623 Shared values, "HISTORY_UNAVAILABLE"):domain, exit 1, HTTP 503, no details, asDOCTOR_UNAVAILABLE(F16).usage.getanswers it whenhistory.dbcould not be opened. Message:The history could not be opened, so no figures can be read; see daemon.log. - No event changes.
How rows become figures (one function each, in src/core/usage/):
- Window. The bucket width is the smallest of the six whose floored window,
floor(from / w) × wtoto, has at most 200 points;fromis floored to it;tois not rounded. The answer'swindowis{ floored from, to }. - Requests. A request belongs to the window its
requestedAtfalls in. A grant, rejection or end aftertois unseen. A lease open attocounts as a request and a grant, with no held or turnaround sample (ADR 0016 §2). - Counts.
requestscounts rows with neitherprobenorrefusedAtAdmission.probescountsproberows; it is absent from a gateway's answer.rejectedcounts every non-probe row rejected byto, byreason,refusedAtAdmissionones included. A declined probe counts only underdeclined.grantedandbySourcecount every row granted byto, bysource, probes included.
- Samples.
- Wait is
(grantedAt or rejectedAt) − requestedAt; a probe or a refused-at-admission row gives none. - Held is the row's
heldMswhenendedAt ≤ to. - Turnaround is wait plus held.
- Provisioning is the
durationMsofdevice.provisionedfacts; boot is that ofdevice.readyfacts.
- Wait is
- Incidents from device facts:
quarantinedcountsdevice.quarantined.crashRecoveredcountsdevice.recovered.quarantineRecoveredcountsdevice.quarantine-recovered.lostcountsdevice.recovery-failed,device.quarantine-abandonedanddevice.quarantine-stranded.declinedcountslease.declined.
- Minute figures.
- The scope's peak is the largest bucket peak;
slots.maxis the largestslotsMaxpeak;ram.limitBytesis the largestramLimitBytespeak. - The mean is the sum of integrals over the sum of
knownMs,nullwith no rows. - Queue and RAM come from
allrows only.utilisation.ramis present only when a row of the scope in the window hasramUsedBytes; otherwise it is left out.
- The scope's peak is the largest bucket peak;
- Scopes.
totals: minute rowsworkerId ""(worker) or"*"(gateway), platformall, and every request row and device fact.platforms.iosandplatforms.android: the sameworkerIdwith that platform, and rows of that platform.workers: minute rows of thatworkerId, platformall, and rows whoseworkerIdit is (""or absent on a worker is the worker itself).- A gateway lists every registry worker and every
workerIdthe rows name. A fleet request with noworkerIdcounts in totals and its platform only.
- Series. From the totals' minute rows;
atis the bucket's end, the last oneto(F22). - Requesters. From request rows, counted as the totals count them: a refused-at-admission row under
rejected, notrequests.labelfrom the token store. A probe counts under itsgw:requester ingrantedandheldTotalMsonly. A gateway takes its own prefix off before the label lookup (F20). - Coverage.
coversFromis the later of the window's start andoldestTs.partialis true whencoversFromis later than the start.- With no rows,
coversFromis the start andpartialis false. HISTORY_NOT_KEPTwhenoldestTsis later thanto.
Other code on the same state
Searches: the projection tables (#629/#630, 0 hits on main); tokens.list() (2 hits: src/daemon/dispatcher.ts:967, src/gateway/dispatcher.ts:285); worker_threads (0 hits in src/).
| Component | What happens when both act | Wins |
|---|---|---|
| #630's projection step (writes rows on the main thread's connection) | The read thread holds one WAL read transaction for its four reads: a commit after it starts is not seen, and the writer never waits on it | Each answer is one snapshot |
#630's prune of rows by metrics.retention |
Same: the read sees the rows as they stood when its transaction began | — |
| #629's prune of events | Not read here; figures do not change when events go | — |
| #629/#630 start (set aside, rebuild) | opened false until the file is open → HISTORY_UNAVAILABLE; the read thread opens its connection on its first read after that |
— |
token.create/revoke |
Labels are a fresh list() per answer |
The store at read time |
Failure modes
| Call | Outcome | What happens | Limit, counted from |
|---|---|---|---|
CLI → daemon usage.get |
ok | figures printed, exit 0 | — |
| bad window | BAD_REQUEST naming the bound, exit 2 |
— | |
| agent session | FORBIDDEN, exit per table |
— | |
| window ends before oldest row | HISTORY_NOT_KEPT { oldestTs }, exit 12 |
— | |
| no daemon | launched as for every admin command (src/cli/AGENTS.md 3) |
5 s, from the first connect | |
| connection lost | DAEMON_CONNECTION_LOST |
— | |
reader → history.status() |
opened false |
HISTORY_UNAVAILABLE, exit 1, nothing posted (Tests) |
— |
| reader → read thread | ok, 7 days over 90 days of rows | answer; the main thread keeps serving leases | 500 ms, from the call (Tests) |
| a second call for the same window while one runs | waits for the first and gets its answer; one read (Tests) | the first's | |
| a read throws (SQLite error) | that call INTERNAL, logged at error (F15); the thread stays |
— | |
| the thread exits or crashes | every call in flight INTERNAL; the next call starts a new thread (Tests) |
— | |
| no answer | the call INTERNAL and the thread is terminated, then as a crash |
30 s, from the post | |
| daemon stop | stop() terminates the thread; calls in flight end with their connection |
— | |
| reader → token store | list() throws |
INTERNAL (F15; no new test) |
— |
Nothing is written. A restart mid-call leaves nothing. Two callers for one window share one read; for two windows, the thread reads them in turn.
Rules in play
- Architecture rule 1:
src/core/usage/imports no platform code. - Architecture rule 8: the CLI computes no figure; it parses flags and prints.
- Architecture rule 11: the read thread is in this process; its 30 s bound still ends a hung read.
- Architecture rule 10: window flags (
contract/usage-window.ts), bucket width, nearest rank, and wait, held and turnaround each live once. - Architecture rule 18:
src/core/usage/exportscreateUsageReaderand types only. - Safety rule 10: "validate shape and bounds before":
usageWindowtakes only strict ISO 8601 times, and the contract bounds the window before any read. - ADR 0016 §2, §5, §7, §8; ADR 0021 §5; ADR 0032 §2, §4, §5, §6.
- Documentation rule 2:
docs/CLI.mdnames no ADR; it drops PR feat(usage): usage.get and simlock stats, the figures from the event history #356's "maintenance" (F26). - Testing rule 2: each refusal test starts from an accepted input.
Tests
Seam: the usage.get handlers in src/daemon/dispatcher.test.ts and src/gateway/dispatcher.test.ts, over a real history.db in a tmp dir, with the real read thread. #629's writer and #630's projections are subscribed to a real EventBus, and rows are written by eventBus.emit with a fake clock. Model: PR #356's "Dispatcher: usage.get" and e2e/event-history.test.ts. CLI: src/cli/index.test.ts "CLI: stats" and src/cli/stats.test.ts from PR #356. usageWindow in src/contract/usage-window.test.ts.
- usage.get counts a request granted, held and released as one request, one grant, and one sample each of wait, held and turnaround, with the milliseconds the events were stamped apart
- usage.get reports wait p50, p95 and max by nearest rank over twenty known waits, and
nullwith count 0 over none - usage.get counts rejections under their reason (
timeout,no-wait,cancelled) and not under grants, and grants underwarm,bootedandprovisionedby their source - usage.get counts a request made before
fromand settled inside the window in no count, a lease open attoas a request and a grant with no held or turnaround sample, and a grant aftertoas a request only - usage.get counts a refused-at-admission rejection (
already-leased) underrejectedand not underrequests, in the totals and in its requester's entry alike - usage.get on a worker counts a probe under
probesandgranted, notrequests, with no wait or turnaround sample, a declined probe underdeclinedand notrejected, and lists the granted probe'sgw:requester with the grant and held time and no request - usage.get with
fleettakes a fleet grant's held time from the row'sheldMs, and answers noprobesfield in totals or worker entries - usage.get reports provisioning and boot p50, p95 and max from
device.provisionedanddevice.ready, and countsquarantined,crashRecovered,quarantineRecovered,lost(each of its three events),declinedandfailures.byEvent["device.recovery-failed"], one event of each - usage.get splits figures by platform and by worker: on a worker an iOS and an Android request land in their platform entries; on a gateway the platform entries read the
*rows of that platform and two workers' devices land in their worker entries - usage.get picks 1 min for 1 h, 5 min for 6 h, 15 min for 24 h, 1 h for 7 d, 6 h for 30 d and 1 day for 90 d, floors
fromto it, leavestoas asked, and picks 5 min for a 200-minute window starting at :30 s, which 1 min would cut into 201 points, and accepts exactly 90 days whosefromis off a bucket boundary though the floored window is longer - usage.get ends each series point at its bucket's end and the last at
to, gives it the peak of each field over the bucket (minutes peaking at 2 and 4 → 4), carries a value into a bucket with no row, givesnullin every field to a bucket after a gap marker with no row since, andramUsedBytesonly where a row has it - usage.get on a gateway takes the totals' slots peak from the
*rows: two workers peaking at 2 each, a minute apart, give 2, not 4 - usage.get reports a time-weighted slots, RAM and queue mean from the integrals (1 slot for 45 s, 3 for 15 s → 1.5),
ram.limitBytesfromramLimitBytes, and leavesutilisation.ramout when no row in the window hasramUsedBytes - usage.get sets
coversFromto the oldest row andpartialtrue when that row is inside the window,partialfalse when it is beforefrom, and covers any window with no rows - usage.get answers HISTORY_NOT_KEPT with
oldestTsand the messageThe history does not reach back to the end of that window; its figures start at <ISO>.whentois 1 ms before the oldest row, and figures whentois that row's time - the worker and the gateway handler answer HISTORY_UNAVAILABLE with the message
The history could not be opened, so no figures can be read; see daemon.log.whilehistory.status().openedis false, after answering figures while it was true - usage.get answers the same figures after The event history is a SQLite file, history.db #629's prune has removed every event of the window, from the rows alone
- usage.get runs two calls for one window as one read on the read thread and gives both its answer, and two windows as two reads
- usage.get answers INTERNAL to a call in flight when the read thread exits, and answers the next call from a new thread
- (timing) over 90 days of seeded rows — 3 minute rows a minute (
ios,android,all; 388,800), 100,000 request rows, 10,000 device facts — a 7-day call answers within 500 ms, and the main thread's event-loop delay stays under 50 ms throughout (src/core/usage/usage-read.timing.test.ts) - usage.get lists requesters by request count then id, with the token label of a known token, and none when the daemon has no token store; the gateway handler strips its own
gw:<instance>:prefix before the lookup and leaves another prefix alone - the worker handler answers one worker entry, itself, with its instance id and
gateway.label, or no label when none is set (F25); the gateway handler lists every registry worker with its label and a worker id the rows name that the registry lacks, and counts a fleet request with no worker in totals and its platform only usage.getis an admin operation an agent token cannot call, and its input refusesfromnot beforeto, a span of 90 days + 1 ms, a fraction, a negative, a bound above 8.64e15 and a string, after accepting{ from: 0, to: 1 }and exactly 90 days (PR feat(usage): usage.get and simlock stats, the figures from the event history #356 tests); HISTORY_NOT_KEPT is domain, exit 12, HTTP 422 witholdestTs, and HISTORY_UNAVAILABLE domain, exit 1, HTTP 503 with no details- the server routes a
usage.getframe to the dispatcher, and the admin client'susagereturns the daemon's answer (PR feat(usage): usage.get and simlock stats, the figures from the event history #356 tests) - usageWindow answers the last 24 hours with no field,
sinceback from now,fromtotoandfromto now, and refuses each of:sincewithfrom,towithoutfrom,fromnot beforeto, a bad duration, and the times1,2026,10/15/2026,2026-10-15T00:00(no zone) and2026-10-15T00:00 02:00, naming the parameter, after accepting2026-10-15T00:00Zand2026-10-15T00:00:00.5+02:00 - simlock stats words each refusal as the Inputs table says, exits 2, and asks
usage.getfor the windowusageWindowgives - simlock stats --json prints the operation's output unchanged, and prints the HISTORY_NOT_KEPT error line with exit 12
- formatUsage prints the header, the partial note when
partial, then totals, platforms, workers and requesters with labels, and theFailures:row (device.recovery-failed 1) only when there is one (PR feat(usage): usage.get and simlock stats, the figures from the event history #356stats.test.ts) - (e2e) after a scripted run against the fake driver with waits, a
--no-waitrefusal and a timeout,simlock stats --from <before the run> --to <after it, before the stop> --jsonreports the counts the test derives fromsimlock events, and prints the same stdout, byte for byte, aftersimlock daemon stopandsimlock daemon start - (e2e) on a gateway with two workers,
simlock stats --jsonhas fleet totals and one entry per worker, and each worker's own covers itself only - A window ending inside a running minute reports slot, RAM and queue figures for the complete minutes only.
- A
device.readywithbootDuration0 adds no boot tostats.
Done when
-
After a scripted run against the fake driver,
simlock stats --since 1hprints:- requests, and grants by source;
- wait, held, turnaround, provisioning and boot p50/p95/max;
- rejections by reason and incidents;
- use per platform, worker and requester.
--jsonprints the same figures, and the counts matchsimlock events --since 1hcounted by hand. -
simlock stats --from <before the run> --to <after it>, with--tobefore the stop, prints the same output, whole, aftersimlock daemon stopandsimlock daemon start. -
On a gateway with two workers, the output has fleet totals and one row per worker; each worker's own output has one row, itself.
-
simlock stats --since 30don a fresh install printsFigures cover from <time>above the figures; a window ending before the oldest row exits 12 with theHISTORY_NOT_KEPTmessage. -
simlock statswhilehistory.dbcould not be opened exits 1 withHISTORY_UNAVAILABLE. -
docs/CLI.mddescribessimlock stats, its flags, the partial note and exits 12 and 1;docs/CLIENT.mddescribesusage.
Out of scope
GET /v1/statsand the CSV ledger (GET /v1/statsand thesimlock stats --csvledger #632).- The console's Overview and Usage page (Overview and Waiting: a range picker, wait p95, leases granted and three charts #633, Console Usage page #634).
- Writing or pruning rows (Projections: request, minute and device fact rows #630).
Depends on
Written by an agent.
Activity
feat(usage): usage.get reads the history rows on a read thread (#631)
feat(cli): simlock stats prints the figures of a window (#631)
fix(usage): minute figures cover complete minutes, so a restart does …
docs: simlock stats, the client's usage, and the manuals of the usage…
docs: keep the gateway manual within its budget (#631)
refactor(usage): split the figure functions and drop unused re-exports (
refactor(usage): figuresFor takes its request figures from one functi…
fix(contract,test): usage window refuses a day the month lacks and ho…
test(usage): start the read thread before the timed 7-day call, so a …
fix(usage): a dropped read thread's late exit rejects only its own re…
feat(history): history.db, usage projections, simlock stats, GET /v1/…