---
title: 'Choose the observability database: SQLite or ClickHouse'
description: 'Studio and the local sink store recorded runs in an obsdb database: SQLite (one file, one host, the default) or ClickHouse (a hosted fleet). How to open each, what KeepDeltas and TTL change, how migrations behave, and which backend holds what.'
url: https://weftgo.dev/docs/production/storage-backends/
type: how-to
sources:
  - 'W11-auditB1-fix, v0.20.2: weft/obsdb/sqlite/stats.go:115-126 (WARN span_stats rollup write failed, once: spanStatsWarn), 185-202 (INFO 0023 backfill and done; nothing for a file with no spans); weft/obsdb/sqlite/write.go:285-304 (INFO 0026 re-deriving N and done); weft/obsdb/clickhouse/migrations.go:115-139 (INFO 0031 re-deriving N and done)'
  - 'W11-fix3, v0.20.2: go doc ./obsdb/sqlite DB and ./obsdb/clickhouse DB (every method: SessionEvents, Stats, ErrorCounts, DeleteRuntime, PutBreakpointSet, BreakpointSet beside the rest); weft/CHANGELOG.md:115, 227 (Stats 0.19.0, SessionEvents 0.18.0); weft/cmd/weft/main.go:85-97, 641; weft/cmd/weft/dev.go:276 (the <db>.lock taken by weft studio and weft dev only; weft vacuum and sqlite.Open take none); weft/cmd/weft/dblock.go:15-25'
  - 'weft/obsdb/sqlite/migrations/0023_span_stats.sql:1-57 (span_stats, the backfill in the migration''s transaction), 24, 25, 26 (headers); weft/obsdb/clickhouse/migrations/0028-0033 (headers); weft/CHANGELOG.md:81-86 (0.20.0 upgrade notes: schema 0026 / 0033, the re-derive''s scope and cost, ErrNewerSchema, the breakpoints column) — v0.20.2'
  - 'weft/obsdb/sqlite/sqlite.go:1-12 (package doc: one writer plus a read pool, WAL, Hub), 34-62 (DB, Option, KeepDeltas), 64-108 (Open: pragmas, WAL once, migrate, Path), 155-200 (openHandles: 4 read connections, MkdirAll, :memory: one handle), 206-219 (Hub, Path), 221-235 (Close)'
  - 'weft/obsdb/sqlite/migrations.go:14-19 (obsdb_migrations, one file can also hold thread''s sessions), 48-64 (postMigrations: 0004 backfill), 81-89 (ErrNewerSchema), 91-151 (migrate: one transaction per version, the re-read)'
  - weft/obsdb/sqlite/write.go:23-27, 146-169 (deltas counted, stored only under KeepDeltas; heartbeats never stored)
  - weft/obsdb/sqlite/migrations/0001_init.sql to 0022_session_events.sql (header comments)
  - weft/obsdb/clickhouse/migrations/0023_runs_caller.sql to 0027_runs_chat_role_restated.sql (header comments)
  - weft/obsdb/clickhouse/README.md:19-21 (ClickHouse 25.6 or later)
  - 'weft/obsdb/clickhouse/clickhouse.go:15-21 (DefaultContentTTL, DefaultMetaTTL), 25-36 (DB), 52-58 (KeepDeltas), 60-84 (TTL), 86-137 (Open: ParseDSN, async_insert, Ping, migrate, applyTTLs), 139-158 (applyTTLs, the five tables), 160-165 (ttlSeconds rounds up), 167-178 (Close, ErrClosed)'
  - 'weft/obsdb/clickhouse/migrations.go:18-25, 216-222 (ErrNewerSchema), 224-273 (migrate), 242-243 (its error text: database has migration N)'
  - weft/obsdb/clickhouse/migrations/0003_status_spelling.sql, 0005_raw_record.sql:42 (the view takes request, prompt, tools, raw), 0016_spans_run_index_manifests.sql:1-16 (RunId bloom index, MATERIALIZE INDEX, manifests), 0020_runs_parent_index.sql:14-16 (ALTER … IF NOT EXISTS)
  - clickhouse-go v2.48.0 clickhouse_options.go:257-262 (dial_timeout is a driver option), 278-285 and 377 (secure turns TLS on), 359-369 (unknown parameters become settings), 383-397 (no clickhouses scheme), via docs-site/factcheck/production-b.md
  - weft/obsdb/sqlite/search.go:342-346 (the short-term ASCII fold)
  - weft/obsdb/clickhouse/doc.go (collector-compatible stance, weft_records, weft_runs, derived runs)
  - weft/obsdb/clickhouse/README.md (tables, DSN forms, port 9000, lightweight DELETE on 23.3+, the parked filter's column scan, the container recipe, gated tests)
  - weft/obsdb/clickhouse/delete.go:15-23 (lightweight DELETE, GA since 23.3)
  - weft/obsdb/clickhouse/example_test.go:13-38 (ExampleOpen, compiled not run)
  - weft/obsdb/sqlite/sqlite_test.go:1437-1449 (ExampleDB_Path)
  - 'weft/cmd/weft/main.go:862-907 (newServer: sqlite://, clickhouse://, the only import of the driver, the error texts), 915-937 (dbFile: $WEFT_DB, .weft/weft.db)'
  - weft/cmd/weft/vacuum.go:126-166 (openVacuumDB)
  - 'weft/studio/studio.go (Open, DB godoc), 245-249 (the hub: the DB''s own, else obsdb.NewHub fed by ingest)'
  - 'weft/studio/meta.go:147-157 (metaDB: path and size, the WAL included), 299-332 (mayReadDBPath, dbFile)'
  - weft/studio/api.go:2927-2946 (dbKind)
  - weft/studio/README.md:2722-2731 (CommandStore on both backends; one Studio per command store)
  - 'weft/docs/adr/0024-observability-data.md:46-66 (obsdb, the SQLite sink first-class), 120-134 (D4: the shared handle), 185-195 (D10 Q4 deltas never stored, Q5, Q6), 300-334 (the obsdb_migrations contract, root_ended)'
  - weft/docs/adr/0026-thread-storage-backends.md:24-28 (thread never writes to the observability database)
  - 'weft/CHANGELOG.md:562 (event without a position at -1), 606 (0007/0008 command tables), 608 (PruneCommands), 1044 (search: sqlite 0004, ClickHouse none), 1193 (experiment index, MATERIALIZE INDEX), 2518 (Path), 3285 (paths with % ? #), 3146 and 3033 (ClickHouse 0003 status spelling), 3049, 3866, 3970, 3981, 3985, 4035, 4099, 4111, 4125, 4133, 4151, 4156, 4260'
  - 'observed: weft v0.17.0 studio --db sqlite://prodB.db on a fresh file: prodB.db 4,096 B plus a 457,352 B -wal after the migrations; /api/meta db.size 461448, 2026-10-18'
  - docs-site/examples/production/storage.go (storageBackends, clickhouseOpen, hostedOnClickHouse), main_test.go TestOperations
---

# Choose the observability database: SQLite or ClickHouse

Every recorded run lands in an `obsdb` database. Use [`sqlite.Open`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#Open), one file on one host, for development, a single server or a Studio beside its app; it is what `otel.Local`, `studio.Open` and `weft studio` open by default. Use [`clickhouse.Open`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#Open) for a hosted Studio that a fleet of apps exports to, where you want table TTLs and a schema a stock OTel Collector can also write. Both return the same [`obsdb.DB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DB), so Studio reads either with the same calls.

Open a SQLite file that also keeps the streaming deltas, in `production/storage.go`:

```go title="production/storage.go"
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:"
```

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

`Open` creates the file and its directory when missing and brings the schema up to date before it returns. The `Path()` it exposes is the absolute path Studio's `/api/meta` reports as `db.path`.

## Which backend holds what

| Aspect | SQLite | ClickHouse |
|---|---|---|
| Where | One file (plus `-wal` and `-shm` beside it) | A database on a ClickHouse server, named by the DSN's path |
| Writers | One writer connection per process; other processes wait on the 30 s busy timeout | Any number, through the driver's pool and async inserts |
| Live lane | In process: the handle's `Hub()` publishes every write, which is what makes setup A live | None in the handle: Studio makes an in-process hub its OTLP ingest feeds |
| Expiry | None: [`studio.Retain`](https://weftgo.dev/docs/production/retention/#retain) and `weft vacuum` | Table TTLs (content 30 days, spans and runs 90 days), plus `Retain` |
| Opened by | `otel.Local(path)`, `studio.Open(path)`, `weft studio` (default), `weft dev` | Your server's `clickhouse.Open(dsn)`, `weft studio --db clickhouse://…` |
| Shared with | `thread/sqlite`'s sessions may live in the same file | Rows from a stock OTel Collector pinned to exporter v0.162.0 |

What an obsdb database holds: the spans, the weft records (events, transcript batches, request, prompt and tools records, raw provider bodies when [`otel.RawBodies`](https://weftgo.dev/docs/production/content-and-privacy/#raw-provider-bodies) is on), the app log lines bridged under a run's spans, the run rows derived from them, saved experiments, stored manifests and the playground's command records. It never holds a conversation: sessions are `thread`'s, and `thread` never writes to the observability database (ADR 0026). For session storage see [Store sessions](https://weftgo.dev/docs/sessions/storage/).

Two things are never stored on either backend by default. Deltas (the streaming text and argument fragments) are counted on the run row and dropped; heartbeats only move the run's last-seen time, which is how a silent run reads interrupted after 30 s. Writes are idempotent on (run, record kind, position) and (trace, span), so a retried export is a no-op.

## SQLite

`sqlite.Open(path, opts...)` returns a [`*sqlite.DB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB) as an `obsdb.DB`. It runs on the CGO-free `modernc.org/sqlite` driver, so it needs no C toolchain.

- **Connections.** One writer connection serializes every `Write`; a pool of four read connections serves queries. The file is switched to `journal_mode=WAL` once (a property of the file). The writer connection carries `synchronous=NORMAL`, `busy_timeout=30000`, `foreign_keys=ON` and `_txlock=immediate`; the read connections carry `busy_timeout=30000` and `foreign_keys=ON`.
- **Another process.** WAL lets a reader in another process see the same data through its own `Open`, history only: a second handle has no live lane. The live lane is the handle's own [`Hub()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.Hub), which every `Write` publishes to before it returns. That is why setup A passes the pipeline's handle, `studio.DB(otel.LocalDB())`, instead of opening the file again.
- **`:memory:`.** One in-process database on a single handle, nothing on disk; `Path()` returns `""` and `/api/meta` reports no path or size.
- **Odd paths.** A path containing `%`, `?` or `#`, or one starting with `//`, opens the file it names (fixed in obsdb 0.2.0; before it, such a path opened a misparsed location).
- **[`KeepDeltas()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#KeepDeltas)** stores each delta record in the `records` table under kind `delta`, for debugging. Deltas keep their own counter either way, so storing or dropping them never opens a hole in the durable event sequence.
- **One Studio per file.** Since 0.20.0 `weft studio` and `weft dev` take `<db>.lock` beside the file while they serve, an exclusive OS lock the kernel releases when the process ends. A second `weft studio` on the file is refused (exit 1); `weft dev` reuses the running one. `sqlite.Open` itself takes no lock, so your own code and `weft vacuum` still open the file ([Run the weft studio binary](https://weftgo.dev/docs/observe/studio/setup/#run-the-weft-studio-binary)).
- **A file shared with sessions.** obsdb tracks its schema in its own `obsdb_migrations` table, and `thread/sqlite` in its own, so one file can hold both. Deletion and vacuum touch obsdb's tables only ([Studio's tables only](https://weftgo.dev/docs/production/retention/#studios-tables-only)).
- **Search.** The FTS5 trigram index (migration 0004) is kept by the writer. A term under three runes is matched with `LIKE`, case-folded for ASCII only; ClickHouse folds UTF-8.

[`ExampleDB_Path`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#example-DB.Path) reads the path back through the same interface Studio uses.

**Sizing.** A fresh file after its migrations was 4,096 bytes plus a 457,352-byte `-wal`, and `/api/meta` reported `"size": 461448` for it: Studio's figure includes the WAL. The file grows with spans, records and app log lines; content-off destinations store events without bodies, so they are smaller. Deleting rows does not shrink the file: `weft vacuum` rewrites it ([Sweep and vacuum once](https://weftgo.dev/docs/production/retention/#sweep-and-vacuum-once)).

### The SQLite DB's methods

The methods are the `obsdb.DB` interface and its optional extensions. Studio calls them; you call them to read runs from your own code or tests.

| Group | Methods |
|---|---|
| Write and live | [`Write`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.Write) · [`Hub`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.Hub) |
| Runs | [`Runs`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.Runs) · [`Run`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.Run) · [`ChildRuns`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.ChildRuns) · [`Search`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.Search) · [`ResolvePublicID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.ResolvePublicID) |
| One run's records | [`Events`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.Events) · [`Transcript`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.Transcript) · [`TranscriptBatches`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.TranscriptBatches) · [`Compactions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.Compactions) · [`Requests`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.Requests) · [`Prompt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.Prompt) · [`Tools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.Tools) · [`Catalogs`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.Catalogs) |
| Spans and logs | [`RunSpans`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.RunSpans) · [`RunTreeSpans`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.RunTreeSpans) · [`Trace`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.Trace) · [`Traces`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.Traces) · [`OtherLogs`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.OtherLogs) · [`CountLogs`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.CountLogs) |
| Sessions | [`Sessions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.Sessions) · [`Session`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.Session) · [`SessionEvents`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.SessionEvents) (0.18.0) |
| Aggregates | [`Stats`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.Stats) · [`ErrorCounts`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.ErrorCounts) (0.19.0) |
| Experiments and manifests | [`SaveExperiment`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.SaveExperiment) · [`Experiments`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.Experiments) · [`Experiment`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.Experiment) · [`PutManifest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.PutManifest) · [`Manifest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.Manifest) |
| Playground commands ([the command store](https://weftgo.dev/docs/production/studio-operations/#the-command-store)) | [`PutCommand`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.PutCommand) · [`Commands`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.Commands) · [`PutRoute`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.PutRoute) · [`Route`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.Route) · [`PutBreakpoints`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.PutBreakpoints) · [`Breakpoints`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.Breakpoints) · [`PutRuntime`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.PutRuntime) · [`Runtimes`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.Runtimes) · [`DeleteRuntime`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.DeleteRuntime) (0.19.0) · [`PutBreakpointSet`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.PutBreakpointSet) · [`BreakpointSet`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.BreakpointSet) (0.20.0) · [`PruneCommands`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.PruneCommands) |
| Deletion and lifecycle | [`DeleteRun`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.DeleteRun) · [`DeleteSession`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.DeleteSession) · [`Sweep`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.Sweep) · [`Vacuum`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.Vacuum) · [`Path`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.Path) · [`Close`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.Close) |

A call after `Close` returns `obsdb.ErrClosed`, including one that raced `Close`. [`sqlite.Option`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#Option) is the option type `Open` takes; `KeepDeltas` is its one value.

## ClickHouse

`clickhouse.Open(dsn, opts...)` connects with clickhouse-go v2, pings the server, migrates the schema and applies any TTL override. The schema needs ClickHouse 25.6 or later: migration 0001 puts TTLs on `DateTime64(9)` columns, which older servers refuse. Open it in your own server and hand it to Studio:

```go title="production/storage.go"
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
```

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

The example program has no ClickHouse server, so it calls this function with port 1 and prints the error `Open` returns, `clickhouse: ping`. A closed port, a wrong password or a missing database fails at `Open`, not at the first write. `srv.Close()` leaves a `DB(db)` you passed open: close the handle after the server ([`studio.DB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#DB)).

**The DSN.** `clickhouse://user:pass@host:9000/database` uses the native protocol, on port 9000, not the HTTP port 8123. `?secure=1` (or `secure=true`) turns TLS on; the driver has no `clickhouses://` scheme, and `weft studio --db` accepts the `clickhouse://` prefix only. Driver parameters such as `dial_timeout=10s` are read by clickhouse-go; any other parameter, such as `max_execution_time=60`, becomes a server setting. Open adds `async_insert=1` and `wait_for_async_insert=1`, so a write returns once the server has flushed its batch and a read right after it sees the rows.

**The tables.**

| Table | Engine and key | What it holds |
|---|---|---|
| `otel_traces`, `otel_logs` | The OTel Collector exporter's columns, pinned at v0.162.0 | Every span and log record. The weft identity is materialized beside them with bloom skip indexes on `SessionId`, `PublicId`, `Agent` and `TraceId` |
| `weft_records` | `ReplacingMergeTree(InsertTime) ORDER BY (RunId, Kind, Pos)` | Event, transcript, request, prompt, tools and raw records, filled by a materialized view from `otel_logs`; never deltas or heartbeats. It has its own content TTL, because a source table's TTL does not cascade through a view |
| `weft_runs` | `AggregatingMergeTree ORDER BY RunId` | One row per run, filled by two views (from `otel_logs`, heartbeats included, and from `otel_traces`). Status is never stored: every read derives it |
| `weft_deltas` | `ReplacingMergeTree` on `(RunId, Pos)` | Delta rows, only with `KeepDeltas()`; nothing else feeds it |
| `obsdb_migrations` | `MergeTree ORDER BY version` | The applied migrations |

A stock collector pinned to exporter v0.162.0 and configured with `create_schema: false` writes into the same `otel_traces` and `otel_logs`; Studio derives runs from its GenAI spans. Since migration 0003, spans are written with the collector's spelling (`Internal`, `Error`, …), and both spellings read back.

**[`TTL(content, meta)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#TTL)** sets the retention windows. `content` applies to `otel_logs`, `weft_records` and `weft_deltas`; `meta` to `otel_traces` and `weft_runs`. A value of 0 or less keeps that class's default, [`DefaultContentTTL`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DefaultContentTTL) (30 days) or [`DefaultMetaTTL`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DefaultMetaTTL) (90 days). Open applies a non-default window with `ALTER TABLE … MODIFY TTL`, in whole seconds rounded up. An Open with both classes at their defaults alters nothing, so a process that opens the database without `TTL`, such as `weft studio --db clickhouse://…`, never undoes the windows your writer set. When either window is set, Open writes both on all five tables: `TTL(0, 7*24*time.Hour)` also resets the content tables to 30 days, undoing an earlier `TTL(60*24*time.Hour, …)`. Every process that passes `TTL` must pass the same pair.

**[`KeepDeltas()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#KeepDeltas)** makes `Write` also insert each delta into `weft_deltas`. It lives in `Write`, not in the schema, because a view cannot be gated on an option. [`clickhouse.Option`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#Option) is the type of both options.

**Deletion.** `DeleteRun`, `DeleteSession` and `Sweep` issue lightweight `DELETE FROM … WHERE` on the five data tables (lightweight deletes, available since ClickHouse 23.3, below the schema's own 25.6 floor). Rows are masked at once and leave the parts at the next merge; `Vacuum` forces that with `OPTIMIZE TABLE … FINAL`. Each chunk of a deletion (400 runs, 200 span keys) issues up to seven synchronous mutations, so a large sweep is many mutations. The TTLs stay as they are ([ClickHouse TTLs](https://weftgo.dev/docs/production/retention/#clickhouse-ttls)).

**Query cost.** The `parked` status filter (`/api/runs?status=parked`) reads the `ResumedFrom` column of every `weft_runs` row on each query; the other status words read only the grouped rows the order index walks.

**One Studio per database.** Two Studios over one ClickHouse database do not see each other's playground acks and heartbeats; a restarted one would load the other's queued and accepted commands and mark them lost ([After a restart](https://weftgo.dev/docs/production/studio-operations/#after-a-restart)).

**Testing against a server.** The package's conformance table ([`obsdbtest.Run`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/obsdbtest#Run)) runs only when `WEFT_CLICKHOUSE_DSN` is set, each subtest on a fresh database. weft's README for the package gives the container weft's CI uses:

```sh
docker run -d --name weft-clickhouse -p 127.0.0.1:9000:9000 \
  -e CLICKHOUSE_PASSWORD=weft --ulimit nofile=262144:262144 \
  clickhouse/clickhouse-server:25.8-alpine
```

[`ExampleOpen`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#example-Open) opens with `TTL(0, 7*24*time.Hour)` and `KeepDeltas()`; like this page's example, it is compiled but needs a server to run. This page's ClickHouse claims come from the code and its tests, not from a run against a server.

### The ClickHouse DB's methods

The same groups as SQLite's, minus `Hub` and `Path`:

| Group | Methods |
|---|---|
| Write | [`Write`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.Write) |
| Runs | [`Runs`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.Runs) · [`Run`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.Run) · [`ChildRuns`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.ChildRuns) · [`Search`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.Search) · [`ResolvePublicID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.ResolvePublicID) |
| One run's records | [`Events`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.Events) · [`Transcript`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.Transcript) · [`TranscriptBatches`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.TranscriptBatches) · [`Compactions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.Compactions) · [`Requests`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.Requests) · [`Prompt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.Prompt) · [`Tools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.Tools) · [`Catalogs`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.Catalogs) |
| Spans and logs | [`RunSpans`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.RunSpans) · [`RunTreeSpans`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.RunTreeSpans) · [`Trace`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.Trace) · [`Traces`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.Traces) · [`OtherLogs`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.OtherLogs) · [`CountLogs`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.CountLogs) |
| Sessions | [`Sessions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.Sessions) · [`Session`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.Session) · [`SessionEvents`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.SessionEvents) (0.18.0) |
| Aggregates | [`Stats`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.Stats) · [`ErrorCounts`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.ErrorCounts) (0.19.0) |
| Experiments and manifests | [`SaveExperiment`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.SaveExperiment) · [`Experiments`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.Experiments) · [`Experiment`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.Experiment) · [`PutManifest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.PutManifest) · [`Manifest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.Manifest) |
| Playground commands | [`PutCommand`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.PutCommand) · [`Commands`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.Commands) · [`PutRoute`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.PutRoute) · [`Route`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.Route) · [`PutBreakpoints`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.PutBreakpoints) · [`Breakpoints`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.Breakpoints) · [`PutRuntime`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.PutRuntime) · [`Runtimes`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.Runtimes) · [`DeleteRuntime`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.DeleteRuntime) (0.19.0) · [`PutBreakpointSet`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.PutBreakpointSet) · [`BreakpointSet`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.BreakpointSet) (0.20.0) · [`PruneCommands`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.PruneCommands) |
| Deletion and lifecycle | [`DeleteRun`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.DeleteRun) · [`DeleteSession`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.DeleteSession) · [`Sweep`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.Sweep) · [`Vacuum`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.Vacuum) · [`Close`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB.Close) |

[`clickhouse.DB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB) is safe for concurrent use. Lists read through `GROUP BY RunId`, single-run pages through `FINAL` narrowed by primary key, and every call after `Close` (or racing it) returns `obsdb.ErrClosed`.

## Open it from the weft command

`weft studio`, `weft dev` and `weft vacuum` take the database as a URL in `--db`:

```sh
weft studio                                            # $WEFT_DB, else ./.weft/weft.db
weft studio --db sqlite://weft.db                      # relative to the working directory
weft studio --db sqlite:///var/lib/weft/weft.db        # absolute: three slashes
weft studio --db clickhouse://default:pass@ch.internal:9000/weft
```

`sqlite://` with no path is an error (`--db sqlite:// needs a path (sqlite://weft.db, sqlite:///var/lib/weft.db)`), and any other scheme is `--db must be sqlite://path or clickhouse://user:pass@host:9000/db`. A ClickHouse URL is passed whole to `clickhouse.Open`, so a dial failure ends the command before it serves. Within weft, `cmd/weft` is the only package that imports `obsdb/clickhouse`; a Go program pays for the driver only when it imports the package itself. [The weft command](https://weftgo.dev/docs/reference/cli/#weft-studio) lists every flag.

## Migrations

Both backends version their schema the same way: embedded SQL files numbered from 0001, applied in order by `Open`, recorded in an `obsdb_migrations` table. On SQLite each migration runs in its own transaction, and a second process opening the same fresh file skips what the first applied. On ClickHouse every statement is idempotent (`CREATE` and `ALTER … IF NOT EXISTS`, `MODIFY QUERY`, `MATERIALIZE INDEX`), so two racing Opens converge.

Upgrading weft migrates in place: the next `Open` (your server's, or `weft studio`'s) applies the new files. There is no way back. A database whose recorded version is ahead of the binary fails `Open` with `ErrNewerSchema`, [`sqlite.ErrNewerSchema`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#ErrNewerSchema) or [`clickhouse.ErrNewerSchema`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#ErrNewerSchema), whose text names both versions: `file has migration N, this binary knows up to M` on SQLite, `database has migration N, this binary knows up to M` on ClickHouse. Upgrade every process that opens the database, Studio and every app with a local sink, before or with the first one that migrates it.

At 0.20.2, as at 0.20.1 and 0.20.0, SQLite is at migration 26 and ClickHouse at 33; 0.19.0 left them at 25 and 28, v0.18.3 at 22 and 27. The numbers differ because each backend has migrations the other does not need (among others: ClickHouse's status spelling, raw-record restatements and meta extractions; SQLite's extra indexes). The ones with an operator-visible effect:

| SQLite | ClickHouse | What it adds |
|---|---|---|
| 0001 | 0001 | The schema: spans, records, app logs, runs (SQLite); the collector-compatible tables and the weft views (ClickHouse) |
| 0002 | 0002 | The `experiments` table behind `SaveExperiment`, `Experiments` and `Experiment` (ClickHouse as a `ReplacingMergeTree(InsertTime)`) |
| — | 0003 | Spans stored in the collector's status spelling. Breaking for anyone querying `otel_traces.SpanKind` or `StatusCode` strings directly; rows stored before it are not backfilled |
| 0004 | — | Search: `run_search`, `run_tools` and the FTS5 trigram table `runs_fts`, with the runs already stored indexed in the migration's transaction. ClickHouse needs no migration: it derives the fields at read time |
| 0006 | 0007 | An index for an experiment's runs. On ClickHouse, parts written before it are indexed when merged; `ALTER TABLE weft_runs MATERIALIZE INDEX idx_experiment` does it at once |
| 0007 | 0008 | The playground's command store: `commands`, `run_routes`, `breakpoints`, `runtimes` (on ClickHouse `ReplacingMergeTree` tables read `FINAL`) |
| 0009 | 0010 | `root_ended`: a run whose root span is stored reads finished, backfilled from the spans already stored |
| 0014 | 0016 | The `manifests` table `/api/manifests/{hash}` reads, plus run-list indexes (SQLite) or a bloom index on `otel_traces.RunId`, built in the background by `MATERIALIZE INDEX` (ClickHouse) |
| 0019, 0020 | — | Start-time indexes on spans for the traces list and a trace's spans |
| 0021 | 0023 | A run's caller link (`caller_run_id`, `caller_call_id`) and a session's lineage. On ClickHouse a background mutation backfills it |
| 0022 | 0025 | `session_events` (`weft_session_events` on ClickHouse): every `thread` record and compaction marker indexed by session, backfilled from the records already stored |
| — | 0024, 0027 | The run views restated so a summarizer's `chat` span feeds no column of the run row |
| — | 0026 | `idx_meta`, an ngram index over `Meta` for the `tag.<k>=<v>` session filter, materialized by a background mutation |
| 0023, 0025 | — | 0.19.0: `span_stats`, one row per stored run, model call and tool call, so `GET /api/stats` reads no attribute JSON. Backfilled from the stored spans inside the migration's transaction, so `Open` waits for it. ClickHouse aggregates its spans natively and needs no table |
| 0024 | 0028 | 0.19.0: an experiment's pass predicate, stored verbatim. No backfill: an experiment saved before it reads `""` |
| — | 0029, 0030, 0033 | 0.20.0: the traces view restated so the new span attributes (`weft.tool.denied_by`, `error_masked`, `args_repaired`, the `layer` attributes, `weft.tool.origin`, `weft.attempt.giveup_reason`, `weft.output.type`) stay out of a run's `meta`. No backfill: no span stored before carries them |
| 0026 | 0031 | 0.20.0: stock GenAI traces re-derived by the new derived-run rule ([below](#the-020-re-derive)) |
| — | 0032 | 0.20.0: a remote caller link (`weft.caller.remote`) is not a run's caller; SQLite derives this in Go and needs no migration |

### The 0.20 re-derive

SQLite 0026 and ClickHouse 0031 re-derive the stored stock GenAI traces that the 0.20.0 derived-run rule changes. Those are the traces holding a non-weft `invoke_agent` span without a string `gen_ai.conversation.id`, a non-weft `chat` span carrying message content, or a conversation-rooted `invoke_agent` span in a trace no writer derived. A database from before derived runs (SQLite 0008, ClickHouse 0009) has every stock trace re-derived. Afterwards a setup B database may list runs it did not list before, top-level agent spans without a conversation id, and its derived rows gain their message count.

It is a one-time cost on the first open, and `Open` waits for it. An INFO line names the trace count before, `weft/obsdb/sqlite: migrating: re-deriving N stock traces (SQLite 0026); Open waits for it` (`… (ClickHouse 0031) …`), and another the time after: about 1 s per 10,000 traces on either backend. It is idempotent: an interrupted run records nothing and the next open starts again from the beginning. On SQLite it runs inside the migration's write transaction, so an app's local sink writing to the same file waits on its 30 s busy timeout meanwhile. If the store holds many stock traces, open the file with `weft studio` once before pointing a running app at it.

A 0.19.x binary refuses the migrated database with `ErrNewerSchema`. Breakpoints a 0.20.0 Studio set through a surface are stored as a JSON object in the same column, so a 0.19.x Studio opened on that store reads no set for that runtime; the runtime's registration re-delivers its own.

On ClickHouse, the unreleased first text of migration 0004 (written only by development builds before 0.10.0) lacks columns the released text adds; a database that applied it must be recreated.

### Migration log lines

The backends log through `slog.Default()`, so the lines land in the log of whatever opens the database: `weft studio`, or your app's local sink.

| Level | Message | Attributes | When |
|---|---|---|---|
| INFO | `weft/obsdb/sqlite: migration 0023 backfills the span_stats rollup; Open waits for it` | `spans` | SQLite 0023 on a file that holds spans; a new file logs nothing |
| INFO | `weft/obsdb/sqlite: migration 0023 backfill done` | `spans`, `duration` | The backfill finished |
| INFO | `weft/obsdb/sqlite: migrating: re-deriving N stock traces (SQLite 0026); Open waits for it` | `traces` | SQLite 0026 found stock traces to re-derive ([above](#the-020-re-derive)) |
| INFO | `weft/obsdb/sqlite: migration 0026 re-derive done` | `traces`, `duration` | The re-derive finished |
| INFO | `weft/obsdb/clickhouse: migrating: re-deriving N stock traces (ClickHouse 0031); Open waits for it` | `traces` | ClickHouse 0031 found stock traces to re-derive |
| INFO | `weft/obsdb/clickhouse: migration 0031 re-derive done` | `duration` | The re-derive finished |
| WARN | `weft/obsdb/sqlite: span_stats rollup write failed; the span is stored, the stats skip it (further failures are not logged)` | `trace_id`, `span_id`, `error` | A span's `span_stats` row could not be written. The span is kept, and `GET /api/stats` leaves it out. Logged once per process |

### Changes by release that affect stored data

- **Positions.** An `event` record with no `weft.event.pos` is stored at position -1 on both backends, never at 0 where it collided with `run_start`; a `delta` without one counts as position 0 (0.15.0).
- **Command pruning.** `PruneCommands` deletes on SQLite in passes of `obsdb.SweepBatch` terminal commands, each its own transaction. On ClickHouse it deletes exactly the row versions each rule selected, so a `PutCommand`, `PutRoute` or `PutRuntime` landing mid-prune keeps its row; the caller still serializes the prune with its writes. A stale empty breakpoint set no runtime names is pruned on both (0.15.0).
- **Sessions.** `Session(id)` reads the session's own grouped row on both backends, so a session older than the newest 500 resolves (obsdb 0.1.1, pinned by `TestSessionBeyondNewestPage`).
- **Paging on ClickHouse.** Cursors compare in integer nanoseconds; before obsdb/clickhouse 0.1.1 they floored to the second and skipped rows at page boundaries (`TestCursorSubSecondPaging`).
- **Experiments on ClickHouse.** `SaveExperiment` surfaces every read error except `ErrNotFound`, so a transient failure no longer resets `Created` (`TestExperimentCreatedSurvivesUpdate`); migration 0002's engine shape is pinned offline by `TestSpecExperimentsEnginePresent` (obsdb/clickhouse 0.1.1).
- **ClickHouse 0.2.0.** `ResolvePublicID` orders by (turn, started) as SQLite does; TTL windows round up to whole seconds; detail reads narrow `FINAL` by primary key; calls racing `Close` return `ErrClosed`.
- **The first releases (0.7.0).** `obsdb/sqlite` arrived with an idempotent one-transaction `Write` (`INSERT OR IGNORE` on (run, kind, pos) and (trace, span)), deltas counted and never stored, heartbeats moving last-seen only, and a reordered batch's provisional start corrected when `run_start` lands. `obsdb/clickhouse` arrived with the collector-compatible tables, the `weft_records` and `weft_runs` views, `KeepDeltas` into `weft_deltas`, and the conformance table gated on `WEFT_CLICKHOUSE_DSN`.

## Complete example

`storage.go` is a file of the Production example package. Its `storageBackends` opens the SQLite file with `KeepDeltas`, serves Studio over it, records one run through OTLP and reads back what Studio and the file hold; `clickhouseOpen` shows the hosted call:

```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
```

`deltas stored: 1` is `KeepDeltas` at work: without it the same run counts one delta and stores none. The log and ingest lines belong to [Operate Studio](https://weftgo.dev/docs/production/studio-operations/). `TestOperations` in `main_test.go` pins this output.

## Best practices & gotchas

- **Pass the pipeline's handle to an embedded Studio.** A second `sqlite.Open` of the same file reads history but no live runs: the live lane is the handle's hub. (Source: ADR 0024 D4; `obsdb/sqlite/sqlite.go:206-210`)
- **Upgrade every reader before the first writer migrates.** An older binary fails `Open` with `ErrNewerSchema` on a migrated file, and migrations are one-way. (Source: `obsdb/sqlite/migrations.go:81-101`)
- **Set ClickHouse TTLs in one place, as a pair.** An Open without `TTL` changes nothing, so `weft studio` never resets them; but an Open with `TTL` rewrites both windows, so every process that passes it must pass the same two values. (Source: `clickhouse.TTL` godoc; `obsdb/clickhouse/clickhouse.go:138-148`)
- **Use port 9000 in the DSN.** The driver speaks ClickHouse's native protocol; 8123 is the HTTP interface. (Source: `obsdb/clickhouse/README.md`, DSN forms)
- **Leave `KeepDeltas` for debugging.** With it, every streamed fragment becomes a stored row; without it, deltas are counted and dropped by design. (Source: `sqlite.KeepDeltas` godoc; `obsdb/sqlite/write.go:154-164`; ADR 0024 D10 Q4)
- **Run one Studio per ClickHouse database.** Two Studios on one command store decide each other's commands lost after a restart. (Source: `studio/README.md:2722-2731`)

## See also

- [Keep and delete recorded runs](https://weftgo.dev/docs/production/retention/)
- [Operate Studio: logs, restarts and the runtime link](https://weftgo.dev/docs/production/studio-operations/)
- [Deploy an agent service with a hosted Studio](https://weftgo.dev/docs/production/deploying/)
- [Store sessions](https://weftgo.dev/docs/sessions/storage/)

Symbols used: [`sqlite.Open`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#Open) · [`sqlite.KeepDeltas`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#KeepDeltas) · [`sqlite.DB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB) · [`sqlite.ErrNewerSchema`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#ErrNewerSchema) · [`clickhouse.Open`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#Open) · [`clickhouse.TTL`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#TTL) · [`clickhouse.KeepDeltas`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#KeepDeltas) · [`clickhouse.DB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB) · [`clickhouse.ErrNewerSchema`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#ErrNewerSchema) · [`obsdb.DB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DB) · [`obsdb.ErrClosed`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#ErrClosed) · [`obsdb.SweepBatch`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#SweepBatch) · [`obsdbtest.Run`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/obsdbtest#Run) · [`studio.DB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#DB) · [`studio.Open`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#Open) · [`studio.New`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#New) · [`otel.LocalDB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#LocalDB)
