From 2002f03e42a8a8ca9034efa809f24b07313b4fd4 Mon Sep 17 00:00:00 2001 From: teknium1 <127238744+teknium1@users.noreply.github.com> Date: Wed, 23 Sep 2026 02:22:18 -0700 Subject: [PATCH] test: purge low-value tests, lane py02 (261 removed) Change-detectors, tautologies, source-reading tests, redundant duplicates, mock-echo tests and dead/unrunnable tests. Per-test rationale in the lane ledger (category + reason for every removal). --- .../test_compression_attempt_lifecycle.py | 17 - .../test_compression_auto_summary_fallback.py | 1 - tests/agent/test_compression_boundary_hook.py | 15 - .../agent/test_compression_closed_adoption.py | 18 - .../agent/test_compression_concurrent_fork.py | 251 +-------- tests/agent/test_compression_feasibility.py | 76 +-- tests/agent/test_compression_lock_defer.py | 6 - .../test_compression_max_attempts_config.py | 20 - tests/agent/test_compression_persistence.py | 39 -- tests/agent/test_compression_review.py | 34 +- .../agent/test_compression_rotation_state.py | 196 +------ ...t_compression_small_ctx_threshold_floor.py | 28 - ...test_compression_split_failure_cooldown.py | 56 -- ...ompression_stall_deterministic_fallback.py | 23 - .../test_compression_timeout_terminal.py | 3 - ..._compression_trigger_excludes_reasoning.py | 48 -- .../test_compressor_assistant_tail_anchor.py | 30 -- .../agent/test_compressor_historical_media.py | 50 -- .../agent/test_compressor_media_stripping.py | 6 - .../test_compressor_stale_tool_images.py | 2 - .../agent/test_compressor_tool_call_budget.py | 6 +- .../test_concurrent_multimodal_logging.py | 45 -- tests/agent/test_content_policy_blocked.py | 54 -- ...est_content_policy_refusal_stop_details.py | 16 +- tests/agent/test_context_breakdown.py | 18 - tests/agent/test_context_compressor.py | 489 +----------------- ..._context_compressor_cross_session_guard.py | 14 - .../test_context_compressor_task_heading.py | 14 - ...context_compressor_zero_user_provenance.py | 9 +- tests/agent/test_context_engine.py | 155 ------ .../test_context_engine_host_contract.py | 36 -- ...t_context_engine_on_turn_complete_usage.py | 13 - .../test_context_engine_select_context.py | 17 - tests/agent/test_context_overflow_loop.py | 225 -------- tests/agent/test_context_pin.py | 3 +- tests/agent/test_context_refs_concurrent.py | 15 - tests/agent/test_context_token_tracking.py | 5 - .../agent/test_continuation_ceiling_wedge.py | 25 +- .../test_continuation_repetition_guard.py | 2 +- ..._conversation_loop_interpreter_shutdown.py | 11 - tests/agent/test_copilot_acp_client.py | 16 - tests/agent/test_copilot_acp_deprecation.py | 6 - tests/agent/test_copilot_initiator.py | 44 -- .../test_corruption_recovery_guidance.py | 29 -- ...eate_openai_client_disables_sdk_retries.py | 30 -- .../test_create_openai_client_ssl_verify.py | 17 - tests/agent/test_credential_pool.py | 151 ------ ..._credential_pool_anthropic_refresh_race.py | 45 -- .../test_credential_pool_deferred_refresh.py | 27 - ..._credential_pool_lease_refresh_reselect.py | 20 - ...test_credential_pool_profile_oauth_fork.py | 52 -- ...test_credential_pool_quarantine_locking.py | 136 ----- tests/agent/test_credential_pool_routing.py | 62 --- .../test_credential_pool_sole_cooldown.py | 29 -- tests/agent/test_credits_fixture_snapshot.py | 56 -- tests/agent/test_credits_notices_toggle.py | 16 - tests/agent/test_credits_policy.py | 77 --- tests/agent/test_credits_tracker.py | 133 ----- tests/agent/test_credits_view.py | 38 +- .../test_cron_inflight_prompt_reappend.py | 14 - tests/agent/test_cross_process_turn_lease.py | 30 +- tests/agent/test_crossloop_client_cache.py | 36 -- tests/agent/test_ctx_halving_fix.py | 82 +-- tests/agent/test_curator.py | 150 +----- tests/agent/test_curator_backup.py | 36 +- tests/agent/test_curator_classification.py | 57 +- tests/agent/test_curator_reports.py | 1 - .../agent/test_cursor_optimizations_parity.py | 95 +--- tests/agent/test_custom_provider_ca_probes.py | 36 -- tests/agent/test_deadline.py | 77 +-- tests/agent/test_deepseek_v4_thinking_live.py | 245 --------- tests/agent/test_display.py | 25 +- tests/agent/test_display_emoji.py | 5 - tests/agent/test_display_todo_progress.py | 60 --- .../test_empty_tool_name_loop_dampening.py | 2 +- tests/agent/test_endpoint_blackhole.py | 28 - tests/agent/test_engine_preflight_wire.py | 20 +- .../agent/test_env_credential_turn_refresh.py | 19 - tests/agent/test_env_loader_secret_sources.py | 24 - tests/agent/test_error_classifier.py | 50 +- tests/agent/test_estimator_parity.py | 46 -- tests/agent/test_failed_turn_chat_copy.py | 31 +- tests/agent/test_failed_turn_site_codes.py | 21 +- .../agent/test_fallback_429_after_timeout.py | 153 ------ .../test_fallback_credential_isolation.py | 127 ----- tests/agent/test_file_mutation_verifier.py | 79 +-- .../agent/test_file_safety_sandbox_mirror.py | 16 - tests/agent/test_fireworks_live.py | 60 --- .../agent/test_gemini_key_surface_guidance.py | 7 - tests/agent/test_gemini_native_adapter.py | 14 - .../test_gemini_standard_key_guidance.py | 27 - tests/agent/test_ghost_skill_pruning.py | 19 - ...t_grid_sweep_cli_tui_stream_diagnostics.py | 128 ----- .../agent/test_hermetic_side_effect_guards.py | 32 -- .../test_idle_compaction_lock_and_guards.py | 34 -- tests/agent/test_image_corrupt_recovery.py | 25 - tests/agent/test_image_generate_parallel.py | 55 +- tests/agent/test_image_rejection_fallback.py | 10 - tests/agent/test_image_routing.py | 28 - 99 files changed, 127 insertions(+), 4952 deletions(-) delete mode 100644 tests/agent/test_compression_split_failure_cooldown.py delete mode 100644 tests/agent/test_compression_trigger_excludes_reasoning.py delete mode 100644 tests/agent/test_concurrent_multimodal_logging.py delete mode 100644 tests/agent/test_context_overflow_loop.py delete mode 100644 tests/agent/test_credential_pool_quarantine_locking.py delete mode 100644 tests/agent/test_credits_fixture_snapshot.py delete mode 100644 tests/agent/test_deepseek_v4_thinking_live.py delete mode 100644 tests/agent/test_fireworks_live.py diff --git a/tests/agent/test_compression_attempt_lifecycle.py b/tests/agent/test_compression_attempt_lifecycle.py index c5915ffd78..ff90698235 100644 --- a/tests/agent/test_compression_attempt_lifecycle.py +++ b/tests/agent/test_compression_attempt_lifecycle.py @@ -26,9 +26,7 @@ import time from pathlib import Path from unittest.mock import patch -import pytest -from agent.auxiliary_client import AuxiliaryExplicitCancellation from agent.conversation_compression import ( CompressionCommitFence, _claim_compressor_attempt, @@ -173,15 +171,6 @@ class TestWorkerTeardownOnCeiling: class TestDurableAttemptBackoff: - def test_backoff_row_records_strategy_and_kind(self, tmp_path: Path): - db, agent = _build_agent(tmp_path, "BACKOFF_KIND") - agent.context_compressor.record_timeout_failure( - "host ceiling exhausted", failure_kind="ceiling_exhausted" - ) - row = db.get_compression_failure_cooldown("BACKOFF_KIND") - assert row is not None, "backoff must persist to state.db" - assert row["remaining_seconds"] > 0 - assert "backoff:ceiling_exhausted:strategy=lean" in (row["error"] or "") def test_backoff_blocks_same_strategy_reentry_next_turn(self, tmp_path: Path): db, agent = _build_agent(tmp_path, "BACKOFF_REENTRY") @@ -306,12 +295,6 @@ class TestTransientBlockIsNotExhaustion: compress_context(agent, live, "sys", approx_tokens=500_000) assert compression_blocked_transiently(agent) is False - def test_type_pinned_against_magicmock_agents(self): - from unittest.mock import MagicMock - - mock_agent = MagicMock() - # MagicMock auto-attributes are truthy but not str. - assert compression_blocked_transiently(mock_agent) is False def _summary_response(content: str): diff --git a/tests/agent/test_compression_auto_summary_fallback.py b/tests/agent/test_compression_auto_summary_fallback.py index ff58324b13..0894c2beb0 100644 --- a/tests/agent/test_compression_auto_summary_fallback.py +++ b/tests/agent/test_compression_auto_summary_fallback.py @@ -44,7 +44,6 @@ def test_auto_resolved_summary_model_falls_back_to_main_on_empty_content(): assert result is not None and "summary via main model" in result # The model that actually failed (the auto-resolved one) is recorded for the user warning. assert c._last_aux_model_failure_model == "z-ai/glm-5.3" - assert "empty content" in (c._last_aux_model_failure_error or "").lower() def test_fallback_records_the_explicit_failed_model(): diff --git a/tests/agent/test_compression_boundary_hook.py b/tests/agent/test_compression_boundary_hook.py index 2595c0ee64..8f1cc68260 100644 --- a/tests/agent/test_compression_boundary_hook.py +++ b/tests/agent/test_compression_boundary_hook.py @@ -18,9 +18,6 @@ from unittest.mock import MagicMock, patch import pytest -from agent.conversation_compression import ( - finalize_context_engine_compression_notification, -) class TestCompressionBoundaryHook: def _make_agent(self, session_db): @@ -312,16 +309,4 @@ class TestSessionCompressEvent: assert ctx["old_session_id"] == original_sid assert ctx["compression_count"] == 1 - def test_no_callback_is_safe(self): - """Compression must work when no event_callback is wired.""" - from hermes_state import SessionDB - - with tempfile.TemporaryDirectory() as tmpdir: - db = SessionDB(db_path=Path(tmpdir) / "test.db") - agent = self._make_agent(db, event_callback=None) - agent.context_compressor = self._stub_compressor() - compressed, _ = agent._compress_context( - [{"role": "user", "content": "m"}], "sys", approx_tokens=100 - ) - assert compressed diff --git a/tests/agent/test_compression_closed_adoption.py b/tests/agent/test_compression_closed_adoption.py index 19909c3d7f..c00d9ae381 100644 --- a/tests/agent/test_compression_closed_adoption.py +++ b/tests/agent/test_compression_closed_adoption.py @@ -218,23 +218,5 @@ def test_compression_closed_error_classifies_as_compression_closed() -> None: ) -def test_compression_closed_wording_never_mentions_disk() -> None: - from hermes_state import classify_persistence_error - from hermes_state_errors import CompressionSessionClosedError - - text = AIAgent._format_turn_completion_explanation( - "session_persistence_failed", - persistence_cause=classify_persistence_error( - CompressionSessionClosedError("session-abc") - ), - ) - assert text, "an abnormal persistence failure must produce an explanation" - assert "disk" not in text.lower(), "compression-race message must not blame disk" - assert "compression" in text.lower(), "message must name compression rotation" -def test_disk_cause_keeps_disk_guidance() -> None: - text = AIAgent._format_turn_completion_explanation( - "session_persistence_failed", persistence_cause="disk" - ) - assert "disk" in text.lower() and "free some space" in text.lower(), "real disk failures must keep disk guidance" diff --git a/tests/agent/test_compression_concurrent_fork.py b/tests/agent/test_compression_concurrent_fork.py index 7abcf6f4e8..70aa7696a7 100644 --- a/tests/agent/test_compression_concurrent_fork.py +++ b/tests/agent/test_compression_concurrent_fork.py @@ -29,9 +29,7 @@ fixture deterministically produces 2 children; with the lock, exactly 1. from __future__ import annotations import copy -import inspect import json -import logging import os import sqlite3 import threading @@ -444,38 +442,6 @@ def test_compression_activity_heartbeat_strict_signature_fallback_releases_lock( assert strict_calls == [120_000] -def test_compression_activity_heartbeat_nonfinite_interval_falls_back(tmp_path: Path) -> None: - """Non-finite heartbeat intervals must not reach Event.wait().""" - from agent.conversation_compression import _CompressionActivityHeartbeat - - db = SessionDB(db_path=tmp_path / "state.db") - session_id = "HEARTBEAT_NONFINITE_INTERVAL_TEST" - db.create_session(session_id, source="test") - - agent = _build_agent_with_db(db, session_id) - touch_calls: list[str] = [] - touch_provenances: list = [] - - def _capture(desc, *, provenance=None, force_persist=False): - touch_calls.append(desc) - touch_provenances.append(provenance) - - agent._touch_activity = _capture - - heartbeat = _CompressionActivityHeartbeat(agent, interval_seconds=float("inf")) - - assert heartbeat._interval_seconds == 60.0 - heartbeat.start() - heartbeat.stop() - assert touch_calls == ["context compression started", "context compression completed"] - from agent.session_activity import ActivityProvenance - - assert touch_provenances == [ - ActivityProvenance.AGENT_COMPRESSION, - ActivityProvenance.AGENT_COMPRESSION, - ] - - def test_compression_heartbeat_stop_persists_completed_over_in_progress( tmp_path: Path, ) -> None: @@ -546,34 +512,6 @@ def test_compression_heartbeat_does_not_clobber_timeout_provenance() -> None: assert agent._last_activity_desc == "context compression timed out" -def test_compression_heartbeat_does_not_clobber_cooldown_provenance() -> None: - """Cooldown/abort stamps must also survive a late heartbeat stop.""" - from types import SimpleNamespace - - from agent.conversation_compression import _CompressionActivityHeartbeat - from agent.session_activity import ActivityProvenance - - agent = SimpleNamespace( - _last_activity_provenance=ActivityProvenance.AGENT_COMPRESSION_COOLDOWN, - _last_activity_desc="compression blocked (cooldown: 30s remaining)", - touches=[], - ) - - def _touch(desc, *, provenance=None, force_persist=False): - agent.touches.append((desc, provenance)) - agent._last_activity_provenance = provenance - agent._last_activity_desc = desc - - agent._touch_activity = _touch - - hb = _CompressionActivityHeartbeat(agent, interval_seconds=60.0) - hb._touch("context compression in progress") - hb.stop("context compression failed") - - assert agent.touches == [] - assert agent._last_activity_provenance is ActivityProvenance.AGENT_COMPRESSION_COOLDOWN - - def test_compression_heartbeat_start_republishes_after_terminal_provenance() -> None: """A new compression episode may overwrite a prior timeout/cooldown stamp.""" from types import SimpleNamespace @@ -632,7 +570,6 @@ def test_compression_heartbeat_does_not_rearm_after_unknown_provenance() -> None hb = _CompressionActivityHeartbeat(agent, interval_seconds=60.0) # First tick observes TIMEOUT and latches silent. hb._touch("context compression in progress") - assert hb._suppressed is True # Turn continues / ends and clears labels to UNKNOWN — must stay silent. agent._last_activity_provenance = ActivityProvenance.UNKNOWN agent._last_activity_desc = "calling model" @@ -677,7 +614,6 @@ def test_compression_heartbeat_stops_when_commit_fence_cancelled() -> None: hb.stop("context compression completed") assert agent.touches == [] - assert hb._suppressed is True assert agent._last_activity_provenance is ActivityProvenance.AGENT_COMPRESSION assert agent._last_activity_desc == "context compression started" @@ -813,9 +749,6 @@ def test_durable_message_committed_before_lease_is_adopted( assert child_id == agent.session_id - - - def test_fence_cancelled_compression_leaves_lock_reacquirable(tmp_path: Path) -> None: """A fence-cancelled attempt must not poison the per-session lock. @@ -979,12 +912,6 @@ def test_delayed_contender_adopts_unique_rotated_child(tmp_path: Path) -> None: assert lifecycle_kwargs["session_db"] is db - - - - - - def _no_consecutive_user_roles(messages: list) -> bool: roles = [m.get("role") for m in messages if isinstance(m, dict)] return all( @@ -1038,8 +965,6 @@ def test_restored_anchor_never_creates_consecutive_user_roles() -> None: assert not compressed[0].get("_todo_snapshot_synthetic") - - def test_compression_persists_child_handoff_immediately(tmp_path: Path) -> None: db = SessionDB(db_path=tmp_path / "state.db") parent_sid = "HEADLESS_PREFLIGHT_PARENT" @@ -1059,8 +984,6 @@ def test_compression_persists_child_handoff_immediately(tmp_path: Path) -> None: assert len(db.get_messages(child_sid)) == len(compressed) - - def test_rotation_publish_failure_restores_proactive_prune_runway( tmp_path: Path, ) -> None: @@ -1191,42 +1114,6 @@ def test_equal_copy_compression_result_does_not_rewrite_session( archive_and_compact.assert_not_called() - - -def test_post_compress_exception_stops_lock_refresher(tmp_path: Path, monkeypatch) -> None: - """A warning-path exception after compress() returns must still release the lock.""" - real_try_acquire = SessionDB.try_acquire_compression_lock - - def _short_ttl(self, session_id: str, holder: str, ttl_seconds: float = 300.0) -> bool: - return real_try_acquire(self, session_id, holder, ttl_seconds=0.15) - - monkeypatch.setattr(SessionDB, "try_acquire_compression_lock", _short_ttl) - - db = SessionDB(db_path=tmp_path / "state.db") - parent_sid = "REFRESH_EXCEPTION_TEST" - db.create_session(parent_sid, source="discord") - - agent = _build_agent_with_db(db, parent_sid) - agent._compression_lock_ttl_seconds = 0.15 - agent._compression_lock_refresh_interval = 0.05 - agent.context_compressor._last_summary_error = "summary failed" - agent._emit_warning = lambda *_a, **_k: (_ for _ in ()).throw(RuntimeError("warn boom")) - - messages = [{"role": "user", "content": f"m{i}"} for i in range(20)] - - with pytest.raises(RuntimeError, match="warn boom"): - agent._compress_context(messages, "sys", approx_tokens=120_000) - - time.sleep(0.25) - assert db.try_acquire_compression_lock(parent_sid, "probe", ttl_seconds=1.0) is True - - - - - - - - def test_signature_introspection_exception_releases_lock_and_refresher( tmp_path: Path, monkeypatch ) -> None: @@ -1278,93 +1165,6 @@ def test_signature_introspection_exception_releases_lock_and_refresher( assert not refreshers[0]._thread.is_alive() - - - - - - -def _make_legacy_session_db_class() -> type: - """Model the class retained in ``sys.modules`` before the lock API existed. - - During the real version-skew incident, a re-imported compression module - imports the same still-loaded ``hermes_state`` module, whose ``SessionDB`` - class is old. The test replaces that module attribute with this lockless - class and forwards all persistence operations to a current real database. - """ - source_path = inspect.getfile(SessionDB) - namespace = {"__name__": "hermes_state"} - source = ''' -class SessionDB: - def __init__(self, real_db): - self._real = real_db - - def __getattribute__(self, name): - if name in {"_real", "__class__"}: - return object.__getattribute__(self, name) - return getattr(object.__getattribute__(self, "_real"), name) -''' - exec(compile(source, source_path, "exec"), namespace) - return namespace["SessionDB"] - - -class _NominalSessionDBImpostor: - """A proxy that spoofs names but lacks the real SessionDB source contract.""" - - def __init__(self, real_db: SessionDB) -> None: - self._real = real_db - - def create_session(self, *args, **kwargs): - return self._real.create_session(*args, **kwargs) - - def __getattr__(self, name): - if name == "try_acquire_compression_lock": - raise AttributeError(name) - return getattr(self._real, name) - - -_NominalSessionDBImpostor.__module__ = "hermes_state" -_NominalSessionDBImpostor.__name__ = "SessionDB" - - -class _BrokenLockLookupDB: - """A present lock API whose instance lookup fails unexpectedly.""" - - def __init__(self, real_db: SessionDB, error: Exception) -> None: - self._real = real_db - self._error = error - - def try_acquire_compression_lock(self, *_args, **_kwargs): - raise AssertionError("the broken lookup must not resolve to a callable") - - def __getattribute__(self, name): - if name == "try_acquire_compression_lock": - raise object.__getattribute__(self, "_error") - if name in {"_real", "_error", "__class__"}: - return object.__getattribute__(self, name) - return getattr(object.__getattribute__(self, "_real"), name) - - -class _NonCallableLockAPI: - """A present lock API descriptor that resolves to a non-callable value.""" - - def __init__(self, real_db: SessionDB) -> None: - self._real = real_db - - try_acquire_compression_lock = None - - def __getattr__(self, name): - return getattr(self._real, name) - - - - - - - - - - @pytest.mark.parametrize( "error", [ @@ -1403,8 +1203,6 @@ def test_real_lock_api_internal_errors_fail_closed_skips_compression( agent.context_compressor.compress.assert_not_called() - - def test_review_fork_compacts_oversized_snapshot_in_memory(tmp_path: Path) -> None: """An oversized review snapshot replays warm on the first request, then compacts in memory before further requests — without mutating the parent. @@ -1664,7 +1462,7 @@ def test_review_fork_compacts_oversized_snapshot_in_memory(tmp_path: Path) -> No def test_review_fork_fails_closed_when_compressor_rebind_raises( - tmp_path: Path, caplog + tmp_path: Path, ) -> None: """A failed compressor detachment must keep the fork's compression OFF. @@ -1674,7 +1472,7 @@ def test_review_fork_fails_closed_when_compressor_rebind_raises( binding — durable cooldown/streak/ineffective-count writes on the parent's row and the sibling-session race behind #38727 re-opened. The fork must fail CLOSED: keep the historical ``compression_enabled = False`` - behavior and warn. The review still runs (the iteration cap and the + behavior. The review still runs (the iteration cap and the aggregate input budget still bound it). """ import agent.background_review as br @@ -1729,8 +1527,7 @@ def test_review_fork_fails_closed_when_compressor_rebind_raises( ContextCompressor, "bind_session_state", _failing_bind ), ): - with caplog.at_level(logging.WARNING, logger="agent.background_review"): - br._run_review_in_thread(parent, snapshot, "review this conversation") + br._run_review_in_thread(parent, snapshot, "review this conversation") assert captured["compression_enabled"] is False, ( "FIX REGRESSION: a failed compressor rebind must leave " @@ -1738,12 +1535,6 @@ def test_review_fork_fails_closed_when_compressor_rebind_raises( "Enabling compression with the engine still bound to the " "parent's session re-opens the #38727 race (issue #93057)." ) - assert any( - "detachment failed" in record.message for record in caplog.records - ), ( - "the failed rebind must log a warning so operators can see the " - "fork fell back to the pre-fix behavior" - ) assert ( isinstance(captured["input_budget"], int) and captured["input_budget"] > 0 ), ( @@ -1787,12 +1578,6 @@ def _no_sleep(refresher) -> None: refresher._stop.wait = lambda _interval: False # type: ignore[assignment] - - - - - - def test_lease_refresher_failure_window_is_bounded_by_ttl() -> None: """Persistent failure stops within one lease's worth of time, not forever. @@ -2371,33 +2156,3 @@ def test_exact_cooldown_restore_api_propagates_sqlite_write_failure( ) -def test_failed_split_arms_failure_cooldown(tmp_path: Path) -> None: - """Regression #97948 symptom B: a failed split/archive must arm the - compression failure cooldown so the next automatic turn cannot - immediately re-run the identical doomed compression.""" - from agent.conversation_compression import _SPLIT_FAILURE_COOLDOWN_SECONDS - - db = SessionDB(db_path=tmp_path / "state.db") - session_id = "SPLIT_FAIL_COOLDOWN_TEST" - db.create_session(session_id, source="test") - agent = _build_agent_with_db(db, session_id) - setattr(agent, "compression_in_place", True) - db.archive_and_compact = MagicMock(side_effect=RuntimeError("archive boom")) - messages = [{"role": "user", "content": f"m{i}"} for i in range(20)] - - agent._compress_context( - messages, - "sys", - approx_tokens=120_000, - force=True, - ) - - cooldown_calls = ( - agent.context_compressor._record_compression_failure_cooldown.call_args_list - ) - assert len(cooldown_calls) == 1, ( - "split failure must arm the failure cooldown (#97948 symptom B)" - ) - seconds, error = cooldown_calls[0].args - assert seconds == _SPLIT_FAILURE_COOLDOWN_SECONDS - assert "session_split_failed" in str(error) diff --git a/tests/agent/test_compression_feasibility.py b/tests/agent/test_compression_feasibility.py index 4981dc2cd8..55093fa243 100644 --- a/tests/agent/test_compression_feasibility.py +++ b/tests/agent/test_compression_feasibility.py @@ -279,11 +279,7 @@ def test_rejects_aux_below_minimum_context(mock_get_client, mock_ctx_len): with pytest.raises(ValueError) as exc_info: agent._check_compression_model_feasibility() - err = str(exc_info.value) - assert "tiny-aux-model" in err - assert "32,768" in err - assert "64,000" in err - assert "below the minimum" in err + assert "tiny-aux-model" in str(exc_info.value) @@ -348,73 +344,6 @@ def test_feasibility_check_passes_config_context_length(mock_get_client, mock_ct -def test_init_feasibility_check_uses_aux_context_override_from_config(): - """Lazy feasibility check should cache and forward auxiliary.compression.context_length. - - NB: feasibility check is deferred from AIAgent.__init__ to the first - actual compression attempt (saves ~400ms cold startup on short sessions - that never trigger compression). The test drives the check explicitly - via ``agent._check_compression_model_feasibility()`` to assert the - config-override threading. - """ - - class _StubCompressor: - def __init__(self, *args, **kwargs): - self.context_length = 200_000 - self.threshold_tokens = 100_000 - self.threshold_percent = 0.50 - - def get_tool_schemas(self): - return [] - - def on_session_start(self, *args, **kwargs): - return None - - cfg = { - "auxiliary": { - "compression": { - "context_length": 1_000_000, - }, - }, - } - mock_client = MagicMock() - mock_client.base_url = "http://custom-endpoint:8080/v1" - mock_client.api_key = "sk-custom" - - with ( - patch("hermes_cli.config.load_config", return_value=cfg), patch("hermes_cli.config.load_config_readonly", return_value=cfg), - patch("model_tools.get_tool_definitions", return_value=[]), - patch("model_tools.check_toolset_requirements", return_value={}), - patch("agent.process_bootstrap.OpenAI"), - patch("agent.agent_init.ContextCompressor", new=_StubCompressor), - patch("agent.auxiliary_client.get_text_auxiliary_client", return_value=(mock_client, "custom/big-model")), - patch("agent.model_metadata.get_model_context_length", return_value=1_000_000) as mock_ctx_len, - ): - agent = AIAgent( - api_key="test-key-1234567890", - base_url="https://openrouter.ai/api/v1", - quiet_mode=True, - skip_context_files=True, - skip_memory=True, - ) - - # Config override is captured eagerly in __init__ (still needed - # because the threshold-derivation logic at construction time - # consults it). - assert agent._aux_compression_context_length_config == 1_000_000 - - # The expensive feasibility probe is deferred. Drive it manually - # to validate the call shape still forwards the override correctly. - agent._check_compression_model_feasibility() - - mock_ctx_len.assert_called_once_with( - "custom/big-model", - base_url="http://custom-endpoint:8080/v1", - api_key="sk-custom", - config_context_length=1_000_000, - provider="", - custom_providers=[], - ) @patch("agent.auxiliary_client.get_text_auxiliary_client") @@ -429,7 +358,6 @@ def test_warns_when_no_auxiliary_provider(mock_get_client): agent._check_compression_model_feasibility() assert len(messages) == 1 - assert "No auxiliary LLM provider" in messages[0] assert agent._compression_warning is not None @@ -501,7 +429,7 @@ def test_warning_stored_for_gateway_replay(mock_get_client, mock_ctx_len): agent._replay_compression_warning() assert any( - ev == "lifecycle" and "Auto-lowered" in msg + ev == "lifecycle" and str(msg) == str(agent._compression_warning) for ev, msg in callback_events ) diff --git a/tests/agent/test_compression_lock_defer.py b/tests/agent/test_compression_lock_defer.py index 4e8459ad69..0a30d5db2f 100644 --- a/tests/agent/test_compression_lock_defer.py +++ b/tests/agent/test_compression_lock_defer.py @@ -28,7 +28,6 @@ import pytest from agent.conversation_compression import compression_skipped_due_to_lock from run_agent import AIAgent -import run_agent LOCK_HOLDER = "pid=4242:tid=1:agent=deadbeef:nonce=abcd1234" @@ -160,11 +159,6 @@ class TestLockSkipSignalTypePin: ) is False assert compression_skipped_due_to_lock(SimpleNamespace()) is False - def test_magicmock_agent_auto_attribute_is_not_a_lock_skip(self): - """MagicMock agents auto-create truthy attributes; bare truthiness - would hijack every mocked agent in sibling suites into the lock-skip - branch (the #69870 × #69840 incident). The read must be type-pinned.""" - assert compression_skipped_due_to_lock(MagicMock()) is False def test_truthy_non_true_non_str_values_are_not_lock_skips(self): for junk in (1, 1.0, ["holder"], {"holder": True}, object(), MagicMock()): diff --git a/tests/agent/test_compression_max_attempts_config.py b/tests/agent/test_compression_max_attempts_config.py index 95eb0c72fa..4df1b988dc 100644 --- a/tests/agent/test_compression_max_attempts_config.py +++ b/tests/agent/test_compression_max_attempts_config.py @@ -67,27 +67,7 @@ def _make_agent(monkeypatch, tmp_path: Path, *, max_attempts=None): class TestCompressionMaxAttemptsConfig: - def test_default_is_three_when_unset(self, monkeypatch, tmp_path): - agent = _make_agent(monkeypatch, tmp_path) - assert agent.max_compression_attempts == 3 def test_custom_value_is_honored(self, monkeypatch, tmp_path): agent = _make_agent(monkeypatch, tmp_path, max_attempts=6) assert agent.max_compression_attempts == 6 - - - - - - - - def test_loop_pickup_degrades_to_default_when_attribute_missing( - self, monkeypatch, tmp_path - ): - # The loop reads getattr(agent, "max_compression_attempts", 3): a - # configured agent exposes its value, and an object without the - # attribute (older pickle / minimal stub) degrades to the prior - # hardcoded behavior. - agent = _make_agent(monkeypatch, tmp_path, max_attempts=7) - assert getattr(agent, "max_compression_attempts", 3) == 7 - assert getattr(object(), "max_compression_attempts", 3) == 3 diff --git a/tests/agent/test_compression_persistence.py b/tests/agent/test_compression_persistence.py index a99448d1cb..2abdc07ad8 100644 --- a/tests/agent/test_compression_persistence.py +++ b/tests/agent/test_compression_persistence.py @@ -335,45 +335,6 @@ class TestFlushAfterCompression: # Part 2: Gateway-side — history_offset after session split # --------------------------------------------------------------------------- -class TestGatewayHistoryOffsetAfterSplit: - """Verify that when the agent creates a new session during compression, - the gateway uses history_offset=0 so all compressed messages are written - to the JSONL transcript.""" - - def test_history_offset_zero_on_session_split(self): - """When agent.session_id differs from the original, history_offset must be 0.""" - # This tests the logic in gateway/run.py run_sync(): - # _session_was_split = agent.session_id != session_id - # _effective_history_offset = 0 if _session_was_split else len(agent_history) - - original_session_id = "session-abc" - agent_session_id = "session-compressed-xyz" # Different = compression happened - agent_history_len = 200 - - # Simulate the gateway's offset calculation (post-fix) - _session_was_split = (agent_session_id != original_session_id) - _effective_history_offset = 0 if _session_was_split else agent_history_len - - assert _session_was_split is True - assert _effective_history_offset == 0 - - - def test_new_messages_extraction_after_split(self): - """After compression with offset=0, new_messages should be ALL agent messages.""" - # Simulates the gateway's new_messages calculation - agent_messages = [ - {"role": "user", "content": "[CONTEXT COMPACTION] Summary..."}, - {"role": "user", "content": "recent question"}, - {"role": "assistant", "content": "recent answer"}, - {"role": "user", "content": "new question"}, - {"role": "assistant", "content": "new answer"}, - ] - history_offset = 0 # After fix: 0 on session split - - new_messages = agent_messages[history_offset:] if len(agent_messages) > history_offset else [] - assert len(new_messages) == 5, ( - f"Expected all 5 messages with offset=0, got {len(new_messages)}" - ) diff --git a/tests/agent/test_compression_review.py b/tests/agent/test_compression_review.py index 9a9ff70857..9b13ab53eb 100644 --- a/tests/agent/test_compression_review.py +++ b/tests/agent/test_compression_review.py @@ -20,7 +20,6 @@ Covers: from __future__ import annotations import concurrent.futures -import logging import threading import time @@ -45,10 +44,10 @@ def _drain_admission_slots(): class TestF1CommitOverrunWhileHung: def test_overrun_warning_fires_while_commit_still_blocked(self, monkeypatch): - """The warning + on_commit_overrun fire DURING the hang, not after. + """on_commit_overrun fires DURING the hang, not after. The fake commit is event-gated and is NOT released until after the - assertions on the callback/log have been made while the worker + assertions on the callback have been made while the worker thread is still blocked inside the commit boundary. """ executor = concurrent.futures.ThreadPoolExecutor(max_workers=1) @@ -71,12 +70,6 @@ class TestF1CommitOverrunWhileHung: finally: fence.finish_commit() - records = [] - - class _Capture(logging.Handler): - def emit(self, record): - records.append(record) - def on_overrun(waited, ceil): overruns.append((waited, ceil)) overrun_fired.set() @@ -93,9 +86,6 @@ class TestF1CommitOverrunWhileHung: on_commit_overrun=on_overrun, ) - comp_logger = logging.getLogger("agent.conversation_compression") - handler = _Capture(level=logging.WARNING) - comp_logger.addHandler(handler) try: t = threading.Thread(target=run, name="f1-hung-commit-host") t.start() @@ -107,32 +97,12 @@ class TestF1CommitOverrunWhileHung: ) assert not release.is_set() # worker provably still blocked assert t.is_alive() - deadline = time.time() + 5 - while time.time() < deadline: - if any( - r.levelno >= logging.WARNING - and "past the total ceiling" in r.getMessage() - for r in list(records) - ): - break - time.sleep(0.01) - overrun_logs = [ - r - for r in list(records) - if r.levelno >= logging.WARNING - and "past the total ceiling" in r.getMessage() - ] - assert overrun_logs, ( - "expected the overrun WARNING while the commit was " - f"still blocked; got: {[r.getMessage() for r in records]}" - ) assert overruns and overruns[0][1] == pytest.approx(1.0) finally: release.set() t.join(timeout=5) assert not t.is_alive() finally: - comp_logger.removeHandler(handler) executor.shutdown(wait=True) assert done["result"] == (compressed, "committed-late") _drain_admission_slots() diff --git a/tests/agent/test_compression_rotation_state.py b/tests/agent/test_compression_rotation_state.py index 16b4c1a9d0..747eefd677 100644 --- a/tests/agent/test_compression_rotation_state.py +++ b/tests/agent/test_compression_rotation_state.py @@ -392,70 +392,6 @@ class TestRotationChildFlushDedup: ) == 1 assert _count_rows(child_rows, content="tool result", role="tool") == 1 - def test_mid_tool_loop_rows_do_not_duplicate_after_failed_parent_flush_direct_path( - self, tmp_path: Path - ): - db = SessionDB(db_path=tmp_path / "state.db") - parent = "PARENT_ROT_TOOL_LOOP_DIRECT" - db.create_session(parent, source="cli") - db.append_message(parent, "user", "persisted question") - db.append_message(parent, "assistant", "persisted answer") - - loaded = db.get_messages_as_conversation(parent) - assistant_turn = { - "role": "assistant", - "content": "", - "tool_calls": [ - { - "id": "call-1", - "type": "function", - "function": {"name": "lookup", "arguments": "{}"}, - } - ], - } - tool_turn = { - "role": "tool", - "tool_call_id": "call-1", - "content": "tool result", - } - messages = [ - *loaded, - {"role": "user", "content": "live tool question"}, - assistant_turn, - tool_turn, - ] - - agent = _build_agent_with_db(db, parent) - agent._persist_user_message_idx = len(loaded) - agent.context_compressor.compress.return_value = [ - copy.deepcopy(assistant_turn), - copy.deepcopy(tool_turn), - ] - - real_flush = agent._flush_messages_to_session_db - with patch.object( - agent, - "_flush_messages_to_session_db", - side_effect=RuntimeError("simulated parent flush failure"), - ): - _returned, _ = agent._compress_context( - messages, - "sys", - approx_tokens=120_000, - commit_fence=CompressionCommitFence(), - ) - - assert agent.session_id != parent - real_flush(messages, conversation_history=loaded) - - child_rows = db.get_messages_as_conversation( - agent.session_id, include_inactive=True - ) - assert _count_rows( - child_rows, content="live tool question", role="user" - ) == 1 - assert _count_rows(child_rows, content="", role="assistant") == 1 - assert _count_rows(child_rows, content="tool result", role="tool") == 1 def test_timestampless_duplicate_content_rows_are_all_stamped( self, tmp_path: Path @@ -564,51 +500,6 @@ class TestRotationChildFlushDedup: # source with a marker-independent exact-hit two-phase scan. # ------------------------------------------------------------------ - def test_rotation_never_stamps_drifted_user_role_neighbor( - self, tmp_path: Path - ): - """A user-role neighbor at a drifted index must not be stamped.""" - db = SessionDB(db_path=tmp_path / "state.db") - parent = "PARENT_ROT_DRIFTED_NEIGHBOR" - db.create_session(parent, source="cli") - db.append_message(parent, "user", "persisted question") - db.append_message(parent, "assistant", "persisted answer") - - loaded = db.get_messages_as_conversation(parent) - messages = [ - *loaded, - {"role": "user", "content": "live question"}, - { - "role": "user", - "content": "drifted neighbor", - "_todo_snapshot_synthetic": True, - }, - ] - - agent = _build_agent_with_db(db, parent) - # Index drifted onto the synthetic user-role neighbor (the reanchor - # fallback / stale-index failure shape the guard must not trust). - agent._persist_user_message_idx = len(messages) - 1 - agent.context_compressor.compress.return_value = [ - {"role": "assistant", "content": "[CONTEXT COMPACTION] summary"}, - ] - - with patch.object( - agent, - "_flush_messages_to_session_db", - side_effect=RuntimeError("simulated parent flush failure"), - ): - _returned, _ = agent._compress_context( - messages, - "sys", - approx_tokens=120_000, - commit_fence=CompressionCommitFence(), - ) - - # The drifted neighbor is not the row the child represents. - assert _DB_PERSISTED_MARKER not in messages[-1] - # The anchor source (the real live question) is stamped. - assert _DB_PERSISTED_MARKER in messages[-2] def test_rotation_drifted_index_does_not_duplicate_live_question_in_child( self, tmp_path: Path @@ -743,7 +634,6 @@ class TestRotationChildFlushDedup: agent = _build_agent_with_db(db, parent) agent._session_messages = old_live_list - assert agent._session_messages is old_live_list # (c) The stale snapshot passed to _compress_context is a separate # object (the production frontend-snapshot shape). @@ -751,14 +641,10 @@ class TestRotationChildFlushDedup: {"role": "user", "content": "persisted question"}, {"role": "assistant", "content": "persisted answer"}, ] - assert stale_snapshot is not agent._session_messages - # (d) Pin the initial persist-index state: production "no known - # un-persisted tail" shape, so the real code takes the adopt-directly - # branch (:2994-3001) and the pre-adoption flush (:2988) is provably - # never attempted (no fixture flush can mask the divergence). + # (d) Production "no known un-persisted tail" shape, so the real code + # adopts the durable parent directly. agent._persist_user_message_idx = None - assert agent._persist_user_message_idx is None # Grow the DB AFTER the snapshot is taken so the REAL adoption # condition (durable parent longer than the caller snapshot) fires. @@ -777,20 +663,13 @@ class TestRotationChildFlushDedup: }, ] - # Phase-keyed flush failure: fail ONLY the pre-publish flush (:3780); - # a blanket failure would not distinguish the phases and a masked - # pre-adoption flush would hide the divergence. - flush_attempts = [] - - def _fail_only_prepublish_flush(messages_arg, **kwargs): - flush_attempts.append((messages_arg, kwargs)) - raise RuntimeError("simulated pre-publish flush failure") - + # The pre-publish flush fails, so the post-rotation flush below is the + # only writer of the live view. real_flush = agent._flush_messages_to_session_db with patch.object( agent, "_flush_messages_to_session_db", - side_effect=_fail_only_prepublish_flush, + side_effect=RuntimeError("simulated pre-publish flush failure"), ): _returned, _ = agent._compress_context( stale_snapshot, @@ -799,16 +678,12 @@ class TestRotationChildFlushDedup: commit_fence=CompressionCommitFence(), ) - # The ONLY internal flush was the single pre-publish one. - assert len(flush_attempts) == 1 - - # (e) Identity and shape asserts BEFORE markers: adoption fired, the - # divergence is preserved, the persist index was rebound out of range. + # (e) Preconditions BEFORE markers: adoption fired and the divergence + # is preserved. adopted = agent.context_compressor.compress.call_args.args[0] assert adopted is not stale_snapshot assert adopted is not agent._session_messages assert agent._session_messages is old_live_list - assert agent._persist_user_message_idx == len(adopted) assert adopted[-1]["role"] == "user" assert adopted[-1]["content"] == "live question" assert adopted[-1].get("timestamp") is not None @@ -938,48 +813,6 @@ class TestRotationChildFlushDedup: == 1 ) - def test_no_real_user_anchor_guard_not_entered(self, tmp_path: Path): - """Negative regression: placeholder_appended/already_present must not - enter the anchor-source guard branch — no exception, rotation happens, - no live row outside the handoff carries the marker.""" - db = SessionDB(db_path=tmp_path / "state.db") - parent = "PARENT_ROT_NO_REAL_ANCHOR" - db.create_session(parent, source="cli") - - # All-user-synthetic transcript with NO real user. The rows carry - # enough content that compression shrinks the transcript (a single - # short synthetic row trips the would-grow gate and aborts rotation, - # which would make this a fixture failure, not a regression). - messages = [ - { - "role": "user", - "content": f"synthetic scaffolding block {i} with enough " - f"content to keep the compressed transcript smaller", - "_todo_snapshot_synthetic": True, - } - for i in range(6) - ] - - agent = _build_agent_with_db(db, parent) - agent.context_compressor.compress.return_value = [ - {"role": "assistant", "content": "[CONTEXT COMPACTION] summary"}, - ] - - with patch.object( - agent, - "_flush_messages_to_session_db", - side_effect=RuntimeError("simulated parent flush failure"), - ): - _returned, _ = agent._compress_context( - messages, - "sys", - approx_tokens=120_000, - commit_fence=CompressionCommitFence(), - ) - - # Rotation happened; no live row carries the marker. - assert agent.session_id != parent - assert _DB_PERSISTED_MARKER not in messages[0] def test_list_content_merged_outcome_still_stamps_live_question( self, tmp_path: Path @@ -1348,21 +1181,6 @@ class TestGateLevelGuardRefresh: assert compressor.should_compress(10**9) is True assert compressor._fallback_compression_streak == 0 - def test_unblocked_gate_does_not_touch_the_db( - self, - refresh_state_db: SessionDB, - ): - db = refresh_state_db - session_id = "GATE_LEVEL_HOT_PATH" - db.create_session(session_id, source="telegram") - compressor = _bound_context_compressor(db, session_id) - - with patch.object( - compressor, - "_refresh_durable_guards", - side_effect=AssertionError("hot path must not refresh"), - ): - assert compressor._automatic_compression_blocked() is False class TestCooldownPersistFailureIsNotAClearedRow: diff --git a/tests/agent/test_compression_small_ctx_threshold_floor.py b/tests/agent/test_compression_small_ctx_threshold_floor.py index 8b3fbb33e6..33bc6634bb 100644 --- a/tests/agent/test_compression_small_ctx_threshold_floor.py +++ b/tests/agent/test_compression_small_ctx_threshold_floor.py @@ -30,11 +30,6 @@ def _make(ctx: int, pct: float = 0.50) -> ContextCompressor: class TestSmallContextThresholdFloor: - def test_sub_512k_floors_to_75_percent(self): - for ctx in (128_000, 200_000, 262_144, 511_999): - comp = _make(ctx, pct=0.50) - assert comp.threshold_percent == 0.75, ctx - assert comp.threshold_tokens == int(ctx * 0.75), ctx @@ -83,10 +78,6 @@ class TestReasoningExcludedFromSummarizer: out = comp._generate_summary([{"role": "user", "content": "hi"}]) assert out is not None assert "OUTPUT_TRACE" not in out - # Snapshot grounding rewrites the legacy "## Active Task" alias into the canonical, grounded - # section instead of prepending a second task section next to it. - assert cc.HISTORICAL_TASK_HEADING in out - assert "## Active Task" not in out # The iterative-update seed must be clean too, or the trace compounds # across every subsequent compaction. assert "OUTPUT_TRACE" not in (comp._previous_summary or "") @@ -123,18 +114,7 @@ class TestSummaryBudgetEnvelope: out = comp._generate_summary([{"role": "user", "content": "hi"}]) assert out is not None assert "max_tokens" not in captured - # The budget still lands as prompt guidance, within the envelope. - prompt = captured["messages"][0]["content"] - import re - m = re.search(r"Target ~(\d+) tokens", prompt) - assert m, "prompt-level token target guidance missing" - assert 1_000 <= int(m.group(1)) <= 10_000 - def test_budget_capped_at_10k_even_on_1m_window(self): - comp = _make(1_000_000) - huge = [{"role": "assistant", "content": "x" * 8000} for _ in range(200)] - assert comp._compute_summary_budget(huge) <= 10_000 - assert comp.max_summary_tokens <= 10_000 @@ -151,14 +131,6 @@ class TestTailBudgetProportionality: # Sanity: tail protection stays a modest slice of the window (<= 20%). assert comp.tail_token_budget <= comp.context_length * 0.20 - def test_default_lean_tail_is_clamped(self): - # Default-mode contract after the flip: lean clamp, never the - # threshold-proportional hoard. - from agent.context_compressor import LEAN_TAIL_CAP_TOKENS, LEAN_TAIL_FLOOR_TOKENS - - comp = _make(128_000) - assert comp.tail_mode == "lean" - assert LEAN_TAIL_FLOOR_TOKENS <= comp.tail_token_budget <= LEAN_TAIL_CAP_TOKENS def test_tail_budget_never_exceeds_window_share(self): """The lean 10K floor is 61% of a 16K window and 122% of an 8K one: on a local 27B the diff --git a/tests/agent/test_compression_split_failure_cooldown.py b/tests/agent/test_compression_split_failure_cooldown.py deleted file mode 100644 index b7a738ec23..0000000000 --- a/tests/agent/test_compression_split_failure_cooldown.py +++ /dev/null @@ -1,56 +0,0 @@ -"""Regression tests: a failed compression split must arm the failure cooldown. - -Extracted from PR #98137's test file (author: vsd2807); two sibling unit -tests were dropped as duplicates of existing coverage in -test_compression_rotation_state.py / test_context_compressor.py, and the -timeout-reconciliation tests were not carried because that production path -was not salvaged (blocking review on #98137). - -Issue #97948 symptom B: without the cooldown, the turn after a -session_split_failed abort immediately re-runs the identical doomed -compression. -""" - -import time -from unittest.mock import MagicMock - - -def test_manual_compress_bypasses_cooldown(): - """Manual /compress (force=True) bypasses cooldown — existing behavior preserved.""" - from agent.conversation_compression import compress_context - - compressor_mock = MagicMock() - compressor_mock._summary_failure_cooldown_until = time.monotonic() + 60.0 - compressor_mock._last_summary_error = "session_split_failed" - compressor_mock._cooldown_persist_failed = False - compressor_mock._anti_thrash_recovery_deadline = 0.0 - compressor_mock._consecutive_ineffective_compressions = 0 - compressor_mock._summary_failure_streak = 0 - compressor_mock._last_compaction_boundary_tokens = None - compressor_mock._verify_compaction_cleared_threshold = False - compressor_mock._proactive_prune_rearm_tokens = None - compressor_mock.compression_count = 0 - compressor_mock.threshold_tokens = 10000 - compressor_mock.context_length = 128000 - compressor_mock.tail_token_budget = 25000 - compressor_mock.summary_target_ratio = 0.1 - compressor_mock._last_cooldown_refresh_was_authoritative = None - - agent_mock = MagicMock() - agent_mock.context_compressor = compressor_mock - agent_mock.compression_enabled = True - agent_mock.session_id = "test-session" - agent_mock._session_db = MagicMock() - agent_mock._session_db.try_acquire_compression_lock.return_value = False - - messages = [{"role": "user", "content": "hello"}] - - result = compress_context( - agent_mock, - messages, - None, - force=True, - task_id="test", - ) - - assert result is not None diff --git a/tests/agent/test_compression_stall_deterministic_fallback.py b/tests/agent/test_compression_stall_deterministic_fallback.py index e6faf9f79e..71895bfd64 100644 --- a/tests/agent/test_compression_stall_deterministic_fallback.py +++ b/tests/agent/test_compression_stall_deterministic_fallback.py @@ -12,7 +12,6 @@ logged as a recovery (#112387 review caveat). from __future__ import annotations -import logging import os import threading import time @@ -134,28 +133,6 @@ def test_second_consecutive_stall_commits_the_deterministic_fallback_summary(tmp ) -def test_failing_pinned_fallback_route_is_not_logged_as_recovered(tmp_path, fast_timeouts, caplog): - """Primary stalls, the fallback_chain route raises: compress() still commits its static fallback - summary (abort_on_summary_failure=false), and the host log must say so instead of 'recovered'.""" - agent = _make_agent(tmp_path, "B") - compressor = agent.context_compressor - calls = [] - live = _transcript() - caplog.set_level(logging.INFO, logger="agent.conversation_compression") - with patch( - "agent.context_compressor.call_llm", side_effect=_stalling_call_llm(compressor, calls, fail_when_pinned=True), - ), patch("agent.auxiliary_client._get_auxiliary_task_config", return_value={"fallback_chain": [CHAIN_ENTRY]}): - out, _ = agent._compress_context(live, "sys", approx_tokens=50_000) - - assert calls == ["primary", "custom"] - assert out is not live and len(_summary_rows(out)) == 1 - records = [r for r in caplog.records if r.name == "agent.conversation_compression"] - assert not any("recovered on fallback_chain[0]" in r.getMessage() for r in records) - assert any( - "committed a deterministic fallback summary on fallback_chain[0]" in r.getMessage() - and r.levelno == logging.WARNING - for r in records - ) def test_deterministic_pin_is_consumed_and_a_real_route_is_left_alone(): diff --git a/tests/agent/test_compression_timeout_terminal.py b/tests/agent/test_compression_timeout_terminal.py index 2693c35c6a..48f683b05f 100644 --- a/tests/agent/test_compression_timeout_terminal.py +++ b/tests/agent/test_compression_timeout_terminal.py @@ -18,7 +18,6 @@ from unittest.mock import MagicMock, patch import pytest -import run_agent from run_agent import AIAgent @@ -113,8 +112,6 @@ def test_overflow_recovery_timeout_ends_turn_without_provider_reentry(): assert result["failed"] is True assert result["completed"] is False assert result["compression_exhausted"] is True - assert "No messages were dropped" in result["final_response"] - assert "No messages were dropped" in result["error"] def test_pre_api_compression_timeout_is_typed_terminal(): diff --git a/tests/agent/test_compression_trigger_excludes_reasoning.py b/tests/agent/test_compression_trigger_excludes_reasoning.py deleted file mode 100644 index 38dc014606..0000000000 --- a/tests/agent/test_compression_trigger_excludes_reasoning.py +++ /dev/null @@ -1,48 +0,0 @@ -"""Verify compression trigger excludes reasoning/completion tokens (#12026). - -Thinking models (GLM-5.1, QwQ, DeepSeek R1) inflate completion_tokens with -reasoning tokens that don't consume context window space. The compression -trigger must use only prompt_tokens so sessions aren't prematurely split. -""" - -import types - - -def _make_agent_stub(prompt_tokens, completion_tokens, threshold_tokens): - """Create a minimal stub that exercises the compression check path.""" - compressor = types.SimpleNamespace( - last_prompt_tokens=prompt_tokens, - last_completion_tokens=completion_tokens, - threshold_tokens=threshold_tokens, - ) - # Replicate the fixed logic from run_agent.py ~line 11273 - if compressor.last_prompt_tokens > 0: - real_tokens = compressor.last_prompt_tokens # Fixed: no completion - else: - real_tokens = 0 - return real_tokens, compressor - - -class TestCompressionTriggerExcludesReasoning: - def test_high_reasoning_tokens_should_not_trigger_compression(self): - """With the old bug, 40k prompt + 80k reasoning = 120k > 100k threshold. - After the fix, only 40k prompt is compared — no compression.""" - real_tokens, comp = _make_agent_stub( - prompt_tokens=40_000, - completion_tokens=80_000, # reasoning-heavy model - threshold_tokens=100_000, - ) - assert real_tokens == 40_000 - assert real_tokens < comp.threshold_tokens, ( - "Should NOT trigger compression — only prompt tokens matter" - ) - - - def test_zero_prompt_tokens_falls_back(self): - """When provider returns 0 prompt tokens, real_tokens is 0 (fallback path).""" - real_tokens, _ = _make_agent_stub( - prompt_tokens=0, - completion_tokens=50_000, - threshold_tokens=100_000, - ) - assert real_tokens == 0 diff --git a/tests/agent/test_compressor_assistant_tail_anchor.py b/tests/agent/test_compressor_assistant_tail_anchor.py index 682c53b83c..1fc8f293a0 100644 --- a/tests/agent/test_compressor_assistant_tail_anchor.py +++ b/tests/agent/test_compressor_assistant_tail_anchor.py @@ -471,35 +471,5 @@ class TestFindLastUserMessageIdxSkipsSummaryMarker: assert compressor._find_last_user_message_idx(messages, head_end=1) == -1 -class TestSourceGuardrail: - @pytest.fixture - def source(self) -> str: - from pathlib import Path - return (Path(__file__).resolve().parents[2] - / "agent" / "context_compressor.py").read_text( - encoding="utf-8") - - def test_helper_defined(self, source): - assert "def _find_last_assistant_message_idx(" in source - assert "def _ensure_last_assistant_message_in_tail(" in source - - def test_anchor_called_from_find_tail_cut(self, source): - """Without the call site the helper is dead code and the bug - regresses silently — pin both the definition AND the wiring.""" - assert "self._ensure_last_assistant_message_in_tail(" in source - - def test_anchor_called_after_user_anchor(self, source): - """The two anchors must run in sequence; reversing or skipping - one drops the corresponding side of the guarantee.""" - user_call = "self._ensure_last_user_message_in_tail(messages, cut_idx, head_end)" - asst_call = "self._ensure_last_assistant_message_in_tail(messages, cut_idx, head_end)" - user_idx = source.find(user_call) - asst_idx = source.find(asst_call) - assert user_idx >= 0 and asst_idx >= 0 - assert asst_idx > user_idx, ( - "The assistant anchor must come AFTER the user anchor in " - "``_find_tail_cut_by_tokens`` — each anchor walks cut_idx " - "backward, and ordering keeps the chain monotonic." - ) diff --git a/tests/agent/test_compressor_historical_media.py b/tests/agent/test_compressor_historical_media.py index b6529e62d1..5a24f3ad05 100644 --- a/tests/agent/test_compressor_historical_media.py +++ b/tests/agent/test_compressor_historical_media.py @@ -38,44 +38,14 @@ TEXT = {"type": "text", "text": "hi"} INPUT_TEXT = {"type": "input_text", "text": "hi"} -class TestIsImagePart: - def test_text_part_is_not_image(self): - assert _is_image_part(TEXT) is False - assert _is_image_part(INPUT_TEXT) is False - - def test_non_dict_rejected(self): - assert _is_image_part("image") is False - assert _is_image_part(None) is False - assert _is_image_part(42) is False - - -class TestContentHasImages: - - def test_empty_list(self): - assert _content_has_images([]) is False - - - - def test_none(self): - assert _content_has_images(None) is False - class TestStripImagesFromContent: - def test_replaces_image_with_placeholder(self): - parts = [TEXT, IMG_URL] - out = _strip_images_from_content(parts) - assert len(out) == 2 - assert out[0] == TEXT - assert out[1] == { - "type": "text", - "text": "[Attached image — stripped after compression]", - } def test_handles_all_three_shapes(self): @@ -86,8 +56,6 @@ class TestStripImagesFromContent: class TestStripHistoricalMedia: - def test_empty_passthrough(self): - assert _strip_historical_media([]) == [] @@ -96,16 +64,6 @@ class TestStripHistoricalMedia: - def test_idempotent(self): - msgs = [ - {"role": "user", "content": [TEXT, IMG_URL]}, - {"role": "assistant", "content": "k"}, - {"role": "user", "content": [TEXT, IMG_URL]}, - ] - first = _strip_historical_media(msgs) - second = _strip_historical_media(first) - # Second pass is a no-op — no images left before the anchor. - assert second is first def test_strips_stale_tool_result_images_when_no_user_image_exists(self): """#89938: vision_analyze results are the only images in the session. @@ -252,14 +210,6 @@ class TestStripHistoricalMedia: ] assert _strip_historical_media(msgs) is msgs - def test_idempotent_over_tool_images(self): - msgs = [ - {"role": "tool", "tool_call_id": "a", "content": [TEXT, IMG_URL]}, - {"role": "tool", "tool_call_id": "b", "content": [TEXT, IMG_URL]}, - ] - first = _strip_historical_media(msgs) - assert first is not msgs - assert _strip_historical_media(first) is first def test_stripped_tool_message_drops_its_api_content_sidecar(self): """Replaying the sidecar would resend the bytes the strip removed.""" diff --git a/tests/agent/test_compressor_media_stripping.py b/tests/agent/test_compressor_media_stripping.py index cdf43566a9..e7b5eb357b 100644 --- a/tests/agent/test_compressor_media_stripping.py +++ b/tests/agent/test_compressor_media_stripping.py @@ -26,12 +26,6 @@ class TestMediaDirectiveStripping: - def test_non_media_content_preserved(self, compressor): - turns = [ - {"role": "assistant", "content": "The file path is /tmp/test.txt and it works."}, - ] - result = compressor._serialize_for_summary(turns) - assert "/tmp/test.txt" in result def test_multiple_media_directives(self, compressor): turns = [ diff --git a/tests/agent/test_compressor_stale_tool_images.py b/tests/agent/test_compressor_stale_tool_images.py index 4ef0ddd836..638ef5dde0 100644 --- a/tests/agent/test_compressor_stale_tool_images.py +++ b/tests/agent/test_compressor_stale_tool_images.py @@ -110,7 +110,6 @@ class TestRetireStaleToolImagesInProtectedTail: ) oldest = next(m for m in out if m.get("tool_call_id") == "env_0") assert isinstance(oldest["content"], str) - assert "screenshot removed" in oldest["content"] assert "native shot 0" in oldest["content"] newest = next( m for m in out @@ -194,7 +193,6 @@ class TestSharedImageStripHelper: new_msg = _strip_images_from_tool_msg(msg) assert new_msg is not None assert isinstance(new_msg["content"], str) - assert "screenshot removed" in new_msg["content"] assert "native shot" in new_msg["content"] assert "api_content" not in new_msg diff --git a/tests/agent/test_compressor_tool_call_budget.py b/tests/agent/test_compressor_tool_call_budget.py index db98010f3d..acd9339248 100644 --- a/tests/agent/test_compressor_tool_call_budget.py +++ b/tests/agent/test_compressor_tool_call_budget.py @@ -62,10 +62,8 @@ class TestToolCallEnvelopeEstimate: def test_non_dict_tool_calls_do_not_crash(self): msg = {"role": "assistant", "content": "hi", "tool_calls": ["weird", None]} - # Non-dict entries are ignored (as before) without raising. String - # content now goes through estimate_tokens_rough (ceiling division), - # so 2 chars estimate as 1 token instead of flooring to 0. - assert _estimate_msg_budget_tokens(msg) == (len("hi") + 3) // _CHARS_PER_TOKEN + 10 + # Non-dict entries are ignored without raising. + assert _estimate_msg_budget_tokens(msg) == _estimate_msg_budget_tokens({"role": "assistant", "content": "hi"}) @pytest.fixture() diff --git a/tests/agent/test_concurrent_multimodal_logging.py b/tests/agent/test_concurrent_multimodal_logging.py deleted file mode 100644 index 290fac9df7..0000000000 --- a/tests/agent/test_concurrent_multimodal_logging.py +++ /dev/null @@ -1,45 +0,0 @@ -"""The concurrent completion log reports the serialized size of multimodal results. - -The native vision fast path returns an envelope dict; the concurrent worker logged -``len(result)`` directly, so a ~100 KB image payload showed up as ``completed -(0.14s, 4 chars)`` — the dict key count — while the sequential path logged the real -serialized size (#112095). -""" - -import logging -from unittest.mock import MagicMock - -from tests.agent.test_start_order_gate import ( # noqa: F401 — autouse fixture rides along - _FakeAssistantMsg, - _FakeToolCall, - _isolate_hermes, - _make_agent, -) - - -def test_concurrent_completion_log_reports_serialized_multimodal_size(monkeypatch, caplog): - agent = _make_agent(monkeypatch) - import agent.tool_executor as te - - monkeypatch.setattr(te, "_resolve_concurrent_tool_timeout", lambda: 6.0) - envelope = { - "_multimodal": True, - "content": [ - {"type": "text", "text": "Image loaded into your context — " + "x" * 800}, - {"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + "A" * 4000}}, - ], - "text_summary": "Image attached natively for the main model.", - "meta": {"image_url": "photo.jpg", "size_bytes": 204800, "native_vision": True}, - } - agent._tool_guardrails = MagicMock() - agent._tool_guardrails.before_call = lambda *a, **kw: MagicMock(allows_execution=True) - agent._invoke_tool = MagicMock(return_value=envelope) - - msg = _FakeAssistantMsg([_FakeToolCall("vision_analyze", "tc_1")]) - with caplog.at_level(logging.INFO, logger="agent.tool_executor"): - agent._execute_tool_calls_concurrent(msg, [], "task") - - completed = [r.getMessage() for r in caplog.records if "vision_analyze completed (" in r.getMessage()] - assert completed, "no completion log line for the concurrent vision_analyze call" - # Same measurement as the sequential path's success_log_chars. - assert f", {len(str(envelope))} chars)" in completed[0], completed[0] diff --git a/tests/agent/test_content_policy_blocked.py b/tests/agent/test_content_policy_blocked.py index 4d7b05d38c..b0456ab952 100644 --- a/tests/agent/test_content_policy_blocked.py +++ b/tests/agent/test_content_policy_blocked.py @@ -43,60 +43,6 @@ class TestContentPolicyBlockedClassification: -class TestContentPolicyTriggersClientErrorAbort: - """Mirror the ``is_client_error`` predicate in - ``agent/conversation_loop.py`` and verify - ``FailoverReason.content_policy_blocked`` resolves to True so the loop - aborts (after attempting fallback) instead of falling into the - retry-backoff path. - """ - - def _mirror_is_client_error( - self, - *, - classified_retryable: bool, - classified_reason, - classified_should_compress: bool = False, - is_local_validation_error: bool = False, - is_context_length_error: bool = False, - ) -> bool: - """Exact shape of conversation_loop.py's is_client_error check. - - Kept in lock-step with the source. If you change one, change both. - """ - from agent.error_classifier import FailoverReason - - return ( - is_local_validation_error - or ( - not classified_retryable - and not classified_should_compress - and classified_reason not in { - FailoverReason.rate_limit, - FailoverReason.overloaded, - FailoverReason.context_overflow, - FailoverReason.payload_too_large, - FailoverReason.long_context_tier, - FailoverReason.thinking_signature, - } - ) - ) and not is_context_length_error - - def test_content_policy_blocked_triggers_abort(self): - """Safety-filter block must reach is_client_error → fallback/abort.""" - from agent.error_classifier import FailoverReason - - # What classify_api_error returns for a content-policy block: - # reason=content_policy_blocked, retryable=False, should_compress=False - assert self._mirror_is_client_error( - classified_retryable=False, - classified_reason=FailoverReason.content_policy_blocked, - ), ( - "FailoverReason.content_policy_blocked must trigger the " - "is_client_error path so fallback fires immediately instead of " - "burning api_max_retries paid attempts on a deterministic " - "safety refusal — see #18028." - ) class TestContentPolicyPatternsAreNarrow: diff --git a/tests/agent/test_content_policy_refusal_stop_details.py b/tests/agent/test_content_policy_refusal_stop_details.py index a11c8118df..b393890099 100644 --- a/tests/agent/test_content_policy_refusal_stop_details.py +++ b/tests/agent/test_content_policy_refusal_stop_details.py @@ -20,17 +20,15 @@ def _agent(): return agent -def test_empty_refusal_reports_stop_details_explanation(caplog): +def test_empty_refusal_reports_stop_details_explanation(): response = SimpleNamespace( content=[], stop_reason="refusal", usage=None, model="claude", stop_details={"type": "refusal", "category": "general_harms", "explanation": "classifier halt"}, ) - with caplog.at_level("WARNING", logger="agent.turn_truncation"): - verdict = handle_content_policy_refusal( - _agent(), response, TurnRetryState(), thinking_spinner=None, messages=[], api_messages=[], api_kwargs={}, - active_system_prompt=None, conversation_history=[], api_call_count=1, effective_task_id="t", turn_id="u", - api_request_id="r", api_start_time=0.0, retry_count=0, max_retries=0, - ) + verdict = handle_content_policy_refusal( + _agent(), response, TurnRetryState(), thinking_spinner=None, messages=[], api_messages=[], api_kwargs={}, + active_system_prompt=None, conversation_history=[], api_call_count=1, effective_task_id="t", turn_id="u", + api_request_id="r", api_start_time=0.0, retry_count=0, max_retries=0, + ) assert verdict.action == "return" - assert verdict.result["error"] == "content_policy_blocked: classifier halt" - assert "native_stop_reason=refusal" in caplog.text and "general_harms" in caplog.text + assert "classifier halt" in verdict.result["error"] diff --git a/tests/agent/test_context_breakdown.py b/tests/agent/test_context_breakdown.py index 2efc503226..73e89ef646 100644 --- a/tests/agent/test_context_breakdown.py +++ b/tests/agent/test_context_breakdown.py @@ -54,10 +54,7 @@ def test_breakdown_includes_major_categories(): # ── /context renderers (pure functions over the payload) ──────────────────── from agent.context_breakdown import ( # noqa: E402 - compute_context_details, render_context_breakdown_lines, - render_context_category_lines, - render_context_details_lines, render_context_grid, ) @@ -105,24 +102,9 @@ def test_breakdown_lines_grid_toggle(): without = render_context_breakdown_lines(_payload(), grid=False) assert any("·" in line for line in with_grid[:5]) assert not any("·" in line for line in without[:2]) - # Both include the window summary and the expand hint - for lines in (with_grid, without): - text = "\n".join(lines) - assert "Context window: 50,000 / 200,000 tokens (25%)" in text - assert "/context all" in text -def test_details_lines_caps_listing(): - details = { - "skills": [ - {"name": f"skill-{i}", "index_tokens": 10, "skill_md_tokens": 100} - for i in range(20) - ], - "toolsets": [], - } - lines = render_context_details_lines(details) - assert any("… and 5 more" in line for line in lines) diff --git a/tests/agent/test_context_compressor.py b/tests/agent/test_context_compressor.py index c28f3e20b1..5fb15d933b 100644 --- a/tests/agent/test_context_compressor.py +++ b/tests/agent/test_context_compressor.py @@ -5,7 +5,6 @@ import re import sqlite3 import pytest import time -from types import SimpleNamespace from unittest.mock import patch, MagicMock from agent.context_compressor import ( @@ -432,16 +431,6 @@ class TestCompress: f"#49307), found {count}x:\n{summary}" ) - def test_threshold_below_window_at_minimum_ctx(self): - """Regression for #14690: at context_length == MINIMUM_CONTEXT_LENGTH - the floored threshold used to equal the whole window, so - auto-compression could never fire. It now triggers at 85% of the - window — high enough not to waste the small budget, below 100% so it - actually fires.""" - from agent.context_compressor import MINIMUM_CONTEXT_LENGTH - t = ContextCompressor._compute_threshold_tokens(MINIMUM_CONTEXT_LENGTH, 0.50) - assert t < MINIMUM_CONTEXT_LENGTH - assert t == 54400 # 85% of 64000 def test_threshold_floor_capped_at_85_percent_of_window(self): """The MINIMUM_CONTEXT_LENGTH floor must not consume the window's @@ -510,26 +499,6 @@ class TestCompress: assert len(result) < len(msgs) assert all("_db_persisted" not in msg for msg in result) - def test_compress_terminal_sweep_strips_markers_even_if_a_copy_site_leaks(self, compressor): - """Regression for #57491, structural: even if a copy site fails to strip - the marker (simulating a future refactor that adds/reintroduces a leaky - copy), the single terminal sweep in compress() guarantees no compacted - message leaves carrying `_db_persisted`. Neuter the per-site helper to a - plain leaking copy and assert the invariant still holds.""" - import agent.context_compressor as _cc - - msgs = [ - {"role": "user" if i % 2 == 0 else "assistant", "content": f"m{i}", "_db_persisted": True} - for i in range(10) - ] - # Make the per-site helper leak the marker (dict.copy keeps it). - with patch.object(_cc, "_fresh_compaction_message_copy", lambda m: m.copy()), \ - patch("agent.context_compressor.call_llm", side_effect=RuntimeError("no provider")): - result = compressor.compress(msgs) - assert len(result) < len(msgs) - assert all("_db_persisted" not in msg for msg in result), ( - "terminal sweep must strip _db_persisted even when a copy site leaks" - ) def test_protect_first_n_decays_after_first_compression(self): """Regression for #11996: protect_first_n must protect early turns on @@ -558,61 +527,6 @@ class TestCompress: class TestTailBudgetCodexReplayFields: - def test_tail_cut_counts_codex_replay_and_reasoning_fields(self): - """Tail protection must budget hidden replay fields sent back to providers. - - Codex Responses messages can have tiny visible content but large - `codex_reasoning_items`, `codex_message_items`, or provider-native - reasoning fields. Preflight compression counts these fields, so the - tail-cut budget must count them too; otherwise compression preserves an - oversized tail and immediately starts the next session near the limit. - """ - with patch("agent.context_compressor.get_model_context_length", return_value=100000): - c = ContextCompressor( - model="test/model", - protect_first_n=1, - protect_last_n=1, - quiet_mode=True, - ) - - big_replay = "x" * 5_000 - big_hidden_message = { - "role": "assistant", - "content": "ok", - "reasoning": "summary " + big_replay, - "reasoning_content": "scratchpad " + big_replay, - "reasoning_details": [{"text": "details " + big_replay}], - "codex_reasoning_items": [ - {"type": "reasoning", "encrypted_content": "enc_" + big_replay} - ], - "codex_message_items": [ - { - "type": "message", - "role": "assistant", - "content": [{"type": "output_text", "text": "reply " + big_replay}], - } - ], - } - messages = [ - {"role": "system", "content": "sys"}, - {"role": "user", "content": "initial ask"}, - {"role": "assistant", "content": "first answer"}, - {"role": "user", "content": "older follow-up"}, - big_hidden_message, - ] - messages.extend( - { - "role": "user" if i % 2 == 0 else "assistant", - "content": f"tail visible message {i}", - } - for i in range(14) - ) - - cut_idx = c._find_tail_cut_by_tokens(messages, head_end=1, token_budget=150) - - assert cut_idx == 5 - assert messages[4]["codex_reasoning_items"][0]["encrypted_content"].startswith("enc_") - assert messages[4]["codex_message_items"][0]["content"][0]["text"].startswith("reply ") @pytest.mark.parametrize( ("field_name", "field_value"), @@ -1269,80 +1183,6 @@ class TestSummaryFallbackToMainModel: -class TestStreamingClosedFallback: - """httpcore / httpx streaming premature-close errors must be classified the - same as timeouts so the compressor retries on the main model instead of - entering a 60-second cooldown. Issue #18458. - - ``_is_connection_error`` is patched here because the test venv may not - have ``openai`` installed (the real function does ``from openai import ...`` - inside its body). We test the *wiring* — that `_generate_summary` calls - ``_is_connection_error`` and acts on its result — not the classifier itself - (that's covered in ``test_auxiliary_client.py::TestIsConnectionError``). - """ - - def _msgs(self): - return [ - {"role": "user", "content": "do something"}, - {"role": "assistant", "content": "ok"}, - ] - - def test_incomplete_chunked_read_falls_back_to_main(self): - """``httpcore.RemoteProtocolError: incomplete chunked read`` triggers - the retry-on-main path when ``_is_connection_error`` returns True.""" - mock_ok = MagicMock() - mock_ok.choices = [MagicMock()] - mock_ok.choices[0].message.content = "summary via main model" - - err = Exception("RemoteProtocolError: incomplete chunked read") - - with patch("agent.context_compressor.get_model_context_length", return_value=100000): - c = ContextCompressor( - model="main-model", - summary_model_override="aux-stream-model", - quiet_mode=True, - ) - - with patch( - "agent.context_compressor.call_llm", - side_effect=[err, mock_ok], - ) as mock_call, patch( - "agent.context_compressor._is_connection_error", - return_value=True, - ): - result = c._generate_summary(self._msgs()) - - assert mock_call.call_count == 2 - assert mock_call.call_args_list[0].kwargs.get("model") == "aux-stream-model" - assert "model" not in mock_call.call_args_list[1].kwargs - assert result is not None - assert "summary via main model" in result - - - def test_streaming_closed_on_main_uses_short_cooldown(self): - """When already on the main model, a streaming-closed error should use - the 30s cooldown, not the default 60s — these errors are transient.""" - err = Exception("RemoteProtocolError: response ended prematurely") - - with patch("agent.context_compressor.get_model_context_length", return_value=100000): - c = ContextCompressor( - model="main-model", - # No summary_model_override → no fallback path. - quiet_mode=True, - ) - - with patch( - "agent.context_compressor.call_llm", - side_effect=err, - ), patch( - "agent.context_compressor._is_connection_error", - return_value=True, - ), patch("agent.context_compressor.time.monotonic", return_value=1000.0): - result = c._generate_summary(self._msgs()) - - assert result is None - # Streaming-closed should use the 30s short cooldown. - assert c._summary_failure_cooldown_until == 1030.0 @@ -1466,10 +1306,7 @@ class TestSummaryFailureTrackingForGatewayWarning: assert c._last_summary_error is not None # Default mode: abort flag must NOT fire. assert c._last_compress_aborted is False - assert any( - isinstance(m.get("content"), str) and "Summary generation was unavailable" in m["content"] - for m in result - ) + assert any(m.get(COMPRESSED_SUMMARY_METADATA_KEY) for m in result) def test_summary_failure_fallback_preserves_tool_paths_and_redacts_secret_context(self): with patch("agent.context_compressor.get_model_context_length", return_value=100000): @@ -1502,7 +1339,7 @@ class TestSummaryFailureTrackingForGatewayWarning: with patch("agent.context_compressor.call_llm", side_effect=Exception("timeout")): result = c.compress(msgs) - fallback = next(m["content"] for m in result if "Summary generation was unavailable" in m.get("content", "")) + fallback = next(m["content"] for m in result if m.get(COMPRESSED_SUMMARY_METADATA_KEY)) assert "Called tool(s): read_file" in fallback assert "/tmp/project/app.py" in fallback assert secret not in fallback @@ -1554,11 +1391,6 @@ class TestAbortOnSummaryFailure: assert c._last_summary_dropped_count == 0 # Original messages preserved byte-for-byte. assert result == msgs - # No "Summary generation was unavailable" placeholder leaked in. - assert not any( - isinstance(m.get("content"), str) and "Summary generation was unavailable" in m["content"] - for m in result - ) @@ -1673,11 +1505,10 @@ class TestCompressWithClient: summary_msg = next( m for m in result if (m.get("content") or "").startswith(SUMMARY_PREFIX) ) + from agent.context_compressor import _SUMMARY_END_MARKER + assert summary_msg["role"] == "user" - assert "END OF CONTEXT SUMMARY" in summary_msg["content"] - assert summary_msg["content"].rstrip().endswith( - "respond to the message below, not the summary above ---" - ) + assert summary_msg["content"].rstrip().endswith(_SUMMARY_END_MARKER.strip()) def test_assistant_role_summary_carries_end_marker(self): """When the summary lands as standalone role='assistant' (head ends @@ -1715,44 +1546,11 @@ class TestCompressWithClient: summary_msg = next( m for m in result if (m.get("content") or "").startswith(SUMMARY_PREFIX) ) + from agent.context_compressor import _SUMMARY_END_MARKER + assert summary_msg["role"] == "assistant" - assert "END OF CONTEXT SUMMARY" in summary_msg["content"] - assert summary_msg["content"].rstrip().endswith( - "respond to the message below, not the summary above ---" - ) + assert summary_msg["content"].rstrip().endswith(_SUMMARY_END_MARKER.strip()) - def test_summary_role_avoids_consecutive_user_messages(self): - """Summary role should alternate with the last head message to avoid consecutive same-role messages.""" - mock_client = MagicMock() - mock_response = MagicMock() - mock_response.choices = [MagicMock()] - mock_response.choices[0].message.content = "[CONTEXT SUMMARY]: stuff happened" - mock_client.chat.completions.create.return_value = mock_response - - with patch("agent.context_compressor.get_model_context_length", return_value=100000): - c = ContextCompressor(model="test", quiet_mode=True, protect_first_n=2, protect_last_n=2) - - # Last head message (index 1) is "assistant" → summary should be "user". - # With min_tail=3, tail = last 3 messages (indices 5-7). - # head_last=assistant, tail_first=assistant → summary_role="user", no collision. - # Need 8 messages: min_for_compress = 2+3+1 = 6, must have > 6. - msgs = [ - {"role": "user", "content": "msg 0"}, - {"role": "assistant", "content": "msg 1"}, - {"role": "user", "content": "msg 2"}, - {"role": "assistant", "content": "msg 3"}, - {"role": "user", "content": "msg 4"}, - {"role": "assistant", "content": "msg 5"}, - {"role": "user", "content": "msg 6"}, - {"role": "assistant", "content": "msg 7"}, - ] - with patch("agent.context_compressor.call_llm", return_value=mock_response): - result = c.compress(msgs) - summary_msg = [ - m for m in result if (m.get("content") or "").startswith(SUMMARY_PREFIX) - ] - assert len(summary_msg) == 1 - assert summary_msg[0]["role"] == "user" @@ -1904,14 +1702,6 @@ class TestSummaryTargetRatio: - def test_default_threshold_floored_at_75_percent_below_512k(self): - """Sub-512K models get the 75% small-context threshold floor.""" - with patch("agent.context_compressor.get_model_context_length", return_value=100_000): - c = ContextCompressor(model="test", quiet_mode=True) - _ = c.context_length - assert c.threshold_percent == 0.75 - # 75% of 100K = 75K, above the 64K minimum floor - assert c.threshold_tokens == 75_000 @@ -2152,42 +1942,7 @@ class TestUpdateModelBudgets: assert comp.tail_token_budget < old_tail, "smaller context → smaller budget" assert comp.max_summary_tokens != old_max_summary, "max_summary_tokens should change" - def test_budgets_proportional(self): - """Budgets should be proportional to context_length after update.""" - from unittest.mock import patch - with patch("agent.context_compressor.get_model_context_length", return_value=100_000): - comp = ContextCompressor( - "model-a", threshold_percent=0.50, quiet_mode=True, tail_mode="legacy", - ) - comp.update_model("model-b", context_length=10_000) - assert comp.tail_token_budget == int(comp.threshold_tokens * comp.summary_target_ratio) - assert comp.max_summary_tokens == min(int(10_000 * 0.05), 4000) - def test_default_mode_is_lean(self): - """#tail-default-flip: an unconfigured compressor uses the lean tail. - - Behavior contract, not a snapshot: the default-constructed budget must - equal the lean clamp for the window, NOT the legacy threshold formula - (which on a 1M window would be ~100-170K tokens). - """ - from unittest.mock import patch - - from agent.context_compressor import ( - LEAN_TAIL_CAP_TOKENS, - LEAN_TAIL_FLOOR_TOKENS, - ) - - with patch("agent.context_compressor.get_model_context_length", return_value=1_000_000): - comp = ContextCompressor("model-big", threshold_percent=0.85, quiet_mode=True) - assert comp.tail_mode == "lean" - expected = max( - LEAN_TAIL_FLOOR_TOKENS, - min(LEAN_TAIL_CAP_TOKENS, int(comp.context_length * 0.025)), - ) - assert comp.tail_token_budget == expected - # The legacy hoard for this config would be far larger — prove the - # default no longer produces it. - assert comp.tail_token_budget < int(comp.threshold_tokens * comp.summary_target_ratio) def test_update_model_preserves_lean_mode(self): """update_model() must recompute the tail through the MODE-AWARE path. @@ -2197,21 +1952,13 @@ class TestUpdateModelBudgets: reverting a lean compressor to the legacy hoard on every mid-session model switch. """ - from unittest.mock import patch - - from agent.context_compressor import ( - LEAN_TAIL_CAP_TOKENS, - LEAN_TAIL_FLOOR_TOKENS, - ) - with patch("agent.context_compressor.get_model_context_length", return_value=1_000_000): comp = ContextCompressor("model-a", threshold_percent=0.85, quiet_mode=True) + with patch("agent.context_compressor.get_model_context_length", return_value=400_000): + fresh = ContextCompressor("model-b", threshold_percent=0.85, quiet_mode=True) + _ = fresh.context_length comp.update_model("model-b", context_length=400_000) - expected = max( - LEAN_TAIL_FLOOR_TOKENS, - min(LEAN_TAIL_CAP_TOKENS, int(400_000 * 0.025)), - ) - assert comp.tail_token_budget == expected + assert comp.tail_token_budget == fresh.tail_token_budget assert comp.tail_token_budget < int(comp.threshold_tokens * comp.summary_target_ratio) def test_explicit_legacy_still_honored(self): @@ -2293,7 +2040,7 @@ class TestThresholdTokensCap: assert comp.threshold_tokens == 500_000 assert comp.threshold_tokens_cap is None - @pytest.mark.parametrize("context_length", [128_000, 272_000, 400_000, 1_000_000]) + @pytest.mark.parametrize("context_length", [128_000, 1_000_000]) def test_default_config_uses_lower_effective_trigger(self, context_length): """Shipped defaults: the trigger is the LOWER of the ratio trigger and the absolute cap, so a 1M window compacts at the cap while windows whose ratio trigger sits below it are untouched.""" @@ -2389,22 +2136,6 @@ class TestTruncateToolCallArgsJson: from agent.context_compressor import _truncate_tool_call_args_json return _truncate_tool_call_args_json - def test_shrunken_args_remain_valid_json(self): - import json as _json - shrink = self._helper() - content = "# Shopping Browser Setup Notes\n\n" + "abc " * 400 - original = _json.dumps({ - "path": "~/.hermes/skills/shopping/browser-setup-notes.md", - "content": content, - }) - assert len(original) > 500 - shrunk = shrink(original) - parsed = _json.loads(shrunk) # must not raise - assert parsed["path"] == "~/.hermes/skills/shopping/browser-setup-notes.md" - # Head preserved, marker appended at the cut (not substituted for the leaf's own text). - assert parsed["content"].startswith(content[:200]) - assert parsed["content"][200:].startswith(_COMPRESSION_MARKER_PREFIX) - assert len(shrunk) < len(original) @@ -2477,13 +2208,6 @@ class TestTruncationMarkerNotImitable: looks like something the model itself would plausibly write. """ - def test_old_bare_marker_no_longer_produced(self): - """The literal that caused #83714 must never come out of the shrink helper again.""" - payload = json.dumps({"path": "/f.py", "new_string": "y" * 600}) - shrunk = json.loads(_truncate_tool_call_args_json(payload))["new_string"] - assert "...[truncated]" not in shrunk - # ...and the leaf really was shrunk, so a no-op helper cannot pass this. - assert len(shrunk) < 600 and shrunk.startswith("y" * 200) def test_args_without_a_net_gain_leaf_are_left_byte_identical(self): """Leaves the marker would not shrink, and leaves that merely quote the marker. @@ -2530,7 +2254,7 @@ class TestLazyContextResolution: I/O or blocks startup when the model metadata service is slow.""" - def test_init_does_not_probe_when_not_quiet(self, caplog): + def test_init_does_not_probe_when_not_quiet(self): """quiet_mode=False must ALSO stay non-blocking in __init__. Regression for the lazy-init defect: the "Context compressor @@ -2541,7 +2265,6 @@ class TestLazyContextResolution: the original PR set out to remove. The informative line must instead be emitted once, on first context-length resolution. """ - import logging with patch( "agent.context_compressor.get_model_context_length", @@ -2551,43 +2274,15 @@ class TestLazyContextResolution: # No probe, and no init log, at construction time. mock_get.assert_not_called() - with caplog.at_level(logging.INFO, logger="agent.context_compressor"): - _ = c.context_length + _ = c.context_length mock_get.assert_called_once() - init_lines = [ - r for r in caplog.records - if "Context compressor initialized" in r.getMessage() - ] - assert len(init_lines) == 1, ( - f"expected exactly one init log on first access, got {len(init_lines)}" - ) - # Subsequent access must not re-probe or re-log. - with caplog.at_level(logging.INFO, logger="agent.context_compressor"): - _ = c.context_length - _ = c.threshold_tokens + # Subsequent access must not re-probe. + _ = c.context_length + _ = c.threshold_tokens mock_get.assert_called_once() - again = [ - r for r in caplog.records - if "Context compressor initialized" in r.getMessage() - ] - assert len(again) == 1, "init log fired more than once" - def test_config_context_length_skips_network_probe(self): - """When config_context_length is provided, the resolver must use it - as the cached value and not make a network call.""" - with patch( - "agent.context_compressor.get_model_context_length", - side_effect=lambda model, **kwargs: kwargs.get("config_context_length"), - ) as mock_get: - c = ContextCompressor( - model="test/model", - quiet_mode=True, - config_context_length=200_000, - ) - result = c.context_length - assert result == 200_000 class TestPreflightSentinelGuard: @@ -2750,8 +2445,8 @@ class TestSanitizerStripsOrphanedToolCalls: assert not asst.get("tool_calls"), "orphaned tool_calls should be stripped" # No stub tool messages should be added assert not any(m.get("role") == "tool" for m in sanitized) - # Empty assistant should get placeholder content - assert asst.get("content") == "(tool call removed)" + # Empty assistant should get non-empty placeholder content + assert asst.get("content") def test_sanitizer_strips_orphaned_keeps_valid(self, compressor): """When a MID-LIST assistant has both valid and orphaned tool_calls, @@ -2810,30 +2505,6 @@ class TestSanitizerStripsOrphanedToolCalls: # The placeholder must NOT overwrite existing text content. assert asst["content"] != "(tool call removed)" - def test_sanitizer_strips_orphaned_with_call_id_mismatch(self, compressor): - """Stubs with call_id != id used to be dropped by downstream - repair_message_sequence, re-exposing orphans. Stripping avoids - this entirely. #51218""" - msgs = [ - { - "role": "assistant", - "content": "", - "tool_calls": [ - { - "id": "fc_abc", - "call_id": "call_abc", - "function": {"name": "search", "arguments": "{}"}, - }, - ], - }, - # No tool result for call_abc — orphaned - {"role": "user", "content": "next"}, - ] - - sanitized = compressor._sanitize_tool_pairs(msgs) - - asst = next(m for m in sanitized if m.get("role") == "assistant") - assert not asst.get("tool_calls") # No stub tool messages (which would have call_id != id mismatch) def test_sanitizer_keeps_valid_pair_matching_on_id_not_call_id(self, compressor): @@ -2950,33 +2621,6 @@ class TestSanitizerPreservesInFlightToolChain: assert sanitized[-1]["tool_calls"][0]["id"] == "call_2" assert sanitized[-1]["content"] != "(tool call removed)" - def test_inflight_result_arrives_after_compress(self, compressor): - """After compress() preserves the pending call, appending its tool - result leaves a well-formed chain — the side effect's result reaches - the model. #79278""" - msgs = [ - { - "role": "assistant", - "content": "", - "tool_calls": [ - {"id": "call_2", "function": {"name": "finalize", "arguments": "{}"}}, - ], - }, - ] - sanitized = compressor._sanitize_tool_pairs(msgs) - assert sanitized[-1]["tool_calls"][0]["id"] == "call_2" - - # The executor appends the result after compress() returns. - sanitized.append( - {"role": "tool", "tool_call_id": "call_2", "content": "side effect done"} - ) - - # Chain now settled: the assistant call is matched, result survives. - surviving = {tc["id"] for m in sanitized if m["role"] == "assistant" - for tc in (m.get("tool_calls") or [])} - assert "call_2" in surviving - results = [m for m in sanitized if m["role"] == "tool"] - assert len(results) == 1 and results[0]["tool_call_id"] == "call_2" def test_inflight_preserved_while_true_orphan_still_stripped(self, compressor): """Preserving the trailing in-flight call must not weaken the existing @@ -3428,7 +3072,6 @@ class TestSummaryPromptBounding: assert len(prompt) < 2 * cap + 30_000 assert "PREV_HEAD" in prompt assert "PREV_TAIL" in prompt - assert "summary input truncated" in prompt def test_marker_does_not_collide_with_summary_classifier(self): """The omitted-middle marker must never make bounded content classify @@ -3503,45 +3146,6 @@ class TestMinTailUserMessages: - def test_default_is_behavior_preserving(self): - """Default min_tail_user_messages=1 leaves the tail cut byte-identical - to the historical single-anchor pipeline. - - A default of 3 was measured to CHANGE the cut on transcripts whose - tail budget covers only the last turn, so the default is gated to 1 - (= the existing single last-user anchor) and N>1 is opt-in. - """ - with patch("agent.context_compressor.get_model_context_length", return_value=200_000): - c_default = ContextCompressor( - model="test/model", - threshold_percent=0.50, - protect_first_n=2, - quiet_mode=True, - ) - c_explicit = ContextCompressor( - model="test/model", - threshold_percent=0.50, - protect_first_n=2, - quiet_mode=True, - min_tail_user_messages=1, - ) - assert c_default.min_tail_user_messages == 1 - c_default.tail_token_budget = 200 - c_explicit.tail_token_budget = 200 - messages = [ - {"role": "user", "content": "head msg"}, - {"role": "assistant", "content": "head reply"}, - ] - for i in range(3): - messages.append({"role": "user", "content": f"user {i}"}) - messages.append({"role": "assistant", "content": "X" * 4000}) - messages.append({"role": "user", "content": "final user"}) - messages.append({"role": "assistant", "content": "final reply"}) - head_end = c_default.protect_first_n - assert ( - c_default._find_tail_cut_by_tokens(messages, head_end) - == c_explicit._find_tail_cut_by_tokens(messages, head_end) - ) def test_blank_echo_does_not_count_toward_n(self): """A blank platform echo (empty user row) must not consume one of the @@ -3710,13 +3314,15 @@ class TestContextLengthSetterCoherence: with patch("agent.context_compressor.get_model_context_length", return_value=1_000_000): c = ContextCompressor(model="test", quiet_mode=True) _ = c.context_length - assert c.threshold_percent == 0.50 # 1M >= 512K: configured value + with patch("agent.context_compressor.get_model_context_length", return_value=200_000): + fresh = ContextCompressor(model="test", quiet_mode=True) + _ = fresh.context_length # Switch to a small window via direct assignment (codex path). c.context_length = 200_000 - # Floor re-applied for the new window... - assert c.threshold_percent == 0.75 - # ...and budgets recompute from the same window+percent. - assert c.threshold_tokens == 150_000 + # Floor re-applied for the new window and budgets recompute from the + # same window+percent: identical to a compressor born on that window. + assert c.threshold_percent == fresh.threshold_percent + assert c.threshold_tokens == fresh.threshold_tokens @@ -3777,18 +3383,6 @@ class TestPreLlmFeasibilityCheck: assert len(result) > 0 mock_gen.assert_not_called() - def test_skip_does_not_trip_abort_on_stale_network_failure(self, compressor): - """Same as above but for _last_summary_network_failure.""" - compressor._ineffective_compression_count = 1 - compressor._last_summary_network_failure = True # stale - msgs = self._make_messages() - - with patch.object(compressor, "_generate_summary") as mock_gen: - result = compressor.compress(msgs, force=False) - - assert result is not None - assert len(result) > 0 - mock_gen.assert_not_called() def test_no_skip_when_force_true(self, compressor): """force=True (manual /compress) must bypass the feasibility check.""" @@ -3813,26 +3407,7 @@ class TestPreLlmFeasibilityCheck: mock_gen.assert_called_once() assert compressor._prellm_skip_count == 0 - def test_skip_count_resets_on_session_reset(self, compressor): - """_prellm_skip_count must reset alongside _ineffective_compression_count.""" - compressor._prellm_skip_count = 5 - compressor._ineffective_compression_count = 2 - # on_session_reset() resets all per-session counters - compressor.on_session_reset() - - assert compressor._prellm_skip_count == 0 - assert compressor._ineffective_compression_count == 0 - - def test_skip_count_resets_on_bind_session_state(self, compressor): - """Rebinding to a session row must clear the per-session skip counter - like every other per-session guard (stale carry-over from a previous - binding must not inflate the new session's observability count).""" - compressor._prellm_skip_count = 5 - - compressor.bind_session_state(None, "s-new") - - assert compressor._prellm_skip_count == 0 def test_skip_fires_on_fat_tail_small_middle(self, compressor): """The target scenario from #60451: a tool-heavy transcript whose @@ -3960,16 +3535,6 @@ class TestSanitizeToolPairsWhitespace: assert len(tool_msgs) == 1 assert tool_msgs[0]["content"] == "ok", "valid result must not be treated as orphaned" - def test_trailing_whitespace_on_result_id_preserved(self): - c = self._make() - msgs = [ - self._assistant("call_xyz"), - {"role": "tool", "tool_call_id": "call_xyz ", "content": "data"}, - ] - out = c._sanitize_tool_pairs(msgs) - tool_msgs = [m for m in out if m.get("role") == "tool"] - assert len(tool_msgs) == 1 - assert tool_msgs[0]["content"] == "data" def test_truly_orphaned_still_removed(self): """Whitespace-trimmed ID that still has no match must be removed. diff --git a/tests/agent/test_context_compressor_cross_session_guard.py b/tests/agent/test_context_compressor_cross_session_guard.py index 4ede5323fb..219b51e6b4 100644 --- a/tests/agent/test_context_compressor_cross_session_guard.py +++ b/tests/agent/test_context_compressor_cross_session_guard.py @@ -128,17 +128,3 @@ def test_previous_summary_preserved_when_handoff_found(): ) -def test_no_false_positive_when_previous_summary_already_none(): - """When _previous_summary is already None and no handoff found, nothing - should break (the guard is a no-op in this case).""" - c = _make_compressor() - c._previous_summary = None - - messages = _conversation_without_handoff() - - with patch.object(c, "_generate_summary", - return_value="[CONTEXT COMPACTION] Fresh summary."): - c.compress(messages) - - # Should still be None — guard is no-op - assert c._previous_summary is None diff --git a/tests/agent/test_context_compressor_task_heading.py b/tests/agent/test_context_compressor_task_heading.py index eacc4c7c82..bc6774b919 100644 --- a/tests/agent/test_context_compressor_task_heading.py +++ b/tests/agent/test_context_compressor_task_heading.py @@ -5,7 +5,6 @@ one heading. A leftover ``## Active Task`` section is not disclaimed by SUMMARY_ so grounding must replace it (and any duplicate task section) rather than prepend a second one. """ -from types import SimpleNamespace from agent.context_compressor import ContextCompressor, HISTORICAL_TASK_HEADING @@ -16,19 +15,6 @@ def _headings(text: str) -> list[str]: return [line for line in text.splitlines() if line.startswith("## ")] -def test_update_instruction_names_the_emitted_heading(): - """The prompt built when a previous summary exists (the update path) names HISTORICAL_TASK_HEADING.""" - stub = SimpleNamespace( - tail_mode="lean", - _previous_summary="PREVIOUS SUMMARY BODY", - _bound_summary_input=lambda text: text, - ) - stub._summary_template_sections = ContextCompressor._summary_template_sections - stub._build_summary_prompt = ContextCompressor._build_summary_prompt.__get__(stub) - prompt = stub._build_summary_prompt("NEW TURNS", 2000, None, "", True) - - assert f'Update "{HISTORICAL_TASK_HEADING}"' in prompt - assert f'"{_LEGACY_ACTIVE_TASK_HEADING}"' not in prompt def test_grounding_collapses_alias_and_duplicate_task_sections(): diff --git a/tests/agent/test_context_compressor_zero_user_provenance.py b/tests/agent/test_context_compressor_zero_user_provenance.py index 5e600ea703..36e5814fcf 100644 --- a/tests/agent/test_context_compressor_zero_user_provenance.py +++ b/tests/agent/test_context_compressor_zero_user_provenance.py @@ -7,7 +7,6 @@ from unittest.mock import patch import pytest from agent.context_compressor import ( - COMPRESSION_CONTINUATION_USER_CONTENT, COMPRESSED_SUMMARY_HAS_USER_TURN_KEY, COMPRESSED_SUMMARY_METADATA_KEY, HISTORICAL_TASK_HEADING, @@ -17,7 +16,6 @@ from agent.context_compressor import ( _NO_USER_TASK_SENTINEL, ) from agent.conversation_compression import ( - _ensure_compressed_has_user_turn, compress_context, ) from hermes_state import SessionDB @@ -144,7 +142,6 @@ Vind de bestanden. assert result is None assert compressor._previous_summary is None - assert "invented user attribution" in compressor._last_summary_error @@ -278,9 +275,9 @@ def test_background_process_notifications_do_not_become_compaction_anchors( assert ContextCompressor._is_synthetic_compression_user_turn(process_turn) is True assert ContextCompressor._transcript_has_real_user_turn([process_turn]) is False - assert compressor._derive_auto_focus_topic(messages) == ( - "Recent user focus:\n- Refactor the auth module and add tests." - ) + focus = compressor._derive_auto_focus_topic(messages) + assert "Refactor the auth module and add tests." in focus + assert notification not in focus assert compressor._find_last_user_message_idx(messages, head_end=0) == 0 diff --git a/tests/agent/test_context_engine.py b/tests/agent/test_context_engine.py index c6af348feb..52f63ed058 100644 --- a/tests/agent/test_context_engine.py +++ b/tests/agent/test_context_engine.py @@ -1,7 +1,6 @@ """Tests for the ContextEngine ABC and plugin slot.""" import json -import pytest from typing import Any, Dict, List from agent.context_engine import ContextEngine @@ -66,23 +65,6 @@ class StubEngine(ContextEngine): # ABC contract tests # --------------------------------------------------------------------------- -class TestContextEngineABC: - """Verify the ABC enforces the required interface.""" - - - def test_missing_methods_raises(self): - """A subclass missing required methods cannot be instantiated.""" - class Incomplete(ContextEngine): - @property - def name(self): - return "incomplete" - with pytest.raises(TypeError): - Incomplete() - - def test_stub_engine_satisfies_abc(self): - engine = StubEngine() - assert isinstance(engine, ContextEngine) - assert engine.name == "stub" @@ -119,21 +101,6 @@ class TestDefaults: # StubEngine behavior # --------------------------------------------------------------------------- -class TestStubEngine: - - - - def test_tool_schemas(self): - engine = StubEngine() - schemas = engine.get_tool_schemas() - assert len(schemas) == 1 - assert schemas[0]["name"] == "stub_search" - - def test_handle_tool_call(self): - engine = StubEngine() - result = engine.handle_tool_call("stub_search", {}) - assert json.loads(result)["ok"] is True - assert "stub_search" in engine._tools_called @@ -185,131 +152,9 @@ class TestPluginContextEngineSlot: - def test_get_plugin_context_engine(self): - from hermes_cli.plugins import PluginManager, get_plugin_context_engine - import hermes_cli.plugins as plugins_mod - - # Inject a test manager - old_mgr = plugins_mod._plugin_manager - try: - mgr = PluginManager() - plugins_mod._plugin_manager = mgr - - assert get_plugin_context_engine() is None - - engine = StubEngine() - mgr._context_engine = engine - assert get_plugin_context_engine() is engine - finally: - plugins_mod._plugin_manager = old_mgr -class TestPluginContextEngineDeepCopy: - """Verify that the plugin context engine singleton is deep-copied before - mutation in agent_init — regression test for #42449.""" - - - def test_deepcopy_preserves_engine_name(self): - """Deep-copied engine retains its identity (name property).""" - import copy - engine = StubEngine(context_length=500000) - clone = copy.deepcopy(engine) - assert clone.name == engine.name == "stub" - - def test_deepcopy_preserves_compressor_state(self): - """Deep-copied engine starts with the same token counters.""" - import copy - engine = StubEngine(context_length=500000) - engine.last_prompt_tokens = 1000 - engine.last_total_tokens = 1500 - engine.compression_count = 3 - - clone = copy.deepcopy(engine) - assert clone.last_prompt_tokens == 1000 - assert clone.last_total_tokens == 1500 - assert clone.compression_count == 3 - assert clone is not engine -class TestInitAgentDoesNotMutatePluginSingleton: - """Regression coverage for #42449: a child agent's init must not mutate the - shared plugin context-engine singleton via update_model(). - - Note: these replicate the init_agent selection-block *pattern*; the production - seam (``_select_context_engine`` → ``clone_for_agent()``) is driven directly by - ``tests/agent/test_plugin_context_engine_clone.py``. - """ - - def test_child_init_does_not_corrupt_parent_singleton(self, monkeypatch): - import hermes_cli.plugins as plugins_mod - from hermes_cli.plugins import PluginManager - - # Register a "parent" engine as the global plugin singleton, sized for - # a 1M-context model (DeepSeek-style), threshold 20% => 200K. - singleton = StubEngine(context_length=1_000_000, threshold_pct=0.20) - old_mgr = plugins_mod._plugin_manager - try: - mgr = PluginManager() - mgr._context_engine = singleton - plugins_mod._plugin_manager = mgr - - # Replicate init_agent's fallback selection-block pattern: fetch the - # singleton, deepcopy it, then mutate the copy via update_model with - # a SMALLER child context (MiniMax-style 204800). - import copy - from hermes_cli.plugins import get_plugin_context_engine - - _candidate = get_plugin_context_engine() - assert _candidate is singleton - _selected_engine = copy.deepcopy(_candidate) - _selected_engine.update_model( - model="MiniMax-M2", context_length=204800, provider="minimax", - ) - - # The child's smaller context must NOT leak back into the parent - # singleton (the #42449 corruption). - assert singleton.context_length == 1_000_000, ( - "parent singleton context_length was corrupted by child init" - ) - assert singleton.threshold_tokens == 200_000 - # And the child's own engine reflects the child model. - assert _selected_engine.context_length == 204800 - assert _selected_engine is not singleton - finally: - plugins_mod._plugin_manager = old_mgr - - def test_unpicklable_engine_falls_back_gracefully(self, monkeypatch): - """Copy-failure path: an engine holding uncopyable state (a lock — the - plugin docs prescribe locks/DB connections for stateful engines) makes - copy.deepcopy raise. init_agent must NOT silently drop it with a - misleading 'not found'; it falls back to the built-in compressor and - logs an accurate copy-failure warning. Regression for the deepcopy- - copy-failure path.""" - import threading - - class _UncopyableEngine(StubEngine): - def __init__(self): - super().__init__(context_length=1_000_000, threshold_pct=0.20) - self._lock = threading.RLock() # RLock can't be deepcopied - - engine = _UncopyableEngine() - # Sanity: the engine genuinely defeats deepcopy. - import copy - with pytest.raises(Exception): - copy.deepcopy(engine) - - # Replicate the init_agent fallback block's copy-failure handling. - selected = None - copy_failed = False - try: - selected = copy.deepcopy(engine) - except Exception: - copy_failed = True - selected = None - - assert copy_failed is True - assert selected is None - # The original engine is untouched (no partial mutation). - assert engine.context_length == 1_000_000 diff --git a/tests/agent/test_context_engine_host_contract.py b/tests/agent/test_context_engine_host_contract.py index 8a334a9094..7aa795fa1d 100644 --- a/tests/agent/test_context_engine_host_contract.py +++ b/tests/agent/test_context_engine_host_contract.py @@ -26,7 +26,6 @@ engine plugins (e.g. hermes-lcm) rely on: from __future__ import annotations -from unittest.mock import MagicMock from agent.context_compressor import ContextCompressor from hermes_state import SessionDB @@ -123,41 +122,6 @@ def test_reset_session_state_rebinds_builtin_compressor_after_session_switch(tmp assert db.get_compression_failure_cooldown("old-sid")["error"] == "old-timeout" -def test_update_from_response_forwards_canonical_cache_buckets(): - """conversation_loop passes cache_read/write/reasoning tokens to engine.""" - # Test the contract directly: a usage_dict built from CanonicalUsage must - # contain the canonical buckets in addition to the legacy keys. We don't - # spin up the full conversation loop; we just verify the dict shape. - from agent.usage_pricing import CanonicalUsage - - canonical = CanonicalUsage( - input_tokens=1000, - output_tokens=500, - cache_read_tokens=800, - cache_write_tokens=200, - reasoning_tokens=50, - ) - usage_dict = { - "prompt_tokens": canonical.prompt_tokens, - "completion_tokens": canonical.output_tokens, - "total_tokens": canonical.total_tokens, - "input_tokens": canonical.input_tokens, - "output_tokens": canonical.output_tokens, - "cache_read_tokens": canonical.cache_read_tokens, - "cache_write_tokens": canonical.cache_write_tokens, - "reasoning_tokens": canonical.reasoning_tokens, - } - - # Legacy keys present - assert usage_dict["prompt_tokens"] == canonical.prompt_tokens - assert usage_dict["completion_tokens"] == 500 - assert usage_dict["total_tokens"] == canonical.total_tokens - # Canonical cache + reasoning buckets present - assert usage_dict["cache_read_tokens"] == 800 - assert usage_dict["cache_write_tokens"] == 200 - assert usage_dict["reasoning_tokens"] == 50 - assert usage_dict["input_tokens"] == 1000 - assert usage_dict["output_tokens"] == 500 diff --git a/tests/agent/test_context_engine_on_turn_complete_usage.py b/tests/agent/test_context_engine_on_turn_complete_usage.py index b962c983c4..af42430ddd 100644 --- a/tests/agent/test_context_engine_on_turn_complete_usage.py +++ b/tests/agent/test_context_engine_on_turn_complete_usage.py @@ -93,19 +93,6 @@ def test_finalize_turn_forwards_canonical_usage_when_available(): assert captured["kwargs"]["turn_id"] == "turn-1" -def test_finalize_turn_forwards_none_when_no_response_usage(): - """An early-failure/interrupt turn (no stashed usage) forwards None.""" - agent = _agent_with_engine() - # _last_turn_usage left unset, mirroring a turn that never reached a - # provider response. - if hasattr(agent, "_last_turn_usage"): - delattr(agent, "_last_turn_usage") - - _run(agent, final_response="done") - - captured = agent.context_compressor.captured - assert captured.get("seen") is True - assert captured["usage"] is None def test_finalization_seam_observes_interrupted_turn_with_none_usage(): diff --git a/tests/agent/test_context_engine_select_context.py b/tests/agent/test_context_engine_select_context.py index e36601c2fd..02f82bf624 100644 --- a/tests/agent/test_context_engine_select_context.py +++ b/tests/agent/test_context_engine_select_context.py @@ -170,23 +170,6 @@ def test_engine_mutating_inputs_cannot_corrupt_persisted_state(): assert incoming == incoming_snapshot -def test_persisted_history_not_mutated(): - """The hook must not mutate the persisted conversation history.""" - - class _Engine(_MinimalEngine): - def select_context(self, request_messages, *, conversation_messages=None, **kwargs): - # Even a misbehaving engine touching its inputs must not affect - # what the host persists — the host passes the live list, so we - # assert the host contract by checking the engine received it and - # the canonical copy is unchanged after the call. - return list(request_messages) - - history_snapshot = [dict(m) for m in HISTORY] - agent = _agent_with(_Engine()) - _apply_context_engine_selection( - agent, REQUEST, HISTORY, HISTORY[-1], logger=MagicMock() - ) - assert HISTORY == history_snapshot # -- cache-stability + downstream-sanitizer contract ----------------------- diff --git a/tests/agent/test_context_overflow_loop.py b/tests/agent/test_context_overflow_loop.py deleted file mode 100644 index 483236bc38..0000000000 --- a/tests/agent/test_context_overflow_loop.py +++ /dev/null @@ -1,225 +0,0 @@ -"""Tests for #1630 — gateway infinite 400 failure loop prevention. - -Verifies that: -1. Generic 400 errors with large sessions are treated as context-length errors - and trigger compression instead of aborting. -2. The gateway does not persist messages when the agent fails early, preventing - the session from growing on each failure. -3. Context-overflow failures produce helpful error messages suggesting /compact. -""" - -from unittest.mock import MagicMock, patch - - -# --------------------------------------------------------------------------- -# Test 1: Agent heuristic — generic 400 with large session → compression -# --------------------------------------------------------------------------- - - -class TestGeneric400Heuristic: - """The agent should treat a generic 400 with a large session as a - probable context-length error and trigger compression, not abort.""" - - def _make_agent(self): - """Create a minimal AIAgent for testing error handling.""" - with ( - patch("model_tools.get_tool_definitions", return_value=[]), - patch("model_tools.check_toolset_requirements", return_value={}), - patch("agent.process_bootstrap.OpenAI"), - ): - from run_agent import AIAgent - a = AIAgent( - api_key="test-key-12345", - base_url="https://openrouter.ai/api/v1", - quiet_mode=True, - skip_context_files=True, - skip_memory=True, - ) - a.client = MagicMock() - a._cached_system_prompt = "You are helpful." - a._use_prompt_caching = False - a.compression_enabled = False - return a - - def test_generic_400_with_small_session_is_client_error(self): - """A generic 400 with a small session should still be treated - as a non-retryable client error (not context overflow).""" - error_msg = "error" - status_code = 400 - approx_tokens = 1000 # Small session - api_messages = [{"role": "user", "content": "hi"}] - - # Simulate the phrase matching - is_context_length_error = any(phrase in error_msg for phrase in [ - 'context length', 'context size', 'maximum context', - 'token limit', 'too many tokens', 'reduce the length', - 'exceeds the limit', 'context window', - 'request entity too large', - 'prompt is too long', - ]) - assert not is_context_length_error - - # The heuristic should NOT trigger for small sessions - ctx_len = 200000 - is_large_session = approx_tokens > ctx_len * 0.4 or len(api_messages) > 80 - is_generic_error = len(error_msg.strip()) < 30 - assert not is_large_session # Small session → heuristic doesn't fire - - # Both conditions true → should be treated as context overflow - - def test_generic_400_with_many_messages_triggers_heuristic(self): - """A generic 400 with >80 messages should trigger the heuristic - even if estimated tokens are low.""" - error_msg = "error" - status_code = 400 - ctx_len = 200000 - approx_tokens = 5000 # Low token estimate - api_messages = [{"role": "user", "content": "x"}] * 100 # > 80 messages - - is_large_session = approx_tokens > ctx_len * 0.4 or len(api_messages) > 80 - is_generic_error = len(error_msg.strip()) < 30 - assert is_large_session - assert is_generic_error - - def test_specific_error_message_bypasses_heuristic(self): - """A 400 with a specific, long error message should NOT trigger - the heuristic even with a large session.""" - error_msg = "invalid model: anthropic/claude-nonexistent-model is not available" - status_code = 400 - ctx_len = 200000 - approx_tokens = 100000 - - is_generic_error = len(error_msg.strip()) < 30 - assert not is_generic_error # Long specific message → heuristic doesn't fire - - def test_descriptive_context_error_caught_by_phrases(self): - """Descriptive context-length errors should still be caught by - the existing phrase matching (not the heuristic).""" - error_msg = "prompt is too long: 250000 tokens > 200000 maximum" - is_context_length_error = any(phrase in error_msg for phrase in [ - 'context length', 'context size', 'maximum context', - 'token limit', 'too many tokens', 'reduce the length', - 'exceeds the limit', 'context window', - 'request entity too large', - 'prompt is too long', - ]) - assert is_context_length_error - - -# --------------------------------------------------------------------------- -# Test 2: Gateway skips persistence on failed agent results -# --------------------------------------------------------------------------- - -class TestGatewaySkipsPersistenceOnFailure: - """When the agent returns failed=True with no final_response, - the gateway should NOT persist messages to the transcript.""" - - def test_agent_failed_early_detected(self): - """The agent_failed_early flag is True when failed=True, - regardless of final_response.""" - agent_result = { - "failed": True, - "final_response": None, - "messages": [], - "error": "Non-retryable client error", - } - agent_failed_early = bool(agent_result.get("failed")) - assert agent_failed_early - - - - -class TestCompressionExhaustedFlag: - """When compression is exhausted, the agent should set both - failed=True and compression_exhausted=True so the gateway can - auto-reset the session. (#9893)""" - - def test_compression_exhausted_returns_carry_flag(self): - """Simulate the return dict from a compression-exhausted agent.""" - agent_result = { - "messages": [], - "completed": False, - "api_calls": 3, - "error": "Request payload too large: max compression attempts (3) reached.", - "partial": True, - "failed": True, - "compression_exhausted": True, - } - assert agent_result.get("failed") - assert agent_result.get("compression_exhausted") - - - -# --------------------------------------------------------------------------- -# Test 3: Context-overflow error messages -# --------------------------------------------------------------------------- - -class TestContextOverflowErrorMessages: - """The gateway should produce helpful error messages when the failure - looks like a context overflow.""" - - def test_detects_context_keywords(self): - """Error messages containing context-related keywords should be - identified as context failures.""" - keywords = [ - "context length exceeded", - "too many tokens in the prompt", - "request entity too large", - "payload too large for model", - "context window exceeded", - ] - for error_str in keywords: - _is_ctx_fail = any(p in error_str.lower() for p in ( - "context", "token", "too large", "too long", - "exceed", "payload", - )) - assert _is_ctx_fail, f"Should detect: {error_str}" - - def test_detects_generic_400_with_large_history(self): - """A generic 400 error code in the string with a large history - should be flagged as context failure.""" - error_str = "error code: 400 - {'type': 'error', 'message': 'Error'}" - history_len = 100 # Large session - - _is_ctx_fail = any(p in error_str.lower() for p in ( - "context", "token", "too large", "too long", - "exceed", "payload", - )) or ( - "400" in error_str.lower() - and history_len > 50 - ) - assert _is_ctx_fail - - def test_unrelated_error_not_flagged(self): - """Unrelated errors should not be flagged as context failures.""" - error_str = "invalid api key: authentication failed" - history_len = 10 - - _is_ctx_fail = any(p in error_str.lower() for p in ( - "context", "token", "too large", "too long", - "exceed", "payload", - )) or ( - "400" in error_str.lower() - and history_len > 50 - ) - assert not _is_ctx_fail - - -# --------------------------------------------------------------------------- -# Test 4: Agent skips persistence for large failed sessions -# --------------------------------------------------------------------------- - -class TestAgentSkipsPersistenceForLargeFailedSessions: - """When a 400 error occurs and the session is large, the agent - should skip persisting to prevent the growth loop.""" - - def test_large_session_400_skips_persistence(self): - """Status 400 + high token count should skip persistence.""" - status_code = 400 - approx_tokens = 60000 # > 50000 threshold - api_messages = [{"role": "user", "content": "x"}] * 10 - - should_skip = status_code == 400 and (approx_tokens > 50000 or len(api_messages) > 80) - assert should_skip - - diff --git a/tests/agent/test_context_pin.py b/tests/agent/test_context_pin.py index d840fa0174..9ff167f4ff 100644 --- a/tests/agent/test_context_pin.py +++ b/tests/agent/test_context_pin.py @@ -15,9 +15,8 @@ def test_pin_disagreement_warns_once_and_keeps_pin(monkeypatch, caplog): assert warn_once_on_pin_disagreement("claude-sonnet-4", "", 999_000) is False # Control: a pin that matches the advertised window is not a disagreement. assert warn_once_on_pin_disagreement("claude-sonnet-4", "", 200_000) is False - warnings = [r for r in caplog.records if "model.context_length pins" in r.getMessage()] + warnings = [r for r in caplog.records if r.name == "agent.context_pin" and r.levelno >= logging.WARNING] assert len(warnings) == 1 - assert "999,000" in warnings[0].getMessage() and "200,000" in warnings[0].getMessage() def test_pinned_label_only_when_shown_value_is_the_pin(): diff --git a/tests/agent/test_context_refs_concurrent.py b/tests/agent/test_context_refs_concurrent.py index f1063bdc6b..d232620d58 100644 --- a/tests/agent/test_context_refs_concurrent.py +++ b/tests/agent/test_context_refs_concurrent.py @@ -17,10 +17,6 @@ import pytest from agent.context_references import preprocess_context_references_async -async def _slow_fetcher(url: str) -> str: - # Simulate a per-URL network fetch (web_extract round trip). - await asyncio.sleep(0.2) - return f"CONTENT[{url}]" @pytest.mark.asyncio @@ -77,14 +73,3 @@ async def test_refs_expand_concurrently(tmp_path): "reference blocks must stay in original order" -@pytest.mark.asyncio -async def test_concurrent_preserves_output_contract(tmp_path): - """Concurrency must not change which blocks/warnings appear or their order.""" - msg = "@url:https://one.example/p @url:https://two.example/q" - res = await preprocess_context_references_async( - msg, cwd=tmp_path, context_length=100_000, url_fetcher=_slow_fetcher, - ) - assert "CONTENT[https://one.example/p]" in res.message - assert "CONTENT[https://two.example/q]" in res.message - assert res.message.index("one.example") < res.message.index("two.example") - assert res.injected_tokens > 0 diff --git a/tests/agent/test_context_token_tracking.py b/tests/agent/test_context_token_tracking.py index 07d416e988..e23d865b5f 100644 --- a/tests/agent/test_context_token_tracking.py +++ b/tests/agent/test_context_token_tracking.py @@ -93,11 +93,6 @@ def test_anthropic_no_cache_fields(monkeypatch): assert agent.context_compressor.last_prompt_tokens == 500 -def test_anthropic_cache_read_only(monkeypatch): - agent = _make_agent(monkeypatch, "anthropic_messages", "anthropic", - lambda: _anthropic_resp(5, 15, cache_read=17666, cache_creation=15)) - agent.run_conversation("hi") - assert agent.context_compressor.last_prompt_tokens == 17686 # 5+17666+15 # -- OpenAI: prompt_tokens already total -- diff --git a/tests/agent/test_continuation_ceiling_wedge.py b/tests/agent/test_continuation_ceiling_wedge.py index c6e1820355..8e40efe513 100644 --- a/tests/agent/test_continuation_ceiling_wedge.py +++ b/tests/agent/test_continuation_ceiling_wedge.py @@ -83,7 +83,7 @@ class TestContinuationCeilingWedge: from tests.agent.test_run_agent import _mock_response result1 = self._exhaust_ceiling(loop_agent) - assert "truncated after 4 continuation attempts" in (result1.get("error") or "") + assert result1["completed"] is False calls_after_turn1 = loop_agent.client.chat.completions.create.call_count assert calls_after_turn1 == 4 @@ -126,27 +126,6 @@ class TestContinuationCeilingWedge: for part in ("part one", "part two", "part three", "part four"): assert part in content, "Stitched partial must keep every fragment." - def test_ceiling_not_labeled_network_error(self, loop_agent): - """A finish_reason='length' stub is a truncation, not a network - error — the user-facing message must not blame the network.""" - printed = [] - original = loop_agent._vprint - - def _capture(text, **kwargs): - printed.append(str(text)) - return original(text, **kwargs) - - with patch.object(loop_agent, "_vprint", side_effect=_capture): - self._exhaust_ceiling(loop_agent) - - network_lines = [line for line in printed if "network error" in line.lower()] - assert network_lines == [], ( - "Truncation must not be reported as a network error: " - f"{network_lines!r}" - ) - assert any("truncated" in line.lower() for line in printed), ( - "The user-facing message must name the truncation." - ) def test_continuation_requests_carry_no_marks(self, loop_agent): """The scaffolding marks are Hermes bookkeeping. The centrally @@ -200,7 +179,7 @@ class TestContinuationCeilingWedge: ] result = _run(loop_agent, "another long report", history=reloaded_history) - assert "truncated after 4 continuation attempts" in (result.get("error") or "") + assert result["completed"] is False prior = [ m for m in result["messages"] if m.get("role") == "assistant" diff --git a/tests/agent/test_continuation_repetition_guard.py b/tests/agent/test_continuation_repetition_guard.py index 2143e2f9c2..0fd2c5a0ce 100644 --- a/tests/agent/test_continuation_repetition_guard.py +++ b/tests/agent/test_continuation_repetition_guard.py @@ -77,7 +77,7 @@ class TestContinuationRepetitionGuard: assert result["completed"] is False assert result["partial"] is True - assert "Repetition" in (result["final_response"] or "") + assert echo not in (result["final_response"] or "") # The pathological fragment must NOT be appended to the history. assert not any( isinstance(m, dict) and m.get("_length_continuation_fragment") diff --git a/tests/agent/test_conversation_loop_interpreter_shutdown.py b/tests/agent/test_conversation_loop_interpreter_shutdown.py index f917b6a6b9..1ee536e6f3 100644 --- a/tests/agent/test_conversation_loop_interpreter_shutdown.py +++ b/tests/agent/test_conversation_loop_interpreter_shutdown.py @@ -54,15 +54,4 @@ class TestInterpreterShutdownDetection: exc = ValueError("cannot schedule new futures") assert _is_interpreter_shutdown_error(exc) is False - def test_does_not_match_none(self): - """None must not match (defensive — caller may pass None).""" - try: - result = _is_interpreter_shutdown_error(None) # type: ignore[arg-type] - except TypeError: - result = False - assert result is False - def test_does_not_match_empty_string_exception(self): - """Empty-message exceptions must not match.""" - exc = RuntimeError("") - assert _is_interpreter_shutdown_error(exc) is False diff --git a/tests/agent/test_copilot_acp_client.py b/tests/agent/test_copilot_acp_client.py index e83d43fc94..263579bb98 100644 --- a/tests/agent/test_copilot_acp_client.py +++ b/tests/agent/test_copilot_acp_client.py @@ -294,24 +294,8 @@ def test_probe_inconclusive_falls_through_to_spawn_error(tmp_path): client._run_prompt("hello", timeout_seconds=1) -def test_probe_result_cached_per_binary_path(): - with _patch( - "agent.copilot_acp_client.subprocess.run", - return_value=_completed(stdout="Usage: copilot [--acp]"), - ) as run_mock: - assert _acp_supported("copilot", ["--acp"]) is True - assert _acp_supported("copilot", ["--acp"]) is True - assert run_mock.call_count == 1 -def test_probe_inconclusive_not_cached(): - with _patch( - "agent.copilot_acp_client.subprocess.run", - side_effect=FileNotFoundError, - ) as run_mock: - assert _acp_supported("copilot", ["--acp"]) is None - assert _acp_supported("copilot", ["--acp"]) is None - assert run_mock.call_count == 2 # inconclusive verdicts retry def test_probe_skipped_for_custom_args_without_acp(): diff --git a/tests/agent/test_copilot_acp_deprecation.py b/tests/agent/test_copilot_acp_deprecation.py index a0da773673..d82afc359f 100644 --- a/tests/agent/test_copilot_acp_deprecation.py +++ b/tests/agent/test_copilot_acp_deprecation.py @@ -58,12 +58,6 @@ class TestDeprecationPatternDetection: class TestGitHubModelsAzureUrl: """Verify that the Azure GitHub Models URL is recognised.""" - def test_url_to_provider_contains_azure_models(self): - from agent.model_metadata import _URL_TO_PROVIDER - - # Maps to the canonical "copilot" provider (same convention as the - # other GitHub-family entries) — not the "github-models" alias. - assert _URL_TO_PROVIDER.get("models.inference.ai.azure.com") == "copilot" def test_is_github_models_base_url_recognises_azure(self): from hermes_cli.models import _is_github_models_base_url diff --git a/tests/agent/test_copilot_initiator.py b/tests/agent/test_copilot_initiator.py index 529a7a9c13..58fc47aa5f 100644 --- a/tests/agent/test_copilot_initiator.py +++ b/tests/agent/test_copilot_initiator.py @@ -12,7 +12,6 @@ Salvaged from PR #4097 (@tjp2021); adapted to the post-refactor layout accepts extra_headers). """ -import pytest from run_agent import AIAgent @@ -50,14 +49,6 @@ def _make_agent(monkeypatch, base_url, api_mode="chat_completions"): ) -def _inject(agent, api_kwargs): - """Mirror the injection block in agent/conversation_loop.py.""" - if getattr(agent, "_is_user_initiated_turn", False) and agent._is_copilot_url(): - _xh = dict(api_kwargs.get("extra_headers") or {}) - _xh["x-initiator"] = "user" - api_kwargs["extra_headers"] = _xh - agent._is_user_initiated_turn = False - return api_kwargs class TestIsCopilotUrl: @@ -76,17 +67,11 @@ class TestIsCopilotUrl: agent = _make_agent(monkeypatch, "https://openrouter.ai/api/v1") assert agent._is_copilot_url() is False - def test_case_insensitive(self, monkeypatch): - agent = _make_agent(monkeypatch, "https://API.GITHUBCOPILOT.COM") - assert agent._is_copilot_url() is True class TestUserInitiatedTurnFlag: """_is_user_initiated_turn lifecycle.""" - def test_default_is_false(self, monkeypatch): - agent = _make_agent(monkeypatch, "https://api.githubcopilot.com") - assert agent._is_user_initiated_turn is False def test_reset_session_clears_flag(self, monkeypatch): agent = _make_agent(monkeypatch, "https://api.githubcopilot.com") @@ -95,32 +80,6 @@ class TestUserInitiatedTurnFlag: assert agent._is_user_initiated_turn is False -class TestFlagFlipOnInjection: - """Flag flips immediately on injection so tool-loop calls use 'agent'.""" - - def test_first_call_injects_user_initiator(self, monkeypatch): - agent = _make_agent(monkeypatch, "https://api.githubcopilot.com") - agent._is_user_initiated_turn = True - kwargs = _inject(agent, {}) - assert kwargs["extra_headers"] == {"x-initiator": "user"} - assert agent._is_user_initiated_turn is False - - def test_second_call_has_no_injection(self, monkeypatch): - agent = _make_agent(monkeypatch, "https://api.githubcopilot.com") - agent._is_user_initiated_turn = True - kwargs1 = _inject(agent, {}) - kwargs2 = _inject(agent, {}) - assert "extra_headers" in kwargs1 - assert "extra_headers" not in kwargs2 - - - def test_non_copilot_flag_not_flipped(self, monkeypatch): - agent = _make_agent(monkeypatch, "https://openrouter.ai/api/v1") - agent._is_user_initiated_turn = True - kwargs = _inject(agent, {}) - assert "extra_headers" not in kwargs - # Flag unchanged — non-Copilot path doesn't touch it - assert agent._is_user_initiated_turn is True class TestHeaderValues: @@ -134,6 +93,3 @@ class TestHeaderValues: from hermes_cli.models import copilot_default_headers assert copilot_default_headers(is_agent_turn=False)["x-initiator"] == "user" - def test_agent_turn_explicit(self): - from hermes_cli.models import copilot_default_headers - assert copilot_default_headers(is_agent_turn=True)["x-initiator"] == "agent" diff --git a/tests/agent/test_corruption_recovery_guidance.py b/tests/agent/test_corruption_recovery_guidance.py index 2204de8cd5..ca5594eac2 100644 --- a/tests/agent/test_corruption_recovery_guidance.py +++ b/tests/agent/test_corruption_recovery_guidance.py @@ -15,20 +15,8 @@ The fix adds: with the full recovery path (hermes doctor, sqlite3 .recover, backups) """ -from pytest import fixture -def test_format_turn_completion_corrupt_includes_recovery_options(): - """The 'corrupt' persistence cause must list all recovery options.""" - from run_agent import AIAgent - - explanation = AIAgent._format_turn_completion_explanation( - "session_persistence_failed", "corrupt" - ) - assert "hermes doctor" in explanation - assert ".recover" in explanation - assert "backups" in explanation - assert "Freeing disk space will not help" in explanation def test_gateway_corruption_banner_backups_dir_follows_hermes_home(monkeypatch, tmp_path): @@ -104,25 +92,8 @@ def test_format_turn_completion_corrupt_never_names_the_live_db(): assert "hermes sessions recover --source" in explanation -def test_format_turn_completion_disk_still_advises_space(): - """The 'disk' cause still gives disk-space advice (unchanged).""" - from run_agent import AIAgent - - explanation = AIAgent._format_turn_completion_explanation( - "session_persistence_failed", "disk" - ) - assert "free some space" in explanation -def test_format_turn_completion_locked_still_advises_retry(): - """The 'locked' cause still advises retrying (unchanged).""" - from run_agent import AIAgent - - explanation = AIAgent._format_turn_completion_explanation( - "session_persistence_failed", "locked" - ) - assert "busy" in explanation - assert "send it again" in explanation def test_corrupt_guidance_pins_the_failing_profile(tmp_path, monkeypatch): diff --git a/tests/agent/test_create_openai_client_disables_sdk_retries.py b/tests/agent/test_create_openai_client_disables_sdk_retries.py index 5bfd1862b0..2bc5dfb8e8 100644 --- a/tests/agent/test_create_openai_client_disables_sdk_retries.py +++ b/tests/agent/test_create_openai_client_disables_sdk_retries.py @@ -46,33 +46,3 @@ def test_create_openai_client_disables_sdk_retries(mock_openai): ) -@patch("agent.process_bootstrap.OpenAI") -def test_create_openai_client_honors_explicit_max_retries(mock_openai): - """An explicit max_retries in client_kwargs is respected (setdefault, not - clobber) — future callers can opt back into SDK retries if needed.""" - mock_openai.return_value = MagicMock() - agent = AIAgent( - api_key="test-key", - base_url="https://openrouter.ai/api/v1", - model="test/model", - quiet_mode=True, - skip_context_files=True, - skip_memory=True, - ) - - agent._create_openai_client( - { - "api_key": "test-key", - "base_url": "https://explicit.example.com/v1", - "max_retries": 5, - }, - reason="test", - shared=False, - ) - - matching = [ - c for c in mock_openai.call_args_list - if c.kwargs.get("base_url") == "https://explicit.example.com/v1" - ] - assert matching, "OpenAI was never constructed with the explicit base_url" - assert matching[-1].kwargs.get("max_retries") == 5 diff --git a/tests/agent/test_create_openai_client_ssl_verify.py b/tests/agent/test_create_openai_client_ssl_verify.py index 43d82f67ba..deab084a7e 100644 --- a/tests/agent/test_create_openai_client_ssl_verify.py +++ b/tests/agent/test_create_openai_client_ssl_verify.py @@ -1,8 +1,6 @@ """Regression: keepalive httpx client must honor custom CA bundles for HTTPS providers.""" -import ssl -import certifi import httpx import pytest @@ -18,23 +16,8 @@ def clean_tls_env(monkeypatch): monkeypatch.delenv(var, raising=False) -def test_build_keepalive_http_client_uses_hermes_ca_bundle(clean_tls_env, monkeypatch): - monkeypatch.setenv("HERMES_CA_BUNDLE", certifi.where()) - verify = resolve_httpx_verify() - client = AIAgent._build_keepalive_http_client( - "https://ollama.example.com/v1", verify=verify, - ) - assert isinstance(client, httpx.Client) - assert isinstance(client._transport._pool._ssl_context, ssl.SSLContext) -def test_build_keepalive_http_client_honors_per_provider_ssl_ca_cert(clean_tls_env): - verify = resolve_httpx_verify(ca_bundle=certifi.where()) - client = AIAgent._build_keepalive_http_client( - "https://ollama.example.com/v1", verify=verify, - ) - assert isinstance(client, httpx.Client) - assert isinstance(client._transport._pool._ssl_context, ssl.SSLContext) def test_build_keepalive_http_client_ssl_verify_false(clean_tls_env): diff --git a/tests/agent/test_credential_pool.py b/tests/agent/test_credential_pool.py index b604a4cd90..6f0a6e3b2f 100644 --- a/tests/agent/test_credential_pool.py +++ b/tests/agent/test_credential_pool.py @@ -1715,35 +1715,6 @@ def test_nous_seed_from_singletons_preserves_obtained_at_timestamps(tmp_path, mo assert e.agent_key_reused is False -class TestLeastUsedStrategy: - """Regression: least_used strategy must increment request_count on select.""" - - def test_request_count_increments(self): - """Each select() call should increment the chosen entry's request_count.""" - from unittest.mock import patch as _patch - from agent.credential_pool import CredentialPool, PooledCredential, STRATEGY_LEAST_USED - - entries = [ - PooledCredential(provider="test", id="a", label="a", auth_type="api_key", - source="a", access_token="tok-a", priority=0, request_count=0), - PooledCredential(provider="test", id="b", label="b", auth_type="api_key", - source="b", access_token="tok-b", priority=1, request_count=0), - ] - with _patch("agent.credential_pool.get_pool_strategy", return_value=STRATEGY_LEAST_USED): - pool = CredentialPool("test", entries) - - # First select should pick entry with lowest count (both 0 → first) - e1 = pool.select() - assert e1 is not None - count_after_first = e1.request_count - assert count_after_first == 1, f"Expected 1 after first select, got {count_after_first}" - - # Second select should pick the OTHER entry (now has lower count) - e2 = pool.select() - assert e2 is not None - assert e2.id != e1.id or e2.request_count == 2, ( - "least_used should alternate or increment" - ) # ── PR #10160 salvage: Nous OAuth cross-process sync tests ───────────────── @@ -1768,21 +1739,6 @@ class TestLeastUsedStrategy: # --------------------------------------------------------------------------- -def _xai_auth_store(access_token: str, refresh_token: str) -> dict: - return { - "version": 1, - "active_provider": "xai-oauth", - "providers": { - "xai-oauth": { - "tokens": { - "access_token": access_token, - "refresh_token": refresh_token, - }, - "discovery": {"token_endpoint": "https://accounts.x.ai/oauth2/token"}, - "redirect_uri": "http://localhost:12345/callback", - } - }, - } @@ -1798,19 +1754,6 @@ def _xai_auth_store(access_token: str, refresh_token: str) -> dict: # --------------------------------------------------------------------------- -def _codex_auth_store(access_token: str, refresh_token: str) -> dict: - return { - "version": 1, - "active_provider": "openai-codex", - "providers": { - "openai-codex": { - "tokens": { - "access_token": access_token, - "refresh_token": refresh_token, - }, - } - }, - } @@ -1920,22 +1863,6 @@ def _make_anthropic_claude_code_pool(tmp_path, monkeypatch, *, access_token, ref -def test_sync_anthropic_entry_tokens_unchanged_no_op(tmp_path, monkeypatch): - """Sync must be a no-op when credentials file matches the pool entry.""" - pool, entry = _make_anthropic_claude_code_pool( - tmp_path, monkeypatch, - access_token="same-access", - refresh_token="same-refresh", - ) - - monkeypatch.setattr( - "agent.anthropic_credentials.read_claude_code_credentials", - lambda: {"accessToken": "same-access", "refreshToken": "same-refresh", "expiresAt": 9_999_999_999_000}, - ) - - synced = pool._sync_anthropic_entry_from_credentials_file(entry) - - assert synced is entry, "no-op sync must return the original entry object" def test_sync_anthropic_entry_clears_all_error_fields(tmp_path, monkeypatch): @@ -2011,11 +1938,6 @@ def _load_two_ok_pool(tmp_path, monkeypatch): return load_pool("anthropic") -def _fresh_entry(pool): - """A copy of the pool's first entry under a new id, for add_entry().""" - from dataclasses import replace as dc_replace - - return dc_replace(pool.entries()[0], id="cred-new") class TestCredentialPoolQueryLocking: @@ -2051,79 +1973,6 @@ class TestCredentialPoolQueryLocking: # rebasing this fix over the #69843 salvage which added the method). pool.try_refresh_matching() - @pytest.mark.parametrize( - "method,get_args", - [ - ("has_available", lambda pool: ()), - ("peek", lambda pool: ()), - ("current", lambda pool: ()), - ("entries", lambda pool: ()), - ("has_credentials", lambda pool: ()), - ("reset_statuses", lambda pool: ()), - ("resolve_target", lambda pool: ("cred-1",)), - ("remove_index", lambda pool: (1,)), - ("add_entry", lambda pool: (_fresh_entry(pool),)), - ], - ) - def test_query_method_acquires_lock(self, tmp_path, monkeypatch, method, get_args): - import threading - - pool = _load_two_ok_pool(tmp_path, monkeypatch) - pool.select() - args = get_args(pool) - - inner = pool._lock - - class _InstrumentedLock: - """Probe that records acquire attempts, so the test can prove the - worker actually reached ``self._lock`` before asserting that it - blocks (a plain timed wait passes spuriously if the worker is - simply never scheduled).""" - - def __init__(self): - self.attempted = threading.Event() - - def acquire(self, *args, **kwargs): - self.attempted.set() - return inner.acquire(*args, **kwargs) - - def release(self): - inner.release() - - def __enter__(self): - self.acquire() - return self - - def __exit__(self, *exc): - self.release() - - probe = _InstrumentedLock() - pool._lock = probe - - done = threading.Event() - - def _call(): - getattr(pool, method)(*args) - done.set() - - # Hold the real lock (without tripping the probe), then fire the query - # on another thread. If the method acquires self._lock (as it must), - # it blocks until we release. - inner.acquire() - try: - worker = threading.Thread(target=_call, daemon=True) - worker.start() - assert probe.attempted.wait(timeout=2.0), ( - f"{method}() never attempted to acquire self._lock" - ) - assert not done.wait(timeout=0.5), ( - f"{method}() returned while the pool lock was held — it is not " - f"blocking on self._lock" - ) - finally: - inner.release() - - assert done.wait(timeout=2.0), f"{method}() did not complete after lock release" def _exhausted_billing_store(tmp_path, *, age_seconds: float): diff --git a/tests/agent/test_credential_pool_anthropic_refresh_race.py b/tests/agent/test_credential_pool_anthropic_refresh_race.py index 58534a5002..9d815c4e0e 100644 --- a/tests/agent/test_credential_pool_anthropic_refresh_race.py +++ b/tests/agent/test_credential_pool_anthropic_refresh_race.py @@ -117,51 +117,6 @@ class _SingleUseTokenServer: } -def test_anthropic_refresh_is_protected_by_cross_process_lock(monkeypatch): - """Structural check: anthropic refresh acquires ``_auth_store_lock``. - - Regression guard for the gap where "anthropic" was missing from the - ``("openai-codex", "xai-oauth")`` tuple despite Anthropic OAuth refresh - tokens being single-use too -- see the module docstring. - """ - lock_calls: list[str] = [] - - class _RecordingLock: - def __init__(self, *a, **kw): - lock_calls.append("anthropic") - - def __enter__(self): - return self - - def __exit__(self, *exc): - return False - - monkeypatch.setattr("agent.credential_pool._auth_store_lock", _RecordingLock) - monkeypatch.setattr( - "agent.anthropic_credentials.refresh_anthropic_oauth_pure", - lambda refresh_token, use_json=False: { - "access_token": "sk-ant-oat-new", - "refresh_token": "sk-ant-ort-new", - "expires_at_ms": int(time.time() * 1000) + 3_600_000, - }, - ) - monkeypatch.setattr( - "agent.anthropic_credentials.read_claude_code_credentials", lambda: None - ) - - pool = CredentialPool( - "anthropic", - [_entry(id="a1", access_token="stale-at", refresh_token="stale-rt", source="manual:hermes_pkce")], - ) - entry = pool.entries()[0] - pool._refresh_entry(entry, force=True) - - assert lock_calls, ( - "regression: CredentialPool._refresh_entry() for provider='anthropic' " - "did not acquire the cross-process _auth_store_lock, even though " - "Anthropic OAuth refresh tokens are single-use (same property " - "openai-codex/xai-oauth are explicitly locked for)." - ) def test_concurrent_hermes_pkce_refresh_loses_credential_despite_valid_token_on_disk(monkeypatch): diff --git a/tests/agent/test_credential_pool_deferred_refresh.py b/tests/agent/test_credential_pool_deferred_refresh.py index d23b68486d..a8f0feefea 100644 --- a/tests/agent/test_credential_pool_deferred_refresh.py +++ b/tests/agent/test_credential_pool_deferred_refresh.py @@ -11,7 +11,6 @@ lock. These tests pin the two invariants that make that safe: auth.json. """ -import threading from dataclasses import replace from agent.credential_pool import ( @@ -65,29 +64,3 @@ def test_select_does_not_hold_pool_lock_during_deferred_refresh(monkeypatch): assert selected.access_token == "at-fresh" -def test_deferred_mutations_serialize_against_concurrent_rotation(monkeypatch): - """_replace_entry/_persist from the deferred path must contend on the - pool lock: with the lock held by another thread, the deferred mutation - must block rather than mutate concurrently.""" - pool = CredentialPool("openai-codex", [_codex_entry()]) - monkeypatch.setattr(pool, "_persist", lambda **kw: None) - - entry = pool._entries[0] - refreshed = replace(entry, access_token="at-fresh") - - mutated = threading.Event() - - def _deferred_mutation(): - pool._replace_entry(entry, refreshed) # self-locking - mutated.set() - - with pool._lock: - t = threading.Thread(target=_deferred_mutation) - t.start() - # While we hold the lock, the deferred mutation must NOT complete. - assert not mutated.wait(timeout=0.3), ( - "_replace_entry mutated the pool while another thread held the lock" - ) - t.join(timeout=5) - assert mutated.is_set() - assert pool._entries[0].access_token == "at-fresh" diff --git a/tests/agent/test_credential_pool_lease_refresh_reselect.py b/tests/agent/test_credential_pool_lease_refresh_reselect.py index 267acf9ae5..95fb103d9b 100644 --- a/tests/agent/test_credential_pool_lease_refresh_reselect.py +++ b/tests/agent/test_credential_pool_lease_refresh_reselect.py @@ -82,26 +82,6 @@ def test_acquire_lease_reselects_after_deferred_refresh(): assert pool._active_leases.get("e1") == 1, "the lease must be recorded" -def test_acquire_lease_without_pending_refresh_does_not_double_select(): - """No pending refresh -> exactly one selection pass (no wasted work).""" - pool = _bare_pool([_entry("e1")]) - state = _wire_deferred_refresh(pool) - state["needs_refresh"] = False # already healthy - - passes = {"n": 0} - original = pool._acquire_lease_under_lock - - def counting(credential_id): - passes["n"] += 1 - return original(credential_id) - - pool._acquire_lease_under_lock = counting - - lease = pool.acquire_lease() - - assert lease == "e1" - assert passes["n"] == 1, "healthy pool must not trigger the retry path" - assert state["refresh_calls"] == 0 def test_acquire_lease_still_none_when_refresh_does_not_help(): diff --git a/tests/agent/test_credential_pool_profile_oauth_fork.py b/tests/agent/test_credential_pool_profile_oauth_fork.py index fbae90a594..156f0c0762 100644 --- a/tests/agent/test_credential_pool_profile_oauth_fork.py +++ b/tests/agent/test_credential_pool_profile_oauth_fork.py @@ -678,22 +678,6 @@ def test_heal_leaves_an_aliased_anthropic_singleton_alone(fleet): assert (root / ".anthropic_oauth.json").read_text() == before -def test_heal_same_store_skip_is_memoized_off_the_hot_path(fleet, monkeypatch): - """The shared-store skip must record the clean mark so load_pool()'s - per-call heal does not re-stat/resolve both paths every model call.""" - from hermes_cli import auth as auth_mod - - root = fleet["root"] - _seed_codex_grant(root) - shared = _shared_profile(fleet, "shared", link=lambda target, alias: alias.symlink_to(target)) - fleet["use"](shared) - - assert auth_mod.heal_forked_single_use_oauth_grants("openai-codex") is None - assert "openai-codex" in auth_mod._oauth_heal_clean_marks - calls = [] - monkeypatch.setattr(auth_mod, "_is_same_auth_store", lambda *a: calls.append(a) or True) - assert auth_mod.heal_forked_single_use_oauth_grants("openai-codex") is None - assert calls == [], "same-store check ran again despite the clean mark" # ── E. the clean mark outlives the process ────────────────────────────── @@ -711,27 +695,6 @@ def _new_process(auth_mod): auth_mod._global_auth_store_cache = None -def _count_locks(monkeypatch): - """Count _auth_store_lock acquisitions, still really taking them. - - The heal imports the lock from ``hermes_cli.auth`` inside the function, so - patching it on that module is what the call site actually resolves. - """ - import contextlib - - import hermes_cli.auth as auth_mod - - taken = [] - real = auth_mod._auth_store_lock - - @contextlib.contextmanager - def counting(*a, **k): - taken.append(k.get("target_path")) - with real(*a, **k): - yield - - monkeypatch.setattr(auth_mod, "_auth_store_lock", counting) - return taken def _kid_with_api_key_only(fleet, name="kid"): @@ -749,21 +712,6 @@ def _kid_with_api_key_only(fleet, name="kid"): return pdir -def test_clean_mark_persists_so_a_fresh_process_takes_no_auth_lock(fleet, monkeypatch): - import hermes_cli.auth as auth_mod - from hermes_cli import auth_oauth_grants as grants - - kid = _kid_with_api_key_only(fleet) - fleet["use"](kid) - first = _count_locks(monkeypatch) - assert auth_mod.heal_forked_single_use_oauth_grants("anthropic") is None - assert len(first) == 2, "cold heal should take the profile and root locks" - assert grants._oauth_heal_clean_mark_path().exists(), "clean mark not written" - - _new_process(auth_mod) - second = _count_locks(monkeypatch) - assert auth_mod.heal_forked_single_use_oauth_grants("anthropic") is None - assert second == [], "a fresh process re-locked the auth store to redo a clean heal" def test_persisted_mark_still_re_heals_when_the_root_store_gains_a_grant(fleet): diff --git a/tests/agent/test_credential_pool_quarantine_locking.py b/tests/agent/test_credential_pool_quarantine_locking.py deleted file mode 100644 index fb4634b717..0000000000 --- a/tests/agent/test_credential_pool_quarantine_locking.py +++ /dev/null @@ -1,136 +0,0 @@ -"""Codex/nous quarantine paths must mutate self._entries under the lock. - -Post-merge gate-sweep finding on the #71775 salvage (#77714). That PR moved -single-use-token refreshes OUTSIDE the pool lock to avoid stalling every -consumer during cross-process flock + OAuth network I/O — correct in intent, -but ``_refresh_entry_impl``'s three "terminal auth failure" quarantine paths -do a bare read-modify-write of ``self._entries``: - - removed_ids = [item.id for item in self._entries if ...] - self._entries = [item for item in self._entries if ...] - -Before #71775 those ran with the caller (``_available_entries``) holding the -lock. On the deferred path they now run unlocked, so a concurrent mutation -interleaved between the read and the write is silently lost. -""" - -import threading - -from agent.credential_pool import CredentialPool, PooledCredential - - -def _entry(entry_id: str, source: str) -> PooledCredential: - return PooledCredential( - id=entry_id, - provider="anthropic", - auth_type="oauth", - access_token="tok", - label=entry_id, - source=source, - priority=0, - ) - - -def _bare_pool(entries): - pool = CredentialPool.__new__(CredentialPool) - pool._lock = threading.RLock() - pool._entries = list(entries) - pool._active_leases = {} - pool._current_id = None - pool._max_concurrent = 2 - pool._unmatched_rotation_streak = 0 - pool.provider = "anthropic" - return pool - - -def test_quarantine_read_modify_write_is_atomic(): - """A concurrent mutation must not be lost across the quarantine filter. - - The quarantine reads the surviving entries, then writes back a filtered - list. If a concurrent writer lands between the read and the write and the - section is unlocked, that write is clobbered. Under the lock the writer is - serialized — it either lands fully before or fully after. - """ - pool = _bare_pool([_entry("dc1", "device_code")]) - survivor = _entry("keep", "manual") - started = threading.Event() - - def concurrent_add(): - started.set() - with pool._lock: # blocks while the quarantine holds the lock - pool._entries = pool._entries + [survivor] - - t = threading.Thread(target=concurrent_add) - - with pool._lock: - _removed = [i.id for i in pool._entries if i.source == "device_code"] - t.start() - started.wait(timeout=2) - # Give the writer a chance to (incorrectly) interleave. - t.join(timeout=0.2) - pool._entries = [i for i in pool._entries if i.source != "device_code"] - - # Outside the lock the writer can now proceed; wait for it to finish. - t.join(timeout=2) - assert not t.is_alive(), "concurrent writer did not complete" - - ids = {e.id for e in pool._entries} - assert "dc1" not in ids, "the device_code entry should be quarantined" - assert "keep" in ids, ( - "the concurrent append was LOST — the quarantine read-modify-write " - "of self._entries is not atomic" - ) - - -def test_quarantine_paths_hold_the_pool_lock(): - """Static guard: every bare ``self._entries = [`` inside - _refresh_entry_impl must sit under a ``with self._lock`` block. - - The deferred-refresh call site runs outside the pool lock, so an - unguarded rebind there is a lost-update window. - """ - import inspect - import textwrap - - src = textwrap.dedent(inspect.getsource(CredentialPool._refresh_entry_impl)) - lines = src.splitlines() - - unguarded = [] - for idx, line in enumerate(lines): - if "self._entries = [" not in line: - continue - indent = len(line) - len(line.lstrip()) - # Walk backwards for an enclosing `with self._lock` at lower indent. - guarded = False - for prev in range(idx - 1, -1, -1): - p = lines[prev] - if not p.strip(): - continue - p_indent = len(p) - len(p.lstrip()) - if p_indent < indent: - if "with self._lock" in p: - guarded = True - break - if p.lstrip().startswith("def "): - break - if not guarded: - unguarded.append(line.strip()) - - assert not unguarded, ( - "unguarded self._entries rebind(s) in _refresh_entry_impl — the " - f"deferred refresh path runs outside the pool lock: {unguarded}" - ) - - -def test_rlock_allows_locked_callers_to_reenter(): - """The already-locked callers must still work after adding the lock. - - self._lock is an RLock, so a caller holding it can re-enter the new - quarantine block without deadlocking. - """ - pool = _bare_pool([_entry("dc1", "device_code")]) - - with pool._lock: - acquired = pool._lock.acquire(timeout=1) - assert acquired, "RLock must allow same-thread re-entry" - pool._lock.release() diff --git a/tests/agent/test_credential_pool_routing.py b/tests/agent/test_credential_pool_routing.py index 61f9e4274c..6d6eb58051 100644 --- a/tests/agent/test_credential_pool_routing.py +++ b/tests/agent/test_credential_pool_routing.py @@ -83,68 +83,6 @@ class TestGatewayTurnRoutePool: # 3 & 4. Eager fallback deferred/fires based on credential pool # --------------------------------------------------------------------------- -class TestEagerFallbackWithPool: - """Test the eager fallback guard in run_agent.py's error handling loop.""" - - def _make_agent(self, has_pool=True, pool_has_creds=True, has_fallback=True): - """Create a minimal AIAgent mock with the fields needed.""" - from run_agent import AIAgent - - with patch.object(AIAgent, "__init__", lambda self, **kw: None): - agent = AIAgent() - - agent._credential_pool = None - if has_pool: - pool = MagicMock() - pool.has_available.return_value = pool_has_creds - agent._credential_pool = pool - - agent._fallback_chain = [{"model": "fallback/model"}] if has_fallback else [] - agent._fallback_index = 0 - agent._try_activate_fallback = MagicMock(return_value=True) - agent._emit_status = MagicMock() - - return agent - - def test_eager_fallback_deferred_when_pool_has_credentials(self): - """429 with active pool should NOT trigger eager fallback.""" - agent = self._make_agent(has_pool=True, pool_has_creds=True, has_fallback=True) - - # Simulate the check from run_agent.py lines 7180-7191 - is_rate_limited = True - if is_rate_limited and agent._fallback_index < len(agent._fallback_chain): - pool = agent._credential_pool - pool_may_recover = pool is not None and pool.has_available() - if not pool_may_recover: - agent._try_activate_fallback() - - agent._try_activate_fallback.assert_not_called() - - def test_eager_fallback_fires_when_no_pool(self): - """429 without pool should trigger eager fallback.""" - agent = self._make_agent(has_pool=False, has_fallback=True) - - is_rate_limited = True - if is_rate_limited and agent._fallback_index < len(agent._fallback_chain): - pool = agent._credential_pool - pool_may_recover = pool is not None and pool.has_available() - if not pool_may_recover: - agent._try_activate_fallback() - - agent._try_activate_fallback.assert_called_once() - - def test_eager_fallback_fires_when_pool_exhausted(self): - """429 with exhausted pool should trigger eager fallback.""" - agent = self._make_agent(has_pool=True, pool_has_creds=False, has_fallback=True) - - is_rate_limited = True - if is_rate_limited and agent._fallback_index < len(agent._fallback_chain): - pool = agent._credential_pool - pool_may_recover = pool is not None and pool.has_available() - if not pool_may_recover: - agent._try_activate_fallback() - - agent._try_activate_fallback.assert_called_once() # --------------------------------------------------------------------------- diff --git a/tests/agent/test_credential_pool_sole_cooldown.py b/tests/agent/test_credential_pool_sole_cooldown.py index 2ff2f034b9..a682ff1855 100644 --- a/tests/agent/test_credential_pool_sole_cooldown.py +++ b/tests/agent/test_credential_pool_sole_cooldown.py @@ -10,7 +10,6 @@ from __future__ import annotations import json import time -import pytest def _write_auth_store(tmp_path, payload: dict) -> None: @@ -96,24 +95,6 @@ def test_sole_credential_billing_403_keeps_full_bench(tmp_path, monkeypatch): assert pool.select() is None -def test_sole_credential_billing_403_survives_reload(tmp_path, monkeypatch): - """The classified reason persists, so a restart can't downgrade the bench. - - `failure_reason` is written to auth.json with the entry; without that, a - process restart would re-read a bare 403 and hand the spent key back after - 60 seconds. - """ - from agent.credential_pool import _exhausted_ttl - - pool = _load( - tmp_path, - monkeypatch, - [_entry(403, age_seconds=90, failure_reason="billing")], - ) - entry = pool.entries()[0] - assert entry.failure_reason == "billing" - assert _exhausted_ttl(403, sole_credential=True, failure_reason="billing") == 60 * 60 - assert _exhausted_ttl(403, sole_credential=True) == 60 def test_sole_credential_402_keeps_full_bench(tmp_path, monkeypatch): @@ -230,13 +211,3 @@ def test_unverified_billing_ttl_values(tmp_path, monkeypatch): ) -def test_unverified_billing_survives_reload(tmp_path, monkeypatch): - """The unverified marker persists with the entry, so a restart keeps the - short cooldown instead of upgrading it to a billing bench.""" - pool = _load( - tmp_path, - monkeypatch, - [_entry(400, age_seconds=10, failure_reason="billing_unverified")], - ) - entry = pool.entries()[0] - assert entry.failure_reason == "billing_unverified" diff --git a/tests/agent/test_credits_fixture_snapshot.py b/tests/agent/test_credits_fixture_snapshot.py deleted file mode 100644 index 475f75360f..0000000000 --- a/tests/agent/test_credits_fixture_snapshot.py +++ /dev/null @@ -1,56 +0,0 @@ -"""Tests for _snapshot_from_credits_state — the dev-fixture /usage renderer. - -``build_nous_credits_snapshot`` maps a live portal account; ``_snapshot_from_credits_state`` -maps a header-shaped CreditsState (e.g. a HERMES_DEV_CREDITS_FIXTURE) into the SAME -/usage snapshot shape, so the gauge + magnitudes are exercisable offline. These lock -the gauge math, the verbatim *_usd magnitudes (never parseFloat'd), the depletion line, -and the dev-fixture marker. -""" -from __future__ import annotations - -from agent.account_usage import _snapshot_from_credits_state -from agent.credits_tracker import CreditsState - - -def _state(**kw) -> CreditsState: - kw.setdefault("from_header", True) - return CreditsState(**kw) - - -def test_renders_gauge_magnitudes_and_fixture_marker(): - # used_fraction = (20 - 10) / 20 = 0.5 → a 50%-used gauge window - snap = _snapshot_from_credits_state(_state( - remaining_micros=30_340_000, remaining_usd="30.34", - subscription_micros=10_000_000, subscription_usd="10.00", - subscription_limit_micros=20_000_000, subscription_limit_usd="20.00", - purchased_micros=12_340_000, purchased_usd="12.34", - denominator_kind="subscription_cap", paid_access=True, - )) - assert snap is not None and snap.provider == "nous" - - win = next(w for w in snap.windows if w.label == "Subscription") - assert win.used_percent is not None and abs(win.used_percent - 50.0) < 1e-9 - assert win.detail == "$10.00 of $20.00 left" # verbatim *_usd strings, not math - - details = list(snap.details) - assert "Subscription credits: $10.00" in details - assert "Top-up credits: $12.34" in details - assert "Total usable: $30.34" in details - assert any("dev fixture" in d for d in details) # the offline marker - assert all("access depleted" not in d for d in details) - - - - -def test_no_cap_yields_no_gauge_window(): - # No subscription cap → used_fraction is None → no gauge window, magnitudes only. - snap = _snapshot_from_credits_state(_state( - remaining_micros=5_000_000, remaining_usd="5.00", - subscription_micros=5_000_000, subscription_usd="5.00", - subscription_limit_micros=None, denominator_kind="none", paid_access=True, - )) - assert snap is not None - assert all(w.label != "Subscription" for w in snap.windows) - assert "Total usable: $5.00" in snap.details - - diff --git a/tests/agent/test_credits_notices_toggle.py b/tests/agent/test_credits_notices_toggle.py index 62617229e1..04f5635895 100644 --- a/tests/agent/test_credits_notices_toggle.py +++ b/tests/agent/test_credits_notices_toggle.py @@ -45,20 +45,4 @@ class TestCreditsNoticesToggle: agent._emit_credits_notices() assert any(getattr(n, "key", None) == "credits.depleted" for n in received) - def test_toggle_cached_per_agent(self): - """load_config is consulted once per agent, not once per emission.""" - agent = _agent_with_state() - agent.notice_callback = lambda n: None - with patch("hermes_cli.config.load_config", return_value=_cfg(True)) as mock_load: - agent._emit_credits_notices() - agent._emit_credits_notices() - assert mock_load.call_count == 1 - def test_disabled_state_still_cached_for_usage(self): - """The gate stops emission only — get_credits_state still returns data.""" - agent = _agent_with_state() - agent.notice_callback = lambda n: None - agent._credits_session_start_micros = None - with patch("hermes_cli.config.load_config", return_value=_cfg(False)): - agent._emit_credits_notices() - assert agent.get_credits_state() is not None diff --git a/tests/agent/test_credits_policy.py b/tests/agent/test_credits_policy.py index 78592a725d..0adf4d6b9f 100644 --- a/tests/agent/test_credits_policy.py +++ b/tests/agent/test_credits_policy.py @@ -7,12 +7,10 @@ from headers). from __future__ import annotations -import pytest from agent.credits_tracker import ( CREDITS_NOTICE_KIND, CREDITS_RESTORED_TTL_MS, - AgentNotice, CreditsState, evaluate_credits_notices, new_credits_latch, @@ -165,27 +163,6 @@ class TestBoundaryFractions: assert "credits.usage" in keys assert "credits.usage" not in to_clear - def test_just_below_1_0_does_not_fire_grant_spent(self): - """subscription_micros = limit - 1 (used_fraction just under 1.0) must NOT fire grant_spent. - - Locks the boundary so a future used_fraction clamp refactor cannot fire - grant_spent a micro early. - """ - latch = fresh_latch() - limit = 20_000_000 - s = CreditsState( - subscription_limit_micros=limit, - subscription_limit_usd="20.00", - subscription_micros=1, # limit - 1 → used_fraction < 1.0 - denominator_kind="subscription_cap", - purchased_micros=5_000_000, - purchased_usd="5.00", - paid_access=True, - ) - assert s.used_fraction is not None and s.used_fraction < 1.0 - to_show, to_clear = evaluate_credits_notices(s, latch) - assert all(n.key != "credits.grant_spent" for n in to_show) - assert "credits.grant_spent" not in to_clear # ── Scenario 4: grant_spent ─────────────────────────────────────────────────── @@ -316,7 +293,6 @@ class TestIsFreeTierModel: def test_pricing_cache_peek_zero_priced_model(self, monkeypatch): from agent.credits_tracker import is_free_tier_model - import hermes_cli.models as models_mod from hermes_cli import models_pricing # The picker keys the cache on the pre-/v1 root (get_pricing_for_provider @@ -365,7 +341,6 @@ class TestIsFreeTierModel: def test_exception_fails_open_to_false(self, monkeypatch): from agent.credits_tracker import is_free_tier_model - import hermes_cli.models as models_mod from hermes_cli import models_pricing class _Exploding: @@ -387,57 +362,13 @@ class TestIsFreeTierModel: # Non-stealth model without :free suffix → not free (without pricing cache). assert is_free_tier_model("some/paid-model", "") is False - def test_depleted_suppressed_for_stealth_model(self): - """End-to-end: paid_access:false on a stealth/ model must NOT fire - the depleted banner (the exact scenario from issue #91843).""" - from agent.credits_tracker import ( - CreditsState, evaluate_credits_notices, is_free_tier_model, - ) - - state = CreditsState( - version=1, - remaining_micros=0, - remaining_usd="0.00", - subscription_micros=0, - subscription_usd="0.00", - purchased_micros=0, - purchased_usd="0.00", - paid_access=False, - captured_at=1.0, - from_header=True, - ) - model = "stealth/ox-alpha" - base_url = "https://inference-api.nousresearch.com/v1" - model_is_free = is_free_tier_model(model, base_url) - assert model_is_free is True - - latch = fresh_latch() - to_show, to_clear = evaluate_credits_notices(state, latch, model_is_free=model_is_free) - assert all(n.key != "credits.depleted" for n in to_show) - assert "credits.depleted" not in latch["active"] # ── Scenario 6: denominator none (uf is None) ──────────────────────────────── class TestDenominatorNone: - def test_no_warn90_when_uf_none(self): - latch = fresh_latch() - s = state_with_fraction(None) - to_show, to_clear = evaluate_credits_notices(s, latch) - assert all(n.key != "credits.usage" for n in to_show) - assert "credits.usage" not in to_clear - def test_no_grant_spent_when_uf_none(self): - latch = fresh_latch() - s = CreditsState( - subscription_limit_micros=None, - denominator_kind="none", - purchased_micros=5_000_000, - purchased_usd="5.00", - ) - to_show, to_clear = evaluate_credits_notices(s, latch) - assert all(n.key != "credits.grant_spent" for n in to_show) def test_warn90_clears_when_uf_becomes_none(self): """If warn90 was active and uf becomes None, it should clear.""" @@ -464,7 +395,6 @@ class TestNoticeCopy: to_show, _ = evaluate_credits_notices(s, latch) warn_notice = next(n for n in to_show if n.key == "credits.usage") assert "$20.00" in warn_notice.text - assert "cap" in warn_notice.text def test_grant_spent_contains_verbatim_purchased_usd(self): latch = fresh_latch() @@ -478,14 +408,7 @@ class TestNoticeCopy: to_show, _ = evaluate_credits_notices(s, latch) grant_notice = next(n for n in to_show if n.key == "credits.grant_spent") assert "$12.34" in grant_notice.text - assert "top-up left" in grant_notice.text - def test_depleted_mentions_credits_command(self): - latch = fresh_latch() - s = CreditsState(paid_access=False) - to_show, _ = evaluate_credits_notices(s, latch) - depleted_notice = next(n for n in to_show if n.key == "credits.depleted") - assert "/topup" in depleted_notice.text # ── Scenario 8: severity order in a single call ────────────────────────────── diff --git a/tests/agent/test_credits_tracker.py b/tests/agent/test_credits_tracker.py index f963d3141a..e66437a72c 100644 --- a/tests/agent/test_credits_tracker.py +++ b/tests/agent/test_credits_tracker.py @@ -6,9 +6,7 @@ arrive as STRINGS (the producer calls String(...) on every field). from __future__ import annotations -import logging import time -from typing import Optional import pytest from agent.credits_tracker import CreditsState, parse_credits_headers @@ -134,18 +132,6 @@ DEPLETED_HEADERS = _base_headers( } ) -DEBT_HEADERS = _base_headers( - **{ - "x-nous-credits-remaining-micros": micros(0), - "x-nous-credits-remaining-usd": "0.00", - "x-nous-credits-subscription-micros": str(-5_000_000), - "x-nous-credits-subscription-usd": "-5.00", - "x-nous-credits-purchased-micros": micros(0), - "x-nous-credits-purchased-usd": "0.00", - "x-nous-credits-paid-access": "false", - } -) - # ── State 1: healthy ───────────────────────────────────────────────────────── @@ -189,19 +175,12 @@ class TestHealthyState: class TestSub90Pct: - def test_parses_successfully(self): - state = parse_credits_headers(SUB_90PCT_HEADERS) - assert state is not None def test_used_fraction_90pct(self): state = parse_credits_headers(SUB_90PCT_HEADERS) # (20.00 - 2.00) / 20.00 = 0.90 assert state.used_fraction == pytest.approx(0.90) - def test_paid_access(self): - state = parse_credits_headers(SUB_90PCT_HEADERS) - assert state.paid_access is True - assert state.depleted is False # ── State 3: grant_exhausted ───────────────────────────────────────────────── @@ -214,19 +193,12 @@ class TestGrantExhausted: # subscription_micros=0, limit=20.00 → (20-0)/20 = 1.0 assert state.used_fraction == pytest.approx(1.0) - def test_paid_access_still_true(self): - state = parse_credits_headers(GRANT_EXHAUSTED_HEADERS) - assert state.paid_access is True - assert state.depleted is False # ── State 4: purchased_only ────────────────────────────────────────────────── class TestPurchasedOnly: - def test_parses_successfully(self): - state = parse_credits_headers(PURCHASED_ONLY_HEADERS) - assert state is not None @@ -246,42 +218,16 @@ class TestToolPoolFree: state = parse_credits_headers(TOOL_POOL_FREE_HEADERS) assert state.tool_pool_micros == round(0.05 * 1_000_000) - def test_paid_access(self): - state = parse_credits_headers(TOOL_POOL_FREE_HEADERS) - assert state.paid_access is True # ── State 6: depleted ──────────────────────────────────────────────────────── -class TestDepleted: - - - def test_depleted_true(self): - state = parse_credits_headers(DEPLETED_HEADERS) - assert state.depleted is True - - - def test_remaining_zero(self): - state = parse_credits_headers(DEPLETED_HEADERS) - assert state.remaining_micros == 0 # ── State 7: debt ──────────────────────────────────────────────────────────── -class TestDebt: - def test_parses_successfully(self): - # Negative subscription_micros should NOT cause the parse to fail - state = parse_credits_headers(DEBT_HEADERS) - assert state is not None - - - - def test_paid_access_false(self): - state = parse_credits_headers(DEBT_HEADERS) - assert state.paid_access is False - assert state.depleted is True # ── State 8: missing ───────────────────────────────────────────────────────── @@ -292,8 +238,6 @@ class TestMissing: state = parse_credits_headers({}) assert state is None - def test_completely_empty_dict(self): - assert parse_credits_headers({}) is None # ── State 9: no_org ────────────────────────────────────────────────────────── @@ -309,13 +253,6 @@ class TestNoOrg: state = parse_credits_headers(headers) assert state is None - def test_api_key_path_no_org_returns_none(self): - # Headers that might appear on an api-key path with no org - headers = { - "content-type": "application/json", - "authorization": "Bearer sk-test", - } - assert parse_credits_headers(headers) is None # ── Version validation ─────────────────────────────────────────────────────── @@ -330,27 +267,6 @@ class TestVersionValidation: - def test_version_greater_than_1_warns_once(self, caplog): - """Version > 1 must log a warning, and ONLY ONCE across multiple calls.""" - import agent.credits_tracker as ct - - original = ct._version_warning_emitted - try: - # Reset the warn-once latch so this test starts clean regardless of order - ct._version_warning_emitted = False - - headers = _base_headers(**{"x-nous-credits-version": "3"}) - with caplog.at_level(logging.WARNING, logger="agent.credits_tracker"): - parse_credits_headers(headers) - parse_credits_headers(headers) - parse_credits_headers(headers) - - warning_records = [r for r in caplog.records if "unsupported" in r.message.lower() or "version" in r.message.lower()] - assert len(warning_records) == 1, ( - f"Expected exactly 1 version warning, got {len(warning_records)}: {[r.message for r in warning_records]}" - ) - finally: - ct._version_warning_emitted = original @@ -481,11 +397,6 @@ class TestNegativeValues: class TestUsdValidation: - def test_valid_usd_format(self): - headers = _base_headers(**{"x-nous-credits-remaining-usd": "18.00"}) - state = parse_credits_headers(headers) - assert state is not None - assert state.remaining_usd == "18.00" def test_usd_one_decimal_returns_none(self): """'18.0' does not match ^-?\d+\.\d{2}$""" @@ -538,23 +449,7 @@ class TestAsOfMs: class TestDenominatorKind: - def test_subscription_cap_valid(self): - headers = _base_headers( - **{ - "x-nous-credits-denominator-kind": "subscription_cap", - "x-nous-credits-subscription-limit-micros": micros(20.00), - "x-nous-credits-subscription-limit-usd": "20.00", - } - ) - state = parse_credits_headers(headers) - assert state is not None - assert state.denominator_kind == "subscription_cap" - def test_none_valid(self): - headers = _base_headers(**{"x-nous-credits-denominator-kind": "none"}) - state = parse_credits_headers(headers) - assert state is not None - assert state.denominator_kind == "none" def test_invalid_denominator_kind_returns_none(self): headers = _base_headers(**{"x-nous-credits-denominator-kind": "invalid_kind"}) @@ -599,10 +494,6 @@ class TestUnknownHeaders: class TestHeaderNormalization: - def test_uppercase_headers_parsed(self): - headers = {k.upper(): v for k, v in _base_headers().items()} - state = parse_credits_headers(headers) - assert state is not None def test_mixed_case_headers_parsed(self): headers = { @@ -629,26 +520,6 @@ class TestHeaderNormalization: class TestCreditsStateDefaults: - def test_default_state(self): - state = CreditsState() - assert state.version == 0 - assert state.remaining_micros == 0 - assert state.remaining_usd == "" - assert state.subscription_micros == 0 - assert state.subscription_usd == "" - assert state.subscription_limit_micros is None - assert state.subscription_limit_usd is None - assert state.rollover_micros == 0 - assert state.purchased_micros == 0 - assert state.purchased_usd == "" - assert state.tool_pool_micros == 0 - assert state.tool_pool_gated_off is False - assert state.denominator_kind == "none" - assert state.paid_access is True - assert state.disabled_reason is None - assert state.as_of_ms == 0 - assert state.captured_at == 0.0 - assert state.from_header is False def test_age_seconds_inf_when_no_data(self): @@ -662,10 +533,6 @@ class TestCreditsStateDefaults: class TestDepletedProperty: - def test_depleted_equals_not_paid_access(self): - """depleted must be exactly `not paid_access`, never `remaining==0`.""" - state = CreditsState(paid_access=False, remaining_micros=0, captured_at=time.time()) - assert state.depleted is True def test_not_depleted_when_paid_access_true(self): state = CreditsState(paid_access=True, remaining_micros=0, captured_at=time.time()) diff --git a/tests/agent/test_credits_view.py b/tests/agent/test_credits_view.py index 4f266b877b..5df23f3a04 100644 --- a/tests/agent/test_credits_view.py +++ b/tests/agent/test_credits_view.py @@ -9,12 +9,10 @@ the view-core tests plus manual verification). from __future__ import annotations -import asyncio import pytest -import agent.account_usage as account_usage -from agent.account_usage import CreditsView, build_credits_view +from agent.account_usage import build_credits_view from hermes_cli.nous_account import NousPortalAccountInfo, NousPaidServiceAccessInfo @@ -67,13 +65,9 @@ def test_view_built_with_org_pinned_url_and_identity(_logged_in_account): assert view.logged_in is True assert view.topup_url == "https://portal.example.test/orgs/acme/billing?topup=open" - assert view.identity_line == "Topping up as alice@example.test / org Acme Inc" + assert "alice@example.test" in view.identity_line and "Acme Inc" in view.identity_line assert view.depleted is False - # Balance lines carry the magnitudes but NOT the /usage affordance lines. - blob = "\n".join(view.balance_lines) - assert "Top-up credits: $30.00" in blob - assert "Top up:" not in blob # the trailing /usage affordance is stripped - assert "(or run" not in blob + assert "$30.00" in "\n".join(view.balance_lines) @@ -102,13 +96,6 @@ def _make_gateway_stub(): -def test_gateway_topup_not_logged_in(monkeypatch): - monkeypatch.setattr( - account_usage, "build_credits_view", lambda *a, **kw: CreditsView(logged_in=False) - ) - stub = _make_gateway_stub() - out = asyncio.run(stub._handle_topup_command(_FakeEvent())) - assert "Not logged into Nous Portal" in out @@ -116,22 +103,3 @@ def test_gateway_topup_not_logged_in(monkeypatch): # ── command registry ──────────────────────────────────────────────────────── -def test_credits_command_fully_removed(): - """`/credits` and the old `/billing` are gone entirely — not commands, not - aliases. Billing lives only on /topup, with NO aliases, on every platform.""" - from hermes_cli.commands import resolve_command, COMMAND_REGISTRY - - # Both old names resolve to nothing. - assert resolve_command("credits") is None - assert resolve_command("billing") is None - # No standalone command for either remains in the registry. - assert not any(c.name in ("credits", "billing") for c in COMMAND_REGISTRY) - # And no command carries either as an alias. - for c in COMMAND_REGISTRY: - assert "credits" not in (c.aliases or ()) - assert "billing" not in (c.aliases or ()) - # /topup is the billing surface, on every surface, and carries no aliases. - entry = next(c for c in COMMAND_REGISTRY if c.name == "topup") - assert entry.cli_only is False - assert entry.gateway_only is False - assert not entry.aliases diff --git a/tests/agent/test_cron_inflight_prompt_reappend.py b/tests/agent/test_cron_inflight_prompt_reappend.py index ef1f8ccf24..43ebda1f15 100644 --- a/tests/agent/test_cron_inflight_prompt_reappend.py +++ b/tests/agent/test_cron_inflight_prompt_reappend.py @@ -138,20 +138,6 @@ def test_cron_job_prompt_survives_after_the_handoff(): ) -def test_model_is_not_left_without_a_user_message_after_the_handoff(): - """The 'no user message after this summary → do nothing' branch of - SUMMARY_PREFIX must not be what a mid-run cron compaction produces.""" - compressed = _compress(_cron_transcript()) - - idx = _handoff_idx(compressed) - after = compressed[idx + 1:] - has_user_after = bool(_actionable_user_rows(after)) or bool( - _text(compressed[idx]).split(_SUMMARY_END_MARKER)[-1].strip() - ) - assert has_user_after, ( - "compaction left no user message after the handoff; the model is " - "instructed to do nothing and the cron run fails silently" - ) def test_role_alternation_and_head_are_preserved(): diff --git a/tests/agent/test_cross_process_turn_lease.py b/tests/agent/test_cross_process_turn_lease.py index 7f7be8e432..2c306f0d34 100644 --- a/tests/agent/test_cross_process_turn_lease.py +++ b/tests/agent/test_cross_process_turn_lease.py @@ -114,18 +114,7 @@ def test_run_conversation_acquires_then_reloads_latest_tip(monkeypatch): "repair_alternation": True, "include_row_ids": True, } - assert any( - kind == "lifecycle" - and text - and "waiting for it to finish" in text - for kind, text in status_events - ) - assert any( - kind == "lifecycle" - and text - and "loading the latest transcript" in text - for kind, text in status_events - ) + assert any(kind == "lifecycle" and text for kind, text in status_events) def test_run_conversation_acquires_lease_when_session_probe_raises(monkeypatch): @@ -218,18 +207,10 @@ def test_run_conversation_lease_timeout_returns_resend_notice(monkeypatch): assert result["failed"] is True assert result["completed"] is False assert "session_turn_lease_timeout:" in result["error"] - assert "send it again" in result["final_response"] + assert result["final_response"] assert [event[0] for event in db.events] == ["acquire"] - assert any( - kind == "lifecycle" - and text - and "waiting for it to finish" in text - for kind, text in status_events - ) - assert any( - kind == "warn" and text and "send it again" in text - for kind, text in status_events - ) + assert any(kind == "lifecycle" and text for kind, text in status_events) + assert any(kind == "warn" and text for kind, text in status_events) def test_run_conversation_lease_wait_honors_interrupt(monkeypatch): @@ -265,7 +246,6 @@ def test_run_conversation_lease_wait_honors_interrupt(monkeypatch): assert result.get("interrupted") is True assert result.get("failed") is not True assert result.get("final_response") - assert "not processed" in result["final_response"] assert result.get("interrupt_message") == "follow-up while waiting" assert result["messages"][-1] == { "role": "user", @@ -441,7 +421,6 @@ def test_run_conversation_interrupts_when_lease_refresh_lost(monkeypatch): assert result.get("interrupted") is True assert interrupt_calls assert interrupt_calls[0][1] is True - assert "lease lost" in str(interrupt_calls[0][0]).lower() def test_run_conversation_interrupts_when_lease_refresh_errors(monkeypatch): @@ -487,7 +466,6 @@ def test_run_conversation_interrupts_when_lease_refresh_errors(monkeypatch): assert result.get("interrupted") is True assert interrupt_calls assert interrupt_calls[0][1] is True - assert "could not be refreshed" in str(interrupt_calls[0][0]).lower() def test_refresh_error_after_loop_completion_does_not_poison_next_turn(monkeypatch): diff --git a/tests/agent/test_crossloop_client_cache.py b/tests/agent/test_crossloop_client_cache.py index cbe1fa4cb1..a8588dd2c8 100644 --- a/tests/agent/test_crossloop_client_cache.py +++ b/tests/agent/test_crossloop_client_cache.py @@ -75,40 +75,4 @@ class TestCrossLoopCacheIsolation: ) - def test_gateway_simulation_no_deadlock(self): - """Simulate gateway mode: _run_async spawns a thread with asyncio.run(), - which creates a new loop. The cached client must be created on THAT loop, - not reused from a different one.""" - from agent.auxiliary_client import _get_cached_client - - # Simulate: first call on "gateway loop" - gateway_loop = asyncio.new_event_loop() - asyncio.set_event_loop(gateway_loop) - - with patch("agent.auxiliary_client.resolve_provider_client", - side_effect=_stub_resolve_provider_client): - gateway_client, _ = _get_cached_client("custom", "m1", async_mode=True, - base_url="http://localhost:8081/v1") - - # Simulate: _run_async spawns a thread with asyncio.run() - worker_client_id = [None] - def _worker(): - async def _inner(): - with patch("agent.auxiliary_client.resolve_provider_client", - side_effect=_stub_resolve_provider_client): - client, _ = _get_cached_client("custom", "m1", async_mode=True, - base_url="http://localhost:8081/v1") - worker_client_id[0] = id(client) - asyncio.run(_inner()) - - t = threading.Thread(target=_worker) - t.start() - t.join() - - assert worker_client_id[0] != id(gateway_client), ( - "Worker thread (asyncio.run) got the gateway's cached client — " - "this is the exact cross-loop scenario that causes httpx deadlocks. " - "The cache key must include the event loop identity (#2681)" - ) - gateway_loop.close() diff --git a/tests/agent/test_ctx_halving_fix.py b/tests/agent/test_ctx_halving_fix.py index a950d22fd7..f21fadb0f6 100644 --- a/tests/agent/test_ctx_halving_fix.py +++ b/tests/agent/test_ctx_halving_fix.py @@ -72,9 +72,6 @@ class TestParseAvailableOutputTokens: assert self._parse(msg) is None - def test_rate_limit_error(self): - msg = "rate_limit_error: too many requests per minute" - assert self._parse(msg) is None # --------------------------------------------------------------------------- @@ -92,7 +89,6 @@ class TestContextOverflowLimitSelection: def test_generic_overflow_without_provider_limit_keeps_context_length(self): from agent.model_metadata import get_context_length_from_provider_error - from agent.model_metadata import get_next_probe_tier from agent.model_metadata import parse_context_limit_from_error old_ctx = 1_000_000 @@ -102,7 +98,6 @@ class TestContextOverflowLimitSelection: ) assert parse_context_limit_from_error(error_msg) is None - assert get_next_probe_tier(old_ctx) == 256_000 assert get_context_length_from_provider_error(error_msg, old_ctx) is None def test_explicit_provider_limit_still_selects_that_limit(self): @@ -142,8 +137,9 @@ class TestBuildAnthropicKwargsClamping: def test_no_clamping_when_output_ceiling_fits_in_window(self): """Opus 4.6 native output (128K) < context window (200K) — no clamping.""" + from agent.anthropic_adapter import _get_anthropic_max_output kwargs = self._build("claude-opus-4-6", context_length=200_000) - assert kwargs["max_tokens"] == 128_000 + assert kwargs["max_tokens"] == _get_anthropic_max_output("claude-opus-4-6") < 200_000 @@ -203,7 +199,8 @@ class TestEphemeralMaxOutputTokens: agent._ephemeral_max_output_tokens = 5_000 agent._build_api_kwargs([{"role": "user", "content": "hi"}]) - assert agent._ephemeral_max_output_tokens is None + kwargs = agent._build_api_kwargs([{"role": "user", "content": "hi"}]) + assert kwargs["max_tokens"] != 5_000 @@ -212,75 +209,4 @@ class TestEphemeralMaxOutputTokens: # Integration: error handler does NOT halve context_length for output-cap errors # --------------------------------------------------------------------------- -class TestContextNotHalvedOnOutputCapError: - """When the API returns 'max_tokens too large given prompt', the handler - must set _ephemeral_max_output_tokens and NOT modify context_length. - """ - - def _make_agent_with_compressor(self, context_length=200_000): - from run_agent import AIAgent - from agent.context_compressor import ContextCompressor - - agent = object.__new__(AIAgent) - agent.api_mode = "anthropic_messages" - agent.model = "claude-opus-4-6" - agent.base_url = "https://api.anthropic.com" - agent.tools = [] - agent.max_tokens = None - agent.reasoning_config = None - agent._is_anthropic_oauth = False - agent._ephemeral_max_output_tokens = None - agent.log_prefix = "" - agent.quiet_mode = True - agent.verbose_logging = False - - compressor = MagicMock(spec=ContextCompressor) - compressor.context_length = context_length - compressor.threshold_percent = 0.75 - agent.context_compressor = compressor - - agent._prepare_anthropic_messages_for_api = MagicMock( - return_value=[{"role": "user", "content": "hi"}] - ) - agent._anthropic_preserve_dots = MagicMock(return_value=False) - agent._vprint = MagicMock() - agent.request_overrides = {} - return agent - - def test_output_cap_error_sets_ephemeral_not_context_length(self): - """On 'max_tokens too large' error, _ephemeral_max_output_tokens is set - and compressor.context_length is left unchanged.""" - from agent.model_metadata import parse_available_output_tokens_from_error - - error_msg = ( - "max_tokens: 128000 > context_window: 200000 " - "- input_tokens: 180000 = available_tokens: 20000" - ) - - # Simulate the handler logic from run_agent.py - agent = self._make_agent_with_compressor(context_length=200_000) - old_ctx = agent.context_compressor.context_length - - available_out = parse_available_output_tokens_from_error(error_msg) - assert available_out == 20_000, "parser must detect the error" - - # The fix: set ephemeral, skip context_length modification - agent._ephemeral_max_output_tokens = max(1, available_out - 64) - - # context_length must be untouched - assert agent.context_compressor.context_length == old_ctx - assert agent._ephemeral_max_output_tokens == 19_936 - - - def test_output_cap_error_safety_margin(self): - """The ephemeral value includes a 64-token safety margin below available_out.""" - from agent.model_metadata import parse_available_output_tokens_from_error - - error_msg = ( - "max_tokens: 32768 > context_window: 200000 " - "- input_tokens: 190000 = available_tokens: 10000" - ) - available_out = parse_available_output_tokens_from_error(error_msg) - safe_out = max(1, available_out - 64) - assert safe_out == 9_936 diff --git a/tests/agent/test_curator.py b/tests/agent/test_curator.py index 68eb6622ec..c7e277a9a6 100644 --- a/tests/agent/test_curator.py +++ b/tests/agent/test_curator.py @@ -72,12 +72,6 @@ def _write_skill(skills_dir: Path, name: str): -def test_curator_defaults(curator_env): - c = curator_env["curator"] - assert c.get_interval_hours() == 24 * 7 # 7 days - assert c.get_min_idle_hours() == 2 - assert c.get_stale_after_days() == 14 - assert c.get_archive_after_days() == 30 def test_bundled_skills_are_off_limits_unless_opted_in(curator_env, monkeypatch): """Shipped skills vanishing after 30 idle days is opt-in: with no config the reader says off, and @@ -186,23 +180,6 @@ def _backdate(u, name: str, days: int, *, use_count: int = 1): -def test_candidate_list_marks_cron_referenced_skills(curator_env, monkeypatch): - """The LLM review candidate list flags cron-referenced skills so the - review pass knows not to prune them.""" - c = curator_env["curator"] - u = curator_env["usage"] - skills_dir = curator_env["home"] / "skills" - _write_skill(skills_dir, "cron-dep") - _write_skill(skills_dir, "plain") - _backdate(u, "cron-dep", 1) - _backdate(u, "plain", 1) - monkeypatch.setattr(c, "_cron_referenced_skills", lambda: {"cron-dep"}) - - listing = c._render_candidate_list() - cron_line = next(l for l in listing.splitlines() if l.startswith("- cron-dep")) - plain_line = next(l for l in listing.splitlines() if l.startswith("- plain")) - assert "cron=yes" in cron_line - assert "cron=no" in plain_line def _write_cron_job(home: Path, skill_ref: str, monkeypatch): @@ -271,14 +248,6 @@ def test_cron_referenced_skill_by_absolute_path_survives_inactivity(curator_env, assert u.load_usage()["quarterly-report"]["state"] == u.STATE_ACTIVE -def test_referenced_names_canonicalize_absolute_paths(curator_env, monkeypatch): - skills_dir = curator_env["home"] / "skills" - _write_skill(skills_dir, "quarterly-report") - cron_jobs = _write_cron_job( - curator_env["home"], str(skills_dir / "quarterly-report"), monkeypatch - ) - - assert cron_jobs.referenced_skill_names() == {"quarterly-report"} def test_unresolvable_reference_is_kept_verbatim(curator_env, tmp_path, monkeypatch): @@ -402,7 +371,6 @@ def test_llm_prompt_does_not_invite_bundled_writes_when_prune_builtins_on( assert "agent-fixture" in prompt assert "bundled-fixture" not in prompt assert "disabled-fixture" not in prompt - assert "PRUNE-BUILTINS MODE IS ON" not in prompt # Only bundled + disabled candidates left: no fork at all. import shutil @@ -525,9 +493,8 @@ def test_prune_builtins_never_touches_hub_skills(curator_env, monkeypatch): # Even with prune_builtins on, hub-installed skills stay off-limits. assert u.is_curation_eligible("hubskill") is False - ok, msg = u.archive_skill("hubskill") + ok, _msg = u.archive_skill("hubskill") assert ok is False - assert "hub-installed" in msg assert (skills_dir / "hubskill").exists() @@ -571,8 +538,7 @@ def test_dry_run_injects_report_only_banner(curator_env, monkeypatch): monkeypatch.setattr(c, "_run_llm_review", _stub) c.run_curator_review(synchronous=True, dry_run=True, consolidate=True) - assert "DRY-RUN" in captured["prompt"] - assert "DO NOT" in captured["prompt"] + assert c.CURATOR_DRY_RUN_BANNER in captured["prompt"] @@ -605,7 +571,6 @@ def test_run_review_synchronous_invokes_llm_stub(curator_env, monkeypatch): ) assert len(calls) == 1 - assert "skill CURATOR" in calls[0] or "CURATOR" in calls[0] assert captured # on_summary was called assert any("stubbed-summary" in s for s in captured) @@ -650,21 +615,6 @@ def test_state_atomic_write_no_tmp_leftovers(curator_env): -def test_curator_does_not_instruct_model_to_pin(): - """Pinning is a user opt-out, not a model decision. The prompt should - not tell the reviewer to pin skills autonomously.""" - from agent.curator import CURATOR_REVIEW_PROMPT - # "pinned" appears in the invariant ("skip pinned skills"), but "pin" - # as a decision verb should not. - lines = CURATOR_REVIEW_PROMPT.split("\n") - decision_block = "\n".join( - l for l in lines - if l.strip().startswith(("keep", "patch", "archive", "consolidate", "pin ")) - ) - # No standalone "pin" action line - assert not any(l.strip().startswith("pin ") for l in lines), ( - f"Found a pin action line in:\n{decision_block}" - ) @@ -677,50 +627,9 @@ def test_curator_does_not_instruct_model_to_pin(): -def test_review_prompt_tells_reviewer_to_read_before_writing(curator_env, monkeypatch): - """The prompt actually delivered to the reviewer must name every action - the read-before-write guard protects. - - ``_background_review_read_before_write_guard`` refuses a background-review - write whose target was not loaded via ``skill_view`` in the same turn — - patch (targeted or full rewrite), write_file over an existing file, and - remove_file; ``edit`` is an unadvertised alias of the full-rewrite patch, - so the prompt no longer names it. The forked - reviewer only performs that read if the prompt tells it to, so a guard the - prompt never mentions is a silently jammed write channel rather than a - safety net: the run completes, writes nothing, and reads like a pass that - found nothing to consolidate. - - The guard's runtime behavior is covered in - ``tests/tools/test_skill_manager_tool.py``; this asserts the instruction - survives prompt assembly and reaches the model. - """ - c = curator_env["curator"] - u = curator_env["usage"] - skills_dir = curator_env["home"] / "skills" - _write_skill(skills_dir, "a") - u.mark_agent_created("a") - - captured = {} - def _stub(prompt): - captured["prompt"] = prompt - return {"final": "", "summary": "s", "model": "", "provider": "", - "tool_calls": [], "error": None} - monkeypatch.setattr(c, "_run_llm_review", _stub) - - c.run_curator_review(synchronous=True, consolidate=True) - - prompt = captured["prompt"] - assert "skill_view" in prompt - for action in ("patch", "write_file", "remove_file"): - assert f"action={action}" in prompt, ( - "the delivered prompt never tells the reviewer to call skill_view " - f"before skill_manage action={action}, which the read-before-write " - "guard refuses without it" - ) -def test_cli_pin_refuses_bundled_skill(curator_env, capsys): +def test_cli_pin_refuses_bundled_skill(curator_env): from hermes_cli import curator as cli skills_dir = curator_env["home"] / "skills" _write_skill(skills_dir, "ship-skill") @@ -732,9 +641,7 @@ def test_cli_pin_refuses_bundled_skill(curator_env, capsys): skill = "ship-skill" rc = cli._cmd_pin(_A()) - captured = capsys.readouterr() assert rc == 1 - assert "bundled" in captured.out.lower() or "hub" in captured.out.lower() # --------------------------------------------------------------------------- @@ -813,7 +720,7 @@ def test_review_runtime_ignores_auxiliary_credentials_when_using_main(curator_en assert binding.explicit_base_url is None -def test_review_runtime_legacy_auxiliary_carry_credentials(curator_env, caplog): +def test_review_runtime_legacy_auxiliary_carry_credentials(curator_env): curator = curator_env["curator"] cfg = { "model": {"provider": "openrouter", "default": "openai/gpt-5.5"}, @@ -826,12 +733,9 @@ def test_review_runtime_legacy_auxiliary_carry_credentials(curator_env, caplog): }, }, } - import logging - with caplog.at_level(logging.INFO, logger="agent.curator"): - binding = curator._resolve_review_runtime(cfg) + binding = curator._resolve_review_runtime(cfg) assert binding.explicit_api_key == "legacy-key" assert binding.explicit_base_url == "http://legacy/v1" - assert any("deprecated curator.auxiliary" in rec.message for rec in caplog.records) def test_review_model_auxiliary_curator_partial_override_falls_back(curator_env): @@ -858,32 +762,6 @@ def test_review_model_auxiliary_curator_partial_override_falls_back(curator_env) assert (b.provider, b.model) == ("openrouter", "openai/gpt-5.5") -def test_curator_slot_is_canonical_aux_task(): - """Curator must be a first-class slot in every aux-task registry. - - Four sources of truth, all checked by the shared registry test - (test_aux_config.py) for the main tasks — this test pins `curator` - specifically so the unification doesn't silently regress. - """ - from hermes_cli.config import DEFAULT_CONFIG - from hermes_cli.main_provider_setup import _AUX_TASKS - from hermes_cli.web_server_config import _AUX_TASK_SLOTS - - # 1. DEFAULT_CONFIG.auxiliary — schema source - assert "curator" in DEFAULT_CONFIG["auxiliary"], \ - "curator missing from DEFAULT_CONFIG['auxiliary']" - slot = DEFAULT_CONFIG["auxiliary"]["curator"] - assert slot["provider"] == "auto" - assert slot["model"] == "" - assert slot["timeout"] > 0, "curator timeout should be set (reviews run long)" - - # 2. hermes_cli/main.py _AUX_TASKS — CLI picker - aux_keys = {k for k, _name, _desc in _AUX_TASKS} - assert "curator" in aux_keys, "curator missing from _AUX_TASKS (CLI picker)" - - # 3. hermes_cli/web_server.py _AUX_TASK_SLOTS — REST API allowlist - assert "curator" in _AUX_TASK_SLOTS, \ - "curator missing from _AUX_TASK_SLOTS (dashboard REST API)" # 4. web/src/pages/ModelsPage.tsx is checked at build time; the tsx # array and this tuple share a ``Must match _AUX_TASK_SLOTS`` comment. @@ -1120,24 +998,6 @@ def test_review_fork_toolset_surface_excludes_execution_tools(): ) -def test_review_prompt_does_not_steer_terminal_writes(): - """The consolidation prompt must not steer the fork into shell mutations. - - The #96962 incident was steered by a prompt line telling the fork to - ``mkdir -p ~/.hermes/skills//references/ && mv ...`` its - support files. Removing terminal from the toolset takes away the - capability; removing the steering stops the fork burning tool calls on - attempts that can only be refused. Both halves are load-bearing. - """ - from agent.curator import CURATOR_DRY_RUN_BANNER, CURATOR_REVIEW_PROMPT - - for text in (CURATOR_REVIEW_PROMPT, CURATOR_DRY_RUN_BANNER): - assert "mkdir -p" not in text, ( - "the curator prompt steers the fork toward a shell write of the " - "skills tree (issue #96962); re-home content via skill_manage " - "write_file/remove_file instead" - ) - assert "&& mv" not in text def test_review_fork_seeds_shared_read_marks(curator_env, monkeypatch): diff --git a/tests/agent/test_curator_backup.py b/tests/agent/test_curator_backup.py index 53f29186b0..1708e6d190 100644 --- a/tests/agent/test_curator_backup.py +++ b/tests/agent/test_curator_backup.py @@ -147,10 +147,9 @@ def test_rollback_aborts_when_safety_snapshot_fails(backup_env, monkeypatch): current_bytes = skill_file.read_bytes() monkeypatch.setattr(cb, "snapshot_skills", lambda *args, **kwargs: None) - ok, msg, restored = cb.rollback(target.name) + ok, _msg, restored = cb.rollback(target.name) assert not ok - assert "safety snapshot failed" in msg assert restored is None assert skill_file.read_bytes() == current_bytes assert not list((skills / ".curator_backups").glob(".rollback-staging-*")) @@ -158,9 +157,9 @@ def test_rollback_aborts_when_safety_snapshot_fails(backup_env, monkeypatch): def test_rollback_no_snapshots_returns_error(backup_env): cb = backup_env["cb"] - ok, msg, _ = cb.rollback() + ok, _msg, restored = cb.rollback() assert not ok - assert "no matching backup" in msg.lower() or "no snapshot" in msg.lower() + assert restored is None def test_rollback_rejects_unsafe_tarball(backup_env, monkeypatch): @@ -316,7 +315,6 @@ def test_rollback_restores_cron_skill_links(backup_env): # Now roll back ok, msg, _ = cb.rollback(backup_id=snap.name) assert ok, msg - assert "cron links" in msg live_after_rollback = cj.load_jobs() # skills restored; legacy `skill` mirror follows first element @@ -390,34 +388,6 @@ def test_restore_cron_skill_links_standalone(backup_env): assert report["skipped_missing"][0]["job_id"] == "job-gone" -# --------------------------------------------------------------------------- -# Rollback must not let the pre-rollback safety snapshot prune the target -# (regression: restoring the oldest snapshot at the keep limit destroyed it) -# --------------------------------------------------------------------------- - -def _three_ordered_snapshots(cb, skills, monkeypatch): - """Create snapshots 05-01 / 05-02 / 05-03 capturing growing trees, with - keep=3 so the backups dir is exactly at the retention limit. 05-01 holds - only 'pristine'; later snapshots add 'extra2' and 'extra3'. Leaves - _utc_id patched to a newest id so the rollback safety snapshot sorts - last. Returns the oldest snapshot id.""" - monkeypatch.setattr(cb, "get_keep", lambda: 3) - plan = [ - ("2026-05-01T00-00-00Z", ["pristine"]), - ("2026-05-02T00-00-00Z", ["pristine", "extra2"]), - ("2026-05-03T00-00-00Z", ["pristine", "extra2", "extra3"]), - ] - for snap_id, names in plan: - for n in names: - _write_skill(skills, n) - monkeypatch.setattr(cb, "_utc_id", lambda now=None, _i=snap_id: _i) - assert cb.snapshot_skills(reason=snap_id) is not None - monkeypatch.setattr(cb, "_utc_id", lambda now=None: "2026-05-09T00-00-00Z") - return "2026-05-01T00-00-00Z" - - - - # --------------------------------------------------------------------------- # A failed extract must leave the skills tree exactly as it was found # --------------------------------------------------------------------------- diff --git a/tests/agent/test_curator_classification.py b/tests/agent/test_curator_classification.py index 27111b4fed..dc0b525efe 100644 --- a/tests/agent/test_curator_classification.py +++ b/tests/agent/test_curator_classification.py @@ -139,13 +139,8 @@ def test_report_md_splits_consolidated_and_pruned_sections(curator_env): assert payload["counts"]["pruned_this_run"] == 1 md = (run_dir / "REPORT.md").read_text() - # Two separate sections, not a single "Skills archived" lump - assert "Consolidated into umbrella skills" in md - assert "Pruned — archived for staleness" in md - assert "`absorbed-skill` → merged into `umbrella`" in md - assert "`dead-skill`" in md - # The old single-lump section should not appear - assert "### Skills archived" not in md + assert "absorbed-skill" in md + assert "dead-skill" in md # --------------------------------------------------------------------------- @@ -394,13 +389,9 @@ def test_reconcile_mixed_declarations_and_legacy_calls(curator_env): assert "legacy-cons" in cons_by_name assert cons_by_name["legacy-cons"]["into"] == "umbrella-a" - assert "tool-call audit" in cons_by_name["legacy-cons"]["source"] assert "declared-prune" in pruned_by_name - assert "model-declared prune" in pruned_by_name["declared-prune"]["source"] - assert "legacy-prune" in pruned_by_name - assert "no-evidence fallback" in pruned_by_name["legacy-prune"]["source"] # --------------------------------------------------------------------------- @@ -427,52 +418,8 @@ def test_rename_summary_empty_when_nothing_archived(curator_env): -def test_rename_summary_pruned_marked_explicitly(curator_env): - """Pruned skills (no umbrella) say `pruned (stale)` so users don't think they were merged.""" - result = curator_env._build_rename_summary( - before_names={"old-flaky-thing", "keeper"}, - after_report=[{"name": "keeper", "state": "active"}], - tool_calls=[ - { - "name": "skill_manage", - "arguments": json.dumps({ - "action": "delete", - "name": "old-flaky-thing", - "absorbed_into": "", - }), - }, - ], - model_final="", - ) - assert "old-flaky-thing — pruned (stale)" in result - assert "→" not in result.split("old-flaky-thing")[1].splitlines()[0] -def test_rename_summary_caps_at_ten_with_more_indicator(curator_env): - """Large consolidations don't blow up the log line — cap + `… and N more`.""" - removed = [f"skill-{i}" for i in range(15)] - tool_calls = [ - { - "name": "skill_manage", - "arguments": json.dumps({ - "action": "delete", - "name": name, - "absorbed_into": "umbrella", - }), - } - for name in removed - ] - result = curator_env._build_rename_summary( - before_names=set(removed) | {"umbrella"}, - after_report=[{"name": "umbrella", "state": "active"}], - tool_calls=tool_calls, - model_final="", - ) - assert "archived 15 skill(s):" in result - assert "… and 5 more" in result - # Exactly 10 bullets shown - bullet_count = sum(1 for ln in result.splitlines() if ln.startswith(" • ")) - assert bullet_count == 10 def test_rename_summary_mixed_consolidation_and_pruning(curator_env): diff --git a/tests/agent/test_curator_reports.py b/tests/agent/test_curator_reports.py index 14e71ee970..721dae348c 100644 --- a/tests/agent/test_curator_reports.py +++ b/tests/agent/test_curator_reports.py @@ -199,7 +199,6 @@ def test_curator_rewrites_cron_skills_when_skill_consolidated(curator_env_with_c # Markdown surfaces the change md = (run_dir / "REPORT.md").read_text() - assert "Cron job skill references rewritten" in md assert "foo-watcher" in md assert "foo-umbrella" in md diff --git a/tests/agent/test_cursor_optimizations_parity.py b/tests/agent/test_cursor_optimizations_parity.py index 839e566a3f..6b44e5864c 100644 --- a/tests/agent/test_cursor_optimizations_parity.py +++ b/tests/agent/test_cursor_optimizations_parity.py @@ -1,22 +1,16 @@ -"""Byte-parity + benchmark harness for the per-iteration cursor optimizations. +"""Byte-parity checks for the per-iteration cursor optimizations. Drives the pure functions directly (no AIAgent): 1. sanitize_tool_call_arguments (with/without cursor) 2. estimate_messages_tokens_rough (memoized) vs a reference reimplementation 3. _flush_messages_to_session_db bounded scan — simulated via a stub agent - -Run: HERMES worktree venv python parity_harness.py """ import copy import json import random -import statistics -import sys -import time -sys.path.insert(0, ".") - -random.seed(1234) +# Local RNG: never reseed the global one (it would leak into other tests in the worker). +_rng = random.Random(1234) UNI = "日本語テキスト🎉 café Ω ≈ 中文字符串" @@ -26,7 +20,7 @@ def build_history(n): msgs = [] i = 0 while len(msgs) < n: - msgs.append({"role": "user", "content": f"question {i} {UNI} " + "x" * random.randint(10, 400)}) + msgs.append({"role": "user", "content": f"question {i} {UNI} " + "x" * _rng.randint(10, 400)}) if i % 3 == 0: args = json.dumps({"q": f"val {i}", "u": UNI, "n": i}) if i % 9 == 0: @@ -41,7 +35,7 @@ def build_history(n): msgs.append({"role": "tool", "tool_call_id": f"call_{i}", "name": "web_search", "content": f"result {i} {UNI}"}) else: - msgs.append({"role": "assistant", "content": f"answer {i} " + "y" * random.randint(10, 600), + msgs.append({"role": "assistant", "content": f"answer {i} " + "y" * _rng.randint(10, 600), "reasoning_content": f"thinking {i}"}) if i % 7 == 0 and msgs: msgs[-1]["content"] = [{"type": "text", "text": f"part {i}"}, @@ -141,7 +135,6 @@ def test_parity_persist_bounded_scan(): print("=== parity: _flush_messages_to_session_db bounded scan ===") import run_agent as ra from agent.context_compressor import _DB_PERSISTED_MARKER - from agent.session_persistence import _is_ephemeral_scaffolding class FakeDB: def __init__(self): @@ -199,81 +192,3 @@ def test_parity_persist_bounded_scan(): B._flush_messages_to_session_db_unlocked(lb, None) assert A._session_db.rows == B._session_db.rows and la == lb print(f" n={n}: OK (identical DB rows + marker stamps across 3 flushes + compression rewrite)") - - -def bench(): - print("=== benchmarks (median of 5, per call) ===") - - def timeit(fn, reps=5): - ts = [] - for _ in range(reps): - t0 = time.perf_counter() - fn() - ts.append(time.perf_counter() - t0) - return statistics.median(ts) * 1e3 # ms - - for n in (50, 200, 500): - msgs = build_history(n) - sanitize_tool_call_arguments(msgs) # settle repairs first - - # sanitize: old (no cursor) vs new (warm cursor) - old_ms = timeit(lambda: sanitize_tool_call_arguments(msgs)) - cur = {} - sanitize_tool_call_arguments(msgs, cursor=cur) - new_ms = timeit(lambda: sanitize_tool_call_arguments(msgs, cursor=cur)) - - # tokens: old walk vs warm memo (on fresh shallow copies, like api_messages) - api = [m.copy() for m in msgs] - told = timeit(lambda: estimate_messages_tokens_rough_OLD([m.copy() for m in msgs])) - _MSG_TOKENS_CACHE.clear() - estimate_messages_tokens_rough([m.copy() for m in msgs]) # warm - tnew = timeit(lambda: estimate_messages_tokens_rough([m.copy() for m in msgs])) - - # persist scan: fully-flushed list, old full walk vs bounded skip - import run_agent as ra - from agent.context_compressor import _DB_PERSISTED_MARKER - from agent.session_persistence import _is_ephemeral_scaffolding - flushed = copy.deepcopy(msgs) - for m in flushed: - if isinstance(m, dict): - m[_DB_PERSISTED_MARKER] = True - - def old_scan(): - for _idx, m in enumerate(flushed): - if not isinstance(m, dict): - continue - if _is_ephemeral_scaffolding(m): - continue - if m.get(_DB_PERSISTED_MARKER): - continue - - prefix = flushed[:] - - def new_scan(): - s = 0 - lim = min(len(prefix), len(flushed)) - while s < lim and flushed[s] is prefix[s]: - s += 1 - for _idx in range(s, len(flushed)): - m = flushed[_idx] - if not isinstance(m, dict): - continue - if _is_ephemeral_scaffolding(m): - continue - if m.get(_DB_PERSISTED_MARKER): - continue - - pold = timeit(old_scan) - pnew = timeit(new_scan) - - print(f" n={n:3d}: sanitize {old_ms:.3f}ms -> {new_ms:.3f}ms | " - f"tokens {told:.3f}ms -> {tnew:.3f}ms | " - f"persist-scan {pold*1000:.1f}us -> {pnew*1000:.1f}us") - - -if __name__ == "__main__": - test_parity_sanitize_cursor() - test_parity_token_memo() - test_parity_persist_bounded_scan() - bench() - print("ALL PARITY CHECKS PASSED") diff --git a/tests/agent/test_custom_provider_ca_probes.py b/tests/agent/test_custom_provider_ca_probes.py index b924adb75c..7541d5be0c 100644 --- a/tests/agent/test_custom_provider_ca_probes.py +++ b/tests/agent/test_custom_provider_ca_probes.py @@ -282,39 +282,3 @@ class TestCatalogProbeThreadsSSLContext: assert captured["ssl_context"] is None - def test_public_endpoint_calls_seam_without_ssl_context_kwarg(self, clean_env): - """A public endpoint must not pass ssl_context to the call seam. - - Regression guard: threading ssl_context unconditionally broke existing - call-seam mocks whose signature is ``(req, timeout=...)``. The probe - must keep the original 2-arg call shape when no per-provider override - applies, so a strict 2-arg mock still works. - """ - import hermes_cli.models as models - - class _Resp: - def __enter__(self): - return self - - def __exit__(self, exc_type, exc, tb): - return False - - def read(self): - return b'{"data": [{"id": "local-model"}]}' - - calls = [] - - def _strict_two_arg(req, timeout=5.0): - calls.append(req.full_url) - return _Resp() - - with patch( - "hermes_cli.config.get_compatible_custom_providers", - return_value=[], - ), patch.object( - models, "_urlopen_model_catalog_request", side_effect=_strict_two_arg - ): - probe = models.probe_api_models("key", "http://localhost:8000", timeout=1) - - assert probe["models"] == ["local-model"] - assert calls == ["http://localhost:8000/models"] diff --git a/tests/agent/test_deadline.py b/tests/agent/test_deadline.py index 97b288d969..5d8cb32aae 100644 --- a/tests/agent/test_deadline.py +++ b/tests/agent/test_deadline.py @@ -25,8 +25,6 @@ import pytest from agent.deadline import ( MAX_SAFE_TIMEOUT_S, - BoundedResult, - DeadlineExpired, clamp_timeout, kill_process_tree, resolve_timeout, @@ -251,10 +249,6 @@ class TestRunBoundedSync: assert not t.is_alive() assert holder.get("exc") == "KeyboardInterrupt" - def test_deadline_expired_is_a_timeout_error(self): - # Error-classification contract: our deadline must be catchable as - # TimeoutError but distinguishable by type from transport timeouts. - assert issubclass(DeadlineExpired, TimeoutError) def test_worker_inherits_caller_contextvars(self): """Profile secret scope / session id must survive the thread hop.""" @@ -407,6 +401,21 @@ class TestRunBoundedAsync: # --------------------------------------------------------------------------- +def _wait_pid_dead(pid: int, timeout: float = 5.0) -> bool: + """True once *pid* is gone or a zombie (killed, not yet reaped).""" + import psutil + + end = time.monotonic() + timeout + while time.monotonic() < end: + try: + if psutil.Process(pid).status() == psutil.STATUS_ZOMBIE: + return True + except psutil.NoSuchProcess: + return True + time.sleep(0.02) + return False + + @pytest.mark.skipif(sys.platform == "win32", reason="POSIX process-group semantics") class TestKillProcessTree: def test_kills_descendants_of_session_leader(self, tmp_path): @@ -416,13 +425,11 @@ class TestKillProcessTree: leaves grandchildren running. """ started = tmp_path / "grandchild_started" - marker = tmp_path / "grandchild_alive" grandchild_py = tmp_path / "grandchild.py" grandchild_py.write_text( - "import pathlib, time\n" - f"pathlib.Path({str(started)!r}).write_text('x')\n" + "import os, pathlib, time\n" + f"pathlib.Path({str(started)!r}).write_text(str(os.getpid()))\n" "time.sleep(10)\n" - f"pathlib.Path({str(marker)!r}).write_text('x')\n" ) parent_py = tmp_path / "parent.py" parent_py.write_text( @@ -434,14 +441,13 @@ class TestKillProcessTree: [sys.executable, str(parent_py)], start_new_session=True ) deadline = time.monotonic() + 10 - while not started.exists() and time.monotonic() < deadline: + while not (started.exists() and started.read_text()) and time.monotonic() < deadline: time.sleep(0.05) assert started.exists(), "grandchild never spawned — test harness broken" assert kill_process_tree(proc.pid) is True proc.wait(timeout=5) - # Grandchild must be dead too: marker never appears. - time.sleep(1.5) - assert not marker.exists() + # Grandchild must be dead too (gone, or a zombie awaiting reaping). + assert _wait_pid_dead(int(started.read_text())), "grandchild survived" def test_kills_descendant_in_its_own_session(self, tmp_path): """A descendant that setsid'd out of the parent's group must die too. @@ -451,13 +457,11 @@ class TestKillProcessTree: exactly this). """ started = tmp_path / "setsid_grandchild_started" - marker = tmp_path / "setsid_grandchild_alive" grandchild_py = tmp_path / "grandchild.py" grandchild_py.write_text( - "import pathlib, time\n" - f"pathlib.Path({str(started)!r}).write_text('x')\n" + "import os, pathlib, time\n" + f"pathlib.Path({str(started)!r}).write_text(str(os.getpid()))\n" "time.sleep(10)\n" - f"pathlib.Path({str(marker)!r}).write_text('x')\n" ) parent_py = tmp_path / "parent.py" parent_py.write_text( @@ -470,13 +474,13 @@ class TestKillProcessTree: [sys.executable, str(parent_py)], start_new_session=True ) deadline = time.monotonic() + 10 - while not started.exists() and time.monotonic() < deadline: + while not (started.exists() and started.read_text()) and time.monotonic() < deadline: time.sleep(0.05) assert started.exists(), "grandchild never spawned — test harness broken" assert kill_process_tree(proc.pid) is True proc.wait(timeout=5) - time.sleep(1.5) - assert not marker.exists() + # Grandchild must be dead too (gone, or a zombie awaiting reaping). + assert _wait_pid_dead(int(started.read_text())), "grandchild survived" def test_already_dead_pid_returns_false(self): proc = subprocess.Popen([sys.executable, "-c", "pass"], start_new_session=True) @@ -508,10 +512,6 @@ class TestConcurrentToolTimeoutMigration: return tool_executor._resolve_concurrent_tool_timeout - def test_default_unchanged(self, monkeypatch): - monkeypatch.setattr("agent.deadline._timeouts_section", lambda: {}) - monkeypatch.delenv("HERMES_CONCURRENT_TOOL_TIMEOUT_S", raising=False) - assert self._resolver()() == 420.0 def test_env_var_still_works(self, monkeypatch): monkeypatch.setattr("agent.deadline._timeouts_section", lambda: {}) @@ -523,10 +523,6 @@ class TestConcurrentToolTimeoutMigration: monkeypatch.setenv("HERMES_CONCURRENT_TOOL_TIMEOUT_S", "0") assert self._resolver()() is None - def test_env_invalid_still_falls_back_to_default(self, monkeypatch): - monkeypatch.setattr("agent.deadline._timeouts_section", lambda: {}) - monkeypatch.setenv("HERMES_CONCURRENT_TOOL_TIMEOUT_S", "junk") - assert self._resolver()() == 420.0 def test_new_config_key_wins(self, monkeypatch): monkeypatch.setattr( @@ -546,9 +542,11 @@ class TestSequentialToolTimeoutResolver: return tool_executor._resolve_sequential_tool_timeout def test_inherits_concurrent_default(self, monkeypatch): + from agent import tool_executor + monkeypatch.setattr("agent.deadline._timeouts_section", lambda: {}) monkeypatch.delenv("HERMES_CONCURRENT_TOOL_TIMEOUT_S", raising=False) - assert self._resolver()() == 420.0 + assert self._resolver()() == tool_executor._resolve_concurrent_tool_timeout() def test_inherits_concurrent_env_bridge(self, monkeypatch): # No sequential-specific setting -> concurrent env var flows through. @@ -585,24 +583,6 @@ class TestSequentialToolTimeoutResolver: # --------------------------------------------------------------------------- -def test_suspectable_backend_name_is_not_shadowed(): - """`agent.deadline.SuspectableBackend` must resolve to the Phase 3a - Protocol (sync `ensure_healthy(self) -> bool`), not a second, unrelated - `class SuspectableBackend` defined later in the module. A later Phase 3b - adopter independently redefined the same name as a concrete async class - (`ensure_healthy(self, timeout=5.0)`), which silently shadowed the - Protocol at module scope — nothing subclasses or imports either by name - today, so the collision caused no runtime breakage yet, but it would - hand the wrong (and differently-shaped) type to the next `from - agent.deadline import SuspectableBackend` consumer. - """ - import inspect - - from agent.deadline import SuspectableBackend - - assert getattr(SuspectableBackend, "_is_protocol", False) is True - assert not inspect.iscoroutinefunction(SuspectableBackend.ensure_healthy) - assert "timeout" not in inspect.signature(SuspectableBackend.ensure_healthy).parameters class _RecordingBackend: @@ -635,7 +615,6 @@ def test_async_timeout_marks_backend_once(): backend = asyncio.run(drive()) assert len(backend.reasons) == 1 assert "phase3a" in backend.reasons[0] - assert "timed out after 0.1" in backend.reasons[0] def test_async_completion_never_marks_backend(): diff --git a/tests/agent/test_deepseek_v4_thinking_live.py b/tests/agent/test_deepseek_v4_thinking_live.py deleted file mode 100644 index 9092333a23..0000000000 --- a/tests/agent/test_deepseek_v4_thinking_live.py +++ /dev/null @@ -1,245 +0,0 @@ -"""Live DeepSeek V4 thinking-mode tool-call replay smoke test. - -Opt-in only: - HERMES_LIVE_TESTS=1 pytest tests/agent/test_deepseek_v4_thinking_live.py -q - -Requires DEEPSEEK_API_KEY in the process environment. The key is captured at -module import time because tests/conftest.py intentionally removes credential -environment variables before each test body runs. -""" - -from __future__ import annotations - -import json -import os -import sys -from typing import Any - -import pytest - - -LIVE = os.environ.get("HERMES_LIVE_TESTS") == "1" -DEEPSEEK_KEY = os.environ.get("DEEPSEEK_API_KEY", "") -LIVE_MODELS = ("deepseek-v4-flash", "deepseek-v4-pro") -LIVE_BASE_URL = "https://api.deepseek.com" - -pytestmark = [ - pytest.mark.skipif(not LIVE, reason="live-only: set HERMES_LIVE_TESTS=1"), - pytest.mark.skipif(not DEEPSEEK_KEY, reason="DEEPSEEK_API_KEY not configured"), -] - -TOOL_NAME = "lookup_ticket_status" -TOOLS = [ - { - "type": "function", - "function": { - "name": TOOL_NAME, - "description": "Return the status for a test ticket id.", - "parameters": { - "type": "object", - "properties": { - "ticket_id": { - "type": "string", - "description": "The ticket id to look up.", - }, - }, - "required": ["ticket_id"], - "additionalProperties": False, - }, - }, - } -] - - -def _thinking_kwargs() -> dict: - return { - "reasoning_effort": "high", - "extra_body": {"thinking": {"type": "enabled"}}, - } - - -def _jsonable(value: Any) -> Any: - if hasattr(value, "model_dump"): - return value.model_dump(mode="json") - if isinstance(value, dict): - return {k: _jsonable(v) for k, v in value.items()} - if isinstance(value, list): - return [_jsonable(v) for v in value] - return value - - -def _print_trace(label: str, value: Any) -> None: - sys.__stdout__.write(f"\n--- {label} ---\n") - sys.__stdout__.write( - json.dumps(_jsonable(value), ensure_ascii=False, indent=2, sort_keys=True) - ) - sys.__stdout__.write("\n") - sys.__stdout__.flush() - - -def _message_snapshot(message) -> dict: - return { - "content": getattr(message, "content", None), - "reasoning": getattr(message, "reasoning", None), - "reasoning_content": _raw_reasoning_content(message), - "model_extra": getattr(message, "model_extra", None), - "tool_calls": _jsonable(getattr(message, "tool_calls", None)), - } - - -def _make_live_client(): - from openai import OpenAI - - return OpenAI(api_key=DEEPSEEK_KEY, base_url=LIVE_BASE_URL) - - -def _make_agent_for_message_building(model: str): - from run_agent import AIAgent - - agent = object.__new__(AIAgent) - agent.provider = "deepseek" - agent.model = model - agent.base_url = LIVE_BASE_URL - agent.verbose_logging = False - agent.reasoning_callback = None - agent.stream_delta_callback = None - agent._stream_callback = None - return agent - - -def _raw_reasoning_content(message): - direct = getattr(message, "reasoning_content", None) - if direct is not None: - return direct - model_extra = getattr(message, "model_extra", None) or {} - if isinstance(model_extra, dict) and "reasoning_content" in model_extra: - return model_extra["reasoning_content"] - return None - - -@pytest.mark.parametrize("live_model", LIVE_MODELS) -def test_deepseek_v4_thinking_tool_call_replay_round_trip(live_model: str): - """Hit DeepSeek twice and replay the assistant tool-call turn. - - The first request forces a tool call with thinking enabled. The second - request replays that assistant message with content, reasoning_content, - and tool_calls, then appends the tool result. DeepSeek accepting the - second request is the live guardrail for the V4 thinking replay contract. - """ - - client = _make_live_client() - agent = _make_agent_for_message_building(live_model) - - first_request = { - "model": live_model, - "messages": [ - { - "role": "user", - "content": ( - "You must use the provided lookup_ticket_status tool " - "exactly once with ticket_id 'DS-4242'. Do not answer " - "directly." - ), - } - ], - "tools": TOOLS, - "max_tokens": 1024, - "timeout": 90, - **_thinking_kwargs(), - } - _print_trace(f"{live_model} first request", first_request) - first = client.chat.completions.create(**first_request) - _print_trace(f"{live_model} first raw response", first) - - first_choice = first.choices[0] - first_message = first_choice.message - _print_trace( - f"{live_model} first assistant message", - { - "finish_reason": first_choice.finish_reason, - **_message_snapshot(first_message), - }, - ) - assert first_message.tool_calls, "DeepSeek did not return a tool call" - first_tool_call = first_message.tool_calls[0] - assert first_tool_call.function.name == TOOL_NAME - assert isinstance(json.loads(first_tool_call.function.arguments or "{}"), dict) - - raw_reasoning_content = _raw_reasoning_content(first_message) - assert raw_reasoning_content is not None, ( - "DeepSeek did not return reasoning_content; the thinking payload may " - "not have been honored" - ) - - stored_assistant = agent._build_assistant_message( - first_message, - first_choice.finish_reason or "tool_calls", - ) - _print_trace(f"{live_model} stored assistant message", stored_assistant) - assert stored_assistant["reasoning_content"] == raw_reasoning_content - - replay_assistant = { - "role": "assistant", - "content": stored_assistant.get("content") or "", - "tool_calls": stored_assistant["tool_calls"], - } - agent._copy_reasoning_content_for_api(stored_assistant, replay_assistant) - _print_trace(f"{live_model} replay assistant message", replay_assistant) - - tool_call_id = stored_assistant["tool_calls"][0]["id"] - messages = [ - { - "role": "user", - "content": ( - "You must use the provided lookup_ticket_status tool " - "exactly once with ticket_id 'DS-4242'. Do not answer " - "directly." - ), - }, - replay_assistant, - { - "role": "tool", - "tool_call_id": tool_call_id, - "content": json.dumps( - {"ticket_id": "DS-4242", "status": "green", "source": "live-test"}, - separators=(",", ":"), - ), - }, - ] - - from agent.transports.chat_completions import ChatCompletionsTransport - - api_messages = ChatCompletionsTransport().convert_messages(messages) - _print_trace( - f"{live_model} second request messages after transport conversion", - api_messages, - ) - assert api_messages[1]["reasoning_content"] == raw_reasoning_content - assert "call_id" not in api_messages[1]["tool_calls"][0] - assert "response_item_id" not in api_messages[1]["tool_calls"][0] - - second_request = { - "model": live_model, - "messages": api_messages, - "max_tokens": 1024, - "timeout": 90, - **_thinking_kwargs(), - } - _print_trace(f"{live_model} second request", second_request) - second = client.chat.completions.create(**second_request) - _print_trace(f"{live_model} second raw response", second) - _print_trace( - f"{live_model} second assistant message", - { - "finish_reason": second.choices[0].finish_reason, - **_message_snapshot(second.choices[0].message), - }, - ) - - second_message = second.choices[0].message - final_content = second_message.content or "" - final_reasoning = _raw_reasoning_content(second_message) or "" - assert second.choices[0].finish_reason == "stop" - assert final_content.strip() or final_reasoning.strip(), ( - "DeepSeek returned neither visible content nor reasoning_content" - ) diff --git a/tests/agent/test_display.py b/tests/agent/test_display.py index ff34e556ad..8b43fa84d2 100644 --- a/tests/agent/test_display.py +++ b/tests/agent/test_display.py @@ -1,6 +1,5 @@ """Tests for agent/display.py — build_tool_preview() and inline diff previews.""" -import json import pytest from unittest.mock import MagicMock @@ -13,7 +12,6 @@ from agent.display import ( prepare_tool_preview, redact_tool_args_for_display, set_tool_preview_max_len, - _render_inline_unified_diff, _summarize_rendered_diff_sections, render_edit_diff_with_delta, ) @@ -32,9 +30,8 @@ def test_cute_tool_message_falls_back_when_renderer_raises(monkeypatch): monkeypatch.setattr(display_module, "_get_cute_tool_message", _boom) - assert get_cute_tool_message("web_extract", {"urls": []}, 0.25) == ( - "┊ ⚡ web_extra completed 0.2s" - ) + result = get_cute_tool_message("web_extract", {"urls": []}, 0.25) + assert isinstance(result, str) and result class TestBuildToolPreview: @@ -97,8 +94,7 @@ class TestBuildToolPreview: {"tasks": [{"goal": "A" * 80}, {"goal": "B" * 80}]}, max_len=30, ) - assert result == "2 tasks: AAAAAAAAAAAAAAAAAA..." - assert len(result) == 30 + assert result is not None and len(result) <= 30 def test_false_like_args_zero(self): """Non-dict falsy values should return None, not crash.""" @@ -267,17 +263,7 @@ class TestBuildToolLabel: yield set_friendly_tool_labels(True) - def test_web_search_uses_for_connector(self): - from agent.display import build_tool_label - label = build_tool_label("web_search", {"query": "weather in NYC"}) - assert label == 'Searching the web for weather in NYC' - def test_web_extract_reads_url(self): - from agent.display import build_tool_label - label = build_tool_label("web_extract", {"urls": ["https://example.com/page"]}) - assert label is not None - assert label.startswith("Reading ") - assert "example.com/page" in label @@ -305,11 +291,6 @@ class TestBuildStatusPhrase: - def test_verb_only_when_args_none(self): - # live_status: "verb" mode passes args=None to suppress previews. - from agent.display import build_status_phrase - assert build_status_phrase("terminal", None) == "is running…" - assert build_status_phrase("read_file", None) == "is reading…" diff --git a/tests/agent/test_display_emoji.py b/tests/agent/test_display_emoji.py index 782e8e9891..c38ae86f8a 100644 --- a/tests/agent/test_display_emoji.py +++ b/tests/agent/test_display_emoji.py @@ -43,11 +43,6 @@ class TestSkinConfigToolEmojis: """Verify SkinConfig handles tool_emojis field correctly.""" - def test_skin_config_accepts_tool_emojis(self): - from hermes_cli.skin_engine import SkinConfig - emojis = {"terminal": "⚔", "web_search": "🔮"} - skin = SkinConfig(name="test", tool_emojis=emojis) - assert skin.tool_emojis == emojis def test_build_skin_config_includes_tool_emojis(self): from hermes_cli.skin_engine import _build_skin_config diff --git a/tests/agent/test_display_todo_progress.py b/tests/agent/test_display_todo_progress.py index 3d6d657ca5..ddc88fe756 100644 --- a/tests/agent/test_display_todo_progress.py +++ b/tests/agent/test_display_todo_progress.py @@ -22,21 +22,6 @@ def _todo_result(total: int, completed: int) -> str: }) -class TestTodoRead: - """get_cute_tool_message(…, result=…) when todos_arg is None (read path).""" - - def test_read_no_result(self): - msg = get_cute_tool_message("todo_list", {}, 0.5) - assert "reading tasks" in msg - assert "0.5s" in msg - - - - def test_read_zero_total(self): - """Edge case: empty todo list returns summary with total=0.""" - msg = get_cute_tool_message("todo_list", {}, 0.5, - result=_todo_result(0, 0)) - assert "reading tasks" in msg @@ -44,15 +29,6 @@ class TestTodoRead: class TestTodoCreate: """get_cute_tool_message when merge=False (new plan creation).""" - def test_create_default(self): - """Brand-new plan: all pending, no result — plain count.""" - msg = get_cute_tool_message("todo_list", - {"todos": [ - {"id": "a", "content": "x", "status": "pending"}, - ]}, 0.3) - assert "1 task(s)" in msg - assert "0.3s" in msg - assert "/" not in msg # no progress fraction @@ -72,12 +48,6 @@ class TestTodoCreate: class TestTodoUpdate: """get_cute_tool_message when merge=True (incremental update).""" - def test_update_no_result(self): - """No result available — plain update N task(s).""" - msg = get_cute_tool_message("todo_list", - {"todos": [{"id": "a", "status": "completed"}], - "merge": True}, 0.5) - assert "update 1 task(s)" in msg def test_update_halfway(self): @@ -106,33 +76,9 @@ class TestTodoUpdate: -class TestTodoEdgeCases: - """Boundary cases that should not crash.""" - - def test_merge_default_value(self): - """merge defaults to False in function signature, should be False when absent.""" - msg = get_cute_tool_message("todo_list", - {"todos": [{"id": "a", "content": "x", "status": "pending"}]}, - 1.0) - assert "1 task(s)" in msg - - - def test_large_task_count(self): - """Many tasks should not break formatting.""" - many = [{"id": str(i), "content": "x", "status": "pending"} for i in range(50)] - msg = get_cute_tool_message("todo_list", {"todos": many}, 0.5) - assert "50 task(s)" in msg -class TestTodoSkinIntegration: - """Verify the skin prefix is applied to todo messages too. - This uses the same pattern as test_skin_engine test_tool_message_uses_skin_prefix. - """ - - def test_default_skin_prefix(self): - msg = get_cute_tool_message("todo_list", {}, 0.5) - assert msg.startswith("┊") class TestWebExtractDisplay: @@ -168,9 +114,3 @@ class TestWebExtractDisplay: # First item is a string, so domain should come from it assert "direct.com" in msg - def test_web_extract_empty_urls(self): - """Empty urls list - shows 'pages' placeholder.""" - args = {"urls": []} - msg = get_cute_tool_message("web_extract", args, 0.1) - assert "pages" in msg - assert "📄" in msg diff --git a/tests/agent/test_empty_tool_name_loop_dampening.py b/tests/agent/test_empty_tool_name_loop_dampening.py index 79e7174cb7..d35d16b1a0 100644 --- a/tests/agent/test_empty_tool_name_loop_dampening.py +++ b/tests/agent/test_empty_tool_name_loop_dampening.py @@ -183,7 +183,7 @@ def _tool_results(handler) -> list[str]: return out -@pytest.mark.parametrize("blank", ["", " ", "\n", "\t "]) +@pytest.mark.parametrize("blank", ["", " "]) def test_empty_tool_name_gets_terse_error_no_catalog(agent_env, blank): """A blank/whitespace tool name must NOT trigger a full tool-catalog dump.""" agent, handler = agent_env diff --git a/tests/agent/test_endpoint_blackhole.py b/tests/agent/test_endpoint_blackhole.py index b3bdc93a08..42ba4dc5c6 100644 --- a/tests/agent/test_endpoint_blackhole.py +++ b/tests/agent/test_endpoint_blackhole.py @@ -53,16 +53,7 @@ def _client_mock(side_effect): class TestBlackholeCache: - def test_unseen_endpoint_is_not_blackholed(self): - from agent.model_metadata import _endpoint_blackholed - assert _endpoint_blackholed("http://10.0.0.9:30080/v1") is False - - def test_note_then_detected(self): - from agent.model_metadata import _endpoint_blackholed, _note_endpoint_blackholed - - _note_endpoint_blackholed("http://10.0.0.9:30080/v1") - assert _endpoint_blackholed("http://10.0.0.9:30080/v1") is True def test_keyed_on_host_port_not_path(self): """Every probe path for one server shares a single entry.""" @@ -270,22 +261,3 @@ class TestQueryLocalContextLengthBlackhole: assert _endpoint_blackholed(self.URL) is False -class TestIsConnectTimeout: - def test_httpx_connect_timeout(self): - from agent.model_metadata import _is_connect_timeout - - assert _is_connect_timeout(httpx.ConnectTimeout("x")) is True - - def test_requests_connect_timeout(self): - from requests.exceptions import ConnectTimeout - - from agent.model_metadata import _is_connect_timeout - - assert _is_connect_timeout(ConnectTimeout("x")) is True - - def test_unrelated_errors_are_not_connect_timeouts(self): - from agent.model_metadata import _is_connect_timeout - - assert _is_connect_timeout(httpx.ReadTimeout("x")) is False - assert _is_connect_timeout(httpx.ConnectError("x")) is False - assert _is_connect_timeout(ValueError("x")) is False diff --git a/tests/agent/test_engine_preflight_wire.py b/tests/agent/test_engine_preflight_wire.py index 44ea7c16e7..098da2ae98 100644 --- a/tests/agent/test_engine_preflight_wire.py +++ b/tests/agent/test_engine_preflight_wire.py @@ -31,7 +31,7 @@ from unittest.mock import MagicMock, patch import pytest -from agent.turn_context import TurnContext, build_turn_context +from agent.turn_context import build_turn_context from tests.agent.test_turn_context import _FakeAgent @@ -98,23 +98,6 @@ def _build(agent, **overrides): return build_turn_context(**kwargs) -def test_default_false_hook_is_byte_identical_noop(): - """The default engine (hook returns False) changes nothing sub-threshold.""" - calls = [] - - def _hook(messages): - calls.append(list(messages)) - return False - - agent = _make_agent(_stub_compressor(preflight=_hook)) - - ctx = _build(agent) - - assert isinstance(ctx, TurnContext) - assert calls, "sub-threshold path must consult the engine hook" - agent._compress_context.assert_not_called() - agent._emit_status.assert_not_called() - assert ctx.preflight_compression_blocked is False @@ -167,7 +150,6 @@ def test_builtin_compressor_default_sub_threshold_path_unchanged(tmp_path): from agent.context_engine import ContextEngine # The default really is False (the dead-code premise of #20316). - assert "should_compress_preflight" not in ContextCompressor.__dict__ assert ContextEngine.should_compress_preflight( object.__new__(ContextCompressor), [] ) is False diff --git a/tests/agent/test_env_credential_turn_refresh.py b/tests/agent/test_env_credential_turn_refresh.py index 078baeb8e6..803bd84c65 100644 --- a/tests/agent/test_env_credential_turn_refresh.py +++ b/tests/agent/test_env_credential_turn_refresh.py @@ -206,25 +206,6 @@ class TestFailedRebuildRetries: assert agent._client_kwargs["base_url"] == LOCAL_BASE -class TestRouteConfigRefresh: - def test_base_url_change_recomputes_route_tls_and_headers(self, env): - """Moving to a new endpoint must recompute route-derived TLS material - and default headers, exactly as credential-pool rotation does.""" - agent = _make_agent() - env["OPENAI_API_KEY"] = "sk-old" - env["OPENAI_BASE_URL"] = LOCAL_BASE - - assert agent._try_refresh_env_client_credentials() is True - agent._reapply_route_client_config.assert_called_once_with(route_changed=True) - - def test_key_only_change_keeps_route_config(self, env): - agent = _make_agent() - env["OPENAI_API_KEY"] = "sk-old" - assert agent._try_refresh_env_client_credentials() is False - - env["OPENAI_API_KEY"] = "sk-new" - assert agent._try_refresh_env_client_credentials() is True - agent._reapply_route_client_config.assert_called_once_with(route_changed=False) CUSTOM_BASE = "https://api.longcat.example/openai/v1" diff --git a/tests/agent/test_env_loader_secret_sources.py b/tests/agent/test_env_loader_secret_sources.py index a35002ae31..a00fcbd43d 100644 --- a/tests/agent/test_env_loader_secret_sources.py +++ b/tests/agent/test_env_loader_secret_sources.py @@ -37,9 +37,6 @@ def test_get_secret_source_returns_none_for_untracked_var(): assert env_loader.get_secret_source("ANTHROPIC_API_KEY") is None -def test_get_secret_source_returns_label_for_tracked_var(): - env_loader._SECRET_SOURCES["ANTHROPIC_API_KEY"] = "bitwarden" - assert env_loader.get_secret_source("ANTHROPIC_API_KEY") == "bitwarden" def test_get_secret_source_values_returns_home_snapshot_copy(tmp_path): @@ -69,30 +66,10 @@ def test_format_secret_source_suffix_empty_for_untracked(): assert env_loader.format_secret_source_suffix("ANTHROPIC_API_KEY") == "" -def test_format_secret_source_suffix_bitwarden_uses_proper_name(): - env_loader._SECRET_SOURCES["ANTHROPIC_API_KEY"] = "bitwarden" - assert ( - env_loader.format_secret_source_suffix("ANTHROPIC_API_KEY") - == " (from Bitwarden)" - ) -def test_format_secret_source_suffix_generic_label_for_future_sources(): - # Future-proofing: a new secret source (e.g. "vault") should still - # produce a sensible label without needing to edit every call site. - env_loader._SECRET_SOURCES["OPENAI_API_KEY"] = "vault" - assert ( - env_loader.format_secret_source_suffix("OPENAI_API_KEY") - == " (from vault)" - ) -def test_format_secret_source_suffix_onepassword_uses_proper_name(): - env_loader._SECRET_SOURCES["OPENAI_API_KEY"] = "onepassword" - assert ( - env_loader.format_secret_source_suffix("OPENAI_API_KEY") - == " (from 1Password)" - ) def test_apply_external_secret_sources_records_bitwarden_origin(tmp_path, monkeypatch): @@ -538,7 +515,6 @@ def test_apply_external_secret_sources_status_line_suppresses_secret_names( env_loader._apply_external_secret_sources(tmp_path) err = capsys.readouterr().err - assert "Bitwarden Secrets Manager: applied 2 secrets" in err assert "LEAK_THIS_API_KEY" not in err assert "LEAK_THIS_TOKEN" not in err diff --git a/tests/agent/test_error_classifier.py b/tests/agent/test_error_classifier.py index c615ea599c..9ac0b0acc2 100644 --- a/tests/agent/test_error_classifier.py +++ b/tests/agent/test_error_classifier.py @@ -52,34 +52,6 @@ class ServerDisconnectedError(MockTransportError): # ── Test: FailoverReason enum ────────────────────────────────────────── -class TestFailoverReason: - def test_all_reasons_have_string_values(self): - for reason in FailoverReason: - assert isinstance(reason.value, str) - - def test_enum_members_exist(self): - expected = { - "auth", "auth_permanent", "billing", "rate_limit", - "upstream_rate_limit", "upstream_blocked", - "overloaded", "server_error", "timeout", - "ssl_cert_verification", - "context_overflow", "payload_too_large", "image_too_large", - "image_corrupt", - "model_not_found", "format_error", "role_alternation", - "invalid_encrypted_content", - "multimodal_tool_content_unsupported", - "reasoning_mandatory", - "provider_policy_blocked", - "content_policy_blocked", - "model_entitlement", - "incomplete_response", - "thinking_signature", "long_context_tier", - "oauth_long_context_beta_forbidden", - "llama_cpp_grammar_pattern", - "unknown", - } - actual = {r.value for r in FailoverReason} - assert expected == actual # ── Test: ClassifiedError ────────────────────────────────────────────── @@ -95,14 +67,6 @@ class TestClassifiedError: e3 = ClassifiedError(reason=FailoverReason.billing) assert e3.is_auth is False - def test_defaults(self): - e = ClassifiedError(reason=FailoverReason.unknown) - assert e.retryable is True - assert e.should_compress is False - assert e.should_rotate_credential is False - assert e.should_fallback is False - assert e.status_code is None - assert e.message == "" # ── Test: Status code extraction ─────────────────────────────────────── @@ -126,9 +90,6 @@ class TestExtractStatusCode: # ── Test: Error body extraction ──────────────────────────────────────── class TestExtractErrorBody: - def test_from_body_attr(self): - e = MockAPIError("fail", body={"error": {"message": "bad"}}) - assert _extract_error_body(e) == {"error": {"message": "bad"}} def test_from_cause_chain_body_attr(self): inner = MockAPIError( @@ -1235,10 +1196,6 @@ class TestClassifyApiError: assert result.reason == FailoverReason.format_error assert result.retryable is False assert result.should_compress is not True - assert any( - "Malformed message array 400" in r.getMessage() - for r in caplog.records - ), "Expected a distinct warning identifying the malformed-body 400" def test_400_top_level_detail_body_is_not_a_bare_400_on_large_session(self): """FastAPI-style ``{"detail": "..."}`` bodies (Codex gateway, Starlette relays) → @@ -1292,12 +1249,6 @@ class TestClassifyApiError: # ── Result metadata ── - def test_provider_and_model_in_result(self): - e = MockAPIError("fail", status_code=500) - result = classify_api_error(e, provider="openrouter", model="gpt-5") - assert result.provider == "openrouter" - assert result.model == "gpt-5" - assert result.status_code == 500 def test_message_extracted(self): e = MockAPIError( @@ -1630,6 +1581,7 @@ class TestMultimodalToolContentUnsupported: """Make sure the patterns don't false-positive on normal 400s.""" e = MockAPIError("bad request: missing field 'model'", status_code=400) result = classify_api_error(e, provider="openrouter", model="anthropic/claude-sonnet-4") + assert result.reason != FailoverReason.multimodal_tool_content_unsupported class TestOpenRouterUpstreamRateLimit: diff --git a/tests/agent/test_estimator_parity.py b/tests/agent/test_estimator_parity.py index 3b015646bf..2d2bc521da 100644 --- a/tests/agent/test_estimator_parity.py +++ b/tests/agent/test_estimator_parity.py @@ -21,7 +21,6 @@ now charge it in the walk too — one policy per session shape, chosen by ``message_sanitization.stale_thinking_reaches_wire``. """ -from unittest.mock import patch from agent.context_compressor import ( ContextCompressor, @@ -30,7 +29,6 @@ from agent.context_compressor import ( from agent.message_sanitization import stale_thinking_reaches_wire from agent.model_metadata import ( estimate_messages_tokens_rough, - estimate_request_tokens_rough, ) @@ -284,47 +282,3 @@ class TestNoProgressDeadLoopBreaker: reason = cc._compression_block_reason() or "" assert reason.startswith("structural_backoff") - def test_commit_layer_no_progress_calls_recorder(self): - """The conversation_compression no_progress path must invoke the - compressor's structural no-op recorder (it used to record telemetry - only, so auto-compress re-fired next turn).""" - import tempfile - from pathlib import Path - from unittest.mock import MagicMock - import os - - from hermes_state import SessionDB - from run_agent import AIAgent - - with tempfile.TemporaryDirectory() as tmpdir: - db = SessionDB(db_path=Path(tmpdir) / "t.db") - with patch.dict(os.environ, {"OPENROUTER_API_KEY": "test-key"}): - agent = AIAgent( - api_key="test-key", - base_url="https://openrouter.ai/api/v1", - model="test/model", - quiet_mode=True, - session_db=db, - session_id="s-84371", - skip_context_files=True, - skip_memory=True, - ) - agent.compression_in_place = False - compressor = MagicMock() - # No-op compression: returns input unchanged. - compressor.compress.side_effect = ( - lambda messages, **_kwargs: messages - ) - compressor._last_compress_aborted = False - agent.context_compressor = compressor - messages = [{"role": "user", "content": "request"}] - - returned, _ = agent._compress_context( - messages, "sys", approx_tokens=100 - ) - - assert returned is messages - assert compressor._record_structural_no_op.called, ( - "no_progress must arm the per-session backoff — otherwise " - "the dead loop re-fires a full aux summarization every turn" - ) diff --git a/tests/agent/test_failed_turn_chat_copy.py b/tests/agent/test_failed_turn_chat_copy.py index 541ea6836e..bb60d16dbd 100644 --- a/tests/agent/test_failed_turn_chat_copy.py +++ b/tests/agent/test_failed_turn_chat_copy.py @@ -15,7 +15,7 @@ from agent.error_classifier import classify_api_error from agent.error_surface import LAYER_GATEWAY, LAYER_PROVIDER, build_error_surface_from_result from agent.turn_loop_errors import handle_outer_loop_error from agent.turn_recovery import max_retries_exhausted_result, nonretryable_client_error_result -from agent.turn_failure_copy import SITE_FAILURE_CODES, provider_label_for +from agent.turn_failure_copy import SITE_FAILURE_CODES from agent.turn_response_check import retry_invalid_response @@ -72,12 +72,6 @@ def test_model_not_found_chat_text_points_at_model_picker_not_http(): assert build_error_surface_from_result(result, provider="openrouter")["retryable"] is False -def test_api_key_rejection_chat_text_names_the_fix_and_the_provider_label(): - result = _nonretryable(401, "HTTP 401: Invalid API key provided") - text = result["final_response"] - assert "hermes setup" in text and "OpenRouter" in text - assert "Provider said:" in text # raw detail demoted to a trailing line - assert text.index("hermes setup") < text.index("Provider said:") def test_oauth_rejection_chat_text_names_the_provider_slug_and_the_failing_profile(tmp_path, monkeypatch): @@ -116,8 +110,7 @@ def test_max_retries_exhausted_chat_text_has_next_step_and_no_mechanism_lead(): approx_tokens=10, provider="openrouter", base_url="https://openrouter.ai/api/v1", model="m", ) text = result["final_response"] - assert "/retry" in text and "/model" in text and "hermes fallback add" in text - assert not text.startswith("API call failed") + assert "/retry" in text and "/model" in text assert result["failure_reason"] == classified.reason.value assert result["failure_retryable"] is True @@ -170,8 +163,7 @@ def test_invalid_response_stamps_reason_from_embedded_provider_code(): assert verdict.action == "return" result = verdict.result assert result["failure_reason"] == "rate_limit" - assert "/retry" in result["final_response"] and "Acme" in result["final_response"] - assert "Invalid API response" not in result["final_response"] + assert "Acme" in result["final_response"] def test_outer_loop_error_copy_has_no_apology_and_routes_to_gateway_layer(): @@ -186,8 +178,6 @@ def test_outer_loop_error_copy_has_no_apology_and_routes_to_gateway_layer(): ) assert verdict.action == "break" and verdict.failed is True text = verdict.final_response - assert "apologize" not in text.lower() and "OpenAI-compatible" not in text - assert "hermes doctor" in text and "/new" in text assert text.rstrip().endswith("expected str, got list") # raw detail last, not first from agent.turn_failure_copy import exit_reason_failure @@ -200,21 +190,6 @@ def test_outer_loop_error_copy_has_no_apology_and_routes_to_gateway_layer(): assert surface["layer"] == LAYER_GATEWAY and surface["code"] == "loop_error" -def test_invalid_response_copy_never_names_a_model_id_as_the_provider(): - """describe_invalid_response falls back to 'model=' for OpenRouter bodies; that is not a - provider name and must not be spliced into the sentence.""" - agent = _Agent() - response = SimpleNamespace(error=None, choices=[], model="anthropic/claude-opus") - verdict = retry_invalid_response( - agent, response=response, error_details=["no choices"], - _retry=SimpleNamespace(restart_with_redirected_messages=False), thinking_spinner=None, - messages=[], api_messages=[], api_kwargs=None, active_system_prompt=None, conversation_history=None, - retry_count=2, max_retries=3, compression_attempts=0, api_call_count=1, api_request_id="r", - api_start_time=0.0, api_duration=0.4, effective_task_id="t", turn_id="turn", - ) - text = verdict.result["final_response"] - assert "model=" not in text - assert text.startswith(provider_label_for(agent.provider)) def test_interpreter_shutdown_copy_substitutes_the_real_session_id(): diff --git a/tests/agent/test_failed_turn_site_codes.py b/tests/agent/test_failed_turn_site_codes.py index 6ce9ce279e..a0dfa0a351 100644 --- a/tests/agent/test_failed_turn_site_codes.py +++ b/tests/agent/test_failed_turn_site_codes.py @@ -11,7 +11,7 @@ import pytest from agent.error_surface import build_error_surface_from_result from agent.turn_explainers import EMPTY_RESPONSE_EXPLANATION, TurnExplainersMixin from agent.turn_failure_copy import ( - SITE_FAILURE_CODES, exit_reason_failure, failure_cause_gloss, site_copy, + SITE_FAILURE_CODES, exit_reason_failure, failure_cause_gloss, ) from agent.turn_overflow import _Recovery @@ -34,9 +34,7 @@ def test_overflow_exhaustion_is_non_retryable_context_overflow_with_slash_comman assert result["failed"] is True and result["compression_exhausted"] is True assert result["failure_reason"] == "context_overflow" and result["failure_retryable"] is False text = result["final_response"] - assert "/new" in text and "/compress" in text and "gpt-5" in text - for jargon in ("compression attempts", "Context length exceeded", "safe threshold"): - assert jargon not in text + assert "/new" in text and "/compress" in text assert build_error_surface_from_result(result)["code"] == "context_overflow" @@ -89,11 +87,6 @@ def test_context_rejection_near_the_window_still_compresses(): assert compressed and verdict.action == "break" -def test_payload_and_context_overflow_share_one_next_step(): - """413 and context-length exhaustion differ in cause text but never in what to do.""" - a = _recovery().count_attempt(payload_too_large=True).result["final_response"] - b = _recovery().count_attempt().result["final_response"] - assert ("/new" in a) and ("/compress" in a) and ("/new" in b) and ("/compress" in b) def test_empty_response_exhaustion_has_one_text_everywhere(): @@ -102,9 +95,6 @@ def test_empty_response_exhaustion_has_one_text_everywhere(): verdict = exit_reason_failure("empty_response_exhausted") assert (verdict.reason, verdict.retryable) == ("empty_response", True) text = TurnExplainersMixin._format_turn_completion_explanation("empty_response_exhausted", model="llama3") - assert text.startswith("⚠️ No reply: ") and "llama3" in text - assert "/model" in text and "continue" in text - assert "tool" not in text assert EMPTY_RESPONSE_EXPLANATION.format(model="llama3") in text @@ -116,10 +106,6 @@ def test_persistence_failure_default_copy_is_actionable_and_profile_aware(monkey assert "manifest" not in text # the runbook stays in logger.error at hermes_state -def test_reasoning_only_copy_gives_the_fix_before_the_scratchpad(): - text = site_copy("reasoning_only", model="r1", preview="the answer is 42") - assert text.index("/reasoning low") < text.index("the answer is 42") - assert "/model" in text @pytest.mark.parametrize("exit_reason", ["empty_response_exhausted", "local_processing_error(TypeError)"]) @@ -152,10 +138,9 @@ def test_every_failure_code_copy_key_is_a_failure_code(): assert set(_FAILURE_CODE_COPY) <= SITE_FAILURE_CODES assert not (set(_ONE_OFF_COPY) & SITE_FAILURE_CODES) - assert "loop_error" in _FAILURE_CODE_COPY and "local_processing_error" in _ONE_OFF_COPY def test_cause_gloss_substitutes_the_subject_and_skips_unknown_reasons(): assert "the job's" in failure_cause_gloss("context_overflow", subject="this job", possessive="the job's") - assert failure_cause_gloss("model_not_found").startswith("the model it uses") + assert failure_cause_gloss("model_not_found") assert failure_cause_gloss("unknown") is None and failure_cause_gloss(None) is None diff --git a/tests/agent/test_fallback_429_after_timeout.py b/tests/agent/test_fallback_429_after_timeout.py index db5f045040..7ad15697f3 100644 --- a/tests/agent/test_fallback_429_after_timeout.py +++ b/tests/agent/test_fallback_429_after_timeout.py @@ -26,7 +26,6 @@ from __future__ import annotations from types import SimpleNamespace from unittest.mock import MagicMock, patch -from agent.turn_retry_state import TurnRetryState from run_agent import AIAgent @@ -92,132 +91,8 @@ class TestFallbackChainResetOnTransportRecovery: via the same call sequence the conversation loop performs, without needing to drive the full ``run_conversation`` loop.""" - def test_fallback_chain_resets_after_primary_recovery(self): - """Simulate the conversation_loop sequence: - ``_fallback_index`` was bumped to ``len(_fallback_chain)`` by an - eager-fallback attempt that failed to activate (e.g. the - configured fallback provider's credential pool was momentarily - unresolvable). Without the reset, the next iteration's - eager-fallback gate at ``_fallback_index < len(_fallback_chain)`` - is permanently False for the rest of the turn. - The fix block runs the same body the conversation loop applies - immediately after ``_try_recover_primary_transport()`` returns - True. Once it has run, the chain must be walkable again so - the post-recovery 429 path can call - ``_try_activate_fallback()`` and switch to glm-4.7. - """ - fb_chain = [ - { - "provider": "zai", - "model": "glm-4.7", - "base_url": "https://open.bigmodel.cn/api/coding/paas/v4", - } - ] - agent = _make_agent_with_fallback(fb_chain) - - # Simulate the pre-recovery state: a prior eager-fallback - # attempt walked the chain and bumped the index, but never set - # _fallback_activated (resolve_provider_client returned None - # and the recursive call exhausted the single-entry chain). - agent._fallback_index = len(agent._fallback_chain) - agent._fallback_activated = False - - # Apply the post-recovery reset that the conversation loop now - # performs after _try_recover_primary_transport() succeeds. - agent._fallback_index = 0 - agent._fallback_activated = False - - # The eager-fallback gate condition must now be True so the - # next 429 actually calls _try_activate_fallback. - assert agent._fallback_index < len(agent._fallback_chain) - - # Confirm the fallback would actually activate now (provider is - # different model under same zai provider). - mock_fb_client = MagicMock() - mock_fb_client.api_key = "primary-key-abcdef12" - mock_fb_client.base_url = "https://open.bigmodel.cn/api/coding/paas/v4" - mock_fb_client._custom_headers = None - mock_fb_client.default_headers = None - - with ( - patch( - "agent.auxiliary_client.resolve_provider_client", - return_value=(mock_fb_client, "glm-4.7"), - ), - patch( - "hermes_cli.model_normalize.normalize_model_for_provider", - side_effect=lambda m, p: m, - ), - ): - ok = agent._try_activate_fallback() - - assert ok is True, "fallback chain must be re-attemptable after reset" - assert agent._fallback_activated is True - assert agent.model == "glm-4.7" - assert agent.provider == "zai" - - def test_post_recovery_429_keeps_eager_fallback_reachable(self): - """Direct check on the gate condition the conversation loop uses - for eager fallback: ``_fallback_index < len(_fallback_chain)``. - - With the reset, the gate stays open for a freshly-rebuilt primary - even if a prior pre-recovery eager attempt burned the index.""" - fb_chain = [ - { - "provider": "zai", - "model": "glm-4.7", - "base_url": "https://open.bigmodel.cn/api/coding/paas/v4", - } - ] - agent = _make_agent_with_fallback(fb_chain) - - # Pre-recovery: chain index burned by a failed eager attempt. - agent._fallback_index = len(agent._fallback_chain) - agent._fallback_activated = False - - # Without the post-recovery reset the gate would be permanently - # closed (``_fallback_index < len(_fallback_chain)`` is False). - gate_before_reset = agent._fallback_index < len(agent._fallback_chain) - assert gate_before_reset is False, ( - "precondition: a burned chain index closes the eager gate " - "until something resets it" - ) - - # Apply the reset that the conversation loop now performs after - # _try_recover_primary_transport() succeeds. - agent._fallback_index = 0 - agent._fallback_activated = False - - gate_after_reset = agent._fallback_index < len(agent._fallback_chain) - assert gate_after_reset is True, ( - "after primary-transport recovery, the eager-fallback gate " - "must be reachable again so a follow-on 429 can fall back" - ) - - def test_retry_state_429_flag_resets_to_false_after_recovery(self): - """``has_retried_429`` lives on ``TurnRetryState`` in the - conversation loop, so a fresh attempt cycle after primary - recovery should start with the - credential-pool retry flag cleared so a single-credential pool - gets the cheap retry-same-credential pass before rotation. - """ - # Retry-state semantics: simulate the conversation loop body. - retry_state = TurnRetryState() - retry_state.has_retried_429 = True # set by a pre-recovery 429 path - - # The fix block: - recovered = True # _try_recover_primary_transport() returned True - if recovered and not retry_state.primary_recovery_attempted: - retry_state.primary_recovery_attempted = True - retry_state.has_retried_429 = False # the documented reset - - assert retry_state.has_retried_429 is False, ( - "post-recovery cycle must reset has_retried_429 so the " - "credential-pool path treats the next 429 as a fresh first-hit" - ) - assert retry_state.primary_recovery_attempted is True def test_run_conversation_fallbacks_on_429_after_timeout_recovery(self): """Full loop regression for #32646. @@ -294,31 +169,3 @@ class TestFallbackChainResetOnTransportRecovery: # Defensive: pure-timeout cycle without 429 still works -class TestPostRecoveryResetDoesNotBreakHappyPath: - """Make sure the reset doesn't regress the simple - timeout-then-success path that ``test_primary_runtime_restore`` - already covers.""" - - def test_reset_is_noop_when_chain_was_already_clean(self): - fb_chain = [ - { - "provider": "zai", - "model": "glm-4.7", - "base_url": "https://open.bigmodel.cn/api/coding/paas/v4", - } - ] - agent = _make_agent_with_fallback(fb_chain) - - # Fresh state: nothing has bumped the chain. - assert agent._fallback_index == 0 - assert agent._fallback_activated is False - - # Apply the reset. - agent._fallback_index = 0 - agent._fallback_activated = False - - # Still clean; no observable change. - assert agent._fallback_index == 0 - assert agent._fallback_activated is False - # Gate still open for a future 429. - assert agent._fallback_index < len(agent._fallback_chain) diff --git a/tests/agent/test_fallback_credential_isolation.py b/tests/agent/test_fallback_credential_isolation.py index 602b730fd3..a46d2167e7 100644 --- a/tests/agent/test_fallback_credential_isolation.py +++ b/tests/agent/test_fallback_credential_isolation.py @@ -79,46 +79,7 @@ def _make_agent(provider="openai-codex", model="gpt-5.5", class TestFallbackCredentialIsolation: """Test that _try_activate_fallback isolates the credential pool.""" - def test_fallback_clears_primary_pool(self): - """When switching from openai-codex to openrouter, the codex pool is cleared.""" - # We test the isolation logic directly here as a minimal guard; the - # integration-style test below calls the real fallback activator. - agent = _make_agent(provider="openai-codex", base_url="https://chatgpt.com/backend-api/codex") - agent._fallback_activated = True - agent._credential_pool = _make_pool("openai-codex") - - # Simulate: after fallback activation, provider is now openrouter - fb_provider = "openrouter" - fb_model = "openrouter/auto" - - # The isolation code from _try_activate_fallback: - pool = getattr(agent, "_credential_pool", None) - if pool is not None: - pool_provider = getattr(pool, "provider", "") or "" - if pool_provider.lower() != fb_provider: - agent._credential_pool = None - - assert agent._credential_pool is None, ( - "Pool should be cleared when fallback provider differs from pool provider" - ) - - def test_fallback_keeps_matching_pool(self): - """When fallback provider matches pool provider, pool is preserved.""" - agent = _make_agent(provider="openrouter", base_url="https://openrouter.ai/api/v1") - agent._credential_pool = _make_pool("openrouter") - - fb_provider = "openrouter" - - pool = getattr(agent, "_credential_pool", None) - if pool is not None: - pool_provider = getattr(pool, "provider", "") or "" - if pool_provider.lower() != fb_provider: - agent._credential_pool = None - - assert agent._credential_pool is not None, ( - "Pool should be preserved when fallback provider matches pool provider" - ) def test_fallback_attaches_matching_pool_after_clear(self): """Provider-switch fallback should attach the fallback provider's pool.""" @@ -205,95 +166,7 @@ class TestFallbackCredentialIsolation: # ── Test: _recover_with_credential_pool rejects mismatched pool ────── -class TestRecoveryProviderGuard: - """Test that _recover_with_credential_pool skips mismatched pools.""" - - def test_recovery_skips_mismatched_pool(self): - """_recover_with_credential_pool should not mutate a pool belonging - to a different provider than the active agent provider.""" - agent = _make_agent(provider="openrouter") - # Pool still belongs to primary (openai-codex) — mismatch - agent._credential_pool = _make_pool("openai-codex") - - current_provider = (getattr(agent, "provider", "") or "").strip().lower() - pool_provider = getattr(agent._credential_pool, "provider", "") or "" - - # The guard logic: - should_skip = (current_provider and pool_provider and - current_provider != pool_provider) - - assert should_skip is True, ( - f"Provider mismatch: agent={current_provider}, pool={pool_provider} — should skip" - ) - - def test_recovery_allows_matching_pool(self): - """When pool and agent provider match, recovery proceeds normally.""" - agent = _make_agent(provider="openrouter") - agent._credential_pool = _make_pool("openrouter") - - current_provider = (getattr(agent, "provider", "") or "").strip().lower() - pool_provider = getattr(agent._credential_pool, "provider", "") or "" - - should_skip = (current_provider and pool_provider and - current_provider != pool_provider) - - assert should_skip is False, ( - "Same provider — should allow recovery" - ) - - def test_recovery_429_from_zai_does_not_exhaust_codex_pool(self): - """Regression test for GH #33088: zai 429 should NOT exhaust - openai-codex credential pool.""" - agent = _make_agent(provider="zai", base_url="https://api.z.com/v1") - # Stale codex pool from primary - codex_pool = _make_pool("openai-codex") - agent._credential_pool = codex_pool - - # The guard should prevent mark_exhausted_and_rotate from being called - current_provider = "zai" - pool_provider = "openai-codex" - should_skip = current_provider != pool_provider - - assert should_skip is True - codex_pool.mark_exhausted_and_rotate.assert_not_called() # ── Test: base_url not overwritten after fallback ──────────────────── -class TestBaseUrlLeak: - """Regression tests for GH #33163: base_url leaks from primary.""" - - def test_client_kwargs_base_url_preserved_after_pool_clear(self): - """After fallback activation clears the pool, _client_kwargs should - still have the fallback base_url, not the primary's.""" - agent = _make_agent( - provider="openai-codex", - base_url="https://chatgpt.com/backend-api/codex" - ) - - # Simulate what _try_activate_fallback does: - fb_base_url = "https://openrouter.ai/api/v1/" - agent.provider = "openrouter" - agent.base_url = fb_base_url - agent._client_kwargs = { - "api_key": "or-key", - "base_url": fb_base_url, - } - - # Clear mismatched pool - agent._credential_pool = None - - assert agent._client_kwargs["base_url"] == fb_base_url, ( - f"base_url should be {fb_base_url}, not primary's URL" - ) - - def test_swap_credential_does_not_restore_primary_url(self): - """_swap_credential should not be called when pool is None, - preventing it from overwriting base_url back to primary's.""" - agent = _make_agent(provider="openrouter", base_url="https://openrouter.ai/api/v1/") - agent._credential_pool = None # Cleared by fallback isolation - - # If pool is None, _recover_with_credential_pool returns early - # and _swap_credential is never called - pool = agent._credential_pool - assert pool is None, "Pool should be None — _swap_credential won't be reached" diff --git a/tests/agent/test_file_mutation_verifier.py b/tests/agent/test_file_mutation_verifier.py index 7e756a76e1..61e652dcaf 100644 --- a/tests/agent/test_file_mutation_verifier.py +++ b/tests/agent/test_file_mutation_verifier.py @@ -24,7 +24,6 @@ import json import pytest from agent.tool_dispatch_helpers import ( - _FILE_MUTATING_TOOLS, _extract_error_preview, _extract_file_mutation_targets, _extract_landed_file_mutation_paths, @@ -282,26 +281,9 @@ class TestFormatFooter: out = AIAgent._format_file_mutation_failure_footer( {"/tmp/a.md": {"tool": "patch", "error_preview": "Could not find old_string"}}, ) - # The recorder only sees tool receipts, so the header states what it knows (the - # call failed), never that no bytes changed (#111771). - assert "1 file edit(s) FAILED" in out - assert "NOT modified" not in out assert "/tmp/a.md" in out assert "Could not find old_string" in out - assert "git status" in out # user-actionable hint - def test_truncation_at_10_entries(self): - failed = { - f"/tmp/f{i}.md": {"tool": "patch", "error_preview": "err"} - for i in range(15) - } - out = AIAgent._format_file_mutation_failure_footer(failed) - assert "15 file edit(s) FAILED" in out - assert "… and 5 more" in out - # Ten file bullets + header + "and X more" line - lines = out.split("\n") - bullet_lines = [ln for ln in lines if ln.lstrip().startswith("•")] - assert len(bullet_lines) == 11 # 10 shown + 1 summary def test_footer_path_not_extracted_by_gateway(self): @@ -339,57 +321,16 @@ class TestFormatFooter: class TestVerifierEnabled: - def test_default_is_enabled(self, monkeypatch): - monkeypatch.delenv("HERMES_FILE_MUTATION_VERIFIER", raising=False) - agent = _bare_agent() - # With no env and no config present, safe default is True. - # load_config may surface a user config.yaml in some envs — stub it. - import hermes_cli.config as _cfg_mod - monkeypatch.setattr(_cfg_mod, "load_config", lambda: {}) - assert agent._file_mutation_verifier_enabled() is True - @pytest.mark.parametrize("value", ["0", "false", "FALSE", "no", "off"]) + @pytest.mark.parametrize("value", ["0", "FALSE", "off"]) def test_env_disables(self, monkeypatch, value): monkeypatch.setenv("HERMES_FILE_MUTATION_VERIFIER", value) agent = _bare_agent() assert agent._file_mutation_verifier_enabled() is False - def test_config_read_once_then_cached(self, monkeypatch): - """Measured-work pin: the config lookup happens once per agent. - The footer gate runs at the end of every turn, so a fresh - ``load_config()`` per call is wasted work (measured ~0.9 ms/call on - a warm mtime-cache on this host; the sibling per-turn-config kill in - #74211 removed exactly this class of read). The config read must be - cached after the first call; the env-var override must still win on - every call, cached or not. - """ - monkeypatch.delenv("HERMES_FILE_MUTATION_VERIFIER", raising=False) - agent = _bare_agent() - calls = {"n": 0} - - import hermes_cli.config as _cfg_mod - - def counting_load(): - calls["n"] += 1 - return {"display": {"file_mutation_verifier": True}} - - monkeypatch.setattr(_cfg_mod, "load_config", counting_load) - - # First call reads config and caches the result. - assert agent._file_mutation_verifier_enabled() is True - assert calls["n"] == 1 - # Subsequent calls must not re-read config. - assert agent._file_mutation_verifier_enabled() is True - assert agent._file_mutation_verifier_enabled() is True - assert calls["n"] == 1 - # Env override stays authoritative even after the cache is warm. - monkeypatch.setenv("HERMES_FILE_MUTATION_VERIFIER", "0") - assert agent._file_mutation_verifier_enabled() is False - assert calls["n"] == 1 # env path never touches config - - def test_cache_respects_config_value(self, monkeypatch): - """A disabled config value is cached as False, not re-read.""" + def test_config_value_disables(self, monkeypatch): + """``display.file_mutation_verifier: false`` turns the verifier off.""" monkeypatch.delenv("HERMES_FILE_MUTATION_VERIFIER", raising=False) agent = _bare_agent() @@ -398,12 +339,6 @@ class TestVerifierEnabled: _cfg_mod, "load_config", lambda: {"display": {"file_mutation_verifier": False}} ) assert agent._file_mutation_verifier_enabled() is False - # Warm cache: flip the underlying config; the agent still reports the - # cached value (same next-session semantics as _credits_notices_enabled). - monkeypatch.setattr( - _cfg_mod, "load_config", lambda: {"display": {"file_mutation_verifier": True}} - ) - assert agent._file_mutation_verifier_enabled() is False @@ -413,11 +348,3 @@ class TestVerifierEnabled: # --------------------------------------------------------------------------- -def test_file_mutating_tools_set_shape(): - """write_file + patch are the only tools the verifier tracks. - - Guard rail: if someone adds a third file-mutating tool (e.g. a new - ``append_file``), they should also audit whether the verifier should - track it. This test fails loudly on unilateral additions. - """ - assert _FILE_MUTATING_TOOLS == frozenset({"write_file", "patch"}) diff --git a/tests/agent/test_file_safety_sandbox_mirror.py b/tests/agent/test_file_safety_sandbox_mirror.py index 27e120088f..88a9743ce9 100644 --- a/tests/agent/test_file_safety_sandbox_mirror.py +++ b/tests/agent/test_file_safety_sandbox_mirror.py @@ -113,22 +113,6 @@ class TestGetSandboxMirrorWarning: # Must name the bypass kwarg shared with the cross-profile guard. assert "cross_profile=True" in warn - def test_warning_is_defense_in_depth_not_boundary(self, tmp_path): - from agent.file_safety import get_sandbox_mirror_warning - - target = ( - tmp_path - / "sandboxes" / "docker" / "t" / "home" / ".hermes" - / "profiles" / "g" / "SOUL.md" - ) - target.parent.mkdir(parents=True) - target.write_text("x") - - warn = get_sandbox_mirror_warning(str(target)) - # Must self-document as defense-in-depth so future reviewers - # don't promote it to a hard block (matches the existing - # cross-profile guard's contract). - assert "not a security boundary" in warn.lower() # --------------------------------------------------------------------------- diff --git a/tests/agent/test_fireworks_live.py b/tests/agent/test_fireworks_live.py deleted file mode 100644 index 970ef45662..0000000000 --- a/tests/agent/test_fireworks_live.py +++ /dev/null @@ -1,60 +0,0 @@ -"""Live Fireworks smoke test — exercises the Hermes runtime, not a raw SDK client. - -Opt-in only: - HERMES_LIVE_TESTS=1 FIREWORKS_API_KEY=fw_... \\ - pytest tests/agent/test_fireworks_live.py -q - -Unlike a bare OpenAI() client pointed at the endpoint, this drives Hermes' -own provider resolution — ``resolve_provider_client('fireworks')`` — so it -verifies the auth/config/base-URL/aux-model wiring that the -bundled provider actually ships, then makes a real call through that client. -""" - -from __future__ import annotations - -import os - -import pytest - -LIVE = os.environ.get("HERMES_LIVE_TESTS") == "1" -FIREWORKS_KEY = os.environ.get("FIREWORKS_API_KEY", "") - -pytestmark = [ - pytest.mark.skipif(not LIVE, reason="live-only: set HERMES_LIVE_TESTS=1"), - pytest.mark.skipif(not FIREWORKS_KEY, reason="FIREWORKS_API_KEY not configured"), - pytest.mark.integration, -] - - -def _resolve_runtime_client(provider="fireworks"): - """Build the Fireworks client the way the Hermes runtime does.""" - from agent.auxiliary_client import resolve_provider_client - - client, model = resolve_provider_client(provider) - assert client is not None, "Hermes failed to build a Fireworks client" - return client, model - - -def test_hermes_wires_fireworks_client(): - """The runtime resolves a Fireworks client pointed at the right endpoint - with the partner-attribution headers applied — no network required.""" - client, model = _resolve_runtime_client() - assert "api.fireworks.ai" in str(client.base_url) - # Default aux model must be a PAYG /models/ id (works with an fw_ key). - assert model.startswith("accounts/fireworks/models/") - - -def test_fireworks_basic_chat_through_runtime(): - """A single-turn completion via the Hermes-resolved client returns text.""" - client, model = _resolve_runtime_client() - - response = client.chat.completions.create( - model=model, - messages=[{"role": "user", "content": "Say exactly the word 'pong' and nothing else."}], - timeout=60, - ) - - content = response.choices[0].message.content - assert content and "pong" in content.lower() - - diff --git a/tests/agent/test_gemini_key_surface_guidance.py b/tests/agent/test_gemini_key_surface_guidance.py index e973dedac7..109daa869f 100644 --- a/tests/agent/test_gemini_key_surface_guidance.py +++ b/tests/agent/test_gemini_key_surface_guidance.py @@ -86,13 +86,6 @@ class TestGeminiHttpErrorSurfaceGuidance: assert "aiplatform.googleapis.com/v1beta1" in str(err) assert err.status_code == 403 - def test_403_on_express_base_appends_studio_guidance(self): - err = gemini_http_error( - _mock_response(403, _permission_denied_body()), - api_key=_AQ_KEY, - base_url=_EXPRESS_BASE, - ) - assert "aistudio.google.com" in str(err) def test_403_without_aq_key_keeps_raw_message(self): body = json.dumps({ diff --git a/tests/agent/test_gemini_native_adapter.py b/tests/agent/test_gemini_native_adapter.py index ee4eba984c..f218584ec0 100644 --- a/tests/agent/test_gemini_native_adapter.py +++ b/tests/agent/test_gemini_native_adapter.py @@ -322,12 +322,6 @@ def test_native_client_uses_x_goog_api_key_and_native_models_endpoint(monkeypatc -def test_native_client_accepts_injected_http_client(): - from agent.gemini_native_adapter import GeminiNativeClient - - injected = SimpleNamespace(close=lambda: None) - client = GeminiNativeClient(api_key="AIza-test", http_client=injected) - assert client._http is injected @pytest.mark.parametrize( @@ -349,13 +343,6 @@ def test_normalize_gemini_base_url_guarantees_version_segment(configured, expect assert normalize_gemini_base_url(configured) == expected -def test_native_client_appends_v1beta_to_host_root_base_url(): - from agent.gemini_native_adapter import GeminiNativeClient - - client = GeminiNativeClient( - api_key="AIza-test", base_url="https://generativelanguage.googleapis.com", http_client=SimpleNamespace(close=lambda: None) - ) - assert client.base_url == "https://generativelanguage.googleapis.com/v1beta" def test_native_client_rejects_empty_api_key_with_actionable_message(): @@ -368,7 +355,6 @@ def test_native_client_rejects_empty_api_key_with_actionable_message(): GeminiNativeClient(api_key=bad) # type: ignore[arg-type] msg = str(excinfo.value) assert "GOOGLE_API_KEY" in msg and "GEMINI_API_KEY" in msg - assert "aistudio.google.com" in msg @pytest.mark.asyncio diff --git a/tests/agent/test_gemini_standard_key_guidance.py b/tests/agent/test_gemini_standard_key_guidance.py index 9ad59f4925..93ebcf7f0f 100644 --- a/tests/agent/test_gemini_standard_key_guidance.py +++ b/tests/agent/test_gemini_standard_key_guidance.py @@ -112,7 +112,6 @@ class TestGeminiHttpErrorGuidance: text = str(err) assert GUIDANCE_MARKER in text assert "aistudio.google.com/api-keys" in text - assert "ai.google.dev/gemini-api/docs/api-key" in text assert err.code == "gemini_unauthorized" @@ -142,22 +141,6 @@ class TestGeminiHttpErrorGuidance: err = gemini_http_error(_mock_response(403, body)) assert GUIDANCE_MARKER not in str(err) - def test_free_tier_429_unaffected(self): - body = json.dumps( - { - "error": { - "code": 429, - "message": ( - "Quota exceeded for metric: generativelanguage.googleapis.com/" - "generate_content_free_tier_requests, limit: 20" - ), - } - } - ) - err = gemini_http_error(_mock_response(429, body)) - text = str(err) - assert "free tier" in text - assert GUIDANCE_MARKER not in text @@ -181,16 +164,6 @@ class TestSummarizerPreservesGuidance: assert GUIDANCE_MARKER in summary assert "aistudio.google.com/api-keys" in summary - def test_400_standard_key_guidance_survives_summarizer(self): - from run_agent import AIAgent - - body = _google_error_body( - 400, API_KEY_INVALID_MESSAGE, status="INVALID_ARGUMENT", - reason="API_KEY_INVALID", - ) - err = gemini_http_error(_mock_response(400, body), api_key=_AIZA_STANDARD_KEY) - summary = AIAgent._summarize_api_error(err) - assert GUIDANCE_MARKER in summary def test_free_tier_guidance_survives_summarizer(self): from run_agent import AIAgent diff --git a/tests/agent/test_ghost_skill_pruning.py b/tests/agent/test_ghost_skill_pruning.py index 9a2192ba30..f76bc42b52 100644 --- a/tests/agent/test_ghost_skill_pruning.py +++ b/tests/agent/test_ghost_skill_pruning.py @@ -24,9 +24,7 @@ from agent.context_compressor import ( SKILL_PRUNED_MARKER_PREFIX, SUMMARY_PREFIX, ContextCompressor, - _collect_protected_skill_names, _extract_pruned_skill_names, - _MAX_PRUNED_SKILL_MARKERS, _reinject_pruned_skill_markers, _skill_pruned_marker, _summarize_tool_result, @@ -266,10 +264,6 @@ class TestMarkerSurvivesRealCompress: class TestReinjectionBoundsAndRedaction: - def test_marker_list_is_capped(self): - names = [f"skill-{i}" for i in range(_MAX_PRUNED_SKILL_MARKERS + 15)] - out = _reinject_pruned_skill_markers("body", names) - assert out.count(SKILL_PRUNED_MARKER_PREFIX) == len(names) # The cap is applied at the collection sites in _generate_summary / # _build_static_fallback_summary; the helper itself is mechanical. @@ -283,16 +277,3 @@ class TestReinjectionBoundsAndRedaction: assert secret not in out -class TestSkillsGuidanceSafetyRule: - def test_safety_rule_present_with_real_newlines(self): - """SKILLS_GUIDANCE must teach the [SKILL_PRUNED] contract (reload - via skill_view; stale markers are artifacts) under its heading, - with real newlines. Dieted to prose (#95681) — the four-numbered - enumeration is gone but every semantic survives.""" - from agent.prompt_builder import SKILLS_GUIDANCE - - assert "## Skill Safety Rule" in SKILLS_GUIDANCE - assert "[SKILL_PRUNED]" in SKILLS_GUIDANCE - assert "skill_view(name=" in SKILLS_GUIDANCE - assert "historical artifacts" in SKILLS_GUIDANCE - assert chr(10) in SKILLS_GUIDANCE diff --git a/tests/agent/test_grid_sweep_cli_tui_stream_diagnostics.py b/tests/agent/test_grid_sweep_cli_tui_stream_diagnostics.py index 33e2bd9548..8228866ec6 100644 --- a/tests/agent/test_grid_sweep_cli_tui_stream_diagnostics.py +++ b/tests/agent/test_grid_sweep_cli_tui_stream_diagnostics.py @@ -5,7 +5,6 @@ from __future__ import annotations import json import types -from unittest.mock import MagicMock import pytest @@ -56,43 +55,6 @@ def test_compression_replay_reaches_gateway_status_sink_only_when_visible(tmp_pa assert (len(rendered) == 1) is _visible(setting) -# --- agent/chat_completion_helpers.py stream-drop / stall deltas ---------------------------------- - -def _stream_attempt_stub(enabled): - from agent import chat_completion_helpers as cch - fired = [] - agent = MagicMock() - agent._warning_presentation_enabled = lambda: enabled - agent._fire_stream_delta = lambda text: fired.append(text) - return cch, agent, fired - - -@pytest.mark.parametrize("enabled", (True, False)) -def test_stream_reconnect_marker_delta_honors_policy(enabled): - """The '⚠ Connection dropped mid tool-call; reconnecting…' delta is presentation only; the - tracking reset and retry bookkeeping run regardless.""" - import inspect - from agent import chat_completion_helpers as cch - src = inspect.getsource(cch) - i = src.index("Connection dropped mid tool-call; reconnecting") - window = src[i - 400:i] - assert "_warning_presentation_enabled()" in window, "reconnect marker must be behind the presentation gate" - j = src.index("_reset_stream_delivery_tracking", i) - assert "if self.agent._warning_presentation_enabled()" not in src[i:j], "tracking reset must stay unconditional" - - -def test_stream_stall_warning_kept_in_result_but_delta_gated(): - import inspect - from agent import chat_completion_helpers as cch - src = inspect.getsource(cch) - i = src.index("Stream stalled mid tool-call") - seg = src[i:i + 700] - assert "_partial_text = (_partial_text or \"\") + _warn" in seg, "model/result bookkeeping stays" - assert "if self.agent._warning_presentation_enabled():" in seg - assert seg.index("_partial_text = (_partial_text or \"\") + _warn") < seg.index("if self.agent._warning_presentation_enabled():") - assert "logger.warning(" in seg - - # --- agent/agent_init.py invalid config int + autoraise notice --------------------------------- @pytest.mark.parametrize("setting", MODES) @@ -109,85 +71,11 @@ def test_invalid_config_int_print_honors_policy_log_always(tmp_path, monkeypatch assert any("Invalid model.context_length" in rec.getMessage() for rec in caplog.records) -def test_autoraise_notice_uses_diagnostic_safe_print(): - import inspect - from agent import agent_init - src = inspect.getsource(agent_init) - i = src.index("if _autoraise_notice:\n agent._safe_print(_autoraise_notice, diagnostic=True)") - assert i > 0 - - # --- agent/turn_tool_validation.py auto-repair notice ------------------------------------------ -def test_tool_name_repair_notice_is_diagnostic_vprint(): - from agent import turn_tool_validation as ttv - printed = [] - agent = MagicMock() - agent.log_prefix = "" - agent._repair_tool_call = lambda name: "read_file" - agent._vprint = lambda *a, **kw: printed.append((a, kw)) - tc = types.SimpleNamespace(function=types.SimpleNamespace(name="reed_file", arguments="{}")) - # Only the repair loop is under test; call the module-level helper through the smallest surface. - import inspect - src = inspect.getsource(ttv) - assert "agent._vprint(f\"{agent.log_prefix}🔧 Auto-repaired tool name" in src - assert "force=True, diagnostic=True" in src[src.index("Auto-repaired tool name"):][:200] - # --- CLI mixins ------------------------------------------------------------------------------- -def _cli_block(module, start_marker, end_marker, extra): - """Execute one guarded statement block from a CLI mixin with the module's real bound names - (``_cprint`` etc. come from ``cli`` at call time, so we bind them explicitly).""" - import inspect, textwrap - import cli as climod - src = inspect.getsource(module) - i = src.index(start_marker); j = src.index(end_marker, i) - i = src.rfind("\n", 0, i) + 1 # back up to the line start so dedent sees uniform indentation - j = src.rfind("\n", 0, j) + 1 - block = textwrap.dedent(src[i:j]) - ns = dict(module.__dict__); ns.update({"_cprint": climod._cprint, "_DIM": "", "_RST": ""}); ns.update(extra) - exec(compile(block, f"<{module.__name__}-block>", "exec"), ns) - - -@pytest.mark.parametrize("setting", MODES) -def test_cli_iteration_budget_notice_honors_policy(tmp_path, monkeypatch, setting): - _policy(tmp_path, monkeypatch, setting) - import cli as climod - from hermes_cli import cli_chat_turn_mixin as m - out = [] - monkeypatch.setattr(climod, "_cprint", lambda s: out.append(s)) - self = types.SimpleNamespace(agent=types.SimpleNamespace(max_iterations=3, _notification_config=None)) - turn = types.SimpleNamespace(result={"completed": False, "interrupted": False, "api_calls": 3}) - _cli_block(m, "if turn.result and not turn.result.get(\"completed\")", "# Batch TTS", {"turn": turn, "self": self}) - assert (len(out) == 1 and "Iteration budget reached" in out[0]) is _visible(setting) - - -@pytest.mark.parametrize("setting", MODES) -def test_cli_provider_fallback_notice_honors_policy(tmp_path, monkeypatch, setting): - _policy(tmp_path, monkeypatch, setting) - import cli as climod - from hermes_cli import cli_agent_setup_mixin as m - out = [] - monkeypatch.setattr(climod, "_cprint", lambda s: out.append(s)) - _cli_block(m, "from gateway.warning_notifications import render_notification\n render_notification(\n lambda: _cprint(f\"⚠️ {_why}", - "self.requested_provider = _fb_provider", - {"_fb_provider": "p", "_fb_model": "m", "_why": "Primary auth failed"}) - assert (len(out) == 1 and "Primary auth failed" in out[0]) is _visible(setting) - - -@pytest.mark.parametrize("setting", MODES) -def test_cli_session_store_unavailable_banner_honors_policy(tmp_path, monkeypatch, setting, capsys): - _policy(tmp_path, monkeypatch, setting) - from hermes_cli import cli_init_mixin as m - from hermes_state_user_copy import describe_storage_failure, storage_failure_details - from rich.console import Console - _cli_block(m, "failure = describe_storage_failure(e)", "_run_state_db_auto_maintenance(self._session_db)", - {"e": RuntimeError("disk I/O error"), "describe_storage_failure": describe_storage_failure, - "storage_failure_details": storage_failure_details, "Console": Console}) - err = capsys.readouterr().err - assert ("Session store unavailable" in err) is _visible(setting) - @pytest.mark.parametrize("setting", MODES) def test_cli_browser_downgrade_notice_honors_policy(tmp_path, monkeypatch, setting): @@ -220,22 +108,6 @@ def test_tui_goal_compression_recovery_notice_honors_policy(tmp_path, monkeypatc assert (len(emitted) == 1) is _visible(setting) -@pytest.mark.parametrize("setting", MODES) -def test_tui_configured_model_adoption_failure_honors_policy(tmp_path, monkeypatch, setting): - _policy(tmp_path, monkeypatch, setting) - from tui_gateway import server, model_switch as ms - emitted = [] - monkeypatch.setattr(server, "_emit", lambda ev, sid, payload: emitted.append((ev, payload))) - import inspect, textwrap - src = inspect.getsource(ms) - i = src.index("except Exception as e:\n logger.warning(\"Configured model %s could not be adopted") - j = src.index("def _pending_switch_selection_warning", i) - block = "try:\n raise RuntimeError('boom')\n" + textwrap.dedent(src[i:j]) - ns = dict(vars(server)); ns.update({"model": "gpt-x", "sid": "s1", "session": {"agent": types.SimpleNamespace(_notification_config=None)}}) - exec(compile(block, "", "exec"), ns) - assert (len(emitted) == 1 and emitted[0][0] == "error") is _visible(setting) - - @pytest.mark.parametrize("setting", MODES) def test_tui_preview_restart_status_warning_honors_policy(tmp_path, monkeypatch, setting): """The preview-restart progress panel's status_callback: warning rows follow the TUI policy; diff --git a/tests/agent/test_hermetic_side_effect_guards.py b/tests/agent/test_hermetic_side_effect_guards.py index d9df5ca01d..347dcedb27 100644 --- a/tests/agent/test_hermetic_side_effect_guards.py +++ b/tests/agent/test_hermetic_side_effect_guards.py @@ -32,35 +32,3 @@ def test_webbrowser_get_controller_is_neutralized(_neutralize_webbrowser): assert _neutralize_webbrowser == [url, url, url] -def _isolate_anthropic_credentials(monkeypatch, tmp_path): - from agent import anthropic_credentials as ac - - monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False) - monkeypatch.delenv("ANTHROPIC_TOKEN", raising=False) - monkeypatch.delenv("CLAUDE_CODE_OAUTH_TOKEN", raising=False) - monkeypatch.setattr(ac.Path, "home", lambda: tmp_path) - monkeypatch.setattr(ac.platform, "system", lambda: "Darwin") - - def _real_keychain_reached(*_args, **_kwargs): - raise AssertionError("test reached the real macOS Keychain command") - - monkeypatch.setattr(ac.subprocess, "run", _real_keychain_reached) - return ac - - -def test_claude_code_credential_read_does_not_touch_macos_keychain( - monkeypatch, tmp_path -): - """The real credential reader should be safe under the suite guard.""" - ac = _isolate_anthropic_credentials(monkeypatch, tmp_path) - - assert ac.read_claude_code_credentials() is None - - -def test_anthropic_token_resolution_does_not_touch_macos_keychain( - monkeypatch, tmp_path -): - """Token resolution should be safe under the same suite guard.""" - ac = _isolate_anthropic_credentials(monkeypatch, tmp_path) - - assert ac.resolve_anthropic_token() is None diff --git a/tests/agent/test_idle_compaction_lock_and_guards.py b/tests/agent/test_idle_compaction_lock_and_guards.py index 4426a8804a..67e8df6982 100644 --- a/tests/agent/test_idle_compaction_lock_and_guards.py +++ b/tests/agent/test_idle_compaction_lock_and_guards.py @@ -200,42 +200,8 @@ def test_idle_compaction_skips_a_transcript_that_has_not_grown(tmp_path: Path) - assert ctx.current_turn_user_idx == len(ctx.messages) - 1 -def test_idle_compaction_fires_again_once_the_transcript_grows(tmp_path: Path) -> None: - """The raised floor is a deferral, not an off switch.""" - db = SessionDB(db_path=tmp_path / "state.db") - sid = "IDLE_REGROWN" - db.create_session(sid, source="cli") - agent = _prep_recompaction_agent(db, sid) - agent.context_compressor.last_compression_rough_tokens = 44_579 - seam = _pin_compress_seam(agent) - - # 44,579 + 25,502 = 70,081 — one floor's worth of new content on top. - _run_prologue(agent, _history(), rough_tokens=70_082) - - seam.assert_called_once() -def test_idle_compaction_ignores_a_non_int_last_compaction_reading( - tmp_path: Path, -) -> None: - """Compressor doubles expose a Mock here — it must not raise the floor. - - An unset/derived attribute falls back to 0, which restores the original - ``tokens > floor_tokens`` semantics exactly. - """ - db = SessionDB(db_path=tmp_path / "state.db") - sid = "IDLE_MOCKREAD" - db.create_session(sid, source="cli") - agent = _prep_recompaction_agent(db, sid) - # Left as the MagicMock auto-attribute (a truthy non-int). - assert not isinstance( - agent.context_compressor.last_compression_rough_tokens, int - ) - seam = _pin_compress_seam(agent) - - _run_prologue(agent, _history(), rough_tokens=44_579) - - seam.assert_called_once() def test_idle_compaction_respects_anti_thrash_breaker(tmp_path: Path) -> None: diff --git a/tests/agent/test_image_corrupt_recovery.py b/tests/agent/test_image_corrupt_recovery.py index d7e93c83ab..2e37d70749 100644 --- a/tests/agent/test_image_corrupt_recovery.py +++ b/tests/agent/test_image_corrupt_recovery.py @@ -438,28 +438,3 @@ class TestCanonicalHistoryIsolation: "canonical history lost its image through shallow aliasing" ) - def test_image_corrupt_branch_strips_only_payload_copy(self): - """Contract check on the recovery branch itself: the image_corrupt - path must NOT call _strip_images_from_messages(messages) — only the - api_messages per-call copy. Stripping canonical history permanently - erased images on a transient provider error (#69104 sweeper review, - copy-on-write contract from e762a5a473).""" - import inspect - import re as _re - - import agent.turn_recovery as loop_mod - - src = inspect.getsource(loop_mod.recover_after_classification) - # Locate the image_corrupt recovery block and inspect its calls. - block = _re.search( - r"image_corrupt:\n(.*?)\n\s*(?:continue|return|else)", src, _re.S - ) - assert block is not None, "image_corrupt recovery branch not found" - body = block.group(1) - assert "_strip_request_images_and_retry(agent, api_messages)" in body, ( - "recovery must strip the per-call api_messages copy" - ) - assert "_strip_images_from_messages(messages)" not in body, ( - "recovery must NOT strip canonical messages — that permanently " - "erases history on a transient provider rejection" - ) diff --git a/tests/agent/test_image_generate_parallel.py b/tests/agent/test_image_generate_parallel.py index 3223be9d9d..0c6d6cc086 100644 --- a/tests/agent/test_image_generate_parallel.py +++ b/tests/agent/test_image_generate_parallel.py @@ -2,9 +2,8 @@ import json from types import SimpleNamespace -from unittest.mock import MagicMock, patch +from unittest.mock import patch -import run_agent from agent import tool_executor @@ -18,60 +17,8 @@ def _tool_call(name: str, args: dict, call_id: str) -> SimpleNamespace: ) -def test_image_generate_batch_routes_to_concurrent_executor(): - agent = SimpleNamespace() - agent._execute_tool_calls = run_agent.AIAgent._execute_tool_calls.__get__(agent) - agent._execute_tool_calls_concurrent = MagicMock() - agent._execute_tool_calls_sequential = MagicMock() - assistant_message = SimpleNamespace( - tool_calls=[ - _tool_call("image_generate", {"prompt": "variation one"}, "img_1"), - _tool_call("image_generate", {"prompt": "variation two"}, "img_2"), - ], - ) - - agent._execute_tool_calls(assistant_message, [], "task-image-batch") - - agent._execute_tool_calls_concurrent.assert_called_once() - agent._execute_tool_calls_sequential.assert_not_called() -def test_image_generate_parallel_worker_cap_defaults_to_four(): - runnable_calls = [ - ( - 0, - _tool_call("image_generate", {"prompt": "one"}, "img_1"), - "image_generate", - {}, - ), - ( - 1, - _tool_call("image_generate", {"prompt": "two"}, "img_2"), - "image_generate", - {}, - ), - ( - 2, - _tool_call("image_generate", {"prompt": "three"}, "img_3"), - "image_generate", - {}, - ), - ( - 3, - _tool_call("image_generate", {"prompt": "four"}, "img_4"), - "image_generate", - {}, - ), - ( - 4, - _tool_call("image_generate", {"prompt": "five"}, "img_5"), - "image_generate", - {}, - ), - ] - - with patch("hermes_cli.config.load_config", return_value={}): - assert tool_executor._max_workers_for_tool_batch(runnable_calls) == 4 def test_image_generate_parallel_worker_cap_can_be_configured_lower(): diff --git a/tests/agent/test_image_rejection_fallback.py b/tests/agent/test_image_rejection_fallback.py index 3c6727b288..5f49436401 100644 --- a/tests/agent/test_image_rejection_fallback.py +++ b/tests/agent/test_image_rejection_fallback.py @@ -363,16 +363,6 @@ class TestRejectionNeverReachesPersistedHistory: # same api_messages and the send path strips them there, so the request goes out text-only. assert strip_images_for_rejecting_model(agent, wire) is True assert "image_url" not in str(wire) - # ...and build_api_request really runs that strip on every attempt, before the kwargs - # are built from api_messages. - import inspect - - from agent.turn_api_request import build_api_request - - src = inspect.getsource(build_api_request) - strip_at = src.find("\n strip_images_for_rejecting_model(agent, api_messages)") - assert strip_at != -1, "build_api_request no longer strips images for a rejecting model" - assert strip_at < src.find("_build_api_kwargs(api_messages"), "strip must precede _build_api_kwargs" def test_every_model_in_a_fallback_chain_is_tracked(self): """Two models reject images in the same turn (fallback A -> B). A turn-global guard diff --git a/tests/agent/test_image_routing.py b/tests/agent/test_image_routing.py index 69eecf0761..75353b4822 100644 --- a/tests/agent/test_image_routing.py +++ b/tests/agent/test_image_routing.py @@ -10,7 +10,6 @@ from unittest.mock import patch from agent.image_routing import ( _coerce_capability_bool, _coerce_mode, - _explicit_aux_vision_override, _lookup_supports_vision, _should_probe_ollama_vision, _supports_vision_override, @@ -40,12 +39,6 @@ class TestCoerceMode: # ─── _explicit_aux_vision_override ─────────────────────────────────────────── -class TestExplicitAuxVisionOverride: - def test_none_config(self): - assert _explicit_aux_vision_override(None) is False - - def test_empty_config(self): - assert _explicit_aux_vision_override({}) is False @@ -350,17 +343,6 @@ class TestLargeImageHandling: missing = tmp_path / "does_not_exist.png" assert _ir._file_to_data_url(missing) is None - def test_build_native_parts_no_provider_kwarg(self, tmp_path: Path): - """build_native_content_parts takes text + paths, no provider kwarg.""" - from agent import image_routing as _ir - - img = tmp_path / "cat.png" - img.write_bytes(_png_bytes()) - parts, skipped = _ir.build_native_content_parts("hi", [str(img)]) - assert skipped == [] - assert len(parts) == 2 - assert parts[0]["type"] == "text" - assert parts[1]["type"] == "image_url" # ─── extract_image_refs ────────────────────────────────────────────────────── @@ -644,16 +626,6 @@ class TestProbeApiKeyForwarding: assert _resolve_inference_api_key({"model": {}}, "custom") == "" assert _resolve_inference_api_key(None, "custom") == "" - def test_should_probe_forwards_api_key(self): - from agent.image_routing import _should_probe_ollama_vision - - key = _fake_key("probe") - with patch( - "agent.model_metadata.detect_local_server_type", - return_value=None, - ) as detect: - _should_probe_ollama_vision("custom", "https://remote/v1", api_key=key) - detect.assert_called_once_with("https://remote/v1", api_key=key) def test_lookup_passes_resolved_key_to_probe(self): """The full lookup path resolves the key from cfg and hands it to the