Download testing/agent_evaluation/evaluators/trace.py from yuhanqin/ut-evaluation: direct link, hf CLI and curl.
- Browser
- Download file 37 kB
-
https://huggingface.co/datasets/yuhanqin/ut-evaluation/resolve/main/testing/agent_evaluation/evaluators/trace.py
- Command line
-
hf download hf://datasets/yuhanqin/ut-evaluation/testing/agent_evaluation/evaluators/trace.py
-
curl -L -o trace.py https://huggingface.co/datasets/yuhanqin/ut-evaluation/resolve/main/testing/agent_evaluation/evaluators/trace.py
37 kB
| """Trace-family evaluator rules and their static definitions.""" | |
| from __future__ import annotations | |
| from dataclasses import dataclass | |
| from typing import Any, Mapping | |
| from ..models import TestPoint, TestPointSet | |
| from ..trace_evidence import TraceEvidence | |
| from ..models import deep_thaw | |
| from .contracts import (EmptyParams, EvaluationContext, EvaluatorDefinition, | |
| EvaluatorResult, EvidenceBinding, FrozenParams, | |
| LLMJudgeDefinition, LLMJudgeRequest, ScorePolicy, | |
| evaluator_result) | |
| class DurationWithinLimitParams(FrozenParams): | |
| max_duration_seconds: float | |
| class ProcessQualityParams(FrozenParams): | |
| max_steps: int | |
| class BottleneckDiagnosisParams(FrozenParams): | |
| min_duration_seconds: float | |
| max_testpoints_per_case: int | |
| max_trace_chars: int | |
| max_span_chars: int | |
| max_skill_chars: int | |
| def _validate_keys(params: dict[str, Any], allowed: set[str]) -> None: | |
| if not isinstance(params, dict): | |
| raise ValueError("evaluator params must be an object") | |
| unknown = set(params) - allowed | |
| if unknown: | |
| raise ValueError(f"unknown evaluator params: {sorted(unknown)}") | |
| def validate_no_params(params: dict[str, Any]) -> None: | |
| _validate_keys(params, set()) | |
| def validate_duration(params: dict[str, Any]) -> None: | |
| _validate_keys(params, {"max_duration_seconds"}) | |
| value = params.get("max_duration_seconds") | |
| if not isinstance(value, (int, float)) or isinstance(value, bool) or value < 0: | |
| raise ValueError("duration_within_limit requires non-negative numeric max_duration_seconds") | |
| def validate_process_quality(params: dict[str, Any]) -> None: | |
| _validate_keys(params, {"max_steps"}) | |
| value = params.get("max_steps") | |
| if not isinstance(value, int) or isinstance(value, bool) or value < 1: | |
| raise ValueError("process_quality max_steps must be a positive integer") | |
| def validate_bottleneck_diagnosis(params: dict[str, Any]) -> None: | |
| required = { | |
| "min_duration_seconds", "max_testpoints_per_case", "max_trace_chars", | |
| "max_span_chars", "max_skill_chars", | |
| } | |
| _validate_keys(params, required) | |
| missing = required - set(params) | |
| if missing: | |
| raise ValueError(f"testpoint_bottleneck_diagnosis is missing params: {sorted(missing)}") | |
| duration = params["min_duration_seconds"] | |
| if not isinstance(duration, (int, float)) or isinstance(duration, bool) or duration < 0: | |
| raise ValueError("min_duration_seconds must be a non-negative number") | |
| for key in ("max_testpoints_per_case", "max_trace_chars", "max_span_chars", "max_skill_chars"): | |
| value = params[key] | |
| if not isinstance(value, int) or isinstance(value, bool) or value < 1: | |
| raise ValueError(f"{key} must be a positive integer") | |
| if params["max_trace_chars"] < params["max_span_chars"]: | |
| raise ValueError("max_trace_chars must be >= max_span_chars") | |
| def normalize_empty_params(params: Mapping[str, Any]) -> EmptyParams: | |
| validate_no_params(dict(params)) | |
| return EmptyParams() | |
| def normalize_duration_params(params: Mapping[str, Any]) -> DurationWithinLimitParams: | |
| raw = dict(params) | |
| validate_duration(raw) | |
| return DurationWithinLimitParams(float(raw["max_duration_seconds"])) | |
| def normalize_process_quality_params(params: Mapping[str, Any]) -> ProcessQualityParams: | |
| raw = dict(params) | |
| validate_process_quality(raw) | |
| return ProcessQualityParams(int(raw["max_steps"])) | |
| def normalize_bottleneck_params(params: Mapping[str, Any]) -> BottleneckDiagnosisParams: | |
| raw = dict(params) | |
| validate_bottleneck_diagnosis(raw) | |
| return BottleneckDiagnosisParams( | |
| float(raw["min_duration_seconds"]), int(raw["max_testpoints_per_case"]), | |
| int(raw["max_trace_chars"]), int(raw["max_span_chars"]), | |
| int(raw["max_skill_chars"]), | |
| ) | |
| _ASSESSMENT_RESPONSE_SCHEMA = { | |
| "type": "object", "required": ["label", "reason", "evidence_refs"], | |
| "additionalProperties": False, | |
| "properties": { | |
| "label": {"type": "string", "enum": ["pass", "partial", "fail"]}, | |
| "reason": {"type": "string", "minLength": 1}, | |
| "evidence_refs": {"type": "array", "minItems": 1, | |
| "items": {"type": "string"}}, | |
| }, | |
| } | |
| PROCESS_QUALITY_JUDGE = LLMJudgeDefinition( | |
| prompt_template="""Evaluate only the quality of the recorded execution process. | |
| Pass requires a coherent progression through the expected testpoints without material failed, | |
| duplicated, disordered, or wasteful steps. Partial means the process is substantially useful but | |
| contains a material gap, ambiguity, failure, or avoidable detour. Fail means the process is mostly | |
| failed, incoherent, unsupported by its explicit events, or does not meaningfully execute the task. | |
| Do not judge deliverable contents and do not infer hidden prompt or tool content. | |
| Expected testpoints: | |
| ${testpoints} | |
| Trace status: | |
| ${trace_status} | |
| Observed testpoint events: | |
| ${testpoint_events} | |
| Ordered trace steps: | |
| ${steps} | |
| Evidence references: | |
| ${evidence_refs}""", | |
| input_mapping={ | |
| "testpoints": EvidenceBinding("skill.expected_testpoints", "json"), | |
| "trace_status": EvidenceBinding("trace.status", "text"), | |
| "testpoint_events": EvidenceBinding("trace.testpoint_event_status", "json"), | |
| "steps": EvidenceBinding("trace.steps", "json"), | |
| "evidence_refs": EvidenceBinding("evidence_refs", "json"), | |
| }, | |
| response_schema=_ASSESSMENT_RESPONSE_SCHEMA, | |
| output_mapping={"label": "label", "reason": "explanation", | |
| "evidence_refs": "evidence_refs"}, | |
| score_policy=ScorePolicy( | |
| label_mapping={"pass": "pass", "partial": "partial", "fail": "fail"}, | |
| score_mapping={"pass": 1.0, "partial": 0.5, "fail": 0.0}, | |
| ), | |
| ) | |
| TESTPOINT_BOTTLENECK_JUDGE = LLMJudgeDefinition( | |
| prompt_template="""Diagnose why this selected TestPoint consumed substantial time. | |
| Identify concrete latency bottlenecks supported by the supplied trace structure and visible content. | |
| Distinguish repeated work, failed or retried tools, unnecessary serialization, excessive reasoning, | |
| large I/O, and Skill-instruction problems when the evidence supports them. Explain the impact and | |
| recommend a specific change. Do not infer redacted, missing, truncated, or policy-omitted content, | |
| and do not judge final deliverable quality. | |
| Selection: | |
| ${selection} | |
| Trace interval: | |
| ${trace} | |
| Skill context: | |
| ${skill} | |
| Evidence completeness: | |
| ${evidence_completeness} | |
| Evidence references: | |
| ${evidence_refs}""", | |
| input_mapping={ | |
| "selection": EvidenceBinding("selection", "json"), | |
| "trace": EvidenceBinding("trace", "json"), | |
| "skill": EvidenceBinding("skill", "json"), | |
| "evidence_completeness": EvidenceBinding("evidence_completeness", "text"), | |
| "evidence_refs": EvidenceBinding("evidence_refs", "json"), | |
| }, | |
| response_schema={ | |
| "type": "object", | |
| "required": ["summary", "bottlenecks", "evidence_completeness"], | |
| "additionalProperties": False, | |
| "properties": { | |
| "summary": {"type": "string", "minLength": 1}, | |
| "bottlenecks": { | |
| "type": "array", "minItems": 1, | |
| "items": { | |
| "type": "object", | |
| "required": ["category", "finding", "impact", "recommendation", | |
| "confidence", "evidence_refs"], | |
| "additionalProperties": False, | |
| "properties": { | |
| "category": {"type": "string", "minLength": 1}, | |
| "finding": {"type": "string", "minLength": 1}, | |
| "impact": {"type": "string", "minLength": 1}, | |
| "recommendation": {"type": "string", "minLength": 1}, | |
| "confidence": {"type": "string", "enum": ["low", "medium", "high"]}, | |
| "evidence_refs": {"type": "array", "minItems": 1, | |
| "items": {"type": "string"}}, | |
| }, | |
| }, | |
| }, | |
| "evidence_completeness": {"type": "string", "enum": ["complete", "partial"]}, | |
| }, | |
| }, | |
| output_mapping={"summary": "explanation", "bottlenecks": "value.bottlenecks", | |
| "evidence_completeness": "metadata.evidence_completeness"}, | |
| score_policy=ScorePolicy( | |
| label_mapping={"diagnosed": "diagnosed", "not_selected": "not_selected", | |
| "incomplete": "incomplete"}, score_mapping={} | |
| ), | |
| ) | |
| def _trace(context: EvaluationContext) -> TraceEvidence: | |
| if context.trace is None: | |
| raise ValueError("trace evaluator requires TraceEvidence") | |
| return context.trace | |
| def process_quality( | |
| context: EvaluationContext, params: ProcessQualityParams | |
| ) -> LLMJudgeRequest: | |
| evidence = _trace(context) | |
| max_steps = int(params.max_steps) | |
| all_steps = [{ | |
| "index": step.index, "span_id": step.span_id, "parent_id": step.parent_id, | |
| "name": step.name, "kind": step.kind, "status": step.status, | |
| "duration_seconds": step.duration_seconds, | |
| } for step in (evidence.steps or [])] | |
| steps = all_steps[:max_steps] | |
| return LLMJudgeRequest( | |
| evidence={ | |
| "case": {"case_id": context.case.case_id}, | |
| "skill": { | |
| "skill_id": context.skill.skill_id, | |
| "expected_testpoints": [ | |
| point.to_dict() for point in context.testpoint_set.test_points | |
| ], | |
| }, | |
| "trace": { | |
| "status": evidence.status, | |
| "duration_seconds": evidence.duration_seconds, | |
| "testpoint_event_status": evidence.testpoint_event_status or {}, | |
| "steps": steps, | |
| "step_count": len(all_steps), | |
| }, | |
| }, | |
| evidence_refs=("skill.testpoints", "trace.root", | |
| "trace.testpoint_events", "trace.steps"), | |
| projection_truncated=len(steps) < len(all_steps), | |
| ) | |
| def duration_within_limit( | |
| context: EvaluationContext, params: DurationWithinLimitParams | |
| ) -> EvaluatorResult: | |
| evidence = _trace(context) | |
| limit = float(params.max_duration_seconds) | |
| passed = evidence.duration_seconds is not None and evidence.duration_seconds <= limit | |
| return evaluator_result(score=float(passed), label="pass" if passed else "fail", | |
| explanation=f"duration={evidence.duration_seconds}; limit={limit}", | |
| evidence_refs=["trace.root.duration_seconds"], | |
| metadata={"session_id": evidence.session_id, "limit": limit}) | |
| def testpoint_reached( | |
| context: EvaluationContext, params: EmptyParams | |
| ) -> EvaluatorResult: | |
| evidence = _trace(context) | |
| point = context.testpoint | |
| if point is None: | |
| raise ValueError("testpoint evaluator requires a bound TestPoint") | |
| state = _testpoint_status(evidence, point) | |
| passed = state == "exact" | |
| return evaluator_result(score=float(passed), label="pass" if passed else "fail", | |
| explanation=f"expected={point.test_point_id}; event_status={state}", | |
| evidence_refs=["trace.events", "trace.testpoint_event_status"], | |
| metadata={"session_id": evidence.session_id, | |
| "attribution_status": state}) | |
| def trace_shape( | |
| context: EvaluationContext, params: EmptyParams | |
| ) -> EvaluatorResult: | |
| evidence = _trace(context) | |
| passed = "Turn" in evidence.span_names and any(name.startswith("LLM") for name in evidence.span_names) | |
| return evaluator_result(score=float(passed), label="pass" if passed else "fail", | |
| explanation=f"spans={evidence.span_names}", | |
| evidence_refs=["trace.span_names", "trace.root.status"], | |
| metadata={"session_id": evidence.session_id}) | |
| def _testpoint_status(evidence: TraceEvidence, point: TestPoint) -> str: | |
| """Return a diagnostic state without conflating missing and unreached.""" | |
| status = (evidence.testpoint_event_status or {}).get(point.test_point_id) | |
| if status: | |
| matching = [event for event in (evidence.events or []) | |
| if event.entity_type == "testpoint" and event.entity_id == point.test_point_id] | |
| if status == "exact" and (len(matching) != 1 or matching[0].sequence != point.ordinal): | |
| return "ambiguous" | |
| return status | |
| return "missing_explicit_event" if not evidence.events else "testpoint_not_reached" | |
| def testpoint_interval(evidence: TraceEvidence, point: TestPoint) -> tuple[float, float] | None: | |
| completions = evidence.testpoint_completion_times or {} | |
| if _testpoint_status(evidence, point) != "exact": | |
| return None | |
| end = completions.get(point.test_point_id) | |
| if end is None: | |
| return None | |
| start = (evidence.root_start_time if point.previous_test_point_id is None | |
| else completions.get(point.previous_test_point_id)) | |
| return None if start is None or end < start else (start, end) | |
| def testpoint_interval_status(evidence: TraceEvidence, point: TestPoint) -> str: | |
| """Explain why an exact event does or does not form a time interval. | |
| ``testpoint_not_reached`` is reserved for a missing completion event. An | |
| observed completion with an unusable neighboring boundary is a distinct | |
| evidence condition and must not be reported as an execution failure. | |
| """ | |
| state = _testpoint_status(evidence, point) | |
| if state != "exact": | |
| return state | |
| completions = evidence.testpoint_completion_times or {} | |
| if point.test_point_id not in completions: | |
| return "completion_timestamp_unavailable" | |
| if point.previous_test_point_id is None: | |
| if evidence.root_start_time is None: | |
| return "root_start_timestamp_unavailable" | |
| return "exact" | |
| previous_id = point.previous_test_point_id | |
| previous_state = (evidence.testpoint_event_status or {}).get(previous_id) | |
| if previous_state != "exact": | |
| return "previous_boundary_ambiguous" if previous_state else "previous_boundary_unavailable" | |
| if previous_id not in completions: | |
| return "previous_boundary_timestamp_unavailable" | |
| if completions[point.test_point_id] < completions[previous_id]: | |
| return "invalid_interval_order" | |
| return "exact" | |
| def testpoint_duration_seconds(evidence: TraceEvidence, point: TestPoint) -> float | None: | |
| interval = testpoint_interval(evidence, point) | |
| return None if interval is None else max(0.0, interval[1] - interval[0]) | |
| def select_slow_testpoints(evidence: TraceEvidence, testpoint_set: TestPointSet, | |
| params: BottleneckDiagnosisParams) -> dict[str, dict[str, Any]]: | |
| """Apply one deterministic threshold-plus-Top-K policy for a case trace.""" | |
| threshold = float(params.min_duration_seconds) | |
| maximum = int(params.max_testpoints_per_case) | |
| selections: dict[str, dict[str, Any]] = {} | |
| eligible: list[tuple[float, int, TestPoint]] = [] | |
| for point in testpoint_set.test_points: | |
| state = _testpoint_status(evidence, point) | |
| duration = testpoint_duration_seconds(evidence, point) | |
| entry = { | |
| "testpoint_id": point.test_point_id, | |
| "duration_seconds": duration, | |
| "min_duration_seconds": threshold, | |
| "max_testpoints_per_case": maximum, | |
| "rank": None, | |
| "eligible": False, | |
| "selected": False, | |
| "reason": state if state != "exact" else "below_threshold", | |
| } | |
| if state == "exact" and duration is not None and duration >= threshold: | |
| entry["eligible"] = True | |
| eligible.append((duration, point.ordinal, point)) | |
| elif state == "exact" and duration is None: | |
| entry["reason"] = "duration_unavailable" | |
| selections[point.test_point_id] = entry | |
| eligible.sort(key=lambda item: (-item[0], item[1])) | |
| for rank, (_, _, point) in enumerate(eligible, start=1): | |
| entry = selections[point.test_point_id] | |
| entry["rank"] = rank | |
| entry["selected"] = rank <= maximum | |
| entry["reason"] = "selected" if entry["selected"] else "outside_top_k" | |
| return selections | |
| def _bounded_content(text: str | None, status: str, *, per_span: int, | |
| remaining: int) -> tuple[str | None, str, int, bool]: | |
| if status != "available" or text is None: | |
| return None, status, remaining, False | |
| allowed = min(per_span, max(0, remaining)) | |
| selected = text[:allowed] | |
| truncated = len(selected) < len(text) | |
| return selected, "truncated" if truncated else "available", remaining - len(selected), truncated | |
| def project_testpoint_trace(evidence: TraceEvidence, point: TestPoint, *, | |
| max_trace_chars: int, max_span_chars: int) -> dict[str, Any]: | |
| """Project one explicit TestPoint interval without reading raw adapter artifacts.""" | |
| interval = testpoint_interval(evidence, point) | |
| if interval is None: | |
| return { | |
| "interval": None, "steps": [], "events": [], "evidence_refs": [], | |
| "projection_truncated": False, "evidence_completeness": "insufficient", | |
| "actionable_span_count": 0, | |
| } | |
| start, end = interval | |
| remaining = max_trace_chars | |
| projected_steps: list[dict[str, Any]] = [] | |
| refs: list[str] = [] | |
| truncated = False | |
| partial = False | |
| actionable = 0 | |
| for step in evidence.steps or []: | |
| if step.start_time is None or step.end_time is None: | |
| continue | |
| starts_after_previous = ( | |
| step.end_time > start if point.previous_test_point_id is not None | |
| else step.end_time >= start | |
| ) | |
| if not starts_after_previous or step.start_time > end: | |
| continue | |
| if step.start_time < start and step.end_time > end: | |
| relation = "encloses_interval" | |
| elif step.start_time < start: | |
| relation = "crosses_start" | |
| elif step.end_time > end: | |
| relation = "crosses_end" | |
| else: | |
| relation = "contained" | |
| attribution = "exact" if relation == "contained" else "shared" | |
| span_remaining = max_span_chars | |
| input_text, input_status, remaining, input_truncated = _bounded_content( | |
| step.input_text, step.input_status, per_span=span_remaining, remaining=remaining | |
| ) | |
| span_remaining -= len(input_text or "") | |
| output_text, output_status, remaining, output_truncated = _bounded_content( | |
| step.output_text, step.output_status, per_span=max(0, span_remaining), remaining=remaining | |
| ) | |
| item = { | |
| **step.to_dict(), | |
| "input_text": input_text, "input_status": input_status, | |
| "output_text": output_text, "output_status": output_status, | |
| "interval_relation": relation, "attribution_status": attribution, | |
| } | |
| projected_steps.append(item) | |
| if step.span_id: | |
| ref = f"trace.span:{step.span_id}" | |
| if ref not in refs: | |
| refs.append(ref) | |
| if step.kind in {"llm", "tool"}: | |
| actionable += 1 | |
| step_partial = attribution == "shared" or any( | |
| value in {"redacted", "missing", "truncated"} | |
| for value in (input_status, output_status) | |
| ) | |
| partial = partial or step_partial | |
| truncated = truncated or input_truncated or output_truncated | |
| projected_events: list[dict[str, Any]] = [] | |
| for event in evidence.events or []: | |
| if event.entity_type != "testpoint" or event.entity_id != point.test_point_id: | |
| continue | |
| item = { | |
| "protocol": event.protocol, "event_type": event.event_type, | |
| "entity_type": event.entity_type, "entity_id": event.entity_id, | |
| "state": event.state, "sequence": event.sequence, "payload": deep_thaw(event.payload), | |
| "source": event.source, "span_id": event.span_id, | |
| "parent_span_id": event.parent_span_id, "observed_at": event.observed_at, | |
| "attribution_status": event.attribution_status, | |
| } | |
| projected_events.append(item) | |
| if event.span_id: | |
| ref = f"trace.event:{event.span_id}:{event.entity_id}" | |
| if ref not in refs: | |
| refs.append(ref) | |
| completeness = "insufficient" if actionable == 0 else ("partial" if partial or truncated else "complete") | |
| return { | |
| "interval": {"start_time": start, "end_time": end, | |
| "duration_seconds": max(0.0, end - start)}, | |
| "steps": projected_steps, "events": projected_events, | |
| "evidence_refs": refs, "projection_truncated": truncated, | |
| "evidence_completeness": completeness, | |
| "actionable_span_count": actionable, | |
| } | |
| def _diagnostic_lifecycle(label: str, explanation: str, *, selection: dict[str, Any], | |
| completeness: str = "insufficient", | |
| evidence_refs: list[str] | None = None) -> EvaluatorResult: | |
| return evaluator_result( | |
| score=None, label=label, explanation=explanation, | |
| evidence_refs=evidence_refs or [], | |
| status=("incomplete" if label == "incomplete" else "success"), | |
| metadata={"selection": selection, "evidence_completeness": completeness}, | |
| result_kind="diagnostic", | |
| ) | |
| def testpoint_bottleneck_diagnosis( | |
| context: EvaluationContext, params: BottleneckDiagnosisParams | |
| ) -> EvaluatorResult | LLMJudgeRequest: | |
| evidence = _trace(context) | |
| point = context.testpoint | |
| if point is None: | |
| raise ValueError("testpoint evaluator requires a bound TestPoint") | |
| selection = select_slow_testpoints( | |
| evidence, context.testpoint_set, params | |
| )[point.test_point_id] | |
| if selection["reason"] not in {"selected", "below_threshold", "outside_top_k"}: | |
| return _diagnostic_lifecycle( | |
| "incomplete", f"{point.test_point_id} has no exact duration boundary: {selection['reason']}", | |
| selection=selection, | |
| ) | |
| if not selection["selected"]: | |
| return _diagnostic_lifecycle( | |
| "not_selected", f"{point.test_point_id} was not selected by the slow TestPoint policy", | |
| selection=selection, | |
| ) | |
| projection = project_testpoint_trace( | |
| evidence, point, max_trace_chars=int(params.max_trace_chars), | |
| max_span_chars=int(params.max_span_chars), | |
| ) | |
| if projection["evidence_completeness"] == "insufficient": | |
| return _diagnostic_lifecycle( | |
| "incomplete", f"{point.test_point_id} has no actionable persisted spans", | |
| selection=selection, evidence_refs=list(projection["evidence_refs"]), | |
| ) | |
| max_skill_chars = int(params.max_skill_chars) | |
| skill_content = context.skill.content[:max_skill_chars] | |
| skill_truncated = len(skill_content) < len(context.skill.content) | |
| completeness = "partial" if skill_truncated else projection["evidence_completeness"] | |
| skill_refs = [f"skill.entrypoint:{context.skill.bundle_hash}", | |
| f"skill.testpoint:{point.test_point_id}"] | |
| refs = tuple(dict.fromkeys([*projection["evidence_refs"], *skill_refs])) | |
| return LLMJudgeRequest( | |
| evidence={ | |
| "case": {"case_id": context.case.case_id}, | |
| "selection": selection, | |
| "evidence_completeness": completeness, | |
| "trace": projection, | |
| "skill": { | |
| "skill_id": context.skill.skill_id, | |
| "bundle_hash": context.skill.bundle_hash, | |
| "target_testpoint": point.to_dict(), | |
| "testpoint_outline": [ | |
| item.to_dict() for item in context.testpoint_set.test_points | |
| ], | |
| "content": skill_content, "content_truncated": skill_truncated, | |
| "original_char_count": len(context.skill.content), | |
| }, | |
| }, | |
| evidence_refs=refs, | |
| projection_truncated=bool(projection["projection_truncated"] or skill_truncated), | |
| metadata={"selection": selection, "evidence_completeness": completeness, | |
| "testpoint_id": point.test_point_id}, | |
| ) | |
| def _overlapping_spans(evidence: TraceEvidence, interval: tuple[float, float], point: TestPoint): | |
| start, end = interval | |
| anchors = evidence.testpoint_completion_llm_ids or {} | |
| current_anchor = anchors.get(point.test_point_id) | |
| previous_anchor = anchors.get(point.previous_test_point_id) if point.previous_test_point_id else None | |
| if current_anchor and previous_anchor and current_anchor == previous_anchor: | |
| # One LLM span can parent multiple sequential emitter calls. Its token | |
| # total is indivisible, so never attribute it to both adjacent points. | |
| return | |
| llm_ids = {span.span_id for span in evidence.llm_spans or []} | |
| if current_anchor not in llm_ids: | |
| current_anchor = None | |
| if previous_anchor not in llm_ids: | |
| previous_anchor = None | |
| # A completion event without an LLM parent has a valid timestamp for the | |
| # duration evaluator, but it does not establish token ownership. Do not | |
| # fall back to interval overlap: that would turn unrelated LLM spans into | |
| # an apparently exact TestPoint measurement. | |
| if current_anchor is None: | |
| return | |
| for span in evidence.llm_spans or []: | |
| if span.start_time is None or span.end_time is None: | |
| continue | |
| overlap = max(0.0, min(end, span.end_time) - max(start, span.start_time)) | |
| if overlap <= 0 and not (start == end == span.start_time == span.end_time): | |
| continue | |
| anchored = current_anchor is not None and span.span_id == current_anchor | |
| fully_inside = span.start_time >= start and span.end_time <= end | |
| if current_anchor: | |
| # The event carrier's parent LLM span is the authoritative owner | |
| # for this boundary. Keep it once for the TestPoint even though its | |
| # message/tool span may wrap child spans; keep other spans only | |
| # when wholly inside the interval to prevent double counting. | |
| if not (anchored or fully_inside): | |
| continue | |
| elif span.span_id == previous_anchor: | |
| continue | |
| # Even an explicitly anchored owner is partial when its persisted | |
| # interval crosses the TestPoint boundary. We keep the whole token count | |
| # (no proportional estimate), but expose the attribution limitation. | |
| yield span, not fully_inside | |
| def _measurement(*, metric: str, unit: str, value: Any, score: float | int | None = None, | |
| attribution_status: str, explanation: str, evidence_refs: list[str], | |
| session_id: str, testpoint_id: str) -> EvaluatorResult: | |
| available = value is not None | |
| return evaluator_result(score=score if score is not None else value, | |
| label="measurement" if value is not None else "unavailable", | |
| explanation=explanation, evidence_refs=evidence_refs, | |
| status="success" if available else "unavailable", | |
| value=value, metric=metric, unit=unit, | |
| result_kind="measurement", | |
| metadata={"attribution_status": attribution_status, "session_id": session_id}) | |
| def testpoint_total_tokens( | |
| context: EvaluationContext, params: EmptyParams | |
| ) -> EvaluatorResult: | |
| evidence = _trace(context) | |
| point = context.testpoint | |
| if point is None: | |
| raise ValueError("testpoint evaluator requires a bound TestPoint") | |
| interval = testpoint_interval(evidence, point) | |
| state = _testpoint_status(evidence, point) | |
| if state in {"missing_explicit_event", "testpoint_not_reached"}: | |
| return _measurement(metric="testpoint_total_tokens", unit="tokens", value=None, | |
| attribution_status=state, explanation=f"{point.test_point_id} completion event unavailable", | |
| evidence_refs=["trace.events"], session_id=evidence.session_id, testpoint_id=point.test_point_id) | |
| if state != "exact": | |
| return _measurement(metric="testpoint_total_tokens", unit="tokens", value=None, | |
| attribution_status=state, | |
| explanation=f"{point.test_point_id} event attribution is not exact", | |
| evidence_refs=["trace.events"], session_id=evidence.session_id, testpoint_id=point.test_point_id) | |
| if interval is None: | |
| interval_status = testpoint_interval_status(evidence, point) | |
| return _measurement(metric="testpoint_total_tokens", unit="tokens", value=None, | |
| attribution_status=interval_status, explanation=f"{point.test_point_id} interval unavailable: {interval_status}", | |
| evidence_refs=["trace.testpoint_completion_times"], session_id=evidence.session_id, testpoint_id=point.test_point_id) | |
| anchors = evidence.testpoint_completion_llm_ids or {} | |
| if point.previous_test_point_id and anchors.get(point.test_point_id) == anchors.get(point.previous_test_point_id): | |
| return _measurement(metric="testpoint_total_tokens", unit="tokens", value=None, | |
| attribution_status="ambiguous", explanation=f"{point.test_point_id} reuses the previous TestPoint LLM owner", | |
| evidence_refs=["trace.testpoint_completion_llm_ids"], session_id=evidence.session_id, testpoint_id=point.test_point_id) | |
| matches = list(_overlapping_spans(evidence, interval, point)) | |
| if not matches or any( | |
| token is None | |
| for span, _ in matches | |
| for token in (span.prompt_tokens, span.completion_tokens, span.total_tokens) | |
| ): | |
| return _measurement(metric="testpoint_total_tokens", unit="tokens", value=None, | |
| attribution_status="token_attributes_missing", explanation=f"{point.test_point_id} has no complete LLM token attributes", | |
| evidence_refs=["trace.llm_spans.token_count"], session_id=evidence.session_id, testpoint_id=point.test_point_id) | |
| value = { | |
| "prompt": sum(int(span.prompt_tokens or 0) for span, _ in matches), | |
| "completion": sum(int(span.completion_tokens or 0) for span, _ in matches), | |
| "total": sum(int(span.total_tokens) for span, _ in matches), | |
| } | |
| status = "partial" if any(clipped for _, clipped in matches) else "exact" | |
| return _measurement(metric="testpoint_total_tokens", unit="tokens", value=value, | |
| score=value["total"], | |
| attribution_status=status, explanation=f"{point.test_point_id} total tokens={value}", | |
| evidence_refs=["trace.llm_spans.token_count", "trace.testpoint_completion_times"], | |
| session_id=evidence.session_id, testpoint_id=point.test_point_id) | |
| def testpoint_duration( | |
| context: EvaluationContext, params: EmptyParams | |
| ) -> EvaluatorResult: | |
| evidence = _trace(context) | |
| point = context.testpoint | |
| if point is None: | |
| raise ValueError("testpoint evaluator requires a bound TestPoint") | |
| interval = testpoint_interval(evidence, point) | |
| state = _testpoint_status(evidence, point) | |
| if state in {"missing_explicit_event", "testpoint_not_reached"}: | |
| return _measurement(metric="testpoint_duration", unit="seconds", value=None, | |
| attribution_status=state, explanation=f"{point.test_point_id} completion event unavailable", | |
| evidence_refs=["trace.events"], session_id=evidence.session_id, testpoint_id=point.test_point_id) | |
| if state != "exact": | |
| return _measurement(metric="testpoint_duration", unit="seconds", value=None, | |
| attribution_status=state, | |
| explanation=f"{point.test_point_id} event attribution is not exact", | |
| evidence_refs=["trace.events"], session_id=evidence.session_id, testpoint_id=point.test_point_id) | |
| if interval is None: | |
| interval_status = testpoint_interval_status(evidence, point) | |
| return _measurement(metric="testpoint_duration", unit="seconds", value=None, | |
| attribution_status=interval_status, explanation=f"{point.test_point_id} interval unavailable: {interval_status}", | |
| evidence_refs=["trace.testpoint_completion_times"], session_id=evidence.session_id, testpoint_id=point.test_point_id) | |
| value = max(0.0, interval[1] - interval[0]) | |
| return _measurement(metric="testpoint_duration", unit="seconds", value=value, | |
| attribution_status="exact", explanation=f"{point.test_point_id} duration={value:.6f}s", | |
| evidence_refs=["trace.root.start_time", "trace.testpoint_completion_times"], | |
| session_id=evidence.session_id, testpoint_id=point.test_point_id) | |
| TRACE_EVALUATORS = { | |
| "duration_within_limit": EvaluatorDefinition( | |
| evaluator_id="duration_within_limit", family="trace", | |
| result_kind="assessment", expansion="once", rule=duration_within_limit, | |
| scope="generic", | |
| required_evidence=frozenset({"trace_shape"}), aggregation="mean", direction="maximize", | |
| params_type=DurationWithinLimitParams, normalize_params=normalize_duration_params, | |
| params_schema={"type": "object", "required": ["max_duration_seconds"], "additionalProperties": False, | |
| "properties": {"max_duration_seconds": {"type": "number", "minimum": 0}}}, | |
| ), | |
| "testpoint_reached": EvaluatorDefinition( | |
| evaluator_id="testpoint_reached", family="trace", | |
| result_kind="assessment", expansion="testpoint", rule=testpoint_reached, | |
| scope="skill", | |
| required_evidence=frozenset({"testpoint_state"}), aggregation="mean", direction="maximize", | |
| params_type=EmptyParams, normalize_params=normalize_empty_params, | |
| params_schema={"type": "object", "additionalProperties": False}, | |
| ), | |
| "trace_shape": EvaluatorDefinition( | |
| evaluator_id="trace_shape", family="trace", | |
| result_kind="assessment", expansion="once", rule=trace_shape, | |
| scope="generic", | |
| required_evidence=frozenset({"trace_shape"}), aggregation="mean", direction="maximize", | |
| params_type=EmptyParams, normalize_params=normalize_empty_params, | |
| params_schema={"type": "object", "additionalProperties": False}, | |
| ), | |
| "testpoint_total_tokens": EvaluatorDefinition( | |
| evaluator_id="testpoint_total_tokens", family="trace", | |
| result_kind="measurement", expansion="testpoint", rule=testpoint_total_tokens, | |
| scope="skill", | |
| metric="testpoint_total_tokens", unit="tokens", | |
| required_evidence=frozenset({"testpoint_state", "event_timestamp", "event_span_owner", "llm_token_attributes"}), | |
| aggregation="mean", direction="minimize", params_type=EmptyParams, | |
| normalize_params=normalize_empty_params, | |
| params_schema={"type": "object", "additionalProperties": False}, | |
| ), | |
| "testpoint_duration": EvaluatorDefinition( | |
| evaluator_id="testpoint_duration", family="trace", | |
| result_kind="measurement", expansion="testpoint", rule=testpoint_duration, | |
| scope="skill", | |
| metric="testpoint_duration", unit="seconds", | |
| required_evidence=frozenset({"testpoint_state", "event_timestamp"}), aggregation="mean", direction="minimize", | |
| params_type=EmptyParams, normalize_params=normalize_empty_params, | |
| params_schema={"type": "object", "additionalProperties": False}, | |
| ), | |
| "process_quality": EvaluatorDefinition( | |
| evaluator_id="process_quality", family="trace", | |
| result_kind="assessment", expansion="once", rule=process_quality, | |
| scope="skill", | |
| version="process-quality-v1", | |
| required_evidence=frozenset({"trace_shape", "testpoint_state"}), aggregation="mean", direction="maximize", | |
| params_type=ProcessQualityParams, normalize_params=normalize_process_quality_params, | |
| params_schema={"type": "object", "required": ["max_steps"], "additionalProperties": False, | |
| "properties": {"max_steps": {"type": "integer", "minimum": 1}}}, | |
| judge=PROCESS_QUALITY_JUDGE), | |
| "testpoint_bottleneck_diagnosis": EvaluatorDefinition( | |
| evaluator_id="testpoint_bottleneck_diagnosis", family="trace", | |
| result_kind="diagnostic", expansion="testpoint", rule=testpoint_bottleneck_diagnosis, | |
| scope="skill", | |
| version="testpoint-bottleneck-diagnosis-v1", | |
| required_evidence=frozenset({"testpoint_state", "event_timestamp", "trace_content"}), | |
| aggregation="none", direction="neutral", params_type=BottleneckDiagnosisParams, | |
| normalize_params=normalize_bottleneck_params, | |
| params_schema={"type": "object", "required": ["min_duration_seconds", "max_testpoints_per_case", "max_trace_chars", "max_span_chars", "max_skill_chars"], | |
| "additionalProperties": False, "properties": { | |
| "min_duration_seconds": {"type": "number", "minimum": 0}, | |
| "max_testpoints_per_case": {"type": "integer", "minimum": 1}, | |
| "max_trace_chars": {"type": "integer", "minimum": 1}, | |
| "max_span_chars": {"type": "integer", "minimum": 1}, | |
| "max_skill_chars": {"type": "integer", "minimum": 1}, | |
| }}, | |
| judge=TESTPOINT_BOTTLENECK_JUDGE), | |
| } | |