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),
)
+3 -3
View File
@@ -209,7 +209,7 @@ class RuntimeClient:
return self._loop.bus.subscribe(handler, SessionTurnPersisted)
async def compact_session(self, session_key: str) -> SessionSnapshot:
"""Archive one session through the shared idle-compaction path."""
"""Summarize one session and exclude its archived messages from replay."""
session = self._loop.sessions.get_or_create(session_key)
runtime = self._loop.runtime_for_session(session)
await self._loop.consolidator.compact_idle_session(
@@ -218,8 +218,8 @@ class RuntimeClient:
)
return snapshot_from_session(self._loop.sessions.get_or_create(session_key))
async def compact_idle_session(self, session_key: str, *, max_suffix: int = 8) -> str | None:
"""Run idle-session compaction for one session and return the summary."""
async def compact_idle_session(self, session_key: str, *, max_suffix: int = 0) -> str | None:
"""Return a replacement summary; legacy ``max_suffix`` no longer retains history."""
session = self._loop.sessions.get_or_create(session_key)
runtime = self._loop.runtime_for_session(session)
return await self._loop.consolidator.compact_idle_session(
+29 -29
View File
@@ -27,7 +27,7 @@ from nanobot.runtime_context import (
RUNTIME_CONTEXT_HISTORY_META,
public_history_message,
)
from nanobot.session.history_visibility import is_hidden_history_message
from nanobot.session.history_visibility import HIDDEN_HISTORY_META, is_hidden_history_message
from nanobot.session.model_selection import SESSION_MODEL_PRESET_METADATA_KEY
from nanobot.session.summary import SUMMARY_CONTINUATION_TEXT
from nanobot.utils.helpers import (
@@ -42,7 +42,6 @@ from nanobot.utils.helpers import (
from nanobot.utils.subagent_channel_display import scrub_subagent_announce_body
SESSION_CACHE_MAX_SIZE = 128
MIN_COMPACTED_REPLAY_MESSAGES = 8
_MESSAGE_TIME_PREFIX_RE = re.compile(r"^\[Message Time: [^\]]+\]\n?")
_LOCAL_IMAGE_BREADCRUMB_RE = re.compile(r"^\[image: (?:/|~)[^\]]+\]\s*$")
_TOOL_CALL_ECHO_RE = re.compile(r'^\s*(?:generate_image|message)\([^)]*\)\s*$')
@@ -321,6 +320,27 @@ class Session:
self.messages.append(msg)
self.updated_at = datetime.now()
def commit_summary_checkpoint(
self,
summary: str,
*,
insert_at: int | None = None,
last_active: datetime | None = None,
) -> None:
"""Replace replay before a hidden boundary while preserving the transcript."""
boundary = len(self.messages) if insert_at is None else insert_at
self.messages.insert(boundary, {
"role": "user",
"content": SUMMARY_CONTINUATION_TEXT,
HIDDEN_HISTORY_META: True,
"timestamp": datetime.now().isoformat(),
})
self.metadata["_last_summary"] = {
"text": summary,
"last_active": (last_active or self.updated_at).isoformat(),
}
self.last_archived = boundary
def get_history(
self,
max_messages: int = 0,
@@ -331,39 +351,19 @@ class Session:
) -> list[dict[str, Any]]:
"""Return recent replayable messages for LLM input.
A committed in-turn checkpoint replaces its old prefix with the stored
A committed summary checkpoint replaces its old prefix with the stored
summary and resumes replay at a hidden continuation marker. A positive
``max_messages`` applies an additional caller-owned count limit.
"""
replay_start = self.last_archived
resumes_from_checkpoint = (
replay_start < len(self.messages)
and is_hidden_history_message(self.messages[replay_start])
and self.messages[replay_start].get("content") == SUMMARY_CONTINUATION_TEXT
)
if replay_start and not resumes_from_checkpoint:
recent_start = recent_message_start_index(
self.messages,
MIN_COMPACTED_REPLAY_MESSAGES,
extend_to_user=True,
)
replay_start = min(replay_start, recent_start)
replayable = self.messages[replay_start:]
replayable = self.messages[self.last_archived:]
if max_messages <= 0:
start_idx = 0
else:
unarchived_count = len(self.messages) - self.last_archived
if replay_start < self.last_archived and unarchived_count < max_messages:
# The archived replay suffix can exceed the nominal count when one
# tool-heavy turn spans the boundary. Preserve that complete turn.
start_idx = 0
else:
start_idx = recent_message_start_index(
replayable,
max_messages,
extend_to_user=extend_to_user,
)
start_idx = recent_message_start_index(
replayable,
max_messages,
extend_to_user=extend_to_user,
)
sliced = replayable[start_idx:]
# Avoid starting mid-turn when possible, except for proactive
+11 -1
View File
@@ -5,12 +5,22 @@ from __future__ import annotations
from collections.abc import Mapping
from dataclasses import dataclass
from datetime import datetime
from typing import TypedDict, cast
from typing import Any, TypedDict, cast
from nanobot.session.history_visibility import is_hidden_history_message
SUMMARY_CONTINUATION_TEXT = (
"Continue the active task from the working-memory checkpoint above."
)
def is_summary_checkpoint(message: Mapping[str, Any]) -> bool:
"""Identify the durable boundary of a replacement summary."""
return (
is_hidden_history_message(message)
and message.get("content") == SUMMARY_CONTINUATION_TEXT
)
class SessionSummary(TypedDict):
text: str
last_active: str
@@ -39,4 +39,4 @@ When space is limited, prioritize user corrections and preferences, then solutio
Return one concise retained fact per line in this form:
- [mark] fact
Use `(nothing)` when no fact qualifies and there is no active working state.
Use `(nothing)` when neither the previous checkpoint nor the current conversation contains a qualifying fact or active working state.