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

observability.md

736 lines26.6 KB

1# Observability
2​
3> For maintainers. Using T3 Code? See [docs/user](../user/).
4​
5T3 Code has one server-side observability model:
6​
7- pretty logs go to stdout for humans
8- completed spans go to a local NDJSON trace file
9- traces, metrics, and logs can also be exported over OTLP to a real backend like Grafana LGTM
10​
11The local trace file is the persisted source of truth for normal local launches. Those launches do not
12write a separate server log file, but SSH-managed launches also persist the remote process's
13stdout/stderr at `~/.t3/ssh-launch/<state>/server.log`.
14​
15## Where To Find Things
16​
17### Logs
18​
19Logs are human-facing:
20​
21- destination: stdout
22- format: `Logger.consolePretty()`
23- normal local persistence: none
24- SSH-managed launch persistence: `~/.t3/ssh-launch/<state>/server.log`
25- remote export: OTLP only, when configured
26​
27If you want a log message to show up in the trace file, emit it inside an active span with `Effect.log...`. `Logger.tracerLogger` will attach it as a span event.
28​
29Configuring a logs endpoint takes over that job. The server then exports log records, which cover
30every message instead of only the ones inside an active span and carry the trace and span ids so
31they still line up with the trace. `Logger.tracerLogger` is dropped in that mode, so the same
32message is not exported twice and the trace file stops carrying log messages. stdout output and
33SSH-managed launch persistence stay unchanged either way.
34​
35### Traces
36​
37Completed spans are written as NDJSON records to `serverTracePath`. The default depends on how the
38server starts: production and explicitly configured homes use
39`<home>/userdata/logs/server.trace.ndjson` (so `~/.t3/userdata/...` by default, or
40`/custom/path/userdata/...` with `--home-dir /custom/path`), a linked worktree dev run uses
41`<worktree>/.t3/userdata/logs/server.trace.ndjson`, and an implicit dev run outside a linked
42worktree uses `~/.t3/dev/logs/server.trace.ndjson`.
43​
44Important fields common to both record types:
45​
46- `type`: `effect-span` or `otlp-span`
47- `name`: span name
48- `traceId`, `spanId`, `parentSpanId`: correlation
49- `durationMs`: elapsed time
50- `attributes`: structured context
51- `events`: embedded logs and custom events
52​
53`effect-span` records also contain `exit` with `Success`, `Failure`, or `Interrupted`. `otlp-span`
54records instead carry OTLP resource, scope, and optional status fields.
55​
56The `TraceRecord`, `EffectTraceRecord`, and `OtlpTraceRecord` schemas live in
57`packages/shared/src/observability.ts`.
58​
59SQL statement spans (named `sqlite`) and `sql.transaction` spans carry `db.connection` and
60`db.lock_wait_ms`. `db.connection` is `writer` for the main connection, which runs on the event loop,
61or `reader` for the read-only connection in a worker thread. `db.lock_wait_ms` is the part of the
62span spent waiting for that connection, behind other SQL. That wait does not block the event loop,
63so subtract it before you blame a slow span on the query. Statements inside a transaction use its
64connection and do not carry these attributes.
65​
66An MCP request over HTTP has a `McpHttpServer.authenticateRequest` span that covers only admitting
67it: the credential check, the mode limit, and the Linked environments gate. The request runs after
68it, under the `McpServer.…/<method>` span, and each tool call has its own `mcp.tool.<name>` span
69that times it. That span's attributes name the tool, never its arguments.
70​
71DPoP proof failures include the safe `environment.dpop.failure_code` span
72attribute. A `time_window` failure means that a signed proof was too old or too
73far in the future for the environment server's allowed window. It can point to
74a date or time problem on either device, but it can also result from a delayed
75request.
76​
77#### Summarize the trace file
78​
79`t3 trace summary` reads the trace file and its rotated backups directly, so it works while the
80server is stalled or stopped. It prints counts, rates, and latency percentiles per span name. Use
81it to measure background work or to compare two builds.
82​
83```bash
84t3 trace summary --since 30m --limit 40
85```
86​
87It reads `T3CODE_TRACE_FILE` if set, else `<home>/userdata/logs/server.trace.ndjson` for
88`--base-dir` or `T3CODE_HOME`, plus the `T3CODE_TRACE_MAX_FILES` rotated backups. For a dev run or
89a copied file, set `T3CODE_TRACE_FILE`. `--since 30m` keeps spans that ended in the last 30
90minutes. The rate is per minute between the first and last span end.
91​
92### Metrics
93​
94Metrics are not written to a local file.
95​
96- local persistence: none
97- remote export: OTLP only, when configured
98- current definitions: `apps/server/src/observability/Metrics.ts`
99​
100If OTLP is not configured, metrics still exist in-process, but you will not have a local artifact to inspect.
101​
102### Event Loop Stalls
103​
104`apps/server/src/observability/EventLoopMonitor.ts` samples the server's event loop every 30 s. When
105the loop stalled for more than 2 s since the previous sample, it records a root
106`server.eventLoop.stall` span with a warning. The span has trace level `Warn`, so it stays when
107`T3CODE_TRACE_MIN_LEVEL` is `Warn`. The warning shows in Settings > Diagnostics unless OTLP logs are
108on. The span time is when the sample ran, not when the stall happened.
109​
110The trace file rotates in well under an hour on a busy server, so each stall is also appended as one
111NDJSON line to `event-loop-stalls.ndjson`, next to the trace file. A line has `time` and the span
112attributes. The file keeps the last 1000 or more stalls, with one rotated backup
113(`event-loop-stalls.ndjson.1`). Use it to see how often a server stalls over days.
114​
115Some delay is not recorded:
116​
117- `delayMaxMs` is the longest stall, and can undercount it by up to 1 s. The 2 s threshold applies to
118 this value, so a stall over 3 s is normally recorded, and a shorter one can be missed. A stall
119 that ends just as a sample runs can be missed too.
120- Time the computer spends asleep reads as delay on macOS and Windows. So a sample only counts when
121 the loop was busy, not waiting for events, for at least `delayMaxMs`. Busy time covers the whole
122 window, so a short sleep in an otherwise busy window can still record a false stall. The span then
123 shows CPU time far below `delayMaxMs`.
124- The first sample after launch is skipped. Startup work such as migrations and projection bootstrap
125 can block the loop for seconds on a large database.
126​
127CPU times and page faults cover the whole process over the whole window since the previous sample.
128The window is nominally 30 s, but a long stall delays the sample and makes the window longer. Other
129work in the window can hide a wait, so only CPU time far below `delayMaxMs` proves the thread was
130waiting. Read CPU together with page faults:
131​
132- High `cpuSystemMs` with many page faults means memory pressure. Major faults are reads from disk or swap.
133 On macOS, reads from compressed memory are minor faults plus system CPU.
134- High `cpuUserMs` with few page faults means JavaScript work or garbage collection.
135- Low CPU with few major page faults points at synchronous disk I/O, such as SQLite reads or trace
136 file writes.
137- Many `involuntaryContextSwitches` mean other processes were competing for the CPU.
138​
139### Related Artifacts
140​
141Provider event NDJSON files still exist for provider runtime streams. Those are separate from the main server trace file.
142​
143## Run The Server In Instrumented Mode
144​
145There are two useful modes:
146​
147- local-only: stdout + local `server.trace.ndjson`
148- full local observability: stdout + local trace file + OTLP export to Grafana/Tempo/Prometheus
149​
150The local trace file is always on. OTLP export is opt-in.
151​
152### Option 1: Local Traces Only
153​
154You do not need any extra env vars. Just run the app normally and inspect `server.trace.ndjson`.
155​
156Examples:
157​
158```bash
159t3
160```
161​
162```bash
163node --run dev
164```
165​
166```bash
167node --run dev:desktop
168```
169​
170### Option 2: Run With A Local LGTM Stack
171​
172#### 1. Start Grafana LGTM
173​
174```bash
175docker run --name lgtm \
176 -p 3000:3000 \
177 -p 4317:4317 \
178 -p 4318:4318 \
179 --rm -ti \
180 grafana/otel-lgtm
181```
182​
183Then open `http://localhost:3000`.
184​
185Default Grafana login:
186​
187- username: `admin`
188- password: `admin`
189​
190#### 2. Export OTLP env vars
191​
192For endpoint settings and startup precedence, see the
193[user telemetry guide](../user/telemetry.md#export-diagnostics-to-your-own-receiver).
194In a worktree, use `vp run dev` instead of `t3` to keep state isolated.
195​
196```bash
197export T3CODE_OTLP_TRACES_URL=http://localhost:4318/v1/traces
198export T3CODE_OTLP_METRICS_URL=http://localhost:4318/v1/metrics
199export T3CODE_OTLP_LOGS_URL=http://localhost:4318/v1/logs
200export OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=development
201```
202​
203Optional:
204​
205```bash
206export T3CODE_TRACE_MIN_LEVEL=Info
207export T3CODE_TRACE_TIMING_ENABLED=true
208```
209​
210#### 3. Launch the app from that same shell
211​
212CLI:
213​
214```bash
215t3
216```
217​
218Monorepo web/server dev:
219​
220```bash
221node --run dev
222```
223​
224Monorepo desktop dev:
225​
226```bash
227node --run dev:desktop
228```
229​
230Packaged desktop app:
231​
232Launch the actual app executable from the same shell so the desktop app and embedded backend inherit `T3CODE_OTLP_*`.
233​
234macOS app bundle example:
235​
236```bash
237T3CODE_OTLP_TRACES_URL=http://localhost:4318/v1/traces \
238T3CODE_OTLP_METRICS_URL=http://localhost:4318/v1/metrics \
239T3CODE_OTLP_LOGS_URL=http://localhost:4318/v1/logs \
240"/Applications/T3 Code.app/Contents/MacOS/T3 Code"
241```
242​
243Direct binary example:
244​
245```bash
246T3CODE_OTLP_TRACES_URL=http://localhost:4318/v1/traces \
247T3CODE_OTLP_METRICS_URL=http://localhost:4318/v1/metrics \
248T3CODE_OTLP_LOGS_URL=http://localhost:4318/v1/logs \
249./path/to/your/desktop-app-binary
250```
251​
252Do not rely on launching from Finder, Spotlight, the dock, or the Start menu after setting shell env vars. Those launches usually will not pick them up.
253​
254#### 4. Fully restart after changing env
255​
256The backend reads observability config at process start. If you change OTLP env vars, stop the app completely and start it again.
257​
258## How To Use Traces And Metrics To Debug The Server
259​
260### Start With The Local Trace File
261​
262The trace file is the fastest way to inspect raw span data.
263​
264Resolve the path for the launch mode once. Production and explicitly configured homes store runtime
265state under the base directory's `userdata` folder:
266​
267```bash
268TRACE_FILE="${T3CODE_HOME:-$HOME/.t3}/userdata/logs/server.trace.ndjson"
269```
270​
271A dev server started from a linked worktree defaults to that worktree's local home:
272​
273```bash
274TRACE_FILE="$WORKTREE/.t3/userdata/logs/server.trace.ndjson"
275```
276​
277Only an implicit dev run outside a linked worktree uses the shared dev directory:
278​
279```bash
280TRACE_FILE="$HOME/.t3/dev/logs/server.trace.ndjson"
281```
282​
283Tail the selected file:
284​
285```bash
286tail -f "$TRACE_FILE"
287```
288​
289Show failed spans:
290​
291```bash
292jq -c 'select(.type == "effect-span" and .exit._tag != "Success") | {
293 name,
294 durationMs,
295 exit,
296 attributes
297}' "$TRACE_FILE"
298```
299​
300Show slow spans:
301​
302```bash
303jq -c 'select(.durationMs > 1000) | {
304 name,
305 durationMs,
306 traceId,
307 spanId
308}' "$TRACE_FILE"
309```
310​
311Inspect embedded log events:
312​
313```bash
314jq -c 'select(any(.events[]?; .attributes["effect.logLevel"] != null)) | {
315 name,
316 durationMs,
317 events: [
318 .events[]
319 | select(.attributes["effect.logLevel"] != null)
320 | {
321 message: .name,
322 level: .attributes["effect.logLevel"]
323 }
324 ]
325}' "$TRACE_FILE"
326```
327​
328Follow one trace:
329​
330```bash
331jq -r 'select(.traceId == "TRACE_ID_HERE") | [
332 .name,
333 .spanId,
334 (.parentSpanId // "-"),
335 .durationMs
336] | @tsv' "$TRACE_FILE"
337```
338​
339Filter orchestration commands:
340​
341```bash
342jq -c 'select(.attributes["orchestration_v2.command_type"] != null) | {
343 name,
344 durationMs,
345 commandType: .attributes["orchestration_v2.command_type"],
346 threadId: .attributes["orchestration_v2.thread_id"]
347}' "$TRACE_FILE"
348```
349​
350Filter git activity:
351​
352```bash
353jq -c 'select(.attributes["git.operation"] != null) | {
354 name,
355 durationMs,
356 operation: .attributes["git.operation"],
357 cwd: .attributes["git.cwd"],
358 hookEvents: [
359 .events[]
360 | select(.name == "git.hook.started" or .name == "git.hook.finished")
361 ]
362}' "$TRACE_FILE"
363```
364​
365### Use Tempo When You Need A Real Trace Viewer
366​
367Tempo is better than raw NDJSON when you want to:
368​
369- search across many traces
370- inspect parent/child relationships visually
371- compare many slow traces
372- drill into one failing request without hand-joining by `traceId`
373​
374Recommended flow in Grafana:
375​
3761. Open `Explore`.
3772. Pick the `Tempo` data source.
3783. Set the time range to something recent like `Last 15 minutes`.
3794. Start broad. Do not begin with a very narrow query.
3805. Look for spans from the `t3code-server` or `t3code-desktop` service, then narrow by span name or
381 attributes.
382​
383Good first searches:
384​
385- service name `t3code-server` or `t3code-desktop`, plus a resource attribute such as
386 `deployment.environment.name`
387- span names like `sendTurn` or a Git operation such as `GitVcsDriver.statusDetails.status`
388- Git spans whose `git.operation` attribute identifies the operation
389- orchestration spans with attributes like `orchestration_v2.command_type`
390​
391Once you know traces are arriving, narrower TraceQL queries for names such as `sendTurn` or Git
392operation names become useful.
393​
394### Use Metrics To See Systemic Problems
395​
396Traces are best for one request. Metrics are best for trends.
397​
398Good metric families to watch:
399​
400- `t3_rpc_request_duration`
401- `t3_orchestration_command_duration`
402- `t3_provider_turn_duration` (how long the provider adapter takes to start a turn, not the turn's run time)
403- `t3_git_command_duration`
404​
405Counters tell you volume and failure rate:
406​
407- `t3_rpc_requests_total`
408- `t3_orchestration_commands_total`
409- `t3_provider_turns_total`
410- `t3_git_commands_total`
411​
412Webhooks have their own families:
413​
414- `t3_webhook_deliveries_total` by `outcome` and `source` (`relay` or `direct`). Beyond what the
415 sender sees, `queue_full` means a task already had its limit of deliveries waiting,
416 `prompt_too_long` means the filled-in prompt passed the provider limit, and `duplicate` means
417 the relay delivered a request this environment had already run.
418- `t3_webhook_runs_total` by `outcome` (`started`, `skipped`, `failed`) for the runs those
419 deliveries start, which happen after the sender has its answer.
420- `t3_webhook_held_delay` for how long requests the relay held waited before arriving.
421​
422- `t3_secret_requests_total` by `status` (`saved`, `declined`, `cancelled`, `timed_out`) for secrets
423 agents asked users for, and `t3_secret_refs_consumed_total` by `result` (`used`, `rejected`) for
424 tools redeeming them. Neither ever carries a value.
425​
426`ScheduledTaskService.triggerWebhook` spans carry the same outcome per request, and each run
427started from a delivery is its own `ScheduledTaskService.runWebhookDelivery` trace. For a request
428the relay forwarded, the span also goes to the T3 Connect trace export as a child of the relay's
429span; requests that reach the environment directly never join a sender's trace.
430​
431Use metrics when the question is:
432​
433- "is this always slow?"
434- "did this get worse after a change?"
435- "which command type is failing most often?"
436​
437Use traces when the question is:
438​
439- "what happened in this specific request?"
440- "which child span caused this one slow interaction?"
441- "what logs were emitted inside the failing flow?"
442​
443## Common Workflows
444​
445### "Why did this request fail?"
446​
4471. Start with the local NDJSON file.
4482. Find `effect-span` records where `exit._tag != "Success"`.
4493. Group by `traceId`.
4504. Inspect sibling spans and span events.
4515. If needed, move to Tempo for the full trace tree.
452​
453### "Why is the UI feeling slow?"
454​
4551. Search for slow top-level spans in the trace file or Tempo.
4562. Check child spans for sqlite, git, provider, or terminal work.
4573. Look at the matching duration metrics to see whether the slowness is systemic.
458​
459### "Are git hooks causing latency?"
460​
4611. Filter `git.operation` spans.
4622. Inspect `git.hook.started` and `git.hook.finished` events.
4633. Compare hook timing to the enclosing git span duration.
464​
465### "Why do I have spans locally but nothing in Grafana?"
466​
467Usually one of these is true:
468​
469- `T3CODE_OTLP_TRACES_URL` was not set
470- the app was launched from a different environment than the one where you exported the vars
471- the app was not fully restarted after changing env
472- Grafana is looking at the wrong time range or service name
473​
474If the local NDJSON file is updating, local tracing is working. The problem is almost always OTLP export configuration or process startup.
475​
476## How To Think About Adding Tracing To Future Code
477​
478### Prefer Boundaries Over Tiny Helpers
479​
480Good span boundaries:
481​
482- RPC methods
483- orchestration command handling
484- provider adapter calls
485- external process calls
486- persistence writes
487- queue handoffs
488​
489Avoid tracing every tiny helper. Most helpers should inherit the active span rather than create a new one.
490​
491### Reuse `Effect.fn(...)` Where It Already Exists
492​
493The codebase already uses `Effect.fn("name")` heavily. That should usually be your first tracing boundary.
494​
495For ad hoc work:
496​
497```ts
498import { Effect } from "effect";
499​
500const runThing = Effect.gen(function* () {
501 yield* Effect.annotateCurrentSpan({
502 "thing.id": "abc123",
503 "thing.kind": "example",
504 });
505​
506 yield* Effect.logInfo("starting thing");
507 return yield* doWork();
508}).pipe(Effect.withSpan("thing.run"));
509```
510​
511### Put High-Cardinality Detail On Spans
512​
513Use span annotations for IDs, paths, and other detailed context:
514​
515```ts
516yield *
517 Effect.annotateCurrentSpan({
518 "provider.thread_id": input.threadId,
519 "provider.request_id": input.requestId,
520 "git.cwd": input.cwd,
521 });
522```
523​
524### Keep Metric Labels Low Cardinality
525​
526Good metric labels:
527​
528- operation kind
529- method name
530- provider kind
531- aggregate kind
532- outcome
533​
534Bad metric labels:
535​
536- raw thread IDs
537- command IDs
538- file paths
539- cwd
540- full prompts
541- full model strings when a normalized family label would do
542​
543Detailed context belongs on spans, not metrics.
544​
545### Use Logs As Span Events
546​
547Logs inside a span become part of the trace story:
548​
549```ts
550yield * Effect.logInfo("starting provider turn");
551yield * Effect.logDebug("waiting for approval response");
552```
553​
554Those messages show up as span events because `Logger.tracerLogger` is installed.
555​
556### Use The Pipeable Metrics API
557​
558`withMetrics(...)` is the default way to attach a counter and timer to an effect:
559​
560```ts
561import { someCounter, someDuration, withMetrics } from "../observability/Metrics.ts";
562​
563const program = doWork().pipe(
564 withMetrics({
565 counter: someCounter,
566 timer: someDuration,
567 attributes: {
568 operation: "work",
569 },
570 }),
571);
572```
573​
574## Detailed API Reference
575​
576### Runtime Wiring
577​
578The server observability layer is assembled in `apps/server/src/observability/Observability.ts`.
579​
580It provides:
581​
582- pretty stdout logger
583- `Logger.tracerLogger`
584- local NDJSON tracer
585- optional OTLP trace exporter
586- optional OTLP metrics exporter
587- optional OTLP log exporter
588- Effect trace-level and timing refs
589​
590The desktop main process is a second producer, assembled in
591`apps/desktop/src/app/DesktopObservability.ts`. It reads the same `T3CODE_OTLP_*` names and the same
592Settings entries as the backend it supervises, and covers work the backend cannot see: app startup,
593window and menu handling, backend supervision, and updates. It reports as service
594`t3code-desktop`, so a collector shows it alongside the backend rather than mixed into it. It
595exports traces and logs only; the main process records no metrics, so the metrics endpoint applies
596to the backend alone.
597​
598### Env Vars
599​
600Local trace file:
601​
602- `T3CODE_TRACE_FILE`: override trace file path
603- `T3CODE_TRACE_MAX_BYTES`: per-file rotation size, default `10485760`
604- `T3CODE_TRACE_MAX_FILES`: rotated file count, default `10`
605- `T3CODE_TRACE_BATCH_WINDOW_MS`: flush window, default `1000`
606- `T3CODE_TRACE_MIN_LEVEL`: minimum trace level, default `Info`
607- `T3CODE_TRACE_TIMING_ENABLED`: enable timing metadata, default `true`
608​
609OTLP export:
610​
611- `T3CODE_OTLP_TRACES_URL`: OTLP trace endpoint
612- `T3CODE_OTLP_METRICS_URL`: OTLP metric endpoint
613- `T3CODE_OTLP_LOGS_URL`: OTLP log endpoint
614- `T3CODE_OTLP_EXPORT_INTERVAL_MS`: export interval, default `10000`
615- `T3CODE_OTLP_HEADERS`: extra headers for all three exporters, same format as
616 `OTEL_EXPORTER_OTLP_HEADERS`: comma-separated `key=value` pairs with percent-encoded values.
617- `T3CODE_OTLP_PROTOCOL`: `http/json` (default) or `http/protobuf`
618​
619The server and the desktop app also read the standard
620`OTEL_EXPORTER_OTLP_{TRACES,METRICS,LOGS}_ENDPOINT` and generic `OTEL_EXPORTER_OTLP_ENDPOINT` (with
621`/v1/traces`, `/v1/metrics`, or `/v1/logs` appended), for a collector expecting those instead. A
622non-blank `T3CODE_OTLP_*_URL` wins over either, and a per-signal endpoint wins over the generic one
623for its signal. A blank value counts as unset. A signal with an OTEL endpoint takes its headers from
624`OTEL_EXPORTER_OTLP_HEADERS` and its protocol from `OTEL_EXPORTER_OTLP_PROTOCOL` (default
625`http/protobuf`, read case-insensitively), and a per-signal
626`OTEL_EXPORTER_OTLP_{TRACES,METRICS,LOGS}_HEADERS` or `_PROTOCOL` wins over the generic one for its
627signal. `T3CODE_OTLP_HEADERS` and `T3CODE_OTLP_PROTOCOL` never apply to it. An endpoint that is not
628an `http` or `https` URL, a protocol other than `http/protobuf` or `http/json` such as `grpc`, or
629headers that are not `key=value` pairs with percent-encoded values turn that signal's export off
630with a startup warning, rather than sending it to the Settings endpoint.
631​
632Service names are fixed: `t3code-server` for the backend and `t3code-desktop` for the desktop main
633process, both in `service.namespace` `t3code`. `OTEL_SERVICE_NAME` and a `service.name` or
634`service.namespace` in `OTEL_RESOURCE_ATTRIBUTES` are ignored. Tell installations apart with other
635resource attributes, such as `OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=staging`.
636​
637Each process reports its own build, not the one it talks to: the server, the desktop main process,
638the UI, and the mobile app each carry `t3code.release.channel` (`dev`, `stable`, `nightly`, or
639`preview`, from their own version; desktop PR builds count as `preview`, and a server not built by a
640release workflow reports `dev`) and `deployment.environment.name` (`development`, `production`, or
641`staging` for `preview`). On the server and the desktop main process either key in
642`OTEL_RESOURCE_ATTRIBUTES` wins. The UI and mobile app never read that variable: Vercel PR previews
643set `VITE_RELEASE_CHANNEL=preview` because their `APP_VERSION` must stay comparable with the
644server's, and the mobile app maps its build variant (`development`, `preview`, `production`), or
645reports `dev` from a development bundle.
646​
647Attributes specific to T3 Code use the `t3code.` prefix. The UI runs as `t3code-web` in both a
648browser and the desktop window, since it is the same code, and `t3code.client.surface` is `desktop`
649or `web`. The server's `t3code.server.managed_by` is `desktop` when the desktop app launched it and
650`standalone` otherwise. The desktop main process reports `t3code.desktop.mode` as `development` or
651`packaged` (formerly `service.mode`; dashboards filtering on that key must switch). Node processes
652also report the semantic `process.runtime.name`, `process.runtime.version`, and
653`process.runtime.description`, and UI traces report `browser.language`, `user_agent.original`, and,
654in Chromium, `browser.platform`, `browser.mobile`, and `browser.brands`.
655​
656Every resource also carries a `service.instance.id`: random per process for the server and desktop,
657per page load for the UI, and the Expo session on mobile. A `service.instance.id` in
658`OTEL_RESOURCE_ATTRIBUTES` replaces the generated one on the server and desktop.
659​
660If the OTLP URLs are unset, local tracing still works, metrics stay in-process only, and logs stay
661on stdout only.
662​
663### The Kill Switch
664​
665`T3CODE_OTEL_SDK_DISABLED` and `OTEL_SDK_DISABLED` turn off every OTLP export in both the server and
666the desktop main process, overriding any endpoint from the environment or Settings. Local trace
667files and stdout logs are unaffected.
668​
669`T3CODE_OTEL_SDK_DISABLED` wins when set, so `T3CODE_OTEL_SDK_DISABLED=false` re-enables export on a
670machine that sets `OTEL_SDK_DISABLED` for everything else. It accepts the usual boolean spellings
671(`true`/`false`, `yes`/`no`, `on`/`off`, `1`/`0`, `y`/`n`). `OTEL_SDK_DISABLED` follows the
672OpenTelemetry specification and only `true` disables export, so `OTEL_SDK_DISABLED=1` does not.
673Values are case-insensitive and trimmed. An unrecognized value is ignored with a startup warning.
674​
675`OTEL_TRACES_EXPORTER`, `OTEL_METRICS_EXPORTER`, or `OTEL_LOGS_EXPORTER` set to `none` turns off
676just that signal, overriding an OTEL endpoint and the Settings endpoint. A `T3CODE_OTLP_*_URL` still
677wins for its signal. `otlp` is the default, and any other exporter name, such as `console` or
678`prometheus`, is ignored with a startup warning.
679​
680### What Is Instrumented Today
681​
682Current high-value span and metric boundaries include:
683​
684- WebSocket RPC request spans (`ws.rpc.<method>`) and metrics in
685 `apps/server/src/observability/RpcInstrumentation.ts`
686- startup phases
687- orchestration command processing
688- provider session and turn operations
689- git command execution and git hook events
690- terminal session lifecycle
691- sqlite query execution, except the statements inside `orchestrationV2.EventSink.write`, which
692 its `sql.transaction` span times as one
693- event loop stalls (`server.eventLoop.stall`)
694​
695### Current Constraints
696​
697- logs outside spans are not persisted in the trace file; SSH-managed launch stdout/stderr is still
698 captured in its launcher log
699- metrics are not snapshotted locally
700​
701## Heap Snapshots
702​
703To see what a long-running server holds in memory, send it `SIGUSR2`. The server writes a V8 heap
704snapshot to its logs dir and logs the path. This works for desktop, `npx t3`, and service installs
705on macOS and Linux. Windows has no `SIGUSR2`.
706​
707Send the signal to the server pid in `server-runtime.json`, which sits in the server's state dir
708next to the `logs` dir. For a dev server or a `--home-dir` launch, use that server's state dir from
709[Traces](#traces). Do not send it to the desktop app or the service launcher: a process without the
710handler exits on `SIGUSR2`. After a crash the file can keep a stale pid that now belongs to a
711different process, so check the pid first.
712​
713```bash
714pid="$(jq .pid "${T3CODE_HOME:-$HOME/.t3}/userdata/server-runtime.json")"
715ps -p "$pid" -o command=
716```
717​
718If `ps` shows the T3 Code server, send the signal:
719​
720```bash
721kill -USR2 "$pid"
722```
723​
724The file is `<logsDir>/server-<pid>-<timestamp>.heapsnapshot`, next to `server.trace.ndjson`. To
725open it, use the Memory tab in Chrome DevTools and select Load.
726​
727Before you take one:
728​
729- The server stops while it writes the file. For a large heap this can take a minute or more.
730 Connected clients can reconnect during the pause, and an event loop monitor, if the server has
731 one, records the pause as a stall. Send the signal once. A second signal sent during a write
732 takes another snapshot after the first one finishes.
733- The write needs about as much free memory as the heap uses. On a machine that is already
734 swapping, it can make the problem worse or crash the server.
735- The file contains everything in server memory, including tokens, secrets, and thread content. Do
736 not share it publicly. Delete it when you are done, because storage cleanup does not remove it.