fix: use summary checkpoints for all compaction triggers (#5694)

* fix: exclude archived history after manual compaction

* refactor: share summary checkpoints across compaction paths

* fix: use summary checkpoints for every compaction trigger

* test: assert replay starts at the archived boundary

* fix: preserve nothing summaries without raw fallback

* test: assert compaction results positively

* test: verify checkpoint continuation after session reload
This commit is contained in:
chengyongru authored and GitHub committed 2026-09-08 13:16:45 +08:00
1 parent c039a7052a
commit 3548aec576
18 files changed
+335 -271

No files matched your search

+8 -6
View File
@@ -9,8 +9,12 @@ from typing import TYPE_CHECKING, Any, Callable, Coroutine
from loguru import logger
from nanobot.events import NO_EVENTS, EventSink
from nanobot.session.manager import MIN_COMPACTED_REPLAY_MESSAGES, Session, SessionManager
from nanobot.session.summary import SessionSummary, session_summary_from_metadata
from nanobot.session.manager import Session, SessionManager
from nanobot.session.summary import (
SessionSummary,
is_summary_checkpoint,
session_summary_from_metadata,
)
if TYPE_CHECKING:
from nanobot.agent.memory import Consolidator
@@ -20,7 +24,6 @@ SessionEventFactory = Callable[[str], EventSink]
class AutoCompact:
_RECENT_SUFFIX_MESSAGES = MIN_COMPACTED_REPLAY_MESSAGES
_INTERNAL_SESSION_PREFIXES = ("dream:",)
def __init__(self, sessions: SessionManager, consolidator: Consolidator,
@@ -54,7 +57,7 @@ class AutoCompact:
def _has_unarchived_messages(self, key: str) -> bool:
session = self.sessions.get_or_create(key)
return any(
not message.get("_command")
not message.get("_command") and not is_summary_checkpoint(message)
for message in session.messages[session.last_archived:]
)
@@ -95,10 +98,9 @@ class AutoCompact:
summary = await self.consolidator.compact_idle_session(
key,
runtime=runtime,
max_suffix=self._RECENT_SUFFIX_MESSAGES,
events=self._bind_events(key) if self._bind_events else NO_EVENTS,
)
if summary and summary != "(nothing)":
if summary:
session = self.sessions.get_or_create(key)
stored = session_summary_from_metadata(
session.metadata,
+1 -1
View File
@@ -142,7 +142,7 @@ class ContextBuilder:
if skills_summary:
parts.append(render_template("agent/skills_section.md", skills_summary=skills_summary))
if session_summary:
if session_summary and session_summary["text"] != "(nothing)":
parts.append(
"[Archived Context Summary]\n\n"
f"Previous conversation summary (last active {session_summary['last_active']}):\n"
+4 -32
View File
@@ -99,7 +99,6 @@ from nanobot.session.recovery import (
restore_runtime_checkpoint,
)
from nanobot.session.summary import (
SUMMARY_CONTINUATION_TEXT,
SessionSummary,
SessionSummaryCheckpoint,
)
@@ -2140,32 +2139,6 @@ class AgentLoop:
return filtered
@staticmethod
def _insert_summary_checkpoint(
session: Session,
checkpoint: SessionSummaryCheckpoint,
*,
insert_at: int | None = None,
) -> None:
"""Commit a replacement summary and its hidden transcript boundary."""
hint = {
"role": "user",
"content": SUMMARY_CONTINUATION_TEXT,
HIDDEN_HISTORY_META: True,
"timestamp": datetime.now().isoformat(),
}
if insert_at is None:
session.messages.append(hint)
checkpoint_session_index = len(session.messages) - 1
else:
session.messages.insert(insert_at, hint)
checkpoint_session_index = insert_at
session.metadata["_last_summary"] = {
"text": checkpoint.summary,
"last_active": session.updated_at.isoformat(),
}
session.last_archived = checkpoint_session_index
@staticmethod
def _validated_checkpoint_boundary(
checkpoint: SessionSummaryCheckpoint | None,
@@ -2227,9 +2200,8 @@ class AgentLoop:
# the first message after the replacement checkpoint.
if summary_checkpoint is not None and checkpoint_boundary == skip - 1:
insert_at = len(session.messages) - (1 if input_persisted_early else 0)
self._insert_summary_checkpoint(
session,
summary_checkpoint,
session.commit_summary_checkpoint(
summary_checkpoint.summary,
insert_at=insert_at,
)
@@ -2237,7 +2209,7 @@ class AgentLoop:
# Insert against the raw transcript index before filtering the
# message so persistence cleanup cannot shift the H/Δ boundary.
if summary_checkpoint is not None and checkpoint_boundary == message_index:
self._insert_summary_checkpoint(session, summary_checkpoint)
session.commit_summary_checkpoint(summary_checkpoint.summary)
entry = dict(message)
followup_id_value = cast(object, entry.pop(PENDING_FOLLOWUP_ID_KEY, None))
@@ -2319,7 +2291,7 @@ class AgentLoop:
if tc.get("id")
)
if summary_checkpoint is not None and checkpoint_boundary == len(messages):
self._insert_summary_checkpoint(session, summary_checkpoint)
session.commit_summary_checkpoint(summary_checkpoint.summary)
if turn_latency_ms is not None and last_assistant_idx is not None:
session.messages[last_assistant_idx]["latency_ms"] = int(turn_latency_ms)
if saved_followup_ids:
+19 -59
View File
@@ -25,12 +25,8 @@ from nanobot.events import NO_EVENTS, ContextCompactionEvent, EventSink
from nanobot.llm_usage.context import llm_usage_source
from nanobot.providers.base import ProviderCallContext, ProviderConversationState
from nanobot.runtime_context import public_history_messages
from nanobot.session.manager import (
MIN_COMPACTED_REPLAY_MESSAGES,
Session,
SessionManager,
)
from nanobot.session.summary import session_summary_from_metadata
from nanobot.session.manager import Session, SessionManager
from nanobot.session.summary import is_summary_checkpoint, session_summary_from_metadata
from nanobot.utils.gitstore import GitStore
from nanobot.utils.helpers import (
content_with_media_breadcrumbs,
@@ -947,7 +943,7 @@ class MemoryArchiver:
"""Archive a captured session prefix without mutating the session."""
messages = [
message for message in session.messages[session.last_archived:archive_end]
if not message.get("_command")
if not message.get("_command") and not is_summary_checkpoint(message)
]
if not messages:
return None
@@ -1080,13 +1076,6 @@ class Consolidator:
fallback_max_tokens=max(1, checkpoint_tokens),
provider_state=provider_state,
)
if summary == "(nothing)":
summary = self.archiver._raw_checkpoint(
source_messages,
session_key=session_key,
previous_summary=previous_summary,
max_tokens=max_output_tokens,
)
if summary is None:
return None
return truncate_text_to_tokens(summary, max(1, max_output_tokens))
@@ -1120,19 +1109,6 @@ class Consolidator:
return []
return session.get_history()
@staticmethod
def _set_last_summary(
session: Session,
summary: str,
*,
last_active: datetime | None = None,
) -> None:
if summary != "(nothing)":
session.metadata["_last_summary"] = {
"text": summary,
"last_active": (last_active or session.updated_at).isoformat(),
}
def estimate_session_prompt_tokens(
self,
session: Session,
@@ -1187,22 +1163,14 @@ class Consolidator:
session_key: str,
*,
runtime: LLMRuntime,
max_suffix: int = MIN_COMPACTED_REPLAY_MESSAGES,
max_suffix: int = 0,
events: EventSink = NO_EVENTS,
) -> str | None:
"""Archive the full idle tail while keeping recent messages replayable.
"""Replace archived history with a summary checkpoint.
``max_suffix`` remains accepted for SDK compatibility. Replay retention
is now derived independently from archive progress using the project-wide
compacted-session window.
``max_suffix`` is accepted for SDK compatibility and no longer retains
archived messages. All compaction triggers share checkpoint replay.
"""
if max_suffix != MIN_COMPACTED_REPLAY_MESSAGES:
logger.debug(
"Idle-session compact for {} uses the fixed replay window ({}, requested {})",
session_key,
MIN_COMPACTED_REPLAY_MESSAGES,
max_suffix,
)
lock = self.get_lock(session_key)
async with lock:
self.sessions.invalidate(session_key)
@@ -1210,7 +1178,11 @@ class Consolidator:
archive_start = session.last_archived
messages_to_archive = list(session.messages[archive_start:])
if not any(not message.get("_command") for message in messages_to_archive):
has_new_messages = any(
not message.get("_command") and not is_summary_checkpoint(message)
for message in messages_to_archive
)
if not has_new_messages:
return ""
compaction_id = uuid4().hex
@@ -1221,20 +1193,13 @@ class Consolidator:
archive_end = archive_start + len(messages_to_archive)
try:
summary = await self.archive_session(
session,
archive_end=archive_end,
runtime=runtime,
session, archive_end=archive_end, runtime=runtime,
)
if summary is not None:
self._set_last_summary(
session,
summary,
last_active=last_active,
if summary:
# Concurrent appends remain after the captured boundary.
session.commit_summary_checkpoint(
summary, insert_at=archive_end, last_active=last_active,
)
# A turn can append while the provider call is in flight. Advance only
# through the captured batch so new messages remain eligible next time.
session.last_archived = archive_end
# Resume from the summary and retained transcript, not the old provider history.
session.provider_state = None
self.sessions.save(session)
@@ -1246,7 +1211,7 @@ class Consolidator:
),
)
raise
if summary is None:
if not summary:
await events.emit(
ContextCompactionEvent(compaction_id=compaction_id, phase="failed"),
)
@@ -1259,16 +1224,11 @@ class Consolidator:
),
)
visible = session.get_history(
max_messages=MIN_COMPACTED_REPLAY_MESSAGES,
extend_to_user=True,
)
logger.info(
"Idle-session compact for {}: archived={}, visible={}, retained={}, summary={}",
session_key,
len(messages_to_archive),
len(visible),
len(session.get_history()),
len(session.messages),
bool(summary),
)