---
title: Write your own thread.Storage
description: Implement the five thread.Storage methods over your own store, add the optional capabilities by type assertion, resolve the open options with thread/backend, and prove it with threadtest.
url: https://weftgo.dev/docs/sessions/custom-storage/
type: how-to
sources:
  - weft/thread/storage.go:35-81 (Storage and its method contracts, One writer)
  - weft/thread/open.go:21-27 (OpenOption), 116-137 (Flusher, Releaser), 159-216 (Leaser, Watcher)
  - weft/thread/entry.go (Entry, UnmarshalEntry)
  - weft/thread/header.go:36 (Header)
  - weft/thread/errors.go:26 (ErrNotFound), 31 (ErrExists), 40 (ErrLocked), 52 (ErrStale), 60 (ErrCorrupt), 75 (ErrNewerFormat), 190 (CorruptError)
  - weft/thread/backend/backend.go:34-57 (Config, Resolve) and package doc
  - weft/thread/threadtest/threadtest.go:39-72 (Run), 298 (RunWatch), 718-729 (RawInjector, RawHeaderInjector), 1699 (RunTwoWriters)
  - weft/thread/threadtest/leaser.go:70 (RunLeaser); onewriter.go:27 (RunOneWriter); turns.go:22 (RunTurns)
  - weft/thread/threadtest/crashmatrix.go:60-110 (CrashMatrix, the ids), 786 (RunCrashMatrixChild); crashturn.go:29-40 (CrashSession, CrashTurn), 140 (RunCrashTurnChild)
  - weft/thread/jsonl/crashmatrix_test.go, weft/thread/jsonl/crash_test.go:284-302 (wiring the crash harness)
  - weft/thread/storage_test.go:22-24 (Memory runs threadtest.Run)
  - weft/docs/adr/0011-thread-sessions.md (§5 storage, amendment B the lease)
  - weft/docs/adr/0026-thread-storage-backends.md (Context; D12 conformance)
  - weft/CHANGELOG.md:3826 (crash matrix), 3837 (Leaser, ErrStale), 3844 (thread/backend), 3879 (threadtest additions), 5289 (the Storage contract)
  - weft/thread/storage_example_test.go ExampleReleaser
  - docs-site/examples/customstorage/mapstore.go, main.go, main_test.go TestRun, TestConformance, TestTurns
---

# Write your own thread.Storage

