Skip to content

Limits and performance

View as Markdown

These are the caps, budgets, queue sizes and timeouts that an operator meets, grouped by where they apply: the agent loop, the recording pipeline, the observability database, Studio, the playground link, the devtools panel, the weft command and sessions. “Fixed” means a constant in the code with no option. The model-visible ones (the tool-result cap, timeouts, budgets) are behaviour your agent depends on; the rest bound what Studio stores and reads.

Put a tool’s result cap and deadline beside the run’s budgets, in production/main.go:

production/main.go
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
)

production/main.go on GitHub

monthly_report (4123 bytes): …\n…[truncated 60904 bytes]
carrier_status (error): tool "carrier_status" timed out after 50ms

The model reads the first 4,096 bytes and a marker that names the 60,904 bytes it did not get; the slow tool’s call becomes an error result and the run continues.

Budgets are checked only when the loop would call the model again, so a step that ends the run succeeds even past one; a breach is a *RunError with the partial transcript (How does a run stop?).

LimitValueSet byWhen hitSource
Steps10 model callsweft.MaxSteps(n); per run lower onlyErrMaxSteps, stopped_by max_stepscore/agent.go:23
Usagenoneweft.UsageLimit(u); subagent usage countsErrUsageLimit, stopped_by usage_limitcore/agent.go:125
Model retries3 consecutive RETRY results per toolweft.MaxModelRetries(n)ErrModelRetriesExceededcore/agent.go:25
Loop detectionoffweft.DetectLoops(repeats)ErrLoopDetectedcore/agent.go:187
Parallel tool calls4weft.Parallelism(n), weft.Sequential(); per run lower onlyfurther calls waitcore/agent.go:24
Tool result64 KiB of textweft.MaxResultBytes(n) per agent or per tool; 0 = no capcut on a rune boundary, marker …[truncated N bytes] the model seescore/agent.go:28, core/loop.go:2221
Tool deadlinenoneweft.Timeout(d) per agent or per toolerror result tool "X" timed out after d; the handler’s goroutine is abandonedcore/tool.go:508, core/loop.go:1980
Output tokens per stepthe provider’s; Anthropic 4096the adapter’s MaxTokens(n), weft.Paramsmax_tokens stop; tool calls in that step are not executedanthropic/model.go:185
Stream idle gap60 s between chunksthe adapter’s IdleTimeout(d); 0 disablesErrStreamIdleopenai/model.go:165, core/errors.go:77
mw.Retry3 retries, 500 ms doubling, each wait capped at 8 s, ±25% jittermw.MaxRetries, mw.BaseDelaythe last errorcore/mw/retry.go:26-28
SDK transport retries2 (OpenAI, Anthropic), the SDKs’ defaultthe adapter’s MaxRetries(n)—openai/model.go:115, anthropic/model.go:107
mw.Retry provider wait60 smw.MaxWait(d); 0 = no capmw.ErrRetryAfterTooLongcore/mw/retry.go:29
Metadata64 keys, 128-byte keys, 1,024-byte valuesfixedthe entry is dropped, never truncated, and counted in weft.metadata.droppedcore/metadata.go:14-16
Resumed calls on a span32 in weft.resume.callsfixedthe rest written as ,…+kcore/loop.go:1519
LimitValueSet byWhen hitSource
Content field32 KiB per event field, delta, prompt or catalog body; never the transcriptotel.ContentConfig{MaxBytes}; negative = no capcut, weft.content.truncated_bytes setotel/options.go:31
Destination queue2,048 per chain (records and spans each); Studio 16,384; Local has no queueotel.QueueSize(n)refused by tier: deltas at ½, records at ⅞, run brackets and heartbeats when full; one WARN; weft.records.droppedotel/admission.go:53-54, 119-121
Blocking wait5 s per stallotel.Blocking(), development gate only (WEFT_ENV=dev or otel.DevMode())refused until an export beginsotel/admission.go:60
Heartbeatevery 10 s per open runotel.Heartbeat(d); 0 disablesa run silent for a fixed 30 s reads interrupted (three default beats), whatever the intervalotel/pipeline.go:392, obsdb/db.go:998
Studio batch intervallogs 200 ms, spans 1 s; others the SDK’sotel.BatchDelay(d)—otel/config.go:129-136
Raw body256 KiB per wire bodyfixed (otel.RawBodies, dev only)cut and counted in the body’s truncated_bytescore/raw.go:40
Raw batch to Studio16 records per batch, 12 MiB per exportfixedthe export is splitotel/pipeline.go:397, 407
Bridged log attributes120 per linefixeddropped, counted in weft.log.attrs_droppedotel/slog.go:51
Shutdown flush5 sfixed; Pipeline.Shutdown(ctx) flushes for at most 5 s within your ctx, which bounds the provider shutdowns after itunflushed records are lostotel/pipeline.go:177, 365

