Context lifecycle: select, inject, compress, expire

Context is not a one-off prompt. It is built, shaped, shrunk and retired on every call, and the memory tiers behind it decide what survives from one step to the next.

Context lifecycle in 60 seconds

  • Four stages: selection, injection, compression, and expiration with refresh.
  • Hallucination is often a context problem: if the right facts are absent or buried, the model fills the gap. Tell it to answer only from what it was given.
  • Bigger windows are not free: more tokens mean slower first words, higher cost, and in many tests worse accuracy for facts placed in the middle.
  • Three memory tiers: working (this call), short-term (this session), long-term (kept and searchable).
  • Typical failures: stuffing, stale loops, generic retrieval, mixed-up templates and memory that only grows.

The problem it solves

An agent that runs for more than a few steps accumulates material: tool outputs, earlier answers, retrieved passages, user corrections. If every step simply appends to the prompt, the window fills with things that were useful ten steps ago. Costs rise, the model's attention thins out, and old assumptions keep steering new decisions.

The context engineering page describes how a single context is assembled. This page is about time. What is chosen, how it is laid out, how it is shortened, and when it must be thrown away or rebuilt. Treating these as separate, testable stages makes agent behaviour far easier to reason about.

The four stages

Context moves through selection, injection, compression and expiry, with feedback driving refreshes.

Stage 1: selection

Selection decides which candidates are even considered. A single search method is rarely enough. Dense vector search finds passages with similar meaning. Keyword scoring finds exact names, codes and rare terms that embeddings blur. Graph traversal finds items that are linked, such as a customer, their orders and the policy that applies to each. Combining the three, then re-ranking, usually beats any one.

What drives the choice is the situation: the user's intent, the task type, the risk of getting it wrong, the caller's role and the time. The same corpus should give different context to different agents. A support agent and an auditing agent may read the same ticket history, but they need different slices of it.

Stage 2: injection

Injection is how selected items are placed in the prompt. Use a template with named sections: system instructions, user and session facts, retrieved evidence, a few worked examples and the required output schema. Order and grouping matter. Evidence about one topic should sit together, and instructions should not be scattered through the retrieved text.

Stage 3: compression

When selected material exceeds the budget, shorten it. Options include a small model that summarises, or deterministic steps such as keeping only the fields a task needs, dropping duplicate lines or collapsing repeated log entries. Deterministic methods are cheaper and predictable. Model-based summaries read better but can lose or invent details.

So summaries need validation. Useful checks include the ratio of perplexity between the original and the summary, token-level KL divergence between the model's output distributions with the full and shortened context, and a chi-square test when the output is a category, such as an approve or reject decision. If the shortened context shifts the outputs too much, the summary is dropping something that matters.

Stage 4: expiration and refresh

Every item should have a reason to leave. Assumptions made early in a task may no longer hold. Prices change, tickets close, a customer corrects themselves. If old items stay, the agent keeps acting on a world that has gone. Retire items by age, by event or by relevance score, and rebuild context when a feedback signal says something moved. For example, a drop in customer satisfaction scores for a car-sharing service could trigger a refresh of the policy and pricing context its agents use.

Hallucination is mostly a context failure

When a model invents a fact, the usual cause is missing or poorly placed evidence, not a mysterious flaw. The cheapest defence is two-part. First, supply the relevant facts. Second, instruct the model to answer only from the supplied context and to say when the answer is not there. That second line turns a confident guess into a visible gap that you can measure and fix.

Token economics

Large context windows invite lazy design: when everything fits, why choose? The cost shows up in three places. Time to first token rises with prompt length. Spend rises with every token on every call, and agents make many calls. And accuracy can fall, because models do not read all positions equally well.

Accuracy tends to dip for facts placed in the middle of a long context.

