Skip to content

Operate sessions in production

View as Markdown

A weft/thread deployment is a storage backend, an fsync policy, one writer per session, and a shutdown that closes what it opened. A reader that meets data it does not understand fails loudly and never guesses: thread.ErrCorrupt for a damaged line, thread.ErrNewerFormat for a newer weft’s data. This page is weft’s operator’s page (docs/thread-operations.md) for users: what is on disk, how to back it up, what each error means, and what to do after a crash.

sessions/operations.go opens a JSONL directory with the backend’s logger set:

sessions/operations.go
logger := textLogger(w) // your application's logger
sessions := filepath.Join(dir, "ops")
st, err := jsonl.Open(sessions,
thread.OpenLogger(logger), // where the backend reports its own repairs
)
if err != nil {
return err
}
agent := say(logger, "Order 1234 shipped on Tuesday.", "It arrives on Friday.")
s, err := thread.Create(ctx, st, agent, ctxWindow, ids("s_ops", "a"), at(base))

sessions/operations.go on GitHub

Store sessions covers the three storage backends and their options. ids, at and ctxWindow are the demos’ helpers for pinned ids, a pinned clock and a context window.

Four decisions, each with its default:

DecisionDefaultChoose otherwise when
Backendjsonl.Open(dir): one file per session; jq and cp work on itmany sessions in one file, List paged in SQL, TitleSearch without reading entries: sqlite.Open(path). thread.Memory() loses everything with the process: tests only
Fsync policythread.FsyncEveryAppend(): every append survives a power cutappends must be cheaper and a power cut may cost the unsynced tail of a turn: thread.FsyncOnFlush()
Lockingthe backend’s cross-process lock, one writer per sessionthe platform has no advisory file lock, or the filesystem’s locks cannot be trusted: thread.NoLock() on jsonl, and one writer becomes your promise
Logsthe backend reports its own repairs (a torn tail removed, a lock taken over) to slog.Default()pass thread.OpenLogger(l) to route them to your logger

Session-level warnings (a repaired load, a failed step write, a compaction that failed) go through the agent’s logger, weft.Logger, not the backend’s. weft/thread is pre-1.0 and not frozen: the API and the stored format may change between minor versions, and the CHANGELOG says how. Nothing here is a compatibility promise beyond the reader’s behaviour.

Aspectthread/jsonlthread/sqlite
Layoutone directory; one <id>.jsonl file per sessionone database file holding every session
A sessionthe header line, then one JSON line per entry, append-onlythe same line bytes, one per row (sessions.header, entries.line)
Permissionsfiles 0600; the directory 0700 when Open creates it (an existing directory keeps its mode)the file 0600 and its directory 0700 when Open creates them
Side filesnone<file>-wal and <file>-shm (WAL mode, set once on the file)
Lockan advisory lock on the session filea row per session in session_locks
Schemathe format itselfembedded migrations, tracked in thread_migrations; a database from a newer weft fails Open with sqlite.ErrNewerSchema

A session id is 1 to 128 letters, digits, _ or - (thread.ValidID), always one path component. Read a jsonl session with jq -c . <dir>/<id>.jsonl; The session log format lists every entry kind and field. thread/sqlite is the one package that imports the SQLite driver.

  • jsonl fsyncs every Append before it returns, and the file and directory at Create. Under FsyncOnFlush a Session flushes after the prompt, every receipt and bookkeeping write, and at the turn’s end; the step appends in between are not synced. A crash can lose the unsynced tail of a turn, never a synced one.
  • sqlite commits every Append as one transaction in WAL mode, so a process that dies never loses an Append that returned. The fsync policy is SQLite’s synchronous level: FsyncEveryAppend is synchronous=FULL, the log fsynced at every commit. FsyncOnFlush is synchronous=NORMAL: a power cut or kernel crash can roll back the commits since the last sync (the database stays consistent), and Flush runs PRAGMA wal_checkpoint(PASSIVE), which syncs the log.
  • Both: an Append batch is atomic against the writer’s death. After a crash a load returns all of it or none of it.

jsonl. cp, rsync or a filesystem snapshot of the directory is a backup, at any time, with writers running. A file copied mid-append can end in a half-written line; the copy still loads (the torn line is dropped and reported) and is missing at most that one batch. Restore by putting files back. The advisory lock is not in the file, so a restored copy is unlocked.

sqlite. The main file alone is not a backup while the database is in use: committed data can still be in -wal. Use SQLite’s online backup, or stop every writer and copy the main file with -wal and -shm:

Terminal window
sqlite3 sessions.db ".backup out.db"
sqlite3 sessions.db "VACUUM INTO 'out.db'"

A sqlite backup carries the session_locks rows of the writers that held sessions when it was taken. Restored on the same host they belong to a dead process and are taken over on first write, one Warn line each. Restored on a host with a different hostname they are never taken over: break them after such a restore.

Neither backend has export, import or encryption at rest; encrypt the volume.

There are two layers, and they answer different questions (T1).

The backend’s lock: which Storage value, in which process, may write. It is taken on a session’s first write and held until the session is released, deleted, or the process dies. A second writer gets thread.ErrLocked. Readers never lock: Load, List, Watch, thread.Open and every read of a Session always work.

  • jsonl: flock on unix, LockFileEx on Windows. The kernel drops it however the holder exits, so a crashed writer never strands a session. It costs one open file descriptor per session a process is writing, until that session is closed: size the fd limit for the sessions you hold open at once.
  • sqlite: the lock row names its holder by Storage instance, host, a random per-process token, pid and process start time. A later writer decides from those whether the holder is dead:
The row’s holderJudged
this process, another Storage valuealive: ErrLocked
this process’s pid under another process token (a restarted container that is PID 1 again)an earlier incarnation: taken over
a pid that is not running, or running but started at another time (the pid was reused)dead: taken over
a different hostnamenever judged dead from here: ErrLocked

The start time is read from /proc on Linux and from the kernel on macOS and Windows. On other unixes it is unknown, and an unrelated live process wearing a dead holder’s pid keeps the session locked until it exits. A takeover is logged as one Warn through OpenLogger.

