Skip to content

Hermes Agent context engine: the main model writes the compaction handoff on its cached prompt prefix

Stop compaction when model summaries fail

Elevatormusicc21dfa27a428
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml
index 0a3ce35..3139ca2 100644
--- a/.github/ISSUE_TEMPLATE/bug_report.yml
+++ b/.github/ISSUE_TEMPLATE/bug_report.yml
@@ -122,7 +122,7 @@ body:
id: log
attributes:
label: Redacted compaction diagnostics
- description: Paste relevant warm_compaction lines from logs/agent.log and adjacent plugin warnings about capture, fallback, or fixed summaries. Keep path, reason, elapsed time, token counts, and error class when available. Do not attach the whole log. If absent, state no log line and why.
+ description: Paste relevant warm_compaction lines from logs/agent.log and adjacent plugin warnings about capture, fallback, or aborted compaction. Keep path, reason, elapsed time, token counts, and safe error codes when available. Do not attach the whole log. If absent, state no log line and why.
render: text
validations:
required: true
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d9e81cc..3c09a57 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,15 @@ All notable changes are listed here. The format follows [Keep a Changelog](https
## [Unreleased]
+### Changed
+
+- Remove the fixed summary without a model. If the warm request and model-based fallback cannot produce a usable summary, stop the current compaction pass, preserve its input history, and report safe error codes. Hermes can retry an automatic failure; the plugin does not stop the entire host turn. This includes incomplete or oversized fallback replies and a retained-history layout that cannot fit safely.
+- Keep the fallback on `auxiliary.warm_compaction`; `auto` follows the main chat route. This task stays separate from the built-in compressor's `auxiliary.compression` task.
+
+### Limits
+
+- Hermes controls automatic chat notices through `compression.progress_notices` (default `false`). Its current completion notice is generic. A notice that names the completed warm or model-based fallback path needs a public hook after a confirmed history commit, with no success notice for an error or cancellation. This host dependency is unmet; the plugin does not patch Hermes or use private callbacks.
+
### Fixed
- Match captured content with the stored `api_content` text for context-injected rows. Keep role, tool, and native replay checks. Report each history refusal stage and use the fallback when the capture is ahead of the live history.
@@ -12,7 +21,7 @@ All notable changes are listed here. The format follows [Keep a Changelog](https
- Accept trailing whitespace removal by Hermes from complete text strings, including `api_content`, without a false `source_transform_unsupported` fallback. Keep the captured request prefix unchanged.
- Keep safe request refusal codes in status and logs, instead of the generic `settings_unsupported`.
- Keep the captured `x-opencode-session` header on warm requests, including the header that Hermes adds for OpenCode routes. Refuse unknown headers and header rewrites; send the session value only as an HTTP header.
-- Report `missing_end_marker` or `output_token_limit` when a fallback reply fails the completion check. Incomplete replies still use the fixed summary.
+- Report `missing_end_marker` or `output_token_limit` when a fallback reply fails the completion check. Incomplete replies stop the current compaction pass and preserve its input history.
### Added
@@ -21,7 +30,7 @@ All notable changes are listed here. The format follows [Keep a Changelog](https
- Native provider and conversation checks in CI against the minimum Hermes version and upstream `main`. The conversation checks cover manual and automatic compaction, tools, and saved-session reload.
- Hypothesis tests for native histories, stream events, and capture changes, plus branch coverage reports. These tools are test dependencies only.
- A WARNING for each saved compaction that Hermes confirms without the warm path, with its reason (Hermes copies it to `errors.log`).
-- After 3 confirmed compactions in a row without the warm path, one notice with a hint for each distinct reason, in the logs and at the next automatic compaction when engine status is enabled. The notice has no routine progress text. Later confirmed failures update the pending notice and its fixed-summary count until Hermes shows it.
+- After 3 confirmed compactions in a row without the warm path, one notice with a hint for each distinct reason, in the logs and at the next automatic compaction when engine status is enabled. The notice has no routine progress text. Later confirmed failures update the pending notice until Hermes shows it. Aborted attempts do not count as confirmed compactions.
### Security
@@ -29,7 +38,7 @@ All notable changes are listed here. The format follows [Keep a Changelog](https
## [0.2.0] - 2026-10-06
-First public release.
+First public release. This section records historical behavior; the unreleased changes above remove the fixed summary.
### Added
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 61d9876..6faafc7 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -26,7 +26,7 @@ Include:
Use invented messages that reproduce the failure. State the approximate message count and token count. If no safe reproduction is available, explain that limit. Do not attach real or private histories, generated summaries, full configurations, raw requests, credentials, header/query values, account identifiers, or private local paths. Clearly label synthetic fixtures, synthetic summaries, and fake credential or option values used for tests. Do not enable full request dumps just to complete a report.
-Copy the relevant `warm_compaction:` lines from `logs/agent.log`, and any adjacent plugin warnings about capture, fallback, or fixed summaries. Keep path, reason, elapsed time, token counts, and error class when available. Report `no log line` with a reason when the plugin never loaded or no compaction ran. Review the selected lines before you paste them; do not attach the whole log.
+Copy the relevant `warm_compaction:` lines from `logs/agent.log`, and any adjacent plugin warnings about capture, fallback, or aborted compaction. Keep path, reason, elapsed time, token counts, and safe error codes when available. Report `no log line` with a reason when the plugin never loaded or no compaction ran. Review the selected lines before you paste them; do not attach the whole log.
Run this command in the same terminal environment where Hermes runs, then provide the redacted check results:
diff --git a/README.md b/README.md
index d1c1d22..b81d561 100644
--- a/README.md
+++ b/README.md
@@ -68,7 +68,7 @@ Run these commands in a terminal (PowerShell, Terminal, or any shell) where the
At each compaction, the plugin sends the last main-model request of the session again. It adds the rows that came after that request and one handoff instruction at the end. This is the *warm request*. The server can reuse the cached prefix of the earlier request, so it reads only the new rows. The reply is a Markdown handoff with five headings: Goal, User instructions, Current state, Key facts, and Next step. The plugin replaces the older rows with the handoff and keeps a verbatim tail of recent rows.
-If the warm request cannot run, or if its reply fails the gate, the same compaction attempt uses a fallback summary through the Hermes auxiliary model route. If that also fails, the plugin writes a fixed-format summary without a model request; it keeps the newest earlier summary as a quote. When Hermes cancels an attempt, the history stays unchanged.
+If the warm request cannot run, or if its reply fails the gate, the same compaction attempt uses a model-based fallback summary through the Hermes auxiliary route. If neither path produces a usable summary, the plugin stops the current compaction pass, preserves its original input history, and reports an error with safe codes only. It never creates a summary without a model. Hermes can retry an automatic failure; the plugin cannot stop the entire host turn through its documented API. When Hermes cancels an attempt, the history stays unchanged.
The plugin does this for manual `/compress` and for automatic compaction.
@@ -182,7 +182,7 @@ On Chat Completions routes, the warm request sends the whole earlier request aga
## Fallback model and keys
-The fallback summary uses the auxiliary task `warm_compaction`. Set `auxiliary.warm_compaction.provider` and `auxiliary.warm_compaction.model` to use a different model. The default `auto` uses the main model route. The fallback reply must end with the line `[END OF SUMMARY]`: the auxiliary route reports no finish reason, so a reply without that line counts as cut off. The warning uses `missing_end_marker` when the final line is absent, or `output_token_limit` when the reported output count reaches the 2,048-token limit. A marker earlier in the reply does not pass the check. These cases still use the fixed summary; the plugin cannot confirm completion from the five headings alone. The fallback request is at most about 11,000 tokens: a transcript of about 8,000 tokens, the instruction, and a 2,048-token reply. The focus topic and the memory context are cut to about 1,000 tokens and take their size from the transcript. A fallback model needs a context window of at least 16,000 tokens. Hermes accepts main models with 64,000 tokens or more, so the default route has enough space.
+The fallback summary uses the auxiliary task `warm_compaction`. Set `auxiliary.warm_compaction.provider` and `auxiliary.warm_compaction.model` to use a different model. The default `auto` follows the main chat route. This task is separate from `auxiliary.compression`, which controls the built-in compressor. The fallback reply must end with the line `[END OF SUMMARY]`: the auxiliary route reports no finish reason, so a reply without that line counts as cut off. The error code is `missing_end_marker` when the final line is absent, or `output_token_limit` when the reported output count reaches the 2,048-token limit. A marker earlier in the reply does not pass the check. These cases stop the current compaction pass and preserve its input history; the plugin cannot confirm completion from the five headings alone. The fallback request is at most about 11,000 tokens: a transcript of about 8,000 tokens, the instruction, and a 2,048-token reply. The focus topic and the memory context are cut to about 1,000 tokens and take their size from the transcript. A fallback model needs a context window of at least 16,000 tokens. Hermes accepts main models with 64,000 tokens or more, so the default route has enough space.
For a custom endpoint that needs a key, put the key name in the model settings:
@@ -203,7 +203,7 @@ Hermes writes compaction metadata to `logs/agent.log` in the Hermes home folder:
warm_compaction: path=warm reason=accepted elapsed_s=10.656 prompt_tokens=108021 cached_tokens=107968
```
-- `path` is `warm`, `fallback`, or `fixed`. `unchanged` means that an indivisible native replay block left no room for a valid new history; no compaction was committed.
+- A successful `path` is `warm` or `fallback`. `path=aborted` means that the pass failed without replacing its input history. `reason` records the warm refusal; `fallback_reason` records the safe fallback error code, such as `unavailable`, `gate:<code>`, `summary_too_large`, `quote_capacity`, `capacity`, or `error:<exception class>`. No raw exception text is reported.
- `reason` is `accepted` or the refusal code of the warm request: `disabled`, `no_capture`, `provider_not_allowed`, `api_mode_unsupported`, `auth_unsupported`, `route_changed`, `settings_unsupported`, `request_not_mapping`, `request_options_unsupported`, `request_not_json`, `source_transform_unsupported`, `history_changed`, `capacity`, `cancelled`, `middleware_unavailable`, `middleware_refused`, `middleware_rewrite`, `middleware_repeated`, `middleware_after_capture`, `middleware_order_unknown`, `headers_unknown`, `tls_unknown`, `tls_unverified`, `middleware_changed_reply`, `provider_error`, `timeout`, `incomplete_response`, or `gate:<reason>`. The warm request goes through the Hermes `llm_request` and `llm_execution` middleware, as a main request does.
- `cached_tokens` is `None` when the server does not report it. Then the cache reuse is unknown.
@@ -215,9 +215,17 @@ The engine status (`get_status()`) has the same values in `warm_last`. After a n
Manual `/compress` can report `No changes from compression` when all messages fit in the recent-history tail. Then the plugin has no older history to summarize. The request estimate also includes system instructions and tool definitions, which the plugin does not compress. Use `/context` to see the token counts for each part. This unchanged result does not count as a warm-path failure.
+If both summary paths fail, the plugin raises a compaction error before it can replace the input history. In the inspected Hermes source (`05eecbcd`), manual `/compress` reports that safe error before history installation. The automatic post-tool handler can catch the error and retry the whole turn, up to eight times. Each failed plugin pass preserves its own input history; this does not promise that the host stops immediately or that the whole turn stays unchanged. The plugin reports only safe error codes, not provider response text, credentials, or conversation text. Hermes controls how each surface shows the error. This source review does not qualify a particular UI.
+
+### Automatic completion notices
+
+Set `compression.progress_notices: true` to show routine automatic compaction start and completion notices on chat platforms. The default is `false`. This Hermes setting applies to both this plugin and the built-in compressor. See the [Hermes configuration guide at the inspected source](https://github.com/NousResearch/hermes-agent/blob/05eecbcd972c8737ebc7722ea08aab47fb538043/website/docs/user-guide/configuration.md#L1032).
+
+The current Hermes completion notice is generic: `Context compaction complete`. The documented plugin API cannot label a completed pass as warm compaction or model-based fallback. That label needs a public completion hook that runs only after a confirmed history commit and never reports success for an error or cancellation. This host dependency is unmet. The plugin does not use private callbacks or patch Hermes to add it.
+
### When the warm path keeps failing
-When the warm summary cannot be used, the plugin tries the fallback summary. If that summary cannot be used, it uses the fixed summary. The plugin reports these results:
+When the warm summary cannot be used, the plugin tries the model-based fallback summary. If that summary cannot be used, the current compaction pass stops and preserves its input history. The plugin reports these results:
- Each saved compaction that Hermes confirms without the warm path writes a WARNING with its reason, for example `Warm compaction skipped (provider_error); used the fallback summary`. Hermes copies warnings to `logs/errors.log`.
- A host compatibility failure (`middleware_order_unknown` or `middleware_unavailable`) prepares a notice after the first confirmed failure. It identifies the failed Hermes check and the summary path used. It does not wait for three failures.
@@ -227,7 +235,7 @@ When the warm summary cannot be used, the plugin tries the fallback summary. If
⚠ Warm compaction unavailable: the last 3 compactions did not use the warm summary (provider_error: the server refused the warm request (a provider error, or a gateway that needs a cookie)). Compaction continues with the fallback summary. Details: the warm_compaction lines in logs/agent.log.
```
-- When the fallback summary could not be used, the notice says how many times, and that those compactions used the fixed summary (no model, less detail).
+- When the fallback summary cannot be used, the attempt reports an error. It does not count as a confirmed compaction in the notice streak.
- A warm summary can fail the handoff checks even when the server reports cached tokens. The notice describes the summary result. It does not prove a cache miss, a speed change, or that all details were kept.
- A confirmed warm compaction or a session reset ends the streak. The notice can then show again at the first host compatibility failure, or after 3 other failures. A cancelled or rejected attempt does not count or clear the streak, and `warm: false` is not a failure.
- When the engine's automatic status is disabled, warnings stay in the logs. The engine keeps a pending notice until status is enabled or a confirmed warm compaction or session reset clears it.
@@ -236,7 +244,7 @@ When the warm summary cannot be used, the plugin tries the fallback summary. If
## Results
-All runs used synthetic conversations of 100,000 or more prompt tokens on unpatched Hermes `45871e10`, one session at a time. The records have metadata only. "DGX" is an OpenAI-compatible server on an NVIDIA DGX that reports cached tokens. "LM Studio 4B" is LM Studio with a Qwen3.5 4B model; it reports no cached-token counter.
+These are historical results from the versions and settings in the linked records. They do not test the current stop-on-failure behavior. All runs used synthetic conversations of 100,000 or more prompt tokens on unpatched Hermes `45871e10`, one session at a time. The records have metadata only. "DGX" is an OpenAI-compatible server on an NVIDIA DGX that reports cached tokens. "LM Studio 4B" is LM Studio with a Qwen3.5 4B model; it reports no cached-token counter.
**Plugin against the built-in compressor** ([record](evidence/plugin-live.json)), ten cases per engine and mode, median seconds:
@@ -284,9 +292,9 @@ The plugin was faster than both other engines in 10 of 10 cases. hermes-lcm and
- A provider or API key switch forgets the capture of the session: the next compaction uses the fallback summary (`no_capture`) until a main request on the new configuration completes. A key that Hermes gives as a function can change without a switch (a token that refreshes or rotates): the capture keeps a PBKDF2-HMAC-SHA-256 digest of the key that sent it, never the key, and the warm request is not sent with another key (reason `credential_changed`). The digest uses a random salt made when the plugin module loads. The salt and the captures stay in memory. A key change while a request is open keeps no capture.
- A captured row with a field that Hermes does not send for the stored row (other than the prompt caching marker `cache_control`) refuses the warm path (`source_transform_unsupported`).
- On Chat Completions routes, the source check accepts exact text or removal of trailing whitespace from a complete text string, including a stored `api_content` string. Leading or inner whitespace changes, added whitespace, and changes to text inside a content list still refuse the warm path (`source_transform_unsupported`). The captured request prefix stays unchanged.
-- Responses and Anthropic Messages use their own source checks. Native signed and encrypted replay records stay whole and count in tail estimates. A record that leaves no room for a valid new history returns the original history with `path=unchanged reason=capacity`. See [Provider support](docs/provider-support.md).
+- Responses and Anthropic Messages use their own source checks. Native signed and encrypted replay records stay whole and count in tail estimates. A record that leaves no room for a valid new history fails with `path=aborted` and a safe capacity code, without replacing the input history. See [Provider support](docs/provider-support.md).
- The handoff must start with `## Goal`: text before the first heading is refused (`gate:heading_preamble`).
-- The verbatim tail keeps the newest rows that fit in `tail_tokens`, and in the free room after the system rows and tool schemas of a usable capture, the reply reserve, and a summary: a large system prompt can make a short history compact. It stops at the first older row that does not fit, and that row goes into the summary. When the newest unit alone is larger than the tail or the free room, its largest sent payloads keep only their start and end: message text, tool call arguments (kept as a JSON object), and reasoning text. A large image or other media part is replaced by its attachment mark: a web URL or a file name stays (at most 200 characters), a data URL does not. If the cuts are not enough, the payloads are dropped, largest first; only the row structure stays. Signed `reasoning_details` stay as they are. The fallback summary gets the cut middles, and the fixed summary quotes them (at most 8,000 characters), also the cut middle of a long latest user message that goes in front of the tail. A fallback summary above its 4,096-token reserve (a dense CJK summary, for example) is not used: the fixed summary quotes the parts that the final tail cuts. Each quote makes the fixed summary larger and the tail smaller; after 10 rounds, the tail is cut at the size that the summary quotes, also when that is a little above the free room. The sizes come from the fields that Hermes sends: row metadata does not count; reasoning counts only on a route that needs it back (DeepSeek, Kimi, MiMo thinking; a capture of the route shows it, else a stored row with `reasoning_content`); `reasoning_details` counts only on a route that replays it, without the private native-assistant entries; the native-assistant entry type that the provider profile declares (`native_reasoning_details_type`) counts on every route of the provider, as Hermes replays it; a tool call counts only its id, type, name, and arguments, and a usable thought signature counts only for a Gemini or Gemma model. The fixed summary keeps bounded quotes of the earlier summary, the focus topic, the memory context, and the cut middles; together with the tool inventory (the most used names, and one count for the others) they stay in one budget (4,096 tokens, and at most the free room). When the fallback summary is used and the latest user request in front of the tail must be cut, the cut middle goes after the summary as a bounded quote, in what the summary budget has left: the fallback transcript had only the start and end of a long row. When no quote fits there, the fixed summary is used: it quotes the cut middle. A fallback summary that does not fit in the free room is not used: the fixed summary takes its place. A model, session, window, or threshold change at any time during the compaction discards its result (reason `route_changed`). On a Gemini or Gemma route, a tool call with a thought signature stays whole: Gemini needs it back as it was. A change of the provider or the key forgets the capture, also from an empty provider and key. A warm summary that does not fit in the free room (a dense reply under a low threshold, for example) is not used: the fallback summary runs (reason `summary_too_large`). A retry middleware cannot send the warm request a second time, also after a failed send. A warm reply body above 1 MiB is not read (reason `response_too_large`). The fallback request does not start after a model, provider, or session switch. The plugin API has no request on a fixed route (an override needs a trust setting), so a switch in the short time after that check, before the host resolves the auxiliary route, can still send the transcript to the new route. Reasoning is cut only when a usable capture of the route shows that the route sends it: other reasoning (of an earlier route after a model switch, for example) does not go to the fallback model or into the fixed summary. The latest user request in front of the tail gets the room that stays after the tail is cut. Hermes notifications, task lists, and recovery nudges are not user requests only when the whole text matches the Hermes template. The copied user messages get the room that stays after the tail is cut. Without a usable capture (after a restart, after a model change, or when a middleware changed the captured rows), the request overhead is unknown: the summary has no copied user messages, the summary, the prepended row, and the tail take at most half of the free room, the check before a request compacts when the history estimate reaches half of the window less the reply reserve, and the reply reserve is a quarter of the window (at most 65,536 and at least 4,096 tokens). The same reserve applies when the captured request had no positive `max_tokens` or `max_completion_tokens`: the provider default is not known. The host token count is not used for the overhead: it does not use the plugin tokenizer.
+- The verbatim tail keeps the newest rows that fit in `tail_tokens`, and in the free room after the system rows and tool schemas of a usable capture, the reply reserve, and a summary: a large system prompt can make a short history compact. It stops at the first older row that does not fit, and that row goes into the summary. When the newest unit alone is larger than the tail or the free room, its largest sent payloads keep only their start and end: message text, tool call arguments (kept as a JSON object), and reasoning text. A large image or other media part is replaced by its attachment mark: a web URL or a file name stays (at most 200 characters), a data URL does not. If the cuts are not enough, the payloads are dropped, largest first; only the row structure stays. Signed `reasoning_details` stay as they are. The fallback summary gets the cut middles. A fallback summary above its 4,096-token reserve (a dense CJK summary, for example) stops the current compaction pass and preserves its input history. The sizes come from the fields that Hermes sends: row metadata does not count; reasoning counts only on a route that needs it back (DeepSeek, Kimi, MiMo thinking; a capture of the route shows it, else a stored row with `reasoning_content`); `reasoning_details` counts only on a route that replays it, without the private native-assistant entries; the native-assistant entry type that the provider profile declares (`native_reasoning_details_type`) counts on every route of the provider, as Hermes replays it; a tool call counts only its id, type, name, and arguments, and a usable thought signature counts only for a Gemini or Gemma model. When the fallback summary is used and the latest user request in front of the tail must be cut, the cut middle goes after the summary as a bounded quote, in what the summary budget has left: the fallback transcript had only the start and end of a long row. When no quote fits there, the current compaction pass stops and preserves its input history. A fallback summary that does not fit in the free room also stops the current compaction pass. A model, session, window, or threshold change at any time during the compaction discards its result (reason `route_changed`). On a Gemini or Gemma route, a tool call with a thought signature stays whole: Gemini needs it back as it was. A change of the provider or the key forgets the capture, also from an empty provider and key. A warm summary that does not fit in the free room (a dense reply under a low threshold, for example) is not used: the fallback summary runs (reason `summary_too_large`). A retry middleware cannot send the warm request a second time, also after a failed send. A warm reply body above 1 MiB is not read (reason `response_too_large`). The fallback request does not start after a model, provider, or session switch. The plugin API has no request on a fixed route (an override needs a trust setting), so a switch in the short time after that check, before the host resolves the auxiliary route, can still send the transcript to the new route. Reasoning is cut only when a usable capture of the route shows that the route sends it: other reasoning (of an earlier route after a model switch, for example) does not go to the fallback model. The latest user request in front of the tail gets the room that stays after the tail is cut. Hermes notifications, task lists, and recovery nudges are not user requests only when the whole text matches the Hermes template. The copied user messages get the room that stays after the tail is cut. Without a usable capture (after a restart, after a model change, or when a middleware changed the captured rows), the request overhead is unknown: the summary has no copied user messages, the summary, the prepended row, and the tail take at most half of the free room, the check before a request compacts when the history estimate reaches half of the window less the reply reserve, and the reply reserve is a quarter of the window (at most 65,536 and at least 4,096 tokens). The same reserve applies when the captured request had no positive `max_tokens` or `max_completion_tokens`: the provider default is not known. The host token count is not used for the overhead: it does not use the plugin tokenizer.
- Responses warm requests are streamed; Chat Completions and Messages warm requests are not streamed. No warm request is retried. Its time limit is 120 seconds. The fallback request also has a 120-second limit. Native formats have additional limits in [Provider support](docs/provider-support.md).
- On Chat Completions routes, per-request `extra_headers` supports only one `x-opencode-session` header, with a non-empty plain ASCII string value, no control characters, and no leading or trailing space. Other headers, duplicate names with different case, non-empty `extra_query`, or an invalid `extra_body` use the fallback (`request_options_unsupported`). A JSON `extra_body.extra_headers` field cannot be combined with the session header. A request with `n` above 1, a forced `tool_choice`, `response_format`, or audio settings uses the fallback (`settings_unsupported`).
- After `/compress`, Hermes builds the system prompt again from its configuration. A system message that a host gave in code is not kept. This is Hermes behavior, and it is the same for the built-in compressor.
diff --git a/docs/provider-support.md b/docs/provider-support.md
index 9b34782..73d3aa1 100644
--- a/docs/provider-support.md
+++ b/docs/provider-support.md
@@ -8,7 +8,7 @@ The warm path supports three API formats. A model name alone does not identify i
| `codex_responses` | Stateless Responses requests with text and function tools, including the consumer Codex endpoint. Verified encrypted reasoning and native assistant message phases are replayed. |
| `anthropic_messages` | API-key Messages routes with text and function tools. Native Claude signed and redacted thinking blocks retain their exact order and bytes. |
-Requests that cannot pass the source, route, credential, middleware, or capacity checks use the normal auxiliary summary. A failed auxiliary summary uses the fixed summary. A live cache or speed benefit needs a separate provider test.
+Requests that cannot pass the source, route, credential, middleware, or capacity checks use a model-based fallback through `auxiliary.warm_compaction`. Its default `auto` follows the main chat route. It is separate from the built-in compressor's `auxiliary.compression` task. If the fallback fails, is incomplete, or cannot fit safely, the current compaction pass stops and preserves its input history. Hermes can retry an automatic failure; the documented plugin API does not stop the entire host turn. The plugin reports safe error codes and never creates a summary without a model. A live cache or speed benefit needs a separate provider test.
## Responses
@@ -30,7 +30,7 @@ Forced or server tools, media, structured output, unknown request controls, and
## Retained history and checks
-Native replay fields count in retained-tail estimates. A signed or encrypted assistant record stays whole, including the canonical text and tool data that its replay blocks describe. If an indivisible retained record exceeds the context budget, the attempt returns the original history with `path=unchanged reason=capacity`.
+Native replay fields count in retained-tail estimates. A signed or encrypted assistant record stays whole, including the canonical text and tool data that its replay blocks describe. If an indivisible retained record exceeds the context budget, the pass fails with `path=aborted` and a safe capacity code without replacing its input history.
The provider transport check uses synthetic data and a loopback server. It calls real Hermes transports, hooks, and middleware explicitly. A separate native conversation check runs the real Hermes agent loop. It covers manual and automatic compaction, native tool rounds, and saved-session reload in a fresh process. Both checks require a clean source checkout and keep source and plugin hashes unchanged.
diff --git a/scripts/check_plugin_hermes.py b/scripts/check_plugin_hermes.py
index 634abb9..91e5687 100644
--- a/scripts/check_plugin_hermes.py
+++ b/scripts/check_plugin_hermes.py
@@ -13,6 +13,7 @@ processes, and writes outside the scenario folder. The report has metadata only.
from __future__ import annotations
import argparse
+import copy
import hashlib
import inspect
import json
@@ -76,7 +77,7 @@ TOOL_PLUGIN = {
' "parameters": {"type": "object", "properties": {}, "required": []}})\n'
),
}
-SCENARIOS = ("enable_manual_warm", "manual_context", "manual_whitespace", "manual_fallback", "manual_fixed",
+SCENARIOS = ("enable_manual_warm", "manual_context", "manual_whitespace", "manual_fallback", "manual_aborted",
"auto_tool_loop", "auto_context_tool", "auto_warm_failures", "rollback")
# The scenarios with automatic compaction in a tool loop.
AUTO_SCENARIOS = ("auto_tool_loop", "auto_context_tool", "auto_warm_failures")
@@ -377,7 +378,7 @@ def plan_for(scenario):
return {"main": [{"content": "The code word is BLUE-7."}, {"content": "Next: report BLUE-7."}]}
if scenario == "manual_fallback":
return {"warm_status": 500, "main": [{"content": "The code word is BLUE-7."}, {"content": "Next."}]}
- if scenario == "manual_fixed":
+ if scenario == "manual_aborted":
return {"warm_status": 500, "fallback_status": 500,
"main": [{"content": "The code word is BLUE-7."}, {"content": "Next."}]}
if scenario == "auto_warm_failures":
@@ -561,7 +562,7 @@ def run_phase(spec, session_dir):
_compress_session_history, finalize_context_engine_compression_notification)
else:
run_manual(agent, engine, db, history, server, result, checks, scenario,
- _compress_session_history, finalize_context_engine_compression_notification)
+ _compress_session_history, finalize_context_engine_compression_notification, statuses)
check_native_notice(agent, engine, db, server, result, checks, statuses, home, config_before)
if scenario == "auto_warm_failures":
# The boundary probe uses a second engine. Check the main engine's log count first.
@@ -776,7 +777,7 @@ def check_native_notice(agent, engine, db, server, result, checks, statuses, hom
checks["native_notice_not_in_saved_history"] = NATIVE_NOTICE_MARK not in json.dumps(saved)
-def run_manual(agent, engine, db, history, server, result, checks, scenario, compress, finalize):
+def run_manual(agent, engine, db, history, server, result, checks, scenario, compress, finalize, statuses):
question = CONTEXT_QUESTION if scenario == "manual_context" else SEED_QUESTION
seed = agent.run_conversation(question, system_message=SYSTEM, conversation_history=history)
messages = seed.get("messages") or []
@@ -790,12 +791,15 @@ def run_manual(agent, engine, db, history, server, result, checks, scenario, com
check_injected_context(messages, seed_request, checks, "manual", question)
checks["capture_keeps_reported_prompt_tokens"] = capture.get("prompt_tokens") == len(
json.dumps(seed_request["body"]["messages"])) // 4
+ if scenario == "manual_aborted":
+ run_manual_aborted(agent, engine, db, session, capture, server, result, checks, compress, finalize, statuses)
+ return
begin = time.perf_counter()
failures_before = engine._warm_failures
removed, _usage = compress(session, "")
checks["failure_streak_waits_for_manual_commit"] = engine._warm_failures == failures_before
finalize(agent, committed=True)
- expected_failures = failures_before + (scenario in ("manual_fallback", "manual_fixed"))
+ expected_failures = failures_before + (scenario == "manual_fallback")
checks["failure_streak_after_manual_commit"] = engine._warm_failures == expected_failures
checks["manual_commit_notification_one_time"] = finalize(agent, committed=True) is False
result["compress_seconds"] = round(time.perf_counter() - begin, 3)
@@ -803,7 +807,7 @@ def run_manual(agent, engine, db, history, server, result, checks, scenario, com
result["warm_last"] = warm_last
expected = {"enable_manual_warm": ("warm", "accepted"), "manual_context": ("warm", "accepted"),
"manual_fallback": ("fallback", "provider_error"),
- "manual_fixed": ("fixed", "provider_error"), "rollback": ("warm", "accepted")}[scenario]
+ "rollback": ("warm", "accepted")}[scenario]
checks["path_and_reason"] = (warm_last.get("path"), warm_last.get("reason")) == expected
checks["removed_rows"] = removed > 0
after = session["history"]
@@ -817,8 +821,6 @@ def run_manual(agent, engine, db, history, server, result, checks, scenario, com
if scenario == "manual_fallback":
checks["one_fallback_request"] = len(by_kind(server, "fallback")) == 1
checks["fallback_in_summary"] = "(fallback)" in str(after[1].get("content"))
- if scenario == "manual_fixed":
- checks["fixed_in_summary"] = "Summary unavailable." in str(after[1].get("content"))
saved = db.get_messages_as_conversation(agent.session_id)
checks["history_saved"] = [row.get("content") for row in saved] == [row.get("content") for row in after]
result["session_rotated"] = agent.session_id != f"wc-{scenario}"
@@ -835,6 +837,69 @@ def run_manual(agent, engine, db, history, server, result, checks, scenario, com
later[0]["body"]["messages"][0].get("content") or "")
+def run_manual_aborted(agent, engine, db, session, capture, server, result, checks, compress, finalize, statuses):
+ """Two failed synthetic model requests must stop the real manual history transaction."""
+ module = sys.modules[type(engine).__module__]
+ abort_type = getattr(module, "CompactionAborted", None)
+ checks["abort_type_from_installed_plugin"] = (
+ isinstance(abort_type, type) and issubclass(abort_type, RuntimeError)
+ and inside(inspect.getfile(abort_type), Path(os.environ["HERMES_HOME"]) / "plugins" / "warm_compaction"))
+ before_history = copy.deepcopy(session["history"])
+ history_object = session["history"]
+ before_saved = copy.deepcopy(db.get_messages_as_conversation(agent.session_id))
+ before_capture = copy.deepcopy(capture)
+ before_session = agent.session_id
+ before_engine_session = engine._wc_session_id
+ before_version = session["history_version"]
+ before_count = engine.compression_count
+ before_failures = engine._warm_failures
+ before_notice = engine._warm_notice
+ before_notice_issued = engine._warm_notice_issued
+ before_requests = len(server.requests)
+ before_statuses = len(statuses)
+ begin = time.perf_counter()
+ try:
+ compress(session, "")
+ except Exception as error:
+ checks["expected_abort_error"] = abort_type is not None and type(error) is abort_type
+ checks["abort_error_name"] = type(error).__name__ == "CompactionAborted"
+ # Compare the fixed public text in memory. Never copy arbitrary exception text to the report.
+ checks["abort_error_is_sanitized"] = str(error) == (
+ "Warm compaction stopped; history is unchanged "
+ "(warm: provider_error; fallback: error:InternalServerError).")
+ result["abort_error_type"] = type(error).__name__
+ else:
+ checks["expected_abort_error"] = False
+ result["compress_seconds"] = round(time.perf_counter() - begin, 3)
+ last = dict(engine.warm_last or {})
+ result["warm_last"] = last
+ checks["path_and_reason"] = (last.get("path"), last.get("reason"), last.get("fallback_reason")) == (
+ "aborted", "provider_error", "error:InternalServerError")
+ checks["manual_history_object_unchanged"] = session["history"] is history_object
+ checks["manual_history_unchanged"] = session["history"] == before_history
+ checks["saved_history_unchanged"] = db.get_messages_as_conversation(before_session) == before_saved
+ checks["capture_unchanged"] = engine._store.latest(before_engine_session) == before_capture
+ checks["session_id_unchanged"] = agent.session_id == before_session
+ checks["engine_session_unchanged"] = engine._wc_session_id == before_engine_session
+ checks["session_history_version_unchanged"] = session["history_version"] == before_version
+ checks["session_key_unchanged"] = session["session_key"] == before_session
+ checks["compression_count_unchanged"] = engine.compression_count == before_count
+ checks["failure_streak_unchanged"] = engine._warm_failures == before_failures
+ checks["failure_notice_unchanged"] = (
+ engine._warm_notice == before_notice and engine._warm_notice_issued == before_notice_issued)
+ checks["no_pending_successful_boundary"] = engine._pending_warm_result is None
+ checks["no_successful_boundary_notification"] = finalize(agent, committed=True) is False
+ checks["aborted_manual_has_no_compacted_status"] = not any(
+ kind == "compacted" for kind, _message in statuses[before_statuses:])
+ checks["no_generated_summary"] = not any(row.get("_compressed_summary") for row in session["history"])
+ attempted = server.requests[before_requests:]
+ checks["only_two_summary_requests"] = [(row["kind"], row["status"]) for row in attempted] == [
+ ("warm", 500), ("fallback", 500)]
+ result["session_rotated"] = False
+ result["compression_count"] = engine.compression_count
+ result["automatic_stop_contract"] = "not checked: Hermes has no documented terminal plugin abort result"
+
+
def run_manual_whitespace(agent, engine, db, history, server, result, checks, compress, finalize):
"""Repeat manual compaction when Hermes strips a string only in the sent request."""
messages, outcomes = history, []
@@ -895,10 +960,16 @@ def check_injected_context(messages, request, checks, label, question):
def run_auto(agent, engine, history, server, result, checks, statuses):
+ from agent.conversation_compression import COMPACTION_DONE_STATUS
+
checks["threshold_from_settings"] = engine.threshold_tokens == int(CONTEXT_LENGTH * 0.4)
context_case = result["scenario"] == "auto_context_tool"
question = CONTEXT_TOOL_QUESTION if context_case else TOOL_QUESTION
+ before_first_statuses = len(statuses)
first = agent.run_conversation(question, system_message=SYSTEM, conversation_history=history)
+ checks["first_automatic_compacted_status"] = [
+ message for kind, message in statuses[before_first_statuses:] if kind == "compacted"
+ ] == [COMPACTION_DONE_STATUS]
first_notice_count = sum(NATIVE_NOTICE_MARK in message for _kind, message in statuses)
checks["native_notice_on_first_automatic_compaction"] = (
first_notice_count == int(result["native_warm_handoff"]["available"]))
@@ -914,8 +985,12 @@ def run_auto(agent, engine, history, server, result, checks, statuses):
checks["first_summary_rows"] = summary_rows_ok(after_first)
checks["wait_flag_cleared"] = engine.awaiting_real_usage_after_compression is False
question = CONTEXT_TOOL_AGAIN_QUESTION if context_case else TOOL_AGAIN_QUESTION
+ before_second_statuses = len(statuses)
second = agent.run_conversation(question, system_message=SYSTEM,
conversation_history=list(after_first))
+ checks["second_automatic_compacted_status"] = [
+ message for kind, message in statuses[before_second_statuses:] if kind == "compacted"
+ ] == [COMPACTION_DONE_STATUS]
checks["second_turn_final"] = second.get("final_response") == "Done again."
if context_case:
check_injected_context(second.get("messages") or [], by_kind(server, "main")[-1], checks, "auto2", question)
diff --git a/tests/property/test_native_properties.py b/tests/property/test_native_properties.py
index cc20485..911993e 100644
--- a/tests/property/test_native_properties.py
+++ b/tests/property/test_native_properties.py
@@ -281,6 +281,30 @@ class CaptureLifecycleProperties(unittest.TestCase):
import wc_hermes_stub
wc_hermes_stub.install(self)
+ @PROPERTIES
+ @given(histories(), TEXT, st.sampled_from((RESPONSES, MESSAGES)))
+ def test_summary_failure_keeps_native_history_capture_and_counters(self, rows, answer, route):
+ from warm_compaction.engine import CompactionAborted, WarmCompactionEngine
+ saved = capture(rows, assistant(answer), route)
+ store = CaptureStore()
+ engine = WarmCompactionEngine(store=store, settings={"warm": False, "tail_tokens": 1})
+ engine.update_model(route[0], 200_000, base_url=route[1], api_mode=route[2],
+ provider="synthetic-provider", api_key="synthetic-key")
+ engine.on_session_start("synthetic-session")
+ saved["key_stamp"] = engine._key_stamp()
+ store._sessions["synthetic-session"] = copy.deepcopy(saved)
+ current = copy.deepcopy([*rows, assistant(answer)])
+ before = copy.deepcopy(current)
+ captured = copy.deepcopy(store.latest("synthetic-session"))
+ with self.assertRaises(CompactionAborted):
+ engine.compress(current)
+ self.assertEqual(current, before)
+ self.assertEqual(store.latest("synthetic-session"), captured)
+ self.assertEqual(engine.compression_count, 0)
+ self.assertIsNone(engine._pending_warm_result)
+ self.assertEqual(engine._warm_failures, 0)
+ self.assertEqual((engine.warm_last["path"], engine.warm_last["fallback_reason"]), ("aborted", "unavailable"))
+
@PROPERTIES
@given(histories(), TEXT, st.sampled_from((RESPONSES, MESSAGES)),
st.lists(st.sampled_from(("same", "route", "provider", "credential", "session", "history")),
diff --git a/tests/test_wc_engine.py b/tests/test_wc_engine.py
index 35cea25..ef7f51d 100644
--- a/tests/test_wc_engine.py
+++ b/tests/test_wc_engine.py
@@ -92,6 +92,26 @@ class EngineTest(unittest.TestCase):
self.commit(engine)
return result
+ def assert_aborted(self, engine, history, fallback_reason, **kwargs):
+ """Check a synthetic failure without a history or state change."""
+ original = copy.deepcopy(history)
+ captured = copy.deepcopy(self.store.latest(engine._wc_session_id))
+ count = engine.compression_count
+ failures = (engine._warm_failures, list(engine._warm_failure_reasons), engine._warm_notice)
+ with self.assertRaises(RuntimeError) as stopped:
+ engine.compress(history, **kwargs)
+ from warm_compaction.engine import CompactionAborted
+ self.assertIsInstance(stopped.exception, CompactionAborted)
+ self.assertEqual(history, original)
+ self.assertEqual(self.store.latest(engine._wc_session_id), captured)
+ self.assertEqual(engine.compression_count, count)
+ self.assertIsNone(engine._pending_warm_result)
+ self.assertEqual((engine._warm_failures, engine._warm_failure_reasons, engine._warm_notice), failures)
+ self.assertEqual((engine.warm_last["path"], engine.warm_last["fallback_reason"]),
+ ("aborted", fallback_reason))
+ self.assertIn("Warm compaction stopped; history is unchanged", str(stopped.exception))
+ return stopped.exception
+
def test_threshold_comes_from_the_setting(self):
self.assertEqual(self.engine.threshold_tokens, 100_000)
self.assertFalse(self.engine.should_compress(99_999))
@@ -191,7 +211,7 @@ class EngineTest(unittest.TestCase):
self.assertNotIn("done", sent.split("\n"))
self.assertNotIn(rows[-2]["content"][:20], sent)
- def test_request_refusals_reach_fallback_and_fixed_status_without_private_data(self):
+ def test_request_refusals_reach_fallback_or_abort_without_private_data(self):
private = "synthetic-private-request-value"
cases = (
([private], "request_not_mapping"),
@@ -201,10 +221,10 @@ class EngineTest(unittest.TestCase):
({"value": SimpleNamespace(secret=private)}, "request_not_json"),
)
rows, reply = old_turns(4), assistant("final")
- for path in ("fallback", "fixed"):
+ for path in ("fallback", "aborted"):
for body, code in cases:
with self.subTest(path=path, code=code):
- self.llm = FakeLlm(error=RuntimeError(private) if path == "fixed" else None)
+ self.llm = FakeLlm(error=RuntimeError(private) if path == "aborted" else None)
engine = self.make(tail_tokens=10)
engine.update_model(model=ROUTE[0], context_length=200_000, base_url=ROUTE[1], api_key=private,
provider="custom", api_mode=ROUTE[2])
@@ -218,13 +238,17 @@ class EngineTest(unittest.TestCase):
self.store.on_post_api_request(api_request_id="r1", session_id="s1", finish_reason="stop",
assistant_message=reply_object(reply))
history = [*rows, reply]
- new = self.compress_committed(engine, history)
+ if path == "aborted":
+ error = self.assert_aborted(engine, history, "error:RuntimeError")
+ self.assertNotIn(private, str(error))
+ else:
+ new = self.compress_committed(engine, history)
status = engine.get_status()["warm_last"]
self.assertEqual((status["path"], status["reason"]), (path, code))
self.assertEqual((result, calls), ("response", [1]))
- self.assertIsNot(new, history)
- self.assertTrue(any("Fallback summary." in str(row.get("content")) for row in new)
- if path == "fallback" else any(row.get("_compressed_summary") for row in new))
+ if path == "fallback":
+ self.assertIsNot(new, history)
+ self.assertTrue(any("Fallback summary." in str(row.get("content")) for row in new))
self.assertEqual(len(self.llm.calls), 1)
self.assertEqual(self.post.calls, [])
self.assertIn(f"path={path} reason={code}", "\n".join(logs.output))
@@ -572,29 +596,22 @@ class EngineTest(unittest.TestCase):
api_mode=ROUTE[2])
self.assertIsNone(self.store.latest("s1"))
- def test_the_fixed_summary_keeps_the_focus_and_the_memory_context(self):
- # The last path has no model: the inputs given for this compaction must stay.
- self.llm.error = RuntimeError("down")
+ def test_failed_summary_keeps_history_with_focus_and_memory(self):
+ self.llm.error = RuntimeError("synthetic failure")
engine = self.make(warm=False)
- new = engine.compress([*old_turns(), assistant("done")], focus_topic="FOCUS-ON-PARSER",
- memory_context="MEMORY-FACT-42")
- self.assertEqual(engine.warm_last["path"], "fixed")
- summary = "\n".join(str(row["content"]) for row in new if row.get("_compressed_summary"))
- self.assertIn("FOCUS-ON-PARSER", summary)
- self.assertIn("MEMORY-FACT-42", summary)
+ history = [*old_turns(), assistant("done")]
+ self.assert_aborted(engine, history, "error:RuntimeError", focus_topic="FOCUS-ON-PARSER",
+ memory_context="MEMORY-FACT-42")
- def test_a_fallback_summary_above_the_room_goes_to_the_fixed_summary(self):
- # Under the reserve, but a large system prompt and a low threshold leave less room than the summary needs.
+ def test_a_fallback_summary_above_the_room_stops_compaction(self):
self.llm = FakeLlm(text=HEADINGS_TEXT.replace("Finish the test task.", "word " * 1_200) + "\n" + END_LINE)
engine = self.make(threshold=0.10, warm=False)
engine.update_model(model=ROUTE[0], context_length=64_000, base_url=ROUTE[1], api_key="k",
provider="custom", api_mode=ROUTE[2])
- rows = old_turns(8)
- reply = assistant("final")
+ rows, reply = old_turns(8), assistant("final")
self.seed(rows, reply, system={"role": "system", "content": "s " * 10_000}, extra={"max_tokens": 4_096})
- engine.compress([*rows, reply])
+ self.assert_aborted(engine, [*rows, reply], "summary_too_large")
self.assertEqual(len(self.llm.calls), 1)
- self.assertEqual(engine.warm_last["path"], "fixed")
def test_a_switch_before_the_result_is_used_discards_it(self):
# The check covers the whole compaction: a switch while the new history is built also stops it.
@@ -615,11 +632,11 @@ class EngineTest(unittest.TestCase):
self.assertEqual((engine.warm_last["path"], engine.warm_last["reason"]), ("cancelled", "route_changed"))
self.assertEqual(engine.compression_count, 0)
- def test_the_fixed_budget_is_not_above_a_small_room(self):
+ def test_the_summary_budget_is_not_above_a_small_room(self):
self.engine._room = lambda *args, **kwargs: 100
- self.assertEqual(self.engine._fixed_budget(0, 0), 100)
+ self.assertEqual(self.engine._summary_budget(0, 0), 100)
self.engine._room = lambda *args, **kwargs: -5
- self.assertEqual(self.engine._fixed_budget(0, 0), 0)
+ self.assertEqual(self.engine._summary_budget(0, 0), 0)
def test_the_fallback_summary_gets_the_cut_middle_of_the_prepended_row(self):
# The fallback transcript has only the start and end of a long row: the middle that the tail cuts from
@@ -734,9 +751,7 @@ class EngineTest(unittest.TestCase):
self.engine.compress([*rows, reply])
self.assertEqual(self.engine.warm_last["path"], "warm")
- def test_a_fallback_summary_without_room_for_the_cut_quote_becomes_the_fixed_summary(self):
- # The fallback summary takes almost all of its budget: no quote of the cut middle of the prepended request
- # fits after it. The fixed summary then quotes that middle (its start: the marker is near it).
+ def test_a_fallback_summary_without_room_for_the_cut_quote_stops_compaction(self):
rows = [*old_turns(4), user("BIG start " + "q" * 1_000 + " MID-REQ " + "q" * 40_000 + " big end"),
assistant("", [("c1", "read", "{}")]), tool("c1", "r1"), assistant("done")]
self.llm.text = (HEADINGS_TEXT.replace("Finish the test task.", "Fallback summary. " + "z" * 16_150)
@@ -744,9 +759,7 @@ class EngineTest(unittest.TestCase):
engine = self.make(threshold=0.95, tail_tokens=2_000, warm=False)
engine.update_model(model=ROUTE[0], context_length=64_000, base_url=ROUTE[1], api_key="k",
provider="custom", api_mode=ROUTE[2])
- new = engine.compress(rows)
- self.assertEqual(engine.warm_last["path"], "fixed")
- self.assertTrue(any("MID-REQ" in str(row.get("content")) for row in new if row.get("_compressed_summary")))
+ self.assert_aborted(engine, rows, "quote_capacity")
def test_no_fallback_request_starts_after_a_switch(self):
# A fallback task on the auto route follows the main route: after a switch, the old transcript must not
@@ -792,26 +805,36 @@ class EngineTest(unittest.TestCase):
def test_a_host_compatibility_failure_tells_the_user_at_the_first_commit(self):
for reason in ("middleware_order_unknown", "middleware_unavailable"):
- for path in ("fallback", "fixed"):
- with self.subTest(reason=reason, path=path):
- self.llm.error = RuntimeError("synthetic fallback failure") if path == "fixed" else None
- engine = self.make()
- self.compatibility_candidate(engine, reason)
- self.assertEqual(engine.warm_last["path"], path)
- self.assertEqual(engine._warm_failures, 0)
- self.assertIsNone(engine._warm_notice)
- self.commit(engine)
- notice = engine.get_automatic_compaction_status_message(
- phase="compress", default_message="Compacting")
- self.assertIn("Hermes compatibility", notice)
- self.assertIn(reason, notice)
- self.assertIn("fallback summary", notice)
- self.assertIn("logs/agent.log", notice)
- self.assertNotIn("no messages were dropped", notice)
- if path == "fixed":
- self.assertIn("fixed summary (no model, less detail)", notice)
- else:
- self.assertIn("Compaction continues with the fallback summary.", notice)
+ with self.subTest(reason=reason):
+ engine = self.make()
+ self.compatibility_candidate(engine, reason)
+ self.assertEqual(engine.warm_last["path"], "fallback")
+ self.assertEqual(engine._warm_failures, 0)
+ self.assertIsNone(engine._warm_notice)
+ self.commit(engine)
+ notice = engine.get_automatic_compaction_status_message(phase="compress", default_message="Compacting")
+ self.assertIn("Hermes compatibility", notice)
+ self.assertIn(reason, notice)
+ self.assertIn("Compaction continues with the fallback summary.", notice)
+ self.assertIn("logs/agent.log", notice)
+
+ def test_a_host_compatibility_failure_stops_if_backup_also_fails(self):
+ self.llm.error = RuntimeError("synthetic fallback failure")
+ for reason in ("middleware_order_unknown", "middleware_unavailable"):
+ with self.subTest(reason=reason):
+ engine = self.make()
+ rows, reply = old_turns(), assistant("done")
+ if reason == "middleware_order_unknown":
+ with patch.object(wc_hermes_stub.PLUGINS, "_delivery_manager",
+ side_effect=AttributeError("synthetic change")):
+ self.seed(rows, reply)
+ self.assert_aborted(engine, [*rows, reply], "error:RuntimeError")
+ else:
+ self.seed(rows, reply)
+ with patch.dict(wc_hermes_stub.MIDDLEWARE.__dict__, clear=True):
+ self.assert_aborted(engine, [*rows, reply], "error:RuntimeError")
+ self.assertEqual(engine.warm_last["reason"], reason)
+ self.assertIsNone(engine._warm_notice)
def test_a_compatibility_notice_stays_pending_when_the_host_hides_status(self):
engine = self.make()
@@ -824,15 +847,12 @@ class EngineTest(unittest.TestCase):
phase="compress", default_message="Compacting"))
self.assertEqual(engine._warm_notice, pending)
self.llm.error = RuntimeError("synthetic fallback failure")
- self.compress_committed(engine, [*old_turns(), assistant("done")])
+ self.assert_aborted(engine, [*old_turns(), assistant("done")], "error:RuntimeError")
engine.emit_automatic_compaction_status = True
- notice = engine.get_automatic_compaction_status_message(phase="compress", default_message="Compacting")
- self.assertIn("Hermes compatibility", notice)
- self.assertIn("no_capture", notice)
- self.assertIn("the last 2 compactions", notice)
- self.assertIn("the fallback summary could not be used 1 of 2 times", notice)
- self.assertEqual(engine.get_automatic_compaction_status_message(
- phase="compress", default_message="Compacting"), "Compacting")
+ self.assertEqual(engine.get_automatic_compaction_status_message(phase="compress", default_message="Compacting"),
+ pending)
+ self.assertEqual(engine.get_automatic_compaction_status_message(phase="compress", default_message="Compacting"),
+ "Compacting")
def test_a_consumed_compatibility_notice_does_not_repeat_at_the_third_failure(self):
engine = self.make()
@@ -951,21 +971,17 @@ class EngineTest(unittest.TestCase):
self.assertEqual(engine.get_automatic_compaction_status_message(phase="compress",
default_message="Compacting"), "Compacting")
- def test_a_pending_notice_includes_a_later_fixed_summary(self):
+ def test_an_aborted_attempt_keeps_the_pending_notice(self):
engine = self.make()
history = [*old_turns(), assistant("done")]
- with self.assertLogs("warm_compaction.engine", level="WARNING") as logs:
- for _ in range(3):
- self.compress_committed(engine, history)
- self.llm.error = RuntimeError("down")
+ for _ in range(3):
self.compress_committed(engine, history)
- self.assertEqual(engine.warm_last["path"], "fixed")
- notice = engine.get_automatic_compaction_status_message(phase="compress", default_message="Compacting")
- self.assertIn("the last 4 compactions", notice)
- self.assertIn("the fallback summary could not be used 1 of 4 times", notice)
- self.assertIn("fixed summary (no model, less detail)", notice)
- self.assertEqual(sum("Warm compaction skipped" in line for line in logs.output), 4)
- self.assertEqual(sum("Warm compaction failed" in line for line in logs.output), 1)
+ pending = engine._warm_notice
+ self.llm.error = RuntimeError("synthetic failure")
+ self.assert_aborted(engine, history, "error:RuntimeError")
+ self.assertEqual(engine.get_automatic_compaction_status_message(phase="compress", default_message="Compacting"),
+ pending)
+ self.assertIn("the last 3 compactions", pending)
def test_a_pending_notice_keeps_each_reason_with_its_hint(self):
engine = self.make()
@@ -1004,12 +1020,14 @@ class EngineTest(unittest.TestCase):
self.compress_committed(engine, history)
self.assertIn("Warm compaction unavailable", engine.get_automatic_compaction_status_message(
phase="compress", default_message="Compacting"))
- self.llm.error = RuntimeError("down")
+ self.llm.error = RuntimeError("synthetic fallback failure")
for _ in range(2):
- self.compress_committed(engine, history)
+ self.assert_aborted(engine, history, "error:RuntimeError")
self.assertEqual(engine.get_automatic_compaction_status_message(
phase="compress", default_message="Compacting"), "Compacting")
- self.assertEqual(sum("Warm compaction skipped" in line for line in logs.output), 5)
+ self.assertEqual(engine._warm_failures, 3)
+ self.assertEqual(sum("Warm compaction skipped" in line for line in logs.output), 3)
+ self.assertEqual(sum("Warm compaction stopped" in line for line in logs.output), 2)
self.assertEqual(sum("Warm compaction failed" in line for line in logs.output), 1)
def test_a_rejected_warm_reply_with_cached_tokens_does_not_claim_a_cache_miss(self):
@@ -1036,7 +1054,7 @@ class EngineTest(unittest.TestCase):
self.seed(rows, reply)
self.compress_committed(engine, [*rows, reply])
self.assertEqual(engine.warm_last["path"], "warm")
- self.assertEqual((engine._warm_failures, engine._warm_fixed, engine._warm_failure_reasons), (0, 0, []))
+ self.assertEqual((engine._warm_failures, engine._warm_failure_reasons), (0, []))
self.assertEqual(engine.get_automatic_compaction_status_message(phase="compress",
default_message="Compacting"), "Compacting")
self.store.forget(session_id="s1")
@@ -1083,21 +1101,14 @@ class EngineTest(unittest.TestCase):
self.assertEqual(engine.get_automatic_compaction_status_message(
phase="compress", default_message="Compacting"), "Compacting")
- def test_the_notice_tells_when_the_fallback_also_failed(self):
- # The fixed summary has no model request: the notice must not say that the fallback summary works.
- self.llm = FakeLlm(error=RuntimeError("down"))
+ def test_summary_failures_stop_without_a_success_notice(self):
+ self.llm = FakeLlm(error=RuntimeError("synthetic failure"))
engine = self.make()
history = [*old_turns(), assistant("done")]
- with self.assertLogs("warm_compaction.engine", level="WARNING") as logs:
- for _ in range(3):
- self.compress_committed(engine, history)
- self.assertEqual(engine.warm_last["path"], "fixed")
- notice = engine.get_automatic_compaction_status_message(phase="compress", default_message="Compacting")
- self.assertNotIn("continues with the slower fallback summary", notice)
- self.assertIn("the fallback summary could not be used 3 of 3 times", notice)
- self.assertIn("fixed summary", notice)
- self.assertNotIn("no messages were dropped", notice)
- self.assertEqual(sum("3 of them with the fixed summary" in line for line in logs.output), 1)
+ for _ in range(3):
+ self.assert_aborted(engine, history, "error:RuntimeError")
+ self.assertEqual(engine._warm_failures, 0)
+ self.assertIsNone(engine._warm_notice)
def test_a_session_reset_clears_the_failure_streak(self):
# A notice or a streak of the old session does not show in the new session.
@@ -1106,7 +1117,7 @@ class EngineTest(unittest.TestCase):
for _ in range(3):
self.compress_committed(engine, history)
engine.on_session_reset()
- self.assertEqual((engine._warm_failures, engine._warm_fixed, engine._warm_failure_reasons), (0, 0, []))
+ self.assertEqual((engine._warm_failures, engine._warm_failure_reasons), (0, []))
self.assertEqual(engine.get_automatic_compaction_status_message(phase="compress",
default_message="Compacting"), "Compacting")
for _ in range(2):
@@ -1117,7 +1128,7 @@ class EngineTest(unittest.TestCase):
def test_a_result_is_not_counted_before_the_commit_boundary(self):
engine = self.make()
engine.compress([*old_turns(), assistant("done")])
- self.assertEqual((engine._warm_failures, engine._warm_fixed), (0, 0))
+ self.assertEqual(engine._warm_failures, 0)
self.assertIsNone(engine._warm_notice)
self.commit(engine)
self.assertEqual(engine._warm_failures, 1)
@@ -1561,13 +1572,98 @@ class EngineTest(unittest.TestCase):
section = summary.split("## Copied user messages", 1)[1].strip()
self.assertEqual(not section.startswith("(none)"), copied)
- def test_fixed_summary_when_the_fallback_fails(self):
- self.llm = FakeLlm(error=RuntimeError("down"))
+ def test_compaction_stops_when_the_fallback_fails(self):
+ self.llm = FakeLlm(error=RuntimeError("synthetic failure"))
engine = self.make()
- with self.assertLogs("warm_compaction.fallback", level="WARNING"):
- new = engine.compress([*old_turns(), assistant("done")])
- self.assertEqual(engine.warm_last["path"], "fixed")
- self.assertIn("Summary unavailable.", new[1]["content"])
+ self.assert_aborted(engine, [*old_turns(), assistant("done")], "error:RuntimeError")
+
+ def test_provider_error_and_backup_internal_server_error_stop_with_safe_metadata(self):
+ class InternalServerError(RuntimeError):
+ pass
+
+ private = "synthetic-private-message-and-credential"
+ self.llm.error = InternalServerError(private)
+ engine = self.make()
+ rows, reply = old_turns(), assistant("synthetic final reply")
+ self.seed(rows, reply)
+ engine._post = lambda *args, **kwargs: (500, private.encode())
+ with self.assertLogs("warm_compaction", level="INFO") as logs:
+ error = self.assert_aborted(engine, [*rows, reply], "error:InternalServerError")
+ self.assertEqual(engine.warm_last["reason"], "provider_error")
+ self.assertIn("warm: provider_error; fallback: error:InternalServerError", str(error))
+ self.assertNotIn(private, str(error))
+ self.assertNotIn(private, str(logs.output))
+ self.assertNotIn(private, json.dumps(engine.get_status()))
+ self.assertIsNone(error.__cause__)
+ self.assertTrue(error.__suppress_context__)
+
+ def test_absent_rejected_empty_and_incomplete_backup_summaries_stop_compaction(self):
+ cases = (
+ (None, "unavailable"),
+ (FakeLlm(text="synthetic answer\n" + END_LINE), "gate:heading_missing"),
+ (FakeLlm(text=""), "gate:missing_end_marker"),
+ (FakeLlm(text=HEADINGS_TEXT), "gate:missing_end_marker"),
+ (FakeLlm(text=HEADINGS_TEXT.replace("Finish the test task.", "x" * 30_000) + "\n" + END_LINE),
+ "gate:byte_bound"),
+ )
+ for llm, reason in cases:
+ with self.subTest(reason=reason):
+ self.llm = llm
+ engine = self.make(warm=False)
+ self.assert_aborted(engine, [*old_turns(), assistant("synthetic final reply")], reason)
+
+ def test_late_backup_errors_after_cancel_or_route_switch_keep_history(self):
+ for action in ("cancel", "route", "session"):
+ with self.subTest(action=action):
+ engine = self.make(warm=False)
+ history = [*old_turns(), assistant("synthetic final reply")]
+ original = copy.deepcopy(history)
+
+ def failed(*args, action=action, engine=engine, **kwargs):
+ if action == "cancel":
+ engine._compression_cancelled_check = lambda: True
+ elif action == "route":
+ engine.update_model("synthetic-other-model", 200_000)
+ else:
+ engine.on_session_start("synthetic-new-session")
+ raise RuntimeError("synthetic private late failure")
+
+ with patch.object(self.llm, "complete", side_effect=failed):
+ self.assertIs(engine.compress(history), history)
+ self.assertEqual(history, original)
+ self.assertEqual(engine.compression_count, 0)
+ self.assertIsNone(engine._pending_warm_result)
+ if action == "session":
+ self.assertIsNone(engine.warm_last)
+ else:
+ self.assertEqual(engine.warm_last["path"], "cancelled")
+
+ def test_a_stale_backup_error_cannot_replace_a_newer_result_or_raise(self):
+ engine = self.make(warm=False)
+ history = [*old_turns(), assistant("synthetic final reply")]
+ original = copy.deepcopy(history)
+ complete = self.llm.complete
+ latest = {}
+
+ def stale(*args, **kwargs):
+ self.llm.complete = complete
+ try:
+ candidate = copy.deepcopy(history)
+ self.assertIsNot(engine.compress(candidate), candidate)
+ latest.update(engine.warm_last)
+ finally:
+ self.llm.complete = stale
+ raise RuntimeError("synthetic private stale failure")
+
+ self.llm.complete = stale
+ try:
+ self.assertIs(engine.compress(history), history)
+ finally:
+ self.llm.complete = complete
+ self.assertEqual(history, original)
+ self.assertEqual(engine.warm_last, latest)
+ self.assertEqual(engine.compression_count, 1)
+ self.assertIsNotNone(engine._pending_warm_result)
def test_disabled_setting(self):
engine = self.make(warm=False)
@@ -1608,8 +1704,8 @@ class EngineTest(unittest.TestCase):
self.compress_committed(engine, history)
self.assertEqual((engine.warm_last["path"], engine.warm_last["reason"]),
("fallback", "provider_not_allowed"))
- self.assertEqual((engine._warm_failures, engine._warm_fixed, engine._warm_failure_reasons),
- (0, 0, []))
+ self.assertEqual((engine._warm_failures, engine._warm_failure_reasons),
+ (0, []))
self.assertEqual(engine.get_automatic_compaction_status_message(
phase="compress", default_message="Compacting"), "Compacting")
self.assertEqual(self.post.calls, [])
@@ -1625,7 +1721,7 @@ class EngineTest(unittest.TestCase):
self.compress_committed(engine, history)
self.assertEqual((engine.warm_last["path"], engine.warm_last["reason"]),
("fallback", "no_capture"))
- self.assertEqual((engine._warm_failures, engine._warm_fixed), (3, 0))
+ self.assertEqual(engine._warm_failures, 3)
self.assertEqual(engine._warm_failure_reasons, ["no_capture"] * 3)
self.assertEqual(self.post.calls, [])
self.assertEqual(len(self.llm.calls), 3)
@@ -1646,8 +1742,8 @@ class EngineTest(unittest.TestCase):
self.compress_committed(engine, [*rows, reply])
self.assertEqual((engine.warm_last["path"], engine.warm_last["reason"]),
("fallback", "provider_not_allowed"))
- self.assertEqual((engine._warm_failures, engine._warm_fixed, engine._warm_failure_reasons),
- (0, 0, []))
+ self.assertEqual((engine._warm_failures, engine._warm_failure_reasons),
+ (0, []))
self.assertEqual(engine.get_automatic_compaction_status_message(
phase="compress", default_message="Compacting"), "Compacting")
self.assertEqual(self.post.calls, [])
@@ -1671,7 +1767,7 @@ class EngineTest(unittest.TestCase):
self.compress_committed(engine, [*rows, reply])
self.assertEqual((engine.warm_last["path"], engine.warm_last["reason"]),
("fallback", "provider_error"))
- self.assertEqual((engine._warm_failures, engine._warm_fixed), (3, 0))
+ self.assertEqual(engine._warm_failures, 3)
self.assertEqual(engine._warm_failure_reasons, ["provider_error"] * 3)
self.assertEqual((len(requests), len(self.llm.calls)), (3, 3))
self.assertEqual(sum("Warm compaction skipped (provider_error); used the fallback summary" in line
@@ -1682,27 +1778,19 @@ class EngineTest(unittest.TestCase):
self.assertIn("the last 3 compactions", notice)
self.assertIn("provider_error", notice)
- def test_an_excluded_provider_with_a_failed_fallback_still_reports_the_failure_streak(self):
+ def test_an_excluded_provider_with_a_failed_fallback_stops_compaction(self):
engine = self.make(warm_providers="opencode-go,commandcode")
rows, reply = old_turns(), assistant("final")
self.llm.error = RuntimeError("synthetic fallback failure")
- with self.assertLogs("warm_compaction.engine", level="WARNING") as logs:
- for _ in range(3):
- self.seed(rows, reply)
- self.compress_committed(engine, [*rows, reply])
- self.assertEqual((engine.warm_last["path"], engine.warm_last["reason"]),
- ("fixed", "provider_not_allowed"))
- self.assertEqual((engine._warm_failures, engine._warm_fixed), (3, 3))
- self.assertEqual(engine._warm_failure_reasons, ["provider_not_allowed"] * 3)
+ for _ in range(3):
+ self.seed(rows, reply)
+ self.assert_aborted(engine, [*rows, reply], "error:RuntimeError")
+ self.assertEqual(engine.warm_last["reason"], "provider_not_allowed")
+ self.assertEqual(engine._warm_failures, 0)
+ self.assertEqual(engine._warm_failure_reasons, [])
self.assertEqual(self.post.calls, [])
self.assertEqual(len(self.llm.calls), 3)
- self.assertEqual(sum("Warm compaction skipped (provider_not_allowed); used the fixed summary" in line
- for line in logs.output), 3)
- self.assertEqual(sum("Warm compaction failed 3 times in a row (provider_not_allowed)" in line
- for line in logs.output), 1)
- notice = engine.get_automatic_compaction_status_message(phase="compress", default_message="Compacting")
- self.assertIn("the last 3 compactions", notice)
- self.assertIn("the fallback summary could not be used 3 of 3 times", notice)
+ self.assertIsNone(engine._warm_notice)
def test_a_provider_inside_the_list_uses_the_warm_request(self):
engine = self.make(warm_providers="opencode-go, custom ")
@@ -1747,25 +1835,14 @@ class EngineTest(unittest.TestCase):
self.assertIs(self.engine.compress(messages), messages)
self.assertIsNone(self.engine.warm_last)
- def test_the_fixed_summary_quotes_the_cut_middle_of_the_prepended_row(self):
- # The prepended row is the latest user message; it is not copied, so its cut middle must stay in the
- # summary when no model summary is available.
- from warm_compaction.layout import MIN_COPY_CHARS
- from warm_compaction.rows import estimate_tokens
- from warm_compaction.warm import DEFAULT_RESERVE
- self.llm.error = RuntimeError("down")
+ def test_failed_summary_keeps_the_complete_prepended_row(self):
+ self.llm.error = RuntimeError("synthetic failure")
rows = [*old_turns(4), user("BIG start " + "q" * 1_000 + " MID-REQ " + "q" * 40_000 + " big end"),
assistant("", [("c1", "read", "{}")]), tool("c1", "r1"), assistant("done")]
engine = self.make(threshold=0.95, tail_tokens=2_000, warm=False)
engine.update_model(model=ROUTE[0], context_length=64_000, base_url=ROUTE[1], api_key="k",
provider="custom", api_mode=ROUTE[2])
- new = engine.compress(rows)
- self.assertEqual(engine.warm_last["path"], "fixed")
- prepended = next(row for row in new if str(row.get("content")).startswith("BIG start"))
- self.assertLessEqual(len(prepended["content"]), MIN_COPY_CHARS)
- self.assertNotIn("MID-REQ", prepended["content"])
- self.assertTrue(any("MID-REQ" in str(row.get("content")) for row in new if row.get("_compressed_summary")))
- self.assertLessEqual(estimate_tokens(new), min(engine.threshold_tokens, 64_000 - DEFAULT_RESERVE))
+ self.assert_aborted(engine, rows, "error:RuntimeError")
def test_a_provider_or_key_switch_forgets_the_capture(self):
# Two configurations can share the model, the base URL, and the API mode; the old body must not go out
@@ -1782,55 +1859,34 @@ class EngineTest(unittest.TestCase):
api_mode=ROUTE[2], **change)
self.assertIsNone(self.store.latest("s1"))
- def test_the_fixed_path_builds_the_tail_at_the_cap_that_the_summary_quotes(self):
- # Each quote makes the summary larger and the cap smaller. When the rounds stop before the cap is stable,
- # the tail must be cut at the cap whose cut the summary quotes, not at a smaller one.
- from warm_compaction import layout
- self.llm.error = RuntimeError("down")
- text = "".join(f"{index:07d}" for index in range(30_000))
- rows = [*old_turns(4), user("go"), assistant("", [("c1", "read", "{}")]), tool("c1", text)]
+ def test_a_failed_summary_does_not_build_replacement_history(self):
+ self.llm.error = RuntimeError("synthetic failure")
+ rows = [*old_turns(4), user("go"), assistant("", [("c1", "read", "{}")]),
+ tool("c1", "synthetic payload " * 30_000)]
engine = self.make(threshold=0.95, tail_tokens=30_000, warm=False)
- caps = iter(range(30_000, 0, -1_500))
- engine._tail_cap = lambda *args, **kwargs: next(caps)
- cuts, built = [], {}
- real_bound, real_build = layout.bound_tail, layout.build
-
- def bound(rows, tokens, removed=None, *args, **kwargs):
- if removed is not None:
- cuts.append(tokens)
- return real_bound(rows, tokens, removed, *args, **kwargs)
-
- def build(*args, **kwargs):
- built.update(kwargs)
- return real_build(*args, **kwargs)
- layout.bound_tail, layout.build = bound, build
- try:
- engine.compress(rows)
- finally:
- layout.bound_tail, layout.build = real_bound, real_build
- self.assertEqual(engine.warm_last["path"], "fixed")
- self.assertEqual(built["tail_tokens"], cuts[-1])
+ with patch("warm_compaction.layout.build") as build:
+ self.assert_aborted(engine, rows, "error:RuntimeError")
+ build.assert_not_called()
def test_a_large_captured_overhead_makes_a_short_history_compact(self):
- # The history fits the nominal tail, but the system rows and tool schemas of the captured request leave no
- # room for it and the reply reserve.
- rows = old_turns(4)
- reply = assistant("final")
+ # The warm request is above capacity, but the smaller model fallback summary fits.
+ rows, reply = old_turns(4), assistant("final")
engine = self.make(threshold=0.95)
engine.update_model(model=ROUTE[0], context_length=64_000, base_url=ROUTE[1], api_key="k",
provider="custom", api_mode=ROUTE[2])
self.seed(rows, reply, system={"role": "system", "content": "s " * 112_000}, extra={"max_tokens": 4_096})
history = [*rows, reply]
+ before = copy.deepcopy(history)
self.assertTrue(engine.should_compress_preflight(history))
self.assertTrue(engine.has_content_to_compress(history))
new = engine.compress(history)
self.assertIsNot(new, history)
self.assertLess(len(new), len(history))
+ self.assertEqual(history, before)
+ self.assertEqual((engine.warm_last["path"], engine.warm_last["reason"]), ("fallback", "capacity"))
+ self.assertEqual(len(self.llm.calls), 1)
def test_the_copied_messages_are_sized_after_the_tail_cut(self):
- # A huge newest unit fills the room before the cut; after the cut there is room for the copies, which the
- # fixed summary needs (it does not keep the earlier user text).
- self.llm.error = RuntimeError("down")
rows = [*old_turns(4), user("go")]
reply = assistant("", [("c1", "read", "{}")])
self.seed(rows, reply)
@@ -1838,7 +1894,7 @@ class EngineTest(unittest.TestCase):
engine.update_model(model=ROUTE[0], context_length=64_000, base_url=ROUTE[1], api_key="k",
provider="custom", api_mode=ROUTE[2])
new = engine.compress([*rows, reply, tool("c1", "t" * 400_000)])
- self.assertEqual(engine.warm_last["path"], "fixed")
+ self.assertEqual(engine.warm_last["path"], "fallback")
summary = "\n".join(str(row["content"]) for row in new if row.get("_compressed_summary"))
self.assertIn("ask 0 ", summary)
@@ -1947,42 +2003,28 @@ class EngineTest(unittest.TestCase):
self.assertIn("u" * 100, transcript)
self.assertTrue(any(str(row.get("content")).endswith(" end") for row in new))
- def test_a_fallback_summary_above_the_reserve_goes_to_the_fixed_summary(self):
- # A dense summary (CJK) can pass the byte gate and still be above the token reserve: the tail would then
- # cut more than the fallback transcript had.
+ def test_a_fallback_summary_above_the_reserve_stops_compaction(self):
dense = HEADINGS_TEXT.replace("Finish the test task.", "\u76ee\u6807" * 2_500)
self.llm = FakeLlm(text=dense + "\n" + END_LINE)
engine = self.make(warm=False)
- engine.compress([*old_turns(), assistant("done")])
- self.assertEqual(engine.warm_last["path"], "fixed")
+ self.assert_aborted(engine, [*old_turns(), assistant("done")], "summary_too_large")
- def test_the_fixed_summary_quotes_the_middle_that_the_final_tail_cuts(self):
- # A large earlier summary (CJK) makes the fixed summary larger than the reserve: the tail is cut at the
- # final cap, and the quote starts where the kept start ends.
- from warm_compaction.rows import MIDDLE_MARK
- self.llm.error = RuntimeError("down")
+ def test_failed_summary_keeps_the_earlier_summary_and_native_tail(self):
+ self.llm.error = RuntimeError("synthetic failure")
text = "".join(f"{index:07d}" for index in range(30_000))
rows = [assistant("\u65e7" * 9_000, _compressed_summary=True), *old_turns(4), user("go"),
assistant("", [("c1", "read", "{}")]), tool("c1", text)]
engine = self.make(threshold=0.95, tail_tokens=30_000, warm=False)
engine.update_model(model=ROUTE[0], context_length=64_000, base_url=ROUTE[1], api_key="k",
provider="custom", api_mode=ROUTE[2])
- new = engine.compress(rows)
- self.assertEqual(engine.warm_last["path"], "fixed")
- kept = next(row for row in new if row.get("role") == "tool")["content"]
- head = kept.split(MIDDLE_MARK)[0]
- summary = "\n".join(str(row["content"]) for row in new if row.get("_compressed_summary"))
- self.assertIn("> " + text[len(head):len(head) + 40], summary)
+ self.assert_aborted(engine, rows, "error:RuntimeError")
- def test_the_fixed_summary_gets_the_middles_that_the_tail_cuts(self):
- self.llm.error = RuntimeError("down")
+ def test_failed_summary_keeps_the_middles_that_the_tail_would_cut(self):
+ self.llm.error = RuntimeError("synthetic failure")
rows = [*old_turns(4), user("go"), assistant("", [("c1", "read", "{}")]),
tool("c1", "head " + "u" * 20_000 + " MIDDLE-FACT " + "u" * 20_000 + " end")]
engine = self.make(tail_tokens=2_000, warm=False)
- new = engine.compress(rows)
- self.assertEqual(engine.warm_last["path"], "fixed")
- self.assertTrue(any("## Key facts" in str(row.get("content")) and "u" * 50 in str(row.get("content"))
- for row in new))
+ self.assert_aborted(engine, rows, "error:RuntimeError")
def test_a_capture_with_a_changed_source_is_not_used_for_the_budget(self):
# A middleware removed a stored row: the captured body no longer shows which rows are the system rows.
diff --git a/tests/test_wc_fallback.py b/tests/test_wc_fallback.py
index dd27ecc..e8f50b0 100644
--- a/tests/test_wc_fallback.py
+++ b/tests/test_wc_fallback.py
@@ -1,14 +1,13 @@
-"""Tests for the fallback summary and the fixed-format summary."""
+"""Tests for the fallback model summary and its bounded quotes."""
import unittest
from types import SimpleNamespace
from warm_compaction.fallback import (
END_LINE, FALLBACK_INSTRUCTION, MAX_TOKENS, MIDDLE_MARK, TASK, TOOL_CHARS, TRANSCRIPT_CHARS, TRANSCRIPT_TOKENS,
- fixed_summary, llm_summary, render_row, transcript,
+ llm_summary, render_row, transcript,
)
from warm_compaction.rows import estimate_tokens
-from warm_compaction.handoff import HEADINGS
from wc_fixtures import assistant, tool, user
PREFIXES = ("[HERMES PREFIX]", "[CONTEXT SUMMARY]:")
@@ -214,62 +213,49 @@ class LlmSummaryTest(unittest.TestCase):
self.assertEqual(llm_summary(FakeLlm(error=RuntimeError("x")), [user("hi")], PREFIXES), (None, None))
self.assertIn("(RuntimeError)", logs.output[0])
+ def test_failure_metadata_has_codes_only(self):
+ private = "synthetic-private-provider-body"
+ cases = (
+ (None, "unavailable"),
+ (FakeLlm(error=RuntimeError(private)), "error:RuntimeError"),
+ (FakeLlm(text=""), "gate:missing_end_marker"),
+ (FakeLlm(text=SUMMARY), "gate:missing_end_marker"),
+ (FakeLlm(text="synthetic answer\n" + END_LINE), "gate:heading_missing"),
+ (FakeLlm(text=SUMMARY + "\n" + END_LINE, output_tokens=MAX_TOKENS), "gate:output_token_limit"),
+ )
+ for llm, reason in cases:
+ with self.subTest(reason=reason):
+ failure = {"reason": "old"}
+ self.assertEqual(llm_summary(llm, [user("synthetic request")], PREFIXES, failure=failure),
+ (None, None))
+ self.assertEqual(failure, {"reason": reason})
+ self.assertNotIn(private, str(failure))
+
+ def test_a_success_clears_old_failure_metadata(self):
+ failure = {"reason": "old"}
+ self.assertEqual(llm_summary(FakeLlm(), [user("synthetic request")], PREFIXES, failure=failure),
+ (SUMMARY, 321))
+ self.assertEqual(failure, {})
+
+ def test_an_unready_request_reports_cancelled_without_a_model_call(self):
+ llm, failure = FakeLlm(), {}
+ self.assertEqual(llm_summary(llm, [user("synthetic request")], PREFIXES,
+ ready=lambda: False, failure=failure), (None, None))
+ self.assertEqual(failure, {"reason": "cancelled"})
+ self.assertEqual(llm.calls, [])
+
+ def test_an_unsafe_exception_class_name_is_not_published(self):
+ unsafe = type("synthetic provider body / secret", (Exception,), {})
+ failure = {}
+ with self.assertLogs("warm_compaction.fallback", level="WARNING") as logs:
+ self.assertEqual(llm_summary(FakeLlm(error=unsafe("synthetic private message")),
+ [user("synthetic request")], PREFIXES, failure=failure), (None, None))
+ self.assertEqual(failure, {"reason": "error:Exception"})
+ self.assertNotIn("secret", str(logs.output))
+ self.assertNotIn("private message", str(logs.output))
-class FixedSummaryTest(unittest.TestCase):
- def test_the_fixed_summary_quotes_the_cut_middles(self):
- # Without a model summary, the middles that the tail cut are not lost: a bounded quote keeps them.
- from warm_compaction.layout import CUT_NOTE
- rows = [user("old"), assistant("a"), tool("c1", CUT_NOTE + "REQ-42 must stay " + "m" * 40_000 + " REQ-END")]
- text = fixed_summary(rows)
- self.assertIn("REQ-42 must stay", text)
- self.assertIn("REQ-END", text)
- self.assertLess(len(text), 12_000)
-
- def test_five_headings_and_tool_counts(self):
- rows = [assistant("", [("c1", "read", "{}"), ("c2", "read", "{}")]), assistant("", [("c3", "ls", "{}")])]
- text = fixed_summary(rows)
- for heading in HEADINGS:
- self.assertIn(heading + "\n", text)
- self.assertIn("- Tool calls: ls x1", text)
- self.assertIn("- Tool calls: read x2", text)
- self.assertIn("[OPEN] Continue from the latest user message.", text)
-
- def test_keeps_the_earlier_summary(self):
- # Goals and rules that only the earlier summary has must not be lost when both summary requests fail.
- old = assistant("[CONTEXT SUMMARY]:\n## Goal\nShip the old goal.\n## Next step\nold step\n\n"
- "--- END OF CONTEXT SUMMARY x", _compressed_summary=True)
- text = fixed_summary([old, user("x")], PREFIXES)
- self.assertIn("> ## Goal\n> Ship the old goal.", text)
- self.assertNotIn("END OF CONTEXT SUMMARY", text)
- self.assertEqual([line for line in text.splitlines() if line == "## Goal"], ["## Goal"])
- self.assertNotIn("earlier summary", fixed_summary([user("x")], PREFIXES))
-
- def test_all_quotes_share_one_budget(self):
- # The earlier summary, the focus, the memory context, and the cut middles together stay in the budget, and
- # each keeps a part.
- from warm_compaction.layout import CUT_NOTE
- from warm_compaction.rows import estimate_tokens
- old = assistant("[CONTEXT SUMMARY]:\nOLD-GOAL " + "o" * 40_000 + "\n\n--- END OF CONTEXT SUMMARY x ---",
- _compressed_summary=True)
- rows = [old, user("x"), tool("c1", CUT_NOTE + "CUT-START " + "m" * 40_000)]
- for budget in (4_096, 1_000):
- with self.subTest(budget=budget):
- text = fixed_summary(rows, PREFIXES, "FOCUS-START " + "f" * 40_000, "MEMORY-START " + "y" * 40_000,
- max_tokens=budget)
- self.assertLessEqual(estimate_tokens(text), budget)
- for mark in ("OLD-GOAL", "FOCUS-START", "MEMORY-START", "CUT-START"):
- self.assertIn(mark, text)
-
- def test_many_tool_names_stay_in_the_budget(self):
- # The tool inventory is in the budget too: the most used names stay, the others become one count.
- from warm_compaction.rows import estimate_tokens
- rows = [assistant("", [(f"c{index}", f"synthetic_tool_name_{index:04d}", "{}")]) for index in range(500)]
- rows.append(assistant("", [("x1", "read", "{}"), ("x2", "read", "{}")]))
- text = fixed_summary(rows, max_tokens=1_000)
- self.assertLessEqual(estimate_tokens(text), 1_000)
- self.assertIn("- Tool calls: read x2", text)
- self.assertIn("- Other tool calls:", text)
+class CutQuoteTest(unittest.TestCase):
def test_the_cut_quote_block_fits_its_budget_with_its_label(self):
from warm_compaction.fallback import cut_quote
from warm_compaction.layout import CUT_NOTE
@@ -281,9 +267,6 @@ class FixedSummaryTest(unittest.TestCase):
self.assertLessEqual(estimate_tokens(block), budget)
self.assertIn("m" * 50, cut_quote(rows, 2_000))
- def test_no_tool_calls(self):
- self.assertIn("- No tool calls.", fixed_summary([user("x")]))
-
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_wc_layout.py b/tests/test_wc_layout.py
index 414b8bb..a0bbd95 100644
--- a/tests/test_wc_layout.py
+++ b/tests/test_wc_layout.py
@@ -277,8 +277,7 @@ class BoundTailTest(unittest.TestCase):
self.assertNotIn("SECRET", str(removed))
def test_unsent_reasoning_is_not_cut_or_given_back(self):
- # A route that does not send reasoning: the private reasoning must not go to the fallback model or into
- # the fixed summary.
+ # A route that does not send reasoning: the private reasoning must not go to the fallback model.
from warm_compaction.layout import bound_tail
from warm_compaction.rows import SendPolicy
for key in ("reasoning", "reasoning_content"):
diff --git a/tests/test_wc_native.py b/tests/test_wc_native.py
index 6df9044..2a2cb3e 100644
--- a/tests/test_wc_native.py
+++ b/tests/test_wc_native.py
@@ -89,6 +89,7 @@ class NativeNoticeTest(unittest.TestCase):
def test_manual_compaction_logs_once_after_it_has_content(self):
from warm_compaction.native import NOTICE
+ from warm_compaction.engine import CompactionAborted
from wc_fixtures import assistant, user
rows = [user("synthetic old request " + "x" * 500), assistant("synthetic old answer " + "y" * 500),
user("synthetic latest request")]
@@ -97,7 +98,8 @@ class NativeNoticeTest(unittest.TestCase):
with patch("warm_compaction.engine.logger.info") as log:
self.engine.compress([])
log.assert_not_called()
- self.engine.compress(rows)
- self.engine.compress(rows)
+ for _ in range(2):
+ with self.assertRaises(CompactionAborted):
+ self.engine.compress(rows)
self.assertEqual(sum(call.args == (NOTICE,) for call in log.call_args_list), 1)
self.assertEqual(self.status(), NOTICE)
diff --git a/tests/test_wc_protocol.py b/tests/test_wc_protocol.py
index 6bf75c1..09d3010 100644
--- a/tests/test_wc_protocol.py
+++ b/tests/test_wc_protocol.py
@@ -248,24 +248,24 @@ class NativeTailTest(unittest.TestCase):
def test_native_replay_above_threshold_without_capture_keeps_history(self):
for mode in ("codex_responses", "anthropic_messages"):
with self.subTest(mode=mode):
- _fixture, engine, rows = self.native_history(mode, 36000)
+ fixture, engine, rows = self.native_history(mode, 36000)
self.assertIsNone(engine._store.latest(engine._wc_session_id))
self.assertGreater(sent_tokens(rows[-1], engine._policy(rows)), engine.threshold_tokens)
self.assertLess(sent_tokens(rows[-1], engine._policy(rows)) + 4096, engine.context_length)
- self.assertTrue(engine.compress(rows) is rows, "Oversized native replay must keep the original history")
+ fixture.assert_aborted(engine, rows, "capacity")
self.assertEqual(engine.compression_count, 0)
- self.assertEqual((engine.warm_last["path"], engine.warm_last["reason"]), ("unchanged", "capacity"))
+ self.assertEqual((engine.warm_last["path"], engine.warm_last["reason"]), ("aborted", "disabled"))
def test_native_replay_above_unknown_overhead_budget_keeps_history(self):
for mode in ("codex_responses", "anthropic_messages"):
with self.subTest(mode=mode):
- _fixture, engine, rows = self.native_history(mode, 20000)
+ fixture, engine, rows = self.native_history(mode, 20000)
replay_tokens = sent_tokens(rows[-1], engine._policy(rows))
self.assertGreater(replay_tokens, engine.threshold_tokens // 2)
self.assertLess(replay_tokens, engine.threshold_tokens)
- self.assertTrue(engine.compress(rows) is rows, "Oversized native replay must keep the original history")
+ fixture.assert_aborted(engine, rows, "capacity")
self.assertEqual(engine.compression_count, 0)
- self.assertEqual((engine.warm_last["path"], engine.warm_last["reason"]), ("unchanged", "capacity"))
+ self.assertEqual((engine.warm_last["path"], engine.warm_last["reason"]), ("aborted", "disabled"))
def test_native_replay_with_known_overhead_must_fit_below_threshold(self):
from warm_compaction import anthropic, responses
@@ -285,10 +285,9 @@ class NativeTailTest(unittest.TestCase):
total = sent_tokens(rows[-1], engine._policy(rows)) + request_overhead(capture, rows)
self.assertGreater(total, engine.threshold_tokens)
self.assertLess(total + 4096, engine.context_length)
- self.assertTrue(engine.compress(rows) is rows,
- "Oversized native replay must keep the original history")
+ fixture.assert_aborted(engine, rows, "capacity")
self.assertEqual(engine.compression_count, 0)
- self.assertEqual((engine.warm_last["path"], engine.warm_last["reason"]), ("unchanged", "capacity"))
+ self.assertEqual((engine.warm_last["path"], engine.warm_last["reason"]), ("aborted", "disabled"))
def test_small_native_replay_without_capture_can_compact(self):
from warm_compaction.rows import estimate_tokens, sent_rows
@@ -348,10 +347,9 @@ class NativeTailTest(unittest.TestCase):
api_key="fake", provider="custom", api_mode="codex_responses")
rows = [*old_turns(3), {"role": "user", "content": "synthetic last request"},
{"role": "assistant", "content": "synthetic", "codex_reasoning_items": [{"data": "x" * 100000}]}]
- result = engine.compress(rows)
- self.assertIs(result, rows)
+ fixture.assert_aborted(engine, rows, "capacity")
self.assertEqual(engine.compression_count, 0)
- self.assertEqual(engine.warm_last["reason"], "capacity")
+ self.assertEqual((engine.warm_last["path"], engine.warm_last["reason"]), ("aborted", "no_capture"))
if __name__ == "__main__":
diff --git a/warm_compaction/engine.py b/warm_compaction/engine.py
index cfaf4b5..5eae6d8 100644
--- a/warm_compaction/engine.py
+++ b/warm_compaction/engine.py
@@ -30,8 +30,6 @@ TAIL_MAX = 25_000
CARRIER_TOKENS = 500
# The summary size that the tail cap keeps free before the fallback summary is known: two times its reply
# limit, because the estimate and the server count do not use the same tokenizer.
-# Rounds of the fixed path: cut the tail, quote the cut, and size the cap again.
-FIXED_ROUNDS = 10
SUMMARY_RESERVE = 2 * fallback.MAX_TOKENS
# The largest reply reserve for an unknown reply limit: the Hermes output reserve of a native Gemini route.
UNKNOWN_RESERVE_MAX = 65_536
@@ -66,6 +64,14 @@ HERMES_END_MARKER = "--- END OF CONTEXT SUMMARY — respond to the message below
HERMES_DB_MARKER = "_db_persisted"
+class CompactionAborted(RuntimeError):
+ """A summary failure that stops compaction before history changes."""
+
+ def __init__(self, reason: str, fallback_reason: str) -> None:
+ super().__init__("Warm compaction stopped; history is unchanged "
+ f"(warm: {reason}; fallback: {fallback_reason}).")
+
+
def _valid(key: str, value: Any) -> bool:
if key == "warm":
return isinstance(value, bool)
@@ -357,20 +363,22 @@ class WarmCompactionEngine(ContextEngine):
layout.bound_tail(messages[start:], self._tail_cap(SUMMARY_RESERVE, overhead, reserve), removed, policy)
# Only the rows before the tail: the tail stays as it is, and a transcript of the whole history
# can spend its budget on the tail.
- # The plugin API has no request on a fixed route (an override needs a trust setting), and the auto
+ # The plugin API has no request on a set route (an override needs a trust setting), and the auto
# task follows the main route. The last check runs just before the request starts: after a switch,
# the old transcript does not go to the new route.
+ failure: dict[str, str] = {}
summary, _tokens = fallback.llm_summary(
self._llm, [*messages[:start], *removed], prefixes, focus_topic=focus_topic, memory_context=memory,
task=self._task, summary_words=self._settings["summary_words"],
- ready=lambda: not self._cancelled() and self._attempt() == attempt)
+ ready=lambda: not self._cancelled() and self._attempt() == attempt, failure=failure)
+ if summary is None:
+ record["fallback_reason"] = failure.get("reason", "unavailable")
if summary is not None and (estimate_tokens(summary) > SUMMARY_RESERVE
or not self._summary_fits(summary, overhead, reserve)):
# A dense summary (CJK, for example) above the reserve: the tail would cut more than the
# transcript had. Or above the room (a large system prompt and a low threshold): the next request
- # would compact again at once. The fixed summary quotes what the final tail cuts, in the room.
- logger.warning("Warm compaction fallback summary is above its token reserve or the free context; "
- "using the fixed summary")
+ # would compact again at once. Keep history when the summary does not fit.
+ record["fallback_reason"] = "summary_too_large"
summary = None
if summary is not None:
record["path"] = "fallback"
@@ -384,11 +392,8 @@ class WarmCompactionEngine(ContextEngine):
record.update(path="cancelled", reason="route_changed")
self._finish(record, started, attempt[-1])
return messages
- # The fixed summary takes at most the reserve, and at most the room.
- fixed_budget = self._fixed_budget(overhead, reserve)
if summary is None:
- summary = fallback.fixed_summary([*messages[:start], *removed], prefixes, focus_topic, memory, fixed_budget)
- record["path"] = "fixed"
+ return self._abort(messages, record, started, attempt)
# The prepended user row must be in the tail: when it does not fit in the room, keep its start and end.
# With an unknown overhead, the room is unknown too: the row keeps only its minimum. The room is after the
# tail as the cap cuts it: an uncut large tool result would leave no room.
@@ -408,7 +413,7 @@ class WarmCompactionEngine(ContextEngine):
# left (the tail cap stays at least the cap of the fallback transcript); the room keeps space
# for it.
left = max(0, min(fallback.CUT_QUOTE_CHARS // 4,
- self._fixed_budget(overhead, reserve) - estimate_tokens(summary) - 4))
+ self._summary_budget(overhead, reserve) - estimate_tokens(summary) - 4))
fitted = layout.fit_user_row(prepend, allowed - left, cut)
block = fallback.cut_quote(cut, left)
if block or not fallback.cut_quote(cut, fallback.CUT_QUOTE_CHARS // 4):
@@ -416,35 +421,11 @@ class WarmCompactionEngine(ContextEngine):
if block:
summary = summary.rstrip() + "\n\n" + block
else:
- # No quote fits after the summary: the cut middle would be lost. The fixed summary has
- # the room for it.
- logger.warning("No room for the cut quote after the fallback summary; using the fixed "
- "summary")
- record["path"] = "fixed"
- cut = []
- if record["path"] == "fixed":
- # The row is not copied and the fixed summary does not have it: its cut middle goes into the
- # summary as a quote. The room keeps space for that quote.
- prepend = layout.fit_user_row(prepend, allowed - fallback.CUT_QUOTE_CHARS // 4, cut)
- summary = fallback.fixed_summary([*messages[:start], *removed, *cut], prefixes, focus_topic, memory,
- fixed_budget)
+ # A required cut quote cannot fit. Keep the complete input history.
+ record["fallback_reason"] = "quote_capacity"
+ return self._abort(messages, record, started, attempt)
prepend_tokens = sent_tokens(prepend, policy) if prepend is not None else 0
tail_tokens = self._tail_cap(estimate_tokens(summary), overhead, reserve, prepend_tokens)
- if record["path"] == "fixed":
- # The fixed summary quotes what the tail cuts: cut and quote at the same cap. A larger summary makes a
- # smaller cap, and the cap only goes down. When the rounds stop before the cap is stable, the tail is
- # cut at the cap that the summary quotes: a little above the room, but no cut text is lost.
- for _round in range(FIXED_ROUNDS):
- final: list = []
- layout.bound_tail(messages[start:], tail_tokens, final, policy)
- if final != removed:
- removed = final
- summary = fallback.fixed_summary([*messages[:start], *removed, *cut], prefixes, focus_topic, memory,
- fixed_budget)
- lower = self._tail_cap(estimate_tokens(summary), overhead, reserve, prepend_tokens)
- if lower >= tail_tokens or _round == FIXED_ROUNDS - 1:
- break
- tail_tokens = lower
# The copies get the room after the tail as build cuts it: the uncut tail can be much larger.
copy_tokens = 0 if overhead is None else self._copy_tokens(
layout.bound_tail(messages[start:], tail_tokens, policy=policy), summary, overhead, reserve, policy)
@@ -472,15 +453,30 @@ class WarmCompactionEngine(ContextEngine):
return messages
if native_overflow:
# An indivisible native replay block cannot be cut to make a valid signed request.
- record.update(path="unchanged", reason="capacity")
- self._finish(record, started, attempt[-1])
- return messages
+ record["fallback_reason"] = "capacity"
+ return self._abort(messages, record, started, attempt)
self.compression_count += 1
self._finish(record, started, attempt[-1])
# The host can still reject this candidate. Only its successful boundary updates the failure streak.
self._pending_warm_result = (attempt[3], self.compression_count, dict(record))
return new
+ def _abort(self, messages: list, record: dict[str, Any], started: float, attempt: tuple) -> list:
+ """Stop a current attempt with safe metadata. A cancelled or stale attempt keeps its input."""
+ with self._wc_result_lock:
+ cancelled = self._cancelled()
+ if cancelled or self._attempt() != attempt:
+ record.update(path="cancelled", reason="cancelled" if cancelled else "route_changed")
+ self._finish(record, started, attempt[-1])
+ return messages
+ record["path"] = "aborted"
+ reason = str(record.get("reason") or "unavailable")
+ fallback_reason = str(record.get("fallback_reason") or "unavailable")
+ self._finish(record, started, attempt[-1])
+ logger.warning("Warm compaction stopped (warm=%s fallback=%s); history is unchanged",
+ reason, fallback_reason)
+ raise CompactionAborted(reason, fallback_reason) from None
+
def _policy(self, messages: list) -> SendPolicy:
"""The route-dependent fields that warm.wire_row sends: reasoning_details on a route that replays them,
the tool-call thought signature for a model that reads it, and reasoning_content on a route that needs it
@@ -558,7 +554,7 @@ class WarmCompactionEngine(ContextEngine):
record["reason"] = refusal.code
return None
except Exception as error:
- record["reason"] = f"error:{type(error).__name__}"
+ record["reason"] = f"error:{fallback.error_class(error)}"
return None
record.update(path="warm", reason="accepted")
return text
@@ -682,15 +678,14 @@ class WarmCompactionEngine(ContextEngine):
return limit - (overhead + estimate_tokens(sent_rows(tail_rows, policy)) + estimate_tokens(summary)
+ CARRIER_TOKENS)
- def _fixed_budget(self, overhead: int | None, reserve: int) -> int:
- """The token budget of the fixed summary: the summary reserve, and at most the free room (half of it with
+ def _summary_budget(self, overhead: int | None, reserve: int) -> int:
+ """The token budget of the model summary and its quotes: at most the free room (half of it with
an unknown overhead)."""
free = self._room([], "", overhead or 0, reserve)
if free is None:
return SUMMARY_RESERVE
if overhead is None:
free //= 2
- # Not above a small room: the headings take less, and the quotes then have no share.
return max(0, min(SUMMARY_RESERVE, free))
def _summary_fits(self, summary: str, overhead: int | None, reserve: int) -> bool:
@@ -757,12 +752,13 @@ class WarmCompactionEngine(ContextEngine):
return
record["elapsed_s"] = round(self._clock() - started, 3)
self.warm_last = record
- logger.info("warm_compaction: path=%s reason=%s elapsed_s=%s prompt_tokens=%s cached_tokens=%s",
+ logger.info("warm_compaction: path=%s reason=%s elapsed_s=%s prompt_tokens=%s cached_tokens=%s "
+ "fallback_reason=%s",
record["path"], record["reason"], record["elapsed_s"], record["prompt_tokens"],
- record["cached_tokens"])
+ record["cached_tokens"], record.get("fallback_reason"))
def _clear_warm_failures(self) -> None:
- self._warm_failures, self._warm_fixed = 0, 0
+ self._warm_failures = 0
self._warm_failure_reasons: list[str] = []
self._warm_notice: str | None = None
self._warm_notice_issued = False
@@ -781,12 +777,10 @@ class WarmCompactionEngine(ContextEngine):
logger.info("Warm compaction works again after %d compactions without it", self._warm_failures)
self._clear_warm_failures()
return
- if (path not in ("fallback", "fixed") or reason == "disabled"
- or (path == "fallback" and reason == "provider_not_allowed")):
+ if path != "fallback" or reason in ("disabled", "provider_not_allowed"):
return
logger.warning("Warm compaction skipped (%s); used the %s summary", reason, path)
self._warm_failures += 1
- self._warm_fixed += path == "fixed"
self._warm_failure_reasons.append(reason)
first_notice = ((not self._warm_notice_issued and self._warm_failures >= WARM_FAILURE_STREAK)
or (reason in HOST_COMPATIBILITY_REFUSALS and not self._warm_compatibility_notice_issued))
@@ -795,14 +789,8 @@ class WarmCompactionEngine(ContextEngine):
hints = "; ".join(
f"{item}: {FAILURE_HINTS.get(item.split(':', 1)[0], 'see the Limits section of the plugin README')}"
for item in dict.fromkeys(self._warm_failure_reasons))
- # The fixed summary has no model request: when the fallback also failed, the notice says so.
- if self._warm_fixed:
- continues = (f"Compaction continues, but the fallback summary could not be used {self._warm_fixed} of "
- f"{self._warm_failures} times, so those used the fixed summary (no model, less detail)")
- log_continues = f"compaction continues, {self._warm_fixed} of them with the fixed summary"
- else:
- continues = "Compaction continues with the fallback summary"
- log_continues = "compaction continues with the fallback summary"
+ continues = "Compaction continues with the fallback summary"
+ log_continues = "compaction continues with the fallback summary"
# The Hermes warning style on screen: the sign, the subject, what continues, and where to look.
compatibility = ("Hermes compatibility check failed; "
if HOST_COMPATIBILITY_REFUSALS.intersection(self._warm_failure_reasons) else "")
diff --git a/warm_compaction/fallback.py b/warm_compaction/fallback.py
index e95a5da..d9001d0 100644
--- a/warm_compaction/fallback.py
+++ b/warm_compaction/fallback.py
@@ -1,4 +1,4 @@
-"""The fallback summary through ctx.llm, and the fixed-format summary."""
+"""The fallback model summary through ctx.llm."""
from __future__ import annotations
@@ -28,10 +28,9 @@ ARGUMENT_CHARS = 300
CUT_MARK = " [cut]"
ROW_CHARS = 4_000
MIN_PART_CHARS = 200
-# The fixed summary quotes the middles that the tail cut (layout.bound_tail): at most this many characters.
+# A valid model summary can quote the middles that the tail cut: at most this many characters.
CUT_QUOTE_CHARS = 8_000
-# The default budget of the whole fixed summary (the summary reserve of the engine), and the smallest quote.
-FIXED_TOKENS = 2 * MAX_TOKENS
+# The smallest quote.
MIN_QUOTE_TOKENS = 16
# Token limits for dense text (CJK text, emoji): the character limits divided by 4. ASCII text meets the two
# limits at about the same point; dense text meets the token limit first, so a small fallback model can read it.
@@ -196,13 +195,25 @@ def _complete_reply(result: Any, raw: str) -> tuple[str | None, str]:
return None, "\n".join(lines[:-1])
+def error_class(error: Exception) -> str:
+ """Return a bounded exception class name without its message or data."""
+ name = type(error).__name__
+ return name if name.isascii() and name.isidentifier() and len(name) <= 80 else "Exception"
+
+
def llm_summary(llm: Any, messages: list, prefixes: Iterable[str], *, focus_topic: str | None = None,
memory_context: str = "", task: str | None = TASK, timeout_s: float = TIMEOUT_S,
summary_words: int = DEFAULT_SUMMARY_WORDS,
- ready: Callable[[], bool] | None = None) -> tuple[str | None, int | None]:
+ ready: Callable[[], bool] | None = None,
+ failure: dict[str, str] | None = None) -> tuple[str | None, int | None]:
"""Return (summary text, prompt tokens) from ctx.llm, or (None, None) when the request or the reply fails.
- ready is the last check before the request starts: when it is false, no request is sent."""
+ ready is the last check before the request starts: when it is false, no request is sent.
+ failure gets a refusal code or an exception class only. It never gets provider text."""
+ if failure is not None:
+ failure.clear()
if llm is None:
+ if failure is not None:
+ failure["reason"] = "unavailable"
return None, None
prefixes = tuple(prefixes)
# The start (the focus line) and the end of a large memory context.
@@ -213,11 +224,16 @@ def llm_summary(llm: Any, messages: list, prefixes: Iterable[str], *, focus_topi
{"role": "user", "content": transcript(messages, prefixes, len(extra), estimate_tokens(extra))},
]
if ready is not None and not ready():
+ if failure is not None:
+ failure["reason"] = "cancelled"
return None, None
try:
result = llm.complete(request, task=task, max_tokens=MAX_TOKENS, timeout=timeout_s, purpose=PURPOSE)
except Exception as error:
- logger.warning("Warm compaction fallback summary request failed (%s)", type(error).__name__)
+ name = error_class(error)
+ if failure is not None:
+ failure["reason"] = f"error:{name}"
+ logger.warning("Warm compaction fallback summary request failed (%s)", name)
return None, None
# The same checks as the warm reply: the five headings, the byte limit, and no summary markers. A reply
# without them (cut off, or an answer to the conversation) must not replace the history.
@@ -227,29 +243,14 @@ def llm_summary(llm: Any, messages: list, prefixes: Iterable[str], *, focus_topi
if reason is None:
text, reason = gate({"content": body, "finish_reason": "stop"}, prefixes)
if text is None:
+ if failure is not None:
+ failure["reason"] = f"gate:{reason}"
logger.warning("Warm compaction fallback summary refused (%s)", reason)
return None, None
tokens = getattr(getattr(result, "usage", None), "input_tokens", None)
return text, tokens if isinstance(tokens, int) and tokens > 0 else None
-def _tool_lines(counts: collections.Counter, max_tokens: int) -> list[str]:
- """One line for each tool name, in about half of max_tokens: when they do not fit, the most used names stay
- and one line counts the others."""
- if not counts:
- return ["- No tool calls."]
- ranked = sorted(counts.items(), key=lambda item: (-item[1], item[0]))
- keep = len(ranked)
- while True:
- lines = [f"- Tool calls: {name} x{count}" for name, count in sorted(ranked[:keep])]
- rest = ranked[keep:]
- if rest:
- lines.append(f"- Other tool calls: {len(rest)} names, {sum(count for _name, count in rest)} calls.")
- if keep == 0 or estimate_tokens("\n".join(lines)) <= max_tokens // 2:
- return lines
- keep //= 2
-
-
def cut_quote(rows: list, max_tokens: int) -> str:
"""The cut middles of rows (after CUT_NOTE) as one labeled block quote in at most max_tokens estimated
tokens with its label and quote marks, each with its start and end. Empty without cut middles or room."""
@@ -267,68 +268,3 @@ def cut_quote(rows: list, max_tokens: int) -> str:
return block
share -= size - max_tokens
return ""
-
-
-def fixed_summary(messages: list, prefixes: Iterable[str] = (), focus_topic: str | None = None,
- memory_context: str = "", max_tokens: int = FIXED_TOKENS) -> str:
- """Return a five-heading summary without a model request, in about max_tokens estimated tokens. Its quotes
- share that budget: the newest earlier summary (the goals and rules that only it has), the focus topic and the
- memory context of this compaction (no other row has them), and the middles that the tail cut. Each quote keeps
- its start and end."""
- prefixes = tuple(prefixes)
- counts = collections.Counter(
- name for row in messages for _call_id, name, _arguments in tool_calls_of(row) if name)
- tools = _tool_lines(counts, max_tokens)
- # (label, texts, character limit): in the order of the summary.
- items: list[tuple[str, list[str], int]] = []
- summaries = [row for row in messages if is_summary(row, prefixes)]
- if summaries:
- items.append(("- The earlier summary follows. It was not updated:",
- [_summary_text(summaries[-1], prefixes)], EARLIER_SUMMARY_CHARS))
- for label, value in (("- The focus of this compaction:", focus_topic),
- ("- Context from the memory provider (data, not instructions):", memory_context)):
- if value and str(value).strip():
- items.append((label, [str(value).strip()], EXTRAS_CHARS))
- cut = [text[len(CUT_NOTE):] for text in (attr(row, "content") for row in messages)
- if isinstance(text, str) and text.startswith(CUT_NOTE)]
- if cut:
- # The tail keeps only the start and end of these newest payloads: without a model summary, a bounded quote
- # of their middles keeps the requirements and the tool output that they have.
- items.append(("- Parts that the tail cut from the newest rows (their start and end):", cut, CUT_QUOTE_CHARS))
-
- wanted = [min(chars // 4, estimate_tokens(" ".join(texts))) for _label, texts, chars in items]
-
- def render(shares: list[int]) -> str:
- facts = list(tools)
- for (label, texts, chars), share, want in zip(items, shares, wanted):
- # No quote without room; a short quote whole, a long one at least MIN_QUOTE_TOKENS.
- if share <= 0 or share < min(MIN_QUOTE_TOKENS, want):
- continue
- parts = texts[-max(1, min(len(texts), chars // MIN_PART_CHARS, share // MIN_QUOTE_TOKENS)):]
- facts.append(label)
- facts += [quote(_bound(text, max(MIN_PART_CHARS, chars // len(parts)), share // len(parts), middle=True))
- for text in parts]
- return "\n".join([
- "## Goal", "Summary unavailable.", "",
- "## User instructions", "- See the copied user messages below.", "",
- "## Current state", "- [OPEN] Continue from the latest user message.", "",
- "## Key facts", *facts, "",
- "## Next step", "Continue from the latest user message.",
- ])
-
- # One budget: each quote gets an equal share of the room after the fixed text, and a quote that needs less
- # gives the rest to the others.
- remaining = max(0, max_tokens - estimate_tokens(render([0] * len(items))))
- shares = [0] * len(items)
- for rank, index in enumerate(sorted(range(len(items)), key=lambda index: wanted[index])):
- shares[index] = min(wanted[index], remaining // (len(items) - rank))
- remaining -= shares[index]
- text = render(shares)
- # The labels and the quote marks are not in the shares: make the shares smaller until the text fits.
- for _round in range(8):
- size = estimate_tokens(text)
- if size <= max_tokens:
- break
- shares = [share * max_tokens // (size + 1) - 1 for share in shares]
- text = render(shares)
- return text