Skip to content

Keep long sessions inside the context window (compaction)

View as Markdown

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:

sessions/compaction.go
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()))

sessions/compaction.go on GitHub

compaction: threshold first kept: e_a4 tokens before: 81
user: "<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

The 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.

s.Compact(ctx): a summary entry replaces e1 to e3 in the context; nothing is deleted.A session log holds e1 to e5. s.Compact(ctx) appends a compaction entry C, a summary of e1 to e3. Those entries stay in the file; the context at the leaf becomes the summary, then e4 and e5, the kept recent entries. s.Uncompact(ctx) undoes it by branching back to the entry before the compaction.

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:

  1. The summary, as one user message: <weft-summary>\n + summary + \n</weft-summary>.
  2. The pinned entries below the cut, raw, in path order.
  3. The kept tail from FirstKept on, with every recorded trim replayed. Signed reasoning recorded before the latest compaction or trim is stripped.
  4. Branch summaries where they sit on the path, behind the same marker.
  5. weft.Repair last, 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.

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:

sessions/compaction.go
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
}
}

sessions/compaction.go on GitHub

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.

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:

sessions/compaction.go
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)

sessions/compaction.go on GitHub

turn: <nil> | Order 5678 is processing. | run: s_overflow-t3
compaction: overflow

The 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).

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:

sessions/compaction.go
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")

sessions/compaction.go on GitHub

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: true
after Compact: Goal: refund order 1234. | 4 messages
  • thread.SummaryInstructions(text) is the one thread.CompactOption: it appends per-call instructions to this compaction’s summary prompt, as the last line. The agent’s own weft.Instructions are untouched. It took this name in thread 0.9.0, like NoAutoCompact.
  • Uncompact rewinds later turns too. The example calls Uncompact right after Compact, so nothing is lost. After later turns, Uncompact rewinds past them: q1 to q3, Compact, q4 and q5, then Uncompact leaves the context [q1 a1 q2 a2 q3 a3]. To get the later turns back, take leaf := s.Leaf() before the undo and call s.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 ErrBusy until the turn ends; it does not wait. A tail that fits inside KeepRecent is ErrNothingToCompact, not an empty plan.
  • ApplyCompaction validates the plan against the leaf’s path, whatever happened since it was computed. FirstKept must be an entry on the path (ErrNoEntry when the session does not hold it, ErrInvalidCompaction when it is on another branch), at or after the previous summary’s boundary. The same boundary twice is ErrNothingToCompact. A plan without a summary must be a trim with its record. An empty Reason is recorded as manual. 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, a custom_message or a branch_summary); anything else is ErrNotPinnable, an unknown id ErrNoEntry. 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, kind weft/pin (ExampleSession_Pin).

The package examples are ExampleSession_Compact and ExampleSession_PreviewCompaction.

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.

OptionDefaultEffect
ContextWindow(n)unknown: no automatic compactionThe window the trigger budgets against, in tokens. Zero or negative is ignored.
ModelWindows(map)nonePer-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)nonePer-model Reserve, resolved the same way.
Reserve(n)16,384The headroom: fire before the context is within n tokens of the window. Also sizes the summary cap (0.8 × n).
KeepRecent(n)20,000Roughly how many estimated tokens of the tail stay raw.
TriggerFunc(fn)LastInput + Estimated > Window − ReserveReplaces 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 limitNo automatic compaction or trim within n turns of the last compaction on the leaf’s path.
MaxPerSession(n)0: no capAt most n automatic compactions (trims included) on the leaf’s path; manual Compact keeps working.
WithEstimator(est)a quarter of the wire bytesReplaces the token estimator: the trigger’s delta, the cut’s walk, TokensBefore.
NoAutoCompact()offNo trigger, no trim, no warning. Manual calls and the overflow re-run are unaffected.
SummaryModel(m)the session’s modelA cheaper model for summaries. On failure the session’s model takes over; then the compaction fails.
SummaryPrompt(tmpl)the skeletonReplaces the summarizer’s system prompt whole.
SummaryFocus(text)noneAppends a standing instruction (“keep every file path”) after the prompt.
SummaryMaxTokens(n)0.8 × ReserveThe summary’s output cap. A summary that reaches it fails as ErrSummaryTruncated.
WithSummarizer(s)a model callReplaces text production only. SummaryModel and PreferNative do not apply; CheckSummary does.
WithCompactor(c)the built-in algorithmReplaces everything past the cut; no summary layer runs.
WithTrimmer(t)offA custom pre-pass before summarizing, on the threshold trigger only: Compact and the overflow re-run always summarize.
ClearOldToolResults(keepLast)offThe built-in trimmer: stub every tool result but the newest keepLast.
BeforeCompact(fn)noneSees every summary compaction before the summarizer runs and returns a Verdict.
AfterCompact(fn)noneRuns with the durable CompactionEntry after any compaction or trim lands.
CompactFailed(fn)noneRuns when a compaction that was to be written is not, with the reason it was attempted for.
CheckSummary(fn)noneValidates each summary; a rejection retries once, then falls back.
PreferNative()offUse the provider’s own compaction when the summary model implements NativeCompactor.
ReRunOnOverflow(on)onCompact 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.

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:

sessions/compaction.go
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
}

sessions/compaction.go on GitHub

The same session compacted three times, the hook’s answer changed between calls:

sessions/compaction.go
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].")])

sessions/compaction.go on GitHub

cancel: true entries written: 0
replace: 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:

FieldEditableHolds
ReasonnoWhy the compaction runs.
ContextnoThe context the model is shown now: the previous summary, pins, the kept tail with trims applied.
MessagesyesThe range to summarize, as stored. Redact here.
PrevSummarynoThe previous summary on the path, trims skipped.
FirstKeptyesThe 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.
TokensBeforenoThe estimated size of Context.
InstructionsyesThe per-call text from SummaryInstructions.
PinnedyesThe 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.

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:

sessions/compaction.go
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))])
}
}
}

sessions/compaction.go on GitHub

compaction: trim | summary empty: true | stubs: 1
call_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

The 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).

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. A thread.SummaryInput carries Messages (the range, serialized), PrevSummary, Instructions, MaxTokens, Reason and SystemPrompt, the prompt the default would send, which a custom summarizer may reuse or ignore. It returns a thread.Summary with Text (empty is a failure) and the Usage and Model it cost, zero when no model ran. One that knows it was cut short returns an error wrapping ErrSummaryTruncated (ExampleWithSummarizer).
  • thread.Compactor, Compact(ctx, Preparation) (*Compaction, error), is the whole algorithm past the cut, after the hook’s edits. It may keep any FirstKept on the path past the previous boundary; a returned plan with no Reason takes 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’s Content (and IsError) replaced in place; any other change fails the trim with ErrInvalidCompaction, reported through the logger and CompactFailed, 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.

A thread.Compaction is the plan PreviewCompaction returns and ApplyCompaction writes, field for field:

FieldMeaning
SummaryThe summary text, shown behind the marker. Empty only on a trim.
FirstKeptThe first entry the context still shows raw.
TokensBeforeThe estimated size of the context the model was shown, the compacted view, not the raw path.
ReasonWhy it ran (below).
SummarizerUsage, SummarizerModelWhat the summary cost and which model made it.
FilesReadThe file URLs the summarized range carried, sorted and deduplicated.
PinnedThe pinned ids below FirstKept, re-included after the summary.
RangeHashThe SHA-256 of the serialized range the summarizer was fed.
TrimThe 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.

Match each with errors.Is; nothing is written on any of them.

ErrorReturned when
ErrNothingToCompactThe tail fits inside KeepRecent, nothing new sits past the previous boundary, or a plan names the boundary the previous compaction left.
ErrCompactCanceledBeforeCompact answered Cancel.
ErrSummaryTruncatedThe last summarizer in the chain stopped at the output cap (the chain wraps its last error); raise SummaryMaxTokens or Reserve.
ErrInvalidCompactionA 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.
ErrCompactConfigCreate or Open with a known window and Reserve or KeepRecent too large for it.
ErrNotPinnablePin on an entry that contributes no message.
ErrNoEntryPin or a plan names an entry the session does not hold, or Uncompact finds no compaction on the path.
ErrAwaitingApprovalCompact or ApplyCompaction while approval requests are pending.
ErrBusyCompact, ApplyCompaction or Uncompact while a turn runs.

