Append-Only Context for LLM Agents: Why You Should Never Rewrite the Prefix

    This article explains a core constraint of modern reasoning-oriented LLM APIs: the conversation history prefix is immutable, and any modification invalidates the accumulated reasoning state. It covers why rewriting the prefix breaks reasoning reuse, which five common context-management practices violate this rule, and how to replace them with an append-only event-stream design. You will also find guidance on cache-friendly prompt placement, a migration and acceptance checklist, and engineering conventions for building reliable AI agents.

    1. An Underestimated Constraint: Conversation History Is Append-Only

    As LLM applications evolve from single-turn Q&A to multi-turn agents, context management has become a distinct engineering discipline. Over the past two years, the community has accumulated many seemingly reasonable techniques: dynamically assembling system prompts per scenario, rewriting the opening based on retrieval results, truncating overly long tool logs, compressing early conversation into summaries, switching output structures by task phase, and adding or removing available tools based on permissions.

    Starting with a certain class of newer reasoning-oriented chat APIs, all of these approaches run into the same hard constraint: the history prefix of a multi-turn session is treated as an immutable region. Any modification to content that has already been sent is classified as a prefix change, which causes the accumulated reasoning state after that point to be discarded entirely. This is a fairly common design choice among current reasoning-oriented APIs in the industry, though specific implementations and terminology vary across platforms. As a default engineering assumption, design for “immutable prefix, changes appended afterward.”

    This constraint has three direct consequences:

    • Cost: once the reasoning state is invalidated, the model must re-derive it, increasing the consumption of reasoning tokens.
    • Latency: re-reasoning means longer time to first token and longer overall response time, degrading the interactive experience.
    • Quality: when reasoning cannot be effectively reused, output stability and consistency decline.

    A more critical point is often overlooked: this discarding behavior is typically enforced by the platform as part of its safety policy, not merely as a billing choice. In other words, even if you are willing to bear the extra cost, you may not be able to recover the original reasoning continuity.

    2. Why Rewriting the Prefix Breaks Reasoning Reuse

    Reasoning models differ fundamentally from traditional text completion. In the traditional mode, the context is just an input token sequence; changing one character changes exactly one character, with a linear and predictable cost. A reasoning model, however, leaves explicit reasoning artifacts at every turn, and these artifacts are strongly bound to the context prefix that existed when they were generated: the prefix determined the facts, constraints, and tool returns the model saw at that time, and the reasoning chain was built on top of that set of facts.

    Once the prefix is rewritten, a semantic break occurs: the premises that subsequent reasoning depends on no longer exist. Continuing to reuse the old reasoning means letting the model keep reasoning from false premises; not reusing it means starting over from scratch. A more robust engineering abstraction is to treat the session as an event stream that only allows appends: history is an accomplished fact, and changes can only be recorded as new events at the end.

    3. Why Five Common Practices All Cross the Line

    The following five context-management actions are extremely common in practice, and under the “immutable prefix” assumption they all qualify as prefix modifications:

    1. Dynamically assembling system prompts: rewriting the opening instructions each turn based on retrieval or scenario.
    2. Truncating tool returns: going back to compress tool results in the history when logs are too long.
    3. Summarizing history: replacing multiple early turns with a summary once a length threshold is exceeded.
    4. Switching output structures: changing the field definitions of structured output by phase.
    5. Dynamically adjusting the tool list: adding or removing callable tools based on permissions or phase.

    A team maintaining a code-review agent once ran a self-audit: their context-trimming logic was written with considerable care, yet it hit four of the five items. What had previously been regarded as “optimization” became, under the new constraint, a persistent source of reasoning invalidation.

    4. The Alternative Paradigm: Record Changes as a New Entry at the End

    The idea is not complicated: do not modify anything already sent; treat the “configuration change” itself as a new message appended to the end. Common mappings are as follows (described as general practices, not tied to specific API names):

    • To adjust reasoning effort: keep request-level parameters unchanged and append a configuration-change record at the end.
    • To change the output structure: likewise declare new field constraints via an appended configuration-change record.
    • To restrict or expand tools: append an available-tools declaration, or constrain the current turn’s scope with an allow list.
    • To correct the opening instructions: do not go back and edit; instead append a new developer instruction at the end that declares the override relationship.
    • To shorten tool output: complete the trimming before the content is first sent to the model, and never modify it afterward.

    An illustrative message organization:

    1. [developer] Fixed responsibilities and global constraints (never modified once written)
    2. [user] First-turn task
    3. [assistant] Reply and reasoning artifacts
    4. [tool] Tool result (trimmed before first entering the context)
    5. [developer] Config change: output structure switches to v2 from this turn on
    6. [user] Second-turn task

    Recommended engineering conventions to write into your coding standards:

    • Context-building functions provide append semantics only and expose no edit/replace.
    • All trimming is completed before insertion; content is read-only once inserted.
    • Changes are recorded as explicit event types for easy auditing and replay.
    • Session snapshots persist the full event stream when stored, avoiding “rewrite history” style fixes.

    5. Easily Overlooked Billing and Caching Details

    Another frequent pitfall concerns the placement of fixed instructions. When the top-level instruction field is positioned after the input sequence, it cannot enter the cacheable prefix region, and the fixed portion is billed as uncached input. The engineering fix is to migrate long-term stable responsibility descriptions, output specifications, and safety constraints into the first developer message of the input sequence, and to keep it byte-for-byte stable, including punctuation, whitespace, and ordering. Cache-friendly prefixes share one common trait: they are byte-level invariant.

    This yields a general principle: place and freeze anything “long-term stable” at the front, and place and append anything that “will change” at the back.

    6. Migration and Acceptance Checklist

    • Inventory: list all code paths that modify historical messages and mark their risk level.
    • Refactor: rewrite modification operations as end-appends, and move trimming ahead of insertion.
    • Stabilize: freeze the fixed prefix and verify byte-level consistency of the serialization result.
    • Observability: record new tokens per turn, number of reasoning recomputations, time to first token, and cache hit rate.
    • Regression: use a fixed test set to compare output consistency and cost curves before and after the refactor.

    In agent practice on platforms such as Baidu AI Cloud, this kind of “event-stream context plus prefix freezing” design applies as well: keeping session logs with a log service, passing long-running task state asynchronously through object storage or message queues, and observing resources and call chains via container platforms and monitoring/alerting systems all enable traceable, auditable context evolution without modifying history.

    7. Conclusion

    “Append only, never rewrite” may look like a plain engineering discipline, but it is in fact the first-principle constraint of context architecture in the era of reasoning-oriented LLMs. It uniformly rewrites optimization techniques that once relied on “going back to patch things” into an event-stream design that “declares changes going forward.” For developers, the earlier this constraint is written into the abstraction layer and coding standards, the more reliably you can balance cost, latency, and output quality.