gooddata-eval 1.80.1.dev2__py3-none-any.whl → 1.80.1.dev3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. gooddata_eval/cli/agentic_runner.py +13 -0
  2. gooddata_eval/core/agentic/_failed_runs.py +53 -19
  3. gooddata_eval/core/agentic/_failure_message.py +198 -0
  4. gooddata_eval/core/agentic/_gate.py +10 -3
  5. gooddata_eval/core/agentic/_outcome.py +198 -3
  6. gooddata_eval/core/agentic/_trace_linker.py +3 -2
  7. gooddata_eval/core/agentic/alert_skill.py +30 -5
  8. gooddata_eval/core/agentic/anomaly_detection.py +40 -15
  9. gooddata_eval/core/agentic/conversation.py +9 -3
  10. gooddata_eval/core/agentic/dashboard_skill.py +31 -6
  11. gooddata_eval/core/agentic/document_skill.py +24 -4
  12. gooddata_eval/core/agentic/general_question.py +30 -7
  13. gooddata_eval/core/agentic/guardrail.py +30 -7
  14. gooddata_eval/core/agentic/kda_skill.py +38 -6
  15. gooddata_eval/core/agentic/metric_skill.py +41 -5
  16. gooddata_eval/core/agentic/visualization.py +133 -14
  17. gooddata_eval/core/agentic/what_if.py +42 -17
  18. gooddata_eval/core/chat/sse_client.py +39 -12
  19. gooddata_eval/core/evaluators/_llm_judge.py +4 -0
  20. gooddata_eval/core/evaluators/visualization.py +197 -3
  21. gooddata_eval/core/models.py +31 -5
  22. gooddata_eval/core/outcome.py +159 -0
  23. gooddata_eval/core/reporting/json_report.py +3 -0
  24. gooddata_eval/core/runner.py +10 -0
  25. {gooddata_eval-1.80.1.dev2.dist-info → gooddata_eval-1.80.1.dev3.dist-info}/METADATA +43 -2
  26. {gooddata_eval-1.80.1.dev2.dist-info → gooddata_eval-1.80.1.dev3.dist-info}/RECORD +29 -27
  27. {gooddata_eval-1.80.1.dev2.dist-info → gooddata_eval-1.80.1.dev3.dist-info}/WHEEL +0 -0
  28. {gooddata_eval-1.80.1.dev2.dist-info → gooddata_eval-1.80.1.dev3.dist-info}/entry_points.txt +0 -0
  29. {gooddata_eval-1.80.1.dev2.dist-info → gooddata_eval-1.80.1.dev3.dist-info}/licenses/LICENSE.txt +0 -0
@@ -404,6 +404,16 @@ def _apply_run_counts(item_report: ItemReport, source: Any) -> None:
404
404
  item_report.runs_ungraded = unscored
405
405
 
406
406
 
407
+ def _apply_labels(item_report: ItemReport, source: Any) -> None:
408
+ """Copy the item's harness label and shadow verdict off an outcome or a failure, if set."""
409
+ harness_error = getattr(source, "harness_error", None)
410
+ if isinstance(harness_error, dict):
411
+ item_report.harness_error = harness_error
412
+ shadow = getattr(source, "shadow", None)
413
+ if isinstance(shadow, dict):
414
+ item_report.shadow = shadow
415
+
416
+
407
417
  def _apply_failed_runs(item_report: ItemReport, source: Any) -> None:
