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

observability.md

527 lines12.9 KB

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