---
title: 'Operate Studio: logs, restarts and the runtime link'
description: 'Run a hosted Studio day to day: its server log and X-Request-Id, weft doctor and /api/meta as the health check with ingest drop accounting, what a restart keeps and forgets, the command store, stable runtime ids and the discovery file.'
url: https://weftgo.dev/docs/production/studio-operations/
type: how-to
sources:
  - 'weft/AGENTS.md:236-244 (meta fields and the doctor lines: studio, token, discovery, db, content, data, otlp, ingest, runtimes, panel, manifest; the fields doctor does not check), 508-512 (/api/runtimes breakpoints_set_at and breakpoints_surface, kept in the command store); weft/CHANGELOG.md:44 (DiscoveryFile, OffReason, content.latest''s new fields, the token wall''s words); weft/internal/doctor/doctor.go:185-216; observed: weft doctor v0.20.2 against a private weft studio v0.20.2 on a scratch SQLite file, one stock OTLP batch ingested, 2026-10-27'
  - 'weft/CHANGELOG.md:286 (the server log: X-Request-Id, the WARN and ERROR lines, the limiter, --log-level/--log-format, ingest accepted/refused/last_error, the doctor line)'
  - 'weft/studio/internal/reqlog/reqlog.go:1-28 (package doc: request id, WARN per refused ingest batch, ERROR per 5xx and per panic, the limiter keyed by remote, route class, status and code, 1,024 keys, suppressed fields, a reverse proxy shares one remote), 50-52 (maxID 64), 101-115 (validID), 240-310 (the lines and their fields)'
  - 'weft/cmd/weft/logflags.go:11-73 (logFlags: the flag wins over WEFT_LOG_LEVEL/WEFT_LOG_FORMAT, a level alone installs a text handler, neither leaves slog.Default, a bad value is a usage error)'
  - 'W11-auditB1-fix, v0.20.2: weft/studio/runtime/store.go:397-401 (could not load the stored runtimes), 419-422 (stored commands), 470-489 (restored from the store: runtimes, open_commands, lost_commands, hint; only when one is non-zero)'
  - 'weft/AGENTS.md:409-414 (block 7: X-Request-Id, the WARN and ERROR lines, --log-level, --log-format), 502-515 (block 7a: runtime ids, CommandStore, restart, /api/runtimes fields)'
  - 'weft/studio/meta.go:20-143 (metaDoc fields), 147-157 (metaDB), 240-296 (serveMeta: ingest omitted for a panel token), 299-312 (mayReadDBPath), 314-332 (size with the WAL), 369-374 (metaReadFailed: Studio logs through slog.Default)'
  - 'weft/studio/ingesthealth.go:14-31 (the drop table: largest weft.records.dropped per service, in memory, OTLP path only), 75-98 (metaIngest)'
  - weft/internal/doctor/doctor.go:31 (5 s), 191 (the token FAIL line)
  - 'weft/studio/README.md:2722-2948 (After a Studio restart: what survives, what is decided lost, when the store lags, retention of command rows, stable runtime ids, cwd, instance)'
  - weft/studio/runtime/store.go:121-130 (WithStore, the 30 s breaker)
  - weft/studio/runtime/runtime.go (RuntimeView, AgentView godoc)
  - weft/obsdb/commands.go (CommandStore godoc, PruneCommands rules)
  - weft/obsdb/example_test.go:314-340 (ExampleCommandStore)
  - weft/studio/delete.go:194-202, live.go:884, manifests.go:70, handoff.go:96, runtime/runtime.go:981, runtime/store.go:400-895 (the other slog lines)
  - 'weft/studio/auth.go:750-760 (Expose-Headers on the CORS response to an allowed Origin); weft/studio/playground.go:55-68 (the runtime server only under Playground(true)); weft/internal/discovery/discovery.go:121-140 (Stale: pid, 24 h)'
  - weft/studio/proposals.go:15-25 (proposals in memory, forgotten on restart)
  - 'weft/studio/auth.go:169-180 (panel tokens signed with Token''s value); weft/studio/livegrant.go:88-98 (the live grant key: from the token, else random per process)'
  - weft/studio/studio.go:279-283 (the live hub)
  - weft/CHANGELOG.md:511 (WithStore, the ordered writer, the restore), 537 (cwd, restored), 539 (Cwd, Instance), 605 (obsdb.CommandStore), 613 (stable runtime ids), 1654 (connected), 1673 (the accepted-ack heartbeat), 1694 (no defaults from an old runtime), 4179 (full-feed drop, late accepted ack)
  - weft/CHANGELOG.md:300 (breakpoints_set_at, in the 0.17.0 Added entry)
  - weft/internal/discovery/discovery.go:121-135 (Stale rejects a dead pid), 167-232 (Remove restores a displaced entry non-atomically), 181-190 (Write clears stale files)
  - docs-site/factcheck/studio-2.md (writer's question 4, the concurrent SIGTERM repro; WEFT_DISCOVERY=off affects readers only)
  - 'observed: weft v0.17.0 studio --db sqlite://prodB.db --addr 127.0.0.1:7391 --log-format json --retain 720h; the refused POST /v1/traces line; /api/meta; weft doctor with and without --token (exit 0, exit 1); SIGTERM removed studio.json; a restart without --retain read ingest {accepted 0, refused 0} and retention null; --log-level warn alone wrote text lines; 2026-10-18'
  - docs-site/examples/production/storage.go (storageBackends), main_test.go TestOperations
---

# Operate Studio: logs, restarts and the runtime link

Studio has no logger of its own: it logs through the package-level `slog` functions, so its lines go to whatever `slog.Default` is when each is written. Among them are one WARN line per refused ingest batch and one ERROR line per 5xx or handler panic, each naming the request's `X-Request-Id`. `weft doctor` and `GET /api/meta` are its health check. A restart keeps everything in the database (runs, manifests, the playground's command records) and forgets what lives in memory: ingest counters, registered manifests, proposals and setup A's live grants.

