obsdb: reading the observability database from Go
Package obsdb is the observability database: what the local sink writes and Studio reads. obsdb.DB is the interface every backend implements, obsdb/sqlite by default and obsdb/clickhouse hosted. A Go reader calls it to list runs and sessions, page a run’s events, read its transcript, request records and spans, and delete or sweep runs. This page lists the interface, its optional capabilities, every query, page and row type, the status words, the caps and the errors; obsdb record and span types lists the stored records themselves.
Open a SQLite file, write one run’s records the way otel.Local does, and read it back, in the obsdb example’s main.go:
db, err := sqlite.Open(filepath.Join(dir, "weft.db"))if err != nil { return err}defer db.Close()
t0 := time.Now().UTC()if err := db.Write(ctx, obsdb.Batch{Records: []obsdb.Record{ record(t0, "event", "run_start", 0, `{"type":"run_start","id":"run_1","agent":"support-bot"}`), record(t0, "messages", "", 0, `[{"role":"user","content":[{"type":"text","text":"Where is order 1234?"}]}]`), record(t0.Add(time.Second), "messages", "", 1, `[{"role":"assistant","content":[{"type":"text","text":"It ships on Friday."}]}]`), record(t0.Add(time.Second), "event", "run_finish", 1, `{"type":"run_finish","steps":1,"usage":{"input_tokens":12,"output_tokens":6}}`),}}); err != nil { return err}
page, err := db.Runs(ctx, obsdb.RunQuery{Agent: "support-bot", Status: obsdb.StatusSucceeded})if err != nil { return err}for _, r := range page.Runs { fmt.Fprintf(w, "run %s %s steps=%d tokens=%d prompt=%q\n", r.ID, r.Status, r.Steps, r.Usage.InputTokens+r.Usage.OutputTokens, r.PromptPreview)}
events, err := db.Events(ctx, "run_1", -1, 0) // after -1: from position 0if err != nil { return err}fmt.Fprintf(w, "events: %d done=%v gaps=%v\n", len(events.Events), events.Done, events.Gaps)
if s, ok := db.(obsdb.Searcher); ok { found, err := s.Search(ctx, obsdb.SearchQuery{Text: "friday"}) if err != nil { return err } fmt.Fprintf(w, "search friday: %d run(s)\n", found.Total)}
_, err = db.Run(ctx, "run_2")fmt.Fprintln(w, "run_2 not found:", errors.Is(err, obsdb.ErrNotFound))Write is the only write a pipeline makes. Every read takes a query value whose zero value is the common case: RunQuery{} lists top-level runs, newest first, 50 at a time. Events takes after exclusive, so -1 reads from the run_start at position 0. Search is an optional interface, asserted with db.(obsdb.Searcher). An unknown id is ErrNotFound.
How the package fits
Section titled “How the package fits”The model is OTLP-shaped: spans and log records, resource included, so a stock OpenTelemetry pipeline’s data and weft’s own land in the same tables. Weft identity (the run, session and public id chain) is derived from attributes, never parsed out of ids. Status is derived at read time from a four-row table, never stored. Deltas travel but are not stored, and heartbeats only move a run’s last-seen: both rules are Write’s, shared by every backend.
| Part | What it is | Where |
|---|---|---|
obsdb.DB | The backend interface: one write, the reads, deletion and retention | The DB interface |
| Optional interfaces | Searcher, TreeReader, SessionEventReader, Aggregator, CommandStore, BreakpointProvenanceStore, ManifestStore: a backend implements them beside DB | Optional capabilities |
| The hub | The live lane: every sqlite Write publishes its frames before it returns; for another backend Studio feeds its own hub from ingest | Hub, Selector |
obsdb/sqlite, obsdb/clickhouse | The two first-party backends | Open a backend |
obsdb/obsdbtest | The conformance table every backend runs | Conformance |
Within weft, otel.Local writes through a DB, otel.LocalDB returns the installed pipeline’s handle, and studio.DB serves Studio over one. The package’s own history:
| Release | What arrived |
|---|---|
| 0.7.0 | obsdb itself: the OTLP-shaped model (Span, Record, Batch), the derived identity, the DB interface, the four-row status table and the hub |
| 0.10.0 | The readers the request-record, compaction and log views use: the compaction constants, HoleCause, LogSkew, ParseSeverity, SeverityText, the RequestBody parts |
| 0.10.0 | InstructionsHash, CatalogHash and RequestCount on RunRow, and so on RunDetail, which embeds it |
The DB interface
Section titled “The DB interface”obsdb.DB must be safe for concurrent use: writers are rare (the local sink’s synchronous processors), readers many (Studio). Methods by group; ErrNotFound is the answer for an id the database does not hold unless the row says otherwise.
| Method | Returns | Meaning |
|---|---|---|
Write(ctx, Batch) | error | Stores one batch, idempotent on (run, record kind, position) and (trace, span): a retried transport’s duplicate is a no-op. Deltas are counted, never stored; heartbeats are never stored and only move last-seen |
Runs(ctx, RunQuery) | RunPage | Lists runs: RunQuery filters, newest Started first |
Run(ctx, id) | RunDetail | One run with its subagent children |
Events(ctx, runID, after, limit) | EventPage | Pages a run’s durable events in position order. after is exclusive: pass -1 to start (0 would skip the run_start), then NextAfter. limit 0 is 100, at most 1,000 |
Transcript(ctx, runID) | []json.RawMessage | The messages bodies in index order, one per growth messages record, deduplicated so they concatenate to the transcript the run held. A compaction view is never part of it |
TranscriptBatches(ctx, runID) | []TranscriptBatch | Transcript with each record’s index, step (-1 when absent) and input flag: TranscriptBatch |
Compactions(ctx, runID) | []Compaction | Every run-scope view in index order, then the session markers thread filed under the run. Empty for a run that never compacted; an unknown weft.messages.reason is an error: Compaction |
Requests(ctx, runID, RequestQuery) | []RequestRecord | Pages the request records in index order, one per model-call attempt (RequestQuery, RequestRecord) |
Prompt(ctx, runID, hash) | PromptRecord | The run’s prompt record of one system hash. Missing: ErrNotFound, as a *HoleError when the reason is known (not_recorded, stripped, gap) |
Tools(ctx, runID, hash) | ToolsRecord | The run’s tools record of one catalog hash, with Prompt’s errors |
Catalogs(ctx, runID) | []ToolsRecord | Every tools record of the run, one per hash, in index order; a content-off run has none |
RunSpans(ctx, runID) | []Span | The run’s own spans |
OtherLogs(ctx, runID, LogQuery) | LogPage | Pages the run’s app log records, attributed through the spans they were emitted under, in time order. Empty Logs (not nil) for a run with none; a *HoleError (Kind logs, not_recorded) for a finished run with no span to attribute them through |
CountLogs(ctx, runID, minSeverity) | LogCounts | Counts app log records at or above an OTLP severity number (13 is WARN) in one scan, without paging bodies; capped past MaxLogCandidates |
Trace(ctx, traceID) | []Span | Every stored span of a trace. An unknown trace is empty, not an error: a trace is only the spans that arrived |
Traces(ctx, TraceQuery) | TracePage | Lists traces, weft and non-weft, one row per trace id, newest first; a trace whose root never arrived has Root nil |
Sessions(ctx, SessionQuery) | SessionPage | Lists sessions, newest activity first |
Session(ctx, id) | SessionDetail | One session with every turn |
ResolvePublicID(ctx, publicID) | sessionID string | The session a public id names |
SaveExperiment(ctx, Experiment) | error | Upserts a saved playground experiment by ID (Experiment) |
Experiments(ctx) | []Experiment | Every saved experiment, newest update first |
Experiment(ctx, id) | Experiment | One saved experiment |
DeleteRun(ctx, id) | error | Removes a run and every run whose parent chain reaches it, with their records, search rows, spans and the app log records under those spans, plus the derived run of a stock agent under the run’s tool. A run still being written is deleted as it stands |
DeleteSession(ctx, id) | error | DeleteRun for every run carrying the weft.session.id. The app’s own conversation store is never touched |
Sweep(ctx, before) | int, error | Deletes the runs last seen before the cutoff that are not running (interrupted counts as not running), with their not-running children, in passes of SweepBatch roots; returns how many runs it deleted |
Vacuum(ctx) | error | Gives freed space back: VACUUM on SQLite, OPTIMIZE TABLE … FINAL on the mutated ClickHouse tables (heavy on a large database) |
Close() | error | Closes the handle; every later call returns ErrClosed |
The four deletion methods touch the observability tables alone: never another module’s tables sharing the file (thread’s sessions in one SQLite file stay byte-identical), never the experiments table, and never a CommandStore’s or ManifestStore’s rows. Keep and delete recorded runs covers retention as an operator runs it.
Changes to the interface’s behaviour by release, for a reader of an older database:
| Release | Area | Change |
|---|---|---|
| 0.18.0 | Sessions | A session row carries its turn facts, counted in SQL on both backends: Pending, FailedTurns, EndedTurns, CancelledTurns, Resumes, Outcomes and ForkedFrom (SessionTurnFacts). SessionQuery gained the Awaiting, Failed, Compacted, Lineage, Status and Since filters |
| 0.18.0 | Caller links | RunRow.CallerRunID and CallerCallID link a run to the tool call that started it without a Subagent. RunQuery.CallerRunID and SessionIDs, SessionQuery.Parents, and the session lineage fields arrived |
| 0.18.0 | Session pages | RunQuery.TurnBelow, TurnAbove and Oldest read a turn’s neighbours in O(1) rows; SessionQuery.IDs reads a known set of sessions |
| 0.14.0 | Deletion | SpanLink and SpanKey name the one rule both backends delete spans and app log lines by: a run’s own spans and the non-weft spans below them, the rule its logs page attributes lines by |
| 0.14.0 | Conformance | The table gained DeleteRun, DeleteSession, Sweep and Vacuum |
| obsdb 0.2.0 (0.8.0) | OTLP decode | FromOTLPTraces and FromOTLPLogs keep real OTLP/JSON senders’ hex ids, skip nil elements at any layer and render structured log bodies as JSON |
| obsdb 0.2.0 (0.8.0) | Hub | A resume cursor from a previous process no longer mutes the subscription; an overflow drop releases its watcher goroutine |
| obsdb 0.2.0 (0.8.0) | Transcript | DedupTranscript arrived: a resume’s rebuilt tool message supersedes the partial one; every backend’s Transcript reads through it |
| obsdb 0.2.0 (0.8.0) | Paging | MaxGaps (1,000) and MaxTies (500) arrived, with the exact cursors RunQuery.BeforeID / RunPage.NextBeforeID and SessionQuery.BeforeID / SessionPage.NextBeforeID |
| obsdb 0.2.0 (0.8.0) | Paging | SessionPage.Total no longer shrinks with the cursor |
| obsdb/sqlite (0.8.0) | Events | Events never reports Done with stored events missing; gap detection no longer scans the run on every page |
| obsdb/sqlite (0.8.0) | Write | A NaN or Inf attribute no longer fails the batch; zero timestamps are stored as unknown and records fall back to Observed; a run’s Started is the earliest time seen of any record or span |
| obsdb/sqlite (0.8.0) | Sessions | Session returns every turn (a 500 cap had dropped the newest); paging never skips rows tied on the cursor time; the status filter and the row’s status use one clock |
| obsdb/clickhouse 0.2.0 (0.8.0) | Filters | Runs and Sessions read each run’s merged row, so subagent runs no longer surface as top-level runs or session turns before a merge |
| obsdb/clickhouse 0.2.0 (0.8.0) | Paging | Tied rows ride along, bounded by MaxTies; the exact BeforeID cursor is honoured; Total is the whole match |
| obsdb/clickhouse 0.2.0 (0.8.0) | Events, sessions | Events reads the terminal flags before the events and caps Gaps; Session returns every turn without exceeding max_query_size |
| obsdb/clickhouse 0.2.0 (0.8.0) | Write | Non-finite attributes no longer cost a span its typed attributes; a zero record time falls back to Observed; one batch may span any number of day partitions |
Optional capabilities
Section titled “Optional capabilities”A backend implements these beside DB. Both first-party backends implement all seven, and the conformance table holds them to the same answers. Its cases for Searcher, TreeReader, SessionEventReader, CommandStore and ManifestStore skip on a backend that lacks one. Its Stats and ErrorCounts cases fail a backend without Aggregator.
| Interface | Methods | Without it |
|---|---|---|
obsdb.Searcher | Search(ctx, SearchQuery) (RunPage, error): runs found by what they said and did, sorted as asked, Total the whole match; NextBefore stays nil, a search pages by Offset | Studio leaves its search capability off and says why |
obsdb.TreeReader | RunTreeSpans(ctx, TreeQuery) (RunTree, error): the spans of a run and every run descending from it, found from the run rows and read by run id (a derived run is cut from its trace); at most TreeSpanCap. ChildRuns(ctx, parentIDs) (map[string][]RunRow, error): the direct children of many runs in one read, each parent’s by Started then id, a childless parent absent; past ChildRunsCap rows, ErrChildRunsCapped | Studio leaves spans_tree off and reads each run’s children one run at a time |
obsdb.SessionEventReader | SessionEvents(ctx, SessionEventQuery) (SessionEventPage, error): a session’s state log, its thread records and compaction markers, by record time, then run id, kind and body. An unknown session is an empty page, not an error (Session events). Since 0.18.0 | Studio leaves its timeline capability off; GET /api/sessions/{id}/timeline and /entries answer 501 |
obsdb.Aggregator | Stats(ctx, StatsQuery) (StatsPage, error): numbers across runs, grouped (Aggregates). ErrorCounts(ctx, SearchQuery) ([]ErrorCount, bool, error): the distinct error texts of the runs a search matches, most frequent first, at most MaxErrorTexts; the bool says capped. Since 0.19.0 | Studio leaves its stats capability off: GET /api/stats and the error_class facet and filter are off |
obsdb.CommandStore | The playground link’s commands, run routes, breakpoints and runtimes | Studio’s runtime server keeps them in memory only |
obsdb.BreakpointProvenanceStore | A breakpoint set with when and from which surface it was set. Since 0.20.0 | Studio stores the tools alone, through CommandStore |
obsdb.ManifestStore | Each agent’s configuration by its manifest hash | Studio leaves its manifests capability off: a run’s ManifestHash resolves to no stored configuration |
On SQLite, Search reads an FTS5 trigram index maintained on write; on ClickHouse, case-insensitive substring scans over the stored records. The live lane is a separate value, not an interface on DB: sqlite.DB exposes Hub(), and Studio builds an obsdb.NewHub fed by ingest for a backend without one.
Open a backend
Section titled “Open a backend”Both backends return an obsdb.DB whose concrete type also implements the four optional interfaces. Choose the observability database covers paths, DSNs, pragmas, TTLs and migrations.
| Call | Options | Notes |
|---|---|---|
sqlite.Open(path, opts...) | sqlite.KeepDeltas() | One file on the CGO-free modernc driver; :memory: for tests. Open returns an obsdb.DB; assert it to *sqlite.DB to reach Hub() (every Write publishes to it before returning) and Path() (the absolute file path; "" for :memory:) |
clickhouse.Open(dsn, opts...) | clickhouse.KeepDeltas(), clickhouse.TTL(content, meta) | The hosted backend, column-compatible with the OTel Collector’s ClickHouse exporter; the concrete type is *clickhouse.DB; no hub. Without TTL, DefaultContentTTL (30 days: content-bearing rows) and DefaultMetaTTL (90 days: spans and runs) are the retention defaults |
Options are values of each package’s own option type, sqlite.Option and clickhouse.Option. Each Open fails with its own ErrNewerSchema on a database migrated by a newer weft (Errors). Two godoc examples: sqlite ExampleDB_Path reads the file path through interface{ Path() string }, as Studio’s /api/meta does; clickhouse ExampleOpen opens a DSN with TTL(0, 7*24*time.Hour) (compiled, not run: it needs a server).
Queries
Section titled “Queries”Every list query’s zero value is the common case. A Limit of 0 means 50 and anything above 500 reads as 500. List cursors are the pair (time, id): pass the page’s NextBefore and NextBeforeID back as Before and BeforeID.
RunQuery
Section titled “RunQuery”obsdb.RunQuery selects runs for Runs. The zero value lists top-level runs, newest first, 50 at a time. Every set field must match.
| Field | Type | Meaning |
|---|---|---|
Agent | string | The run’s agent name |
SessionID | string | The weft.session.id its turns carry |
PublicID | string | The weft.public_id: a panel token’s scope |
ParentRunID | string | "" top-level runs only (no parent and no caller link), "*" every run, else the children of that run |
Status | Status | "" any; a word of StatusWords, the read-time parked and cancelled included |
Playground | *bool | nil any; true or false for playground runs or app runs |
ExperimentID | string | The runs of one saved experiment |
Meta | map[string]string | A subset match on the run’s metadata |
Before | time.Time | Cursor on Started; zero is the newest |
BeforeID | string | With Before, makes the cursor the pair (Started, ID), exact inside a group sharing one Started: pass RunPage.NextBeforeID |
LastSeenAfter | time.Time | Keeps runs last seen at or after it (zero no bound). A running run is always among them once the bound is older than InterruptedAfter |
Limit | int | Page size: 0 is 50, at most 500 |
StoppedBy | string | Exactly this RunRow.StoppedBy; a value ending in : is a prefix (has_tool_call: matches every has_tool_call:<tools>) |
ErrorType | string | Exactly this RunRow.ErrorType: max_steps, cancelled, model_error, … |
IDPrefix | string | Runs whose ID starts with it, byte for byte, no wildcard or case folding: a pasted short id |
Errs | []string | Runs whose Err is exactly one of these texts: nil any, an empty non-nil slice none. An error_class filter reads its texts through it (ErrorClassTexts) |
CallerRunID | string | Runs started from one of that run’s tool calls without being its Subagent children (RunRow.CallerRunID): its thread/pool child turns, its nested Generates. Pair it with ParentRunID "*", since such a run is top-level by ParentRunID |
SessionIDs | []string | Runs of any of these sessions; nil any. With SessionID, both apply |
TurnBelow, TurnAbove | int | Runs whose Turn is below or above it; 0 no bound. With SessionID, a turn’s neighbours: TurnBelow N with Limit 1 is the turn before N, and Total counts them |
Oldest | bool | Turns the list around: oldest first, by start then id ascending. Before and BeforeID then read the runs after that one. Runs only: Search keeps its own sort |
SearchQuery
Section titled “SearchQuery”obsdb.SearchQuery selects runs for Searcher.Search. Its embedded RunQuery carries the same filters Runs reads, so a scope applied to one applies to the other; Before and BeforeID are not read, and Limit is the page size.
| Field | Type | Meaning |
|---|---|---|
RunQuery | RunQuery | The list filters, as above |
Text | string | Search terms in ParseSearch’s grammar. A run matches when every term is a case-insensitive substring of its prompt (the turn’s own), its answer (the last assistant message with text), its error, or a tool name it called; each term may match a different field. A content-off run has no prompt or answer: only its error and tool names can match |
Tool | string | The exact name of a tool the run called |
Model | string | The exact model name on the run row |
Error | string | A case-insensitive substring of the run’s error |
Since, Until | time.Time | Started ≥ Since, Started < Until; zero is open |
MinTokens | int64 | Input plus output tokens at least this; 0 any |
Sort | SearchSort | The order; "" is SortStarted |
Offset | int | Rows to skip in that order, at most MaxSearchOffset |
obsdb.SearchSort is a search’s order. Every order breaks ties by Started, then run id, both descending, so a result is total and stable.
| Constant | Value | Order |
|---|---|---|
SortStarted | started | Newest first (the default) |
SortDuration | duration | Longest first: Finished (or LastSeen while unfinished) minus Started |
SortTokens | tokens | Most input plus output tokens first |
The search grammar and its bounds:
| Name | Value | Meaning |
|---|---|---|
ParseSearch(text) | []string, error | Splits text into terms: whitespace separates them; a double-quoted span is one term with its spaces (a phrase); an unclosed quote runs to the end; an empty quoted span is no term. No stemming and no operators: AND, OR and * are ordinary text |
MaxSearchTerms | 16 | More terms is ErrInvalidSearch |
MaxSearchTermBytes | 256 | A longer term is ErrInvalidSearch; so is a Tool, Model or Error filter longer than this |
MaxSearchOffset | 100,000 | The largest SearchQuery.Offset; a negative offset is refused too |
CheckSearch(q) | []string, error | The checks every backend’s Search runs before reading: an unknown Sort, an Offset outside 0–MaxSearchOffset, a negative MinTokens or a filter over MaxSearchTermBytes is ErrInvalidSearch; else ParseSearch(q.Text) |
PromptPreviewRunes | 200 | The cut of RunRow.PromptPreview |
SessionQuery
Section titled “SessionQuery”obsdb.SessionQuery selects sessions. The zero value lists them newest activity first, 50 at a time.
| Field | Type | Meaning |
|---|---|---|
Agent | string | The session’s agent |
PublicID | string | Scopes the runs a session is grouped over, before the grouping: the session is listed when one of its turns carries the public id, and its turns, usage, times, status, order, Total and cursor are those turns’ alone |
Q | string | Text: every whitespace-separated term a case-insensitive substring of the title, the first turn’s whole prompt, the id, the public id or the agent (terms AND, fields OR). ASCII folding on SQLite, Unicode on ClickHouse |
IDPrefix | string | Since 0.20.0, sessions whose id starts with it, byte for byte: the ⌘K palette’s lookup of a pasted short id |
Meta | map[string]string | Scopes the turns a session is grouped over to those carrying every pair, as PublicID does (tag.<k>=<v> on /api/sessions). Since 0.20.0 a session whose turns carry the tags only partly is listed, counted and summed from the tagged turns alone |
Parents | []string | Sessions delegated by any of these sessions (SessionRow.ParentSession): one read lists a level of a delegation tree. Empty any |
IDs | []string | Sessions whose id is one of these. Every aggregate is still over all of each one’s turns. Empty any |
Awaiting | bool | Sessions whose newest turn is an open park (SessionRow.Pending > 0) |
Failed | bool | Sessions with a failed turn (SessionRow.FailedTurns > 0). A busy-ended or cancelled turn is no failure |
Compacted | bool | Sessions thread compacted: a compaction marker in the session events index |
Status | Status | Sessions whose newest turn’s outcome (OutcomeOf) is this word: running, succeeded, failed or interrupted. A cancelled or busy-ended turn is not failed, a parked one not succeeded; parked and cancelled keep none |
Lineage | string | LineageChild (child) the delegated sessions, LineageFork (fork) the forked ones; any other value keeps none |
Since | time.Time | Sessions last seen at or after it; zero any |
Before | time.Time | Cursor on LastSeen; zero is the newest |
BeforeID | string | With Before, the (LastSeen, ID) pair |
Limit | int | 0 is 50, at most 500 |
TraceQuery
Section titled “TraceQuery”obsdb.TraceQuery selects traces for Traces. The zero value lists every trace, newest first, 50 at a time. A trace’s time is its Start, the earliest start of its spans.
| Field | Type | Meaning |
|---|---|---|
Service | string | Traces holding at least one span whose resource service name is exactly this |
PublicID | string | Traces every span of which carries this weft.public_id, the rule a panel token’s trace read applies; a non-weft span or another public id’s run excludes the trace |
Meta | map[string]string | Since 0.20.0, traces holding, for each pair, a span whose attributes carry it: tag.<k>=<v> and flow= on /api/traces |
ScopeMeta | map[string]string | Since 0.20.0, traces every span of which carries each pair: PublicID’s rule for a tag-scoped panel token |
NotRun | bool | Since 0.20.0, the GenAI traces that make no run: a non-weft GenAI span, no span carrying weft.run.id, and no derived run of the trace. Studio’s “GenAI traces that are not runs” |
IDPrefix | string | Since 0.20.0, traces whose id starts with it, byte for byte |
Since | time.Time | Start at or after; zero no bound |
Until | time.Time | Start before; zero no bound |
Before | time.Time | Cursor on Start; zero is the newest |
BeforeID | string | With Before, the (Start, TraceID) pair: pass TracePage.NextBeforeID |
Limit | int | 0 is 50, at most 500 |
TreeQuery, RequestQuery, LogQuery, Selector
Section titled “TreeQuery, RequestQuery, LogQuery, Selector”obsdb.TreeQuery names the run tree RunTreeSpans reads.
| Field | Meaning |
|---|---|
RunID | The tree’s root run |
PublicID | When set, scopes the tree to one public id: the root’s spans stay; a descendant stays when its row and each of its spans carry the public id and its parent stays. Any other descendant is left out with its subtree, counted in RunTree.HiddenCount, never named. The cap counts visible spans only |
Meta | Since 0.20.0, scopes the tree to the runs carrying every pair by the same rule: a descendant stays when its row’s metadata and each of its spans carry them, and its parent stays. With PublicID, both apply |
Scoped() | Reports whether PublicID or Meta is set |
obsdb.RequestQuery selects a run’s request records for Requests, in request-index order. The zero value reads every step from index 0, 100 at a time.
| Field or method | Meaning |
|---|---|
Step | *int: when set, only that step’s attempts |
From | The first index read, inclusive: pass the last returned Index + 1 to continue |
Limit | 0 is 100, at most 1,000. A page shorter than PageLimit() is the last |
PageLimit() | The normalized limit: 100 for 0 or negative, 1,000 at most |
obsdb.LogQuery selects a run’s app log records for OtherLogs. The zero value reads every record from index 0, 100 at a time.
| Field or method | Meaning |
|---|---|
From | The first index read, inclusive: the last returned Index + 1 continues |
Limit | 0 is 100, at most 1,000 |
MinSeverity | When above 0, keeps records whose OTLP severity number is at least this. Index is the place among all of the run’s app logs, so a filtered page’s indexes skip and From continues a filtered walk alike |
PageLimit() | The normalized limit: 100 for 0 or negative, 1,000 at most |
obsdb.Selector scopes a Hub.Subscribe: exactly one field set. An empty or over-set selector matches nothing, never everything. Session- and public-id scopes span many runs, which is why the hub’s cursor is hub-wide.
| Field | Meaning |
|---|---|
RunID | One run’s frames |
SessionID | The frames of every run of one session |
PublicID | The frames of every run carrying one public id |
Agent | The frames of one agent’s runs |
All | Every run’s frames, subagent children included (Studio’s Live page). It must be asked for; set with any other field, the selector matches nothing |
Pages and rows
Section titled “Pages and rows”RunPage and RunDetail
Section titled “RunPage and RunDetail”obsdb.RunPage is one Runs result, newest Started first (ties by ID, descending). A page does not end inside a group of runs sharing one Started: the rest of the group rides along, up to MaxTies rows past Limit, so paging on Before alone skips nothing. A longer tie is cut there, and only the (Before, BeforeID) pair resumes inside it.
| Field | Meaning |
|---|---|
Runs | The page’s RunRows |
Total | The whole match, cursor aside |
NextBefore | *time.Time: the next page’s RunQuery.Before; nil on the last page |
NextBeforeID | The next page’s RunQuery.BeforeID; "" on the last page |
obsdb.RunDetail is Run’s answer.
| Field | Meaning |
|---|---|
RunRow | The run, embedded |
Children | Its subagent children: runs whose ParentRunID is this run, by Started |
RunRow
Section titled “RunRow”obsdb.RunRow is one run in a list or detail: the identity chain, timing, derived status and the usage and counts the list reads without a second query. Studio’s run JSON is this row in snake case; Studio HTTP API has the wire names.
| Field | Type | Meaning |
|---|---|---|
ID | string | The run id |
ParentRunID | string | The parent run of a subagent child (weft.parent.run.id); "" for a top-level run |
ParentCallID | string | The parent’s tool call that started this child |
TraceID | string | The trace of its root span |
Agent | string | The agent name (gen_ai.agent.name) |
Provider, Model | string | The model the run requested, from run_start or the root span |
ManifestHash | string | The weft.manifest.hash its spans carried; a ManifestStore resolves it |
WeftVersion | string | The weft version from the root span’s weft.version, else its resource’s; beside run_start’s value the larger string is kept |
Service | string | The root span’s resource service.name |
SessionID, PublicID | string | The weft.session.id and weft.public_id a thread turn carries |
Turn | int | The session turn number (weft.turn) |
Playground | bool | A playground run (weft.playground) |
ExperimentID | string | The weft.experiment.id of a playground experiment |
ForkedFrom | string | The run a playground run was forked from (weft.forked_from) |
ResumedFrom | string | The parked run this one resumes (weft.resumed_from, set by weft.ResumeOf) |
ResumedBy | string | On a parked run, the latest run (by start; a tie, the larger id) whose ResumedFrom names it, derived at read time on both backends; "" when none |
CallerRunID, CallerCallID | string | The run and tool call this run was started from when it is no Subagent child (weft.caller.run.id, weft.caller.call.id): a thread/pool child session’s turn, a Generate inside a handler. A link, never parenthood. "" when none, and on runs recorded before 0.18.0 |
Meta | map[string]string | The caller metadata its records and spans carried |
Started | time.Time | The earliest time seen of any record or span of the run |
Finished | *time.Time | When it finished; nil while it has not |
LastSeen | time.Time | The newest record or span time, heartbeats included: DeriveStatus’s clock |
Status | Status | The derived status: running, succeeded, failed or interrupted |
Err | string | A failed run’s error text |
Steps | int | Steps run, from run_finish or the root span’s weft.run.steps |
Pending | int | Calls awaiting a decision; above 0 on a succeeded run means parked at an approval |
StopReason | string | The root span’s weft.run.stop_reason (max_tokens when the last step hit the limit) |
Usage | core.Usage | Token usage, from run_finish or the root span’s gen_ai.usage.* |
EventCount, MessageCount | int64 | Event records and growth messages records stored |
DeltaCount | int64 | Deltas counted; deltas are never stored |
InstructionsHash | string | run_start’s weft.instructions.hash; "" on a run written before the request record |
CatalogHash | string | Request index 0’s weft.catalog.hash; "" when it offered no tools |
RequestCount | int64 | The request records’ high-water mark: max weft.request.index + 1 |
PromptPreview | string | The turn’s own prompt cut to PromptPreviewRunes runes; "" for a content-off run or one with no user text |
Derived | bool | A derived run built from stock GenAI spans, id otel-<trace id>-<root span id>: no events, transcript or request records, status succeeded or failed only |
RootEnded | bool | Its invoke_agent span is stored. A span is exported once it ended, so the run is over whatever records are missing |
Removed | bool | Since 0.20.0, on a live frame only: the row no longer exists, a derived run a later derivation folded into its enclosing agent’s run. An open list drops it; no store returns such a row |
FinishRecorded | bool | Its run_finish record is stored. Root ended without it: the record tail was lost, or there never were records |
Settling | bool | Root ended, not derived or failed, no run_finish, heard from within InterruptedAfter: records may still land, so no loss and no EventPage.Done yet. Read time, never stored (settling) |
StoppedBy | string | What ended the run in the manifest’s stop_when vocabulary (has_tool_call:<tools>, final_answer, parked, max_steps, canceled, …), from the root span or run_finish; "" when neither carried one |
CancelCause | string | A canceled run’s weft.cancel.cause (thread.interrupted, studio.cancel, deadline, a weft.CancelCause kind); "" otherwise |
EventsEmitted, MessagesEmitted | int64 | What the core says it emitted (weft.run.events, weft.run.messages on the root span); 0 when the root carried neither. Fewer stored than emitted is a loss |
ErrorType | string | A failed run’s kind, the root span’s error.type, with context errors read as cancelled (ErrorTypeCancelled); "" otherwise |
Problems | Problems | The run’s problem counters |
| Method | Returns | Meaning |
|---|---|---|
RequestsHole() | Hole | The badge for the run’s request records: derived for a derived run; "" while the run is settling; gap when its root is stored and says records were emitted but none is stored; not_recorded when its root is stored and says none were emitted, or when the run predates request records; "" otherwise |
RequestsHoleCause() | Hole, HoleCause | RequestsHole with its cause: stock_spans for a derived run, events_lost beside gap, no_logger for a run that exported spans only, the default for one written before the request record; none while settling |
The holes and causes are on Badges and holes.
Problems
Section titled “Problems”obsdb.Problems are a run’s problem counters: what went wrong inside a run that may still have succeeded. The span counters are folded at read time from tokens the writers derive at ingest, one per problem span keyed by span id, so a retried batch never counts a span twice.
| Field or method | Counts |
|---|---|
AttemptsRetried | Model attempts that failed and were followed by another attempt of the same call (mw.Retry’s retries, mw.Fallback’s fallen-back-from tries, an adapter’s reported retries). A call’s last attempt is never counted |
Fallbacks | Model calls a fallback layer answered: successful attempt spans with weft.attempt.layer fallback |
ToolErrors | Tool calls ending in an error result, except DENIED, RETRY and a context error; NO_SUCH_TOOL counts |
Denied | Refused tool calls: error.type DENIED (a policy middleware) plus the calls a resume denied, from weft.run.denied |
Truncated | Tool results the result cap cut (weft.tool.truncated_bytes > 0) |
Repaired | Tool calls whose arguments a model middleware repaired before the loop saw them (mw.RepairJSON): execute_tool spans with weft.tool.args_repaired true. Reported since 0.20.0; 0 for runs recorded before |
TapPanics | Observer panics the run contained (weft.tap.panics): the run is unchanged, an observer saw less |
MetadataDropped | Metadata pairs the core’s limits dropped (64 keys, 128-byte keys, 1 KiB values): the run document’s truncated hole, cause metadata_cap, not a problem badge |
LogWarn | App log records under the run’s spans at WARN (13–16). Read time, through CountLogs, on the run document only |
LogError | The same at ERROR or above (17–24) |
Any() | Reports whether any counter is non-zero |
EventPage
Section titled “EventPage”obsdb.EventPage is one page of a run’s durable events.
| Field | Meaning |
|---|---|
Events | The page’s PosEvents: body verbatim at its position |
NextAfter | *int64: the after for the next page |
Done | Every stored event was returned and the run is terminal: its run_finish is stored, its root ended with Error, or its root is stored and it was silent past InterruptedAfter. An interrupted run (no root, stale) is not Done here |
Gaps | Durable positions missing below the high-water mark (a lost batch, never a delta), lowest first, at most MaxGaps |
Sessions
Section titled “Sessions”obsdb.SessionPage is one Sessions result, paged as RunPage is: newest LastSeen first (ties by ID, descending), ties riding along up to MaxTies.
| Field | Meaning |
|---|---|
Sessions | The page’s SessionRows |
Total | The whole match, cursor aside |
NextBefore | The next SessionQuery.Before; nil on the last page |
NextBeforeID | The next SessionQuery.BeforeID; "" on the last page |
obsdb.SessionRow is one session: a GROUP BY over its own turns. A turn is a non-playground run carrying the session id whose id is <session>-t<turn>, or one linked to no run at all. A Subagent child is no turn; a thread/pool child session is a session of its own.
| Field | Meaning |
|---|---|
ID | The session id |
PublicID | Its public id |
Agent | Its agent |
Turns | How many turns |
FirstSeen, LastSeen | The time range its turns cover |
Status | The newest turn’s status |
Usage | The turns’ summed core.Usage |
Title | The newest turn’s non-empty weft.session.title (SessionTitleKey), a label that survives content-off; "" when none carried one |
FirstPrompt | The first turn’s PromptPreview; "" when that turn carried no content, never a later turn’s |
ContentOff | The first turn was recorded without content: events stored, no messages record, not derived, not running or settling. The list says “(content not captured)” for it |
SummarizerUsage | What thread’s summarizer calls cost the session: the chat spans marked weft.chat.role summarizer under its runs. Never part of Usage or any run’s usage; add it for the session’s whole cost |
SummarizerModels | SummarizerUsage split by provider and model, sorted, as ModelUsage parts; nil when nothing was summarized |
ParentSession, ParentCall, ParentRun | A delegated session’s lineage: the session that delegated it, the delegating tool call, and the parent’s run that call belonged to. "" for a session nothing delegated; ParentRun "" for a child submitted outside a run |
Pending | The newest turn’s pending calls when it is an open park, else 0: the session awaits a decision |
FailedTurns | The failed turns that were neither ended nor cancelled |
EndedTurns | The turns thread’s busy policy ended (Interrupt or Rollback; cancel cause BusyCancelCause) |
CancelledTurns | The other failed turns whose error type is cancelled: a caller’s cancel, a deadline, thread.closed, studio.cancel |
Resumes | The turns that resume a parked one; Turns − Resumes is the session’s exchanges |
Outcomes | The newest MaxOutcomes turns’ TurnOutcomes, oldest first |
ForkedFrom | The weft.session.forked_from its turns carry, <origin>#<entry>; "" for a session no fork made |
SessionTurnFacts sets the turn facts, Pending through ForkedFrom; every backend reads the same rule in SQL.
obsdb.TurnOutcome is one turn’s mark on a session’s outcome strip: a run’s derived status, with an open park told from a decided one and a busy-policy end from a failure.
| Name | Value | Meaning |
|---|---|---|
OutcomeSucceeded | succeeded | Succeeded, no pending calls |
OutcomeFailed | failed | Failed, not cancelled or ended |
OutcomeRunning | running | Still running |
OutcomeInterrupted | interrupted | The heartbeat went stale |
OutcomeCancelled | cancelled | Failed with error type cancelled |
OutcomeEnded | ended | thread’s busy policy cancelled it |
OutcomeParked | parked | Pending calls and no resumer |
OutcomeResumed | resumed | Pending calls a resumer decided |
OutcomeOf(r) | func | A turn’s outcome: a failed turn with BusyCancelCause is ended, else cancelled with that error type; a succeeded turn with pending calls is parked, or resumed once a run resumed it; else its status |
SessionTurnFacts(row, turns) | func | Sets a row’s turn facts from its turns, given in any order: read by turn, then start, then id, the newest last |
MaxOutcomes | 40 | Bounds SessionRow.Outcomes: a strip, not the turn list |
BusyCancelCause | thread.interrupted | The weft.cancel.cause of a turn the Interrupt or Rollback busy policy cancelled: EndedTurns, never FailedTurns |
SessionForkedFromKey | weft.session.forked_from | The run metadata a forked session’s turns carry: <origin session>#<entry> |
obsdb.ModelUsage is one model’s part of a summed usage: Provider and Model as a span named them ("" when it named none) and the Usage of those spans. SumModelUsage(parts) returns the parts’ total and the parts sorted by provider, then model (nil for none): the rule for SummarizerUsage and SummarizerModels.
obsdb.SessionDetail is Session’s answer.
| Field | Meaning |
|---|---|
SessionRow | The session, embedded |
Runs | Every turn: top-level runs by Turn, then Started; experiments excluded |
Session events
Section titled “Session events”A SessionEventReader reads a session’s state log from the session events index. thread’s records and its compaction markers feed the index at ingest when they carry a weft.session.id, a record filed under no run included. DeleteRun and Sweep remove a run’s events with the run; DeleteSession removes every event of the session.
obsdb.SessionEventQuery selects one session’s events.
| Field | Type | Meaning |
|---|---|---|
SessionID | string | The session |
PublicID | string | Keeps only the events carrying this weft.public_id, a panel token’s scope. The page, offsets and Total count those alone |
RunIDs | []string | Keeps only the events filed under one of these runs: one turn’s facts without paging the whole session. A runless record is under none |
Kinds | []string | Keeps only the events whose SessionEventKind is one of these (compaction, interrupt, rewind, …) |
Offset | int | Events to skip: the previous offset plus the page’s length continues |
Limit | int | 0 is 100, at most MaxSessionEventLimit; PageLimit() returns the normalized value |
obsdb.SessionEventPage is one answer: Events in order, and Total, every event the query selects.
obsdb.SessionEvent is one stored event, a thread record or a compaction marker as it arrived.
| Field | Meaning |
|---|---|
SessionID | The session |
RunID | The run it is filed under; "" for a record held at Close, a session-level fact |
Kind | Its weft.record: thread or compaction |
Name | Its event name, weft.thread.<kind> or weft.compaction, derived from the body’s kind when the record carried none |
PublicID | Its weft.public_id |
Content | Its weft.content |
Time | The record time |
Body | The record’s body, verbatim |
| Name | Value | Meaning |
|---|---|---|
SessionEventKind(e) | func | The short kind an event names: the name past weft.thread. for a thread record (approval.decision, receipt), compaction for a marker |
SessionEventName(kind, eventName, body) | func | An event’s name: the record’s own, else the one its kind and body imply. "" when the body names no kind |
IsSessionEventKind(kind) | func | Whether records of a weft.record kind feed the index: thread and compaction |
MaxSessionEventLimit | 1,000 | Bounds one SessionEvents page |
Traces
Section titled “Traces”obsdb.TracePage is one Traces result: newest Start first (ties by TraceID, descending), ties riding along up to MaxTies. A trace whose earlier span arrives between reads can be listed again on a later page, never skipped: dedupe by TraceID.
| Field | Meaning |
|---|---|
Traces | The page’s TraceRows |
Total | The whole match, cursor aside |
NextBefore | The next TraceQuery.Before; nil on the last page |
NextBeforeID | The next TraceQuery.BeforeID; "" on the last page |
obsdb.TraceRow is one trace in a list, computed from its spans.
| Field | Meaning |
|---|---|
TraceID | The trace id |
Root | *TraceRoot: the earliest span with no parent; nil when only child spans arrived (a hole the reader badges) |
Service | The root’s service, else the earliest span’s |
Start, End | The time range the spans cover |
SpanCount | Spans, each (trace, span) once |
Error | Whether any span ended with status error |
RunIDs | The distinct weft.run.id values, sorted (a subagent child shares its parent’s trace) |
obsdb.TraceRoot is a trace’s root span.
| Field | Meaning |
|---|---|
SpanID | Its span id |
Name | Its name |
Run trees
Section titled “Run trees”obsdb.RunTree is RunTreeSpans’ answer.
| Field | Meaning |
|---|---|
Spans | The tree’s TreeSpans in start order, then span id: at most TreeSpanCap, the first ones |
Truncated | The tree holds more than TreeSpanCap spans (or more than TreeRowCap runs) |
TraceTruncated | A derived run’s trace held more than TreeTraceCap spans; never set for a weft run |
Missing | Descendant runs known from their rows with no span in Spans and not running, by Started then id, at most TreeMissingCap. Empty when Truncated |
MissingCount | How many are missing, before the cap |
Hidden | TreeQuery’s scope (PublicID, Meta) left runs out |
HiddenCount | How many runs it left out, subtrees included; never their ids. 0 unless Hidden |
obsdb.TreeRun names one run of a tree.
| Field | Meaning |
|---|---|
ID | The run id |
ParentRunID | Its parent |
PublicID | Its weft.public_id, what a scoped reader filters by; "" when none |
Meta | Its row’s metadata, which TreeQuery.Meta reads (0.20.0) |
Started | RunRow.Started, the order Missing lists runs in |
Status | Its derived status with the read’s clock: a running run is never missing |
obsdb.TreeSpan is one span of a run tree. A reader draws one run’s spans under another’s by the key (RunID, SpanID).
| Field | Meaning |
|---|---|
Span | The Span, embedded |
RunID | The run it belongs to: its weft.run.id, or the derived run whose subtree holds it |
ParentRunID | That run’s parent; "" for the root run when it has none |
obsdb.StockRun is one run derived from stock spans (How Studio derives a run).
| Field | Meaning |
|---|---|
Row | Its RunRow: Derived true, the id otel-<trace id>-<root span id>, identity from the root, Steps the subtree’s chat spans, Usage the root’s gen_ai.usage.* or the chat spans’ sum, status succeeded or failed only |
Spans | Its subtree in start order, down to (not into) a nested root or a weft span, with weft.step.index and weft.tool.seq numbered by the reader |
obsdb.SpanLink is one stored span’s place in its trace, what the deletion walk reads; obsdb.SpanKey names one span.
| Type | Field | Meaning |
|---|---|---|
SpanLink | TraceID, SpanID | The span’s key |
SpanLink | ParentSpanID | Its parent span |
SpanLink | RunID | The weft.run.id it carries; "" for a non-weft span |
SpanKey | TraceID, SpanID | The trace and span ids |
obsdb.LogPage is one OtherLogs answer: the page and what the reader knows it could not show.
| Field | Meaning |
|---|---|
Logs | The page’s OtherLogs |
Partial | The run is running: a line under an in-flight span appears once the span arrives, so indexes are stable only once the run ended |
Gap | Lines in the run’s traces naming a span no stored span has (dropped or still open); not in Logs. 0 while Partial |
Truncated | The run’s traces hold more than MaxLogCandidates lines in its window (anyone’s: the cap applies before attribution) |
NoBridge | The root span is stored without weft.logs.bridged and no line is attributed: the pipeline had no slog bridge (otel.Slog). A hint, never a loss |
obsdb.LogCounts is one CountLogs answer.
| Field | Meaning |
|---|---|
Total | App log records at or above the asked severity |
Warn | Those at WARN (13–16) |
Error | Those at ERROR or above (17–24) |
Capped | The scan stopped at MaxLogCandidates: every count is a floor, shown as ”≥” |
| Name | Kind | Meaning |
|---|---|---|
ParseSeverity(s) | func | Reads a severity filter: a level name (trace, debug, info, warn or warning, error, fatal, any case: the range’s first number), a SeverityText spelling (WARN2), or a number 1–24; ok false otherwise |
SeverityText(n) | func | An OTLP severity number’s short name: TRACE … FATAL for each range’s first number, the ordinal after it for the rest (WARN2 is 14); "" for 0 and outside 1–24 |
LogSkew | const, 1 minute | Widens a run’s time window for the app-log scan (Started − LogSkew to LastSeen + LogSkew): clock skew between one run’s emitters |
MaxLogCandidates | const, 10,000 | Log records one OtherLogs read loads, chosen by time before attribution; more is LogPage.Truncated |
LogCandidates | func type | A backend’s half of OtherLogs: the non-weft records of the given traces within [from, to], the first limit in time order. obsdb’s shared reader does the attribution, dedup and paging |
Aggregates
Section titled “Aggregates”An Aggregator answers numbers across runs instead of one run’s records. SQLite reads them from its span_stats rollup, an index written at ingest beside every weft span (migration 0023). ClickHouse groups otel_traces and weft_runs natively. Studio’s GET /api/stats and the error_class facet read it.
obsdb.StatsQuery selects what Stats aggregates.
| Field | Type | Meaning |
|---|---|---|
RunQuery | RunQuery | The /api/runs filters, with the same meaning. Before, BeforeID, Limit and Oldest are not read. Playground nil counts both kinds |
By | StatsBy | What to group by |
Since, Until | time.Time | Both required, Since before Until. A run is in when Since ≤ Started < Until, and every span of it counts in its run’s bucket |
Buckets | int | The series’ bucket count: 0 is StatsBuckets, at most MaxStatsBuckets |
A derived run counts as a run with no calls: it has no weft spans to aggregate.
obsdb.StatsBy is what Stats groups by. RunLevel() is true for the run-level groupings, agent and error type, and false for the span-level ones.
| Constant | Value | Groups |
|---|---|---|
StatsByAgent | agent | Runs by agent name |
StatsByErrorType | error_type | Failed runs by ErrorType |
StatsByModel | model | Model calls (chat spans) by requested model name; two providers’ models of one name are one group |
StatsByTool | tool | Tool calls (execute_tool spans) by tool name |
StatsByStep | step | Model calls by step index. A replay’s calls key on the replay’s own step index, counted from its from_step as 0 |
obsdb.StatsPage is one Stats answer.
| Field | Meaning |
|---|---|
By | The grouping |
Since, Until | The window as read |
Buckets | The bucket count |
Bucket | Each bucket’s width, a time.Duration |
Groups | The StatsGroups: most runs first, then most calls, then by key (by step: step index ascending) |
GroupsCut | How many groups MaxStatsGroups cut |
obsdb.StatsGroup is one key’s numbers over the window. What a field counts depends on By.
| Field | Meaning |
|---|---|
Key | The group’s key |
Runs | The runs in the group; for model, tool and step, the distinct runs that made a call in it |
Failed | Those runs that failed |
Calls | Model calls (the group’s runs’ for agent and error type, its own for model and step), or tool calls for tool. A summarizer’s call and a call a resume denied are none |
FailedCalls | Those calls that failed. For a tool, the record contract’s tool_errors rule: DENIED, RETRY and context errors are no failure |
Retried | Model calls that took more than one attempt; 0 for tool |
Denials | The record contract’s problems.denied rule over the group’s spans; 0 for model and step |
Usage, Models | The model calls’ own usage, split by provider and model into ModelUsage parts. Never a run’s rolled-up total, so a subagent’s tokens are its own agent’s. Zero for tool |
Delegated, DelegatedModels, DelegatedRuns | By agent only: the model calls of the runs below the group’s runs whose agent is another, and how many such runs made a call. Under a scope, a descendant counts only when it and every run above it are in scope. Never sum these across groups |
Duration, TTFT | Percentiles in milliseconds: run durations for agent and error type, call durations for the others; TTFT the model calls’ weft.ttft_ms |
Series | The same sums per bucket, as StatsBuckets |
obsdb.StatsBucket is one bucket of a series: Runs, Failed, Calls, FailedCalls, InputTokens and OutputTokens over the runs that started in it.
obsdb.Percentiles holds P50 and P95 over N values: nearest-rank percentiles, the value at rank ⌈p·N/100⌉ of the sorted list. Both backends compute exactly this. N 0 means no value, and both percentiles are 0.
A backend builds its answer from GROUP BY rows with these:
| Name | Meaning |
|---|---|
StatsCell | One group’s sums in one bucket: Key, Bucket, Runs, Failed, Calls, FailedCalls, Retried, Denials, InputTokens, OutputTokens, CachedInputTokens, CacheWriteTokens, ReasoningTokens and DelegatedRuns (summed into the group, never a bucket). Bucket is clamped into the series |
StatsModelPart | One group’s usage on one provider and model: Key, an embedded ModelUsage, and Delegated for its subagents’ part |
StatsPercentiles | One group’s Duration and TTFT percentiles, by Key |
BuildStats(q, cells, models, pcts) | Sums the cells per key and bucket, attaches the model parts and percentiles, then sorts and cuts the groups. A key in models or percentiles alone still gets a group |
CheckStats(q) | Validates a query (a known By, a window, a bucket count in bounds) and returns the bucket count and width. The width is rounded up to a whole nanosecond, so the last bucket ends at or after Until |
PercentileRank(p, n) | The 1-based nearest rank ⌈p·n/100⌉ in integers, the rank both backends’ SQL reads |
AttemptIndex(attrs) | An attempt span’s weft.attempt.index as every aggregate reads it: an integer, a whole float64, or a string of decimal digits |
| Constant | Value | Bounds |
|---|---|---|
StatsBuckets | 24 | The default bucket count: an hour a bucket over a day |
MaxStatsBuckets | 366 | StatsQuery.Buckets |
MaxStatsGroups | 200 | A page’s groups; past it the groups with the fewest runs, then calls, are cut |
MinStatsYear, MaxStatsYear | 1678, 2262 | The window’s years: what Unix nanoseconds hold in an int64. Past 2262’s April 11th a time is refused too |
Stats answers ErrInvalidStats for a query outside CheckStats’ bounds.
Error classes
Section titled “Error classes”ErrorCounts returns ErrorCounts, which fold into the error_class facet:
| Name | Meaning |
|---|---|
ErrorCount | One distinct error text, Err, and Count, how many runs carry it |
ErrorClassCount | One error class, Class, and Count, how many runs’ texts fold into it |
ErrorClass(err) | Normalizes an error text into its class. A number becomes N (with its unit: Ns), an id becomes <id>, other words and quoted spans stay. Cut at MaxErrorClassBytes; "" for "" |
ErrorClasses(counts, limit) | Folds counts into classes, most runs first, ties by class; at most limit (0 all) |
ErrorClassTexts(counts, class) | The texts whose class is class: RunQuery.Errs for an error_class filter. Never nil: no text matches no run |
MaxErrorTexts | 2,000: the distinct texts one read takes; past it the rarest are not read and the answer says capped |
MaxErrorClassBytes | 240: a longer class is cut at a rune boundary and ends in …, so it stays a usable search filter |
Status
Section titled “Status”obsdb.Status is a run’s derived state, never stored. running, succeeded and failed are what the data says; interrupted is what a reader concludes from a stale last-seen, so a crash leaves evidence and a live run in another process is not mistaken for a dead one. Every backend derives it from one table:
| Condition | Status |
|---|---|
The invoke_agent span ended with status error | failed |
A run_finish record exists, or the invoke_agent span ended with any other status | succeeded |
Neither, and now − LastSeen ≤ InterruptedAfter | running |
| Neither, and older | interrupted |
failed outranks succeeded. A succeeded run with Pending > 0 is parked at an approval, not stuck.
| Name | Value | Meaning |
|---|---|---|
StatusRunning | running | Derived: heard from within InterruptedAfter |
StatusSucceeded | succeeded | Derived: run_finish stored, or a root that did not error |
StatusFailed | failed | Derived: the root span ended with error |
StatusInterrupted | interrupted | Derived: neither, and silent past InterruptedAfter |
StatusParked | parked | Filter only: an open park, succeeded with Pending > 0 and no resumer (ResumedBy empty) |
StatusCancelled | cancelled | Filter only: failed with error_type cancelled |
StatusWords | var | Every word RunQuery.Status takes, in the order an error names them: the four derived, then parked and cancelled |
ParseStatus(s) | func | Reads a status filter: "" is any, a StatusWords word is itself, anything else wraps ErrInvalidStatus, never an empty answer for a typo |
Status.Stored() | method | The derived status a filter word narrows: parked reads succeeded runs, cancelled failed ones; the four derived are themselves |
ErrorTypeCancelled | cancelled | The run row’s ErrorType when the root span names context.Canceled or context.DeadlineExceeded; CancelCause names which cancel |
InterruptedAfter | 30 s | The last-seen age that turns a non-terminal run interrupted: three missed heartbeats. Also the settling window |
Caps and constants
Section titled “Caps and constants”| Constant | Value | Bounds |
|---|---|---|
MaxTies | 500 | How far a RunPage, SessionPage or TracePage runs past its Limit to finish a group sharing the cursor’s time |
MaxGaps | 1,000 | EventPage.Gaps: one stray high position never turns a page into a list of every position below it |
TreeSpanCap | 10,000 | Spans in one RunTreeSpans answer, the first in start order; more sets RunTree.Truncated (Studio’s truncated hole, cause response_cap) |
TreeRowCap | 10,000 | Run rows one RunTreeSpans read takes of a weft run’s tree, in row order; more sets Truncated |
TreeTraceCap | 50,000 | Spans a derived run’s tree reads of its trace before cutting the subtree; more sets RunTree.TraceTruncated |
TreeMissingCap | 100 | RunTree.Missing, the first by start; MissingCount has the whole count |
ChildRunsCap | 10,000 | Child rows in one ChildRuns call over every parent it names; more is ErrChildRunsCapped and no map |
SweepBatch | 500 | Root runs per Sweep pass (one writer transaction on SQLite, one round of DELETE mutations on ClickHouse), so a large backlog interleaves with ingest; also PruneCommands’ pass on SQLite |
MaxLogCandidates, LogSkew | 10,000, 1 min | The app-log scan (Logs) |
InterruptedAfter | 30 s | Status (Status) |
MaxSearchTerms, MaxSearchTermBytes, MaxSearchOffset, PromptPreviewRunes | 16, 256, 100,000, 200 | Search (SearchQuery) |
StockErrNoDescription | the root span's status is Error (no description) | A failed derived run’s Err when its root’s Error status has no description: a failed run never reads an empty error |
| TreeCutParent | "\x00cut" | The parent a backend maps a run to when its read found the run but may not show it, such as a run past ClickHouse’s retention cut. No run has it, so that run and its descendants are no tree members |
| RecordThread | thread | The weft.record of thread’s session records, the state log (since 0.18.0) |
| AttrChatRole, ChatRoleSummarizer | weft.chat.role, summarizer | The chat span attribute naming a model call that is not the run’s own step, and its value for thread’s summarizer: that usage is the session’s SummarizerUsage, never the run’s |
The live lane’s queue depth, QueueSize (default 1,000), and the other record-kind constants are on obsdb record and span types.
Errors
Section titled “Errors”| Error | Match with | Returned when |
|---|---|---|
ErrNotFound | errors.Is | Run, Session, Events, Transcript, TranscriptBatches, Compactions, RunSpans, OtherLogs, CountLogs, TreeReader.RunTreeSpans, Requests, Prompt, Tools, Catalogs, Experiment, DeleteRun, DeleteSession and ResolvePublicID for an id the database does not hold (Prompt and Tools also for a hash, possibly as a *HoleError). Trace answers an unknown trace with no spans instead |
ErrClosed | errors.Is | A backend used after Close, or racing it |
ErrInvalidStatus | errors.Is | ParseStatus for a word outside StatusWords; its message names them: status must be running, succeeded, failed, interrupted, parked or cancelled |
ErrInvalidSearch | errors.Is | ParseSearch and Search for a query outside the grammar or its bounds; Studio answers it 400 |
ErrInvalidStats | errors.Is | CheckStats and Aggregator.Stats for a query outside their bounds; Studio answers it 400 |
ErrChildRunsCapped | errors.Is | ChildRuns past ChildRunsCap: read those parents’ children as not known, never as a part |
ErrInvalidCommand | errors.Is | A CommandStore write whose row lacks its key, or whose command state is not one of the five |
ErrInvalidManifest | errors.Is | PutManifest of a body that is not a JSON object or whose hash is not its sha256 |
ErrStepMessages | errors.Is | The stored records do not rebuild the messages a step’s request names; every *StepMessagesError matches it |
*HoleError | errors.As | Prompt, Tools, OtherLogs and CountLogs when the reader knows why a record is missing; errors.Is(err, ErrNotFound) holds |
sqlite.ErrNewerSchema | errors.Is | sqlite.Open on a file migrated by a newer weft |
clickhouse.ErrNewerSchema | errors.Is | clickhouse.Open on a database migrated by a newer weft |
A failed read is that read’s error, never ErrNotFound: since obsdb 0.2.0 (0.8.0) calls racing Close return ErrClosed, and Experiment reports a failed read as the read’s error.
Conformance
Section titled “Conformance”Package obsdbtest is the shared conformance suite for obsdb.DB backends: both first-party backends run it, and a third-party backend runs it to prove the same answers. Run it from a _test.go, as the example’s main_test.go does:
// TestConformance runs obsdbtest's table against a SQLite file: a fresh// database per subtest. A third-party backend passes its own Open here; the// rows for an optional interface it does not implement (Searcher,// TreeReader, CommandStore, ManifestStore) skip.func TestConformance(t *testing.T) { obsdbtest.Run(t, func(t *testing.T) obsdb.DB { db, err := sqlite.Open(filepath.Join(t.TempDir(), "conformance.db")) if err != nil { t.Fatal(err) } t.Cleanup(func() { _ = db.Close() }) return db })}open returns a fresh database for each subtest; the table never shares state between them. Its cases for Searcher, TreeReader, SessionEventReader, CommandStore and ManifestStore skip on a backend that does not implement them. Its Stats and ErrorCounts cases fail a backend without Aggregator.
| Function | What it checks |
|---|---|
obsdbtest.Run(t, open) | The whole table: round trip, idempotence, reordering, gaps, status at every boundary, sessions, children, paging and ties, the delta and heartbeat rules, non-weft and derived spans, traces, the transcript and compactions, request and raw records, logs, search, deletion, sweep, vacuum, the close race, commands, manifests and the run tree; since 0.18.0 the session events and turn facts; since 0.19.0 the stats and error counts |
obsdbtest.CheckTurnFactFilters(t, db) | Pins the SQL against Go over whatever db holds: each session’s turn facts as the list counts them equal SessionTurnFacts over its runs, and the Awaiting, Failed and Status filters keep exactly the matching sessions. The turn-facts cases run it, and obsdb’s contract test over every contract fixture |
obsdbtest.SummarizerSpanIsNotRunFact(t, db) | The SummarizerSpanIsNotRunFact case of Run on one database, empty of its sessions: an upgrade test runs it on a database built at an older schema |
obsdbtest.CommandsRestart(t, open) | The restart property: what one handle wrote through CommandStore, a second handle on the same storage reads back after the first closed. open returns the first handle and a func that opens the second. Skips for a non-CommandStore |
obsdbtest.CommandsPruneRace(t, db, between) | PruneCommands’ race rule: a Put landing after a prune rule chose its rows and before it deleted them survives. between runs fn inside the prune at that point once per rule (age, keep, routes, runtimes); a backend that holds writes off for a whole rule calls fn for each name before returning. Skips for a non-CommandStore |
| Release | Added |
|---|---|
| 0.7.0 | The table: round trip, idempotence, reordering, gaps, status at every boundary including the crash, sessions and public ids, children, paging cursors, the delta and heartbeat rules, non-weft spans and records |
| obsdb 0.2.0 (0.8.0) | PipelineSpellings, PagingTies, SessionPaging, TranscriptRebuilt, NonFiniteAttrs, ZeroTimes, OutOfOrder, HeartbeatOnly |
| obsdb 0.2.0 (0.8.0) | Strings, MetaFilter, SessionUncapped, ReadErrorIsNotNotFound, FilterCombinations, PagingBigTie, ManyDaysOneBatch, CloseRace; status fixtures on the wall clock |
| 0.14.0 | DeleteRun, DeleteSession, Sweep, Vacuum |
| 0.15.0 | The Commands and CommandsPrune cases of Run, and the separate CommandsRestart function, run on a SQLite file and on ClickHouse |
| 0.15.0 | The separate CommandsPruneRace function |
Reading a run
Section titled “Reading a run”The package’s own godoc examples each run against sqlite.Open(":memory:") or plain values. ExampleDB_Write and ExampleDB_Requests are on interface methods, which go/doc does not attach, so pkg.go.dev does not show them: the links go to their source.
| Example | Shows |
|---|---|
ExampleParseStatus | parked parses and narrows to succeeded; completed is ErrInvalidStatus naming the six words |
ExampleDB_Write | A run_start event and a messages record written in one batch, read back through Events and Transcript |
ExampleDB_Requests | A content-off copy’s request records read stripped, and Prompt answers a *HoleError matching ErrNotFound |
ExampleMessagesAsOf | The messages each step’s model call carried, a compaction view applied at step 1 |
ExampleSearcher | The two terms refund failed (each a substring, unquoted) find one of two runs; the row carries its prompt preview |
ExampleCutRunTree | A trace’s spans cut to one run’s subtree, each keyed by its run and that run’s parent |
ExampleCommandStore | A command’s state and times, the route from its run back to the runtime, and the runtime’s breakpoint set, read back through CommandStore |
ExampleCheckToolArgs | A playground tool_args edit checked against a tool’s stored schema, refused in the loop’s wording |
ExampleTreeMembers | A tree’s members from the rows alone: the parent chain first, then core’s id rule |
ExampleSessionQuery (meta) | Since 0.20.0: SessionQuery.Meta groups a session over its tagged turns only, for a batch that started mid-session |
ExampleAttrTrue | A weft flag read the same in both spellings: the bool true and the string "true" are set, an absent key is not |
ExampleSessionTurnFacts | A session’s turn facts: a busy-policy interrupt is ended, another cancel cancelled, a decided park resumed, and the newest open park is Pending |
ExampleSessionQuery (states) | SessionQuery’s Compacted and Status filters keep a compacted session, and SessionEventQuery.Kinds reads its compaction marker alone |
ExampleSessionEventReader | A session’s state log in record time, a runless record among it; RunIDs narrows to one turn’s events |
ExampleAggregator | Per-agent stats over a day from the stored spans, and two usage-limit failures folded into one error class |
ExampleErrorClass | Error texts as classes: numbers N, quoted names kept |
ExampleStockToolContent | Since 0.20.0: a stock agent with no conversation id is a run with no session, and its tool span’s captured content is the call’s arguments and result |
Reader functions
Section titled “Reader functions”Functions a Go reader may call on rows and bodies it already holds:
| Function | Meaning |
|---|---|
CheckToolArgs | Checks a tool call’s arguments against a tools record’s schema: the check a playground tool_args edit passes; a *core.ToolError coded INVALID_INPUT on failure |
PromptPreview | Cuts a prompt to PromptPreviewRunes runes, the cut both backends make in SQL |
PromptText | The turn’s own prompt as one messages record body holds it |
TurnPrompt | A run’s prompt from its input record and the next one: the resume rule |
LastAssistantText | The text of a body’s last assistant message with text: the run’s answer |
SessionContentOff | SessionRow.ContentOff’s rule over the session’s first turn |
RunErrorType | The run row’s error_type for a root span’s error.type, context errors read as cancelled |
LimitOf | Normalizes a list limit: 0 or negative is 50, above 500 is 500 |
DeriveStatus | The four-row status table every backend reads through |
DeriveSettling | RunRow.Settling’s rule |
ReadOtherLogs | DB.OtherLogs for every backend: attribution, order, index and paging over a backend’s LogCandidates |
CountOtherLogs | DB.CountLogs for every backend, over a severity-filtered scan |
SpanProblems | The problem tokens one weft span contributes to its run’s Problems |
CountProblems | Folds a run’s problem tokens into its counters; duplicates count once |
DeletedSpans | The spans a deletion takes: the deleted runs’ own and the non-weft spans below them |
StepRange | The smallest and largest Step of a page of request records |
SortCompactions | Orders DB.Compactions’ answer: views by index, then session markers |
NonMetaKeys | The record and span contract keys MetaOf leaves out of a row’s metadata |
MetaOf | The caller metadata a set of attributes carries |
StockHasMessages | Since 0.20.0: whether a stock chat span carries the conventions’ message content, current or legacy keys. A derived run’s message count counts the chat spans that do |
StockToolContent | Since 0.20.0: a derived run’s execute_tool span’s arguments as JSON and result as text, with whether the span carried each. An absent attribute leaves them unknown, never empty |
StockNotRun | Since 0.20.0: why a trace’s spans make no run, and the fix. "" for a weft run or a trace that derives one; else a GenAI span’s parent not stored yet, chat or execute_tool spans with no invoke_agent span, or no GenAI span at all |
StockFoldedRuns | Since 0.20.0: the derived runs an earlier derivation of the trace may have made that the spans no longer make, each a RunRow with Removed set, for a publisher to announce |
StockRunPrefix | Since 0.20.0: otel-<trace id>-, lowercase, the prefix of every derived run id of a trace: a store keyed by run id reads a trace’s derived rows by it |
Shared plumbing
Section titled “Shared plumbing”MessagesAsOf, the stock derivation functions (on obsdb record and span types) and the functions below are mostly plumbing the two backends, Studio, studio/ingest and otel share so they read one table alike. pkg.go.dev lists every exported function; besides the reader functions above and the parsers and constructors these two pages name, most are this kind of plumbing. pkg.go.dev documents each.
| Function | Meaning |
|---|---|
TreeIDRule | The parent core’s id rule gives an id inside a run’s subtree |
TreeChildID | Whether an id has the shape core gives a child run of a parent |
TreeMembers | A run’s subtree from the parents a backend knows |
TreeMemberIDs | TreeMembers’ ids, sorted |
TreeReadIDs | The run ids a backend reads a tree’s spans by, scope applied |
CutRunTree | Cuts spans to one run’s subtree |
CapTree | A backend’s last step: cut, scope, cap and Missing |
LostRecordsHole | The hole of a weft run whose spans were stored and none of its records |
TailLostHole | The hole of a weft run whose event records a destination dropped |
EventsLostHole | The counted event gap: fewer events stored than the root says were emitted |
MessagesLostHole | The counted transcript gap: some messages records stored, fewer than emitted |
EventsLostReason(r, below) | The counted event gap in words: N of M events were lost, then how many are missing below the last stored position and how many are the run’s tail. below is the gap count a reader walked (EventPage.Gaps’ length); -1 leaves the split out. "" when nothing is lost |
MessagesLostReason(r) | MessagesLostHole in words: K of N transcript batches were lost: …. "" when that hole is not raised |
ExplainMissing | The error Prompt and Tools return for a hash the run holds no record of |
MetadataCapReason | The metadata_cap hole’s reason with its count |
AttrTrue(m, k) | Whether a boolean attribute is set true: a bool true, or the string "true" a store that stringifies attributes reads back. weft.tool.denied and weft.tool.approved are read through it. ExampleAttrTrue prints true true false: a bool, the string, an absent key |
Complete example
Section titled “Complete example”The example’s main.go opens a SQLite file in a temporary directory, writes one run and reads it back:
// Command obsdb opens an observability database, writes one run's records// into it the way weft/otel's local sink does, and reads the run back// through obsdb.DB: the runs list, the run, its events and a search.package main
import ( "context" "errors" "fmt" "io" "log" "os" "path/filepath" "time"
"github.com/weftgo/weft/obsdb" "github.com/weftgo/weft/obsdb/sqlite")
func main() { dir, err := os.MkdirTemp("", "obsdb-example-") if err != nil { log.Fatal(err) } defer os.RemoveAll(dir) if err := run(context.Background(), os.Stdout, dir); err != nil { log.Fatal(err) }}
// record builds one weft log record for run_1: an event at its position or// a messages record at its index.func record(at time.Time, kind, eventType string, pos int64, body string) obsdb.Record { attrs := map[string]any{"weft.record": kind, "weft.run.id": "run_1", "gen_ai.agent.name": "support-bot"} switch kind { case "event": attrs["weft.event.type"] = eventType attrs["weft.event.pos"] = pos case "messages": attrs["weft.messages.index"] = pos } return obsdb.Record{Time: at, EventName: "weft." + kind, Body: body, Attrs: attrs}}
func run(ctx context.Context, w io.Writer, dir string) error { db, err := sqlite.Open(filepath.Join(dir, "weft.db")) if err != nil { return err } defer db.Close()
t0 := time.Now().UTC() if err := db.Write(ctx, obsdb.Batch{Records: []obsdb.Record{ record(t0, "event", "run_start", 0, `{"type":"run_start","id":"run_1","agent":"support-bot"}`), record(t0, "messages", "", 0, `[{"role":"user","content":[{"type":"text","text":"Where is order 1234?"}]}]`), record(t0.Add(time.Second), "messages", "", 1, `[{"role":"assistant","content":[{"type":"text","text":"It ships on Friday."}]}]`), record(t0.Add(time.Second), "event", "run_finish", 1, `{"type":"run_finish","steps":1,"usage":{"input_tokens":12,"output_tokens":6}}`), }}); err != nil { return err }
page, err := db.Runs(ctx, obsdb.RunQuery{Agent: "support-bot", Status: obsdb.StatusSucceeded}) if err != nil { return err } for _, r := range page.Runs { fmt.Fprintf(w, "run %s %s steps=%d tokens=%d prompt=%q\n", r.ID, r.Status, r.Steps, r.Usage.InputTokens+r.Usage.OutputTokens, r.PromptPreview) }
events, err := db.Events(ctx, "run_1", -1, 0) // after -1: from position 0 if err != nil { return err } fmt.Fprintf(w, "events: %d done=%v gaps=%v\n", len(events.Events), events.Done, events.Gaps)
if s, ok := db.(obsdb.Searcher); ok { found, err := s.Search(ctx, obsdb.SearchQuery{Text: "friday"}) if err != nil { return err } fmt.Fprintf(w, "search friday: %d run(s)\n", found.Total) }
_, err = db.Run(ctx, "run_2") fmt.Fprintln(w, "run_2 not found:", errors.Is(err, obsdb.ErrNotFound)) return nil}View on GitHub · run it from docs-site/examples:
go run ./obsdbgo test ./obsdbrun run_1 succeeded steps=1 tokens=18 prompt="Where is order 1234?"events: 2 done=true gaps=[]search friday: 1 run(s)run_2 not found: trueThe run reads succeeded because its run_finish record is stored, and its event page is Done for the same reason. TestRun in main_test.go pins this output; TestConformance runs the whole obsdbtest table on a t.TempDir() file.
Best practices & gotchas
Section titled “Best practices & gotchas”- Read status from the row, never store it.
interrupted,parkedandcancelledare read-time conclusions; a writer that stores a status freezes a crash asrunning. (Source:obsdb.Statusgodoc,obsdb/db.go:417-439) - Page with both cursor fields.
Beforealone skips nothing up toMaxTiestied rows; past that, only the (Before,BeforeID) pair resumes inside the tie. (Source:obsdb.RunPagegodoc,obsdb/db.go:617-627) - Start
Eventsat -1.afteris exclusive, so 0 skips therun_startat position 0. (Source:DB.Eventsgodoc,obsdb/db.go:35-39) - Treat
ErrChildRunsCappedas unknown. PastChildRunsCapthe call returns no map; a reader that shows a partial child list would misprice the tree. (Source:obsdb/tree.go:129-137) - Do not wait on
Donefor an interrupted run. A run with no root that went silent is neverDone; decide from the row’s derivedStatus. (Source:EventPage.Donegodoc,obsdb/db.go:655-672) - Run
obsdbtest.Runon every backend change. It is the one definition of the promises Studio relies on; implement the optional interfaces and their cases stop skipping. (Source:obsdb/obsdbtest/obsdbtest.go:1-114)
See also
Section titled “See also”- obsdb record and span types
- Choose the observability database: SQLite or ClickHouse
- Keep and delete recorded runs
- Badges and holes
- Studio HTTP API
Symbols used: obsdb.DB · obsdb.Searcher · obsdb.TreeReader · obsdb.CommandStore · obsdb.ManifestStore · obsdb.Hub · obsdb.RunQuery · obsdb.SearchQuery · obsdb.SessionQuery · obsdb.TraceQuery · obsdb.TreeQuery · obsdb.RunRow · obsdb.Batch · obsdb.Record · sqlite.Open · clickhouse.Open · obsdbtest.Run · otel.LocalDB · studio.DB