Keep long sessions inside the context window (compaction)
Compaction keeps a long session inside the model’s context window: the older part of the conversation is summarized behind a fixed marker, the recent part stays raw, and the summarized entries stay in the file. thread.ContextWindow(n) arms the automatic trigger; s.Compact compacts by hand; s.Uncompact undoes it.
sessions/compaction.go gives the session a 1,000-token window and a scripted model whose second reply reports 900 input tokens:
agent := weft.New(wefttest.Script( wefttest.Say("Order 1234 shipped on Tuesday.").WithUsage(weft.Usage{InputTokens: 300}), wefttest.Say("Order 5678 is still processing.").WithUsage(weft.Usage{InputTokens: 900}), wefttest.Say("Goal: track orders 1234 and 5678."), // the summary, made by the same model))s, err := thread.Create(ctx, thread.Memory(), agent, ids("s_window", "a"), thread.ContextWindow(1_000), // arms the trigger: fire past 1,000 − Reserve thread.Reserve(200), // default 16,384 thread.KeepRecent(40)) // default 20,000: estimated tokens kept rawif err != nil { return err}for _, q := range []string{"Where is order 1234?", "And order 5678?"} { if err := send(ctx, s, q); err != nil { // send waits for WaitIdle: the trigger runs after the turn return err }}for _, e := range s.Entries() { if c, ok := e.(thread.CompactionEntry); ok { fmt.Fprintln(w, "compaction:", c.Reason, "first kept:", c.FirstKept, "tokens before:", c.TokensBefore) }}for _, m := range s.Context() { fmt.Fprintf(w, "%s: %q\n", m.Role, m.Text())}fmt.Fprintln(w, "entries in the file:", len(s.Entries()))compaction: threshold first kept: e_a4 tokens before: 81user: "<weft-summary>\nGoal: track orders 1234 and 5678.\n</weft-summary>"user: "And order 5678?"assistant: "Order 5678 is still processing."entries in the file: 7The second turn crossed window − Reserve (800), so the session compacted after it. The model now sees the summary and the last turn; the file still holds both turns’ six entries plus the compaction entry. The small Reserve and KeepRecent only make the demo fit; the defaults are 16,384 and 20,000 tokens.
How compaction works
Section titled “How compaction works”A compaction is a thread.CompactionEntry appended at the leaf: the summary text, the id of the first entry kept raw, the estimated tokens before, the reason, the summarizer’s usage and model, the files the range read, the pinned ids and a hash of the summarized range. Nothing is deleted. A later compaction summarizes from the previous kept boundary and is fed the previous summary, so the chain is iterative.
The trigger. It runs on the session’s runner before a turn starts (after the prompt is on the path) and after each turn ends. It fires when the last turn’s measured input plus an estimate of the messages added since crosses window − Reserve. The measured input is the provider-reported input of the turn’s final model step plus an estimate of that step’s own messages, the tail the report cannot cover, recorded on the turn entry. The reported number is the signal; only what no report covers is estimated, never the whole context. When it fires, it checks the rate limits, tries the trimmer if one is set, and summarizes.
The trigger stands down when no step was ever measured, when a Branch or Uncompact moved the line since the measurement, or when a compaction landed after it; the next turn’s report re-arms it. A turn that reported 0 input tokens counts as measured, so the trigger in practice never fires (gotcha).
The cut. Walking back from the leaf, the session keeps about KeepRecent estimated tokens raw. The cut lands only on a user or assistant message and never between a tool call and its result. A single turn larger than KeepRecent is split at an assistant message inside it and summarized in one pass.
The summary. By default the session’s own model writes it (Agent.Model(), middleware included, so mw.Retry and mw.Fallback apply), with no cache hints and the output capped at 0.8 × Reserve. The prompt is a fixed skeleton with the headings Goal:, Constraints:, Progress:, Key Decisions:, Next Steps:, Critical Context:, then cumulative Files read: and Files modified: lists. The range goes to the summarizer as the conversation’s own role-tagged messages, the previous summary first, under the skeleton system prompt: tool results capped at 2,000 characters plus a …[truncated] marker, signed reasoning dropped, files reduced to [file: name]. (ADR 0020 §2 says a plain transcript; the code sends the messages.) A summary that hits the output cap is never stored.
The context after it. s.Context() is, in order:
- The summary, as one user message:
<weft-summary>\n+ summary +\n</weft-summary>. - The pinned entries below the cut, raw, in path order.
- The kept tail from
FirstKepton, with every recorded trim replayed. Signed reasoning recorded before the latest compaction or trim is stripped. - Branch summaries where they sit on the path, behind the same marker.
weft.Repairlast, so every tool call shown has a result.
Undo is a navigation. Uncompact appends a leaf entry pointing at the entry before the latest compaction or trim on the path, so the context is exactly what it was when that entry landed. Every turn sent after the compaction is off the new path too: it stays in the file, but the model no longer sees it (gotcha). After a compaction and then a trim, the first Uncompact undoes the trim and a second one the compaction.
Between turns only. Compact, ApplyCompaction and Uncompact fail with thread.ErrBusy while a turn runs; Compact checks before it pays for a model call. Compact and ApplyCompaction fail with thread.ErrAwaitingApproval while approval requests are pending, and an open boundary holds the automatic trigger too: the parked calls must stay raw for their decisions to resolve (approvals). The trigger re-arms on the turn that resolves the boundary.
Cost. Each entry records its summarizer’s usage, and s.Usage().Summaries sums them in their own bucket, never mixed with the turns’ (usage). Only the summary call that was stored is counted: a rejected or truncated attempt, a SummaryModel that failed before the fallback, and a compaction that failed outright leave no entry, so their tokens are on no ledger (gotcha).
Every compaction is logged at Info through the agent’s logger, as thread: compacted or thread: trimmed old tool results, with trace=compaction, the session, the reason and tokens_before.
With no window
Section titled “With no window”Without ContextWindow (or a ModelWindows entry for the agent’s model) there is no automatic compaction and the session logs one warning through the agent’s logger, once per Session value:
logger := slog.New(slog.NewTextHandler(w, &slog.HandlerOptions{ ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr { if a.Key == slog.TimeKey { return slog.Attr{} // stable output } return a },}))agent := weft.New(wefttest.Script(wefttest.Say("Shipped."), wefttest.Say("Processing.")), weft.Logger(logger))s, err := thread.Create(ctx, thread.Memory(), agent) // no ContextWindowif err != nil { return err}for _, q := range []string{"Order 1234?", "Order 5678?"} { if err := send(ctx, s, q); err != nil { return err }}level=WARN msg="thread: no context window known for this session; automatic compaction stays off until one is configured (manual Compact always works)"Manual compaction and the overflow re-run still work. thread.NoAutoCompact() turns the trigger off on purpose: no trigger, no trim and no warning, for a session that compacts only by hand. It took this name in thread 0.9.0; the CHANGELOG’s migration checklist maps the old one.
A known window must leave room for the other two knobs: Reserve below the window, and KeepRecent below window − Reserve. Otherwise Create and Open fail with thread.ErrCompactConfig rather than build a session that never compacts.
When a turn overflows
Section titled “When a turn overflows”A turn that fails with weft.ErrContextOverflow, which every first-party adapter maps, compacts with reason overflow and re-runs once over the shrunken path, under a fresh run id:
agent := weft.New(wefttest.Script( wefttest.Say("Order 1234 shipped on Tuesday."), wefttest.Fail(weft.ErrContextOverflow), // the provider refuses the request wefttest.Say("Goal: track order 1234."), // the overflow compaction's summary wefttest.Say("Order 5678 is processing."), // the re-run, over the shrunken path))s, err := thread.Create(ctx, thread.Memory(), agent, ids("s_overflow", "a"), thread.KeepRecent(40)) // ReRunOnOverflow is on by defaultif err != nil { return err}if err := send(ctx, s, "Where is order 1234?"); err != nil { return err}turn, err := s.Send(ctx, weft.User("And order 5678?"))if err != nil { return err}res, err := turn.Wait()fmt.Fprintln(w, "turn:", err, "|", res.Text(), "| run:", turn.RunID())fmt.Fprintln(w, "compaction:", lastCompaction(s).Reason)turn: <nil> | Order 5678 is processing. | run: s_overflow-t3compaction: overflowThe caller sees one turn with the re-run’s answer; run t2 is the attempt that overflowed. A second overflow fails the turn with both errors joined. thread.ReRunOnOverflow(false) turns the re-run off, and the first overflow then fails the turn. NoAutoCompact does not affect it. While an approval boundary is open the overflow compaction is skipped and the turn fails (ExampleReRunOnOverflow).
Compact by hand
Section titled “Compact by hand”s.PreviewCompaction(ctx, opts...) runs the whole algorithm, the hook and the summarizer included, and returns the plan as a *thread.Compaction without writing anything. s.ApplyCompaction(ctx, plan) writes it as it stands, and s.Compact(ctx, opts...) does both. s.Pin(ctx, entryID) keeps an entry in the context through every compaction:
first := s.Entries()[0].(thread.MessageEntry) // "Where is order 1234?"if err := s.Pin(ctx, first.ID); err != nil { // keep it raw through every compaction return err}before := len(s.Context())plan, err := s.PreviewCompaction(ctx, thread.SummaryInstructions("Keep every order number."))if err != nil { return err}fmt.Fprintln(w, "plan:", plan.Summary, "| first kept:", plan.FirstKept, "| pinned:", plan.Pinned)sys := model.Requests()[len(model.Requests())-1].Systemfmt.Fprintln(w, "the summarizer's prompt ends:", sys[strings.LastIndex(sys, "\n")+1:])
if err := s.ApplyCompaction(ctx, plan); err != nil { // writes the plan as previewed return err}for _, m := range s.Context() { fmt.Fprintf(w, "%s: %q\n", m.Role, m.Text())}
if err := s.Uncompact(ctx); err != nil { // a branch back: nothing deleted return err}fmt.Fprintln(w, "after Uncompact:", len(s.Context()), "messages, as before:", len(s.Context()) == before)
// Preview and apply in one call; the session model summarizes again.if err := s.Compact(ctx); err != nil { return err}fmt.Fprintln(w, "after Compact:", lastCompaction(s).Summary, "|", len(s.Context()), "messages")plan: Goal: refund order 1234 and email the receipt. | first kept: e_a7 | pinned: [e_a1]the summarizer's prompt ends: Keep every order number.user: "<weft-summary>\nGoal: refund order 1234 and email the receipt.\n</weft-summary>"user: "Where is order 1234?"user: "Email me the receipt."assistant: "The receipt is on its way."after Uncompact: 6 messages, as before: trueafter Compact: Goal: refund order 1234. | 4 messagesthread.SummaryInstructions(text)is the onethread.CompactOption: it appends per-call instructions to this compaction’s summary prompt, as the last line. The agent’s ownweft.Instructionsare untouched. It took this name in thread 0.9.0, likeNoAutoCompact.Uncompactrewinds later turns too. The example callsUncompactright afterCompact, so nothing is lost. After later turns,Uncompactrewinds past them: q1 to q3,Compact, q4 and q5, thenUncompactleaves the context[q1 a1 q2 a2 q3 a3]. To get the later turns back, takeleaf := s.Leaf()before the undo and calls.Branch(ctx, leaf): the context is again the summary,a3, and q4 to a5.- A preview is a dry run. It may run while a turn is in flight, since it reads a snapshot, but applying it fails at once with
ErrBusyuntil the turn ends; it does not wait. A tail that fits insideKeepRecentisErrNothingToCompact, not an empty plan. ApplyCompactionvalidates the plan against the leaf’s path, whatever happened since it was computed.FirstKeptmust be an entry on the path (ErrNoEntrywhen the session does not hold it,ErrInvalidCompactionwhen it is on another branch), at or after the previous summary’s boundary. The same boundary twice isErrNothingToCompact. A plan without a summary must be a trim with its record. An emptyReasonis recorded asmanual. You can hand it your own plan:&thread.Compaction{Summary: "…", FirstKept: id}(ExampleSession_ApplyCompaction).- A pin does not hold the cut back. Compactions summarize past a pinned entry, record its id in
Pinned, and the context re-includes it raw after the summary. Only an entry that contributes a message can be pinned (a message, acustom_messageor abranch_summary); anything else isErrNotPinnable, an unknown idErrNoEntry. A pin is read when a compaction is computed, so a pin on an entry already below the boundary takes effect at the next one. The pin is a reserved custom entry, kindweft/pin(ExampleSession_Pin).
The package examples are ExampleSession_Compact and ExampleSession_PreviewCompaction.
Configure compaction
Section titled “Configure compaction”Every part of the algorithm is replaceable, in five layers (ADR 0020 §3): knobs, the summary, swapped implementations, hooks, and provider-native compaction. All are thread.SessionOption values passed to Create or Open. Every function or implementation you supply runs without the session lock and may call the session; the write after a hook re-validates against the tree as it is then. An Estimator that called back into the session used to deadlock; since thread 0.2.0 it runs outside the lock like the rest.
Options
Section titled “Options”| Option | Default | Effect |
|---|---|---|
ContextWindow(n) | unknown: no automatic compaction | The window the trigger budgets against, in tokens. Zero or negative is ignored. |
ModelWindows(map) | none | Per-model windows keyed by weft.ModelInfo; the agent’s model is looked up once, at Create or Open, and overrides ContextWindow. A run that swaps its model with weft.UseModel keeps the agent’s window. |
ModelReserves(map) | none | Per-model Reserve, resolved the same way. |
Reserve(n) | 16,384 | The headroom: fire before the context is within n tokens of the window. Also sizes the summary cap (0.8 × n). |
KeepRecent(n) | 20,000 | Roughly how many estimated tokens of the tail stay raw. |
TriggerFunc(fn) | LastInput + Estimated > Window − Reserve | Replaces the condition. Consulted only when a window is known and a report describes the path; a panic reads as “do not fire”. |
MinTurnsBetween(n) | 0: no limit | No automatic compaction or trim within n turns of the last compaction on the leaf’s path. |
MaxPerSession(n) | 0: no cap | At most n automatic compactions (trims included) on the leaf’s path; manual Compact keeps working. |
WithEstimator(est) | a quarter of the wire bytes | Replaces the token estimator: the trigger’s delta, the cut’s walk, TokensBefore. |
NoAutoCompact() | off | No trigger, no trim, no warning. Manual calls and the overflow re-run are unaffected. |
SummaryModel(m) | the session’s model | A cheaper model for summaries. On failure the session’s model takes over; then the compaction fails. |
SummaryPrompt(tmpl) | the skeleton | Replaces the summarizer’s system prompt whole. |
SummaryFocus(text) | none | Appends a standing instruction (“keep every file path”) after the prompt. |
SummaryMaxTokens(n) | 0.8 × Reserve | The summary’s output cap. A summary that reaches it fails as ErrSummaryTruncated. |
WithSummarizer(s) | a model call | Replaces text production only. SummaryModel and PreferNative do not apply; CheckSummary does. |
WithCompactor(c) | the built-in algorithm | Replaces everything past the cut; no summary layer runs. |
WithTrimmer(t) | off | A custom pre-pass before summarizing, on the threshold trigger only: Compact and the overflow re-run always summarize. |
ClearOldToolResults(keepLast) | off | The built-in trimmer: stub every tool result but the newest keepLast. |
BeforeCompact(fn) | none | Sees every summary compaction before the summarizer runs and returns a Verdict. |
AfterCompact(fn) | none | Runs with the durable CompactionEntry after any compaction or trim lands. |
CompactFailed(fn) | none | Runs when a compaction that was to be written is not, with the reason it was attempted for. |
CheckSummary(fn) | none | Validates each summary; a rejection retries once, then falls back. |
PreferNative() | off | Use the provider’s own compaction when the summary model implements NativeCompactor. |
ReRunOnOverflow(on) | on | Compact and re-run once when a turn fails with weft.ErrContextOverflow. |
The examples are ExampleSummaryModel (its cost lands in Usage().Summaries), ExampleTriggerFunc and ExampleCheckSummary.
The summary chain. With SummaryModel set the chain is that model, then the session’s model, then no compaction. Each source gets one retry when its summary is rejected, by CheckSummary or as truncated at the cap; a source that errors outright is not retried. A summary with no text is a failure. When the chain is exhausted nothing is stored, the error is returned, and CompactFailed hears of it.
Hook a compaction
Section titled “Hook a compaction”thread.BeforeCompact(fn) is told the reason and returns a thread.Verdict: thread.Proceed() runs the compaction with whatever the hook edited (the zero Verdict proceeds), thread.Cancel() stops it, and thread.Replace(c) writes the hook’s own compaction, recorded with reason from_hook:
verdict := "cancel"hook := thread.BeforeCompact(func(ctx context.Context, p *thread.Preparation) (thread.Verdict, error) { switch verdict { case "cancel": return thread.Cancel(), nil case "replace": // your own summary; recorded with Reason from_hook return thread.Replace(&thread.Compaction{Summary: "Order 1234: refund started.", FirstKept: p.FirstKept}), nil } for i, m := range p.Messages { // redact the range before the summarizer sees it p.Messages[i] = weft.Message{Role: m.Role, Content: []weft.Part{ weft.TextPart{Text: strings.ReplaceAll(m.Text(), "ada@example.com", "[email]")}, }} } return thread.Proceed(), nil})s, err := thread.Create(ctx, thread.Memory(), weft.New(model), ids("s_hook", "a"), thread.KeepRecent(40), hook)if err != nil { return err}The same session compacted three times, the hook’s answer changed between calls:
n := len(s.Entries())err = s.Compact(ctx)fmt.Fprintln(w, "cancel:", errors.Is(err, thread.ErrCompactCanceled), "entries written:", len(s.Entries())-n)
verdict = "replace"if err := s.Compact(ctx); err != nil { return err}fmt.Fprintln(w, "replace:", lastCompaction(s).Reason, lastCompaction(s).Summary)
verdict = "proceed"if err := s.Uncompact(ctx); err != nil { return err}if err := s.Compact(ctx); err != nil { return err}fed := model.Requests()[len(model.Requests())-1].Messages[0].Text()fmt.Fprintln(w, "proceed:", lastCompaction(s).Reason, "| the summarizer saw:", fed[:len("I am [email].")])cancel: true entries written: 0replace: from_hook Order 1234: refund started.proceed: manual | the summarizer saw: I am [email].Cancel writes nothing and the call fails with thread.ErrCompactCanceled; on the automatic path it stays quiet. A Replace plan’s FirstKept must be an entry the session holds; ApplyCompaction’s rules decide the rest. A hook error or panic fails the compaction with that error. A trim never passes through the hook, since it summarizes nothing. The package example is ExampleBeforeCompact.
The hook receives a *thread.Preparation. Four fields are editable, and the compaction proceeds with the edited values; edits to the rest are ignored:
| Field | Editable | Holds |
|---|---|---|
Reason | no | Why the compaction runs. |
Context | no | The context the model is shown now: the previous summary, pins, the kept tail with trims applied. |
Messages | yes | The range to summarize, as stored. Redact here. |
PrevSummary | no | The previous summary on the path, trims skipped. |
FirstKept | yes | The first entry kept raw. It must be a user or assistant message on the path, past the previous boundary, that splits no call from its result; moved alone, the range is rebuilt. |
TokensBefore | no | The estimated size of Context. |
Instructions | yes | The per-call text from SummaryInstructions. |
Pinned | yes | The pinned ids below the cut. |
The two observers run after the fact. thread.AfterCompact(fn) gets the durable entry for every compaction however it was written (Compact, ApplyCompaction, the trigger, the overflow re-run, a trim), and the Context it reads already shows it. thread.CompactFailed(fn) runs when a compaction that was to be written is not, after every fallback, including an ApplyCompaction that fails to validate or store. It does not run for PreviewCompaction, nor for the refusals that attempt nothing: ErrNothingToCompact, ErrCompactCanceled, ErrBusy and ErrAwaitingApproval. A panic in either is contained and logged. thread.CheckSummary(fn) validates each thread.Summary; a panic in it counts as a rejection, and a truncated summary never reaches it.
Clear old tool results first
Section titled “Clear old tool results first”thread.ClearOldToolResults(keepLast) is a cheap pre-pass: when the trigger fires, every tool result in the context except the newest keepLast is replaced with a stub naming the call. If that brings the estimate under window − Reserve, no summary is made:
read := weft.Tool("read_file", "Read a file.", func(ctx context.Context, in struct { Path string `json:"path"`}) (string, error) { return strings.Repeat(in.Path+" ", 300), nil // about 450 estimated tokens each})agent := weft.New(wefttest.Script( wefttest.ToolCalls( wefttest.Call{Name: "read_file", ID: "call_a", Args: `{"path":"a.go"}`}, wefttest.Call{Name: "read_file", ID: "call_b", Args: `{"path":"b.go"}`}, ), wefttest.Say("Both files read.").WithUsage(weft.Usage{InputTokens: 1_900}),), read)s, err := thread.Create(ctx, thread.Memory(), agent, ids("s_trim", "a"), thread.ContextWindow(2_000), thread.Reserve(500), thread.KeepRecent(40), thread.ClearOldToolResults(1)) // keep the newest result rawif err != nil { return err}if err := send(ctx, s, "Read a.go and b.go."); err != nil { return err}c := lastCompaction(s)fmt.Fprintln(w, "compaction:", c.Reason, "| summary empty:", c.Summary == "", "| stubs:", len(c.Trim.Stubs))for _, m := range s.Context() { for _, p := range m.Content { if r, ok := p.(weft.ToolResultPart); ok { fmt.Fprintln(w, r.CallID+":", r.Content[:min(38, len(r.Content))]) } }}compaction: trim | summary empty: true | stubs: 1call_a: [cleared tool result read_file call_a]call_b: b.go b.go b.go b.go b.go b.go b.go b.gThe entry has reason trim, no summary, and a thread.TrimRecord whose thread.TrimStub values name each stubbed result: the entry, the call id, the replacement content. The stored results are untouched. Later context builds replay the record, never the option, so reopening with another keepLast never changes what a recorded trim shows. A trim keeps the boundary in force; it never governs it and never feeds the summary chain. A trim that changes nothing, or does not fit, writes nothing and the summary runs (ExampleClearOldToolResults).
Swap the parts
Section titled “Swap the parts”Four interfaces replace a part of the algorithm:
thread.Summarizer,Summarize(ctx, SummaryInput) (Summary, error), produces the text and nothing else; the cut, the serialization, the entry and the retry chain stay the session’s. Athread.SummaryInputcarriesMessages(the range, serialized),PrevSummary,Instructions,MaxTokens,ReasonandSystemPrompt, the prompt the default would send, which a custom summarizer may reuse or ignore. It returns athread.SummarywithText(empty is a failure) and theUsageandModelit cost, zero when no model ran. One that knows it was cut short returns an error wrappingErrSummaryTruncated(ExampleWithSummarizer).thread.Compactor,Compact(ctx, Preparation) (*Compaction, error), is the whole algorithm past the cut, after the hook’s edits. It may keep anyFirstKepton the path past the previous boundary; a returned plan with noReasontakes the preparation’s.thread.Trimmer,Trim(ctx, msgs) ([]weft.Message, error), edits a copy of the context. The one change the record can hold is a tool result’sContent(andIsError) replaced in place; any other change fails the trim withErrInvalidCompaction, reported through the logger andCompactFailed, and the summary runs instead. An error or panic is logged and the summary runs.thread.Estimator,Estimate(msgs) int64, weighs messages in tokens, called with one message during the cut’s walk and with a batch otherwise. The default weighs a message’s JSON, so an inline file’s base64 bytes count as text (gotcha).
A panic in a Summarizer or Compactor fails the compaction. thread.NativeCompactor, CompactNative(ctx, req, instructions), is what an adapter implements when its provider compacts server-side; PreferNative looks for it on the summary model by following Unwrap() through middleware. The walk compares models structurally under a depth cap of 64, so an unhashable or self-wrapping wrapper ends the walk instead of panicking or looping (since thread 0.2.0). Only the returned message’s text is kept, stored like any other summary. No first-party adapter implements the interface in v0.20.2, and on a model without it, an error or an empty text, the text summary runs.
What a compaction records
Section titled “What a compaction records”A thread.Compaction is the plan PreviewCompaction returns and ApplyCompaction writes, field for field:
| Field | Meaning |
|---|---|
Summary | The summary text, shown behind the marker. Empty only on a trim. |
FirstKept | The first entry the context still shows raw. |
TokensBefore | The estimated size of the context the model was shown, the compacted view, not the raw path. |
Reason | Why it ran (below). |
SummarizerUsage, SummarizerModel | What the summary cost and which model made it. |
FilesRead | The file URLs the summarized range carried, sorted and deduplicated. |
Pinned | The pinned ids below FirstKept, re-included after the summary. |
RangeHash | The SHA-256 of the serialized range the summarizer was fed. |
Trim | The trim record: required on a trim, forbidden otherwise. |
The thread.Reason values are ReasonManual ("manual": Compact, or ApplyCompaction of a preview), ReasonThreshold ("threshold": the trigger), ReasonOverflow ("overflow": before the re-run), ReasonFromHook ("from_hook": a Replace) and ReasonTrim ("trim"). MaxPerSession counts every reason but manual as automatic.
The trigger reads a thread.TriggerInput: LastInput, the last step’s provider-reported input plus an estimate of that step’s own messages, recorded on the turn entry; Estimated, the tokens added since that turn; and the Window and Reserve in force.
Errors
Section titled “Errors”Match each with errors.Is; nothing is written on any of them.
| Error | Returned when |
|---|---|
ErrNothingToCompact | The tail fits inside KeepRecent, nothing new sits past the previous boundary, or a plan names the boundary the previous compaction left. |
ErrCompactCanceled | BeforeCompact answered Cancel. |
ErrSummaryTruncated | The last summarizer in the chain stopped at the output cap (the chain wraps its last error); raise SummaryMaxTokens or Reserve. |
ErrInvalidCompaction | A plan that cannot be written as given: FirstKept off the path or before the boundary, a summary-less non-trim, a bad trim record, or a Trimmer change the record cannot hold. |
ErrCompactConfig | Create or Open with a known window and Reserve or KeepRecent too large for it. |
ErrNotPinnable | Pin on an entry that contributes no message. |
ErrNoEntry | Pin or a plan names an entry the session does not hold, or Uncompact finds no compaction on the path. |
ErrAwaitingApproval | Compact or ApplyCompaction while approval requests are pending. |
ErrBusy | Compact, ApplyCompaction or Uncompact while a turn runs. |
TrimRecord, TrimStub, Compaction.Trim and these sentinels arrived in thread 0.9.0.
The compaction marker
Section titled “The compaction marker”Each compaction also emits one informational OTel log record of kind compaction through the agent’s LoggerProvider as it lands, filed under the id of the last run of this session that produced the compacted context. obsdb.DB.Compactions reads it back:
p, err := otel.Start(ctx, otel.Local(filepath.Join(dir, "weft.db")), otel.NoEnv(), otel.NoGlobal())if err != nil { return err}defer p.Shutdown(context.WithoutCancel(ctx))agent := weft.New(wefttest.Script( wefttest.Say("Order 1234 shipped on Tuesday."), wefttest.Say("The refund for order 1234 is started."), wefttest.Say("The receipt is on its way."), wefttest.Say("Goal: refund order 1234."),), weft.TracerProvider(p.TracerProvider()), weft.LoggerProvider(p.LoggerProvider()))s, err := thread.Create(ctx, thread.Memory(), agent, ids("s_marker", "a"), thread.KeepRecent(40))if err != nil { return err}if err := longHistory(ctx, s); err != nil { return err}if err := s.Compact(ctx); err != nil { // the marker goes out as the entry lands return err}marks, err := p.LocalDB().Compactions(ctx, "s_marker-t3") // the last run that produced the contextif err != nil { return err}for _, m := range marks { fmt.Fprintln(w, "marker:", m.Scope, m.Reason, "replaced", m.Replaced, "messages with", m.Entries)}marker: session manual replaced 4 messages with 1- What it carries. Counts and a hash, never messages. It has the event name
weft.compactionand the attributesweft.compaction.scope = session,weft.compaction.hash(the SHA-256 of the entry’s JSON),weft.content = none,gen_ai.agent.nameand the session’s run metadata (weft.session.id,weft.turn,weft.public_id, …), but not thegen_ai.conversation.idandsession.idmirrors a run’s records carry. The body is{scope, hash, entry, reason, replaced, entries, messages_before, messages_after, tokens_before, tokens_after, summarizer_model?, summarizer_usage?, held?}(record contract). Since 0.18.0summarizer_model({provider, name}) andsummarizer_usagesay what the summary cost, counts and a model id, never content; both are absent for a trim or a summarizer that ran no model. - Where it is filed. Under the last run whose turn produced the context. A context no run of this session produced (entries appended by hand, a fork’s copied path) holds the marker for the next run this
Sessiondrives. Still held atClose, it goes out then withheld: truein its body, filed under no run and keyed byweft.session.id, as the state log’s records are: a store indexes it by session, and no run’sCompactionsreads it. - The summarizer’s calls. Since 0.18.0 every summary model call, of a compaction or a
SummarizeLeftbranch, is also achatspan withweft.chat.rolesummarizer, its model and its usage, filed under the turn in flight or the last run. It is never in that run’s own usage, provider, model or metadata:obsdb.SessionRow.SummarizerUsagesums it per session, apart fromUsage, and Studio prices it at read time (See what a run cost). A failed call’s span carrieserror.typesummarizer. - Who reads it. No reader applies it: the next run’s input record already holds the compacted context.
obsdb.DB.Compactionsreturns a run’s run-scope compaction views first, then the session markers filed under it, scopeobsdb.CompactionSession. Studio’s run page draws it at the top as “session compaction · after this run”, with its token line and counts.
Complete example
Section titled “Complete example”sessions/compaction.go runs the trigger, the warning, the manual calls, the hook, a trim, an overflow and the marker, each on its own session:
package main
import ( "context" "errors" "fmt" "io" "log/slog" "path/filepath" "strings"
"github.com/weftgo/weft" "github.com/weftgo/weft/otel" "github.com/weftgo/weft/thread" "github.com/weftgo/weft/wefttest")
// demoCompaction is the page "Keep long sessions inside the context// window (compaction)".func demoCompaction(ctx context.Context, w io.Writer, dir string) error { steps := []func(context.Context, io.Writer, string) error{ compactionWindow, compactionWarn, compactionManual, compactionHook, compactionTrim, compactionOverflow, compactionMarker, } for _, step := range steps { if err := step(ctx, w, dir); err != nil { return err } } return nil}
// compactionWindow: ContextWindow arms the trigger, and a turn whose// reported input crosses window − Reserve compacts after it ends.func compactionWindow(ctx context.Context, w io.Writer, _ string) error { fmt.Fprintln(w, "== automatic") agent := weft.New(wefttest.Script( wefttest.Say("Order 1234 shipped on Tuesday.").WithUsage(weft.Usage{InputTokens: 300}), wefttest.Say("Order 5678 is still processing.").WithUsage(weft.Usage{InputTokens: 900}), wefttest.Say("Goal: track orders 1234 and 5678."), // the summary, made by the same model )) s, err := thread.Create(ctx, thread.Memory(), agent, ids("s_window", "a"), thread.ContextWindow(1_000), // arms the trigger: fire past 1,000 − Reserve thread.Reserve(200), // default 16,384 thread.KeepRecent(40)) // default 20,000: estimated tokens kept raw if err != nil { return err } for _, q := range []string{"Where is order 1234?", "And order 5678?"} { if err := send(ctx, s, q); err != nil { // send waits for WaitIdle: the trigger runs after the turn return err } } for _, e := range s.Entries() { if c, ok := e.(thread.CompactionEntry); ok { fmt.Fprintln(w, "compaction:", c.Reason, "first kept:", c.FirstKept, "tokens before:", c.TokensBefore) } } for _, m := range s.Context() { fmt.Fprintf(w, "%s: %q\n", m.Role, m.Text()) } fmt.Fprintln(w, "entries in the file:", len(s.Entries())) return s.Close(ctx)}
// compactionWarn: a session with no window logs one warning and never// compacts on its own.func compactionWarn(ctx context.Context, w io.Writer, _ string) error { fmt.Fprintln(w, "== no window") logger := slog.New(slog.NewTextHandler(w, &slog.HandlerOptions{ ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr { if a.Key == slog.TimeKey { return slog.Attr{} // stable output } return a }, })) agent := weft.New(wefttest.Script(wefttest.Say("Shipped."), wefttest.Say("Processing.")), weft.Logger(logger)) s, err := thread.Create(ctx, thread.Memory(), agent) // no ContextWindow if err != nil { return err } for _, q := range []string{"Order 1234?", "Order 5678?"} { if err := send(ctx, s, q); err != nil { return err } } return s.Close(ctx)}
// longHistory runs three short turns, so a manual compaction has a cut.func longHistory(ctx context.Context, s *thread.Session) error { for _, q := range []string{"Where is order 1234?", "Refund it.", "Email me the receipt."} { if err := send(ctx, s, q); err != nil { return err } } return nil}
// compactionManual: preview, apply, pin and undo by hand.func compactionManual(ctx context.Context, w io.Writer, _ string) error { fmt.Fprintln(w, "== by hand") model := wefttest.Script( wefttest.Say("Order 1234 shipped on Tuesday."), wefttest.Say("The refund for order 1234 is started."), wefttest.Say("The receipt is on its way."), wefttest.Say("Goal: refund order 1234 and email the receipt."), // the preview's summary wefttest.Say("Goal: refund order 1234."), // Compact's summary ) s, err := thread.Create(ctx, thread.Memory(), weft.New(model), ids("s_manual", "a"), thread.KeepRecent(40)) if err != nil { return err } if err := longHistory(ctx, s); err != nil { return err } first := s.Entries()[0].(thread.MessageEntry) // "Where is order 1234?" if err := s.Pin(ctx, first.ID); err != nil { // keep it raw through every compaction return err } before := len(s.Context()) plan, err := s.PreviewCompaction(ctx, thread.SummaryInstructions("Keep every order number.")) if err != nil { return err } fmt.Fprintln(w, "plan:", plan.Summary, "| first kept:", plan.FirstKept, "| pinned:", plan.Pinned) sys := model.Requests()[len(model.Requests())-1].System fmt.Fprintln(w, "the summarizer's prompt ends:", sys[strings.LastIndex(sys, "\n")+1:])
if err := s.ApplyCompaction(ctx, plan); err != nil { // writes the plan as previewed return err } for _, m := range s.Context() { fmt.Fprintf(w, "%s: %q\n", m.Role, m.Text()) }
if err := s.Uncompact(ctx); err != nil { // a branch back: nothing deleted return err } fmt.Fprintln(w, "after Uncompact:", len(s.Context()), "messages, as before:", len(s.Context()) == before)
// Preview and apply in one call; the session model summarizes again. if err := s.Compact(ctx); err != nil { return err } fmt.Fprintln(w, "after Compact:", lastCompaction(s).Summary, "|", len(s.Context()), "messages") return s.Close(ctx)}
// compactionHook: BeforeCompact decides — Cancel, Replace or Proceed// with an edited Preparation.func compactionHook(ctx context.Context, w io.Writer, _ string) error { fmt.Fprintln(w, "== hook") model := wefttest.Script( wefttest.Say("Order 1234 shipped on Tuesday."), wefttest.Say("The refund for order 1234 is started."), wefttest.Say("The receipt is on its way."), wefttest.Say("Goal: refund the order; the customer is [email]."), // the Proceed summary ) verdict := "cancel" hook := thread.BeforeCompact(func(ctx context.Context, p *thread.Preparation) (thread.Verdict, error) { switch verdict { case "cancel": return thread.Cancel(), nil case "replace": // your own summary; recorded with Reason from_hook return thread.Replace(&thread.Compaction{Summary: "Order 1234: refund started.", FirstKept: p.FirstKept}), nil } for i, m := range p.Messages { // redact the range before the summarizer sees it p.Messages[i] = weft.Message{Role: m.Role, Content: []weft.Part{ weft.TextPart{Text: strings.ReplaceAll(m.Text(), "ada@example.com", "[email]")}, }} } return thread.Proceed(), nil }) s, err := thread.Create(ctx, thread.Memory(), weft.New(model), ids("s_hook", "a"), thread.KeepRecent(40), hook) if err != nil { return err } if err := send(ctx, s, "I am ada@example.com. Where is order 1234?"); err != nil { return err } if err := longHistoryFrom(ctx, s, 1); err != nil { return err } n := len(s.Entries()) err = s.Compact(ctx) fmt.Fprintln(w, "cancel:", errors.Is(err, thread.ErrCompactCanceled), "entries written:", len(s.Entries())-n)
verdict = "replace" if err := s.Compact(ctx); err != nil { return err } fmt.Fprintln(w, "replace:", lastCompaction(s).Reason, lastCompaction(s).Summary)
verdict = "proceed" if err := s.Uncompact(ctx); err != nil { return err } if err := s.Compact(ctx); err != nil { return err } fed := model.Requests()[len(model.Requests())-1].Messages[0].Text() fmt.Fprintln(w, "proceed:", lastCompaction(s).Reason, "| the summarizer saw:", fed[:len("I am [email].")]) return s.Close(ctx)}
// longHistoryFrom runs the rest of longHistory's turns, from turn i.func longHistoryFrom(ctx context.Context, s *thread.Session, i int) error { for _, q := range []string{"Where is order 1234?", "Refund it.", "Email me the receipt."}[i:] { if err := send(ctx, s, q); err != nil { return err } } return nil}
// lastCompaction is the newest compaction entry on the session's path.func lastCompaction(s *thread.Session) thread.CompactionEntry { var out thread.CompactionEntry path, _ := s.Path(s.Leaf()) for _, e := range path { if c, ok := e.(thread.CompactionEntry); ok { out = c } } return out}
// compactionTrim: ClearOldToolResults stubs old tool results first;// when that is enough, no summary is made.func compactionTrim(ctx context.Context, w io.Writer, _ string) error { fmt.Fprintln(w, "== trim") read := weft.Tool("read_file", "Read a file.", func(ctx context.Context, in struct { Path string `json:"path"` }) (string, error) { return strings.Repeat(in.Path+" ", 300), nil // about 450 estimated tokens each }) agent := weft.New(wefttest.Script( wefttest.ToolCalls( wefttest.Call{Name: "read_file", ID: "call_a", Args: `{"path":"a.go"}`}, wefttest.Call{Name: "read_file", ID: "call_b", Args: `{"path":"b.go"}`}, ), wefttest.Say("Both files read.").WithUsage(weft.Usage{InputTokens: 1_900}), ), read) s, err := thread.Create(ctx, thread.Memory(), agent, ids("s_trim", "a"), thread.ContextWindow(2_000), thread.Reserve(500), thread.KeepRecent(40), thread.ClearOldToolResults(1)) // keep the newest result raw if err != nil { return err } if err := send(ctx, s, "Read a.go and b.go."); err != nil { return err } c := lastCompaction(s) fmt.Fprintln(w, "compaction:", c.Reason, "| summary empty:", c.Summary == "", "| stubs:", len(c.Trim.Stubs)) for _, m := range s.Context() { for _, p := range m.Content { if r, ok := p.(weft.ToolResultPart); ok { fmt.Fprintln(w, r.CallID+":", r.Content[:min(38, len(r.Content))]) } } } return s.Close(ctx)}
// compactionOverflow: a turn failing with weft.ErrContextOverflow// compacts and re-runs once.func compactionOverflow(ctx context.Context, w io.Writer, _ string) error { fmt.Fprintln(w, "== overflow") agent := weft.New(wefttest.Script( wefttest.Say("Order 1234 shipped on Tuesday."), wefttest.Fail(weft.ErrContextOverflow), // the provider refuses the request wefttest.Say("Goal: track order 1234."), // the overflow compaction's summary wefttest.Say("Order 5678 is processing."), // the re-run, over the shrunken path )) s, err := thread.Create(ctx, thread.Memory(), agent, ids("s_overflow", "a"), thread.KeepRecent(40)) // ReRunOnOverflow is on by default if err != nil { return err } if err := send(ctx, s, "Where is order 1234?"); err != nil { return err } turn, err := s.Send(ctx, weft.User("And order 5678?")) if err != nil { return err } res, err := turn.Wait() fmt.Fprintln(w, "turn:", err, "|", res.Text(), "| run:", turn.RunID()) fmt.Fprintln(w, "compaction:", lastCompaction(s).Reason) return s.Close(ctx)}
// compactionMarker: each compaction emits one session marker record,// which obsdb reads back under the run that produced the context.func compactionMarker(ctx context.Context, w io.Writer, dir string) error { fmt.Fprintln(w, "== marker") p, err := otel.Start(ctx, otel.Local(filepath.Join(dir, "weft.db")), otel.NoEnv(), otel.NoGlobal()) if err != nil { return err } defer p.Shutdown(context.WithoutCancel(ctx)) agent := weft.New(wefttest.Script( wefttest.Say("Order 1234 shipped on Tuesday."), wefttest.Say("The refund for order 1234 is started."), wefttest.Say("The receipt is on its way."), wefttest.Say("Goal: refund order 1234."), ), weft.TracerProvider(p.TracerProvider()), weft.LoggerProvider(p.LoggerProvider())) s, err := thread.Create(ctx, thread.Memory(), agent, ids("s_marker", "a"), thread.KeepRecent(40)) if err != nil { return err } if err := longHistory(ctx, s); err != nil { return err } if err := s.Compact(ctx); err != nil { // the marker goes out as the entry lands return err } marks, err := p.LocalDB().Compactions(ctx, "s_marker-t3") // the last run that produced the context if err != nil { return err } for _, m := range marks { fmt.Fprintln(w, "marker:", m.Scope, m.Reason, "replaced", m.Replaced, "messages with", m.Entries) } return s.Close(ctx)}View on GitHub · run it from docs-site/examples:
go run ./sessions compactiongo test ./sessions== automaticcompaction: threshold first kept: e_a4 tokens before: 81user: "<weft-summary>\nGoal: track orders 1234 and 5678.\n</weft-summary>"user: "And order 5678?"assistant: "Order 5678 is still processing."entries in the file: 7== no windowlevel=WARN msg="thread: no context window known for this session; automatic compaction stays off until one is configured (manual Compact always works)"== by handplan: Goal: refund order 1234 and email the receipt. | first kept: e_a7 | pinned: [e_a1]the summarizer's prompt ends: Keep every order number.user: "<weft-summary>\nGoal: refund order 1234 and email the receipt.\n</weft-summary>"user: "Where is order 1234?"user: "Email me the receipt."assistant: "The receipt is on its way."after Uncompact: 6 messages, as before: trueafter Compact: Goal: refund order 1234. | 4 messages== hookcancel: true entries written: 0replace: from_hook Order 1234: refund started.proceed: manual | the summarizer saw: I am [email].== trimcompaction: trim | summary empty: true | stubs: 1call_a: [cleared tool result read_file call_a]call_b: b.go b.go b.go b.go b.go b.go b.go b.g== overflowturn: <nil> | Order 5678 is processing. | run: s_overflow-t3compaction: overflow== markermarker: session manual replaced 4 messages with 1The other sessions log their own no-window warning and their Info lines on stderr, through slog.Default. sessions/sessions_test.go also pins that a compaction only appends, that Uncompact restores the context, and that Cancel writes nothing and calls no model.
Best practices & gotchas
Section titled “Best practices & gotchas”- Set
ContextWindowfor every session that runs long. Without it nothing compacts until a turn overflows the provider’s window and pays for a failed request first. (Source:thread/compaction.go:1306-1320; ADR 0020 §2) - Compact between turns.
Compact,ApplyCompactionandUncompactfail withErrBusywhile a turn runs; wait for the turn, or calls.WaitIdle. (Source:thread/compaction.go:290-308, 606-611) - Do not offer
Uncompactas “show the full history”. It branches back to the entry before the latest compaction, so every turn sent since then leaves the model’s context. WithContextWindowthe latest compaction can be many turns back. Undo right after compacting, or keeps.Leaf()from before the undo andBranchback to it. To keep the raw history in view, reads.Entries()ors.Path(leaf)instead. (Source:thread/compaction.go:594-635) - Decide approvals before compacting. A pending approval holds the tail raw:
Compactfails withErrAwaitingApprovaland the trigger waits. (Source:thread/compaction.go:123-126; ADR 0021 amendment 2026-09-29) - Redact in
BeforeCompact, not after. The hook’sPreparation.Messagesis what the summarizer reads; the summary lands in the context and the file. (Source:thread/compactopts.go:351-362;ExampleBeforeCompact) - Wait for idle before reading what the trigger did. The trigger runs after the turn is decided, so a caller of
turn.Waitmay read the session before the compaction lands. (Source:thread/turn.go:1274-1276;ExampleClearOldToolResults) - A summary costs a model call. In a scripted test it consumes a scripted reply; in production the stored summary’s call is billed under
Usage().Summaries. (Source: ADR 0020 §4 cost ledger;ExampleSummaryModel) - Count summary spend from the provider, not from
Summaries.SummariessumsCompactionEntry.SummarizerUsage, the accepted summary’s call alone. Rejected or truncated retries, a failedSummaryModelbefore the fallback, a compaction that failed and everySummarizeLeftsummary are not counted. Without aSummaryModel, a compaction that is always rejected costs two summary calls at each trigger, andSummariesstays zero. (Source:thread/compaction.go:795, 951-989;thread/session.go:1532-1536) - Fix a compaction that keeps failing. The trigger runs before and after every turn. A failed attempt writes no compaction entry, so
MinTurnsBetweenandMaxPerSessionnever count it. Once the gap from the last stored compaction has passed, it is retried at every trigger with no backoff. Each failure logsthread: automatic compaction failedat WARN; the turn itself still runs. (Source:thread/turn.go:951, 1282;thread/compaction.go:1381-1385, 1398-1419, 1580-1606) - Make sure the provider reports input tokens. The trigger’s signal is the final step’s reported
InputTokens. A turn that reports 0 still counts as measured, so the trigger compares only an estimate of the newest messages with the window: it never fires in practice, and nothing is logged. What still compacts: a manuals.Compact, athread.TriggerFuncthat decides on something other than the reported number (it still receives theTriggerInput), and the overflow re-run when the provider’s error maps toweft.ErrContextOverflow. An OpenAI-compatible server withoutinclude_usagereports 0 (providers). (Source:thread/turn.go:1661-1671;thread/compaction.go:1331-1338, 1375-1380, 1424-1428;thread/compactopts.go:123-141) - Give scripted turns usage in a compaction test.
wefttest.Sayandwefttest.ToolCallsreport a fixed 10 input tokens, so the signal stays at 10 however long the scripted conversation grows. Set the reported input on each turn withTurn.WithUsage, assessions/compaction.godoes:wefttest.Say("…").WithUsage(weft.Usage{InputTokens: 900}). (Source:weft/core/wefttest/model.go:32-36, 124-127) - Weigh inline files yourself. The default estimate is a quarter of a message’s JSON bytes, and an inline
FilePart’sDatais base64 in that JSON. A 400 KiB PNG sent inline weighs about 136k estimated tokens, so the trigger before that turn can compact a session whose real input is a few thousand tokens, and pay for the summary. Send the file as a URLFilePart, or passWithEstimatoranEstimatorthat gives file parts their own weight. (Source:thread/compaction.go:1244-1250;thread/compactopts.go:188-202) - Raise the cap, not the retries, on
ErrSummaryTruncated. A cut summary is never stored; give it room withSummaryMaxTokensorReserve. (Source:thread/compaction.go:98-103)
See also
Section titled “See also”- Approvals in sessions: why an open boundary holds compaction
- Label, branch and fork a session:
Uncompactis a branch;SummarizeLeftuses the same summarizer - Send turns and wait for them: the cost ledger and what the model sees
- The session log format: the
compactionentry and its"v":5trim record
Symbols used: thread.ContextWindow · thread.Reserve · thread.KeepRecent · thread.NoAutoCompact · thread.ReRunOnOverflow · thread.SummaryInstructions · thread.BeforeCompact · thread.Proceed · thread.Cancel · thread.Replace · thread.ClearOldToolResults · thread.Preparation · thread.Compaction · thread.CompactionEntry · Session.Compact · Session.PreviewCompaction · Session.ApplyCompaction · Session.Uncompact · Session.Pin · Session.Context · Session.Entries · Session.Path · weft.ErrContextOverflow · weft.Logger · weft.LoggerProvider · weft.TracerProvider · otel.Start · otel.Local · obsdb.DB · wefttest.Script · wefttest.Say · wefttest.ToolCalls · Turn.WithUsage · weft.FilePart · thread.Estimator · thread.WithEstimator