---
title: 'obsdb: reading the observability database from Go'
description: The obsdb.DB interface and its optional Searcher, TreeReader, CommandStore, ManifestStore, SessionEventReader, Aggregator and BreakpointProvenanceStore capabilities, every query, page and row type a reader gets back, the status words, the caps and errors, how the sqlite and clickhouse backends open, and obsdbtest, the conformance suite a third-party backend runs.
url: https://weftgo.dev/docs/reference/obsdb/
type: reference
sources:
  - 'W11-fix3, v0.20.2: weft/obsdb/db.go:209-263 (RunQuery: ParentRunID no caller link; Errs, CallerRunID, SessionIDs, TurnBelow/TurnAbove, Oldest), 690-746 (SessionQuery: Parents, IDs, Meta, Awaiting, Failed, Compacted, Status, Lineage, Since), 748-822 (SessionRow: own turns; SummarizerUsage/Models, ParentSession/Call/Run, Pending, FailedTurns, EndedTurns, CancelledTurns, Resumes, Outcomes, ForkedFrom), 824-880 (LineageChild/Fork, TurnOutcome and the eight outcomes, MaxOutcomes, BusyCancelCause, SessionForkedFromKey, OutcomeOf), SessionTurnFacts; go doc RunRow (CallerRunID, CallerCallID); go doc ModelUsage, SumModelUsage; weft/obsdb/sessionevents.go (SessionEventReader, SessionEventQuery, SessionEventPage, SessionEvent, SessionEventKind, SessionEventName, IsSessionEventKind, MaxSessionEventLimit); weft/obsdb/stats.go (Aggregator, StatsQuery, StatsBy and its five values, RunLevel, StatsPage, StatsGroup, StatsCell, StatsBucket, StatsModelPart, StatsPercentiles, Percentiles, BuildStats, CheckStats, PercentileRank, AttemptIndex, StatsBuckets 24, MaxStatsBuckets 366, MaxStatsGroups 200, MinStatsYear 1678, MaxStatsYear 2262, ErrInvalidStats; ErrorCount, ErrorClassCount, ErrorClass, ErrorClasses, ErrorClassTexts, MaxErrorTexts 2000, MaxErrorClassBytes 240); weft/obsdb/compaction.go:47-66 (RecordThread, AttrChatRole, ChatRoleSummarizer); go doc TreeCutParent, AttrTrue; weft/obsdb/sqlite/{stats,commands,sessionevents}.go and obsdb/clickhouse/{stats,commands,sessionevents}.go (both backends implement all seven); weft/studio/manifest.go:38-39 (offStats, offTimeline); weft/studio/runtime/store.go:228-242, 934-942 (no BreakpointProvenanceStore: the tools alone); weft/obsdb/obsdbtest/obsdbtest.go:60-113 (the table''s cases), sessionevents.go:30-32 (skips), stats.go:215-222 (Stats cases fail without Aggregator), 352-356 (ErrorCounts too), turnfacts.go:212, 227 (CheckTurnFactFilters and the turn-facts case that runs it), partlyexpired.go:97; weft/obsdb/contract_test.go:388 (every contract fixture), summarizerspan.go:30 (SummarizerSpanIsNotRunFact); weft/obsdb/example_test.go:30, 54, 367, 413, 467 (ExampleSessionTurnFacts, ExampleSessionQuery_states, ExampleSessionEventReader, ExampleAggregator, ExampleErrorClass); weft/CHANGELOG.md:115 (0.19.0 stats), 227, 230-235 (0.18.0 timeline index, session states, caller links)'
  - weft/obsdb/db.go:278-302 (TraceQuery Meta, ScopeMeta, NotRun, IDPrefix), 538-548 (RunRow.Removed), 695-745 (SessionQuery IDPrefix, Meta); weft/obsdb/tree.go:64-80 (TreeQuery.Meta, Scoped), 160-182 (RunTree.Hidden, TreeRun.Meta); weft/obsdb/problems.go:44-52 (Repaired); weft/obsdb/stock_content.go:35-190 (StockHasMessages, StockToolContent, StockNotRun, StockFoldedRuns, StockRunPrefix); weft/obsdb/example_test.go:479, stock_content_test.go:13 — v0.20.2
  - every path and line below is in the weft v0.17.0 tag (53bab77f), read from the weft-v0.17.0 worktree
  - 'obsdb/request.go:682-692 (MessagesLostReason), 694-721 (EventsLostReason: below, -1 omits the split)'
  - 'obsdb/doc.go:1-36 (the package: DB, the hub, obsdbtest; Searcher and CommandStore optional; deltas and heartbeats never stored)'
  - 'obsdb/db.go:20-174 (DB: every method''s contract, Delete*/Sweep/Vacuum never touch CommandStore rows), 176-207 (TranscriptBatch), 209-266 (RunQuery), 268-353 (TraceQuery, TraceRow, TraceRoot, TracePage), 417-474 (Status, the read-time words, StatusWords, ErrInvalidStatus, ParseStatus, Stored), 476-615 (RunRow), 617-641 (RunPage, MaxTies, RunDetail), 643-688 (PosEvent, EventPage, MaxGaps), 726-989 (SessionQuery, SessionRow, SessionTitleKey, SessionPage, SessionDetail), 991-1023 (ErrNotFound, ErrClosed, InterruptedAfter, SweepBatch), 1025-1064 (DeriveStatus''s table, DeriveSettling, LimitOf: 0 = 50, at most 500)'
  - obsdb/request.go:290-305 (RequestQuery, PageLimit), 553-611 (RunRow.RequestsHole, RequestsHoleCause)
  - obsdb/search.go:14-62 (Searcher, SearchQuery), 64-89 (SearchSort, the three sorts, MaxSearchTerms, MaxSearchTermBytes, MaxSearchOffset, ErrInvalidSearch), 91-133 (ParseSearch), 154-160 (PromptPreviewRunes)
  - obsdb/tree.go:20-52 (TreeReader), 54-69 (TreeQuery), 108-137 (TreeSpanCap, TreeTraceCap, TreeMissingCap, TreeRowCap, ChildRunsCap, ErrChildRunsCapped), 139-211 (RunTree, TreeRun, TreeSpan)
  - obsdb/logs.go:16-37 (LogQuery, PageLimit), 65-119 (LogSkew, SeverityText, ParseSeverity), 120-172 (MaxLogCandidates, LogPage, LogCandidates), 228-239 (LogCounts)
  - obsdb/problems.go:12-72 (Problems, Any), 106-116 (ErrorTypeCancelled)
  - obsdb/delete.go:8-16 (SpanLink, SpanKey)
  - obsdb/stock.go:24-30 (StockErrNoDescription), 142-191 (StockRun)
  - 'obsdb/hub.go:28-47 (Selector), 104-126 (NewHub: QueueSize default 1000)'
  - obsdb/asof.go:33 (ErrStepMessages)
  - obsdb/commands.go:157-163 (ErrInvalidCommand)
  - obsdb/manifests.go:64-67 (ErrInvalidManifest)
  - obsdb/obsdbtest/obsdbtest.go:1-114 (the package doc; Run and its table of subtests)
  - obsdb/obsdbtest/commands.go:24-30 (the skip for a non-CommandStore), 554-695 (CommandsPruneRace, CommandsRestart)
  - obsdb/obsdbtest/search.go:250-256, obsdb/obsdbtest/tree.go:54-58, obsdb/obsdbtest/manifests.go:24-28 (the other skips)
  - 'obsdb/sqlite/sqlite.go:1-12 (package doc: Hub), 55-75 (KeepDeltas, Open), 206-219 (Hub, Path)'
  - obsdb/sqlite/migrations.go:85 (sqlite.ErrNewerSchema)
  - obsdb/clickhouse/clickhouse.go:52-92 (KeepDeltas, TTL, Open)
  - obsdb/clickhouse/migrations.go:222 (clickhouse.ErrNewerSchema)
  - obsdb/example_test.go:94-361 (ExampleParseStatus, ExampleDB_Write, ExampleDB_Requests, ExampleMessagesAsOf, ExampleSearcher, ExampleCommandStore)
  - 'v0.20.2: weft/obsdb/example_test.go:14-24 (ExampleAttrTrue: true true false)'
  - obsdb/tree_test.go:187-235 (ExampleCutRunTree, ExampleTreeMembers)
  - 'obsdb/sqlite/write.go:744-818 (what the invoke_agent span fills on the row: manifest hash, weft.version, trace, service, usage, steps, pending, stop reason), 939-984 (run_start and run_finish fill provider, model, usage, steps, pending, stopped_by)'
  - 'CHANGELOG.md:607 (0.15.0: the Commands, CommandsPrune and CommandsRestart cases), 1119 (0.14.0: DeletedSpans, SpanLink, SpanKey; the delete cases), 3001 (0.10.0: the phase-1 readers named), 3253-3289 (obsdb 0.2.0), 3291-3325 (obsdb/clickhouse 0.2.0), 4296-4328 (0.7.0: the first obsdb, obsdb/sqlite, obsdbtest)'
  - 'obsdb/request.go:570-626 (RequestsHole through RequestsHoleCause and LostRecordsHole: settling, gap with events_lost, not_recorded with no_logger)'
  - 'obsdb/search.go:135-155 (CheckSearch: sort, offset, min_tokens, the 256-byte filters)'
  - 'obsdb/example_test.go:281-304 (ExampleSearcher: Text refund failed unquoted, two terms), 114, 175 (ExampleDB_Write, ExampleDB_Requests on interface methods: go/doc attaches no example to them), 318 (ExampleCommandStore)'
  - obsdb/args.go:42 (CheckToolArgs), obsdb/args_test.go:79 (ExampleCheckToolArgs)
  - 'obsdb/logs.go:201, 240 (ReadOtherLogs, CountOtherLogs: a run with no span is a HoleError for both)'
  - obsdb/problems.go:117, 137, 198 (RunErrorType, SpanProblems, CountProblems)
  - obsdb/search.go:161, 239, 265, 283 (PromptPreview, PromptText, TurnPrompt, LastAssistantText)
  - obsdb/model.go:469, 486 (NonMetaKeys, MetaOf), obsdb/raw.go:131 (StepRange), obsdb/compaction.go:145 (SortCompactions), obsdb/delete.go:30 (DeletedSpans)
  - obsdb/tree.go:215-544 (TreeIDRule, TreeChildID, TreeMembers, CutRunTree, CapTree, TreeReadIDs, TreeMemberIDs), obsdb/request.go:138, 614-731, 834 (MetadataCapReason, the lost-record holes, ExplainMissing)
  - 'obsdb/sqlite/sqlite.go:34, 48, 212-218 (DB, Option, Hub, Path: "" for :memory:), 100-107 (Open returns *DB), obsdb/sqlite/write.go:420-454 (Write publishes to the hub), obsdb/sqlite/write.go:766-779 (the larger weft version kept)'
  - obsdb/sqlite/sqlite_test.go:1439 (ExampleDB_Path), obsdb/clickhouse/example_test.go:23 (ExampleOpen)
  - obsdb/clickhouse/clickhouse.go:15-21 (DefaultContentTTL 30 days, DefaultMetaTTL 90 days), 27, 39 (DB, Option)
  - 'studio/studio.go:278-283 (a backend without a hub: Studio''s own NewHub fed by ingest)'
  - docs-site/examples/obsdb/main.go, main_test.go (TestRun pins the output; TestConformance runs obsdbtest.Run on a t.TempDir() SQLite file)