A session backend is any type that implements [`thread.Storage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Storage): `Create`, `Append`, `Load`, `List` and `Delete`. Extra behaviour, such as a writer lock or a live tail, comes from optional interfaces the session finds by type assertion. [`threadtest.Run`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#Run) is the conformance table every backend runs before it may call itself one. Every shipped backend passes it, and [`threadtest.RunTurns`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#RunTurns) beside it; passing both is necessary, not sufficient, and a durable store also runs the [crash tests](#crash-tests).

`customstorage/mapstore.go` is a backend over a map, in about 200 lines. It stores the header and each entry as the JSON line a file backend would write:

```go title="customstorage/mapstore.go"
// MapStore is a thread.Storage that keeps every session in a map: the
// header and each entry as the JSON line a file backend would write.
// Storing the encoded lines, not the values, is what keeps Load from
// aliasing what is stored. It implements the five methods and none of
// the optional capabilities.
type MapStore struct {
	mu       sync.Mutex
	sessions map[string]*stored
	cfg      backend.Config
}

type stored struct {
	header []byte   // the header line
	lines  [][]byte // one line per entry, in append order
	title  string   // the last non-empty info title, for Query.TitleSearch
}

// NewMapStore takes the shared open vocabulary every backend accepts. A
// map buffers, locks and repairs nothing, so each option is accepted and
// is a no-op here, as thread/backend asks of a backend it means nothing to.
func NewMapStore(opts ...thread.OpenOption) *MapStore {
	return &MapStore{sessions: map[string]*stored{}, cfg: backend.Resolve(opts...)}
}

var _ thread.Storage = (*MapStore)(nil)
```

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

Its test runs the table:

```go title="customstorage/main_test.go"
// TestConformance runs thread/threadtest's table against MapStore: a
// fresh store per subtest. The rows for capabilities MapStore does not
// implement (Flusher, Releaser, Leaser, Watcher, the raw-injection
// corruption rows) skip.
func TestConformance(t *testing.T) {
	threadtest.Run(t, func(*testing.T) thread.Storage { return NewMapStore() })
}

// TestTurns runs the session-level rows a backend carries beside Run:
// the turn machinery's durable shapes, reloaded from the store.
func TestTurns(t *testing.T) {
	threadtest.RunTurns(t, func(*testing.T) thread.Storage { return NewMapStore() })
}
```

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

`go test ./customstorage` passes: every row of `Run` and `RunTurns` that applies to a backend without capabilities.

## The Storage interface

Each method has a contract that `threadtest` checks. Every method takes `ctx` first and fails before writing anything when it is already canceled. Implementations must be safe for concurrent use.

**`Create(ctx, h)`** writes a session's header. The id must pass `thread.ValidID`, because some backend uses it as a path component; a zero `Header.Weft` means the current `thread.FormatVersion`, and any other envelope is rejected. An id the storage holds fails with `thread.ErrExists`:

```go title="customstorage/mapstore.go"
// Create writes the header. The id must pass thread.ValidID, a zero
// envelope means the current format, and an existing id is ErrExists.
func (m *MapStore) Create(ctx context.Context, h thread.Header) error {
	if err := ctx.Err(); err != nil {
		return err // a canceled context fails before anything is written
	}
	if !thread.ValidID(h.ID) {
		return fmt.Errorf("mapstore: invalid session id %q", h.ID)
	}
	if h.Weft != 0 && h.Weft != thread.FormatVersion {
		return fmt.Errorf("mapstore: header envelope %d, want %d", h.Weft, thread.FormatVersion)
	}
	line, err := json.Marshal(h) // a zero Weft is written as FormatVersion
	if err != nil {
		return err
	}
	m.mu.Lock()
	defer m.mu.Unlock()
	if _, ok := m.sessions[h.ID]; ok {
		return fmt.Errorf("mapstore: %s: %w", h.ID, thread.ErrExists)
	}
	m.sessions[h.ID] = &stored{header: line}
	return nil
}
```

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

**`Append(ctx, session, entries...)`** adds entries in arrival order. A batch is validated whole before anything is written, and it is atomic against the writer's death: after a crash a `Load` returns all of it or none. An unknown session fails with `thread.ErrNotFound`; one another writer holds, with `thread.ErrLocked`:

```go title="customstorage/mapstore.go"
// Append encodes the whole batch before it stores any of it: one entry
// that does not encode rejects the batch, so it lands whole or not at all.
func (m *MapStore) Append(ctx context.Context, session string, entries ...thread.Entry) error {
	if err := ctx.Err(); err != nil {
		return err
	}
	lines := make([][]byte, 0, len(entries))
	title := ""
	for _, e := range entries {
		line, err := json.Marshal(e) // every entry kind carries its "type"
		if err != nil {
			return fmt.Errorf("mapstore: %s: encode entry: %w", session, err)
		}
		lines = append(lines, line)
		if info, ok := e.(thread.InfoEntry); ok && info.Title != "" {
			title = info.Title
		}
	}
	m.mu.Lock()
	defer m.mu.Unlock()
	s, ok := m.sessions[session]
	if !ok {
		return fmt.Errorf("mapstore: %s: %w", session, thread.ErrNotFound)
	}
	s.lines = append(s.lines, lines...)
	if title != "" {
		s.title = title
	}
	return nil
}
```

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

**`Load(ctx, session)`** returns the header and every entry in append order, plus a [`*thread.LoadReport`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#LoadReport) naming a dropped torn tail or skipped lines, nil when clean. The values must never alias what is stored. Decode with [`thread.UnmarshalEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#UnmarshalEntry) to keep the loud rules: an unknown kind or a newer `"v"` is `thread.ErrNewerFormat`, a malformed line `thread.ErrCorrupt` naming the line in a [`*thread.CorruptError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#CorruptError):

```go title="customstorage/mapstore.go"
// Load decodes a snapshot taken under the lock, so a concurrent Delete
// yields the whole session or ErrNotFound. Decoding fresh copies is what
// makes the result the caller's to mutate; thread's own decoder keeps the
// loud rules (an unknown kind or a newer "v" is ErrNewerFormat).
func (m *MapStore) Load(ctx context.Context, session string) (thread.Header, []thread.Entry, *thread.LoadReport, error) {
	if err := ctx.Err(); err != nil {
		return thread.Header{}, nil, nil, err
	}
	m.mu.Lock()
	s, ok := m.sessions[session]
	var header []byte
	var lines [][]byte
	if ok {
		header, lines = s.header, slices.Clone(s.lines)
	}
	m.mu.Unlock()
	if !ok {
		return thread.Header{}, nil, nil, fmt.Errorf("mapstore: %s: %w", session, thread.ErrNotFound)
	}
	var h thread.Header
	if err := json.Unmarshal(header, &h); errors.Is(err, thread.ErrNewerFormat) {
		return thread.Header{}, nil, nil, err // a newer envelope: never ErrCorrupt
	} else if err != nil {
		return thread.Header{}, nil, nil, &thread.CorruptError{Session: session, Line: 1, Err: err}
	}
	entries := make([]thread.Entry, 0, len(lines))
	for i, line := range lines {
		e, err := thread.UnmarshalEntry(line)
		if errors.Is(err, thread.ErrNewerFormat) {
			return thread.Header{}, nil, nil, err // newer, not damaged: never a skip
		}
		if err != nil {
			return thread.Header{}, nil, nil, &thread.CorruptError{Session: session, Line: i + 2, Err: err}
		}
		entries = append(entries, e)
	}
	return h, entries, nil, nil // nil report: nothing dropped or skipped
}
```

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

**`List(ctx, q)`** returns a page of headers, never entries. `Query.Meta` matches the header's metadata, `Query.TitleSearch` the last non-empty info title, the order is newest first with ties by id descending, `Before` and `BeforeID` are a keyset cursor, a limit of 0 means 50 and anything above 500 clamps to 500, and `Total` ignores the cursor and the limit ([List sessions](https://weftgo.dev/docs/sessions/storage/#list-sessions)):

```go title="customstorage/mapstore.go"
// List filters, orders newest first (ties by id, descending), applies the
// keyset cursor and then the limit; Total ignores the cursor and limit.
func (m *MapStore) List(ctx context.Context, q thread.Query) (thread.Page, error) {
	if err := ctx.Err(); err != nil {
		return thread.Page{}, err
	}
	m.mu.Lock()
	var match []thread.Header
	for _, s := range m.sessions {
		var h thread.Header
		if err := json.Unmarshal(s.header, &h); err != nil {
			continue // List skips what it cannot decode; Load names why
		}
		if !metaMatches(h.Meta, q.Meta) {
			continue
		}
		if q.TitleSearch != "" && !strings.Contains(strings.ToLower(s.title), strings.ToLower(q.TitleSearch)) {
			continue
		}
		match = append(match, h)
	}
	m.mu.Unlock()

	slices.SortFunc(match, func(a, b thread.Header) int {
		if c := b.Created.Compare(a.Created); c != 0 {
			return c
		}
		return cmp.Compare(b.ID, a.ID)
	})
	page := thread.Page{Total: len(match)}
	limit := q.Limit
	switch {
	case limit <= 0:
		limit = 50
	case limit > 500:
		limit = 500
	}
	for _, h := range match {
		if !q.Before.IsZero() {
			older := h.Created.Before(q.Before)
			tiedAfter := q.BeforeID != "" && h.Created.Equal(q.Before) && h.ID < q.BeforeID
			if !older && !tiedAfter {
				continue
			}
		}
		if len(page.Sessions) == limit {
			break
		}
		page.Sessions = append(page.Sessions, h)
	}
	return page, nil
}

// metaMatches: every wanted key present, every value equal.
func metaMatches(have, want map[string]string) bool {
	for k, v := range want {
		if got, ok := have[k]; !ok || got != v {
			return false
		}
	}
	return true
}
```

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

**`Delete(ctx, session)`** removes a session; an unknown one is `ErrNotFound`, one another `Storage` or process holds as its writer is `ErrLocked`. A hold of this `Storage` value's own does not refuse it. Nothing else in the interface removes data:

```go title="customstorage/mapstore.go"
// Delete removes the session; nothing else in the interface removes data.
func (m *MapStore) Delete(ctx context.Context, session string) error {
	if err := ctx.Err(); err != nil {
		return err
	}
	m.mu.Lock()
	defer m.mu.Unlock()
	if _, ok := m.sessions[session]; !ok {
		return fmt.Errorf("mapstore: %s: %w", session, thread.ErrNotFound)
	}
	delete(m.sessions, session)
	return nil
}
```

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

Then a session runs on it like on any backend:

```go title="customstorage/main.go"
st := NewMapStore()
s, err := thread.Create(ctx, st, agent, thread.IDs(fixedIDs("s_map")), window)
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
}

again, err := thread.Open(ctx, st, "s_map", agent, window) // Load, through the interface
if err != nil {
	return err
}
fmt.Fprintln(w, "reopened:", len(again.Context()), "messages")
turn, err = again.Send(ctx, weft.User("When will it arrive?"))
if err != nil {
	return err
}
res, err := turn.Wait()
if err != nil {
	return err
}
fmt.Fprintln(w, "answer:", res.Text(), "run:", turn.RunID())
if err := again.Close(ctx); err != nil {
	return err
}
fmt.Fprintln(w, "stored:", st.Sessions())

_, isLeaser := thread.Storage(st).(thread.Leaser)
fmt.Fprintln(w, "Leaser:", isLeaser) // no lease: two Sessions on one MapStore both write
```

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

```text
reopened: 2 messages
answer: It should arrive on Friday. run: s_map-t2
stored: [s_map]
Leaser: false
```

## Optional capabilities

Capabilities are small interfaces discovered by type assertion, so `Storage` never grows (ADR 0011 §5). Implement the ones your store can honour:

| Interface | Methods | What it gives |
|---|---|---|
| [`thread.Flusher`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Flusher) | `Flush(ctx, session)` | Completes buffered durability work: with `FsyncOnFlush` an append writes without syncing and `Flush` makes the session durable. With the default policy it is a no-op that still returns any error held for the session. A missing session is `ErrNotFound`. |
| [`thread.Releaser`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Releaser) | `Release(ctx, session)` | Ends this writer's hold on a session: flush, then let another `Storage` or process write it. A later `Append` re-acquires the hold. |
| [`thread.Leaser`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Leaser) | `Acquire(ctx, session, holder)`, `Yield(ctx, session, holder)` | The per-Session writer lease that keeps two `Session` values on one `Storage` value to one writer. |
| [`thread.Watcher`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Watcher) | `Watch(ctx, session, after)` | The live tail ([Watch a session](https://weftgo.dev/docs/sessions/storage/#watch-a-session)). |

`MapStore` implements none of them, so its last output line is `Leaser: false`.

### Leases

The backend's lock tells `Storage` values and processes apart; it cannot tell two Sessions on one `Storage` value apart, because `Append` names a session, not a writer. A lease can. A Session calls [`Acquire`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Leaser) before every write, naming itself with `holder`, a comparable token it owns:

- `Acquire` takes the backend's cross-instance lock as a first `Append` would (`ErrLocked` when another `Storage` or process holds the session, a torn tail repaired), then the lease: `ErrLocked` naming the session when a different holder has it on this `Storage` value. For the holder that has it, it is idempotent and does no I/O.
- It reports the number of complete entry lines the storage holds (the lines `Load` accounts for, including those skipped under `Salvage`, never a torn tail) and the stored header's `Created`. A Session compares both with what it loaded; a difference is `thread.ErrStale`.
- [`Yield`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Leaser) ends the holder's lease and the storage's hold with it. When a different holder has the lease, it releases nothing and returns nil. A Session's `Close` yields.

The lease is bookkeeping over the lock, not a second lock: the `Storage` methods do not consult it. It ends when its holder yields, when the session is released or deleted through this `Storage` value, or with the process. Without `Leaser`, two Sessions on one value of your backend both write, each blind to the other, and the `ErrStale` check does not exist.

### Releaser

`Release` speaks for the whole `Storage` value: it ends a lease whoever holds it, which is why a Session closes through `Yield` when the backend offers it. It must not race the session's own `Append`; it is the last call of a writer that is done. Releasing a session this `Storage` does not hold is a no-op; one the storage does not hold at all is `ErrNotFound`. A backend that does not lock (Memory) ends the lease and checks that the session exists. The package example is [`ExampleReleaser`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Releaser).

## Resolve open options

Applications pass `thread`'s open options (`Salvage`, `FsyncEveryAppend`, `FsyncOnFlush`, `NoLock`, `OpenLogger`) to your constructor; package [`thread/backend`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/backend) turns them into what a backend acts on. Applications never import it. [`backend.Resolve(opts...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/backend#Resolve) folds the options over the defaults (every append fsynced, the lock on, no salvage, `slog.Default()`) in the order given, skipping nil, and returns a [`backend.Config`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/backend#Config):

| Field | Meaning |
|---|---|
| `Salvage` | A malformed line is a skip reported in the `LoadReport`, not `ErrCorrupt`. `ErrNewerFormat` is never salvaged. |
| `SyncEveryAppend` | `true`, the default, fsyncs every `Append`; `false` defers it to `Flusher`. |
| `NoLock` | Turn off the cross-process writer lock; the caller vouches that one process writes. |
| `Logger` | Where the backend reports its own repairs: a torn tail, a taken-over lock. Never nil. |

Read the config once, at open. An option your backend has no use for is accepted and documented as a no-op, never rejected: `MapStore` buffers, locks and repairs nothing, so all five are no-ops there.

## Conformance

Package [`thread/threadtest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest) is the executable form of the `Storage` promises. Every shipped backend runs it; each table takes a factory that returns fresh storage per subtest:

| Function | What it checks | Runs when |
|---|---|---|
| [`Run(t, open)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#Run) | The interface: round trips without aliasing, atomic batches, arrival order, `ErrNotFound` and invalid ids on every method, `Create` validation, paging through ties, limit normalisation, filters, delete, concurrency, canceled contexts. Then each capability's row. | always |
| [`RunTurns(t, open)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#RunTurns) | The turn machinery's durable shapes on reload: a resume's join, receipts restored from the file alone. | call it beside `Run` |
| [`RunWatch(t, open)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#RunWatch) | The `Watcher` table: backlog, resume point, each entry once, cancel, loud failures, a torn tail waited out, a replaced session ending with `ErrNotFound`. | `Run` calls it for a `Watcher` |
| [`RunLeaser(t, open)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#RunLeaser) | `Acquire` idempotent and counting lines, a second holder `ErrLocked`, `Yield` handing over, `Release` and `Delete` ending the lease. | `Run` calls it for a `Leaser` |
| [`RunOneWriter(t, open)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#RunOneWriter) | The same rule as two `Session` values meet it: `ErrLocked`, `ErrStale`, `Create` and `Fork` taking the lease. | `RunLeaser` runs it |
| [`RunTwoWriters(t, open)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#RunTwoWriters) | Two independent `Storage` values over the same sessions: the second writer `ErrLocked` naming the session, readers never lock, `Release` and `Yield` hand over. | you provide the two-storage factory |

`Run`'s corruption rows (unknown kind, newer `"v"`, malformed and torn lines, a newer header) need a store that can hold undecodable bytes. They run when your storage also implements [`threadtest.RawInjector`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#RawInjector) (`Inject(ctx, session, data)` appends raw bytes, verbatim) and [`threadtest.RawHeaderInjector`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#RawHeaderInjector) (`InjectHeader(ctx, session, line)` creates a session with that first line), and skip otherwise. Memory implements both by holding the raw bytes. For `MapStore` these rows skip, as do Flusher, Releaser, Leaser and Watch:

```sh
go test -v -run TestConformance ./customstorage
```

```text
    --- SKIP: TestConformance/CorruptionIsLoud (0.00s)
    --- SKIP: TestConformance/AppendAfterTornTail (0.00s)
    --- SKIP: TestConformance/HeaderCorruptionIsLoud (0.00s)
    --- SKIP: TestConformance/Flusher (0.00s)
    --- SKIP: TestConformance/Releaser (0.00s)
    --- SKIP: TestConformance/Leaser (0.00s)
    --- SKIP: TestConformance/Watch (0.00s)
```

### Crash tests

A durable backend also proves what survives a killed process. The harness re-executes the test binary as a child, kills it, and asserts through a fresh `Storage` over the same location:

- [`threadtest.CrashTurn(t, helperTest, path, reopen)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#CrashTurn) SIGKILLs the child mid-second-step and checks the first step is on disk. The child side is [`RunCrashTurnChild(t, open)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#RunCrashTurnChild), which creates the session [`CrashSession`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#CrashSession) (`s_crashturn`) at the path in `WEFT_THREADTEST_CRASH_STORAGE`.
- [`threadtest.CrashMatrix(t, helperTest, pathFor, open)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#CrashMatrix) walks every session-layer write point (prompt, turn end, approval, decision, compaction, steer, pool receipt, branch, fork, the expiry sweep, the automatic trim, a queued send's accepted receipt and more), a fresh location per point. The child side is [`RunCrashMatrixChild(t, open)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#RunCrashMatrixChild). The parent asserts over the sessions the child creates, by id: [`CrashMatrixTurnID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#CrashMatrixTurnID), `CrashMatrixParkID`, `CrashMatrixSteerID`, `CrashMatrixPoolID`, `CrashMatrixForkID` and `CrashMatrixKidID` (the pool points' child).

`thread/jsonl` wires both in two pairs of tests: `TestCrashMatrix` calls `CrashMatrix` with `jsonl.Open`, and `TestCrashMatrixHelper` returns at once unless `WEFT_THREADTEST_CRASH_STORAGE` is set, then calls `RunCrashMatrixChild`. A map cannot survive its process, so `MapStore` runs neither.

## Complete example

`customstorage/mapstore.go` is the backend; `customstorage/main.go` runs a session on it:

```go title="customstorage/mapstore.go"
package main

import (
	"cmp"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"maps"
	"slices"
	"strings"
	"sync"

	"github.com/weftgo/weft/thread"
	"github.com/weftgo/weft/thread/backend"
)

// MapStore is a thread.Storage that keeps every session in a map: the
// header and each entry as the JSON line a file backend would write.
// Storing the encoded lines, not the values, is what keeps Load from
// aliasing what is stored. It implements the five methods and none of
// the optional capabilities.
type MapStore struct {
	mu       sync.Mutex
	sessions map[string]*stored
	cfg      backend.Config
}

type stored struct {
	header []byte   // the header line
	lines  [][]byte // one line per entry, in append order
	title  string   // the last non-empty info title, for Query.TitleSearch
}

// NewMapStore takes the shared open vocabulary every backend accepts. A
// map buffers, locks and repairs nothing, so each option is accepted and
// is a no-op here, as thread/backend asks of a backend it means nothing to.
func NewMapStore(opts ...thread.OpenOption) *MapStore {
	return &MapStore{sessions: map[string]*stored{}, cfg: backend.Resolve(opts...)}
}

var _ thread.Storage = (*MapStore)(nil)

// Create writes the header. The id must pass thread.ValidID, a zero
// envelope means the current format, and an existing id is ErrExists.
func (m *MapStore) Create(ctx context.Context, h thread.Header) error {
	if err := ctx.Err(); err != nil {
		return err // a canceled context fails before anything is written
	}
	if !thread.ValidID(h.ID) {
		return fmt.Errorf("mapstore: invalid session id %q", h.ID)
	}
	if h.Weft != 0 && h.Weft != thread.FormatVersion {
		return fmt.Errorf("mapstore: header envelope %d, want %d", h.Weft, thread.FormatVersion)
	}
	line, err := json.Marshal(h) // a zero Weft is written as FormatVersion
	if err != nil {
		return err
	}
	m.mu.Lock()
	defer m.mu.Unlock()
	if _, ok := m.sessions[h.ID]; ok {
		return fmt.Errorf("mapstore: %s: %w", h.ID, thread.ErrExists)
	}
	m.sessions[h.ID] = &stored{header: line}
	return nil
}

// Append encodes the whole batch before it stores any of it: one entry
// that does not encode rejects the batch, so it lands whole or not at all.
func (m *MapStore) Append(ctx context.Context, session string, entries ...thread.Entry) error {
	if err := ctx.Err(); err != nil {
		return err
	}
	lines := make([][]byte, 0, len(entries))
	title := ""
	for _, e := range entries {
		line, err := json.Marshal(e) // every entry kind carries its "type"
		if err != nil {
			return fmt.Errorf("mapstore: %s: encode entry: %w", session, err)
		}
		lines = append(lines, line)
		if info, ok := e.(thread.InfoEntry); ok && info.Title != "" {
			title = info.Title
		}
	}
	m.mu.Lock()
	defer m.mu.Unlock()
	s, ok := m.sessions[session]
	if !ok {
		return fmt.Errorf("mapstore: %s: %w", session, thread.ErrNotFound)
	}
	s.lines = append(s.lines, lines...)
	if title != "" {
		s.title = title
	}
	return nil
}

// Load decodes a snapshot taken under the lock, so a concurrent Delete
// yields the whole session or ErrNotFound. Decoding fresh copies is what
// makes the result the caller's to mutate; thread's own decoder keeps the
// loud rules (an unknown kind or a newer "v" is ErrNewerFormat).
func (m *MapStore) Load(ctx context.Context, session string) (thread.Header, []thread.Entry, *thread.LoadReport, error) {
	if err := ctx.Err(); err != nil {
		return thread.Header{}, nil, nil, err
	}
	m.mu.Lock()
	s, ok := m.sessions[session]
	var header []byte
	var lines [][]byte
	if ok {
		header, lines = s.header, slices.Clone(s.lines)
	}
	m.mu.Unlock()
	if !ok {
		return thread.Header{}, nil, nil, fmt.Errorf("mapstore: %s: %w", session, thread.ErrNotFound)
	}
	var h thread.Header
	if err := json.Unmarshal(header, &h); errors.Is(err, thread.ErrNewerFormat) {
		return thread.Header{}, nil, nil, err // a newer envelope: never ErrCorrupt
	} else if err != nil {
		return thread.Header{}, nil, nil, &thread.CorruptError{Session: session, Line: 1, Err: err}
	}
	entries := make([]thread.Entry, 0, len(lines))
	for i, line := range lines {
		e, err := thread.UnmarshalEntry(line)
		if errors.Is(err, thread.ErrNewerFormat) {
			return thread.Header{}, nil, nil, err // newer, not damaged: never a skip
		}
		if err != nil {
			return thread.Header{}, nil, nil, &thread.CorruptError{Session: session, Line: i + 2, Err: err}
		}
		entries = append(entries, e)
	}
	return h, entries, nil, nil // nil report: nothing dropped or skipped
}

// List filters, orders newest first (ties by id, descending), applies the
// keyset cursor and then the limit; Total ignores the cursor and limit.
func (m *MapStore) List(ctx context.Context, q thread.Query) (thread.Page, error) {
	if err := ctx.Err(); err != nil {
		return thread.Page{}, err
	}
	m.mu.Lock()
	var match []thread.Header
	for _, s := range m.sessions {
		var h thread.Header
		if err := json.Unmarshal(s.header, &h); err != nil {
			continue // List skips what it cannot decode; Load names why
		}
		if !metaMatches(h.Meta, q.Meta) {
			continue
		}
		if q.TitleSearch != "" && !strings.Contains(strings.ToLower(s.title), strings.ToLower(q.TitleSearch)) {
			continue
		}
		match = append(match, h)
	}
	m.mu.Unlock()

	slices.SortFunc(match, func(a, b thread.Header) int {
		if c := b.Created.Compare(a.Created); c != 0 {
			return c
		}
		return cmp.Compare(b.ID, a.ID)
	})
	page := thread.Page{Total: len(match)}
	limit := q.Limit
	switch {
	case limit <= 0:
		limit = 50
	case limit > 500:
		limit = 500
	}
	for _, h := range match {
		if !q.Before.IsZero() {
			older := h.Created.Before(q.Before)
			tiedAfter := q.BeforeID != "" && h.Created.Equal(q.Before) && h.ID < q.BeforeID
			if !older && !tiedAfter {
				continue
			}
		}
		if len(page.Sessions) == limit {
			break
		}
		page.Sessions = append(page.Sessions, h)
	}
	return page, nil
}

// metaMatches: every wanted key present, every value equal.
func metaMatches(have, want map[string]string) bool {
	for k, v := range want {
		if got, ok := have[k]; !ok || got != v {
			return false
		}
	}
	return true
}

// Delete removes the session; nothing else in the interface removes data.
func (m *MapStore) Delete(ctx context.Context, session string) error {
	if err := ctx.Err(); err != nil {
		return err
	}
	m.mu.Lock()
	defer m.mu.Unlock()
	if _, ok := m.sessions[session]; !ok {
		return fmt.Errorf("mapstore: %s: %w", session, thread.ErrNotFound)
	}
	delete(m.sessions, session)
	return nil
}

// Sessions returns the stored session ids, sorted — for the demo's output.
func (m *MapStore) Sessions() []string {
	m.mu.Lock()
	defer m.mu.Unlock()
	return slices.Sorted(maps.Keys(m.sessions))
}
```

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

```go title="customstorage/main.go"
// Command customstorage runs a weft/thread session on MapStore, a
// thread.Storage written from scratch in mapstore.go: go run ./customstorage.
// The model is scripted with wefttest, so it runs offline. main_test.go
// proves the backend with thread/threadtest, the conformance table every
// backend runs.
package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"os"

	"github.com/weftgo/weft"
	"github.com/weftgo/weft/thread"
	"github.com/weftgo/weft/wefttest"
)

func main() {
	if err := run(context.Background(), os.Stdout); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}

func run(ctx context.Context, w io.Writer) error {
	agent := weft.New(wefttest.Script(
		wefttest.Say("Order 1234 shipped on Tuesday."),
		wefttest.Say("It should arrive on Friday."),
	))
	st := NewMapStore()
	s, err := thread.Create(ctx, st, agent, thread.IDs(fixedIDs("s_map")), window)
	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
	}

	again, err := thread.Open(ctx, st, "s_map", agent, window) // Load, through the interface
	if err != nil {
		return err
	}
	fmt.Fprintln(w, "reopened:", len(again.Context()), "messages")
	turn, err = again.Send(ctx, weft.User("When will it arrive?"))
	if err != nil {
		return err
	}
	res, err := turn.Wait()
	if err != nil {
		return err
	}
	fmt.Fprintln(w, "answer:", res.Text(), "run:", turn.RunID())
	if err := again.Close(ctx); err != nil {
		return err
	}
	fmt.Fprintln(w, "stored:", st.Sessions())

	_, isLeaser := thread.Storage(st).(thread.Leaser)
	fmt.Fprintln(w, "Leaser:", isLeaser) // no lease: two Sessions on one MapStore both write

	if err := thread.Delete(ctx, st, "s_map"); err != nil {
		return err
	}
	_, err = thread.Open(ctx, st, "s_map", agent)
	fmt.Fprintln(w, "after Delete:", errors.Is(err, thread.ErrNotFound))
	return nil
}

// window is the model's context window, in tokens: it arms automatic
// compaction, and without one each session logs a WARN at its first turn.
var window = thread.ContextWindow(128_000)

// fixedIDs mints the session id first, then e_1, e_2, … so the output is
// the same on every run.
func fixedIDs(session string) func() string {
	n := 0
	return func() string {
		n++
		if n == 1 {
			return session
		}
		return fmt.Sprintf("e_%d", n-1)
	}
}
```

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

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

```sh
go run ./customstorage
go test ./customstorage
```

```text
reopened: 2 messages
answer: It should arrive on Friday. run: s_map-t2
stored: [s_map]
Leaser: false
after Delete: true
```

## Best practices & gotchas

- **Never return stored values from `Load` or `List`.** The caller may mutate them; `threadtest`'s round-trip row edits the result and loads again. Decode fresh copies, or deep-copy. (Source: `thread/storage.go:62-66`; `threadtest.Run` CreateLoadRoundTrip)
- **Check `ctx` before every call.** A canceled context must fail `Create`, `Append`, `Load`, `List` and `Delete` alike, with nothing written. (Source: `threadtest.Run` ContextCancellation, `thread/threadtest/threadtest.go:1111-1136`)
- **On `Load`, `Append`, `Delete` and the capability methods, answer invalid ids with `ErrNotFound`.** `Create` rejects them with any error. An id is a path component in some backend; `../escape` must not reach the filesystem. (Source: `threadtest.Run` InvalidIDs, CreateValidation, `thread/threadtest/threadtest.go:1243-1277`)
- **Never wrap `ErrNewerFormat` as `ErrCorrupt`.** Newer data is not damage, and `Salvage` must never skip it; `MapStore.Load` returns it unwrapped from both the header and the entry decode. (Source: `thread/errors.go:60-75`; `thread/header.go:88-92`; AGENTS.md T5)
- **Never write a session behind its Session.** An `st.Append` on a session a Session holds is invisible to that Session until the next `Open`, and its next write fails with `ErrStale`. (Source: AGENTS.md T1; `thread/session.go:318` Session godoc, One writer)
- **Implement `Leaser` if two Sessions can share one `Storage` value.** Without it the one-writer rule between them is yours to keep. (Source: `thread/storage.go` Storage godoc, One writer)
- **Run `RunTurns` beside `Run`.** It checks the shapes that only go wrong on a reload. (Source: `thread/threadtest/turns.go:15-25`)

## See also

- [Store sessions: JSONL, SQLite or memory](https://weftgo.dev/docs/sessions/storage/)
- [What is a session?](https://weftgo.dev/docs/sessions/overview/#one-writer): the writer lease
- [The session log format](https://weftgo.dev/docs/sessions/format/): the lines a backend stores
- [ADR 0026](https://github.com/weftgo/weft/blob/v0.20.2/docs/adr/0026-thread-storage-backends.md): storage backends

Symbols used: [`thread.Storage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Storage) · [`thread.Header`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Header) · [`thread.Entry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Entry) · [`thread.UnmarshalEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#UnmarshalEntry) · [`thread.InfoEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#InfoEntry) · [`thread.FormatVersion`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#FormatVersion) · [`thread.ValidID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ValidID) · [`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.LoadReport`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#LoadReport) · [`thread.CorruptError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#CorruptError) · [`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.ErrStale`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrStale) · [`thread.ErrNewerFormat`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrNewerFormat) · [`thread.ErrCorrupt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrCorrupt) · [`thread.Flusher`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Flusher) · [`thread.Releaser`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Releaser) · [`thread.Leaser`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Leaser) · [`thread.Watcher`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Watcher) · [`thread.OpenOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#OpenOption) · [`backend.Resolve`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/backend#Resolve) · [`backend.Config`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/backend#Config) · [`threadtest.Run`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#Run) · [`threadtest.RunTurns`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#RunTurns) · [`threadtest.RunWatch`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#RunWatch) · [`threadtest.RunLeaser`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#RunLeaser) · [`threadtest.RunOneWriter`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#RunOneWriter) · [`threadtest.RunTwoWriters`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#RunTwoWriters) · [`threadtest.RawInjector`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#RawInjector) · [`threadtest.RawHeaderInjector`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#RawHeaderInjector) · [`threadtest.CrashTurn`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#CrashTurn) · [`threadtest.RunCrashTurnChild`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#RunCrashTurnChild) · [`threadtest.CrashMatrix`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#CrashMatrix) · [`threadtest.RunCrashMatrixChild`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#RunCrashMatrixChild) · [`threadtest.CrashSession`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#CrashSession) · [`threadtest.CrashMatrixTurnID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/threadtest#CrashMatrixTurnID) · [`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)
