Skip to content

obsdb: reading the observability database from Go

View as Markdown

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:

obsdb/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 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))

obsdb/main.go on GitHub

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.

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.

PartWhat it isWhere
obsdb.DBThe backend interface: one write, the reads, deletion and retentionThe DB interface
Optional interfacesSearcher, TreeReader, SessionEventReader, Aggregator, CommandStore, BreakpointProvenanceStore, ManifestStore: a backend implements them beside DBOptional capabilities
The hubThe live lane: every sqlite Write publishes its frames before it returns; for another backend Studio feeds its own hub from ingestHub, Selector
obsdb/sqlite, obsdb/clickhouseThe two first-party backendsOpen a backend
obsdb/obsdbtestThe conformance table every backend runsConformance

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:

ReleaseWhat arrived
0.7.0obsdb itself: the OTLP-shaped model (Span, Record, Batch), the derived identity, the DB interface, the four-row status table and the hub
0.10.0The readers the request-record, compaction and log views use: the compaction constants, HoleCause, LogSkew, ParseSeverity, SeverityText, the RequestBody parts
0.10.0InstructionsHash, CatalogHash and RequestCount on RunRow, and so on RunDetail, which embeds it

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.

MethodReturnsMeaning
Write(ctx, Batch)errorStores 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)RunPageLists runs: RunQuery filters, newest Started first
Run(ctx, id)RunDetailOne run with its subagent children
Events(ctx, runID, after, limit)EventPagePages 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.RawMessageThe 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)[]TranscriptBatchTranscript with each record’s index, step (-1 when absent) and input flag: TranscriptBatch
Compactions(ctx, runID)[]CompactionEvery 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)[]RequestRecordPages the request records in index order, one per model-call attempt (RequestQuery, RequestRecord)
Prompt(ctx, runID, hash)PromptRecordThe 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)ToolsRecordThe run’s tools record of one catalog hash, with Prompt’s errors
Catalogs(ctx, runID)[]ToolsRecordEvery tools record of the run, one per hash, in index order; a content-off run has none
RunSpans(ctx, runID)[]SpanThe run’s own spans
OtherLogs(ctx, runID, LogQuery)LogPagePages 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)LogCountsCounts 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)[]SpanEvery stored span of a trace. An unknown trace is empty, not an error: a trace is only the spans that arrived
Traces(ctx, TraceQuery)TracePageLists traces, weft and non-weft, one row per trace id, newest first; a trace whose root never arrived has Root nil
Sessions(ctx, SessionQuery)SessionPageLists sessions, newest activity first
Session(ctx, id)SessionDetailOne session with every turn
ResolvePublicID(ctx, publicID)sessionID stringThe session a public id names
SaveExperiment(ctx, Experiment)errorUpserts a saved playground experiment by ID (Experiment)
Experiments(ctx)[]ExperimentEvery saved experiment, newest update first
Experiment(ctx, id)ExperimentOne saved experiment
DeleteRun(ctx, id)errorRemoves 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)errorDeleteRun for every run carrying the weft.session.id. The app’s own conversation store is never touched
Sweep(ctx, before)int, errorDeletes 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)errorGives freed space back: VACUUM on SQLite, OPTIMIZE TABLE … FINAL on the mutated ClickHouse tables (heavy on a large database)
Close()errorCloses 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:

ReleaseAreaChange
0.18.0SessionsA 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.0Caller linksRunRow.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.0Session pagesRunQuery.TurnBelow, TurnAbove and Oldest read a turn’s neighbours in O(1) rows; SessionQuery.IDs reads a known set of sessions
0.14.0DeletionSpanLink 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.0ConformanceThe table gained DeleteRun, DeleteSession, Sweep and Vacuum
obsdb 0.2.0 (0.8.0)OTLP decodeFromOTLPTraces 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)HubA 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)TranscriptDedupTranscript 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)PagingMaxGaps (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)PagingSessionPage.Total no longer shrinks with the cursor
obsdb/sqlite (0.8.0)EventsEvents never reports Done with stored events missing; gap detection no longer scans the run on every page
obsdb/sqlite (0.8.0)WriteA 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)SessionsSession 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)FiltersRuns 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)PagingTied 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, sessionsEvents 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)WriteNon-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

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.