Control what content leaves the process and queue size and blocking explain the first three.

LimitValueSet byWhen hitSource
List page (runs, traces, sessions)50, at most 500the query’s Limit, ?limit=clampedobsdb/db.go:1056-1061
Running → interrupted30 s since last seenfixed (obsdb.InterruptedAfter)status interrupted; also the 30 s settling windowobsdb/db.go:998
Sweep pass500 root runsfixed (obsdb.SweepBatch)the next passobsdb/db.go:1006
Span tree10,000 spans, 10,000 run rowsfixed (obsdb.TreeSpanCap, TreeRowCap)truncated hole, cause response_capobsdb/tree.go:108, 127
Derived run’s trace read50,000 spansfixedTraceTruncatedobsdb/tree.go:117
Child runs per read10,000fixed (obsdb.ChildRunsCap)ErrChildRunsCapped; cost reads unknownobsdb/tree.go:133
Search16 terms, 256 bytes a term, offset up to 100,000fixedErrInvalidSearch, Studio 400obsdb/search.go:74-76
Prompt preview200 runesfixedcutobsdb/search.go:156
Live subscriber queue1,000 framesobsdb.QueueSize(n) on a hubthe slow subscriber is droppedobsdb/hub.go:114
App log candidates per read10,000 recordsfixedLogPage.Truncatedobsdb/logs.go:120
App log page100, at most 1,000?limit=clampedobsdb/logs.go:31-40, studio/logs.go:28
Requests pageat most 1,000?limit=clampedstudio/requests.go:28
Event gaps listed per page1,000fixed (obsdb.MaxGaps)the rest not listedobsdb/db.go:674
Same-timestamp rows past a page500fixed (obsdb.MaxTies)the page ends thereobsdb/db.go:627
Missing tree children named100, all countedfixed (obsdb.TreeMissingCap)the count onlyobsdb/tree.go:121
ClickHouse table TTLscontent 30 days, spans and runs 90 daysclickhouse.TTL(content, meta)rows expireobsdb/clickhouse/clickhouse.go:20-21
LimitValueSet byWhen hitSource
OTLP ingest body16 MiB after decompressionfixed413 request body exceeds 16 MiB after decompressionstudio/ingest/ingest.go:40
API request body4 MiB, every JSON bodyfixed413 …: larger than the 4 MiB limitstudio/api.go:67-71
Runtime link request body (register, acks)8 MiBfixed413studio/runtime/http.go:44
Events page500, at most 5,000?limit=clampedstudio/api.go:33-34
Search by costthe first 2,000 matches pricedfixedcost_sort_cap in the answerstudio/search.go:146
Diff500 stepsfixedtruncated hole, cause response_capstudio/diff.go:66
Export with tree=1200 subagent runsfixedtruncated hole: the later ones were not exportedstudio/export.go:167
Trace list failed runs500 countedfixedfailed_runs_cappedstudio/traces.go:182
Live backfill, all=1the last hour or running, 500 runsfixedolder runs not replayedstudio/live.go:710-711
Instruction proposals64, in memoryfixedthe oldest evictedstudio/proposals.go:40
Unpriced models named5, then (+n)fixed—studio/pricing.go:521
Experiments list50, at most 200?limit=clamped, total givenstudio/experiments.go:189-190
Panel token1 httl in the mint request; no maximum401 bad or expired tokenstudio/auth.go:671
Live grant60 s to open; never past a panel token’s expiryfixed401; a panel token’s stream ends with event: expiredstudio/livegrant.go:53
Hand-off token5 min, never past the calling panel token’s expiryfixedthe tab falls back to its stored token, if one is stored; with none, the 401 standsstudio/handoff.go:40
Hand-off to2,048 bytesfixed400studio/handoff.go:43
Retentionat least 1 h; sweeps every min(d/10, 1h), at least a minute apartstudio.Retain(d), --retain, WEFT_RETAINunder 1 h: New panics, the CLI exits 2studio/delete.go:141-153
Refused-ingest log linesone a minute per remote, route and status, 1,024 keys trackedfixedthe rest suppressed and counted; 5xx never limitedstudio/internal/reqlog/reqlog.go:181, 185
Live streama ping every 15 s; 30 s to write a frame; 65,536 deduplication keys per connectionfixeda write past 30 s ends the stream; the dedup set evicts its oldest keysstudio/live.go:23, 30, 33
LimitValueSet byWhen hitSource
Command ack30 s from enqueue; the runtime validates within 25 sfixedthe command is marked lost, no ack in timestudio/runtime/runtime.go:882, runtime/executor.go:363
Accepted command without finishmax(10 min, 3 heartbeats); heartbeat every minutefixedmarked loststudio/runtime/runtime.go:2000-2001, runtime/link.go:913
Commands in flight per runtime256fixedrejected ack runtime busy: N commands in flightruntime/link.go:38
Concurrent runs per runtime16fixedthe rest wait, already ackedruntime/link.go:43
Command frame8 MiBfixedthe command is acked as rejected, the stream ends and the link reconnectsruntime/link.go:44-46, 364-374
Source transcript fetched from Studio64 MiBfixeda rejected ack, studio transcript: larger than N bytesruntime/transcript.go:151, 296, 379
Finished commands and routes kept24 hfixedprunedstudio/runtime/runtime.go:885
Command rows in memory10,000fixedthe oldest finished rows prunedstudio/runtime/runtime.go:2201
Command stream30 s to write a frame; 256 frames queued per streamfixedthe stream is dropped; the runtime reconnectsstudio/runtime/runtime.go:886-887
Command id1 to 128 characters of [A-Za-z0-9._:-]fixed400studio/runtime/runtime.go:714
Remembered manifests64fixedthe oldest unheld one forgottenstudio/runtime/manifests.go:23
Command store failureits queue held 30 s, then re-appliedfixed—studio/runtime/store.go:130
Runtime: command ids remembered4,096fixed—runtime/link.go:35
Runtime: HTTP timeoutsregister 15 s, response headers 30 s, an ack post 10 sfixed—runtime/link.go:51-52, 892
Runtime: ack error text2 KiBfixedcut, … appendedruntime/link.go:56
Runtime: resolversModelResolver 10 s, runtime.Sessions resolver 10 sfixed—runtime/executor.go:355, runtime/sessions.go:49
Runtime: kept state64 forked sessions, 128 parked runsfixedthe oldest forgotten; a fork’s park whose session is still held is rebuilt, any other evicted park answers no parked run … on this runtimeruntime/executor.go:779, 1137
Budget per experimentnone: the agent’s own budgets onlyruntime.Limits(runtime.Budget{MaxTokensPerExperiment, MaxRunsPerExperiment})the experiment’s next command is rejected, budget_exceededruntime/options.go:126-136, runtime/executor.go:212-222