The lease: which Session value may write. Two Session values on one Storage look identical to the backend, so a Session takes the session’s lease with its first write (Create and Fork are first writes) and keeps it until Close. Another Session on the same Storage opens and reads normally, and every write it makes fails with ErrLocked. A Session opened before another writer appended fails its write with thread.ErrStale instead. Stale detection is a count plus the header’s creation time: it catches a writer that appended behind it and a session deleted and re-created under the same id, and it is not a content comparison.

  • s.Claim(ctx) asks the lease question ahead of a write: it takes the lease, or fails with ErrLocked, ErrStale or ErrClosed and changes nothing. A Claim with no later write still holds the lease (jsonl’s flock, sqlite’s lock row) until Close: claim only with a Close to come.
  • A Session someone forgot to close holds its lease for the life of the process. st.(thread.Releaser).Release(ctx, id) ends the hold whoever has it; use it only when that Session is truly abandoned.
  • Containers. A restarted container that keeps its hostname reclaims its sqlite sessions on its own. A replacement with a new hostname, the default for a new pod or docker run, does not: give session writers a stable hostname, or close sessions on shutdown so no rows are left.
  • Several hosts. jsonl’s lock is only as good as the filesystem’s flock (network filesystems vary), and a sqlite database on a shared filesystem is outside SQLite’s supported envelope. Run one writer host per directory or database; jsonl readers elsewhere are fine.

sqlite.BreakLock(ctx, st, session) removes the writer lock on a session, whoever holds it. It is the operator’s way out of the one case the lock cannot decide: a row left by a holder on another host, after a container was replaced under a new hostname or a backup carrying lock rows was restored. Here a second Storage value stands in for the new host:

sessions/operations.go
stB, err := sqlite.Open(path, thread.OpenLogger(logger)) // another Storage: another process, as the lock sees it
if err != nil {
return err
}
s, err := thread.Open(ctx, stB, "s_lock", agent, ctxWindow)
if err != nil {
return err
}
err = s.SetInfo(ctx, "Order 1234", nil) // the error names the holder's pid and host
fmt.Fprintln(w, "before:", errors.Is(err, thread.ErrLocked), classify(err))
// You vouch that the holder is gone: nothing can check it.
if err := sqlite.BreakLock(ctx, stB, "s_lock"); err != nil {
return err
}
report(w, "after BreakLock", s.SetInfo(ctx, "Order 1234", nil))
// The old holder's ErrLocked is not a retry: its lock is gone, and the
// session may have been written since. It must open the session again.
err = held.SetInfo(ctx, "Order 5678", nil)
fmt.Fprintf(w, "the old holder: %v\n → reopen (ErrLocked: %v)\n", err, errors.Is(err, thread.ErrLocked))

sessions/operations.go on GitHub

before: true retry
after BreakLock: ok
the old holder: thread: session is locked by another writer: s_lock (this writer's lock was broken; the session may have been written since — open it again)
→ reopen (ErrLocked: true)

You vouch that the holder is gone: nothing can check it. A holder that was alive after all is stopped at its next write, which finds the row is no longer its own and fails with ErrLocked. Here ErrLocked is not a retry: the error says to open the session again, and a Session it serves answers ErrStale if the session was written in between. The demo labels it “reopen” for that reason. The removal is logged at Warn on the storage’s logger, naming the holder. A session with no lock row is left as it is (BreakLock returns nil), and one the database does not hold fails with thread.ErrNotFound. st must be a Storage this package’s Open returned. To clear a whole database after a host change, List the sessions and break each.

s.Close(ctx) works in order. Send and Continue fail with thread.ErrClosed at once. Close waits for the running turn and the queue behind it to drain. The Session is sealed: every later write is ErrClosed, and reads keep answering. The lease and the backend’s hold are released, and with them jsonl’s file descriptor and sqlite’s lock row.

If ctx ends first, Close cancels the running turn (recorded as canceled), ends the queued turns with ErrClosed, and returns ctx.Err(). The canceled turn may still be writing its end: call Close again to finish sealing and releasing. Sends still queued when it gives up keep their accepted receipts in the file, steers their queued ones, and the next Open restores both (the queue).

A parked approval boundary has the same effect without any deadline. Sends queued behind a boundary nobody decides cannot drain, so Close returns at once and their Turns end with ErrClosed. Their receipts stay, and they run after the next Open, once the boundary is decided. In an Open, Send, Close per request handler, do not resend on ErrClosed: the message would be answered twice. Reopen and check s.Queue() and s.Pending() instead.

A shutdown that leaves nothing behind: stop accepting requests, close each pool, close each session with a deadline you can afford, exit:

sessions/operations.go
// shutdown stops a process that writes sessions: pools first, so their
// running children settle their receipts; then every open session.
func shutdown(ctx context.Context, pools []*pool.Pool, sessions []*thread.Session) error {
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
var errs []error
for _, p := range pools {
errs = append(errs, p.Close(ctx)) // a parked child stays parked
}
for _, s := range sessions {
errs = append(errs, s.Close(ctx)) // drains the running turn and the queue
}
return errors.Join(errs...)
}

sessions/operations.go on GitHub

p.Close cancels running pool children and lets them settle their receipts; parked ones stay parked for the next process. Session.Close does not wait for pool children, hence the order. Skipping the sequence is survivable (the crash rules cover it) but costs the in-flight turn, and on sqlite it leaves lock rows for the next process to take over. Never call Close from inside the session’s own run (a tool, a hook): it would wait for the turn that is calling it.

The torn tail. A writer killed inside an append can leave a final line without its newline. Nothing needs doing by hand:

sessions/operations.go
// A writer killed inside an append leaves bytes without a newline.
path := filepath.Join(sessions, "s_ops.jsonl")
f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0)
if err != nil {
return err
}
if _, err := f.WriteString(`{"type":"message","id":"e_a4","par`); err != nil {
return err
}
if err := f.Close(); err != nil {
return err
}
s, err = thread.Open(ctx, st, "s_ops", agent, ctxWindow, ids("", "b"), at(base))
if err != nil {
return err
}
fmt.Fprintln(w, "torn line dropped:", s.LoadReport().Torn)
if err := sendWait(ctx, s, "When does it arrive?"); err != nil { // the next write truncates it
return err
}
fmt.Fprintln(w, "answer:", s.Context()[len(s.Context())-1].Text())