InterfaceMethodsWithout it
obsdb.SearcherSearch(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 OffsetStudio leaves its search capability off and says why
obsdb.TreeReaderRunTreeSpans(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, ErrChildRunsCappedStudio leaves spans_tree off and reads each run’s children one run at a time
obsdb.SessionEventReaderSessionEvents(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.0Studio leaves its timeline capability off; GET /api/sessions/{id}/timeline and /entries answer 501
obsdb.AggregatorStats(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.0Studio leaves its stats capability off: GET /api/stats and the error_class facet and filter are off
obsdb.CommandStoreThe playground link’s commands, run routes, breakpoints and runtimesStudio’s runtime server keeps them in memory only
obsdb.BreakpointProvenanceStoreA breakpoint set with when and from which surface it was set. Since 0.20.0Studio stores the tools alone, through CommandStore
obsdb.ManifestStoreEach agent’s configuration by its manifest hashStudio 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.

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.

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

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.

obsdb.RunQuery selects runs for Runs. The zero value lists top-level runs, newest first, 50 at a time. Every set field must match.

FieldTypeMeaning
AgentstringThe run’s agent name
SessionIDstringThe weft.session.id its turns carry
PublicIDstringThe weft.public_id: a panel token’s scope
ParentRunIDstring"" top-level runs only (no parent and no caller link), "*" every run, else the children of that run
StatusStatus"" any; a word of StatusWords, the read-time parked and cancelled included
Playground*boolnil any; true or false for playground runs or app runs
ExperimentIDstringThe runs of one saved experiment
Metamap[string]stringA subset match on the run’s metadata
Beforetime.TimeCursor on Started; zero is the newest
BeforeIDstringWith Before, makes the cursor the pair (Started, ID), exact inside a group sharing one Started: pass RunPage.NextBeforeID
LastSeenAftertime.TimeKeeps runs last seen at or after it (zero no bound). A running run is always among them once the bound is older than InterruptedAfter
LimitintPage size: 0 is 50, at most 500
StoppedBystringExactly this RunRow.StoppedBy; a value ending in : is a prefix (has_tool_call: matches every has_tool_call:<tools>)
ErrorTypestringExactly this RunRow.ErrorType: max_steps, cancelled, model_error, …
IDPrefixstringRuns whose ID starts with it, byte for byte, no wildcard or case folding: a pasted short id
Errs[]stringRuns 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)
CallerRunIDstringRuns 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[]stringRuns of any of these sessions; nil any. With SessionID, both apply
TurnBelow, TurnAboveintRuns 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
OldestboolTurns 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

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.

FieldTypeMeaning
RunQueryRunQueryThe list filters, as above
TextstringSearch 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
ToolstringThe exact name of a tool the run called
ModelstringThe exact model name on the run row
ErrorstringA case-insensitive substring of the run’s error
Since, Untiltime.TimeStarted ≥ Since, Started < Until; zero is open
MinTokensint64Input plus output tokens at least this; 0 any
SortSearchSortThe order; "" is SortStarted
OffsetintRows 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.

ConstantValueOrder
SortStartedstartedNewest first (the default)
SortDurationdurationLongest first: Finished (or LastSeen while unfinished) minus Started
SortTokenstokensMost input plus output tokens first

The search grammar and its bounds:

NameValueMeaning
ParseSearch(text)[]string, errorSplits 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
MaxSearchTerms16More terms is ErrInvalidSearch
MaxSearchTermBytes256A longer term is ErrInvalidSearch; so is a Tool, Model or Error filter longer than this
MaxSearchOffset100,000The largest SearchQuery.Offset; a negative offset is refused too
CheckSearch(q)[]string, errorThe 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)
PromptPreviewRunes200The cut of RunRow.PromptPreview

obsdb.SessionQuery selects sessions. The zero value lists them newest activity first, 50 at a time.

FieldTypeMeaning
AgentstringThe session’s agent
PublicIDstringScopes 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
QstringText: 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
IDPrefixstringSince 0.20.0, sessions whose id starts with it, byte for byte: the ⌘K palette’s lookup of a pasted short id
Metamap[string]stringScopes 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[]stringSessions delegated by any of these sessions (SessionRow.ParentSession): one read lists a level of a delegation tree. Empty any
IDs[]stringSessions whose id is one of these. Every aggregate is still over all of each one’s turns. Empty any
AwaitingboolSessions whose newest turn is an open park (SessionRow.Pending > 0)
FailedboolSessions with a failed turn (SessionRow.FailedTurns > 0). A busy-ended or cancelled turn is no failure
CompactedboolSessions thread compacted: a compaction marker in the session events index
StatusStatusSessions 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
LineagestringLineageChild (child) the delegated sessions, LineageFork (fork) the forked ones; any other value keeps none
Sincetime.TimeSessions last seen at or after it; zero any
Beforetime.TimeCursor on LastSeen; zero is the newest
BeforeIDstringWith Before, the (LastSeen, ID) pair
Limitint0 is 50, at most 500

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.

FieldTypeMeaning
ServicestringTraces holding at least one span whose resource service name is exactly this
PublicIDstringTraces 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
Metamap[string]stringSince 0.20.0, traces holding, for each pair, a span whose attributes carry it: tag.<k>=<v> and flow= on /api/traces
ScopeMetamap[string]stringSince 0.20.0, traces every span of which carries each pair: PublicID’s rule for a tag-scoped panel token
NotRunboolSince 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”
IDPrefixstringSince 0.20.0, traces whose id starts with it, byte for byte
Sincetime.TimeStart at or after; zero no bound
Untiltime.TimeStart before; zero no bound
Beforetime.TimeCursor on Start; zero is the newest
BeforeIDstringWith Before, the (Start, TraceID) pair: pass TracePage.NextBeforeID
Limitint0 is 50, at most 500

TreeQuery, RequestQuery, LogQuery, Selector

Section titled “TreeQuery, RequestQuery, LogQuery, Selector”

obsdb.TreeQuery names the run tree RunTreeSpans reads.

FieldMeaning
RunIDThe tree’s root run
PublicIDWhen 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
MetaSince 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 methodMeaning
Step*int: when set, only that step’s attempts
FromThe first index read, inclusive: pass the last returned Index + 1 to continue
Limit0 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 methodMeaning
FromThe first index read, inclusive: the last returned Index + 1 continues
Limit0 is 100, at most 1,000
MinSeverityWhen 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.

FieldMeaning
RunIDOne run’s frames
SessionIDThe frames of every run of one session
PublicIDThe frames of every run carrying one public id
AgentThe frames of one agent’s runs
AllEvery run’s frames, subagent children included (Studio’s Live page). It must be asked for; set with any other field, the selector matches nothing

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.

FieldMeaning
RunsThe page’s RunRows
TotalThe whole match, cursor aside
NextBefore*time.Time: the next page’s RunQuery.Before; nil on the last page
NextBeforeIDThe next page’s RunQuery.BeforeID; "" on the last page

obsdb.RunDetail is Run’s answer.

FieldMeaning
RunRowThe run, embedded
ChildrenIts subagent children: runs whose ParentRunID is this run, by Started

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.

FieldTypeMeaning
IDstringThe run id
ParentRunIDstringThe parent run of a subagent child (weft.parent.run.id); "" for a top-level run
ParentCallIDstringThe parent’s tool call that started this child
TraceIDstringThe trace of its root span
AgentstringThe agent name (gen_ai.agent.name)
Provider, ModelstringThe model the run requested, from run_start or the root span
ManifestHashstringThe weft.manifest.hash its spans carried; a ManifestStore resolves it
WeftVersionstringThe weft version from the root span’s weft.version, else its resource’s; beside run_start’s value the larger string is kept
ServicestringThe root span’s resource service.name
SessionID, PublicIDstringThe weft.session.id and weft.public_id a thread turn carries
TurnintThe session turn number (weft.turn)
PlaygroundboolA playground run (weft.playground)
ExperimentIDstringThe weft.experiment.id of a playground experiment
ForkedFromstringThe run a playground run was forked from (weft.forked_from)
ResumedFromstringThe parked run this one resumes (weft.resumed_from, set by weft.ResumeOf)
ResumedBystringOn 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, CallerCallIDstringThe 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
Metamap[string]stringThe caller metadata its records and spans carried
Startedtime.TimeThe earliest time seen of any record or span of the run
Finished*time.TimeWhen it finished; nil while it has not
LastSeentime.TimeThe newest record or span time, heartbeats included: DeriveStatus’s clock
StatusStatusThe derived status: running, succeeded, failed or interrupted
ErrstringA failed run’s error text
StepsintSteps run, from run_finish or the root span’s weft.run.steps
PendingintCalls awaiting a decision; above 0 on a succeeded run means parked at an approval
StopReasonstringThe root span’s weft.run.stop_reason (max_tokens when the last step hit the limit)
Usagecore.UsageToken usage, from run_finish or the root span’s gen_ai.usage.*
EventCount, MessageCountint64Event records and growth messages records stored
DeltaCountint64Deltas counted; deltas are never stored
InstructionsHashstringrun_start’s weft.instructions.hash; "" on a run written before the request record
CatalogHashstringRequest index 0’s weft.catalog.hash; "" when it offered no tools
RequestCountint64The request records’ high-water mark: max weft.request.index + 1
PromptPreviewstringThe turn’s own prompt cut to PromptPreviewRunes runes; "" for a content-off run or one with no user text
DerivedboolA 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
RootEndedboolIts invoke_agent span is stored. A span is exported once it ended, so the run is over whatever records are missing
RemovedboolSince 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
FinishRecordedboolIts run_finish record is stored. Root ended without it: the record tail was lost, or there never were records
SettlingboolRoot 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)
StoppedBystringWhat 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
CancelCausestringA canceled run’s weft.cancel.cause (thread.interrupted, studio.cancel, deadline, a weft.CancelCause kind); "" otherwise
EventsEmitted, MessagesEmittedint64What 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
ErrorTypestringA failed run’s kind, the root span’s error.type, with context errors read as cancelled (ErrorTypeCancelled); "" otherwise
ProblemsProblemsThe run’s problem counters
MethodReturnsMeaning
RequestsHole()HoleThe 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, HoleCauseRequestsHole 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.

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 methodCounts
AttemptsRetriedModel 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
FallbacksModel calls a fallback layer answered: successful attempt spans with weft.attempt.layer fallback
ToolErrorsTool calls ending in an error result, except DENIED, RETRY and a context error; NO_SUCH_TOOL counts
DeniedRefused tool calls: error.type DENIED (a policy middleware) plus the calls a resume denied, from weft.run.denied
TruncatedTool results the result cap cut (weft.tool.truncated_bytes > 0)
RepairedTool 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
TapPanicsObserver panics the run contained (weft.tap.panics): the run is unchanged, an observer saw less
MetadataDroppedMetadata 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
LogWarnApp log records under the run’s spans at WARN (13–16). Read time, through CountLogs, on the run document only
LogErrorThe same at ERROR or above (17–24)
Any()Reports whether any counter is non-zero

obsdb.EventPage is one page of a run’s durable events.

FieldMeaning
EventsThe page’s PosEvents: body verbatim at its position
NextAfter*int64: the after for the next page
DoneEvery 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
GapsDurable positions missing below the high-water mark (a lost batch, never a delta), lowest first, at most MaxGaps

obsdb.SessionPage is one Sessions result, paged as RunPage is: newest LastSeen first (ties by ID, descending), ties riding along up to MaxTies.

FieldMeaning
SessionsThe page’s SessionRows
TotalThe whole match, cursor aside
NextBeforeThe next SessionQuery.Before; nil on the last page
NextBeforeIDThe 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.

FieldMeaning
IDThe session id
PublicIDIts public id
AgentIts agent
TurnsHow many turns
FirstSeen, LastSeenThe time range its turns cover
StatusThe newest turn’s status
UsageThe turns’ summed core.Usage
TitleThe newest turn’s non-empty weft.session.title (SessionTitleKey), a label that survives content-off; "" when none carried one
FirstPromptThe first turn’s PromptPreview; "" when that turn carried no content, never a later turn’s
ContentOffThe 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
SummarizerUsageWhat 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
SummarizerModelsSummarizerUsage split by provider and model, sorted, as ModelUsage parts; nil when nothing was summarized
ParentSession, ParentCall, ParentRunA 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
PendingThe newest turn’s pending calls when it is an open park, else 0: the session awaits a decision
FailedTurnsThe failed turns that were neither ended nor cancelled
EndedTurnsThe turns thread’s busy policy ended (Interrupt or Rollback; cancel cause BusyCancelCause)
CancelledTurnsThe other failed turns whose error type is cancelled: a caller’s cancel, a deadline, thread.closed, studio.cancel
ResumesThe turns that resume a parked one; Turns − Resumes is the session’s exchanges
OutcomesThe newest MaxOutcomes turns’ TurnOutcomes, oldest first
ForkedFromThe 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.

NameValueMeaning
OutcomeSucceededsucceededSucceeded, no pending calls
OutcomeFailedfailedFailed, not cancelled or ended
OutcomeRunningrunningStill running
OutcomeInterruptedinterruptedThe heartbeat went stale
OutcomeCancelledcancelledFailed with error type cancelled
OutcomeEndedendedthread’s busy policy cancelled it
OutcomeParkedparkedPending calls and no resumer
OutcomeResumedresumedPending calls a resumer decided
OutcomeOf(r)funcA 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)funcSets a row’s turn facts from its turns, given in any order: read by turn, then start, then id, the newest last
MaxOutcomes40Bounds SessionRow.Outcomes: a strip, not the turn list
BusyCancelCausethread.interruptedThe weft.cancel.cause of a turn the Interrupt or Rollback busy policy cancelled: EndedTurns, never FailedTurns
SessionForkedFromKeyweft.session.forked_fromThe 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.