Connect your app to Studio’s playground covers the link.

The devtools panel, panel.js, has a size cap of 104 KiB (106,496 bytes) gzipped, the cap in studio/web/panel-budget.json. The build fails over it. At v0.20.2 it ships at 98,986 bytes, 7,510 bytes under the cap. Studio’s whole UI bundle has its own budget of 800 KiB gzipped (700 KiB before 0.19.0), enforced by make studio-check (studio dist exceeds the 800 KiB gzip budget); at v0.20.2 it is 754 KiB. The panel.js copy counts there and under its own cap.

panel-budget.json is an append-only ledger: each panel change appends one row with its label, the budget item it counts against and the bundle’s gzip bytes after it. Every panel build prints the per-item table from it. Sizes are measured with the version stamp replaced by the fixed-length placeholder "v0.00.0" (normalizeStamp), so a version bump moves no byte, and gzipped by pako’s deflate at level 6 so every host measures the same bytes.

Releasepanel.js gzippedCap
0.12.062,591 B¹80 KiB
0.15.078,098 B, the first fully minified release (73,706 B at the minify row, 81,358 B before it)80 KiB
0.16.082,608 B96 KiB, raised from 80 KiB
0.17.090,091 B96 KiB
0.18.0 to 0.18.391,032 B²96 KiB
0.19.095,558 B104 KiB, raised from 96 KiB
0.20.098,921 B104 KiB
0.20.198,994 B104 KiB
0.20.298,986 B104 KiB

