The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): stamp turn-liveness activity from the MoA reference fan-out
Konstantin Khlopkov3714c9b54b1d
diff --git a/agent/moa_loop.py b/agent/moa_loop.pyindex 141c5e4f481..5a03be692f5 100644--- a/agent/moa_loop.py+++ b/agent/moa_loop.py@@ -300,6 +300,37 @@ def _with_cache_disabled(runtime: dict[str, Any], cache_disabled: Any) -> dict[sreturn runtime if cache_disabled is None else {**runtime, "_cache_disabled": cache_disabled}+def _reference_liveness_hook(agent: Any, label: str) -> Any:+ """Thread-local aux progress hook bridging advisor stream chunks to the agent's+ activity clock.++ The MoA fan-out runs in worker threads outside the main agent loop, so without this+ bridge nothing stamps the turn's activity clock while advisors stream — the+ turn-liveness watchdog then reads the clock frozen at the last main-loop stamp and+ force-aborts healthy, still-streaming advisor turns at ``agent.turn_liveness.timeout_s``+ (default 600s) even though the aux stream layer deliberately permits+ ``max(600, 4 × timeout)``. ``call_llm`` preserves a thread-local hook across its+ dispatch/protected-daemon paths and ticks it per substantive stream chunk, so each+ chunk re-arms the watchdog. A failed touch must never break the advisor call.+ """+ touch = getattr(agent, "_touch_activity", None)++ def _touch_on_progress() -> None:+ if callable(touch):+ touch(f"MoA reference {label}: stream progress")++ return _touch_on_progress+++def _touch_fanout_progress(agent: Any, description: str) -> None:+ """Best-effort activity stamp for fan-out milestones; never raises (display of+ progress must not decide turn liveness on its own, it only supports it)."""+ touch = getattr(agent, "_touch_activity", None)+ if callable(touch):+ with contextlib.suppress(Exception):+ touch(description)++def _maybe_apply_moa_cache_control(messages: list[dict[str, Any]], runtime: dict[str, Any], *, cache_disabled: bool | None = None,cache_ttl: str | None = None,@@ -367,7 +398,7 @@ def _price_reference_response(def _run_reference(slot: dict[str, Any], ref_messages: list[dict[str, Any]], *, temperature: float | None = None,max_tokens: int | None = None, reference_timeout: float | None = None, context_length_cache: Any = None,- cache_disabled: bool | None = None, cache_ttl: str | None = None,+ cache_disabled: bool | None = None, cache_ttl: str | None = None, agent: Any = None,) -> tuple[str, str, Any]:"""Call one reference model; return ``(label, text, accounting)``. Never raises:a failed reference becomes a labelled ``[failed: …]`` note. Runs in a thread pool."""@@ -393,12 +424,23 @@ def _run_reference(# user's current turn, so mirror the main agent's x-initiator header.from agent.auxiliary_client import _normalize_aux_provideris_copilot = _normalize_aux_provider(str(runtime.get("provider") or "")) in ("copilot", "copilot-acp")- response = call_llm(- task="moa_reference", messages=trimmed, temperature=temperature,- max_tokens=max_tokens,- timeout=reference_timeout, reasoning_config=_slot_reasoning_config(slot),- extra_headers={"x-initiator": "user"} if is_copilot else None, **runtime,- )+ if agent is not None:+ from agent.auxiliary_client import aux_progress_hook++ with aux_progress_hook(_reference_liveness_hook(agent, label)):+ response = call_llm(+ task="moa_reference", messages=trimmed, temperature=temperature,+ max_tokens=max_tokens,+ timeout=reference_timeout, reasoning_config=_slot_reasoning_config(slot),+ extra_headers={"x-initiator": "user"} if is_copilot else None, **runtime,+ )+ else:+ response = call_llm(+ task="moa_reference", messages=trimmed, temperature=temperature,+ max_tokens=max_tokens,+ timeout=reference_timeout, reasoning_config=_slot_reasoning_config(slot),+ extra_headers={"x-initiator": "user"} if is_copilot else None, **runtime,+ )output_text = _extract_text(response) or "(empty response)"acct = _RefAccounting(*_price_reference_response(response, slot, runtime), messages=trimmed, output=output_text, **trace_fields)return label, output_text, acct@@ -593,6 +635,10 @@ def _run_references_parallel(idx = futures[future]results[idx] = future.result()completed += 1+ # Each completion is fan-out progress the main loop cannot see: the+ # fan-out blocks it, so stamp the turn's activity clock here (non-streaming+ # advisors otherwise tick nothing between dispatch and completion).+ _touch_fanout_progress(agent, f"MoA: {completed} of {total} references complete")if progress_callback is not None:try:progress_callback(completed, total, _slot_label(reference_models[idx]))@@ -604,11 +650,20 @@ def _run_references_parallel(if slot.get("provider") == "moa":results[idx] = _placeholder_output(slot, "[skipped: MoA presets cannot recursively reference MoA]")continue- futures[executor.submit(- propagate_context_to_thread(_run_reference), slot, ref_messages, temperature=temperature,- max_tokens=max_tokens, reference_timeout=reference_timeout, context_length_cache=ctx_len_cache,- cache_disabled=cache_disabled, cache_ttl=cache_ttl,- )] = idx+ futures[+ executor.submit(+ propagate_context_to_thread(_run_reference),+ slot,+ ref_messages,+ temperature=temperature,+ max_tokens=max_tokens,+ reference_timeout=reference_timeout,+ context_length_cache=ctx_len_cache,+ cache_disabled=cache_disabled,+ cache_ttl=cache_ttl,+ agent=agent,+ )+ ] = idx# Collect every reference (no early exit except a user interrupt).pending = set(futures)@@ -892,6 +947,9 @@ def aggregate_moa_context(agg_label = _slot_label(aggregator)agg_runtime = _slot_runtime(aggregator)cache_disabled, cache_ttl = _agent_cache_opts(agent)+ _touch_fanout_progress(+ agent, f"MoA: synthesizing aggregator guidance ({agg_label})"+ )try:# Same cache_control decoration as the advisor calls; this synthesis call is# a third independent MoA call path that otherwise re-bills its full input.diff --git a/tests/agent/test_moa_fanout_liveness.py b/tests/agent/test_moa_fanout_liveness.pynew file mode 100644index 00000000000..06aef21ac03--- /dev/null+++ b/tests/agent/test_moa_fanout_liveness.py@@ -0,0 +1,175 @@+"""MoA fan-out must stamp the turn-liveness activity clock (#110015).++The reference fan-out runs in worker threads outside the main agent loop, and nothing+in it used to stamp ``_last_activity_ts`` — so during a healthy multi-minute fan-out+the turn-liveness watchdog read the clock frozen at the last main-loop stamp+("starting API call #1") and force-aborted the turn at ``agent.turn_liveness.timeout_s``+(default 600s), while the aux stream layer deliberately permits+``max(600, 4 × timeout)`` = 3600s for the same advisors.++The fix bridges both progress signals into ``AIAgent._touch_activity`` (the single+activity write path the watchdog samples):++- each advisor's streaming chunks tick the thread-local aux progress hook+ (``call_llm`` ticks it per substantive chunk on every dispatch path);+- each advisor completion and the aggregator synthesis start stamp milestones.++A silent fan-out (no chunks, no completions) still stamps nothing, so a genuinely+wedged advisor turn remains abortable by the watchdog.+"""++from __future__ import annotations++import threading+from types import SimpleNamespace++import pytest+++def _response(content="ok"):+ message = SimpleNamespace(content=content, tool_calls=[])+ choice = SimpleNamespace(message=message, finish_reason="stop")+ return SimpleNamespace(choices=[choice], usage=None, model="fake")+++class _Agent:+ """AIAgent double recording every activity stamp (what the watchdog samples)."""++ def __init__(self):+ self.touches = []+ self._interrupt_requested = False+ self._cache_disabled = None+ self._cache_ttl = None++ def _touch_activity(self, desc, **kwargs):+ self.touches.append(desc)+++def moa_config(tmp_path, monkeypatch):+ home = tmp_path / ".hermes"+ home.mkdir()+ (home / "config.yaml").write_text(+ """+moa:+ default_preset: closed+ presets:+ closed:+ enabled: true+ reference_models:+ - provider: openrouter+ model: anthropic/claude-opus-4.8+ - provider: openrouter+ model: openai/gpt-5.5+ aggregator:+ provider: openrouter+ model: anthropic/claude-opus-4.8+""".strip(),+ encoding="utf-8",+ )+ monkeypatch.setenv("HERMES_HOME", str(home))+ return home+++_SLOTS = [+ {"provider": "openrouter", "model": "anthropic/claude-opus-4.8"},+ {"provider": "openrouter", "model": "openai/gpt-5.5"},+]+++def _tick_current_aux_progress():+ """Simulate one substantive stream chunk: tick the thread-local aux progress hook."""+ from agent.auxiliary_client import _aux_progress++ hook = getattr(_aux_progress, "hook", None)+ if callable(hook):+ hook()+++class TestFanoutStampsActivity:+ def test_streaming_advisor_chunks_stamp_activity(self, moa_config, monkeypatch):+ """Per-chunk ticks from a streaming advisor must reach ``_touch_activity`` —+ the watchdog samples that clock, so chunks re-arm it (#110015)."""+ from agent import moa_loop++ agent = _Agent()+ seen_threads = []+ chunks_per_call = [3, 2]++ def fake_call_llm(**kwargs):+ seen_threads.append(threading.current_thread().name)+ if kwargs.get("task") == "moa_reference":+ for _ in range(chunks_per_call.pop(0)):+ _tick_current_aux_progress()+ return _response("advice")++ monkeypatch.setattr(moa_loop, "call_llm", fake_call_llm)+ facade = moa_loop.MoAChatCompletions("closed", agent=agent)+ facade.create(messages=[{"role": "user", "content": "hello"}])++ stream_stamps = [t for t in agent.touches if "stream progress" in t]+ assert len(stream_stamps) == 5, agent.touches+ assert any("anthropic/claude-opus-4.8" in t for t in stream_stamps)+ assert any("openai/gpt-5.5" in t for t in stream_stamps)+ # The fan-out really ran on worker threads (the bridge is thread-local).+ assert any(not n.startswith("MainThread") for n in seen_threads)++ def test_each_reference_completion_stamps_activity(self, moa_config, monkeypatch):+ """Non-streaming advisors tick nothing per chunk, so each completion must+ itself be fan-out progress the watchdog can see."""+ from agent import moa_loop++ agent = _Agent()+ monkeypatch.setattr(moa_loop, "call_llm", lambda **kwargs: _response("advice"))+ facade = moa_loop.MoAChatCompletions("closed", agent=agent)+ facade.create(messages=[{"role": "user", "content": "hello"}])++ assert "MoA: 1 of 2 references complete" in agent.touches+ assert "MoA: 2 of 2 references complete" in agent.touches++ def test_silent_fanout_stamps_nothing_until_completion(self, moa_config, monkeypatch):+ """No chunks and no completions = no activity stamps: a wedged advisor turn+ must stay abortable by the watchdog (the fix adds progress, never fakes it)."""+ from agent import moa_loop++ agent = _Agent()++ def silent_call_llm(**kwargs):+ assert not any("stream progress" in t for t in agent.touches), (+ "a silent call in flight must not have stamped stream progress"+ )+ return _response("advice")++ monkeypatch.setattr(moa_loop, "call_llm", silent_call_llm)+ facade = moa_loop.MoAChatCompletions("closed", agent=agent)+ facade.create(messages=[{"role": "user", "content": "hello"}])++ assert not any("stream progress" in t for t in agent.touches)++ def test_aggregate_moa_context_stamps_synthesis(self, moa_config, monkeypatch):+ """The one-shot /moa path (no facade) must stamp the aggregator synthesis+ too: it is the longest single call of that path."""+ from agent import moa_loop++ agent = _Agent()+ monkeypatch.setattr(moa_loop, "call_llm", lambda **kwargs: _response("advice"))+ moa_loop.aggregate_moa_context(+ user_prompt="hello",+ api_messages=[{"role": "user", "content": "hello"}],+ reference_models=_SLOTS,+ aggregator={"provider": "openrouter", "model": "anthropic/claude-opus-4.8"},+ agent=agent,+ )++ assert any("synthesizing aggregator guidance" in t for t in agent.touches)++ def test_fanout_without_agent_still_works(self, moa_config, monkeypatch):+ """agent=None (aux/preview callers, test doubles) keeps the old behaviour."""+ from agent import moa_loop++ monkeypatch.setattr(moa_loop, "call_llm", lambda **kwargs: _response("advice"))+ outputs = moa_loop._run_references_parallel(+ _SLOTS, [{"role": "user", "content": "hello"}]+ )+ assert len(outputs) == 2+ assert all(not isinstance(text, str) or isinstance(text, str) for _lbl, text, _acct in outputs)