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

observability.md

695 lines22.8 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#### Summarize the trace file
66​
67`t3 trace summary` reads the trace file and its rotated backups directly, so it works while the
68server is stalled or stopped. It prints counts, rates, and latency percentiles per span name. Use
69it to measure background work or to compare two builds.
70​
71```bash
72t3 trace summary --since 30m --limit 40
73```
74​
75It reads `T3CODE_TRACE_FILE` if set, else `<home>/userdata/logs/server.trace.ndjson` for
76`--base-dir` or `T3CODE_HOME`, plus the `T3CODE_TRACE_MAX_FILES` rotated backups. For a dev run or
77a copied file, set `T3CODE_TRACE_FILE`. `--since 30m` keeps spans that ended in the last 30
78minutes. The rate is per minute between the first and last span end.
79​
80### Metrics
81​
82Metrics are not written to a local file.
83​
84- local persistence: none
85- remote export: OTLP only, when configured
86- current definitions: `apps/server/src/observability/Metrics.ts`
87​
88If OTLP is not configured, metrics still exist in-process, but you will not have a local artifact to inspect.
89​
90### Event Loop Stalls
91​
92`apps/server/src/observability/EventLoopMonitor.ts` samples the server's event loop every 30 s. When
93the loop stalled for more than 2 s since the previous sample, it records a root
94`server.eventLoop.stall` span with a warning. The span has trace level `Warn`, so it stays when
95`T3CODE_TRACE_MIN_LEVEL` is `Warn`. The warning shows in Settings > Diagnostics unless OTLP logs are
96on. The span time is when the sample ran, not when the stall happened.
97​
98Some delay is not recorded:
99​
100- `delayMaxMs` is the longest stall, and can undercount it by up to 1 s. The 2 s threshold applies to
101 this value, so a stall over 3 s is normally recorded, and a shorter one can be missed. A stall
102 that ends just as a sample runs can be missed too.
103- Time the computer spends asleep reads as delay on macOS and Windows. So a sample only counts when
104 the loop was busy, not waiting for events, for at least `delayMaxMs`. Busy time covers the whole
105 window, so a short sleep in an otherwise busy window can still record a false stall. The span then
106 shows CPU time far below `delayMaxMs`.
107- The first sample after launch is skipped. Startup work such as migrations and projection bootstrap
108 can block the loop for seconds on a large database.
109​
110CPU times and page faults cover the whole process over the whole window since the previous sample.
111The window is nominally 30 s, but a long stall delays the sample and makes the window longer. Other
112work in the window can hide a wait, so only CPU time far below `delayMaxMs` proves the thread was
113waiting. Read CPU together with page faults:
114​
115- High `cpuSystemMs` with many page faults means memory pressure. Major faults are reads from disk or swap.
116 On macOS, reads from compressed memory are minor faults plus system CPU.
117- High `cpuUserMs` with few page faults means JavaScript work or garbage collection.
118- Low CPU with few major page faults points at synchronous disk I/O, such as SQLite reads or trace
119 file writes.
120- Many `involuntaryContextSwitches` mean other processes were competing for the CPU.
121​
122### Related Artifacts
123​
124Provider event NDJSON files still exist for provider runtime streams. Those are separate from the main server trace file.
125​
126## Run The Server In Instrumented Mode
127​
128There are two useful modes:
129​
130- local-only: stdout + local `server.trace.ndjson`
131- full local observability: stdout + local trace file + OTLP export to Grafana/Tempo/Prometheus
132​
133The local trace file is always on. OTLP export is opt-in.
134​
135### Option 1: Local Traces Only
136​
137You do not need any extra env vars. Just run the app normally and inspect `server.trace.ndjson`.
138​
139Examples:
140​
141```bash
142npx t3
143```
144​
145```bash
146node --run dev
147```
148​
149```bash
150node --run dev:desktop
151```
152​
153### Option 2: Run With A Local LGTM Stack
154​
155#### 1. Start Grafana LGTM
156​
157```bash
158docker run --name lgtm \
159 -p 3000:3000 \
160 -p 4317:4317 \
161 -p 4318:4318 \
162 --rm -ti \
163 grafana/otel-lgtm
164```
165​
166Then open `http://localhost:3000`.
167​
168Default Grafana login:
169​
170- username: `admin`
171- password: `admin`
172​
173#### 2. Export OTLP env vars
174​
175```bash
176export T3CODE_OTLP_TRACES_URL=http://localhost:4318/v1/traces
177export T3CODE_OTLP_METRICS_URL=http://localhost:4318/v1/metrics
178export T3CODE_OTLP_LOGS_URL=http://localhost:4318/v1/logs
179export OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=development
180```
181​
182Optional:
183​
184```bash
185export T3CODE_TRACE_MIN_LEVEL=Info
186export T3CODE_TRACE_TIMING_ENABLED=true
187```
188​
189#### 3. Launch the app from that same shell
190​
191CLI:
192​
193```bash
194npx t3
195```
196​
197Monorepo web/server dev:
198​
199```bash
200node --run dev
201```
202​
203Monorepo desktop dev:
204​
205```bash
206node --run dev:desktop
207```
208​
209Packaged desktop app:
210​
211Launch the actual app executable from the same shell so the desktop app and embedded backend inherit `T3CODE_OTLP_*`.
212​
213macOS app bundle example:
214​
215```bash
216T3CODE_OTLP_TRACES_URL=http://localhost:4318/v1/traces \
217T3CODE_OTLP_METRICS_URL=http://localhost:4318/v1/metrics \
218T3CODE_OTLP_LOGS_URL=http://localhost:4318/v1/logs \
219"/Applications/T3 Code.app/Contents/MacOS/T3 Code"
220```
221​
222Direct binary example:
223​
224```bash
225T3CODE_OTLP_TRACES_URL=http://localhost:4318/v1/traces \
226T3CODE_OTLP_METRICS_URL=http://localhost:4318/v1/metrics \
227T3CODE_OTLP_LOGS_URL=http://localhost:4318/v1/logs \
228./path/to/your/desktop-app-binary
229```
230​
231Do 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.
232​
233#### 4. Fully restart after changing env
234​
235The backend reads observability config at process start. If you change OTLP env vars, stop the app completely and start it again.
236​
237## How To Use Traces And Metrics To Debug The Server
238​
239### Start With The Local Trace File
240​
241The trace file is the fastest way to inspect raw span data.
242​
243Resolve the path for the launch mode once. Production and explicitly configured homes store runtime
244state under the base directory's `userdata` folder:
245​
246```bash
247TRACE_FILE="${T3CODE_HOME:-$HOME/.t3}/userdata/logs/server.trace.ndjson"
248```
249​
250A dev server started from a linked worktree defaults to that worktree's local home:
251​
252```bash
253TRACE_FILE="$WORKTREE/.t3/userdata/logs/server.trace.ndjson"
254```
255​
256Only an implicit dev run outside a linked worktree uses the shared dev directory:
257​
258```bash
259TRACE_FILE="$HOME/.t3/dev/logs/server.trace.ndjson"
260```
261​
262Tail the selected file:
263​
264```bash
265tail -f "$TRACE_FILE"
266```
267​
268Show failed spans:
269​
270```bash
271jq -c 'select(.type == "effect-span" and .exit._tag != "Success") | {
272 name,
273 durationMs,
274 exit,
275 attributes
276}' "$TRACE_FILE"
277```
278​
279Show slow spans:
280​
281```bash
282jq -c 'select(.durationMs > 1000) | {
283 name,
284 durationMs,
285 traceId,
286 spanId
287}' "$TRACE_FILE"
288```
289​
290Inspect embedded log events:
291​
292```bash
293jq -c 'select(any(.events[]?; .attributes["effect.logLevel"] != null)) | {
294 name,
295 durationMs,
296 events: [
297 .events[]
298 | select(.attributes["effect.logLevel"] != null)
299 | {
300 message: .name,
301 level: .attributes["effect.logLevel"]
302 }
303 ]
304}' "$TRACE_FILE"
305```
306​
307Follow one trace:
308​
309```bash
310jq -r 'select(.traceId == "TRACE_ID_HERE") | [
311 .name,
312 .spanId,
313 (.parentSpanId // "-"),
314 .durationMs
315] | @tsv' "$TRACE_FILE"
316```
317​
318Filter orchestration commands:
319​
320```bash
321jq -c 'select(.attributes["orchestration.command_type"] != null) | {
322 name,
323 durationMs,
324 commandType: .attributes["orchestration.command_type"],
325 aggregateKind: .attributes["orchestration.aggregate_kind"]
326}' "$TRACE_FILE"
327```
328​
329Filter git activity:
330​
331```bash
332jq -c 'select(.attributes["git.operation"] != null) | {
333 name,
334 durationMs,
335 operation: .attributes["git.operation"],
336 cwd: .attributes["git.cwd"],
337 hookEvents: [
338 .events[]
339 | select(.name == "git.hook.started" or .name == "git.hook.finished")
340 ]
341}' "$TRACE_FILE"
342```
343​
344### Use Tempo When You Need A Real Trace Viewer
345​
346Tempo is better than raw NDJSON when you want to:
347​
348- search across many traces
349- inspect parent/child relationships visually
350- compare many slow traces
351- drill into one failing request without hand-joining by `traceId`
352​
353Recommended flow in Grafana:
354​
3551. Open `Explore`.
3562. Pick the `Tempo` data source.
3573. Set the time range to something recent like `Last 15 minutes`.
3584. Start broad. Do not begin with a very narrow query.
3595. Look for spans from the `t3code-server` or `t3code-desktop` service, then narrow by span name or
360 attributes.
361​
362Good first searches:
363​
364- service name `t3code-server` or `t3code-desktop`, plus a resource attribute such as
365 `deployment.environment.name`
366- span names like `sendTurn` or a Git operation such as `GitVcsDriver.statusDetails.status`
367- Git spans whose `git.operation` attribute identifies the operation
368- orchestration spans with attributes like `orchestration.command_type`
369​
370Once you know traces are arriving, narrower TraceQL queries for names such as `sendTurn` or Git
371operation names become useful.
372​
373### Use Metrics To See Systemic Problems
374​
375Traces are best for one request. Metrics are best for trends.
376​
377Good metric families to watch:
378​
379- `t3_rpc_request_duration`
380- `t3_orchestration_command_duration`
381- `t3_orchestration_command_ack_duration`
382- `t3_provider_turn_duration`
383- `t3_git_command_duration`
384​
385Counters tell you volume and failure rate:
386​
387- `t3_rpc_requests_total`
388- `t3_orchestration_commands_total`
389- `t3_provider_turns_total`
390- `t3_git_commands_total`
391​
392Use metrics when the question is:
393​
394- "is this always slow?"
395- "did this get worse after a change?"
396- "which command type is failing most often?"
397​
398Use traces when the question is:
399​
400- "what happened in this specific request?"
401- "which child span caused this one slow interaction?"
402- "what logs were emitted inside the failing flow?"
403​
404### What The New Ack Metric Means
405​
406`t3_orchestration_command_ack_duration` measures:
407​
408- start: command dispatch enters the orchestration engine
409- end: the first committed domain event for that command is published by the server
410​
411That is a server-side acknowledgment metric. It does not measure:
412​
413- websocket transit to the browser
414- client receipt
415- React render time
416​
417If you need those later, add client-side instrumentation or a dedicated server fanout metric.
418​
419## Common Workflows
420​
421### "Why did this request fail?"
422​
4231. Start with the local NDJSON file.
4242. Find `effect-span` records where `exit._tag != "Success"`.
4253. Group by `traceId`.
4264. Inspect sibling spans and span events.
4275. If needed, move to Tempo for the full trace tree.
428​
429### "Why is the UI feeling slow?"
430​
4311. Search for slow top-level spans in the trace file or Tempo.
4322. Check child spans for sqlite, git, provider, or terminal work.
4333. Look at the matching duration metrics to see whether the slowness is systemic.
434​
435### "Did this command take too long to acknowledge?"
436​
4371. Check `t3_orchestration_command_ack_duration` by `commandType`.
4382. If it is high, inspect the corresponding orchestration trace.
4393. Look at child spans for projection, sqlite, provider, or git work.
440​
441### "Are git hooks causing latency?"
442​
4431. Filter `git.operation` spans.
4442. Inspect `git.hook.started` and `git.hook.finished` events.
4453. Compare hook timing to the enclosing git span duration.
446​
447### "Why do I have spans locally but nothing in Grafana?"
448​
449Usually one of these is true:
450​
451- `T3CODE_OTLP_TRACES_URL` was not set
452- the app was launched from a different environment than the one where you exported the vars
453- the app was not fully restarted after changing env
454- Grafana is looking at the wrong time range or service name
455​
456If the local NDJSON file is updating, local tracing is working. The problem is almost always OTLP export configuration or process startup.
457​
458## How To Think About Adding Tracing To Future Code
459​
460### Prefer Boundaries Over Tiny Helpers
461​
462Good span boundaries:
463​
464- RPC methods
465- orchestration command handling
466- provider adapter calls
467- external process calls
468- persistence writes
469- queue handoffs
470​
471Avoid tracing every tiny helper. Most helpers should inherit the active span rather than create a new one.
472​
473### Reuse `Effect.fn(...)` Where It Already Exists
474​
475The codebase already uses `Effect.fn("name")` heavily. That should usually be your first tracing boundary.
476​
477For ad hoc work:
478​
479```ts
480import { Effect } from "effect";
481​
482const runThing = Effect.gen(function* () {
483 yield* Effect.annotateCurrentSpan({
484 "thing.id": "abc123",
485 "thing.kind": "example",
486 });
487​
488 yield* Effect.logInfo("starting thing");
489 return yield* doWork();
490}).pipe(Effect.withSpan("thing.run"));
491```
492​
493### Put High-Cardinality Detail On Spans
494​
495Use span annotations for IDs, paths, and other detailed context:
496​
497```ts
498yield *
499 Effect.annotateCurrentSpan({
500 "provider.thread_id": input.threadId,
501 "provider.request_id": input.requestId,
502 "git.cwd": input.cwd,
503 });
504```
505​
506### Keep Metric Labels Low Cardinality
507​
508Good metric labels:
509​
510- operation kind
511- method name
512- provider kind
513- aggregate kind
514- outcome
515​
516Bad metric labels:
517​
518- raw thread IDs
519- command IDs
520- file paths
521- cwd
522- full prompts
523- full model strings when a normalized family label would do
524​
525Detailed context belongs on spans, not metrics.
526​
527### Use Logs As Span Events
528​
529Logs inside a span become part of the trace story:
530​
531```ts
532yield * Effect.logInfo("starting provider turn");
533yield * Effect.logDebug("waiting for approval response");
534```
535​
536Those messages show up as span events because `Logger.tracerLogger` is installed.
537​
538### Use The Pipeable Metrics API
539​
540`withMetrics(...)` is the default way to attach a counter and timer to an effect:
541​
542```ts
543import { someCounter, someDuration, withMetrics } from "../observability/Metrics.ts";
544​
545const program = doWork().pipe(
546 withMetrics({
547 counter: someCounter,
548 timer: someDuration,
549 attributes: {
550 operation: "work",
551 },
552 }),
553);
554```
555​
556## Detailed API Reference
557​
558### Runtime Wiring
559​
560The server observability layer is assembled in `apps/server/src/observability/Layers/Observability.ts`.
561​
562It provides:
563​
564- pretty stdout logger
565- `Logger.tracerLogger`
566- local NDJSON tracer
567- optional OTLP trace exporter
568- optional OTLP metrics exporter
569- optional OTLP log exporter
570- Effect trace-level and timing refs
571​
572The desktop main process is a second producer, assembled in
573`apps/desktop/src/app/DesktopObservability.ts`. It reads the same `T3CODE_OTLP_*` names and the same
574Settings entries as the backend it supervises, and covers work the backend cannot see: app startup,
575window and menu handling, backend supervision, and updates. It reports as service
576`t3code-desktop`, so a collector shows it alongside the backend rather than mixed into it. It
577exports traces and logs only; the main process records no metrics, so the metrics endpoint applies
578to the backend alone.
579​
580### Env Vars
581​
582Local trace file:
583​
584- `T3CODE_TRACE_FILE`: override trace file path
585- `T3CODE_TRACE_MAX_BYTES`: per-file rotation size, default `10485760`
586- `T3CODE_TRACE_MAX_FILES`: rotated file count, default `10`
587- `T3CODE_TRACE_BATCH_WINDOW_MS`: flush window, default `200`
588- `T3CODE_TRACE_MIN_LEVEL`: minimum trace level, default `Info`
589- `T3CODE_TRACE_TIMING_ENABLED`: enable timing metadata, default `true`
590​
591OTLP export:
592​
593- `T3CODE_OTLP_TRACES_URL`: OTLP trace endpoint
594- `T3CODE_OTLP_METRICS_URL`: OTLP metric endpoint
595- `T3CODE_OTLP_LOGS_URL`: OTLP log endpoint
596- `T3CODE_OTLP_EXPORT_INTERVAL_MS`: export interval, default `10000`
597- `T3CODE_OTLP_HEADERS`: extra headers for all three exporters, same format as
598 `OTEL_EXPORTER_OTLP_HEADERS`: comma-separated `key=value` pairs with percent-encoded values.
599- `T3CODE_OTLP_PROTOCOL`: `http/json` (default) or `http/protobuf`
600​
601The server and the desktop app also read the standard
602`OTEL_EXPORTER_OTLP_{TRACES,METRICS,LOGS}_ENDPOINT` and generic `OTEL_EXPORTER_OTLP_ENDPOINT` (with
603`/v1/traces`, `/v1/metrics`, or `/v1/logs` appended), for a collector expecting those instead. A
604non-blank `T3CODE_OTLP_*_URL` wins over either, and a per-signal endpoint wins over the generic one
605for its signal. A blank value counts as unset. A signal with an OTEL endpoint takes its headers from
606`OTEL_EXPORTER_OTLP_HEADERS` and its protocol from `OTEL_EXPORTER_OTLP_PROTOCOL` (default
607`http/protobuf`, read case-insensitively), and a per-signal
608`OTEL_EXPORTER_OTLP_{TRACES,METRICS,LOGS}_HEADERS` or `_PROTOCOL` wins over the generic one for its
609signal. `T3CODE_OTLP_HEADERS` and `T3CODE_OTLP_PROTOCOL` never apply to it. An endpoint that is not
610an `http` or `https` URL, a protocol other than `http/protobuf` or `http/json` such as `grpc`, or
611headers that are not `key=value` pairs with percent-encoded values turn that signal's export off
612with a startup warning, rather than sending it to the Settings endpoint.
613​
614Service names are fixed: `t3code-server` for the backend and `t3code-desktop` for the desktop main
615process, both in `service.namespace` `t3code`. `OTEL_SERVICE_NAME` and a `service.name` or
616`service.namespace` in `OTEL_RESOURCE_ATTRIBUTES` are ignored. Tell installations apart with other
617resource attributes, such as `OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=development`.
618​
619If the OTLP URLs are unset, local tracing still works, metrics stay in-process only, and logs stay
620on stdout only.
621​
622### The Kill Switch
623​
624`T3CODE_OTEL_SDK_DISABLED` and `OTEL_SDK_DISABLED` turn off every OTLP export in both the server and
625the desktop main process, overriding any endpoint from the environment or Settings. Local trace
626files and stdout logs are unaffected.
627​
628`T3CODE_OTEL_SDK_DISABLED` wins when set, so `T3CODE_OTEL_SDK_DISABLED=false` re-enables export on a
629machine that sets `OTEL_SDK_DISABLED` for everything else. It accepts the usual boolean spellings
630(`true`/`false`, `yes`/`no`, `on`/`off`, `1`/`0`, `y`/`n`). `OTEL_SDK_DISABLED` follows the
631OpenTelemetry specification and only `true` disables export, so `OTEL_SDK_DISABLED=1` does not.
632Values are case-insensitive and trimmed. An unrecognized value is ignored with a startup warning.
633​
634`OTEL_TRACES_EXPORTER`, `OTEL_METRICS_EXPORTER`, or `OTEL_LOGS_EXPORTER` set to `none` turns off
635just that signal, overriding an OTEL endpoint and the Settings endpoint. A `T3CODE_OTLP_*_URL` still
636wins for its signal. `otlp` is the default, and any other exporter name, such as `console` or
637`prometheus`, is ignored with a startup warning.
638​
639### What Is Instrumented Today
640​
641Current high-value span and metric boundaries include:
642​
643- Effect RPC websocket request spans from `effect/rpc`
644- RPC request metrics in `apps/server/src/observability/RpcInstrumentation.ts`
645- startup phases
646- orchestration command processing
647- orchestration command acknowledgment latency
648- provider session and turn operations
649- git command execution and git hook events
650- terminal session lifecycle
651- sqlite query execution
652- event loop stalls (`server.eventLoop.stall`)
653​
654### Current Constraints
655​
656- logs outside spans are not persisted in the trace file; SSH-managed launch stdout/stderr is still
657 captured in its launcher log
658- metrics are not snapshotted locally
659​
660## Heap Snapshots
661​
662To see what a long-running server holds in memory, send it `SIGUSR2`. The server writes a V8 heap
663snapshot to its logs dir and logs the path. This works for desktop, `npx t3`, and service installs
664on macOS and Linux. Windows has no `SIGUSR2`.
665​
666Send the signal to the server pid in `server-runtime.json`, which sits in the server's state dir
667next to the `logs` dir. For a dev server or a `--home-dir` launch, use that server's state dir from
668[Traces](#traces). Do not send it to the desktop app or the service launcher: a process without the
669handler exits on `SIGUSR2`. After a crash the file can keep a stale pid that now belongs to a
670different process, so check the pid first.
671​
672```bash
673pid="$(jq .pid "${T3CODE_HOME:-$HOME/.t3}/userdata/server-runtime.json")"
674ps -p "$pid" -o command=
675```
676​
677If `ps` shows the T3 Code server, send the signal:
678​
679```bash
680kill -USR2 "$pid"
681```
682​
683The file is `<logsDir>/server-<pid>-<timestamp>.heapsnapshot`, next to `server.trace.ndjson`. To
684open it, use the Memory tab in Chrome DevTools and select Load.
685​
686Before you take one:
687​
688- The server stops while it writes the file. For a large heap this can take a minute or more.
689 Connected clients can reconnect during the pause, and an event loop monitor, if the server has
690 one, records the pause as a stall. Send the signal once. A second signal sent during a write
691 takes another snapshot after the first one finishes.
692- The write needs about as much free memory as the heap uses. On a machine that is already
693 swapping, it can make the problem worse or crash the server.
694- The file contains everything in server memory, including tokens, secrets, and thread content. Do
695 not share it publicly. Delete it when you are done, because storage cleanup does not remove it.