Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

fix(bot): bound hook registration and HTTP client lifetimes (#6653)

jmCalvinhyl535f6f7ddf02
diff --git a/bot/tests/test_openviking_api_key_type.py b/bot/tests/test_openviking_api_key_type.py
index 85be5f59d..7598d0586 100644
--- a/bot/tests/test_openviking_api_key_type.py
+++ b/bot/tests/test_openviking_api_key_type.py
@@ -2805,3 +2805,91 @@ async def test_experience_reminder_follows_direct_case_experience_links(monkeypa
assert "direct exp content" not in content
assert exp_uri in uris
assert direct_exp_uri not in uris
+
+
+async def test_repeated_builtin_hook_registration_executes_once_per_event(monkeypatch):
+ from vikingbot.hooks.manager import HookManager
+
+ first = SimpleNamespace(is_sync=False, name="first", execute=AsyncMock())
+ second = SimpleNamespace(is_sync=False, name="second", execute=AsyncMock())
+ manager = HookManager()
+ mapping = {"tool.post_call": [first, second], "message.compact": [first]}
+ monkeypatch.setattr(manager, "import_path", lambda _path: mapping)
+ for _ in range(5):
+ manager.register_path(["builtin.hooks"])
+
+ await manager.execute_hooks(HookContext(event_type="tool.post_call"))
+ assert first.execute.await_count == 1
+ assert second.execute.await_count == 1
+ await manager.execute_hooks(HookContext(event_type="message.compact"))
+ assert first.execute.await_count == 2
+ assert second.execute.await_count == 1
+
+
[email protected]("hook_type", ["post_call", "compact"])
[email protected]("explicit_connection", [False, True])
[email protected]("explicit_config", [False, True])
[email protected]("outcome", ["success", "error", "cancel"])
+async def test_builtin_hook_releases_invocation_client(
+ monkeypatch, hook_type, explicit_connection, explicit_config, outcome
+):
+ import asyncio
+
+ config = SimpleNamespace(
+ ov_server=SimpleNamespace(server_url="http://localhost:1933", admin_user_id="admin"),
+ agents=SimpleNamespace(session_context_enabled=False),
+ )
+ monkeypatch.setattr(openviking_hooks_module, "load_config", lambda: config)
+ cache = {}
+ monkeypatch.setattr(openviking_hooks_module, "_global_clients", cache)
+ entered = asyncio.Event()
+
+ async def operation(*_args, **_kwargs):
+ entered.set()
+ if outcome == "error":
+ raise ValueError("injected hook failure")
+ if outcome == "cancel":
+ await asyncio.Future()
+ return []
+
+ client = SimpleNamespace(
+ search_experiences=operation,
+ commit=operation,
+ close=AsyncMock(),
+ session_owner_user_id=lambda: "admin",
+ )
+ factory = AsyncMock(return_value=client)
+ monkeypatch.setattr(openviking_hooks_module, "VikingClient", SimpleNamespace(create=factory))
+ context = HookContext(
+ event_type="tool.post_call" if hook_type == "post_call" else "message.compact",
+ workspace_id="workspace",
+ session_key=SessionKey(type="test", channel_id="channel", chat_id="chat"),
+ config=config if explicit_config else None,
+ openviking_connection={"user": "test"} if explicit_connection else None,
+ )
+ if hook_type == "post_call":
+ call = openviking_hooks_module.OpenVikingPostCallHook().execute(
+ context,
+ "read_file",
+ {"path": "skills/example/SKILL.md"},
+ "---\nname: example\ndescription: example skill\n---\n",
+ )
+ else:
+ call = OpenVikingCompactHook().execute(context, session=SimpleNamespace(messages=[]))
+ task = asyncio.create_task(call)
+ try:
+ await asyncio.wait_for(entered.wait(), timeout=5)
+ if outcome == "cancel":
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ else:
+ await task
+ client.close.assert_awaited_once()
+ assert cache == {}, "completed hooks must not retain clients in the global cache"
+ finally:
+ if not task.done():
+ task.cancel()
+ await asyncio.gather(task, return_exceptions=True)
diff --git a/bot/vikingbot/hooks/builtins/openviking_hooks.py b/bot/vikingbot/hooks/builtins/openviking_hooks.py
index 9d812786d..b2b026285 100644
--- a/bot/vikingbot/hooks/builtins/openviking_hooks.py
+++ b/bot/vikingbot/hooks/builtins/openviking_hooks.py
@@ -63,16 +63,15 @@ class OpenVikingCompactHook(Hook):
openviking_connection: dict[str, Any] | None = None,
config: Any = None,
) -> tuple[VikingClient, bool]:
- if openviking_connection:
- return (
- await VikingClient.create(
- workspace_id,
- connection=openviking_connection,
- config=config,
- ),
- True,
- )
- return await get_global_client(workspace_id, config=config), False
+ # The execute() finally block owns this client, including local mode.
+ return (
+ await VikingClient.create(
+ workspace_id,
+ connection=openviking_connection,
+ config=config,
+ ),
+ True,
+ )
async def _execute_session_context_commit(
self,
@@ -294,7 +293,9 @@ class OpenVikingPostCallHook(Hook):
is_sync = False
async def _get_client(self, workspace_id: str, config: Any = None) -> VikingClient:
- return await get_global_client(workspace_id, config=config)
+ if config is None:
+ return await VikingClient.create(workspace_id)
+ return await VikingClient.create(workspace_id, config=config)
async def _search_skill_experiences(
self,
@@ -325,8 +326,10 @@ class OpenVikingPostCallHook(Hook):
should_close = True
elif config is None:
ov_client = await self._get_client(workspace_id)
+ should_close = True
else:
ov_client = await self._get_client(workspace_id, config=config)
+ should_close = True
logger.debug(
"[SKILL_EXP]: start workspace_id={} query_len={} query={!r}",
workspace_id,
diff --git a/bot/vikingbot/hooks/manager.py b/bot/vikingbot/hooks/manager.py
index 54132816d..7d9eafc25 100644
--- a/bot/vikingbot/hooks/manager.py
+++ b/bot/vikingbot/hooks/manager.py
@@ -40,6 +40,11 @@ class HookManager:
continue
for event_type, hook_types in hooks.items():
for hook_type in hook_types:
+ # AgentLoop is also constructed per Compile task. Module-level
+ # hook instances must be registered once per event, not once
+ # per AgentLoop; distinct hook instances remain independent.
+ if any(existing is hook_type for existing in self._hooks[event_type]):
+ continue
self._hooks[event_type].append(hook_type)
logger.debug(f"Registered hook '{hook_type}' for event '{event_type}'")