diff --git a/.superpowers/sdd/2026-08-23-conversation-worktree-isolation-plan/task-8-report.md b/.superpowers/sdd/2026-08-23-conversation-worktree-isolation-plan/task-8-report.md new file mode 100644 index 0000000000..fc28c7771c --- /dev/null +++ b/.superpowers/sdd/2026-08-23-conversation-worktree-isolation-plan/task-8-report.md @@ -0,0 +1,34 @@ +# Task 8 — Guarded fast compression lane + +## Scope + +- Existing profile role: `performance-sentinel`. +- No profiles, local configuration, services, TradingBot sources, or subagents changed. +- Main chat route, natural-language routing, and default compression inheritance remain unchanged. + +## TDD evidence + +- RED: the initial focused Python run produced three expected failures: the fast-lane resolver was absent and phase timing telemetry had no contract. +- RED: the request-level wire test then failed with `KeyError: 'max_tokens'`, proving the generic auxiliary builder omitted the configured local fast-lane cap. +- Review RED: `7 failed, 1 passed` proved the first implementation certified configuration before the effective route, suppressed inherited reasoning, treated pre-dispatch liveness as first progress, and did not independently certify fallback caps. +- Review GREEN: `495 passed` across fast-lane, compression telemetry, context-compressor, continuity, fallback-budget, progress-timeout, worker-isolation, auxiliary-client/concurrency, TUI compaction status, and worktree-lineage tests. +- Desktop GREEN: focused compaction lifecycle test passed (`6 passed`); ESLint, Prettier, and TypeScript checks passed. + +## Latency and safety contract + +- A bounded output request is sent only after the concrete primary provider/model has been resolved once and matches the explicit compression route (including a `summary_model` override), with `reasoning_effort: none` and a positive `max_output_tokens`. +- Fallbacks drop primary-only cap/non-reasoning fast controls. A configured fallback gets a cap only when its own provider, model, `reasoning_effort: none`, and positive output cap match the actual fallback destination; auth-refresh retries are re-certified against their actual destination too. +- Inherited, `auto`, unknown, drifted, reasoning, malformed, and boolean-cap routes stay uncapped. Their pre-existing `reasoning_effort` behavior is unchanged. +- Compression telemetry is content-free and carries queue wait, prompt build, provider dispatch, first provider response/chunk, summary generation, and commit timings. Prompt and summary bodies are not logged. A delayed-first-chunk regression proves pre-dispatch liveness cannot set TTFP. +- The structured checkpoint, redaction, tail, archive/commit, fallback, cooldown, and compression-lineage worktree behavior remain on their existing paths. +- Desktop clears a stale compacting flag only from trusted server terminal or resumed-turn evidence, never from a timer. + +## Static checks + +- Ruff (`--no-cache`), `git diff --check`, desktop ESLint (0 errors), Task 8 scoped Prettier, and TypeScript passed. +- The repository-wide desktop Prettier baseline remains non-green in 16 unrelated pre-existing files; none are Task 8 files and none were modified. + +## Commit + +- `d7428c757a perf(compression): add guarded fast summary lane` +- Follow-up review correction: pending commit at report-write time. diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.py index 0053c1cade..40245874dd 100644 --- a/agent/auxiliary_client.py +++ b/agent/auxiliary_client.py @@ -443,6 +443,8 @@ class _AuxiliaryCancellationDecision: # call topology — the aux call and its stream consumption run synchronously # on the thread that installed the hook. _aux_progress = threading.local() +_aux_dispatch = threading.local() +_aux_provider_response = threading.local() def _notify_aux_progress() -> None: @@ -456,6 +458,27 @@ def _notify_aux_progress() -> None: logger.debug("aux progress hook failed", exc_info=True) +def _notify_aux_dispatch() -> None: + """Record an actual provider dispatch without claiming response progress.""" + hook = getattr(_aux_dispatch, "hook", None) + if hook is not None: + try: + hook() + except Exception: + logger.debug("aux dispatch hook failed", exc_info=True) + + +def _notify_aux_provider_response() -> None: + """Record a provider response/chunk, then preserve the liveness signal.""" + hook = getattr(_aux_provider_response, "hook", None) + if hook is not None: + try: + hook() + except Exception: + logger.debug("aux provider response hook failed", exc_info=True) + _notify_aux_progress() + + def _aux_progress_active() -> bool: return getattr(_aux_progress, "hook", None) is not None @@ -475,6 +498,17 @@ def aux_progress_hook(hook): _aux_progress.hook = prev +@contextlib.contextmanager +def _aux_timing_hook(local: threading.local, hook): + """Install one content-free timing hook and restore its prior value.""" + previous = getattr(local, "hook", None) + local.hook = hook if callable(hook) else previous + try: + yield + finally: + local.hook = previous + + def _run_protected_sync_provider_call( callback: Callable[[dict[str, Any]], Any], kwargs: dict[str, Any], @@ -1859,7 +1893,7 @@ class _CodexCompletionsAdapter: # Each SSE event is also forward progress for hosts watching # a progress hook (gateway session hygiene): a reasoning # model streaming a long summary must not look hung. - _notify_aux_progress() + _notify_aux_provider_response() _check_cancelled() event_stream = self._client.responses.create(**stream_kwargs) @@ -2218,7 +2252,7 @@ class _AnthropicCompletionsAdapter: # slow-but-generating summary model. No-op when no hook is # installed (None keeps the fast get_final_message path). on_stream_event=( - (lambda _event: _notify_aux_progress()) + (lambda _event: _notify_aux_provider_response()) if _aux_progress_active() else None ), ) @@ -5283,6 +5317,25 @@ def _call_fallback_candidate_sync( ) effective_timeout = fb_timeout destination = _fallback_destination(task, fb_client, fb_model, fb_label) + fallback_max_tokens = max_tokens + fallback_extra_body = dict(effective_extra_body) + if task == "compression" and max_tokens is None: + task_config = _get_auxiliary_task_config(task) + fallback_entry = _fallback_chain_entry(task, fb_label) + fallback_lane = resolve_compression_fast_lane( + destination.provider, + destination.model, + requested_provider=(fallback_entry or {}).get("provider"), + requested_model=(fallback_entry or {}).get("model"), + route_config=fallback_entry or {}, + ) + fallback_max_tokens = fallback_lane.max_tokens + if fallback_lane.reasoning_config is not None: + fallback_extra_body["reasoning"] = fallback_lane.reasoning_config + elif _compression_config_claims_fast_lane(task_config): + # A primary-only fast control must not leak to an uncertified + # fallback. Inherited/auto reasoning controls retain old behavior. + fallback_extra_body.pop("reasoning", None) fallback_messages, fallback_tools = _replan_synchronous_cache_sections( messages, tools, @@ -5290,10 +5343,14 @@ def _call_fallback_candidate_sync( ) fb_kwargs = _build_call_kwargs( destination.provider, destination.model, fallback_messages, - temperature=temperature, max_tokens=max_tokens, + temperature=temperature, max_tokens=fallback_max_tokens, tools=fallback_tools, timeout=effective_timeout, - extra_body=effective_extra_body, reasoning_config=reasoning_config, + extra_body=fallback_extra_body, reasoning_config=reasoning_config, base_url=destination.base_url, task=task) + if fallback_max_tokens is not None and max_tokens is None: + fb_kwargs.update( + auxiliary_max_tokens_param(fallback_max_tokens, model=destination.model) + ) try: return _validate_llm_response( _relay_sync_completion( @@ -5301,6 +5358,14 @@ def _call_fallback_candidate_sync( fb_kwargs, provider=destination.provider, api_mode=destination.api_mode, + create=lambda request: _create_with_progress( + fb_client, + request, + task, + force_stream=_provider_requires_stream( + destination.provider, destination.base_url + ), + ), ), task, ) @@ -5330,15 +5395,36 @@ def _call_fallback_candidate_sync( tools, destination=retry_destination, ) + retry_max_tokens = max_tokens + retry_extra_body = dict(effective_extra_body) + if task == "compression" and max_tokens is None: + retry_lane = resolve_compression_fast_lane( + retry_destination.provider, + retry_destination.model, + requested_provider=(fallback_entry or {}).get("provider"), + requested_model=(fallback_entry or {}).get("model"), + route_config=fallback_entry or {}, + ) + retry_max_tokens = retry_lane.max_tokens + if retry_lane.reasoning_config is not None: + retry_extra_body["reasoning"] = retry_lane.reasoning_config + elif _compression_config_claims_fast_lane(task_config): + retry_extra_body.pop("reasoning", None) retry_kwargs = _build_call_kwargs( retry_destination.provider, retry_destination.model, retry_messages, - temperature=temperature, max_tokens=max_tokens, + temperature=temperature, max_tokens=retry_max_tokens, tools=retry_tools, timeout=effective_timeout, - extra_body=effective_extra_body, + extra_body=retry_extra_body, reasoning_config=reasoning_config, base_url=retry_destination.base_url, task=task) + if retry_max_tokens is not None and max_tokens is None: + retry_kwargs.update( + auxiliary_max_tokens_param( + retry_max_tokens, model=retry_destination.model + ) + ) try: return _validate_llm_response( _relay_sync_completion( @@ -5346,6 +5432,15 @@ def _call_fallback_candidate_sync( retry_kwargs, provider=retry_destination.provider, api_mode=retry_destination.api_mode, + create=lambda request: _create_with_progress( + retry_client, + request, + task, + force_stream=_provider_requires_stream( + retry_destination.provider, + retry_destination.base_url, + ), + ), ), task, ) @@ -8367,19 +8462,35 @@ class CompressionFastLane(NamedTuple): reasoning_config: Optional[Dict[str, Any]] -def resolve_compression_fast_lane() -> CompressionFastLane: - """Resolve the opt-in compression-only fast lane without changing defaults. +def resolve_compression_fast_lane( + actual_provider: str, + actual_model: Optional[str], + *, + requested_provider: Optional[str] = None, + requested_model: Optional[str] = None, + route_config: Optional[Dict[str, Any]] = None, +) -> CompressionFastLane: + """Certify the opt-in fast lane against one already-resolved route. A cap is safe only when the operator has selected a concrete auxiliary - provider/model and explicitly certified the route as non-reasoning. Auto - and inherited routes deliberately retain the historic uncapped request. + provider/model, explicitly certified it as non-reasoning, and that exact + route is the one Hermes will call. A requested model covers a compressor + summary-model override. Auto/inherited and drifted routes stay uncapped. """ - config = _get_auxiliary_task_config("compression") - provider = str(config.get("provider") or "").strip().lower() - model = str(config.get("model") or "").strip() + config = ( + route_config + if route_config is not None + else _get_auxiliary_task_config("compression") + ) + provider = str(requested_provider or config.get("provider") or "").strip().lower() + model = str(requested_model or config.get("model") or "").strip() effort = str(config.get("reasoning_effort") or "").strip().lower() explicit_route = provider not in {"", "auto"} and model.lower() not in {"", "auto"} - certified = explicit_route and effort == "none" + provider_matches = _normalize_aux_provider( + _fallback_provider_from_label(str(actual_provider or "")) + ) == _normalize_aux_provider(provider) + model_matches = str(actual_model or "").strip().lower() == model.lower() + certified = explicit_route and provider_matches and model_matches and effort == "none" if not certified: return CompressionFastLane(False, None, None) raw_cap = config.get("max_output_tokens") @@ -8394,6 +8505,23 @@ def resolve_compression_fast_lane() -> CompressionFastLane: ) +def _compression_config_claims_fast_lane(config: Dict[str, Any]) -> bool: + """Whether task config declares fast-only controls that cannot leak.""" + provider = str(config.get("provider") or "").strip().lower() + model = str(config.get("model") or "").strip().lower() + effort = str(config.get("reasoning_effort") or "").strip().lower() + try: + cap = int(config.get("max_output_tokens") or 0) + except (TypeError, ValueError): + cap = 0 + return ( + provider not in {"", "auto"} + and model not in {"", "auto"} + and effort == "none" + and cap > 0 + ) + + def _get_task_timeout(task: str, default: float = _DEFAULT_AUX_TIMEOUT) -> float: """Read timeout from auxiliary.{task}.timeout in config, falling back to *default*.""" if not task: @@ -8448,18 +8576,6 @@ def _get_task_extra_body(task: str) -> Dict[str, Any]: result = dict(raw) if isinstance(raw, dict) else {} if "reasoning" not in result: effort = task_config.get("reasoning_effort") - if task == "compression" and str(effort or "").strip().lower() == "none": - # Do not let an inherited/main route silently inherit an explicit - # ``none`` intended for a configured fast summarizer. The main - # chat model and its reasoning policy remain untouched. - fast_lane = resolve_compression_fast_lane() - if fast_lane.reasoning_config is not None: - result["reasoning"] = fast_lane.reasoning_config - return result - # Other explicit compression reasoning policies retain their - # established behavior. This guard is narrowly about a claimed - # fast non-reasoning route. - return result if effort is not None and effort != "": if task in ("moa_reference", "moa_aggregator"): logger.warning( @@ -9183,9 +9299,13 @@ def _create_with_progress( stream-only provider rejects the plain call by definition, so the original error is surfaced to the normal recovery chains instead. """ - _notify_aux_progress() # request dispatched counts as progress + _notify_aux_dispatch() + _notify_aux_progress() # Preserve the watchdog's historical dispatch tick. if (not _aux_progress_active() and not force_stream) or _client_streams_internally(client): - return client.chat.completions.create(**kwargs) + response = client.chat.completions.create(**kwargs) + if not _client_streams_internally(client): + _notify_aux_provider_response() + return response total_ceiling = _aux_stream_total_ceiling(kwargs.get("timeout")) stream_kwargs = dict(kwargs) @@ -9214,12 +9334,15 @@ def _create_with_progress( "Auxiliary %s: streamed request failed (%s); retrying " "non-streaming", task or "call", exc, ) - return client.chat.completions.create(**kwargs) + _notify_aux_dispatch() + response = client.chat.completions.create(**kwargs) + _notify_aux_provider_response() + return response # Some shims (MoA virtual provider under quiet mode, defensive adapters) # return a complete response even when stream=True was requested. if hasattr(chunks, "choices"): - _notify_aux_progress() + _notify_aux_provider_response() return chunks return _aggregate_chat_stream( chunks, model=str(kwargs.get("model") or ""), total_ceiling=total_ceiling, @@ -9275,7 +9398,7 @@ class _ChatStreamAccumulator: self.resp_model = model or "" def feed(self, chunk: Any) -> None: - _notify_aux_progress() + _notify_aux_provider_response() if ( self._total_ceiling is not None and (time.monotonic() - self._started) >= self._total_ceiling @@ -9439,19 +9562,30 @@ def call_llm( latency_info["queue_wait_ms"] = max( 0, int((request_started_at - queue_started_at) * 1000) ) - prior_progress_hook = getattr(_aux_progress, "hook", None) - def _timed_progress() -> None: + def _timed_response() -> None: if latency_info is not None and "time_to_first_progress_ms" not in latency_info: latency_info["time_to_first_progress_ms"] = max( 0, int((time.monotonic() - request_started_at) * 1000) ) - if callable(prior_progress_hook): - prior_progress_hook() + + def _timed_dispatch() -> None: + if latency_info is not None and "provider_dispatch_ms" not in latency_info: + latency_info["provider_dispatch_ms"] = max( + 0, int((time.monotonic() - request_started_at) * 1000) + ) try: - with aux_progress_hook(_timed_progress if latency_info is not None else prior_progress_hook): + with ( + aux_progress_hook( + prior_progress_hook + if callable(prior_progress_hook) + else ((lambda: None) if latency_info is not None else None) + ), + _aux_timing_hook(_aux_dispatch, _timed_dispatch), + _aux_timing_hook(_aux_provider_response, _timed_response), + ): response = _call_llm_impl( task=task, provider=provider, @@ -9653,13 +9787,22 @@ def _call_llm_impl( f"Run: hermes setup") effective_timeout = _effective_aux_timeout(task, timeout) - fast_compression_lane = resolve_compression_fast_lane() if task == "compression" else None - force_fast_compression_cap = bool( - fast_compression_lane is not None - and fast_compression_lane.max_tokens is not None - and max_tokens == fast_compression_lane.max_tokens - ) request_provider = effective_provider or resolved_provider + fast_compression_lane = ( + resolve_compression_fast_lane( + request_provider, + final_model, + requested_provider=provider, + requested_model=model, + ) + if task == "compression" + else None + ) + fast_compression_cap = ( + fast_compression_lane.max_tokens + if fast_compression_lane is not None and max_tokens is None + else None + ) _set_relay_auxiliary_route( request_provider, final_model, @@ -9685,12 +9828,12 @@ def _call_llm_impl( tools=tools, timeout=effective_timeout, extra_body=effective_extra_body, reasoning_config=reasoning_config, base_url=_base_info or resolved_base_url, task=task) - if force_fast_compression_cap: + if fast_compression_cap is not None: # Normal auxiliary calls intentionally omit a cap on most # OpenAI-compatible/local providers. This is the narrow exception: # the configured compression route is concrete and certified # non-reasoning, so a bounded summary request is intentional. - kwargs.update(auxiliary_max_tokens_param(max_tokens, model=final_model)) + kwargs.update(auxiliary_max_tokens_param(fast_compression_cap, model=final_model)) if extra_headers: kwargs["extra_headers"] = dict(extra_headers) diff --git a/agent/context_compressor.py b/agent/context_compressor.py index 62e08d31d1..89e1a00fe2 100644 --- a/agent/context_compressor.py +++ b/agent/context_compressor.py @@ -33,7 +33,6 @@ from agent.auxiliary_client import ( _is_connection_error, aux_interrupt_protection, call_llm, - resolve_compression_fast_lane, ) from agent.context_engine import ContextEngine, sanitize_memory_context from agent.error_classifier import FailoverReason, classify_api_error @@ -5076,7 +5075,6 @@ FOCUS TOPIC: "{focus_topic}" This compaction should PRIORITISE preserving all information related to the focus topic above. For content related to "{focus_topic}", include full detail — exact values, file paths, command outputs, error messages, and decisions. For content NOT related to the focus topic, summarise more aggressively (brief one-liners or omit if truly irrelevant). The focus topic sections should receive roughly 60-70% of the summary token budget. Even for the focus topic, NEVER preserve API keys, tokens, passwords, or credentials — use [REDACTED].""" try: - fast_lane = resolve_compression_fast_lane() call_kwargs = { "task": "compression", "main_runtime": { @@ -5098,36 +5096,20 @@ This compaction should PRIORITISE preserving all information related to the focu # fall back to the model's native output ceiling. # timeout resolved from auxiliary.compression.timeout config by call_llm } - if fast_lane.max_tokens is not None: - call_kwargs["max_tokens"] = fast_lane.max_tokens if self.summary_model: call_kwargs["model"] = self.summary_model - _aux_provider = "" - _aux_model = self.summary_model or "" - _aux_context = None - try: - from agent.auxiliary_client import _resolve_task_provider_model - - _resolved_provider, _resolved_model, _, _, _ = _resolve_task_provider_model( - "compression", - model=(self.summary_model or ""), - ) - _aux_provider = _resolved_provider or "" - _aux_model = _resolved_model or _aux_model or self.model or "" - if _aux_model == self.model: - _aux_context = self.context_length - except Exception: - pass + # ``call_llm`` writes the one concrete route it actually selected; + # do not independently pre-resolve a second, potentially stale + # provider/model pair for telemetry or fast-lane certification. + _aux_route: Dict[str, str] = {} + call_kwargs["route_info"] = _aux_route # A pinned route (stall fallback, #78981) is an explicit override: - # it replaces the task-config route for this one call so the retry - # actually leaves the backend that just stalled, and it re-points - # the aux telemetry at where the request really went. + # it replaces task routing for this one call so the retry actually + # leaves the backend that just stalled. ``call_llm`` still records + # the final selected route in ``_aux_route``. _pinned_route = _pinned_summary_call_kwargs() if _pinned_route: call_kwargs.update(_pinned_route) - _aux_provider = str(_pinned_route.get("provider") or _aux_provider) - _aux_model = str(_pinned_route.get("model") or _aux_model) - _aux_context = None # Compression is atomic: protect the in-flight summary call from a # mid-turn gateway interrupt. Without this, an incoming user message # aborts the summary and compression falls back to a degraded static @@ -5142,6 +5124,11 @@ This compaction should PRIORITISE preserving all information related to the focu with aux_interrupt_protection(): response = call_llm(**call_kwargs) finally: + _aux_provider = _aux_route.get("provider") or self.provider or "" + _aux_model = ( + _aux_route.get("model") or self.summary_model or self.model or "" + ) + _aux_context = self.context_length if _aux_model == self.model else None self._record_aux_compression_call( prompt_messages=call_kwargs["messages"], # Current main intentionally omits max_tokens from the aux diff --git a/tests/agent/test_fast_compression_lane.py b/tests/agent/test_fast_compression_lane.py index b8198bcdb6..6f2840b16b 100644 --- a/tests/agent/test_fast_compression_lane.py +++ b/tests/agent/test_fast_compression_lane.py @@ -1,17 +1,22 @@ """Contract tests for the opt-in non-reasoning compression fast lane.""" import time +from types import SimpleNamespace from unittest.mock import MagicMock, patch -def _resolve(config): +def _resolve(config, *, provider="ollama", model="qwen3:8b", requested_model=None): from agent.auxiliary_client import resolve_compression_fast_lane with patch( "agent.auxiliary_client._get_auxiliary_task_config", return_value=config, ): - return resolve_compression_fast_lane() + return resolve_compression_fast_lane( + provider, + model, + requested_model=requested_model, + ) def test_explicit_non_reasoning_compression_route_is_certified_and_bounded(): @@ -47,7 +52,7 @@ def test_inherited_auto_or_uncertified_compression_routes_remain_uncapped(): assert lane.reasoning_config is None -def test_only_a_certified_lane_forwards_non_reasoning_request_controls(): +def test_inherited_reasoning_control_is_preserved_without_enabling_a_cap(): from agent.auxiliary_client import _get_task_extra_body certified = { @@ -66,13 +71,39 @@ def test_only_a_certified_lane_forwards_non_reasoning_request_controls(): with patch("agent.auxiliary_client._get_auxiliary_task_config", return_value=certified): assert _get_task_extra_body("compression")["reasoning"] == { "enabled": False, - "effort": "none", } with patch("agent.auxiliary_client._get_auxiliary_task_config", return_value=inherited): - assert "reasoning" not in _get_task_extra_body("compression") + assert _get_task_extra_body("compression")["reasoning"] == { + "enabled": False, + } -def test_compression_latency_records_queue_wait_and_first_progress(): +def test_summary_model_override_is_certified_against_the_effective_model(): + config = { + "provider": "ollama", + "model": "qwen3:8b", + "reasoning_effort": "none", + "max_output_tokens": 1400, + } + + override = _resolve( + config, + provider="ollama", + model="qwen3:14b", + requested_model="qwen3:14b", + ) + drifted = _resolve( + config, + provider="ollama", + model="server-selected-model", + requested_model="qwen3:14b", + ) + + assert override.max_tokens == 1400 + assert drifted.max_tokens is None + + +def test_compression_latency_records_delayed_first_provider_chunk(): from agent.auxiliary_client import _notify_aux_progress, call_llm class _DelayedSemaphore: @@ -84,22 +115,45 @@ def test_compression_latency_records_queue_wait_and_first_progress(): timings = {} - def _progressing_call(**_kwargs): + client = MagicMock() + client.base_url = "http://127.0.0.1:11434/v1" + + def _chunks(): + time.sleep(0.02) + yield SimpleNamespace( + id="chunk-1", + model="qwen3:8b", + usage=None, + choices=[ + SimpleNamespace( + finish_reason="stop", + delta=SimpleNamespace(content="summary", tool_calls=None), + ) + ], + ) + + def _resolve_client(*_args, **_kwargs): + # Pre-dispatch liveness must not count as provider response progress. _notify_aux_progress() - return object() + return client, "qwen3:8b" + + client.chat.completions.create.side_effect = lambda **_kwargs: _chunks() with ( patch("agent.auxiliary_client._acquire_sync_aux_semaphore", return_value=_DelayedSemaphore()), - patch("agent.auxiliary_client._call_llm_impl", side_effect=_progressing_call), + patch("agent.auxiliary_client._get_cached_client", side_effect=_resolve_client), ): - call_llm( + response = call_llm( task="compression", messages=[{"role": "user", "content": "summary request"}], latency_info=timings, ) + assert response.choices[0].message.content == "summary" assert timings["queue_wait_ms"] >= 5 - assert timings["time_to_first_progress_ms"] >= 0 + assert timings["provider_dispatch_ms"] >= 0 + assert timings["time_to_first_progress_ms"] >= 15 + assert timings["time_to_first_progress_ms"] >= timings["provider_dispatch_ms"] assert timings["summary_generation_ms"] >= timings["time_to_first_progress_ms"] @@ -125,9 +179,125 @@ def test_certified_fast_lane_sends_the_configured_cap_to_its_provider(): assert call_llm( task="compression", messages=[{"role": "user", "content": "summary request"}], - max_tokens=1400, ) is response request = client.chat.completions.create.call_args.kwargs assert request["max_tokens"] == 1400 - assert request["extra_body"]["reasoning"] == {"enabled": False, "effort": "none"} + assert request["extra_body"]["reasoning"] == {"enabled": False} + + +def test_uncertified_effective_primary_route_does_not_receive_fast_cap(): + from agent.auxiliary_client import call_llm + + config = { + "provider": "ollama", + "model": "qwen3:8b", + "reasoning_effort": "none", + "max_output_tokens": 1400, + } + client = MagicMock() + client.base_url = "http://127.0.0.1:11434/v1" + response = object() + client.chat.completions.create.return_value = response + + with ( + patch("agent.auxiliary_client._get_auxiliary_task_config", return_value=config), + patch( + "agent.auxiliary_client._get_cached_client", + return_value=(client, "server-selected-model"), + ), + patch("agent.auxiliary_client._validate_llm_response", return_value=response), + ): + assert call_llm( + task="compression", + messages=[{"role": "user", "content": "summary request"}], + ) is response + + request = client.chat.completions.create.call_args.kwargs + assert "max_tokens" not in request + assert "max_completion_tokens" not in request + + +def test_summary_model_override_cap_uses_the_actual_primary_request(): + from agent.auxiliary_client import call_llm + + config = { + "provider": "ollama", + "model": "qwen3:8b", + "reasoning_effort": "none", + "max_output_tokens": 1400, + } + client = MagicMock() + client.base_url = "http://127.0.0.1:11434/v1" + response = object() + client.chat.completions.create.return_value = response + + with ( + patch("agent.auxiliary_client._get_auxiliary_task_config", return_value=config), + patch("agent.auxiliary_client._get_cached_client", return_value=(client, "qwen3:14b")), + patch("agent.auxiliary_client._validate_llm_response", return_value=response), + ): + assert call_llm( + task="compression", + model="qwen3:14b", + messages=[{"role": "user", "content": "summary request"}], + ) is response + + request = client.chat.completions.create.call_args.kwargs + assert request["model"] == "qwen3:14b" + assert request["max_tokens"] == 1400 + + +def test_fallback_cap_requires_independent_route_certification(): + from agent.auxiliary_client import _call_fallback_candidate_sync + + response = object() + + def _request_for(entry): + config = { + "fallback_chain": [entry], + "provider": "ollama", + "model": "qwen3:8b", + "reasoning_effort": "none", + "max_output_tokens": 1400, + } + client = MagicMock() + client.base_url = "http://127.0.0.1:11434/v1" + client.chat.completions.create.return_value = response + with ( + patch("agent.auxiliary_client._get_auxiliary_task_config", return_value=config), + patch("agent.auxiliary_client._validate_llm_response", return_value=response), + ): + assert _call_fallback_candidate_sync( + client, + "qwen3:14b", + "fallback_chain[0](ollama)", + task="compression", + messages=[{"role": "user", "content": "summary request"}], + temperature=None, + max_tokens=None, + tools=None, + effective_timeout=300, + effective_extra_body={"reasoning": {"enabled": False, "effort": "none"}}, + reasoning_config=None, + ) is response + return client.chat.completions.create.call_args.kwargs + + uncertified = _request_for({"provider": "ollama", "model": "qwen3:14b"}) + certified = _request_for( + { + "provider": "ollama", + "model": "qwen3:14b", + "reasoning_effort": "none", + "max_output_tokens": 900, + } + ) + + assert "max_tokens" not in uncertified + assert "max_completion_tokens" not in uncertified + assert "reasoning" not in uncertified.get("extra_body", {}) + assert certified["max_tokens"] == 900 + assert certified["extra_body"]["reasoning"] == { + "enabled": False, + "effort": "none", + }