Skip to content

A multi-turn session that survives a crash

View as Markdown

A session from weft/thread keeps a conversation in an append-only file, so a process that dies loses nothing it had accepted. thread.Open in a new process finds the turns, the app’s own ledger entries and the messages that were queued, and Session.Continue runs what the dead writer had accepted.

The first process creates the session in cookbook/sessionmemory/main.go:

cookbook/sessionmemory/main.go
st, err := jsonl.Open(dir) // one <session id>.jsonl file per session
if err != nil {
fail(err)
}
s, err := thread.Create(ctx, st, agent, window)
if err != nil {
fail(err)
}
turn, err := s.Send(ctx, weft.User("Hi, I'm Sam. My order number is 5531."))
if err != nil {
fail(err)
}
res, err := turn.Wait()
if err != nil {
fail(err)
}

cookbook/sessionmemory/main.go on GitHub

The shape comes from the weft-arena scenario rw.session-memory, moved onto weft/thread. A customer introduces themselves and gives an order number. The app notes its own state for the conversation. The customer asks for the status, and while the status tool is running they send a second question. Then the process dies.

The program runs the dying process for real: run starts its own executable again with SESSIONMEMORY_CRASH set, and that child exits with status 9 in the middle of the tool call. What is on disk at that moment:

  • Turn 1: the prompt and the reply, each appended as it joined the run.
  • The ledger entry: the app’s support_plan state, a custom entry.
  • Turn 2: the prompt, and the assistant’s order_status call. Its result never arrived.
  • The queued send: the session was busy, so the second question was accepted under the default Queue policy. Its receipt entry was written and flushed before Send returned (T4).

The JSONL backend holds an advisory lock on the file while a writer has it. The lock dies with the process, so the second process can take the session over.

The second process opens the file, reads its own ledger entry, and runs the queued turn:

cookbook/sessionmemory/main.go
s, err := thread.Open(ctx, st, page.Sessions[0].ID, agent, // reads only: no lock, no run
window, thread.SummaryModel(summarizer), thread.KeepRecent(30))
if err != nil {
return err
}
defer s.Close(ctx)
plan, _ := readPlan(s)
fmt.Fprintf(w, "process 2: opened; plan %+v; queued %d; context %d messages\n", plan, len(s.Queue()), len(s.Context()))
turn, err := s.Continue(ctx) // runs what the dead writer had accepted
if err != nil {
return err
}
res, err := turn.Wait()
if err != nil {
return err
}

cookbook/sessionmemory/main.go on GitHub

  • thread.Open reads and nothing else (T3): no entry, no lock, no run. The queued question is restored to s.Queue().
  • s.Context() is what the model sees, with weft.Repair applied: the dangling order_status call reads no result recorded: the call was interrupted. The provider never receives a call without a result.
  • s.Continue runs the restored send under this ctx. Without it, the same work runs ahead of the next Send.

The second process’s agent is a new value with its own model; the conversation comes from the file. The process takes the session’s writer lease with its first write, and defer s.Close(ctx) gives it back (T1, T2).

The app’s own state lives in the same file as the conversation, as custom entries:

cookbook/sessionmemory/main.go
// planKind is the app's namespace for its ledger entries in the
// session file.
const planKind = "support_plan"
// Plan is the app's own state for the conversation. Each write appends
// the whole state, never a delta, so the last entry alone is enough.
type Plan struct {
Customer string `json:"customer"`
OrderID string `json:"order_id"`
Step string `json:"step"`
}
func writePlan(ctx context.Context, s *thread.Session, p Plan) error {
b, err := json.Marshal(p)
if err != nil {
return err
}
return s.Custom(ctx, planKind, b) // never enters the model's context; survives compaction
}
// readPlan returns the last plan entry on the session.
func readPlan(s *thread.Session) (Plan, bool) {
var p Plan
found := false
for _, e := range s.Entries() {
if c, ok := e.(thread.CustomEntry); ok && c.Kind == planKind && json.Unmarshal(c.Data, &p) == nil {
found = true
}
}
return p, found
}

cookbook/sessionmemory/main.go on GitHub