¹ The CHANGELOG’s figure. The v0.12.0 ledger’s last row reads 62,734 B: rows up to then were measured with the host Node’s node:zlib, whose output varies by host.

² The ledger’s last row. The CHANGELOG’s 0.18.0 entry says 90,778 B, an earlier row of the same ledger.

The panel ships minified and without a sourcemap; its source is studio/web/src/panel in weft’s repository. Install the devtools panel covers loading it.

LimitValueSet byWhen hitSource
Studio port127.0.0.1:7331, then the next free one up to 7340--addr, WEFT_STUDIO_ADDR pin itevery port busy: an error naming the rangeinternal/listen/listen.go:57-60
weft runs50 runs--limit (0 = every match)a note on stderrcmd/weft/api.go:311
weft mcp output64 KiB, at most 4 MiBthe tool’s max_bytes argumentcut with a note naming the sizescmd/weft/mcp.go:42-43
Response or export download512 MiBfixedan errorcmd/weft/api.go:63-67
Discovery filetrusted under 24 h old, read up to 64 KiBfixedignored at Debuginternal/discovery/discovery.go:65-69
API client2 min per request; weft runs fetches pages of 100fixed—cmd/weft/api.go:43, 300
weft mcp error excerpt2,048 bytes of a refused answerfixedcutcmd/weft/mcp.go:603
Port probe2 sfixed—internal/listen/listen.go:66
weft doctor5 s per requestfixed—internal/doctor/doctor.go:31
LimitValueSet byWhen hitSource
thread.List page50, at most 500thread.Query{Limit}clampedthread/storage.go:114-116
Compaction reserve16,384 tokens; 20,000 recent tokens keptthread.Reserve, thread.KeepRecent, thread.ContextWindow(n) arms itcompaction runsthread/compaction.go:25-28
Compaction summarizer inputtool results cut at 2,000 charactersfixedcut with …[truncated]thread/compaction.go:31, 1175
Compaction summary output0.8 × the reserve, sent as the request’s max tokensthread.SummaryMaxTokens(n)not cut: the summary is not stored and the step fails with ErrSummaryTruncated (after retry, then fallback)thread/compactopts.go:269-273, 808-813, thread/compaction.go:782, 1673
Pool delegation depth8pool.MaxDepth(n)ErrDepththread/pool/pool.go:143
Approval request expirynonethread.RequestExpiry(d)ErrExpiredthread/approval.go:326
Signed refusal audits16 per requestfixedno further audit entriesthread/signing.go:495
JSONL header1 MiB before the first newlinefixedthe file is skipped by Listthread/jsonl/jsonl.go:48

Operate sessions in production covers what a session costs as it grows.

The Production pages share one example program; toolLimits is this page’s:

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:]
}

View production/main.go on GitHub

View on GitHub · from docs-site/examples:

Terminal window
go test ./production

TestProduction in main_test.go pins the marker and the timeout text above.

  • Lift the result cap per tool, not per agent. weft.MaxResultBytes(0) on the one tool whose output must arrive whole keeps the 64 KiB guard on every other tool. (Source: MaxResultBytes godoc, core/agent.go:527-535)
  • Handlers must honour ctx. A timed-out handler’s goroutine is abandoned, not killed; one that ignores ctx keeps running. (Source: AGENTS rule 9; core/tool.go:501-508)
  • Raise QueueSize, not Blocking, in production. Blocking is refused outside the development gate (WEFT_ENV=dev, or otel.DevMode()). (Source: otel/pipeline.go:264)
  • Two caps, two audiences. MaxResultBytes bounds what the model reads; ContentConfig.MaxBytes bounds what a destination stores, and never the transcript. (Source: core/agent.go:28; otel/options.go:23-31)

Symbols used: weft.Tool · weft.New · weft.MaxResultBytes · weft.Timeout · weft.MaxSteps · weft.UsageLimit · weft.Usage · weft.ToolResultPart · otel.QueueSize · otel.Heartbeat · obsdb.InterruptedAfter · obsdb.SweepBatch · obsdb.TreeSpanCap · obsdb.ChildRunsCap · studio.Retain · wefttest.Script