fix: reject length-capped compaction summaries (#8437)

* fix: 拒绝超过输出上限的压缩摘要

* fix: 识别原生 Ollama 摘要截断

* fix: 将 Ollama 截断检测限定在会话压缩
This commit is contained in:
Hazenix 2026-11-22 09:24:34 +08:00 committed by GitHub
parent 9809784e95
commit 9ba9bfad41
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
6 changed files with 206 additions and 2 deletions

View File

@ -53,6 +53,10 @@ durable or distributed cost budget. Callers without a thread ID keep only the
per-pass limit. Other generation failures retain their existing retry behavior.
Configured/run-model fallback may make two candidate attempts per chunk, and SDK
retries are separate. This bounds middleware steps, not a monetary bill or deadline.
If the provider reports an output token limit, including native Ollama's
`done_reason: length`, the chunk's partial response is discarded and the run-model
fallback is tried when available. If no candidate produces a complete summary,
compaction preserves the active history.
For legitimate histories beyond this limit, increase the existing per-call budget
within the model's capacity or compact earlier. There is no new configuration.
Impossibly small budgets that cannot fit a nonempty marked carry or source fail

View File

@ -87,6 +87,18 @@ class OpenAIResponsesLengthDetector:
return None
class OllamaLengthDetector:
"""Native Ollama ``done_reason == "length"`` signal."""
name = "ollama_length"
def detect(self, message: AIMessage) -> ModelLengthTermination | None:
value = _get_metadata_value(message, "done_reason")
if value != "length":
return None
return ModelLengthTermination(detector=self.name, reason_field="done_reason", reason_value=value)
class AnthropicMaxTokensDetector:
"""Anthropic ``stop_reason == "max_tokens"`` signal."""
@ -142,6 +154,7 @@ __all__ = [
"GeminiMaxTokensDetector",
"ModelLengthTermination",
"ModelLengthTerminationDetector",
"OllamaLengthDetector",
"OpenAICompatibleLengthDetector",
"OpenAIResponsesLengthDetector",
"default_detectors",

View File

@ -27,6 +27,7 @@ from langgraph.runtime import Runtime
from deerflow.agents.middlewares.dynamic_context_middleware import is_dynamic_context_reminder
from deerflow.agents.middlewares.message_utils import is_genuine_user_message
from deerflow.agents.middlewares.model_length_termination_detectors import OllamaLengthDetector, default_detectors
from deerflow.agents.middlewares.pii_redaction_middleware import redact_text
from deerflow.agents.middlewares.todo_middleware import TODO_REMINDER_MESSAGE_NAME
from deerflow.config.app_config import get_app_config
@ -46,6 +47,9 @@ _COMPACTION_TRANSFORM_VERSION = "2"
_UNSET = object()
_NOOP_CACHE_MAX_ENTRIES = 128
_MAX_SUMMARY_CHUNKS = 64
# Keep native Ollama detection local to compaction; the shared defaults also
# drive tool-call suppression and project document summaries.
_SUMMARY_LENGTH_DETECTORS = (*default_detectors(), OllamaLengthDetector())
_SUMMARY_CHUNK_RETRY_SECONDS = 300
_SUMMARY_CHUNK_RETRY_MAX_ENTRIES = 128
_SUMMARY_CHUNK_RETRY_CACHE: OrderedDict[str, tuple[float, int]] = OrderedDict()
@ -274,6 +278,8 @@ class DeerFlowSummarizationMiddleware(SummarizationMiddleware):
"chunk_limit_retry_seconds": _SUMMARY_CHUNK_RETRY_SECONDS,
"chunk_limit_retry_max_entries": _SUMMARY_CHUNK_RETRY_MAX_ENTRIES,
"summary_carry_budget_fraction": 0.5,
"reject_length_capped_summary": True,
"summary_length_detectors": [detector.name for detector in _SUMMARY_LENGTH_DETECTORS],
"summary_prompt_hash": canonical_hash(self.summary_prompt),
# Model objects are not JSON-serialisable. Keep generation and context
# budget ownership distinct in the identity: changing either can alter
@ -539,7 +545,7 @@ class DeerFlowSummarizationMiddleware(SummarizationMiddleware):
logger.warning("Summarization no-op cache store failed", exc_info=True)
def _invoke_summary(self, model: Any | None, prompt: str, *, last: bool = False) -> str | None:
"""Invoke ``model`` for a summary; ``None`` on error or a blank response.
"""Invoke ``model`` for a summary and return ``None`` on generation failure.
Text extraction / non-empty validation runs *inside* the try: reading the
response's ``.text`` is part of consuming the provider result, so a failing
@ -599,6 +605,10 @@ class DeerFlowSummarizationMiddleware(SummarizationMiddleware):
return None
def _checked_summary(self, response: Any, last: bool) -> str | None:
if any(detector.detect(response) is not None for detector in _SUMMARY_LENGTH_DETECTORS):
action = "skipping compaction this turn" if last else "falling back to the run model"
logger.warning("Summary model reached its output token limit; %s", action)
return None
summary = self._nonempty_summary(getattr(response, "text", None))
if summary is None:
self._log_summary_empty(last)

View File

@ -77,6 +77,20 @@ def test_additional_kwargs_finish_reason_length_records_stop_reason():
assert runtime.context["stop_reason"] == MODEL_LENGTH_CAPPED_STOP_REASON
def test_default_middleware_leaves_ollama_done_reason_to_compaction():
runtime = _runtime()
message = AIMessage(
content="Checking the input",
tool_calls=[{"name": "read_file", "args": {"path": "notes.txt"}, "id": "call-1"}],
response_metadata={"done_reason": "length"},
)
middleware = ModelLengthFinishReasonMiddleware()
assert middleware.after_model({"messages": [message]}, runtime) is None
assert "stop_reason" not in runtime.context
assert middleware.consume_stop_reason("run-1") is None
def test_gemini_max_tokens_finish_reason_records_stop_reason():
mw = ModelLengthFinishReasonMiddleware()
runtime = _runtime()

View File

@ -209,6 +209,22 @@ class TestGenerator:
assert (await docs.get("doc-1", user_id="u1"))["summary"] is None
assert generator.metrics()["failed"] == 1
async def test_ollama_done_reason_does_not_change_document_summary_policy(self, repos, text_file, monkeypatch):
sf, projects, docs = repos
project, _row = await _shelf_row(projects, docs)
_patch_source(monkeypatch, (text_file, None))
monkeypatch.setattr(summaries, "run_oneshot_llm_detailed", lambda **kwargs: _fake_model("A one-line summary", {"done_reason": "length"}))
generator = SummaryGenerator(session_factory=sf, paths=None, app_config=_app_config())
await generator.start()
try:
generator.enqueue(document_id="doc-1", project_id=project["id"], user_id="u1")
await _drain(generator)
finally:
await generator.stop()
assert (await docs.get("doc-1", user_id="u1"))["summary"] == "A one-line summary"
assert generator.metrics()["success"] == 1
async def test_anthropic_style_stop_reason_also_detected(self, repos, text_file, monkeypatch):
sf, projects, docs = repos
await _shelf_row(projects, docs)

View File

@ -13,9 +13,11 @@ from langchain_core.messages import AIMessage, HumanMessage, RemoveMessage, Syst
from langchain_core.messages.utils import count_tokens_approximately
from langchain_core.outputs import ChatGeneration, ChatResult
from langchain_core.runnables import RunnableBinding
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.constants import TAG_NOSTREAM
from pydantic import ValidationError
from pydantic import Field, ValidationError
from deerflow.agents.assembly_descriptor import describe_middleware
from deerflow.agents.memory.summarization_hook import memory_flush_hook
from deerflow.agents.middlewares.dynamic_context_middleware import _DYNAMIC_CONTEXT_REMINDER_KEY, DynamicContextMiddleware, is_dynamic_context_reminder
from deerflow.agents.middlewares.summarization_middleware import DeerFlowSummarizationMiddleware, SummarizationEvent, SummaryGenerationError, create_summarization_middleware
@ -890,6 +892,151 @@ def _blank_model(*, text: str = " \n\t ") -> MagicMock:
return model
class _CompactionSummaryModel(_StaticChatModel):
responses: list[AIMessage] = Field(default_factory=list)
prompts: list[str] = Field(default_factory=list)
def _generate(self, messages, stop=None, run_manager=None, **kwargs):
self.prompts.append("\n".join(message.text for message in messages))
response = self.responses.pop(0) if self.responses else AIMessage(content=self.text)
return ChatResult(generations=[ChatGeneration(message=response)])
def _compaction_with_response_models(primary, fallback, *, trim_tokens=None, before_summarization=None):
return DeerFlowSummarizationMiddleware(
model=primary,
trigger=("messages", 4),
keep=("messages", 2),
token_counter=lambda messages: sum(len(message.text) for message in messages),
trim_tokens_to_summarize=trim_tokens,
summary_prompt="{messages}",
configured_model_name="primary",
run_model_name="fallback",
anchor_model_name="primary",
prebuilt_models={"fallback": fallback},
before_summarization=before_summarization,
)
def _long_compaction_state():
messages = _messages()
messages[0].content = " ".join(f"fact_{index:03d}: distinct evidence" for index in range(24))
return {"messages": messages, "summary_text": "S"}
@pytest.mark.anyio
@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"])
@pytest.mark.parametrize(
"metadata",
[
{"finish_reason": "length"},
{"stop_reason": "max_tokens"},
{"finish_reason": "MAX_TOKENS"},
{"status": "incomplete", "incomplete_details": {"reason": "max_output_tokens"}},
{"done_reason": "length"},
],
ids=["openai-chat", "anthropic", "gemini", "openai-responses", "ollama"],
)
async def test_length_capped_middle_chunk_uses_fallback_before_next_carry(asynchronous, metadata):
primary = _CompactionSummaryModel(responses=[AIMessage(content="PRIMARY_ONE"), AIMessage(content="PARTIAL", response_metadata=metadata)])
fallback = _CompactionSummaryModel(text="FALLBACK_TWO")
middleware = _compaction_with_response_models(primary, fallback, trim_tokens=96)
state = _long_compaction_state()
update = await middleware.abefore_model(state, _runtime()) if asynchronous else middleware.before_model(state, _runtime())
assert update is not None
assert fallback.prompts == [primary.prompts[1]]
assert "<existing_summary>\nPRIMARY_ONE\n</existing_summary>" in primary.prompts[1]
assert "<existing_summary>\nFALLBACK_TWO\n</existing_summary>" in primary.prompts[2]
def test_compaction_release_policy_lists_supported_length_detectors():
middleware = _compaction_with_response_models(_CompactionSummaryModel(), _CompactionSummaryModel())
descriptor = describe_middleware(middleware)
assert descriptor.policy_parameters["summary_length_detectors"] == [
"openai_compatible_length",
"anthropic_max_tokens",
"gemini_max_tokens",
"openai_responses_length",
"ollama_length",
]
@pytest.mark.anyio
@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"])
@pytest.mark.parametrize("done_reason", ["length", "stop"])
async def test_ollama_summary_compaction_checkpoint(asynchronous, done_reason):
summary = AIMessage(content="Ollama summary", response_metadata={"done_reason": done_reason})
primary = _CompactionSummaryModel(responses=[summary])
fallback = _CompactionSummaryModel(responses=[summary.model_copy(deep=True)])
middleware = _compaction_with_response_models(primary, fallback)
graph = create_agent(_StaticChatModel(text="new answer"), middleware=[middleware], state_schema=ThreadState, checkpointer=InMemorySaver())
config = {"configurable": {"thread_id": "ollama-compaction"}}
messages = _messages()
for index, message in enumerate(messages):
message.id = f"message-{index}"
state = {"messages": messages, "summary_text": "S"}
if asynchronous:
await graph.ainvoke(state, config)
snapshot = await graph.aget_state(config)
else:
graph.invoke(state, config)
snapshot = graph.get_state(config)
persisted_messages = snapshot.values["messages"]
assert persisted_messages[-1].content == "new answer"
assert len(primary.prompts) == 1
if done_reason == "length":
assert persisted_messages[:2] == messages[:2]
assert snapshot.values["summary_text"] == "S"
assert fallback.prompts == primary.prompts
else:
assert {message.id for message in persisted_messages}.isdisjoint(message.id for message in messages[:2])
assert snapshot.values["summary_text"] == "Ollama summary"
assert fallback.prompts == []
@pytest.mark.anyio
@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"])
async def test_length_capped_final_chunk_preserves_history_and_retries(asynchronous):
state = _long_compaction_state()
control = _CompactionSummaryModel(text="S")
control_middleware = _compaction_with_response_models(control, _CompactionSummaryModel(), trim_tokens=96)
control_result = await control_middleware.abefore_model(state, _runtime()) if asynchronous else control_middleware.before_model(state, _runtime())
assert control_result is not None
chunk_count = len(control.prompts)
assert chunk_count > 1
capped = AIMessage(content="S", response_metadata={"finish_reason": "length"})
primary = _CompactionSummaryModel(responses=[AIMessage(content="S") for _ in range(chunk_count - 1)] + [capped, capped.model_copy(), AIMessage(content="COMPLETE")])
fallback = _CompactionSummaryModel(responses=[capped.model_copy(), capped.model_copy()])
hook = mock.Mock()
middleware = _compaction_with_response_models(primary, fallback, trim_tokens=96, before_summarization=[hook])
original_messages = list(state["messages"])
result = await middleware.abefore_model(state, _runtime()) if asynchronous else middleware.before_model(state, _runtime())
assert result is None
assert state["messages"] == original_messages
assert state["summary_text"] == "S"
hook.assert_not_called()
with pytest.raises(SummaryGenerationError):
if asynchronous:
await middleware.acompact_state(state, _runtime(), force=True, raise_on_failure=True)
else:
middleware.compact_state(state, _runtime(), force=True, raise_on_failure=True)
hook.assert_not_called()
result = await middleware.abefore_model(state, _runtime()) if asynchronous else middleware.before_model(state, _runtime())
assert result is not None and result["summary_text"] == "COMPLETE"
assert len(primary.prompts) == chunk_count + 2
assert len(fallback.prompts) == 2
hook.assert_called_once()
def test_null_model_summarizes_with_the_run_model(monkeypatch: pytest.MonkeyPatch) -> None:
"""model_name: null must summarize with the model the run actually uses, not
config.models[0]. This is the model-ownership fix: a run on a non-default model