Write your own thread.Storage
A session backend is any type that implements 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 is the conformance table every backend runs before it may call itself one. Every shipped backend passes it, and threadtest.RunTurns beside it; passing both is necessary, not sufficient, and a durable store also runs the 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:
// 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)Its test runs the table:
// 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() })}go test ./customstorage passes: every row of Run and RunTurns that applies to a backend without capabilities.
The Storage interface
Section titled “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:
// 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(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:
// 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(ctx, session) returns the header and every entry in append order, plus a *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 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:
// 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(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):
// 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(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:
// 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}Then a session runs on it like on any backend:
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 interfaceif 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 writereopened: 2 messagesanswer: It should arrive on Friday. run: s_map-t2stored: [s_map]Leaser: falseOptional capabilities
Section titled “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 | 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 | 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 | 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 | Watch(ctx, session, after) | The live tail (Watch a session). |
MapStore implements none of them, so its last output line is Leaser: false.
Leases
Section titled “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 before every write, naming itself with holder, a comparable token it owns:
Acquiretakes the backend’s cross-instance lock as a firstAppendwould (ErrLockedwhen anotherStorageor process holds the session, a torn tail repaired), then the lease:ErrLockednaming the session when a different holder has it on thisStoragevalue. 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
Loadaccounts for, including those skipped underSalvage, never a torn tail) and the stored header’sCreated. A Session compares both with what it loaded; a difference isthread.ErrStale. Yieldends 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’sCloseyields.
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
Section titled “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.
Resolve open options
Section titled “Resolve open options”Applications pass thread’s open options (Salvage, FsyncEveryAppend, FsyncOnFlush, NoLock, OpenLogger) to your constructor; package thread/backend turns them into what a backend acts on. Applications never import it. backend.Resolve(opts...) 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:
| 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
Section titled “Conformance”Package 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) | 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) | 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) | 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) | 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) | The same rule as two Session values meet it: ErrLocked, ErrStale, Create and Fork taking the lease. | RunLeaser runs it |
RunTwoWriters(t, open) | 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 (Inject(ctx, session, data) appends raw bytes, verbatim) and 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:
go test -v -run TestConformance ./customstorage --- 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
Section titled “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)SIGKILLs the child mid-second-step and checks the first step is on disk. The child side isRunCrashTurnChild(t, open), which creates the sessionCrashSession(s_crashturn) at the path inWEFT_THREADTEST_CRASH_STORAGE.threadtest.CrashMatrix(t, helperTest, pathFor, open)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 isRunCrashMatrixChild(t, open). The parent asserts over the sessions the child creates, by id:CrashMatrixTurnID,CrashMatrixParkID,CrashMatrixSteerID,CrashMatrixPoolID,CrashMatrixForkIDandCrashMatrixKidID(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
Section titled “Complete example”customstorage/mapstore.go is the backend; customstorage/main.go runs a session on it:
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))}// 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) }}View on GitHub · run it from docs-site/examples:
go run ./customstoragego test ./customstoragereopened: 2 messagesanswer: It should arrive on Friday. run: s_map-t2stored: [s_map]Leaser: falseafter Delete: trueBest practices & gotchas
Section titled “Best practices & gotchas”- Never return stored values from
LoadorList. 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.RunCreateLoadRoundTrip) - Check
ctxbefore every call. A canceled context must failCreate,Append,Load,ListandDeletealike, with nothing written. (Source:threadtest.RunContextCancellation,thread/threadtest/threadtest.go:1111-1136) - On
Load,Append,Deleteand the capability methods, answer invalid ids withErrNotFound.Createrejects them with any error. An id is a path component in some backend;../escapemust not reach the filesystem. (Source:threadtest.RunInvalidIDs, CreateValidation,thread/threadtest/threadtest.go:1243-1277) - Never wrap
ErrNewerFormatasErrCorrupt. Newer data is not damage, andSalvagemust never skip it;MapStore.Loadreturns 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.Appendon a session a Session holds is invisible to that Session until the nextOpen, and its next write fails withErrStale. (Source: AGENTS.md T1;thread/session.go:318Session godoc, One writer) - Implement
Leaserif two Sessions can share oneStoragevalue. Without it the one-writer rule between them is yours to keep. (Source:thread/storage.goStorage godoc, One writer) - Run
RunTurnsbesideRun. It checks the shapes that only go wrong on a reload. (Source:thread/threadtest/turns.go:15-25)
See also
Section titled “See also”- Store sessions: JSONL, SQLite or memory
- What is a session?: the writer lease
- The session log format: the lines a backend stores
- ADR 0026: storage backends
Symbols used: thread.Storage · thread.Header · thread.Entry · thread.UnmarshalEntry · thread.InfoEntry · thread.FormatVersion · thread.ValidID · thread.Query · thread.Page · thread.LoadReport · thread.CorruptError · thread.ErrNotFound · thread.ErrExists · thread.ErrLocked · thread.ErrStale · thread.ErrNewerFormat · thread.ErrCorrupt · thread.Flusher · thread.Releaser · thread.Leaser · thread.Watcher · thread.OpenOption · backend.Resolve · backend.Config · threadtest.Run · threadtest.RunTurns · threadtest.RunWatch · threadtest.RunLeaser · threadtest.RunOneWriter · threadtest.RunTwoWriters · threadtest.RawInjector · threadtest.RawHeaderInjector · threadtest.CrashTurn · threadtest.RunCrashTurnChild · threadtest.CrashMatrix · threadtest.RunCrashMatrixChild · threadtest.CrashSession · threadtest.CrashMatrixTurnID · thread.Create · thread.Open