---

# obsdb: reading the observability database from Go

<span id="overview"></span>Package [`obsdb`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb) is the observability database: what the [local sink](https://weftgo.dev/docs/reference/glossary/#local-sink) writes and Studio reads. [`obsdb.DB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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](https://weftgo.dev/docs/reference/obsdb-records/) 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`:

```go title="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](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/obsdb/main.go)

`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

The model is OTLP-shaped: [spans](https://weftgo.dev/docs/reference/glossary/#span) 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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DB) | The backend interface: one write, the reads, deletion and retention | [The DB interface](#the-db-interface) |
| Optional interfaces | [`Searcher`](#searcher), [`TreeReader`](#treereader), [`SessionEventReader`](#sessioneventreader), [`Aggregator`](#aggregator), [`CommandStore`](https://weftgo.dev/docs/reference/obsdb-records/#commandstore), `BreakpointProvenanceStore`, [`ManifestStore`](https://weftgo.dev/docs/reference/obsdb-records/#manifeststore): a backend implements them beside `DB` | [Optional capabilities](#optional-capabilities) |
| The [hub](https://weftgo.dev/docs/reference/glossary/#hub) | The live lane: every `sqlite` `Write` publishes its frames before it returns; for another backend Studio feeds its own hub from ingest | [`Hub`](https://weftgo.dev/docs/reference/obsdb-records/#hub), [`Selector`](#selector) |
| `obsdb/sqlite`, `obsdb/clickhouse` | The two first-party backends | [Open a backend](#open-a-backend) |
| `obsdb/obsdbtest` | The conformance table every backend runs | [Conformance](#conformance) |

Within weft, `otel.Local` writes through a `DB`, [`otel.LocalDB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#LocalDB) returns the installed pipeline's handle, and [`studio.DB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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

<span id="db"></span>[`obsdb.DB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DB.Write) | `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)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DB.Runs) | [`RunPage`](#runpage) | Lists runs: [`RunQuery`](#runquery) filters, newest `Started` first |
| [`Run(ctx, id)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DB.Run) | [`RunDetail`](#rundetail) | One run with its subagent children |
| [`Events(ctx, runID, after, limit)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DB.Events) | [`EventPage`](#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)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DB.Transcript) | `[]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)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DB.TranscriptBatches) | `[]TranscriptBatch` | `Transcript` with each record's index, step (-1 when absent) and input flag: [`TranscriptBatch`](https://weftgo.dev/docs/reference/obsdb-records/#transcriptbatch) |
| [`Compactions(ctx, runID)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DB.Compactions) | `[]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`](https://weftgo.dev/docs/reference/obsdb-records/#compaction) |
| [`Requests(ctx, runID, RequestQuery)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DB.Requests) | `[]RequestRecord` | Pages the request records in index order, one per model-call attempt ([`RequestQuery`](#requestquery), [`RequestRecord`](https://weftgo.dev/docs/reference/obsdb-records/#requestrecord)) |
| [`Prompt(ctx, runID, hash)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DB.Prompt) | `PromptRecord` | The run's prompt record of one system hash. Missing: `ErrNotFound`, as a [`*HoleError`](https://weftgo.dev/docs/reference/badges/#holeerror) when the reason is known (`not_recorded`, `stripped`, `gap`) |
| [`Tools(ctx, runID, hash)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DB.Tools) | `ToolsRecord` | The run's tools record of one catalog hash, with `Prompt`'s errors |
| [`Catalogs(ctx, runID)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DB.Catalogs) | `[]ToolsRecord` | Every tools record of the run, one per hash, in index order; a content-off run has none |
| [`RunSpans(ctx, runID)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DB.RunSpans) | `[]Span` | The run's own spans |
| [`OtherLogs(ctx, runID, LogQuery)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DB.OtherLogs) | [`LogPage`](#logpage) | Pages the run's [app log records](https://weftgo.dev/docs/reference/glossary/#app-log-record), 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)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DB.CountLogs) | [`LogCounts`](#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)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DB.Trace) | `[]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)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DB.Traces) | [`TracePage`](#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)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DB.Sessions) | [`SessionPage`](#sessionpage) | Lists [sessions](https://weftgo.dev/docs/reference/glossary/#session), newest activity first |
| [`Session(ctx, id)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DB.Session) | [`SessionDetail`](#sessiondetail) | One session with every turn |
| [`ResolvePublicID(ctx, publicID)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DB.ResolvePublicID) | `sessionID string` | The session a [public id](https://weftgo.dev/docs/reference/glossary/#public-id) names |
| [`SaveExperiment(ctx, Experiment)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DB.SaveExperiment) | `error` | Upserts a saved playground experiment by ID ([`Experiment`](https://weftgo.dev/docs/reference/obsdb-records/#experiment)) |
| [`Experiments(ctx)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DB.Experiments) | `[]Experiment` | Every saved experiment, newest update first |
| [`Experiment(ctx, id)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DB.Experiment) | `Experiment` | One saved experiment |
| [`DeleteRun(ctx, id)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DB.DeleteRun) | `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)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DB.DeleteSession) | `error` | `DeleteRun` for every run carrying the `weft.session.id`. The app's own conversation store is never touched |
| [`Sweep(ctx, before)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DB.Sweep) | `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)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DB.Vacuum) | `error` | Gives freed space back: `VACUUM` on SQLite, `OPTIMIZE TABLE … FINAL` on the mutated ClickHouse tables (heavy on a large database) |
| [`Close()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DB.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](https://weftgo.dev/docs/production/retention/) 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`](#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`](#spanlink) and [`SpanKey`](#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

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 |
|---|---|---|
| <span id="searcher"></span>[`obsdb.Searcher`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#Searcher) | [`Search(ctx, SearchQuery) (RunPage, error)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#Searcher.Search): 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 |
| <span id="treereader"></span>[`obsdb.TreeReader`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#TreeReader) | [`RunTreeSpans(ctx, TreeQuery) (RunTree, error)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#TreeReader.RunTreeSpans): 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)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#TreeReader.ChildRuns): 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 |
| <span id="sessioneventreader"></span>[`obsdb.SessionEventReader`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#SessionEventReader) | [`SessionEvents(ctx, SessionEventQuery) (SessionEventPage, error)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#SessionEventReader.SessionEvents): 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](#session-events)). Since 0.18.0 | Studio leaves its `timeline` capability off; `GET /api/sessions/{id}/timeline` and `/entries` answer 501 |
| <span id="aggregator"></span>[`obsdb.Aggregator`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#Aggregator) | [`Stats(ctx, StatsQuery) (StatsPage, error)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#Aggregator.Stats): numbers across runs, grouped ([Aggregates](#aggregates)). [`ErrorCounts(ctx, SearchQuery) ([]ErrorCount, bool, error)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#Aggregator.ErrorCounts): 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`](https://weftgo.dev/docs/reference/obsdb-records/#commandstore) | The playground link's commands, run routes, breakpoints and runtimes | Studio's runtime server keeps them in memory only |
| [`obsdb.BreakpointProvenanceStore`](https://weftgo.dev/docs/reference/obsdb-records/#commandstore) | 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`](https://weftgo.dev/docs/reference/obsdb-records/#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`](https://weftgo.dev/docs/reference/obsdb-records/#newhub) fed by ingest for a backend without one.

## Open a backend

Both backends return an `obsdb.DB` whose concrete type also implements the four optional interfaces. [Choose the observability database](https://weftgo.dev/docs/production/storage-backends/) covers paths, DSNs, pragmas, TTLs and migrations.

| Call | Options | Notes |
|---|---|---|
| [`sqlite.Open(path, opts...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#Open) | [`sqlite.KeepDeltas()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#KeepDeltas) | One file on the CGO-free modernc driver; `:memory:` for tests. `Open` returns an `obsdb.DB`; assert it to [`*sqlite.DB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB) to reach [`Hub()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.Hub) (every `Write` publishes to it before returning) and [`Path()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#DB.Path) (the absolute file path; `""` for `:memory:`) |
| [`clickhouse.Open(dsn, opts...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#Open) | [`clickhouse.KeepDeltas()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#KeepDeltas), [`clickhouse.TTL(content, meta)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#TTL) | The hosted backend, column-compatible with the OTel Collector's ClickHouse exporter; the concrete type is [`*clickhouse.DB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DB); no hub. Without `TTL`, [`DefaultContentTTL`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DefaultContentTTL) (30 days: content-bearing rows) and [`DefaultMetaTTL`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#DefaultMetaTTL) (90 days: spans and runs) are the retention defaults |

Options are values of each package's own option type, [`sqlite.Option`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#Option) and [`clickhouse.Option`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#Option). Each `Open` fails with its own `ErrNewerSchema` on a database migrated by a newer weft ([Errors](#errors)). Two godoc examples: [`sqlite` `ExampleDB_Path`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#example-DB.Path) reads the file path through `interface{ Path() string }`, as Studio's `/api/meta` does; [`clickhouse` `ExampleOpen`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#example-Open) opens a DSN with `TTL(0, 7*24*time.Hour)` (compiled, not run: it needs a server).

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

[`obsdb.RunQuery`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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`](#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`](#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 `Generate`s. 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`

[`obsdb.SearchQuery`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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` |

<span id="searchsort"></span>[`obsdb.SearchSort`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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 |
|---|---|---|
| <span id="sortstarted"></span>[`SortStarted`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#SortStarted) | `started` | Newest first (the default) |
| <span id="sortduration"></span>[`SortDuration`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#SortDuration) | `duration` | Longest first: `Finished` (or `LastSeen` while unfinished) minus `Started` |
| <span id="sorttokens"></span>[`SortTokens`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#SortTokens) | `tokens` | Most input plus output tokens first |

The search grammar and its bounds:

| Name | Value | Meaning |
|---|---|---|
| <span id="parsesearch"></span>[`ParseSearch(text)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#ParseSearch) | `[]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 |
| <span id="maxsearchterms"></span>[`MaxSearchTerms`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#MaxSearchTerms) | 16 | More terms is `ErrInvalidSearch` |
| <span id="maxsearchtermbytes"></span>[`MaxSearchTermBytes`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#MaxSearchTermBytes) | 256 | A longer term is `ErrInvalidSearch`; so is a `Tool`, `Model` or `Error` filter longer than this |
| <span id="maxsearchoffset"></span>[`MaxSearchOffset`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#MaxSearchOffset) | 100,000 | The largest `SearchQuery.Offset`; a negative offset is refused too |
| [`CheckSearch(q)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#CheckSearch) | `[]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)` |
| <span id="promptpreviewrunes"></span>[`PromptPreviewRunes`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#PromptPreviewRunes) | 200 | The cut of `RunRow.PromptPreview` |

### `SessionQuery`

[`obsdb.SessionQuery`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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`](#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` | <span id="lineagechild"></span>[`LineageChild`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#LineageChild) (`child`) the delegated sessions, <span id="lineagefork"></span>[`LineageFork`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#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`

[`obsdb.TraceQuery`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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`

<span id="treequery"></span>[`obsdb.TreeQuery`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#TreeQuery.Scoped) | Reports whether `PublicID` or `Meta` is set |

<span id="requestquery"></span>[`obsdb.RequestQuery`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#RequestQuery.PageLimit) | The normalized limit: 100 for 0 or negative, 1,000 at most |

<span id="logquery"></span>[`obsdb.LogQuery`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#LogQuery.PageLimit) | The normalized limit: 100 for 0 or negative, 1,000 at most |

<span id="selector"></span>[`obsdb.Selector`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#Selector) scopes a [`Hub.Subscribe`](https://weftgo.dev/docs/reference/obsdb-records/#hub): 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

### `RunPage` and `RunDetail`

<span id="runpage"></span>[`obsdb.RunPage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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 [`RunRow`](#runrow)s |
| `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 |

<span id="rundetail"></span>[`obsdb.RunDetail`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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`

[`obsdb.RunRow`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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](https://weftgo.dev/docs/reference/studio-api/) has the wire names.

| Field | Type | Meaning |
|---|---|---|
| `ID` | `string` | The run id |
| `ParentRunID` | `string` | The parent run of a [subagent](https://weftgo.dev/docs/reference/glossary/#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](https://weftgo.dev/docs/reference/glossary/#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](https://weftgo.dev/docs/reference/glossary/#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](https://weftgo.dev/docs/reference/glossary/#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`](#problems) | The run's problem counters |

| Method | Returns | Meaning |
|---|---|---|
| [`RequestsHole()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#RunRow.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()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#RunRow.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](https://weftgo.dev/docs/reference/badges/).

### `Problems`

[`obsdb.Problems`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#Problems.Any) | Reports whether any counter is non-zero |

### `EventPage`

[`obsdb.EventPage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#EventPage) is one page of a run's durable events.

| Field | Meaning |
|---|---|
| `Events` | The page's [`PosEvent`](https://weftgo.dev/docs/reference/obsdb-records/#posevent)s: 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

<span id="sessionpage"></span>[`obsdb.SessionPage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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 `SessionRow`s |
| `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 |

<span id="sessionrow"></span>[`obsdb.SessionRow`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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`](#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`](#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' [`TurnOutcome`](#turnoutcome)s, oldest first |
| `ForkedFrom` | The `weft.session.forked_from` its turns carry, `<origin>#<entry>`; `""` for a session no fork made |

[`SessionTurnFacts`](#sessionturnfacts) sets the turn facts, `Pending` through `ForkedFrom`; every backend reads the same rule in SQL.

<span id="turnoutcome"></span>[`obsdb.TurnOutcome`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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 |
|---|---|---|
| <span id="outcomesucceeded"></span>[`OutcomeSucceeded`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#OutcomeSucceeded) | `succeeded` | Succeeded, no pending calls |
| <span id="outcomefailed"></span>[`OutcomeFailed`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#OutcomeFailed) | `failed` | Failed, not cancelled or ended |
| <span id="outcomerunning"></span>[`OutcomeRunning`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#OutcomeRunning) | `running` | Still running |
| <span id="outcomeinterrupted"></span>[`OutcomeInterrupted`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#OutcomeInterrupted) | `interrupted` | The heartbeat went stale |
| <span id="outcomecancelled"></span>[`OutcomeCancelled`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#OutcomeCancelled) | `cancelled` | Failed with error type `cancelled` |
| <span id="outcomeended"></span>[`OutcomeEnded`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#OutcomeEnded) | `ended` | `thread`'s busy policy cancelled it |
| <span id="outcomeparked"></span>[`OutcomeParked`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#OutcomeParked) | `parked` | Pending calls and no resumer |
| <span id="outcomeresumed"></span>[`OutcomeResumed`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#OutcomeResumed) | `resumed` | Pending calls a resumer decided |
| <span id="outcomeof"></span>[`OutcomeOf(r)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#OutcomeOf) | 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 |
| <span id="sessionturnfacts"></span>[`SessionTurnFacts(row, turns)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#SessionTurnFacts) | func | Sets a row's turn facts from its turns, given in any order: read by turn, then start, then id, the newest last |
| <span id="maxoutcomes"></span>[`MaxOutcomes`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#MaxOutcomes) | 40 | Bounds `SessionRow.Outcomes`: a strip, not the turn list |
| <span id="busycancelcause"></span>[`BusyCancelCause`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#BusyCancelCause) | `thread.interrupted` | The `weft.cancel.cause` of a turn the Interrupt or Rollback busy policy cancelled: `EndedTurns`, never `FailedTurns` |
| <span id="sessionforkedfromkey"></span>[`SessionForkedFromKey`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#SessionForkedFromKey) | `weft.session.forked_from` | The run metadata a forked session's turns carry: `<origin session>#<entry>` |

<span id="modelusage"></span>[`obsdb.ModelUsage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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. <span id="summodelusage"></span>[`SumModelUsage(parts)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#SumModelUsage) returns the parts' total and the parts sorted by provider, then model (nil for none): the rule for `SummarizerUsage` and `SummarizerModels`.

<span id="sessiondetail"></span>[`obsdb.SessionDetail`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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

A [`SessionEventReader`](#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.

<span id="sessioneventquery"></span>[`obsdb.SessionEventQuery`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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`](#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 |

<span id="sessioneventpage"></span>[`obsdb.SessionEventPage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#SessionEventPage) is one answer: `Events` in order, and `Total`, every event the query selects.

<span id="sessionevent"></span>[`obsdb.SessionEvent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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 |
|---|---|---|
| <span id="sessioneventkind"></span>[`SessionEventKind(e)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#SessionEventKind) | func | The short kind an event names: the name past `weft.thread.` for a thread record (`approval.decision`, `receipt`), `compaction` for a marker |
| <span id="sessioneventname"></span>[`SessionEventName(kind, eventName, body)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#SessionEventName) | func | An event's name: the record's own, else the one its kind and body imply. `""` when the body names no kind |
| <span id="issessioneventkind"></span>[`IsSessionEventKind(kind)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#IsSessionEventKind) | func | Whether records of a `weft.record` kind feed the index: `thread` and `compaction` |
| <span id="maxsessioneventlimit"></span>[`MaxSessionEventLimit`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#MaxSessionEventLimit) | 1,000 | Bounds one `SessionEvents` page |

### Traces

<span id="tracepage"></span>[`obsdb.TracePage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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 `TraceRow`s |
| `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 |

<span id="tracerow"></span>[`obsdb.TraceRow`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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) |

<span id="traceroot"></span>[`obsdb.TraceRoot`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#TraceRoot) is a trace's root span.

| Field | Meaning |
|---|---|
| `SpanID` | Its span id |
| `Name` | Its name |

### Run trees

<span id="runtree"></span>[`obsdb.RunTree`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#RunTree) is `RunTreeSpans`' answer.

| Field | Meaning |
|---|---|
| `Spans` | The tree's [`TreeSpan`](#treespan)s 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` |

<span id="treerun"></span>[`obsdb.TreeRun`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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 |

<span id="treespan"></span>[`obsdb.TreeSpan`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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`](https://weftgo.dev/docs/reference/obsdb-records/#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 |

<span id="stockrun"></span>[`obsdb.StockRun`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#StockRun) is one run derived from stock spans ([How Studio derives a run](https://weftgo.dev/docs/observe/other-languages/#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 |

<span id="spanlink"></span>[`obsdb.SpanLink`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#SpanLink) is one stored span's place in its trace, what the deletion walk reads; <span id="spankey"></span>[`obsdb.SpanKey`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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 |

### Logs

<span id="logpage"></span>[`obsdb.LogPage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#LogPage) is one `OtherLogs` answer: the page and what the reader knows it could not show.

| Field | Meaning |
|---|---|
| `Logs` | The page's [`OtherLog`](https://weftgo.dev/docs/reference/obsdb-records/#otherlog)s |
| `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 |

<span id="logcounts"></span>[`obsdb.LogCounts`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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 |
|---|---|---|
| <span id="parseseverity"></span>[`ParseSeverity(s)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#ParseSeverity) | 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 |
| <span id="severitytext"></span>[`SeverityText(n)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#SeverityText) | 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 |
| <span id="logskew"></span>[`LogSkew`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#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 |
| <span id="maxlogcandidates"></span>[`MaxLogCandidates`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#MaxLogCandidates) | const, 10,000 | Log records one `OtherLogs` read loads, chosen by time before attribution; more is `LogPage.Truncated` |
| <span id="logcandidates"></span>[`LogCandidates`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#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

An [`Aggregator`](#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.

<span id="statsquery"></span>[`obsdb.StatsQuery`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#StatsQuery) selects what `Stats` aggregates.

| Field | Type | Meaning |
|---|---|---|
| `RunQuery` | [`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.

<span id="statsby"></span>[`obsdb.StatsBy`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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 |
|---|---|---|
| <span id="statsbyagent"></span>[`StatsByAgent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#StatsByAgent) | `agent` | Runs by agent name |
| <span id="statsbyerrortype"></span>[`StatsByErrorType`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#StatsByErrorType) | `error_type` | Failed runs by `ErrorType` |
| <span id="statsbymodel"></span>[`StatsByModel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#StatsByModel) | `model` | Model calls (`chat` spans) by requested model name; two providers' models of one name are one group |
| <span id="statsbytool"></span>[`StatsByTool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#StatsByTool) | `tool` | Tool calls (`execute_tool` spans) by tool name |
| <span id="statsbystep"></span>[`StatsByStep`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#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 |

<span id="statspage"></span>[`obsdb.StatsPage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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 [`StatsGroup`](#statsgroup)s: most runs first, then most calls, then by key (by step: step index ascending) |
| `GroupsCut` | How many groups `MaxStatsGroups` cut |

<span id="statsgroup"></span>[`obsdb.StatsGroup`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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`](#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`](#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 [`StatsBucket`](#statsbucket)s |

<span id="statsbucket"></span>[`obsdb.StatsBucket`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#StatsBucket) is one bucket of a series: `Runs`, `Failed`, `Calls`, `FailedCalls`, `InputTokens` and `OutputTokens` over the runs that started in it.

<span id="percentiles"></span>[`obsdb.Percentiles`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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 |
|---|---|
| <span id="statscell"></span>[`StatsCell`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#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 |
| <span id="statsmodelpart"></span>[`StatsModelPart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#StatsModelPart) | One group's usage on one provider and model: `Key`, an embedded `ModelUsage`, and `Delegated` for its subagents' part |
| <span id="statspercentiles"></span>[`StatsPercentiles`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#StatsPercentiles) | One group's `Duration` and `TTFT` percentiles, by `Key` |
| <span id="buildstats"></span>[`BuildStats(q, cells, models, pcts)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#BuildStats) | 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 |
| <span id="checkstats"></span>[`CheckStats(q)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#CheckStats) | 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` |
| <span id="percentilerank"></span>[`PercentileRank(p, n)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#PercentileRank) | The 1-based nearest rank ⌈p·n/100⌉ in integers, the rank both backends' SQL reads |
| <span id="attemptindex"></span>[`AttemptIndex(attrs)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#AttemptIndex) | 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 |
|---|---|---|
| <span id="statsbuckets"></span>[`StatsBuckets`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#StatsBuckets) | 24 | The default bucket count: an hour a bucket over a day |
| <span id="maxstatsbuckets"></span>[`MaxStatsBuckets`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#MaxStatsBuckets) | 366 | `StatsQuery.Buckets` |
| <span id="maxstatsgroups"></span>[`MaxStatsGroups`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#MaxStatsGroups) | 200 | A page's groups; past it the groups with the fewest runs, then calls, are cut |
| <span id="minstatsyear"></span>[`MinStatsYear`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#MinStatsYear), <span id="maxstatsyear"></span>[`MaxStatsYear`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#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`](#errinvalidstats) for a query outside `CheckStats`' bounds.

### Error classes

`ErrorCounts` returns [`ErrorCount`](#errorcount)s, which fold into the `error_class` facet:

| Name | Meaning |
|---|---|
| <span id="errorcount"></span>[`ErrorCount`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#ErrorCount) | One distinct error text, `Err`, and `Count`, how many runs carry it |
| <span id="errorclasscount"></span>[`ErrorClassCount`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#ErrorClassCount) | One error class, `Class`, and `Count`, how many runs' texts fold into it |
| <span id="errorclass"></span>[`ErrorClass(err)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#ErrorClass) | 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 `""` |
| <span id="errorclasses"></span>[`ErrorClasses(counts, limit)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#ErrorClasses) | Folds counts into classes, most runs first, ties by class; at most `limit` (0 all) |
| <span id="errorclasstexts"></span>[`ErrorClassTexts(counts, class)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#ErrorClassTexts) | The texts whose class is `class`: `RunQuery.Errs` for an `error_class` filter. Never nil: no text matches no run |
| <span id="maxerrortexts"></span>[`MaxErrorTexts`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#MaxErrorTexts) | 2,000: the distinct texts one read takes; past it the rarest are not read and the answer says capped |
| <span id="maxerrorclassbytes"></span>[`MaxErrorClassBytes`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#MaxErrorClassBytes) | 240: a longer class is cut at a rune boundary and ends in `…`, so it stays a usable search filter |

## Status

[`obsdb.Status`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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 |
|---|---|---|
| <span id="statusrunning"></span>[`StatusRunning`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#StatusRunning) | `running` | Derived: heard from within `InterruptedAfter` |
| <span id="statussucceeded"></span>[`StatusSucceeded`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#StatusSucceeded) | `succeeded` | Derived: `run_finish` stored, or a root that did not error |
| <span id="statusfailed"></span>[`StatusFailed`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#StatusFailed) | `failed` | Derived: the root span ended with error |
| <span id="statusinterrupted"></span>[`StatusInterrupted`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#StatusInterrupted) | `interrupted` | Derived: neither, and silent past `InterruptedAfter` |
| <span id="statusparked"></span>[`StatusParked`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#StatusParked) | `parked` | Filter only: an open [park](https://weftgo.dev/docs/reference/glossary/#park), succeeded with `Pending > 0` and no resumer (`ResumedBy` empty) |
| <span id="statuscancelled"></span>[`StatusCancelled`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#StatusCancelled) | `cancelled` | Filter only: failed with `error_type` `cancelled` |
| <span id="statuswords"></span>[`StatusWords`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#StatusWords) | var | Every word `RunQuery.Status` takes, in the order an error names them: the four derived, then `parked` and `cancelled` |
| <span id="parsestatus"></span>[`ParseStatus(s)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#ParseStatus) | 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()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#Status.Stored) | method | The derived status a filter word narrows: `parked` reads succeeded runs, `cancelled` failed ones; the four derived are themselves |
| <span id="errortypecancelled"></span>[`ErrorTypeCancelled`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#ErrorTypeCancelled) | `cancelled` | The run row's `ErrorType` when the root span names `context.Canceled` or `context.DeadlineExceeded`; `CancelCause` names which cancel |
| <span id="interruptedafter"></span>[`InterruptedAfter`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#InterruptedAfter) | 30 s | The last-seen age that turns a non-terminal run [interrupted](https://weftgo.dev/docs/reference/glossary/#interrupted): three missed heartbeats. Also the settling window |

## Caps and constants

| Constant | Value | Bounds |
|---|---|---|
| <span id="maxties"></span>[`MaxTies`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#MaxTies) | 500 | How far a `RunPage`, `SessionPage` or `TracePage` runs past its `Limit` to finish a group sharing the cursor's time |
| <span id="maxgaps"></span>[`MaxGaps`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#MaxGaps) | 1,000 | `EventPage.Gaps`: one stray high position never turns a page into a list of every position below it |
| <span id="treespancap"></span>[`TreeSpanCap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#TreeSpanCap) | 10,000 | Spans in one `RunTreeSpans` answer, the first in start order; more sets `RunTree.Truncated` (Studio's `truncated` hole, cause `response_cap`) |
| <span id="treerowcap"></span>[`TreeRowCap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#TreeRowCap) | 10,000 | Run rows one `RunTreeSpans` read takes of a weft run's tree, in row order; more sets `Truncated` |
| <span id="treetracecap"></span>[`TreeTraceCap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#TreeTraceCap) | 50,000 | Spans a derived run's tree reads of its trace before cutting the subtree; more sets `RunTree.TraceTruncated` |
| <span id="treemissingcap"></span>[`TreeMissingCap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#TreeMissingCap) | 100 | `RunTree.Missing`, the first by start; `MissingCount` has the whole count |
| <span id="childrunscap"></span>[`ChildRunsCap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#ChildRunsCap) | 10,000 | Child rows in one `ChildRuns` call over every parent it names; more is `ErrChildRunsCapped` and no map |
| <span id="sweepbatch"></span>[`SweepBatch`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#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`](#maxlogcandidates), [`LogSkew`](#logskew) | 10,000, 1 min | The app-log scan ([Logs](#logs)) |
| [`InterruptedAfter`](#interruptedafter) | 30 s | Status ([Status](#status)) |
| [`MaxSearchTerms`](#maxsearchterms), [`MaxSearchTermBytes`](#maxsearchtermbytes), [`MaxSearchOffset`](#maxsearchoffset), [`PromptPreviewRunes`](#promptpreviewrunes) | 16, 256, 100,000, 200 | Search ([`SearchQuery`](#searchquery)) |
| <span id="stockerrnodescription"></span>[`StockErrNoDescription`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#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 |

| <span id="treecutparent"></span>[`TreeCutParent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#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 |
| <span id="recordthread"></span>[`RecordThread`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#RecordThread) | `thread` | The `weft.record` of `thread`'s session records, the state log (since 0.18.0) |
| <span id="attrchatrole"></span>[`AttrChatRole`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#AttrChatRole), <span id="chatrolesummarizer"></span>[`ChatRoleSummarizer`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#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`](https://weftgo.dev/docs/reference/obsdb-records/#queuesize) (default 1,000), and the other record-kind constants are on [obsdb record and span types](https://weftgo.dev/docs/reference/obsdb-records/).

## Errors

| Error | Match with | Returned when |
|---|---|---|
| <span id="errnotfound"></span>[`ErrNotFound`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#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 |
| <span id="errclosed"></span>[`ErrClosed`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#ErrClosed) | `errors.Is` | A backend used after `Close`, or racing it |
| <span id="errinvalidstatus"></span>[`ErrInvalidStatus`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#ErrInvalidStatus) | `errors.Is` | `ParseStatus` for a word outside `StatusWords`; its message names them: `status must be running, succeeded, failed, interrupted, parked or cancelled` |
| <span id="errinvalidsearch"></span>[`ErrInvalidSearch`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#ErrInvalidSearch) | `errors.Is` | `ParseSearch` and `Search` for a query outside the grammar or its bounds; Studio answers it 400 |
| <span id="errinvalidstats"></span>[`ErrInvalidStats`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#ErrInvalidStats) | `errors.Is` | `CheckStats` and `Aggregator.Stats` for a query outside their bounds; Studio answers it 400 |
| <span id="errchildrunscapped"></span>[`ErrChildRunsCapped`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#ErrChildRunsCapped) | `errors.Is` | `ChildRuns` past `ChildRunsCap`: read those parents' children as not known, never as a part |
| <span id="errinvalidcommand"></span>[`ErrInvalidCommand`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#ErrInvalidCommand) | `errors.Is` | A `CommandStore` write whose row lacks its key, or whose command state is not one of the five |
| <span id="errinvalidmanifest"></span>[`ErrInvalidManifest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#ErrInvalidManifest) | `errors.Is` | `PutManifest` of a body that is not a JSON object or whose hash is not its sha256 |
| <span id="errstepmessages"></span>[`ErrStepMessages`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#ErrStepMessages) | `errors.Is` | The stored records do not rebuild the messages a step's request names; every [`*StepMessagesError`](https://weftgo.dev/docs/reference/badges/#stepmessageserror) matches it |
| [`*HoleError`](https://weftgo.dev/docs/reference/badges/#holeerror) | `errors.As` | `Prompt`, `Tools`, `OtherLogs` and `CountLogs` when the reader knows why a record is missing; `errors.Is(err, ErrNotFound)` holds |
| [`sqlite.ErrNewerSchema`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#ErrNewerSchema) | `errors.Is` | `sqlite.Open` on a file migrated by a newer weft |
| [`clickhouse.ErrNewerSchema`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/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

Package [`obsdbtest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/obsdbtest) is the shared [conformance suite](https://weftgo.dev/docs/reference/glossary/#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:

```go title="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](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/obsdb/main_test.go)

`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)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/obsdbtest#Run) | 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)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/obsdbtest#CheckTurnFactFilters) | 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)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/obsdbtest#SummarizerSpanIsNotRunFact) | 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)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/obsdbtest#CommandsRestart) | 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)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/obsdbtest#CommandsPruneRace) | `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

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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#example-ParseStatus) | `parked` parses and narrows to `succeeded`; `completed` is `ErrInvalidStatus` naming the six words |
| [`ExampleDB_Write`](https://github.com/weftgo/weft/blob/v0.20.2/obsdb/example_test.go#L114) | A `run_start` event and a messages record written in one batch, read back through `Events` and `Transcript` |
| [`ExampleDB_Requests`](https://github.com/weftgo/weft/blob/v0.20.2/obsdb/example_test.go#L175) | A content-off copy's request records read `stripped`, and `Prompt` answers a `*HoleError` matching `ErrNotFound` |
| [`ExampleMessagesAsOf`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#example-MessagesAsOf) | The messages each step's model call carried, a compaction view applied at step 1 |
| [`ExampleSearcher`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#example-Searcher) | The two terms `refund failed` (each a substring, unquoted) find one of two runs; the row carries its prompt preview |
| [`ExampleCutRunTree`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#example-CutRunTree) | A trace's spans cut to one run's subtree, each keyed by its run and that run's parent |
| [`ExampleCommandStore`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#example-CommandStore) | 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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#example-CheckToolArgs) | A playground `tool_args` edit checked against a tool's stored schema, refused in the loop's wording |
| [`ExampleTreeMembers`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#example-TreeMembers) | A tree's members from the rows alone: the parent chain first, then core's id rule |
| [`ExampleSessionQuery (meta)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#example-SessionQuery-Meta) | Since 0.20.0: `SessionQuery.Meta` groups a session over its tagged turns only, for a batch that started mid-session |
| [`ExampleAttrTrue`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#example-AttrTrue) | A weft flag read the same in both spellings: the bool `true` and the string `"true"` are set, an absent key is not |
| [`ExampleSessionTurnFacts`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#example-SessionTurnFacts) | 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)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#example-SessionQuery-States) | `SessionQuery`'s `Compacted` and `Status` filters keep a compacted session, and `SessionEventQuery.Kinds` reads its compaction marker alone |
| [`ExampleSessionEventReader`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#example-SessionEventReader) | A session's state log in record time, a runless record among it; `RunIDs` narrows to one turn's events |
| [`ExampleAggregator`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#example-Aggregator) | Per-agent stats over a day from the stored spans, and two usage-limit failures folded into one error class |
| [`ExampleErrorClass`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#example-ErrorClass) | Error texts as classes: numbers `N`, quoted names kept |
| [`ExampleStockToolContent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#example-StockToolContent) | 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

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

| Function | Meaning |
|---|---|
| [`CheckToolArgs`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#PromptPreview) | Cuts a prompt to `PromptPreviewRunes` runes, the cut both backends make in SQL |
| [`PromptText`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#PromptText) | The turn's own prompt as one messages record body holds it |
| [`TurnPrompt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#TurnPrompt) | A run's prompt from its input record and the next one: the resume rule |
| [`LastAssistantText`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#LastAssistantText) | The text of a body's last assistant message with text: the run's answer |
| [`SessionContentOff`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#SessionContentOff) | `SessionRow.ContentOff`'s rule over the session's first turn |
| [`RunErrorType`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#RunErrorType) | The run row's `error_type` for a root span's `error.type`, context errors read as `cancelled` |
| [`LimitOf`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#LimitOf) | Normalizes a list limit: 0 or negative is 50, above 500 is 500 |
| [`DeriveStatus`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DeriveStatus) | The four-row status table every backend reads through |
| [`DeriveSettling`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DeriveSettling) | `RunRow.Settling`'s rule |
| [`ReadOtherLogs`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#ReadOtherLogs) | `DB.OtherLogs` for every backend: attribution, order, index and paging over a backend's `LogCandidates` |
| [`CountOtherLogs`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#CountOtherLogs) | `DB.CountLogs` for every backend, over a severity-filtered scan |
| [`SpanProblems`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#SpanProblems) | The problem tokens one weft span contributes to its run's `Problems` |
| [`CountProblems`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#CountProblems) | Folds a run's problem tokens into its counters; duplicates count once |
| [`DeletedSpans`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DeletedSpans) | The spans a deletion takes: the deleted runs' own and the non-weft spans below them |
| [`StepRange`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#StepRange) | The smallest and largest `Step` of a page of request records |
| [`SortCompactions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#SortCompactions) | Orders `DB.Compactions`' answer: views by index, then session markers |
| [`NonMetaKeys`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#NonMetaKeys) | The record and span contract keys `MetaOf` leaves out of a row's metadata |
| [`MetaOf`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#MetaOf) | The caller metadata a set of attributes carries |
| <span id="stockhasmessages"></span>[`StockHasMessages`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#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 |
| <span id="stocktoolcontent"></span>[`StockToolContent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#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 |
| <span id="stocknotrun"></span>[`StockNotRun`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#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 |
| <span id="stockfoldedruns"></span>[`StockFoldedRuns`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#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 |
| <span id="stockrunprefix"></span>[`StockRunPrefix`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#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

`MessagesAsOf`, the stock derivation functions (on [obsdb record and span types](https://weftgo.dev/docs/reference/obsdb-records/)) 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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#TreeIDRule) | The parent core's id rule gives an id inside a run's subtree |
| [`TreeChildID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#TreeChildID) | Whether an id has the shape core gives a child run of a parent |
| [`TreeMembers`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#TreeMembers) | A run's subtree from the parents a backend knows |
| [`TreeMemberIDs`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#TreeMemberIDs) | `TreeMembers`' ids, sorted |
| [`TreeReadIDs`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#TreeReadIDs) | The run ids a backend reads a tree's spans by, scope applied |
| [`CutRunTree`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#CutRunTree) | Cuts spans to one run's subtree |
| [`CapTree`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#CapTree) | A backend's last step: cut, scope, cap and `Missing` |
| [`LostRecordsHole`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#LostRecordsHole) | The hole of a weft run whose spans were stored and none of its records |
| [`TailLostHole`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#TailLostHole) | The hole of a weft run whose event records a destination dropped |
| [`EventsLostHole`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#EventsLostHole) | The counted event gap: fewer events stored than the root says were emitted |
| [`MessagesLostHole`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#MessagesLostHole) | The counted transcript gap: some messages records stored, fewer than emitted |
| [`EventsLostReason(r, below)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#EventsLostReason) | 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)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#MessagesLostReason) | `MessagesLostHole` in words: `K of N transcript batches were lost: …`. `""` when that hole is not raised |
| [`ExplainMissing`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#ExplainMissing) | The error `Prompt` and `Tools` return for a hash the run holds no record of |
| [`MetadataCapReason`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#MetadataCapReason) | The `metadata_cap` hole's reason with its count |
| <span id="attrtrue"></span>[`AttrTrue(m, k)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#AttrTrue) | 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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#example-AttrTrue) prints `true true false`: a bool, the string, an absent key |

## Complete example

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

```go title="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
}
```

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

[View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/obsdb) · run it from `docs-site/examples`:

```sh
go run ./obsdb
go test ./obsdb
```

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

## Best practices & gotchas

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

## See also

- [obsdb record and span types](https://weftgo.dev/docs/reference/obsdb-records/)
- [Choose the observability database: SQLite or ClickHouse](https://weftgo.dev/docs/production/storage-backends/)
- [Keep and delete recorded runs](https://weftgo.dev/docs/production/retention/)
- [Badges and holes](https://weftgo.dev/docs/reference/badges/)
- [Studio HTTP API](https://weftgo.dev/docs/reference/studio-api/)

Symbols used: [`obsdb.DB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DB) · [`obsdb.Searcher`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#Searcher) · [`obsdb.TreeReader`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#TreeReader) · [`obsdb.CommandStore`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#CommandStore) · [`obsdb.ManifestStore`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#ManifestStore) · [`obsdb.Hub`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#Hub) · [`obsdb.RunQuery`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#RunQuery) · [`obsdb.SearchQuery`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#SearchQuery) · [`obsdb.SessionQuery`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#SessionQuery) · [`obsdb.TraceQuery`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#TraceQuery) · [`obsdb.TreeQuery`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#TreeQuery) · [`obsdb.RunRow`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#RunRow) · [`obsdb.Batch`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#Batch) · [`obsdb.Record`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#Record) · [`sqlite.Open`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#Open) · [`clickhouse.Open`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#Open) · [`obsdbtest.Run`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/obsdbtest#Run) · [`otel.LocalDB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#LocalDB) · [`studio.DB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#DB)
