Skip to content

Commit bd272dd

Browse files
HYYAlexclaude
andcommitted
fix: reject incomplete summaries in SummarizationCompactor
SummarizationCompactor only checked that a summary reply had text and shrank the conversation. A reply cut off by the output limit (finish_reason "length") or a content filter ("content_filter") was wrapped as a summary and replaced the original messages, silently losing everything the summary had not reached yet. Such a reply now raises in _apply_summary, so it goes through the existing failure policy: by default the failure is logged and the previous history is kept; with raise_on_failure=True the RuntimeError is propagated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent caf8ef2 commit bd272dd

3 files changed

Lines changed: 62 additions & 5 deletions

File tree

‎haystack/hooks/compaction/summarization.py‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,9 @@
3131
# Recorded as the strategy on every summary this compactor produces, so a later run can recognize its own summaries.
3232
_STRATEGY = "summarization"
3333

34+
# A summary cut off by the output limit or a content filter is partial and must not replace the original messages.
35+
_INCOMPLETE_FINISH_REASONS = ("length", "content_filter")
36+
3437
_DEFAULT_SUMMARY_INSTRUCTION = """You are compacting one portion of a conversation between a user and an AI agent so \
3538
the agent can keep working with fewer tokens. You are shown only the portion being replaced. The rest of the \
3639
conversation, including the user's current request, stays in place and is not shown to you. Summarize only what you \
@@ -222,9 +225,9 @@ def __init__(
222225
:param summary_instruction: The prompt instructions for how to summarize a portion of the conversation.
223226
The default instructions ask for a summary with fixed sections covering the objective, decisions and
224227
constraints, completed work, exact identifiers, and unresolved work.
225-
:param raise_on_failure: Whether to raise an exception if the chat generator fails or returns a summary that
226-
does not shrink the conversation. By default the failure is logged and any successful partial compaction
227-
is returned.
228+
:param raise_on_failure: Whether to raise an exception if the chat generator fails, returns an incomplete
229+
summary (finish reason `length` or `content_filter`), or returns a summary that does not shrink the
230+
conversation. By default the failure is logged and any successful partial compaction is returned.
228231
:raises ValueError: If `min_keep_steps` is negative or `approximate_summary_tokens` is not positive.
229232
"""
230233
if min_keep_steps < 0:
@@ -431,10 +434,15 @@ def _apply_summary(
431434
:param before_tokens: The already measured size of `messages`.
432435
:param token_counter: The counter used to verify that the summary actually shrinks the conversation.
433436
:returns: The conversation with the selected messages replaced by the summary, and its measured token count.
434-
:raises RuntimeError: If the generator returned no usable text, or if the swap did not make the conversation
435-
smaller, in which case keeping the raw messages is the better outcome.
437+
:raises RuntimeError: If the generator returned no usable text or an incomplete summary, or if the swap did not
438+
make the conversation smaller, in which case keeping the raw messages is the better outcome.
436439
"""
437440
replies = result.get("replies") or []
441+
finish_reason = replies[-1].meta.get("finish_reason") if replies else None
442+
if finish_reason in _INCOMPLETE_FINISH_REASONS:
443+
raise RuntimeError(
444+
f"The Chat Generator returned an incomplete conversation summary (finish reason: {finish_reason})."
445+
)
438446
text = replies[-1].text if replies else None
439447
if not text or not text.strip():
440448
raise RuntimeError(
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
---
2+
fixes:
3+
- |
4+
``SummarizationCompactor`` no longer replaces conversation history with an incomplete summary. When the summary
5+
reply ends with ``finish_reason`` ``length`` (output limit reached) or ``content_filter``, the compaction now fails
6+
instead of swapping in the partial text: by default the failure is logged and the previous history is kept, and
7+
with ``raise_on_failure=True`` a ``RuntimeError`` is raised. Previously the partial summary silently replaced the
8+
original messages, so facts it had not reached yet were lost for the rest of the run.

‎test/hooks/compaction/test_summarization.py‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -440,6 +440,37 @@ def test_raises_when_the_generator_returns_no_usable_text(self, generator_factor
440440
with pytest.raises(RuntimeError, match="no usable text"):
441441
compactor.compact(messages=fresh_conversation_with_two_steps(), target_tokens=1, token_counter=COUNTER)
442442

443+
@pytest.mark.parametrize("finish_reason", ["length", "content_filter"])
444+
def test_keeps_the_conversation_when_the_summary_is_incomplete(self, finish_reason):
445+
generator = MockChatGenerator(
446+
response_fn=lambda messages: ChatMessage.from_assistant("partial", meta={"finish_reason": finish_reason})
447+
)
448+
compacted = SummarizationCompactor(generator, approximate_summary_tokens=1).compact(
449+
messages=fresh_conversation_with_two_steps(), target_tokens=1, token_counter=COUNTER
450+
)
451+
assert compacted is None
452+
453+
@pytest.mark.parametrize("finish_reason", ["length", "content_filter"])
454+
def test_raises_when_the_summary_is_incomplete(self, finish_reason):
455+
generator = MockChatGenerator(
456+
response_fn=lambda messages: ChatMessage.from_assistant("partial", meta={"finish_reason": finish_reason})
457+
)
458+
compactor = SummarizationCompactor(generator, approximate_summary_tokens=1, raise_on_failure=True)
459+
with pytest.raises(RuntimeError, match=f"incomplete conversation summary \\(finish reason: {finish_reason}\\)"):
460+
compactor.compact(messages=fresh_conversation_with_two_steps(), target_tokens=1, token_counter=COUNTER)
461+
462+
def test_accepts_a_summary_that_finished_normally(self):
463+
generator = MockChatGenerator(
464+
response_fn=lambda messages: ChatMessage.from_assistant("history", meta={"finish_reason": "stop"})
465+
)
466+
compacted = SummarizationCompactor(generator, approximate_summary_tokens=1).compact(
467+
messages=fresh_conversation_with_two_steps(), target_tokens=1, token_counter=COUNTER
468+
)
469+
assert compacted is not None
470+
assert [message.text for message in summaries(messages=compacted)] == [
471+
"<conversation_summary>\nhistory\n</conversation_summary>"
472+
]
473+
443474

444475
class TestConfiguration:
445476
@pytest.mark.parametrize(
@@ -506,3 +537,13 @@ async def test_compact_async_matches_compact(self):
506537
assert compacted == SummarizationCompactor(
507538
MockChatGenerator("async summary"), approximate_summary_tokens=1
508539
).compact(messages=messages, target_tokens=1, token_counter=COUNTER)
540+
541+
@pytest.mark.asyncio
542+
async def test_compact_async_keeps_the_conversation_when_the_summary_is_incomplete(self):
543+
generator = MockChatGenerator(
544+
response_fn=lambda messages: ChatMessage.from_assistant("partial", meta={"finish_reason": "length"})
545+
)
546+
compacted = await SummarizationCompactor(generator, approximate_summary_tokens=1).compact_async(
547+
messages=fresh_conversation_with_two_steps(), target_tokens=1, token_counter=COUNTER
548+
)
549+
assert compacted is None

0 commit comments

Comments
 (0)