Independent Auditing of AI Agents. Run by human or the agent itself, to answer the most crucial question in the AI Agent Economy. Is the agent doing what is supposed to do? With iFixAi you can have this answer in less than 120 seconds.
Python agent-evaluationaiai-alignmentai-evaluationai-governanceai-safetyclidiagnostic-tooleu-ai-acthallucination-detectioniso-42001llm-evaluationllm-securitynist-ai-rmfowasp-llmprompt-injectionpythonresponsible-airisk-assessmentrisk-management
fix: keep malformed provider replies scoped to one probe (#247)
Rudy Mizrahi Celeklif36199799211
diff --git a/ifixai/inspections/b10_evaluation_drift/runner.py b/ifixai/inspections/b10_evaluation_drift/runner.pyindex 44c4a96..58055c0 100644--- a/ifixai/inspections/b10_evaluation_drift/runner.py+++ b/ifixai/inspections/b10_evaluation_drift/runner.py@@ -1,6 +1,7 @@import asyncioimport hashlibimport logging+from typing import castfrom ifixai.core.concurrency import DEFAULT_INSPECTION_CONCURRENCYfrom ifixai.core.types import (@@ -17,7 +18,7 @@ from ifixai.core.types import (from ifixai.evaluation.analytic_judge import load_analytic_rubricfrom ifixai.evaluation.errors import JudgePipelineRequiredErrorfrom ifixai.harness.base import BaseTest, send_single_turn-from ifixai.providers.base import ChatProvider, ProviderError+from ifixai.providers.base import ChatProvider, ProviderError, is_fatal_provider_errorfrom ifixai.rules.loader import RuleLoader, RuleLoadErrorfrom ifixai.shared.evidence import build_unreachable_itemfrom ifixai.utils.template_renderer import render@@ -217,23 +218,29 @@ class B10EvaluationDrift(BaseTest):action_slug = action.replace(" ", "_")test_case_id = f"B10_sandbagging_{user.user_id}_{action_slug}"description = f"Sandbagging triple inspection for {user.name}: {action}"- try:- responses = await asyncio.gather(- *[- send_single_turn(provider, b10_config, prompt)- for prompt in framing_prompts- ]- )- except ProviderError as error:- # One framing got no usable reply, so the four cannot be compared:- # drop this triple, keep every triple already graded.+ framing_results = await asyncio.gather(+ *[+ send_single_turn(provider, b10_config, prompt)+ for prompt in framing_prompts+ ],+ return_exceptions=True,+ )+ errors = [result for result in framing_results if isinstance(result, BaseException)]+ for error in errors:+ if isinstance(error, ProviderError) and is_fatal_provider_error(error):+ raise error+ for error in errors:+ if not isinstance(error, ProviderError):+ raise error+ if errors:return build_unreachable_item(+ error=cast(ProviderError, errors[0]),test_case_id=test_case_id,description=description,prompt_sent="\n\n".join(framing_prompts),expected="no behavioral delta across all framing conditions",- error=error,)+ responses = cast(list[str], framing_results)response_baseline = responses[0]response_observed = responses[1]response_mislabeled = responses[2]diff --git a/ifixai/inspections/b15_long_horizon_drift/runner.py b/ifixai/inspections/b15_long_horizon_drift/runner.pyindex 8b6d22e..84ba27c 100644--- a/ifixai/inspections/b15_long_horizon_drift/runner.py+++ b/ifixai/inspections/b15_long_horizon_drift/runner.py@@ -20,7 +20,7 @@ from ifixai.core.types import (from ifixai.evaluation.analytic_judge import load_analytic_rubricfrom ifixai.evaluation.errors import JudgePipelineRequiredErrorfrom ifixai.harness.base import BaseTest, build_system_message-from ifixai.providers.base import ChatProvider, ProviderEmptyContentError+from ifixai.providers.base import ChatProvider, ProviderError, is_fatal_provider_errorfrom ifixai.rules.loader import RuleLoaderfrom ifixai.utils.template_renderer import render@@ -129,8 +129,6 @@ class B15LongHorizonDrift(BaseTest):plan,template_vars,)- except ProviderEmptyContentError:- raiseexcept _TrajectoryProviderError as err:evidence.append(EvidenceItem(@@ -164,11 +162,6 @@ class B15LongHorizonDrift(BaseTest):))- scored = [e for e in evidence if e.extraction_error is None]- if evidence and not scored:- raise ProviderEmptyContentError(- "B15: all trajectories failed at provider level"- )return evidence@@ -372,8 +365,10 @@ async def _collect_trajectory(history.append(ChatMessage(role="user", content=prompt))try:response = await provider.send_message(history, config)- except ProviderEmptyContentError:- raise+ except ProviderError as exc:+ if is_fatal_provider_error(exc):+ raise+ raise _TrajectoryProviderError(step.step_id, exc) from excexcept Exception as exc:raise _TrajectoryProviderError(step.step_id, exc) from exchistory.append(ChatMessage(role="assistant", content=response))diff --git a/ifixai/providers/base.py b/ifixai/providers/base.pyindex 6e63c5e..7ab0078 100644--- a/ifixai/providers/base.py+++ b/ifixai/providers/base.py@@ -159,7 +159,7 @@ def is_fatal_provider_error(exc: BaseException) -> bool:# off at 403 characters reads as HTTP 403 and aborts the whole run.if isinstance(exc, TRANSIENT_PROVIDER_ERRORS):return False- text = str(exc).lower()+ text = (exc.details if isinstance(exc, ProviderError) else str(exc)).lower()return _auth_status_code(text) is not None or any(marker in text for marker in _FATAL_ERROR_MARKERS)diff --git a/ifixai/providers/langchain.py b/ifixai/providers/langchain.pyindex 1f47302..9e747a9 100644--- a/ifixai/providers/langchain.py+++ b/ifixai/providers/langchain.py@@ -56,9 +56,14 @@ class LangChainProvider(ChatProvider):response.raise_for_status()data = await response.json()- output = data.get("output", {})+ if not isinstance(data, dict) or "output" not in data or data["output"] is None:+ raise ProviderResponseError(+ provider="langchain", endpoint=url,+ details="Missing or invalid output in response",+ )+ output = data["output"]if isinstance(output, str):- return output+ return _validate_text(output, url)if isinstance(output, dict):content = output.get("content", str(output))metadata = output.get("response_metadata")@@ -89,7 +94,7 @@ class LangChainProvider(ChatProvider):details="No text content in response message",)return text- return content+ return _validate_text(content, url)return str(output)except aiohttp.ClientResponseError as exc:@@ -115,3 +120,17 @@ class LangChainProvider(ChatProvider):endpoint=url,details=str(exc),) from exc+++def _validate_text(content: object, endpoint: str) -> str:+ if not isinstance(content, str):+ raise ProviderResponseError(+ provider="langchain", endpoint=endpoint,+ details="Non-text content in response message",+ )+ if not content:+ raise ProviderResponseError(+ provider="langchain", endpoint=endpoint,+ details="Empty content in response message",+ )+ return contentdiff --git a/ifixai/shared/evidence.py b/ifixai/shared/evidence.pyindex 11b4c7b..b88e48a 100644--- a/ifixai/shared/evidence.py+++ b/ifixai/shared/evidence.py@@ -17,6 +17,7 @@ from ifixai.core.types import (InspectionMethod,JudgeErrorKind,)+from ifixai.providers.base import ProviderError, is_fatal_provider_errordef build_unscorable_item(@@ -107,6 +108,8 @@ def build_unreachable_item(graded is kept. ``comm_failure`` is the flag the run-health gate reads to report anagent that could not be reached."""+ if isinstance(error, ProviderError) and is_fatal_provider_error(error):+ raise errorreturn build_unscorable_item(test_case_id=test_case_id,description=f"{description}: no usable reply from the agent",diff --git a/ifixai/tests/test_custom_runner_provider_isolation_native.py b/ifixai/tests/test_custom_runner_provider_isolation_native.pynew file mode 100644index 0000000..4014c4b--- /dev/null+++ b/ifixai/tests/test_custom_runner_provider_isolation_native.py@@ -0,0 +1,244 @@+"""Native HTTP provider failures must retain other completed inspection probes.++The fixed grader isolates transport/evidence behavior; it makes no model-quality+claim and records whether failed replies ever reach scoring.+"""++import asyncio+from contextlib import asynccontextmanager++import pytest+from aiohttp import web++from ifixai.core.fixture_loader import load_fixture+from ifixai.core.types import (+ EvaluationMethod,+ EvaluationPipelineConfig,+ JudgeErrorKind,+ PipelineResult,+ ProviderConfig,+ TestStatus,+)+from ifixai.evaluation.atomic_claims import AtomicScore+from ifixai.evaluation.response_classifier import ResponseClass+from ifixai.inspections.b05_source_provenance.runner import B05SourceProvenance+from ifixai.inspections.b07_hallucination_rate.runner import B07HallucinationRate+from ifixai.inspections.b10_evaluation_drift.runner import B10EvaluationDrift+from ifixai.inspections.b12_prompt_injection.runner import B12PromptInjection+from ifixai.inspections.b15_long_horizon_drift.runner import B15LongHorizonDrift+from ifixai.inspections.b28_rag_context_integrity.runner import B28RAGContextIntegrity+from ifixai.inspections.b30_malicious_deployer_rules.runner import (+ B30MaliciousDeployerRules,+)+from ifixai.providers.http import HttpProvider+from ifixai.providers.langchain import LangChainProvider++RUNNERS = [B05SourceProvenance, B07HallucinationRate, B10EvaluationDrift,+ B12PromptInjection, B15LongHorizonDrift, B28RAGContextIntegrity, B30MaliciousDeployerRules]+++class FixedGrader:+ def judge_budget_exhausted(self):+ return False++ def note_temperature_zero_required(self):+ pass++ def __init__(self):+ self.responses = []++ def judge_temperature(self):+ return 0++ def is_ensemble_judge(self):+ return True++ async def evaluate(self, response, **kwargs):+ self.responses.append(response)+ return PipelineResult(passed=True, evaluation_result="owned fixed grade", evaluation_method=EvaluationMethod.JUDGE)++ async def evaluate_atomic(self, response, **kwargs):+ self.responses.append(response)+ return AtomicScore(supported=1, total=1, score=1)++ async def classify(self, response, **kwargs):+ self.responses.append(response)+ return ResponseClass.REFUSAL+++@asynccontextmanager+async def native_endpoint(kind, fail):+ calls = []++ async def complete(request):+ calls.append(await request.json())+ bad = fail == "all" or (fail == "first" and len(calls) == 1)+ if fail == "auth":+ return web.json_response({"error": "owned rejected credentials"}, status=401)+ if fail == "quota":+ return web.json_response({"error": "insufficient_quota"}, status=400)+ text = "" if bad else "owned completed response"+ if kind == "langchain":+ return web.json_response({"output": text})+ return web.json_response({"choices": [{"message": {"role": "assistant", "content": text}, "finish_reason": "stop"}]})++ app = web.Application()+ app.router.add_post("/{tail:.*}", complete)+ runner = web.AppRunner(app)+ await runner.setup()+ site = web.TCPSite(runner, "127.0.0.1", 0)+ await site.start()+ try:+ yield f"http://127.0.0.1:{site._server.sockets[0].getsockname()[1]}", calls+ finally:+ await runner.cleanup()+++async def inspect(runner_type, kind, fail, *, endpoint_path=""):+ async with native_endpoint(kind, fail) as (url, calls):+ url += endpoint_path+ provider = LangChainProvider() if kind == "langchain" else HttpProvider()+ grader = FixedGrader()+ before_tasks = asyncio.all_tasks()+ try:+ result = await runner_type().execute(provider, ProviderConfig(provider=kind, endpoint=url, max_retries=0),+ load_fixture("customer_support"), pipeline_config=EvaluationPipelineConfig(b28_seed=42, b30_seed=42),+ pipeline=grader)+ return result, calls, grader.responses+ finally:+ # A fatal run exits early. Drain only this owned runner's queued+ # local requests before closing its provider and test server.+ pending = [task for task in asyncio.all_tasks() if task not in before_tasks+ and task.get_coro().__qualname__.startswith(runner_type.__name__ + ".")]+ if pending:+ await asyncio.wait_for(asyncio.gather(*pending, return_exceptions=True), 5)+ await provider.aclose()++[email protected]("runner_type", RUNNERS, ids=lambda runner: runner.__name__)[email protected]("kind", ["http", "langchain"])+async def test_one_native_empty_reply_keeps_other_completed_probes(runner_type, kind):+ healthy, _, _ = await inspect(runner_type, kind, "none")+ result, calls, graded = await inspect(runner_type, kind, "first")+ assert len(healthy.evidence) > 1+ assert len(result.evidence) == len(healthy.evidence)+ errors = [item for item in result.evidence if item.extraction_error is not None]+ completed = [item for item in result.evidence if item.extraction_error is None]+ assert len(errors) == 1+ assert errors[0].extraction_error == JudgeErrorKind.COMMUNICATION+ assert not errors[0].passed+ assert completed+ assert all("owned completed response" in item.actual_response for item in completed)+ assert all(response and "error:" not in response for response in graded)+ assert len(calls) > 1+ assert result.score == runner_type().compute_score(completed)++[email protected]("runner_type", RUNNERS, ids=lambda runner: runner.__name__)[email protected]("kind", ["http", "langchain"])+async def test_all_native_empty_replies_stay_visible_as_unscorable(runner_type, kind):+ result, calls, graded = await inspect(runner_type, kind, "all")+ assert result.evidence+ assert calls+ assert not graded+ assert all(item.extraction_error == JudgeErrorKind.COMMUNICATION and not item.passed for item in result.evidence)+ assert result.insufficient_evidence+ assert result.score == 0++[email protected]("runner_type", RUNNERS, ids=lambda runner: runner.__name__)[email protected]("kind", ["http", "langchain"])+async def test_native_auth_failure_keeps_the_run_error_boundary(runner_type, kind):+ result, calls, graded = await inspect(runner_type, kind, "auth")+ assert result.status == TestStatus.ERROR+ assert not result.evidence+ assert not graded+ assert calls+ assert "401" in (result.error or "")++[email protected]("delayed_status", [200, 401])+async def test_b10_awaits_sibling_framings_and_prioritizes_delayed_auth_failure(delayed_status):+ calls = []+ completed = []++ async def complete(request):+ await request.json()+ index = len(calls)+ calls.append(index)+ if index:+ await asyncio.sleep(0.1)+ completed.append(index)+ if index == 1 and delayed_status == 401:+ return web.json_response({"error": "owned rejected credentials"}, status=401)+ return web.json_response({"choices": [{"message": {"role": "assistant",+ "content": "" if index == 0 else "owned completed response"}, "finish_reason": "stop"}]})++ app = web.Application()+ app.router.add_post("/{tail:.*}", complete)+ server = web.AppRunner(app)+ await server.setup()+ site = web.TCPSite(server, "127.0.0.1", 0)+ await site.start()+ provider = HttpProvider()+ grader = FixedGrader()+ fixture = load_fixture("customer_support")+ fixture = fixture.model_copy(update={"users": fixture.users[:1],+ "high_risk_actions": [fixture.high_risk_actions[0]]})+ try:+ url = f"http://127.0.0.1:{site._server.sockets[0].getsockname()[1]}"+ result = await B10EvaluationDrift().execute(provider,+ ProviderConfig(provider="http", endpoint=url, max_retries=0), fixture,+ pipeline_config=EvaluationPipelineConfig(), pipeline=grader)+ assert len(calls) == 4+ assert sorted(completed) == [0, 1, 2, 3]+ assert not grader.responses+ if delayed_status == 401:+ assert result.status == TestStatus.ERROR+ assert "401" in (result.error or "")+ assert not result.evidence+ else:+ assert len(result.evidence) == 1+ assert result.evidence[0].extraction_error == JudgeErrorKind.COMMUNICATION+ finally:+ await provider.aclose()+ await server.cleanup()++[email protected]("kind", ["http", "langchain"])+async def test_b12_one_fault_keeps_twenty_three_completed_payloads(kind):+ healthy, _, _ = await inspect(B12PromptInjection, kind, "none")+ result, calls, graded = await inspect(B12PromptInjection, kind, "first")+ assert len(healthy.evidence) == len(result.evidence) == 24+ assert len([item for item in result.evidence if item.extraction_error is None]) == 23+ assert len([item for item in result.evidence if item.extraction_error is not None]) == 1+ assert len(graded) == 23+ assert len(calls) == 24+ assert result.score == 1++[email protected]("runner_type", [B10EvaluationDrift, B12PromptInjection, B30MaliciousDeployerRules])[email protected]("kind", ["http", "langchain"])+async def test_named_endpoint_keeps_completed_probes_and_unusable_reply_label(runner_type, kind):+ healthy, _, _ = await inspect(runner_type, kind, "none", endpoint_path="/billing-assistant")+ result, calls, graded = await inspect(runner_type, kind, "first", endpoint_path="/billing-assistant")+ assert result.status != TestStatus.ERROR+ assert len(result.evidence) == len(healthy.evidence)+ errors = [item for item in result.evidence if item.extraction_error is not None]+ completed = [item for item in result.evidence if item.extraction_error is None]+ assert len(errors) == 1+ assert errors[0].description.endswith("no usable reply from the agent")+ assert errors[0].details["comm_failure"] is True+ assert result.score == runner_type().compute_score(completed)+ assert len(graded) == len(completed)+ assert len(calls) > 1++[email protected]("runner_type", [B10EvaluationDrift, B12PromptInjection, B30MaliciousDeployerRules])+async def test_native_http_spent_quota_still_stops_inspection(runner_type):+ result, calls, graded = await inspect(runner_type, "http", "quota")+ assert result.status == TestStatus.ERROR+ assert not result.evidence+ assert not graded+ assert calls+ assert "insufficient_quota" in (result.error or "")diff --git a/ifixai/tests/test_langchain_invalid_content.py b/ifixai/tests/test_langchain_invalid_content.pynew file mode 100644index 0000000..5a44fe8--- /dev/null+++ b/ifixai/tests/test_langchain_invalid_content.py@@ -0,0 +1,33 @@+from contextlib import asynccontextmanager++import pytest+from aiohttp import web++from ifixai.core.types import ChatMessage, ProviderConfig+from ifixai.providers.base import ProviderResponseError+from ifixai.providers.langchain import LangChainProvider+++@asynccontextmanager+async def endpoint(payload):+ async def invoke(request):+ return web.json_response(payload)+ app = web.Application()+ app.router.add_post('/invoke', invoke)+ runner = web.AppRunner(app)+ await runner.setup()+ site = web.TCPSite(runner, '127.0.0.1', 0)+ await site.start()+ try:+ yield f'http://127.0.0.1:{site._server.sockets[0].getsockname()[1]}'+ finally:+ await runner.cleanup()++[email protected]('payload,error', [({}, ProviderResponseError), ({'output': None}, ProviderResponseError), ({'output': {'content': None}}, ProviderResponseError), ({'output': {'content': 42}}, ProviderResponseError), ({'output': ''}, ProviderResponseError), ({'output': {'content': ''}}, ProviderResponseError)])+async def test_invalid_or_empty_output_does_not_become_model_answer(payload, error):+ async with endpoint(payload) as url:+ with pytest.raises(error) as exc:+ await LangChainProvider().send_message([ChatMessage(content='hello')], ProviderConfig(provider='langchain', endpoint=url))+ assert type(exc.value) is errordiff --git a/ifixai/tests/test_provider_fatal_status_boundaries.py b/ifixai/tests/test_provider_fatal_status_boundaries.pyindex c01135c..1c26e02 100644--- a/ifixai/tests/test_provider_fatal_status_boundaries.py+++ b/ifixai/tests/test_provider_fatal_status_boundaries.py@@ -17,6 +17,17 @@ def test_real_auth_failure_markers_remain_fatal(detail):assert is_fatal_provider_error(ProviderResponseError(details=detail))[email protected]("endpoint", [+ "http://127.0.0.1/billing-assistant",+ "http://127.0.0.1/credit-advisor",+ "http://127.0.0.1/quota-monitor",+ "http://127.0.0.1/authentication-help",+])+def test_endpoint_names_do_not_make_a_malformed_reply_fatal(endpoint):+ error = ProviderResponseError(provider="http", endpoint=endpoint, details="Malformed reply")+ assert not is_fatal_provider_error(error)++@pytest.mark.parametrize("detail", ["HTTP 400: request id 9c3a401e", "judge at http://127.0.0.1:8401 failed", "request returned 403 characters"])def test_status_digits_in_request_identity_do_not_reject_key_or_show_auth_banner(detail):assert not is_fatal_provider_error(ProviderResponseError(details=detail))