FieldMeaning
SessionRowThe session, embedded
RunsEvery turn: top-level runs by Turn, then Started; experiments excluded

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.

FieldTypeMeaning
SessionIDstringThe session
PublicIDstringKeeps only the events carrying this weft.public_id, a panel token’s scope. The page, offsets and Total count those alone
RunIDs[]stringKeeps 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[]stringKeeps only the events whose SessionEventKind is one of these (compaction, interrupt, rewind, …)
OffsetintEvents to skip: the previous offset plus the page’s length continues
Limitint0 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.

FieldMeaning
SessionIDThe session
RunIDThe run it is filed under; "" for a record held at Close, a session-level fact
KindIts weft.record: thread or compaction
NameIts event name, weft.thread.<kind> or weft.compaction, derived from the body’s kind when the record carried none
PublicIDIts weft.public_id
ContentIts weft.content
TimeThe record time
BodyThe record’s body, verbatim
NameValueMeaning
SessionEventKind(e)funcThe 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)funcAn event’s name: the record’s own, else the one its kind and body imply. "" when the body names no kind
IsSessionEventKind(kind)funcWhether records of a weft.record kind feed the index: thread and compaction
MaxSessionEventLimit1,000Bounds one SessionEvents page

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.

FieldMeaning
TracesThe page’s TraceRows
TotalThe whole match, cursor aside
NextBeforeThe next TraceQuery.Before; nil on the last page
NextBeforeIDThe next TraceQuery.BeforeID; "" on the last page

