---
title: 'Store sessions: JSONL, SQLite or memory'
description: Pick a thread.Storage backend (jsonl.Open, sqlite.Open or thread.Memory), set its open options, list and delete sessions, and tail one live with Watch.
url: https://weftgo.dev/docs/sessions/storage/
type: how-to
sources:
  - weft/AGENTS.md:552-556 (block 8, storage)
  - weft/thread/storage.go:35 (Storage), 86 (LoadReport), 100-134 (Query), 137-145 (Page)
  - weft/thread/open.go:21 (OpenOption), 44 (Salvage), 57 (FsyncEveryAppend), 66 (FsyncOnFlush), 86 (NoLock), 106 (OpenLogger), 116 (Flusher), 136 (Releaser), 159 (Leaser), 215 (Watcher)
  - weft/thread/memory.go:85 (Memory)
  - weft/thread/session.go:808 (List), 826 (Delete)
  - weft/thread/errors.go:26 (ErrNotFound), 31 (ErrExists), 40 (ErrLocked), 60 (ErrCorrupt), 190 (CorruptError)
  - weft/thread/jsonl/jsonl.go:63 (Open) and package doc
  - weft/thread/sqlite/sqlite.go:118 (Open), 167-174 (synchronous FULL or NORMAL), 847-867 (Flush, wal_checkpoint PASSIVE), 1191 (BreakLock); weft/thread/sqlite/migrations.go:80 (ErrNewerSchema)
  - weft/docs/thread-operations.md (§1 on disk, §2 durability, §4 locks, §6 after a crash, §9 costs and limits)
  - weft/docs/adr/0011-thread-sessions.md (§5 storage)
  - 'weft/docs/adr/0026-thread-storage-backends.md (Context: three ways to store sessions)'
  - weft/CHANGELOG.md:3840 (Releaser, NoLock, OpenLogger), 3860 (Query.BeforeID), 4756 (thread_migrations), 4999 (thread/sqlite), 5013 (Watcher), 5017 (Query filters), 5026 (Load snapshot), 5204 (jsonl header read)
  - weft/thread/example_test.go ExampleMemory, ExampleQuery, ExampleWatcher
  - weft/thread/example_session_test.go ExampleList, ExampleDelete, ExampleSalvage
  - weft/thread/storage_example_test.go ExampleQuery_keysetCursor
  - weft/thread/jsonl/example_test.go ExampleOpen, ExampleOpen_release, ExampleOpen_tornTail, ExampleOpen_noLock
  - weft/thread/sqlite/example_test.go ExampleOpen, ExampleOpen_secondWriter
  - docs-site/examples/sessions/storage.go, sessions_test.go TestDemos/storage
---

# Store sessions: JSONL, SQLite or memory

