Skip to content

Record every run with otel.Install

View as Markdown

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:

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

recording/main.go on GitHub

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.

Recording: the app's runs go through otel.Install to the local sink or a Studio, and the Inspector reads them back.Your app runs agents with agt.Generate; every run leaves as OpenTelemetry spans and log records. otel.Install starts the pipeline and sends them to every destination at once; with no options and no destination named by the environment it writes the local sink only. otel.Local writes .weft/weft.db synchronously; otel.Studio exports OTLP over HTTP to a running weft studio. The Inspector reads them back: embedded with studio.Handler over otel.LocalDB(), or served by weft studio.
otel.Install's pipeline: the run's spans and log records go to every destination at once; the Inspector reads the local sink back.

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_agent span per run, one chat span per model call, one execute_tool span per tool call, and an attempt span under chat for each try that mw.Retry, mw.Fallback or 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_start to run_finish, is one log record whose body is the event’s wire JSON, numbered by weft.event.pos from 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.messages record 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 equal RunResult.Messages byte 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.

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

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, and otel.LocalDB() is nil. Pass otel.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 explicit otel.Studio, writes only to the stores it names and the environment’s, never into a running weft studio it found on disk. To write to both, name both: otel.Install(otel.Local(path), otel.Studio(url, tok)), or set WEFT_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=off or otel.NoEnv() stops it (The discovery file).
  • The environment and the discovery file are read once, when Install or Start builds the pipeline. A Studio started later is never joined.

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:

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

recording/main_test.go on GitHub

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:

MethodReturns 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

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

recording/main.go
// 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
}

View recording/main.go on GitHub

From docs-site/examples:

Terminal window
go run ./recording
go test ./recording
support-bot succeeded steps: 2 events: 8 transcript batches: 4
run_start step_start tool_start tool_finish step_finish step_start step_finish run_finish
span: invoke_agent support-bot
span: chat script
span: execute_tool lookup_order
span: chat script

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

  • Name the local sink when you read it. With WEFT_STUDIO_URL, OTEL_EXPORTER_OTLP_ENDPOINT or a running weft studio, a zero-option Install writes no local sink, and otel.LocalDB() is nil; studio.DB(nil) makes studio.New panic. otel.Install(otel.Local("")) keeps it. (Source: otel/pipeline.go:218-238, 342-351; TestZeroOptionInstall)
  • Call the function Install returns. It flushes the batch queues of the exporting destinations; a program that exits without it loses what was still queued. (Source: otel.Install godoc; otel/pipeline.go:364-369)
  • Use Start where a failure must show. Install logs a destination that fails to build and goes on without it; Start returns the error. (Source: otel.Start godoc)
  • Name the store in a test, and add NoEnv to isolate it. otel.Start(ctx, otel.Local(p), otel.NoGlobal()) no longer joins a running weft studio through the discovery file (before 0.19.0 it did, and wrote every run twice), but the environment’s destinations still apply: a WEFT_STUDIO_URL or OTEL_EXPORTER_OTLP_ENDPOINT set in the shell still receives the test’s runs. Add otel.NoEnv() to write only to p, as the example’s test does. A pipeline whose only destinations are otel.OTLP, Datadog, Langfuse or Exporters also still reads the discovery file: otel.NoDiscovery() stops that alone. (Source: otel/pipeline.go:224-236; CHANGELOG.md:154)
  • Start weft studio before the app, or restart the app. The discovery file is read once, in Install or Start. 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 dev is not affected: it binds Studio before it starts the app, passes WEFT_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.InterruptedAfter is a fixed 30 s whatever the interval; a slower beat makes a quiet run read interrupted. (Source: obsdb/db.go:998; otel.Heartbeat godoc)
  • Do not expect deltas in the database. Deltas are counted on the run row (DeltaCount) and never stored. (Source: obsdb.DB godoc, Write)

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