obsdb.TraceRow is one trace in a list, computed from its spans.

FieldMeaning
TraceIDThe trace id
Root*TraceRoot: the earliest span with no parent; nil when only child spans arrived (a hole the reader badges)
ServiceThe root’s service, else the earliest span’s
Start, EndThe time range the spans cover
SpanCountSpans, each (trace, span) once
ErrorWhether any span ended with status error
RunIDsThe distinct weft.run.id values, sorted (a subagent child shares its parent’s trace)

obsdb.TraceRoot is a trace’s root span.

FieldMeaning
SpanIDIts span id
NameIts name

obsdb.RunTree is RunTreeSpans’ answer.

FieldMeaning
SpansThe tree’s TreeSpans in start order, then span id: at most TreeSpanCap, the first ones
TruncatedThe tree holds more than TreeSpanCap spans (or more than TreeRowCap runs)
TraceTruncatedA derived run’s trace held more than TreeTraceCap spans; never set for a weft run
MissingDescendant runs known from their rows with no span in Spans and not running, by Started then id, at most TreeMissingCap. Empty when Truncated
MissingCountHow many are missing, before the cap
HiddenTreeQuery’s scope (PublicID, Meta) left runs out
HiddenCountHow many runs it left out, subtrees included; never their ids. 0 unless Hidden

