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

observability.md

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