diff --git a/CHANGELOG.d/tool-loop-emitting-agent-routing.md b/CHANGELOG.d/tool-loop-emitting-agent-routing.md new file mode 100644 index 000000000..d1f7a6dd0 --- /dev/null +++ b/CHANGELOG.d/tool-loop-emitting-agent-routing.md @@ -0,0 +1,30 @@ +# Tool-loop-emitting-agent routing + +Closed a paper-fidelity gap (Fugu report arXiv:2606.21228 §3; Fugu-Ultra +Conductor): the paper's Conductor routes a tool loop back to the agent that +emitted the tool call, but a follow-up `POST /v1/chat/completions` carrying +`role: "tool"` results for a prior `tool_calls` batch was previously ranked +like any new request under a virtual selector (`orchestrator/free`, +`orchestrator/auto`, `contextual-orchestrator`), so a different provider or +model could receive tool results for calls it never emitted. + +`TaskOrchestrator` now keeps a bounded, thread-safe `tool_loop_memory` map +(`tool_call_id -> emitting agent id`, default bound +`TOOL_LOOP_MEMORY_MAX_ENTRIES = 4096`, configurable via the new +`tool_loop_memory_max_entries` constructor argument) recorded whenever a +served response carries `tool_calls` on `proxy_completion`'s single-agent +passthrough, `route_once`, `conduct`'s worker step, and +`_orchestrated_provider_completion`'s structured synthesis (both the +Responses API's `function_call` items, keyed by `call_id`, and +`response_format`-only chat passthrough's `tool_calls`). A follow-up whose +`role: "tool"` messages (or, on the Responses surface, `function_call_output` +items — already normalized to the same `role: "tool"` / `tool_call_id` shape +by the existing input-to-chat conversion) reference a remembered +`tool_call_id`/`call_id` moves that agent to the front of the +already-fully-filtered candidate order — but only when it is still eligible +under the request's own constraints (explicit concrete model, free/ZDR +scope, circuit-breaker state); an ineligible remembered agent falls back to +the normal order instead. Served responses now carry +`orchestration.tool_loop_route` (`"emitting_agent"` or `"fallback"`) and +`orchestration.tool_loop_agent_id` as routing evidence on every one of these +paths. diff --git a/contextual_orchestrator/orchestrator.py b/contextual_orchestrator/orchestrator.py index 53dcbb05c..b5150cad4 100644 --- a/contextual_orchestrator/orchestrator.py +++ b/contextual_orchestrator/orchestrator.py @@ -5380,6 +5380,19 @@ class TaskOrchestrator: #: Operational memory bound mirroring ``cache_max_entries``; not a routing weight. EVIDENCE_CACHE_MAX_ENTRIES = 512 + #: Bound on remembered ``tool_call_id -> emitting-agent-id`` entries (the + #: ``tool_loop_memory`` map -- Fugu report arXiv:2606.21228 S3 / Fugu-Ultra + #: Conductor's tool-loop-return contract). This is an operational memory + #: bound, like ``EVIDENCE_CACHE_MAX_ENTRIES``, not a product limit on how + #: many in-flight tool loops a deployment may run; an LRU eviction is + #: sufficient because a tool loop that idles past the bound has, in + #: practice, already completed or been abandoned by the caller, so no TTL + #: is layered on top. The default is sized for concurrent callers (the + #: org CI review lanes run many tool loops in parallel, each with several + #: call ids): 4096 two-string entries cost well under 1 MiB, while an + #: in-flight loop evicted early would silently degrade to ``fallback``. + TOOL_LOOP_MEMORY_MAX_ENTRIES = 4096 + def __init__( self, agents: list[ModelAgent], @@ -5393,6 +5406,7 @@ def __init__( cache_max_entries: int = 256, tool_retry_attempts: int = 1, tool_retry_backoff_seconds: float = 0.25, + tool_loop_memory_max_entries: int = TOOL_LOOP_MEMORY_MAX_ENTRIES, cache_provider: ResponseCacheProvider | None = None, role_effort_catalog: dict[str, ReasoningEffortProfile] | None = None, pii_key_name: str = DEFAULT_PII_KEY_NAME, @@ -5475,6 +5489,19 @@ def __init__( "tool_retry_backoff_seconds must be a finite nonnegative number" ) self.tool_retry_backoff_seconds = float(tool_retry_backoff_seconds) + if ( + isinstance(tool_loop_memory_max_entries, bool) + or not isinstance(tool_loop_memory_max_entries, int) + or tool_loop_memory_max_entries < 1 + ): + raise ValueError( + "tool_loop_memory_max_entries must be a positive integer" + ) + self.tool_loop_memory_max_entries = tool_loop_memory_max_entries + # tool_call_id -> emitting-agent-id, bounded LRU (see + # TOOL_LOOP_MEMORY_MAX_ENTRIES); guarded by _evidence_lock alongside the + # other bounded evidence caches below. + self._tool_loop_memory: OrderedDict[str, str] = OrderedDict() # Injectable seams keep retry timing deterministic in tests while # production uses full jitter to avoid synchronized retry bursts. self._tool_retry_sleep = time.sleep @@ -5966,6 +5993,13 @@ def proxy_completion( self._group_router.observe_success( agent.id, time.perf_counter() - started_at ) + # Explicit concrete models are never re-ranked for a tool-loop + # follow-up (see _apply_tool_loop_route's precedence contract), + # but this served response's own tool_calls are still remembered + # so a *later* virtual-selector follow-up can return to it. + self._record_tool_loop_agents( + self._served_tool_calls(result, api_surface), agent.id + ) return result allowed_agent_ids = ({agent.id} if isinstance(required_agent_id, str) else ( @@ -6030,6 +6064,13 @@ def proxy_completion( continue seen_providers.add(provider_key) candidates.append(candidate) + # Route a tool-result follow-up back to the agent that emitted the + # call, when it is still one of the already-fully-filtered candidates + # above (Fugu report arXiv:2606.21228 S3 / Fugu-Ultra Conductor). + # required_agent_id already collapsed `candidates` to a single pinned + # agent, so this is a no-op there -- an explicit concrete model is + # never re-ranked. + candidates, tool_loop_evidence = self._apply_tool_loop_route(candidates, messages) last_failure: tuple[Exception, ModelAgent] | None = None every_failure_was_request_too_large = True # Rate-limit-storm admission (evidence: noema run 34758641142, strix @@ -6152,6 +6193,15 @@ def proxy_completion( self._group_router.observe_success( candidate.id, time.perf_counter() - started_at ) + self._record_tool_loop_agents( + self._served_tool_calls(result, api_surface), candidate.id + ) + if tool_loop_evidence is not None and isinstance(result, dict): + orchestration_extension = result.get("orchestration") + if not isinstance(orchestration_extension, dict): + orchestration_extension = {} + result["orchestration"] = orchestration_extension + orchestration_extension.update(tool_loop_evidence) if rate_limited_skipped and isinstance(result, dict): orchestration = result.setdefault("orchestration", {}) if isinstance(orchestration, dict): @@ -6517,6 +6567,24 @@ def _orchestrated_provider_completion( transport="structured_synthesis", ) final_agent = synthesis_candidates[0] + # Route a Responses/structured-synthesis tool-loop follow-up back to + # the agent that emitted the call, mirroring proxy_completion's and + # conduct's worker step (Fugu report arXiv:2606.21228 S3 / Fugu-Ultra + # Conductor). ``messages`` is already the chat-shaped conversation + # (``_responses_to_chat_payload`` translated ``function_call_output`` + # items into ``role: "tool"`` / ``tool_call_id`` for the Responses + # surface), so no separate lookup is needed for that surface. + # ``synthesis_candidates`` is already fully filtered (required tags, + # free/ZDR, request exclusions), so this only reorders within that + # eligible set; an explicit concrete model keeps a single-candidate + # list and is therefore never reordered. + tool_loop_evidence: dict[str, str] | None = None + if virtual_model: + synthesis_candidates, tool_loop_evidence = self._apply_tool_loop_route( + synthesis_candidates, messages + ) + if synthesis_candidates and synthesis_candidates[0].id != final_agent.id: + final_agent = synthesis_candidates[0] def provider_output(agent: ModelAgent, response: Mapping[str, Any]) -> str: """Extract non-empty structured output from the attempted provider.""" @@ -7089,6 +7157,12 @@ def next_structured_candidate(failed_agent: ModelAgent) -> ModelAgent: self._group_router.observe_success( final_agent.id, time.perf_counter() - synthesis_started ) + # Remember which agent emitted this served response's tool calls, so a + # later tool-loop follow-up on either surface returns to it (see the + # reorder above and _record_tool_loop_agents). + self._record_tool_loop_agents( + self._served_tool_calls(raw, api_surface), final_agent.id + ) if response_request: raw.setdefault("output_text", synthesis_output) echo = raw.get("echo") @@ -7128,6 +7202,8 @@ def next_structured_candidate(failed_agent: ModelAgent) -> ModelAgent: } if isinstance(route, dict): raw["orchestration"]["route"] = route + if tool_loop_evidence is not None: + raw["orchestration"].update(tool_loop_evidence) return raw @contextmanager @@ -8790,6 +8866,16 @@ def route_once( if self._is_general_free_agent(candidate) and self._zdr_agent_allowed(candidate) } allowed_agent_ids = free_ids if free_only else None + # A tool-result follow-up returns to its emitting agent when that + # agent is still one of the already role/free/ZDR-filtered + # ``ranked_pool`` candidates above (Fugu report arXiv:2606.21228 S3 / + # Fugu-Ultra Conductor). An explicit concrete model (``requested``) + # is never re-ranked and must not carry tool-loop evidence either: + # the caller pinned the agent, so neither ``emitting_agent`` nor + # ``fallback`` describes a gateway decision there. + tool_loop_evidence: dict[str, str] | None = None + if requested is None: + ranked_pool, tool_loop_evidence = self._apply_tool_loop_route(ranked_pool, messages) max_attempts = 1 + min(self.tool_retry_attempts, MAX_TOOL_RETRY_ATTEMPTS) trace_rows: list[dict[str, Any]] = [] @@ -8897,8 +8983,11 @@ def route_once( if isinstance(extras, dict): if extras.get("tool_calls"): result["tool_calls"] = extras["tool_calls"] + self._record_tool_loop_agents(extras["tool_calls"], served_id or None) if extras.get("finish_reason"): result["finish_reason"] = extras["finish_reason"] + if tool_loop_evidence is not None: + result.update(tool_loop_evidence) if prompt_bound is not None and prompt_bound_source is not None: result = self._with_context_window_evidence( result, prompt_bound, prompt_bound_source, context_window_excluded @@ -9042,6 +9131,7 @@ def conduct( outputs: dict[int, str] = {} trace: list[dict[str, Any]] = [] tool_result: dict[str, Any] | None = None + tool_loop_evidence: dict[str, str] | None = None free_ids = { candidate.id for candidate in self.agents @@ -9092,6 +9182,28 @@ def conduct( capable = [] if capable: agent = capable[0] + if step.role == "worker" and requested_agent is None: + # A tool-result follow-up returns to the agent that emitted + # the call it is answering, when that agent is still eligible + # under this step's own constraints (Fugu report + # arXiv:2606.21228 S3 / Fugu-Ultra Conductor). requested_agent + # is None only for a virtual selector -- an explicit concrete + # model pins ``agent`` above and is never re-ranked here. + worker_candidates, step_tool_loop_evidence = self._apply_tool_loop_route( + self._failover_candidates( + agent, + step.subtask, + "worker", + allowed_agent_ids=( + free_ids if model_name == self.FREE_MODEL else _allowed_agent_ids + ), + ), + messages, + ) + if worker_candidates: + agent = worker_candidates[0] + if step_tool_loop_evidence is not None: + tool_loop_evidence = step_tool_loop_evidence if progress is not None: _notify_progress(progress, step.role, "started") prior = "\n\n".join(f"Step {i}: {outputs[i]}" for i in step.access) @@ -9160,7 +9272,9 @@ def conduct( _notify_progress(progress, step.role, "completed", redact_value(output)) if step.role == "worker" and isinstance(extras, dict) and extras.get("tool_calls"): tool_result = extras + self._record_tool_loop_agents(extras["tool_calls"], served_id or agent.id) break + tool_loop_evidence = None if tool_result is not None: answer = output @@ -9218,6 +9332,8 @@ def last_output(role: str) -> str: if tool_result is not None: result["tool_calls"] = tool_result["tool_calls"] result["finish_reason"] = tool_result.get("finish_reason") or "tool_calls" + if tool_loop_evidence is not None: + result.update(tool_loop_evidence) if prompt_bound is not None and prompt_bound_source is not None: result = self._with_context_window_evidence( result, prompt_bound, prompt_bound_source, context_window_excluded @@ -10892,6 +11008,156 @@ def _failover_candidates( self._last_context_window_excluded = excluded return healthy + def _record_tool_loop_agents(self, tool_calls: Any, agent_id: str | None) -> None: + """Remember which agent emitted each tool call, keyed by ``tool_call_id``. + + Feeds :meth:`_apply_tool_loop_route`, which routes a follow-up request + carrying that call's ``role: tool`` result back to the same agent + (Fugu report arXiv:2606.21228 S3 / Fugu-Ultra Conductor's + tool-loop-return contract) instead of a freshly ranked one. The map is + bounded LRU (:data:`TOOL_LOOP_MEMORY_MAX_ENTRIES` / + ``tool_loop_memory_max_entries``); a call id that is never followed up + simply ages out. + """ + if not agent_id or not isinstance(tool_calls, list): + return + call_ids = [ + call["id"] + for call in tool_calls + if isinstance(call, dict) and isinstance(call.get("id"), str) and call["id"] + ] + if not call_ids: + return + with self._evidence_lock: + for call_id in call_ids: + self._tool_loop_memory[call_id] = agent_id + self._tool_loop_memory.move_to_end(call_id) + while len(self._tool_loop_memory) > self.tool_loop_memory_max_entries: + self._tool_loop_memory.popitem(last=False) + + @staticmethod + def _tool_loop_call_ids(messages: Any) -> list[str]: + """Return every ``tool_call_id`` a request's ``role: tool`` messages carry.""" + if not isinstance(messages, list): + return [] + return [ + message["tool_call_id"] + for message in messages + if isinstance(message, dict) + and message.get("role") == "tool" + and isinstance(message.get("tool_call_id"), str) + and message["tool_call_id"] + ] + + def _remembered_tool_loop_agent(self, messages: Any) -> str | None: + """Return the remembered emitting-agent id for a tool-result follow-up, if any.""" + call_ids = self._tool_loop_call_ids(messages) + if not call_ids: + return None + with self._evidence_lock: + for call_id in call_ids: + agent_id = self._tool_loop_memory.get(call_id) + if agent_id is not None: + return agent_id + return None + + def _apply_tool_loop_route( + self, + candidates: list[ModelAgent], + messages: Any, + ) -> tuple[list[ModelAgent], dict[str, str] | None]: + """Move a tool-result follow-up's emitting agent to the front, when eligible. + + ``candidates`` must already be fully filtered/ordered by every request + constraint that applies (virtual selector, free/ZDR eligibility, + circuit state, provider exclusions) -- this only reorders within that + eligible set, so an explicit concrete model (whose call sites never + reach this helper) and every other precedence rule are preserved + unconditionally: the remembered agent is used only when it is already + one of ``candidates``. + + Returns ``(candidates, None)`` when the request carries no tool-loop + follow-up evidence (no remembered ``tool_call_id``); otherwise the + (possibly reordered) candidates plus a routing-evidence mapping with + ``tool_loop_route`` (``"emitting_agent"`` when the remembered agent is + still eligible and was moved to the front, ``"fallback"`` when it is + no longer eligible and the original order is kept) and + ``tool_loop_agent_id`` (the remembered agent id either way). + """ + remembered_agent_id = self._remembered_tool_loop_agent(messages) + if remembered_agent_id is None: + return candidates, None + for index, candidate in enumerate(candidates): + if candidate.id != remembered_agent_id: + continue + reordered = ( + candidates + if index == 0 + else [candidate, *candidates[:index], *candidates[index + 1 :]] + ) + return reordered, { + "tool_loop_route": "emitting_agent", + "tool_loop_agent_id": remembered_agent_id, + } + return candidates, { + "tool_loop_route": "fallback", + "tool_loop_agent_id": remembered_agent_id, + } + + @staticmethod + def _chat_response_tool_calls(response: Any) -> list[Any] | None: + """Return a chat-completions-shaped provider response's ``tool_calls``, if any.""" + if not isinstance(response, Mapping): + return None + choices = response.get("choices") + if not isinstance(choices, list) or not choices: + return None + first = choices[0] + message = first.get("message") if isinstance(first, Mapping) else None + tool_calls = message.get("tool_calls") if isinstance(message, Mapping) else None + return tool_calls if isinstance(tool_calls, list) and tool_calls else None + + @staticmethod + def _responses_output_tool_calls(response: Any) -> list[dict[str, Any]] | None: + """Return a Responses-shaped provider response's ``function_call`` items. + + Adapts each item's ``call_id`` into the ``{"id": ...}`` shape + :meth:`_record_tool_loop_agents` already expects from chat's + ``tool_calls``, so a Responses-surface tool call feeds the same + ``tool_loop_memory`` map as a chat one. + """ + if not isinstance(response, Mapping): + return None + output = response.get("output") + if not isinstance(output, list): + return None + call_ids = [ + item["call_id"] + for item in output + if isinstance(item, Mapping) + and item.get("type") == "function_call" + and isinstance(item.get("call_id"), str) + and item["call_id"] + ] + return [{"id": call_id} for call_id in call_ids] if call_ids else None + + @staticmethod + def _served_tool_calls(response: Any, api_surface: str) -> list[Any] | None: + """Extract a served response's tool calls for whichever wire surface served it. + + A single dispatch point for :meth:`_record_tool_loop_agents` callers + that can serve either surface (``proxy_completion``'s explicit-model + and virtual passthrough branches, and + ``_orchestrated_provider_completion``'s structured synthesis), so the + Responses-vs-chat extractor choice is made once instead of repeating + the same ``api_surface == "responses"`` branch at each call site. + """ + return ( + TaskOrchestrator._responses_output_tool_calls(response) + if api_surface == "responses" + else TaskOrchestrator._chat_response_tool_calls(response) + ) + def _circuit_open(self, agent_id: str) -> bool: with self._circuit_lock: state = self._circuit.get(agent_id) @@ -19069,6 +19335,8 @@ def chat_completion_response( "routing_reason": result.get("routing_reason"), "usage_record_id": result.get("usage_record_id"), "cost": result.get("cost"), + "tool_loop_route": result.get("tool_loop_route"), + "tool_loop_agent_id": result.get("tool_loop_agent_id"), "requested_output_tokens": result.get("requested_output_tokens"), "effective_output_tokens": result.get("effective_output_tokens"), "output_budget_clamped": result.get("output_budget_clamped"), @@ -19200,6 +19468,8 @@ def chat_completion_chunks( "workflow_run_id": result.get("workflow_run_id"), "mode": result.get("mode"), "verification": result.get("verification"), + "tool_loop_route": result.get("tool_loop_route"), + "tool_loop_agent_id": result.get("tool_loop_agent_id"), "requested_output_tokens": result.get("requested_output_tokens"), "effective_output_tokens": result.get("effective_output_tokens"), "output_budget_clamped": result.get("output_budget_clamped"), diff --git a/docs/architecture.md b/docs/architecture.md index b7677cfc8..80b407aca 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -53,6 +53,33 @@ The Fugu report combines these ideas into production constraints: - The agent pool is swappable, allowing provider preference, model exclusion, and compliance controls. - Multi-agent tool/function-call workflows need memory discipline: isolate agents inside the current workflow, but keep useful shared memory across turns. +Fidelity note (2026-09-13, Fugu report arXiv:2606.21228 S3 / Fugu-Ultra +Conductor): the paper's Conductor routes a tool loop back to the agent that +emitted the tool call — when the client executes the tool and sends the +results back, the continuation goes to the same worker, not a freshly +selected one. This gateway previously did not do that: a follow-up carrying +`role: "tool"` results was ranked like any new request, so a virtual selector +(`orchestrator/free`, `orchestrator/auto`, `contextual-orchestrator`) could +hand a different provider/model the results for calls it never emitted. This +is now closed by `TaskOrchestrator`'s bounded `tool_loop_memory` map +(`tool_call_id -> emitting agent id`, see `_apply_tool_loop_route` in +`contextual_orchestrator/orchestrator.py`): a follow-up's remembered emitting +agent is moved to the front of the already-filtered candidate order on +`proxy_completion`'s single-agent passthrough, `route_once`, `conduct`'s +worker step, and `_orchestrated_provider_completion`'s structured synthesis +-- covering both of that path's callers (the Responses API and +`response_format`-only chat passthrough) -- but only when it is still +eligible under the request's own constraints (explicit concrete model, +free/ZDR, circuit state); otherwise routing falls back to the normal order. +On the Responses surface a served `function_call` item's `call_id` is +recorded the same way a chat `tool_calls[].id` is, and a follow-up's +`function_call_output` item needs no separate lookup: the existing +input-to-chat conversion already turns it into a `role: "tool"` / +`tool_call_id` message before candidate selection runs. The served +response's `orchestration` extension records `tool_loop_route` +(`"emitting_agent"`/`"fallback"`) and `tool_loop_agent_id` as evidence on +every one of these paths. + ## Implementation Mapping This repository implements the interface and control plane, not the trained diff --git a/docs/doctoring/TOOL_EXECUTION_FALLBACKS.md b/docs/doctoring/TOOL_EXECUTION_FALLBACKS.md index d68bafe48..fd3d855b7 100644 --- a/docs/doctoring/TOOL_EXECUTION_FALLBACKS.md +++ b/docs/doctoring/TOOL_EXECUTION_FALLBACKS.md @@ -51,6 +51,30 @@ live-provider evidence. Do not bypass model routing in the review workflow. Protected owner merge, immutable release, consumer adoption, and a real review replay remain necessary before claiming the review-agent outage is repaired. +## Tool-loop-emitting-agent routing (2026-09-13) + +A handoff (above) tells the caller which agent to execute the tool for, but +until this change the *follow-up* carrying that tool's `role: "tool"` result +was not guaranteed to return to the same agent: a virtual selector +(`orchestrator/free`, `orchestrator/auto`, `contextual-orchestrator`) ranks +every request fresh, so a differently-ranked or failed-over provider could +receive tool results for a call it never emitted — an id-format and behavior +mismatch across providers (NIM/OpenRouter/OpenCode), and a real failure mode +for the `noema` and `opencode` reviewers that depend on multi-turn tool use +through this gateway. This closes the Fugu report's (arXiv:2606.21228 §3) +Conductor tool-loop-return contract: `TaskOrchestrator` remembers, in a +bounded `tool_loop_memory` map, which agent served each `tool_call_id`, and +`_apply_tool_loop_route` moves that agent to the front of the +already-fully-filtered candidate order for a follow-up that carries its +result — never overriding an explicit concrete model, and never placing an +otherwise-ineligible agent (circuit open, wrong free/ZDR scope) ahead of the +normal order. Served responses annotate `orchestration.tool_loop_route` +(`"emitting_agent"` or `"fallback"`) and `orchestration.tool_loop_agent_id` +so callers can observe which happened. See +`tests/test_passthrough_provider_failover.py` for the routing, fallback, +explicit-model-precedence, free-model-precedence, and LRU-eviction +contracts. + ## References — APA 7th Autio, C., Schwartz, R., Dunietz, J., Jain, S., Stanley, M., Tabassi, E., Hall, P., & Roberts, K. (2024). *Artificial intelligence risk management framework: Generative artificial intelligence profile* (NIST AI 600-1). National Institute of Standards and Technology. https://doi.org/10.6028/NIST.AI.600-1 diff --git a/docs/product-technical-gap-baseline.md b/docs/product-technical-gap-baseline.md index 9412255a2..05d429cfa 100644 --- a/docs/product-technical-gap-baseline.md +++ b/docs/product-technical-gap-baseline.md @@ -6045,6 +6045,57 @@ attempt log without reading provider text or bodies (89 related tests pass, 15.28 seconds). Full verification and release of this diagnostic addition remain pending; provider availability itself is not repaired by better logs. +### Tool-loop-emitting-agent routing — 2026-09-13 + +Paper fidelity gap (Fugu report arXiv:2606.21228 §3; Fugu-Ultra Conductor): +the paper routes a tool loop back to the agent that emitted the tool call, +but this gateway previously ranked a follow-up carrying `role: "tool"` +results like any new request under a virtual selector (`orchestrator/free`, +`orchestrator/auto`, `contextual-orchestrator`), so a different +provider/model could receive tool results for calls it never emitted — an +id-format and behavior mismatch across NIM/OpenRouter/OpenCode models, and a +real failure mode for the `noema` and `opencode` reviewers (org CI) that use +tools through this gateway. + +Local repair: `TaskOrchestrator` now keeps a bounded, thread-safe +`tool_loop_memory` map (`tool_call_id -> emitting agent id`, LRU-bounded by +`tool_loop_memory_max_entries`, default 4096 — a memory bound, not a product +limit) recorded whenever a served response carries `tool_calls` on +`proxy_completion`'s single-agent passthrough, `route_once`, `conduct`'s +worker step, and `_orchestrated_provider_completion`'s structured synthesis. +The last of these generalizes to both of its callers and both provider +surfaces: the Responses API's `function_call` items (keyed by `call_id`, +adapted into the same `{"id": ...}` shape `_record_tool_loop_agents` already +consumes from chat's `tool_calls`) and `response_format`-only chat +passthrough's `tool_calls`. `_apply_tool_loop_route` moves a follow-up's +remembered emitting agent to the front of the already-fully-filtered +candidate order only when it is still eligible under the request's own +constraints (an explicit concrete model is never overridden; free/ZDR scope +and circuit-breaker state are re-checked), falling back to the normal order +otherwise. On the Responses surface, no separate follow-up lookup was +needed: `_orchestrated_provider_completion` already converts `input` to +chat-shaped messages before candidate selection, and that conversion already +turns a `function_call_output` item into a `role: "tool"` / +`tool_call_id: call_id` message, so `_apply_tool_loop_route`'s existing chat +lookup covers it unchanged. Served responses carry +`orchestration.tool_loop_route` (`"emitting_agent"`/`"fallback"`) and +`orchestration.tool_loop_agent_id` as evidence on every one of these paths. +Nine targeted tests in `tests/test_passthrough_provider_failover.py` cover: +routing to the emitting agent over a higher-ranked one, falling back when +the emitting agent's circuit is open, explicit-concrete-model precedence +(on both `proxy_completion` and the Responses structured-synthesis path), +free-model precedence (never returns to a non-free emitting agent), LRU +eviction, a Responses `function_call` recording the serving agent, a +Responses `function_call_output` follow-up returning to it, and a +`response_format`-only chat passthrough follow-up returning to it; the +touched suite plus `tests/test_api_contract.py`, `tests/test_self_check.py`, +and `tests/test_tool_execution_fallback.py` pass locally (192 passed, 4 +known pre-existing local-only failures from the openai SDK version pin +mismatch — 2.44.0 installed vs. the locked 2.54.0 — unrelated to this +change); `python -m interrogate` reports 100% docstring coverage unchanged. +A live-traffic/consumer-adoption result from `noema` or `opencode` remains +open and is not established by this local test evidence. + ### Message-count provenance registry — 2026-09-14 Issue #1157 (shared-context accounting) required provider/model-specific diff --git a/tests/test_passthrough_provider_failover.py b/tests/test_passthrough_provider_failover.py index 0e8b4eb7e..a8257381f 100644 --- a/tests/test_passthrough_provider_failover.py +++ b/tests/test_passthrough_provider_failover.py @@ -11,6 +11,7 @@ from copy import deepcopy from dataclasses import replace from typing import Any +from unittest.mock import patch import pytest @@ -2012,6 +2013,513 @@ def test_ambiguous_transport_predicate_stops_at_the_chain_limit() -> None: assert _is_ambiguous_passthrough_transport_failure(error) is False +def _tool_call_choice(call_id: str) -> dict[str, Any]: + """Build a chat-completions-shaped provider response carrying one tool call.""" + return { + "model": "fallback-model", + "choices": [ + { + "message": { + "role": "assistant", + "tool_calls": [ + { + "id": call_id, + "type": "function", + "function": {"name": "inspect", "arguments": "{}"}, + } + ], + }, + "finish_reason": "tool_calls", + } + ], + } + + +def _plain_choice(model: str) -> dict[str, Any]: + """Build a chat-completions-shaped provider response with plain text content.""" + return { + "model": model, + "choices": [ + {"message": {"role": "assistant", "content": "done"}, "finish_reason": "stop"} + ], + } + + +def _tool_result_followup( + tools_body: dict[str, Any], call_id: str, *, model: str +) -> dict[str, Any]: + """Build a follow-up chat/completions body carrying one tool result.""" + return { + "model": model, + "messages": [ + *tools_body["messages"], + { + "role": "assistant", + "tool_calls": [ + { + "id": call_id, + "type": "function", + "function": {"name": "inspect", "arguments": "{}"}, + } + ], + }, + {"role": "tool", "tool_call_id": call_id, "content": "42"}, + ], + "tools": tools_body["tools"], + } + + +def test_tool_loop_follow_up_returns_to_the_emitting_agent() -> None: + """A tool-result follow-up is served by the agent that emitted the call, not the top-ranked one.""" + client = SequencedProxyClient( + { + "primary_agent": _http_error(503), + "fallback_agent": _tool_call_choice("call_1"), + } + ) + orchestrator = _build(client) + body = { + "model": TaskOrchestrator.AUTO_MODEL, + "messages": [{"role": "user", "content": "review code"}], + "tools": [{"type": "function", "function": {"name": "inspect"}}], + } + + first = orchestrator.proxy_completion(body) + + assert first["model"] == "fallback-model" + assert [agent_id for agent_id, _ in client.calls] == ["primary_agent", "fallback_agent"] + assert orchestrator._tool_loop_memory["call_1"] == "fallback_agent" + + client.calls.clear() + client.outcomes["fallback_agent"] = _plain_choice("fallback-model") + follow_up = _tool_result_followup(body, "call_1", model=TaskOrchestrator.AUTO_MODEL) + + result = orchestrator.proxy_completion(follow_up) + + # The top-ranked primary_agent is never attempted: the follow-up goes + # straight to the agent that emitted call_1. + assert [agent_id for agent_id, _ in client.calls] == ["fallback_agent"] + assert result["orchestration"]["tool_loop_route"] == "emitting_agent" + assert result["orchestration"]["tool_loop_agent_id"] == "fallback_agent" + + +def test_tool_loop_falls_back_when_emitting_agent_circuit_is_open() -> None: + """A circuit-open emitting agent is skipped; routing falls back and says so.""" + client = SequencedProxyClient( + { + "primary_agent": _http_error(503), + "fallback_agent": _tool_call_choice("call_2"), + } + ) + orchestrator = _build(client) + body = { + "model": TaskOrchestrator.AUTO_MODEL, + "messages": [{"role": "user", "content": "review code"}], + "tools": [{"type": "function", "function": {"name": "inspect"}}], + } + orchestrator.proxy_completion(body) + assert orchestrator._tool_loop_memory["call_2"] == "fallback_agent" + + for _ in range(orchestrator.circuit_failure_threshold): + orchestrator._record_failure("fallback_agent") + assert orchestrator._circuit_open("fallback_agent") is True + + client.calls.clear() + client.outcomes["primary_agent"] = _plain_choice("primary-model") + follow_up = _tool_result_followup(body, "call_2", model=TaskOrchestrator.AUTO_MODEL) + + result = orchestrator.proxy_completion(follow_up) + + assert [agent_id for agent_id, _ in client.calls] == ["primary_agent"] + assert result["orchestration"]["tool_loop_route"] == "fallback" + assert result["orchestration"]["tool_loop_agent_id"] == "fallback_agent" + + +def test_explicit_concrete_model_ignores_tool_loop_memory() -> None: + """An explicit concrete model is never re-ranked toward a remembered emitting agent.""" + client = SequencedProxyClient( + { + "primary_agent": _http_error(503), + "fallback_agent": _tool_call_choice("call_3"), + } + ) + orchestrator = _build(client) + body = { + "model": TaskOrchestrator.AUTO_MODEL, + "messages": [{"role": "user", "content": "review code"}], + "tools": [{"type": "function", "function": {"name": "inspect"}}], + } + orchestrator.proxy_completion(body) + assert orchestrator._tool_loop_memory["call_3"] == "fallback_agent" + + client.calls.clear() + client.outcomes["primary_agent"] = _plain_choice("primary-model") + follow_up = _tool_result_followup(body, "call_3", model="primary-model") + + result = orchestrator.proxy_completion(follow_up) + + assert [agent_id for agent_id, _ in client.calls] == ["primary_agent"] + assert "orchestration" not in result + + +def test_explicit_model_responses_passthrough_records_the_serving_agent() -> None: + """Explicit-model /v1/responses passthrough remembers a served function_call's + agent (recording only -- an explicit concrete model is still never reordered + or given tool-loop evidence).""" + client = SequencedProxyClient( + {"primary_agent": _responses_function_call("resp_call_5", "primary-model")} + ) + orchestrator = _build(client) + + result = orchestrator.proxy_completion( + {"model": "primary-model", "input": "call the tool"}, + endpoint="responses", + ) + + assert [agent_id for agent_id, _ in client.calls] == ["primary_agent"] + assert orchestrator._tool_loop_memory["resp_call_5"] == "primary_agent" + assert "orchestration" not in result + + +def test_free_model_follow_up_never_routes_to_a_non_free_emitting_agent() -> None: + """orchestrator/free never returns to a paid emitting agent, even when remembered.""" + client = SequencedProxyClient( + { + "primary_agent": _tool_call_choice("call_4"), + "fallback_agent": _plain_choice("fallback-model"), + } + ) + orchestrator = _build(client) + orchestrator.agents = [ + replace(agent, tags=(*agent.tags, "cost:free")) + if agent.id == "fallback_agent" + else agent + for agent in orchestrator.agents + ] + body = { + "model": TaskOrchestrator.AUTO_MODEL, + "messages": [{"role": "user", "content": "review code"}], + "tools": [{"type": "function", "function": {"name": "inspect"}}], + } + + orchestrator.proxy_completion(body) + assert orchestrator._tool_loop_memory["call_4"] == "primary_agent" + + client.calls.clear() + follow_up = _tool_result_followup(body, "call_4", model=TaskOrchestrator.FREE_MODEL) + + result = orchestrator.proxy_completion(follow_up) + + assert [agent_id for agent_id, _ in client.calls] == ["fallback_agent"] + assert result["orchestration"]["tool_loop_route"] == "fallback" + assert result["orchestration"]["tool_loop_agent_id"] == "primary_agent" + + +def _structured_workflow() -> dict[str, Any]: + """Return bounded pre-synthesis evidence for _orchestrated_provider_completion tests.""" + return { + "mode": "conduct", + "answer": "evidence", + "trace": [], + "verification": {}, + "plan_source": "template", + } + + +def _retryable_upstream_error(agent: ModelAgent) -> ProviderUpstreamError: + """Build a retryable structured-synthesis transport failure for one agent.""" + return ProviderUpstreamError( + agent_id=agent.id, + model=agent.model, + error_code="api_error", + message="synthetic upstream failure", + client_status=502, + provider_status=502, + retryable=True, + transport="structured_synthesis", + ) + + +def _responses_function_call(call_id: str, model: str) -> dict[str, Any]: + """Build a Responses-shaped provider response carrying one function_call.""" + return { + "model": model, + "output_text": "calling tool", + "output": [ + { + "type": "function_call", + "call_id": call_id, + "name": "inspect", + "arguments": "{}", + } + ], + } + + +def _responses_plain_output(model: str, text: str) -> dict[str, Any]: + """Build a Responses-shaped provider response with no tool call.""" + return {"model": model, "output_text": text, "output": []} + + +def test_orchestrated_responses_function_call_records_the_serving_agent() -> None: + """A served Responses ``function_call`` remembers call_id -> serving agent.""" + first = ModelAgent("first_agent", "first-model", "mock://first") + second = ModelAgent("second_agent", "second-model", "mock://second") + orchestrator = TaskOrchestrator([first, second]) + + def send(agent: ModelAgent, _endpoint: str, _payload: dict[str, Any]): + if agent.id == first.id: + raise _retryable_upstream_error(first) + return _responses_function_call("resp_call_1", second.model) + + with ( + patch.object(orchestrator, "conduct", return_value=_structured_workflow()), + patch.object(orchestrator, "_select_agent", return_value=first), + patch.object(orchestrator, "_ranked_agents", return_value=[first, second]), + patch.object(orchestrator.client, "proxy_send_once", side_effect=send), + ): + orchestrator.proxy_completion( + { + "model": TaskOrchestrator.AUTO_MODEL, + "input": "call the tool", + "tools": [{"type": "function", "function": {"name": "inspect"}}], + }, + endpoint="responses", + single_agent=False, + ) + + assert orchestrator._tool_loop_memory["resp_call_1"] == "second_agent" + + +def test_orchestrated_responses_follow_up_routes_to_the_emitting_agent() -> None: + """A Responses ``function_call_output`` follow-up returns to the emitting agent.""" + first = ModelAgent("first_agent", "first-model", "mock://first") + second = ModelAgent("second_agent", "second-model", "mock://second") + orchestrator = TaskOrchestrator([first, second]) + orchestrator._tool_loop_memory["resp_call_2"] = "second_agent" + + calls: list[str] = [] + + def send(agent: ModelAgent, _endpoint: str, _payload: dict[str, Any]): + calls.append(agent.id) + return _responses_plain_output(agent.model, "done") + + with ( + patch.object(orchestrator, "conduct", return_value=_structured_workflow()), + patch.object(orchestrator, "_select_agent", return_value=first), + patch.object(orchestrator, "_ranked_agents", return_value=[first, second]), + patch.object(orchestrator.client, "proxy_send_once", side_effect=send), + ): + result = orchestrator.proxy_completion( + { + "model": TaskOrchestrator.AUTO_MODEL, + "input": [ + { + "type": "function_call", + "call_id": "resp_call_2", + "name": "inspect", + "arguments": "{}", + }, + { + "type": "function_call_output", + "call_id": "resp_call_2", + "output": "42", + }, + ], + }, + endpoint="responses", + single_agent=False, + ) + + # The top-ranked first_agent is never attempted: the follow-up goes + # straight to the agent that emitted resp_call_2. + assert calls == ["second_agent"] + assert result["orchestration"]["tool_loop_route"] == "emitting_agent" + assert result["orchestration"]["tool_loop_agent_id"] == "second_agent" + + +def test_explicit_concrete_model_on_responses_path_ignores_tool_loop_memory() -> None: + """An explicit concrete model on the Responses surface is never re-ranked.""" + first = ModelAgent("first_agent", "first-model", "mock://first") + second = ModelAgent("second_agent", "second-model", "mock://second") + orchestrator = TaskOrchestrator([first, second]) + orchestrator._tool_loop_memory["resp_call_3"] = "second_agent" + + calls: list[str] = [] + + def send(agent: ModelAgent, _endpoint: str, _payload: dict[str, Any]): + calls.append(agent.id) + return _responses_plain_output(agent.model, "done") + + with ( + patch.object(orchestrator, "conduct", return_value=_structured_workflow()), + patch.object(orchestrator.client, "proxy_send", side_effect=send), + ): + result = orchestrator.proxy_completion( + { + "model": "first-model", + "input": [ + { + "type": "function_call_output", + "call_id": "resp_call_3", + "output": "42", + }, + ], + }, + endpoint="responses", + single_agent=False, + ) + + assert calls == ["first_agent"] + orchestration = result.get("orchestration") or {} + assert "tool_loop_route" not in orchestration + assert "tool_loop_agent_id" not in orchestration + + +def test_response_format_chat_passthrough_follow_up_routes_to_the_emitting_agent() -> None: + """response_format-only chat passthrough (the other _orchestrated_provider_completion + caller) also returns a tool-loop follow-up to the emitting agent.""" + first = ModelAgent("first_agent", "first-model", "mock://first") + second = ModelAgent("second_agent", "second-model", "mock://second") + orchestrator = TaskOrchestrator([first, second]) + body = { + "model": TaskOrchestrator.AUTO_MODEL, + "messages": [{"role": "user", "content": "classify and maybe call a tool"}], + "response_format": {"type": "json_object"}, + "tools": [{"type": "function", "function": {"name": "inspect"}}], + } + calls: list[str] = [] + + def send(agent: ModelAgent, _endpoint: str, _payload: dict[str, Any]): + calls.append(agent.id) + if agent.id == first.id: + raise _retryable_upstream_error(first) + # Content satisfies the requested json_object contract *and* the + # message carries a tool call, so this is accepted without a repair + # round while still exercising tool-loop recording. + return { + "model": second.model, + "choices": [ + { + "message": { + "role": "assistant", + "content": '{"status":"pending"}', + "tool_calls": [ + { + "id": "chat_call_1", + "type": "function", + "function": {"name": "inspect", "arguments": "{}"}, + } + ], + }, + "finish_reason": "tool_calls", + } + ], + } + + with ( + patch.object(orchestrator, "conduct", return_value=_structured_workflow()), + patch.object(orchestrator, "_select_agent", return_value=first), + patch.object(orchestrator, "_ranked_agents", return_value=[first, second]), + patch.object(orchestrator.client, "proxy_send_once", side_effect=send), + ): + orchestrator.proxy_completion(body, single_agent=False) + + assert calls == ["first_agent", "second_agent"] + assert orchestrator._tool_loop_memory["chat_call_1"] == "second_agent" + + calls.clear() + follow_up = { + **_tool_result_followup(body, "chat_call_1", model=TaskOrchestrator.AUTO_MODEL), + "response_format": {"type": "json_object"}, + } + + def follow_up_send(agent: ModelAgent, _endpoint: str, _payload: dict[str, Any]): + calls.append(agent.id) + return { + "model": agent.model, + "choices": [ + { + "message": {"role": "assistant", "content": '{"status":"ok"}'}, + "finish_reason": "stop", + } + ], + } + + with ( + patch.object(orchestrator, "conduct", return_value=_structured_workflow()), + patch.object(orchestrator, "_select_agent", return_value=first), + patch.object(orchestrator, "_ranked_agents", return_value=[first, second]), + patch.object(orchestrator.client, "proxy_send_once", side_effect=follow_up_send), + ): + result = orchestrator.proxy_completion(follow_up, single_agent=False) + + assert calls == ["second_agent"] + assert result["orchestration"]["tool_loop_route"] == "emitting_agent" + assert result["orchestration"]["tool_loop_agent_id"] == "second_agent" + + +def test_tool_loop_memory_evicts_the_oldest_entry_past_its_bound() -> None: + """The bounded tool_loop_memory map is an LRU, not a growing log.""" + orchestrator = TaskOrchestrator( + [ModelAgent("solo_agent", "solo-model")], + client=SequencedProxyClient({}), + tool_loop_memory_max_entries=1, + ) + + orchestrator._record_tool_loop_agents( + [{"id": "call_old", "type": "function"}], "agent_x" + ) + orchestrator._record_tool_loop_agents( + [{"id": "call_new", "type": "function"}], "agent_y" + ) + + assert dict(orchestrator._tool_loop_memory) == {"call_new": "agent_y"} + + +def test_route_once_explicit_model_carries_no_tool_loop_evidence() -> None: + """``route_once`` with a pinned concrete model emits no tool-loop evidence. + + The remembered emitting agent differs from the pinned one, so an unguarded + call would have produced ``tool_loop_route: "fallback"`` for a request the + gateway never re-ranked (CodeRabbit review on PR #1177). + """ + agents = [ + ModelAgent("primary_agent", "primary-model", base_url="mock://primary", priority=10), + ModelAgent("fallback_agent", "fallback-model", base_url="mock://fallback", priority=5), + ] + orchestrator = TaskOrchestrator(agents) + called: list[str] = [] + + def chat(agent: ModelAgent, _messages: list[dict], **_kwargs: object) -> str: + called.append(agent.id) + return f"served by {agent.id}" + + orchestrator.client.chat = chat # type: ignore[method-assign] + orchestrator._record_tool_loop_agents([{"id": "call_9"}], "fallback_agent") + messages = [ + {"role": "user", "content": "inspect"}, + { + "role": "assistant", + "content": None, + "tool_calls": [ + {"id": "call_9", "type": "function", "function": {"name": "inspect", "arguments": "{}"}} + ], + }, + {"role": "tool", "tool_call_id": "call_9", "content": "ok"}, + ] + + pinned = orchestrator.route_once(messages, model_name="primary-model") + assert called == ["primary_agent"] + assert "tool_loop_route" not in pinned + assert "tool_loop_agent_id" not in pinned + + called.clear() + virtual = orchestrator.route_once(messages, model_name=TaskOrchestrator.AUTO_MODEL) + assert called[0] == "fallback_agent" + assert virtual["tool_loop_route"] == "emitting_agent" + assert virtual["tool_loop_agent_id"] == "fallback_agent" + @pytest.mark.parametrize( ("status", "body", "expected"), [ @@ -2235,4 +2743,3 @@ def test_context_window_filter_does_not_apply_to_an_explicit_model_request() -> assert result["model"] == "tiny-window-model" assert [agent_id for agent_id, _ in client.calls] == ["tiny_window_agent"] assert "orchestration" not in result -