obsdb.TreeRun names one run of a tree.

FieldMeaning
IDThe run id
ParentRunIDIts parent
PublicIDIts weft.public_id, what a scoped reader filters by; "" when none
MetaIts row’s metadata, which TreeQuery.Meta reads (0.20.0)
StartedRunRow.Started, the order Missing lists runs in
StatusIts 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).

FieldMeaning
SpanThe Span, embedded
RunIDThe run it belongs to: its weft.run.id, or the derived run whose subtree holds it
ParentRunIDThat 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).

FieldMeaning
RowIts 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
SpansIts 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.

TypeFieldMeaning
SpanLinkTraceID, SpanIDThe span’s key
SpanLinkParentSpanIDIts parent span
SpanLinkRunIDThe weft.run.id it carries; "" for a non-weft span
SpanKeyTraceID, SpanIDThe trace and span ids

obsdb.LogPage is one OtherLogs answer: the page and what the reader knows it could not show.

FieldMeaning
LogsThe page’s OtherLogs
PartialThe run is running: a line under an in-flight span appears once the span arrives, so indexes are stable only once the run ended
GapLines in the run’s traces naming a span no stored span has (dropped or still open); not in Logs. 0 while Partial
TruncatedThe run’s traces hold more than MaxLogCandidates lines in its window (anyone’s: the cap applies before attribution)
NoBridgeThe 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.