The study Lost in the Middle (Liu et al., 2023) found that accuracy follows a U shape. Models do best when the relevant passage is near the start or the end, and worst when it sits in the middle. The practical lessons are to keep context short, put the most important evidence and the task at the edges, and avoid padding the middle with marginal items.

  • Context budgets: a fixed token allowance per task type, with a stated rule for what is cut first.
  • Pruning: remove low-scoring items and duplicates before assembly, not after.
  • Caching: keep stable material, such as system instructions and fixed policy text, at the front so a prefix cache can reuse it across calls.

Memory tiers behind the context

Working, short-term and long-term memory differ in lifetime, speed and how they are written.
  • Working memory: the prompt itself. It is rebuilt or reset on each call and holds only what this step needs.
  • Short-term memory: a session cache in a fast in-memory store, living for minutes to hours. It holds the running state of a task, recent turns and intermediate results.
  • Long-term memory: durable facts and experience, written asynchronously to a vector store and a graph, so the write never slows a reply. It is searched on later sessions.

Moving information between tiers is a decision, not an accident. A user's stated preference may be promoted from the session to long-term memory after it has been confirmed twice. A tool result that mattered for one step is dropped when the step ends. See tiered memory and session memory for the storage patterns.

Anti-patterns and their fixes

Anti-patternWhat goes wrongFix
Context stuffingToo many weak items bury the useful ones and inflate cost.Apply a relevance threshold and drop low scores.
Stale data loopsOld facts are retrieved, used, written back and retrieved again.Filter by timestamp metadata and invalidate on events.
Generic retrievalThe user's raw wording does not match how documents are written.Rewrite the query first, using a small model.
Implicit and explicit mismatchThe model cannot tell instructions, user facts and the task apart.Use a structured template with separate sections.
Unbounded memory growthStores swell, searches slow and old noise surfaces.Set a time to live by category.

For the last fix, a simple policy works well. Sensory and live signals live for minutes to hours. Task and session context lives until the task is done. Core knowledge is kept, but re-validated on a schedule so it does not quietly rot.

A worked example

Acme Bank runs an agent that helps staff investigate a disputed card payment over a session of about twenty steps.

  • Selection: at step 1, hybrid search over dispute policy, merchant records and the customer's recent transactions. Items below a 0.55 relevance score are dropped.
  • Injection: a template with sections for rules, case facts, evidence and task. The dispute deadline rule sits at the top, and the question sits at the bottom, so both are in the strong positions.
  • Compression: by step 8 the tool outputs reach 6,000 tokens. A deterministic step keeps only transaction id, amount, date and status. The older narrative is summarised in 150 tokens, and a check confirms the decision on a test case does not change.
  • Expiry: a merchant record fetched at step 2 has a 15-minute limit. At step 14 it is refetched, because the merchant has since been marked as closed.
  • Memory: the session keeps the case state. When the case closes, only the outcome and the reason are written to long-term memory. The raw tool outputs are discarded.

The window stayed under 2,000 tokens, and the stale merchant status was caught.

Building it

A context store with budget, time to live and compression (illustrative) (python)
import time

MAX_TOKENS = 2_000          # budget for the assembled context
COMPRESS_ABOVE = 1_500      # start shrinking before the hard limit
TTL_SECONDS = {             # time to live by category
    "live": 15 * 60,
    "session": 4 * 3600,
    "knowledge": 7 * 24 * 3600,   # kept, but re-validated weekly
}

class ContextStore:
    def __init__(self):
        self.items = []  # each: {text, tokens, category, added_at, score}

    def add(self, text, tokens, category, score):
        self.items.append({"text": text, "tokens": tokens, "category": category,
                           "added_at": time.time(), "score": score})

    def expire(self):
        now = time.time()
        # Drop anything past its time to live for its category.
        self.items = [i for i in self.items
                      if now - i["added_at"] < TTL_SECONDS[i["category"]]]

    def assemble(self) -> str:
        self.expire()
        total = sum(i["tokens"] for i in self.items)
        if total > COMPRESS_ABOVE:
            # Placeholder: shrink the weakest items with a deterministic step
            # first, and a small summariser only if that is not enough.
            self.items = shrink_weakest(self.items, target=COMPRESS_ABOVE)
        # Strongest evidence first, hard stop at the budget.
        used, out = 0, []
        for item in sorted(self.items, key=lambda i: -i["score"]):
            if used + item["tokens"] > MAX_TOKENS:
                break
            out.append(item["text"])
            used += item["tokens"]
        return "\n\n".join(out)

