---
title: Run bounded child sessions with a pool
description: 'Delegate work from a weft/thread session to child agents with thread/pool: pool.New(max) bounds the child runs at work, MustWrap and Submit start children as sessions of their own, receipts record each delegation, and Decide, Wait, Forward, Cancel, Recover and Close manage them.'
url: https://weftgo.dev/docs/sessions/pools/
type: how-to
sources:
  - 'W11-auditA2-fix, v0.20.2: weft/thread/approval.go:1206-1221; weft/google/stream.go:155-167; weft/thread/threadrec.go:769-772; docs-site/examples/sessions/idempotent.go (the key: session, call id, order id), idempotent_test.go TestIdempotentRefundPerSession'
  - weft/AGENTS.md:591-594 (block 8, Pool), 714-724 (rule 13 and its pool exception)
  - weft/README.md:633-661 (delegation is bounded and receipted)
  - weft/docs/adr/0022-thread-pool.md (§1 the pool, §2 sync and async, §3 child sessions, §4 receipts, §7 nested approvals, §8 forwarding; amendment §A the slot rule, §B depth, §C the replay rule, §D the wrapper is never decidable, §E Decide arms, §F receipts end, §G recovery, §H inherited expiry and signing, §I model-visible text, §J delete, branch and fork, §K the bound is per pool, §M async children)
  - weft/docs/thread-operations.md (§5 shutdown, §10 pool operations)
  - weft/thread/pool/pool.go:1-61 (package doc - the bound, costs, lineage), 81-139 (ErrClosed, ErrUnknownReceipt, ErrNotRunning, ErrNoAgent, ErrDepth, ErrCycle, ErrDuplicateWrap, StateError), 143 (DefaultMaxDepth), 176 (Pool), 259-292 (Option, IDs, MaxDepth, New), 323-376 (State, Receipt, Settled), 399 (Submit), 464 (Cancel), 558 (Wait), 629 (Close), 695 (Receipts), 744 (Children), 763 (Descendants), 867-968 (submit - the child session and its options), 942 (a new delegation attaches the watch), 989-1151 (run - the running receipt before the turn; 874-877 a queued child canceled before it starts), 1397-1398 (a settlement's usage is Turns plus Summaries)
  - weft/thread/pool/wrap.go:12-66 (CodeSubagentDepth, CodeSubagentCanceled, the model-visible texts), 72-100 (WrapOption, Async, ToolOptions), 135 (Wrap), 226 (MustWrap)
  - 'weft/thread/pool/wrap.go:156-160 (no parent session: the bare path, before the async check at 178-184)'
  - weft/thread/pool/bridge.go:941 (Register), 1045 (Decide), 1067 (DecideSigned), 1074 (DecideSigned attaches the watch), 1778 (Forward)
  - 'v0.20.2: weft/thread/pool/bridge.go:1757-1777 (Forward needs the run''s turn in flight; in the window a child refuses as the state it is leaving, accepted or parked; a retry a moment later steers; Forward waits for a send under way, ctx bounding it; a refusal of this pool''s child never reads running, only an Orphan''s); weft/thread/pool/forwardwindow_internal_test.go:211 (TestForwardRetriedFromTheReceiptSteers)'
  - 'v0.20.2: weft/thread/pool/pool.go:414-463 (Cancel: a run reaching its boundary first settles canceled; a child still parking: Cancel waits for the park, ctx bounding it; a child that is a parent ends its sync grandchildren first, each settled canceled in its ledger, waiting at most 30 s; past that the pool settles it canceled, its stop naming the bound, its run abandoned and still counted by Close; async children not ended), 587-628 (Close: a parked child under a parent at rest stays parked; a sync child parked under a child Close cancels is canceled at its boundary; Cancel''s 30 s bound); weft/thread/pool/bridge.go:401-406 (nestedEndWait 30 s), 1001-1012 (a grandchild''s re-park mirrors on up, supersedes the earlier request, an earlier decision does not decide it)'
  - weft/thread/pool/recover.go:58 (Recover)
  - 'weft/thread/pool/recover.go:13-43 (v0.20.2: a child whose resume was under way is still at its decided boundary, the pump resumes it again and an approved call whose result was not recorded runs again, at any depth; Replay classes do not gate a session resume; a child that never finished its first run settles failed and is not started again); weft/thread/pool/twolevel_test.go:632 (TestNestedRestartMidApprovedCallRunsItAgain); weft/docs/thread-operations.md:400-418 (key it by the call id, weft.CallFromContext)'
  - weft/core/tool.go:768-790 (Call, CallID; CallFromContext for per-call idempotency keys); docs-site/examples/sessions/idempotent.go, idempotent_test.go TestIdempotentRefund (two resumes of one parked call under one approval run the handler twice; the keyed tool pays once)
  - weft/thread/entry.go:513-556 (PoolReceiptEntry and the Pool* statuses)
  - weft/thread/approval.go:73-83 (ErrDelegated), 861-895 (the chain never decides a delegating call)
  - 'weft/thread/poolplumbing.go:361-369 (MirrorWatchers: the owners of a WatchMirrors notification, several pools on one parent)'
  - weft/thread/poolplumbing.go:11-25 (the plumbing boundary), 37 (AppendPoolReceipt), 66 (AppendApprovalRequests), 107-121 (MirroredRequest), 132 (MirroredRequests), 180 (ResolveDelegation), 209 (DenyMirrored), 261 (ReplayDecisions), 307 (CancelDelegated), 348 (WatchMirrors), 417 (InheritApprovals)
  - weft/thread/session.go:1535-1539 (Delegated sums direct settlements), Usage (Delegated), Session.Storage, Session.Lineage, SessionFromContext; WithLineage, WithMeta
  - weft/thread/compaction.go:1306-1319 (the no-context-window warning)
  - weft/CHANGELOG.md:3247 (an async child keeps the delegating run's values), 3871 (thread 0.9.0 pool additions), 4049-4060 (model-visible pool texts), 4101 (Recover's limits), 4942-4983 (thread 0.5.0 - New, Wrap, Submit, receipts, Usage.Delegated, nested approvals, Forward, the plumbing)
  - weft/thread/pool/example_test.go ExamplePool_Wrap, ExamplePool_Submit, ExamplePool_Submit_watch, ExamplePool_Decide, ExamplePool_Cancel, ExamplePool_Close, ExamplePool_Forward, ExampleReceipts, ExamplePool_Register, ExamplePool_Recover, ExampleMaxDepth, ExampleDescendants
  - weft/thread/pool/text_test.go TestFailureTextMatchesCore, TestModelVisibleTexts; bridge_test.go TestCloseCoversEverything; pool_test.go TestWrapAsyncGolden, TestWrapOutsideSession, TestNewMaxPanics; sem_test.go TestFIFOQueue, TestSlotHandOff; bridge_test.go TestChainNeverDecidesWrapper, TestWrapperNotDecidable, TestInterruptReachesParkedChild; lineage_test.go TestDeleteParentOrphansChildren
  - docs-site/examples/sessions/pools.go, pools_test.go TestPoolBound, TestPoolAsyncDecided, TestPoolRecover, TestDelegatedUsage, sessions_test.go TestDemos/pools
---

# Run bounded child sessions with a pool

[`pool.New(max)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#New) returns a [`*pool.Pool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool) that admits at most `max` child runs at work at once. [`p.MustWrap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.MustWrap) turns an agent into a delegation tool, and [`p.Submit`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.Submit) hands it work directly. Every child runs as a [session](https://weftgo.dev/docs/reference/glossary/#session) of its own in the parent's storage, each delegation leaves receipt entries in the parent, and the child's cost lands in the parent's `Usage.Delegated`.

`sessions/pools.go` wraps a research agent and lets the support agent call it:

```go title="sessions/pools.go"
p := pool.New(4, childIDs()) // at most 4 child runs at work at once
researcher := weft.New(wefttest.Script(wefttest.Say("Order 1234 left the Leeds depot on Monday.")))
research := p.MustWrap("research", "Research an order in depth.", researcher)

support := weft.New(wefttest.Script(
	wefttest.ToolCalls(wefttest.Call{Name: "research", ID: "call_1", Args: `{"prompt":"Trace order 1234."}`}),
	wefttest.Say("Order 1234 left the depot on Monday."),
), research)
s, err := thread.Create(ctx, st, support, ctxWindow, ids("s_support", "a"), at(base))
if err != nil {
	return thread.Usage{}, err
}
turn, err := s.Send(ctx, weft.User("Where is order 1234?"))
if err != nil {
	return thread.Usage{}, err
}
res, err := turn.Wait()
if err != nil {
	return thread.Usage{}, err
}
fmt.Fprintln(w, "reply:", res.Text())
for _, r := range pool.Receipts(s) {
	fmt.Fprintf(w, "receipt %s: %s child %s call %s stop %q\n", r.ID, r.State, r.Child, r.Call, r.Stop)
}
u := s.Usage()
fmt.Fprintln(w, "output tokens: run", res.Usage.OutputTokens, "| turns", u.Turns.OutputTokens, "| delegated", u.Delegated.OutputTokens)
```

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

```text
reply: Order 1234 left the depot on Monday.
receipt e_a3: done child c_1 call call_1 stop "Order 1234 left the Leeds depot on Monday."
output tokens: run 10 | turns 10 | delegated 5
```

The call waited for the child and read its answer. The receipt names the child session (`c_1`, minted by `childIDs`, a [`pool.IDs`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#IDs) option that keeps the output stable) and the call that delegated. The child's 5 output tokens are in `Delegated`, not in the run's usage. `ids`, `at` and `ctxWindow` are the demos' helpers for pinned ids, a pinned clock and a context window.

## How a pool works

A pool is a bound on concurrent child runs, per `Pool` value: two pools are two bounds, and a process that wants one bound shares one `Pool`. The bound is the pool's reason to exist, so `pool.New` panics when `max` is below 1.

- **A slot is held while a child works, not while it waits.** A child holds one slot during its model calls and tool calls. A child waiting on a sync delegation of its own gives its slot up for the wait and queues for one again before it works again. A child parked at an approval holds none. That hand-off is why fan-out times depth is safe on any `max`, 1 included.
- **Admission is first in, first out**, in the order work queued: `Submit` queues before it returns, a wrapped tool queues when it is called, and a parent taking its slot back queues behind whatever was already waiting.
- **Depth has its own bound.** [`pool.MaxDepth(n)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#MaxDepth) caps how deep a chain of delegations goes: 1 allows children, 2 children of children. The default is [`pool.DefaultMaxDepth`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#DefaultMaxDepth), 8. Since waiting parents hold no slot, depth costs sessions and tokens, not capacity ([`ExampleMaxDepth`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#example-MaxDepth)). In thread 0.5.0 the bound doubled as the depth guard and a too-deep chain read `SUBAGENT_CYCLE`; since thread 0.9.0 depth is `MaxDepth`'s and reads `SUBAGENT_DEPTH`.
- **A child is a session.** It is created in the parent's storage with a header whose `lineage` names the parent session and, for a wrapped tool, the delegating call. A wrapped child also records the wrap's name in its header metadata (`pool_agent`): the name is the resume key after a restart. The child inherits the parent's approval policy through [`thread.InheritApprovals`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#InheritApprovals): request expiry, quorum, keyring, `RequireSigned` and clock.
- **A child's events are its own.** They are not [`weft.Nested`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Nested) events in the parent's stream; read or tail the child session instead.
- **The pool changes nothing in the core.** A wrapped tool is the core's [`weft.Subagent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Subagent) under a tool-level [`weft.WrapTools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WrapTools) middleware, plus session entries and pool-owned goroutines.

A pool is safe for concurrent use; the zero value is not usable. The package's own API, in one place:

| Call | Does |
|---|---|
| [`pool.New(max, opts...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#New) | A pool of `max` slots; options `pool.MaxDepth`, `pool.IDs` |
| [`p.Wrap(name, desc, agent, opts...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.Wrap) | A delegation tool, `(*weft.ToolDef, error)`; `p.MustWrap` panics instead |
| [`p.Submit(ctx, parent, agent, prompt)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.Submit) | Start a child now; returns its `*Receipt` at once |
| [`p.Wait(ctx, parent, receiptID)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.Wait) | Block until the delegation is settled or parked |
| [`p.Decide(ctx, parent, ds...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.Decide) | Record decisions over children's requests and arm the children; does not wait |
| [`p.DecideSigned(ctx, parent, sd)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.DecideSigned) | `Decide` for one signed decision |
| [`p.Forward(ctx, parent, receiptID, msg)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.Forward) | Steer a running child |
| [`p.Cancel(ctx, parent, receiptID)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.Cancel) | End one delegation |
| [`p.Register(sessionID, agent)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.Register) | Attach an agent to a child no wrap names, before `Recover` |
| [`p.Recover(ctx, parent)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.Recover) | After a restart, make the parent's ledger say what is true |
| [`p.Close(ctx)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.Close) | Cancel what runs, drain, take no more work |
| [`pool.Receipts(parent)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Receipts) | The parent's delegations, from its entries |
| [`pool.Children(ctx, parent)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Children), [`pool.Descendants(ctx, parent)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Descendants) | The child sessions, direct or the whole subtree |

## Delegate with a pool

There are two ways in. A wrapped tool lets the parent's model delegate; `Submit` lets your code delegate. Both create the child session, write the acceptance receipt in the parent and queue the child before they return.

### Wait for the child's answer

`p.Wrap(name, description, agent, opts...)` returns a subagent tool whose children the pool runs. Inside a session's run, found through the run's context ([`thread.SessionFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SessionFromContext)), the call is sync by default: it waits, and the result is the child's answer. The tool's input is the subagent schema, `{"prompt": "..."}`.

- `Wrap` fails on a nil agent or an empty name, and with [`pool.ErrDuplicateWrap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#ErrDuplicateWrap) for a name the pool already wraps a different agent under: one name names one agent. Wrapping the same agent again returns another tool for it. `MustWrap` panics on those errors, for wiring where the arguments are the program's own.
- [`pool.ToolOptions(opts...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#ToolOptions) forwards weft tool options to the underlying subagent tool: `Timeout`, `MaxResultBytes`, a snippet. `weft.RequireApproval` gates the act of delegating, as on any tool.
- A wrapped tool called outside any session, from a bare `Generate`, has no parent to receipt into. It falls back to the ordinary subagent path under a slot (`TestWrapOutsideSession`).

The package example is [`ExamplePool_Wrap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#example-Pool.Wrap).

### Delegate in the background

[`pool.Async()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Async) makes the tool's result an acceptance receipt instead of the child's answer. The model reads one line, and the child runs on:

```go title="sessions/pools.go"
p := pool.New(4, childIDs())
refunds := p.MustWrap("refunds", "Start a refund in the background.", refunder, pool.Async())
support := weft.New(wefttest.Script(
	wefttest.ToolCalls(wefttest.Call{Name: "refunds", ID: "call_1", Args: `{"prompt":"Refund order 1234."}`}),
	wefttest.Say("The refund has started."),
), refunds)
s, err := thread.Create(ctx, st, support, ctxWindow, ids("s_async", "a"), at(base))
if err != nil {
	return pool.Receipt{}, err
}
turn, err := s.Send(ctx, weft.User("Refund order 1234."))
if err != nil {
	return pool.Receipt{}, err
}
res, err := turn.Wait()
if err != nil {
	return pool.Receipt{}, err
}
fmt.Fprintln(w, "the model read:", lastToolResult(res.Messages))
fmt.Fprintln(w, "reply:", res.Text())
```

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

```text
the model read: background task accepted; receipt e_a3
reply: The refund has started.
```

The line `background task accepted; receipt <id>` is model-visible text, pinned by `TestWrapAsyncGolden`. The answer reaches the model only when your application delivers it in a later turn.

`Async` needs a parent session. Under a plain `Generate`, with no `thread.Session` on the context, the wrap takes the bare path before it checks `Async`: the call blocks until the child finishes, and the model reads the child's answer instead of the receipt line.

`p.Submit(ctx, parent, agent, prompt)` is the same primitive, called by your code. It returns a [`*pool.Receipt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Receipt) at once, state `accepted`. The child runs on a pool-owned context: the submitting caller's cancellation does not reach it, and only `Cancel` or `Close` end it. Its context still carries the delegating run's values, so a `weft.ParkAllExcept` list and the run metadata bind it as they bind a sync child. `parent` and `agent` must not be nil. Called from inside a pool child's run, `Submit` counts depth and ancestry from there and fails with [`pool.ErrDepth`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#ErrDepth) or [`pool.ErrCycle`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#ErrCycle). Four submits on a pool of two:

```go title="sessions/pools.go"
p := pool.New(2, childIDs())
var receipts []*pool.Receipt
for i := range 4 {
	r, err := p.Submit(ctx, parent, wk.agent(), fmt.Sprintf("task %d", i+1))
	if err != nil {
		return 0, err
	}
	receipts = append(receipts, r) // returned at once, state accepted
}
<-wk.started
<-wk.started // two children are inside their tool; the other two queue
states := map[pool.State]int{}
for _, r := range pool.Receipts(parent) {
	states[r.State]++
}
fmt.Fprintln(w, "running:", states[pool.Running], "accepted:", states[pool.Accepted])

close(wk.release)
for i, r := range receipts {
	final, err := p.Wait(ctx, parent, r.ID)
	if err != nil {
		return 0, err
	}
	fmt.Fprintf(w, "task %d: %s\n", i+1, final.State)
}
if err := p.Close(ctx); err != nil {
	return 0, err
}
```

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

```text
running: 2 accepted: 2
task 1: done
task 2: done
task 3: done
task 4: done
```

Two children hold the slots; the other two wait in the pool's queue, their receipts `accepted`. `p.Wait` blocks until a delegation is at rest: settled, or parked at an approval. A receipt no child of this pool is working returns at once, as it stands. `TestPoolBound` asserts that no more than two were ever at work at once; the package example is [`ExamplePool_Submit`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#example-Pool.Submit).

To watch a child live, tail its session: `r.Child` names it, and a storage with the [`thread.Watcher`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Watcher) capability (jsonl, sqlite; `thread.Memory` has none) yields its entries as they land ([`ExamplePool_Submit_watch`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#example-Pool.Submit-Watch), [Watch a session](https://weftgo.dev/docs/sessions/storage/#watch-a-session)).

### Decide a child's approvals

A child that reaches a `weft.RequireApproval` tool parks, and its request surfaces on the parent's [`s.Pending()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Pending). Decide it through the pool:

```go title="sessions/pools.go"
r := pool.Receipts(s)[0]
rest, err := p.Wait(ctx, s, r.ID) // at rest: settled, or parked at an approval
if err != nil {
	return pool.Receipt{}, err
}
fmt.Fprintln(w, "receipt:", rest.State)
for _, req := range s.Pending() {
	fmt.Fprintln(w, "pending:", req.CallID, req.Tool, "in", req.Child)
}
if err := p.Decide(ctx, s, thread.Approve(s.Pending()[0].CallID)); err != nil {
	return pool.Receipt{}, err // Decide records and arms the child; it does not wait
}
final, err := p.Wait(ctx, s, r.ID)
if err != nil {
	return pool.Receipt{}, err
}
fmt.Fprintf(w, "receipt: %s %q | delegated output tokens: %d\n", final.State, final.Stop, s.Usage().Delegated.OutputTokens)
```

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

```text
receipt: parked
pending: c_1/call_r refund in c_1
receipt: done "Refunded order 1234." | delegated output tokens: 10
```

The request's call id is namespaced, `<child>/<call>`, and `Request.Child` names the session it parks in. `p.Decide` records the decision in the parent first, through the parent's own `Decide` (validation, quorum, audit and expiry live there), then runs the pump: every child whose pending calls now all hold a verdict is queued to resume. It returns once the decisions are recorded and the children queued; follow the child with `p.Wait`. The error joins every failure: the parent's refusal (nothing recorded, nothing pumped), or per child, why it could not be armed. A `RequireSigned` parent refuses `Decide` with `thread.ErrSignatureRequired`; use [`p.DecideSigned`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.DecideSigned) ([Sign approval decisions](https://weftgo.dev/docs/sessions/signed-approvals/)). `p.Decide(ctx, parent)` with no decisions is the pump alone, and always safe to call. The mechanism is in [Nested approvals](#nested-approvals); the package example is [`ExamplePool_Decide`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#example-Pool.Decide).

### Steer a running child

`p.Forward(ctx, parent, receiptID, msg)` sends `msg` to the child's session under the `Steer` policy. It is delivered at the run's next drain point, or deferred to a follow-up turn when the run ends first ([Steer into the running turn](https://weftgo.dev/docs/sessions/busy-and-steering/#steer-into-the-running-turn)). Nothing is ever forwarded implicitly:

```go title="sessions/pools.go"
r, err := p.Submit(ctx, s, converter, "Convert the totals.")
if err != nil {
	return err
}
<-started // the child is mid-run, inside its tool
if _, err := p.Forward(ctx, s, r.ID, weft.User("Use euros, not dollars.")); err != nil {
	return err
}
close(release)
final, err := p.Wait(ctx, s, r.ID)
if err != nil {
	return err
}
fmt.Fprintln(w, "forwarded:", final.State, final.Stop)

_, err = p.Forward(ctx, s, r.ID, weft.User("Too late."))
var se *pool.StateError
fmt.Fprintln(w, "after the end:", errors.Is(err, pool.ErrNotRunning), errors.As(err, &se) && se.State == pool.Done)
```

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

```text
forwarded: done Converted the totals to euros.
after the end: true true
```

A child that is not running refuses with a [`*pool.StateError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#StateError) naming its state: `accepted` (a steer now would run as the session's first turn), `parked` (its fate is the decision) or settled. The returned `*thread.Turn` is the steer's receipt turn ([`ExamplePool_Forward`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#example-Pool.Forward)).

**A child that has just taken its slot can refuse for a moment; retry.** `Forward` needs the run's turn in flight, not only its `running` receipt. Between taking the slot and sending its turn, the child refuses as the state it is leaving: `accepted` before its first turn, `parked` before a resume. The refusal changes nothing, and a retry a moment later steers. Once the send is under way, `Forward` waits for it, bounded by `ctx`. A refusal of this pool's child never reads `running`; only an `Orphan`'s can (`TestForwardRetriedFromTheReceiptSteers`).

### Cancel a delegation

`p.Cancel(ctx, parent, receiptID)` ends one delegation:

```go title="sessions/pools.go"
r, err = p.Submit(ctx, s, holder, "Wait for the warehouse.")
if err != nil {
	return err
}
<-held
if err := p.Cancel(ctx, s, r.ID); err != nil { // cancels the run; Wait follows the settlement
	return err
}
final, err = p.Wait(ctx, s, r.ID)
if err != nil {
	return err
}
fmt.Fprintln(w, "canceled:", final.State, final.Settled())
fmt.Fprintln(w, "cancel again:", errors.Is(p.Cancel(ctx, s, r.ID), pool.ErrNotRunning))
fmt.Fprintln(w, "unknown receipt:", errors.Is(p.Cancel(ctx, s, "e_nope"), pool.ErrUnknownReceipt))
```

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

```text
canceled: canceled true
cancel again: true
unknown receipt: true
```

What it does depends on where the child is:

- **Running:** the run is canceled and the child records a canceled turn.
- **Queued for a slot:** it never starts; the child session records no turn. In both cases the receipt settles `canceled` on the delegation's goroutine. `Cancel` does not wait for that; `Wait` does. A sync delegation's model reads `SUBAGENT_CANCELED`.
- **Parked:** the child's pending requests are denied in the child session, its run is not resumed, the receipt settles `canceled` before `Cancel` returns, and the mirrored requests leave the parent's `Pending`.
- **Unsettled in the ledger with no child of this pool running:** a previous process's. It is recovered first, then canceled if recovery left it parked.
- **Still parking** (its requests mirrored, perhaps its receipt reading `parked`): `Cancel` waits for the park to finish, bounded by `ctx`, then cancels it as a parked child. A running child that reaches its approval boundary before the cancel stops it does not park; it settles `canceled`.

**A child that is itself a parent ends its own sync delegations first.** Each parked or running grandchild is canceled and settles `canceled` in the child's ledger, never resumed. The child waits for them at most 30 s. A grandchild still running past that, such as a handler that ignores its context with no `Timeout`, is settled `canceled` by the pool. Its stop names the bound, and its run is abandoned; `Close`'s drain still counts it. Async children the child submitted are not ended with it.

A settled receipt fails with a `*pool.StateError` ([`pool.ErrNotRunning`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#ErrNotRunning) under `errors.Is`); an id the ledger does not hold fails with [`pool.ErrUnknownReceipt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#ErrUnknownReceipt) ([`ExamplePool_Cancel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#example-Pool.Cancel)).

### Recover after a restart

The ledger is entries; the pool's memory is not. A new process brings a parent's delegations back with `p.Recover(ctx, parent)`, once per parent session it takes over, after the agents are wrapped or registered. Here the first process parks a sync delegation and stops; the second opens the same files:

```go title="sessions/pools.go"
// The second process: a new Storage, a new pool, the same agents
// wrapped under the same names.
st, err := jsonl.Open(sessions)
if err != nil {
	return pool.Receipt{}, err
}
p := pool.New(4)
refunder := weft.New(wefttest.Script(wefttest.Say("Refunded order 1234.")), refundTool())
support := weft.New(wefttest.Script(wefttest.Say("Order 1234 is refunded.")),
	p.MustWrap("refunds", "Run the refund flow.", refunder))
s, err := thread.Open(ctx, st, "s_refunds", support, ctxWindow, ids("", "b"), at(base))
if err != nil {
	return pool.Receipt{}, err
}
if err := p.Recover(ctx, s); err != nil { // once per parent session, after the wraps
	return pool.Receipt{}, err
}
req := s.Pending()[0]
fmt.Fprintln(w, "after Recover:", pool.Receipts(s)[0].State, "| pending", req.CallID)
if err := p.Decide(ctx, s, thread.Approve(req.CallID)); err != nil {
	return pool.Receipt{}, err
}
final, err := p.Wait(ctx, s, pool.Receipts(s)[0].ID)
if err != nil {
	return pool.Receipt{}, err
}
fmt.Fprintln(w, "receipt:", final.State, final.Stop)
if err := p.Close(ctx); err != nil {
	return pool.Receipt{}, err
}
if err := s.Close(ctx); err != nil { // waits for the parent's own resume
	return pool.Receipt{}, err
}
msgs := s.Context()
fmt.Fprintln(w, "parent:", msgs[len(msgs)-1].Text())
```

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

```text
first process: pending 1 | receipt parked
after Recover: parked | pending c_1/call_r
receipt: done Refunded order 1234.
parent: Order 1234 is refunded.
```

For each unsettled receipt no child of this pool is working, `Recover` reads the child session and makes the ledger say what is true:

| The child | Recover |
|---|---|
| is parked at an approval | rebuilds the bridge (reopens the child under its agent), mirrors any request the parent lacks, records `parked`; the child resumes when decided. A child whose resume was under way when the process died is here too: its decisions are on file, so it resumes again, and an approved call whose result was not recorded runs again |
| finished its run | settles the receipt from the child's own ledger, with its usage: `done` with its final text, or `failed`, `capped`, `canceled` with the recorded cause |
| never finished its first run (queued, or mid-run with no approval boundary on file) | settles `failed`, saying so; the run is not started again |
| is gone | settles `failed` |

A sync delegation's call still parked in the parent is resolved with the settlement, and last the pump runs. A child whose agent the pool does not hold is reported with [`pool.ErrNoAgent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#ErrNoAgent) and left for a later call. Wrapped children need nothing more than the same wraps under the same names. A `Submit` child, or a wrap renamed between runs, needs `p.Register(childID, agent)` first ([`ExamplePool_Register`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#example-Pool.Register)). `Recover` on a live session leaves alone the receipts this pool is working ([`ExamplePool_Recover`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#example-Pool.Recover)).

#### Make an approved tool idempotent

A child's first run is never started again, but its resume is. A resume that started and did not finish leaves the boundary resumable, with its decisions in force. The pump at the end of `Recover` resumes it, and an approved call whose result was not recorded runs again. The same holds at any depth: a grandchild resumes through its parent's recovered delegation (`TestNestedRestartMidApprovedCallRunsItAgain`).

Nothing on file tells a call that never started from one cut off half-way. `weft.Replay`'s side-effect classes are the playground's and do not gate a session resume. So a tool that must not run twice has to be idempotent itself. Key it by the call id from [`weft.CallFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CallFromContext), the session id (`weft.session.id`, which thread stamps on every run, read with [`weft.MetadataFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MetadataFromContext)) and a business key for what the call acts on. The call id is the same on every run of one call, so the run a resume repeats finds the first run's entry. The session id keeps conversations apart, but it is the same on every turn of one session. Within a session only the business key reliably tells operations apart, because a later turn may reuse a call id (weft's Gemini adapter, for one, numbers calls `call_0`, `call_1`, … per step when the API sends no id): keyed by the order id, a later turn's refund of the same order under a repeated call id reads as already done. Name the operation itself, such as a refund request id, when one order may be refunded twice:

```go title="sessions/idempotent.go"
// refunds stands in for the payment side's ledger: one row per
// idempotency key. A real one is a table with a unique key, written in
// the same transaction as the refund itself.
type refunds struct {
	mu   sync.Mutex
	done map[string]string // key → the result the first run returned
	runs int               // times the handler ran
	paid int               // refunds actually issued
}

// tool is a refund tool that pays each approved call once. A resume
// that runs the call again, after a crash cut the first run off, reads
// the recorded result instead of paying twice.
func (r *refunds) tool() *weft.ToolDef {
	return weft.Tool("refund", "Refund an order. Requires a human decision.",
		func(ctx context.Context, in struct {
			OrderID string `json:"order_id"`
		}) (string, error) {
			call, _ := weft.CallFromContext(ctx)
			// The call id is the same on every run of this call, so the
			// run a resume repeats finds this entry. The session id keeps
			// conversations apart but is the same on every turn, so within
			// a session only the order id reliably tells operations apart:
			// a later turn may reuse a call id (weft's Gemini adapter
			// numbers call_0, call_1, … per step when the API sends none),
			// and a later refund of the same order under a repeated id
			// reads as done. Key by a refund request id instead when one
			// order may be refunded twice.
			session := weft.MetadataFromContext(ctx)["weft.session.id"]
			key := session + "/" + call.CallID + "/" + in.OrderID
			r.mu.Lock()
			defer r.mu.Unlock()
			r.runs++
			if out, ok := r.done[key]; ok {
				return out, nil
			}
			r.paid++
			out := "Refunded order " + in.OrderID + "."
			r.done[key] = out
			return out, nil
		},
		weft.RequireApproval(),
	)
}
```

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

`TestIdempotentRefund` resumes one parked call twice under one approval: the handler runs twice and pays once. `TestIdempotentRefundPerSession` sends the same call id and order on plain `Generate` runs under two session ids, stamped with `weft.Metadata` as thread stamps `weft.session.id`, and opens no `thread` session: two refunds.

### Delete a parent and its children

Deleting a session deletes none of its children. [`pool.Children`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Children) lists the direct ones, and [`pool.Descendants`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Descendants) the whole subtree, deepest first:

```go title="sessions/pools.go"
children, err := pool.Children(ctx, s)
if err != nil {
	return err
}
all, err := pool.Descendants(ctx, s) // deepest first
if err != nil {
	return err
}
fmt.Fprintln(w, "children:", children, "descendants:", all)
for _, id := range append(all, s.ID()) { // the parent last
	if err := thread.Delete(ctx, st, id); err != nil {
		return err
	}
}
page, err := thread.List(ctx, st, thread.Query{})
if err != nil {
	return err
}
fmt.Fprintln(w, "sessions left:", page.Total)
```

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

```text
children: [c_1] descendants: [c_4 c_1]
sessions left: 0
```

Deleting in the order returned, the parent last, never leaves a child whose parent is already gone. `Children` lists the child of every receipt whose stored header names the parent as its lineage, and leaves out deleted ones. A child still running when its parent is deleted runs to its end and cannot record its settlement (the failure is logged). A `Branch` in the parent moves no child. A `Fork` copies the ledger but not the delegations: the fork's copies of unsettled receipts are settled `canceled`, and `Children` does not list the origin's children for the fork ([`ExampleDescendants`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#example-Descendants)).

### Close the pool

`p.Close(ctx)` stops taking work and drains. Every queued or running child is canceled (a sync child's parent model reads `SUBAGENT_CANCELED`), wrapped calls running outside any session are canceled too, and `Close` waits for all of them to settle their receipts and end. A child parked at an approval under a parent at rest is not canceled: its session is closed, its receipt stays `parked`, and a later pool resumes it. A sync grandchild parked under a child that `Close` cancels is canceled at its boundary, and settles `canceled` in that child's ledger. A canceled child that is itself a parent waits for its own sync delegations under `Cancel`'s 30 s bound. `ctx` bounds the wait; a second `Close` returns nil. After `Close`, `Submit`, `Decide`, `Recover` and a wrapped tool's call fail with [`pool.ErrClosed`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#ErrClosed). `Session.Close` does not wait for pool children, so close pools before sessions ([shutdown](https://weftgo.dev/docs/sessions/operations/#close-and-shutdown); [`ExamplePool_Close`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#example-Pool.Close)).

## Receipts

A delegation's journey is a run of [`thread.PoolReceiptEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#PoolReceiptEntry) entries in the parent (`pool_receipt`, `"v": 4` on the wire: [the format](https://weftgo.dev/docs/sessions/format/#poolreceiptentry)). [`pool.Receipts(parent)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Receipts) reads them back, in acceptance order, each at the state its entries record last. It reads the same after a restart as live: entries are the truth, and the pool holds no receipt state of its own. The first settlement a receipt records is its state for good. A session that never delegated returns nil.

A [`pool.Receipt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Receipt) is the handle and what is known:

| Field | Is |
|---|---|
| `ID` | the acceptance entry's id: the handle `Wait`, `Cancel` and `Forward` take |
| `State` | the state the ledger records last, a [`pool.State`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#State) |
| `Child` | the child session's id |
| `Call` | the delegating tool call, for a wrapped tool; empty for a `Submit` |
| `Stop` | on settlement, the child's answer when `done`; the cause otherwise |

[`r.Settled()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Receipt.Settled) reports whether the receipt reached a final state ([`ExampleReceipts`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#example-Receipts)).

`*pool.StateError` reports a receipt whose child is not in the state a call serves: `Forward` to a queued, parked or settled child, `Cancel` of a settled one. Its fields are `Receipt` (the id the call named), `State`, and `Orphan` (an unsettled receipt no child of this pool runs for, which `Recover` settles). `Error` names the receipt and its state; `Is` matches `pool.ErrNotRunning`.

### Receipt states

`accepted` → `running` ⇄ `parked` → exactly one of `done`, `failed`, `canceled`, `capped`. A delegation canceled or failed before its child ever ran settles straight from `accepted`. The `pool.State` constants are the wire strings of the `thread.PoolAccepted` to `thread.PoolCapped` constants:

| `pool.State` | `thread` constant | Wire | Means |
|---|---|---|---|
| `pool.Accepted` | [`thread.PoolAccepted`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#PoolAccepted) | `accepted` | recorded, and queued for a slot |
| `pool.Running` | [`thread.PoolRunning`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#PoolRunning) | `running` | the slot is acquired and the child's turn started (or the child waits, slotless, on a sync delegation of its own); written before the turn flies |
| `pool.Parked` | [`thread.PoolParked`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#PoolParked) | `parked` | the run ended at an approval boundary; no slot; the next `running` is its resume |
| `pool.Done` | [`thread.PoolDone`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#PoolDone) | `done` | ran to its intended end; `Stop` is its answer, `Usage` its total cost |
| `pool.Failed` | [`thread.PoolFailed`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#PoolFailed) | `failed` | the run failed, or the delegation could not proceed; `Stop` is the cause |
| `pool.Canceled` | [`thread.PoolCanceled`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#PoolCanceled) | `canceled` | `Cancel`, the pool's `Close`, or for a sync child the delegating call's own cancellation or timeout; never the submitting turn's end, which an async child survives |
| `pool.Capped` | [`thread.PoolCapped`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#PoolCapped) | `capped` | died on a budget: `weft.ErrMaxSteps` or `weft.ErrUsageLimit` (the stop text says which) |

[`State.Settled`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#State.Settled) is true for the last four; an unknown state, a newer writer's, is not settled. [`State.String`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#State.String) returns the wire string. A receipt that stays `accepted` or `running` across a restart needs `Recover`.

## Usage

A pool child is a session, not a tool-call child of the core's `weft.Subagent`, so the core's rule "a child's usage is yours" does not reach it. Its usage is on neither the parent run's `RunResult.Usage` nor `StepRecord.SubagentUsage`. It is on the settling receipt, and [`s.Usage()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Usage) sums the settled receipts into [`thread.Usage.Delegated`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Usage), the ledger's third bucket beside `Turns` and `Summaries` (AGENTS rule 13's one exception; `TestDelegatedUsage`).

A settlement's `Usage` is the child session's turns and summaries: every run it made for the delegation, the ones before a park included. That is why the async refund above reports 10 output tokens: the child's model ran once to park and once to finish. It does not include the child's own `Delegated`, and a session's `Delegated` sums only its direct receipts, so a grandchild's tokens are not in the root's `Delegated`. For a nested tree, sum `Usage().Delegated` over the sessions [`pool.Descendants`](#delete-a-parent-and-its-children) returns as well.

A budget such as [`weft.UsageLimit`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#UsageLimit) on the parent run does not see delegated work; a budget that must cover it reads `Delegated`, across the tree.

## Nested approvals

A child parks in its own session; the pool mirrors its requests onto the parent so the parent's `Pending` shows them with their lineage:

- **The mirror.** Each mirrored request is an `approval_request` entry in the parent with a namespaced call id (`<child>/<call>`), `child` naming the child session and `wrapper` the parent-side delegating call (empty for an async delegation). `Pending()` lists the mirrors and hides the parked wrapper call.
- **The wrapper is never decidable.** A decision naming the delegating call fails with [`thread.ErrDelegated`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrDelegated): approving it would run the delegation a second time, in a second child session. The parent's decision chain keeps the same rule: no grant and no live `Approver` is consulted for a delegating call when it parks (`TestChainNeverDecidesWrapper`).
- **The replay.** When a child resumes, the parent's decisions for its pending calls are replayed into the child session, keeping the decider's identity, with `via` `parent`. Only calls pending in the child now are replayed, so an earlier park's decisions never are.
- **A re-park supersedes.** A grandchild that parks again while the child waits on it mirrors its new request up the chain. The new request keeps the namespaced call id and names the new occurrence by its run. It supersedes the earlier one, and a decision recorded for the earlier one does not decide it.
- **The resolution.** When the child ends, a sync delegation's parked call resolves with the child's outcome (`via` `child`): a resolve with the answer for a `done` child, a `resolve_error` otherwise. That resumes the parent: the parked turn's `Next` is the continuation once `Wait` reports the receipt settled. A child that parks again mirrors its new requests and waits for the next `Decide`.
- **Decisions by other paths reach the children.** The pool watches every parent it delegates from. A `Session.Decide` or `DecideSigned` used directly, an interrupting `Send`'s denial (the child resumes with `DENIED: interrupted by a newer message`), or a request lapsing past its expiry runs the pump on a pool goroutine. After a restart nothing is watched until the pool next touches the parent: `Recover`, `Decide`, `DecideSigned` or a new delegation.

[`thread.MirroredRequest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#MirroredRequest) is one mirror as the parent holds it. `Request` is the mirror: its `CallID` in the namespaced form, `Child`, and `RunID` the child run that parked. `Wrapper` is the delegating call, empty for async. Then `Decisions` (the decisions in force for this occurrence, in record order) and `Decided` (whether they reach an effective verdict under the parent's `Quorum`, the moment the pool replays them). `thread.InheritApprovals(parent)` is the session option that gives a child the parent's expiry, quorum, keyring, `RequireSigned` rule and clock; `Submit` and `Wrap` apply it.

## Limits and errors

| Name | Kind | Meaning |
|---|---|---|
| [`pool.Option`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Option) | type | configures a pool at `New` |
| `pool.MaxDepth(n)` | option | delegation depth; `New` panics below 1 |
| `pool.DefaultMaxDepth` | const, 8 | the depth when `MaxDepth` is not given |
| `pool.IDs(f)` | option | mints child session ids and every entry id inside each child; the parent's ids stay its own. Called from many goroutines under session locks: safe for concurrent use, quick, never repeating |
| [`pool.WrapOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#WrapOption) | type | configures one wrapped tool: `pool.Async`, `pool.ToolOptions` |
| `pool.ErrClosed` | error | work handed to a closed pool |
| `pool.ErrCycle` | error | `Submit` to an agent already running above the delegating run; a wrapped tool reports `SUBAGENT_CYCLE` |
| `pool.ErrDepth` | error | `Submit` past `MaxDepth`; a wrapped tool reports `SUBAGENT_DEPTH` |
| `pool.ErrDuplicateWrap` | error | `Wrap` of a different agent under a name already in use |
| `pool.ErrNoAgent` | error | `Decide`, `Recover`, `Cancel` need to reopen a child and the pool holds no agent for it: wrap it again under its name, or `Register` it |
| `pool.ErrNotRunning` | error | what every `*StateError` matches |
| `pool.ErrUnknownReceipt` | error | `Cancel`, `Forward`, `Wait` with an id the parent's ledger does not hold |
| [`pool.CodeSubagentDepth`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#CodeSubagentDepth) | const | `SUBAGENT_DEPTH`, refused before any child is created; the core has no depth limit |
| [`pool.CodeSubagentCanceled`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#CodeSubagentCanceled) | const | `SUBAGENT_CANCELED`, a sync child the pool canceled; the parent's own cancellation ends the parent's run instead |

### Result codes

What a delegating model reads is a contract (AGENTS rule 5), every string pinned by a test. Besides the child's answer and the async receipt line:

| Result | When |
|---|---|
| `SUBAGENT_CYCLE: agent "<name>" is already running in this call chain` | the agent is already running above the call; only for a real cycle |
| `SUBAGENT_DEPTH: delegation depth <n> exceeds the pool's limit <m>` | the delegation would exceed `MaxDepth` (it used to read `SUBAGENT_CYCLE`) |
| `SUBAGENT_FAILED: agent "<name>" failed at step <n>: <cause>` | the child's run failed: the core's text, byte for byte |
| `SUBAGENT_FAILED: agent "<name>" failed: <cause>` | a failure outside a child run, or one `Recover` read from the ledger |
| `SUBAGENT_FAILED: agent "<name>" parked at an approval the pool could not surface: <cause>` | the mirror could not be written on the parent |
| `SUBAGENT_CANCELED: agent "<name>" was canceled before it finished` | `Cancel` or `Close` ended a sync child |
| `DENIED: the delegation was canceled while awaiting approval` | what a canceled, parked child's model reads if its session is ever resumed |
| `thread/pool: pool is closed` | a wrapped tool called after the pool's `Close`: the model reads `pool.ErrClosed`'s text as the result |

A delegating call is never re-executed by a decision: its result is the child's answer, once. Arguments that do not decode as `{"prompt": "..."}` read `thread/pool: decode "<name>" arguments: ` followed by `encoding/json`'s description, and leave no receipt.

## Session plumbing

The pool lives in another package, so `thread` exports what it needs to write its ledger and bridge approvals. An application delegates with `Wrap` and `Submit`, decides with `Decide`, `DecideSigned` and `p.Decide`, and never calls these. Go has no package-private export; this is the boundary (`thread/poolplumbing.go:11-25`), and it is still exported before the freeze (a known limit).

| Method or function | What the pool uses it for |
|---|---|
| [`Session.AppendPoolReceipt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.AppendPoolReceipt) | one receipt entry per state; returns it stored, its id the receipt handle. Exactly one settlement per receipt is the caller's contract, since `Usage` sums them |
| [`Session.AppendApprovalRequests`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.AppendApprovalRequests) | mirrored requests, one atomic batch; every request must name its `Child` |
| [`Session.MirroredRequests`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.MirroredRequests) | the mirrors in force, decided or not; expiry resolved first |
| [`Session.ReplayDecisions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.ReplayDecisions) | in a child, record the parent's decisions (`via` `parent`) and resume; idempotent |
| [`Session.ResolveDelegation`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.ResolveDelegation) | resolve a delegating call with the child's outcome (`who` `thread/pool`, `via` `child`) |
| [`Session.DenyMirrored`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.DenyMirrored) | deny a child's still-pending mirrors when its delegation ends |
| [`Session.CancelDelegated`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.CancelDelegated) | in a parked child, deny every pending request and resume nothing |
| [`Session.WatchMirrors`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.WatchMirrors) | be told when the parent records a decision for a mirror |
| [`Session.MirrorWatchers`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.MirrorWatchers) | the owners holding a `WatchMirrors` notification on the session: the pools delegating from it, or handed it by `Decide`, `DecideSigned` or `Recover`. With several pools on one parent, each pool's pump walks every receipt of the parent's ledger and asks it to tell another pool's child from one it cannot resume |
| [`Session.Storage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Storage), [`Session.Lineage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Lineage), [`thread.SessionFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#SessionFromContext) | where to create children; a session's parent; the session a run's context carries |
| [`thread.WithLineage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#WithLineage), [`thread.WithMeta`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#WithMeta), `thread.InheritApprovals` | the child's header options and inherited policy |

`thread.Request.Child` names the session a mirrored request parks in.

## Complete example

`sessions/pools.go` wraps, bounds, delegates in the background, steers, cancels, recovers and cascades:

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

import (
	"context"
	"errors"
	"fmt"
	"io"
	"path/filepath"
	"sync"
	"sync/atomic"

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

// demoPools is the page "Run bounded child sessions with a pool".
func demoPools(ctx context.Context, w io.Writer, dir string) error {
	fmt.Fprintln(w, "== wrap")
	if _, err := poolWrap(ctx, w); err != nil {
		return err
	}
	fmt.Fprintln(w, "== bound")
	if _, err := poolBound(ctx, w); err != nil {
		return err
	}
	fmt.Fprintln(w, "== async")
	if _, err := poolAsync(ctx, w); err != nil {
		return err
	}
	fmt.Fprintln(w, "== forward and cancel")
	if err := poolForwardCancel(ctx, w); err != nil {
		return err
	}
	fmt.Fprintln(w, "== recover")
	if _, err := poolRecover(ctx, w, dir); err != nil {
		return err
	}
	fmt.Fprintln(w, "== cascade")
	return poolCascade(ctx, w)
}

// childIDs mints the ids of the child sessions a pool creates, and
// the entry ids inside them: c_1, c_2, … It is safe for concurrent
// use and never repeats, as pool.IDs requires. An application leaves
// pool.IDs out and gets time-sortable random ids.
func childIDs() pool.Option {
	var n atomic.Int64
	return pool.IDs(func() string { return fmt.Sprintf("c_%d", n.Add(1)) })
}

// poolWrap: a sync delegation. The wrapped tool's child runs as a
// session of its own; the call waits for its answer. It returns the
// parent session's ledger for the test.
func poolWrap(ctx context.Context, w io.Writer) (thread.Usage, error) {
	st := thread.Memory()
	p := pool.New(4, childIDs()) // at most 4 child runs at work at once
	researcher := weft.New(wefttest.Script(wefttest.Say("Order 1234 left the Leeds depot on Monday.")))
	research := p.MustWrap("research", "Research an order in depth.", researcher)

	support := weft.New(wefttest.Script(
		wefttest.ToolCalls(wefttest.Call{Name: "research", ID: "call_1", Args: `{"prompt":"Trace order 1234."}`}),
		wefttest.Say("Order 1234 left the depot on Monday."),
	), research)
	s, err := thread.Create(ctx, st, support, ctxWindow, ids("s_support", "a"), at(base))
	if err != nil {
		return thread.Usage{}, err
	}
	turn, err := s.Send(ctx, weft.User("Where is order 1234?"))
	if err != nil {
		return thread.Usage{}, err
	}
	res, err := turn.Wait()
	if err != nil {
		return thread.Usage{}, err
	}
	fmt.Fprintln(w, "reply:", res.Text())
	for _, r := range pool.Receipts(s) {
		fmt.Fprintf(w, "receipt %s: %s child %s call %s stop %q\n", r.ID, r.State, r.Child, r.Call, r.Stop)
	}
	u := s.Usage()
	fmt.Fprintln(w, "output tokens: run", res.Usage.OutputTokens, "| turns", u.Turns.OutputTokens, "| delegated", u.Delegated.OutputTokens)
	if err := s.Close(ctx); err != nil {
		return thread.Usage{}, err
	}
	return u, p.Close(ctx)
}

// worker is a child agent whose one tool call blocks until release is
// closed, recording how many such calls are in flight at once.
type worker struct {
	started chan struct{}
	release chan struct{}
	mu      sync.Mutex
	active  int
	peak    int
	tool    *weft.ToolDef
}

func newWorker() *worker {
	wk := &worker{started: make(chan struct{}, 16), release: make(chan struct{})}
	wk.tool = weft.Tool("work", "Do one slow task.", func(ctx context.Context, _ struct{}) (string, error) {
		wk.mu.Lock()
		wk.active++
		wk.peak = max(wk.peak, wk.active)
		wk.mu.Unlock()
		defer func() { wk.mu.Lock(); wk.active--; wk.mu.Unlock() }()
		wk.started <- struct{}{}
		select {
		case <-wk.release:
			return "finished", nil
		case <-ctx.Done():
			return "", ctx.Err()
		}
	})
	return wk
}

// agent returns a fresh child agent: each child gets its own script.
func (wk *worker) agent() *weft.Agent {
	return weft.New(wefttest.Script(
		wefttest.ToolCalls(wefttest.Call{Name: "work", ID: "call_w"}),
		wefttest.Say("done"),
	), wk.tool)
}

// poolBound: four children on a pool of two. Two work, two wait in
// the pool's queue with an accepted receipt. It returns the peak
// number of children at work at once.
func poolBound(ctx context.Context, w io.Writer) (int, error) {
	parent, err := thread.Create(ctx, thread.Memory(), weft.New(wefttest.Script()), ctxWindow, ids("s_batch", "a"), at(base))
	if err != nil {
		return 0, err
	}
	wk := newWorker()
	p := pool.New(2, childIDs())
	var receipts []*pool.Receipt
	for i := range 4 {
		r, err := p.Submit(ctx, parent, wk.agent(), fmt.Sprintf("task %d", i+1))
		if err != nil {
			return 0, err
		}
		receipts = append(receipts, r) // returned at once, state accepted
	}
	<-wk.started
	<-wk.started // two children are inside their tool; the other two queue
	states := map[pool.State]int{}
	for _, r := range pool.Receipts(parent) {
		states[r.State]++
	}
	fmt.Fprintln(w, "running:", states[pool.Running], "accepted:", states[pool.Accepted])

	close(wk.release)
	for i, r := range receipts {
		final, err := p.Wait(ctx, parent, r.ID)
		if err != nil {
			return 0, err
		}
		fmt.Fprintf(w, "task %d: %s\n", i+1, final.State)
	}
	if err := p.Close(ctx); err != nil {
		return 0, err
	}
	fmt.Fprintln(w, "at work at once, at most:", wk.peak)
	return wk.peak, parent.Close(ctx)
}

// poolAsync: an async wrapped tool. The model reads a receipt line;
// the child parks at an approval, the application decides it through
// the pool and waits for the settlement. It returns the final receipt.
func poolAsync(ctx context.Context, w io.Writer) (pool.Receipt, error) {
	st := thread.Memory()
	refunder := weft.New(wefttest.Script(
		refundCall("call_r", "1234"),
		wefttest.Say("Refunded order 1234."),
	), refundTool())
	p := pool.New(4, childIDs())
	refunds := p.MustWrap("refunds", "Start a refund in the background.", refunder, pool.Async())
	support := weft.New(wefttest.Script(
		wefttest.ToolCalls(wefttest.Call{Name: "refunds", ID: "call_1", Args: `{"prompt":"Refund order 1234."}`}),
		wefttest.Say("The refund has started."),
	), refunds)
	s, err := thread.Create(ctx, st, support, ctxWindow, ids("s_async", "a"), at(base))
	if err != nil {
		return pool.Receipt{}, err
	}
	turn, err := s.Send(ctx, weft.User("Refund order 1234."))
	if err != nil {
		return pool.Receipt{}, err
	}
	res, err := turn.Wait()
	if err != nil {
		return pool.Receipt{}, err
	}
	fmt.Fprintln(w, "the model read:", lastToolResult(res.Messages))
	fmt.Fprintln(w, "reply:", res.Text())

	r := pool.Receipts(s)[0]
	rest, err := p.Wait(ctx, s, r.ID) // at rest: settled, or parked at an approval
	if err != nil {
		return pool.Receipt{}, err
	}
	fmt.Fprintln(w, "receipt:", rest.State)
	for _, req := range s.Pending() {
		fmt.Fprintln(w, "pending:", req.CallID, req.Tool, "in", req.Child)
	}
	if err := p.Decide(ctx, s, thread.Approve(s.Pending()[0].CallID)); err != nil {
		return pool.Receipt{}, err // Decide records and arms the child; it does not wait
	}
	final, err := p.Wait(ctx, s, r.ID)
	if err != nil {
		return pool.Receipt{}, err
	}
	fmt.Fprintf(w, "receipt: %s %q | delegated output tokens: %d\n", final.State, final.Stop, s.Usage().Delegated.OutputTokens)
	if err := s.Close(ctx); err != nil {
		return pool.Receipt{}, err
	}
	return final, p.Close(ctx)
}

// lastToolResult returns the content of the last tool result in msgs.
func lastToolResult(msgs []weft.Message) string {
	out := ""
	for _, m := range msgs {
		for _, part := range m.Content {
			if r, ok := part.(weft.ToolResultPart); ok {
				out = r.Content
			}
		}
	}
	return out
}

// poolForwardCancel: steer a running child, then cancel another.
func poolForwardCancel(ctx context.Context, w io.Writer) error {
	s, err := thread.Create(ctx, thread.Memory(), weft.New(wefttest.Script()), ctxWindow, ids("s_steer", "a"), at(base))
	if err != nil {
		return err
	}
	p := pool.New(2, childIDs())
	convert, started, release := slowTool("convert")
	converter := weft.New(wefttest.Script(
		wefttest.ToolCalls(wefttest.Call{Name: "convert", ID: "call_c"}),
		wefttest.Say("Converted the totals to euros."),
	), convert)

	r, err := p.Submit(ctx, s, converter, "Convert the totals.")
	if err != nil {
		return err
	}
	<-started // the child is mid-run, inside its tool
	if _, err := p.Forward(ctx, s, r.ID, weft.User("Use euros, not dollars.")); err != nil {
		return err
	}
	close(release)
	final, err := p.Wait(ctx, s, r.ID)
	if err != nil {
		return err
	}
	fmt.Fprintln(w, "forwarded:", final.State, final.Stop)

	_, err = p.Forward(ctx, s, r.ID, weft.User("Too late."))
	var se *pool.StateError
	fmt.Fprintln(w, "after the end:", errors.Is(err, pool.ErrNotRunning), errors.As(err, &se) && se.State == pool.Done)

	hold, held, _ := slowTool("hold")
	holder := weft.New(wefttest.Script(wefttest.ToolCalls(wefttest.Call{Name: "hold", ID: "call_h"})), hold)
	r, err = p.Submit(ctx, s, holder, "Wait for the warehouse.")
	if err != nil {
		return err
	}
	<-held
	if err := p.Cancel(ctx, s, r.ID); err != nil { // cancels the run; Wait follows the settlement
		return err
	}
	final, err = p.Wait(ctx, s, r.ID)
	if err != nil {
		return err
	}
	fmt.Fprintln(w, "canceled:", final.State, final.Settled())
	fmt.Fprintln(w, "cancel again:", errors.Is(p.Cancel(ctx, s, r.ID), pool.ErrNotRunning))
	fmt.Fprintln(w, "unknown receipt:", errors.Is(p.Cancel(ctx, s, "e_nope"), pool.ErrUnknownReceipt))
	if err := p.Close(ctx); err != nil {
		return err
	}
	return s.Close(ctx)
}

// poolRecover: a sync delegation parks at an approval, the process
// stops, and a second process recovers it from the JSONL files.
// It returns the final receipt.
func poolRecover(ctx context.Context, w io.Writer, dir string) (pool.Receipt, error) {
	sessions := filepath.Join(dir, "pool-sessions")
	// The first process: the child parks, then pool and session close.
	{
		st, err := jsonl.Open(sessions)
		if err != nil {
			return pool.Receipt{}, err
		}
		p := pool.New(4, childIDs())
		refunder := weft.New(wefttest.Script(refundCall("call_r", "1234")), refundTool())
		support := weft.New(wefttest.Script(
			wefttest.ToolCalls(wefttest.Call{Name: "refunds", ID: "call_1", Args: `{"prompt":"Refund order 1234."}`}),
		), p.MustWrap("refunds", "Run the refund flow.", refunder))
		s, err := thread.Create(ctx, st, support, ctxWindow, ids("s_refunds", "a"), at(base))
		if err != nil {
			return pool.Receipt{}, err
		}
		turn, err := s.Send(ctx, weft.User("Refund order 1234."))
		if err != nil {
			return pool.Receipt{}, err
		}
		res, err := turn.Wait()
		if err != nil {
			return pool.Receipt{}, err
		}
		fmt.Fprintln(w, "first process: pending", len(res.Pending), "| receipt", pool.Receipts(s)[0].State)
		if err := p.Close(ctx); err != nil { // a parked child stays parked
			return pool.Receipt{}, err
		}
		if err := s.Close(ctx); err != nil {
			return pool.Receipt{}, err
		}
	}

	// The second process: a new Storage, a new pool, the same agents
	// wrapped under the same names.
	st, err := jsonl.Open(sessions)
	if err != nil {
		return pool.Receipt{}, err
	}
	p := pool.New(4)
	refunder := weft.New(wefttest.Script(wefttest.Say("Refunded order 1234.")), refundTool())
	support := weft.New(wefttest.Script(wefttest.Say("Order 1234 is refunded.")),
		p.MustWrap("refunds", "Run the refund flow.", refunder))
	s, err := thread.Open(ctx, st, "s_refunds", support, ctxWindow, ids("", "b"), at(base))
	if err != nil {
		return pool.Receipt{}, err
	}
	if err := p.Recover(ctx, s); err != nil { // once per parent session, after the wraps
		return pool.Receipt{}, err
	}
	req := s.Pending()[0]
	fmt.Fprintln(w, "after Recover:", pool.Receipts(s)[0].State, "| pending", req.CallID)
	if err := p.Decide(ctx, s, thread.Approve(req.CallID)); err != nil {
		return pool.Receipt{}, err
	}
	final, err := p.Wait(ctx, s, pool.Receipts(s)[0].ID)
	if err != nil {
		return pool.Receipt{}, err
	}
	fmt.Fprintln(w, "receipt:", final.State, final.Stop)
	if err := p.Close(ctx); err != nil {
		return pool.Receipt{}, err
	}
	if err := s.Close(ctx); err != nil { // waits for the parent's own resume
		return pool.Receipt{}, err
	}
	msgs := s.Context()
	fmt.Fprintln(w, "parent:", msgs[len(msgs)-1].Text())
	return final, nil
}

// poolCascade: deleting a parent deletes no child; Descendants lists
// the subtree deepest first, the order to delete in.
func poolCascade(ctx context.Context, w io.Writer) error {
	st := thread.Memory()
	p := pool.New(2, childIDs())
	lookup := weft.New(wefttest.Script(wefttest.Say("Order 1234: Leeds depot.")))
	research := weft.New(wefttest.Script(
		wefttest.ToolCalls(wefttest.Call{Name: "lookup", ID: "call_l", Args: `{"prompt":"Find order 1234."}`}),
		wefttest.Say("It is at the Leeds depot."),
	), p.MustWrap("lookup", "Look an order up.", lookup))
	support := weft.New(wefttest.Script(
		wefttest.ToolCalls(wefttest.Call{Name: "research", ID: "call_r", Args: `{"prompt":"Where is order 1234?"}`}),
		wefttest.Say("Order 1234 is at the Leeds depot."),
	), p.MustWrap("research", "Research an order.", research))
	s, err := thread.Create(ctx, st, support, ctxWindow, ids("s_tree", "a"), at(base))
	if err != nil {
		return err
	}
	turn, err := s.Send(ctx, weft.User("Where is order 1234?"))
	if err != nil {
		return err
	}
	if _, err := turn.Wait(); err != nil {
		return err
	}
	if err := p.Close(ctx); err != nil {
		return err
	}
	if err := s.Close(ctx); err != nil {
		return err
	}
	children, err := pool.Children(ctx, s)
	if err != nil {
		return err
	}
	all, err := pool.Descendants(ctx, s) // deepest first
	if err != nil {
		return err
	}
	fmt.Fprintln(w, "children:", children, "descendants:", all)
	for _, id := range append(all, s.ID()) { // the parent last
		if err := thread.Delete(ctx, st, id); err != nil {
			return err
		}
	}
	page, err := thread.List(ctx, st, thread.Query{})
	if err != nil {
		return err
	}
	fmt.Fprintln(w, "sessions left:", page.Total)
	return nil
}
```

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

```text
== wrap
reply: Order 1234 left the depot on Monday.
receipt e_a3: done child c_1 call call_1 stop "Order 1234 left the Leeds depot on Monday."
output tokens: run 10 | turns 10 | delegated 5
== bound
running: 2 accepted: 2
task 1: done
task 2: done
task 3: done
task 4: done
at work at once, at most: 2
== async
the model read: background task accepted; receipt e_a3
reply: The refund has started.
receipt: parked
pending: c_1/call_r refund in c_1
receipt: done "Refunded order 1234." | delegated output tokens: 10
== forward and cancel
forwarded: done Converted the totals to euros.
after the end: true true
canceled: canceled true
cancel again: true
unknown receipt: true
== recover
first process: pending 1 | receipt parked
after Recover: parked | pending c_1/call_r
receipt: done Refunded order 1234.
parent: Order 1234 is refunded.
== cascade
children: [c_1] descendants: [c_4 c_1]
sessions left: 0
```

Standard error carries 12 lines of `WARN thread: no context window known for this session`, one per child `Session` value that ran a turn: the pool creates each child without a `thread.ContextWindow` ([gotchas](#best-practices--gotchas)).

## Best practices & gotchas

- **Let one pool own a storage's delegations.** `Recover` treats an unsettled receipt no child of this pool is running as left by a dead process; with two live pools over the same sessions, a `Recover` or `Cancel` through one settles the other's running work `failed`. (Source: `docs/thread-operations.md` §10; `thread/pool/pool.go:176` Pool godoc)
- **Keep wrap names stable.** The name is the resume key a restarted process finds the agent by. Renamed a wrap or used `Submit`? `p.Register(childID, agent)` before `Recover`. (Source: `thread/pool/wrap.go:135` Wrap godoc; `thread/pool/bridge.go:941`)
- **Wrap and register before `Recover`, and call it once per parent the process takes over.** A child whose agent the pool lacks is left for later with `ErrNoAgent`. (Source: `thread/pool/recover.go:58` Recover godoc)
- **`Recover` never re-runs a child's first run.** A child that died mid-run with no approval boundary on file settles `failed`. A finished child's answer is read back as its last assistant text, so a structured `Output` answer is not recovered as such. The cycle guard above a rebuilt child restarts at that child's own agent (the depth limit still holds). (Source: `CHANGELOG.md:4101`; `docs/thread-operations.md` §10)
- **Make an approved tool idempotent.** A child whose resume a crash cut off resumes again after `Recover`, and an approved call whose result was not recorded runs again, at any depth. Key the side effect by `weft.CallFromContext`'s call id, the session id (`weft.session.id` in [`weft.MetadataFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MetadataFromContext)) and a business key for what the call acts on, such as the order id. The call id is the same on every run of one call, so the run a resume repeats finds the first run's entry. The session id keeps conversations apart, but it is the same on every turn of one session. Within a session only the business key reliably tells operations apart, because a later turn may reuse a call id (weft's Gemini adapter, for one, numbers calls `call_0`, `call_1`, … per step when the API sends no id): keyed by the order id, a later turn's refund of the same order under a repeated call id reads as already done. Name the operation itself, such as a refund request id, when one order may be refunded twice. (Source: `thread/pool/recover.go:13-36` Recover godoc; `thread/pool/twolevel_test.go:632` TestNestedRestartMidApprovedCallRunsItAgain)
- **Budgets on the parent run do not cover delegated work.** Read `s.Usage().Delegated`, summed over `pool.Descendants` for a nested tree. (Source: AGENTS rule 13; `thread/pool/pool.go:34-43`, 1089-1090; `thread/session.go:1535-1539`)
- **Pool children get no context window.** The pool creates children with lineage, inherited approvals, metadata and ids only, so each child `Session` value logs the no-window `WARN` at its first turn and never compacts on its own. (Source: `thread/pool/pool.go:886-897`; `thread/compaction.go:1306-1319`)
- **Close pools before sessions.** `Session.Close` does not wait for pool children; a parked child stays parked across `Close`. (Source: `docs/thread-operations.md` §5; `thread/pool/pool.go:629` Close godoc)
- **Cascade deletes yourself.** Delete `Descendants` in the order returned, then the parent. (Source: `thread/pool/pool.go:763`; `ExampleDescendants`)
- **Default-deny reaches every child.** A parent turn sent with `thread.RunOptions(weft.ParkAllExcept(...))` binds its children, sync and async, on every turn they run; name a wrap's tool in the list for the delegation itself to run. (Source: `docs/thread-operations.md` §10; `CHANGELOG.md:3247`)
- **Run an `Async` wrap inside a session turn.** Called from a plain `Generate`, the tool ignores `pool.Async()`: it waits for the child and returns its answer, so the run is as slow as the child and nothing is receipted. Send the turn through `s.Send` instead. (Source: `thread/pool/wrap.go:156-160`, 178-184)
- **Do not decide the delegating call.** Decide the child's mirrored requests; the delegating call completes with the child's answer, and deciding it fails with `thread.ErrDelegated`. (Source: `thread/approval.go:73-83`; `TestWrapperNotDecidable`)

## See also

- [Delegate to a subagent](https://weftgo.dev/docs/guides/subagents/): the core's `weft.Subagent`, which the pool builds on
- [Approvals in sessions](https://weftgo.dev/docs/sessions/approvals/)
- [Operate sessions in production](https://weftgo.dev/docs/sessions/operations/#pool-operations)
- [The session log format](https://weftgo.dev/docs/sessions/format/#poolreceiptentry)
- [Package thread/pool on pkg.go.dev](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool)

Symbols used: [`pool.New`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#New) · [`pool.Pool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool) · [`Pool.Wrap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.Wrap) · [`Pool.MustWrap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.MustWrap) · [`Pool.Submit`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.Submit) · [`Pool.Wait`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.Wait) · [`Pool.Decide`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.Decide) · [`Pool.DecideSigned`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.DecideSigned) · [`Pool.Forward`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.Forward) · [`Pool.Cancel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.Cancel) · [`Pool.Register`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.Register) · [`Pool.Recover`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.Recover) · [`Pool.Close`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Pool.Close) · [`pool.Receipts`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Receipts) · [`pool.Receipt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Receipt) · [`pool.State`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#State) · [`pool.StateError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#StateError) · [`pool.Children`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Children) · [`pool.Descendants`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Descendants) · [`pool.Async`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#Async) · [`pool.ToolOptions`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#ToolOptions) · [`pool.MaxDepth`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#MaxDepth) · [`pool.IDs`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/pool#IDs) · [`thread.PoolReceiptEntry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#PoolReceiptEntry) · [`thread.Usage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Usage) · [`thread.MirroredRequest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#MirroredRequest) · [`thread.InheritApprovals`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#InheritApprovals) · [`thread.ErrDelegated`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#ErrDelegated) · [`Session.Pending`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Pending) · [`Session.Usage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Usage) · [`thread.Watcher`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Watcher) · [`thread.Approve`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Approve) · [`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.Delete`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Delete) · [`thread.List`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#List) · [`jsonl.Open`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread/jsonl#Open) · [`weft.Subagent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Subagent) · [`weft.WrapTools`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WrapTools) · [`weft.Nested`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Nested) · [`weft.UsageLimit`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#UsageLimit) · [`weft.RequireApproval`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RequireApproval) · [`weft.ParkAllExcept`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ParkAllExcept) · [`weft.CallFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CallFromContext) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script)
