File size: 9,126 Bytes
fd11263
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
from agent_evaluation.reporting.render import (
    _bar,
    _backend_link,
    _chart_maxima,
    _display_value,
    _numeric_value,
    _measurement_value_html,
    _publication_html,
    _status_class,
    render_evaluation_document,
)

import html
import json
from dataclasses import replace
from agent_evaluation.reporting.models import ReportData

import pytest

from agent_evaluation.evaluators import assessment_result, diagnostic_result, measurement_result
from agent_evaluation.models import ScoreIdentity, ScoreRecord


def test_renderer_keeps_unknown_measurement_values_structured():
    assert _display_value({"count": 3, "source": "new-evaluator"}) == '{"count": 3, "source": "new-evaluator"}'
    assert _status_class("previous_boundary_ambiguous") == "status-unavailable"


def test_renderer_accepts_new_result_status_without_evaluator_id_rules():
    # Unknown status values remain visible as warnings rather than crashing or
    # being silently rendered as a numeric success.
    assert _status_class("custom-evidence-state") == "status-warning"


def test_measurement_values_are_charted_from_structure_not_metric_names():
    assert _numeric_value(42) == 42.0
    assert _numeric_value({"total": 42, "other": 3}) == 42.0
    assert _numeric_value({"only": 42}) == 42.0
    assert _numeric_value({"p50": 12, "p95": 44, "samples": 3}) is None
    assert _numeric_value({"value": "not numeric"}) is None


def test_measurement_chart_scales_are_grouped_by_unit():
    rows = [
        {"unit": "seconds", "value": 2},
        {"unit": "seconds", "value": 4},
        {"unit": "tokens", "value": 1000},
    ]
    assert _chart_maxima(rows) == {"seconds": 4.0, "tokens": 1000.0}


@pytest.mark.parametrize("value", [True, False, float("inf"), float("-inf"), float("nan"), "3", None])
def test_non_chartable_scalar(value):
    assert _numeric_value(value) is None


def test_zero_negative_and_structured_measurements_are_not_misrepresented():
    assert "width:0.00%" in _bar(0, 10)
    assert _bar(-1, 10) == ""
    value = {"prompt": 1, "completion": 2, "total": 3, "extra": {"retained": 4}}
    assert json.loads(_display_value(value)) == value


def test_measurement_value_has_one_rounded_headline_and_separate_details():
    document = _measurement_value_html(330.87999987602234, "seconds", 400)
    assert document.count("330.9") == 1
    assert '<strong>330.9</strong><span class="unit">seconds</span>' in document
    # Precision is available on demand, not repeated beside the chart.
    assert '<summary>Exact value</summary><pre>330.87999987602234</pre>' in document
    assert '<span class="number">' not in document
    value = {"completion": 91, "prompt": 113824, "total": 113915, "custom": 3.45678}
    document = html.unescape(_measurement_value_html(value, "tokens", 113915))
    assert '<strong>113,915.0</strong>' in document
    assert '<div class="value-breakdown"><code>' in document
    assert '"custom": 3.5' in document
    assert value["custom"] == 3.45678  # Rendering must not mutate audit data.


def test_publication_is_a_readable_stats_card_with_optional_raw_details():
    backend = {"metadata": {"publications": {"custom_operation": {"attempted": 2, "published": 1}},
                            "warnings": [{"operation": "custom_operation", "code": "partial", "message": "<unsafe>"}]}}
    document = _publication_html(backend)
    assert '<h3>custom operation</h3>' in document
    assert '<dt>published</dt><dd>1</dd>' in document
    assert '<details><summary>Raw publication data</summary><pre>' in document
    assert '<unsafe>' not in document and '&lt;unsafe&gt;' in document
    assert 'No publication warnings' not in document


def test_report_uses_identity_grid_and_explicit_table_columns():
    report = render_evaluation_document(renderer_example_result())
    assert '<dl class="identity-grid">' in report
    assert '<dt>Backend</dt><dd>synthetic-renderer-only</dd>' in report
    assert '<dt>Agent model</dt>' in report
    assert report.count('<div class="experiment-id">') == 1
    assert 'Experiment backend:' not in report
    assert '<table class="assessments-table"><colgroup>' in report
    assert '<col class="col-attribution">' in report
    assert 'table-layout:fixed' in report
    assert '100.0%' in report


@pytest.mark.parametrize("url", [None, "", "javascript:alert(1)", "data:text/html,bad", "//example.com", "http://", "http://[", "https://host:bad", "https://user:secret@host", "https://host\n/bad"])
def test_unsafe_or_missing_backend_links_are_not_clickable(url):
    assert _backend_link(url) == ""


