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:
1 parent
c039a7052a
commit
3548aec576
18 files changed
+335
-271
No files matched your search
@@ -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,
|
||||
|
||||
@@ -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
@@ -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
@@ -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),
|
||||
)
|
||||
|
||||
@@ -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
@@ -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
|
||||
|
||||
@@ -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.
|
||||
@@ -15,6 +15,7 @@ from nanobot.command import CommandContext
|
||||
from nanobot.config.schema import AgentDefaults, Config
|
||||
from nanobot.events import NO_EVENTS
|
||||
from nanobot.providers.base import LLMResponse
|
||||
from nanobot.session.summary import SUMMARY_CONTINUATION_TEXT
|
||||
|
||||
|
||||
def _make_loop(
|
||||
@@ -116,7 +117,7 @@ def _make_fake_compact(
|
||||
"last_active": last_active.isoformat(),
|
||||
}
|
||||
|
||||
session.last_archived = archive_end
|
||||
session.commit_summary_checkpoint(s, insert_at=archive_end, last_active=last_active)
|
||||
loop.sessions.save(session)
|
||||
return s
|
||||
|
||||
@@ -298,16 +299,15 @@ class TestAutoCompact:
|
||||
|
||||
assert len(archived_messages) == 12
|
||||
session_after = loop.sessions.get_or_create("cli:test")
|
||||
assert len(session_after.messages) == 12
|
||||
assert len(session_after.messages) == 13
|
||||
assert session_after.messages[0]["content"] == "msg user 0"
|
||||
visible = session_after.get_history(max_messages=12)
|
||||
assert len(visible) == loop.auto_compact._RECENT_SUFFIX_MESSAGES
|
||||
assert visible[0]["content"] == "msg user 2"
|
||||
assert visible[-1]["content"] == "msg assistant 5"
|
||||
assert len(visible) == 1
|
||||
assert [m["content"] for m in visible] == [SUMMARY_CONTINUATION_TEXT]
|
||||
await loop.aclose()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_auto_compact_extends_recent_suffix_to_user_turn(self, tmp_path):
|
||||
async def test_auto_compact_replaces_entire_tool_turn(self, tmp_path):
|
||||
loop = _make_loop(tmp_path, session_ttl_minutes=15)
|
||||
session = loop.sessions.get_or_create("cli:test")
|
||||
_add_turns(session, 2, prefix="old")
|
||||
@@ -322,19 +322,7 @@ class TestAutoCompact:
|
||||
session_after = loop.sessions.get_or_create("cli:test")
|
||||
assert session_after.messages[0]["content"] == "old user 0"
|
||||
visible = session_after.get_history(max_messages=len(session_after.messages))
|
||||
assert len(visible) > loop.auto_compact._RECENT_SUFFIX_MESSAGES
|
||||
assert visible[0]["content"] == "record this"
|
||||
assert visible[-1]["content"] == "done"
|
||||
tool_results = {
|
||||
m.get("tool_call_id")
|
||||
for m in visible
|
||||
if m.get("role") == "tool"
|
||||
}
|
||||
assert all(
|
||||
tc["id"] in tool_results
|
||||
for m in visible
|
||||
for tc in (m.get("tool_calls") or [])
|
||||
)
|
||||
assert [m["content"] for m in visible] == [SUMMARY_CONTINUATION_TEXT]
|
||||
await loop.aclose()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -355,10 +343,8 @@ class TestAutoCompact:
|
||||
assert entry is not None
|
||||
assert entry["text"] == "User said hello."
|
||||
session_after = loop.sessions.get_or_create("cli:test")
|
||||
assert len(session_after.messages) == 12
|
||||
assert len(session_after.get_history(max_messages=12)) == (
|
||||
loop.auto_compact._RECENT_SUFFIX_MESSAGES
|
||||
)
|
||||
assert len(session_after.messages) == 13
|
||||
assert len(session_after.get_history(max_messages=12)) == 1
|
||||
await loop.aclose()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -586,12 +572,10 @@ class TestAutoCompactEdgeCases:
|
||||
await loop.auto_compact._archive("cli:test", runtime=loop.llm_runtime())
|
||||
|
||||
session_after = loop.sessions.get_or_create("cli:test")
|
||||
assert len(session_after.messages) == 12
|
||||
assert len(session_after.get_history(max_messages=12)) == (
|
||||
loop.auto_compact._RECENT_SUFFIX_MESSAGES
|
||||
)
|
||||
# "(nothing)" summary should not be stored
|
||||
assert "cli:test" not in loop.auto_compact._summaries
|
||||
assert len(session_after.messages) == 13
|
||||
assert len(session_after.get_history(max_messages=12)) == 1
|
||||
assert loop.auto_compact._summaries["cli:test"]["text"] == "(nothing)"
|
||||
assert session_after.metadata["_last_summary"]["text"] == "(nothing)"
|
||||
|
||||
await loop.aclose()
|
||||
|
||||
@@ -609,10 +593,8 @@ class TestAutoCompactEdgeCases:
|
||||
await loop.auto_compact._archive("cli:test", runtime=loop.llm_runtime())
|
||||
|
||||
session_after = loop.sessions.get_or_create("cli:test")
|
||||
assert len(session_after.messages) == 12
|
||||
assert len(session_after.get_history(max_messages=12)) == (
|
||||
loop.auto_compact._RECENT_SUFFIX_MESSAGES
|
||||
)
|
||||
assert len(session_after.messages) == 13
|
||||
assert len(session_after.get_history(max_messages=12)) == 1
|
||||
|
||||
await loop.aclose()
|
||||
|
||||
@@ -661,7 +643,7 @@ class TestAutoCompactIntegration:
|
||||
"Example: 'I walked to the store yesterday.'"
|
||||
)
|
||||
|
||||
# Phase 1: User has a conversation longer than the retained recent suffix
|
||||
# Phase 1: User has an extended conversation before compaction
|
||||
session.add_message("user", "I'm learning English, teach me past tense")
|
||||
session.add_message("assistant", "Past tense is used for actions completed in the past...")
|
||||
session.add_message("user", "Give me an example")
|
||||
@@ -834,10 +816,8 @@ class TestProactiveAutoCompact:
|
||||
await self._run_check_expired(loop)
|
||||
|
||||
session_after = loop.sessions.get_or_create("cli:test")
|
||||
assert len(session_after.messages) == 10
|
||||
assert len(session_after.get_history(max_messages=10)) == (
|
||||
loop.auto_compact._RECENT_SUFFIX_MESSAGES
|
||||
)
|
||||
assert len(session_after.messages) == 11
|
||||
assert len(session_after.get_history(max_messages=10)) == 1
|
||||
assert len(archived_messages) == 10
|
||||
entry = loop.auto_compact._summaries.get("cli:test")
|
||||
assert entry is not None
|
||||
@@ -1020,10 +1000,8 @@ class TestProactiveAutoCompact:
|
||||
|
||||
assert _fake_compact.state["count"] == 1
|
||||
s1_after = loop.sessions.get_or_create("cli:expired_idle")
|
||||
assert len(s1_after.messages) == 12
|
||||
assert len(s1_after.get_history(max_messages=12)) == (
|
||||
loop.auto_compact._RECENT_SUFFIX_MESSAGES
|
||||
)
|
||||
assert len(s1_after.messages) == 13
|
||||
assert len(s1_after.get_history(max_messages=12)) == 1
|
||||
s2_after = loop.sessions.get_or_create("cli:expired_active")
|
||||
assert len(s2_after.messages) == 12 # Preserved
|
||||
s3_after = loop.sessions.get_or_create("cli:recent")
|
||||
@@ -1152,10 +1130,8 @@ class TestSummaryPersistence:
|
||||
|
||||
# prepare_session should recover summary from metadata
|
||||
reloaded = loop.sessions.get_or_create("cli:test")
|
||||
assert len(reloaded.messages) == 12
|
||||
assert len(reloaded.get_history(max_messages=12)) == (
|
||||
loop.auto_compact._RECENT_SUFFIX_MESSAGES
|
||||
)
|
||||
assert len(reloaded.messages) == 13
|
||||
assert len(reloaded.get_history(max_messages=12)) == 1
|
||||
_, summary = loop.auto_compact.prepare_session(reloaded, "cli:test")
|
||||
|
||||
assert summary is not None
|
||||
|
||||
@@ -268,7 +268,6 @@ class TestCheckExpired:
|
||||
ac.consolidator.compact_idle_session.assert_awaited_once_with(
|
||||
"cli:old",
|
||||
runtime=admitted,
|
||||
max_suffix=ac._RECENT_SUFFIX_MESSAGES,
|
||||
events=NO_EVENTS,
|
||||
)
|
||||
|
||||
@@ -444,7 +443,6 @@ class TestArchiveDelegates:
|
||||
ac.consolidator.compact_idle_session.assert_awaited_once_with(
|
||||
"cli:test",
|
||||
runtime=runtime,
|
||||
max_suffix=ac._RECENT_SUFFIX_MESSAGES,
|
||||
events=NO_EVENTS,
|
||||
)
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@ from nanobot.runtime_context import (
|
||||
)
|
||||
from nanobot.session.keys import UNIFIED_SESSION_KEY, remember_last_channel
|
||||
from nanobot.session.manager import Session
|
||||
from nanobot.session.summary import SUMMARY_CONTINUATION_TEXT
|
||||
from nanobot.utils.llm_runtime import LLMRuntime
|
||||
from nanobot.utils.prompt_templates import render_template
|
||||
|
||||
@@ -127,11 +128,13 @@ async def _archive(
|
||||
|
||||
|
||||
class TestTurnTranscriptSummary:
|
||||
@pytest.mark.parametrize("summary", ["replacement checkpoint", "(nothing)"])
|
||||
async def test_uses_exact_accepted_prefix_and_existing_archiver(
|
||||
self,
|
||||
consolidator,
|
||||
mock_provider,
|
||||
runtime,
|
||||
summary,
|
||||
):
|
||||
accepted = [
|
||||
{"role": "system", "content": "stable system"},
|
||||
@@ -139,7 +142,7 @@ class TestTurnTranscriptSummary:
|
||||
]
|
||||
tools = [{"type": "function", "function": {"name": "inspect"}}]
|
||||
mock_provider.chat_with_retry.return_value = LLMResponse(
|
||||
content="replacement checkpoint",
|
||||
content=summary,
|
||||
)
|
||||
|
||||
result = await consolidator.summarize_transcript(
|
||||
@@ -150,7 +153,7 @@ class TestTurnTranscriptSummary:
|
||||
tools=tools,
|
||||
)
|
||||
|
||||
assert result == "replacement checkpoint"
|
||||
assert result == summary
|
||||
call = mock_provider.chat_with_retry.await_args.kwargs
|
||||
assert call["messages"][:-1] == accepted
|
||||
assert call["messages"][-1]["role"] == "user"
|
||||
@@ -474,7 +477,7 @@ class TestConsolidatorPromptEstimate:
|
||||
assert len(captured["history"]) == 160
|
||||
assert captured["history"][0]["content"].endswith("msg-0")
|
||||
|
||||
async def test_estimate_includes_recent_archived_replay(self, consolidator, runtime):
|
||||
async def test_estimate_excludes_archived_replay(self, consolidator, runtime):
|
||||
session = Session(key="test:archived-replay")
|
||||
for i in range(10):
|
||||
session.add_message("user", f"msg-{i}")
|
||||
@@ -490,8 +493,7 @@ class TestConsolidatorPromptEstimate:
|
||||
|
||||
consolidator.estimate_session_prompt_tokens(session, runtime=runtime)
|
||||
|
||||
assert len(captured["history"]) == 8
|
||||
assert captured["history"][0]["content"] == "msg-2"
|
||||
assert captured["history"] == []
|
||||
|
||||
class TestCompactIdleSession:
|
||||
"""Idle compaction tests."""
|
||||
@@ -519,7 +521,7 @@ class TestCompactIdleSession:
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_archives_full_tail_preserves_messages_and_replays_recent_suffix(
|
||||
async def test_archives_full_tail_preserves_messages_and_replays_checkpoint(
|
||||
self, real_consolidator, mock_provider, runtime
|
||||
):
|
||||
mock_provider.chat_with_retry.return_value = MagicMock(
|
||||
@@ -542,14 +544,12 @@ class TestCompactIdleSession:
|
||||
|
||||
sessions.invalidate("cli:test")
|
||||
reloaded = sessions.get_or_create("cli:test")
|
||||
assert len(reloaded.messages) == 40
|
||||
assert len(reloaded.messages) == 41
|
||||
assert reloaded.messages[0]["content"] == "user msg 0"
|
||||
assert reloaded.last_archived == 40
|
||||
assert reloaded.provider_state is None
|
||||
visible = reloaded.get_history(max_messages=40)
|
||||
assert len(visible) == 8
|
||||
assert visible[0]["content"] == "user msg 16"
|
||||
assert visible[-1]["content"] == "assistant msg 19"
|
||||
assert [m["content"] for m in visible] == [SUMMARY_CONTINUATION_TEXT]
|
||||
meta = reloaded.metadata.get("_last_summary")
|
||||
assert meta is not None
|
||||
assert meta["text"] == "Summary of old conversation."
|
||||
@@ -629,7 +629,7 @@ class TestCompactIdleSession:
|
||||
assert len(store.read_unprocessed_history(since_cursor=0)) == 1
|
||||
reloaded = sessions.get_or_create("cli:short")
|
||||
assert reloaded.last_archived == 2
|
||||
assert [message["content"] for message in reloaded.get_history()] == ["hello", "hi"]
|
||||
assert [message["content"] for message in reloaded.get_history()] == [SUMMARY_CONTINUATION_TEXT]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_idle_compaction_with_no_new_messages_is_noop(
|
||||
@@ -692,7 +692,7 @@ class TestCompactIdleSession:
|
||||
contents = [message.get("content", "") for message in sent["messages"]]
|
||||
assert "Archived conversation summary." in contents[0]
|
||||
assert "question-0" not in contents
|
||||
assert "question-9" in contents
|
||||
assert contents[1:-1] == [SUMMARY_CONTINUATION_TEXT]
|
||||
assert "Next question" in contents[-1]
|
||||
finally:
|
||||
await loop.aclose()
|
||||
@@ -715,6 +715,32 @@ class TestCompactIdleSession:
|
||||
assert reloaded.last_archived == 0
|
||||
assert "_last_summary" not in reloaded.metadata
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("summary", [None, ""])
|
||||
async def test_missing_summary_preserves_replay(self, real_consolidator, runtime, summary):
|
||||
sessions = real_consolidator.sessions
|
||||
session = sessions.get_or_create("cli:missing-summary")
|
||||
session.add_message("user", "Keep this context")
|
||||
session.provider_state = _provider_state()
|
||||
sessions.save(session)
|
||||
real_consolidator.archive_session = AsyncMock(return_value=summary)
|
||||
events = []
|
||||
|
||||
async def observe(event):
|
||||
events.append(event)
|
||||
|
||||
result = await real_consolidator.compact_idle_session(
|
||||
session.key, runtime=runtime, events=EventSink(observe),
|
||||
)
|
||||
|
||||
assert result is None
|
||||
assert [event.phase for event in events] == ["started", "failed"]
|
||||
sessions.invalidate(session.key)
|
||||
reloaded = sessions.get_or_create(session.key)
|
||||
assert reloaded.provider_state == _provider_state()
|
||||
assert reloaded.last_archived == 0
|
||||
assert reloaded.get_history() == [{"role": "user", "content": "Keep this context"}]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_new_messages_advance_existing_archive_progress(
|
||||
self, real_consolidator, mock_provider, runtime
|
||||
@@ -748,16 +774,15 @@ class TestCompactIdleSession:
|
||||
latest_build = real_consolidator.archiver._build_messages.call_args_list[-1].kwargs
|
||||
assert latest_build["session_summary"]["text"] == "First replacement checkpoint."
|
||||
latest_messages = mock_provider.chat_with_retry.await_args_list[-1].kwargs["messages"]
|
||||
assert [message["content"] for message in latest_messages[1:5]] == [
|
||||
"first user",
|
||||
"first assistant",
|
||||
assert [message["content"] for message in latest_messages[1:-1]] == [
|
||||
SUMMARY_CONTINUATION_TEXT,
|
||||
"second user",
|
||||
"second assistant",
|
||||
]
|
||||
assert latest_messages[-1]["content"] == _ARCHIVE_PROMPT
|
||||
sessions.invalidate("cli:incremental")
|
||||
reloaded = sessions.get_or_create("cli:incremental")
|
||||
assert reloaded.last_archived == 4
|
||||
assert reloaded.last_archived == 5
|
||||
assert reloaded.metadata["_last_summary"]["text"] == second
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -805,7 +830,7 @@ class TestCompactIdleSession:
|
||||
assert reloaded.metadata["_last_summary"]["text"] == fallback
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_nothing_keeps_previous_replacement_checkpoint(
|
||||
async def test_nothing_replaces_previous_checkpoint(
|
||||
self,
|
||||
real_consolidator,
|
||||
mock_provider,
|
||||
@@ -837,12 +862,13 @@ class TestCompactIdleSession:
|
||||
assert result == "(nothing)"
|
||||
sessions.invalidate("cli:nothing-after-summary")
|
||||
reloaded = sessions.get_or_create("cli:nothing-after-summary")
|
||||
assert reloaded.last_archived == 4
|
||||
assert reloaded.metadata["_last_summary"]["text"] == "Existing checkpoint."
|
||||
assert reloaded.last_archived == 5
|
||||
assert reloaded.metadata["_last_summary"]["text"] == result
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("max_suffix", [8, 0])
|
||||
async def test_concurrent_append_remains_unarchived(
|
||||
self, real_consolidator, mock_provider, runtime
|
||||
self, real_consolidator, mock_provider, runtime, max_suffix
|
||||
):
|
||||
sessions = real_consolidator.sessions
|
||||
session = sessions.get_or_create("cli:concurrent")
|
||||
@@ -859,17 +885,22 @@ class TestCompactIdleSession:
|
||||
|
||||
mock_provider.chat_with_retry.side_effect = append_during_archive
|
||||
|
||||
await real_consolidator.compact_idle_session("cli:concurrent", runtime=runtime)
|
||||
await real_consolidator.compact_idle_session(
|
||||
"cli:concurrent", runtime=runtime, max_suffix=max_suffix,
|
||||
)
|
||||
|
||||
sessions.invalidate("cli:concurrent")
|
||||
reloaded = sessions.get_or_create("cli:concurrent")
|
||||
assert len(reloaded.messages) == 4
|
||||
assert len(reloaded.messages) == 5
|
||||
assert reloaded.last_archived == 2
|
||||
assert reloaded.provider_state is None
|
||||
assert reloaded.get_history()[-1]["content"] == "late assistant"
|
||||
assert [m["content"] for m in reloaded.get_history()] == [
|
||||
SUMMARY_CONTINUATION_TEXT, "late user", "late assistant",
|
||||
]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_summarizes_retained_suffix_not_just_dropped_prefix(
|
||||
async def test_summarizes_latest_correction_with_full_history(
|
||||
self, real_consolidator, mock_provider, runtime
|
||||
):
|
||||
"""idleCompact must summarize over the full unarchived tail, including
|
||||
@@ -884,7 +915,7 @@ class TestCompactIdleSession:
|
||||
for i in range(18):
|
||||
session.add_message("user", f"user msg {i}")
|
||||
session.add_message("assistant", f"assistant msg {i}")
|
||||
# Final correction exchange lands inside the retained max_suffix window.
|
||||
# The latest correction must be included in the replacement summary.
|
||||
session.add_message("user", "no, that's wrong, use approach B")
|
||||
session.add_message("assistant", "CORRECTED_FINAL_RESULT_alpha")
|
||||
sessions.save(session)
|
||||
@@ -924,8 +955,8 @@ class TestCompactIdleSession:
|
||||
assert "user msg 0" in raw
|
||||
assert "RETAINED_SUFFIX_marker" in raw
|
||||
reloaded = sessions.get_or_create("cli:rawdrop")
|
||||
assert len(reloaded.messages) == 38
|
||||
assert reloaded.messages[-1]["content"] == "RETAINED_SUFFIX_marker"
|
||||
assert len(reloaded.messages) == 39
|
||||
assert reloaded.messages[-2]["content"] == "RETAINED_SUFFIX_marker"
|
||||
assert reloaded.provider_state is None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -975,10 +1006,10 @@ class TestCompactIdleSession:
|
||||
assert reloaded.metadata == {}
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_nothing_summary_not_stored(
|
||||
async def test_nothing_commits_checkpoint_once_without_raw_archive(
|
||||
self, real_consolidator, mock_provider, runtime
|
||||
):
|
||||
"""LLM returns '(nothing)' → neither history nor metadata stores it."""
|
||||
"""A model's decision to retain nothing is a successful replacement."""
|
||||
mock_provider.chat_with_retry.return_value = MagicMock(
|
||||
content="(nothing)", finish_reason="stop"
|
||||
)
|
||||
@@ -999,8 +1030,10 @@ class TestCompactIdleSession:
|
||||
assert second == ""
|
||||
|
||||
reloaded = sessions.get_or_create("cli:nothing")
|
||||
assert "_last_summary" not in reloaded.metadata
|
||||
assert reloaded.metadata["_last_summary"]["text"] == result
|
||||
assert real_consolidator.store.read_unprocessed_history(0) == []
|
||||
assert reloaded.last_archived == 20
|
||||
assert [m["content"] for m in reloaded.get_history()] == [SUMMARY_CONTINUATION_TEXT]
|
||||
mock_provider.chat_with_retry.assert_awaited_once()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -1028,19 +1061,10 @@ class TestCompactIdleSession:
|
||||
assert entries[0]["content"].startswith("[RAW] 20 messages")
|
||||
|
||||
reloaded = sessions.get_or_create("cli:fail")
|
||||
assert reloaded.messages == session.messages
|
||||
assert reloaded.messages[:-1] == session.messages
|
||||
assert reloaded.last_archived == 22
|
||||
assert reloaded.metadata["_last_summary"]["text"] == result
|
||||
assert [m["content"] for m in reloaded.get_history(max_messages=20)] == [
|
||||
"u6",
|
||||
"a6",
|
||||
"u7",
|
||||
"a7",
|
||||
"u8",
|
||||
"a8",
|
||||
"u9",
|
||||
"a9",
|
||||
]
|
||||
assert [m["content"] for m in reloaded.get_history(max_messages=20)] == [SUMMARY_CONTINUATION_TEXT]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_respects_last_archived(
|
||||
@@ -1063,7 +1087,7 @@ class TestCompactIdleSession:
|
||||
)
|
||||
assert result == "Tail summary."
|
||||
reloaded = sessions.get_or_create("cli:offset")
|
||||
assert len(reloaded.messages) == 60
|
||||
assert len(reloaded.messages) == 61
|
||||
assert reloaded.last_archived == 60
|
||||
|
||||
# Verify only the unarchived tail was processed:
|
||||
@@ -1077,7 +1101,7 @@ class TestCompactIdleSession:
|
||||
assert sent_messages[-1]["content"] == _ARCHIVE_PROMPT
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_full_archive_keeps_extended_legal_replay_suffix(
|
||||
async def test_full_archive_replaces_entire_tool_turn(
|
||||
self,
|
||||
real_consolidator,
|
||||
mock_provider,
|
||||
@@ -1100,25 +1124,11 @@ class TestCompactIdleSession:
|
||||
assert result == "Tail summary."
|
||||
|
||||
reloaded = sessions.get_or_create("cli:noncontiguous")
|
||||
assert len(reloaded.messages) == 25
|
||||
assert len(reloaded.messages) == 26
|
||||
assert reloaded.last_archived == 25
|
||||
assert [m["content"] for m in reloaded.get_history(max_messages=25)] == [
|
||||
"user-14",
|
||||
"assistant-00",
|
||||
"assistant-01",
|
||||
"assistant-02",
|
||||
"assistant-03",
|
||||
"assistant-04",
|
||||
"assistant-05",
|
||||
"assistant-06",
|
||||
"assistant-07",
|
||||
"assistant-08",
|
||||
"assistant-09",
|
||||
]
|
||||
assert [m["content"] for m in reloaded.get_history(max_messages=25)] == [SUMMARY_CONTINUATION_TEXT]
|
||||
|
||||
# #4264: idle compaction now summarizes the full unarchived tail, so
|
||||
# the dropped head (user-00) and retained suffix (user-14 through
|
||||
# assistant-09) are all summarized.
|
||||
# Both the first question and the final tool-heavy exchange are summarized.
|
||||
archived_call = mock_provider.chat_with_retry.call_args
|
||||
sent_content = [message.get("content") for message in archived_call.kwargs["messages"]]
|
||||
assert "user-00" in sent_content
|
||||
@@ -1168,8 +1178,8 @@ class TestCompactIdleSession:
|
||||
assert "tool_choice" not in call
|
||||
|
||||
reloaded = sessions.get_or_create("cli:tool-history")
|
||||
assert len(reloaded.messages) == 4
|
||||
assert reloaded.messages[-1]["content"] == "final answer"
|
||||
assert len(reloaded.messages) == 5
|
||||
assert reloaded.messages[-2]["content"] == "final answer"
|
||||
assert all(
|
||||
"memory overview" not in str(message.get("content", "")).lower()
|
||||
for message in reloaded.messages
|
||||
@@ -1298,8 +1308,6 @@ class TestCompactIdleSession:
|
||||
|
||||
sent = mock_provider.chat_with_retry.call_args.kwargs["messages"]
|
||||
assert [message.get("content") for message in sent[1:-1]] == [
|
||||
"already archived user",
|
||||
"already archived answer",
|
||||
"new user",
|
||||
"new answer",
|
||||
]
|
||||
|
||||
@@ -339,6 +339,11 @@ class TestBuildSystemPrompt:
|
||||
assert "Previous chat about Python." in result
|
||||
assert "[Archived Context Summary]" in result
|
||||
|
||||
def test_nothing_summary_builds_the_prompt_without_archived_context(self, tmp_path):
|
||||
builder = _builder(tmp_path)
|
||||
summary = {"text": "(nothing)", "last_active": "2026-08-19T10:00:00"}
|
||||
assert builder.build_system_prompt(session_summary=summary) == builder.build_system_prompt()
|
||||
|
||||
def test_sections_separated_by_separator(self, tmp_path):
|
||||
(tmp_path / "AGENTS.md").write_text("Rules.", encoding="utf-8")
|
||||
builder = _builder(tmp_path)
|
||||
|
||||
@@ -95,12 +95,6 @@ class TestNewCommandArchival:
|
||||
session.last_archived = len(session.messages) - 2
|
||||
ordinary_history = session.get_history()
|
||||
assert [message["content"] for message in ordinary_history] == [
|
||||
"msg1",
|
||||
"resp1",
|
||||
"msg2",
|
||||
"resp2",
|
||||
"msg3",
|
||||
"resp3",
|
||||
"msg4",
|
||||
"resp4",
|
||||
]
|
||||
|
||||
@@ -157,7 +157,7 @@ def test_orphan_trim_with_last_archived():
|
||||
assert all(m.get("role") != "tool" or m["tool_call_id"].startswith("new_") for m in history)
|
||||
|
||||
|
||||
def test_get_history_replays_recent_messages_after_full_archive():
|
||||
def test_get_history_does_not_replay_messages_after_full_archive():
|
||||
session = Session(key="test:fully-archived")
|
||||
for i in range(10):
|
||||
session.messages.append({"role": "user", "content": f"u{i}"})
|
||||
@@ -166,19 +166,10 @@ def test_get_history_replays_recent_messages_after_full_archive():
|
||||
|
||||
history = session.get_history(max_messages=100)
|
||||
|
||||
assert [message["content"] for message in history] == [
|
||||
"u6",
|
||||
"a6",
|
||||
"u7",
|
||||
"a7",
|
||||
"u8",
|
||||
"a8",
|
||||
"u9",
|
||||
"a9",
|
||||
]
|
||||
assert history == []
|
||||
|
||||
|
||||
def test_get_history_extends_archived_replay_to_preceding_user():
|
||||
def test_get_history_does_not_restore_archived_user_turn():
|
||||
session = Session(key="test:archived-tool-turn")
|
||||
session.messages.extend(
|
||||
[
|
||||
@@ -195,12 +186,11 @@ def test_get_history_extends_archived_replay_to_preceding_user():
|
||||
|
||||
history = session.get_history(max_messages=100)
|
||||
|
||||
assert history[0]["content"] == "run tools"
|
||||
assert history[-1]["content"] == "done"
|
||||
_assert_no_orphans(history)
|
||||
assert history == []
|
||||
assert len(session.messages) > 8
|
||||
|
||||
|
||||
def test_archived_tool_turn_can_extend_past_message_cap():
|
||||
def test_archived_tool_turn_stays_out_of_replay():
|
||||
session = Session(key="test:long-archived-tool-turn")
|
||||
session.messages.extend(
|
||||
[
|
||||
@@ -216,10 +206,8 @@ def test_archived_tool_turn_can_extend_past_message_cap():
|
||||
|
||||
history = session.get_history(max_messages=120)
|
||||
|
||||
assert len(history) > 120
|
||||
assert history[0]["content"] == "run many tools"
|
||||
assert history[-1]["content"] == "done"
|
||||
_assert_no_orphans(history)
|
||||
assert history == []
|
||||
assert len(session.messages) > 8
|
||||
|
||||
|
||||
# --- Edge: no tool messages at all ---
|
||||
|
||||
@@ -14,6 +14,8 @@ from nanobot.bus.runtime_events import TurnCompleted
|
||||
from nanobot.command.builtin import cmd_stop
|
||||
from nanobot.command.router import CommandContext
|
||||
from nanobot.providers.base import GenerationSettings, LLMResponse, ProviderConversationState
|
||||
from nanobot.session.history_visibility import is_hidden_history_message
|
||||
from nanobot.session.summary import SUMMARY_CONTINUATION_TEXT
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -73,8 +75,11 @@ async def test_compact_emits_one_lifecycle_and_keeps_the_session(loop, command)
|
||||
loop.sessions.invalidate("cli:test")
|
||||
reloaded = loop.sessions.get_or_create("cli:test")
|
||||
assert reloaded.provider_state is None
|
||||
assert reloaded.messages == session.messages
|
||||
assert reloaded.messages[:-1] == session.messages
|
||||
assert is_hidden_history_message(reloaded.messages[-1])
|
||||
assert reloaded.last_archived == 2
|
||||
assert [m["content"] for m in reloaded.get_history()] == [SUMMARY_CONTINUATION_TEXT]
|
||||
assert reloaded.metadata["_last_summary"]["text"] == "Portable checkpoint."
|
||||
assert len(loop.consolidator.store.read_unprocessed_history(0)) == 1
|
||||
|
||||
response = await loop._process_message(msg, runtime=loop.llm_runtime())
|
||||
@@ -83,6 +88,56 @@ async def test_compact_emits_one_lifecycle_and_keeps_the_session(loop, command)
|
||||
loop.provider.chat_with_retry.assert_awaited_once()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("trigger", ["manual", "idle"])
|
||||
@pytest.mark.parametrize("summary", ["The current task is to inspect the checkpoint.", "(nothing)"])
|
||||
async def test_checkpoint_continues_through_reloaded_session(loop, trigger, summary) -> None:
|
||||
key = "cli:checkpoint-resume"
|
||||
session = loop.sessions.get_or_create(key)
|
||||
session.add_message("user", "Inspect the checkpoint")
|
||||
session.add_message("assistant", "Inspection started")
|
||||
loop.sessions.save(session)
|
||||
loop.provider.estimate_prompt_tokens.return_value = (100, "test")
|
||||
loop.provider.chat_with_retry.return_value = LLMResponse(content=summary)
|
||||
|
||||
if trigger == "manual":
|
||||
await loop._process_message(
|
||||
InboundMessage(channel="cli", sender_id="user", chat_id="checkpoint-resume",
|
||||
content="/compact"),
|
||||
runtime=loop.llm_runtime(),
|
||||
)
|
||||
else:
|
||||
await loop.auto_compact._archive(key, runtime=loop.llm_runtime())
|
||||
|
||||
loop.sessions.invalidate(key)
|
||||
loop.auto_compact._summaries.clear()
|
||||
reloaded = loop.sessions.get_or_create(key)
|
||||
assert reloaded.metadata["_last_summary"]["text"] == summary
|
||||
assert reloaded.last_archived == 2
|
||||
assert reloaded.get_history() == [{"role": "user", "content": SUMMARY_CONTINUATION_TEXT}]
|
||||
|
||||
loop.provider.chat_with_retry.reset_mock()
|
||||
loop.provider.chat_with_retry.return_value = LLMResponse(content="Inspection complete.")
|
||||
response = await loop.process_direct("Continue the inspection", session_key=key)
|
||||
assert response.content == "Inspection complete."
|
||||
loop.provider.chat_with_retry.assert_awaited_once()
|
||||
sent = loop.provider.chat_with_retry.call_args.kwargs["messages"]
|
||||
expected_summary = reloaded.metadata["_last_summary"] if summary != "(nothing)" else None
|
||||
assert sent[0] == {
|
||||
"role": "system",
|
||||
"content": loop.context.build_system_prompt(channel="cli", session_summary=expected_summary),
|
||||
}
|
||||
assert [message["role"] for message in sent] == ["system", "user", "user"]
|
||||
assert sent[1] == {"role": "user", "content": SUMMARY_CONTINUATION_TEXT}
|
||||
assert "Continue the inspection" in sent[2]["content"]
|
||||
|
||||
loop.sessions.invalidate(key)
|
||||
resumed = loop.sessions.get_or_create(key)
|
||||
assert [message["role"] for message in resumed.get_history()] == ["user", "user", "assistant"]
|
||||
assert resumed.get_history()[0]["content"] == SUMMARY_CONTINUATION_TEXT
|
||||
assert resumed.get_history()[-1]["content"] == "Inspection complete."
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("legacy_commands", [False, True])
|
||||
async def test_empty_compact_finishes_silently_and_does_not_schedule_idle_archive(
|
||||
@@ -206,3 +261,47 @@ async def test_stop_finishes_inflight_compaction_as_cancelled(loop) -> None:
|
||||
reloaded = loop.sessions.get_or_create(key)
|
||||
assert reloaded.messages == session.messages
|
||||
assert reloaded.last_archived == 0
|
||||
assert reloaded.get_history() == session.get_history()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_idle_and_manual_compact_share_persisted_checkpoint(loop) -> None:
|
||||
key = "cli:test"
|
||||
session = loop.sessions.get_or_create(key)
|
||||
session.add_message("user", "large tool turn")
|
||||
for i in range(20):
|
||||
session.add_message("assistant", "", tool_calls=[{
|
||||
"id": f"tool-{i}", "type": "function",
|
||||
"function": {"name": "exec", "arguments": "{}"},
|
||||
}])
|
||||
session.add_message("tool", "x" * 10_000, tool_call_id=f"tool-{i}")
|
||||
session.add_message("assistant", "done")
|
||||
loop.sessions.save(session)
|
||||
runtime = loop.llm_runtime()
|
||||
await loop.consolidator.compact_idle_session(key, runtime=runtime)
|
||||
assert [m["content"] for m in loop.sessions.get_or_create(key).get_history()] == [
|
||||
SUMMARY_CONTINUATION_TEXT,
|
||||
]
|
||||
|
||||
await loop._process_message(
|
||||
InboundMessage(channel="cli", sender_id="user", chat_id="test", content="/compact"),
|
||||
runtime=runtime,
|
||||
)
|
||||
loop.provider.chat_with_retry.assert_awaited_once()
|
||||
assert loop.bus.outbound_size == 0
|
||||
loop.sessions.invalidate(key)
|
||||
reloaded = loop.sessions.get_or_create(key)
|
||||
assert len(reloaded.messages) == 43
|
||||
assert is_hidden_history_message(reloaded.messages[-1])
|
||||
assert [m["content"] for m in reloaded.get_history()] == [SUMMARY_CONTINUATION_TEXT]
|
||||
assert reloaded.metadata["_last_summary"]["text"] == "Portable checkpoint."
|
||||
|
||||
reloaded.add_message("user", "next question")
|
||||
reloaded.add_message("assistant", "next answer")
|
||||
loop.sessions.save(reloaded)
|
||||
await loop.consolidator.compact_idle_session(key, runtime=runtime)
|
||||
loop.sessions.invalidate(key)
|
||||
reloaded = loop.sessions.get_or_create(key)
|
||||
assert [m["content"] for m in reloaded.get_history()] == [
|
||||
SUMMARY_CONTINUATION_TEXT,
|
||||
]
|
||||
@@ -58,7 +58,9 @@ def test_valid_offset_is_preserved():
|
||||
session = _session(10, 4)
|
||||
assert session.last_consolidated == 4
|
||||
assert session.last_archived == 4
|
||||
assert len(session.get_history()) == 8
|
||||
assert session.get_history() == [
|
||||
{"role": "user", "content": f"msg{i}"} for i in range(4, 10)
|
||||
]
|
||||
|
||||
|
||||
def test_last_archived_field_migrates_with_legacy_alias(tmp_path: Path):
|
||||
|
||||
@@ -92,6 +92,9 @@ function sameMessageShape(a: MessageShape, b: MessageShape): boolean {
|
||||
function latestComposerContextUsage(messages: UIMessage[]): ComposerContextUsage | null {
|
||||
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
||||
const message = messages[index];
|
||||
if (message.kind === "compaction" && message.compaction?.phase === "succeeded") {
|
||||
return null;
|
||||
}
|
||||
const contextTokens = message.usage?.context_tokens;
|
||||
if (
|
||||
message.role !== "assistant"
|
||||
|
||||
@@ -497,6 +497,53 @@ describe("ThreadShell", () => {
|
||||
expect(screen.getByRole("img", {
|
||||
name: /input tokens 16,400.*KV cache hit rate 99%.*output tokens 236/i,
|
||||
})).toBeInTheDocument();
|
||||
expect(screen.getByTestId("composer-context-meter")).toBeInTheDocument();
|
||||
for (const phase of ["started", "failed"] as const) {
|
||||
act(() => client._emitChat("usage-chart", {
|
||||
event: "context_compaction", chat_id: "usage-chart", compaction_id: "failed", phase,
|
||||
}));
|
||||
expect(screen.getByTestId("composer-context-meter")).toBeInTheDocument();
|
||||
}
|
||||
act(() => client._emitChat("usage-chart", {
|
||||
event: "context_compaction", chat_id: "usage-chart",
|
||||
compaction_id: "success", phase: "succeeded",
|
||||
}));
|
||||
expect(trigger).toHaveAccessibleName("Open context usage");
|
||||
expect(screen.getAllByTestId("round-usage-bar")).toHaveLength(4);
|
||||
});
|
||||
|
||||
it.each([false, true])("restores context after compaction only with newer usage (%s)", async (newReply) => {
|
||||
const client = makeClient();
|
||||
const messages: UIMessage[] = [
|
||||
{
|
||||
id: "old", role: "assistant", content: "Before compact", createdAt: 1_000,
|
||||
contextWindowTokens: 1_000_000, usage: { context_tokens: 170_000 },
|
||||
roundUsages: [{ prompt_tokens: 170_000 }],
|
||||
},
|
||||
{
|
||||
id: "compact", role: "assistant", kind: "compaction", content: "", createdAt: 2_000,
|
||||
compaction: { id: "compact", phase: "succeeded" },
|
||||
},
|
||||
];
|
||||
if (newReply) messages.push({
|
||||
id: "new", role: "assistant", content: "After compact", createdAt: 3_000,
|
||||
contextWindowTokens: 1_000_000, usage: { context_tokens: 20_700 },
|
||||
});
|
||||
vi.stubGlobal("fetch", vi.fn((input: RequestInfo | URL) => Promise.resolve(
|
||||
String(input).includes("websocket%3Acompact-usage/webui-thread")
|
||||
? httpJson({ schemaVersion: 3, messages })
|
||||
: { ok: false, status: 404, json: async () => ({}) },
|
||||
)));
|
||||
render(wrap(client, <ThreadShell
|
||||
session={session("compact-usage")} title="Compact usage" onToggleSidebar={() => {}}
|
||||
settingsSnapshot={modelSettings("test-model", "deepseek")}
|
||||
/>));
|
||||
const trigger = await screen.findByTestId("composer-context-usage");
|
||||
if (newReply) {
|
||||
expect(trigger).toHaveAccessibleName("Context 2%. Open context usage");
|
||||
} else {
|
||||
expect(trigger).toHaveAccessibleName("Open context usage");
|
||||
}
|
||||
});
|
||||
|
||||
it("moves the session handle into the pane only when the workbench is split", () => {
|
||||
|
||||
Reference in new issue
Block a user