Store sessions: JSONL, SQLite or memory
A session lives in a thread.Storage backend. Three ship with weft: jsonl.Open(dir), one file per session; sqlite.Open(path), every session in one database file; and thread.Memory(), in process. Pass the result to thread.Create or thread.Open; the Session API is the same on all three, and only the capabilities differ.
sessions/storage.go opens a JSONL directory, runs one turn and reads the file back:
sessions := filepath.Join(dir, "sessions")st, err := jsonl.Open(sessions, thread.FsyncOnFlush()) // fsync at the turn's end, not every appendif err != nil { return err}s, err := thread.Create(ctx, st, agent, ctxWindow, ids("s_jsonl", "a"), at(base))if err != nil { return err}turn, err := s.Send(ctx, weft.User("Where is order 1234?"))if err != nil { return err}if _, err := turn.Wait(); err != nil { return err}if err := s.Close(ctx); err != nil { return err}data, err := os.ReadFile(filepath.Join(sessions, "s_jsonl.jsonl"))if err != nil { return err}lines := strings.Split(strings.TrimSpace(string(data)), "\n")fmt.Fprintln(w, "lines:", len(lines))fmt.Fprintln(w, lines[0])fmt.Fprintln(w, lines[1])lines: 4{"type":"session","weft":1,"id":"s_jsonl","created":"2026-10-18T09:00:00Z"}{"type":"message","id":"e_a1","created":"2026-10-18T09:00:00Z","message":{"role":"user","content":[{"type":"text","text":"Where is order 1234?"}]},"run_id":"s_jsonl-t1"}The header line comes first, then one entry per line: the prompt (carrying the run id minted for its turn), the reply and the turn’s ledger. In the demos, ids pins the ids for stable output and ctxWindow is thread.ContextWindow(128_000), the model’s context window (why).
Backends
Section titled “Backends”| Aspect | thread/jsonl | thread/sqlite | thread.Memory |
|---|---|---|---|
| Layout | one <id>.jsonl file per session in a directory | one SQLite file for every session, WAL | a map in the process |
| Survives the process | yes | yes | no |
| One writer across processes | advisory file lock (flock, LockFileEx on Windows) | a lock row per session | one process only |
| Default durability | every append fsynced | every commit fsynced (synchronous=FULL) | nothing to sync |
Watch (live tail) | yes | yes | no |
| Use for | the default; jq and cp work on it | many sessions in one file; TitleSearch without reading entries | tests and examples |
All three implement the Releaser and Leaser capabilities; jsonl and sqlite also implement Flusher and Watcher. All three accept the same open options and pass the same conformance table (Write your own thread.Storage). jsonl and sqlite store the same line bytes, so they differ in where the lines live, never in what they say.
Every backend’s Load reads one snapshot: a session deleted under a concurrent load answers thread.ErrNotFound or the whole session, never a header without its entries. ADR 0026 lists three ways to store sessions: your own thread.Storage (Write your own thread.Storage), thread/sqlite, and a Postgres backend that it designs but that does not ship in v0.20.2.
jsonl.Open(dir, opts...) returns a storage rooted at dir: one <id>.jsonl file per session, the directory created 0700 when missing and files created 0600. Create writes the header and fsyncs the file and the directory; Append writes a batch in one write and fsyncs it.
The writer lock is an advisory file lock taken on a session’s first write and held until the session is released, deleted, or the process exits; the kernel drops it however the holder exits. It costs one open file descriptor per session the process is writing. On a platform with no advisory file lock (not unix, not Windows), jsonl.Open fails wrapping errors.ErrUnsupported unless you pass thread.NoLock().
A crash mid-append leaves at most a torn final line. A load drops it and reports it in LoadReport.Torn; the next writer truncates it before its first append. List reads every header in the directory on each call, so its cost grows with the number of sessions. The package examples are ExampleOpen, ExampleOpen_release (a second Storage gets ErrLocked until the holder releases), ExampleOpen_tornTail and ExampleOpen_noLock. Since thread 0.2.0 a header is read to its end, so a short read no longer hides a session from List.
SQLite
Section titled “SQLite”sqlite.Open(path, opts...) opens, creating if needed, one database file holding every session, on the CGO-free modernc.org/sqlite driver. thread/sqlite is the only package that imports the driver; thread never does. (It was its own module when it shipped in thread 0.4.0; in v0.20.2 it is a package of github.com/weftgo/weft.) ":memory:" opens a private in-process database. The file is created 0600, its directory 0700; -wal and -shm side files sit beside it.
Every Append is one committed transaction, so a process that dies never loses an Append that returned. The one-writer rule is a lock row per session; a holder whose process died on this host is taken over, and a holder on another host is never judged dead from here (see Operate sessions and sqlite.BreakLock). A second Storage over the same file is refused like another process:
path := filepath.Join(dir, "sessions.db")st, err := sqlite.Open(path) // every session in one file, WALif err != nil { return err}s, err := thread.Create(ctx, st, agent, ctxWindow, ids("s_sqlite", "a"))if err != nil { return err}if err := s.SetInfo(ctx, "Refund for order 1234", nil); err != nil { return err}
// A second Storage over the same file: another process, in effect.other, err := sqlite.Open(path)if err != nil { return err}reader, err := thread.Open(ctx, other, "s_sqlite", agent, ctxWindow, ids("", "b"))if err != nil { return err}fmt.Fprintln(w, "reader sees:", reader.Title())err = reader.SetInfo(ctx, "Refund denied", nil)fmt.Fprintln(w, "second writer:", errors.Is(err, thread.ErrLocked))reader sees: Refund for order 1234second writer: trueSchema migrations are embedded and tracked in the thread_migrations table, so a thread database can share a file with the local sink’s obsdb_migrations. A file migrated by a newer weft fails Open with sqlite.ErrNewerSchema. The session title is kept in a column, so Query.TitleSearch never reads a session’s entries. The package examples are ExampleOpen and ExampleOpen_secondWriter.
Memory
Section titled “Memory”thread.Memory(opts...) keeps sessions in a map behind a mutex, gone when the process is:
st := thread.Memory() // in process: tests and examplesIt is for tests, examples, and the reference the durable backends are compared against. It takes the open options: Salvage and OpenLogger mean what they mean on disk, and the fsync options and NoLock are no-ops. Its Storage methods never return ErrLocked, since there is no second process; two Sessions on one Memory are still kept to one writer by its lease. The package example is ExampleMemory.
Open options
Section titled “Open options”Every backend’s Open takes the same thread.OpenOption values, so you never learn a backend to say Salvage:
| Option | Effect |
|---|---|
thread.FsyncEveryAppend() | The default: every Append fsyncs before it returns, so an accepted entry is durable before anything replies on it. |
thread.FsyncOnFlush() | Defer the fsync to the Flusher capability: a Session flushes after the prompt, every receipt and bookkeeping write, and at the turn’s end; the steps in between are not synced. A crash can lose the unsynced tail of a turn, never a synced one. On sqlite it opens the database with synchronous=NORMAL instead of FULL, and Flush runs PRAGMA wal_checkpoint(PASSIVE): every commit survives the process dying, and a power cut can roll back the commits since the last checkpoint. |
thread.NoLock() | Open a file backend without its cross-process lock. One writer per session becomes your promise: a second process can interleave lines. sqlite and Memory accept it and keep locking. |
thread.OpenLogger(l) | Where the backend reports what it repairs on its own: a torn tail truncated, a dead holder’s lock taken over. One Warn line each; the default is slog.Default(). |
thread.Salvage() | Skip malformed lines instead of failing the load, each skip reported in LoadReport.Skipped. Data from a newer weft still fails with ErrNewerFormat. |
Recover a damaged file with Salvage
Section titled “Recover a damaged file with Salvage”A damaged line that is not the final one fails the load with thread.ErrCorrupt, carried by a *thread.CorruptError that names the session and the 1-based line (the header is line 1). Here the reply’s line is damaged, and the session is opened twice:
st, err := jsonl.Open(sessions)if err != nil { return err}_, err = thread.Open(ctx, st, "s_jsonl", agent, ctxWindow)var corrupt *thread.CorruptErrorif errors.As(err, &corrupt) { fmt.Fprintln(w, "refused:", errors.Is(err, thread.ErrCorrupt), "line", corrupt.Line)}
salvaged, err := jsonl.Open(sessions, thread.Salvage())if err != nil { return err}s, err := thread.Open(ctx, salvaged, "s_jsonl", agent, ctxWindow)if err != nil { return err}report := s.LoadReport()fmt.Fprintln(w, "skipped lines:", report.Skipped, "orphaned:", report.Orphaned)refused: true line 3skipped lines: [3] orphaned: [e_a3]Under Salvage the load skips line 3 and the session opens. The turn entry whose parent was on that line is kept and listed as orphaned; a context below it starts at that entry. Open also logs the repair once through the agent’s logger. Use Salvage to recover: open with it, read s.LoadReport(), and decide whether the session is still usable. The package example is ExampleSalvage. Storage-level loads report through thread.LoadReport: Torn for a dropped final line, Skipped for salvaged ones.
List sessions
Section titled “List sessions”thread.List(ctx, st, q) returns a thread.Page of session headers, never entries, and needs no Session. A thread.Query filters and pages it. The demo creates five sessions, each with header metadata and a title:
s, err := thread.Create(ctx, st, agent, ctxWindow, ids(c.id, "a"), at(base.Add(time.Duration(i)*time.Minute)), thread.WithMeta(map[string]string{"env": c.env})) // header metadata: what Query.Meta matchesif err != nil { return err}if err := s.SetInfo(ctx, c.title, nil); err != nil { // the title: what Query.TitleSearch matches return err}Then it filters, and pages through everything two at a time:
page, err := thread.List(ctx, st, thread.Query{ Meta: map[string]string{"env": "prod"}, // every pair present, exactly TitleSearch: "checkout", // the current title, any case})if err != nil { return err}for _, h := range page.Sessions { // newest first, headers only fmt.Fprintln(w, "match:", h.ID)}fmt.Fprintln(w, "total:", page.Total)
q := thread.Query{Limit: 2}for { page, err := thread.List(ctx, st, q) if err != nil { return err } if len(page.Sessions) == 0 { break } var got []string for _, h := range page.Sessions { got = append(got, h.ID) } fmt.Fprintln(w, "page:", got, "of", page.Total) last := page.Sessions[len(page.Sessions)-1] // the keyset cursor q.Before, q.BeforeID = last.Created, last.ID}match: s_cmatch: s_atotal: 2page: [s_e s_d] of 5page: [s_c s_b] of 5page: [s_a] of 5Page.Sessionsis newest first byCreated, ties by id descending.Page.Totalcounts every session the filters match, ignoring the cursor and the limit.Query.Metamatches every pair exactly against the header’s create-time metadata, whatthread.WithMetaandthread.PublicIDset. A key must be present to match, and a key a laterSetInfoadded never matches.Query.TitleSearchmatches the session’s current title (the last info entry with a non-empty title,s.Title()) case-insensitively as a substring. It is the one filter that may read beyond headers: jsonl reads each candidate’s file.Query.Limitcaps the page: 0 or negative means 50, above 500 clamps to 500.Query.BeforeandQuery.BeforeIDare a keyset cursor over the same order: pass the last session of the previous page.Beforealone returns only sessions created strictly before it and skips the rest of a group sharing that time; setBeforeIDto walk through ties. There are no offsets: they drift under concurrent inserts.
List skips what it cannot decode (a torn or foreign header, a newer envelope) without an error; Load on that id says why. The examples are ExampleList, ExampleQuery and ExampleQuery_keysetCursor.
Delete a session
Section titled “Delete a session”thread.Delete(ctx, st, id) removes a session and its entries. It is the one operation that removes data:
if err := thread.Delete(ctx, st, "s_b"); err != nil { return err}_, err = thread.Open(ctx, st, "s_b", agent, ctxWindow)fmt.Fprintln(w, "after Delete:", errors.Is(err, thread.ErrNotFound))after Delete: trueAn id the storage does not hold fails with thread.ErrNotFound, as Load and Append do. Create over an id the storage holds fails with thread.ErrExists: a session is never silently replaced. Delete does not look for open Sessions: through the Storage value the writer uses it always removes, and the writer’s next write fails with ErrNotFound; through another Storage value it fails with ErrLocked while a writer holds the session. Close the session first. The package example is ExampleDelete.
Watch a session
Section titled “Watch a session”thread.Watcher is the optional capability that tails a session as it is appended to, for a reader in another process. jsonl and sqlite implement it. Watch(ctx, session, after) yields the entries after the entry after names ("": from the start) in arrival order, each once, then keeps yielding as appends land, until ctx ends:
reader, err := jsonl.Open(sessions) // a reader: it never locksif err != nil { return err}wctx, stop := context.WithCancel(ctx)defer stop()tail, err := reader.(thread.Watcher).Watch(wctx, "s_watch", "") // "": from the first entryif err != nil { return err}seen := make(chan thread.Entry)go func() { defer close(seen) for e, err := range tail { if err != nil { return } seen <- e }}()
turn, err := s.Send(ctx, weft.User("How long do refunds take?"))if err != nil { return err}if _, err := turn.Wait(); err != nil { return err}for e := range seen { fmt.Fprintln(w, "watched:", kind(e)) if _, ok := e.(thread.TurnEntry); ok { stop() // the turn's ledger: the turn has landed }}watched: message (user)watched: message (assistant)watched: turnA watcher is a reader that waits: it never locks, and the loop may call the same Storage. An unknown session, or an after the session does not hold, fails before the first yield. The stream ends with one error when the session is deleted (or deleted and created again) under it, ErrNotFound, or when it meets data it cannot decode. A torn final line is a write in flight: it is yielded once complete. The jsonl and sqlite watchers poll every 200 ms. The package example is ExampleWatcher.
Complete example
Section titled “Complete example”sessions/storage.go writes a JSONL session, salvages it, refuses a second SQLite writer, lists, deletes and watches:
package main
import ( "context" "errors" "fmt" "io" "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/sqlite" "github.com/weftgo/weft/wefttest")
// demoStorage is the page "Store sessions: JSONL, SQLite or memory".func demoStorage(ctx context.Context, w io.Writer, dir string) error { agent := weft.New(wefttest.Script( wefttest.Say("Order 1234 shipped on Tuesday."), wefttest.Say("Refunds take three to five days."), )) if err := storeJSONL(ctx, w, dir, agent); err != nil { return err } if err := salvage(ctx, w, dir, agent); err != nil { return err } if err := storeSQLite(ctx, w, dir, agent); err != nil { return err } if err := listSessions(ctx, w, agent); err != nil { return err } return watch(ctx, w, dir, agent)}
func storeJSONL(ctx context.Context, w io.Writer, dir string, agent *weft.Agent) error { sessions := filepath.Join(dir, "sessions") st, err := jsonl.Open(sessions, thread.FsyncOnFlush()) // fsync at the turn's end, not every append if err != nil { return err } s, err := thread.Create(ctx, st, agent, ctxWindow, ids("s_jsonl", "a"), at(base)) if err != nil { return err } turn, err := s.Send(ctx, weft.User("Where is order 1234?")) if err != nil { return err } if _, err := turn.Wait(); err != nil { return err } if err := s.Close(ctx); err != nil { return err } data, err := os.ReadFile(filepath.Join(sessions, "s_jsonl.jsonl")) if err != nil { return err } lines := strings.Split(strings.TrimSpace(string(data)), "\n") fmt.Fprintln(w, "lines:", len(lines)) fmt.Fprintln(w, lines[0]) fmt.Fprintln(w, lines[1]) return nil}
// salvage damages the reply's line in s_jsonl's file, then loads it twice:// without Salvage and with it.func salvage(ctx context.Context, w io.Writer, dir string, agent *weft.Agent) error { sessions := filepath.Join(dir, "sessions") path := filepath.Join(sessions, "s_jsonl.jsonl") data, err := os.ReadFile(path) if err != nil { return err } lines := strings.Split(string(data), "\n") lines[2] = `{"type":"message","id":` // line 3, the reply: a damaged line, not a torn tail if err := os.WriteFile(path, []byte(strings.Join(lines, "\n")), 0o600); err != nil { return err }
st, err := jsonl.Open(sessions) if err != nil { return err } _, err = thread.Open(ctx, st, "s_jsonl", agent, ctxWindow) var corrupt *thread.CorruptError if errors.As(err, &corrupt) { fmt.Fprintln(w, "refused:", errors.Is(err, thread.ErrCorrupt), "line", corrupt.Line) }
salvaged, err := jsonl.Open(sessions, thread.Salvage()) if err != nil { return err } s, err := thread.Open(ctx, salvaged, "s_jsonl", agent, ctxWindow) if err != nil { return err } report := s.LoadReport() fmt.Fprintln(w, "skipped lines:", report.Skipped, "orphaned:", report.Orphaned) return nil}
func storeSQLite(ctx context.Context, w io.Writer, dir string, agent *weft.Agent) error { path := filepath.Join(dir, "sessions.db") st, err := sqlite.Open(path) // every session in one file, WAL if err != nil { return err } s, err := thread.Create(ctx, st, agent, ctxWindow, ids("s_sqlite", "a")) if err != nil { return err } if err := s.SetInfo(ctx, "Refund for order 1234", nil); err != nil { return err }
// A second Storage over the same file: another process, in effect. other, err := sqlite.Open(path) if err != nil { return err } reader, err := thread.Open(ctx, other, "s_sqlite", agent, ctxWindow, ids("", "b")) if err != nil { return err } fmt.Fprintln(w, "reader sees:", reader.Title()) err = reader.SetInfo(ctx, "Refund denied", nil) fmt.Fprintln(w, "second writer:", errors.Is(err, thread.ErrLocked)) if err := reader.Close(ctx); err != nil { return err } return s.Close(ctx)}
func listSessions(ctx context.Context, w io.Writer, agent *weft.Agent) error { st := thread.Memory() // in process: tests and examples seed := []struct{ id, env, title string }{ {"s_a", "prod", "Checkout bug"}, {"s_b", "dev", "Login flow"}, {"s_c", "prod", "Checkout again"}, {"s_d", "prod", "Refund for order 1234"}, {"s_e", "prod", "Address change"}, } for i, c := range seed { s, err := thread.Create(ctx, st, agent, ctxWindow, ids(c.id, "a"), at(base.Add(time.Duration(i)*time.Minute)), thread.WithMeta(map[string]string{"env": c.env})) // header metadata: what Query.Meta matches if err != nil { return err } if err := s.SetInfo(ctx, c.title, nil); err != nil { // the title: what Query.TitleSearch matches return err } if err := s.Close(ctx); err != nil { return err } }
page, err := thread.List(ctx, st, thread.Query{ Meta: map[string]string{"env": "prod"}, // every pair present, exactly TitleSearch: "checkout", // the current title, any case }) if err != nil { return err } for _, h := range page.Sessions { // newest first, headers only fmt.Fprintln(w, "match:", h.ID) } fmt.Fprintln(w, "total:", page.Total)
q := thread.Query{Limit: 2} for { page, err := thread.List(ctx, st, q) if err != nil { return err } if len(page.Sessions) == 0 { break } var got []string for _, h := range page.Sessions { got = append(got, h.ID) } fmt.Fprintln(w, "page:", got, "of", page.Total) last := page.Sessions[len(page.Sessions)-1] // the keyset cursor q.Before, q.BeforeID = last.Created, last.ID }
if err := thread.Delete(ctx, st, "s_b"); err != nil { return err } _, err = thread.Open(ctx, st, "s_b", agent, ctxWindow) fmt.Fprintln(w, "after Delete:", errors.Is(err, thread.ErrNotFound)) return nil}
// watch tails a session from a second Storage while the first one writes// a turn into it.func watch(ctx context.Context, w io.Writer, dir string, agent *weft.Agent) error { sessions := filepath.Join(dir, "sessions") st, err := jsonl.Open(sessions) if err != nil { return err } s, err := thread.Create(ctx, st, agent, ctxWindow, ids("s_watch", "a")) if err != nil { return err } reader, err := jsonl.Open(sessions) // a reader: it never locks if err != nil { return err } wctx, stop := context.WithCancel(ctx) defer stop() tail, err := reader.(thread.Watcher).Watch(wctx, "s_watch", "") // "": from the first entry if err != nil { return err } seen := make(chan thread.Entry) go func() { defer close(seen) for e, err := range tail { if err != nil { return } seen <- e } }()
turn, err := s.Send(ctx, weft.User("How long do refunds take?")) if err != nil { return err } if _, err := turn.Wait(); err != nil { return err } for e := range seen { fmt.Fprintln(w, "watched:", kind(e)) if _, ok := e.(thread.TurnEntry); ok { stop() // the turn's ledger: the turn has landed } } return s.Close(ctx)}View on GitHub · run it from docs-site/examples:
go run ./sessions storagego test ./sessionslines: 4{"type":"session","weft":1,"id":"s_jsonl","created":"2026-10-18T09:00:00Z"}{"type":"message","id":"e_a1","created":"2026-10-18T09:00:00Z","message":{"role":"user","content":[{"type":"text","text":"Where is order 1234?"}]},"run_id":"s_jsonl-t1"}refused: true line 3skipped lines: [3] orphaned: [e_a3]reader sees: Refund for order 1234second writer: truematch: s_cmatch: s_atotal: 2page: [s_e s_d] of 5page: [s_c s_b] of 5page: [s_a] of 5after Delete: truewatched: message (user)watched: message (assistant)watched: turnStandard error carries one line: the salvage warning Open logs through the agent’s logger, WARN thread: session loaded with a repair session=s_jsonl torn_line=0 skipped_lines=[3] orphaned_entries=[e_a3].
Best practices & gotchas
Section titled “Best practices & gotchas”- Back up sqlite with SQLite’s own backup, not
cp. Committed data can still be in-wal; use.backuporVACUUM INTO, or stop every writer and copy the three files. A jsonl directory can be copied at any time. (Source:docs/thread-operations.md§3) - Run one writer host per directory or database. jsonl’s lock is only as good as the filesystem’s
flock, and sqlite on a shared filesystem is outside SQLite’s supported envelope. (Source:docs/thread-operations.md§4) - Use
NoLockonly where no lock exists or can be trusted. Two processes writing one session under it interleave their lines. (Source:thread/open.go:68-86) - Use
Salvageto recover, not by default. It hides damage from every load; open with it, readLoadReport, decide. It never skips newer data. (Source:thread/open.go:31-44;docs/thread-operations.md§6) - Page with
BeforeandBeforeIDtogether.Beforealone skips sessions sharing the cursor’s creation time. (Source:thread/storage.go:100-113) - Close a session before you delete it.
Deletedoes not look for open Sessions; a turn running at that moment loses the entries it had yet to write. (Source:thread/session.go:826Delete godoc) Query.Metasees create-time metadata only. Put what you filter on inWithMetaatCreate;SetInfokeys never match. (Source:thread/storage.go:117-125)
See also
Section titled “See also”- What is a session?
- Write your own thread.Storage
- Operate sessions in production: backups, locks, shutdown
- The session log format
Symbols used: thread.Storage · jsonl.Open · sqlite.Open · sqlite.ErrNewerSchema · sqlite.BreakLock · thread.Memory · thread.OpenOption · thread.FsyncEveryAppend · thread.FsyncOnFlush · thread.NoLock · thread.OpenLogger · thread.Salvage · thread.CorruptError · thread.LoadReport · Session.LoadReport · thread.List · thread.Query · thread.Page · thread.Delete · thread.ErrNotFound · thread.ErrExists · thread.ErrLocked · thread.ErrCorrupt · thread.Watcher · thread.WithMeta · Session.SetInfo · thread.Create · thread.Open