Record every run with otel.Install
otel.Install starts weft’s observability pipeline and registers it as the process’s OpenTelemetry providers. With no option and no destination named by the environment, defer otel.Install()() writes every run to the local sink, a SQLite file at ./.weft/weft.db, content on, no network: each event, transcript batch and span is written as it happens. otel.LocalDB hands back the database, and the recorded run reads back through obsdb.DB.
Record a run and read it back, in recording/main.go:
defer otel.Install(otel.Local(""))() // the local sink: $WEFT_DB, else ./.weft/weft.db
agt := weft.New(script(), weft.Name("support-bot"), lookup)res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"))if err != nil { return err}
db := otel.LocalDB() // the pipeline's own handle on the sinkrec, err := db.Run(ctx, res.ID)if err != nil { return err}fmt.Fprintln(w, rec.Agent, rec.Status, "steps:", rec.Steps, "events:", rec.EventCount, "transcript batches:", rec.MessageCount)
page, err := db.Events(ctx, res.ID, -1, 50) // -1: from the first eventif err != nil { return err}var types []stringfor _, e := range page.Events { types = append(types, eventType(e.Event))}fmt.Fprintln(w, strings.Join(types, " "))
spans, err := db.RunSpans(ctx, res.ID)if err != nil { return err}for _, s := range spans { fmt.Fprintln(w, "span:", s.Name)}The agent needs no option: the core reports through the global OTel providers, and Install registered them. otel.Local("") names the local sink explicitly, which keeps it when the environment adds a destination (below). The run is in the database as soon as Generate returns, because the local sink writes synchronously.
Install
Section titled “Install”otel.Install(opts...) takes otel.Option values: the destinations, the content policy and the pipeline’s settings. It returns a function that flushes every destination and shuts the pipeline down; call it on exit, hence defer otel.Install(...)(). That function waits at most 5 seconds. Install never panics and never fails the program: a destination that cannot be built is logged at WARN and skipped. The package example, ExampleInstall, installs a local sink under otel.NoEnv(), runs a scripted agent, calls the returned function, and reopens the file with obsdb/sqlite to read the run back.
otel.Local(path) is the local sink: obsdb/sqlite at path, or at $WEFT_DB, else ./.weft/weft.db, when path is "". It writes synchronously, so nothing emitted is lost, and it holds content: message text, tool arguments and results, the system prompt and the catalog.
What the pipeline receives from each run:
- Spans. One
invoke_agentspan per run, onechatspan per model call, oneexecute_toolspan per tool call, and anattemptspan underchatfor each try thatmw.Retry,mw.Fallbackor an adapter reports; all with ids, names, counts, durations and error types but never content. Use your own OpenTelemetry SDK lists their attributes. - Event records. Every durable event, from
run_starttorun_finish, is one log record whose body is the event’s wire JSON, numbered byweft.event.posfrom 0. Deltas (text_delta,reasoning_delta,tool_args_delta) are records on their own counter,weft.delta.pos, so dropping them never opens a hole in the durable sequence. The local sink counts deltas and stores none. - Transcript records. A
weft.messagesrecord at each point the transcript grows: the input at run start, each assistant message, each tool message, each steered batch, the tool message a resume builds. Concatenated, their bodies equalRunResult.Messagesbyte for byte. They are emitted only when some destination takes content, and none after the run’s context ends. - Request records. What each model call was given: the request, the system prompt and the tool catalog, by hash (the record contract §4).
Tool-call arguments that are not JSON do not drop records: the tool_start event, the assistant’s transcript batch and later input records carry the raw bytes as a JSON string.
A store keys every record on (run id, kind, position), so a record exported twice is stored once. Each positioned kind’s positions run from 0 without gaps (heartbeats and thread’s compaction markers have no position); a hole below the highest position is a lost record, and Studio badges it gap.
Read a run back
Section titled “Read a run back”otel.LocalDB() returns the installed pipeline’s obsdb.DB: the same handle the local sink writes. It is nil before Install, after its shutdown, and in a pipeline without a local sink. The interface reads what Studio reads: Runs and Run (the run row, with its derived status and its subagent children), Events (positioned pages; -1 reads from the first), Transcript, RunSpans, OtherLogs (your app log lines), sessions and traces.
After the process exits, the file reopens with sqlite.Open, and weft studio serves it: its default database is the same ./.weft/weft.db.
To serve Studio inside the app over the same handle, mount studio.Handler(studio.DB(otel.LocalDB())). Studio then sees each run live as the pipeline writes it (Run Studio).
otel.StudioEndpoint() returns the URL and token of the installed pipeline’s Studio destination, "" without one. weft/runtime dials that Studio by default (Connect your app to the playground).
What the environment adds
Section titled “What the environment adds”Install and Start read the environment for extra destinations: WEFT_STUDIO_URL adds a Studio, OTEL_EXPORTER_OTLP_ENDPOINT an OTLP endpoint, and with WEFT_STUDIO_URL unset, the discovery file of a running weft studio or weft dev adds that Studio. Environment variables lists every rule. Three of them shape this page:
- A zero-option
otel.Install()writes the local sink only when the environment adds nothing. When it adds a destination, the pipeline exports there instead, andotel.LocalDB()is nil. Passotel.Local("")to keep the local sink beside an environment destination, as the example does. - A store named in code turns discovery off. Since 0.19.0 an explicit
otel.Local, like an explicitotel.Studio, writes only to the stores it names and the environment’s, never into a runningweft studioit found on disk. To write to both, name both:otel.Install(otel.Local(path), otel.Studio(url, tok)), or setWEFT_STUDIO_URL. A pipeline that joins a discovered Studio says so in one INFO line,weft/otel: joined the running Studio;otel.NoDiscovery(),WEFT_DISCOVERY=offorotel.NoEnv()stops it (The discovery file). - The environment and the discovery file are read once, when
InstallorStartbuilds the pipeline. A Studio started later is never joined.
Start in tests
Section titled “Start in tests”otel.Start is Install that returns errors: any destination that fails to build fails the call, and what was already built is shut down. otel.NoGlobal() leaves the OTel globals alone, so you pass the pipeline’s providers to the agent. A test that records to its own database, in recording/main_test.go:
p, err := otel.Start(ctx, otel.NoEnv(), // no WEFT_* / OTEL_* variable or discovery file adds a destination otel.NoGlobal(), // the OTel globals stay as they were otel.Local(filepath.Join(dir, "weft.db")),)if err != nil { t.Fatal(err)}defer func() { _ = p.Shutdown(ctx) }()
agt := weft.New(script(), weft.Name("support-bot"), lookup, weft.TracerProvider(p.TracerProvider()), // hand the agent this pipeline's providers weft.LoggerProvider(p.LoggerProvider()),)res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"))if err != nil { t.Fatal(err)}rec, err := p.LocalDB().Run(ctx, res.ID)if err != nil { t.Fatal(err)}if rec.Status != obsdb.StatusSucceeded || rec.Steps != 2 { t.Fatalf("recorded %s in %d steps, want succeeded in 2", rec.Status, rec.Steps)}otel.NoEnv() ignores the WEFT_* and OTEL_* destination variables and the discovery file, so no destination joins the test from outside. Under NoGlobal, otel.LocalDB() and otel.StudioEndpoint() see no pipeline; use the methods of the *otel.Pipeline:
| Method | Returns or does |
|---|---|
TracerProvider() | the pipeline’s *sdktrace.TracerProvider, for weft.TracerProvider |
LoggerProvider() | the pipeline’s *otel.LoggerProvider, for weft.LoggerProvider |
LocalDB() | the local sink’s obsdb.DB; nil without one |
StudioEndpoint() | the Studio destination’s URL and token; "" without one |
SlogHandler(next) | a slog.Handler bridged to this pipeline (app logs) |
ForceFlush(ctx) | flushes every destination at once, each on its own goroutine, so a hung destination costs only its own data |
Shutdown(ctx) | stops heartbeats, flushes every destination in parallel (5 s budget), shuts the providers down, closes the local database last; runs once, every wait bounded by ctx |
Heartbeats
Section titled “Heartbeats”A run that waits 45 seconds on a tool emits nothing for 45 seconds. So the pipeline’s run tracker emits one weft.heartbeat record per open run every 10 seconds, carrying the run’s id and identity attributes and no body. A reader moves the run’s last-seen time on each one and never stores it. Three missed intervals, 30 seconds of silence, is what obsdb reads as interrupted: a crashed process stops beating, and its runs stop reading running.
otel.Heartbeat(d) sets the interval; 0 or less turns heartbeats off. Keep it well under 30 seconds: the 30-second rule is fixed in obsdb (InterruptedAfter), not three times your interval, so with a longer interval a quiet run reads interrupted between beats. A run that is sampled out and then fails or is cancelled leaves the tracker too, so it never heartbeats forever. A destination that has lost records adds its count, weft.records.dropped, to its copy of each heartbeat (queues).
Complete example
Section titled “Complete example”// Command recording runs the example of the guide "Record every run with// otel.Install": go run ./recording. The model is scripted with// wefttest, so it runs offline; the run is recorded to ./.weft/weft.db// (or $WEFT_DB) and read back from it.package main
import ( "context" "encoding/json" "fmt" "io" "log" "os" "strings"
"github.com/weftgo/weft" "github.com/weftgo/weft/otel" "github.com/weftgo/weft/wefttest")
// LookupInput is the lookup tool's argument.type LookupInput struct { OrderID string `json:"order_id" jsonschema:"the order to look up"`}
var lookup = weft.Tool("lookup_order", "Look up an order by ID.", func(_ context.Context, in LookupInput) (string, error) { return "order " + in.OrderID + " has shipped", nil })
// script is a two-step dialogue: one tool call, then an answer.func script() *wefttest.Model { return wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "lookup_order", Args: `{"order_id":"1234"}`}), wefttest.Say("Order 1234 has shipped."), )}
func main() { if err := run(context.Background(), os.Stdout); err != nil { log.Fatal(err) }}
// run records one run with otel.Install and reads it back from the// local sink.func run(ctx context.Context, w io.Writer) error { defer otel.Install(otel.Local(""))() // the local sink: $WEFT_DB, else ./.weft/weft.db
agt := weft.New(script(), weft.Name("support-bot"), lookup) res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")) if err != nil { return err }
db := otel.LocalDB() // the pipeline's own handle on the sink rec, err := db.Run(ctx, res.ID) if err != nil { return err } fmt.Fprintln(w, rec.Agent, rec.Status, "steps:", rec.Steps, "events:", rec.EventCount, "transcript batches:", rec.MessageCount)
page, err := db.Events(ctx, res.ID, -1, 50) // -1: from the first event if err != nil { return err } var types []string for _, e := range page.Events { types = append(types, eventType(e.Event)) } fmt.Fprintln(w, strings.Join(types, " "))
spans, err := db.RunSpans(ctx, res.ID) if err != nil { return err } for _, s := range spans { fmt.Fprintln(w, "span:", s.Name) } return nil}
// eventType reads the "type" discriminator of an event's wire JSON.func eventType(body []byte) string { var ev struct { Type string `json:"type"` } _ = json.Unmarshal(body, &ev) return ev.Type}From docs-site/examples:
go run ./recordinggo test ./recordingsupport-bot succeeded steps: 2 events: 8 transcript batches: 4run_start step_start tool_start tool_finish step_finish step_start step_finish run_finishspan: invoke_agent support-botspan: chat scriptspan: execute_tool lookup_orderspan: chat scriptThe run took two steps, so its row reads 2. Eight durable events, four transcript batches (the prompt, the assistant’s tool call, the tool result, the answer) and four spans were written. go run leaves the recording in ./.weft/weft.db; weft studio, started in the same directory, serves it.
Best practices & gotchas
Section titled “Best practices & gotchas”- Name the local sink when you read it. With
WEFT_STUDIO_URL,OTEL_EXPORTER_OTLP_ENDPOINTor a runningweft studio, a zero-optionInstallwrites no local sink, andotel.LocalDB()is nil;studio.DB(nil)makesstudio.Newpanic.otel.Install(otel.Local(""))keeps it. (Source:otel/pipeline.go:218-238, 342-351;TestZeroOptionInstall) - Call the function
Installreturns. It flushes the batch queues of the exporting destinations; a program that exits without it loses what was still queued. (Source:otel.Installgodoc;otel/pipeline.go:364-369) - Use
Startwhere a failure must show.Installlogs a destination that fails to build and goes on without it;Startreturns the error. (Source:otel.Startgodoc) - Name the store in a test, and add
NoEnvto isolate it.otel.Start(ctx, otel.Local(p), otel.NoGlobal())no longer joins a runningweft studiothrough the discovery file (before 0.19.0 it did, and wrote every run twice), but the environment’s destinations still apply: aWEFT_STUDIO_URLorOTEL_EXPORTER_OTLP_ENDPOINTset in the shell still receives the test’s runs. Addotel.NoEnv()to write only top, as the example’s test does. A pipeline whose only destinations areotel.OTLP,Datadog,LangfuseorExportersalso still reads the discovery file:otel.NoDiscovery()stops that alone. (Source:otel/pipeline.go:224-236; CHANGELOG.md:154) - Start
weft studiobefore the app, or restart the app. The discovery file is read once, inInstallorStart. An app started before Studio, or still running when Studio comes back on another port, never exports to it, and nothing above Debug says so.weft devis not affected: it binds Studio before it starts the app, passesWEFT_STUDIO_URL, and starts a new process on each reload. (Source:otel/pipeline.go:218-236;otel/env.go:151-176;cmd/weft/dev.go:156-183) - Keep
Heartbeat(d)well under 30 s.obsdb.InterruptedAfteris a fixed 30 s whatever the interval; a slower beat makes a quiet run readinterrupted. (Source:obsdb/db.go:998;otel.Heartbeatgodoc) - Do not expect deltas in the database. Deltas are counted on the run row (
DeltaCount) and never stored. (Source:obsdb.DBgodoc,Write)
See also
Section titled “See also”- Send records to Studio, Datadog, Langfuse or any OTLP backend: more destinations, each with its own content policy
- Run Studio: embedded, local binary or hosted
- Bridge your app’s slog lines into runs
- Environment variables
- The record contract: every span, record and attribute
Symbols used: otel.Install · otel.Start · otel.Option · otel.Local · otel.LocalDB · otel.StudioEndpoint · otel.NoEnv · otel.NoGlobal · otel.Heartbeat · otel.Pipeline · obsdb.DB · sqlite.Open · studio.Handler · studio.DB · weft.TracerProvider · weft.LoggerProvider · ExampleInstall