def renderer_example_result():
    """Synthetic rendering-only input; no agent or backend is executed."""
    values = [
        ("quality_custom", assessment_result(score=1.0, label="pass", explanation="Synthetic quality check.")),
        ("latency_profile", measurement_result(metric="latency_profile", unit="ms", value={"p50": 12, "p95": 44, "samples": 3})),
        ("energy", measurement_result(metric="energy", unit="joules", value=42)),
        ("capacity", measurement_result(metric="capacity", unit="items", value={"total": 1000, "used": 500, "extra": {"retained": True}})),
        ("delta", measurement_result(metric="delta", unit="joules", value=-4)),
        ("missing", measurement_result(metric="custom_missing", unit="items", value=None, status="unavailable")),
        ("custom_diagnosis", diagnostic_result(label="diagnosed", explanation="Custom diagnostic without bottlenecks.", value={"finding": "Preserve <all> details"})),
        ("partial_diagnosis", diagnostic_result(label="incomplete", explanation="Insufficient evidence.", status="incomplete", value=None)),
    ]
    scores = [ScoreRecord(f"score-{index}", ScoreIdentity("run", "synthetic-case", f"execution.{name}", "execution", "code", "generic", "v1"),
                          result, {"custom_metadata": {"keep": "<script>alert(1)</script>"}})
              for index, (name, result) in enumerate(values)]
    warning = {"operation": "span_annotations", "code": "unconfirmed", "message": "Synthetic publication warning (not a real experiment)."}
    backend_metadata = {"ui_url": "https://example.test/evaluation", "warnings": [warning],
                        "publications": {"span_annotations": {"attempted": 1, "published": 0, "unconfirmed": 1}}}
    summary = {"inputs": {}, "evaluation": {"assessment_count": 1, "measurement_count": 5, "diagnostic_count": 2, "pass_rate": 1.0},
               "backend": {"name": "synthetic-renderer-only", "metadata": backend_metadata}}
    return ReportData("renderer-synthetic-demo", (), tuple(scores), summary["inputs"], summary["backend"])


def test_generic_renderer_retains_every_result_and_escapes_content():
    result = renderer_example_result()
    report = render_evaluation_document(result, backend_ui_url="https://example.test/ui?a=1&b=2")
    visible = html.unescape(report)
    assert "Static audit snapshot" in report and "synthetic-renderer-only" in report
    assert 'href="https://example.test/ui?a=1&amp;b=2"' in report
    assert "127.0.0.1" not in report and "Phoenix" not in report
    assert "<script>alert" not in report and "&lt;script&gt;" in report
    for score in result.scores:
        assert score.evaluator_id in visible
        assert score.explanation in visible
        assert score.status in visible
    assert '"extra": {"retained": true}' in visible
    assert '"p95": 44' in visible and '"finding": "Preserve <all> details"' in visible
    assert "Synthetic publication warning" in visible
    assert "duration=" not in visible and "rank=" not in visible
    missing_row = next(row for row in report.split("<tr>") if "execution.missing" in row)
    assert "unavailable" in missing_row and 'class="bar"' not in missing_row
    negative_row = next(row for row in report.split("<tr>") if "execution.delta" in row)
    assert "-4" in negative_row and 'class="bar"' not in negative_row
    plain = render_evaluation_document(result)
    assert "Open backend UI" not in plain  # No implicit metadata fallback.


def test_artifacts_and_renderer_share_score_records(tmp_path):
    from .test_loop import _fixture, _loop
    from agent_evaluation.artifacts import ExperimentArtifactWriter
    from agent_evaluation.integrations.simulator import SimulatorAdapter
    skill, dataset = _fixture(tmp_path)
    result = _loop(SimulatorAdapter()).run(skill, dataset, tmp_path / "base", evolve=False)
    example = renderer_example_result()
    result = replace(result, scores=example.scores, backend_name="alternate-backend",
                     backend_metadata=example.backend["metadata"])
    root = ExperimentArtifactWriter.write(result, tmp_path / "output")
    saved = [json.loads(line) for line in (root / "scores.jsonl").read_text().splitlines()]
    assert saved == [score.to_dict() for score in result.scores]
    report = html.unescape((root / "report/index.html").read_text())
    assert "alternate-backend" in report and "https://example.test/evaluation" in report
    for score in saved:
        assert score["evaluator_id"] in report and score["explanation"] in report