The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test: Bedrock Converse/ConverseStream wire-conformance E2E suite (SigV4-verified eventstream fake, tools, signed reasoning, resume, compaction, faults)
teknium10be109efaf62
diff --git a/tests/e2e/core/providers/test_native_bedrock_converse_faults.py b/tests/e2e/core/providers/test_native_bedrock_converse_faults.pynew file mode 100644index 00000000000..a201a8548e0--- /dev/null+++ b/tests/e2e/core/providers/test_native_bedrock_converse_faults.py@@ -0,0 +1,168 @@+"""Bedrock Converse / ConverseStream fault semantics through the real ``hermes chat -q`` CLI.++Each scenario owns a loopback Bedrock fake (``tests/fakes/providers/bedrock_converse.py``) that the real+boto3 client reaches via ``AWS_ENDPOINT_URL_BEDROCK_RUNTIME``; faults are the service's documented ones+in the AWS JSON error shape (``x-amzn-ErrorType`` + ``{"message"}``) or ``:message-type exception``+event-stream frames, plus connection drops. Assertions: requests counted at the fake, the retried+request's body, ``state.db`` rows (no duplicated assistant content) and what the CLI prints.+"""++from __future__ import annotations++from concurrent.futures import ThreadPoolExecutor+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any++import pytest++pytest.importorskip("botocore")++from tests.e2e.core.providers._native_helpers import ( # noqa: E402+ ChatResult, NativeHome, assert_no_duplicate_assistant_text, make_home, messages, run_chat,+)+from tests.fakes.providers.bedrock_converse import ( # noqa: E402+ ACCESS_KEY, REGION, SECRET_KEY, Drop, FakeBedrock, HttpError, Reasoning, Reply, StreamException, Text,+ Turn, seq,+)++MODEL = "deepseek.v3-v1:0"+FINAL = "Recovered answer ZEBRA-7731 is complete and whole."+REASONING = "Reasoning for the recovered answer, streamed in several deltas."+VALIDATION_MARK = "FAKE-VALIDATION-9921"+IAM_DENIAL = ("User: arn:aws:iam::123456789012:user/e2e is not authorized to perform: "+ "bedrock:InvokeModelWithResponseStream on resource: arn:aws:bedrock:us-east-1::foundation-model/"+ + MODEL)++KNOWN = {+ "validation_retried": "#121294 a Bedrock 400 ValidationException is retried and reported as 'temporarily unavailable'",+ "eof_before_message_stop": "#109988 a ConverseStream that ends before messageStop is accepted as the answer",+}+++CHUNK = 7+# Event index 3 text deltas into the answer: messageStart, reasoning deltas, signature, contentBlockStop.+CUT_MID_TEXT = 1 + -(-len(REASONING) // CHUNK) + 2 + 3+++def _answer() -> Turn:+ return Turn([Reasoning(REASONING), Text(FINAL, chunk=CHUNK)])+++@dataclass+class Scenario:+ replies: tuple[Reply, ...]+ env: dict[str, str] = field(default_factory=dict)+ by_op: dict[str, tuple[Reply, ...]] = field(default_factory=dict)+++# Each fault precedes a good answer: a retryable fault must be retried into it, a terminal one must not.+SCENARIOS: dict[str, Scenario] = {+ # botocore's own retries are off (documented AWS_MAX_ATTEMPTS) so the 429 reaches Hermes' loop.+ "throttle_http": Scenario((HttpError("ThrottlingException", "Too many requests, please wait before trying again."),+ _answer()), env={"AWS_MAX_ATTEMPTS": "1"}),+ "unavailable_http": Scenario((HttpError("ServiceUnavailableException", "Bedrock is unable to process your request."),+ _answer()), env={"AWS_MAX_ATTEMPTS": "1"}),+ "throttle_in_stream": Scenario((StreamException(_answer(), "throttlingException",+ "Too many tokens, please wait before trying again.", after=CUT_MID_TEXT),+ _answer())),+ "drop_mid_stream": Scenario((Drop(_answer(), after=CUT_MID_TEXT), _answer())),+ "eof_before_message_stop": Scenario((Drop(_answer(), after=CUT_MID_TEXT, clean=True), _answer())),+ "validation": Scenario((HttpError("ValidationException", f"The model returned the following errors: "+ f"malformed input request: {VALIDATION_MARK}"), _answer())),+ "stream_denied_falls_back": Scenario((), by_op={+ "ConverseStream": (HttpError("AccessDeniedException", IAM_DENIAL),), "Converse": (_answer(),)}),+}+++def _responder(sc: Scenario):+ if not sc.by_op:+ return seq(*sc.replies)+ per_op = {op: seq(*replies) for op, replies in sc.by_op.items()}+ return lambda rec: per_op[rec["op"]](rec)+++def _run(name: str, root: Path) -> dict[str, Any]:+ sc = SCENARIOS[name]+ fake = FakeBedrock(_responder(sc))+ with fake:+ nh = make_home(root, {"provider": "bedrock", "default": MODEL, "context_length": 64000},+ env_file={"AWS_ACCESS_KEY_ID": ACCESS_KEY, "AWS_SECRET_ACCESS_KEY": SECRET_KEY,+ "AWS_REGION": REGION})+ result = run_chat(nh, "Give me the recovered answer.",+ env={"AWS_ENDPOINT_URL_BEDROCK_RUNTIME": fake.endpoint, **sc.env})+ return {"nh": nh, "result": result, "requests": fake.snapshot()}++[email protected](scope="module")+def runs(tmp_path_factory: pytest.TempPathFactory) -> dict[str, dict[str, Any]]:+ base = tmp_path_factory.mktemp("bedrock_faults")+ with ThreadPoolExecutor(len(SCENARIOS)) as pool:+ futures = {name: pool.submit(_run, name, base / name) for name in SCENARIOS}+ return {name: fut.result() for name, fut in futures.items()}+++def _assistant_rows(nh: NativeHome) -> list[dict[str, Any]]:+ return [r for r in messages(nh) if r["role"] == "assistant"]+++def _recovered(run: dict[str, Any], expected_requests: int) -> None:+ """Exit 0, the full answer printed once, one assistant row, the retry re-sent the same history."""+ result: ChatResult = run["result"]+ assert result.returncode == 0, result.describe()+ requests = run["requests"]+ assert not [r["rejected"] for r in requests if r.get("rejected")], requests+ assert len(requests) == expected_requests, f"fake saw {len(requests)} requests\n{result.describe()}"+ assert all(r["body"]["messages"] == requests[0]["body"]["messages"] for r in requests), \+ "the retry did not re-send the original history (partial output leaked into the request?)"+ assert result.stdout.count(FINAL) == 1, result.describe()+ rows = _assistant_rows(run["nh"])+ assert_no_duplicate_assistant_text(rows, FINAL[:12])+ assert [r["content"] for r in rows] == [FINAL], rows++[email protected]("name", ["throttle_http", "unavailable_http", "throttle_in_stream"])+def test_retryable_fault_is_retried_once_into_the_answer(name: str, runs: dict[str, Any]) -> None:+ _recovered(runs[name], expected_requests=2)+++def test_mid_stream_drop_retries_without_duplicated_persisted_content(runs: dict[str, Any]) -> None:+ run = runs["drop_mid_stream"]+ _recovered(run, expected_requests=2)+ assert run["requests"][0]["reply"] == "Drop", run["requests"][0]++[email protected](strict=True, reason=KNOWN["eof_before_message_stop"])+def test_stream_ending_before_message_stop_is_not_accepted(runs: dict[str, Any]) -> None:+ run = runs["eof_before_message_stop"]+ assert run["result"].returncode == 0, run["result"].describe()+ rows = [r["content"] for r in _assistant_rows(run["nh"])]+ sent = len(run["requests"])+ # Symptom: the truncated first stream is persisted as the final answer and never retried.+ assert (sent, rows) == (2, [FINAL]), f"{KNOWN['eof_before_message_stop']}: requests={sent} rows={rows}"++[email protected](strict=True, reason=KNOWN["validation_retried"])+def test_validation_exception_is_surfaced_once_without_retry(runs: dict[str, Any]) -> None:+ run = runs["validation"]+ result: ChatResult = run["result"]+ # Symptom: the 400 is retried (the scripted success behind it is reached).+ sent = len(run["requests"])+ assert sent == 1, f"{KNOWN['validation_retried']}: fake saw {sent} requests"+ shown = result.stdout + result.stderr+ assert result.returncode != 0 and FINAL not in shown, result.describe()+ assert VALIDATION_MARK in shown and "ValidationException" in shown, result.describe()+ assert "temporarily unavailable" not in shown, result.describe()+ assert [r["content"] for r in _assistant_rows(run["nh"])] != [FINAL]+++def test_streaming_iam_denial_falls_back_to_converse(runs: dict[str, Any]) -> None:+ run = runs["stream_denied_falls_back"]+ result: ChatResult = run["result"]+ assert result.returncode == 0, result.describe()+ requests = run["requests"]+ assert [r["op"] for r in requests] == ["ConverseStream", "Converse"], [r["op"] for r in requests]+ assert requests[1]["body"]["messages"] == requests[0]["body"]["messages"]+ assert FINAL in result.stdout, result.describe()+ rows = _assistant_rows(run["nh"])+ assert [(r["content"], r["reasoning_content"]) for r in rows] == [(FINAL, REASONING)], rowsdiff --git a/tests/e2e/core/providers/test_native_bedrock_converse_turns.py b/tests/e2e/core/providers/test_native_bedrock_converse_turns.pynew file mode 100644index 00000000000..fd3c2411588--- /dev/null+++ b/tests/e2e/core/providers/test_native_bedrock_converse_turns.py@@ -0,0 +1,356 @@+"""Bedrock Converse / ConverseStream wire conformance: tools, signed reasoning, resume, compaction.++Real ``hermes chat -q`` subprocesses with ``model.provider: bedrock`` talk to the real boto3+``bedrock-runtime`` client, redirected by botocore's documented ``AWS_ENDPOINT_URL_BEDROCK_RUNTIME``+override to the loopback fake in ``tests/fakes/providers/bedrock_converse.py``. The fake verifies the+SigV4 signature, validates each body against the botocore service model plus Converse's conversation+rules (tool pairing, signed reasoning replay, final-assistant thinking), and streams real+``application/vnd.amazon.eventstream`` frames. Independent scenarios run concurrently in one module+fixture; each test asserts one property of the wire requests, ``state.db`` rows or CLI output.+"""++from __future__ import annotations++import json+from concurrent.futures import ThreadPoolExecutor+from pathlib import Path+from typing import Any, Callable++import pytest++pytest.importorskip("botocore")++from tests.e2e.core.providers._native_helpers import ( # noqa: E402+ ChatResult, NativeHome, latest_session, make_home, messages, run_chat, session_ids, tool_calls_of,+)+from tests.fakes.providers.bedrock_converse import ( # noqa: E402+ ACCESS_KEY, REGION, SECRET_KEY, FakeBedrock, Reasoning, Text, ToolUse, Turn, seq,+)++MODEL = "deepseek.v3-v1:0"++KNOWN = {+ "reasoning_shredded": "#98468 streamed reasoning is persisted with '\\n\\n' between every delta",+ "resume_drops_reasoning": "#121293 --resume replays Bedrock assistant turns without their signed reasoningContent",+}++SEED_TEXT = "codeword PELICAN-5501"+SEED2_TEXT = "second codeword OSPREY-7712"+R_A1 = "The user wants both the seed file and an echo; run them in parallel first."+R_A2 = "Both results are back; now read the second seed before answering."+R_A3 = "I have both codewords and the echo, so I can answer now."+FINAL_A = "Answer: PELICAN-5501 / OSPREY-7712 / MARK-42."+R_B1 = "Resume scenario: read the seed file to learn the codeword before replying."+R_B2 = "The seed file holds the codeword, report it back verbatim to the user."+FINAL_B1 = "The codeword is PELICAN-5501."+FINAL_B2 = "Still PELICAN-5501 after the resume."+SUMMARY_TOKEN = "SUMMARY-OK-BEDROCK"+FINAL_C = "Compaction scenario finished: DONE-C."+COMPACTION_FILES = 8+++def _home(root: Path, fake: FakeBedrock, extra_config: dict[str, Any] | None = None) -> NativeHome:+ """Bedrock home: fake static creds in the profile .env (the chain Hermes loads), endpoint via env."""+ nh = make_home(root, {"provider": "bedrock", "default": MODEL, "context_length": 64000},+ env_file={"AWS_ACCESS_KEY_ID": ACCESS_KEY, "AWS_SECRET_ACCESS_KEY": SECRET_KEY,+ "AWS_REGION": REGION},+ extra_config=extra_config)+ (nh.project / "seed.txt").write_text(SEED_TEXT + "\n", encoding="utf-8")+ (nh.project / "seed2.txt").write_text(SEED2_TEXT + "\n", encoding="utf-8")+ return nh+++def _endpoint_env(fake: FakeBedrock) -> dict[str, str]:+ return {"AWS_ENDPOINT_URL_BEDROCK_RUNTIME": fake.endpoint}+++# --------------------------------------------------------------------------------------------------+# Scenarios (each owns its fake + home; run concurrently)+# --------------------------------------------------------------------------------------------------+++def _scenario_tools(root: Path) -> dict[str, Any]:+ """Parallel toolUse (read_file + terminal) -> toolResults, a second tool round, then the answer."""+ def first(_rec: dict[str, Any]) -> Turn:+ return Turn([Reasoning(R_A1), ToolUse("read_file", {"path": str(root / "project" / "seed.txt")}),+ ToolUse("terminal", {"command": "echo MARK-$((6*7))"})])++ fake = FakeBedrock(seq(first, lambda _r: Turn([Reasoning(R_A2), ToolUse(+ "read_file", {"path": str(root / "project" / "seed2.txt")})]), Turn([Reasoning(R_A3), Text(FINAL_A)])))+ with fake:+ nh = _home(root, fake)+ result = run_chat(nh, "Read seed.txt, echo a marker, then read seed2.txt and report.",+ env=_endpoint_env(fake))+ return {"fake": fake, "nh": nh, "result": result, "requests": fake.snapshot()}+++def _scenario_resume(root: Path) -> dict[str, Any]:+ """Turn 1 (reasoning + toolUse, then reasoning + text) in one process; turn 2 via --resume in another."""+ fake = FakeBedrock(seq(+ lambda _r: Turn([Reasoning(R_B1), ToolUse("read_file", {"path": str(root / "project" / "seed.txt")})]),+ Turn([Reasoning(R_B2), Text(FINAL_B1)]), Turn([Text(FINAL_B2)])))+ with fake:+ nh = _home(root, fake)+ first = run_chat(nh, "What codeword is in seed.txt?", env=_endpoint_env(fake))+ sid = latest_session(nh) if first.returncode == 0 else ""+ second = run_chat(nh, "Say it again.", resume=sid, env=_endpoint_env(fake)) if sid else first+ return {"fake": fake, "nh": nh, "first": first, "second": second, "sid": sid, "requests": fake.snapshot()}+++def _compaction_responder(root: Path) -> Callable[[dict[str, Any]], Turn]:+ """Main turns (with toolConfig) read files and report huge input usage; aux calls are summaries."""+ main_calls: list[int] = []++ def respond(rec: dict[str, Any]) -> Turn:+ if "toolConfig" not in rec["body"]:+ return Turn([Text(f"## Goal\nRead the files ({SUMMARY_TOKEN}).\n## Progress\n- files read so far\n")],+ input_tokens=600)+ main_calls.append(1)+ n = len(main_calls)+ # Small usage first so the transcript is long enough to compact, then far past the threshold.+ usage = 40_000 if n >= 6 else 3_000+ if n <= COMPACTION_FILES:+ return Turn([Reasoning(f"Step {n}: read f{n}.txt next and keep going through the list."),+ ToolUse("read_file", {"path": str(root / "project" / f"f{n}.txt")})], input_tokens=usage)+ return Turn([Reasoning("Every file has been read; write the final answer."), Text(FINAL_C)],+ input_tokens=usage)++ return respond+++def _scenario_compaction(root: Path) -> dict[str, Any]:+ fake = FakeBedrock(_compaction_responder(root))+ with fake:+ nh = _home(root, fake, extra_config={"compression": {"threshold_tokens": 12_000, "protect_last_n": 4}})+ for i in range(1, COMPACTION_FILES + 1):+ (nh.project / f"f{i}.txt").write_text(f"file {i} " + "lorem ipsum dolor " * 250 + "\n", encoding="utf-8")+ result = run_chat(nh, f"Read f1.txt through f{COMPACTION_FILES}.txt one by one, then say done.",+ env=_endpoint_env(fake))+ return {"fake": fake, "nh": nh, "result": result, "requests": fake.snapshot()}+++SCENARIOS: dict[str, Callable[[Path], dict[str, Any]]] = {+ "tools": _scenario_tools, "resume": _scenario_resume, "compaction": _scenario_compaction,+}++[email protected](scope="module")+def runs(tmp_path_factory: pytest.TempPathFactory) -> dict[str, dict[str, Any]]:+ base = tmp_path_factory.mktemp("bedrock_turns")+ with ThreadPoolExecutor(len(SCENARIOS)) as pool:+ futures = {name: pool.submit(fn, base / name) for name, fn in SCENARIOS.items()}+ return {name: fut.result() for name, fut in futures.items()}+++# --------------------------------------------------------------------------------------------------+# Assertion helpers+# --------------------------------------------------------------------------------------------------+++def _ok(result: ChatResult) -> None:+ assert result.returncode == 0, result.describe()+++def _accepted(requests: list[dict[str, Any]]) -> None:+ rejected = [r["rejected"] for r in requests if r.get("rejected")]+ assert not rejected, f"Bedrock (fake) rejected {len(rejected)} request(s): {rejected}"+++def _main(requests: list[dict[str, Any]]) -> list[dict[str, Any]]:+ return [r for r in requests if "toolConfig" in (r.get("body") or {})]+++def _results(message: dict[str, Any]) -> dict[str, str]:+ return {b["toolResult"]["toolUseId"]: json.dumps(b["toolResult"]["content"])+ for b in message["content"] if "toolResult" in b}+++def _tool_uses(blocks: list[dict[str, Any]]) -> list[dict[str, Any]]:+ return [b["toolUse"] for b in blocks if "toolUse" in b]+++def _blob(request: dict[str, Any]) -> str:+ return json.dumps(request["body"].get("messages", []))+++# --------------------------------------------------------------------------------------------------+# a. multi-turn with tools+# --------------------------------------------------------------------------------------------------+++def test_every_call_is_sigv4_signed_for_bedrock_with_the_profile_credentials(runs: dict[str, Any]) -> None:+ requests = [r for run in runs.values() for r in run["requests"]]+ assert requests, "no request reached the Bedrock fake"+ _accepted(requests)+ for rec in requests:+ assert rec["auth"]["key"] == ACCESS_KEY and rec["auth"]["service"] == "bedrock", rec["headers"]+ assert rec["auth"]["region"] == REGION, rec["auth"]+ assert rec["model"] == MODEL and rec["op"] in ("Converse", "ConverseStream"), rec["path"]+++def test_parallel_tool_uses_round_trip_as_tool_results_paired_by_id(runs: dict[str, Any]) -> None:+ run = runs["tools"]+ _ok(run["result"])+ requests = run["requests"]+ _accepted(requests)+ assert [r["op"] for r in requests] == ["ConverseStream"] * 3, [r["op"] for r in requests]+ first_ids = [tu["toolUseId"] for tu in _tool_uses(requests[0]["emitted"])]+ second = requests[1]["body"]["messages"]+ # The assistant turn goes back byte-for-byte: signed reasoning first, then both toolUse blocks.+ assert second[-2] == {"role": "assistant", "content": requests[0]["emitted"]}, second[-2]+ results = _results(second[-1])+ assert list(results) == first_ids, f"toolResult ids {list(results)} != toolUse ids {first_ids}"+ assert SEED_TEXT in results[first_ids[0]] and "MARK-42" in results[first_ids[1]], results+ third = requests[2]["body"]["messages"]+ assert third[:len(second)] == second, "history prefix changed between tool rounds"+ assert third[-2] == {"role": "assistant", "content": requests[1]["emitted"]}, third[-2]+ (second_id,) = [tu["toolUseId"] for tu in _tool_uses(requests[1]["emitted"])]+ assert SEED2_TEXT in _results(third[-1])[second_id], third[-1]+++def test_tool_turn_prints_final_answer_and_persists_paired_rows(runs: dict[str, Any]) -> None:+ run = runs["tools"]+ _ok(run["result"])+ assert FINAL_A in run["result"].stdout, run["result"].describe()+ rows = messages(run["nh"])+ assert [r["role"] for r in rows] == ["user", "assistant", "tool", "tool", "assistant", "tool", "assistant"], rows+ issued = [[tu["toolUseId"] for tu in _tool_uses(r["emitted"])] for r in run["requests"][:2]]+ assert [tc["id"] for tc in tool_calls_of(rows[1])] == issued[0]+ assert [r["tool_call_id"] for r in rows[2:4]] == issued[0]+ assert [tc["id"] for tc in tool_calls_of(rows[4])] == issued[1] and rows[5]["tool_call_id"] == issued[1][0]+ assert rows[-1]["content"] == FINAL_A+++def _reasoning_rows(nh: NativeHome) -> list[str]:+ return [r["reasoning_content"] for r in messages(nh) if r["role"] == "assistant" and r["reasoning_content"]]++[email protected](strict=True, reason=KNOWN["reasoning_shredded"])+def test_persisted_reasoning_equals_the_streamed_reasoning_text(runs: dict[str, Any]) -> None:+ persisted = _reasoning_rows(runs["tools"]["nh"])+ assert [p.replace("\n\n", "") for p in persisted] == [R_A1, R_A2, R_A3], persisted+ assert persisted == [R_A1, R_A2, R_A3], f"{KNOWN['reasoning_shredded']}: {persisted}"+++# --------------------------------------------------------------------------------------------------+# b. signed reasoning replay across --resume+# --------------------------------------------------------------------------------------------------+++def test_resume_in_new_process_replays_tool_history_valid_for_converse(runs: dict[str, Any]) -> None:+ run = runs["resume"]+ _ok(run["first"])+ _ok(run["second"])+ assert FINAL_B2 in run["second"].stdout, run["second"].describe()+ requests = run["requests"]+ _accepted(requests)+ assert len(requests) == 3 and session_ids(run["nh"]) == [run["sid"]], (len(requests), session_ids(run["nh"]))+ resumed = requests[2]["body"]["messages"]+ (tool_use,) = _tool_uses(requests[0]["emitted"])+ assert [m["role"] for m in resumed] == ["user", "assistant", "user", "assistant", "user"], resumed+ assert _tool_uses(resumed[1]["content"]) == [tool_use], resumed[1]+ assert SEED_TEXT in _results(resumed[2])[tool_use["toolUseId"]], resumed[2]+ assert {"text": FINAL_B1} in resumed[3]["content"] and resumed[4]["content"] == [{"text": "Say it again."}]+ rows = messages(run["nh"], run["sid"])+ assert [r["role"] for r in rows] == ["user", "assistant", "tool", "assistant", "user", "assistant"], rows+ assert rows[-1]["content"] == FINAL_B2++[email protected](strict=True, reason=KNOWN["resume_drops_reasoning"])+def test_resume_replays_signed_reasoning_verbatim(runs: dict[str, Any]) -> None:+ requests = runs["resume"]["requests"]+ signed = [b for b in requests[0]["emitted"] if "reasoningContent" in b]+ # In-process the tool-use turn goes back with its signed reasoning ...+ assert requests[1]["body"]["messages"][1]["content"][0] == signed[0]+ # ... and after --resume (new process) it must be identical.+ resumed = requests[2]["body"]["messages"]+ assert resumed[1]["content"][0] == signed[0], f"{KNOWN['resume_drops_reasoning']}: {resumed[1]['content']}"+ assert [b for b in resumed[3]["content"] if "reasoningContent" in b] == [+ b for b in requests[1]["emitted"] if "reasoningContent" in b]+++# --------------------------------------------------------------------------------------------------+# c. compaction in a reasoning session+# --------------------------------------------------------------------------------------------------+++def test_compaction_in_reasoning_session_keeps_every_request_converse_valid(runs: dict[str, Any]) -> None:+ run = runs["compaction"]+ _ok(run["result"])+ assert FINAL_C in run["result"].stdout, run["result"].describe()+ requests = run["requests"]+ _accepted(requests) # tool pairs, signatures and final-assistant thinking checked on every request+ summaries = [i for i, r in enumerate(requests) if r["op"] == "Converse" and "toolConfig" not in r["body"]]+ assert summaries, "compaction never called the summarizer over Converse"+ after = [r for r in _main(requests[summaries[0] + 1:])]+ assert after, "no main request after the compaction summary"+ before_len = max(len(r["body"]["messages"]) for r in _main(requests[:summaries[0]]))+ assert all(SUMMARY_TOKEN in _blob(r) for r in after), "a post-compaction request lost the summary"+ assert len(after[0]["body"]["messages"]) < before_len, "compaction did not shrink the wire history"+ last = after[-1]["body"]["messages"]+ # The open tool loop's final assistant turn still leads with the signed reasoning Bedrock issued.+ assert "reasoningContent" in last[-2]["content"][0] and _results(last[-1]), last[-2:]+++def test_compaction_persists_summary_and_archives_compacted_rows(runs: dict[str, Any]) -> None:+ run = runs["compaction"]+ _ok(run["result"])+ every = messages(run["nh"], active_only=False)+ live = messages(run["nh"])+ assert any(r["compacted"] == 1 for r in every), "no row archived as compacted"+ assert any(SUMMARY_TOKEN in (r["content"] or "") for r in live), "summary not in the live transcript"+ assert live[-1]["role"] == "assistant" and live[-1]["content"] == FINAL_C, live[-1]+ live_ids = {r["tool_call_id"] for r in live if r["role"] == "tool"}+ issued = {tc["id"] for r in live if r["role"] == "assistant" for tc in tool_calls_of(r)}+ assert live_ids <= issued, f"orphaned live tool rows: {live_ids - issued}"+++# --------------------------------------------------------------------------------------------------+# The fake itself rejects what Bedrock rejects (so a green scenario above is not a pass-through)+# --------------------------------------------------------------------------------------------------+++def _mutate_request(case: str, kwargs: dict[str, Any]) -> dict[str, Any]:+ msgs = kwargs["messages"]+ table: dict[str, Callable[[], None]] = {+ "orphan_tool_result": lambda: msgs[2]["content"][0]["toolResult"].update(toolUseId="tooluse_nobody"),+ "tampered_signature": lambda: msgs[1]["content"][0]["reasoningContent"]["reasoningText"].update(signature="Zm9yZ2Vk"),+ "unsigned_final_thinking": lambda: msgs[1]["content"].pop(0),+ "two_members_in_union": lambda: msgs[0]["content"][0].update(image={"format": "png", "source": {"bytes": b"x"}}),+ "blank_text": lambda: msgs[0]["content"][0].update(text=" "),+ }+ table[case]()+ return kwargs++[email protected]("case", ["valid", "orphan_tool_result", "tampered_signature", "unsigned_final_thinking",+ "two_members_in_union", "blank_text", "bad_secret"])+def test_fake_rejects_requests_bedrock_rejects(case: str) -> None:+ boto3 = pytest.importorskip("boto3")+ from botocore.config import Config+ from botocore.exceptions import ClientError, ParamValidationError++ fake = FakeBedrock(seq(lambda _r: Turn([Reasoning("sig check reasoning"), ToolUse("noop", {})]),+ Turn([Text("fine")])))+ with fake:+ client = boto3.client(+ "bedrock-runtime", region_name=REGION, endpoint_url=fake.endpoint, aws_access_key_id=ACCESS_KEY,+ aws_secret_access_key="wrong-secret" if case == "bad_secret" else SECRET_KEY,+ config=Config(retries={"max_attempts": 1}, parameter_validation=False))+ base = [{"role": "user", "content": [{"text": "go"}]}]+ first = client.converse(modelId=MODEL, messages=base) if case != "bad_secret" else None+ blocks = first["output"]["message"]["content"] if first else []+ tool_id = next((b["toolUse"]["toolUseId"] for b in blocks if "toolUse" in b), "none")+ kwargs = {"modelId": MODEL, "messages": base + [+ {"role": "assistant", "content": blocks or [{"text": "x"}]},+ {"role": "user", "content": [{"toolResult": {"toolUseId": tool_id, "content": [{"text": "ok"}]}}]}]}+ if case not in ("valid", "bad_secret"):+ kwargs = _mutate_request(case, kwargs)+ try:+ client.converse(**kwargs)+ except (ClientError, ParamValidationError) as exc:+ code = getattr(exc, "response", {}).get("Error", {}).get("Code", type(exc).__name__)+ else:+ code = "OK"+ expected = {"valid": "OK", "bad_secret": "InvalidSignatureException"}.get(case, "ValidationException")+ assert code == expected, (case, code, fake.snapshot()[-1].get("rejected"))diff --git a/tests/fakes/providers/bedrock_converse.py b/tests/fakes/providers/bedrock_converse.pynew file mode 100644index 00000000000..9f98ec5f4bf--- /dev/null+++ b/tests/fakes/providers/bedrock_converse.py@@ -0,0 +1,499 @@+"""Loopback fake of the AWS Bedrock Runtime Converse / ConverseStream API.++The real ``boto3`` ``bedrock-runtime`` client inside Hermes is pointed here through botocore's+documented endpoint override (``AWS_ENDPOINT_URL_BEDROCK_RUNTIME``), so the SDK serializes, signs+(SigV4) and parses exactly as against AWS; only the service is fake.++What the fake enforces, the way Bedrock does:++* SigV4: every request must carry ``Authorization: AWS4-HMAC-SHA256 Credential=<key>/<date>/<region>/+ bedrock/aws4_request, SignedHeaders=..., Signature=...``; the signature is RE-COMPUTED with the known+ fake secret and must match (a tampered body or wrong key is a 403, like AWS).+* Request shape: the JSON body plus the ``modelId`` from the URI is validated against the botocore+ service model's ``Converse`` / ``ConverseStream`` input shape (``ParamValidator``: types, required+ members, tagged unions). Violations are a 400 ``ValidationException``.+* Conversation semantics the service model cannot express but Converse rejects (messages the real+ endpoint answers with a ValidationException): first message must be ``user``; roles alternate;+ text blocks are non-blank; every ``toolResult`` answers a ``toolUse`` of the immediately+ preceding assistant turn and every such ``toolUse`` is answered; a replayed ``reasoningText`` must+ carry exactly the signature this fake issued for that text (unsigned or altered thinking is+ rejected, as signed-thinking models do).++Errors use the AWS JSON error shape (``x-amzn-ErrorType`` header + ``{"message": ...}``);+ConverseStream answers real ``application/vnd.amazon.eventstream`` binary frames (prelude, typed+headers, CRC32s), including ``:message-type exception`` frames and mid-stream connection drops.+"""++from __future__ import annotations++import base64+import binascii+import json+import re+import struct+import threading+import time+from dataclasses import dataclass, field+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from typing import Any, Callable, Union+from urllib.parse import unquote++import botocore.session+from botocore.auth import SigV4Auth+from botocore.awsrequest import AWSRequest+from botocore.credentials import Credentials+from botocore.validate import ParamValidator++ACCESS_KEY = "AKIAFAKEE2EBEDROCK01"+SECRET_KEY = "fake/e2e/secret/never+real/0000000000000"+REGION = "us-east-1"++_SERVICE = botocore.session.get_session().get_service_model("bedrock-runtime")+_ROUTE_RE = re.compile(r"^/model/(?P<model>[^/]+)/(?P<op>converse|converse-stream)$")+_OPS = {"converse": "Converse", "converse-stream": "ConverseStream"}+_AUTH_RE = re.compile(+ r"^AWS4-HMAC-SHA256 Credential=(?P<key>[^/]+)/(?P<date>\d{8})/(?P<region>[a-z0-9-]+)/"+ r"(?P<service>[a-z0-9-]+)/aws4_request, ?SignedHeaders=(?P<signed>[a-z0-9;-]+), ?"+ r"Signature=(?P<sig>[0-9a-f]{64})$")+# HTTP status + x-amzn-ErrorType per Bedrock Runtime error (botocore service model metadata).+ERROR_STATUS = {+ name: shape.metadata["error"]["httpStatusCode"]+ for name in _SERVICE.shape_names+ if (shape := _SERVICE.shape_for(name)).metadata.get("exception")+}+++# --------------------------------------------------------------------------------------------------+# Scripted content (Converse ContentBlock shapes)+# --------------------------------------------------------------------------------------------------+++@dataclass+class Text:+ text: str+ chunk: int = 12+++@dataclass+class Reasoning:+ """``reasoningContent.reasoningText``; the signature is issued by the fake and remembered."""++ text: str+ signature: str = ""+++@dataclass+class ToolUse:+ name: str+ input: dict[str, Any]+ tool_use_id: str = ""+++Block = Union[Text, Reasoning, ToolUse]+++@dataclass+class Turn:+ """One assistant message (streamed or not) + usage the service reports."""++ blocks: list[Block]+ stop_reason: str = ""+ input_tokens: int = 120+ output_tokens: int = 30+++@dataclass+class HttpError:+ """An AWS JSON error response before any stream starts (e.g. 429 ThrottlingException)."""++ code: str+ message: str+++@dataclass+class StreamException:+ """ConverseStream: emit ``after`` events of ``turn`` then a ``:message-type exception`` frame."""++ turn: Turn+ exception: str # event member name, e.g. "throttlingException"+ message: str+ after: int = 2+++@dataclass+class Drop:+ """ConverseStream: emit ``after`` events of ``turn`` then close the socket mid-stream.++ ``clean=True`` ends the HTTP body properly instead (valid framing, but the event stream stops+ before ``messageStop``: the service never finished the message)."""++ turn: Turn+ after: int = 3+ clean: bool = False+++Reply = Union[Turn, HttpError, StreamException, Drop]+++# --------------------------------------------------------------------------------------------------+# Event-stream framing (application/vnd.amazon.eventstream)+# --------------------------------------------------------------------------------------------------+++def _header(name: str, value: str) -> bytes:+ n, v = name.encode(), value.encode()+ return struct.pack("!B", len(n)) + n + b"\x07" + struct.pack("!H", len(v)) + v # 7 = string+++def encode_frame(headers: dict[str, str], payload: bytes) -> bytes:+ """One event-stream message: prelude(total, headers_len) + prelude CRC + headers + payload + CRC."""+ hdr = b"".join(_header(k, v) for k, v in headers.items())+ total = 12 + len(hdr) + len(payload) + 4+ prelude = struct.pack("!II", total, len(hdr))+ head = prelude + struct.pack("!I", binascii.crc32(prelude) & 0xFFFFFFFF) + hdr + payload+ return head + struct.pack("!I", binascii.crc32(head) & 0xFFFFFFFF)+++def event_frame(event_type: str, body: dict[str, Any]) -> bytes:+ _validate_event(event_type, body)+ return encode_frame({":event-type": event_type, ":content-type": "application/json",+ ":message-type": "event"}, json.dumps(body).encode())+++def exception_frame(exception: str, message: str) -> bytes:+ return encode_frame({":exception-type": exception, ":content-type": "application/json",+ ":message-type": "exception"}, json.dumps({"message": message}).encode())+++def _validate_event(event_type: str, body: dict[str, Any]) -> None:+ """The fake only emits events valid for the ConverseStream output shape (self-check)."""+ shape = _SERVICE.operation_model("ConverseStream").output_shape.members["stream"].members[event_type]+ report = ParamValidator().validate(body, shape)+ if report.has_errors():+ raise AssertionError(f"fake built an invalid {event_type} event: {report.generate_report()}")+++# --------------------------------------------------------------------------------------------------+# Request validation+# --------------------------------------------------------------------------------------------------+++class Rejection(Exception):+ def __init__(self, code: str, message: str) -> None:+ super().__init__(message)+ self.code = code+ self.message = message+++def _wire_to_params(shape: Any, value: Any) -> Any:+ """rest-json wire value -> botocore param value (blobs arrive base64-encoded)."""+ kind = shape.type_name+ if kind == "blob" and isinstance(value, str):+ try:+ return base64.b64decode(value, validate=True)+ except (binascii.Error, ValueError):+ raise Rejection("ValidationException", f"Invalid base64 blob for {shape.name}") from None+ if kind == "structure" and isinstance(value, dict) and not shape.metadata.get("document"):+ return {k: (_wire_to_params(shape.members[k], v) if k in shape.members else v) for k, v in value.items()}+ if kind == "list" and isinstance(value, list):+ return [_wire_to_params(shape.member, v) for v in value]+ if kind == "map" and isinstance(value, dict):+ return {k: _wire_to_params(shape.value, v) for k, v in value.items()}+ return value+++def validate_shape(op: str, model_id: str, body: dict[str, Any]) -> None:+ shape = _SERVICE.operation_model(op).input_shape+ params = _wire_to_params(shape, {**body, "modelId": model_id})+ report = ParamValidator().validate(params, shape)+ if report.has_errors():+ raise Rejection("ValidationException", report.generate_report())+++def _tool_ids(content: list[dict[str, Any]], kind: str) -> list[str]:+ return [b[kind]["toolUseId"] for b in content if kind in b]+++def validate_conversation(body: dict[str, Any], signatures: dict[str, str], reasoned_tools: set[str]) -> None:+ """Converse-side rules beyond the schema (real ValidationException texts)."""+ messages = body.get("messages") or []+ if not messages or messages[0]["role"] != "user":+ raise Rejection("ValidationException", "A conversation must start with a user message. "+ "Try again with a conversation that starts with a user message.")+ for i, msg in enumerate(messages):+ if i and msg["role"] == messages[i - 1]["role"]:+ raise Rejection("ValidationException", "A conversation must alternate between user and "+ "assistant roles. Make sure the conversation alternates between user and "+ "assistant roles and try again.")+ for j, block in enumerate(msg["content"]):+ if "text" in block and not block["text"].strip():+ raise Rejection("ValidationException", f"The text field in the ContentBlock object at "+ f"messages.{i}.content.{j} is blank. Add text to the text field, and try again.")+ _check_reasoning(block.get("reasoningContent"), signatures, f"messages.{i}.content.{j}")+ expected = _tool_ids(messages[i - 1]["content"], "toolUse") if i and msg["role"] == "user" else []+ got = _tool_ids(msg["content"], "toolResult")+ if sorted(expected) != sorted(got):+ raise Rejection("ValidationException", f"Expected toolResult blocks at messages.{i}.content "+ f"for the following Ids: {', '.join(expected) or '(none)'}; got {', '.join(got) or '(none)'}")+ _check_final_assistant_thinking(messages, reasoned_tools)+++def _check_final_assistant_thinking(messages: list[dict[str, Any]], reasoned_tools: set[str]) -> None:+ """Signed-thinking models: while a tool loop is open (the request ends in toolResults), the final+ assistant turn must START with its reasoning block if it was issued with one."""+ if len(messages) < 2 or not _tool_ids(messages[-1]["content"], "toolResult"):+ return+ final = messages[-2]["content"]+ if set(_tool_ids(final, "toolUse")) & reasoned_tools and "reasoningContent" not in final[0]:+ first = next(iter(final[0]), "?")+ raise Rejection("ValidationException", f"messages.{len(messages) - 2}.content.0.type: Expected "+ f"`thinking` or `redacted_thinking`, but found `{first}`. When `thinking` is enabled, "+ "a final `assistant` message must start with a thinking block (preceeding the lastmost "+ "set of `tool_use` and `tool_result` blocks).")+++def _check_reasoning(reasoning: Any, signatures: dict[str, str], where: str) -> None:+ text_block = (reasoning or {}).get("reasoningText")+ if not text_block:+ return+ issued = signatures.get(text_block.get("text", ""))+ if issued is None or text_block.get("signature") != issued:+ raise Rejection("ValidationException", f"{where}: The reasoning block signature is missing or "+ "invalid. Reasoning content must be passed back unmodified with its signature.")+++def verify_sigv4(method: str, url: str, headers: dict[str, str], body: bytes) -> dict[str, str]:+ """Re-compute the SigV4 signature with the fake secret; return the parsed credential scope."""+ auth = headers.get("authorization", "")+ m = _AUTH_RE.match(auth)+ if not m:+ raise Rejection("MissingAuthenticationTokenException", f"Missing or malformed SigV4 Authorization: {auth!r}")+ if m["key"] != ACCESS_KEY or m["service"] != "bedrock":+ raise Rejection("UnrecognizedClientException", "The security token included in the request is invalid.")+ signed = {h: headers[h] for h in m["signed"].split(";") if h in headers}+ request = AWSRequest(method=method, url=url, data=body, headers=signed)+ request.context["timestamp"] = headers.get("x-amz-date", "")+ signer = SigV4Auth(Credentials(ACCESS_KEY, SECRET_KEY), "bedrock", m["region"])+ canonical = signer.canonical_request(request)+ expected = signer.signature(signer.string_to_sign(request, canonical), request)+ if expected != m["sig"]:+ raise Rejection("InvalidSignatureException", "The request signature we calculated does not match "+ "the signature you provided.")+ return m.groupdict()+++# --------------------------------------------------------------------------------------------------+# Server+# --------------------------------------------------------------------------------------------------+++Responder = Callable[[dict[str, Any]], Reply]+++@dataclass+class FakeBedrock:+ """Recording, validating Bedrock Runtime fake. ``responder(record) -> Reply`` scripts each call."""++ responder: Responder+ requests: list[dict[str, Any]] = field(default_factory=list)+ signatures: dict[str, str] = field(default_factory=dict) # reasoning text -> issued signature+ reasoned_tools: set[str] = field(default_factory=set) # toolUseIds issued in a turn with reasoning+ _lock: threading.Lock = field(default_factory=threading.Lock)+ _ids: int = 0+ _httpd: ThreadingHTTPServer | None = None++ def __enter__(self) -> "FakeBedrock":+ self._httpd = ThreadingHTTPServer(("127.0.0.1", 0), _handler_for(self))+ self._httpd.daemon_threads = True+ threading.Thread(target=self._httpd.serve_forever, daemon=True).start()+ return self++ def __exit__(self, *_exc: object) -> None:+ if self._httpd:+ self._httpd.shutdown()+ self._httpd.server_close()++ @property+ def endpoint(self) -> str:+ assert self._httpd is not None+ return f"http://127.0.0.1:{self._httpd.server_address[1]}"++ def client_env(self) -> dict[str, str]:+ """Env for a Hermes child: botocore endpoint override + fake static credentials."""+ return {"AWS_ENDPOINT_URL_BEDROCK_RUNTIME": self.endpoint, "AWS_ACCESS_KEY_ID": ACCESS_KEY,+ "AWS_SECRET_ACCESS_KEY": SECRET_KEY, "AWS_REGION": REGION}++ def snapshot(self) -> list[dict[str, Any]]:+ with self._lock:+ return list(self.requests)++ def next_id(self, prefix: str) -> str:+ with self._lock:+ self._ids += 1+ return f"{prefix}{self._ids:04d}{int(time.monotonic() * 1000) % 100000:05d}"++ def record(self, rec: dict[str, Any]) -> None:+ with self._lock:+ self.requests.append(rec)++ def materialize(self, turn: Turn) -> list[dict[str, Any]]:+ """Resolve ids/signatures and return Converse ContentBlocks for the turn."""+ out: list[dict[str, Any]] = []+ for block in turn.blocks:+ if isinstance(block, Text):+ out.append({"text": block.text})+ elif isinstance(block, Reasoning):+ block.signature = block.signature or base64.b64encode(+ f"sig:{self.next_id('r')}:{len(block.text)}".encode()).decode()+ with self._lock:+ self.signatures[block.text] = block.signature+ out.append({"reasoningContent": {"reasoningText": {"text": block.text, "signature": block.signature}}})+ else:+ block.tool_use_id = block.tool_use_id or self.next_id("tooluse_")+ out.append({"toolUse": {"toolUseId": block.tool_use_id, "name": block.name, "input": block.input}})+ if any(isinstance(b, Reasoning) for b in turn.blocks):+ with self._lock:+ self.reasoned_tools.update(b.tool_use_id for b in turn.blocks if isinstance(b, ToolUse))+ if not turn.stop_reason:+ turn.stop_reason = "tool_use" if any(isinstance(b, ToolUse) for b in turn.blocks) else "end_turn"+ return out+++def _usage(turn: Turn) -> dict[str, int]:+ return {"inputTokens": turn.input_tokens, "outputTokens": turn.output_tokens,+ "totalTokens": turn.input_tokens + turn.output_tokens}+++def _pieces(text: str, size: int) -> list[str]:+ return [text[i:i + size] for i in range(0, len(text), size)] or [""]+++def _block_events(index: int, block: dict[str, Any], chunk: int) -> list[tuple[str, dict[str, Any]]]:+ """ContentBlockStart/Delta/Stop events for one block (text blocks get no start, as on AWS)."""+ events: list[tuple[str, dict[str, Any]]] = []+ if "toolUse" in block:+ tu = block["toolUse"]+ events.append(("contentBlockStart", {"contentBlockIndex": index, "start": {+ "toolUse": {"toolUseId": tu["toolUseId"], "name": tu["name"]}}}))+ deltas = [{"toolUse": {"input": p}} for p in _pieces(json.dumps(tu["input"]), chunk)]+ elif "reasoningContent" in block:+ rt = block["reasoningContent"]["reasoningText"]+ deltas = [{"reasoningContent": {"text": p}} for p in _pieces(rt["text"], chunk)]+ deltas.append({"reasoningContent": {"signature": rt["signature"]}})+ else:+ deltas = [{"text": p} for p in _pieces(block["text"], chunk)]+ events += [("contentBlockDelta", {"contentBlockIndex": index, "delta": d}) for d in deltas]+ events.append(("contentBlockStop", {"contentBlockIndex": index}))+ return events+++def stream_events(blocks: list[dict[str, Any]], turn: Turn) -> list[bytes]:+ chunk = min((b.chunk for b in turn.blocks if isinstance(b, Text)), default=12)+ events: list[tuple[str, dict[str, Any]]] = [("messageStart", {"role": "assistant"})]+ for i, block in enumerate(blocks):+ events += _block_events(i, block, chunk)+ events.append(("messageStop", {"stopReason": turn.stop_reason}))+ events.append(("metadata", {"usage": _usage(turn), "metrics": {"latencyMs": 7}}))+ return [event_frame(name, body) for name, body in events]+++def _handler_for(fake: FakeBedrock) -> type[BaseHTTPRequestHandler]:+ class Handler(BaseHTTPRequestHandler):+ protocol_version = "HTTP/1.1"++ def log_message(self, *_args: Any) -> None:+ return++ def do_POST(self) -> None: # noqa: N802 - http.server API+ raw = self.rfile.read(int(self.headers.get("Content-Length") or 0))+ headers = {k.lower(): v for k, v in self.headers.items()}+ route = _ROUTE_RE.match(self.path.split("?", 1)[0])+ rec: dict[str, Any] = {"path": self.path, "headers": headers, "raw": raw, "t": time.time(),+ "op": _OPS.get(route["op"]) if route else None,+ "model": unquote(route["model"]) if route else None}+ try:+ body = json.loads(raw or b"{}")+ except ValueError:+ body = None+ rec["body"] = body+ try:+ if not route:+ raise Rejection("UnknownOperationException", f"No route for {self.path}")+ rec["auth"] = verify_sigv4("POST", f"http://{headers.get('host')}{self.path}", headers, raw)+ if not isinstance(body, dict):+ raise Rejection("SerializationException", "Request body is not a JSON object")+ validate_shape(rec["op"], rec["model"], body)+ validate_conversation(body, dict(fake.signatures), set(fake.reasoned_tools))+ except Rejection as rej:+ rec["rejected"] = f"{rej.code}: {rej.message}"+ fake.record(rec)+ return self._error(rej.code, rej.message)+ fake.record(rec)+ reply = fake.responder(rec)+ rec["reply"] = type(reply).__name__+ if isinstance(reply, HttpError):+ return self._error(reply.code, reply.message)+ turn = reply if isinstance(reply, Turn) else reply.turn+ rec["emitted"] = fake.materialize(turn)+ if rec["op"] == "Converse":+ return self._converse(turn, rec["emitted"])+ return self._stream(reply, turn, rec["emitted"])++ def _send(self, status: int, headers: dict[str, str], body: bytes) -> None:+ self.send_response(status)+ for k, v in {**headers, "Content-Length": str(len(body)),+ "x-amzn-RequestId": fake.next_id("req-")}.items():+ self.send_header(k, v)+ self.end_headers()+ self.wfile.write(body)+ self.wfile.flush()++ def _error(self, code: str, message: str) -> None:+ status = ERROR_STATUS.get(code, 403 if "Signature" in code or "Token" in code else 400)+ self._send(status, {"Content-Type": "application/json", "x-amzn-ErrorType": f"{code}:http://internal.amazon.com/coral/com.amazon.bedrock/"},+ json.dumps({"message": message}).encode())++ def _converse(self, turn: Turn, blocks: list[dict[str, Any]]) -> None:+ body = {"output": {"message": {"role": "assistant", "content": blocks}},+ "stopReason": turn.stop_reason, "usage": _usage(turn), "metrics": {"latencyMs": 9}}+ self._send(200, {"Content-Type": "application/json"}, json.dumps(body).encode())++ def _stream(self, reply: Reply, turn: Turn, blocks: list[dict[str, Any]]) -> None:+ frames = stream_events(blocks, turn)+ cut = len(frames) if isinstance(reply, Turn) else min(reply.after, len(frames))+ self.send_response(200)+ self.send_header("Content-Type", "application/vnd.amazon.eventstream")+ self.send_header("Transfer-Encoding", "chunked")+ self.send_header("x-amzn-RequestId", fake.next_id("req-"))+ self.end_headers()+ for frame in frames[:cut]:+ self._chunk(frame)+ if isinstance(reply, Drop) and not reply.clean:+ self.close_connection = True+ self.wfile.flush()+ self.connection.shutdown(2) # socket.SHUT_RDWR: no terminating chunk+ return+ if isinstance(reply, StreamException):+ self._chunk(exception_frame(reply.exception, reply.message))+ self.wfile.write(b"0\r\n\r\n")+ self.wfile.flush()++ def _chunk(self, data: bytes) -> None:+ self.wfile.write(f"{len(data):x}\r\n".encode() + data + b"\r\n")+ self.wfile.flush()++ return Handler+++def seq(*replies: Reply | Callable[[dict[str, Any]], Reply]) -> Responder:+ """Responder answering the Nth call with ``replies[N]`` (the last one repeats); callables get the record."""+ calls: list[int] = []+ lock = threading.Lock()++ def respond(rec: dict[str, Any]) -> Reply:+ with lock:+ calls.append(1)+ reply = replies[min(len(calls), len(replies)) - 1]+ return reply(rec) if callable(reply) else reply++ return respond