Compress, Don’t Truncate: Building a Context Gateway Agents Can Audit

  created  by  Sherlock {{tag}}
创建于 2026年10月30日 10:56:48 最后修改于 2026年10月30日 10:56:48

Most agent outages are blamed on the model. The postmortem then discovers something less flattering: the model was asked to reason inside a junk drawer. A wrong product ID entered the working summary and never left.

A 40k-token tool dump drowned the system prompt. Two retrieved policies contradicted each other, and the agent split the difference into a confident mistake.

Context engineering is the discipline of stopping that junk drawer from becoming the operating system. Compression is the sharpest tool in the kit, and also the easiest to misuse. Silent truncation is not compression.


Summarizing without lineage is not compression. “Stuff everything until the window sings” is how you buy distraction at retail prices.

What production teams need is a context gateway: a versioned pipeline that normalizes inputs, scores what deserves a seat, transforms bulky material into reversible forms, enforces policy budgets, and emits an audit trail of what was kept, dropped, and why.

Four failure modes that look like “the model got dumber”


Figure: Context engineering for production agents (Splunk blog art)

Figure: Context engineering for production agents (Splunk blog art)


Splunk’s production context guide restates a taxonomy that keeps showing up in real traces.

Context poisoning: a hallucination lands in goals or state and gets re-read every turn, so the agent argues for a false world with increasing confidence.

Context distraction: the window grows so large that the model pattern-matches history instead of using trained knowledge, sometimes summarizing the pile while ignoring instructions.


Context confusion: superfluous tools and snippets get used because they are present; tool menus that look generous become cognitive tax.

Context clash: contradictory shards accumulate across turns; multi-turn “sharded” benchmarks have shown average drops near 39 percent when information arrives piecemeal and conflicts with itself.

If your dashboard only shows token counts and latency, you will misdiagnose all four as “needs a bigger model.” A bigger model with a poisoned goal section is a more eloquent wrong agent.


Why truncation fails the audit test


Figure: Blind truncation vs audited compression

Figure: Blind truncation vs audited compression

Truncation is attractive because it is deterministic and cheap to implement: keep the system prompt, keep the last N turns, drop the middle. It fails three production requirements.

First, it is not policy-aware. The discarded middle might contain the only signed constraint that made an action legal. Second, it is not reversible. Once dropped, the agent cannot fetch the original when a later step needs the exact table.


Third, it is not explainable. On-call cannot answer “which evidence did we hide from the model?” without replaying folklore.

Compression earns its keep when it preserves recoverability.

The Manus-style pattern of treating the filesystem as external memory, returning a short summary plus a pointer, is the canonical example: ratios around 100:1 are possible when the full artifact remains fetchable. The summary is a working set.


The artifact is still the source of truth.

A practical five-stage gateway


Figure: Normalize → Score → Transform → Gate → Trace

Figure: Normalize → Score → Transform → Gate → Trace

Patterns described across industry write-ups, including the context compression gateway sketch, converge on a pipeline you can implement without waiting for a research breakthrough.


Stage one: intake normalization. Wrap every candidate chunk in a canonical envelope: source type (doc, chat, tool, log), risk class, freshness, owner, lineage id. Policy checks should run before tokenization.

If you cannot name the owner of a chunk, you are not ready to feed it to a model that can act.

Stage two: relevance plus novelty scoring. Semantic relevance to the current task is necessary and insufficient. Novelty against already selected chunks stops the classic failure where the same paragraph appears three times in slightly rewritten form.


Dual scoring is how you fight both under-retrieval and self-plagiarism bloat.

Stage three: deterministic transforms. Strip boilerplate, collapse verbose logs into event summaries, convert wide tables into compact key-value bullets when precision survives, and keep verbatim spans for legal or policy text.

Treat the transform list as a versioned package. When quality regresses, you need to replay the same compressor, not “whatever the prompt did last Tuesday.”


Stage four: policy gate. Enforce hard budgets by risk tier, forbid classes such as secrets or regulated identifiers, and require citations before high-impact actions. If policy blocks context, return a machine-readable refusal payload.

Silent truncation here is how compliance incidents are born.

Stage five: trace emission. Write selected versus rejected chunk ids, token counts before and after, policy decisions, and the model routing choice that followed. This is the flight recorder. Without it, compression debates become theology.


A workable starting budget per call, adjusted to your domain, often looks like: system and policy 10–15 percent, user task 15–20 percent, retrieved context 35–45 percent, tool schemas and examples 15–20 percent, response reserve 10–15 percent.

Many teams over-allocate retrieval and under-allocate response reserve, then wonder why answers feel clipped.

Five architectural patterns that make compression safe


Offloading: externalize high-token tool payloads; pass metadata and summaries; retrieve on demand.


