feat: make context compaction visible in channels (#5656)

* feat: surface context compaction lifecycle

* fix: complete and simplify context compaction notifications
This commit is contained in:
chengyongru authored and GitHub committed 2026-09-05 20:21:54 +08:00
1 parent 455533169d
commit 5229989f28
52 files changed
+1849 -140

No files matched your search

+57 -14
View File
@@ -13,8 +13,10 @@ from nanobot.agent.context_governance import (
ContextGovernanceConfig,
ContextGovernor,
ContextWindowExceededError,
ModelRequestState,
)
from nanobot.agent.runner import AgentRunner, AgentRunSpec
from nanobot.bus.outbound_events import ContextCompactionEvent
from nanobot.config.schema import AgentDefaults
from nanobot.providers.base import (
LLMProvider,
@@ -23,6 +25,7 @@ from nanobot.providers.base import (
ProviderConversationState,
ToolCallRequest,
)
from nanobot.providers.conversation_state import ProviderConversationStateController
from nanobot.session.summary import SUMMARY_CONTINUATION_TEXT
_MAX_TOOL_RESULT_CHARS = AgentDefaults().max_tool_result_chars
@@ -369,7 +372,13 @@ async def test_native_compaction_uses_provider_request_boundary(
lambda *_args: (100, "test-counter"),
)
consolidate = AsyncMock(return_value="portable checkpoint")
consolidate_native = AsyncMock(return_value="portable checkpoint")
consolidate_native = AsyncMock(
return_value="portable checkpoint"
)
compaction_events: list[ContextCompactionEvent] = []
async def observe_compaction(event: ContextCompactionEvent) -> None:
compaction_events.append(event)
result = await AgentRunner().run(make_run_spec(
provider,
@@ -391,6 +400,7 @@ async def test_native_compaction_uses_provider_request_boundary(
max_tokens=100,
max_iterations=2,
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
compaction_callback=observe_compaction,
))
consolidate.assert_not_awaited()
@@ -405,6 +415,10 @@ async def test_native_compaction_uses_provider_request_boundary(
assert result.provider_compaction_applied is True
assert any(message.get("content") == "inspect the project" for message in result.messages)
assert any(message.get("content") == "complete tool result" for message in result.messages)
assert [event.phase for event in compaction_events] == ["started", "succeeded"]
assert {event.compaction_id for event in compaction_events} == {
compaction_events[0].compaction_id
}
async def test_runner_keeps_current_tool_exchange_outside_summary(monkeypatch):
@@ -506,7 +520,14 @@ async def test_repeated_pressure_advances_summary_boundary(monkeypatch):
"nanobot.agent.context_governance.estimate_prompt_tokens_chain",
estimate,
)
consolidate = AsyncMock(side_effect=["checkpoint-1", "checkpoint-2"])
consolidate = AsyncMock(side_effect=[
"checkpoint-1",
"checkpoint-2",
])
compaction_events: list[ContextCompactionEvent] = []
async def observe_compaction(event: ContextCompactionEvent) -> None:
compaction_events.append(event)
result = await AgentRunner().run(make_run_spec(
provider,
@@ -521,6 +542,7 @@ async def test_repeated_pressure_advances_summary_boundary(monkeypatch):
max_tokens=100,
max_iterations=3,
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
compaction_callback=observe_compaction,
))
assert consolidate.await_count == 2
@@ -533,6 +555,13 @@ async def test_repeated_pressure_advances_summary_boundary(monkeypatch):
assert result.summary_checkpoint is not None
assert result.summary_checkpoint.summary == "checkpoint-2"
assert result.summary_checkpoint.transcript_boundary == 4
assert [event.phase for event in compaction_events] == [
"started", "succeeded", "started", "succeeded",
]
first_id, second_id = compaction_events[0].compaction_id, compaction_events[2].compaction_id
assert first_id == compaction_events[1].compaction_id
assert second_id == compaction_events[3].compaction_id
assert first_id != second_id
async def test_runner_refuses_checkpoint_that_cannot_fit_with_delta(monkeypatch):
@@ -874,7 +903,7 @@ async def test_runner_fits_max_iteration_finalization_before_dispatch(monkeypatc
("input_tokens", "expected_fitted"),
[(500, True), (100, False)],
)
def test_matching_reported_provider_usage_avoids_local_estimate(
async def test_matching_reported_provider_usage_avoids_local_estimate(
monkeypatch,
input_tokens,
expected_fitted,
@@ -901,18 +930,25 @@ def test_matching_reported_provider_usage_avoids_local_estimate(
governor = ContextGovernor()
monkeypatch.setattr(governor, "fit_to_budget", lambda *_args, **_kwargs: [])
_messages, fitted = governor.fit_request(
_governance_config(provider, tools, spec),
state = ModelRequestState(
config=_governance_config(provider, tools, spec),
conversation=ProviderConversationStateController(
provider=provider, model=spec.runtime.model, messages=spec.initial_messages,
),
usage=LLMUsage.reported(input_tokens=input_tokens, output_tokens=10),
messages=spec.initial_messages,
tool_definitions=[],
)
messages, _context = await governor.prepare_request(
state,
spec.initial_messages,
LLMUsage.reported(input_tokens=input_tokens, output_tokens=10),
usage_matches_messages=True,
tool_definitions=tools.get_definitions(),
)
assert fitted is expected_fitted
assert messages == ([] if expected_fitted else spec.initial_messages)
def test_changed_messages_use_local_estimate_after_reported_usage(monkeypatch):
async def test_changed_messages_use_local_estimate_after_reported_usage(monkeypatch):
provider = MagicMock(spec=LLMProvider)
tools = MagicMock()
tools.get_definitions.return_value = []
@@ -934,15 +970,22 @@ def test_changed_messages_use_local_estimate_after_reported_usage(monkeypatch):
governor = ContextGovernor()
monkeypatch.setattr(governor, "fit_to_budget", lambda *_args, **_kwargs: [])
_messages, fitted = governor.fit_request(
_governance_config(provider, tools, spec),
state = ModelRequestState(
config=_governance_config(provider, tools, spec),
conversation=ProviderConversationStateController(
provider=provider, model=spec.runtime.model, messages=spec.initial_messages,
),
usage=LLMUsage.reported(input_tokens=900, output_tokens=10),
messages=[{"role": "user", "content": "previous request"}],
tool_definitions=[],
)
messages, _context = await governor.prepare_request(
state,
spec.initial_messages,
LLMUsage.reported(input_tokens=900, output_tokens=10),
usage_matches_messages=False,
tool_definitions=tools.get_definitions(),
)
assert fitted is True
assert messages == []
estimate.assert_called_once()