Session Compaction and Restorable Filesystem Offloading
Explore how session compaction controls growing conversation history after tool-result pruning reaches its limits. You’ll archive older turns to a filesystem, preserve recent context, design structured summaries around required facts, test save-first behavior, and restore original details without relying on a model call.
We'll cover the following...
In the previous lesson, we built a pruning hook that reduces the size of each tool result before adding it to the conversation history. It removes duplicate results and unnecessary fields and shortens long logs. However, pruning operates on individual tool results. During a prolonged incident, the conversation can accumulate many relevant, compact tool results: a deployment change lookup, a metrics query, multiple runbook reads, and a feature flag update. Even when individual results cannot be pruned further, the conversation history continues to grow.
In this lesson, we'll observe how a session exceeds a configured token threshold despite tool-result pruning. We'll then implement compaction. When the session exceeds the token threshold, we'll archive older turns in a file, replace them in the conversation history with a summary, and retain recent turns unchanged. We'll verify that archived turns can be restored from the file, that the summary preserves relevant facts, and that compaction works without a model call.
A session with nothing to prune
Let's construct a nine-turn conversation based on our incident scenario. Each turn introduces a new question and a concise, distinct tool result, leaving nothing for the pruning hook to remove. The session captures the incident timeline: the v2.31 deployment and the new_tax_display flag, the latency spike, the runbook, disabling the feature flag, service recovery, and an unresolved rollback decision.
In the code above:
Line 5: We set
COMPACT_THRESHOLD, the session size at which we’ll compact. Our notes are short, so we use 400 tokens. A real assistant would set it as a share of its context window.Lines 7–19: We write the nine turns as a question, a tool, and the tool’s already-pruned result.
Lines 22–23: We number the turns and store each one as a dictionary in
HISTORY.Lines 26–27: We define
render(), which turns a list of turns into the text the model would see.Lines 30–33: We measure the session after each turn and mark when it passes the threshold.
The session grows with every turn and crosses the threshold at turn ...