sessions/operations.go on GitHub

level=WARN msg="thread: session loaded with a repair" session=s_ops torn_line=5 skipped_lines=[] orphaned_entries=[]
torn line dropped: 5
level=WARN msg="thread/jsonl: removed a torn tail before appending" session=s_ops dropped_bytes=34
answer: It arrives on Friday.

The load drops the torn line and says so twice: LoadReport.Torn (from s.LoadReport() on an opened session, or from Storage.Load), and one Warn through the agent’s logger. The next writer removes it before appending (jsonl truncates to the last newline and fsyncs; sqlite deletes the torn row) and logs one Warn through OpenLogger. A live tail (Watch) treats a torn line as a write in flight and waits. A crash costs the half-written batch and nothing after it.

A damaged line elsewhere fails the load with ErrCorrupt, carried by a *thread.CorruptError naming the session, the line and, when the tree is the problem, the entry. Open the backend with thread.Salvage() to skip such lines and report them:

sessions/operations.go
damaged := slicesWith(lines, 2, `{"type":"message","id":`) // line 3: a damaged line, not a torn tail
if err := os.WriteFile(path, []byte(strings.Join(damaged, "\n")+"\n"), 0o600); err != nil {
return err
}
st, err := jsonl.Open(sessions)
if err != nil {
return err
}
_, err = thread.Open(ctx, st, "s_errs", agent, ctxWindow)
report(w, "a damaged line", err)
salvaged, err := jsonl.Open(sessions, thread.Salvage())
if err != nil {
return err
}
s, err := thread.Open(ctx, salvaged, "s_errs", agent, ctxWindow)
if err != nil {
return err
}
lr := s.LoadReport()
fmt.Fprintln(w, "salvaged: skipped", lr.Skipped, "orphaned", lr.Orphaned, "torn", lr.Torn)
// The same line from a newer weft: "v" above what this build reads.
newer := slicesWith(lines, 2, strings.Replace(lines[2], `{"type":"message",`, `{"type":"message","v":2,`, 1))
if err := os.WriteFile(path, []byte(strings.Join(newer, "\n")+"\n"), 0o600); err != nil {
return err
}
_, err = thread.Open(ctx, salvaged, "s_errs", agent, ctxWindow)
report(w, "a newer line, under Salvage", err)

sessions/operations.go on GitHub

a damaged line: thread: session s_errs line 3 is corrupt: unexpected end of JSON input
→ terminal: inspect the line, or open with Salvage
salvaged: skipped [3] orphaned [e_a3] torn 0
a newer line, under Salvage: thread: session format newer than this build: entry kind "message" carries v=2, this build reads v=1
→ terminal: upgrade this build
  • thread.LoadReport is what a load dropped or skipped: Torn, the 1-based line number of the incomplete final line (0 when the session ended on a complete line), and Skipped, the 1-based line numbers skipped under Salvage, in file order. A clean load returns a nil report.
  • thread.OpenReport embeds it and adds Orphaned: the ids of entries whose parent was on a skipped line. They are kept, never dropped, and a context for a leaf below one starts at that entry: everything before the skipped line is off the path.
  • Salvage never skips data from a newer weft. It is a recovery tool: open with it, read s.LoadReport(), decide whether the session is still usable.

A file with no complete header line, a crash inside Create, is ErrCorrupt on line 1 and is not repaired: thread.Delete it and create the session again.

The interrupted turn. Its prompt and every message its steps emitted are in the file. A tool call left without a result is given an error result by the loop’s input repair (weft.Repair), so the next turn’s model sees a complete transcript. The turn entry may be missing; the run id is not reused, since it is on the prompt entry.

An approved call cut off by a crash runs again. A resume writes its started audit entry before its run starts, and the approved calls’ results join the transcript right after they run, before the next model call. A crash after the started entry and before an approved call’s result is recorded leaves that call unanswered on the boundary, with its decision still in force. The next resume runs it again: Resume, Continue, a Send under AutoResume, or a pool’s Recover for a child. A crash after the result is recorded leaves no open boundary, and nothing runs again. Nothing on file tells a call that never started from one cut off half-way, and weft.Replay classes do not gate a session resume. Make such a tool idempotent, keyed by the call id from weft.CallFromContext together with the session id (weft.session.id in weft.MetadataFromContext) and a business key such as the order id (an example). The call id is the same on every run of one call, so the run a resume repeats finds the first run’s entry. The session id keeps conversations apart, but it is the same on every turn of one session. Within a session only the business key reliably tells operations apart, because a later turn may reuse a call id (weft’s Gemini adapter, for one, numbers calls call_0, call_1, … per step when the API sends no id): keyed by the order id, a later turn’s refund of the same order under a repeated call id reads as already done. Name the operation itself, such as a refund request id, when one order may be refunded twice.

Accepted input that never ran is back in s.Queue() after Open, and Open never runs anything on its own (the queue). Pool delegations a dead process left unsettled need Recover.

Match with errors.Is. Each error has a class that says what the caller does next:

sessions/operations.go
// classify maps a thread error to what the caller does next.
func classify(err error) string {
switch {
case err == nil:
return "ok"
case errors.Is(err, thread.ErrBusy), errors.Is(err, thread.ErrLocked):
return "retry"
case errors.Is(err, thread.ErrStale), errors.Is(err, thread.ErrClosed):
return "reopen"
case errors.Is(err, thread.ErrNewerFormat):
return "terminal: upgrade this build"
case errors.Is(err, thread.ErrCorrupt):
return "terminal: inspect the line, or open with Salvage"
}
return "unknown: " + err.Error()
}

sessions/operations.go on GitHub

The demo provokes three of them on one directory:

