feat(compaction): rebuild dynamic tool schemas at the compaction commit boundary — forever-sessions finally pick up config changes (#97073)
This commit is contained in:
@@ -234,6 +234,35 @@ def _builtin_memory_prompt_snapshot(agent: Any) -> Optional[Tuple[str, str]]:
|
||||
return memory, user
|
||||
|
||||
|
||||
def _refresh_agent_tool_definitions(agent) -> bool:
|
||||
"""Rebuild agent.tools at the compaction commit boundary.
|
||||
|
||||
Forever-sessions (Bot Mode desktop chats, gateway channels) never
|
||||
restart, so compaction is the only moment a config change can reach the
|
||||
tool snapshot: dynamic schemas (image_generate capability gating,
|
||||
delegate_task limits, execute_code interpreter/stub text) are built
|
||||
once at agent init and then frozen for cache stability. The prompt
|
||||
cache is already invalidated at this boundary, so refreshing here is
|
||||
free; between compactions the snapshot stays byte-stable as before.
|
||||
|
||||
Delegates to tools.mcp_tool.refresh_agent_mcp_tools — the single shared
|
||||
snapshot rebuild (atomic publish, generation guard, memory/LCM tool
|
||||
re-injection) — in content_aware mode, which also swaps when schema
|
||||
CONTENT changed under a stable name set (the dynamic-schema case; the
|
||||
name-only diff is sufficient for its MCP-reload callers). Returns True
|
||||
when new tools were added. Never raises: tool staleness must not fail
|
||||
a compaction.
|
||||
"""
|
||||
from tools.mcp_tool import refresh_agent_mcp_tools
|
||||
|
||||
added = refresh_agent_mcp_tools(agent, content_aware=True)
|
||||
if added:
|
||||
logger.info(
|
||||
"Compaction tool refresh added tools: %s", sorted(added),
|
||||
)
|
||||
return bool(added)
|
||||
|
||||
|
||||
def _cached_prompt_reflects_builtin_memory(agent: Any, cached_prompt: str) -> bool:
|
||||
"""Whether the cached system prompt already embeds current built-in memory.
|
||||
|
||||
@@ -3853,6 +3882,24 @@ def compress_context(
|
||||
cached_system_prompt = agent._cached_system_prompt
|
||||
agent._invalidate_system_prompt()
|
||||
|
||||
# Refresh dynamic tool schemas at the same admitted-commit boundary
|
||||
# that rebuilds the system prompt (maintainer-directed, #95681 arc):
|
||||
# forever-sessions (Bot Mode chats, gateway channels) never restart,
|
||||
# so compaction is the ONLY point where a config change — image
|
||||
# model swap, delegation depth, code_execution mode — can reach
|
||||
# agent.tools. The prompt cache is already broken here, so the
|
||||
# refresh is free; when nothing changed the snapshot is byte-equal
|
||||
# and we keep the existing list object (identity matters to
|
||||
# provider-side tool-block caching on some backends).
|
||||
try:
|
||||
_refresh_agent_tool_definitions(agent)
|
||||
except Exception: # noqa: BLE001
|
||||
logger.warning(
|
||||
"compaction tool-definition refresh failed; keeping the "
|
||||
"session's existing tool snapshot",
|
||||
exc_info=True,
|
||||
)
|
||||
|
||||
# Built-in memory is the only system-prompt input that a normal
|
||||
# compaction reloads. When the cached prompt already embeds the
|
||||
# freshly-reloaded memory blocks verbatim, keep the exact cached
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
"""Compaction rebuilds dynamic tool schemas (forever-session fix, #95681 arc).
|
||||
|
||||
Forever-sessions (Bot Mode, gateway channels) never restart; compaction is
|
||||
the only boundary where the prompt cache is already broken, so it is the
|
||||
one sanctioned point for a tool-snapshot rebuild. These tests pin:
|
||||
- refresh_agent_mcp_tools(content_aware=True) swaps on CONTENT change under
|
||||
a stable name set (the dynamic-schema case its name-only diff missed)
|
||||
- content_aware=False keeps the old no-churn behavior (MCP-reload callers)
|
||||
- the compaction helper is wired into the commit path and never raises
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
|
||||
|
||||
|
||||
class _Agent:
|
||||
quiet_mode = True
|
||||
enabled_toolsets = ["image_gen"]
|
||||
disabled_toolsets = None
|
||||
|
||||
|
||||
def _defs(desc):
|
||||
return [{"type": "function", "function": {
|
||||
"name": "image_generate", "description": desc,
|
||||
"parameters": {"type": "object", "properties": {}},
|
||||
}}]
|
||||
|
||||
|
||||
class TestContentAwareRefresh(unittest.TestCase):
|
||||
def _agent_with(self, desc):
|
||||
agent = _Agent()
|
||||
agent.tools = _defs(desc)
|
||||
agent.valid_tool_names = {"image_generate"}
|
||||
agent._tool_snapshot_generation = 0
|
||||
return agent
|
||||
|
||||
def _refresh(self, agent, new_desc, **kw):
|
||||
from tools.mcp_tool import refresh_agent_mcp_tools
|
||||
|
||||
with patch("model_tools.get_tool_definitions",
|
||||
return_value=_defs(new_desc)), \
|
||||
patch("tools.mcp_tool._reinject_post_build_tools",
|
||||
return_value=set()):
|
||||
return refresh_agent_mcp_tools(agent, **kw)
|
||||
|
||||
def test_content_change_swaps_when_content_aware(self):
|
||||
agent = self._agent_with("old capabilities text")
|
||||
self._refresh(agent, "new capabilities text", content_aware=True)
|
||||
self.assertIn("new capabilities",
|
||||
agent.tools[0]["function"]["description"])
|
||||
|
||||
def test_content_change_ignored_when_name_only(self):
|
||||
"""MCP-reload callers keep the historical no-churn contract."""
|
||||
agent = self._agent_with("old capabilities text")
|
||||
self._refresh(agent, "new capabilities text", content_aware=False)
|
||||
self.assertIn("old capabilities",
|
||||
agent.tools[0]["function"]["description"])
|
||||
|
||||
def test_identical_content_keeps_identity(self):
|
||||
agent = self._agent_with("same text")
|
||||
before = agent.tools
|
||||
self._refresh(agent, "same text", content_aware=True)
|
||||
self.assertIs(agent.tools, before)
|
||||
|
||||
|
||||
class TestCompactionWiring(unittest.TestCase):
|
||||
def test_helper_delegates_content_aware(self):
|
||||
from agent.conversation_compression import _refresh_agent_tool_definitions
|
||||
|
||||
agent = _Agent()
|
||||
with patch("tools.mcp_tool.refresh_agent_mcp_tools",
|
||||
return_value={"newly_added"}) as m:
|
||||
changed = _refresh_agent_tool_definitions(agent)
|
||||
self.assertTrue(changed)
|
||||
m.assert_called_once_with(agent, content_aware=True)
|
||||
|
||||
def test_commit_path_calls_helper_and_survives_failure(self):
|
||||
"""The commit boundary invokes the refresh and a raising refresh
|
||||
must not break compaction (wrapped in try/except at the call site).
|
||||
Pin the call-site contract by source: the helper call sits between
|
||||
_invalidate_system_prompt and the prompt rebuild, inside a
|
||||
try/except."""
|
||||
import inspect
|
||||
from agent import conversation_compression as cc
|
||||
|
||||
src = inspect.getsource(cc)
|
||||
i_invalidate = src.find("agent._invalidate_system_prompt()")
|
||||
i_refresh = src.find("_refresh_agent_tool_definitions(agent)",
|
||||
i_invalidate)
|
||||
i_rebuild = src.find("_cached_prompt_reflects_builtin_memory(agent",
|
||||
i_refresh)
|
||||
self.assertGreater(i_refresh, i_invalidate,
|
||||
"refresh must follow prompt invalidation")
|
||||
self.assertGreater(i_rebuild, i_refresh,
|
||||
"refresh must precede the prompt rebuild")
|
||||
guard_window = src[i_refresh - 400:i_refresh]
|
||||
self.assertIn("try:", guard_window,
|
||||
"refresh call must be exception-guarded")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+26
-4
@@ -8143,6 +8143,7 @@ def refresh_agent_mcp_tools(
|
||||
enabled_override=None,
|
||||
disabled_override=None,
|
||||
quiet_mode: bool = True,
|
||||
content_aware: bool = False,
|
||||
) -> set:
|
||||
"""Re-derive an already-built agent's tool snapshot from the live registry.
|
||||
|
||||
@@ -8244,10 +8245,31 @@ def refresh_agent_mcp_tools(
|
||||
for t in (getattr(agent, "tools", None) or [])
|
||||
}
|
||||
if new_names == current:
|
||||
# No change → leave the live snapshot untouched (no churn), but
|
||||
# record the generation so an in-flight older caller can't clobber.
|
||||
agent._tool_snapshot_generation = max(published_gen, snapshot_generation)
|
||||
return set()
|
||||
# Same NAME set. For MCP-reload callers that is "no change" —
|
||||
# leave the live snapshot untouched (no churn). Content-aware
|
||||
# callers (the compaction boundary) also diff the serialized
|
||||
# bytes: dynamic schemas (image_generate capabilities,
|
||||
# delegate_task limits, execute_code stubs) change CONTENT
|
||||
# under stable names when config changes between compactions.
|
||||
content_changed = False
|
||||
if content_aware:
|
||||
try:
|
||||
_stable = json.dumps(
|
||||
(getattr(agent, "tools", None) or []),
|
||||
sort_keys=True, separators=(",", ":"), default=str,
|
||||
)
|
||||
_new = json.dumps(
|
||||
new_defs, sort_keys=True, separators=(",", ":"),
|
||||
default=str,
|
||||
)
|
||||
content_changed = _stable != _new
|
||||
except Exception: # noqa: BLE001
|
||||
content_changed = False
|
||||
if not content_changed:
|
||||
# Record the generation so an in-flight older caller can't
|
||||
# clobber.
|
||||
agent._tool_snapshot_generation = max(published_gen, snapshot_generation)
|
||||
return set()
|
||||
agent.tools = new_defs
|
||||
agent.valid_tool_names = new_names
|
||||
# Publish context-engine routing names atomically with the snapshot.
|
||||
|
||||
Reference in New Issue
Block a user