Open History to see the last commit
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
168Tail it:
169
170```bash
171tail -f "$T3CODE_HOME/userdata/logs/server.trace.ndjson"
172```
173
174In monorepo dev, use:
175
176```bash
177tail -f ./dev/logs/server.trace.ndjson
178```
179
180Show failed spans:
181
182```bash
183jq -c 'select(.exit._tag != "Success") | {
184 name,
185 durationMs,
186 exit,
187 attributes
188}' "$T3CODE_HOME/userdata/logs/server.trace.ndjson"
189```
190
191Show slow spans:
192
193```bash
194jq -c 'select(.durationMs > 1000) | {
195 name,
196 durationMs,
197 traceId,
198 spanId
199}' "$T3CODE_HOME/userdata/logs/server.trace.ndjson"
200```
201
202Inspect embedded log events:
203
204```bash
205jq -c 'select(any(.events[]?; .attributes["effect.logLevel"] != null)) | {
206 name,
207 durationMs,
208 events: [
209 .events[]
210 | select(.attributes["effect.logLevel"] != null)
211 | {
212 message: .name,
213 level: .attributes["effect.logLevel"]
214 }
215 ]
216}' "$T3CODE_HOME/userdata/logs/server.trace.ndjson"
217```
218
219Follow one trace:
220
221```bash
222jq -r 'select(.traceId == "TRACE_ID_HERE") | [
223 .name,
224 .spanId,
225 (.parentSpanId // "-"),
226 .durationMs
227] | @tsv' "$T3CODE_HOME/userdata/logs/server.trace.ndjson"
228```
229
230Filter orchestration commands:
231
232```bash
233jq -c 'select(.attributes["orchestration.command_type"] != null) | {
234 name,
235 durationMs,
236 commandType: .attributes["orchestration.command_type"],
237 aggregateKind: .attributes["orchestration.aggregate_kind"]
238}' "$T3CODE_HOME/userdata/logs/server.trace.ndjson"
239```
240
241Filter git activity:
242
243```bash
244jq -c 'select(.attributes["git.operation"] != null) | {
245 name,
246 durationMs,
247 operation: .attributes["git.operation"],
248 cwd: .attributes["git.cwd"],
249 hookEvents: [
250 .events[]
251 | select(.name == "git.hook.started" or .name == "git.hook.finished")
252 ]
253}' "$T3CODE_HOME/userdata/logs/server.trace.ndjson"
254```
255
256### Use Tempo When You Need A Real Trace Viewer
257
258Tempo is better than raw NDJSON when you want to:
259
260- search across many traces
261- inspect parent/child relationships visually
262- compare many slow traces
263- drill into one failing request without hand-joining by `traceId`
264
265Recommended flow in Grafana:
266
2671. Open `Explore`.
2682. Pick the `Tempo` data source.
2693. Set the time range to something recent like `Last 15 minutes`.
2704. Start broad. Do not begin with a very narrow query.
2715. Look for spans from your configured service name, then narrow by span name or attributes.
272
273Good first searches:
274
275- service name such as `t3-local`, `t3-dev`, or `t3-desktop`
276- span names like `sql.execute`, `git.runCommand`, `provider.sendTurn`
277- orchestration spans with attributes like `orchestration.command_type`
278
279Once you know traces are arriving, narrower TraceQL queries like `name = "sql.execute"` become useful.
280
281### Use Metrics To See Systemic Problems
282
283Traces are best for one request. Metrics are best for trends.
284
285Good metric families to watch:
286
287- `t3_rpc_request_duration`
288- `t3_orchestration_command_duration`
289- `t3_orchestration_command_ack_duration`
290- `t3_provider_turn_duration`
291- `t3_git_command_duration`
292- `t3_db_query_duration`
293
294Counters tell you volume and failure rate:
295
296- `t3_rpc_requests_total`
297- `t3_orchestration_commands_total`
298- `t3_provider_turns_total`
299- `t3_git_commands_total`
300- `t3_db_queries_total`
301
302Use metrics when the question is:
303
304- "is this always slow?"
305- "did this get worse after a change?"
306- "which command type is failing most often?"
307
308Use traces when the question is:
309
310- "what happened in this specific request?"
311- "which child span caused this one slow interaction?"
312- "what logs were emitted inside the failing flow?"
313
314### What The New Ack Metric Means
315
316`t3_orchestration_command_ack_duration` measures:
317
318- start: command dispatch enters the orchestration engine
319- end: the first committed domain event for that command is published by the server
320
321That is a server-side acknowledgment metric. It does not measure:
322
323- websocket transit to the browser
324- client receipt
325- React render time
326
327If you need those later, add client-side instrumentation or a dedicated server fanout metric.
328
329## Common Workflows
330
331### "Why did this request fail?"
332
3331. Start with the local NDJSON file.
3342. Find spans where `exit._tag != "Success"`.
3353. Group by `traceId`.
3364. Inspect sibling spans and span events.
3375. If needed, move to Tempo for the full trace tree.
338
339### "Why is the UI feeling slow?"
340
3411. Search for slow top-level spans in the trace file or Tempo.
3422. Check child spans for sqlite, git, provider, or terminal work.
3433. Look at the matching duration metrics to see whether the slowness is systemic.
344
345### "Did this command take too long to acknowledge?"
346
3471. Check `t3_orchestration_command_ack_duration` by `commandType`.
3482. If it is high, inspect the corresponding orchestration trace.
3493. Look at child spans for projection, sqlite, provider, or git work.
350
351### "Are git hooks causing latency?"
352
3531. Filter `git.operation` spans.
3542. Inspect `git.hook.started` and `git.hook.finished` events.
3553. Compare hook timing to the enclosing git span duration.
356
357### "Why do I have spans locally but nothing in Grafana?"
358
359Usually one of these is true:
360
361- `T3CODE_OTLP_TRACES_URL` was not set
362- the app was launched from a different environment than the one where you exported the vars
363- the app was not fully restarted after changing env
364- Grafana is looking at the wrong time range or service name
365
366If the local NDJSON file is updating, local tracing is working. The problem is almost always OTLP export configuration or process startup.
367
368## How To Think About Adding Tracing To Future Code
369
370### Prefer Boundaries Over Tiny Helpers
371
372Good span boundaries:
373
374- RPC methods
375- orchestration command handling
376- provider adapter calls
377- external process calls
378- persistence writes
379- queue handoffs
380
381Avoid tracing every tiny helper. Most helpers should inherit the active span rather than create a new one.
382
383### Reuse `Effect.fn(...)` Where It Already Exists
384
385The codebase already uses `Effect.fn("name")` heavily. That should usually be your first tracing boundary.
386
387For ad hoc work:
388
389```ts
390import { Effect } from "effect";
391
392const runThing = Effect.gen(function* () {
393 yield* Effect.annotateCurrentSpan({
394 "thing.id": "abc123",
395 "thing.kind": "example",
396 });
397
398 yield* Effect.logInfo("starting thing");
399 return yield* doWork();
400}).pipe(Effect.withSpan("thing.run"));
401```
402
403### Put High-Cardinality Detail On Spans
404
405Use span annotations for IDs, paths, and other detailed context:
406
407```ts
408yield *
409 Effect.annotateCurrentSpan({
410 "provider.thread_id": input.threadId,
411 "provider.request_id": input.requestId,
412 "git.cwd": input.cwd,
413 });
414```
415
416### Keep Metric Labels Low Cardinality
417
418Good metric labels:
419
420- operation kind
421- method name
422- provider kind
423- aggregate kind
424- outcome
425
426Bad metric labels:
427
428- raw thread IDs
429- command IDs
430- file paths
431- cwd
432- full prompts
433- full model strings when a normalized family label would do
434
435Detailed context belongs on spans, not metrics.
436
437### Use Logs As Span Events
438
439Logs inside a span become part of the trace story:
440
441```ts
442yield * Effect.logInfo("starting provider turn");
443yield * Effect.logDebug("waiting for approval response");
444```
445
446Those messages show up as span events because `Logger.tracerLogger` is installed.
447
448### Use The Pipeable Metrics API
449
450`withMetrics(...)` is the default way to attach a counter and timer to an effect:
451
452```ts
453import { someCounter, someDuration, withMetrics } from "../observability/Metrics.ts";
454
455const program = doWork().pipe(
456 withMetrics({
457 counter: someCounter,
458 timer: someDuration,
459 attributes: {
460 operation: "work",
461 },
462 }),
463);
464```
465
466## Detailed API Reference
467
468### Runtime Wiring
469
470The server observability layer is assembled in `apps/server/src/observability/Layers/Observability.ts`.
471
472It provides:
473
474- pretty stdout logger
475- `Logger.tracerLogger`
476- local NDJSON tracer
477- optional OTLP trace exporter
478- optional OTLP metrics exporter
479- Effect trace-level and timing refs
480
481### Env Vars
482
483Local trace file:
484
485- `T3CODE_TRACE_FILE`: override trace file path
486- `T3CODE_TRACE_MAX_BYTES`: per-file rotation size, default `10485760`
487- `T3CODE_TRACE_MAX_FILES`: rotated file count, default `10`
488- `T3CODE_TRACE_BATCH_WINDOW_MS`: flush window, default `200`
489- `T3CODE_TRACE_MIN_LEVEL`: minimum trace level, default `Info`
490- `T3CODE_TRACE_TIMING_ENABLED`: enable timing metadata, default `true`
491
492OTLP export:
493
494- `T3CODE_OTLP_TRACES_URL`: OTLP trace endpoint
495- `T3CODE_OTLP_METRICS_URL`: OTLP metric endpoint
496- `T3CODE_OTLP_EXPORT_INTERVAL_MS`: export interval, default `10000`
497- `T3CODE_OTLP_SERVICE_NAME`: service name, default `t3-server`
498
499If the OTLP URLs are unset, local tracing still works and metrics stay in-process only.
500
501### What Is Instrumented Today
502
503Current high-value span and metric boundaries include:
504
505- Effect RPC websocket request spans from `effect/rpc`
506- RPC request metrics in `apps/server/src/observability/RpcInstrumentation.ts`
507- startup phases
508- orchestration command processing
509- orchestration command acknowledgment latency
510- provider session and turn operations
511- git command execution and git hook events
512- terminal session lifecycle
513- sqlite query execution
514
515### Current Constraints
516
517- logs outside spans are not persisted
518- metrics are not snapshotted locally
519- the old `serverLogPath` still exists in config for compatibility, but the trace file is the persisted artifact that matters