Isolation: give parallel research subagents private windows so one noisy branch cannot contaminate another; beware coding tasks where isolation creates conflicting edits.

Retrieval: combine embeddings, exact search, and structured indexes; complexity is not automatically quality. Compaction: summarize at high-water marks, but prefer offload-plus-summary over irreversible pruning.

Caching: KV-cache discipline can yield order-of-magnitude cost differences, yet caching a rotten context only makes rot cheaper and faster.


Anti-patterns deserve the same ink. Mutating earlier turns busts caches and multiplies spend; prefer append-only designs. Loading every tool up front degrades selection quality.

Aggressive pruning without recovery deletes the one fact you will need at step seventeen. Dropping error messages teaches the agent to retry the same failure with fresh confidence.

Observe compression like you observe decisions


Figure: Poison, distraction, and conflict look like a dumber model

Figure: Poison, distraction, and conflict look like a dumber model


Operability writing on LLM systems argues for a decision layer on top of classic RED metrics. Context gateways need the same seriousness.

Track tokens in versus tokens after compression, cache hit rate, fraction of retrieval rejected by novelty, policy block rate, and downstream task success.

Alert when compression ratio spikes while human override rate rises: you may be saving money by deleting the plot.


Session-level metrics tell you whether goals completed. Step-level metrics tell you whether tool choice and context adherence held at each hop.

The useful debug question is not “how big was the window?” It is “which chunks were visible when the agent chose tool X?” If your trace cannot answer that, you do not have context observability; you have log volume.

Heuristics for when to bother


Under roughly 10k tokens of honest working set, append-only plus basic caching may be enough. Between 10k and 50k, boundary compression and cache hygiene start paying rent. Past 50k, offloading and selective retrieval usually beat heroic summarization.


Past 100k, multi-agent isolation becomes a serious option for parallel read-only work. Thresholds are not laws; they are prompts to measure your own distraction point.

Studies and field notes repeatedly flag deterioration as contexts grow large and as tool counts climb past a comfortable handful. Instrument your own cliffs instead of worshipping someone else’s.

A worked example: invoice agent without the junk drawer


Imagine an accounts-payable agent that reads supplier emails, opens attachments, and posts draft entries. Without a gateway, a single PDF extraction tool returns 20k tokens of layout noise into the chat.


The next retrieval adds three near-duplicate policy paragraphs. A prior turn mislabeled the vendor’s currency; that wrong currency sits in the running summary and poisons every later calculation.

With a gateway, the PDF lands in object storage; the model receives a 400-token extraction summary, line-item table as compact KV bullets, and a pointer. Novelty scoring drops two of the three policy duplicates.

The currency field is typed in the state envelope with a provenance stamp from the ERP master data, not from free-text memory.


When the agent prepares a posting action, the policy gate demands a citation to the matched payment term chunk; if that chunk was rejected earlier, the gate fails closed and asks for retrieval instead of guessing.

On-call can open the flight recorder and see rejected chunk ids, the compressor version, and the exact evidence present at posting time.

That is the difference between “the model hallucinated a currency” and “we never gave it the master-data field.” One is a training complaint. The other is an engineering fix.


Cost coupling: compression and routing share a ledger


Compression decisions change routing decisions. A thread that stays under a long-context threshold can stay on a cheaper model; a thread that keeps dragging full tool dumps may be wrongly escalated to a long-context premium tier.

Put both behind the same decision_id. When finance asks why spend jumped, you should be able to split “tier mix changed” from “tokens per tier changed.” Most bills move on the second lever while teams argue about the first.

Also cap retries that re-expand context. A flaky validator that re-fetches the full page on every attempt will erase your compression wins and look like model flakiness in the metrics. Emit context_reexpansion_total with reasons.


If the reason is “summary insufficient,” improve the summary schema; do not silently widen the window for every nervous retry.

Team ownership


Platform owns the gateway code, compressor versions, and default budgets. Domain teams own risk classes, citation rules, and which verbatim spans must never be paraphrased. Security owns forbidden data classes and audit retention for tier-three raw payloads.

If those owners are the same person wearing three hats, write the hats down anyway. Compression policy without owners becomes a prompt comment that nobody dares to delete.


Editorial close: make every token earn its seat


The winning stance is not “always compress” or “never compress.” It is “no token enters the window without a job, an owner, and a way back to the source.” A context gateway turns that stance into machinery. It will not make a weak policy smart.

It will stop a strong model from drowning in your unstructured past.

If you ship agents that act on money, code, or customer state, treat silent truncation as a production bug. Compress with lineage. Budget with policy. Emit a flight recorder.


Then, when the model fails, you can argue about the decision that was made with the evidence that was actually present, instead of blaming intelligence for an archival problem.

评论区
评论
{{comment.creator}}
{{comment.createTime}} {{comment.index}}楼
评论

