A multi-turn session that survives a crash
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:
st, err := jsonl.Open(dir) // one <session id>.jsonl file per sessionif 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)}How it works
Section titled “How it works”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_planstate, a custom entry. - Turn 2: the prompt, and the assistant’s
order_statuscall. Its result never arrived. - The queued send: the session was busy, so the second question was accepted under the default
Queuepolicy. Its receipt entry was written and flushed beforeSendreturned (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.
Survive the crash
Section titled “Survive the crash”The second process opens the file, reads its own ledger entry, and runs the queued turn:
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 acceptedif err != nil { return err}res, err := turn.Wait()if err != nil { return err}thread.Openreads and nothing else (T3): no entry, no lock, no run. The queued question is restored tos.Queue().s.Context()is what the model sees, withweft.Repairapplied: the danglingorder_statuscall readsno result recorded: the call was interrupted. The provider never receives a call without a result.s.Continueruns the restored send under thisctx. Without it, the same work runs ahead of the nextSend.
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 refund-plan ledger
Section titled “The refund-plan ledger”The app’s own state lives in the same file as the conversation, as custom entries:
// 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}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.
Compact and branch
Section titled “Compact and branch”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:
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()))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:
leaf := s.Leaf() // the compacted answerif 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}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.
A session from start to finish
Section titled “A session from start to finish”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.
What to look at in Studio
Section titled “What to look at in Studio”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 itinterrupted. - 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.


The weft features it combines
Section titled “The weft features it combines”| Feature | What it does here | Guide |
|---|---|---|
thread.Create, Send, Turn.Wait | durable turns on a JSONL file | Send turns and wait for them |
The Queue busy policy | accepts the second question while turn 2 runs | What happens when you send while a turn runs? |
thread.Open, Queue, Continue | resume in a new process | Operate sessions in production |
Session.Custom | the app’s ledger in the same file | Label, branch and fork a session |
Compact, SummaryModel, KeepRecent | keep the context inside the window | Keep long sessions inside the context window |
Session.Branch | redraft from an earlier entry | Label, branch and fork a session |
jsonl.Open | the backend and its writer lock | Store sessions: JSONL, SQLite or memory |
The program
Section titled “The program”// 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 on GitHub · run it from docs-site/examples:
go run ./cookbook/sessionmemorygo test ./cookbook/sessionmemoryprocess 1: turn 1: Nice to meet you, Sam. I noted order 5531.process 1: turn 2 is inside order_status; turn 3 queued: 1process 1: dies without Closeprocess 2: opened; plan {Customer:Sam OrderID:5531 Step:checking_status}; queued 1; context 5 messagesprocess 2: queued turn: Order 5532 has shipped too and arrives Thursday. os1 → no result recorded: the call was interrupted os2 → order 5532: shipped, arriving Thursdaycompacted: context 9 → 2 messages; the file keeps all 14 entriesplan after compaction: {Customer:Sam OrderID:5532 Step:answered}redraft on a branch: Both parcels are on their way; 5532 arrives Thursday. · context 8 messagesback on the first branch: context 2 messagesrecorded: turn 1 succeededrecorded: turn 2 runningrecorded: turn 3 succeededrecorded: turn 4 succeededThe 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.
Best practices & gotchas
Section titled “Best practices & gotchas”- 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
ContinueafterOpenwhen restored input should run now.Openruns nothing; withoutContinuethe queued send waits for the nextSend. (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.gopackage godoc) - Set
ContextWindow. Without a known window automatic compaction stays off, with one warning;Compactby hand always works. (Source:weft/thread/compactopts.go:36-43) - Branch between turns.
Branchwhile a turn runs fails withErrBusy;Forkworks mid-turn. (Source:weft/thread/branch.go:47-67godoc)
See also
Section titled “See also”- What is a session?: the session, the turn and the thread rules
- Operate sessions in production: crashes, salvage and the writer lease
- Keep long sessions inside the context window (compaction)
- Label, branch and fork a session
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