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

observability.md

578 lines16.0 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​
59DPoP proof failures include the safe `environment.dpop.failure_code` span
60attribute. A `time_window` failure means that a signed proof was too old or too
61far in the future for the environment server's allowed window. It can point to
62a date or time problem on either device, but it can also result from a delayed
63request.
64​
65### Metrics
66​
67Metrics are not written to a local file.
68​
69- local persistence: none
70- remote export: OTLP only, when configured
71- current definitions: `apps/server/src/observability/Metrics.ts`
72​
73If OTLP is not configured, metrics still exist in-process, but you will not have a local artifact to inspect.
74​
75### Related Artifacts
76​
77Provider event NDJSON files still exist for provider runtime streams. Those are separate from the main server trace file.
78​
79## Run The Server In Instrumented Mode
80​
81There are two useful modes:
82​
83- local-only: stdout + local `server.trace.ndjson`
84- full local observability: stdout + local trace file + OTLP export to Grafana/Tempo/Prometheus
85​
86The local trace file is always on. OTLP export is opt-in.
87​
88### Option 1: Local Traces Only
89​
90You do not need any extra env vars. Just run the app normally and inspect `server.trace.ndjson`.
91​
92Examples:
93​
94```bash
95npx t3
96```
97​
98```bash
99node --run dev
100```
101​
102```bash
103node --run dev:desktop
104```
105​
106### Option 2: Run With A Local LGTM Stack
107​
108#### 1. Start Grafana LGTM
109​
110```bash
111docker run --name lgtm \
112 -p 3000:3000 \
113 -p 4317:4317 \
114 -p 4318:4318 \
115 --rm -ti \
116 grafana/otel-lgtm
117```
118​
119Then open `http://localhost:3000`.
120​
121Default Grafana login:
122​
123- username: `admin`
124- password: `admin`
125​
126#### 2. Export OTLP env vars
127​
128```bash
129export T3CODE_OTLP_TRACES_URL=http://localhost:4318/v1/traces
130export T3CODE_OTLP_METRICS_URL=http://localhost:4318/v1/metrics
131export T3CODE_OTLP_LOGS_URL=http://localhost:4318/v1/logs
132export T3CODE_OTLP_SERVICE_NAME=t3-local
133```
134​
135Optional:
136​
137```bash
138export T3CODE_TRACE_MIN_LEVEL=Info
139export T3CODE_TRACE_TIMING_ENABLED=true
140```
141​
142#### 3. Launch the app from that same shell
143​
144CLI:
145​
146```bash
147npx t3
148```
149​
150Monorepo web/server dev:
151​
152```bash
153node --run dev
154```
155​
156Monorepo desktop dev:
157​
158```bash
159node --run dev:desktop
160```
161​
162Packaged desktop app:
163​
164Launch the actual app executable from the same shell so the desktop app and embedded backend inherit `T3CODE_OTLP_*`.
165​
166macOS app bundle example:
167​
168```bash
169T3CODE_OTLP_TRACES_URL=http://localhost:4318/v1/traces \
170T3CODE_OTLP_METRICS_URL=http://localhost:4318/v1/metrics \
171T3CODE_OTLP_LOGS_URL=http://localhost:4318/v1/logs \
172T3CODE_OTLP_SERVICE_NAME=t3-desktop \
173"/Applications/T3 Code.app/Contents/MacOS/T3 Code"
174```
175​
176Direct binary example:
177​
178```bash
179T3CODE_OTLP_TRACES_URL=http://localhost:4318/v1/traces \
180T3CODE_OTLP_METRICS_URL=http://localhost:4318/v1/metrics \
181T3CODE_OTLP_LOGS_URL=http://localhost:4318/v1/logs \
182T3CODE_OTLP_SERVICE_NAME=t3-desktop \
183./path/to/your/desktop-app-binary
184```
185​
186Do 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.
187​
188#### 4. Fully restart after changing env
189​
190The backend reads observability config at process start. If you change OTLP env vars, stop the app completely and start it again.
191​
192## How To Use Traces And Metrics To Debug The Server
193​
194### Start With The Local Trace File
195​
196The trace file is the fastest way to inspect raw span data.
197​
198Resolve the path for the launch mode once. Production and explicitly configured homes store runtime
199state under the base directory's `userdata` folder:
200​
201```bash
202TRACE_FILE="${T3CODE_HOME:-$HOME/.t3}/userdata/logs/server.trace.ndjson"
203```
204​
205A dev server started from a linked worktree defaults to that worktree's local home:
206​
207```bash
208TRACE_FILE="$WORKTREE/.t3/userdata/logs/server.trace.ndjson"
209```
210​
211Only an implicit dev run outside a linked worktree uses the shared dev directory:
212​
213```bash
214TRACE_FILE="$HOME/.t3/dev/logs/server.trace.ndjson"
215```
216​
217Tail the selected file:
218​
219```bash
220tail -f "$TRACE_FILE"
221```
222​
223Show failed spans:
224​
225```bash
226jq -c 'select(.type == "effect-span" and .exit._tag != "Success") | {
227 name,
228 durationMs,
229 exit,
230 attributes
231}' "$TRACE_FILE"
232```
233​
234Show slow spans:
235​
236```bash
237jq -c 'select(.durationMs > 1000) | {
238 name,
239 durationMs,
240 traceId,
241 spanId
242}' "$TRACE_FILE"
243```
244​
245Inspect embedded log events:
246​
247```bash
248jq -c 'select(any(.events[]?; .attributes["effect.logLevel"] != null)) | {
249 name,
250 durationMs,
251 events: [
252 .events[]
253 | select(.attributes["effect.logLevel"] != null)
254 | {
255 message: .name,
256 level: .attributes["effect.logLevel"]
257 }
258 ]
259}' "$TRACE_FILE"
260```
261​
262Follow one trace:
263​
264```bash
265jq -r 'select(.traceId == "TRACE_ID_HERE") | [
266 .name,
267 .spanId,
268 (.parentSpanId // "-"),
269 .durationMs
270] | @tsv' "$TRACE_FILE"
271```
272​
273Filter orchestration commands:
274​
275```bash
276jq -c 'select(.attributes["orchestration.command_type"] != null) | {
277 name,
278 durationMs,
279 commandType: .attributes["orchestration.command_type"],
280 aggregateKind: .attributes["orchestration.aggregate_kind"]
281}' "$TRACE_FILE"
282```
283​
284Filter git activity:
285​
286```bash
287jq -c 'select(.attributes["git.operation"] != null) | {
288 name,
289 durationMs,
290 operation: .attributes["git.operation"],
291 cwd: .attributes["git.cwd"],
292 hookEvents: [
293 .events[]
294 | select(.name == "git.hook.started" or .name == "git.hook.finished")
295 ]
296}' "$TRACE_FILE"
297```
298​
299### Use Tempo When You Need A Real Trace Viewer
300​
301Tempo is better than raw NDJSON when you want to:
302​
303- search across many traces
304- inspect parent/child relationships visually
305- compare many slow traces
306- drill into one failing request without hand-joining by `traceId`
307​
308Recommended flow in Grafana:
309​
3101. Open `Explore`.
3112. Pick the `Tempo` data source.
3123. Set the time range to something recent like `Last 15 minutes`.
3134. Start broad. Do not begin with a very narrow query.
3145. Look for spans from your configured service name, then narrow by span name or attributes.
315​
316Good first searches:
317​
318- service name such as `t3-local`, `t3-dev`, or `t3-desktop`
319- span names like `sendTurn` or a Git operation such as `GitVcsDriver.statusDetails.status`
320- Git spans whose `git.operation` attribute identifies the operation
321- orchestration spans with attributes like `orchestration.command_type`
322​
323Once you know traces are arriving, narrower TraceQL queries for names such as `sendTurn` or Git
324operation names become useful.
325​
326### Use Metrics To See Systemic Problems
327​
328Traces are best for one request. Metrics are best for trends.
329​
330Good metric families to watch:
331​
332- `t3_rpc_request_duration`
333- `t3_orchestration_command_duration`
334- `t3_orchestration_command_ack_duration`
335- `t3_provider_turn_duration`
336- `t3_git_command_duration`
337​
338Counters tell you volume and failure rate:
339​
340- `t3_rpc_requests_total`
341- `t3_orchestration_commands_total`
342- `t3_provider_turns_total`
343- `t3_git_commands_total`
344​
345Use metrics when the question is:
346​
347- "is this always slow?"
348- "did this get worse after a change?"
349- "which command type is failing most often?"
350​
351Use traces when the question is:
352​
353- "what happened in this specific request?"
354- "which child span caused this one slow interaction?"
355- "what logs were emitted inside the failing flow?"
356​
357### What The New Ack Metric Means
358​
359`t3_orchestration_command_ack_duration` measures:
360​
361- start: command dispatch enters the orchestration engine
362- end: the first committed domain event for that command is published by the server
363​
364That is a server-side acknowledgment metric. It does not measure:
365​
366- websocket transit to the browser
367- client receipt
368- React render time
369​
370If you need those later, add client-side instrumentation or a dedicated server fanout metric.
371​
372## Common Workflows
373​
374### "Why did this request fail?"
375​
3761. Start with the local NDJSON file.
3772. Find `effect-span` records where `exit._tag != "Success"`.
3783. Group by `traceId`.
3794. Inspect sibling spans and span events.
3805. If needed, move to Tempo for the full trace tree.
381​
382### "Why is the UI feeling slow?"
383​
3841. Search for slow top-level spans in the trace file or Tempo.
3852. Check child spans for sqlite, git, provider, or terminal work.
3863. Look at the matching duration metrics to see whether the slowness is systemic.
387​
388### "Did this command take too long to acknowledge?"
389​
3901. Check `t3_orchestration_command_ack_duration` by `commandType`.
3912. If it is high, inspect the corresponding orchestration trace.
3923. Look at child spans for projection, sqlite, provider, or git work.
393​
394### "Are git hooks causing latency?"
395​
3961. Filter `git.operation` spans.
3972. Inspect `git.hook.started` and `git.hook.finished` events.
3983. Compare hook timing to the enclosing git span duration.
399​
400### "Why do I have spans locally but nothing in Grafana?"
401​
402Usually one of these is true:
403​
404- `T3CODE_OTLP_TRACES_URL` was not set
405- the app was launched from a different environment than the one where you exported the vars
406- the app was not fully restarted after changing env
407- Grafana is looking at the wrong time range or service name
408​
409If the local NDJSON file is updating, local tracing is working. The problem is almost always OTLP export configuration or process startup.
410​
411## How To Think About Adding Tracing To Future Code
412​
413### Prefer Boundaries Over Tiny Helpers
414​
415Good span boundaries:
416​
417- RPC methods
418- orchestration command handling
419- provider adapter calls
420- external process calls
421- persistence writes
422- queue handoffs
423​
424Avoid tracing every tiny helper. Most helpers should inherit the active span rather than create a new one.
425​
426### Reuse `Effect.fn(...)` Where It Already Exists
427​
428The codebase already uses `Effect.fn("name")` heavily. That should usually be your first tracing boundary.
429​
430For ad hoc work:
431​
432```ts
433import { Effect } from "effect";
434​
435const runThing = Effect.gen(function* () {
436 yield* Effect.annotateCurrentSpan({
437 "thing.id": "abc123",
438 "thing.kind": "example",
439 });
440​
441 yield* Effect.logInfo("starting thing");
442 return yield* doWork();
443}).pipe(Effect.withSpan("thing.run"));
444```
445​
446### Put High-Cardinality Detail On Spans
447​
448Use span annotations for IDs, paths, and other detailed context:
449​
450```ts
451yield *
452 Effect.annotateCurrentSpan({
453 "provider.thread_id": input.threadId,
454 "provider.request_id": input.requestId,
455 "git.cwd": input.cwd,
456 });
457```
458​
459### Keep Metric Labels Low Cardinality
460​
461Good metric labels:
462​
463- operation kind
464- method name
465- provider kind
466- aggregate kind
467- outcome
468​
469Bad metric labels:
470​
471- raw thread IDs
472- command IDs
473- file paths
474- cwd
475- full prompts
476- full model strings when a normalized family label would do
477​
478Detailed context belongs on spans, not metrics.
479​
480### Use Logs As Span Events
481​
482Logs inside a span become part of the trace story:
483​
484```ts
485yield * Effect.logInfo("starting provider turn");
486yield * Effect.logDebug("waiting for approval response");
487```
488​
489Those messages show up as span events because `Logger.tracerLogger` is installed.
490​
491### Use The Pipeable Metrics API
492​
493`withMetrics(...)` is the default way to attach a counter and timer to an effect:
494​
495```ts
496import { someCounter, someDuration, withMetrics } from "../observability/Metrics.ts";
497​
498const program = doWork().pipe(
499 withMetrics({
500 counter: someCounter,
501 timer: someDuration,
502 attributes: {
503 operation: "work",
504 },
505 }),
506);
507```
508​
509## Detailed API Reference
510​
511### Runtime Wiring
512​
513The server observability layer is assembled in `apps/server/src/observability/Layers/Observability.ts`.
514​
515It provides:
516​
517- pretty stdout logger
518- `Logger.tracerLogger`
519- local NDJSON tracer
520- optional OTLP trace exporter
521- optional OTLP metrics exporter
522- optional OTLP log exporter
523- Effect trace-level and timing refs
524​
525The desktop main process is a second producer, assembled in
526`apps/desktop/src/app/DesktopObservability.ts`. It reads the same `T3CODE_OTLP_*` names and the same
527Settings entries as the backend it supervises, and covers work the backend cannot see: app startup,
528window and menu handling, backend supervision, and updates. It reports as service `desktop`
529regardless of `T3CODE_OTLP_SERVICE_NAME`, so a collector shows it alongside the backend rather than
530mixed into it. It exports traces and logs only; the main process records no metrics, so the metrics
531endpoint applies to the backend alone.
532​
533### Env Vars
534​
535Local trace file:
536​
537- `T3CODE_TRACE_FILE`: override trace file path
538- `T3CODE_TRACE_MAX_BYTES`: per-file rotation size, default `10485760`
539- `T3CODE_TRACE_MAX_FILES`: rotated file count, default `10`
540- `T3CODE_TRACE_BATCH_WINDOW_MS`: flush window, default `200`
541- `T3CODE_TRACE_MIN_LEVEL`: minimum trace level, default `Info`
542- `T3CODE_TRACE_TIMING_ENABLED`: enable timing metadata, default `true`
543​
544OTLP export:
545​
546- `T3CODE_OTLP_TRACES_URL`: OTLP trace endpoint
547- `T3CODE_OTLP_METRICS_URL`: OTLP metric endpoint
548- `T3CODE_OTLP_LOGS_URL`: OTLP log endpoint
549- `T3CODE_OTLP_EXPORT_INTERVAL_MS`: export interval, default `10000`
550- `T3CODE_OTLP_SERVICE_NAME`: service name, default `t3-server`
551- `T3CODE_OTLP_HEADERS`: extra headers for all three exporters, same format as
552 `OTEL_EXPORTER_OTLP_HEADERS`: comma-separated `key=value` pairs with percent-encoded values.
553- `T3CODE_OTLP_PROTOCOL`: `http/json` (default) or `http/protobuf`
554​
555If the OTLP URLs are unset, local tracing still works, metrics stay in-process only, and logs stay
556on stdout only.
557​
558### What Is Instrumented Today
559​
560Current high-value span and metric boundaries include:
561​
562- Effect RPC websocket request spans from `effect/rpc`
563- RPC request metrics in `apps/server/src/observability/RpcInstrumentation.ts`
564- startup phases
565- orchestration command processing
566- orchestration command acknowledgment latency
567- provider session and turn operations
568- git command execution and git hook events
569- terminal session lifecycle
570- sqlite query execution
571​
572### Current Constraints
573​
574- logs outside spans are not persisted in the trace file; SSH-managed launch stdout/stderr is still
575 captured in its launcher log
576- metrics are not snapshotted locally
577- the old `serverLogPath` still exists in config for compatibility, but the trace file is the primary
578 structured persisted artifact