Session.Custom appends a caller-named kind with opaque JSON. It never enters the model’s context and survives every compaction. Because the plan and the transcript share one append-only file, they cannot disagree after a crash, and a new process resumes from the last plan entry instead of inferring the step from the model’s phrasing. Write the whole state each time, never a delta: then any single surviving entry is enough.

weft ships the full pattern as thread/examples/refund-plan: a refund flow that runs with -crash and dies after the manager hand-off, then resumes in a new process from the last refund_plan entry. It also versions the plan, and refuses an entry from a newer build (-future) instead of guessing at it.

A long conversation outgrows the model’s window. Session.Compact summarizes the older part with the thread.SummaryModel, keeps about thread.KeepRecent tokens raw, and deletes nothing:

cookbook/sessionmemory/main.go
before := len(s.Context())
if err := s.Compact(ctx); err != nil {
return err
}
fmt.Fprintf(w, "compacted: context %d → %d messages; the file keeps all %d entries\n", before, len(s.Context()), len(s.Entries()))

cookbook/sessionmemory/main.go on GitHub

The context drops from 9 messages to 2: the summary and the latest answer. The file still holds every entry, and the ledger entry is still the last plan. thread.ContextWindow arms the automatic trigger between turns; Compact is the manual path.

Session.Branch moves the leaf to any earlier entry by appending a leaf entry, never a rewrite:

cookbook/sessionmemory/main.go
leaf := s.Leaf() // the compacted answer
if err := s.Branch(ctx, turn.ID()); err != nil { // back to the queued turn's prompt
return err
}
redraft, err := s.Send(ctx, weft.User("Shorter, please."))
if err != nil {
return err
}
res, err = redraft.Wait()
if err != nil {
return err
}
fmt.Fprintln(w, "redraft on a branch:", res.Text(), "· context", len(s.Context()), "messages")
if err := s.WaitIdle(ctx); err != nil {
return err
}
if err := s.Branch(ctx, leaf); err != nil { // and back: nothing was lost
return err
}

cookbook/sessionmemory/main.go on GitHub

The branch starts at the queued turn’s prompt, before the compaction, so its context is the raw history plus the redraft. Branching back to the saved leaf restores the compacted view: nothing on either branch was lost.

weft’s thread/examples/session walks one session through its whole life on the same backend: two turns, a label, a branch off the first answer, a fork into a new session, a compaction with a preview of its plan, a close, and a reopen from disk. Its ids are deterministic (thread.IDs), so its output is stable. Read it next to this recipe for the operations this one leaves out: Label, Fork, PreviewCompaction and ApplyCompaction.

Both processes record with otel.Install(otel.Local("")). The local sink writes synchronously, so the dying process loses nothing to os.Exit. Every turn’s run carries weft.session.id and weft.turn, and the program lists the session’s runs from the sink:

  • Turns 1, 3 and 4 succeeded. Turn 2 reads running: its process died mid-run and no record says it ended. Once nothing has been heard from it for 30 seconds (obsdb.InterruptedAfter), Studio reads it interrupted.
  • Browse sessions and traces in Studio lists the session with one row per turn, the redraft on its branch included.
  • The compaction is a session marker filed under the last run that produced the context, and the run page draws it.