A session lives in a [`thread.Storage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Storage) backend. Three ship with weft: [`jsonl.Open(dir)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/jsonl#Open), one file per session; [`sqlite.Open(path)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/sqlite#Open), every session in one database file; and [`thread.Memory()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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](#backends) differ.

`sessions/storage.go` opens a JSONL directory, runs one turn and reads the file back:

```go title="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](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/storage.go)

```text
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](https://weftgo.dev/docs/sessions/turns/#best-practices--gotchas)).

## 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](#open-options) and pass the same conformance table ([Write your own thread.Storage](https://weftgo.dev/docs/sessions/custom-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](https://weftgo.dev/docs/sessions/custom-storage/)), `thread/sqlite`, and a Postgres backend that it designs but that does not ship in v0.20.2.

### JSONL

[`jsonl.Open(dir, opts...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/jsonl#Open) 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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/jsonl#example-Open), [`ExampleOpen_release`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/jsonl#example-Open-Release) (a second `Storage` gets `ErrLocked` until the holder releases), [`ExampleOpen_tornTail`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/jsonl#example-Open-TornTail) and [`ExampleOpen_noLock`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/jsonl#example-Open-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

[`sqlite.Open(path, opts...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/sqlite#Open) 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](https://weftgo.dev/docs/sessions/operations/) and `sqlite.BreakLock`). A second `Storage` over the same file is refused like another process:

```go title="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](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/storage.go)

```text
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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/sqlite#ErrNewerSchema). The session title is kept in a column, so `Query.TitleSearch` never reads a session's entries. The package examples are [`ExampleOpen`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/sqlite#example-Open) and [`ExampleOpen_secondWriter`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/sqlite#example-Open-SecondWriter).

### Memory

[`thread.Memory(opts...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Memory) keeps sessions in a map behind a mutex, gone when the process is:

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

[sessions/storage.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/storage.go)

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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Memory).

## Open options

Every backend's `Open` takes the same [`thread.OpenOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#OpenOption) values, so you never learn a backend to say `Salvage`:

| Option | Effect |
|---|---|
| [`thread.FsyncEveryAppend()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#FsyncEveryAppend) | The default: every `Append` fsyncs before it returns, so an accepted entry is durable before anything replies on it. |
| [`thread.FsyncOnFlush()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#OpenLogger) | 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()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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

A damaged line that is not the final one fails the load with `thread.ErrCorrupt`, carried by a [`*thread.CorruptError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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:

```go title="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](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/storage.go)

```text
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()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.LoadReport), and decide whether the session is still usable. The package example is [`ExampleSalvage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Salvage). Storage-level loads report through [`thread.LoadReport`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#LoadReport): `Torn` for a dropped final line, `Skipped` for salvaged ones.

## List sessions

[`thread.List(ctx, st, q)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#List) returns a [`thread.Page`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Page) of session headers, never entries, and needs no Session. A [`thread.Query`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Query) filters and pages it. The demo creates five sessions, each with header metadata and a title:

```go 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](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/storage.go)

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

```go title="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](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/storage.go)

```text
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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-List), [`ExampleQuery`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Query) and [`ExampleQuery_keysetCursor`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Query-KeysetCursor).

### Delete a session

[`thread.Delete(ctx, st, id)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Delete) removes a session and its entries. It is the one operation that removes data:

```go title="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](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/storage.go)

```text
after Delete: true
```

An id the storage does not hold fails with [`thread.ErrNotFound`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrNotFound), as `Load` and `Append` do. `Create` over an id the storage holds fails with [`thread.ErrExists`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Delete).

## Watch a session

[`thread.Watcher`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Watcher) 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:

```go title="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](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/storage.go)

```text
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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Watcher).

## Complete example

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

```go title="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)
}
```

[sessions/storage.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/storage.go)

[View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/sessions) · run it from `docs-site/examples`:

```sh
go run ./sessions storage
go test ./sessions
```

```text
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]`.

## Best practices & gotchas

- **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`)

## See also

- [What is a session?](https://weftgo.dev/docs/sessions/overview/)
- [Write your own thread.Storage](https://weftgo.dev/docs/sessions/custom-storage/)
- [Operate sessions in production](https://weftgo.dev/docs/sessions/operations/): backups, locks, shutdown
- [The session log format](https://weftgo.dev/docs/sessions/format/)

Symbols used: [`thread.Storage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Storage) · [`jsonl.Open`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/jsonl#Open) · [`sqlite.Open`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/sqlite#Open) · [`sqlite.ErrNewerSchema`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/sqlite#ErrNewerSchema) · [`sqlite.BreakLock`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/sqlite#BreakLock) · [`thread.Memory`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Memory) · [`thread.OpenOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#OpenOption) · [`thread.FsyncEveryAppend`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#FsyncEveryAppend) · [`thread.FsyncOnFlush`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#FsyncOnFlush) · [`thread.NoLock`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#NoLock) · [`thread.OpenLogger`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#OpenLogger) · [`thread.Salvage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Salvage) · [`thread.CorruptError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#CorruptError) · [`thread.LoadReport`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#LoadReport) · [`Session.LoadReport`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.LoadReport) · [`thread.List`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#List) · [`thread.Query`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Query) · [`thread.Page`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Page) · [`thread.Delete`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Delete) · [`thread.ErrNotFound`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrNotFound) · [`thread.ErrExists`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrExists) · [`thread.ErrLocked`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrLocked) · [`thread.ErrCorrupt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrCorrupt) · [`thread.Watcher`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Watcher) · [`thread.WithMeta`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#WithMeta) · [`Session.SetInfo`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.SetInfo) · [`thread.Create`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Create) · [`thread.Open`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Open)