sessions/operations.go
// Another Session on the same session, while the writer holds it.
other, err := thread.Open(ctx, st, "s_errs", agent, ctxWindow) // reads always work
if err != nil {
return err
}
report(w, "another Session", other.SetInfo(ctx, "Order 1234", nil))
if err := writer.Close(ctx); err != nil {
return err
}
report(w, "after Close", writer.SetInfo(ctx, "Order 1234", nil))
// other was opened before the writer's last append: its view is behind.
ahead, err := thread.Open(ctx, st, "s_errs", agent, ctxWindow)
if err != nil {
return err
}
if err := ahead.SetInfo(ctx, "Order 1234", nil); err != nil {
return err
}
if err := ahead.Close(ctx); err != nil {
return err
}
report(w, "a view behind", other.SetInfo(ctx, "Order 1234", nil))

sessions/operations.go on GitHub

another Session: thread: session is locked by another writer: s_errs
→ retry
after Close: thread: session is closed: session s_errs
→ reopen
a view behind: thread: session changed since it was opened: session s_errs holds 4 entries, this Session has seen 3; open it again
→ reopen
ErrorClassMeansDo
thread.ErrBusyretrya turn is running: a Reject-policy Send, or Branch, Compact, ApplyCompaction, Uncompact, CustomMessagewait (turn.Wait, s.WaitIdle) and call again, or send under Queue
thread.ErrLockedretryanother writer holds the session: another process, another Storage, or another Session not yet closedretry after that writer closes; a dead sqlite holder on another host: break the lock
thread.ErrStalereopenthe stored session moved on behind this Session, or was deleted and created againthread.Open it again and redo the write
thread.ErrClosedreopenthis Session’s Close has runthread.Open it again
thread.ErrNotFoundterminal for the callno such session, or it was deleted under an open Session—
thread.ErrExiststerminal for the callCreate over an existing idpick another id
thread.ErrCorruptterminal for the dataa line this build cannot decode, or a tree that does not hold togetherinspect the line named; reopen the backend with Salvage to read around it
thread.ErrNewerFormatterminal for this buildwritten by a newer weft: an unknown entry kind, a newer "v", a newer header envelopeupgrade the reader; Salvage does not skip it
thread.ErrAwaitingApprovalwaitcompaction while approval requests are pendingdecide them first
sqlite.ErrNewerSchematerminal for this buildthe database was migrated by a newer weftupgrade

ErrNewerFormat covers the header too: a header whose envelope is ahead of thread.FormatVersion fails Load with it on both durable backends, not as line-1 corruption. List reads headers only, so it still shows a session whose entries are newer; it cannot show one whose header is newer.

*thread.CorruptError is the typed shape ErrCorrupt takes when the failure belongs to one place: Session, Line (1-based, the header is line 1; 0 when no one line), Entry (the entry id, when the tree is the problem) and Err (the cause). Error names the session and the place, then the cause. Unwrap returns both the class and the cause, so errors.Is(err, thread.ErrCorrupt) is true for every CorruptError and errors.Is/errors.As also reach what Err wraps.

How a turn ended is on turn.Outcome(), and the error turn.Wait() returns says why (Send turns). ErrNotPersisted is a storage incident: the run ended but its end could not be written, and its usage is in no ledger. A turn entry with late_steps > 0 means step writes failed and landed late: nothing was lost, and the storage was unhealthy for that long. The decision errors (ErrNotPending, ErrExpired, ErrDelegated, ErrInvalidDecision, ErrSignatureRequired, ErrBadSignature, ErrReplay, ErrArgsChanged) each refuse one decision and record no decision from the caller. A refused signed decision naming a pending call leaves a signed audit entry (at most 16 per request), and an expired request is denied by the session itself (Approvals in sessions).

A Send that meets a busy session is, by default, queued, and durable: an accepted receipt entry is written and flushed before Send returns. A steer writes a queued receipt the same way. Receipts are written only for a busy session; an idle Send writes its prompt entry instead. After a crash or a Close that gave up, thread.Open restores both kinds to s.Queue(), and nothing runs until the application says so:

  • the next Send runs behind the restored sends, in order, and a restored steer is delivered into the first turn that runs;
  • s.Continue(ctx) runs them now, with no new message;
  • s.ClearQueue(ctx) drops them, on the record.

A failed Send of a message that will not run leaves the line as it found it, best effort: the receipt is settled dropped and a leaf entry moves the leaf back, in one flushed append. Restored messages run with no run options: run options are not entries. The queue is unbounded: if users can pile messages onto a running turn, check len(s.Queue()) before sending. What happens when you send while a turn runs? has the policies.

The numbers are from weft’s budget tests, measured on the maintainer’s machine on the dates given; CI enforces generous bounds around them, not the numbers.

  • Opening a session reads all of it into memory, and a Session holds its whole tree. A 100,000-entry session opens in about 3 s on both backends (2026-09-30).
  • List on jsonl reads every header in the directory on every call: the directory is the index. A page over 10,000 sessions takes about 70 ms (2026-10-01) and allocates a header’s worth per file. A header line longer than 1 MiB is not listed.
  • List on sqlite pages in SQL: walking 10,000 sessions a hundred at a time takes about 0.17 s in all (2026-10-01).
  • Query.TitleSearch costs more: jsonl reads each candidate’s whole file; sqlite scans a title column.
  • A Session’s lock is held across its storage writes. Under the default fsync policy every method of that Session, reads included, waits out an fsync in progress.
  • Watch polls every 200 ms and reads only what is new.
  • Delete does not look for open Sessions. Close first; a turn running at that moment loses the entries it had yet to write.
  • One pool per storage’s delegations. With two live pools over the same sessions, a Recover or Cancel through one settles the other’s running work failed.
  • After a restart, for each parent the new process takes over: wrap or register the agents, then p.Recover(ctx, parent). It reattaches parked children, settles finished ones from their own files, and settles failed those that never finished their first run; that run is not started again. A child whose resume a crash cut off resumes again, so an approved call whose result was not recorded runs again (below).
  • Wrap names are resume keys. Renamed a wrap, or used Submit? p.Register(childID, agent) before Recover.
  • A receipt that stays accepted or running across a restart needs Recover.
  • p.Decide records and arms; it does not wait. Follow with p.Wait. p.Decide(ctx, parent) with no decisions pumps whatever was decided by other paths, and is always safe.
  • Deleting a parent deletes no child. Delete pool.Descendants(ctx, parent) in the order returned, the parent last.
  • Cost. A child’s usage is on its receipt and in the parent’s Usage().Delegated, not in the parent run’s RunResult.Usage.
  • Depth. pool.MaxDepth(n) (default 8) bounds a delegation chain; the model reads SUBAGENT_DEPTH past it.