FieldMeaning
TotalApp log records at or above the asked severity
WarnThose at WARN (13–16)
ErrorThose at ERROR or above (17–24)
CappedThe scan stopped at MaxLogCandidates: every count is a floor, shown as ”≥”
NameKindMeaning
ParseSeverity(s)funcReads 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)funcAn 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
LogSkewconst, 1 minuteWidens a run’s time window for the app-log scan (Started − LogSkew to LastSeen + LogSkew): clock skew between one run’s emitters
MaxLogCandidatesconst, 10,000Log records one OtherLogs read loads, chosen by time before attribution; more is LogPage.Truncated
LogCandidatesfunc typeA 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

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.

FieldTypeMeaning
RunQueryRunQueryThe /api/runs filters, with the same meaning. Before, BeforeID, Limit and Oldest are not read. Playground nil counts both kinds
ByStatsByWhat to group by
Since, Untiltime.TimeBoth required, Since before Until. A run is in when Since ≤ Started < Until, and every span of it counts in its run’s bucket
BucketsintThe 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.

ConstantValueGroups
StatsByAgentagentRuns by agent name
StatsByErrorTypeerror_typeFailed runs by ErrorType
StatsByModelmodelModel calls (chat spans) by requested model name; two providers’ models of one name are one group
StatsByTooltoolTool calls (execute_tool spans) by tool name
StatsByStepstepModel 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.

FieldMeaning
ByThe grouping
Since, UntilThe window as read
BucketsThe bucket count
BucketEach bucket’s width, a time.Duration
GroupsThe StatsGroups: most runs first, then most calls, then by key (by step: step index ascending)
GroupsCutHow many groups MaxStatsGroups cut

obsdb.StatsGroup is one key’s numbers over the window. What a field counts depends on By.

FieldMeaning
KeyThe group’s key
RunsThe runs in the group; for model, tool and step, the distinct runs that made a call in it
FailedThose runs that failed
CallsModel 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
FailedCallsThose calls that failed. For a tool, the record contract’s tool_errors rule: DENIED, RETRY and context errors are no failure
RetriedModel calls that took more than one attempt; 0 for tool
DenialsThe record contract’s problems.denied rule over the group’s spans; 0 for model and step
Usage, ModelsThe 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, DelegatedRunsBy 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, TTFTPercentiles in milliseconds: run durations for agent and error type, call durations for the others; TTFT the model calls’ weft.ttft_ms
SeriesThe 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:

NameMeaning
StatsCellOne 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
StatsModelPartOne group’s usage on one provider and model: Key, an embedded ModelUsage, and Delegated for its subagents’ part
StatsPercentilesOne 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
ConstantValueBounds
StatsBuckets24The default bucket count: an hour a bucket over a day
MaxStatsBuckets366StatsQuery.Buckets
MaxStatsGroups200A page’s groups; past it the groups with the fewest runs, then calls, are cut
MinStatsYear, MaxStatsYear1678, 2262The 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.

ErrorCounts returns ErrorCounts, which fold into the error_class facet:

NameMeaning
ErrorCountOne distinct error text, Err, and Count, how many runs carry it
ErrorClassCountOne 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
MaxErrorTexts2,000: the distinct texts one read takes; past it the rarest are not read and the answer says capped
MaxErrorClassBytes240: a longer class is cut at a rune boundary and ends in …, so it stays a usable search filter

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:

ConditionStatus
The invoke_agent span ended with status errorfailed
A run_finish record exists, or the invoke_agent span ended with any other statussucceeded
Neither, and now − LastSeen ≤ InterruptedAfterrunning
Neither, and olderinterrupted

failed outranks succeeded. A succeeded run with Pending > 0 is parked at an approval, not stuck.