Compress, Don’t Truncate: Building a Context Gateway Agents Can Audit

Compress, Don’t Truncate: Building a Context Gateway Agents Can Audit

Most agent outages are blamed on the model. The postmortem then discovers something less flattering: the model was asked to reason inside a junk drawer. A wrong product ID entered the working summary and never left.

A 40k-token tool dump drowned the system prompt. Two retrieved policies contradicted each other, and the agent split the difference into a confident mistake.

Context engineering is the discipline of stopping that junk drawer from becoming the operating system. Compression is the sharpest tool in the kit, and also the easiest to misuse. Silent truncation is not compression.


Summarizing without lineage is not compression. “Stuff everything until the window sings” is how you buy distraction at retail prices.

What production teams need is a context gateway: a versioned pipeline that normalizes inputs, scores what deserves a seat, transforms bulky material into reversible forms, enforces policy budgets, and emits an audit trail of what was kept, dropped, and why.

Four failure modes that look like “the model got dumber”


Figure: Context engineering for production agents (Splunk blog art)

Figure: Context engineering for production agents (Splunk blog art)


Splunk’s production context guide restates a taxonomy that keeps showing up in real traces.

Context poisoning: a hallucination lands in goals or state and gets re-read every turn, so the agent argues for a false world with increasing confidence.

Context distraction: the window grows so large that the model pattern-matches history instead of using trained knowledge, sometimes summarizing the pile while ignoring instructions.


Context confusion: superfluous tools and snippets get used because they are present; tool menus that look generous become cognitive tax.

Context clash: contradictory shards accumulate across turns; multi-turn “sharded” benchmarks have shown average drops near 39 percent when information arrives piecemeal and conflicts with itself.

If your dashboard only shows token counts and latency, you will misdiagnose all four as “needs a bigger model.” A bigger model with a poisoned goal section is a more eloquent wrong agent.


Why truncation fails the audit test


Figure: Blind truncation vs audited compression

Figure: Blind truncation vs audited compression

Truncation is attractive because it is deterministic and cheap to implement: keep the system prompt, keep the last N turns, drop the middle. It fails three production requirements.

First, it is not policy-aware. The discarded middle might contain the only signed constraint that made an action legal. Second, it is not reversible. Once dropped, the agent cannot fetch the original when a later step needs the exact table.


Third, it is not explainable. On-call cannot answer “which evidence did we hide from the model?” without replaying folklore.

Compression earns its keep when it preserves recoverability.

The Manus-style pattern of treating the filesystem as external memory, returning a short summary plus a pointer, is the canonical example: ratios around 100:1 are possible when the full artifact remains fetchable. The summary is a working set.


The artifact is still the source of truth.

A practical five-stage gateway


Figure: Normalize → Score → Transform → Gate → Trace

Figure: Normalize → Score → Transform → Gate → Trace

Patterns described across industry write-ups, including the context compression gateway sketch, converge on a pipeline you can implement without waiting for a research breakthrough.


Stage one: intake normalization. Wrap every candidate chunk in a canonical envelope: source type (doc, chat, tool, log), risk class, freshness, owner, lineage id. Policy checks should run before tokenization.

If you cannot name the owner of a chunk, you are not ready to feed it to a model that can act.

Stage two: relevance plus novelty scoring. Semantic relevance to the current task is necessary and insufficient. Novelty against already selected chunks stops the classic failure where the same paragraph appears three times in slightly rewritten form.


Dual scoring is how you fight both under-retrieval and self-plagiarism bloat.

Stage three: deterministic transforms. Strip boilerplate, collapse verbose logs into event summaries, convert wide tables into compact key-value bullets when precision survives, and keep verbatim spans for legal or policy text.

Treat the transform list as a versioned package. When quality regresses, you need to replay the same compressor, not “whatever the prompt did last Tuesday.”


Stage four: policy gate. Enforce hard budgets by risk tier, forbid classes such as secrets or regulated identifiers, and require citations before high-impact actions. If policy blocks context, return a machine-readable refusal payload.

Silent truncation here is how compliance incidents are born.

Stage five: trace emission. Write selected versus rejected chunk ids, token counts before and after, policy decisions, and the model routing choice that followed. This is the flight recorder. Without it, compression debates become theology.


A workable starting budget per call, adjusted to your domain, often looks like: system and policy 10–15 percent, user task 15–20 percent, retrieved context 35–45 percent, tool schemas and examples 15–20 percent, response reserve 10–15 percent.

Many teams over-allocate retrieval and under-allocate response reserve, then wonder why answers feel clipped.

Five architectural patterns that make compression safe


Offloading: externalize high-token tool payloads; pass metadata and summaries; retrieve on demand.


Isolation: give parallel research subagents private windows so one noisy branch cannot contaminate another; beware coding tasks where isolation creates conflicting edits.