Run bounded child sessions with a pool has the code.

  • Keys. A thread.Keyring holds HMAC keys by id; the active key mints challenges, every key verifies. Keys are never written to a session, only key ids. Pass the ring with thread.WithKeyring at every Create and Open.
  • Rotation. Build a new ring with the new key active and the old keys still in it. Drop an old key only when nothing minted under it can still be pending; after that a decision signed with it is ErrBadSignature.
  • RequireSigned is stored in the header at Create (weft.require_signed) and enforced by every later Open; nothing turns it off. s.Grant stays an in-process, unsigned call.
  • Expiry is lazy. An expired request is denied the next time the session is touched (Decide, Resume, Send, the runner, the pool’s pump), never on a timer.
  • Quorum. A signed approval counts as its key; an unsigned one as whatever Who the caller wrote. A quorum that must hold against the deciding process itself needs RequireSigned and one key per approver.
  • The audit trail is an index, not evidence. s.Audit() entries are unsigned and unchained; put tamper-evidence in the storage (an append-only volume, a signed export). Refused signed decisions are recorded, at most 16 per request.

Approvals in sessions and Sign approval decisions have the code.

There is one retention operation: thread.Delete(ctx, st, id). It removes the session and all its entries; nothing else in the module removes data (compaction, branching, Uncompact and ClearQueue all append). There is no TTL, no archive tier and no per-entry redaction; build them on thread.List and Delete:

sessions/operations.go
cutoff := base.Add(-48 * time.Hour) // keep two days
for {
page, err := thread.List(ctx, st, thread.Query{Before: cutoff, Limit: 100})
if err != nil {
return err
}
if len(page.Sessions) == 0 {
break
}
for _, h := range page.Sessions {
if err := thread.Delete(ctx, st, h.ID); err != nil { // closed sessions only
return err
}
fmt.Fprintln(w, "deleted:", h.ID, h.Created.Format(time.DateOnly))
}
}

sessions/operations.go on GitHub

deleted: s_week 2026-10-15
deleted: s_old 2026-10-12
kept: 1

Query.Before alone returns sessions created strictly before the cutoff, which is the retention rule; each pass lists the next page of what is left. Add pool.Descendants for a parent’s children. A session grows for as long as it is used, and so does the cost of opening it.

Every run a session starts carries these as run metadata, on every span and every log record of the run:

KeyValue
weft.session.idthe session id
weft.turnthe turn counter the run id <session>-t<n> was minted from
weft.public_idthe session’s public id, when created with thread.PublicID
weft.session.forked_from<session>#<entry>, on a fork
weft.session.parent, weft.session.parent_callthe parent session and delegating call, on a pool child
weft.session.titlethe session’s current title, once a SetInfo has named one

The session’s keys win over a caller’s colliding thread.RunOptions(weft.Metadata(...)). A key the session has no value for is set to "", so a session’s turn sent from inside another session’s tool handler never carries the enclosing run’s public id, title, fork origin or lineage as its own (Identity).

Every compaction that lands emits one record of kind compaction (event name weft.compaction) through the agent’s LoggerProvider, under the id of the last run that produced the compacted context (The compaction marker).

What the module logs on its own:

ThroughLevelFor
the agent’s logger (weft.Logger)Warna repaired load at Open, a step write that failed and was held, a compaction that failed or fell back
the agent’s loggerErrorwhat could not be recorded (a turn end, a rollback, a receipt), a contained panic in a hook
the agent’s loggerInfoeach compaction that lands
the backend’s logger (thread.OpenLogger)Warna torn tail removed, a lock taken over or broken

No Warn or Error line from thread means the storage took every write the session made.

To follow a session from another process, tail it with the thread.Watcher capability that jsonl and sqlite implement: a watcher is a reader that waits, never locks, and polls every 200 ms (Watch a session).

The format has one envelope, "weft": 1 in every header, and entry versions. A kind added after format 1 carries "v": N, the minimum reader version. So does an entry of a format-1 kind that carries a field an older reader would misread (a trim compaction, "v": 5) (the version rule). What follows for an upgrade:

  • A new build reads every older file. The goldens of every format, thread/testdata/format1 to format5, are read by every release. Nothing is rewritten on open, and there is no migration tool: none has been needed while every change was additive.
  • An older build fails loudly on newer data. A process still on the old build that opens a session the new build wrote with a newer kind or "v" fails with ErrNewerFormat until it is upgraded. Upgrade every process that opens the storage no later than the first one that writes the newer data.
  • Some additions change what an older build does, not what it reads. A build from before the accepted receipt status does not restore a queued send; one from before weft.require_signed does not enforce it. Do not roll writers back across those versions.
  • sqlite migrates its schema at Open. After a newer build opened a database, an older one fails Open with sqlite.ErrNewerSchema.
  • Read the CHANGELOG before upgrading. Pre-1.0, breaking changes ship without deprecation shims and are recorded there; a breaking thread change adds a line to its migration checklist saying what to write instead.

