Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

resource-telemetry.md

394 lines14.3 KB

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 refreshed with
107each sample so process replacements remain visible. Disabling task enumeration
108avoids walking every `/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: 5 seconds in the background and 1 second while live diagnostics is
146 open;
147- unknown or stale power: 5 seconds in the background and 1 second while live
148 diagnostics is open.
149​
150### Sampling limits
151​
152This is counter sampling, not syscall tracing.
153​
154- A process that starts and exits entirely between samples may not be observed.
155- Cumulative CPU and I/O counters still provide accurate deltas for processes
156 that survive across samples.
157- Exact file paths, individual write syscalls, ETW events, eBPF events, and
158 Endpoint Security events are outside this implementation.
159​
160Those deeper tracing systems can be added later as opt-in diagnostic modes
161without changing the public `ResourceTelemetry` model.
162​
163## I/O semantics
164​
165The monitor preserves platform semantics instead of presenting all counters as
166equivalent:
167​
168- Unix-like platforms report storage I/O counters exposed by `sysinfo`.
169- Windows reports all process I/O bytes, not only disk bytes.
170- Operating-system caches can prevent logical application reads or writes from
171 appearing as physical storage bytes.
172​
173The UI therefore labels these values as I/O reads and writes and exposes the
174per-process `ioSemantics` value.
175​
176Group totals are observed deltas since telemetry startup. Per-process total
177columns are the operating system's cumulative counters for that process.
178​
179## Electron telemetry
180​
181Electron main owns `DesktopTelemetryPublisher`.
182​
183Power events trigger an immediate snapshot. While diagnostics is closed, the
184server sends the configured active and idle host-power intervals to Electron
185(30 seconds and 2 minutes in the balanced profile). During those heartbeats
186Electron reads:
187​
188- `powerMonitor.isOnBatteryPower()`;
189- `powerMonitor.getSystemIdleTime()`;
190- `powerMonitor.getSystemIdleState()`;
191- `powerMonitor.getCurrentThermalState()`.
192​
193`app.getAppMetrics()` is only called while diagnostics demand is active. Its
194live cadence is 1 second on AC, 5 seconds on battery, and 15 seconds while
195locked, suspended, or thermally constrained.
196​
197It also listens for:
198​
199- lock and unlock;
200- suspend and resume;
201- AC and battery transitions;
202- thermal-state changes;
203- CPU speed-limit changes.
204​
205Suspension stays latched across event-driven snapshots. An explicit resume
206clears it immediately; a periodic heartbeat also clears a stale latch so a
207missed resume event cannot leave telemetry permanently constrained.
208​
209Electron does not expose a cross-platform low-power-mode getter, so that field
210remains `unknown`.
211​
212The desktop backend is spawned with:
213​
214- fd 3 for the existing bootstrap payload;
215- fd 4 for Electron-to-server telemetry NDJSON;
216- fd 5 for server-to-Electron diagnostics-demand NDJSON.
217​
218These are private Electron-main/server pipes. They do not use the renderer
219WebSocket and are recreated for every backend restart.
220​
221## Server Effect services
222​
223The implementation is under `apps/server/src/resourceTelemetry`.
224​
225### `ResourceMonitorBinary`
226​
227Resolves an executable from:
228​
2291. `T3CODE_RESOURCE_MONITOR_PATH`;
2302. desktop bootstrap configuration;
2313. bundled CLI resources;
2324. local Cargo build outputs.
233​
234Unsupported platforms, missing binaries, and non-executable binaries use
235schema-backed tagged errors with descriptive messages.
236​
237### `NativeTelemetryClient`
238​
239Owns the resource-monitor process and protocol.
240​
241- validates the hello/version handshake;
242- sends configuration and external process roots;
243- adapts the native interval from host power state;
244- enables streaming only for scoped live subscribers;
245- reads chunked native history on demand;
246- exposes `sampleNow`;
247- serializes commands;
248- supervises process exit and protocol failure;
249- restarts with bounded exponential backoff;
250- opens a circuit after repeated failures;
251- supports explicit retry;
252- publishes health changes immediately.
253​
254Snapshot sequence numbers are scoped to a monitor generation. Server ingestion
255uses the monitor restart count as the generation key, so sequence reset after a
256restart cannot freeze telemetry.
257​
258### `DesktopTelemetryReceiver`
259​
260Reads fd 4, decodes schema-validated messages, stores the latest Electron
261snapshot, and publishes desktop health. It writes diagnostics demand to fd 5
262and gives the first sample a 90-second startup deadline. Once samples arrive,
263the stale deadline stays beyond the slower configured host-power interval with
26430 seconds of scheduling grace, so intentional 2–10 minute idle polling does
265not oscillate the policy between constrained and unconstrained states. Decode
266errors, protocol mismatch, control-write failure, stream failure, stale input,
267and normal stream closure are represented explicitly.
268​
269### `ResourceTelemetry`
270​
271Merges native and Electron data and owns public telemetry semantics.
272​
273- calculates CPU and I/O rates from cumulative native counters;
274- preserves the last native rates during desktop-only updates;
275- classifies backend, Electron, and monitor processes;
276- computes process depth and child relationships;
277- tracks starts, exits, CPU time, and observed I/O;
278- projects power data;
279- acquires native streaming and Electron process metrics only for scoped live
280 subscribers;
281- queries and replays native history only when requested;
282- validates `(pid, startTimeMs)` before process signaling;
283- updates history health even when no further native sample arrives.
284​
285Electron and monitor processes are visible but are not valid targets for the
286existing process-signal RPC.
287​
288### History projection
289​
290`ResourceTelemetryHistory` is a pure on-demand projection. It replays raw native
291snapshots to derive rates, lifecycle counters, buckets, and process summaries.
292Current Electron process metrics are intentionally excluded from historical
293replay so they cannot overwrite older native CPU or memory samples.
294​
295### `ResourceAttribution`
296​
297Tracks known logical application I/O separately from OS counters. Current
298integration points record successful writes for:
299​
300- provider native and canonical event logs;
301- the local server trace sink.
302​
303Entries contain component, operation, logical bytes, count, and elapsed time.
304Future persistence paths should call `ResourceAttribution.record` rather than
305adding diagnostics-specific counters.
306​
307## Background policy integration
308​
309`HostPowerMonitor` consumes `DesktopTelemetryReceiver` directly; observing host
310power does not retain live resource diagnostics or invoke shell probes.
311​
312The monitor updates its latest timestamp on every Electron sample but only
313publishes semantic state changes. Increasing idle seconds alone does not cause a
314background-policy broadcast every second.
315​
316## Public API and UI
317​
318The WebSocket RPC surface provides:
319​
320- current snapshot;
321- bounded history;
322- explicit monitor retry;
323- a live snapshot subscription.
324​
325The diagnostics page displays:
326​
327- aggregate CPU, memory, I/O, and process counts;
328- backend, Electron, and monitor overhead groups;
329- power and thermal state;
330- collector health and restart information;
331- CPU and I/O history;
332- a collapsible live process tree;
333- safe process signaling for backend descendants;
334- instrumented logical application I/O.
335​
336Legacy process diagnostics RPCs are projected from the same service so they no
337longer start recurring process-table commands.
338​
339## Packaging
340​
341Desktop artifact builds compile the Rust target, stage it as
342`resources/resource-monitor/t3-resource-monitor[.exe]`, and pass its path to the
343backend bootstrap.
344​
345CLI release jobs upload each active platform monitor artifact and copy it into:
346​
347```text
348apps/server/dist/resource-monitor/<platform>-<arch>/
349```
350​
351The published server package already includes `dist`, so those executables ship
352with the CLI. Missing platform artifacts degrade native telemetry to
353`unavailable`; the server continues running.
354​
355## Resource and failure behavior
356​
357Steady state uses:
358​
359- one native process;
360- power-adaptive native counter sampling with no periodic Node snapshot stream;
361- event-driven Electron power updates plus profile-driven heartbeats (30–60
362 seconds while active and 2–10 minutes while idle);
363- no `app.getAppMetrics()` calls while diagnostics is closed;
364- no telemetry database;
365- no recurring shell probes;
366- bounded PubSub queues and native ring history.
367​
368The diagnostics page exposes the monitor's own process resource usage and
369collection duration so the observer's cost is measurable.
370​
371Failures are isolated:
372​
373- native failure does not stop the server;
374- Electron telemetry loss does not stop native telemetry;
375- schema/version errors are visible in health;
376- repeated native failures stop automatic restart churn until explicit retry;
377- server and desktop shutdown close their respective streams and child process
378 scopes.
379​
380## Future integration points
381​
382High-value follow-up work can use the existing service boundaries:
383​
384- opt-in file-path attribution through platform-specific tracing;
385- process lifecycle events to reduce the chance of missing very short-lived
386 children;
387- additional `ResourceAttribution` instrumentation for databases, checkpoints,
388 caches, and file synchronization;
389- exported diagnostic bundles;
390- adaptive sample intervals based on diagnostics visibility and active work.
391​
392These additions should preserve the current rules: direct platform APIs,
393schema-validated boundaries, explicit metric semantics, bounded retention, and
394no mandatory telemetry persistence.