Skip to content

Store sessions: JSONL, SQLite or memory

View as Markdown

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/storage.go
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])

sessions/storage.go on GitHub

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).

Aspectthread/jsonlthread/sqlitethread.Memory
Layoutone <id>.jsonl file per session in a directoryone SQLite file for every session, WALa map in the process
Survives the processyesyesno
One writer across processesadvisory file lock (flock, LockFileEx on Windows)a lock row per sessionone process only
Default durabilityevery append fsyncedevery commit fsynced (synchronous=FULL)nothing to sync
Watch (live tail)yesyesno
Use forthe default; jq and cp work on itmany sessions in one file; TitleSearch without reading entriestests 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.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:

sessions/storage.go
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))

sessions/storage.go on GitHub

reader sees: Refund for order 1234
second writer: true

Schema 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.

thread.Memory(opts...) keeps sessions in a map behind a mutex, gone when the process is:

sessions/storage.go
st := thread.Memory() // in process: tests and examples

sessions/storage.go on GitHub

It 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.

Every backend’s Open takes the same thread.OpenOption values, so you never learn a backend to say Salvage:

OptionEffect
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.

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:

sessions/storage.go
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)

sessions/storage.go on GitHub

refused: true line 3
skipped 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.

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:

sessions/storage.go
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
}

sessions/storage.go on GitHub

Then it filters, and pages through everything two at a time:

sessions/storage.go
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
}

sessions/storage.go on GitHub

match: s_c
match: s_a
total: 2
page: [s_e s_d] of 5
page: [s_c s_b] of 5
page: [s_a] of 5
  • Page.Sessions is newest first by Created, ties by id descending. Page.Total counts every session the filters match, ignoring the cursor and the limit.
  • Query.Meta matches every pair exactly against the header’s create-time metadata, what thread.WithMeta and thread.PublicID set. A key must be present to match, and a key a later SetInfo added never matches.
  • Query.TitleSearch matches 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.Limit caps the page: 0 or negative means 50, above 500 clamps to 500.
  • Query.Before and Query.BeforeID are a keyset cursor over the same order: pass the last session of the previous page. Before alone returns only sessions created strictly before it and skips the rest of a group sharing that time; set BeforeID to 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.

thread.Delete(ctx, st, id) removes a session and its entries. It is the one operation that removes data:

sessions/storage.go
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))

sessions/storage.go on GitHub

after Delete: true

An 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.

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:

sessions/storage.go
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
}
}

sessions/storage.go on GitHub

watched: message (user)
watched: message (assistant)
watched: turn

A 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.

sessions/storage.go writes a JSONL session, salvages it, refuses a second SQLite writer, lists, deletes and watches:

sessions/storage.go
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 sessions/storage.go on GitHub

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

Terminal window
go run ./sessions storage
go test ./sessions
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"}
refused: true line 3
skipped lines: [3] orphaned: [e_a3]
reader sees: Refund for order 1234
second writer: true
match: s_c
match: s_a
total: 2
page: [s_e s_d] of 5
page: [s_c s_b] of 5
page: [s_a] of 5
after Delete: true
watched: message (user)
watched: message (assistant)
watched: turn

Standard 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].

  • Back up sqlite with SQLite’s own backup, not cp. Committed data can still be in -wal; use .backup or VACUUM 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 NoLock only 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 Salvage to recover, not by default. It hides damage from every load; open with it, read LoadReport, decide. It never skips newer data. (Source: thread/open.go:31-44; docs/thread-operations.md §6)
  • Page with Before and BeforeID together. Before alone skips sessions sharing the cursor’s creation time. (Source: thread/storage.go:100-113)
  • Close a session before you delete it. Delete does not look for open Sessions; a turn running at that moment loses the entries it had yet to write. (Source: thread/session.go:826 Delete godoc)
  • Query.Meta sees create-time metadata only. Put what you filter on in WithMeta at Create; SetInfo keys never match. (Source: thread/storage.go:117-125)

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