Open History to see the last commit
1# Resource telemetry architecture
2
3> For maintainers. Using T3 Code? See [docs/user](../user/).
4
5Status: implemented
6
7## Purpose
8
9Resource telemetry replaces recurring `ps`, PowerShell, `ioreg`, and `pmset`
10subprocess probes with two persistent, direct data sources:
11
121. a standalone Rust resource-monitor executable that reads process counters
13 through operating-system APIs via `sysinfo`;
142. Electron main-process APIs for Electron process metrics and host power state.
15
16The native monitor owns bounded in-memory history. The server only merges and
17summarizes that history when diagnostics requests it. Telemetry history is not
18persisted to disk or continuously copied into Node.
19
20## Why a standalone executable
21
22The monitor is intentionally not a Node native addon.
23
24- No N-API, `ffi-rs`, or dynamic-library ABI is loaded into the server process.
25- A monitor crash cannot corrupt the Node runtime.
26- The server can supervise, restart, version-check, and measure the monitor as a
27 normal child process.
28- The same protocol works for the desktop app and the published CLI.
29- Packaging is a single platform executable instead of an addon toolchain plus
30 Node/Electron ABI matrix.
31
32The cost is one persistent child process and NDJSON serialization. That is a
33better failure boundary than repeatedly spawning shell utilities or loading
34native code into Node.
35
36## Runtime topology
37
38### Desktop
39
40```text
41Electron main
42 ├─ powerMonitor
43 ├─ app.getAppMetrics() while diagnostics is open
44 ├─ inherited fd 4, telemetry NDJSON ─────────────┐
45 └─ inherited fd 5, demand-control NDJSON ◀──────┤
46 ▼
47Node server ── stdin/stdout NDJSON ── Rust resource monitor
48 │
49 ├─ ResourceTelemetry Effect service
50 ├─ background power policy projection
51 └─ WebSocket RPC/subscription ── diagnostics UI
52```
53
54### Web, headless, and remote server
55
56Electron telemetry is unavailable. The native monitor still runs beside the
57server and tracks the server process tree. Power fields degrade to `unknown`
58instead of invoking platform shell commands.
59
60### WSL backend limitation
61
62Windows desktop packages currently ship the Windows resource-monitor executable.
63That executable cannot run inside the Linux WSL backend, so a WSL-only backend
64does not receive `resourceMonitorPath` and reports native process telemetry as
65unavailable. Electron host-power telemetry remains available over the inherited
66desktop pipe. Supporting native WSL process telemetry requires publishing a
67Linux sidecar for each supported architecture in the Windows artifact and
68converting its packaged path into the selected distro; the configuration
69deliberately does not pass the Windows `.exe` into WSL as a false fallback.
70
71## Native monitor
72
73The executable lives in `native/resource-monitor`.
74
75It receives schema-compatible commands on stdin and emits one JSON object per
76line on stdout:
77
78- `configure`
79- `setExternalProcesses`
80- `setSampleInterval`
81- `setStreaming`
82- `sampleNow`
83- `readHistory`
84- `shutdown`
85- `hello`
86- `snapshot`
87- `historyChunk`
88- `error`
89
90The protocol version is defined by
91`RESOURCE_MONITOR_PROTOCOL_VERSION` in
92`packages/contracts/src/resourceTelemetry.ts`.
93
94### Collection
95
96The monitor keeps one `sysinfo::System` instance and refreshes it at the
97power-adaptive interval selected by the server. It collects:
98
99- PID and parent PID;
100- process start time and run time;
101- process name and command line;
102- current and cumulative CPU usage;
103- resident and virtual memory;
104- cumulative process I/O counters.
105
106On Linux, task/thread enumeration is disabled. Command lines are loaded only
107when first needed. This avoids the expensive default behavior of walking every
108`/proc/<pid>/task/<tid>` directory on each refresh.
109
110### Process-tree selection
111
112Each sample scans the accessible process table, builds the PID/PPID graph, and
113retains:
114
115- the server process;
116- every descendant of the server, including provider-spawned grandchildren such
117 as shells, `node`, `tsgo`, language servers, and other tools;
118- Electron processes supplied as explicit external roots;
119- descendants of those Electron roots;
120- the resource monitor itself, because it is a server child.
121
122Process identity is `(pid, startTimeMs)`, not PID alone. Electron and native
123start times are matched with a two-second tolerance because native start times
124can have coarser platform resolution.
125
126The process list is emitted in depth-first tree order so renderer collapse and
127expansion preserves complete subtrees.
128
129### Native history and streaming
130
131Every native sample is appended to a one-hour in-memory ring bounded to 3,600
132snapshots, 20,000 retained process rows, and 64 MiB of retained history bytes.
133History stays in the sidecar until a `readHistory` request and is returned in
134bounded chunks. The first bound reached wins, so high process counts or large
135process names and command lines shorten the effective history window.
136
137Periodic snapshot streaming is disabled by default. The server enables it only
138while at least one diagnostics subscription is retained. `sampleNow` remains
139available for explicit refreshes and identity validation.
140
141The server adjusts native sampling without restarting the sidecar:
142
143- suspended, locked, low-power, or serious/critical thermal state: 15 seconds;
144- battery: 5 seconds;
145- normal AC: 1 second;
146- unknown or stale power: 5 seconds in the background and 1 second while live
147 diagnostics is open.
148
149### Sampling limits
150
151This is counter sampling, not syscall tracing.
152
153- A process that starts and exits entirely between samples may not be observed.
154- Cumulative CPU and I/O counters still provide accurate deltas for processes
155 that survive across samples.
156- Exact file paths, individual write syscalls, ETW events, eBPF events, and
157 Endpoint Security events are outside this implementation.
158
159Those deeper tracing systems can be added later as opt-in diagnostic modes
160without changing the public `ResourceTelemetry` model.
161
162## I/O semantics
163
164The monitor preserves platform semantics instead of presenting all counters as
165equivalent:
166
167- Unix-like platforms report storage I/O counters exposed by `sysinfo`.
168- Windows reports all process I/O bytes, not only disk bytes.
169- Operating-system caches can prevent logical application reads or writes from
170 appearing as physical storage bytes.
171
172The UI therefore labels these values as I/O reads and writes and exposes the
173per-process `ioSemantics` value.
174
175Group totals are observed deltas since telemetry startup. Per-process total
176columns are the operating system's cumulative counters for that process.
177
178## Electron telemetry
179
180Electron main owns `DesktopTelemetryPublisher`.
181
182Power events trigger an immediate snapshot. While diagnostics is closed, the
183server sends the configured active and idle host-power intervals to Electron
184(30 seconds and 2 minutes in the balanced profile). During those heartbeats
185Electron reads:
186
187- `powerMonitor.isOnBatteryPower()`;
188- `powerMonitor.getSystemIdleTime()`;
189- `powerMonitor.getSystemIdleState()`;
190- `powerMonitor.getCurrentThermalState()`.
191
192`app.getAppMetrics()` is only called while diagnostics demand is active. Its
193live cadence is 1 second on AC, 5 seconds on battery, and 15 seconds while
194locked, suspended, or thermally constrained.
195
196It also listens for:
197
198- lock and unlock;
199- suspend and resume;
200- AC and battery transitions;
201- thermal-state changes;
202- CPU speed-limit changes.
203
204Suspension stays latched across event-driven snapshots. An explicit resume
205clears it immediately; a periodic heartbeat also clears a stale latch so a
206missed resume event cannot leave telemetry permanently constrained.
207
208Electron does not expose a cross-platform low-power-mode getter, so that field
209remains `unknown`.
210
211The desktop backend is spawned with:
212
213- fd 3 for the existing bootstrap payload;
214- fd 4 for Electron-to-server telemetry NDJSON;
215- fd 5 for server-to-Electron diagnostics-demand NDJSON.
216
217These are private Electron-main/server pipes. They do not use the renderer
218WebSocket and are recreated for every backend restart.
219
220## Server Effect services
221
222The implementation is under `apps/server/src/resourceTelemetry`.
223
224### `ResourceMonitorBinary`
225
226Resolves an executable from:
227
2281. `T3CODE_RESOURCE_MONITOR_PATH`;
2292. desktop bootstrap configuration;
2303. bundled CLI resources;
2314. local Cargo build outputs.
232
233Unsupported platforms, missing binaries, and non-executable binaries use
234schema-backed tagged errors with descriptive messages.
235
236### `NativeTelemetryClient`
237
238Owns the resource-monitor process and protocol.
239
240- validates the hello/version handshake;
241- sends configuration and external process roots;
242- adapts the native interval from host power state;
243- enables streaming only for scoped live subscribers;
244- reads chunked native history on demand;
245- exposes `sampleNow`;
246- serializes commands;
247- supervises process exit and protocol failure;
248- restarts with bounded exponential backoff;
249- opens a circuit after repeated failures;
250- supports explicit retry;
251- publishes health changes immediately.
252
253Snapshot sequence numbers are scoped to a monitor generation. Server ingestion
254uses the monitor restart count as the generation key, so sequence reset after a
255restart cannot freeze telemetry.
256
257### `DesktopTelemetryReceiver`
258
259Reads fd 4, decodes schema-validated messages, stores the latest Electron
260snapshot, and publishes desktop health. It writes diagnostics demand to fd 5
261and gives the first sample a 90-second startup deadline. Once samples arrive,
262the stale deadline stays beyond the slower configured host-power interval with
26330 seconds of scheduling grace, so intentional 2–10 minute idle polling does
264not oscillate the policy between constrained and unconstrained states. Decode
265errors, protocol mismatch, control-write failure, stream failure, stale input,
266and normal stream closure are represented explicitly.
267
268### `ResourceTelemetry`
269
270Merges native and Electron data and owns public telemetry semantics.
271
272- calculates CPU and I/O rates from cumulative native counters;
273- preserves the last native rates during desktop-only updates;
274- classifies backend, Electron, and monitor processes;
275- computes process depth and child relationships;
276- tracks starts, exits, CPU time, and observed I/O;
277- projects power data;
278- acquires native streaming and Electron process metrics only for scoped live
279 subscribers;
280- queries and replays native history only when requested;
281- validates `(pid, startTimeMs)` before process signaling;
282- updates history health even when no further native sample arrives.
283
284Electron and monitor processes are visible but are not valid targets for the
285existing process-signal RPC.
286
287### History projection
288
289`ResourceTelemetryHistory` is a pure on-demand projection. It replays raw native
290snapshots to derive rates, lifecycle counters, buckets, and process summaries.
291Current Electron process metrics are intentionally excluded from historical
292replay so they cannot overwrite older native CPU or memory samples.
293
294### `ResourceAttribution`
295
296Tracks known logical application I/O separately from OS counters. Current
297integration points record successful writes for:
298
299- provider native and canonical event logs;
300- the local server trace sink.
301
302Entries contain component, operation, logical bytes, count, and elapsed time.
303Future persistence paths should call `ResourceAttribution.record` rather than
304adding diagnostics-specific counters.
305
306## Background policy integration
307
308`HostPowerMonitor` consumes `DesktopTelemetryReceiver` directly; observing host
309power does not retain live resource diagnostics or invoke shell probes.
310
311The monitor updates its latest timestamp on every Electron sample but only
312publishes semantic state changes. Increasing idle seconds alone does not cause a
313background-policy broadcast every second.
314
315## Public API and UI
316
317The WebSocket RPC surface provides:
318
319- current snapshot;
320- bounded history;
321- explicit monitor retry;
322- a live snapshot subscription.
323
324The diagnostics page displays:
325
326- aggregate CPU, memory, I/O, and process counts;
327- backend, Electron, and monitor overhead groups;
328- power and thermal state;
329- collector health and restart information;
330- CPU and I/O history;
331- a collapsible live process tree;
332- safe process signaling for backend descendants;
333- instrumented logical application I/O.
334
335Legacy process diagnostics RPCs are projected from the same service so they no
336longer start recurring process-table commands.
337
338## Packaging
339
340Desktop artifact builds compile the Rust target, stage it as
341`resources/resource-monitor/t3-resource-monitor[.exe]`, and pass its path to the
342backend bootstrap.
343
344CLI release jobs upload each active platform monitor artifact and copy it into:
345
346```text
347apps/server/dist/resource-monitor/<platform>-<arch>/
348```
349
350The published server package already includes `dist`, so those executables ship
351with the CLI. Missing platform artifacts degrade native telemetry to
352`unavailable`; the server continues running.
353
354## Resource and failure behavior
355
356Steady state uses:
357
358- one native process;
359- power-adaptive native counter sampling with no periodic Node snapshot stream;
360- event-driven Electron power updates plus profile-driven heartbeats (30–60
361 seconds while active and 2–10 minutes while idle);
362- no `app.getAppMetrics()` calls while diagnostics is closed;
363- no telemetry database;
364- no recurring shell probes;
365- bounded PubSub queues and native ring history.
366
367The diagnostics page exposes the monitor's own process resource usage and
368collection duration so the observer's cost is measurable.
369
370Failures are isolated:
371
372- native failure does not stop the server;
373- Electron telemetry loss does not stop native telemetry;
374- schema/version errors are visible in health;
375- repeated native failures stop automatic restart churn until explicit retry;
376- server and desktop shutdown close their respective streams and child process
377 scopes.
378
379## Future integration points
380
381High-value follow-up work can use the existing service boundaries:
382
383- opt-in file-path attribution through platform-specific tracing;
384- process lifecycle events to reduce the chance of missing very short-lived
385 children;
386- additional `ResourceAttribution` instrumentation for databases, checkpoints,
387 caches, and file synchronization;
388- exported diagnostic bundles;
389- adaptive sample intervals based on diagnostics visibility and active work.
390
391These additions should preserve the current rules: direct platform APIs,
392schema-validated boundaries, explicit metric semantics, bounded retention, and
393no mandatory telemetry persistence.