NameValueMeaning
StatusRunningrunningDerived: heard from within InterruptedAfter
StatusSucceededsucceededDerived: run_finish stored, or a root that did not error
StatusFailedfailedDerived: the root span ended with error
StatusInterruptedinterruptedDerived: neither, and silent past InterruptedAfter
StatusParkedparkedFilter only: an open park, succeeded with Pending > 0 and no resumer (ResumedBy empty)
StatusCancelledcancelledFilter only: failed with error_type cancelled
StatusWordsvarEvery word RunQuery.Status takes, in the order an error names them: the four derived, then parked and cancelled
ParseStatus(s)funcReads a status filter: "" is any, a StatusWords word is itself, anything else wraps ErrInvalidStatus, never an empty answer for a typo
Status.Stored()methodThe derived status a filter word narrows: parked reads succeeded runs, cancelled failed ones; the four derived are themselves
ErrorTypeCancelledcancelledThe run row’s ErrorType when the root span names context.Canceled or context.DeadlineExceeded; CancelCause names which cancel
InterruptedAfter30 sThe last-seen age that turns a non-terminal run interrupted: three missed heartbeats. Also the settling window
ConstantValueBounds
MaxTies500How far a RunPage, SessionPage or TracePage runs past its Limit to finish a group sharing the cursor’s time
MaxGaps1,000EventPage.Gaps: one stray high position never turns a page into a list of every position below it
TreeSpanCap10,000Spans in one RunTreeSpans answer, the first in start order; more sets RunTree.Truncated (Studio’s truncated hole, cause response_cap)
TreeRowCap10,000Run rows one RunTreeSpans read takes of a weft run’s tree, in row order; more sets Truncated
TreeTraceCap50,000Spans a derived run’s tree reads of its trace before cutting the subtree; more sets RunTree.TraceTruncated
TreeMissingCap100RunTree.Missing, the first by start; MissingCount has the whole count
ChildRunsCap10,000Child rows in one ChildRuns call over every parent it names; more is ErrChildRunsCapped and no map
SweepBatch500Root 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, LogSkew10,000, 1 minThe app-log scan (Logs)
InterruptedAfter30 sStatus (Status)
MaxSearchTerms, MaxSearchTermBytes, MaxSearchOffset, PromptPreviewRunes16, 256, 100,000, 200Search (SearchQuery)
StockErrNoDescriptionthe 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.

ErrorMatch withReturned when
ErrNotFounderrors.IsRun, 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
ErrClosederrors.IsA backend used after Close, or racing it
ErrInvalidStatuserrors.IsParseStatus for a word outside StatusWords; its message names them: status must be running, succeeded, failed, interrupted, parked or cancelled
ErrInvalidSearcherrors.IsParseSearch and Search for a query outside the grammar or its bounds; Studio answers it 400
ErrInvalidStatserrors.IsCheckStats and Aggregator.Stats for a query outside their bounds; Studio answers it 400
ErrChildRunsCappederrors.IsChildRuns past ChildRunsCap: read those parents’ children as not known, never as a part
ErrInvalidCommanderrors.IsA CommandStore write whose row lacks its key, or whose command state is not one of the five
ErrInvalidManifesterrors.IsPutManifest of a body that is not a JSON object or whose hash is not its sha256
ErrStepMessageserrors.IsThe stored records do not rebuild the messages a step’s request names; every *StepMessagesError matches it
*HoleErrorerrors.AsPrompt, Tools, OtherLogs and CountLogs when the reader knows why a record is missing; errors.Is(err, ErrNotFound) holds
sqlite.ErrNewerSchemaerrors.Issqlite.Open on a file migrated by a newer weft
clickhouse.ErrNewerSchemaerrors.Isclickhouse.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.

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:

obsdb/main_test.go
// 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
})
}

obsdb/main_test.go on GitHub

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.

FunctionWhat 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
ReleaseAdded
0.7.0The 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.0DeleteRun, DeleteSession, Sweep, Vacuum
0.15.0The Commands and CommandsPrune cases of Run, and the separate CommandsRestart function, run on a SQLite file and on ClickHouse
0.15.0The separate CommandsPruneRace function

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.