From the CHANGELOG’s thread 0.9.0 section (2026-10-02); each item still holds at v0.20.2:

  • Windows is unexecuted. jsonl’s LockFileEx lock and sqlite’s Windows liveness and start-time checks compile and pass GOOS=windows go vet, run by hand; CI has no Windows job, and no test has run them.
  • Stale-writer detection is a count and the header’s creation time, not a content comparison of the entries.
  • sqlite’s lock does not cross hostnames on its own. A row left by a holder with another hostname is never taken over; call sqlite.BreakLock.
  • Recover never re-runs a child’s first run. A child whose resume a crash cut off resumes again, and an approved call whose result was not recorded runs again (since 0.18.1 the godoc says so). It reads a finished child’s answer as its last assistant text; a structured Output answer is not recovered as such. It cannot rebuild the agent ancestry above a rebuilt child, though the depth limit still holds. It assumes one pool owns a storage’s delegations: with two live pools over the same sessions, a Recover or Cancel through one settles the other’s running work as failed. Several pools of one process delegating from one parent session are the exception: each skips the receipts whose child another pool watching that parent holds (since 0.18.1).
  • Audit() is an index, not evidence: entries are unsigned and unchained; whoever can write the storage can change them.
  • s.Grant is an unsigned, in-process call, under RequireSigned too.
  • The steer queue is unbounded; check len(s.Queue()).
  • jsonl List reads every header per call; sqlite pages in SQL.
  • The pool’s plumbing is still exported on Session (thread/poolplumbing.go), and the option names mix three dialects (With*, bare, Require*/On*); both wait for the freeze.

sessions/operations.go repairs a torn tail, provokes each error class, salvages, breaks a lock, applies retention and shuts down:

sessions/operations.go
package main
import (
"context"
"errors"
"fmt"
"io"
"log/slog"
"os"
"path/filepath"
"strings"
"time"
"github.com/weftgo/weft"
"github.com/weftgo/weft/thread"
"github.com/weftgo/weft/thread/jsonl"
"github.com/weftgo/weft/thread/pool"
"github.com/weftgo/weft/thread/sqlite"
"github.com/weftgo/weft/wefttest"
)
// demoOperations is the page "Operate sessions in production".
func demoOperations(ctx context.Context, w io.Writer, dir string) error {
steps := []func(context.Context, io.Writer, string) error{
opsCrash, opsErrors, opsSalvage, opsBreakLock, opsRetention, opsShutdownDemo,
}
for _, step := range steps {
if err := step(ctx, w, dir); err != nil {
return err
}
}
return nil
}
// textLogger writes slog lines to w without their time, so the demo's
// output is the same on every run.
func textLogger(w io.Writer) *slog.Logger {
return slog.New(slog.NewTextHandler(w, &slog.HandlerOptions{
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
if len(groups) == 0 && a.Key == slog.TimeKey {
return slog.Attr{}
}
return a
},
}))
}
// say is an agent whose model answers each turn with the next reply.
func say(logger *slog.Logger, replies ...string) *weft.Agent {
turns := make([]wefttest.Turn, len(replies))
for i, r := range replies {
turns[i] = wefttest.Say(r)
}
return weft.New(wefttest.Script(turns...), weft.Logger(logger))
}
// sendWait sends one user message and waits for its turn.
func sendWait(ctx context.Context, s *thread.Session, text string) error {
turn, err := s.Send(ctx, weft.User(text))
if err != nil {
return err
}
_, err = turn.Wait()
return err
}
// opsCrash: a writer killed mid-append leaves a torn final line; the
// next Open drops it and says so, the next write removes it.
func opsCrash(ctx context.Context, w io.Writer, dir string) error {
fmt.Fprintln(w, "== after a crash")
logger := textLogger(w) // your application's logger
sessions := filepath.Join(dir, "ops")
st, err := jsonl.Open(sessions,
thread.OpenLogger(logger), // where the backend reports its own repairs
)
if err != nil {
return err
}
agent := say(logger, "Order 1234 shipped on Tuesday.", "It arrives on Friday.")
s, err := thread.Create(ctx, st, agent, ctxWindow, ids("s_ops", "a"), at(base))
if err != nil {
return err
}
if err := sendWait(ctx, s, "Where is order 1234?"); err != nil {
return err
}
if err := s.Close(ctx); err != nil {
return err
}
// A writer killed inside an append leaves bytes without a newline.
path := filepath.Join(sessions, "s_ops.jsonl")
f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0)
if err != nil {
return err
}
if _, err := f.WriteString(`{"type":"message","id":"e_a4","par`); err != nil {
return err
}
if err := f.Close(); err != nil {
return err
}
s, err = thread.Open(ctx, st, "s_ops", agent, ctxWindow, ids("", "b"), at(base))
if err != nil {
return err
}
fmt.Fprintln(w, "torn line dropped:", s.LoadReport().Torn)
if err := sendWait(ctx, s, "When does it arrive?"); err != nil { // the next write truncates it
return err
}
fmt.Fprintln(w, "answer:", s.Context()[len(s.Context())-1].Text())
return s.Close(ctx)
}
// classify maps a thread error to what the caller does next.
func classify(err error) string {
switch {
case err == nil:
return "ok"
case errors.Is(err, thread.ErrBusy), errors.Is(err, thread.ErrLocked):
return "retry"
case errors.Is(err, thread.ErrStale), errors.Is(err, thread.ErrClosed):
return "reopen"
case errors.Is(err, thread.ErrNewerFormat):
return "terminal: upgrade this build"
case errors.Is(err, thread.ErrCorrupt):
return "terminal: inspect the line, or open with Salvage"
}
return "unknown: " + err.Error()
}
// opsErrors provokes each error class on one jsonl directory.
func opsErrors(ctx context.Context, w io.Writer, dir string) error {
fmt.Fprintln(w, "== errors")
logger := textLogger(io.Discard)
sessions := filepath.Join(dir, "errs")
st, err := jsonl.Open(sessions)
if err != nil {
return err
}
agent := say(logger, "Order 1234 shipped on Tuesday.")
writer, err := thread.Create(ctx, st, agent, ctxWindow, ids("s_errs", "a"), at(base))
if err != nil {
return err
}
if err := sendWait(ctx, writer, "Where is order 1234?"); err != nil {
return err
}
// Another Session on the same session, while the writer holds it.
other, err := thread.Open(ctx, st, "s_errs", agent, ctxWindow) // reads always work
if err != nil {
return err
}
report(w, "another Session", other.SetInfo(ctx, "Order 1234", nil))
if err := writer.Close(ctx); err != nil {
return err
}
report(w, "after Close", writer.SetInfo(ctx, "Order 1234", nil))
// other was opened before the writer's last append: its view is behind.
ahead, err := thread.Open(ctx, st, "s_errs", agent, ctxWindow)
if err != nil {
return err
}
if err := ahead.SetInfo(ctx, "Order 1234", nil); err != nil {
return err
}
if err := ahead.Close(ctx); err != nil {
return err
}
report(w, "a view behind", other.SetInfo(ctx, "Order 1234", nil))
return other.Close(ctx)
}
// opsSalvage: a damaged line fails Open with ErrCorrupt; Salvage skips
// it and reports it. A line from a newer weft is never skipped.
func opsSalvage(ctx context.Context, w io.Writer, dir string) error {
fmt.Fprintln(w, "== salvage")
sessions := filepath.Join(dir, "errs") // s_errs from opsErrors
path := filepath.Join(sessions, "s_errs.jsonl")
agent := say(textLogger(io.Discard))
data, err := os.ReadFile(path)
if err != nil {
return err
}
lines := strings.Split(strings.TrimSuffix(string(data), "\n"), "\n")
damaged := slicesWith(lines, 2, `{"type":"message","id":`) // line 3: a damaged line, not a torn tail
if err := os.WriteFile(path, []byte(strings.Join(damaged, "\n")+"\n"), 0o600); err != nil {
return err
}
st, err := jsonl.Open(sessions)
if err != nil {
return err
}
_, err = thread.Open(ctx, st, "s_errs", agent, ctxWindow)
report(w, "a damaged line", err)
salvaged, err := jsonl.Open(sessions, thread.Salvage())
if err != nil {
return err
}
s, err := thread.Open(ctx, salvaged, "s_errs", agent, ctxWindow)
if err != nil {
return err
}
lr := s.LoadReport()
fmt.Fprintln(w, "salvaged: skipped", lr.Skipped, "orphaned", lr.Orphaned, "torn", lr.Torn)
// The same line from a newer weft: "v" above what this build reads.
newer := slicesWith(lines, 2, strings.Replace(lines[2], `{"type":"message",`, `{"type":"message","v":2,`, 1))
if err := os.WriteFile(path, []byte(strings.Join(newer, "\n")+"\n"), 0o600); err != nil {
return err
}
_, err = thread.Open(ctx, salvaged, "s_errs", agent, ctxWindow)
report(w, "a newer line, under Salvage", err)
return nil
}
// slicesWith returns a copy of lines with line i replaced.
func slicesWith(lines []string, i int, line string) []string {
out := append([]string(nil), lines...)
out[i] = line
return out
}
// report prints what a call returned and what classify makes of it.
func report(w io.Writer, what string, err error) {
if err == nil {
fmt.Fprintf(w, "%s: ok\n", what)
return
}
fmt.Fprintf(w, "%s: %v\n → %s\n", what, err, classify(err))
}
// opsBreakLock: a lock row held by a writer that is still alive,
// broken by hand. The old writer is stopped at its next write.
func opsBreakLock(ctx context.Context, w io.Writer, dir string) error {
fmt.Fprintln(w, "== break a lock")
logger := textLogger(io.Discard) // BreakLock logs one Warn naming the holder it removed
path := filepath.Join(dir, "ops.db")
stA, err := sqlite.Open(path, thread.OpenLogger(logger))
if err != nil {
return err
}
agent := say(textLogger(io.Discard), "Order 1234 shipped on Tuesday.")
held, err := thread.Create(ctx, stA, agent, ctxWindow, ids("s_lock", "a"), at(base))
if err != nil {
return err
}
if err := sendWait(ctx, held, "Where is order 1234?"); err != nil {
return err
}
stB, err := sqlite.Open(path, thread.OpenLogger(logger)) // another Storage: another process, as the lock sees it
if err != nil {
return err
}
s, err := thread.Open(ctx, stB, "s_lock", agent, ctxWindow)
if err != nil {
return err
}
err = s.SetInfo(ctx, "Order 1234", nil) // the error names the holder's pid and host
fmt.Fprintln(w, "before:", errors.Is(err, thread.ErrLocked), classify(err))
// You vouch that the holder is gone: nothing can check it.
if err := sqlite.BreakLock(ctx, stB, "s_lock"); err != nil {
return err
}
report(w, "after BreakLock", s.SetInfo(ctx, "Order 1234", nil))
// The old holder's ErrLocked is not a retry: its lock is gone, and the
// session may have been written since. It must open the session again.
err = held.SetInfo(ctx, "Order 5678", nil)
fmt.Fprintf(w, "the old holder: %v\n → reopen (ErrLocked: %v)\n", err, errors.Is(err, thread.ErrLocked))
if err := s.Close(ctx); err != nil {
return err
}
_ = held.Close(ctx) // its lease was taken from it; Close still seals it
return nil
}
// opsRetention deletes the sessions created before a cutoff.
func opsRetention(ctx context.Context, w io.Writer, _ string) error {
fmt.Fprintln(w, "== retention")
st := thread.Memory()
agent := say(textLogger(io.Discard))
for i, name := range []string{"s_old", "s_week", "s_new"} {
created := base.Add(-time.Duration(2-i) * 72 * time.Hour) // 6 days, 3 days, 0 days old
s, err := thread.Create(ctx, st, agent, ctxWindow, ids(name, "a"), at(created))
if err != nil {
return err
}
if err := s.Close(ctx); err != nil {
return err
}
}
cutoff := base.Add(-48 * time.Hour) // keep two days
for {
page, err := thread.List(ctx, st, thread.Query{Before: cutoff, Limit: 100})
if err != nil {
return err
}
if len(page.Sessions) == 0 {
break
}
for _, h := range page.Sessions {
if err := thread.Delete(ctx, st, h.ID); err != nil { // closed sessions only
return err
}
fmt.Fprintln(w, "deleted:", h.ID, h.Created.Format(time.DateOnly))
}
}
page, err := thread.List(ctx, st, thread.Query{})
if err != nil {
return err
}
fmt.Fprintln(w, "kept:", page.Total)
return nil
}
// shutdown stops a process that writes sessions: pools first, so their
// running children settle their receipts; then every open session.
func shutdown(ctx context.Context, pools []*pool.Pool, sessions []*thread.Session) error {
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
var errs []error
for _, p := range pools {
errs = append(errs, p.Close(ctx)) // a parked child stays parked
}
for _, s := range sessions {
errs = append(errs, s.Close(ctx)) // drains the running turn and the queue
}
return errors.Join(errs...)
}
// opsShutdownDemo runs shutdown over one pool and one session.
func opsShutdownDemo(ctx context.Context, w io.Writer, _ string) error {
fmt.Fprintln(w, "== shutdown")
s, err := thread.Create(ctx, thread.Memory(), say(textLogger(io.Discard)), ctxWindow, ids("s_shut", "a"), at(base))
if err != nil {
return err
}
p := pool.New(2)
if _, err := p.Submit(ctx, s, say(textLogger(io.Discard), "Done."), "Tidy up."); err != nil {
return err
}
err = shutdown(ctx, []*pool.Pool{p}, []*thread.Session{s})
fmt.Fprintln(w, "shutdown:", err)
report(w, "a write after shutdown", s.SetInfo(ctx, "late", nil))
return nil
}