Retrieval: combine embeddings, exact search, and structured indexes; complexity is not automatically quality. Compaction: summarize at high-water marks, but prefer offload-plus-summary over irreversible pruning.

Caching: KV-cache discipline can yield order-of-magnitude cost differences, yet caching a rotten context only makes rot cheaper and faster.


Anti-patterns deserve the same ink. Mutating earlier turns busts caches and multiplies spend; prefer append-only designs. Loading every tool up front degrades selection quality.

Aggressive pruning without recovery deletes the one fact you will need at step seventeen. Dropping error messages teaches the agent to retry the same failure with fresh confidence.

Observe compression like you observe decisions


Figure: Poison, distraction, and conflict look like a dumber model

Figure: Poison, distraction, and conflict look like a dumber model


Operability writing on LLM systems argues for a decision layer on top of classic RED metrics. Context gateways need the same seriousness.

Track tokens in versus tokens after compression, cache hit rate, fraction of retrieval rejected by novelty, policy block rate, and downstream task success.

Alert when compression ratio spikes while human override rate rises: you may be saving money by deleting the plot.


Session-level metrics tell you whether goals completed. Step-level metrics tell you whether tool choice and context adherence held at each hop.

The useful debug question is not “how big was the window?” It is “which chunks were visible when the agent chose tool X?” If your trace cannot answer that, you do not have context observability; you have log volume.

Heuristics for when to bother


Under roughly 10k tokens of honest working set, append-only plus basic caching may be enough. Between 10k and 50k, boundary compression and cache hygiene start paying rent. Past 50k, offloading and selective retrieval usually beat heroic summarization.


Past 100k, multi-agent isolation becomes a serious option for parallel read-only work. Thresholds are not laws; they are prompts to measure your own distraction point.

Studies and field notes repeatedly flag deterioration as contexts grow large and as tool counts climb past a comfortable handful. Instrument your own cliffs instead of worshipping someone else’s.

A worked example: invoice agent without the junk drawer


Imagine an accounts-payable agent that reads supplier emails, opens attachments, and posts draft entries. Without a gateway, a single PDF extraction tool returns 20k tokens of layout noise into the chat.


The next retrieval adds three near-duplicate policy paragraphs. A prior turn mislabeled the vendor’s currency; that wrong currency sits in the running summary and poisons every later calculation.

With a gateway, the PDF lands in object storage; the model receives a 400-token extraction summary, line-item table as compact KV bullets, and a pointer. Novelty scoring drops two of the three policy duplicates.

The currency field is typed in the state envelope with a provenance stamp from the ERP master data, not from free-text memory.


When the agent prepares a posting action, the policy gate demands a citation to the matched payment term chunk; if that chunk was rejected earlier, the gate fails closed and asks for retrieval instead of guessing.

On-call can open the flight recorder and see rejected chunk ids, the compressor version, and the exact evidence present at posting time.

That is the difference between “the model hallucinated a currency” and “we never gave it the master-data field.” One is a training complaint. The other is an engineering fix.


Cost coupling: compression and routing share a ledger


Compression decisions change routing decisions. A thread that stays under a long-context threshold can stay on a cheaper model; a thread that keeps dragging full tool dumps may be wrongly escalated to a long-context premium tier.

Put both behind the same decision_id. When finance asks why spend jumped, you should be able to split “tier mix changed” from “tokens per tier changed.” Most bills move on the second lever while teams argue about the first.

Also cap retries that re-expand context. A flaky validator that re-fetches the full page on every attempt will erase your compression wins and look like model flakiness in the metrics. Emit context_reexpansion_total with reasons.


If the reason is “summary insufficient,” improve the summary schema; do not silently widen the window for every nervous retry.

Team ownership


Platform owns the gateway code, compressor versions, and default budgets. Domain teams own risk classes, citation rules, and which verbatim spans must never be paraphrased. Security owns forbidden data classes and audit retention for tier-three raw payloads.

If those owners are the same person wearing three hats, write the hats down anyway. Compression policy without owners becomes a prompt comment that nobody dares to delete.


Editorial close: make every token earn its seat


The winning stance is not “always compress” or “never compress.” It is “no token enters the window without a job, an owner, and a way back to the source.” A context gateway turns that stance into machinery. It will not make a weak policy smart.

It will stop a strong model from drowning in your unstructured past.

If you ship agents that act on money, code, or customer state, treat silent truncation as a production bug. Compress with lineage. Budget with policy. Emit a flight recorder.


Then, when the model fails, you can argue about the decision that was made with the evidence that was actually present, instead of blaming intelligence for an archival problem.


Compress, Don’t Truncate: Building a Context Gateway Agents Can Audit2026-10-30Sherlock

{{commentTitle}}

评论   ctrl+Enter 发送评论