Search⌘ K
AI Features

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.

long_session.py · Python 3.14.0
from note_store import NOTE_STORE
from render_request import count_tokens
NOTES = {note["doc_id"]: note["text"] for note in NOTE_STORE}
COMPACT_THRESHOLD = 400 # tokens; a real assistant would use a share of its context window
TURNS = [ # (question, tool, pruned tool result): nine new results, nothing to dedup or extract
("What changed in checkout around 14:00?", "get_recent_changes",
"14:02 deploy v2.31 (adds a tax-service call); 14:03 flag new_tax_display turned on"),
("Show checkout p99 latency since 13:50.", "get_metrics",
"13:50-14:04 p99 170-190 ms; 14:05 p99 2400 ms; 14:06-14:09 p99 2300-2600 ms"),
("What does the current runbook say?", "read_note", f"[note-1] {NOTES['note-1']}"),
("How quickly does turning off a flag work?", "read_note", f"[note-3] {NOTES['note-3']}"),
("Can we restart Redis to speed things up?", "read_note", f"[note-8] {NOTES['note-8']}"),
("Turn off new_tax_display.", "set_flag", "14:11 new_tax_display turned off for checkout"),
("Did latency recover?", "get_metrics", "14:11 p99 2350 ms; 14:12 p99 640 ms; 14:13 p99 210 ms"),
("Who owns the tax service?", "read_note", f"payments team; [note-6] {NOTES['note-6']}"),
("Should we still roll back v2.31?", "search_documents", f"[note-2] {NOTES['note-2']}"),
]
HISTORY = [{"turn": n, "question": q, "tool": tool, "result": result}
for n, (q, tool, result) in enumerate(TURNS, start=1)]
def render(history):
return "\n".join(f"Q{t['turn']}: {t['question']}\n {t['tool']} -> {t['result']}" for t in history)
if __name__ == "__main__":
for n in range(1, len(HISTORY) + 1):
tokens = count_tokens(render(HISTORY[:n]))
print(f"after turn {n}: {tokens:>4} tokens{' <- over threshold' if tokens > COMPACT_THRESHOLD else ''}")

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