TrimRecord, TrimStub, Compaction.Trim and these sentinels arrived in thread 0.9.0.

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:

sessions/compaction.go
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)
}

sessions/compaction.go on GitHub

marker: session manual replaced 4 messages with 1
  • What it carries. Counts and a hash, never messages. It has the event name weft.compaction and the attributes weft.compaction.scope = session, weft.compaction.hash (the SHA-256 of the entry’s JSON), weft.content = none, gen_ai.agent.name and the session’s run metadata (weft.session.id, weft.turn, weft.public_id, …), but not the gen_ai.conversation.id and session.id mirrors 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.0 summarizer_model ({provider, name}) and summarizer_usage say 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 Session drives. Still held at Close, it goes out then with held: true in its body, filed under no run and keyed by weft.session.id, as the state log’s records are: a store indexes it by session, and no run’s Compactions reads it.
  • The summarizer’s calls. Since 0.18.0 every summary model call, of a compaction or a SummarizeLeft branch, is also a chat span with weft.chat.role summarizer, 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.SummarizerUsage sums it per session, apart from Usage, and Studio prices it at read time (See what a run cost). A failed call’s span carries error.type summarizer.
  • Who reads it. No reader applies it: the next run’s input record already holds the compacted context. obsdb.DB.Compactions returns a run’s run-scope compaction views first, then the session markers filed under it, scope obsdb.CompactionSession. Studio’s run page draws it at the top as “session compaction · after this run”, with its token line and counts.

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:

sessions/compaction.go
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 sessions/compaction.go on GitHub

View on GitHub · run it from docs-site/examples:

Terminal window
go run ./sessions compaction
go test ./sessions
== automatic
compaction: threshold first kept: e_a4 tokens before: 81
user: "<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 window
level=WARN msg="thread: no context window known for this session; automatic compaction stays off until one is configured (manual Compact always works)"
== by hand
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: true
after Compact: Goal: refund order 1234. | 4 messages
== hook
cancel: true entries written: 0
replace: from_hook Order 1234: refund started.
proceed: manual | the summarizer saw: I am [email].
== trim
compaction: trim | summary empty: true | stubs: 1
call_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
== overflow
turn: <nil> | Order 5678 is processing. | run: s_overflow-t3
compaction: overflow
== marker
marker: session manual replaced 4 messages with 1

The 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.

  • Set ContextWindow for 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, ApplyCompaction and Uncompact fail with ErrBusy while a turn runs; wait for the turn, or call s.WaitIdle. (Source: thread/compaction.go:290-308, 606-611)
  • Do not offer Uncompact as “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. With ContextWindow the latest compaction can be many turns back. Undo right after compacting, or keep s.Leaf() from before the undo and Branch back to it. To keep the raw history in view, read s.Entries() or s.Path(leaf) instead. (Source: thread/compaction.go:594-635)
  • Decide approvals before compacting. A pending approval holds the tail raw: Compact fails with ErrAwaitingApproval and the trigger waits. (Source: thread/compaction.go:123-126; ADR 0021 amendment 2026-09-29)
  • Redact in BeforeCompact, not after. The hook’s Preparation.Messages is 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.Wait may 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. Summaries sums CompactionEntry.SummarizerUsage, the accepted summary’s call alone. Rejected or truncated retries, a failed SummaryModel before the fallback, a compaction that failed and every SummarizeLeft summary are not counted. Without a SummaryModel, a compaction that is always rejected costs two summary calls at each trigger, and Summaries stays 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 MinTurnsBetween and MaxPerSession never count it. Once the gap from the last stored compaction has passed, it is retried at every trigger with no backoff. Each failure logs thread: automatic compaction failed at 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 manual s.Compact, a thread.TriggerFunc that decides on something other than the reported number (it still receives the TriggerInput), and the overflow re-run when the provider’s error maps to weft.ErrContextOverflow. An OpenAI-compatible server without include_usage reports 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.Say and wefttest.ToolCalls report a fixed 10 input tokens, so the signal stays at 10 however long the scripted conversation grows. Set the reported input on each turn with Turn.WithUsage, as sessions/compaction.go does: 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’s Data is 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 URL FilePart, or pass WithEstimator an Estimator that 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 with SummaryMaxTokens or Reserve. (Source: thread/compaction.go:98-103)

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