shrink_weakest is a placeholder. In a real build it should log what it removed, so a bad answer can be traced to a bad summary.

Design decisions

  • Time to live per category: decide it up front for live, session and knowledge items, and record the reason. Short lifetimes cost more fetches but cut stale answers.
  • Promotion rules: state when a session item becomes long-term memory, such as after confirmation or at task close, and who may veto it.
  • Write path: make long-term writes asynchronous and idempotent, so a retry never duplicates a memory. See idempotency.
  • Compression policy: prefer deterministic reductions for structured data, and model summaries only for prose, with a validation check.
  • Isolation and deletion: store memory per user or tenant, and support deletion on request across all tiers.
  • Cache friendliness: keep stable text at the front of the prompt, so prefix caching can work.

Measuring it

  • Position sensitivity: run the same questions with the key fact at the start, middle and end, and plot accuracy. This shows how much your model suffers from the U shape.
  • Compression fidelity: compare outputs with full and shortened context, using perplexity ratio, KL divergence or a chi-square test for category outputs.
  • Staleness rate: the share of answers that used an item past its allowed age.
  • Context growth: tokens in the window by step number. A steady climb signals missing pruning.
  • Refresh effectiveness: answer quality before and after a feedback-triggered refresh.
  • Memory hygiene: store size over time, the share of retrieved memories that were used, and the rate of duplicates.

When to use it, and when not to

SituationFormal lifecycle needed?Why
Long-running agents with many stepsYesWithout pruning and expiry the window grows and quality falls.
Facts that change during a taskYesExpiry and refresh stop the agent acting on old values.
Single-turn question answeringLight versionSelection and injection matter. Compression and tiers rarely do.
Users return over days or weeksYesLong-term memory with promotion rules gives continuity without bloat.
Short scripted flows with fixed inputsNoA plain template is enough.

Trade-offs

DimensionEffectWhat to do about it
QualityFresh, short, well-placed context improves accuracy and keeps behaviour steady over long tasks.Test with position and staleness cases before launch.
CostFewer tokens per call, but extra work for summarising, refetching and storage.Track total cost per completed task.
LatencyShorter prompts respond sooner, but refetching and compression add steps.Run compression and long-term writes off the reply path.
ContinuityAggressive expiry can make an agent forget something the user expects it to remember.Agree what must persist, and test it.
ComplexitySeveral stores, lifetimes and rules to operate.Begin with two tiers and add the third when needed.

Compared with caching and plain history

Appending the whole chat history is the simplest approach and works for short chats. It fails on long tasks because nothing is ever removed. Caching, as in the prefix cache page, saves compute on repeated text but does not decide what should be present. The lifecycle decides content. Caching makes the chosen content cheaper to send. The two work well together when stable text is placed first.

What this means for your role

Common mistakes

  • Appending everything to the prompt and relying on a large window to cope.
  • Burying the key evidence in the middle of a long block.
  • Using a model summary without checking that it preserved the details that drive decisions.
  • Writing to long-term memory on the reply path, so slow stores slow every answer.
  • Giving every memory the same lifetime, or no lifetime at all.
  • Retrieving with the user's raw words and never rewriting the query.
  • Skipping the instruction to answer only from supplied context.

Further reading

Good context has a life: it is chosen with care, laid out clearly, shortened honestly and retired on time. Success depends on the architecture around the model: how state is held, which signals take priority, how faults are contained, how fresh data stays, how it is secured and what it costs.

Search topics

↑↓ to move · Enter to open · Esc to close