Choose the observability database: SQLite or ClickHouse
Every recorded run lands in an obsdb database. Use 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 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, so Studio reads either with the same calls.
Open a SQLite file that also keeps the streaming deltas, in production/storage.go:
db, err := sqlite.Open(path, sqlite.KeepDeltas()) // created if missing, migrated to this binary's schemaif 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:"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
Section titled “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 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 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.
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
Section titled “SQLite”sqlite.Open(path, opts...) returns a *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 tojournal_mode=WALonce (a property of the file). The writer connection carriessynchronous=NORMAL,busy_timeout=30000,foreign_keys=ONand_txlock=immediate; the read connections carrybusy_timeout=30000andforeign_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 ownHub(), which everyWritepublishes 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/metareports 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()stores each delta record in therecordstable under kinddelta, 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 studioandweft devtake<db>.lockbeside the file while they serve, an exclusive OS lock the kernel releases when the process ends. A secondweft studioon the file is refused (exit 1);weft devreuses the running one.sqlite.Openitself takes no lock, so your own code andweft vacuumstill open the file (Run the weft studio binary). - A file shared with sessions. obsdb tracks its schema in its own
obsdb_migrationstable, andthread/sqlitein its own, so one file can hold both. Deletion and vacuum touch obsdb’s tables only (Studio’s 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 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).
The SQLite DB’s methods
Section titled “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 · Hub |
| Runs | Runs · Run · ChildRuns · Search · ResolvePublicID |
| One run’s records | Events · Transcript · TranscriptBatches · Compactions · Requests · Prompt · Tools · Catalogs |
| Spans and logs | RunSpans · RunTreeSpans · Trace · Traces · OtherLogs · CountLogs |
| Sessions | Sessions · Session · SessionEvents (0.18.0) |
| Aggregates | Stats · ErrorCounts (0.19.0) |
| Experiments and manifests | SaveExperiment · Experiments · Experiment · PutManifest · Manifest |
| Playground commands (the command store) | PutCommand · Commands · PutRoute · Route · PutBreakpoints · Breakpoints · PutRuntime · Runtimes · DeleteRuntime (0.19.0) · PutBreakpointSet · BreakpointSet (0.20.0) · PruneCommands |
| Deletion and lifecycle | DeleteRun · DeleteSession · Sweep · Vacuum · Path · Close |
A call after Close returns obsdb.ErrClosed, including one that raced Close. sqlite.Option is the option type Open takes; KeepDeltas is its one value.
ClickHouse
Section titled “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:
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 afterThe 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).
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) 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 (30 days) or 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() 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 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).
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).
Testing against a server. The package’s conformance table (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:
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-alpineExampleOpen 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
Section titled “The ClickHouse DB’s methods”The same groups as SQLite’s, minus Hub and Path:
| Group | Methods |
|---|---|
| Write | Write |
| Runs | Runs · Run · ChildRuns · Search · ResolvePublicID |
| One run’s records | Events · Transcript · TranscriptBatches · Compactions · Requests · Prompt · Tools · Catalogs |
| Spans and logs | RunSpans · RunTreeSpans · Trace · Traces · OtherLogs · CountLogs |
| Sessions | Sessions · Session · SessionEvents (0.18.0) |
| Aggregates | Stats · ErrorCounts (0.19.0) |
| Experiments and manifests | SaveExperiment · Experiments · Experiment · PutManifest · Manifest |
| Playground commands | PutCommand · Commands · PutRoute · Route · PutBreakpoints · Breakpoints · PutRuntime · Runtimes · DeleteRuntime (0.19.0) · PutBreakpointSet · BreakpointSet (0.20.0) · PruneCommands |
| Deletion and lifecycle | DeleteRun · DeleteSession · Sweep · Vacuum · Close |
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
Section titled “Open it from the weft command”weft studio, weft dev and weft vacuum take the database as a URL in --db:
weft studio # $WEFT_DB, else ./.weft/weft.dbweft studio --db sqlite://weft.db # relative to the working directoryweft studio --db sqlite:///var/lib/weft/weft.db # absolute: three slashesweft studio --db clickhouse://default:pass@ch.internal:9000/weftsqlite:// 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 lists every flag.
Migrations
Section titled “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 or 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) |
| — | 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
Section titled “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
Section titled “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) |
| 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
Section titled “Changes by release that affect stored data”- Positions. An
eventrecord with noweft.event.posis stored at position -1 on both backends, never at 0 where it collided withrun_start; adeltawithout one counts as position 0 (0.15.0). - Command pruning.
PruneCommandsdeletes on SQLite in passes ofobsdb.SweepBatchterminal commands, each its own transaction. On ClickHouse it deletes exactly the row versions each rule selected, so aPutCommand,PutRouteorPutRuntimelanding 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 byTestSessionBeyondNewestPage). - 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.
SaveExperimentsurfaces every read error exceptErrNotFound, so a transient failure no longer resetsCreated(TestExperimentCreatedSurvivesUpdate); migration 0002’s engine shape is pinned offline byTestSpecExperimentsEnginePresent(obsdb/clickhouse 0.1.1). - ClickHouse 0.2.0.
ResolvePublicIDorders by (turn, started) as SQLite does; TTL windows round up to whole seconds; detail reads narrowFINALby primary key; calls racingClosereturnErrClosed. - The first releases (0.7.0).
obsdb/sqlitearrived with an idempotent one-transactionWrite(INSERT OR IGNOREon (run, kind, pos) and (trace, span)), deltas counted and never stored, heartbeats moving last-seen only, and a reordered batch’s provisional start corrected whenrun_startlands.obsdb/clickhousearrived with the collector-compatible tables, theweft_recordsandweft_runsviews,KeepDeltasintoweft_deltas, and the conformance table gated onWEFT_CLICKHOUSE_DSN.
Complete example
Section titled “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:
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)}View on GitHub · run it from docs-site/examples:
go run ./productiongo test ./production== storage backendsfile: studio.db absolute: truerefused: 415 X-Request-Id: deploy-check-1log: WARN "studio: ingest batch refused" request_id=deploy-check-1 status=415 code=unsupportedmeta db: sqlite studio.dbmeta ingest: accepted>0: true refused: 1 last_error: 415 unsupported: Content-Type must be application/x-protobuf or application/jsonrun: succeeded deltas counted: 1 deltas stored: 1== clickhouseopen failed: clickhouse: pingdeltas 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. TestOperations in main_test.go pins this output.
Best practices & gotchas
Section titled “Best practices & gotchas”- Pass the pipeline’s handle to an embedded Studio. A second
sqlite.Openof 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
OpenwithErrNewerSchemaon 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
TTLchanges nothing, soweft studionever resets them; but an Open withTTLrewrites both windows, so every process that passes it must pass the same two values. (Source:clickhouse.TTLgodoc;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
KeepDeltasfor debugging. With it, every streamed fragment becomes a stored row; without it, deltas are counted and dropped by design. (Source:sqlite.KeepDeltasgodoc;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
Section titled “See also”- Keep and delete recorded runs
- Operate Studio: logs, restarts and the runtime link
- Deploy an agent service with a hosted Studio
- Store sessions
Symbols used: sqlite.Open · sqlite.KeepDeltas · sqlite.DB · sqlite.ErrNewerSchema · clickhouse.Open · clickhouse.TTL · clickhouse.KeepDeltas · clickhouse.DB · clickhouse.ErrNewerSchema · obsdb.DB · obsdb.ErrClosed · obsdb.SweepBatch · obsdbtest.Run · studio.DB · studio.Open · studio.New · otel.LocalDB