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

observability.md

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