---
title: Keep and delete recorded runs
description: 'Studio keeps every run until told otherwise: set a retention with studio.Retain or weft studio --retain (at least 1h), delete one run or one session through the API, and give the space back with weft vacuum.'
url: https://weftgo.dev/docs/production/retention/
type: how-to
sources:
  - weft/studio/delete.go:14-17 (obsdb's tables only), 19-29 (capability delete), 31-37 (the notes), 47-61 (mayDelete), 63-101 (DELETE runs and sessions), 112-139 (Retain godoc), 141-147 (minRetention, retainFloorMsg), 149-153 (sweepInterval), 155-204 (the sweeper, Debug and Warn lines, stops on a closed DB)
  - weft/studio/studio.go:254-258 (New panics under 1h), 330-349 (Close stops the sweeper), 304-316 (Handler cannot be closed)
  - weft/obsdb/db.go:123-155 (DeleteRun, DeleteSession, Sweep, Vacuum), 996-998 (InterruptedAfter 30 s), 1000-1006 (SweepBatch 500)
  - weft/obsdb/delete.go:16-30 (DeletedSpans, the non-weft spans and app logs below a run)
  - 'weft/cmd/weft/vacuum.go:20-56 (--retain, WEFT_RETAIN, resolveRetain, usage errors), 57-66 (retainOptions: the banner line), 68-124 (runVacuum: one sweep, then Vacuum, its output lines: the file and the WAL apart, 117; the not-checkpointed line, 118-120), 126-164 (openVacuumDB, no database at …), 167-180 (fileSizes: the file and its -wal sidecar)'
  - 'weft/obsdb/sqlite/delete.go:207-262 (Vacuum: VACUUM, then a PASSIVE and a TRUNCATE WAL checkpoint under a 250 ms busy timeout; a blocked checkpoint is not an error)'
  - 'weft/CHANGELOG.md:66 (0.20.0: vacuum prints the main file and the WAL apart and checkpoints the WAL)'
  - 'weft/obsdb/tree.go:183-191 (TreeCutParent), 264-270 (a cut run is never a member); weft/CHANGELOG.md:234 (0.18.0: TreeCutParent), 260 (0.18.0: every ClickHouse read that lists or opens runs cuts at weft_runs'' TTL)'
  - weft/studio/README.md:238-270 (Retention)
  - weft/AGENTS.md:223-228 (Retain), 444-447 (weft vacuum, stored manifests never swept, make vacuum, --retain and WEFT_RETAIN)
  - weft/CHANGELOG.md:577 (Sweep counts derived rows, 0.15.0), 1084 (DELETE runs and sessions, 0.14.0), 1098 (Retain, 0.14.0), 1114 (weft vacuum, 0.14.0), 1187 (passes of SweepBatch), 4417 (clickhouse.TTL, 0.7.0)
  - weft/studio/example_test.go:81 (ExampleRetain)
  - weft/studio/delete.go:155-185 (the first sweep runs in the sweeper goroutine)
  - weft/cmd/weft/vacuum.go:109-123 (the sizes before and after Vacuum; ClickHouse prints optimized); cmd/weft/main.go:471, 494 (weft studio prints retainOptions' line in its banner notes); cmd/weft/dev.go:134 (weft dev discards that line)
  - weft/obsdb/sqlite/delete.go:207-211 (VACUUM needs the file to itself); obsdb/sqlite/sqlite.go:169 (busy_timeout 30000)
  - 'weft/AGENTS.md:248-253 (stored manifests: DELETE runs/sessions and Retain never touch them)'
  - 'observed: weft v0.17.0 vacuum --db sqlite://weft.db --retain 1h (exit 0), --retain 30m (exit 2), --db sqlite://missing.db (exit 1), 2026-10-18'
  - 'observed: weft v0.20.2 (go build ./cmd/weft at 13af06ea) vacuum --db sqlite://weft.db --retain 1h on a scratch database weft studio created, exit 0, 2026-10-27'
  - docs-site/examples/production/main.go (retention, sweepAndVacuum), main_test.go TestProduction, TestRetainFloorPanics
---

# Keep and delete recorded runs

Studio keeps every recorded run until told otherwise. [`studio.Retain(d)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#Retain), or `--retain d` on `weft studio` and `weft dev`, starts a sweeper that deletes the runs that are not running and were last seen more than `d` ago; `d` must be at least an hour. `DELETE /api/runs/{id}` and `DELETE /api/sessions/{id}` remove one run or one session now, and `weft vacuum` gives the freed space back to the disk.

Keep 30 days of runs, in `production/main.go`:

```go title="production/main.go"
srv := studio.New(studio.DB(db), studio.Retain(30*24*time.Hour)) // sweeps at New, then hourly
defer func() { _ = srv.Close() }()                               // Close stops the sweeper
```

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

The example records one run and builds this Studio; a run seen seconds ago is never swept, so it is kept. It then sweeps as the clock would read 30 days later and finds nothing left.

## Retain

The sweeper deletes, as `DELETE /api/runs/{id}` does, every run whose status is not running (succeeded, failed or interrupted) and whose `last_seen` is older than `d`, with its children that are not running. It sweeps once when `New` returns, then every `min(d/10, 1h)`, never more often than once a minute: hourly for any retention of 10 hours or more.

| Retention | Sweeps every |
|---|---|
| `1h` | 6 minutes |
| `24h`, `720h` | 1 hour |

The 1-hour floor follows from how a run reads as finished. A run silent for 30 seconds (three missed heartbeats, [`obsdb.InterruptedAfter`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#InterruptedAfter)) reads interrupted, and interrupted counts as not running, so a short retention would sweep a live run paused at a breakpoint. Below the floor:

- `studio.New` panics: `studio: retention must be at least 1h: the sweeper's not-running rule counts a run silent for 30 s as interrupted, so a short retention would sweep a live run paused at a breakpoint`.
- `--retain 30m` or `WEFT_RETAIN=30m` on `weft studio`, `weft dev` or `weft vacuum` is a usage error with the same words, exit 2. A value that is not a Go duration, or is negative, is a usage error too.

```sh
weft studio --db sqlite:///var/lib/weft/weft.db --retain 720h
```

`WEFT_RETAIN=720h` is the same; the flag wins when both are set. On `weft studio` the banner then says `studio: retention 720h0m0s: runs that are not running and were last seen longer ago are deleted (studio's tables only)`; `weft dev` applies the retention without printing that line. `/api/meta`'s `retention` reports it as a Go duration string, `"720h0m0s"`, and `null` when off.

What else to know about a sweep:

- **It works in passes.** Each pass deletes at most [`obsdb.SweepBatch`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#SweepBatch) (500) root runs with their subtrees, one writer transaction each on SQLite, so ingest proceeds between passes. So a large first sweep never blocks ingest for its whole length. On an error, the passes before it stay deleted.
- **It logs.** One Debug line on `slog.Default` per sweep with its count (`deleted_runs`); a failed sweep logs one Warn line and the server keeps serving.
- **A running child stays.** A running child of a swept parent keeps its own subtree and is swept on its own once it ends. Until then it is listed only under `all=1` (or `parent=*`), never among the top-level runs.
- **The count includes derived rows.** A stock agent's derived run under a deleted run's tool is deleted with it and counted.
- **Stored manifests are never swept.** Nor are they removed by `DELETE`.
- **It runs until `Server.Close`.** Build a Studio with `Retain` through `studio.New` and close it. Under `studio.Handler(...)` nothing can close the server; its sweeper stops, with one Debug line, only once the database is closed.

The package example [`ExampleRetain`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#example-Retain) builds a Studio with `Retain` and reads the retention back from `/api/meta`.

### ClickHouse TTLs

On ClickHouse the tables also carry their own TTLs: content (`otel_logs`, `weft_records`, `weft_deltas`) 30 days, spans and runs 90 days by default, set with `clickhouse.TTL(content, meta)`. Retention is additive: a sweep deletes with a lightweight `DELETE FROM … WHERE` (ClickHouse 23.3 or later) and leaves the TTLs as they are.

Since 0.18.0 every ClickHouse read that lists or opens runs cuts at the runs table's TTL, whether or not a merge has dropped the rows yet: the runs list and search, the sessions list and a session's page, a run and its children, the run tree and public-id lookups. A run past its window is no longer listed, counted or opened (`404`), and a child under a cut parent goes with it, so `children[]`, `children_count`, `?tree=1` and the cost all drop it together. A parked run whose resume was cut reads parked again. Each read cuts at one instant on the ClickHouse server's clock. A backend marks such a run with [`obsdb.TreeCutParent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#TreeCutParent) when it builds a run tree: found but not shown, and no member of the tree. A run's own records and spans still read by id until the merge drops them. SQLite cuts nothing; its runs go only through a sweep or `DELETE`. [Choose the observability database](https://weftgo.dev/docs/production/storage-backends/) covers the backend.

## Sweep and vacuum once

`weft vacuum` is the one-shot form: one sweep when a retention is given, then the backend's vacuum. Run it from cron or a maintenance job:

```sh
weft vacuum --db sqlite://weft.db --retain 1h
```

```text
vacuum: swept 0 runs last seen before 2026-10-27T14:37:01Z (retention 1h0m0s)
vacuum: weft.db 270336 → 270336 bytes (WAL 0 → 0 bytes)
```

That output is from a fresh database with no run older than an hour. The second line gives the file and its `-wal` sidecar apart, before and after. On SQLite the vacuum checkpoints the WAL after `VACUUM`, so the file's size after a vacuum is its size on disk. A WAL that a live reader or writer holds, a running Studio's, is not an error: a third line says it is not checkpointed yet and that the next checkpoint folds it into the file. On ClickHouse the second line is `vacuum: <db> optimized` instead. Without `--db` it opens `$WEFT_DB`, else `./.weft/weft.db`, and refuses a file that does not exist rather than create an empty one:

```text
weft: no database at missing.db (nothing to vacuum)
```

That exits 1; a retention under an hour exits 2 with the floor's message. In weft's own repository, `make vacuum` runs it on `$WEFT_DB` or `./.weft/weft.db`.

| Backend | Vacuum does |
|---|---|
| SQLite | `VACUUM`: the whole file is rewritten and shrinks. It needs the file to itself, so it and another process's writer wait on each other, up to the 30 s busy timeout. Other modules' tables in the file keep their contents |
| ClickHouse | `OPTIMIZE TABLE … FINAL` on the tables deletions mutate: every part merged, heavy on a large database |

The same two calls from Go, as Retain's sweeper computes them:

```go title="production/main.go"
cutoff := now.Add(-retain)      // what Retain's sweeper computes each pass
n, err := db.Sweep(ctx, cutoff) // runs not running, last seen before cutoff, with their children
if err != nil {
	return n, err
}
err = db.Vacuum(ctx) // SQLite: VACUUM; ClickHouse: OPTIMIZE TABLE … FINAL
```

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

[`DB.Sweep`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DB) returns how many runs it deleted, children and derived runs included, over every pass.

## Delete runs and sessions

Two routes delete now, under the capability `delete`:

| Route | Deletes |
|---|---|
| `DELETE /api/runs/{id}` | the run and its subagent children, with the runs derived from stock spans under its tools |
| `DELETE /api/sessions/{id}` | every run carrying the session id (`weft.session.id`), children included |

Each removes the run rows, records, search index entries, spans (the non-weft spans below the runs' own too) and the app log lines under them. The answer is 200 with `{deleted, run_id | session_id, note}`; the session's note says the app's conversation store is untouched. An unknown id is 404, and a later read of a deleted run is 404.

```sh
curl -X DELETE -H "Authorization: Bearer $WEFT_STUDIO_TOKEN" http://127.0.0.1:7331/api/runs/r_01J9…
```

Only the dev or server token may delete, or, with no `Token` configured, a request with a loopback `Host` (setup A, without the `AllowOrigins` widening). Every panel token is 403, read or playground, before anything is looked up ([Secure Studio](https://weftgo.dev/docs/production/security/#panel-tokens-and-handoff)).

A live stream following a deleted run emits nothing more unless the app keeps writing to it; a later write starts a new run row under the same id. A run still being written is deleted as it stands.

### Studio's tables only

Deletion, `Retain` and `weft vacuum` touch obsdb's tables only. A SQLite file that also holds `thread`'s sessions keeps them byte-identical. Your conversation store has its own retention: [`thread.Delete`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Delete) removes a session and its entries ([Operate sessions in production](https://weftgo.dev/docs/sessions/operations/#retention)).

## Complete example

The Production pages share one example program; `retention` and `sweepAndVacuum` are this page's:

```go title="production/main.go"
// Command production runs the examples of the Production pages —
// deploying, content and privacy, retention, limits, storage backends
// and Studio operations:
// go run ./production. Every Studio is a stand-in on a loopback port
// over a fresh SQLite file and the model is scripted with wefttest, so
// it runs offline.
package main

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"log"
	"net"
	"net/http"
	"net/http/httptest"
	"os"
	"os/signal"
	"path/filepath"
	"regexp"
	"strings"
	"syscall"
	"time"

	"github.com/weftgo/weft"
	"github.com/weftgo/weft/obsdb"
	"github.com/weftgo/weft/obsdb/sqlite"
	"github.com/weftgo/weft/otel"
	"github.com/weftgo/weft/studio"
	"github.com/weftgo/weft/thread"
	"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"`
}

// lookup returns a customer's email address: the content the pages keep
// out of the records.
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 to jane@example.com", 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() {
	dir, err := os.MkdirTemp("", "weft-production-")
	if err != nil {
		log.Fatal(err)
	}
	defer func() { _ = os.RemoveAll(dir) }()
	// The shutdown example waits for SIGINT or SIGTERM; here it stops
	// itself after one turn so the program ends.
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()
	if err := run(ctx, os.Stdout, dir); err != nil {
		log.Fatal(err)
	}
	if err := runOperations(ctx, os.Stdout, dir); err != nil {
		log.Fatal(err)
	}
}

func run(ctx context.Context, w io.Writer, dir string) error {
	steps := []struct {
		name string
		fn   func(context.Context, io.Writer, string) error
	}{
		{"content policy", contentPolicy},
		{"strip content", stripContent},
		{"hosted studio", hostedStudio},
		{"retention", retention},
		{"tool limits", toolLimits},
		{"graceful shutdown", gracefulShutdown},
	}
	for _, s := range steps {
		fmt.Fprintln(w, "==", s.name)
		if err := s.fn(ctx, w, dir); err != nil {
			return fmt.Errorf("%s: %w", s.name, err)
		}
	}
	return nil
}

// contentPolicy records one run twice: into the local sink with a
// redactor and a cap, and into a third-party OTLP collector with
// content off.
func contentPolicy(ctx context.Context, w io.Writer, dir string) error {
	collectorURL, collectorDB, stopCollector, err := standInStudio(filepath.Join(dir, "collector.db"))
	if err != nil {
		return err
	}
	defer stopCollector()
	path := filepath.Join(dir, "redacted.db")

	email := regexp.MustCompile(`[\w.+-]+@[\w-]+\.[\w.]+`)
	redact := func(kind weft.ContentKind, s string) string {
		return email.ReplaceAllString(s, "[email]") // every content field of every kind
	}
	p, err := otel.Start(ctx,
		otel.Local(path), // content on: the redactor and the cap apply
		otel.OTLP(collectorURL, otel.NoContent()), // a third party: shape only, no content
		otel.Content(otel.ContentConfig{
			MaxBytes: 16 << 10, // one event field, delta, prompt or catalog body; never the transcript
			Redact:   redact,
		}),
		otel.NoEnv(),
	)
	if err != nil {
		return err
	}
	agt := weft.New(script(), weft.Name("support-bot"), lookup,
		weft.TracerProvider(p.TracerProvider()), weft.LoggerProvider(p.LoggerProvider()))
	res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"))
	if err != nil {
		return err
	}
	if err := p.Shutdown(ctx); err != nil {
		return err
	}

	local, err := sqlite.Open(path)
	if err != nil {
		return err
	}
	defer func() { _ = local.Close() }()
	stored, err := everything(ctx, local, res.ID)
	if err != nil {
		return err
	}
	fmt.Fprintln(w, "the model saw:", toolResult(res))
	fmt.Fprintln(w, "local sink holds [email]:", strings.Contains(stored, "[email]"),
		"the address:", strings.Contains(stored, "jane@example.com"))

	rec, err := collectorDB.Run(ctx, res.ID)
	if err != nil {
		return err
	}
	page, err := collectorDB.Events(ctx, res.ID, -1, 50)
	if err != nil {
		return err
	}
	stripped := 0
	for _, e := range page.Events {
		if e.Content == "stripped" {
			stripped++
		}
	}
	fmt.Fprintln(w, "collector:", rec.Status, "events:", rec.EventCount, "stripped:", stripped,
		"transcript batches:", rec.MessageCount)
	return nil
}

// stripContent shows the core's content table and the agent-side veto.
func stripContent(ctx context.Context, w io.Writer, dir string) error {
	path := filepath.Join(dir, "vetoed.db")
	p, err := otel.Start(ctx, otel.Local(path), otel.NoEnv(), otel.NoGlobal()) // Local: content on
	if err != nil {
		return err
	}
	tp, lp := p.TracerProvider(), p.LoggerProvider()

	ev := weft.ToolFinish{Seq: 4, CallID: "call_1", Name: "lookup_order",
		Content: "order 1234 has shipped to jane@example.com"}
	out := weft.StripContent(ev).(weft.ToolFinish) // what a content-off destination receives
	fmt.Fprintf(w, "stripped: name=%s call=%s content=%q\n", out.Name, out.CallID, out.Content)

	// This agent's records never carry content, whatever a destination asks for.
	payroll := weft.New(script(), weft.Name("payroll-bot"), lookup,
		weft.Content(false),
		weft.TracerProvider(tp), weft.LoggerProvider(lp))

	res, err := payroll.Generate(ctx, weft.Prompt("Where is order 1234?"))
	if err != nil {
		return err
	}
	if err := p.Shutdown(ctx); err != nil {
		return err
	}
	db, err := sqlite.Open(path)
	if err != nil {
		return err
	}
	defer func() { _ = db.Close() }()
	rec, err := db.Run(ctx, res.ID)
	if err != nil {
		return err
	}
	stored, err := everything(ctx, db, res.ID)
	if err != nil {
		return err
	}
	fmt.Fprintln(w, "content(false):", rec.Status, "events:", rec.EventCount, "transcript batches:", rec.MessageCount,
		"the address stored:", strings.Contains(stored, "jane@example.com"))
	return nil
}

// hostedStudio is setup C: a Studio behind a Token, its own ingest
// token, one allowed origin and a retention, and an app exporting to it.
func hostedStudio(ctx context.Context, w io.Writer, dir string) error {
	db, err := sqlite.Open(filepath.Join(dir, "hosted.db"))
	if err != nil {
		return err
	}
	defer func() { _ = db.Close() }()
	apiToken, ingestToken := "api-secret", "ingest-secret" // in production: from your secret store

	srv := studio.New(
		studio.DB(db),                                  // the hosted database (SQLite here; clickhouse.Open in a fleet)
		studio.Token(apiToken),                         // every /api route: Authorization: Bearer <apiToken>
		studio.IngestToken(ingestToken),                // /v1/traces and /v1/logs: Authorization: Bearer <ingestToken>
		studio.AllowOrigins("https://app.example.com"), // the app page that loads the devtools panel
		studio.Retain(30*24*time.Hour),                 // delete runs not running, last seen 30 days ago
	)
	defer func() { _ = srv.Close() }() // stops the sweeper
	mux := http.NewServeMux()
	mux.Handle("/studio/", http.StripPrefix("/studio", srv.Handler()))
	ts := httptest.NewServer(mux)
	defer ts.Close()
	base := ts.URL + "/studio"

	// The app's side: export to the hosted Studio with the ingest token.
	p, err := otel.Start(ctx, otel.Studio(base, ingestToken), otel.NoEnv(), otel.NoGlobal())
	if err != nil {
		return err
	}
	agt := weft.New(script(), weft.Name("support-bot"), lookup,
		weft.TracerProvider(p.TracerProvider()), weft.LoggerProvider(p.LoggerProvider()))
	res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"),
		weft.Metadata(map[string]string{"weft.public_id": "pub_jane"}))
	if err != nil {
		return err
	}
	if err := p.Shutdown(ctx); err != nil {
		return err
	}

	noToken, _ := get(base+"/api/runs", "")
	withToken, body := get(base+"/api/runs", apiToken)
	fmt.Fprintln(w, "GET /api/runs without a token:", noToken, "with it:", withToken,
		"lists the run:", strings.Contains(body, res.ID))
	_, meta := get(base+"/api/meta", apiToken)
	var m struct {
		Retention string `json:"retention"`
	}
	_ = json.Unmarshal([]byte(meta), &m)
	fmt.Fprintln(w, "retention:", m.Retention)

	// Your backend mints a panel token for one conversation's public id.
	tok, err := mintPanelToken(base, apiToken, "pub_jane")
	if err != nil {
		return err
	}
	own, _ := get(base+"/api/runs?public_id=pub_jane", tok)
	other, _ := get(base+"/api/runs?public_id=pub_other", tok)
	fmt.Fprintln(w, "panel token, its public id:", own, "another:", other)
	return nil
}

// retention keeps runs 30 days and shows what a sweep 30 days later
// deletes, then gives the space back.
func retention(ctx context.Context, w io.Writer, dir string) error {
	path := filepath.Join(dir, "retained.db")
	p, err := otel.Start(ctx, otel.Local(path), otel.NoEnv(), otel.NoGlobal())
	if err != nil {
		return err
	}
	agt := weft.New(script(), weft.Name("support-bot"), lookup,
		weft.TracerProvider(p.TracerProvider()), weft.LoggerProvider(p.LoggerProvider()))
	if _, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")); err != nil {
		return err
	}
	if err := p.Shutdown(ctx); err != nil {
		return err
	}
	db, err := sqlite.Open(path)
	if err != nil {
		return err
	}
	defer func() { _ = db.Close() }()

	srv := studio.New(studio.DB(db), studio.Retain(30*24*time.Hour)) // sweeps at New, then hourly
	defer func() { _ = srv.Close() }()                               // Close stops the sweeper
	page, err := db.Runs(ctx, obsdb.RunQuery{})
	if err != nil {
		return err
	}
	fmt.Fprintln(w, "kept under a 30-day retention:", len(page.Runs), "run") // a fresh run is never swept

	later := time.Now().Add(30*24*time.Hour + time.Minute) // the clock, 30 days on
	n, err := sweepAndVacuum(ctx, db, later, 30*24*time.Hour)
	if err != nil {
		return err
	}
	page, err = db.Runs(ctx, obsdb.RunQuery{})
	if err != nil {
		return err
	}
	fmt.Fprintln(w, "30 days later: swept", n, "runs; left:", len(page.Runs))
	return nil
}

// sweepAndVacuum is one sweep as Retain's sweeper runs it at now, then
// VACUUM: what `weft vacuum --retain` does.
func sweepAndVacuum(ctx context.Context, db obsdb.DB, now time.Time, retain time.Duration) (int, error) {
	cutoff := now.Add(-retain)      // what Retain's sweeper computes each pass
	n, err := db.Sweep(ctx, cutoff) // runs not running, last seen before cutoff, with their children
	if err != nil {
		return n, err
	}
	err = db.Vacuum(ctx) // SQLite: VACUUM; ClickHouse: OPTIMIZE TABLE … FINAL
	return n, err
}

// ReportInput is the report tool's argument.
type ReportInput struct {
	Month string `json:"month" jsonschema:"the month, YYYY-MM"`
}

// toolLimits runs two tools against their limits: a result past its cap
// and a handler past its deadline.
func toolLimits(ctx context.Context, w io.Writer, _ string) error {
	report := weft.Tool("monthly_report", "Export a month's orders as CSV.",
		func(_ context.Context, in ReportInput) (string, error) {
			return strings.Repeat("order,status\n", 5_000), nil // 65,000 bytes
		},
		weft.MaxResultBytes(4<<10), // this tool's results are cut at 4 KiB, with a marker
		weft.Timeout(10*time.Second),
	)
	slow := weft.Tool("carrier_status", "Ask the carrier where a parcel is.",
		func(ctx context.Context, in LookupInput) (string, error) {
			select {
			case <-ctx.Done(): // honour ctx: the deadline cancels it
				return "", ctx.Err()
			case <-time.After(time.Minute):
				return "in transit", nil
			}
		},
		weft.Timeout(50*time.Millisecond), // past it: an error result, the run goes on
	)
	agt := weft.New(model(), report, slow,
		weft.MaxSteps(5), // budget: ErrMaxSteps past 5 model calls
		weft.UsageLimit(weft.Usage{OutputTokens: 20_000}), // budget: ErrUsageLimit past 20,000 output tokens
	)
	res, err := agt.Generate(ctx, weft.Prompt("Report for 2026-09, and where is parcel 1234?"))
	if err != nil {
		return err
	}
	for _, m := range res.Messages {
		for _, part := range m.Content {
			if r, ok := part.(weft.ToolResultPart); ok {
				if r.IsError {
					fmt.Fprintf(w, "%s (error): %s\n", r.Name, r.Content)
					continue
				}
				fmt.Fprintf(w, "%s (%d bytes): …%s\n", r.Name, len(r.Content), tail(r.Content, 28))
			}
		}
	}
	return nil
}

func model() *wefttest.Model {
	return wefttest.Script(
		wefttest.ToolCalls(
			wefttest.Call{Name: "monthly_report", Args: `{"month":"2026-09"}`},
			wefttest.Call{Name: "carrier_status", Args: `{"order_id":"1234"}`},
		),
		wefttest.Say("The report is partial; the carrier did not answer."),
	)
}

// gracefulShutdown serves one agent over HTTP with a thread session and
// an embedded Studio, then shuts every piece down in order once ctx ends.
func gracefulShutdown(ctx context.Context, w io.Writer, dir string) error {
	path := filepath.Join(dir, "app.db")
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()
	ln, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		return err
	}
	done := make(chan error, 1)
	go func() { done <- serve(ctx, ln, path) }()

	// One request, then the signal.
	resp, err := http.Post("http://"+ln.Addr().String()+"/chat", "text/plain", strings.NewReader("Where is order 1234?"))
	if err != nil {
		return err
	}
	reply, _ := io.ReadAll(resp.Body)
	_ = resp.Body.Close()
	fmt.Fprintln(w, "reply:", string(reply))
	cancel()
	if err := <-done; err != nil {
		return err
	}

	db, err := sqlite.Open(path)
	if err != nil {
		return err
	}
	defer func() { _ = db.Close() }()
	page, err := db.Runs(context.Background(), obsdb.RunQuery{})
	if err != nil {
		return err
	}
	for _, r := range page.Runs {
		fmt.Fprintln(w, "after shutdown the sink holds:", r.Agent, r.Status, "turn", r.Turn)
	}
	return nil
}

// serve runs the app until ctx ends, then shuts down: HTTP first, then
// the session, then Studio, then the recording pipeline.
func serve(ctx context.Context, ln net.Listener, dbPath string) error {
	shutdownRecording := otel.Install(otel.Local(dbPath), otel.NoEnv())
	agt := weft.New(script(), weft.Name("support-bot"), lookup)
	s, err := thread.Create(ctx, thread.Memory(), agt, thread.NoAutoCompact()) // in production: jsonl.Open or sqlite.Open
	if err != nil {
		shutdownRecording()
		return err
	}
	inspector := studio.New(studio.DB(otel.LocalDB()))
	mux := http.NewServeMux()
	mux.Handle("/studio/", http.StripPrefix("/studio", inspector.Handler()))
	mux.HandleFunc("POST /chat", func(rw http.ResponseWriter, r *http.Request) {
		var prompt bytes.Buffer
		_, _ = prompt.ReadFrom(r.Body)
		turn, err := s.Send(r.Context(), weft.User(prompt.String()))
		if err != nil {
			http.Error(rw, err.Error(), http.StatusServiceUnavailable)
			return
		}
		res, err := turn.Wait()
		if err != nil {
			http.Error(rw, err.Error(), http.StatusInternalServerError)
			return
		}
		_, _ = io.WriteString(rw, res.Text())
	})
	httpSrv := &http.Server{Handler: mux, ReadHeaderTimeout: 10 * time.Second}
	go func() { _ = httpSrv.Serve(ln) }()

	<-ctx.Done() // SIGINT or SIGTERM in main
	stopCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()
	err = errors.Join(
		httpSrv.Shutdown(stopCtx), // 1. stop taking requests; in-flight handlers finish
		s.Close(stopCtx),          // 2. drain the running turn and the queue, give the writer lease up
		inspector.Close(),         // 3. stop Retain's sweeper and the playground link
	)
	shutdownRecording() // 4. flush every destination (5 s budget), close the local sink last
	return err
}

// standInStudio serves a Studio over a fresh SQLite file on a loopback
// port: its OTLP ingest takes loopback peers without an ingest token.
func standInStudio(path string) (url string, db obsdb.DB, stop func(), err error) {
	db, err = sqlite.Open(path)
	if err != nil {
		return "", nil, nil, err
	}
	srv := studio.New(studio.DB(db))
	ts := httptest.NewServer(srv.Handler())
	return ts.URL, db, func() { ts.Close(); _ = srv.Close(); _ = db.Close() }, nil
}

// everything is every stored body of a run: its events and its
// transcript, joined.
func everything(ctx context.Context, db obsdb.DB, runID string) (string, error) {
	var sb strings.Builder
	page, err := db.Events(ctx, runID, -1, 500)
	if err != nil {
		return "", err
	}
	for _, e := range page.Events {
		b, _ := json.Marshal(e)
		sb.Write(b)
	}
	batches, err := db.Transcript(ctx, runID)
	if err != nil {
		return "", err
	}
	for _, b := range batches {
		sb.Write(b)
	}
	return sb.String(), nil
}

func get(url, token string) (int, string) {
	req, _ := http.NewRequest(http.MethodGet, url, nil)
	if token != "" {
		req.Header.Set("Authorization", "Bearer "+token)
	}
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return 0, err.Error()
	}
	defer func() { _ = resp.Body.Close() }()
	b, _ := io.ReadAll(resp.Body)
	return resp.StatusCode, string(b)
}

func mintPanelToken(base, apiToken, publicID string) (string, error) {
	body := strings.NewReader(`{"public_id":"` + publicID + `","ttl":"15m"}`)
	req, _ := http.NewRequest(http.MethodPost, base+"/api/panel-tokens", body)
	req.Header.Set("Authorization", "Bearer "+apiToken)
	req.Header.Set("Content-Type", "application/json")
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return "", err
	}
	defer func() { _ = resp.Body.Close() }()
	var out struct {
		Token string `json:"token"`
	}
	if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
		return "", err
	}
	if out.Token == "" {
		return "", fmt.Errorf("panel-tokens: %s", resp.Status)
	}
	return out.Token, nil
}

// toolResult is the text of the run's first tool result: what the model
// read, never changed by a destination's redactor.
func toolResult(res *weft.RunResult) string {
	for _, m := range res.Messages {
		for _, part := range m.Content {
			if r, ok := part.(weft.ToolResultPart); ok {
				return r.Content
			}
		}
	}
	return ""
}

func tail(s string, n int) string {
	s = strings.ReplaceAll(s, "\n", `\n`)
	if len(s) <= n {
		return s
	}
	return s[len(s)-n:]
}
```

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

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

```sh
go run ./production
go test ./production
```

```text
== retention
kept under a 30-day retention: 1 run
30 days later: swept 1 runs; left: 0
```

The rest of the output belongs to the other Production pages. `TestRetainFloorPanics` in [`main_test.go`](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/production/main_test.go) checks that `studio.Retain(30*time.Minute)` makes `New` panic with the floor's message.

## Best practices & gotchas

- **Build a retained Studio with `New`, and `Close` it.** `Handler` returns a server nothing can close; its sweeper outlives every request until the database closes. (Source: `studio.Retain` godoc, `studio/delete.go:131-139`)
- **Retention is about `last_seen`, not start time.** A long session turn is kept until it has been quiet for `d`. (Source: `obsdb.DB.Sweep` godoc, `obsdb/db.go:135-149`)
- **Vacuum after a large first sweep.** Deleting rows does not shrink a SQLite file; `weft vacuum` does, and holds the file while it rewrites it. (Source: `obsdb/db.go:150-155`; `cmd/weft/vacuum.go:68-128`)
- **Delete the conversation separately.** `DELETE /api/sessions/{id}` leaves the app's `thread` store as it is. (Source: `studio/delete.go:14-17`)

## See also

- [Choose the observability database: SQLite or ClickHouse](https://weftgo.dev/docs/production/storage-backends/)
- [Run Studio: embedded, local binary or hosted](https://weftgo.dev/docs/observe/studio/setup/)
- [Operate sessions in production](https://weftgo.dev/docs/sessions/operations/)
- [weft CLI reference](https://weftgo.dev/docs/reference/cli/)

Symbols used: [`studio.Retain`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#Retain) · [`studio.New`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#New) · [`studio.DB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#DB) · [`Server.Close`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#Server.Close) · [`studio.Handler`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#Handler) · [`obsdb.DB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DB) · [`obsdb.SweepBatch`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#SweepBatch) · [`obsdb.InterruptedAfter`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#InterruptedAfter) · [`clickhouse.TTL`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/clickhouse#TTL) · [`sqlite.Open`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#Open) · [`thread.Delete`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Delete)
