The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(vcr): aggregate worker stats on the controller so the session summary actually renders under xdist
claude1ea600bd707f
diff --git a/tests/_vcr_conftest_common.py b/tests/_vcr_conftest_common.pyindex 5cc544187b4..a179a21ba69 100644--- a/tests/_vcr_conftest_common.py+++ b/tests/_vcr_conftest_common.py@@ -825,6 +825,110 @@ def _reset_session_stats() -> None:_session_stats["skip_reason_examples"].clear()+# user_properties keys used to ship structured outcome data from xdist workers+# back to the controller. ``vcr_verdict`` is the human-readable line that+# ``VerboseReporterState.maybe_emit_verdict`` writes next to each test;+# ``vcr_outcome`` + ``vcr_recorded_by`` are the structured payload that+# ``aggregate_report_outcome`` folds into the controller's ``_session_stats``+# so the session-end summary actually has data in xdist mode.+_USER_PROP_VERDICT_LINE = "vcr_verdict"+_USER_PROP_OUTCOME = "vcr_outcome"+_USER_PROP_RECORDED_BY = "vcr_recorded_by"+++def _emit_outcome_payload(+ node,+ verdict: str,+ *,+ skip_reason: str | None = None,+ live_call_hosts: Iterable[str] | None = None,+) -> None:+ """Stash a structured VCR outcome on a pytest node so the xdist+ controller can fold it into ``_session_stats``.++ On a worker, ``record_vcr_outcome`` has already updated the worker-local+ ``_session_stats`` — but in xdist mode that state lives in the worker+ process and never reaches the controller's ``pytest_terminal_summary``.+ We use the report's ``user_properties`` channel (which xdist round-trips+ back to the controller) to ship the outcome, and+ ``aggregate_report_outcome`` rebuilds the controller's stats from there.++ The recorder tags ``vcr_recorded_by`` with ``PYTEST_XDIST_WORKER`` so+ the controller can distinguish "recorded in this same main process —+ already counted" from "recorded in a worker — needs aggregation here".+ """+ node.user_properties.append(+ (+ _USER_PROP_OUTCOME,+ {+ "verdict": verdict,+ "skip_reason": skip_reason,+ "live_call_hosts": list(live_call_hosts) if live_call_hosts else [],+ },+ )+ )+ node.user_properties.append(+ (_USER_PROP_RECORDED_BY, os.environ.get("PYTEST_XDIST_WORKER", ""))+ )+++def aggregate_report_outcome(report) -> None:+ """Fold a worker-produced VCR outcome into the controller's session stats.++ No-op outside the xdist controller path:++ * On a worker, ``_session_stats`` was already updated in-process by+ ``record_vcr_outcome`` — and the worker doesn't render the summary+ anyway, so there's nothing for us to aggregate.+ * In single-process mode, ``vcr_recorded_by`` is the empty string,+ which means the same process that ran the test is now handling the+ report — ``_session_stats`` already has the entry, double-counting+ would be a bug.+ * Only when ``vcr_recorded_by`` is a non-empty worker id (``"gw0"``+ etc.) do we know the controller's ``_session_stats`` is missing this+ test and needs the outcome folded in.+ """+ if os.environ.get("PYTEST_XDIST_WORKER"):+ return+ if report.when != "teardown":+ return++ recorded_by = next(+ (v for k, v in (report.user_properties or []) if k == _USER_PROP_RECORDED_BY),+ None,+ )+ if not recorded_by:+ return++ outcome = next(+ (v for k, v in (report.user_properties or []) if k == _USER_PROP_OUTCOME),+ None,+ )+ if not outcome:+ return++ verdict = outcome.get("verdict")+ if not verdict:+ return++ nodeid = report.nodeid+ _session_stats["verdict_counts"][verdict] += 1++ if verdict == VERDICT_MISS_OVERFLOW:+ _session_stats["overflow_tests"].append(nodeid)+ elif verdict == VERDICT_UNMARKED_LIVE_CALL:+ _session_stats["unmarked_live_call_tests"].append(+ (nodeid, list(outcome.get("live_call_hosts") or []))+ )++ skip_reason = outcome.get("skip_reason")+ if skip_reason:+ _session_stats["skip_reason_counts"][skip_reason] += 1+ examples = _session_stats["skip_reason_examples"][skip_reason]+ if len(examples) < 5:+ examples.append(nodeid)++def session_stats_snapshot() -> dict:"""Read-only copy of the per-session VCR stats. Used by the summary."""return {@@ -993,9 +1097,10 @@ def record_vcr_outcome(request, vcr) -> None:if not test_passed and verdict == VERDICT_MISS_RECORDED:verdict = VERDICT_MISS_NOT_PERSISTED_session_stats["verdict_counts"][verdict] += 1+ _emit_outcome_payload(request.node, verdict)if vcr_outcome_logging_enabled():line = _format_verdict_line(verdict, cassette)- request.node.user_properties.append(("vcr_verdict", line))+ request.node.user_properties.append((_USER_PROP_VERDICT_LINE, line))return# Cassette is None ⇒ test wasn't VCR-marked. Honor the skip reason@@ -1021,9 +1126,15 @@ def record_vcr_outcome(request, vcr) -> None:if len(examples) < 5:examples.append(nodeid)+ _emit_outcome_payload(+ request.node,+ verdict,+ skip_reason=skip_reason,+ live_call_hosts=hosts,+ )if vcr_outcome_logging_enabled():request.node.user_properties.append(- ("vcr_verdict", _format_verdict_line(verdict, None, extra))+ (_USER_PROP_VERDICT_LINE, _format_verdict_line(verdict, None, extra)))@@ -1225,6 +1336,13 @@ class VerboseReporterState:return self.terminal_reporterdef maybe_emit_verdict(self, report) -> None:+ # Aggregate xdist-worker stats into the controller's session counters+ # first — this path is independent of verbose logging because the+ # structured outcome payload is always attached when VCR is active,+ # and ``aggregate_report_outcome`` no-ops outside the xdist-controller+ # case on its own.+ aggregate_report_outcome(report)+if report.when != "teardown":returnif os.environ.get("PYTEST_XDIST_WORKER"):@@ -1235,7 +1353,11 @@ class VerboseReporterState:if reporter is None:returnverdict = next(- (v for k, v in (report.user_properties or []) if k == "vcr_verdict"),+ (+ v+ for k, v in (report.user_properties or [])+ if k == _USER_PROP_VERDICT_LINE+ ),None,)if not verdict:diff --git a/tests/llm_translation/test_vcr_classification.py b/tests/llm_translation/test_vcr_classification.pyindex 9ab0fedbbf7..babb3427311 100644--- a/tests/llm_translation/test_vcr_classification.py+++ b/tests/llm_translation/test_vcr_classification.py@@ -42,6 +42,7 @@ from tests._vcr_conftest_common import ( # noqa: E402_is_live_call_host,_reset_session_stats,_stable_key_value,+ aggregate_report_outcome,apply_vcr_auto_marker_to_items,emit_vcr_classification_summary,install_live_call_probe,@@ -49,7 +50,6 @@ from tests._vcr_conftest_common import ( # noqa: E402session_stats_snapshot,)-# ---------------------------------------------------------------------------# Test doubles# ---------------------------------------------------------------------------@@ -504,6 +504,252 @@ def test_should_emit_no_summary_when_no_tests_observed(vcr_enabled):assert reporter.output == ""+# ---------------------------------------------------------------------------+# xdist controller aggregation+#+# _session_stats lives in module-global memory. Under xdist that memory is+# per-worker, so the controller's pytest_terminal_summary would render an+# empty summary without these aggregation hooks. The tests below simulate+# the controller receiving teardown reports produced by workers.+# ---------------------------------------------------------------------------+++def _worker_report(nodeid: str, user_properties, *, when: str = "teardown"):+ """Stand-in for a pytest TestReport delivered to the xdist controller.++ Only the attributes ``aggregate_report_outcome`` reads (``nodeid``,+ ``when``, ``user_properties``) are populated.+ """+ return SimpleNamespace(+ nodeid=nodeid,+ when=when,+ user_properties=list(user_properties),+ )+++def _outcome_from_worker(+ verdict: str,+ *,+ worker_id: str = "gw0",+ skip_reason=None,+ live_call_hosts=None,+):+ """Build the ``user_properties`` list a worker-side ``record_vcr_outcome``+ would attach. ``worker_id=""`` simulates the single-process case where+ the same process that ran the test is handling the report."""+ return [+ (+ "vcr_outcome",+ {+ "verdict": verdict,+ "skip_reason": skip_reason,+ "live_call_hosts": list(live_call_hosts) if live_call_hosts else [],+ },+ ),+ ("vcr_recorded_by", worker_id),+ ]+++def test_controller_aggregates_hit_outcome_from_worker_report(vcr_enabled):+ """An xdist controller starts with an empty _session_stats; a teardown+ report carrying a worker-produced ``vcr_outcome`` must populate the+ controller's verdict counts so the session summary has data to render."""+ report = _worker_report(+ "t::hit",+ _outcome_from_worker(VERDICT_HIT),+ )++ aggregate_report_outcome(report)++ snap = session_stats_snapshot()+ assert snap["verdict_counts"][VERDICT_HIT] == 1+++def test_controller_records_overflow_nodeid_from_worker_report(vcr_enabled):+ """OVERFLOW outcomes from workers must also populate+ ``overflow_tests`` (the named-list the summary surfaces)."""+ report = _worker_report(+ "t::bedrock_overflow",+ _outcome_from_worker(VERDICT_MISS_OVERFLOW),+ )++ aggregate_report_outcome(report)++ snap = session_stats_snapshot()+ assert snap["verdict_counts"][VERDICT_MISS_OVERFLOW] == 1+ assert snap["overflow_tests"] == ["t::bedrock_overflow"]+++def test_controller_records_live_call_hosts_from_worker_report(vcr_enabled):+ """LIVE_CALL outcomes must round-trip the destination hosts so the+ summary's 'UNMARKED TESTS WITH LIVE API CALLS' section has the same+ detail it would in single-process mode."""+ report = _worker_report(+ "t::prompt_caching",+ _outcome_from_worker(+ VERDICT_UNMARKED_LIVE_CALL,+ skip_reason=SKIP_REASON_INCOMPATIBLE,+ live_call_hosts=["api.anthropic.com", "api.x.ai"],+ ),+ )++ aggregate_report_outcome(report)++ snap = session_stats_snapshot()+ assert snap["verdict_counts"][VERDICT_UNMARKED_LIVE_CALL] == 1+ assert snap["unmarked_live_call_tests"] == [+ ("t::prompt_caching", ["api.anthropic.com", "api.x.ai"])+ ]+ assert snap["skip_reason_counts"][SKIP_REASON_INCOMPATIBLE] == 1+ assert "t::prompt_caching" in snap["skip_reason_examples"][SKIP_REASON_INCOMPATIBLE]+++def test_controller_does_not_double_count_single_process_reports(vcr_enabled):+ """In single-process mode, ``record_vcr_outcome`` updates+ ``_session_stats`` in the same process that later handles the report.+ The aggregator must detect this (via empty ``vcr_recorded_by``) and+ skip — otherwise every verdict would be counted twice."""+ report = _worker_report(+ "t::single_proc",+ _outcome_from_worker(VERDICT_HIT, worker_id=""),+ )++ aggregate_report_outcome(report)++ snap = session_stats_snapshot()+ assert snap["verdict_counts"] == {}+++def test_controller_ignores_reports_without_vcr_outcome(vcr_enabled):+ """Tests outside the VCR plumbing (e.g. when VCR is disabled, or unit+ tests that never went through ``_vcr_outcome_gate``) produce reports+ with no ``vcr_outcome`` user property. The aggregator must no-op."""+ report = _worker_report("t::unrelated", [("other", "value")])++ aggregate_report_outcome(report)++ snap = session_stats_snapshot()+ assert snap["verdict_counts"] == {}+++def test_controller_ignores_non_teardown_phases(vcr_enabled):+ """Only the teardown report carries the final outcome; setup/call+ reports must not contribute to the counts."""+ for phase in ("setup", "call"):+ report = _worker_report(+ "t::phase",+ _outcome_from_worker(VERDICT_HIT),+ when=phase,+ )+ aggregate_report_outcome(report)++ snap = session_stats_snapshot()+ assert snap["verdict_counts"] == {}+++def test_controller_no_ops_when_running_inside_xdist_worker(vcr_enabled, monkeypatch):+ """Workers update their own ``_session_stats`` directly via+ ``record_vcr_outcome`` — re-aggregating from the report would+ double-count their own work. The aggregator must bail when+ ``PYTEST_XDIST_WORKER`` is set."""+ monkeypatch.setenv("PYTEST_XDIST_WORKER", "gw3")+ report = _worker_report(+ "t::on_worker",+ _outcome_from_worker(VERDICT_HIT, worker_id="gw3"),+ )++ aggregate_report_outcome(report)++ snap = session_stats_snapshot()+ assert snap["verdict_counts"] == {}+++def test_controller_aggregated_outcomes_drive_session_summary(vcr_enabled):+ """End-to-end: with only worker-produced reports (no in-process+ ``record_vcr_outcome``), the session-end summary must still render+ the OVERFLOW + LIVE_CALL sections that prove the cost-leak signal+ survived the xdist worker→controller hop."""+ aggregate_report_outcome(+ _worker_report(+ "t::overflow_via_worker",+ _outcome_from_worker(VERDICT_MISS_OVERFLOW),+ )+ )+ aggregate_report_outcome(+ _worker_report(+ "t::live_call_via_worker",+ _outcome_from_worker(+ VERDICT_UNMARKED_LIVE_CALL,+ skip_reason=SKIP_REASON_RESPX,+ live_call_hosts=["api.openai.com"],+ ),+ )+ )++ reporter = _FakeReporter()+ emit_vcr_classification_summary(reporter)++ assert "VCR CACHE CLASSIFICATION SUMMARY" in reporter.output+ assert "CASSETTE OVERFLOW" in reporter.output+ assert "t::overflow_via_worker" in reporter.output+ assert "UNMARKED TESTS WITH LIVE API CALLS" in reporter.output+ assert "api.openai.com" in reporter.output+ assert "t::live_call_via_worker" in reporter.output+++def test_record_vcr_outcome_emits_structured_payload_for_marked_tests(+ vcr_enabled,+):+ """``record_vcr_outcome`` must always stash the structured outcome on+ ``user_properties`` (independent of verbose logging) so the controller+ has something to aggregate from in xdist mode."""+ request = SimpleNamespace(+ node=SimpleNamespace(+ nodeid="t::marked",+ user_properties=[],+ rep_call=SimpleNamespace(passed=True),+ )+ )+ cassette = _cassette(played=1, dirty=False, total=1)+ cassette._path = None+ record_vcr_outcome(request, cassette)++ outcomes = [v for k, v in request.node.user_properties if k == "vcr_outcome"]+ recorded_by = [v for k, v in request.node.user_properties if k == "vcr_recorded_by"]+ assert outcomes == [+ {"verdict": VERDICT_HIT, "skip_reason": None, "live_call_hosts": []}+ ]+ # No PYTEST_XDIST_WORKER set in the vcr_enabled fixture, so the+ # recording-process tag is the empty string (single-process mode).+ assert recorded_by == [""]+++def test_record_vcr_outcome_emits_structured_payload_for_unmarked_live_call(+ vcr_enabled,+):+ """The unmarked-LIVE_CALL path must ship the hosts list and the+ skip-reason so the controller can rebuild both."""+ request_node = SimpleNamespace(+ nodeid="t::leak",+ user_properties=[],+ rep_call=SimpleNamespace(passed=True),+ )+ setattr(request_node, VCR_SKIP_REASON_USER_ATTR, SKIP_REASON_RESPX)+ setattr(request_node, "vcr_live_call_hosts", ["api.openai.com"])+ request = SimpleNamespace(node=request_node)++ record_vcr_outcome(request, None)++ outcomes = [v for k, v in request.node.user_properties if k == "vcr_outcome"]+ assert outcomes == [+ {+ "verdict": VERDICT_UNMARKED_LIVE_CALL,+ "skip_reason": SKIP_REASON_RESPX,+ "live_call_hosts": ["api.openai.com"],+ }+ ]++# ---------------------------------------------------------------------------# Live-call probe# ---------------------------------------------------------------------------