A session's page in Studio: four turns of shop-assistant, turn 2 "What's the status of my order?" interrupted with no steps, turns 1, 3 and 4 succeededA session's page in Studio: four turns of shop-assistant, turn 2 "What's the status of my order?" interrupted with no steps, turns 1, 3 and 4 succeeded
The session's turns table (?view=table&order=oldest), opened with weft studio on the program's local sink: the header counts 4 turns, turn 1 succeeded and turn 2 interrupted with no steps.
FeatureWhat it does hereGuide
thread.Create, Send, Turn.Waitdurable turns on a JSONL fileSend turns and wait for them
The Queue busy policyaccepts the second question while turn 2 runsWhat happens when you send while a turn runs?
thread.Open, Queue, Continueresume in a new processOperate sessions in production
Session.Customthe app’s ledger in the same fileLabel, branch and fork a session
Compact, SummaryModel, KeepRecentkeep the context inside the windowKeep long sessions inside the context window
Session.Branchredraft from an earlier entryLabel, branch and fork a session
jsonl.Openthe backend and its writer lockStore sessions: JSONL, SQLite or memory
cookbook/sessionmemory/main.go
// Command sessionmemory is the recipe "A multi-turn session that survives
// a crash": go run ./cookbook/sessionmemory. A weft/thread session on a
// JSONL file holds a support conversation and the app's own ledger
// entry. The first process dies in the middle of a tool call with a
// second message already accepted; a second process opens the same file,
// finds the conversation, the ledger and the queued message where the
// first left them, runs the queued turn, compacts the context and
// branches to redraft an answer. The first process is this same program,
// started again with SESSIONMEMORY_CRASH set. The models are scripted
// with wefttest, so it runs offline; the session files go to a temporary
// directory that is removed at exit, and both processes record their
// runs to the local sink ($WEFT_DB, else ./.weft/weft.db).
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"os"
"os/exec"
"time"
"github.com/weftgo/weft"
"github.com/weftgo/weft/obsdb"
"github.com/weftgo/weft/otel"
"github.com/weftgo/weft/thread"
"github.com/weftgo/weft/thread/jsonl"
"github.com/weftgo/weft/wefttest"
)
// crashEnv names the session directory of the process that is meant to
// die. main and TestMain both check it first.
const crashEnv = "SESSIONMEMORY_CRASH"
type OrderInput struct {
OrderID string `json:"order_id" jsonschema:"the order id, e.g. 5531"`
}
// planKind is the app's namespace for its ledger entries in the
// session file.
const planKind = "support_plan"
// Plan is the app's own state for the conversation. Each write appends
// the whole state, never a delta, so the last entry alone is enough.
type Plan struct {
Customer string `json:"customer"`
OrderID string `json:"order_id"`
Step string `json:"step"`
}
func writePlan(ctx context.Context, s *thread.Session, p Plan) error {
b, err := json.Marshal(p)
if err != nil {
return err
}
return s.Custom(ctx, planKind, b) // never enters the model's context; survives compaction
}
// readPlan returns the last plan entry on the session.
func readPlan(s *thread.Session) (Plan, bool) {
var p Plan
found := false
for _, e := range s.Entries() {
if c, ok := e.(thread.CustomEntry); ok && c.Kind == planKind && json.Unmarshal(c.Data, &p) == nil {
found = true
}
}
return p, found
}
// quiet is the agents' logger: thread reports through it, and the
// example keeps only its warnings.
var quiet = weft.Logger(slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelWarn})))
// window is the model's context window in tokens: it arms automatic
// compaction, which Compact also runs by hand.
var window = thread.ContextWindow(128_000)
// orderStatus is the shop's tool. hang, when set, makes it block until
// the process dies: the first process's crash point.
func orderStatus(hang chan<- struct{}) *weft.ToolDef {
return weft.Tool("order_status", "Shipping status of an order.",
func(ctx context.Context, in OrderInput) (string, error) {
if hang != nil {
close(hang)
<-ctx.Done() // never, in practice: the process exits first
return "", ctx.Err()
}
return "order " + in.OrderID + ": shipped, arriving Thursday", nil
})
}
// crash is the first process: two turns and a queued third, then death
// in the middle of the second turn's tool call.
func crash(dir string) {
ctx := context.Background()
otel.Install(otel.Local("")) // the local sink writes synchronously: nothing is lost to os.Exit
hang := make(chan struct{})
agent := weft.New(wefttest.Script(
wefttest.Say("Nice to meet you, Sam. I noted order 5531."),
wefttest.ToolCalls(wefttest.Call{ID: "os1", Name: "order_status", Args: `{"order_id":"5531"}`}),
), weft.Name("shop-assistant"), quiet, orderStatus(hang))
st, err := jsonl.Open(dir) // one <session id>.jsonl file per session
if err != nil {
fail(err)
}
s, err := thread.Create(ctx, st, agent, window)
if err != nil {
fail(err)
}
turn, err := s.Send(ctx, weft.User("Hi, I'm Sam. My order number is 5531."))
if err != nil {
fail(err)
}
res, err := turn.Wait()
if err != nil {
fail(err)
}
fmt.Println("process 1: turn 1:", res.Text())
if err := s.WaitIdle(ctx); err != nil {
fail(err)
}
if err := writePlan(ctx, s, Plan{Customer: "Sam", OrderID: "5531", Step: "checking_status"}); err != nil {
fail(err)
}
if _, err := s.Send(ctx, weft.User("What's the status of my order?")); err != nil {
fail(err)
}
<-hang // turn 2 is inside order_status
// The session is busy, so this Send is queued: its receipt entry is
// on disk before Send returns.
if _, err := s.Send(ctx, weft.User("Also, is my second parcel, order 5532, on the way?")); err != nil {
fail(err)
}
fmt.Println("process 1: turn 2 is inside order_status; turn 3 queued:", len(s.Queue()))
fmt.Println("process 1: dies without Close")
os.Exit(9)
}
// reopen is the second process: open the file the first one left,
// carry on, compact and branch.
func reopen(ctx context.Context, w io.Writer, dir string) error {
st, err := jsonl.Open(dir)
if err != nil {
return err
}
page, err := thread.List(ctx, st, thread.Query{Limit: 1})
if err != nil {
return err
}
if len(page.Sessions) != 1 {
return fmt.Errorf("want one session in %s, found %d", dir, len(page.Sessions))
}
agent := weft.New(wefttest.Script(
wefttest.ToolCalls(wefttest.Call{ID: "os2", Name: "order_status", Args: `{"order_id":"5532"}`}),
wefttest.Say("Order 5532 has shipped too and arrives Thursday."),
wefttest.Say("Both parcels are on their way; 5532 arrives Thursday."),
), weft.Name("shop-assistant"), quiet, orderStatus(nil))
summarizer := wefttest.Script(wefttest.Say("Customer Sam: orders 5531 and 5532; 5532 arrives Thursday."))
s, err := thread.Open(ctx, st, page.Sessions[0].ID, agent, // reads only: no lock, no run
window, thread.SummaryModel(summarizer), thread.KeepRecent(30))
if err != nil {
return err
}
defer s.Close(ctx)
plan, _ := readPlan(s)
fmt.Fprintf(w, "process 2: opened; plan %+v; queued %d; context %d messages\n", plan, len(s.Queue()), len(s.Context()))
turn, err := s.Continue(ctx) // runs what the dead writer had accepted
if err != nil {
return err
}
res, err := turn.Wait()
if err != nil {
return err
}
fmt.Fprintln(w, "process 2: queued turn:", res.Text())
for _, m := range s.Context() {
for _, p := range m.Content {
if r, ok := p.(weft.ToolResultPart); ok {
fmt.Fprintf(w, " %s → %s\n", r.CallID, r.Content)
}
}
}
if err := s.WaitIdle(ctx); err != nil {
return err
}
if err := writePlan(ctx, s, Plan{Customer: "Sam", OrderID: "5532", Step: "answered"}); err != nil {
return err
}
before := len(s.Context())
if err := s.Compact(ctx); err != nil {
return err
}
fmt.Fprintf(w, "compacted: context %d → %d messages; the file keeps all %d entries\n", before, len(s.Context()), len(s.Entries()))
plan, _ = readPlan(s)
fmt.Fprintf(w, "plan after compaction: %+v\n", plan)
leaf := s.Leaf() // the compacted answer
if err := s.Branch(ctx, turn.ID()); err != nil { // back to the queued turn's prompt
return err
}
redraft, err := s.Send(ctx, weft.User("Shorter, please."))
if err != nil {
return err
}
res, err = redraft.Wait()
if err != nil {
return err
}
fmt.Fprintln(w, "redraft on a branch:", res.Text(), "· context", len(s.Context()), "messages")
if err := s.WaitIdle(ctx); err != nil {
return err
}
if err := s.Branch(ctx, leaf); err != nil { // and back: nothing was lost
return err
}
fmt.Fprintln(w, "back on the first branch: context", len(s.Context()), "messages")
// Both processes recorded their turns' runs under the session's id.
runs, err := otel.LocalDB().Runs(ctx, obsdb.RunQuery{SessionID: s.ID()})
if err != nil {
return err
}
for i := len(runs.Runs) - 1; i >= 0; i-- { // oldest first
r := runs.Runs[i]
fmt.Fprintf(w, "recorded: turn %d %s\n", r.Turn, r.Status)
}
return nil
}
// run starts the crashing process, then recovers in this one.
func run(ctx context.Context, w io.Writer) (err error) {
defer otel.Install(otel.Local(""))()
dir, err := os.MkdirTemp("", "weft-session-memory-")
if err != nil {
return err
}
defer func() { err = errors.Join(err, os.RemoveAll(dir)) }()
exe, err := os.Executable()
if err != nil {
return err
}
cmd := exec.CommandContext(ctx, exe)
cmd.Env = append(os.Environ(), crashEnv+"="+dir)
cmd.Stdout, cmd.Stderr = w, os.Stderr
cmd.WaitDelay = 10 * time.Second
var exit *exec.ExitError
if err := cmd.Run(); !errors.As(err, &exit) || exit.ExitCode() != 9 {
return fmt.Errorf("the first process should have died with status 9: %v", err)
}
return reopen(ctx, w, dir)
}
func fail(err error) {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
func main() {
if dir := os.Getenv(crashEnv); dir != "" {
crash(dir)
}
if err := run(context.Background(), os.Stdout); err != nil {
fail(err)
}
}

View cookbook/sessionmemory/main.go on GitHub

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

Terminal window
go run ./cookbook/sessionmemory
go test ./cookbook/sessionmemory
process 1: turn 1: Nice to meet you, Sam. I noted order 5531.
process 1: turn 2 is inside order_status; turn 3 queued: 1
process 1: dies without Close
process 2: opened; plan {Customer:Sam OrderID:5531 Step:checking_status}; queued 1; context 5 messages
process 2: queued turn: Order 5532 has shipped too and arrives Thursday.
os1 → no result recorded: the call was interrupted
os2 → order 5532: shipped, arriving Thursday
compacted: context 9 → 2 messages; the file keeps all 14 entries
plan after compaction: {Customer:Sam OrderID:5532 Step:answered}
redraft on a branch: Both parcels are on their way; 5532 arrives Thursday. · context 8 messages
back on the first branch: context 2 messages
recorded: turn 1 succeeded
recorded: turn 2 running
recorded: turn 3 succeeded
recorded: turn 4 succeeded

The test binary plays the dying process too: its TestMain checks SESSIONMEMORY_CRASH first, as main does. The session files go to a temporary directory that is removed at exit.

  • Close every Session that wrote. Until Close, no other Session in the process can write the session; the dead process’s lock went with it, a live one’s does not. (Source: AGENTS.md T1, T2; weft/thread/jsonl/jsonl.go:8-14)
  • Call Continue after Open when restored input should run now. Open runs nothing; without Continue the queued send waits for the next Send. (Source: AGENTS.md T3, weft/thread/session.go:1545-1577)
  • Keep app state in custom entries, whole each time. They survive compaction and never reach the model, and one complete entry is enough to resume. (Source: weft/thread/session.go:1443-1450, weft/thread/examples/refund-plan/main.go)
  • Do not infer the app’s step from the transcript. The model’s phrasing changes between runs; the ledger entry does not. (Source: weft/thread/examples/refund-plan/main.go package godoc)
  • Set ContextWindow. Without a known window automatic compaction stays off, with one warning; Compact by hand always works. (Source: weft/thread/compactopts.go:36-43)
  • Branch between turns. Branch while a turn runs fails with ErrBusy; Fork works mid-turn. (Source: weft/thread/branch.go:47-67 godoc)

Symbols used: thread.Create · thread.Open · thread.List · thread.Query · thread.Session · Session.Send · Session.Queue · Session.Continue · Session.Context · Session.Entries · Session.Custom · Session.Compact · Session.Branch · Session.Leaf · Session.WaitIdle · Session.Close · Turn.Wait · Turn.ID · thread.CustomEntry · thread.ContextWindow · thread.SummaryModel · thread.KeepRecent · jsonl.Open · weft.User · weft.Repair · obsdb.InterruptedAfter · obsdb.RunQuery · otel.Install · otel.Local · weft.Logger · wefttest.Script