Skip to content

The agent that grows with you

fix(memory/hindsight): propagate profile scope into background threads under multiplex

Tekniumcd7811a7a7c9
diff --git a/plugins/memory/hindsight/__init__.py b/plugins/memory/hindsight/__init__.py
index 7f9079ee271..cf3b9f618f3 100644
--- a/plugins/memory/hindsight/__init__.py
+++ b/plugins/memory/hindsight/__init__.py
@@ -32,6 +32,7 @@ from __future__ import annotations
import asyncio
import atexit
+import contextvars
import importlib
import json
import logging
@@ -1314,8 +1315,17 @@ class HindsightMemoryProvider(MemoryProvider):
# If the previous writer exited (e.g. after a prior shutdown), reset
# the flag so this fresh writer is allowed to drain new jobs.
self._shutting_down.clear()
+ # Per-provider background threads start with an EMPTY contextvars
+ # Context. Under multiplex_profiles the spawning thread carries the
+ # profile's secret scope + HERMES_HOME override (gateway/run.py wraps
+ # the agent turn in copy_context().run), and get_secret fails closed
+ # without it (#92608). Snapshot the spawner's context into the thread.
+ # (The shared ``hindsight-loop`` thread needs no wrap: coroutines
+ # scheduled via run_coroutine_threadsafe inherit the submitter's
+ # context per call, so one loop can serve every profile.)
thread = threading.Thread(
- target=self._writer_loop,
+ target=contextvars.copy_context().run,
+ args=(self._writer_loop,),
daemon=True,
name="hindsight-writer",
)
@@ -1835,7 +1845,12 @@ class HindsightMemoryProvider(MemoryProvider):
f.write(f"\n=== Daemon startup failed: {e} ===\n")
traceback.print_exc(file=f)
- t = threading.Thread(target=_start_daemon, daemon=True, name="hindsight-daemon-start")
+ t = threading.Thread(
+ target=contextvars.copy_context().run,
+ args=(_start_daemon,),
+ daemon=True,
+ name="hindsight-daemon-start",
+ )
t.start()
def system_prompt_block(self) -> str:
@@ -1992,7 +2007,12 @@ class HindsightMemoryProvider(MemoryProvider):
self._prefetch_result = recalled.text
self._prefetch_count = recalled.count
- self._prefetch_thread = threading.Thread(target=_run, daemon=True, name="hindsight-prefetch")
+ self._prefetch_thread = threading.Thread(
+ target=contextvars.copy_context().run,
+ args=(_run,),
+ daemon=True,
+ name="hindsight-prefetch",
+ )
self._prefetch_thread.start()
def _build_turn_messages(self, user_content: str, assistant_content: str) -> List[Dict[str, str]]:
diff --git a/tests/plugins/memory/test_hindsight_provider.py b/tests/plugins/memory/test_hindsight_provider.py
index 475e3adb372..b48e2eb383a 100644
--- a/tests/plugins/memory/test_hindsight_provider.py
+++ b/tests/plugins/memory/test_hindsight_provider.py
@@ -10,6 +10,7 @@ import os
import re
import stat
import sys
+import threading
import time
from datetime import datetime
from pathlib import Path
@@ -32,6 +33,7 @@ from plugins.memory.hindsight import (
_normalize_retain_tags,
_resolve_bank_id_template,
_sanitize_bank_segment,
+ _WRITER_SENTINEL,
)
@@ -1643,3 +1645,68 @@ class TestClientAutoUpgradeRoutesThroughLazyDeps:
assert len(calls) == 1 # attempted exactly once, init still completed
assert any("runtime installs are disabled" in r.getMessage()
for r in caplog.records)
+
+
+
+class TestMultiplexBackgroundScope:
+ """Under multiplex_profiles get_secret fails closed on an unscoped thread;
+ the writer / daemon-start threads are spawned from a scoped context and
+ must carry it along (#92608, #94933)."""
+
+ @pytest.fixture()
+ def scoped_embedded(self, tmp_path, monkeypatch):
+ from agent.secret_scope import (
+ build_profile_secret_scope, reset_secret_scope, set_multiplex_active, set_secret_scope,
+ )
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+
+ created = []
+
+ class FakeHindsightEmbedded:
+ def __init__(self, **kwargs):
+ created.append(kwargs["llm_api_key"])
+ self._manager = SimpleNamespace(is_running=lambda profile: False, stop=lambda profile: None)
+ self._ensure_started = lambda: None
+
+ dem = SimpleNamespace(console=None)
+ monkeypatch.setitem(sys.modules, "hindsight", SimpleNamespace(HindsightEmbedded=FakeHindsightEmbedded))
+ monkeypatch.setitem(sys.modules, "hindsight_embed", SimpleNamespace(daemon_embed_manager=dem))
+ monkeypatch.setitem(sys.modules, "hindsight_embed.daemon_embed_manager", dem)
+ monkeypatch.setattr("plugins.memory.hindsight._check_local_runtime", lambda: (True, ""))
+
+ home = tmp_path / "profiles" / "p1"
+ (home / "hindsight").mkdir(parents=True)
+ (home / ".env").write_text("HINDSIGHT_LLM_API_KEY=p1-secret\n")
+ (home / "hindsight" / "config.json").write_text(json.dumps(
+ {"mode": "local_embedded", "llm_provider": "openai", "llm_model": "m", "memory_mode": "hybrid"}
+ ))
+ # Enter the profile scope the way gateway _profile_runtime_scope does.
+ set_multiplex_active(True)
+ monkeypatch.setattr("plugins.memory.hindsight.get_hermes_home", lambda: home)
+ home_tok = set_hermes_home_override(str(home))
+ scope_tok = set_secret_scope(build_profile_secret_scope(home))
+ yield created, home
+ set_multiplex_active(False)
+ reset_secret_scope(scope_tok)
+ reset_hermes_home_override(home_tok)
+
+ def test_writer_thread_resolves_profile_secret(self, scoped_embedded):
+ created, home = scoped_embedded
+ p = HindsightMemoryProvider()
+ p._mode = "local_embedded"
+ p._config = {"profile": "hermes", "llm_provider": "openai", "llm_model": "m"}
+ p._ensure_writer()
+ p._retain_queue.put(p._get_client) # real body: get_secret(HINDSIGHT_LLM_API_KEY)
+ p._retain_queue.put(_WRITER_SENTINEL)
+ p._writer_thread.join(timeout=5)
+ assert created == ["p1-secret"]
+
+ def test_daemon_start_thread_resolves_profile_secret(self, scoped_embedded):
+ created, home = scoped_embedded
+ p = HindsightMemoryProvider()
+ p.initialize(session_id="s1", hermes_home=str(home), platform="cli")
+ for t in threading.enumerate():
+ if t.name == "hindsight-daemon-start":
+ t.join(timeout=5)
+ assert created == ["p1-secret"]
+ assert "Daemon started successfully" in (home / "logs" / "hindsight-embed.log").read_text()