408
418
  """Copy the per-run failure records off an outcome or a failure, if the kind built any.
409
419
 
@@ -555,6 +565,7 @@ def run_agentic_items(
555
565
  _apply_best_run_latency(item_report, outcome)
556
566
  _apply_run_counts(item_report, outcome)
557
567
  _apply_failed_runs(item_report, outcome)
568
+ _apply_labels(item_report, outcome)
558
569
  _apply_run_latencies(item_report, outcome)
559
570
  except AssertionError as exc:
560
571
  item_report.gate_passed = False if gated else None
@@ -567,6 +578,7 @@ def run_agentic_items(
567
578
  _apply_best_run_latency(item_report, exc)
568
579
  _apply_run_counts(item_report, exc)
569
580
  _apply_failed_runs(item_report, exc)
581
+ _apply_labels(item_report, exc)
570
582
  _apply_run_latencies(item_report, exc)
571
583
  # Read off the counts, not off the gate: pass^K fails items where runs did pass,
572
584
  # and reporting those as pass_at_k False would contradict the Langfuse score of
@@ -588,6 +600,7 @@ def run_agentic_items(
588
600
  _apply_timings(item_report, getattr(exc, "timings", None))
589
601
  _apply_run_counts(item_report, exc)
590
602
  _apply_failed_runs(item_report, exc)
603
+ _apply_labels(item_report, exc)
591
604
  _apply_run_latencies(item_report, exc)
592
605
  # Every run ungraded, by definition of this error -- said explicitly rather than
593
606
  # left to _apply_run_counts, whose source is detail["unscored_runs"] and which a
@@ -25,17 +25,28 @@ from __future__ import annotations
25
25
  from collections.abc import Callable, Sequence
26
26
  from typing import Any
27
27
 
28
+ from gooddata_eval.core.agentic._failure_message import cap_failed_checks
29
+ from gooddata_eval.core.agentic._outcome import RunLabels, run_exit_reason, run_outcome
28
30
  from gooddata_eval.core.models import build_tool_calls
31
+ from gooddata_eval.core.outcome import OutcomeStatus
29
32
 
30
33
 
31
34
  def build_failed_runs(
32
35
  run_results: Sequence[Any],
33
36
  *,
34
- passed: Callable[[Any], bool],
35
37
  detail: Callable[[Any], dict],
38
+ labels: RunLabels | None = None,
39
+ passed: Callable[[Any], bool] | None = None,
40
+ failed_checks: Callable[[Any], list[dict]] | None = None,
36
41
  ) -> list[dict]:
37
42
  """One record per run that did not pass, in the order the runs happened.
38
43
 
44
+ A kind that labels its runs passes its ``labels`` (from ``label_runs``, in run order):
45
+ they say which runs did not pass and are the ``outcome`` of each record, so the records,
46
+ the failure message and the Langfuse ``eval_error`` marker read one set of labels. A kind
47
+ that does not label its runs passes ``passed`` instead, and each record's ``outcome`` is
48
+ worked out here from the run alone. Exactly one of the two is given.
49
+
39
50
  ``passed`` and ``detail`` are supplied by the caller because neither is uniform across
40
51
  kinds: guardrail reads ``run.passed`` while visualization reads
41
52
  ``run.eval_result.strict_pass``, and each kind's diagnostic dict is its own. Everything