View sessions/operations.go on GitHub

View on GitHub · run it from docs-site/examples:

Terminal window
go run ./sessions operations
go test ./sessions
== after a crash
level=WARN msg="thread: session loaded with a repair" session=s_ops torn_line=5 skipped_lines=[] orphaned_entries=[]
torn line dropped: 5
level=WARN msg="thread/jsonl: removed a torn tail before appending" session=s_ops dropped_bytes=34
answer: It arrives on Friday.
== errors
another Session: thread: session is locked by another writer: s_errs
→ retry
after Close: thread: session is closed: session s_errs
→ reopen
a view behind: thread: session changed since it was opened: session s_errs holds 4 entries, this Session has seen 3; open it again
→ reopen
== salvage
a damaged line: thread: session s_errs line 3 is corrupt: unexpected end of JSON input
→ terminal: inspect the line, or open with Salvage
salvaged: skipped [3] orphaned [e_a3] torn 0
a newer line, under Salvage: thread: session format newer than this build: entry kind "message" carries v=2, this build reads v=1
→ terminal: upgrade this build
== break a lock
before: true retry
after BreakLock: ok
the old holder: thread: session is locked by another writer: s_lock (this writer's lock was broken; the session may have been written since — open it again)
→ reopen (ErrLocked: true)
== retention
deleted: s_week 2026-10-15
deleted: s_old 2026-10-12
kept: 1
== shutdown
shutdown: <nil>
a write after shutdown: thread: session is closed: session s_shut
→ reopen

Standard error is empty: every agent logs through textLogger, to the output or to io.Discard. The shutdown demo’s pool child has no context window (the pool gives children none), and its no-window warning goes to its discarded logger.

  • Make a tool that must not run twice idempotent. A crash after a resume’s started entry and before the approved call’s result is recorded runs the call again when its boundary is resumed, by the session or by Recover. Key it by weft.CallFromContext’s call id, the session id (weft.session.id in weft.MetadataFromContext) and a business key for what the call acts on, such as the order id. The call id is the same on every run of one call, so the run a resume repeats finds the first run’s entry. The session id keeps conversations apart, but it is the same on every turn of one session. Within a session only the business key reliably tells operations apart, because a later turn may reuse a call id (weft’s Gemini adapter, for one, numbers calls call_0, call_1, … per step when the API sends no id): keyed by the order id, a later turn’s refund of the same order under a repeated call id reads as already done. Name the operation itself, such as a refund request id, when one order may be refunded twice. (Source: thread/approval.go:1127-1130, 1327-1335; thread/pool/recover.go:13-36; docs/thread-operations.md:400-418)
  • Close what you opened to write. A forgotten Session holds its lease, jsonl’s file descriptor and sqlite’s lock row for the life of the process. (Source: AGENTS.md T2; docs/thread-operations.md §4)
  • Close pools before sessions. Session.Close does not wait for pool children. (Source: docs/thread-operations.md §5)
  • Back up sqlite with .backup or VACUUM INTO, not cp of the main file alone. (Source: docs/thread-operations.md §3)
  • Use Salvage to recover, not by default. It hides damage from every load, and never skips a newer weft’s data. (Source: thread/open.go Salvage godoc; AGENTS.md T5)
  • Never write a session behind its Session. st.Append on a session a Session holds breaks the one-writer rule. (Source: AGENTS.md T1)
  • Give session writers a stable hostname on sqlite, or close sessions on shutdown; BreakLock only once the old host is known gone. (Source: docs/thread-operations.md §4; thread/sqlite/sqlite.go:1170-1191)
  • Watch for Warn and Error lines from thread. Their absence means the storage took every write. (Source: docs/thread-operations.md §13)
  • Grants and the Approver never decide a delegating call at v0.20.2. weft’s operator page still advises scoping them away from wrap names, and points to Pool.Decide’s godoc for whether a version has the gap; v0.20.2’s godoc and TestChainNeverDecidesWrapper say it is closed. (Source: docs/thread-operations.md §10; thread/pool/bridge.go:1045 Decide godoc; thread/approval.go:861-895)

Symbols used: jsonl.Open · sqlite.Open · sqlite.BreakLock · sqlite.ErrNewerSchema · thread.FsyncEveryAppend · thread.FsyncOnFlush · thread.NoLock · thread.OpenLogger · thread.Salvage · thread.LoadReport · thread.OpenReport · Session.LoadReport · Session.Close · Session.Claim · thread.CorruptError · thread.ErrBusy · thread.ErrLocked · thread.ErrStale · thread.ErrClosed · thread.ErrCorrupt · thread.ErrNewerFormat · thread.ErrNotFound · thread.ErrExists · thread.ErrAwaitingApproval · thread.FormatVersion · thread.ValidID · thread.Watcher · thread.Releaser · thread.List · thread.Query · thread.Delete · thread.Create · thread.Open · Pool.Close · pool.Descendants · weft.Logger · weft.Repair