ExampleShows
ExampleParseStatusparked parses and narrows to succeeded; completed is ErrInvalidStatus naming the six words
ExampleDB_WriteA run_start event and a messages record written in one batch, read back through Events and Transcript
ExampleDB_RequestsA content-off copy’s request records read stripped, and Prompt answers a *HoleError matching ErrNotFound
ExampleMessagesAsOfThe messages each step’s model call carried, a compaction view applied at step 1
ExampleSearcherThe two terms refund failed (each a substring, unquoted) find one of two runs; the row carries its prompt preview
ExampleCutRunTreeA trace’s spans cut to one run’s subtree, each keyed by its run and that run’s parent
ExampleCommandStoreA command’s state and times, the route from its run back to the runtime, and the runtime’s breakpoint set, read back through CommandStore
ExampleCheckToolArgsA playground tool_args edit checked against a tool’s stored schema, refused in the loop’s wording
ExampleTreeMembersA 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
ExampleAttrTrueA weft flag read the same in both spellings: the bool true and the string "true" are set, an absent key is not
ExampleSessionTurnFactsA 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
ExampleSessionEventReaderA session’s state log in record time, a runless record among it; RunIDs narrows to one turn’s events
ExampleAggregatorPer-agent stats over a day from the stored spans, and two usage-limit failures folded into one error class
ExampleErrorClassError texts as classes: numbers N, quoted names kept
ExampleStockToolContentSince 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

Functions a Go reader may call on rows and bodies it already holds:

FunctionMeaning
CheckToolArgsChecks 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
PromptPreviewCuts a prompt to PromptPreviewRunes runes, the cut both backends make in SQL
PromptTextThe turn’s own prompt as one messages record body holds it
TurnPromptA run’s prompt from its input record and the next one: the resume rule
LastAssistantTextThe text of a body’s last assistant message with text: the run’s answer
SessionContentOffSessionRow.ContentOff’s rule over the session’s first turn
RunErrorTypeThe run row’s error_type for a root span’s error.type, context errors read as cancelled
LimitOfNormalizes a list limit: 0 or negative is 50, above 500 is 500
DeriveStatusThe four-row status table every backend reads through
DeriveSettlingRunRow.Settling’s rule
ReadOtherLogsDB.OtherLogs for every backend: attribution, order, index and paging over a backend’s LogCandidates
CountOtherLogsDB.CountLogs for every backend, over a severity-filtered scan
SpanProblemsThe problem tokens one weft span contributes to its run’s Problems
CountProblemsFolds a run’s problem tokens into its counters; duplicates count once
DeletedSpansThe spans a deletion takes: the deleted runs’ own and the non-weft spans below them
StepRangeThe smallest and largest Step of a page of request records
SortCompactionsOrders DB.Compactions’ answer: views by index, then session markers
NonMetaKeysThe record and span contract keys MetaOf leaves out of a row’s metadata
MetaOfThe caller metadata a set of attributes carries
StockHasMessagesSince 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
StockToolContentSince 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
StockNotRunSince 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
StockFoldedRunsSince 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
StockRunPrefixSince 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

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.

FunctionMeaning
TreeIDRuleThe parent core’s id rule gives an id inside a run’s subtree
TreeChildIDWhether an id has the shape core gives a child run of a parent
TreeMembersA run’s subtree from the parents a backend knows
TreeMemberIDsTreeMembers’ ids, sorted
TreeReadIDsThe run ids a backend reads a tree’s spans by, scope applied
CutRunTreeCuts spans to one run’s subtree
CapTreeA backend’s last step: cut, scope, cap and Missing
LostRecordsHoleThe hole of a weft run whose spans were stored and none of its records
TailLostHoleThe hole of a weft run whose event records a destination dropped
EventsLostHoleThe counted event gap: fewer events stored than the root says were emitted
MessagesLostHoleThe 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
ExplainMissingThe error Prompt and Tools return for a hash the run holds no record of
MetadataCapReasonThe 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

The example’s main.go opens a SQLite file in a temporary directory, writes one run and reads it back:

obsdb/main.go
// 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 obsdb/main.go on GitHub

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

Terminal window
go run ./obsdb
go test ./obsdb
run 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: true

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

  • Read status from the row, never store it. interrupted, parked and cancelled are read-time conclusions; a writer that stores a status freezes a crash as running. (Source: obsdb.Status godoc, obsdb/db.go:417-439)
  • Page with both cursor fields. Before alone skips nothing up to MaxTies tied rows; past that, only the (Before, BeforeID) pair resumes inside the tie. (Source: obsdb.RunPage godoc, obsdb/db.go:617-627)
  • Start Events at -1. after is exclusive, so 0 skips the run_start at position 0. (Source: DB.Events godoc, obsdb/db.go:35-39)
  • Treat ErrChildRunsCapped as unknown. Past ChildRunsCap the 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 Done for an interrupted run. A run with no root that went silent is never Done; decide from the row’s derived Status. (Source: EventPage.Done godoc, obsdb/db.go:655-672)
  • Run obsdbtest.Run on 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)

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