hermes-agent/tests/agent/test_anthropic_whitespace_text_blocks.py
Teknium 6b81590c55
test: prune low-value tests suite-wide (wave 1) — 46,820 → 28,106 test functions
Systematic prune per AGENTS.md test policy, one pass over every major
test tree (gateway, hermes_cli, tools, agent, run_agent, plugins, cli,
cron, tui_gateway, honcho/openviking, root-level):

- DELETE: source-reading tests (read_text/getsource on prod files),
  change-detector tests (exact catalog counts, model-name snapshots,
  config version literals), mock-echo tests (assert a mock returns what
  it was told), assertion-free/trivial tests, near-duplicate
  parametrizations (boundaries + one representative kept), async/sync
  twin duplicates, cosmetic within-file variations.
- KEEP (mandatory): security/redaction/approval guards, message-role
  alternation invariants, prompt-caching/deterministic-call-id
  invariants, issue-number regression tests (deduped), E2E tests.
- 6 test files deleted outright (script-style/no-assert or fully
  redundant); conftest.py, fakes/, fixtures/ untouched.
- tests/acp/conftest.py added: autouse fixture stubs the live
  models.dev/GitHub/Copilot/Anthropic inventory fetches that ACP server
  tests performed on every session create — test_server.py 147s → 3.4s,
  and the tests are now genuinely hermetic.
- Sleep-based slowness shrunk where safe (codex_ttfb_watchdog,
  compression_concurrent_fork, etc.); no wall-clock assertion tightened.

Verification: full hermetic suite via scripts/run_tests.sh —
2439 files, 31,130 tests passed, 0 failed, 0 flaky retries, 315s wall
(baseline: 583s wall, 13,564s subprocess CPU).
2026-07-29 13:10:23 -07:00

96 lines
3.9 KiB
Python

"""Regression: whitespace-only text blocks must be coerced, not sent verbatim.
Reproduces HTTP 400 ``messages: text content blocks must contain non-whitespace
text``. When context compression (or certain tool-call flows) produces an
assistant message with an empty or whitespace-only text block, that block is
stored in session history and replayed on every subsequent turn — permanently
wedging the session behind the same 400.
Fix (mirrors ``bedrock_adapter._safe_text``, ref #9486): coerce empty/whitespace
text to a non-whitespace placeholder at two points on the Anthropic request path
— ``_sanitize_replay_block`` (ordered-blocks replay) and the final content walk
in ``_convert_assistant_message`` (main path). Ref #69512.
"""
import pytest
from agent.anthropic_adapter import (
_EMPTY_TEXT_PLACEHOLDER,
_safe_text,
_sanitize_replay_block,
_convert_assistant_message,
)
def _text_blocks(msg):
return [b for b in msg["content"] if isinstance(b, dict) and b.get("type") == "text"]
def _assert_no_blank_text(msg):
"""No text content block in the converted message is empty/whitespace-only."""
assert isinstance(msg["content"], list)
for b in _text_blocks(msg):
assert b["text"].strip(), f"blank text block survived: {b!r}"
class TestSafeText:
def test_none_becomes_placeholder(self):
assert _safe_text(None) == _EMPTY_TEXT_PLACEHOLDER
@pytest.mark.parametrize("blank", [" ", "\n", "\t", " \n\t "])
def test_whitespace_only_becomes_placeholder(self, blank):
assert _safe_text(blank) == _EMPTY_TEXT_PLACEHOLDER
class TestSanitizeReplayBlockWhitespace:
def test_whitespace_text_block_dropped(self):
# Blank text blocks are DROPPED at the block level (not coerced in
# place) — the caller relocates any cache_control the block carried
# and appends the non-whitespace placeholder only when nothing
# cacheable survives, so real thinking/tool_use blocks aren't
# cluttered with "(empty)" noise. See _convert_assistant_message.
assert _sanitize_replay_block({"type": "text", "text": " \n"}) is None
def test_none_text_block_dropped_without_crash(self):
# text=None (invalid upstream payload) must not reach .strip().
assert _sanitize_replay_block({"type": "text", "text": None}) is None
def test_real_text_block_unchanged(self):
out = _sanitize_replay_block({"type": "text", "text": "hi"})
assert out == {"type": "text", "text": "hi"}
class TestConvertAssistantMessageWhitespace:
def test_ordered_blocks_replay_coerces_blank_text(self):
# The interleaved-thinking fast path replays anthropic_content_blocks
# through _sanitize_replay_block; a stored whitespace text block here is
# exactly the compression-produced poison that wedges the session.
msg = {
"role": "assistant",
"anthropic_content_blocks": [
{"type": "thinking", "thinking": "reasoning", "signature": "sig-A"},
{"type": "text", "text": " "},
],
}
out = _convert_assistant_message(msg)
_assert_no_blank_text(out)
assert _text_blocks(out) == [{"type": "text", "text": _EMPTY_TEXT_PLACEHOLDER}]
def test_thinking_block_not_treated_as_text(self):
# Only text blocks are coerced; thinking blocks are left untouched even
# if their payload is whitespace (they obey a different schema rule).
msg = {
"role": "assistant",
"anthropic_content_blocks": [
{"type": "thinking", "thinking": " ", "signature": "sig-B"},
{"type": "text", "text": "real"},
],
}
out = _convert_assistant_message(msg)
thinking = [b for b in out["content"] if b.get("type") == "thinking"]
assert thinking == [{"type": "thinking", "thinking": " ", "signature": "sig-B"}]