"""Native persistence/HTTP integration. Subjects and LLMs here are test doubles.""" from concurrent.futures import ThreadPoolExecutor from dataclasses import replace import json from pathlib import Path import re import threading from urllib.error import HTTPError from urllib.request import Request, urlopen from urllib.parse import quote import pytest from agent_evaluation.backend import NativeStore, NativeTraceStore, NativeExperimentBackend, create_native_adapters from agent_evaluation.backend.server import NativeServer from agent_evaluation.backend import server as server_module from agent_evaluation.backend.otlp import decode_otlp from agent_evaluation.datasets.loader import JsonDatasetLoader from agent_evaluation.integrations.simulator import SimulatorAdapter from agent_evaluation.instrumentation import build_instrumentation from agent_evaluation.loop import EvaluationLoop from agent_evaluation.models import TraceRef from agent_evaluation.backend.views import report_data_from_experiment from agent_evaluation.reporting.render import render_evaluation_document from .support import CallableLLMBackend, write_canonical_dataset def otlp_span(span_id="0000000000000001", name="Turn", start=0, end=200, attrs=None): attributes = {"session.id": "session-test", **(attrs or {})} def value(item): if isinstance(item, int): return {"intValue": str(item)} return {"stringValue": item} return {"traceId": "1" * 32, "spanId": span_id, "name": name, "startTimeUnixNano": str((1800000000 + start) * 1000000000), "endTimeUnixNano": str((1800000000 + end) * 1000000000), "attributes": [{"key": key, "value": value(item)} for key, item in attributes.items()]} def payload(spans): return {"resourceSpans": [{"resource": {"attributes": [{"key": "service.name", "value": {"stringValue": "opencode"}}]}, "scopeSpans": [{"spans": spans}]}]} @pytest.fixture def server(tmp_path, monkeypatch): monkeypatch.setenv("NO_PROXY", "127.0.0.1,localhost") monkeypatch.setenv("no_proxy", "127.0.0.1,localhost") store = NativeStore(tmp_path / "native.sqlite") http = NativeServer(("127.0.0.1", 0), store) thread = threading.Thread(target=http.serve_forever) thread.start() yield store, f"http://127.0.0.1:{http.server_port}" http.shutdown() http.server_close() thread.join() def post(endpoint, spans): request = Request(endpoint + "/v1/traces", data=json.dumps(payload(spans)).encode(), headers={"Content-Type": "application/json", "X-Trace-Project": "subject"}) with urlopen(request) as response: return json.load(response) def test_otlp_ingest_is_durable_idempotent_and_validates_before_write(server): store, endpoint = server span = otlp_span(attrs={"eval.events": "[]", "output.value": ""}) assert post(endpoint, [span]) == {} post(endpoint, [span]) stored = NativeStore(store.path).spans("subject", "session-test") assert len(stored) == 1 assert stored[0]["attributes"]["output.value"] == "" with pytest.raises(HTTPError) as error: post(endpoint, [otlp_span("0000000000000002"), {**span, "traceId": "bad"}]) assert error.value.code == 400 assert len(store.spans("subject", "session-test")) == 1 assert not store.spans("other", "session-test") create_native_adapters(store.path, endpoint) with pytest.raises(ValueError, match="same --database"): create_native_adapters(store.path.parent / "other.sqlite", endpoint) @pytest.mark.parametrize("field,value", [("traceId", "0" * 32), ("spanId", "no"), ("name", ""), ("endTimeUnixNano", "1"), ("startTimeUnixNano", True)]) def test_otlp_invalid_span(field, value): with pytest.raises((ValueError, TypeError)): decode_otlp(payload([{**otlp_span(), field: value}])) def test_trace_cache_is_one_stable_evidence_for_concurrent_readers(server): store, endpoint = server post(endpoint, [otlp_span()]) trace = NativeTraceStore(store, wait_seconds=0) instrumentation = build_instrumentation("eval-events/v1", ("llm_message", "tool_call")) calls = [] original = store.spans def counted(*args): calls.append(args) return original(*args) store.spans = counted with ThreadPoolExecutor(max_workers=8) as pool: evidence = list(pool.map(lambda _: trace.read(TraceRef("subject", "session-test"), instrumentation=instrumentation), range(20))) assert len(calls) == 1 assert all(item is evidence[0] for item in evidence) def _fixture(tmp_path, store, *, annotate=False): labels = ["Preflight: prepare"] + [f"Stage {i}: work" for i in range(1, 13)] labels.insert(6, "Handoff: transfer") ids = ["preflight", *[f"stage-{i}" for i in range(1, 6)], "handoff", *[f"stage-{i}" for i in range(6, 13)]] skill = tmp_path / "skill" skill.mkdir() states = "\n".join(f"{i}. `{label}`" for i, label in enumerate(labels, 1)) (skill / "SKILL.md").write_text(f"---\nname: test\n---\n## Runtime State Machine\n\n{states}\n") dataset = write_canonical_dataset(tmp_path / "dataset", [{"case_id": "case-1", "input": "work", "metadata": {}}]) profile = Path(__file__).parents[1] / "evaluation_profiles" / "veritas-ut-testplan-gen.yaml" content = profile.read_text() if annotate: for name in ["ut_m001_compile_errors", "ut_p001_deliverables"]: content = content.replace(f"- id: {name}", f"- id: {name}\n annotate: true") profile = tmp_path / "profile.yaml" profile.write_text(content) elapsed, spans = 0, [] for i, point in enumerate(ids): duration = [120, 100, 80, 70][i] if i < 4 else 5 event = {"protocol": "eval-events/v1", "event_type": "state", "entity_type": "testpoint", "entity_id": point, "state": "completed", "sequence": i+1} span = otlp_span(f"{i+2:016x}", "LLM: " + point, elapsed, elapsed + duration, {"llm.token_count.prompt": 100, "llm.token_count.completion": 20, "llm.token_count.total": 120, "openinference.span.kind": "LLM", "output.value": "Completed work.", "eval.events": json.dumps([event])}) span["parentSpanId"] = "0000000000000001" spans.append(span) elapsed += duration spans.insert(0, otlp_span(end=elapsed)) store.save_spans("subject", [s for _, s in decode_otlp(payload(spans))]) return skill, dataset, profile class CountingAdapter(SimulatorAdapter): count = 0 def run(self, *args): self.count += 1 return replace(super().run(*args), trace_ref=TraceRef("subject", "session-test")) def _loop(store, adapter, *, llm=None): trace = NativeTraceStore(store, wait_seconds=0) backend = NativeExperimentBackend(store, trace_store=trace) return EvaluationLoop(adapter, experiment_backend=backend, dataset_loader=JsonDatasetLoader(), trace_store=trace, llm_backend=llm) @pytest.mark.parametrize("annotate", [False, True]) def test_complete_profile_records_one_score_per_listed_evaluator(server, tmp_path, annotate): store, endpoint = server skill, dataset, profile = _fixture(tmp_path, store, annotate=annotate) calls = [] def complete(prompt, schema): calls.append(prompt) if "Diagnose why this selected TestPoint" in prompt: ref = re.search(r"trace\.span:[A-Za-z0-9_-]+", prompt).group(0) return {"summary": "Extended analysis dominates latency.", "bottlenecks": [{ "category": "analysis", "finding": "Long model call", "impact": "Latency", "recommendation": "Bound analysis", "confidence": "medium", "evidence_refs": [ref]}], "evidence_completeness": "partial"} return {"label": "pass", "reason": "Supported", "evidence_refs": [ "execution.deliverables" if "Execution validation:" in prompt else "trace.steps"]} adapter = CountingAdapter() loop = _loop(store, adapter, llm=CallableLLMBackend(complete)) result = loop.run(skill, dataset, tmp_path / "artifacts", evaluation_profile=profile, evolve=False) assert adapter.count == 1 assert result.backend_evaluation_count == 69 assert len(result.scores) == 69 assert result.published_result_count == (2 if annotate else 0) saved = store.experiment(result.experiment_id) assert saved["status"] == "completed" assert saved["scores"] == [s.to_dict() for s in result.scores] assert saved["inputs"]["evaluation_profile"]["sha256"] == result.evaluation_profile.profile_hash jsonl = tmp_path / "artifacts" / result.experiment_id / "scores.jsonl" assert [json.loads(line) for line in jsonl.read_text().splitlines()] == saved["scores"] assert len(store.annotations("subject", "session-test")) == (2 if annotate else 0) second = loop.run(skill, dataset, tmp_path / "artifacts", evaluation_profile=profile, evolve=False) assert second.experiment_id != result.experiment_id assert len(second.scores) == 69 and adapter.count == 2 assert len(store.experiments()) == 2 for path in ["/", "/sessions", "/trace?project=subject&session_id=session-test", f"/experiments/{result.experiment_id}", f"/experiments/{result.experiment_id}/report/index.html"]: with urlopen(endpoint + path) as response: document = response.read().decode() assert "" not in text and "<script>" in text request = Request(endpoint + "/v1/traces", data=b'{}', headers={"Content-Type": "application/json", "Origin": "https://untrusted.test"}) with pytest.raises(HTTPError) as error: urlopen(request) assert error.value.code == 403 def _execution_fixture(tmp_path, store, *, annotate=False): skill, dataset, profile = _fixture(tmp_path, store) import yaml config = yaml.safe_load(profile.read_text()) config["evaluation"]["evaluators"] = { "execution": [{"id": "expected_files_present", "annotate": annotate, "params": {"expected_files": ["result.md"]}}], "trace": []} profile.write_text(yaml.safe_dump(config)) return skill, dataset, profile def test_annotation_off_does_not_read_trace(server, tmp_path, monkeypatch): store, _ = server skill, dataset, profile = _execution_fixture(tmp_path, store) def unexpected(*args, **kwargs): raise AssertionError("execution-only run must not read trace") monkeypatch.setattr(store, "spans", unexpected) result = _loop(store, SimulatorAdapter()).run(skill, dataset, tmp_path / "artifacts", evaluation_profile=profile) assert result.published_result_count == 0 assert result.backend_metadata["warnings"] == [] assert result.backend_metadata["publications"]["span_annotations"]["attempted"] == 0 def test_annotation_missing_trace_preserves_assessment(server, tmp_path): store, _ = server skill, dataset, profile = _execution_fixture(tmp_path, store, annotate=True) result = _loop(store, SimulatorAdapter()).run(skill, dataset, tmp_path / "artifacts", evaluation_profile=profile) assert result.pass_rate == 1 assert result.backend_metadata["warnings"][0]["code"] == "target_missing" assert result.backend_metadata["publications"]["span_annotations"]["skipped"] == 1 def test_failed_task_is_persisted_and_evaluated_once(server, tmp_path): store, _ = server skill, dataset, profile = _execution_fixture(tmp_path, store) class FailedAgent(SimulatorAdapter): calls = 0 def run(self, *args): self.calls += 1 raise RuntimeError("test task failed") adapter = FailedAgent() result = _loop(store, adapter).run(skill, dataset, tmp_path / "artifacts", evaluation_profile=profile) assert adapter.calls == 1 and len(result.runs) == len(result.scores) == 1 assert result.runs[0].status == "failed" assert result.pass_rate == 0 assert len(store.experiment(result.experiment_id)["runs"]) == 1 def test_storage_failure_does_not_rerun_rule(server, tmp_path, monkeypatch): store, _ = server skill, dataset, profile = _execution_fixture(tmp_path, store) from agent_evaluation.evaluators.runtime import BoundEvaluator calls = [] original = BoundEvaluator.evaluate def counted(self, *args): calls.append(self.evaluator_id) return original(self, *args) def fail(*args): raise OSError("disk unavailable") monkeypatch.setattr(BoundEvaluator, "evaluate", counted) monkeypatch.setattr(store, "save_score", fail) with pytest.raises(OSError): _loop(store, SimulatorAdapter()).run(skill, dataset, tmp_path / "artifacts", evaluation_profile=profile) assert calls == ["execution.expected_files_present"] experiment = store.experiments()[0] assert experiment["status"] == "interrupted" assert experiment["run_count"] == 1 and experiment["score_count"] == 0 def test_rule_error_creates_one_error_record(server, tmp_path, monkeypatch): store, _ = server skill, dataset, profile = _execution_fixture(tmp_path, store) from agent_evaluation.evaluators.runtime import BoundEvaluator calls = [] def fail(self, *args): calls.append(self.evaluator_id) raise ValueError("test rule failed") monkeypatch.setattr(BoundEvaluator, "evaluate", fail) result = _loop(store, SimulatorAdapter()).run(skill, dataset, tmp_path / "artifacts", evaluation_profile=profile) assert len(calls) == len(result.scores) == 1 assert result.scores[0].status == "error" assert store.experiment(result.experiment_id)["scores"] == [result.scores[0].to_dict()] @pytest.mark.parametrize("failure", ["provider", "schema"]) def test_judge_error_is_recorded_once_without_sensitive_details(server, tmp_path, failure): import yaml store, _ = server skill, dataset, profile = _execution_fixture(tmp_path, store) config = yaml.safe_load(profile.read_text()) config["evaluation"]["evaluators"]["execution"] = [{ "id": "deliverable_quality", "params": { "artifact_paths": ["result.md"], "include_fixture": False, "max_chars_per_file": 1000, "max_total_chars": 2000}}] profile.write_text(yaml.safe_dump(config)) calls = [] def respond(*args): calls.append(1) if failure == "provider": raise RuntimeError("PRIVATE provider credential/body") return {"label": "PRIVATE", "reason": "ok", "evidence_refs": ["execution.deliverables"]} result = _loop(store, SimulatorAdapter(), llm=CallableLLMBackend(respond)).run( skill, dataset, tmp_path / "artifacts", evaluation_profile=profile, evolve=False) assert len(calls) == len(result.scores) == 1 score = result.scores[0] assert score.status == "error" and score.score is None assert score.metadata["error_stage"] == ("model_call" if failure == "provider" else "response_schema") assert score.metadata["error_code"] == ("completion_failed" if failure == "provider" else "schema_enum") assert score.metadata["error_path"] == (None if failure == "provider" else "response.label") saved = store.experiment(result.experiment_id) assert saved["scores"] == [score.to_dict()] assert "PRIVATE" not in json.dumps(saved) root = tmp_path / "artifacts" / result.experiment_id assert "PRIVATE" not in (root / "scores.jsonl").read_text() assert "PRIVATE" not in (root / "report" / "index.html").read_text() def test_reused_loop_gets_new_trace_snapshot(server, tmp_path): store, endpoint = server skill, dataset, profile = _execution_fixture(tmp_path, store) loop = _loop(store, CountingAdapter()) instrumentation = build_instrumentation("eval-events/v1", ("llm_message", "tool_call")) ref = TraceRef("subject", "session-test") first = loop.trace_store.read(ref, instrumentation=instrumentation) post(endpoint, [otlp_span(end=999)]) assert loop.trace_store.read(ref, instrumentation=instrumentation) is first loop.run(skill, dataset, tmp_path / "artifacts", evaluation_profile=profile) second = loop.trace_store.read(ref, instrumentation=instrumentation) assert second is not first and second.duration_seconds == 999 def test_annotations_idempotent_and_host_guard(server, tmp_path): store, endpoint = server skill, dataset, profile = _execution_fixture(tmp_path, store, annotate=True) result = _loop(store, CountingAdapter()).run(skill, dataset, tmp_path / "artifacts", evaluation_profile=profile) score = result.scores[0] for _ in range(2): store.annotate(score.score_id, "subject", "session-test", "0000000000000001") assert len(store.annotations("subject", "session-test")) == 1 with pytest.raises(HTTPError) as error: urlopen(Request(endpoint + "/api/sessions", headers={"Host": "attacker.example"})) assert error.value.code == 403 def test_server_allows_explicit_lan_host_allowlist(server, tmp_path): """A configured LAN Host is accepted while arbitrary Host values remain blocked.""" store, _ = server lan = NativeServer(("127.0.0.1", 0), store, allowed_hosts={"evalbox.lan", "192.168.1.20"}) thread = threading.Thread(target=lan.serve_forever) thread.start() try: endpoint = f"http://127.0.0.1:{lan.server_port}" with urlopen(Request(endpoint + "/api/health", headers={"Host": "evalbox.lan"})) as response: assert json.load(response)["backend"] == "native" with pytest.raises(HTTPError) as error: urlopen(Request(endpoint + "/api/health", headers={"Host": "other.lan"})) assert error.value.code == 403 finally: lan.shutdown() lan.server_close() thread.join() def test_default_lan_host_is_allowlisted(): assert "10.239.93.115" in server_module.DEFAULT_ALLOWED_HOSTS