---
title: What is a session?
description: A weft/thread session is a conversation stored as an append-only tree of entries, written by one Session at a time, durable step by step; Open only reads.
url: https://weftgo.dev/docs/sessions/overview/
type: concept
sources:
  - weft/AGENTS.md:552-589 (block 8), 725-752 (thread rules T1–T5)
  - weft/README.md:570-599 (Sessions, one writer), 607-614 (durability), 781-787 (not frozen)
  - weft/thread/doc.go (Sessions, Concurrency, Errors, Identity)
  - 'weft/thread/session.go:1643-1649 (Close step 2: sends queued behind an undecided approval boundary end with ErrClosed, their accepted receipts stay, the next Open restores them), 1697-1698 (no runner: seal at once), 1739-1780 (sealLocked: every queued Turn ends ErrClosed)'
  - 'scratch proof (weft v0.17.0): a parked call plus one queued send; Close returned nil at once, the queued Turn ended ErrClosed; after Open, Queue() 1 and Pending() 1; Decide ran the resume, then the queued send'
  - weft/thread/session.go:30 (SessionOption), 120 (IDs), 146 (Clock), 318 (Session), 519 (Create), 627 (Open), 834 (ID), 841 (Storage), 861 (Claim), 922 (SessionFromContext), 1678 (Close)
  - weft/thread/id.go:15 (NewSessionID), 19 (NewEntryID), 65 (ValidID)
  - weft/thread/errors.go:40 (ErrLocked), 52 (ErrStale), 60 (ErrCorrupt), 75 (ErrNewerFormat), 131 (ErrClosed)
  - weft/thread/compactmarker.go:14-16 (the OTel API imports)
  - weft/thread/turn.go:1592-1619 (a rewritten tail attaches after the last matching entry); weft/thread/perstep.go:283-302 (the overflow re-run's leaf entry)
  - weft/thread/compaction.go:1306-1319 (the no-window warning, once per Session value)
  - weft/docs/adr/0011-thread-sessions.md (§2 entry tree, §4 turns, §5 storage, §7 per-step turns, amendment B the lease)
  - weft/docs/thread-operations.md (§4 locks and leases, §5 close and shutdown, §6 after a crash, §8 the queue)
  - weft/CHANGELOG.md:592 (Claim), 3835 (Close), 3885 (godoc examples), 4748 (OTel API), 5007 (per-step durability), 5300 (Create, Open, List, Delete)
  - weft/thread/example_test.go ExampleCreate, ExampleHeader, ExampleNewSessionID
  - weft/thread/example_session_test.go ExampleOpen, ExampleSession_Close, ExampleClock
  - weft/thread/writer_test.go ExampleSession_Close_handOver
  - docs-site/examples/sessions/overview.go, sessions_test.go TestDemos/overview, TestSecondWriterLocked, TestOpenRestoresReceipts
---

# What is a session?

A [session](https://weftgo.dev/docs/reference/glossary/#session) is a conversation that `weft/thread` stores as an append-only tree of entries: messages, turn ledgers, labels, summaries. A [`*thread.Session`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session) holds that tree in memory and is the session's only writer until it closes. The prompt is written to the storage before the run starts and every step's messages land as they join the run, so a crash loses at most the step in flight and the turn's closing entry.

`sessions/overview.go` creates a session on the JSONL backend, runs one turn and closes it:

```go title="sessions/overview.go"
st, err := jsonl.Open(dir) // one <id>.jsonl file per session
if err != nil {
	return err
}
s, err := thread.Create(ctx, st, agent, ctxWindow, ids("s_support", "a"))
if err != nil {
	return err
}
turn, err := s.Send(ctx, weft.User("Where is order 1234?"))
if err != nil {
	return err
}
res, err := turn.Wait()
if err != nil {
	return err
}
fmt.Fprintln(w, "answer:", res.Text())
fmt.Fprintln(w, "run:", turn.RunID(), "entries:", len(s.Entries()))
if err := s.Close(ctx); err != nil { // drain, seal, give up the writer's lease
	return err
}
```

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

```text
answer: Order 1234 shipped on Tuesday.
run: s_support-t1 entries: 3
```

The turn wrote three entries: the prompt, the reply and the turn's ledger. The `ids` helper pins the ids so the output is stable; an application leaves it out. `ctxWindow` is `thread.ContextWindow(128_000)`, the model's context window, which arms automatic compaction.

## What a session is

The core is stateless on purpose; `weft/thread` is the layer above it. A session is a header and then its entries, in append order. Each entry has an id, a parent and a time, and the **leaf** is the entry the next one attaches to. What the model sees, [`s.Context()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Context), is the messages on the path from a root to the leaf, repaired with `weft.Repair`. Nothing is rewritten or deleted in place: branching appends a leaf entry, a fork writes a new session, and a compaction appends a summary.

> **Diagram:** A session log holds e1 (user: Where is order 1042?), e2 (assistant: Shipped this morning.), e3 (user: And 5678?) and e4 (assistant: Still processing.). s.Branch(ctx, e2) appends a leaf entry pointing at e2; nothing is rewritten. The next write, e5 (user: Cancel 1042 instead.), attaches to e2, so the model's context is e1, e2, e5. e3 and e4 stay in the file, off the path.
>
> **Diagram:** Session A holds e1, e2 and e3. s.Fork(ctx, e2) writes a new session B whose header names its parent, A#e2: B holds copies of e1 and e2 and continues with its own e3. Session A keeps its leaf and its entries; Fork never moves it. Runs in B carry weft.session.forked_from = A#e2.
>
> **Diagram:** A session log holds e1 to e5. s.Compact(ctx) appends a compaction entry C, a summary of e1 to e3. Those entries stay in the file; the context at the leaf becomes the summary, then e4 and e5, the kept recent entries. s.Uncompact(ctx) undoes it by branching back to the entry before the compaction.

On the JSONL backend a session is one file you can read with `jq` and back up with `cp`: one header line, then one line per entry. The other backends store the same lines ([Store sessions](https://weftgo.dev/docs/sessions/storage/)).

`thread` imports the core, the standard library and the OTel API (for the compaction marker record), never a database driver; the SQLite driver lives in `thread/sqlite` alone. Godoc examples cover most of the package; [`ExampleCreate`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Create) shows a session carrying a title, application state and an application message, and [`ExampleHeader`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Header) the header line itself.

## Create and open

[`thread.Create(ctx, st, agent, opts...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Create) starts a new session in a [`thread.Storage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Storage): a fresh header under a new time-sortable id, and an empty tree. The header is all it writes. The agent is the session's own: `Send` runs it and compaction summarizes with its model; it must not be nil. An id the storage already holds fails with `thread.ErrExists`.

[`thread.Open(ctx, st, id, agent, opts...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Open) loads a stored session, positioned at its leaf. Options are [`thread.SessionOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SessionOption) values, the same at `Create`, `Open` and `Fork`; header options (`WithMeta`, `PublicID`, `WithLineage`) fail `Open` with `ErrCreateOnly`.

**`Open` is read-only (T3).** It validates the tree (unique valid ids, every parent an earlier entry) and refuses a file that fails with `thread.ErrCorrupt`. It writes no entry, takes no lock and starts no run. Input a stopped writer had accepted and not settled is restored to the queue and waits for you. Here a writer is shut down while a turn runs and a second message waits behind it; the next process opens the session:

```go title="sessions/overview.go"
st2, err := jsonl.Open(dir)
if err != nil {
	return err
}
reopened, err := thread.Open(ctx, st2, "s_export", next, ctxWindow, ids("", "b"))
if err != nil {
	return err
}
for _, q := range reopened.Queue() { // what the stopped writer accepted, restored
	fmt.Fprintln(w, "restored:", q.Policy, q.Msg.Text())
}
fmt.Fprintln(w, "model calls after Open:", len(model.Requests()))

turn, err := reopened.Continue(ctx) // run it now; the next Send would too
if err != nil {
	return err
}
res, err := turn.Wait()
if err != nil {
	return err
}
fmt.Fprintln(w, "continued:", res.Text())
```

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

```text
restored: queue Then email it to me.
model calls after Open: 0
continued: Sent to the address on file.
```

`Open` restored the queued send and called no model. [`s.Continue(ctx)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Continue) runs it now; without it, the next `Send` runs it first ([Send turns](https://weftgo.dev/docs/sessions/turns/#send-a-turn)). [`s.Queue()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Queue) lists what was restored and `s.ClearQueue(ctx)` drops it ([Busy policies](https://weftgo.dev/docs/sessions/busy-and-steering/#receipts)). The package example is [`ExampleOpen`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Open).

Three accessors identify a session: [`s.ID()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.ID) is the header's id and the storage key; [`s.Storage()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Storage) returns the storage it was created or opened on, read-only by convention (`thread/pool` creates child sessions there); and inside a tool that a session's turn runs, [`thread.SessionFromContext(ctx)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SessionFromContext) returns that session. Outside a session's run it returns nil.

## One writer

**One `Session` writes a session (T1).** A Session takes its session's writer lease with its first write (`Create` and `Fork` are first writes) and holds it until `Close`. Another Session on the same session opens and reads; every write it makes fails with [`thread.ErrLocked`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrLocked) and changes nothing. A Session whose view fell behind, because another writer appended after it was opened, fails its write with [`thread.ErrStale`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrStale): open the session again.

```go title="sessions/overview.go"
writer, err := thread.Open(ctx, st, "s_support", agent, ctxWindow, ids("", "b"))
if err != nil {
	return err
}
other, err := thread.Open(ctx, st, "s_support", agent, ctxWindow, ids("", "c"))
if err != nil {
	return err
}
if err := writer.Claim(ctx); err != nil { // the writer's lease, taken before any write
	return err
}
fmt.Fprintln(w, "other reads:", len(other.Context()), "messages")
err = other.SetInfo(ctx, "Order 1234", nil)
fmt.Fprintln(w, "other writes:", errors.Is(err, thread.ErrLocked))

if err := writer.SetInfo(ctx, "Order 1234: shipped", nil); err != nil {
	return err
}
if err := writer.Close(ctx); err != nil {
	return err
}
err = other.SetInfo(ctx, "Order 1234", nil)
fmt.Fprintln(w, "after the writer closed:", errors.Is(err, thread.ErrStale))
if err := other.Close(ctx); err != nil {
	return err
}
again, err := thread.Open(ctx, st, "s_support", agent, ctxWindow, ids("", "d"))
if err != nil {
	return err
}
fmt.Fprintln(w, "reopened:", again.Title())
```

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

```text
other reads: 2 messages
other writes: true
after the writer closed: true
reopened: Order 1234: shipped
```

The rule has two layers. Between processes and between `Storage` values, the backend's own lock refuses a second writer with `ErrLocked` (a file lock on JSONL, a lock row on SQLite). Between Session values on one `Storage` value, the lease does it: the [`thread.Leaser`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Leaser) capability, which Memory, jsonl and sqlite implement. Reading never takes either: `Open`, `List`, `Load`, `Watch` and every read of a Session work while another writer holds the session. The stale check compares the stored header's creation time and the number of entry lines, not contents. The package example is [`ExampleSession_Close_handOver`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Session.Close-HandOver).

### Claim

[`s.Claim(ctx)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Claim) takes the writer lease now, without writing an entry. It returns nil when this Session holds the lease (or the storage has no `Leaser` to ask), `ErrLocked` while another writer holds the session (nothing taken), `ErrStale` when the stored session moved past this Session's view (the lease is given back, so a fresh Session can claim it), and `ErrClosed` once the Session is sealed. A Session that claimed holds the lease until `Close`, as one that wrote does, so claim only with a `Close` to come. `weft/runtime` uses it to make sure it is the writer before it acknowledges a debugger's decision.

### Close what you open

**`s.Close(ctx)` is how a writer stops (T2).** [`Close`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Close) does four things in order:

1. New work stops at once: `Send` and `Continue` fail with [`thread.ErrClosed`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrClosed).
2. It waits for the running turn, the sends queued behind it and any approval resume those turns arm. Sends queued behind an approval boundary that nobody decides cannot drain: once no turn runs, `Close` goes on and their Turns end with `ErrClosed`.
3. It seals the Session: every later write fails with `ErrClosed`. Reads keep answering, and `Fork` still works because it writes another session.
4. It releases the lease and the backend's hold, so another writer can take the session.

A queued Turn that ends with `ErrClosed` is not lost. Its `accepted` receipt stays in the file, the next `Open` restores it to `s.Queue()`, and it runs once the boundary is decided. A caller that sends the message again on `ErrClosed` gets it answered twice: reopen and read `s.Queue()` instead.

If `ctx` ends while Close waits, Close gives up: it cancels the running turn, ends every queued `Turn` with `ErrClosed` and returns `ctx.Err()`. Call `Close` again to finish sealing and releasing. The queued sends keep their receipts in the file, and the next `Open` restores them, as the region above shows:

```text
close gave up: true
running turn: canceled
queued turn: canceled true
```

`Close` is idempotent. It does not wait for `thread/pool` children (close the pool first), and it must not be called from inside the session's own run, a tool or a hook, because it would wait for the turn that calls it. The package example is [`ExampleSession_Close`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Session.Close).

## Durability

**Accepted input is durable input (T4).** A `Send` that returns a `Turn` has written and flushed its prompt, or the receipt entry of a message it queued or steered. The run's messages are appended as they join its transcript, through `weft.OnMessages`, the core's transcript observer, each step once ([ADR 0011 §7](https://github.com/weftgo/weft/blob/v0.20.2/docs/adr/0011-thread-sessions.md)). The turn's end normally appends only its bookkeeping: the turn entry and any receipts or approval entries, in one atomic batch that completes even if the caller's context is canceled.

So a crash mid-turn loses at most the step in flight (its partial text) and the closing turn entry; the prompt, or the receipt, and every finished step are already stored. A tool call left without a result is answered by the loop's input repair on the next run, so the next model sees a complete transcript. A failed turn whose final form differs from its raw tail (an interrupt's golden texts) is rewritten from its first differing message on a fresh line, attached after the last entry that still matches; the raw tail stays on its own branch. No leaf entry is written for that; a leaf entry back to where the turn started is written only for an overflow re-run's failed attempt.

How durable "stored" is depends on the backend and its fsync policy. `thread.Memory()` loses everything with the process. On jsonl and sqlite every append is fsynced before it returns by default, so it survives an OS crash or a power cut; with [`thread.FsyncOnFlush()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#FsyncOnFlush) an append survives the process dying, and only what was flushed survives an OS crash ([Store sessions](https://weftgo.dev/docs/sessions/storage/#open-options)).

**Readers fail loudly (T5).** An entry kind or a `"v"` version this build does not know is [`thread.ErrNewerFormat`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrNewerFormat), never skipped. A damaged line is `ErrCorrupt` naming the line; opened with `thread.Salvage()` the backend skips it and reports the skip in [`s.LoadReport()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.LoadReport), as it always reports a torn final line it dropped ([Recover a damaged file with Salvage](https://weftgo.dev/docs/sessions/storage/#recover-a-damaged-file-with-salvage)).

## IDs and clocks

Session and entry ids are time-sortable. [`thread.NewSessionID()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#NewSessionID) returns `s_` plus 26 characters: a millisecond timestamp then random bits, in Crockford base32 (the ULID shape). [`thread.NewEntryID()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#NewEntryID) returns `e_` plus 26. Ids born in the same millisecond order randomly, so a session's order of record is its entry order, never id order. [`thread.ValidID(id)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ValidID) reports whether an id is 1 to 128 letters, digits, `_` or `-`, so an id is always one path component:

```go title="sessions/overview.go"
id := thread.NewSessionID()
fmt.Fprintln(w, "new id:", id[:2], len(id), thread.ValidID(id), thread.ValidID("../etc/passwd"))
```

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

```text
new id: s_ 28 true false
```

Two options pin what a session mints, for tests and examples. [`thread.IDs(fn)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#IDs) takes every id from `fn`: the session id `Create` or `Fork` generates, then each entry id. An id that fails `ValidID` or repeats one the session holds fails the write. [`thread.Clock(now)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Clock) makes `now` the session's time source: the header's `Created`, every entry's `Created`, and the approval machinery's expiry arithmetic, all in UTC. Both may run with the session's lock held, so they must return quickly and never call the Session; the `Clock` function may also be called from the runner's goroutine and must be safe for concurrent use. The examples are [`ExampleNewSessionID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-NewSessionID) and [`ExampleClock`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#example-Clock).

## What it does not do

- **It does not merge writers.** One Session writes; a second is refused, not reconciled. On a backend without `Leaser` two Sessions on one `Storage` value both write, each blind to the other.
- **It does not run anything on `Open`.** Restored input waits for `Send` or `Continue`.
- **It does not delete history.** `thread.Delete` removes a whole session; nothing else removes data. `Delete` does not look for open Sessions, so close one first.
- **It does not freeze the format yet.**

## Stability

`weft/thread` is pre-1.0 and not frozen: its API and its stored format may change between minor versions, each change recorded in the CHANGELOG with what to write instead. What holds today: a reader fails loudly on what it does not know, and golden files pin every format version the current build reads ([The session log format](https://weftgo.dev/docs/sessions/format/)).

## Complete example

`sessions/overview.go` creates, writes, hands over, restores and mints ids:

```go title="sessions/overview.go"
package main

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

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

// demoOverview is the page "What is a session?": create a session, run a
// turn, close it; one writer at a time; and what Open restores after a
// writer stopped with work queued.
func demoOverview(ctx context.Context, w io.Writer, dir string) error {
	agent := weft.New(wefttest.Script(
		wefttest.Say("Order 1234 shipped on Tuesday."),
	), weft.Name("support"))

	st, err := jsonl.Open(dir) // one <id>.jsonl file per session
	if err != nil {
		return err
	}
	s, err := thread.Create(ctx, st, agent, ctxWindow, ids("s_support", "a"))
	if err != nil {
		return err
	}
	turn, err := s.Send(ctx, weft.User("Where is order 1234?"))
	if err != nil {
		return err
	}
	res, err := turn.Wait()
	if err != nil {
		return err
	}
	fmt.Fprintln(w, "answer:", res.Text())
	fmt.Fprintln(w, "run:", turn.RunID(), "entries:", len(s.Entries()))
	if err := s.Close(ctx); err != nil { // drain, seal, give up the writer's lease
		return err
	}

	if err := oneWriter(ctx, w, st, agent); err != nil {
		return err
	}
	if err := restore(ctx, w, dir); err != nil {
		return err
	}

	id := thread.NewSessionID()
	fmt.Fprintln(w, "new id:", id[:2], len(id), thread.ValidID(id), thread.ValidID("../etc/passwd"))
	return nil
}

// oneWriter opens the stored session twice on one Storage value: the
// first Session to write is the writer until it closes; the other reads,
// and its writes are refused.
func oneWriter(ctx context.Context, w io.Writer, st thread.Storage, agent *weft.Agent) error {
	writer, err := thread.Open(ctx, st, "s_support", agent, ctxWindow, ids("", "b"))
	if err != nil {
		return err
	}
	other, err := thread.Open(ctx, st, "s_support", agent, ctxWindow, ids("", "c"))
	if err != nil {
		return err
	}
	if err := writer.Claim(ctx); err != nil { // the writer's lease, taken before any write
		return err
	}
	fmt.Fprintln(w, "other reads:", len(other.Context()), "messages")
	err = other.SetInfo(ctx, "Order 1234", nil)
	fmt.Fprintln(w, "other writes:", errors.Is(err, thread.ErrLocked))

	if err := writer.SetInfo(ctx, "Order 1234: shipped", nil); err != nil {
		return err
	}
	if err := writer.Close(ctx); err != nil {
		return err
	}
	err = other.SetInfo(ctx, "Order 1234", nil)
	fmt.Fprintln(w, "after the writer closed:", errors.Is(err, thread.ErrStale))
	if err := other.Close(ctx); err != nil {
		return err
	}
	again, err := thread.Open(ctx, st, "s_support", agent, ctxWindow, ids("", "d"))
	if err != nil {
		return err
	}
	fmt.Fprintln(w, "reopened:", again.Title())
	return again.Close(ctx)
}

// restore stops a writer while a turn runs and a second message waits
// behind it, then opens the session again as the next process would.
func restore(ctx context.Context, w io.Writer, dir string) error {
	export, started, _ := slowTool("export")
	agent := weft.New(wefttest.Script(
		wefttest.ToolCalls(wefttest.Call{Name: "export", ID: "call_1"}),
	), export)
	st, err := jsonl.Open(dir)
	if err != nil {
		return err
	}
	s, err := thread.Create(ctx, st, agent, ctxWindow, ids("s_export", "a"))
	if err != nil {
		return err
	}
	running, err := s.Send(ctx, weft.User("Export my order history."))
	if err != nil {
		return err
	}
	<-started
	queued, err := s.Send(ctx, weft.User("Then email it to me.")) // Queue: an accepted receipt, flushed
	if err != nil {
		return err
	}

	// Shutdown with no time left: Close gives up waiting, cancels the
	// running turn and ends the queued Turn. A second Close finishes.
	expired, cancel := context.WithCancel(ctx)
	cancel()
	err = s.Close(expired)
	fmt.Fprintln(w, "close gave up:", errors.Is(err, context.Canceled))
	if err := s.Close(ctx); err != nil {
		return err
	}
	_, err = running.Wait()
	fmt.Fprintln(w, "running turn:", running.Outcome())
	_, err = queued.Wait()
	fmt.Fprintln(w, "queued turn:", queued.Outcome(), errors.Is(err, thread.ErrClosed))

	// The next process: a fresh Storage over the same directory, and an
	// agent whose model has served nothing yet.
	model := wefttest.Script(wefttest.Say("Sent to the address on file."))
	next := weft.New(model)
	st2, err := jsonl.Open(dir)
	if err != nil {
		return err
	}
	reopened, err := thread.Open(ctx, st2, "s_export", next, ctxWindow, ids("", "b"))
	if err != nil {
		return err
	}
	for _, q := range reopened.Queue() { // what the stopped writer accepted, restored
		fmt.Fprintln(w, "restored:", q.Policy, q.Msg.Text())
	}
	fmt.Fprintln(w, "model calls after Open:", len(model.Requests()))

	turn, err := reopened.Continue(ctx) // run it now; the next Send would too
	if err != nil {
		return err
	}
	res, err := turn.Wait()
	if err != nil {
		return err
	}
	fmt.Fprintln(w, "continued:", res.Text())
	return reopened.Close(ctx)
}
```

[sessions/overview.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/sessions/overview.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 overview
go test ./sessions
```

```text
answer: Order 1234 shipped on Tuesday.
run: s_support-t1 entries: 3
other reads: 2 messages
other writes: true
after the writer closed: true
reopened: Order 1234: shipped
close gave up: true
running turn: canceled
queued turn: canceled true
restored: queue Then email it to me.
model calls after Open: 0
continued: Sent to the address on file.
new id: s_ 28 true false
```

Each `Session` value (from `Create`, `Open` or `Fork`) logs one `WARN` at its first turn, `thread: no context window known for this session`, unless `thread.ContextWindow` or `thread.ModelWindows` gives it a window; without one, automatic compaction stays off. `thread.NoAutoCompact()` turns compaction off and silences the line. The demo passes `ctxWindow`, so standard error stays empty ([compaction](https://weftgo.dev/docs/sessions/compaction/)). The tests in `sessions/sessions_test.go` also pin `ErrLocked` for a second writer, `ErrClosed` after `Close`, and the restored queue.

## Best practices & gotchas

The rules that follow from this model are with the tasks they apply to: closing, retrying (a failed turn included) and `IDs`/`Clock` in [Send turns › Best practices](https://weftgo.dev/docs/sessions/turns/#best-practices--gotchas), deleting in [Store sessions › Best practices](https://weftgo.dev/docs/sessions/storage/#best-practices--gotchas), and never appending behind a Session in [Write your own thread.Storage](https://weftgo.dev/docs/sessions/custom-storage/#best-practices--gotchas).

## See also

- [Store sessions: JSONL, SQLite or memory](https://weftgo.dev/docs/sessions/storage/)
- [Send turns and wait for them](https://weftgo.dev/docs/sessions/turns/)
- [Label, branch and fork a session](https://weftgo.dev/docs/sessions/tree/)
- [Operate sessions in production](https://weftgo.dev/docs/sessions/operations/)
- [Glossary: session](https://weftgo.dev/docs/reference/glossary/#session)

Symbols used: [`thread.Session`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session) · [`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) · [`thread.SessionOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SessionOption) · [`thread.Storage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Storage) · [`thread.Leaser`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Leaser) · [`Session.Send`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Send) · [`Session.Context`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Context) · [`Session.Entries`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Entries) · [`Session.Queue`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Queue) · [`Session.Continue`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Continue) · [`Session.Claim`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Claim) · [`Session.Close`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Close) · [`Session.SetInfo`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.SetInfo) · [`Session.Title`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Title) · [`Session.ID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.ID) · [`Session.Storage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Storage) · [`Session.LoadReport`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.LoadReport) · [`thread.SessionFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SessionFromContext) · [`thread.IDs`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#IDs) · [`thread.Clock`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Clock) · [`thread.NewSessionID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#NewSessionID) · [`thread.NewEntryID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#NewEntryID) · [`thread.ValidID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ValidID) · [`thread.FsyncOnFlush`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#FsyncOnFlush) · [`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.ErrClosed`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrClosed) · [`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) · [`jsonl.Open`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/jsonl#Open) · [`weft.User`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#User) · [`weft.OnMessages`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#OnMessages) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script)
