What is a session?
A session is a conversation that weft/thread stores as an append-only tree of entries: messages, turn ledgers, labels, summaries. A *thread.Session holds that tree in memory and is the session’s only writer until it closes. The prompt is written to the storage before the run starts and every step’s messages land as they join the run, so a crash loses at most the step in flight and the turn’s closing entry.
sessions/overview.go creates a session on the JSONL backend, runs one turn and closes it:
st, err := jsonl.Open(dir) // one <id>.jsonl file per sessionif err != nil { return err}s, err := thread.Create(ctx, st, agent, ctxWindow, ids("s_support", "a"))if err != nil { return err}turn, err := s.Send(ctx, weft.User("Where is order 1234?"))if err != nil { return err}res, err := turn.Wait()if err != nil { return err}fmt.Fprintln(w, "answer:", res.Text())fmt.Fprintln(w, "run:", turn.RunID(), "entries:", len(s.Entries()))if err := s.Close(ctx); err != nil { // drain, seal, give up the writer's lease return err}answer: Order 1234 shipped on Tuesday.run: s_support-t1 entries: 3The turn wrote three entries: the prompt, the reply and the turn’s ledger. The ids helper pins the ids so the output is stable; an application leaves it out. ctxWindow is thread.ContextWindow(128_000), the model’s context window, which arms automatic compaction.
What a session is
Section titled “What a session is”The core is stateless on purpose; weft/thread is the layer above it. A session is a header and then its entries, in append order. Each entry has an id, a parent and a time, and the leaf is the entry the next one attaches to. What the model sees, s.Context(), is the messages on the path from a root to the leaf, repaired with weft.Repair. Nothing is rewritten or deleted in place: branching appends a leaf entry, a fork writes a new session, and a compaction appends a summary.
On the JSONL backend a session is one file you can read with jq and back up with cp: one header line, then one line per entry. The other backends store the same lines (Store sessions).
thread imports the core, the standard library and the OTel API (for the compaction marker record), never a database driver; the SQLite driver lives in thread/sqlite alone. Godoc examples cover most of the package; ExampleCreate shows a session carrying a title, application state and an application message, and ExampleHeader the header line itself.
Create and open
Section titled “Create and open”thread.Create(ctx, st, agent, opts...) starts a new session in a thread.Storage: a fresh header under a new time-sortable id, and an empty tree. The header is all it writes. The agent is the session’s own: Send runs it and compaction summarizes with its model; it must not be nil. An id the storage already holds fails with thread.ErrExists.
thread.Open(ctx, st, id, agent, opts...) loads a stored session, positioned at its leaf. Options are thread.SessionOption values, the same at Create, Open and Fork; header options (WithMeta, PublicID, WithLineage) fail Open with ErrCreateOnly.
Open is read-only (T3). It validates the tree (unique valid ids, every parent an earlier entry) and refuses a file that fails with thread.ErrCorrupt. It writes no entry, takes no lock and starts no run. Input a stopped writer had accepted and not settled is restored to the queue and waits for you. Here a writer is shut down while a turn runs and a second message waits behind it; the next process opens the session:
st2, err := jsonl.Open(dir)if err != nil { return err}reopened, err := thread.Open(ctx, st2, "s_export", next, ctxWindow, ids("", "b"))if err != nil { return err}for _, q := range reopened.Queue() { // what the stopped writer accepted, restored fmt.Fprintln(w, "restored:", q.Policy, q.Msg.Text())}fmt.Fprintln(w, "model calls after Open:", len(model.Requests()))
turn, err := reopened.Continue(ctx) // run it now; the next Send would tooif err != nil { return err}res, err := turn.Wait()if err != nil { return err}fmt.Fprintln(w, "continued:", res.Text())restored: queue Then email it to me.model calls after Open: 0continued: Sent to the address on file.Open restored the queued send and called no model. s.Continue(ctx) runs it now; without it, the next Send runs it first (Send turns). s.Queue() lists what was restored and s.ClearQueue(ctx) drops it (Busy policies). The package example is ExampleOpen.
Three accessors identify a session: s.ID() is the header’s id and the storage key; s.Storage() returns the storage it was created or opened on, read-only by convention (thread/pool creates child sessions there); and inside a tool that a session’s turn runs, thread.SessionFromContext(ctx) returns that session. Outside a session’s run it returns nil.
One writer
Section titled “One writer”One Session writes a session (T1). A Session takes its session’s writer lease with its first write (Create and Fork are first writes) and holds it until Close. Another Session on the same session opens and reads; every write it makes fails with thread.ErrLocked and changes nothing. A Session whose view fell behind, because another writer appended after it was opened, fails its write with thread.ErrStale: open the session again.
writer, err := thread.Open(ctx, st, "s_support", agent, ctxWindow, ids("", "b"))if err != nil { return err}other, err := thread.Open(ctx, st, "s_support", agent, ctxWindow, ids("", "c"))if err != nil { return err}if err := writer.Claim(ctx); err != nil { // the writer's lease, taken before any write return err}fmt.Fprintln(w, "other reads:", len(other.Context()), "messages")err = other.SetInfo(ctx, "Order 1234", nil)fmt.Fprintln(w, "other writes:", errors.Is(err, thread.ErrLocked))
if err := writer.SetInfo(ctx, "Order 1234: shipped", nil); err != nil { return err}if err := writer.Close(ctx); err != nil { return err}err = other.SetInfo(ctx, "Order 1234", nil)fmt.Fprintln(w, "after the writer closed:", errors.Is(err, thread.ErrStale))if err := other.Close(ctx); err != nil { return err}again, err := thread.Open(ctx, st, "s_support", agent, ctxWindow, ids("", "d"))if err != nil { return err}fmt.Fprintln(w, "reopened:", again.Title())other reads: 2 messagesother writes: trueafter the writer closed: truereopened: Order 1234: shippedThe rule has two layers. Between processes and between Storage values, the backend’s own lock refuses a second writer with ErrLocked (a file lock on JSONL, a lock row on SQLite). Between Session values on one Storage value, the lease does it: the thread.Leaser capability, which Memory, jsonl and sqlite implement. Reading never takes either: Open, List, Load, Watch and every read of a Session work while another writer holds the session. The stale check compares the stored header’s creation time and the number of entry lines, not contents. The package example is ExampleSession_Close_handOver.
s.Claim(ctx) takes the writer lease now, without writing an entry. It returns nil when this Session holds the lease (or the storage has no Leaser to ask), ErrLocked while another writer holds the session (nothing taken), ErrStale when the stored session moved past this Session’s view (the lease is given back, so a fresh Session can claim it), and ErrClosed once the Session is sealed. A Session that claimed holds the lease until Close, as one that wrote does, so claim only with a Close to come. weft/runtime uses it to make sure it is the writer before it acknowledges a debugger’s decision.
Close what you open
Section titled “Close what you open”s.Close(ctx) is how a writer stops (T2). Close does four things in order:
- New work stops at once:
SendandContinuefail withthread.ErrClosed. - It waits for the running turn, the sends queued behind it and any approval resume those turns arm. Sends queued behind an approval boundary that nobody decides cannot drain: once no turn runs,
Closegoes on and their Turns end withErrClosed. - It seals the Session: every later write fails with
ErrClosed. Reads keep answering, andForkstill works because it writes another session. - It releases the lease and the backend’s hold, so another writer can take the session.
A queued Turn that ends with ErrClosed is not lost. Its accepted receipt stays in the file, the next Open restores it to s.Queue(), and it runs once the boundary is decided. A caller that sends the message again on ErrClosed gets it answered twice: reopen and read s.Queue() instead.
If ctx ends while Close waits, Close gives up: it cancels the running turn, ends every queued Turn with ErrClosed and returns ctx.Err(). Call Close again to finish sealing and releasing. The queued sends keep their receipts in the file, and the next Open restores them, as the region above shows:
close gave up: truerunning turn: canceledqueued turn: canceled trueClose is idempotent. It does not wait for thread/pool children (close the pool first), and it must not be called from inside the session’s own run, a tool or a hook, because it would wait for the turn that calls it. The package example is ExampleSession_Close.
Durability
Section titled “Durability”Accepted input is durable input (T4). A Send that returns a Turn has written and flushed its prompt, or the receipt entry of a message it queued or steered. The run’s messages are appended as they join its transcript, through weft.OnMessages, the core’s transcript observer, each step once (ADR 0011 §7). The turn’s end normally appends only its bookkeeping: the turn entry and any receipts or approval entries, in one atomic batch that completes even if the caller’s context is canceled.
So a crash mid-turn loses at most the step in flight (its partial text) and the closing turn entry; the prompt, or the receipt, and every finished step are already stored. A tool call left without a result is answered by the loop’s input repair on the next run, so the next model sees a complete transcript. A failed turn whose final form differs from its raw tail (an interrupt’s golden texts) is rewritten from its first differing message on a fresh line, attached after the last entry that still matches; the raw tail stays on its own branch. No leaf entry is written for that; a leaf entry back to where the turn started is written only for an overflow re-run’s failed attempt.
How durable “stored” is depends on the backend and its fsync policy. thread.Memory() loses everything with the process. On jsonl and sqlite every append is fsynced before it returns by default, so it survives an OS crash or a power cut; with thread.FsyncOnFlush() an append survives the process dying, and only what was flushed survives an OS crash (Store sessions).
Readers fail loudly (T5). An entry kind or a "v" version this build does not know is thread.ErrNewerFormat, never skipped. A damaged line is ErrCorrupt naming the line; opened with thread.Salvage() the backend skips it and reports the skip in s.LoadReport(), as it always reports a torn final line it dropped (Recover a damaged file with Salvage).
IDs and clocks
Section titled “IDs and clocks”Session and entry ids are time-sortable. thread.NewSessionID() returns s_ plus 26 characters: a millisecond timestamp then random bits, in Crockford base32 (the ULID shape). thread.NewEntryID() returns e_ plus 26. Ids born in the same millisecond order randomly, so a session’s order of record is its entry order, never id order. thread.ValidID(id) reports whether an id is 1 to 128 letters, digits, _ or -, so an id is always one path component:
id := thread.NewSessionID()fmt.Fprintln(w, "new id:", id[:2], len(id), thread.ValidID(id), thread.ValidID("../etc/passwd"))new id: s_ 28 true falseTwo options pin what a session mints, for tests and examples. thread.IDs(fn) takes every id from fn: the session id Create or Fork generates, then each entry id. An id that fails ValidID or repeats one the session holds fails the write. thread.Clock(now) makes now the session’s time source: the header’s Created, every entry’s Created, and the approval machinery’s expiry arithmetic, all in UTC. Both may run with the session’s lock held, so they must return quickly and never call the Session; the Clock function may also be called from the runner’s goroutine and must be safe for concurrent use. The examples are ExampleNewSessionID and ExampleClock.
What it does not do
Section titled “What it does not do”- It does not merge writers. One Session writes; a second is refused, not reconciled. On a backend without
Leasertwo Sessions on oneStoragevalue both write, each blind to the other. - It does not run anything on
Open. Restored input waits forSendorContinue. - It does not delete history.
thread.Deleteremoves a whole session; nothing else removes data.Deletedoes not look for open Sessions, so close one first. - It does not freeze the format yet.
Stability
Section titled “Stability”weft/thread is pre-1.0 and not frozen: its API and its stored format may change between minor versions, each change recorded in the CHANGELOG with what to write instead. What holds today: a reader fails loudly on what it does not know, and golden files pin every format version the current build reads (The session log format).
Complete example
Section titled “Complete example”sessions/overview.go creates, writes, hands over, restores and mints ids:
package main
import ( "context" "errors" "fmt" "io"
"github.com/weftgo/weft" "github.com/weftgo/weft/thread" "github.com/weftgo/weft/thread/jsonl" "github.com/weftgo/weft/wefttest")
// demoOverview is the page "What is a session?": create a session, run a// turn, close it; one writer at a time; and what Open restores after a// writer stopped with work queued.func demoOverview(ctx context.Context, w io.Writer, dir string) error { agent := weft.New(wefttest.Script( wefttest.Say("Order 1234 shipped on Tuesday."), ), weft.Name("support"))
st, err := jsonl.Open(dir) // one <id>.jsonl file per session if err != nil { return err } s, err := thread.Create(ctx, st, agent, ctxWindow, ids("s_support", "a")) if err != nil { return err } turn, err := s.Send(ctx, weft.User("Where is order 1234?")) if err != nil { return err } res, err := turn.Wait() if err != nil { return err } fmt.Fprintln(w, "answer:", res.Text()) fmt.Fprintln(w, "run:", turn.RunID(), "entries:", len(s.Entries())) if err := s.Close(ctx); err != nil { // drain, seal, give up the writer's lease return err }
if err := oneWriter(ctx, w, st, agent); err != nil { return err } if err := restore(ctx, w, dir); err != nil { return err }
id := thread.NewSessionID() fmt.Fprintln(w, "new id:", id[:2], len(id), thread.ValidID(id), thread.ValidID("../etc/passwd")) return nil}
// oneWriter opens the stored session twice on one Storage value: the// first Session to write is the writer until it closes; the other reads,// and its writes are refused.func oneWriter(ctx context.Context, w io.Writer, st thread.Storage, agent *weft.Agent) error { writer, err := thread.Open(ctx, st, "s_support", agent, ctxWindow, ids("", "b")) if err != nil { return err } other, err := thread.Open(ctx, st, "s_support", agent, ctxWindow, ids("", "c")) if err != nil { return err } if err := writer.Claim(ctx); err != nil { // the writer's lease, taken before any write return err } fmt.Fprintln(w, "other reads:", len(other.Context()), "messages") err = other.SetInfo(ctx, "Order 1234", nil) fmt.Fprintln(w, "other writes:", errors.Is(err, thread.ErrLocked))
if err := writer.SetInfo(ctx, "Order 1234: shipped", nil); err != nil { return err } if err := writer.Close(ctx); err != nil { return err } err = other.SetInfo(ctx, "Order 1234", nil) fmt.Fprintln(w, "after the writer closed:", errors.Is(err, thread.ErrStale)) if err := other.Close(ctx); err != nil { return err } again, err := thread.Open(ctx, st, "s_support", agent, ctxWindow, ids("", "d")) if err != nil { return err } fmt.Fprintln(w, "reopened:", again.Title()) return again.Close(ctx)}
// restore stops a writer while a turn runs and a second message waits// behind it, then opens the session again as the next process would.func restore(ctx context.Context, w io.Writer, dir string) error { export, started, _ := slowTool("export") agent := weft.New(wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "export", ID: "call_1"}), ), export) st, err := jsonl.Open(dir) if err != nil { return err } s, err := thread.Create(ctx, st, agent, ctxWindow, ids("s_export", "a")) if err != nil { return err } running, err := s.Send(ctx, weft.User("Export my order history.")) if err != nil { return err } <-started queued, err := s.Send(ctx, weft.User("Then email it to me.")) // Queue: an accepted receipt, flushed if err != nil { return err }
// Shutdown with no time left: Close gives up waiting, cancels the // running turn and ends the queued Turn. A second Close finishes. expired, cancel := context.WithCancel(ctx) cancel() err = s.Close(expired) fmt.Fprintln(w, "close gave up:", errors.Is(err, context.Canceled)) if err := s.Close(ctx); err != nil { return err } _, err = running.Wait() fmt.Fprintln(w, "running turn:", running.Outcome()) _, err = queued.Wait() fmt.Fprintln(w, "queued turn:", queued.Outcome(), errors.Is(err, thread.ErrClosed))
// The next process: a fresh Storage over the same directory, and an // agent whose model has served nothing yet. model := wefttest.Script(wefttest.Say("Sent to the address on file.")) next := weft.New(model) st2, err := jsonl.Open(dir) if err != nil { return err } reopened, err := thread.Open(ctx, st2, "s_export", next, ctxWindow, ids("", "b")) if err != nil { return err } for _, q := range reopened.Queue() { // what the stopped writer accepted, restored fmt.Fprintln(w, "restored:", q.Policy, q.Msg.Text()) } fmt.Fprintln(w, "model calls after Open:", len(model.Requests()))
turn, err := reopened.Continue(ctx) // run it now; the next Send would too if err != nil { return err } res, err := turn.Wait() if err != nil { return err } fmt.Fprintln(w, "continued:", res.Text()) return reopened.Close(ctx)}View on GitHub · run it from docs-site/examples:
go run ./sessions overviewgo test ./sessionsanswer: Order 1234 shipped on Tuesday.run: s_support-t1 entries: 3other reads: 2 messagesother writes: trueafter the writer closed: truereopened: Order 1234: shippedclose gave up: truerunning turn: canceledqueued turn: canceled truerestored: queue Then email it to me.model calls after Open: 0continued: Sent to the address on file.new id: s_ 28 true falseEach Session value (from Create, Open or Fork) logs one WARN at its first turn, thread: no context window known for this session, unless thread.ContextWindow or thread.ModelWindows gives it a window; without one, automatic compaction stays off. thread.NoAutoCompact() turns compaction off and silences the line. The demo passes ctxWindow, so standard error stays empty (compaction). The tests in sessions/sessions_test.go also pin ErrLocked for a second writer, ErrClosed after Close, and the restored queue.
Best practices & gotchas
Section titled “Best practices & gotchas”The rules that follow from this model are with the tasks they apply to: closing, retrying (a failed turn included) and IDs/Clock in Send turns › Best practices, deleting in Store sessions › Best practices, and never appending behind a Session in Write your own thread.Storage.
See also
Section titled “See also”- Store sessions: JSONL, SQLite or memory
- Send turns and wait for them
- Label, branch and fork a session
- Operate sessions in production
- Glossary: session
Symbols used: thread.Session · thread.Create · thread.Open · thread.SessionOption · thread.Storage · thread.Leaser · Session.Send · Session.Context · Session.Entries · Session.Queue · Session.Continue · Session.Claim · Session.Close · Session.SetInfo · Session.Title · Session.ID · Session.Storage · Session.LoadReport · thread.SessionFromContext · thread.IDs · thread.Clock · thread.NewSessionID · thread.NewEntryID · thread.ValidID · thread.FsyncOnFlush · thread.ErrLocked · thread.ErrStale · thread.ErrClosed · thread.ErrNewerFormat · thread.ErrCorrupt · jsonl.Open · weft.User · weft.OnMessages · wefttest.Script