Skip to content

Choose the observability database: SQLite or ClickHouse

View as Markdown

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:

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

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.

AspectSQLiteClickHouse
WhereOne file (plus -wal and -shm beside it)A database on a ClickHouse server, named by the DSN’s path
WritersOne writer connection per process; other processes wait on the 30 s busy timeoutAny number, through the driver’s pool and async inserts
Live laneIn process: the handle’s Hub() publishes every write, which is what makes setup A liveNone in the handle: Studio makes an in-process hub its OTLP ingest feeds
ExpiryNone: studio.Retain and weft vacuumTable TTLs (content 30 days, spans and runs 90 days), plus Retain
Opened byotel.Local(path), studio.Open(path), weft studio (default), weft devYour server’s clickhouse.Open(dsn), weft studio --db clickhouse://…
Shared withthread/sqlite’s sessions may live in the same fileRows 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.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 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(), 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() 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).
  • 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).
  • 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 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.

GroupMethods
Write and liveWrite · Hub
RunsRuns · Run · ChildRuns · Search · ResolvePublicID
One run’s recordsEvents · Transcript · TranscriptBatches · Compactions · Requests · Prompt · Tools · Catalogs
Spans and logsRunSpans · RunTreeSpans · Trace · Traces · OtherLogs · CountLogs
SessionsSessions · Session · SessionEvents (0.18.0)
AggregatesStats · ErrorCounts (0.19.0)
Experiments and manifestsSaveExperiment · 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 lifecycleDeleteRun · 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.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:

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

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).

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.

TableEngine and keyWhat it holds
otel_traces, otel_logsThe OTel Collector exporter’s columns, pinned at v0.162.0Every span and log record. The weft identity is materialized beside them with bloom skip indexes on SessionId, PublicId, Agent and TraceId
weft_recordsReplacingMergeTree(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_runsAggregatingMergeTree ORDER BY RunIdOne 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_deltasReplacingMergeTree on (RunId, Pos)Delta rows, only with KeepDeltas(); nothing else feeds it
obsdb_migrationsMergeTree ORDER BY versionThe 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:

Terminal window
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 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 same groups as SQLite’s, minus Hub and Path:

GroupMethods
WriteWrite
RunsRuns · Run · ChildRuns · Search · ResolvePublicID
One run’s recordsEvents · Transcript · TranscriptBatches · Compactions · Requests · Prompt · Tools · Catalogs
Spans and logsRunSpans · RunTreeSpans · Trace · Traces · OtherLogs · CountLogs
SessionsSessions · Session · SessionEvents (0.18.0)
AggregatesStats · ErrorCounts (0.19.0)
Experiments and manifestsSaveExperiment · Experiments · Experiment · PutManifest · Manifest
Playground commandsPutCommand · Commands · PutRoute · Route · PutBreakpoints · Breakpoints · PutRuntime · Runtimes · DeleteRuntime (0.19.0) · PutBreakpointSet · BreakpointSet (0.20.0) · PruneCommands
Deletion and lifecycleDeleteRun · 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.

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

Terminal window
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 lists every flag.

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:

SQLiteClickHouseWhat it adds
00010001The schema: spans, records, app logs, runs (SQLite); the collector-compatible tables and the weft views (ClickHouse)
00020002The experiments table behind SaveExperiment, Experiments and Experiment (ClickHouse as a ReplacingMergeTree(InsertTime))
—0003Spans 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
00060007An 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
00070008The playground’s command store: commands, run_routes, breakpoints, runtimes (on ClickHouse ReplacingMergeTree tables read FINAL)
00090010root_ended: a run whose root span is stored reads finished, backfilled from the spans already stored
00140016The 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
00210023A run’s caller link (caller_run_id, caller_call_id) and a session’s lineage. On ClickHouse a background mutation backfills it
00220025session_events (weft_session_events on ClickHouse): every thread record and compaction marker indexed by session, backfilled from the records already stored
—0024, 0027The run views restated so a summarizer’s chat span feeds no column of the run row
—0026idx_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
002400280.19.0: an experiment’s pass predicate, stored verbatim. No backfill: an experiment saved before it reads ""
—0029, 0030, 00330.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
002600310.20.0: stock GenAI traces re-derived by the new derived-run rule (below)
—00320.20.0: a remote caller link (weft.caller.remote) is not a run’s caller; SQLite derives this in Go and needs no migration

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.

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.

LevelMessageAttributesWhen
INFOweft/obsdb/sqlite: migration 0023 backfills the span_stats rollup; Open waits for itspansSQLite 0023 on a file that holds spans; a new file logs nothing
INFOweft/obsdb/sqlite: migration 0023 backfill donespans, durationThe backfill finished
INFOweft/obsdb/sqlite: migrating: re-deriving N stock traces (SQLite 0026); Open waits for ittracesSQLite 0026 found stock traces to re-derive (above)
INFOweft/obsdb/sqlite: migration 0026 re-derive donetraces, durationThe re-derive finished
INFOweft/obsdb/clickhouse: migrating: re-deriving N stock traces (ClickHouse 0031); Open waits for ittracesClickHouse 0031 found stock traces to re-derive
INFOweft/obsdb/clickhouse: migration 0031 re-derive donedurationThe re-derive finished
WARNweft/obsdb/sqlite: span_stats rollup write failed; the span is stored, the stats skip it (further failures are not logged)trace_id, span_id, errorA 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 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.

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:

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)
}

View production/storage.go on GitHub

View on GitHub · run it from docs-site/examples:

Terminal window
go run ./production
go test ./production
== 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. TestOperations in main_test.go pins this output.

  • 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)

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