@@ -45,28 +56,51 @@ def build_failed_runs(
45
56
  ``ToolCallEvent``s, so a run that has the list must hold real events in it.
46
57
 
47
58
  A run the judge could not grade is recorded like any other non-passing run, with its
48
- ``error`` set. That matches ``core/runner.py``, which also records ungraded runs; the
49
- verdict-level accounting of ungraded runs stays with the caller's ``unscored_runs``.
59
+ ``error`` set to the run's ``judge_error``. That matches ``core/runner.py``, which also
60
+ records ungraded runs; the verdict-level accounting of ungraded runs stays with the
61
+ caller's ``unscored_runs``.
62
+
63
+ ``exit_reason`` is the run's ``LoopExit`` value, or null for a kind whose loop records
64
+ none, and ``outcome`` its ``core.outcome.Outcome`` record: ERROR when the harness failed
65
+ (its simulated user, or its judge when the judge's verdict was the one still open), FAIL
66
+ otherwise. ``error`` and ``outcome`` can differ: a run that failed a fixed check and whose
67
+ judge also broke has ``error`` set and is a FAIL. The label decides nothing; the run counts
68
+ as not passed either way.
69
+
70
+ ``failed_checks`` is written only when the caller supplies it: a missing key means the
71
+ kind does not name its failing checks, while an empty list would claim the run failed
72
+ none. Its expected/actual values are capped in size; the run's ``detail`` keeps them whole.
50
73
  """
74
+ if (labels is None) == (passed is None):
75
+ raise ValueError("build_failed_runs takes exactly one of labels and passed")
76
+ if labels is not None and len(labels.outcomes) != len(run_results):
77
+ raise ValueError(f"{len(labels.outcomes)} labels for {len(run_results)} runs")
51
78
  records: list[dict] = []
52
79
  for run_index, run in enumerate(run_results, start=1):
53
- if passed(run):
80
+ if labels is not None:
81
+ outcome = labels.outcomes[run_index - 1]
82
+ else:
83
+ outcome = run_outcome(run, passed=passed is not None and passed(run))
84
+ if outcome.status is OutcomeStatus.PASS:
54
85
  continue
55
86
  tool_calls = list(getattr(run, "tool_call_events", None) or [])
56
87
  reasoning_steps = list(getattr(run, "reasoning_steps", None) or [])
57
- records.append(
58
- {
59
- "run_index": run_index,
60
- "passed": False,
61
- "error": getattr(run, "judge_error", None),
62
- "detail": detail(run),
63
- "conversation_id": getattr(run, "conversation_id", None),
64
- "response_id": getattr(run, "response_id", None),
65
- "reasoning_step_count": len(reasoning_steps),
66
- "reasoning_steps": reasoning_steps,
67
- "tool_call_count": len(tool_calls),
68
- "tool_names": [getattr(e, "function_name", None) for e in tool_calls],
69
- "tool_calls": build_tool_calls(tool_calls),
70
- }
71
- )
88
+ record: dict[str, Any] = {
89
+ "run_index": run_index,
90
+ "passed": False,
91
+ "error": getattr(run, "judge_error", None),
92
+ "detail": detail(run),
93
+ "conversation_id": getattr(run, "conversation_id", None),
94
+ "response_id": getattr(run, "response_id", None),
95
+ "reasoning_step_count": len(reasoning_steps),
96
+ "reasoning_steps": reasoning_steps,
97
+ "tool_call_count": len(tool_calls),
98
+ "tool_names": [getattr(e, "function_name", None) for e in tool_calls],
99
+ "tool_calls": build_tool_calls(tool_calls),
100
+ "exit_reason": run_exit_reason(run),
101
+ "outcome": outcome.as_record(),
102
+ }
103
+ if failed_checks is not None:
104
+ record["failed_checks"] = cap_failed_checks(failed_checks(run))
105
+ records.append(record)
72
106
  return records
@@ -0,0 +1,198 @@
1
+ # (C) 2026 GoodData Corporation
2
+ """The head of an agentic kind's failure message: the gate result, then every failing run.
3
+
4
+ Each kind's assertion message describes its BEST run, which on a partial gate failure (some
5
+ of the K runs passed) is a passing run: every check reads True and the reason the item
6
+ failed is nowhere in the message. This module renders the part that is missing -- for each
7
+ failing run its index, why its loop stopped and the checks it failed, with expected/actual
8
+ where the kind knows them -- from the same ``failed_runs`` records the item reports, so the
9
+ message and the triage data cannot disagree about which runs failed or why.
10
+
11
+ One renderer for every kind that labels its runs, on purpose: the readers of these messages
12
+ (people and the triage tooling) look for one shape, whatever the capability under test.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ from collections.abc import Iterable, Mapping, Sequence
19
+ from dataclasses import dataclass
20
+ from enum import Enum
21
+ from typing import Any
22
+
23
+ from gooddata_eval.core.outcome import UNKNOWN_REASON, OutcomeStatus
24
+
25
+ __all__ = [
26
+ "FailedCheck",
27
+ "cap_failed_checks",
28
+ "failed_check_records",
29
+ "failed_checks_from",
30
+ "failing_runs_note",
31
+ "failure_head",
32
+ "judge_failed_checks",
33
+ ]
34
+
35
+ # A value longer than this is cut: the message is one line per run, and the whole value is in
36
+ # the run's detail anyway.
37
+ _MAX_VALUE_CHARS = 160
38
+
39
+ # The failing runs together are cut past this, at a run boundary: K runs of a kind with a dozen
40
+ # checks would otherwise put tens of thousands of characters into one assertion message. Every
41
+ # run is in ``failed_runs`` whatever the message shows.
42
+ _MAX_FAILING_RUNS_CHARS = 2000
43
+
44
+
45
+ class _Unset(Enum):
46
+ UNSET = "unset"
47
+
48
+
49
+ _UNSET = _Unset.UNSET
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class FailedCheck:
54
+ """One check a run failed, with the expected/actual pair when the kind knows it.
55
+
56
+ ``part`` narrows the check when one name covers several parts, e.g. the ``date`` part of
57
+ ``filters_correct``.
58
+ """
59
+
60
+ name: str
61
+ expected: Any = _UNSET
62
+ actual: Any = _UNSET
63
+ part: str | None = None
64
+
65
+ def as_record(self) -> dict[str, Any]:
66
+ """The JSON-ready form written into a failing run's ``failed_checks``."""
67
+ record: dict[str, Any] = {"name": self.name}
68
+ if self.part is not None:
69
+ record["part"] = self.part
70
+ if self.expected is not _UNSET:
71
+ record["expected"] = self.expected
72
+ if self.actual is not _UNSET:
73
+ record["actual"] = self.actual
74
+ return record
75
+
76
+
77
+ def failed_check_records(checks: Iterable[FailedCheck]) -> list[dict[str, Any]]:
78
+ """``checks`` as the records ``failed_runs[].failed_checks`` holds."""
79
+ return [check.as_record() for check in checks]
80
+
81
+
82
+ def failed_checks_from(checks: Mapping[str, bool], *, prerequisite: str | None = None) -> list[dict[str, Any]]:
83
+ """The records of the checks in ``checks`` that read False, by name, in their order.
84
+
85
+ ``prerequisite`` names the check every other one depends on, e.g. ``alert_created``. When it
86
+ failed, the others read False only because there was nothing to check, so it alone is named.
87
+ """
88
+ if prerequisite is not None and checks.get(prerequisite) is False:
89
+ return failed_check_records([FailedCheck(prerequisite)])
90
+ return failed_check_records(FailedCheck(name) for name, ok in checks.items() if not ok)
91
+
92
+
93
+ def judge_failed_checks(name: str, *, passed: bool, judge_error: str | None, reasoning: Any) -> list[dict[str, Any]]:
94
+ """The judge's verdict ``name`` on a run it failed, with its reasoning as the actual value.
95
+
96
+ Empty when the judge passed the run, or could not grade it: a run with no verdict failed no
97
+ judge check.
98
+ """
99
+ if judge_error is not None or passed:
100
+ return []
101
+ return failed_check_records([FailedCheck(name, part="judge", actual=reasoning)])
102
+
103
+
104
+ def _text(value: Any) -> str:
105
+ text = value if isinstance(value, str) else json.dumps(value, default=str, ensure_ascii=False, sort_keys=True)
106
+ return " ".join(text.split())
107
+
108
+
109
+ def _value(value: Any) -> str:
110
+ if value is None or value == [] or value == {} or value == "":
111
+ return "none"
112
+ text = _text(value)
113
+ return text if len(text) <= _MAX_VALUE_CHARS else text[: _MAX_VALUE_CHARS - 3] + "..."
114
+
115
+
116
+ def cap_failed_checks(records: Sequence[Mapping[str, Any]]) -> list[dict[str, Any]]:
117
+ """``records`` with every expected/actual value cut to what the message shows of it.
118
+
119
+ A check's values can be whole filter or bucket structures, repeated for every failing run
120
+ of every item; the record keeps the same ``_MAX_VALUE_CHARS`` the message does. A value
121
+ that fits stays as it is, JSON and all; a longer one becomes its cut text. The run's
122
+ ``detail`` holds the full values.
123
+ """
124
+ capped: list[dict[str, Any]] = []
125
+ for record in records:
126
+ entry = dict(record)
127
+ for key in ("expected", "actual"):
128
+ if key in entry and len(_text(entry[key])) > _MAX_VALUE_CHARS:
129
+ entry[key] = _value(entry[key])
130
+ capped.append(entry)
131
+ return capped
132
+
133
+
134
+ def _render_check(record: Mapping[str, Any]) -> str:
135
+ name = str(record.get("name", "?"))
136
+ parts: list[str] = []
137
+ if "expected" in record:
138
+ parts.append(f"expected {_value(record['expected'])}")
139
+ if "actual" in record:
140
+ parts.append(f"actual {_value(record['actual'])}")
141
+ part = record.get("part")
142
+ if not parts and part is None:
143
+ return name
144
+ inner = ", ".join(parts)
145
+ if part is not None:
146
+ inner = f"{part}: {inner}" if inner else str(part)
147
+ return f"{name}[{inner}]"
148
+
149
+
150
+ def _render_run(record: Mapping[str, Any], runs_total: int) -> str:
151
+ outcome = record.get("outcome")
152
+ head = f"run {record.get('run_index', '?')}/{runs_total}"
153
+ exit_reason = record.get("exit_reason")
154
+ errored = isinstance(outcome, Mapping) and outcome.get("status") == OutcomeStatus.ERROR.value
155
+ if errored:
156
+ # A harness error: the reason (simulated_user_failed, judge_failed) is the diagnosis.
157
+ # Its checks are still listed: the simulated user is also asked after an answer that
158
+ # was already final, and what that answer missed is the only way to tell.
159
+ head += f" ERROR ({outcome.get('reason') or UNKNOWN_REASON})"
160
+ else:
161
+ head += " FAIL" + (f" (loop exit: {exit_reason})" if exit_reason else "")
162
+ checks = record.get("failed_checks")
163
+ if checks:
164
+ return f"{head}: {', '.join(_render_check(c) for c in checks)}"
165
+ if checks is not None and not errored:
166
+ return f"{head}: no failing check recorded"
167
+ return head
168
+
169
+
170
+ def failing_runs_note(failed_runs: Sequence[Mapping[str, Any]], runs_total: int) -> str:
171
+ """Every failing run, joined with ``; ``. Empty when no run failed.
172
+
173
+ Past ``_MAX_FAILING_RUNS_CHARS`` the runs left are counted instead of rendered. The first
174
+ run is always shown, cut to that length if it alone is longer.
175
+ """
176
+ shown: list[str] = []
177
+ length = 0
178
+ for index, record in enumerate(failed_runs):
179
+ text = _render_run(record, runs_total)
180
+ if shown and length + len("; ") + len(text) > _MAX_FAILING_RUNS_CHARS:
181
+ more = len(failed_runs) - index
182
+ shown.append(f"{more} more failing run(s) in failed_runs")
183
+ break
184
+ if not shown and len(text) > _MAX_FAILING_RUNS_CHARS:
185
+ text = text[: _MAX_FAILING_RUNS_CHARS - 3] + "..."
186
+ shown.append(text)
187
+ length += len(text) + (len("; ") if len(shown) > 1 else 0)
188
+ return "; ".join(shown)
189
+
190
+
191
+ def failure_head(gate_note: str, failed_runs: Sequence[Mapping[str, Any]], runs_total: int) -> str:
192
+ """``gate_note`` followed by the failing runs, ready to start a kind's assertion message.
193
+
194
+ Returns ``gate_note`` unchanged when there is no failing run to list, which is the whole
195
+ head of a kind that builds no ``failed_runs``.
196
+ """
197
+ note = failing_runs_note(failed_runs, runs_total)
198
+ return f"{gate_note} Failing runs: {note}." if note else gate_note
@@ -29,20 +29,27 @@ def gate_label(gate: str | None, k: int) -> str:
29
29
  return f"pass^{k}" if normalize_gate(gate) == "power" else f"pass@{k}"
30
30
 
31
31
 
32
- def gate_failure_note(gate: str | None, runs_passed: int, runs_total: int, runs_ungraded: int = 0) -> str:
32
+ def gate_failure_note(
33
+ gate: str | None, runs_passed: int, runs_total: int, runs_ungraded: int = 0, *, runs_errored: int = 0
34
+ ) -> str:
33
35
  """Gate and how many runs met it, for the assertion message.
34
36
 
35
37
  Needed because the message body describes the BEST run, which under pass^K can be a run
36
38
  that passed — so the reported detail on its own looks like a pass.
37
39
 
38
40
  An ungraded run counts in runs_total but can never count in runs_passed, so the remainder
39
- is not evidence of instability — saying so would blame the agent for a judge outage.
41
+ is not evidence of instability — saying so would blame the agent for a judge outage. A run
42
+ the harness failed (``runs_errored``, labelled ERROR in ``core/outcome.py``) is no evidence
43
+ of instability either, so it is named rather than called one. A pass^K item with a passing
44
+ run and a run the agent itself failed is unstable all the same, whatever else errored.
40
45
  """
41
46
  label = gate_label(gate, runs_total)
42
47
  note = f"Gate {label} failed: {runs_passed}/{runs_total} runs passed"
43
48
  if runs_ungraded:
44
49
  return f"{note}, {runs_ungraded} ungraded."
45
- if normalize_gate(gate) == "power" and runs_passed:
50
+ if runs_errored:
51
+ note = f"{note}, {runs_errored} harness error(s)"
52
+ if normalize_gate(gate) == "power" and runs_passed and runs_passed + runs_errored < runs_total:
46
53
  return f"{note} — unstable, not a clean failure."
47
54
  return f"{note}."
48
55
 
@@ -1,5 +1,5 @@
1
1
  # (C) 2026 GoodData Corporation
2
- """The common tail of every ``evaluate_agentic_*`` function.
2
+ """The common tail of every ``evaluate_agentic_*`` function, and the run labels it carries.
3
3
 
4
4
  Before this module, each of the agentic evaluators hand-wrote the same block: copy
5
5
  ``reasoning_steps``/``conversation_id``/``response_id``/``detail``/``runs_passed``/
@@ -15,22 +15,200 @@ kind silently reported it as ``null`` until this was noticed and fixed kind-by-k
15
15
  ``timeline_detail`` builds both ``latency_breakdown`` and ``tool_calls`` from the same
16
16
  events so they stay index-aligned, but roughly half the evaluators called
17
17
  ``build_latency_breakdown`` directly and silently never got a ``tool_calls`` key.
18
+
19
+ The run labels (``core/outcome.py``) are applied here for the same reason: ``label_runs``
20
+ labels an item's runs once, and the failure message, the Langfuse marker and the fields on
21
+ the raised or returned result all read that one ``RunLabels``. ``chat_failure_exit`` names
22
+ the loop exit of a run whose chat call raised, for every kind alike.
18
23
  """
19
24
 
20
25
  from __future__ import annotations
21
26
 
27
+ from collections.abc import Callable, Sequence
28
+ from dataclasses import dataclass
29
+ from enum import Enum
22
30
  from typing import Any, NoReturn
23
31
 
32
+ from gooddata_eval.core.agentic._failure_message import failure_head
33
+ from gooddata_eval.core.agentic._gate import gate_failure_note
34
+ from gooddata_eval.core.chat.sse_client import TurnIncompleteError, TurnTimeoutError
35
+ from gooddata_eval.core.evaluators._llm_judge import JudgeResponseError
24
36
  from gooddata_eval.core.models import (
25
37
  AgenticAssertionError,
26
38
  AgenticEvalOutcome,
39
+ LoopExit,
27
40
  ReasoningStepEvent,
28
41
  ToolCallEvent,
29
42
  timeline_detail,
30
43
  )
44
+ from gooddata_eval.core.outcome import (
45
+ EVAL_ERROR_SCORE,
46
+ JUDGE_FAILED,
47
+ Outcome,
48
+ classify_run,
49
+ item_outcome,
50
+ shadow_verdict,
51
+ )
31
52
  from gooddata_eval.core.timing import PhaseTimings
32
53
 
33
- __all__ = ["agentic_detail", "agentic_success", "raise_agentic_failure"]
54
+ __all__ = [
55
+ "CHAT_FAILURE_EXITS",
56
+ "EVAL_ERROR_SCORE",
57
+ "RunLabels",
58
+ "agentic_detail",
59
+ "agentic_success",
60
+ "attach_labels",
61
+ "chat_failure_exit",
62
+ "failure_message_head",
63
+ "label_runs",
64
+ "log_eval_error_score",
65
+ "mark_unscored_run",
66
+ "raise_agentic_failure",
67
+ "run_exit_reason",
68
+ "run_outcome",
69
+ ]
70
+
71
+
72
+ CHAT_FAILURE_EXITS = frozenset({LoopExit.CHAT_ERROR, LoopExit.AGENT_TIMEOUT, LoopExit.TURN_INCOMPLETE})
73
+ """Every exit ``chat_failure_exit`` can return: the loop stopped because a chat call raised."""
74
+
75
+
76
+ def chat_failure_exit(exc: BaseException) -> LoopExit:
77
+ """The ``LoopExit`` for a run whose chat call raised ``exc``.
78
+
79
+ ``TurnTimeoutError`` and ``TurnIncompleteError`` subclass ``ChatError`` but are the
80
+ agent's own failures -- too slow, or no final answer -- so they get exits of their own
81
+ instead of reading as a chat API fault. Anything else a kind catches there (a gen-ai
82
+ error event, a broken stream, a 5xx after its retries) is ``CHAT_ERROR``. All three are
83
+ FAIL in ``core/outcome.py``: a customer hits each of them too.
84
+ """
85
+ if isinstance(exc, TurnTimeoutError):
86
+ return LoopExit.AGENT_TIMEOUT
87
+ if isinstance(exc, TurnIncompleteError):
88
+ return LoopExit.TURN_INCOMPLETE
89
+ return LoopExit.CHAT_ERROR
90
+
91
+
92
+ def run_exit_reason(run: Any) -> str | None:
93
+ """The run's ``exit_reason`` as a string, or None for a kind whose run records none."""
94
+ value = getattr(run, "exit_reason", None)
95
+ if isinstance(value, Enum):
96
+ return str(value.value)
97
+ return value if isinstance(value, str) else None
98
+
99
+
100
+ JudgeErrorOf = Callable[[Any], str | None]
101
+ """How a kind reads the judge failure that left a run without a verdict, or None.
102
+
103
+ The default reads ``run.judge_error``, right for a kind whose judge is its only check. A kind
104
+ with other checks returns the judge's error only when the judge's verdict was the one still
105
+ open, and leaves out a failure its ``judge_error`` reports from the product path."""
106
+
107
+
108
+ def _default_judge_error(run: Any) -> str | None:
109
+ value = getattr(run, "judge_error", None)
110
+ return value if isinstance(value, str) else None
111
+
112
+
113
+ def run_outcome(run: Any, *, passed: bool, judge_error: JudgeErrorOf | None = None) -> Outcome:
114
+ """One run's label: ``classify_run`` over the run's exit and its judge failure, if any."""
115
+ error = (judge_error or _default_judge_error)(run)
116
+ return classify_run(run_exit_reason(run), passed=passed, judge_error=error if isinstance(error, str) else None)
117
+
118
+
119
+ @dataclass(frozen=True)
120
+ class RunLabels:
121
+ """The label of every run of an item, in run order.
122
+
123
+ The labels decide nothing: the kind gates on its own pass_at_k/pass_power_k, and an
124
+ ERROR run counts as a run that did not pass. They only say why a run did not pass, and
125
+ whether the whole item is a harness error (``item_outcome``).
126
+ """
127
+
128
+ outcomes: tuple[Outcome, ...]
129
+
130
+ def error_label(self, run_index: int) -> Outcome | None:
131
+ """The ERROR label of run ``run_index`` (0-based), or None when that run is not one."""
132
+ outcome = self.outcomes[run_index] if 0 <= run_index < len(self.outcomes) else None
133
+ return outcome if outcome is not None and outcome.is_error else None
134
+
135
+ @property
136
+ def item_outcome(self) -> Outcome | None:
137
+ """ERROR when every run errored, else None (see ``core.outcome.item_outcome``)."""
138
+ return item_outcome(self.outcomes)
139
+
140
+ @property
141
+ def harness_error_record(self) -> dict[str, Any] | None:
142
+ """``item_outcome`` as the ``harness_error`` record a failed item carries, or None."""
143
+ outcome = self.item_outcome
144
+ return outcome.as_record() if outcome is not None else None
145
+
146
+ def shadow(self, gate: str | None) -> dict[str, Any]:
147
+ """The phase-2 candidate verdict, recorded on every item, passed or failed, and never used."""
148
+ return shadow_verdict(self.outcomes, gate)
149
+
150
+
151
+ def label_runs(
152
+ run_results: Sequence[Any], *, passed: Callable[[Any], bool], judge_error: JudgeErrorOf | None = None
153
+ ) -> RunLabels:
154
+ """The ``RunLabels`` of an item's runs; ``passed`` is the kind's own per-run verdict."""
155
+ return RunLabels(tuple(run_outcome(r, passed=passed(r), judge_error=judge_error) for r in run_results))
156
+
157
+
158
+ def attach_labels(exc: AgenticAssertionError | JudgeResponseError, labels: RunLabels, gate: str | None) -> None:
159
+ """Set ``harness_error`` (only when every run errored) and ``shadow`` on an exception a kind
160
+ raises by hand -- the counterpart of the two ``raise_agentic_failure`` arguments."""
161
+ harness_error = labels.harness_error_record
162
+ if harness_error is not None:
163
+ exc.harness_error = harness_error
164
+ exc.shadow = labels.shadow(gate)
165
+
166
+
167
+ def failure_message_head(
168
+ gate: str | None, labels: RunLabels, runs_passed: int, failed_runs: Sequence[dict], runs_ungraded: int = 0
169
+ ) -> str:
170
+ """The start of a kind's failure message: the gate result, then every failing run.
171
+
172
+ An item whose every run errored says so first. Only when every run's judge failed does it
173
+ also say no run was scored: a run whose simulated user failed was still checked, and its
174
+ failed checks follow. The gate note itself is the one the item was judged by.
175
+ """
176
+ runs_total = len(labels.outcomes)
177
+ runs_errored = sum(1 for o in labels.outcomes if o.is_error)
178
+ note = gate_failure_note(
179
+ gate, runs_passed=runs_passed, runs_total=runs_total, runs_ungraded=runs_ungraded, runs_errored=runs_errored
180
+ )
181
+ item = labels.item_outcome
182
+ if item is not None:
183
+ if all(o.reason == JUDGE_FAILED for o in labels.outcomes):
184
+ note = f"Harness error, no run was scored ({JUDGE_FAILED}). {note}"
185
+ else:
186
+ note = f"Harness error on every run ({item.reason}). {note}"
187
+ return failure_head(note, failed_runs, runs_total)
188
+
189
+
190
+ def log_eval_error_score(ctx: Any, trace_id: Any, outcome: Outcome) -> None:
191
+ """Mark one ERROR run in Langfuse: ``eval_error`` = 1, its comment the reason.
192
+
193
+ An extra score only: the run's pass, gate, check and quality scores are written beside
194
+ it, unchanged. The marker says why the run failed.
195
+ """
196
+ ctx.score(trace_id, name=EVAL_ERROR_SCORE, value=1, data_type="NUMERIC", comment=outcome.reason)
197
+
198
+
199
+ def mark_unscored_run(ctx: Any, run_idx: int, conversation_id: str, error: Outcome | None) -> None:
200
+ """Langfuse for a run that gets no verdict scores (its judge or its request failed).
201
+
202
+ A harness ERROR (``error``, from ``RunLabels.error_label``) is attached to its experiment
203
+ item with the ``eval_error`` marker, joined or not, the way every scored run is, so an
204
+ errored run is counted wherever the item's runs are. Any other unscored run goes through
205
+ ``export_unscored``, which exports the root of a joined run only.
206
+ """
207
+ if error is None:
208
+ ctx.export_unscored(run_idx, conversation_id)
209
+ return
210
+ with ctx.observe(ctx.trace(conversation_id), run_idx, conversation_id=conversation_id) as tid:
211
+ log_eval_error_score(ctx, tid, error)
34
212
 
35
213
 
36
214
  def agentic_detail(
@@ -60,6 +238,8 @@ def raise_agentic_failure(
60
238
  timings: PhaseTimings | None = None,
61
239
  failed_runs: list[dict] | None = None,
62
240
  run_latencies_s: list[float] | None = None,
241
+ harness_error: dict[str, Any] | None = None,
242
+ shadow: dict[str, Any] | None = None,
63
243
  ) -> NoReturn:
64
244
  """Build ``exception_cls(message)`` with every common field attached, and raise it.
65
245
 
@@ -68,6 +248,10 @@ def raise_agentic_failure(
68
248
  "no verdict at all" branch raises a bare ``JudgeResponseError`` instead (not a subclass)
69
249
  does not go through this helper for that branch.
70
250
 
251
+ ``harness_error`` is set only when every run errored (``RunLabels.harness_error_record``), and
252
+ ``shadow`` is the phase-2 candidate verdict (``RunLabels.shadow``); both are labels a
253
+ runner reads, neither changes the failure.
254
+
71
255
  ``timings`` stays optional: only the three kinds that track per-run ``PhaseTimings``
72
256
  (general_question, metric_skill, dashboard_skill) pass one -- the rest keep their
73
257
  own ``PhaseTimings()`` zero default, same as before this helper existed. ``failed_runs``
@@ -88,6 +272,10 @@ def raise_agentic_failure(
88
272
  exc.failed_runs = failed_runs
89
273
  if run_latencies_s is not None:
90
274
  exc.run_latencies_s = run_latencies_s
275
+ if harness_error is not None:
276
+ exc.harness_error = harness_error
277
+ if shadow is not None:
278
+ exc.shadow = shadow
91
279
  raise exc
92
280
 
93
281
 
@@ -103,8 +291,13 @@ def agentic_success(
103
291
  timings: PhaseTimings | None = None,
104
292
  failed_runs: list[dict] | None = None,
105
293
  run_latencies_s: list[float] | None = None,
294
+ shadow: dict[str, Any] | None = None,
106
295
  ) -> AgenticEvalOutcome:
107
- """The success-path mirror of ``raise_agentic_failure`` -- same fields, same shape."""
296
+ """The success-path mirror of ``raise_agentic_failure`` -- same fields, same shape.
297
+
298
+ No ``harness_error``: an item that passed had a run that passed, so it is never one.
299
+ ``shadow`` is recorded all the same (``RunLabels.shadow``).
300
+ """
108
301
  kwargs: dict[str, Any] = {
109
302
  "reasoning_steps": reasoning_steps,
110
303
  "conversation_id": conversation_id,
@@ -120,4 +313,6 @@ def agentic_success(
120
313
  kwargs["failed_runs"] = failed_runs
121
314
  if run_latencies_s is not None:
122
315
  kwargs["run_latencies_s"] = run_latencies_s
316
+ if shadow is not None:
317
+ kwargs["shadow"] = shadow
123
318
  return AgenticEvalOutcome(**kwargs)
@@ -217,9 +217,10 @@ class RunTraceContext:
217
217
  with self.observe(self.trace(conversation_id), run_idx, conversation_id=conversation_id):
218
218
  pass
219
219
 
220
- def score(self, trace_id: Any, *, name: str, value: Any, data_type: str) -> None:
220
+ def score(self, trace_id: Any, *, name: str, value: Any, data_type: str, comment: str | None = None) -> None:
221
221
  """Write one score, swallowing Langfuse failures the way ``score_safe`` always has."""
222
- self._lf.score_safe(self._client, trace_id, name=name, value=value, data_type=data_type)
222
+ extra = {"comment": comment} if comment is not None else {}
223
+ self._lf.score_safe(self._client, trace_id, name=name, value=value, data_type=data_type, **extra)
223
224
 
224
225
  def quality(self, trace_id: Any, *, strict_checks: dict, latency_sec: Any, cost_usd: Any) -> None:
225
226
  """Write the derived quality/value scores for one run."""