In your own server, point `slog.Default` where your logs go, as in `production/storage.go`. Set it before `studio.New` to also catch the lines `New` itself logs (a manifest the store refused, the command store's load):

```go title="production/storage.go"
// Studio has no logger of its own: it logs through slog.Default.
slog.SetDefault(slog.New(slog.NewJSONHandler(&logs, &slog.HandlerOptions{Level: slog.LevelInfo})))
srv := studio.New(studio.DB(db)) // over the handle you opened; Close leaves it open
defer func() { _ = srv.Close() }()
```

[production/storage.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/production/storage.go)

The example then posts one batch Studio cannot read, with `X-Request-Id: deploy-check-1`. The 415 answer echoes that id, and the handler above receives one JSON WARN line, `"msg":"studio: ingest batch refused"`, with `request_id` `deploy-check-1`, `status` 415 and `code` `unsupported`.

## Server logs

`weft studio` and `weft dev` pick the log's handler on stderr:

| Flag | Env var | Values | With neither set |
|---|---|---|---|
| `--log-level` | `WEFT_LOG_LEVEL` | `debug`, `info`, `warn`, `error` | Go's default: INFO and above |
| `--log-format` | `WEFT_LOG_FORMAT` | `text`, `json` | Go's plain log line |

The flag wins over its variable. A level alone installs a text handler. A value outside the list is a usage error naming where it came from. Started with `--log-format json`, a refused batch reads:

```json
{"time":"2026-10-18T16:23:49.281531367+02:00","level":"WARN","msg":"studio: ingest batch refused","request_id":"3fd28a1c13346548","status":415,"method":"POST","path":"/v1/traces","remote":"127.0.0.1","code":"unsupported","reason":"Content-Type must be application/x-protobuf or application/json","bytes":1}
```

The lines to watch: every INFO, WARN and ERROR line `studio` and `studio/runtime` write (the rest are Debug):

| Message | Level | When | Limited |
|---|---|---|---|
| `studio: ingest batch refused` | WARN | A 4xx on an OTLP ingest path (`/v1/traces`, `/v1/logs`, or any other path under `/v1`) | One a minute per remote host, route class (`/v1/traces`, `/v1/logs`, else `/v1/*`), status and code |
| `studio: request failed` | ERROR | Any 5xx | Never |
| `studio: handler panicked` | ERROR | A handler panic (then the panic goes on to `net/http`; `http.ErrAbortHandler` is not logged) | Never |
| `studio: api/meta: …` | WARN | A read `/api/meta` makes failed | Never |
| `studio: retention sweep failed` | WARN | A `Retain` sweep failed; the server keeps serving (each sweep is a Debug `studio: retention sweep` line with `deleted_runs`) | Never |
| `studio: live resume: a run's stored records could not be read` | WARN | A live stream's resume could not backfill a run | Never |
| `studio: the manifest store refused the weft.json's agent; …` | WARN | At `New`: that agent's runs will not resolve their `manifest_hash` | Never |
| `studio: panel hand-off` | INFO | A playground panel token was exchanged for a 5-minute read token at `/api/panel-handoff` (`public_id`, `to`, `exp`) | Never |
| `studio/runtime: a runtime registered without an instance; …` | WARN | A runtime client sent no `instance` | Once per Studio process |
| `studio/runtime: the command store refused a write; …` | WARN, then Debug | The store failed; its writes are held 30 s | One WARN per outage |
| `studio/runtime: the command store writer's queue is full; …` | WARN, then Debug | The held queue passed 20,000 keys | First drop and each doubling |
| `studio/runtime: the command store writer stopped with writes still held; they are dropped` | WARN | `Close` over a still-failing store | Once |
| `studio/runtime: could not load the stored runtimes; starting without them (their queued commands are lost)` | WARN | At `New`: the stored runtimes could not be read; their queued commands are decided lost | Once |
| `studio/runtime: could not load the stored commands; starting without them` | WARN | At `New`: the stored commands could not be read | Once |
| `studio/runtime: restored from the store` | INFO | At `New`, when the store held a runtime or an open command. It carries `runtimes`, `open_commands`, `lost_commands` and a `hint` ([After a restart](#after-a-restart)) | Once per Studio process |

The first three lines carry `request_id`, `status`, `method`, `path` and `remote`, then `code`, `reason` and `bytes` when known; the others carry their own fields, the `api/meta` line only `err`. A 5xx answered to a panel token masks the database's error in the body; the log line still names the real error as `reason`. The retention sweeper logs one Debug line per sweep and one WARN on a failed one ([Retain](https://weftgo.dev/docs/production/retention/#retain)).

**`X-Request-Id`.** Every response carries one: the client's own when it sent a well-formed id (up to 64 characters of `A–Z a–z 0–9 . _ : -`), else a generated 16-hex id. It is exposed to an allowed cross-origin caller (`Access-Control-Expose-Headers` on the CORS response to an allowed `Origin`), and a 5xx error body carries it as `error.request_id`, so a user's report meets its log line.

**The limiter.** The first refusal under a key in a minute is logged; the next line logged under it carries the others as `suppressed`. The limiter holds 1,024 keys. Full, it drops expired windows first and carries their counts onto the next line as `suppressed_expired`; when none has expired, a refusal under a new key is not logged until a window turns, and the next line carries `suppressed_overflow`. Behind a reverse proxy every client arrives from the proxy's address, so all of them share one remote and one limit.

## Check a Studio with weft doctor

`weft doctor` reads `GET /api/meta` and prints one line per check: `studio`, `token`, `discovery`, `db`, `content`, `data`, `otlp`, `ingest`, `runtimes`, `panel` and `manifest`. Against a setup B Studio:

```sh
weft doctor --url http://127.0.0.1:7331 --token "$(cat ~/work/other.db.token)"
```

```text
ok   studio    reachable at http://127.0.0.1:7331 (weft v0.20.2, studio v0.20.2)
ok   token     accepted
ok   discovery ~/xdg/weft/studio.json -> http://127.0.0.1:7331 (this Studio)
ok   db        sqlite ~/work/other.db (627.7 KiB)
warn content   studio stores content as received; latest run otel-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7: unmarked — the latest run carries no content mark: no events stored, a weft older than the mark, or a non-weft exporter
ok   data      newest run 0s ago (service py-support) carries no weft version: a non-weft exporter
ok   otlp      open: OTLP at http://127.0.0.1:7331/v1/traces and /v1/logs takes a loopback app's spans with no ingest token
ok   ingest    1 OTLP batches accepted, 0 refused; no app reported lost records (weft.records.dropped on its heartbeats and run brackets)
warn runtimes  none connected
               - WEFT_ENV is unset in this shell: the app opens the runtime link only with WEFT_ENV=dev (or runtime.Enabled(true))
               - WEFT_STUDIO_URL is unset in this shell: the app dials the Studio a running `weft studio` names in its discovery file, else its otel Studio destination; set WEFT_STUDIO_URL=http://127.0.0.1:7331 to pin this one (or runtime.Studio(url, token))
ok   panel     /panel.js matches studio v0.20.2
ok   manifest  none: no weft.json configured (studio.Manifest, or --manifest / WEFT_MANIFEST) and no runtime registered one, nothing to compare
```

Warnings exit 0; a `FAIL` exits 1. Without the token, the second line is `FAIL token studio requires one: it is in <db>.token beside the database (the start banner names the file); set WEFT_STUDIO_TOKEN or --token to it`, followed by a hint to run `weft open --with-token`. Before 0.20.0 the last line was labelled `weft.json`, and the `discovery`, `data` and `otlp` lines did not exist. `weft doctor` checks those lines' fields, not every field of `/api/meta`: read `retention`, `pricing`, `live_all`, `debug_scope` and `interrupted_after_ms` from `/api/meta` itself, or from `weft mcp`'s `meta` tool. [The weft command](https://weftgo.dev/docs/reference/cli/#weft-doctor) lists every line's rule.

## Read /api/meta as the health page

`GET /api/meta` is computed from the server's own state on each request; every `weft doctor` line reads one of its fields. The ones an operator watches:

| Field | Says | Who sees it |
|---|---|---|
| `weft_version`, `studio_version`, `panel_version` | The framework build, Studio's version, the version stamped into `/panel.js` | Everyone |
| `db.kind` | `sqlite`, `clickhouse` or `memory` | Everyone |
| `db.path`, `db.size`, `pid` | The file, its bytes with the `-wal` sidecar included, the serving process | The server token, or setup A on a loopback `Host`; never a panel token. No path or size for a database with no file |
| `ingest_open` | OTLP ingest on with no `IngestToken`: loopback peers only | Everyone |
| `ingest` | `accepted`, `refused`, `last_error`, `last_at` and `dropped` | Not a panel token |
| `content.latest` | The latest run's content mark (`full`, `stripped`, `none`, `unmarked`) with a note and a fix; since 0.20.0 also its `started`, `weft_version` and `service` | Scoped to a panel token's public id |
| `discovery_file` | Since 0.20.0, the discovery file the hosting command wrote (`studio.DiscoveryFile`), while it names this process | Under `db.path`'s rule |
| `retention` | `Retain`'s duration, `"720h0m0s"`, or `null` | Everyone |
| `runtimes` | Runtimes holding a live command stream now | Everyone |
| `pricing` | `{source, path?, dated, models}` | Everyone; `path` under `db.path`'s rule |
| `manifest_check` | The manifest against each agent's latest run | Not a panel token |
| `capabilities`, `capabilities_off` | What this Studio serves, and the option that left each one off | Everyone |
| `interrupted_after_ms` | 30000: the silence after which a run reads interrupted | Everyone |

**Ingest accounting.** `accepted` and `refused` count the OTLP POSTs under `/v1/` this Studio answered 2xx and 4xx or 5xx since it started. `last_error` is the last refusal as `"<status> <code>: <reason>"`, `last_at` its time; both are omitted before the first. `dropped` lists, per `service.name`, the largest `weft.records.dropped` count heard on an app's heartbeats and `run_start` and `run_finish` records: records the app's destination lost on the way here, from queue overflow or failed exports ([Queue size and blocking](https://weftgo.dev/docs/observe/destinations/#queue-size-and-blocking)). It is kept per service, not per process: an app restarted under the same name reads the earlier, larger count until Studio restarts. It is heard on the OTLP path only; a `Local` destination writes into the database directly and has no queue to overflow. All of this is in memory.

Retention and vacuum are on [Keep and delete recorded runs](https://weftgo.dev/docs/production/retention/). Pricing files (`--pricing`, `WEFT_PRICING`, `studio.Pricing`) are on [Read cost](https://weftgo.dev/docs/observe/studio/cost/#pricing).

## After a restart

Studio keeps its state in two places. What is in the database survives; what is in memory starts empty.

| Survives (in the database or a file) | Starts empty (in memory) |
|---|---|
| Every run, record, span and app log line | `ingest`'s counters, `last_error` and `dropped` |
| Saved experiments | Manifests runtimes registered with, until each registers again |
| Stored manifests (`/api/manifests/{hash}`), kept forever | Proposed prompts (`PUT /api/agents/{name}/proposal`) |
| The playground's commands, run routes, breakpoint sets and runtime registrations, through the command store; since 0.20.0 also when and through which surface each breakpoint set was delivered | — |
| The dev token, in `<db>.token` | Setup A's live grants: without a `Token` their key is random per process |
| Panel tokens and live grants signed by the same `Token` | Every open live stream and runtime link stream: clients reconnect |
| — | The retention: `Retain` / `--retain` is an option read at each start, not stored. Pass it again, or `/api/meta` reads `"retention": null` and nothing is swept |

The command records are written when the backend implements [`obsdb.CommandStore`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#CommandStore). Both first-party backends do (SQLite migration 0007, ClickHouse 0008), and a `studio.New` built with `studio.Playground(true)` passes its DB itself (`weft studio` turns the playground on by default; without it there is no runtime server and nothing to store). A backend without it keeps them in memory, and a restart forgets them.

**What a restarted Studio does with them.** It lists every stored runtime as `connected: false, restored: true`, with its breakpoints and agents, until the runtime registers again: for at least 10 minutes after the restart, then by the usual prune. It answers `GET /api/playground/commands/{id}` for a command issued before the restart. Cancel, steer and the debugger's verbs keep reaching the runtime that started a run, through the stored routes. It never re-runs a command; at load, with the restart as now:

- A `queued` command whose runtime has no stored row (or when the stored runtimes could not be read) is lost: `Studio restarted; the runtime's identity is not stored`.
- A `queued` command older than its 30 s ack window is lost: `Studio restarted; no ack since <created>`. One still inside the window stays queued, and is re-sent only to the process it was queued for when that process reconnects; that process refuses a frame it already took.
- An `accepted` command is watched from its stored last word, the later of its last heartbeat and its accepted ack. It is lost max(10 min, 3 beats) after that for a runtime that heartbeats (10 min otherwise), as if Studio had never restarted; already past, it is lost at load: `Studio restarted; no heartbeat since <t>`. Studio never re-sends an accepted command: the runtime decides whether to run it.
- `finished`, `rejected` and `lost` commands are history.

One INFO line then says what the restart kept, when there was anything: `studio/runtime: restored from the store`. Its `runtimes` counts the runtimes listed restored, and its hint names `GET /api/runtimes` and `/runtimes`. `open_commands` counts the queued and accepted commands still open, `lost_commands` the ones the load decided lost.

**The heartbeat.** While a command is in a runtime's hands, `weft/runtime` re-posts its accepted ack every minute (`heartbeat_ms` at registration). Studio marks a heartbeating runtime's silent accepted command lost after max(10 min, three beats), with the reason `accepted, but no finish and no heartbeat from the runtime in <d>`, stream open or not; a run that keeps beating is never marked lost however long it takes. A runtime older than the heartbeat is watched only once its stream ends. Since the 2026-10-02 patch release (studio 0.3.1), a late accepted ack that revives a row the lost sweep took arms the finish watch, and a full feed ends the stalled stream instead of pinging forever.

**When the store lags or fails.** Writes leave the request path: one writer goroutine applies them in order, the latest per key, each call bounded at 2 s. A failure trips a 30 s breaker that holds the queue, still coalescing, capped at 20,000 keys (past it route writes go first, then the oldest finished commands'; a WARN on the first drop and each doubling), then re-applies all of it. One WARN, then Debug. A store failure changes no command's fate in this Studio; it can only leave the store older than memory, and an older row is the safe one (an accepted command decided lost sooner, never re-run). `studio.Server.Close` drains the queue once, bounded at 5 s, before the database closes; writes still held over a failing store are lost, with one WARN naming how many. A server built with `studio.Handler` is never closed and keeps the writer goroutine for the process's life.

**Command rows have their own retention.** The server's prune runs `PruneCommands` at most once a minute: terminal commands after 24 hours, 10,000 kept at most, queued and accepted never. Run deletion, `Retain` and `weft vacuum` never touch these rows. A runtime's `LastSeen` from keep-alive pings is written at most once a minute.

**Two Studios, one database.** Run one Studio per command store. Two Studios over one ClickHouse database never see each other's acks and beats, so a restarted one would load the other's queued and accepted rows and decide them lost; nothing runs twice, but the other Studio's live commands read lost.

## The command store

`obsdb.CommandStore` is an optional interface beside `obsdb.Searcher`. It persists the playground link's records: commands (`StoredCommand`, with the wire body and last ack verbatim and the times a restarted Studio decides from), run-to-runtime routes (`RunRoute`), per-runtime breakpoint sets (replaced whole; a stored empty set is distinct from none) and runtime registrations (`StoredRuntime`, with a `Cwd`). `PruneCommands(before, keep)` bounds it; `DeleteRun`, `DeleteSession`, `Sweep` and `Vacuum` never touch it.

You do not call it in a normal deployment: `studio.New` hands its DB to the runtime server (`studio/runtime`'s `WithStore`) when the DB implements it. A backend of your own implements it to make the playground survive restarts. [`ExampleCommandStore`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#example-CommandStore) writes a command, its route and a breakpoint set to an in-memory SQLite and reads them back. The per-backend methods are listed on [Storage backends](https://weftgo.dev/docs/production/storage-backends/#the-sqlite-dbs-methods).

## Runtime ids

A runtime's id is stable per (service, working directory, agent set): `rt_` plus the first 16 hex digits of sha256 over the service name (`OTEL_SERVICE_NAME`, else the binary's name), the cwd and the sorted agent names. An app restarted in the same place registers under the same id, so a link to `/runtimes/<id>` survives the restart.

- **Collisions.** When the id is held by another process's live stream (two replicas of one service in one cwd, or two links in one process), or by a disconnected process that still has a queued or accepted command, Studio answers the registration with `<id>-<pid>` (then `<id>-<pid>-2`, …) in `runtime_id`, and the link adopts it. A finished command's run route does not hold the id, so an app restarted minutes after a playground run (`weft dev` restarts on every save) gets its id back. An approval for a run parked on a runtime that went away may then reach the process that took the id, which refuses it (`no parked run …`).
- **`instance`.** A registration carries `cwd` and `instance`, a random value per link kept across its reconnects. A runtime client in another language must send `instance` to keep at-most-once across its own restarts; without it Studio tells processes apart by host and pid alone, and WARNs once.

`GET /api/runtimes` describes each runtime. Among its fields:

| Field | Meaning |
|---|---|
| `id`, `host`, `pid`, `service`, `env` | The registration |
| `cwd` | The app's working directory: served under `db.path`'s rule, never to a panel token |
| `connected` | Holds a live command stream now. A dropped runtime stays listed, `false`, until its commands resolve (10 minutes, 24 hours with breakpoints) |
| `restored` | Listed from the command store after a Studio restart and not registered since; omitted when false |
| `breakpoints`, `breakpoints_set_at`, `breakpoints_surface` | The stored set, when Studio delivered it and through which surface: the PUT body's optional `surface` (`runtimes` from the Runtimes page), else `api`. Since 0.20.0 both are kept in the command store, so they survive a restart; absent for a set adopted from a registration |
| `agents[].resolver`, `agents[].defaults` | Whether the agent takes a model outside its list, and its run defaults. `defaults` is absent for a runtime older than the option lab; Studio then refuses the option lab's knobs, the `user`, `tool_args` and `insert` edit kinds, and a replay across a compaction view |

A read-scoped panel token gets no instructions, default tool-choice name or stop sequences. `/api/meta`'s `runtimes` counts connected runtimes only. [Connect your app to the playground](https://weftgo.dev/docs/observe/playground/connect/) covers the link from the app's side.

## Discovery

`weft studio` and `weft dev` write `studio.json` (url, token, db, pid, start time, version; mode 0600) once the listener is bound, and remove it on exit. Since 0.20.0 they name it to the server with `studio.DiscoveryFile`, so `/api/meta`'s `discovery_file` and `weft doctor`'s `discovery` line say which file it is; a local app's `otel.Install()` and `runtime.Install()` find Studio through it ([The discovery file](https://weftgo.dev/docs/observe/weft-dev/#the-discovery-file)). On a hosted Studio it plays no part: an app trusts the file only when its URL is loopback, it is fresh (a live pid, a start under 24 hours ago) and, on unix, it is mode 0600 and yours, so a fleet exports through `otel.Studio(url, token)` or `WEFT_STUDIO_URL`.

Two operational edges:

- **Start a scratch Studio under `WEFT_DISCOVERY=off`.** Since 0.18.0 it stops the writer too: `weft studio` writes no discovery file and says `studio: no discovery file written (WEFT_DISCOVERY=off)`, so nothing finds it by accident.
- **Stopping several Studios at the same moment can leave a `studio.json` naming a stopped one.** Apps ignore it, because a dead pid is stale, and the next Studio's start removes it.

## Complete example

`storage.go` in the Production example package holds this page's region; its `storageBackends` also checks the request id, the log line and `/api/meta`'s ingest block:

```go title="production/storage.go"
package main

// The examples of the storage-backends and studio-operations pages:
// obsdb/sqlite opened with options, a Studio over that handle with its
// server log on, and the ClickHouse call (no server here: it shows the
// error a closed port gives).

import (
	"bytes"
	"context"
	"database/sql"
	"encoding/json"
	"fmt"
	"io"
	"log/slog"
	"net/http"
	"net/http/httptest"
	"path/filepath"
	"strings"
	"time"

	"github.com/weftgo/weft"
	"github.com/weftgo/weft/obsdb/clickhouse"
	"github.com/weftgo/weft/obsdb/sqlite"
	"github.com/weftgo/weft/otel"
	"github.com/weftgo/weft/studio"
)

// runOperations runs the two pages' steps after the shared ones.
func runOperations(ctx context.Context, w io.Writer, dir string) error {
	steps := []struct {
		name string
		fn   func(context.Context, io.Writer, string) error
	}{
		{"storage backends", storageBackends},
		{"clickhouse", clickhouseOpen},
	}
	for _, s := range steps {
		fmt.Fprintln(w, "==", s.name)
		if err := s.fn(ctx, w, dir); err != nil {
			return fmt.Errorf("%s: %w", s.name, err)
		}
	}
	return nil
}

// storageBackends opens a SQLite file that keeps deltas, serves Studio
// over it with the server log on, refuses one ingest batch, records one
// streamed run through OTLP, and reads back what Studio and the file say.
func storageBackends(ctx context.Context, w io.Writer, dir string) error {
	path := filepath.Join(dir, "studio.db")

	db, err := sqlite.Open(path, sqlite.KeepDeltas()) // created if missing, migrated to this binary's schema
	if err != nil {
		return err // sqlite.ErrNewerSchema: a newer weft wrote this file
	}
	defer func() { _ = db.Close() }()
	file := db.(interface{ Path() string }).Path() // absolute; "" for ":memory:"
	fmt.Fprintln(w, "file:", filepath.Base(file), "absolute:", filepath.IsAbs(file))

	var logs bytes.Buffer
	prev := slog.Default()
	defer slog.SetDefault(prev)

	// Studio has no logger of its own: it logs through slog.Default.
	slog.SetDefault(slog.New(slog.NewJSONHandler(&logs, &slog.HandlerOptions{Level: slog.LevelInfo})))
	srv := studio.New(studio.DB(db)) // over the handle you opened; Close leaves it open
	defer func() { _ = srv.Close() }()
	ts := httptest.NewServer(srv.Handler())
	defer ts.Close()

	// One refused ingest batch: a body Studio cannot read.
	req, _ := http.NewRequest(http.MethodPost, ts.URL+"/v1/traces", strings.NewReader("not otlp"))
	req.Header.Set("Content-Type", "text/plain")
	req.Header.Set("X-Request-Id", "deploy-check-1")
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}
	_ = resp.Body.Close()
	fmt.Fprintln(w, "refused:", resp.StatusCode, "X-Request-Id:", resp.Header.Get("X-Request-Id"))
	var line struct {
		Level     string `json:"level"`
		Msg       string `json:"msg"`
		RequestID string `json:"request_id"`
		Status    int    `json:"status"`
		Code      string `json:"code"`
	}
	if err := json.Unmarshal(firstLine(logs.String()), &line); err != nil {
		return fmt.Errorf("server log: %w (%q)", err, logs.String())
	}
	fmt.Fprintf(w, "log: %s %q request_id=%s status=%d code=%s\n", line.Level, line.Msg, line.RequestID, line.Status, line.Code)

	// An app exporting to this Studio over OTLP (loopback: no ingest token).
	p, err := otel.Start(ctx, otel.Studio(ts.URL, ""), otel.NoEnv(), otel.NoGlobal())
	if err != nil {
		return err
	}
	agt := weft.New(script(), weft.Name("support-bot"), lookup,
		weft.TracerProvider(p.TracerProvider()), weft.LoggerProvider(p.LoggerProvider()))
	res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"))
	if err != nil {
		return err
	}
	if err := p.Shutdown(ctx); err != nil {
		return err
	}

	_, body := get(ts.URL+"/api/meta", "")
	var meta struct {
		DB struct {
			Kind string `json:"kind"`
			Path string `json:"path"`
		} `json:"db"`
		Ingest struct {
			Accepted  int64  `json:"accepted"`
			Refused   int64  `json:"refused"`
			LastError string `json:"last_error"`
		} `json:"ingest"`
	}
	if err := json.Unmarshal([]byte(body), &meta); err != nil {
		return err
	}
	fmt.Fprintln(w, "meta db:", meta.DB.Kind, filepath.Base(meta.DB.Path))
	fmt.Fprintln(w, "meta ingest: accepted>0:", meta.Ingest.Accepted > 0, "refused:", meta.Ingest.Refused,
		"last_error:", meta.Ingest.LastError)

	rec, err := db.Run(ctx, res.ID)
	if err != nil {
		return err
	}
	stored, err := storedDeltas(path, res.ID)
	if err != nil {
		return err
	}
	fmt.Fprintln(w, "run:", rec.Status, "deltas counted:", rec.DeltaCount, "deltas stored:", stored)
	return nil
}

// storedDeltas counts the delta rows the file holds for a run: the
// rows KeepDeltas adds (obsdb/sqlite registers the "sqlite" driver).
func storedDeltas(path, runID string) (int, error) {
	h, err := sql.Open("sqlite", "file:"+path+"?mode=ro")
	if err != nil {
		return 0, err
	}
	defer func() { _ = h.Close() }()
	var n int
	err = h.QueryRow(`SELECT COUNT(*) FROM records WHERE run_id = ? AND kind = 'delta'`, runID).Scan(&n)
	return n, err
}

// clickhouseOpen is the hosted backend's call. No server listens here,
// so Open fails at its ping and returns the error.
func clickhouseOpen(_ context.Context, w io.Writer, _ string) error {
	srv, err := hostedOnClickHouse("clickhouse://default:weft@127.0.0.1:1/weft?dial_timeout=1s")
	if err == nil {
		_ = srv.Close()
		return fmt.Errorf("a server answered on port 1")
	}
	msg, _, _ := strings.Cut(err.Error(), ": dial")
	fmt.Fprintln(w, "open failed:", msg) // a closed port fails at Open's ping
	return nil
}

// hostedOnClickHouse opens the ClickHouse backend and serves Studio
// over it. The caller closes the server, then the DB.
func hostedOnClickHouse(dsn string) (*studio.Server, error) {
	db, err := clickhouse.Open(dsn, // clickhouse://user:pass@host:9000/db — the native port
		clickhouse.TTL(0, 7*24*time.Hour), // content keeps its 30-day default; spans and runs 7 days
	)
	if err != nil {
		return nil, err // a dial or ping failure, a migration error, or clickhouse.ErrNewerSchema
	}
	srv := studio.New(studio.DB(db)) // srv.Close leaves db open: close it after
	return srv, nil
}

func firstLine(s string) []byte {
	s, _, _ = strings.Cut(s, "\n")
	return []byte(s)
}
```

[production/storage.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/production/storage.go)

[View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/production) · run it from `docs-site/examples`:

```sh
go run ./production
go test ./production
```

```text
== storage backends
file: studio.db absolute: true
refused: 415 X-Request-Id: deploy-check-1
log: WARN "studio: ingest batch refused" request_id=deploy-check-1 status=415 code=unsupported
meta db: sqlite studio.db
meta ingest: accepted>0: true refused: 1 last_error: 415 unsupported: Content-Type must be application/x-protobuf or application/json
run: succeeded deltas counted: 1 deltas stored: 1
== clickhouse
open failed: clickhouse: ping
```

`accepted>0` is true because the run that follows the refused batch is exported over OTLP; its exact batch count depends on the exporter's timing. `TestOperations` pins the output.

## Best practices & gotchas

- **Point `slog.Default` where your logs go, before `studio.New` if you want the lines `New` logs.** Studio and its runtime server call the package-level `slog` functions at log time; there is no Studio logger option. (Source: `studio/meta.go:369-374`; `studio/manifests.go:70`; `studio/runtime/store.go:400, 421`)
- **Send your own `X-Request-Id` from a proxy or client.** Studio keeps a well-formed one and logs it, so one id follows the request through your logs and Studio's. (Source: `studio/internal/reqlog/reqlog.go:1-11, 101-115`)
- **Behind a reverse proxy, expect one ingest log line a minute per route class, status and code.** Every client shares the proxy's remote, so the limiter keys them together. (Source: `studio/internal/reqlog/reqlog.go:24-25`)
- **Watch `ingest.dropped`, not only `refused`.** A refusal is Studio saying no; `dropped` is the app saying its own queue lost records before they were sent. (Source: `studio/ingesthealth.go:14-31`)
- **Keep the same `Token` across restarts.** Panel tokens and live grants are signed with it; rotating it invalidates every one issued. (Source: `studio/auth.go:169-180`; `studio/livegrant.go:88-98`)
- **Build a playground Studio with `studio.New` and `Close` it.** `Close` drains the command store's queue before the database closes; `Handler` never does. (Source: `studio/README.md`, "When the store lags or fails")

## See also

- [Choose the observability database: SQLite or ClickHouse](https://weftgo.dev/docs/production/storage-backends/)
- [Keep and delete recorded runs](https://weftgo.dev/docs/production/retention/)
- [Secure Studio: tokens, loopback and origins](https://weftgo.dev/docs/production/security/)
- [weft CLI reference](https://weftgo.dev/docs/reference/cli/)
- [Connect your app to the playground](https://weftgo.dev/docs/observe/playground/connect/)

Symbols used: [`studio.New`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#New) · [`studio.DB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#DB) · [`Server.Close`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#Server.Close) · [`studio.Handler`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#Handler) · [`studio.Retain`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#Retain) · [`studio.Pricing`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#Pricing) · [`obsdb.CommandStore`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#CommandStore) · [`obsdb.Searcher`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#Searcher) · [`obsdb.StoredCommand`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#StoredCommand) · [`obsdb.RunRoute`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#RunRoute) · [`obsdb.StoredRuntime`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#StoredRuntime) · [`runtime.WithStore`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio/runtime#WithStore) · [`runtime.RuntimeView`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio/runtime#RuntimeView) · [`runtime.AgentView`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio/runtime#AgentView) · [`runtime.Registration`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio/runtime#Registration)
