Skip to content

API Reference

This reference is generated from the installed public autobench package. The root package intentionally re-exports the supported API across data, specs, runtime, metrics, evaluation, tracking, records, reports, and errors.

autobench

__version__ module-attribute

__version__ = '0.2.0'

ComparisonVerdict module-attribute

ComparisonVerdict = Literal[
    "improved", "regressed", "unchanged", "inconclusive"
]

PairedBaselineFormula module-attribute

PairedBaselineFormula = Literal[
    "baseline_over_candidate",
    "candidate_over_baseline",
    "candidate_minus_baseline",
    "baseline_minus_candidate",
    "percent_change_from_baseline",
]

PostDerivationMissingPolicy module-attribute

PostDerivationMissingPolicy = Literal['skip', 'diagnostic']

RunMatchKeyKind module-attribute

RunMatchKeyKind = Literal['case_id', 'factor']

ABSTRACTION_LAYER_TAG module-attribute

ABSTRACTION_LAYER_TAG = 'abp.abstraction_layer'

EXTRACTOR_TAG module-attribute

EXTRACTOR_TAG = 'abp.extractor'

EXTRACTOR_VERSION_TAG module-attribute

EXTRACTOR_VERSION_TAG = 'abp.extractor_version'

INSTRUMENTOR_TAG module-attribute

INSTRUMENTOR_TAG = 'abp.instrumentor'

LOGICAL_OPERATION_TAG module-attribute

LOGICAL_OPERATION_TAG = 'abp.logical_operation_id'

MEASUREMENT_SCOPE_TAG module-attribute

MEASUREMENT_SCOPE_TAG = 'abp.measurement_scope'

SUMMARY_TAG module-attribute

SUMMARY_TAG = 'abp.summary'

MeasurementTimer module-attribute

MeasurementTimer: TypeAlias = Callable[
    [Callable[[], MeasuredValue]], float
]

InstrumentationConfig module-attribute

InstrumentationConfig: TypeAlias = Annotated[
    AutoInstrumentation
    | PydanticAIInstrumentation
    | OpenAIInstrumentation
    | OpenAIAgentsInstrumentation
    | HTTPXInstrumentation,
    Field(discriminator="kind"),
]

InstrumentorName module-attribute

InstrumentorName: TypeAlias = Literal[
    "pydantic_ai", "openai", "openai_agents", "httpx"
]

OPENAI_RESPONSES_SOURCE_MAP module-attribute

OPENAI_RESPONSES_SOURCE_MAP = SourceMap(
    id="openai.responses",
    version=1,
    source_system="openai.responses",
    convention_version="v1",
    instrumentor="autobench.openai",
    rules=(
        RenameRule(
            sources=(_selector("request", "model"),),
            semantic_type=LLM_MODEL_REQUESTED,
        ),
        RenameRule(
            sources=(_selector("response", "model"),),
            semantic_type=LLM_MODEL_RESPONSE,
        ),
        RenameRule(
            sources=(
                _selector(
                    "response", "usage", "input_tokens"
                ),
            ),
            semantic_type=LLM_TOKENS_INPUT,
        ),
        RenameRule(
            sources=(
                _selector(
                    "response", "usage", "output_tokens"
                ),
            ),
            semantic_type=LLM_TOKENS_OUTPUT,
        ),
        RenameRule(
            sources=(
                _selector(
                    "response",
                    "usage",
                    "input_tokens_details",
                    "cached_tokens",
                ),
            ),
            semantic_type=LLM_TOKENS_CACHED_INPUT,
        ),
        RenameRule(
            sources=(
                _selector(
                    "response",
                    "usage",
                    "output_tokens_details",
                    "reasoning_tokens",
                ),
            ),
            semantic_type=LLM_TOKENS_REASONING_OUTPUT,
        ),
    ),
)

OPENINFERENCE_SOURCE_MAP module-attribute

OPENINFERENCE_SOURCE_MAP = SourceMap(
    id="openinference",
    version=1,
    source_system="openinference",
    convention_version="1.0",
    rules=(
        RenameRule(
            sources=(_selector("llm.model_name"),),
            semantic_type=LLM_MODEL_RESPONSE,
        ),
        RenameRule(
            sources=(_selector("llm.token_count.prompt"),),
            semantic_type=LLM_TOKENS_INPUT,
        ),
        RenameRule(
            sources=(
                _selector("llm.token_count.completion"),
            ),
            semantic_type=LLM_TOKENS_OUTPUT,
        ),
        RenameRule(
            sources=(_selector("llm.token_count.total"),),
            semantic_type=LLM_TOKENS_TOTAL,
        ),
        RenameRule(
            sources=(_selector("llm.input_messages"),),
            semantic_type=MESSAGE_INPUT,
        ),
        RenameRule(
            sources=(_selector("llm.output_messages"),),
            semantic_type=MESSAGE_OUTPUT,
        ),
        RenameRule(
            sources=(_selector("tool.name"),),
            semantic_type=TOOL_NAME,
        ),
        RenameRule(
            sources=(_selector("tool.parameters"),),
            semantic_type=TOOL_CALL_ARGUMENTS,
        ),
    ),
)

OTEL_GENAI_SOURCE_MAP module-attribute

OTEL_GENAI_SOURCE_MAP = SourceMap(
    id="otel.genai",
    version=1,
    source_system="otel.genai",
    convention_version="1.43.0",
    rules=(
        RenameRule(
            sources=(_selector("gen_ai.request.model"),),
            semantic_type=LLM_MODEL_REQUESTED,
        ),
        RenameRule(
            sources=(_selector("gen_ai.response.model"),),
            semantic_type=LLM_MODEL_RESPONSE,
        ),
        RenameRule(
            sources=(
                _selector("gen_ai.provider.name"),
                _selector("gen_ai.system", deprecated=True),
            ),
            semantic_type=LLM_PROVIDER_NAME,
        ),
        RenameRule(
            sources=(
                _selector("gen_ai.request.temperature"),
            ),
            semantic_type=LLM_TEMPERATURE,
        ),
        RenameRule(
            sources=(
                _selector("gen_ai.usage.input_tokens"),
                _selector(
                    "gen_ai.usage.prompt_tokens",
                    deprecated=True,
                ),
            ),
            semantic_type=LLM_TOKENS_INPUT,
        ),
        RenameRule(
            sources=(
                _selector("gen_ai.usage.output_tokens"),
                _selector(
                    "gen_ai.usage.completion_tokens",
                    deprecated=True,
                ),
            ),
            semantic_type=LLM_TOKENS_OUTPUT,
        ),
        RenameRule(
            sources=(
                _selector(
                    "gen_ai.usage.cache_read.input_tokens"
                ),
            ),
            semantic_type=LLM_TOKENS_CACHED_INPUT,
        ),
        RenameRule(
            sources=(
                _selector(
                    "gen_ai.usage.cache_creation.input_tokens"
                ),
            ),
            semantic_type=LLM_TOKENS_CACHE_WRITE,
        ),
        RenameRule(
            sources=(
                _selector(
                    "gen_ai.usage.reasoning.output_tokens"
                ),
            ),
            semantic_type=LLM_TOKENS_REASONING_OUTPUT,
        ),
        RenameRule(
            sources=(
                _selector(
                    "gen_ai.response.time_to_first_chunk"
                ),
                _selector(
                    "gen_ai.client.operation.time_to_first_chunk"
                ),
            ),
            semantic_type=TIME_FIRST_CHUNK,
        ),
        RenameRule(
            sources=(_selector("gen_ai.agent.id"),),
            semantic_type=AGENT_ID,
        ),
        RenameRule(
            sources=(_selector("gen_ai.agent.name"),),
            semantic_type=AGENT_NAME,
        ),
        RenameRule(
            sources=(_selector("gen_ai.agent.version"),),
            semantic_type=AGENT_VERSION,
        ),
        RenameRule(
            sources=(_selector("gen_ai.workflow.name"),),
            semantic_type=WORKFLOW_NAME,
        ),
        RenameRule(
            sources=(_selector("gen_ai.tool.name"),),
            semantic_type=TOOL_NAME,
        ),
        RenameRule(
            sources=(_selector("gen_ai.tool.type"),),
            semantic_type=TOOL_TYPE,
        ),
        RenameRule(
            sources=(_selector("gen_ai.tool.definitions"),),
            semantic_type=TOOL_DEFINITIONS,
        ),
        RenameRule(
            sources=(_selector("gen_ai.tool.call.id"),),
            semantic_type=TOOL_CALL_ID,
        ),
        RenameRule(
            sources=(
                _selector("gen_ai.tool.call.arguments"),
            ),
            semantic_type=TOOL_CALL_ARGUMENTS,
        ),
        RenameRule(
            sources=(_selector("gen_ai.tool.call.result"),),
            semantic_type=TOOL_CALL_RESULT,
        ),
        RenameRule(
            sources=(_selector("gen_ai.conversation.id"),),
            semantic_type=CONVERSATION_ID,
        ),
        RenameRule(
            sources=(_selector("gen_ai.input.messages"),),
            semantic_type=MESSAGE_INPUT,
        ),
        RenameRule(
            sources=(_selector("gen_ai.output.messages"),),
            semantic_type=MESSAGE_OUTPUT,
        ),
        RenameRule(
            sources=(
                _selector("gen_ai.system_instructions"),
            ),
            semantic_type=PROMPT_SYSTEM,
        ),
        RenameRule(
            sources=(
                _selector("gen_ai.retrieval.query.text"),
            ),
            semantic_type=RETRIEVAL_QUERY,
        ),
        RenameRule(
            sources=(
                _selector("gen_ai.retrieval.documents"),
            ),
            semantic_type=RETRIEVAL_DOCUMENTS,
        ),
        RenameRule(
            sources=(_selector("gen_ai.evaluation.name"),),
            semantic_type=EVALUATION_NAME,
        ),
        RenameRule(
            sources=(
                _selector("gen_ai.evaluation.score.value"),
            ),
            semantic_type=EVALUATION_SCORE,
        ),
        RenameRule(
            sources=(
                _selector("gen_ai.evaluation.score.label"),
            ),
            semantic_type=EVALUATION_LABEL,
        ),
        RenameRule(
            sources=(
                _selector("gen_ai.evaluation.explanation"),
            ),
            semantic_type=EVALUATION_EXPLANATION,
        ),
        ClassificationRule(
            source=_selector("gen_ai.operation.name"),
            cases={
                "chat": SpanClassification(
                    operation="chat", kind=LLM
                ),
                "text_completion": SpanClassification(
                    operation="text_completion", kind=LLM
                ),
                "generate_content": SpanClassification(
                    operation="generate_content", kind=LLM
                ),
                "embeddings": SpanClassification(
                    operation="embeddings", kind=EMBEDDING
                ),
                "execute_tool": SpanClassification(
                    operation="execute_tool", kind=TOOL
                ),
                "invoke_agent": SpanClassification(
                    operation="invoke_agent", kind=AGENT
                ),
                "invoke_workflow": SpanClassification(
                    operation="invoke_workflow",
                    kind=WORKFLOW,
                ),
                "retrieval": SpanClassification(
                    operation="retrieval", kind=RETRIEVER
                ),
            },
        ),
    ),
)

MappingRule module-attribute

MappingRule: TypeAlias = Annotated[
    RenameRule
    | SplitRule
    | ClassificationRule
    | ReferenceRule
    | UnitConversionRule,
    Field(discriminator="kind"),
]

DEFAULT_METRIC_PACKS module-attribute

DEFAULT_METRIC_PACKS = builtin_metric_pack_registry()

DEFAULT_SEMANTIC_REGISTRY module-attribute

DEFAULT_SEMANTIC_REGISTRY: Final[SemanticRegistry] = (
    with_defaults()
)

RECORD_VERSION module-attribute

RECORD_VERSION = 4

TRACE_ARTIFACT_MEDIA_TYPE module-attribute

TRACE_ARTIFACT_MEDIA_TYPE = (
    "application/vnd.autobench.abp-trace+yaml"
)

TRACE_INLINE_LIMIT_BYTES module-attribute

TRACE_INLINE_LIMIT_BYTES = 128 * 1024

CSV_METRICS module-attribute

CSV_METRICS: tuple[tuple[str, str], ...] = (
    ("success", RESULT_SUCCESS),
    ("coverage", COVERAGE_RATIO),
    ("cost", MONEY_COST),
    ("input_tokens", LLM_TOKENS_INPUT),
)

DEFAULT_LEADERBOARD_METRICS module-attribute

DEFAULT_LEADERBOARD_METRICS: tuple[
    MetricAggregation, ...
] = (
    MetricAggregation(
        name="pass_rate",
        semantic_type=RESULT_SUCCESS,
        fn="ratio_true",
    ),
    MetricAggregation(
        name="avg_coverage",
        semantic_type=COVERAGE_RATIO,
        fn="mean",
    ),
    MetricAggregation(
        name="total_cost",
        semantic_type=MONEY_COST,
        fn="sum",
    ),
    MetricAggregation(
        name="avg_input_tokens",
        semantic_type=LLM_TOKENS_INPUT,
        fn="mean",
    ),
)

AggregationFn module-attribute

AggregationFn = Literal[
    "count",
    "mean",
    "sum",
    "min",
    "max",
    "median",
    "p95",
    "stddev",
    "geomean",
    "ratio_true",
]

track module-attribute

track = TrackingRegistry()

__all__ module-attribute

__all__ = (
    "AutoInstrumentation",
    "ABSTRACTION_LAYER_TAG",
    "AggregationFn",
    "ActionMatchResult",
    "ArtifactRef",
    "AssetVersion",
    "AutobenchError",
    "BenchContext",
    "Benchmark",
    "BenchmarkPlan",
    "BenchmarkReport",
    "BenchmarkInfo",
    "BenchmarkSpec",
    "BetweenRequirement",
    "CSV_METRICS",
    "Case",
    "CaseGeneratorInput",
    "CaseMatrix",
    "CaseMatrixReportSpec",
    "CaseDefaults",
    "CheckResult",
    "Component",
    "Compatibility",
    "CompatibilityStatus",
    "ComparisonVerdict",
    "ComparisonVerdictSpec",
    "ComparisonReport",
    "ComparisonReportSpec",
    "CompositeExtractor",
    "DEFAULT_LEADERBOARD_METRICS",
    "DEFAULT_METRIC_PACKS",
    "DEFAULT_SEMANTIC_REGISTRY",
    "DatasetSpec",
    "DerivedMetricOutput",
    "DistributionReportSpec",
    "Direction",
    "DurationMetricSpec",
    "EnvironmentMetadata",
    "EvaluationStatus",
    "ErrorRecord",
    "EXTRACTOR_TAG",
    "EXTRACTOR_VERSION_TAG",
    "ExactScorer",
    "ExtractionContext",
    "ExtractionEvidence",
    "ExtractionResult",
    "ExpectedAction",
    "ExpectedActionScorer",
    "ExperimentRecord",
    "ExperimentResult",
    "FactorValue",
    "FeedbackRecord",
    "FieldAsset",
    "GeneratedCaseBatch",
    "GenAIPricesSource",
    "HTTPXCaptureSettings",
    "HTTPXInstrumentation",
    "INSTRUMENTOR_TAG",
    "InstrumentCall",
    "InstrumentFactorSpec",
    "InstrumentationConflictError",
    "InstrumentationError",
    "InstrumentationHandle",
    "InstrumentationManager",
    "InstrumentationRuntime",
    "InstrumentationConfig",
    "InstrumentationSettings",
    "InstrumentMetricSpec",
    "Instrumentor",
    "InstrumentorCapabilities",
    "InstrumentorInfo",
    "InstrumentorName",
    "InstrumentorStatus",
    "LeaderboardRow",
    "LeaderboardReportSpec",
    "LOGICAL_OPERATION_TAG",
    "Measurement",
    "MeasurementBudget",
    "MeasurementRecord",
    "MeasurementTimer",
    "MEASUREMENT_SCOPE_TAG",
    "MetricAggregation",
    "MetricDistribution",
    "MetricPack",
    "MetricPackRegistry",
    "ModelPricing",
    "Observation",
    "ObservationQuery",
    "ObservationKind",
    "ObservationRole",
    "ObservationSource",
    "OpenAIAgentsInstrumentation",
    "OpenAIInstrumentation",
    "OutputMetricScorer",
    "OptimizationFeedbackInput",
    "PairedBaselineDeriverSpec",
    "PairedBaselineFormula",
    "ParamAsset",
    "ParamSchema",
    "PassFailScorer",
    "PatchDiagnostic",
    "PatchManager",
    "PydanticAIInstrumentation",
    "PolicyResult",
    "PolicySpec",
    "PostDerivationMissingPolicy",
    "PriceSource",
    "PricingTable",
    "ProgressEvent",
    "ProgressEventKind",
    "ProductionSample",
    "ProjectedObservation",
    "ProjectionKey",
    "PydanticEvalCasePayload",
    "PydanticEvalsBridge",
    "PydanticEvalsDatasetPayload",
    "PydanticEvalsUnavailableError",
    "PydanticAIUsage",
    "RECORD_VERSION",
    "TRACE_ARTIFACT_MEDIA_TYPE",
    "TRACE_INLINE_LIMIT_BYTES",
    "MatrixRunSpec",
    "PythonScorer",
    "CanonicalFact",
    "CanonicalizationResult",
    "ClassificationRule",
    "MappingRule",
    "MappingStatus",
    "OPENAI_RESPONSES_SOURCE_MAP",
    "OPENINFERENCE_SOURCE_MAP",
    "OTEL_GENAI_SOURCE_MAP",
    "ReferenceRule",
    "RenameRule",
    "RetainedSourceFact",
    "SourceData",
    "SourceMap",
    "SourceSelector",
    "SourceSnapshot",
    "SpanClassification",
    "SplitOutput",
    "SplitRule",
    "UnitConversionRule",
    "canonicalize",
    "recanonicalize",
    "resolve_nested_value",
    "resolve_source_value",
    "source_map_payload_from_yaml_view",
    "source_map_to_yaml_view",
    "source_selector_label",
    "Semantic",
    "SemanticAggregation",
    "SemanticCardinality",
    "SemanticPrivacy",
    "SemanticRegistry",
    "SemanticStability",
    "SemanticTypeInfo",
    "semantic_registry_payload_from_yaml_view",
    "semantic_registry_to_yaml_view",
    "SchemaScorer",
    "SUMMARY_TAG",
    "ScoreRecord",
    "ScoringCall",
    "SpecLoadError",
    "SpecValidationError",
    "RunContext",
    "RunRecord",
    "RunResult",
    "RunStatus",
    "RecordingError",
    "RecordLineage",
    "ReplayError",
    "ReplayKind",
    "RelativeThreshold",
    "ReportSpec",
    "RunMetricRow",
    "ReviewStatus",
    "SampleReason",
    "SamplingPolicy",
    "RunMatchKey",
    "RunMatchKeyKind",
    "Span",
    "SpanKind",
    "SpanRecord",
    "SpanExtractor",
    "SpanSelector",
    "Stage",
    "StaticPriceSource",
    "TaskResolutionError",
    "TaskResult",
    "TaskStatus",
    "TaskSpec",
    "TraceExtractor",
    "TraceEnvelope",
    "SignalExtractor",
    "TokenCostDeriver",
    "TokenCostDeriverSpec",
    "TokenCostInputs",
    "TrackedAsset",
    "TrackedPrompt",
    "LLMPricesSource",
    "ToolAsset",
    "TokenPrice",
    "TrackingRegistry",
    "TokenPriceTier",
    "TypeAsset",
    "UsageExtractor",
    "Variant",
    "VariantConfigRow",
    "__version__",
    "action_metric_score",
    "apply_policies",
    "asset_index_to_yaml_view",
    "asset_to_yaml_view",
    "attach_trace",
    "benchmark_spec_payload_from_yaml_view",
    "benchmark_spec_to_yaml_view",
    "build_benchmark_plan",
    "build_feedback_records",
    "build_optimization_feedback_input",
    "builtin_metric_pack_registry",
    "build_case_matrix",
    "build_leaderboard",
    "build_metric_distribution",
    "build_report",
    "build_run_metric_rows",
    "build_status_counts",
    "build_variant_configs",
    "capture_environment",
    "check_package_compatibility",
    "collect_benchmark_source_files",
    "compare_variants",
    "classify_metric_comparison",
    "dataset_content_hash",
    "dataset_to_yaml_view",
    "derive_observations",
    "derive_experiment_observations",
    "dump_pricing_table",
    "experiment_record_payload_from_yaml_view",
    "experiment_record_to_yaml_view",
    "experiment_summary",
    "expand_matrix",
    "expected_actions_from_case",
    "filter_observations",
    "generated_batch_from_cases",
    "generate_experiment_id",
    "get_active_run_context",
    "instrument_method",
    "instrumentor_statuses",
    "aggregate_values",
    "export_markdown_report",
    "export_runs_csv",
    "export_summary_yaml",
    "evaluate_policies",
    "evaluate_run_policies",
    "load_experiment_record",
    "load_pricing_table",
    "load_run_record",
    "load_benchmark_spec",
    "measure_callable",
    "mark_generated_case",
    "match_expected_actions",
    "merge_case_defaults",
    "metric_observation",
    "metric_value",
    "normalize_variant_factors",
    "observation_projection_key",
    "observation_priority",
    "observed_action_spans",
    "perf_counter_timer",
    "pricing_table_to_yaml_view",
    "project_observations",
    "progress_event",
    "record_experiment",
    "record_pydantic_ai_usage",
    "render_markdown_report",
    "report_to_yaml_view",
    "resolve_dotted_path",
    "resolve_python_callable",
    "run_benchmark_path",
    "run_benchmark_spec",
    "run_record_from_result",
    "run_python_task",
    "sample_to_case",
    "samples_to_cases",
    "select_spans",
    "replay_experiment",
    "replay_extraction",
    "resolve_instrumentor",
    "resolve_instrumentors",
    "replay_canonicalization",
    "source_priority",
    "stable_run_id",
    "suppress_instrumentation",
    "track",
    "trace_to_observations",
)

BenchContext

Bases: BaseModel

Source code in src/autobench/builders/components.py
41
42
43
44
45
46
47
48
class BenchContext(BaseModel):
    values: dict[str, Any] = Field(default_factory=dict)

    def set(self, key: str, value: Any) -> None:
        self.values[key] = value

    def get(self, key: str) -> Any:
        return self.values[key]

Benchmark

Source code in src/autobench/builders/components.py
 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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
class Benchmark:
    def __init__(self, benchmark_id: str) -> None:
        self._benchmark = BenchmarkInfo(id=benchmark_id)
        self._dataset = DatasetSpec()
        self._task: TaskSpec | None = None
        self._variants: list[Variant] = []
        self._scoring: list[ScoringSpec] = []
        self._derive: list[DeriverSpec] = []
        self._instrumentation: list[InstrumentationConfig] = []
        self._instrumentors: list[Instrumentor] = []

    def description(self, value: str) -> Benchmark:
        self._benchmark = self._benchmark.model_copy(update={"description": value})
        return self

    def dataset(
        self,
        cases: list[Case | dict[str, Any]] | None = None,
        *,
        source: str | Path | None = None,
        dataset_id: str | None = None,
        version: str | None = None,
        metadata: dict[str, Any] | None = None,
        case_defaults: CaseDefaults | dict[str, Any] | None = None,
    ) -> Benchmark:
        defaults = (
            case_defaults
            if isinstance(case_defaults, CaseDefaults)
            else CaseDefaults.model_validate(case_defaults or {})
        )
        self._dataset = DatasetSpec(
            id=dataset_id,
            source=str(source) if source is not None else None,
            version=version,
            metadata=metadata or {},
            cases=[
                case if isinstance(case, Case) else Case.model_validate(case)
                for case in cases or []
            ],
            case_defaults=defaults,
        )
        return self

    def variants(self, variants: list[Variant | dict[str, Any]]) -> Benchmark:
        self._variants = [_normalize_variant(variant) for variant in variants]
        return self

    def task(self, target: str | TaskSpec, *, kind: str = "python") -> Benchmark:
        self._task = target if isinstance(target, TaskSpec) else TaskSpec(kind=kind, target=target)
        return self

    def scoring(self, scoring: list[ScoringSpec]) -> Benchmark:
        self._scoring = list(scoring)
        return self

    def derive(self, derive: list[DeriverSpec]) -> Benchmark:
        self._derive = list(derive)
        return self

    def instrument(
        self,
        *instrumentation: InstrumentationConfig | Instrumentor,
    ) -> Benchmark:
        """Add serializable settings or a custom runtime instrumentor."""

        for item in instrumentation:
            if isinstance(
                item,
                (
                    AutoInstrumentation,
                    PydanticAIInstrumentation,
                    OpenAIInstrumentation,
                    OpenAIAgentsInstrumentation,
                    HTTPXInstrumentation,
                ),
            ):
                self._instrumentation.append(item)
            else:
                self._instrumentors.append(item)
        return self

    def instrument_all(
        self,
        *,
        exclude: Collection[InstrumentorName] = (),
        strict: bool = False,
    ) -> Benchmark:
        """Enable every compatible built-in instrumentor available at runtime."""

        automatic = AutoInstrumentation(exclude=tuple(exclude), strict=strict)
        self._instrumentation = [
            automatic,
            *(
                config
                for config in self._instrumentation
                if not isinstance(config, AutoInstrumentation)
            ),
        ]
        return self

    def to_spec(self) -> BenchmarkSpec:
        return BenchmarkSpec(
            benchmark=self._benchmark,
            dataset=self._dataset,
            task=self._task,
            variants=self._variants,
            scoring=self._scoring,
            derive=self._derive,
            instrumentation=self._instrumentation,
        )

    async def run_async(
        self,
        *,
        experiment_id: str | None = None,
        concurrency_limit: int | None = 1,
    ) -> ExperimentResult:
        from autobench.runtime.pipeline import run_benchmark_spec

        return await run_benchmark_spec(
            self.to_spec(),
            experiment_id=experiment_id,
            concurrency_limit=concurrency_limit,
            instrumentors=self._instrumentors,
        )

    def run(
        self,
        *,
        experiment_id: str | None = None,
        concurrency_limit: int | None = 1,
    ) -> ExperimentResult:
        return run_sync(
            self.run_async(
                experiment_id=experiment_id,
                concurrency_limit=concurrency_limit,
            )
        )

instrument

instrument(
    *instrumentation: InstrumentationConfig | Instrumentor,
) -> Benchmark

Add serializable settings or a custom runtime instrumentor.

Source code in src/autobench/builders/components.py
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
def instrument(
    self,
    *instrumentation: InstrumentationConfig | Instrumentor,
) -> Benchmark:
    """Add serializable settings or a custom runtime instrumentor."""

    for item in instrumentation:
        if isinstance(
            item,
            (
                AutoInstrumentation,
                PydanticAIInstrumentation,
                OpenAIInstrumentation,
                OpenAIAgentsInstrumentation,
                HTTPXInstrumentation,
            ),
        ):
            self._instrumentation.append(item)
        else:
            self._instrumentors.append(item)
    return self

instrument_all

instrument_all(
    *,
    exclude: Collection[InstrumentorName] = (),
    strict: bool = False,
) -> Benchmark

Enable every compatible built-in instrumentor available at runtime.

Source code in src/autobench/builders/components.py
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
def instrument_all(
    self,
    *,
    exclude: Collection[InstrumentorName] = (),
    strict: bool = False,
) -> Benchmark:
    """Enable every compatible built-in instrumentor available at runtime."""

    automatic = AutoInstrumentation(exclude=tuple(exclude), strict=strict)
    self._instrumentation = [
        automatic,
        *(
            config
            for config in self._instrumentation
            if not isinstance(config, AutoInstrumentation)
        ),
    ]
    return self

Component

Bases: Protocol

Source code in src/autobench/builders/components.py
28
29
30
class Component(Protocol):  # pragma: no cover
    id: str
    kind: str

Stage

Bases: Protocol

Source code in src/autobench/builders/components.py
33
34
35
36
37
38
class Stage(Protocol):  # pragma: no cover
    id: str
    consumes: set[str]
    produces: set[str]

    async def run(self, ctx: BenchContext) -> None: ...

Case

Bases: BaseModel

Source code in src/autobench/data/datasets.py
13
14
15
16
17
18
19
class Case(BaseModel):
    id: str = Field(min_length=1)
    input: Any = None
    expected: Any = None
    metadata: dict[str, Any] = Field(default_factory=dict)
    tags: list[str] = Field(default_factory=list)
    attachments: list[ArtifactRef] = Field(default_factory=list)

CaseDefaults

Bases: BaseModel

Source code in src/autobench/data/datasets.py
22
23
24
25
26
27
class CaseDefaults(BaseModel):
    input: Any = None
    expected: Any = None
    metadata: dict[str, Any] = Field(default_factory=dict)
    tags: list[str] = Field(default_factory=list)
    attachments: list[ArtifactRef] = Field(default_factory=list)

DatasetSpec

Bases: BaseModel

Source code in src/autobench/data/datasets.py
30
31
32
33
34
35
36
class DatasetSpec(BaseModel):
    id: str | None = None
    source: str | None = None
    version: str | None = None
    metadata: dict[str, Any] = Field(default_factory=dict)
    cases: list[Case] = Field(default_factory=list)
    case_defaults: CaseDefaults = Field(default_factory=CaseDefaults)

CaseGeneratorInput

Bases: BaseModel

Source code in src/autobench/data/generation.py
18
19
20
21
class CaseGeneratorInput(BaseModel):
    seed_cases: tuple[Case, ...] = ()
    prompt: str | None = None
    metadata: dict[str, Any] = Field(default_factory=dict)

GeneratedCaseBatch

Bases: BaseModel

Source code in src/autobench/data/generation.py
11
12
13
14
15
class GeneratedCaseBatch(BaseModel):
    generator_asset_version: str | None = None
    model_provider: str | None = None
    model_name: str | None = None
    cases: tuple[Case, ...] = ()

ProductionSample

Bases: BaseModel

Source code in src/autobench/data/ingestion.py
27
28
29
30
31
32
33
34
35
36
37
class ProductionSample(BaseModel):
    id: str
    input: Any = None
    output: Any = None
    expected: Any = None
    trace: TraceEnvelope | None = None
    metadata: dict[str, Any] = Field(default_factory=dict)
    timestamp: datetime | None = None
    privacy_tags: tuple[str, ...] = ()
    reason: SampleReason = SampleReason.RANDOM
    review_status: ReviewStatus = ReviewStatus.CANDIDATE

ReviewStatus

Bases: StrEnum

Source code in src/autobench/data/ingestion.py
21
22
23
24
class ReviewStatus(StrEnum):
    CANDIDATE = "candidate"
    ACCEPTED = "accepted"
    REJECTED = "rejected"

SampleReason

Bases: StrEnum

Source code in src/autobench/data/ingestion.py
13
14
15
16
17
18
class SampleReason(StrEnum):
    RANDOM = "random"
    FAILURE_ONLY = "failure_only"
    LOW_CONFIDENCE = "low_confidence"
    HIGH_COST = "high_cost"
    HIGH_LATENCY = "high_latency"

SamplingPolicy

Bases: BaseModel

Source code in src/autobench/data/ingestion.py
40
41
42
class SamplingPolicy(BaseModel):
    reasons: tuple[SampleReason, ...] = (SampleReason.RANDOM,)
    max_samples: int | None = None

FactorValue

Bases: BaseModel

Source code in src/autobench/data/variants.py
10
11
12
13
14
class FactorValue(BaseModel):
    name: str = Field(min_length=1)
    value: Any
    semantic_type: SemanticType | None = None
    optimize: bool = False

Variant

Bases: BaseModel

Source code in src/autobench/data/variants.py
17
18
19
20
class Variant(BaseModel):
    id: str = Field(min_length=1)
    label: str | None = None
    factors: list[FactorValue] = Field(default_factory=list)

AutobenchError

Bases: Exception

Base exception for Autobench.

Source code in src/autobench/errors.py
 9
10
class AutobenchError(Exception):
    """Base exception for Autobench."""

ErrorRecord

Bases: BaseModel

Source code in src/autobench/errors.py
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
class ErrorRecord(BaseModel):
    error_type: str
    message: str
    traceback: str | None = None
    span_id: str | None = None

    @classmethod
    def from_exception(
        cls,
        exc: BaseException,
        *,
        span_id: str | None = None,
        include_traceback: bool = True,
    ) -> ErrorRecord:
        rendered_traceback: str | None = None
        if include_traceback:
            rendered_traceback = "".join(
                traceback_module.format_exception(type(exc), exc, exc.__traceback__)
            )
        return cls(
            error_type=type(exc).__name__,
            message=str(exc),
            traceback=rendered_traceback,
            span_id=span_id,
        )

SpecLoadError

Bases: AutobenchError

Raised when a YAML spec cannot be loaded.

Source code in src/autobench/errors.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class SpecLoadError(AutobenchError):
    """Raised when a YAML spec cannot be loaded."""

    def __init__(
        self,
        message: str,
        *,
        path: Path | None = None,
        line: int | None = None,
        column: int | None = None,
    ) -> None:
        super().__init__(message)
        self.path = path
        self.line = line
        self.column = column

SpecValidationError

Bases: AutobenchError

Raised when a loaded YAML spec does not match the Autobench model.

Source code in src/autobench/errors.py
30
31
class SpecValidationError(AutobenchError):
    """Raised when a loaded YAML spec does not match the Autobench model."""

TaskResolutionError

Bases: AutobenchError

Raised when a Python task target cannot be resolved.

Source code in src/autobench/errors.py
34
35
class TaskResolutionError(AutobenchError):
    """Raised when a Python task target cannot be resolved."""

ActionMatchResult

Bases: BaseModel

Source code in src/autobench/evaluation/actions.py
23
24
25
26
27
28
29
30
31
32
class ActionMatchResult(BaseModel):
    expected: ExpectedAction
    matched_span_id: str | None = None
    target_matched: bool = False
    input_matched: bool = False
    output_matched: bool = False

    @property
    def matched(self) -> bool:
        return self.target_matched and self.input_matched

ExpectedAction

Bases: BaseModel

Source code in src/autobench/evaluation/actions.py
12
13
14
15
16
17
18
19
20
class ExpectedAction(BaseModel):
    id: str
    kind: str = "tool"
    target: str
    input: Any = None
    output: Any = None
    order: int | None = None
    required: bool = True
    tolerance: dict[str, Any] = Field(default_factory=dict)

ComparisonVerdictSpec

Bases: BaseModel

Source code in src/autobench/evaluation/comparison.py
49
50
51
class ComparisonVerdictSpec(BaseModel):
    output: DerivedMetricOutput
    threshold: RelativeThreshold = Field(default_factory=lambda: RelativeThreshold(pct=0.0))

PairedBaselineDeriverSpec

Bases: BaseModel

Source code in src/autobench/evaluation/comparison.py
54
55
56
57
58
59
60
61
62
63
64
65
66
class PairedBaselineDeriverSpec(BaseModel):
    kind: Literal["paired_baseline"] = "paired_baseline"
    baseline_variant: str = Field(min_length=1)
    match_on: tuple[RunMatchKey, ...] = Field(default_factory=lambda: (RunMatchKey(),))
    metric: SemanticType
    output: DerivedMetricOutput
    formula: PairedBaselineFormula = "baseline_over_candidate"
    threshold: RelativeThreshold | None = None
    verdict: ComparisonVerdictSpec | None = None
    include_baseline: bool = False
    missing: PostDerivationMissingPolicy = "diagnostic"
    zero_division: PostDerivationMissingPolicy = "diagnostic"
    diagnostics_name: str = "paired_baseline_unavailable"

RelativeThreshold

Bases: BaseModel

Source code in src/autobench/evaluation/comparison.py
44
45
46
class RelativeThreshold(BaseModel):
    kind: Literal["relative_noise"] = "relative_noise"
    pct: float = Field(ge=0.0)

RunMatchKey

Bases: BaseModel

Source code in src/autobench/evaluation/comparison.py
31
32
33
34
35
36
37
38
39
40
41
class RunMatchKey(BaseModel):
    kind: RunMatchKeyKind = "case_id"
    name: str = ""

    @model_validator(mode="after")
    def _validate_name(self) -> RunMatchKey:
        if self.kind == "factor" and not self.name:
            raise ValueError("factor match keys require name")
        if self.kind == "case_id" and self.name:
            raise ValueError("case_id match keys cannot declare name")
        return self

DerivedMetricOutput

Bases: BaseModel

Source code in src/autobench/evaluation/derivation.py
26
27
28
29
30
31
class DerivedMetricOutput(BaseModel):
    name: str = Field(min_length=1)
    semantic_type: SemanticType
    unit: str | None = None
    direction: Direction | None = None
    role: ObservationRole | None = None

TokenCostDeriver

Source code in src/autobench/evaluation/derivation.py
 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
172
173
174
175
176
177
class TokenCostDeriver:
    def __init__(self, spec: TokenCostDeriverSpec) -> None:
        self.spec = spec

    def derive(
        self,
        *,
        ctx: RunContext,
        observations: list[Observation],
        registry: SemanticRegistry,
    ) -> list[Observation]:
        query = ObservationQuery(observations=observations, registry=registry)
        metric_kinds = (ObservationKind.METRIC, ObservationKind.FACTOR)

        input_tokens = query.first_related(
            self.spec.inputs.input_tokens,
            kind=metric_kinds,
        )
        output_tokens = query.first_related(
            self.spec.inputs.output_tokens,
            kind=metric_kinds,
        )
        provider = query.first_related(
            self.spec.inputs.provider,
            kind=metric_kinds,
        )
        model = query.first_related(
            self.spec.inputs.model,
            kind=metric_kinds,
        )

        if input_tokens is None or output_tokens is None or provider is None or model is None:
            missing = [
                name
                for name, value in (
                    ("input_tokens", input_tokens),
                    ("output_tokens", output_tokens),
                    ("provider", provider),
                    ("model", model),
                )
                if value is None
            ]
            return [
                _diagnostic_observation(
                    ctx=ctx,
                    name="token_cost_missing_inputs",
                    message="Missing inputs required for token cost derivation.",
                    tags={"missing": missing},
                )
            ]

        pricing = load_pricing_table(Path(self.spec.pricing))
        resolved_pricing = pricing.resolve_model_pricing(
            provider=str(provider.value),
            model=str(model.value),
        )
        if resolved_pricing is None:
            return [
                _diagnostic_observation(
                    ctx=ctx,
                    name="token_cost_unknown_pricing",
                    message="No pricing entry found for model/provider.",
                    tags={
                        "provider": str(provider.value),
                        "model": str(model.value),
                    },
                )
            ]
        resolved_model_id, model_pricing = resolved_pricing
        input_rate = model_pricing.input_rate_for_tokens(float(input_tokens.value))
        output_rate = model_pricing.output_rate_for_tokens(float(output_tokens.value))
        if input_rate is None or output_rate is None:
            return [
                _diagnostic_observation(
                    ctx=ctx,
                    name="token_cost_missing_rates",
                    message="Pricing entry did not define input/output rates.",
                    tags={
                        "provider": str(provider.value),
                        "model": str(model.value),
                        "model_id": resolved_model_id,
                    },
                )
            ]

        cost = (float(input_tokens.value) / 1_000_000.0) * input_rate + (
            float(output_tokens.value) / 1_000_000.0
        ) * output_rate
        return [
            Observation(
                id=ctx._next_observation_id(),
                name=self.spec.output.name,
                kind=ObservationKind.METRIC,
                semantic_type=self.spec.output.semantic_type,
                value=cost,
                unit=self.spec.output.unit,
                direction=self.spec.output.direction,
                role=self.spec.output.role,
                source=ObservationSource.DERIVED,
                tags={
                    "provider": str(provider.value),
                    "model": str(model.value),
                    "model_id": resolved_model_id,
                    "pricing_path": self.spec.pricing,
                },
                case_id=ctx.case.id,
                variant_id=ctx.variant.id,
            )
        ]

TokenCostDeriverSpec

Bases: BaseModel

Source code in src/autobench/evaluation/derivation.py
41
42
43
44
45
46
47
48
49
50
51
52
53
class TokenCostDeriverSpec(BaseModel):
    kind: Literal["token_cost"] = "token_cost"
    output: DerivedMetricOutput = Field(
        default_factory=lambda: DerivedMetricOutput(
            name="cost",
            semantic_type=Semantic.MONEY_COST,
            unit="usd",
            direction=Direction.MINIMIZE,
            role=ObservationRole.CONSTRAINT,
        )
    )
    inputs: TokenCostInputs = Field(default_factory=TokenCostInputs)
    pricing: str = Field(min_length=1)

TokenCostInputs

Bases: BaseModel

Source code in src/autobench/evaluation/derivation.py
34
35
36
37
38
class TokenCostInputs(BaseModel):
    input_tokens: SemanticType = Semantic.LLM_TOKENS_INPUT
    output_tokens: SemanticType = Semantic.LLM_TOKENS_OUTPUT
    provider: SemanticType = Semantic.LLM_PROVIDER
    model: SemanticType = Semantic.LLM_MODEL_NAME

CompositeExtractor

Source code in src/autobench/evaluation/extraction.py
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
class CompositeExtractor:
    def __init__(self, *extractors: TraceExtractor) -> None:
        self.extractors = extractors or (
            SignalExtractor(),
            SpanExtractor(),
            UsageExtractor(),
        )
        self.name = "abp.default" if not extractors else "abp.composite"
        self.version = "+".join(
            f"{extractor.name}@{extractor.version}" for extractor in self.extractors
        )

    def extract(
        self,
        trace: Trace,
        *,
        registry: SemanticRegistry,
        context: ExtractionContext,
    ) -> ExtractionResult:
        observations: dict[str, Observation] = {}
        diagnostics: list[Diagnostic] = []
        references: dict[tuple[ReferenceKind, str, str | None], EvidenceRef] = {}
        for extractor in self.extractors:
            result = extractor.extract(trace, registry=registry, context=context)
            observations.update(
                (observation.id, observation) for observation in result.observations
            )
            diagnostics.extend(result.diagnostics)
            for reference in result.references:
                references[(reference.kind, reference.id, reference.version)] = reference
        unique_diagnostics = {
            (
                diagnostic.code,
                diagnostic.signal_id,
                diagnostic.span_id,
                diagnostic.sequence,
            ): diagnostic
            for diagnostic in diagnostics
        }
        return ExtractionResult(
            observations=tuple(observations.values()),
            diagnostics=tuple(unique_diagnostics.values()),
            references=tuple(references.values()),
        )

ExtractionContext

Bases: BaseModel

Source code in src/autobench/evaluation/extraction.py
40
41
42
43
44
45
46
47
class ExtractionContext(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    run_id: str
    benchmark_id: str
    experiment_id: str
    case_id: str
    variant_id: str

ExtractionEvidence

Bases: BaseModel

Source code in src/autobench/evaluation/extraction.py
58
59
60
61
62
63
64
65
class ExtractionEvidence(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    extractor: str
    version: str
    observation_ids: tuple[str, ...] = ()
    diagnostics: tuple[Diagnostic, ...] = ()
    references: tuple[EvidenceRef, ...] = ()

ExtractionResult

Bases: BaseModel

Source code in src/autobench/evaluation/extraction.py
50
51
52
53
54
55
class ExtractionResult(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    observations: tuple[Observation, ...] = ()
    diagnostics: tuple[Diagnostic, ...] = ()
    references: tuple[EvidenceRef, ...] = ()

SignalExtractor

Source code in src/autobench/evaluation/extraction.py
 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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
class SignalExtractor:
    name = "abp.signals"
    version = "2"

    def extract(
        self,
        trace: Trace,
        *,
        registry: SemanticRegistry,
        context: ExtractionContext,
    ) -> ExtractionResult:
        observations: list[Observation] = []
        references: dict[tuple[ReferenceKind, str, str | None], EvidenceRef] = {}
        for signal in trace.signals:
            if isinstance(signal, Measurement):
                attributes = signal.attributes
                kind_value = attributes.get("kind", ObservationKind.METRIC.value)
                kind = (
                    ObservationKind(kind_value)
                    if isinstance(kind_value, str)
                    and kind_value in {kind.value for kind in ObservationKind}
                    else ObservationKind.METRIC
                )
                source_value = attributes.get("source", ObservationSource.IMPORTED.value)
                source = (
                    ObservationSource(source_value)
                    if isinstance(source_value, str)
                    and source_value in {source.value for source in ObservationSource}
                    else ObservationSource.IMPORTED
                )
                tags_value = attributes.get("tags", {})
                tags = dict(tags_value) if isinstance(tags_value, dict) else {}
                tags.setdefault(MEASUREMENT_SCOPE_TAG, signal.measurement_scope.value)
                tags.setdefault(ABSTRACTION_LAYER_TAG, signal.layer.value)
                tags.setdefault(INSTRUMENTOR_TAG, signal.scope.instrumentor_name)
                logical_operation_id = _logical_operation_id(attributes)
                if logical_operation_id is not None:
                    tags.setdefault(LOGICAL_OPERATION_TAG, logical_operation_id)
                observations.append(
                    Observation(
                        id=_observation_id(signal.signal_id, attributes),
                        name=signal.name,
                        kind=kind,
                        semantic_type=registry.normalize(signal.semantic_type),
                        value=signal.value,
                        unit=signal.unit,
                        direction=signal.direction,
                        role=signal.role,
                        span_id=_span_id(signal.span_id, attributes),
                        source=source,
                        tags=tags,
                        case_id=context.case_id,
                        variant_id=context.variant_id,
                    )
                )
            elif isinstance(signal, Event):
                attributes = signal.attributes
                kind_value = attributes.get("kind", ObservationKind.EVENT.value)
                kind = (
                    ObservationKind(kind_value)
                    if isinstance(kind_value, str)
                    and kind_value in {kind.value for kind in ObservationKind}
                    else ObservationKind.EVENT
                )
                source_value = attributes.get("source", ObservationSource.IMPORTED.value)
                source = (
                    ObservationSource(source_value)
                    if isinstance(source_value, str)
                    and source_value in {source.value for source in ObservationSource}
                    else ObservationSource.IMPORTED
                )
                tags_value = attributes.get("tags", {})
                tags = dict(tags_value) if isinstance(tags_value, dict) else {}
                tags.setdefault(ABSTRACTION_LAYER_TAG, signal.scope.layer.value)
                tags.setdefault(INSTRUMENTOR_TAG, signal.scope.instrumentor_name)
                role = (
                    ObservationRole.DIAGNOSTIC
                    if registry.normalize(signal.semantic_type) == Semantic.DIAGNOSTIC_EVENT
                    else None
                )
                value = (
                    signal.reference.model_dump(mode="json")
                    if signal.reference is not None
                    else signal.body
                )
                observations.append(
                    Observation(
                        id=_observation_id(signal.signal_id, attributes),
                        name=signal.name,
                        kind=kind,
                        semantic_type=registry.normalize(signal.semantic_type),
                        value=value,
                        role=role,
                        span_id=_span_id(signal.span_id, attributes),
                        source=source,
                        tags=tags,
                        case_id=context.case_id,
                        variant_id=context.variant_id,
                    )
                )
                if signal.reference is not None:
                    reference = signal.reference
                    references[(reference.kind, reference.id, reference.version)] = reference

        for reference_signal in trace.references:
            reference = reference_signal.reference
            references[(reference.kind, reference.id, reference.version)] = reference
        for span in trace.spans:
            for reference_signal in span.references:
                reference = reference_signal.reference
                references[(reference.kind, reference.id, reference.version)] = reference
            for reference in span.errors:
                references[(reference.kind, reference.id, reference.version)] = reference

        return ExtractionResult(
            observations=tuple(observations),
            diagnostics=trace.diagnostics,
            references=tuple(references.values()),
        )

SpanExtractor

Derive generic operation, topology, timing, and workflow evidence.

Source code in src/autobench/evaluation/extraction.py
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
class SpanExtractor:
    """Derive generic operation, topology, timing, and workflow evidence."""

    name = "abp.spans"
    version = "1"

    def extract(
        self,
        trace: Trace,
        *,
        registry: SemanticRegistry,
        context: ExtractionContext,
    ) -> ExtractionResult:
        del registry
        observations: list[Observation] = []
        diagnostics: list[Diagnostic] = []
        spans = trace.spans
        children: dict[str, list[SpanRecord]] = defaultdict(list)
        spans_by_id = {span.span_id: span for span in spans}
        for span in spans:
            if span.parent_span_id in spans_by_id:
                children[span.parent_span_id].append(span)

        observations.extend(self._operation_evidence(trace, context, children))
        observations.extend(self._workflow_evidence(trace, context))
        observations.extend(self._reference_evidence(trace, context))
        incomplete = tuple(span for span in spans if _is_incomplete(span))
        if incomplete:
            diagnostics.append(
                Diagnostic(
                    code="incomplete_trace_work",
                    message=f"trace contains {len(incomplete)} incomplete operation(s)",
                    details={"span_ids": [span.span_id for span in incomplete]},
                )
            )
        return ExtractionResult(
            observations=tuple(observations),
            diagnostics=(*trace.diagnostics, *diagnostics),
            references=_trace_references(trace),
        )

    def _operation_evidence(
        self,
        trace: Trace,
        context: ExtractionContext,
        children: Mapping[str, list[SpanRecord]],
    ) -> list[Observation]:
        spans = trace.spans
        accounted_spans = _accounted_spans(spans)
        kind_counts = Counter(span.kind for span in accounted_spans)
        operation_counts = Counter(span.operation for span in accounted_spans)
        incomplete_count = sum(_is_incomplete(span) for span in spans)
        max_depth = _max_depth(spans, trace.links)
        fan_out = max(
            (_fan_out(span, children.get(span.span_id, [])) for span in spans),
            default=0,
        )
        intervals = tuple(
            (span.start_monotonic_ns, span.end_monotonic_ns)
            for span in spans
            if span.start_monotonic_ns is not None
            and span.end_monotonic_ns is not None
            and span.end_monotonic_ns >= span.start_monotonic_ns
        )
        critical_path_ns = (
            0
            if not intervals
            else max(end for _, end in intervals) - min(start for start, _ in intervals)
        )
        leaves = tuple(span for span in spans if not children.get(span.span_id))
        leaf_work_ns = sum(span.duration_ns for span in leaves if span.duration_ns is not None)
        observations = [
            self._metric(
                context,
                "operation.count",
                Semantic.OPERATION_COUNT,
                len(accounted_spans),
                summary=True,
            ),
            self._metric(
                context,
                "operation.depth.max",
                Semantic.OPERATION_DEPTH_MAX,
                max_depth,
                summary=True,
            ),
            self._metric(
                context,
                "operation.fan_out.max",
                Semantic.OPERATION_FAN_OUT_MAX,
                fan_out,
                summary=True,
            ),
            self._metric(
                context,
                "operation.incomplete.count",
                Semantic.OPERATION_INCOMPLETE_COUNT,
                incomplete_count,
                summary=True,
            ),
        ]
        if critical_path_ns:
            observations.extend(
                (
                    self._metric(
                        context,
                        "time.critical_path",
                        Semantic.TIME_CRITICAL_PATH,
                        critical_path_ns / 1_000_000_000,
                        unit="s",
                        summary=True,
                    ),
                    self._metric(
                        context,
                        "operation.parallelism",
                        Semantic.OPERATION_PARALLELISM,
                        leaf_work_ns / critical_path_ns,
                        unit="ratio",
                        summary=True,
                    ),
                )
            )
        for kind, count in sorted(kind_counts.items()):
            observations.append(
                self._metric(
                    context,
                    f"operation.kind.{kind}.count",
                    Semantic.OPERATION_COUNT,
                    count,
                    tags={"operation.kind": kind},
                )
            )
        for operation, count in sorted(operation_counts.items()):
            observations.append(
                self._metric(
                    context,
                    f"operation.{operation}.count",
                    Semantic.OPERATION_COUNT,
                    count,
                    tags={"operation.name": operation},
                )
            )
        for span in spans:
            if span.duration_seconds is None:
                continue
            observations.append(
                self._metric(
                    context,
                    "span.duration",
                    Semantic.TIME_LATENCY,
                    span.duration_seconds,
                    unit="s",
                    span=span,
                    tags={MEASUREMENT_SCOPE_TAG: MeasurementScope.DIRECT.value},
                )
            )
        return observations

    def _workflow_evidence(
        self,
        trace: Trace,
        context: ExtractionContext,
    ) -> list[Observation]:
        spans = trace.spans
        retry_pairs = {
            (link.span_id, link.target.span_id)
            for link in trace.links
            if link.relation is LinkRelation.RETRY_OF
            and link.target.trace_id == trace.trace_id
            and link.target.span_id is not None
        }
        retry_targets = {target for _, target in retry_pairs}
        by_id = {span.span_id: span for span in spans}
        first_attempts = tuple(by_id[target] for target in retry_targets if target in by_id)
        retry_events = {
            event.signal_id
            for span in spans
            for event in span.events
            if event.semantic_type in {Semantic.OPERATION_RETRY, Semantic.OPERATION_REPAIR}
            or event.name in {"retry", "repair"}
        }
        validations = tuple(span for span in spans if span.kind == KnownSpanKind.VALIDATION)
        validation_event_ids = {
            event.signal_id
            for span in spans
            for event in span.events
            if span.kind != KnownSpanKind.VALIDATION
            if event.semantic_type == Semantic.VALIDATION_FAILURE
            or event.name == "validation_failure"
        }
        validation_ids = {span.span_id for span in validations} | validation_event_ids
        validation_failure_ids = {
            span.span_id for span in validations if _is_failed(span)
        } | validation_event_ids
        approval_spans = tuple(span for span in spans if span.kind == KnownSpanKind.APPROVAL)
        approval_ids = {span.span_id for span in approval_spans} | {
            event.signal_id
            for span in spans
            for event in span.events
            if span.kind != KnownSpanKind.APPROVAL
            if event.semantic_type == Semantic.APPROVAL_REQUESTED
            or event.name == "approval_requested"
        }
        tools = tuple(span for span in spans if span.kind == KnownSpanKind.TOOL)
        validation_failures = len(validation_failure_ids)
        tool_failures = sum(_is_failed(span) for span in tools)
        tool_successes = sum(_is_successful(span) for span in tools)
        tool_arguments = sum(_has_tool_arguments(span) for span in tools)
        recovered_retries = sum(
            _is_failed(by_id[target]) and _is_successful(by_id[retry])
            for retry, target in retry_pairs
            if retry in by_id and target in by_id
        )
        approval_wait_ns = sum(
            span.duration_ns for span in approval_spans if span.duration_ns is not None
        )
        observations = [
            self._metric(
                context,
                "operation.retry.count",
                Semantic.OPERATION_RETRY_COUNT,
                len(retry_pairs) if retry_pairs else len(retry_events),
                summary=True,
            ),
            self._metric(
                context,
                "operation.retry.recovered.count",
                Semantic.OPERATION_RETRY_RECOVERED_COUNT,
                recovered_retries,
                summary=True,
            ),
            self._metric(
                context,
                "validation.count",
                Semantic.VALIDATION_COUNT,
                len(validation_ids),
                summary=True,
            ),
            self._metric(
                context,
                "validation.failure.count",
                Semantic.VALIDATION_FAILURE_COUNT,
                validation_failures,
                summary=True,
            ),
            self._metric(
                context,
                "approval.count",
                Semantic.APPROVAL_COUNT,
                len(approval_ids),
                summary=True,
            ),
            self._metric(
                context,
                "approval.wait",
                Semantic.APPROVAL_WAIT,
                approval_wait_ns / 1_000_000_000,
                unit="s",
                summary=True,
            ),
            self._metric(
                context,
                "tool.call.count",
                Semantic.TOOL_CALL_COUNT,
                len(tools),
                summary=True,
            ),
            self._metric(
                context,
                "tool.call.success.count",
                Semantic.TOOL_CALL_SUCCESS_COUNT,
                tool_successes,
                summary=True,
            ),
            self._metric(
                context,
                "tool.call.failure.count",
                Semantic.TOOL_CALL_FAILURE_COUNT,
                tool_failures,
                summary=True,
            ),
            self._metric(
                context,
                "tool.call.arguments.present.count",
                Semantic.TOOL_CALL_ARGUMENTS_PRESENT_COUNT,
                tool_arguments,
                summary=True,
            ),
        ]
        if first_attempts:
            observations.append(
                self._metric(
                    context,
                    "operation.first_attempt.success",
                    Semantic.OPERATION_FIRST_ATTEMPT_SUCCESS,
                    sum(_is_successful(span) for span in first_attempts) / len(first_attempts),
                    unit="ratio",
                    summary=True,
                )
            )
        if validation_ids:
            observations.append(
                self._metric(
                    context,
                    "validation.failure.rate",
                    Semantic.VALIDATION_FAILURE_RATE,
                    validation_failures / len(validation_ids),
                    unit="ratio",
                    summary=True,
                )
            )
        input_messages = _message_count(spans, Semantic.MESSAGE_INPUT)
        output_messages = _message_count(spans, Semantic.MESSAGE_OUTPUT)
        if input_messages is not None:
            observations.append(
                self._metric(
                    context,
                    "message.input.count",
                    Semantic.MESSAGE_INPUT_COUNT,
                    input_messages,
                    summary=True,
                )
            )
        if output_messages is not None:
            observations.append(
                self._metric(
                    context,
                    "message.output.count",
                    Semantic.MESSAGE_OUTPUT_COUNT,
                    output_messages,
                    summary=True,
                )
            )
        if input_messages is not None and output_messages is not None:
            observations.append(
                self._metric(
                    context,
                    "message.growth",
                    Semantic.MESSAGE_GROWTH,
                    output_messages - input_messages,
                    summary=True,
                )
            )
        return observations

    def _reference_evidence(
        self,
        trace: Trace,
        context: ExtractionContext,
    ) -> list[Observation]:
        references = _trace_references(trace)
        artifact_count = sum(reference.kind is ReferenceKind.ARTIFACT for reference in references)
        asset_count = sum(
            reference.kind
            in {
                ReferenceKind.ASSET,
                ReferenceKind.PROMPT,
                ReferenceKind.TOOL,
                ReferenceKind.OUTPUT_SCHEMA,
            }
            for reference in references
        )
        return [
            self._metric(
                context,
                "artifact.reference.count",
                Semantic.ARTIFACT_REFERENCE_COUNT,
                artifact_count,
                summary=True,
            ),
            self._metric(
                context,
                "asset.reference.count",
                Semantic.ASSET_REFERENCE_COUNT,
                asset_count,
                summary=True,
            ),
        ]

    def _metric(
        self,
        context: ExtractionContext,
        name: str,
        semantic_type: str,
        value: bool | int | float,
        *,
        unit: str | None = None,
        span: SpanRecord | None = None,
        summary: bool = False,
        tags: dict[str, SerializedValue] | None = None,
    ) -> Observation:
        evidence_tags: dict[str, SerializedValue] = {
            EXTRACTOR_TAG: self.name,
            EXTRACTOR_VERSION_TAG: self.version,
        }
        if summary:
            evidence_tags[SUMMARY_TAG] = True
            evidence_tags[MEASUREMENT_SCOPE_TAG] = MeasurementScope.AGGREGATE.value
        if span is not None:
            evidence_tags.update(
                {
                    ABSTRACTION_LAYER_TAG: span.scope.layer.value,
                    INSTRUMENTOR_TAG: span.scope.instrumentor_name,
                    "operation.kind": span.kind,
                    "operation.name": span.operation,
                }
            )
            logical_operation_id = _logical_operation_id(span.attributes)
            if logical_operation_id is not None:
                evidence_tags[LOGICAL_OPERATION_TAG] = logical_operation_id
        if tags is not None:
            evidence_tags.update(tags)
        suffix = "summary" if span is None else span.span_id
        return Observation(
            id=f"abp_span_v{self.version}_{suffix}_{name}",
            name=name,
            kind=ObservationKind.METRIC,
            semantic_type=semantic_type,
            value=value,
            unit=unit,
            role=ObservationRole.DIAGNOSTIC,
            span_id=None if span is None else span.span_id,
            source=ObservationSource.DERIVED,
            tags=evidence_tags,
            case_id=context.case_id,
            variant_id=context.variant_id,
        )

TraceExtractor

Bases: Protocol

Source code in src/autobench/evaluation/extraction.py
68
69
70
71
72
73
74
75
76
77
78
class TraceExtractor(Protocol):
    name: str
    version: str

    def extract(
        self,
        trace: Trace,
        *,
        registry: SemanticRegistry,
        context: ExtractionContext,
    ) -> ExtractionResult: ...

UsageExtractor

Derive accounting-safe LLM usage and model evidence.

Source code in src/autobench/evaluation/extraction.py
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
class UsageExtractor:
    """Derive accounting-safe LLM usage and model evidence."""

    name = "abp.llm_usage"
    version = "1"

    def extract(
        self,
        trace: Trace,
        *,
        registry: SemanticRegistry,
        context: ExtractionContext,
    ) -> ExtractionResult:
        llm_spans = tuple(span for span in trace.spans if span.kind == KnownSpanKind.LLM)
        direct, aggregate = self._usage_evidence(llm_spans, registry)
        observations: list[Observation] = []
        diagnostics: list[Diagnostic] = []
        for semantic_type in _USAGE_KEYS:
            candidates = tuple(item for item in direct if item.semantic_type == semantic_type)
            if not candidates:
                continue
            selected_layer = min(
                (candidate.span.scope.layer for candidate in candidates),
                key=_layer_priority,
            )
            selected = tuple(
                candidate
                for candidate in candidates
                if candidate.span.scope.layer is selected_layer
            )
            grouped: dict[str, list[_UsageEvidence]] = defaultdict(list)
            for candidate in selected:
                grouped[candidate.logical_operation_id].append(candidate)
            resolved: list[_UsageEvidence] = []
            for logical_operation_id, equivalents in grouped.items():
                candidate, diagnostic = _resolve_usage_equivalents(
                    semantic_type,
                    logical_operation_id,
                    equivalents,
                )
                if diagnostic is not None:
                    diagnostics.append(diagnostic)
                if candidate is not None:
                    resolved.append(candidate)
            if not resolved:
                continue
            total = sum(candidate.value for candidate in resolved)
            observations.append(
                self._metric(
                    context,
                    f"{semantic_type}.total",
                    semantic_type,
                    total,
                    unit=resolved[0].unit,
                    layer=selected_layer,
                    summary=True,
                    tags={
                        "abp.logical_operation_count": len(resolved),
                        "abp.source_span_ids": [candidate.span.span_id for candidate in resolved],
                    },
                )
            )
            for candidate in resolved:
                observations.append(
                    self._metric(
                        context,
                        f"{semantic_type}.direct",
                        semantic_type,
                        candidate.value,
                        unit=candidate.unit,
                        layer=selected_layer,
                        span=candidate.span,
                        tags={
                            MEASUREMENT_SCOPE_TAG: MeasurementScope.DIRECT.value,
                            LOGICAL_OPERATION_TAG: candidate.logical_operation_id,
                            "abp.usage_source": candidate.source_name,
                        },
                    )
                )
            diagnostics.extend(
                _aggregate_diagnostics(semantic_type, total, aggregate, selected_layer)
            )
        observations.extend(self._model_evidence(llm_spans, registry, context))
        return ExtractionResult(
            observations=tuple(observations),
            diagnostics=(*trace.diagnostics, *diagnostics),
            references=_trace_references(trace),
        )

    def _usage_evidence(
        self,
        spans: tuple[SpanRecord, ...],
        registry: SemanticRegistry,
    ) -> tuple[list[_UsageEvidence], list[_UsageEvidence]]:
        direct: list[_UsageEvidence] = []
        aggregate: list[_UsageEvidence] = []
        for span in spans:
            logical_operation_id = _span_logical_operation_id(span)
            span_semantics: set[str] = set()
            for measurement in span.measurements:
                semantic_type = registry.normalize(measurement.semantic_type)
                if semantic_type not in _USAGE_KEYS:
                    continue
                span_semantics.add(semantic_type)
                evidence = _UsageEvidence(
                    semantic_type=semantic_type,
                    value=measurement.value,
                    unit=measurement.unit or _USAGE_UNITS[semantic_type],
                    span=span,
                    logical_operation_id=logical_operation_id,
                    authority=_authority(
                        measurement.attributes,
                        measurement.source.system if measurement.source else None,
                    ),
                    source_name="measurement",
                )
                (
                    direct
                    if measurement.measurement_scope is MeasurementScope.DIRECT
                    else aggregate
                ).append(evidence)
            for semantic_type, keys in _USAGE_KEYS.items():
                values = [span.usage[key] for key in keys if key in span.usage]
                for value in values:
                    if isinstance(value, bool) or not isinstance(value, int | float):
                        continue
                    span_semantics.add(semantic_type)
                    direct.append(
                        _UsageEvidence(
                            semantic_type=semantic_type,
                            value=value,
                            unit=_USAGE_UNITS[semantic_type],
                            span=span,
                            logical_operation_id=logical_operation_id,
                            authority=_authority(span.attributes, None),
                            source_name="span.usage",
                        )
                    )
            if Semantic.LLM_REQUEST_COUNT not in span_semantics:
                direct.append(
                    _UsageEvidence(
                        semantic_type=Semantic.LLM_REQUEST_COUNT,
                        value=1,
                        unit="requests",
                        span=span,
                        logical_operation_id=logical_operation_id,
                        authority=4,
                        source_name="span.count",
                    )
                )
        return direct, aggregate

    def _model_evidence(
        self,
        spans: tuple[SpanRecord, ...],
        registry: SemanticRegistry,
        context: ExtractionContext,
    ) -> list[Observation]:
        del registry
        model_facts: list[tuple[str, str, SpanRecord]] = []
        for span in spans:
            for semantic_type, keys in _MODEL_KEYS.items():
                value = _first_text(span.attributes, span.source_attributes, keys)
                if value is not None:
                    model_facts.append((semantic_type, value, span))
        observations: list[Observation] = []
        for semantic_type in _MODEL_KEYS:
            candidates = tuple(fact for fact in model_facts if fact[0] == semantic_type)
            if not candidates:
                continue
            selected_layer = min((fact[2].scope.layer for fact in candidates), key=_layer_priority)
            selected = tuple(fact for fact in candidates if fact[2].scope.layer is selected_layer)
            seen: set[tuple[str, str]] = set()
            for _, value, span in selected:
                logical_operation_id = _span_logical_operation_id(span)
                if (logical_operation_id, value) in seen:
                    continue
                seen.add((logical_operation_id, value))
                observations.append(
                    self._factor(
                        context,
                        f"{semantic_type}.direct",
                        semantic_type,
                        value,
                        span=span,
                        layer=selected_layer,
                        tags={LOGICAL_OPERATION_TAG: logical_operation_id},
                    )
                )
            values = {value for _, value, _ in selected}
            if len(values) == 1:
                observations.insert(
                    len(observations) - len(seen),
                    self._factor(
                        context,
                        f"{semantic_type}.summary",
                        semantic_type,
                        values.pop(),
                        layer=selected_layer,
                        summary=True,
                    ),
                )
        return observations

    def _metric(
        self,
        context: ExtractionContext,
        name: str,
        semantic_type: str,
        value: int | float,
        *,
        unit: str,
        layer: AbstractionLayer,
        span: SpanRecord | None = None,
        summary: bool = False,
        tags: dict[str, SerializedValue] | None = None,
    ) -> Observation:
        evidence_tags = self._tags(layer, span=span, summary=summary, tags=tags)
        suffix = "summary" if span is None else span.span_id
        return Observation(
            id=f"abp_usage_v{self.version}_{suffix}_{name}",
            name=name,
            kind=ObservationKind.METRIC,
            semantic_type=semantic_type,
            value=value,
            unit=unit,
            role=ObservationRole.DIAGNOSTIC,
            span_id=None if span is None else span.span_id,
            source=ObservationSource.DERIVED,
            tags=evidence_tags,
            case_id=context.case_id,
            variant_id=context.variant_id,
        )

    def _factor(
        self,
        context: ExtractionContext,
        name: str,
        semantic_type: str,
        value: str,
        *,
        layer: AbstractionLayer,
        span: SpanRecord | None = None,
        summary: bool = False,
        tags: dict[str, SerializedValue] | None = None,
    ) -> Observation:
        evidence_tags = self._tags(layer, span=span, summary=summary, tags=tags)
        suffix = "summary" if span is None else span.span_id
        return Observation(
            id=f"abp_usage_v{self.version}_{suffix}_{name}",
            name=name,
            kind=ObservationKind.FACTOR,
            semantic_type=semantic_type,
            value=value,
            span_id=None if span is None else span.span_id,
            source=ObservationSource.DERIVED,
            tags=evidence_tags,
            case_id=context.case_id,
            variant_id=context.variant_id,
        )

    def _tags(
        self,
        layer: AbstractionLayer,
        *,
        span: SpanRecord | None,
        summary: bool,
        tags: dict[str, SerializedValue] | None,
    ) -> dict[str, SerializedValue]:
        evidence_tags: dict[str, SerializedValue] = {
            EXTRACTOR_TAG: self.name,
            EXTRACTOR_VERSION_TAG: self.version,
            ABSTRACTION_LAYER_TAG: layer.value,
        }
        if summary:
            evidence_tags[SUMMARY_TAG] = True
            evidence_tags[MEASUREMENT_SCOPE_TAG] = MeasurementScope.AGGREGATE.value
        if span is not None:
            evidence_tags[INSTRUMENTOR_TAG] = span.scope.instrumentor_name
            evidence_tags["operation.name"] = span.operation
        if tags is not None:
            evidence_tags.update(tags)
        return evidence_tags

FeedbackRecord

Bases: BaseModel

Source code in src/autobench/evaluation/feedback.py
12
13
14
15
16
17
18
19
20
class FeedbackRecord(BaseModel):
    score_name: str | None = None
    semantic_type: str | None = None
    score: float | bool | str | None = None
    passed: bool | None = None
    reason: str | None = None
    failure_category: str | None = None
    related_spans: tuple[str, ...] = ()
    related_assets: tuple[str, ...] = ()

OptimizationFeedbackInput

Bases: BaseModel

Source code in src/autobench/evaluation/feedback.py
23
24
25
26
27
28
29
30
31
32
class OptimizationFeedbackInput(BaseModel):
    run_id: str
    case_id: str
    variant_id: str
    task_status: str
    evaluation_status: str
    factors: dict[str, Any] = Field(default_factory=dict)
    asset_versions: dict[str, str] = Field(default_factory=dict)
    feedback: tuple[FeedbackRecord, ...] = ()
    trace_excerpt: tuple[dict[str, Any], ...] = ()

Measurement

Bases: BaseModel

Source code in src/autobench/evaluation/measurement.py
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
class Measurement(BaseModel):
    samples_seconds: tuple[float, ...] = Field(min_length=1)
    warmup: int = Field(ge=0)
    requested_repetitions: int = Field(ge=1)
    elapsed_seconds: float = Field(ge=0.0)
    timed_out: bool = False

    @model_validator(mode="after")
    def _validate_samples(self) -> Measurement:
        if any(sample < 0.0 for sample in self.samples_seconds):
            raise ValueError("measurement samples cannot be negative")
        return self

    @property
    def repetition_count(self) -> int:
        return len(self.samples_seconds)

    @property
    def samples_ms(self) -> tuple[float, ...]:
        return tuple(sample * 1000.0 for sample in self.samples_seconds)

    @property
    def median_seconds(self) -> float:
        return median(self.samples_seconds)

    @property
    def median_ms(self) -> float:
        return self.median_seconds * 1000.0

    @property
    def mean_seconds(self) -> float:
        return mean(self.samples_seconds)

    @property
    def mean_ms(self) -> float:
        return self.mean_seconds * 1000.0

    @property
    def min_seconds(self) -> float:
        return min(self.samples_seconds)

    @property
    def min_ms(self) -> float:
        return self.min_seconds * 1000.0

    @property
    def max_seconds(self) -> float:
        return max(self.samples_seconds)

    @property
    def max_ms(self) -> float:
        return self.max_seconds * 1000.0

    @property
    def p95_ms(self) -> float:
        return self.percentile_ms(95.0)

    @property
    def standard_deviation_ms(self) -> float:
        return pstdev(self.samples_ms)

    @property
    def range_noise_pct(self) -> float | None:
        if self.median_ms == 0.0:
            return None
        return ((self.max_ms - self.min_ms) / self.median_ms) * 100.0

    def percentile_ms(self, percentile: float) -> float:
        return _percentile(self.samples_ms, percentile)

    def is_noisy(self, threshold_pct: float) -> bool:
        if threshold_pct < 0.0:
            raise ValueError("noise threshold cannot be negative")
        noise = self.range_noise_pct
        return False if noise is None else noise > threshold_pct

MeasurementBudget

Bases: BaseModel

Source code in src/autobench/evaluation/measurement.py
92
93
94
95
class MeasurementBudget(BaseModel):
    warmup: int = Field(default=0, ge=0)
    repetitions: int = Field(default=1, ge=1)
    max_seconds: float | None = Field(default=None, ge=0.0)

BetweenRequirement

Bases: BaseModel

Source code in src/autobench/evaluation/policies.py
18
19
20
21
22
23
24
25
26
27
class BetweenRequirement(BaseModel):
    min: float
    max: float
    inclusive: bool = True

    @model_validator(mode="after")
    def _validate_bounds(self) -> BetweenRequirement:
        if self.min > self.max:
            raise ValueError("between min cannot be greater than max")
        return self

PolicyResult

Bases: BaseModel

Source code in src/autobench/evaluation/policies.py
61
62
63
64
65
66
67
68
69
class PolicyResult(BaseModel):
    policy_name: str
    run_id: str
    case_id: str
    variant_id: str
    metric: SemanticType
    passed: bool
    actual: Any = None
    reason: str | None = None

PolicySpec

Bases: BaseModel

Source code in src/autobench/evaluation/policies.py
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
class PolicySpec(BaseModel):
    name: str = Field(min_length=1)
    metric: SemanticType
    must_equal: Any = None
    must_not_equal: Any = None
    must_greater: float | None = None
    must_greater_equal: float | None = None
    must_less: float | None = None
    must_less_equal: float | None = None
    must_in: tuple[Any, ...] | None = None
    must_not_in: tuple[Any, ...] | None = None
    must_between: BetweenRequirement | None = None

    @model_validator(mode="after")
    def _validate_single_requirement(self) -> PolicySpec:
        configured = [
            self.must_equal is not None,
            self.must_not_equal is not None,
            self.must_greater is not None,
            self.must_greater_equal is not None,
            self.must_less is not None,
            self.must_less_equal is not None,
            self.must_in is not None,
            self.must_not_in is not None,
            self.must_between is not None,
        ]
        if sum(configured) != 1:
            raise ValueError("policy must declare exactly one requirement")
        return self

GenAIPricesSource

Source code in src/autobench/evaluation/pricing.py
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
class GenAIPricesSource:
    def __init__(self, data: list[dict[str, Any]]) -> None:
        self._data = data

    @classmethod
    def from_json_file(cls, path: Path) -> GenAIPricesSource:
        raw = json.loads(path.read_text(encoding="utf-8"))
        return cls(_required_mapping_list(raw, "genai-prices JSON"))

    @classmethod
    def from_url(cls, url: str) -> GenAIPricesSource:
        with urlopen(url, timeout=30) as response:
            raw = json.loads(response.read().decode("utf-8"))
        return cls(_required_mapping_list(raw, "genai-prices JSON"))

    def pricing_table(self) -> PricingTable:
        providers: dict[str, dict[str, ModelPricing]] = {}
        for provider_entry in self._data:
            provider_id = _required_text(provider_entry, "id")
            provider_models = providers.setdefault(provider_id, {})
            for model_entry in _iter_mappings(provider_entry.get("models")):
                pricing = _genai_model_pricing(model_entry)
                if pricing is not None:
                    model_id = _required_text(model_entry, "id")
                    provider_models[model_id] = pricing.model_copy(
                        update={"model_id": _canonical_model_id(provider_id, model_id)}
                    )
        return PricingTable(source="genai-prices", providers=providers)

LLMPricesSource

Source code in src/autobench/evaluation/pricing.py
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
class LLMPricesSource:
    def __init__(self, data: dict[str, Any]) -> None:
        self._data = data

    @classmethod
    def from_json_file(cls, path: Path) -> LLMPricesSource:
        raw = json.loads(path.read_text(encoding="utf-8"))
        if not isinstance(raw, dict):
            raise ValueError("llm-prices JSON must contain an object.")
        return cls(raw)

    @classmethod
    def from_url(cls, url: str) -> LLMPricesSource:
        with urlopen(url, timeout=30) as response:
            raw = json.loads(response.read().decode("utf-8"))
        if not isinstance(raw, dict):
            raise ValueError("llm-prices JSON must contain an object.")
        return cls(raw)

    def pricing_table(self) -> PricingTable:
        providers: dict[str, dict[str, ModelPricing]] = {}
        for entry in _iter_mappings(self._data.get("prices")):
            vendor = _required_text(entry, "vendor")
            model_id = _required_text(entry, "id")
            provider_models = providers.setdefault(vendor, {})
            provider_models[model_id] = ModelPricing(
                model_id=_canonical_model_id(vendor, model_id),
                input_cost_per_million_tokens=_required_float(entry, "input"),
                output_cost_per_million_tokens=_required_float(entry, "output"),
                cache_read_cost_per_million_tokens=_optional_float(entry.get("input_cached")),
                name=_optional_text(entry.get("name")),
                source="llm-prices",
            )
        return PricingTable(
            source="llm-prices",
            updated_at=_optional_text(self._data.get("updated_at")),
            providers=providers,
        )

ModelPricing

Bases: BaseModel

Source code in src/autobench/evaluation/pricing.py
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
class ModelPricing(BaseModel):
    model_id: str | None = None
    input_cost_per_million_tokens: float | None = None
    output_cost_per_million_tokens: float | None = None
    cache_read_cost_per_million_tokens: float | None = None
    cache_write_cost_per_million_tokens: float | None = None
    input_pricing: TokenPrice | None = None
    output_pricing: TokenPrice | None = None
    cache_read_pricing: TokenPrice | None = None
    cache_write_pricing: TokenPrice | None = None
    name: str | None = None
    aliases: tuple[str, ...] = ()
    source: str | None = None
    metadata: dict[str, Any] = Field(default_factory=dict)

    def input_rate_for_tokens(self, tokens: float) -> float | None:
        return _resolve_token_rate(self.input_pricing, self.input_cost_per_million_tokens, tokens)

    def output_rate_for_tokens(self, tokens: float) -> float | None:
        return _resolve_token_rate(self.output_pricing, self.output_cost_per_million_tokens, tokens)

    def cache_read_rate_for_tokens(self, tokens: float) -> float | None:
        return _resolve_token_rate(
            self.cache_read_pricing,
            self.cache_read_cost_per_million_tokens,
            tokens,
        )

    def cache_write_rate_for_tokens(self, tokens: float) -> float | None:
        return _resolve_token_rate(
            self.cache_write_pricing,
            self.cache_write_cost_per_million_tokens,
            tokens,
        )

PriceSource

Bases: Protocol

Source code in src/autobench/evaluation/pricing.py
105
106
class PriceSource(Protocol):  # pragma: no cover
    def pricing_table(self) -> PricingTable: ...

PricingTable

Bases: BaseModel

Source code in src/autobench/evaluation/pricing.py
 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
class PricingTable(BaseModel):
    provider: str | None = None
    source: str | None = None
    updated_at: str | None = None
    models: dict[str, ModelPricing] = Field(default_factory=dict)
    providers: dict[str, dict[str, ModelPricing]] = Field(default_factory=dict)

    def model_pricing(self, *, provider: str, model: str) -> ModelPricing | None:
        resolved = self.resolve_model_pricing(provider=provider, model=model)
        return resolved[1] if resolved is not None else None

    def resolve_model_pricing(
        self, *, provider: str, model: str
    ) -> tuple[str, ModelPricing] | None:
        if self.provider is not None and self.provider != provider:
            return None
        candidates = _model_lookup_candidates(provider=provider, model=model)
        provider_models = self.providers.get(provider, {})
        for candidate in candidates:
            direct = self.models.get(candidate)
            if direct is not None and _pricing_matches_provider(direct, provider):
                return direct.model_id or candidate, direct
            direct = provider_models.get(candidate)
            if direct is not None:
                return direct.model_id or _canonical_model_id(provider, candidate), direct
        for resolved_id, pricing in _iter_pricing_entries(self):
            if not _pricing_matches_provider(pricing, provider):
                continue
            if resolved_id in candidates:
                return resolved_id, pricing
            aliases = set(pricing.aliases)
            if pricing.model_id is not None:
                aliases.add(pricing.model_id)
            if aliases.intersection(candidates):
                return resolved_id, pricing
        return None

StaticPriceSource

Source code in src/autobench/evaluation/pricing.py
109
110
111
112
113
114
class StaticPriceSource:
    def __init__(self, table: PricingTable) -> None:
        self._table = table

    def pricing_table(self) -> PricingTable:
        return self._table

TokenPrice

Bases: BaseModel

Source code in src/autobench/evaluation/pricing.py
19
20
21
22
23
24
25
26
27
28
class TokenPrice(BaseModel):
    unit: Literal["mtok"] = "mtok"
    price_per_million_tokens: float | None = None
    tiers: tuple[TokenPriceTier, ...] = ()

    def rate_for_tokens(self, tokens: float) -> float | None:
        for tier in self.tiers:
            if tier.up_to_tokens is None or tokens <= float(tier.up_to_tokens):
                return tier.price_per_million_tokens
        return self.price_per_million_tokens

TokenPriceTier

Bases: BaseModel

Source code in src/autobench/evaluation/pricing.py
14
15
16
class TokenPriceTier(BaseModel):
    up_to_tokens: int | None = Field(default=None, ge=1)
    price_per_million_tokens: float

ExactScorer

Bases: ScoringSpecBase

Source code in src/autobench/evaluation/scoring.py
88
89
90
91
class ExactScorer(ScoringSpecBase):
    kind: Literal["exact"] = "exact"
    actual: str = Field(min_length=1)
    expected: str = Field(min_length=1)

ExpectedActionScorer

Bases: ScoringSpecBase

Source code in src/autobench/evaluation/scoring.py
108
109
110
111
class ExpectedActionScorer(ScoringSpecBase):
    kind: Literal["expected_action"] = "expected_action"
    metric: ActionMetric = "selection"
    observed_kind: str = "tool"

OutputMetricScorer

Bases: ScoringSpecBase

Source code in src/autobench/evaluation/scoring.py
78
79
80
class OutputMetricScorer(ScoringSpecBase):
    kind: Literal["output"] = "output"
    path: str = Field(min_length=1)

PassFailScorer

Bases: ScoringSpecBase

Source code in src/autobench/evaluation/scoring.py
83
84
85
class PassFailScorer(ScoringSpecBase):
    kind: Literal["pass_fail"] = "pass_fail"
    path: str = Field(min_length=1)

PythonScorer

Bases: ScoringSpecBase

Source code in src/autobench/evaluation/scoring.py
102
103
104
105
class PythonScorer(ScoringSpecBase):
    kind: Literal["python"] = "python"
    target: str = Field(min_length=1)
    module_search_paths: tuple[str, ...] = Field(default_factory=tuple, exclude=True)

SchemaScorer

Bases: ScoringSpecBase

Source code in src/autobench/evaluation/scoring.py
94
95
96
97
98
99
class SchemaScorer(ScoringSpecBase):
    model_config = ConfigDict(populate_by_name=True)

    kind: Literal["schema"] = "schema"
    path: str = "output"
    schema_definition: dict[str, Any] = Field(default_factory=dict, alias="schema")

ScoreRecord

Bases: BaseModel

Source code in src/autobench/evaluation/scoring.py
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
class ScoreRecord(BaseModel):
    name: str
    semantic_type: SemanticType
    value: Any | None = None
    unit: str | None = None
    direction: Direction | None = None
    role: ObservationRole | None = None
    optional: bool = False
    actual_value: Any | None = None
    expected_value: Any | None = None
    span_id: str | None = None
    error: ErrorRecord | None = None
    tags: dict[str, Any] = Field(default_factory=dict)

    def to_observation(
        self,
        *,
        observation_id: str,
        case_id: str,
        variant_id: str,
    ) -> Observation:
        return Observation(
            id=observation_id,
            name=self.name,
            kind=ObservationKind.METRIC,
            semantic_type=self.semantic_type,
            value=self.value,
            unit=self.unit,
            direction=self.direction,
            role=self.role,
            span_id=self.span_id,
            source=ObservationSource.SCORE,
            tags=self.tags,
            case_id=case_id,
            variant_id=variant_id,
        )

ScoringCall dataclass

Source code in src/autobench/evaluation/scoring.py
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
@dataclass(slots=True)
class ScoringCall:
    ctx: RunContext
    task_result: TaskResult
    selected_spans: list[SpanRecord] = field(default_factory=list)

    @property
    def output(self) -> Any:
        return self.task_result.output

    @property
    def case(self) -> Any:
        return self.ctx.case

    @property
    def variant(self) -> Any:
        return self.ctx.variant

    @property
    def observations(self) -> list[Observation]:
        return self.task_result.observations

    @property
    def spans(self) -> list[SpanRecord]:
        return self.selected_spans

SpanSelector

Bases: BaseModel

Source code in src/autobench/evaluation/spans.py
12
13
14
15
16
17
class SpanSelector(BaseModel):
    kind: str | None = None
    name: str | None = None
    tag: dict[str, Any] = Field(default_factory=dict)
    path: str | None = None
    semantic_type: str | None = None

AutoInstrumentation

Bases: InstrumentationSettings

Discover and install every compatible built-in instrumentor.

Source code in src/autobench/instrumentation/config.py
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class AutoInstrumentation(InstrumentationSettings):
    """Discover and install every compatible built-in instrumentor."""

    kind: Literal["all"] = "all"
    exclude: tuple[InstrumentorName, ...] = ()
    strict: bool = False

    @field_validator("exclude")
    @classmethod
    def normalize_exclusions(
        cls,
        values: tuple[InstrumentorName, ...],
    ) -> tuple[InstrumentorName, ...]:
        return tuple(sorted(set(values)))

Compatibility

Bases: BaseModel

Source code in src/autobench/instrumentation/models.py
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
class Compatibility(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    status: CompatibilityStatus = CompatibilityStatus.COMPATIBLE
    target_version: str | None = Field(default=None, min_length=1)
    degraded_features: tuple[str, ...] = ()
    conflicts: tuple[str, ...] = ()
    diagnostics: tuple[str, ...] = ()
    private_seam_supported: bool | None = None

    @property
    def available(self) -> bool:
        return self.status is not CompatibilityStatus.UNAVAILABLE

    @property
    def supported(self) -> bool:
        return self.status not in {
            CompatibilityStatus.UNAVAILABLE,
            CompatibilityStatus.UNSUPPORTED,
        }

    @property
    def installable(self) -> bool:
        return self.status in {
            CompatibilityStatus.COMPATIBLE,
            CompatibilityStatus.DEGRADED,
        }

    @classmethod
    def compatible(cls, *, target_version: str | None = None) -> Compatibility:
        return cls(target_version=target_version)

CompatibilityStatus

Bases: StrEnum

Source code in src/autobench/instrumentation/models.py
24
25
26
27
28
29
class CompatibilityStatus(StrEnum):
    COMPATIBLE = "compatible"
    DEGRADED = "degraded"
    UNAVAILABLE = "unavailable"
    UNSUPPORTED = "unsupported"
    CONFLICT = "conflict"

HTTPXCaptureSettings

Bases: BaseModel

Privacy-first HTTP request and response capture settings.

Source code in src/autobench/instrumentation/config.py
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
class HTTPXCaptureSettings(BaseModel):
    """Privacy-first HTTP request and response capture settings."""

    model_config = ConfigDict(frozen=True, extra="forbid")

    path: Literal["omit", "hash", "full"] = "hash"
    request_headers: tuple[str, ...] = ()
    response_headers: tuple[str, ...] = ()
    request_body: bool = False
    response_body: bool = False
    max_body_bytes: int = Field(default=65_536, ge=1)

    @field_validator("request_headers", "response_headers")
    @classmethod
    def normalize_headers(cls, values: tuple[str, ...]) -> tuple[str, ...]:
        normalized = tuple(dict.fromkeys(value.strip().lower() for value in values))
        if any(not value for value in normalized):
            raise ValueError("captured header names cannot be empty")
        return normalized

HTTPXInstrumentation

Bases: InstrumentationSettings

Capture HTTPX calls at the public transport boundary.

Source code in src/autobench/instrumentation/config.py
79
80
81
82
83
class HTTPXInstrumentation(InstrumentationSettings):
    """Capture HTTPX calls at the public transport boundary."""

    kind: Literal["httpx"] = "httpx"
    capture: HTTPXCaptureSettings = Field(default_factory=HTTPXCaptureSettings)

InstrumentationConflictError

Bases: RuntimeError

Raised when a patch target changed outside Autobench ownership.

Source code in src/autobench/instrumentation/patching.py
18
19
class InstrumentationConflictError(RuntimeError):
    """Raised when a patch target changed outside Autobench ownership."""

InstrumentationError

Bases: RuntimeError

Raised when native instrumentation cannot be installed safely.

Source code in src/autobench/instrumentation/models.py
20
21
class InstrumentationError(RuntimeError):
    """Raised when native instrumentation cannot be installed safely."""

InstrumentationHandle

Bases: AbstractContextManager['InstrumentationHandle']

Source code in src/autobench/instrumentation/models.py
 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
class InstrumentationHandle(AbstractContextManager["InstrumentationHandle"]):
    def __init__(
        self,
        close_callback: Callable[[], None],
        *,
        info: InstrumentorInfo | None = None,
    ) -> None:
        self._close_callback = close_callback
        self.info = info
        self._closed = False

    @property
    def closed(self) -> bool:
        return self._closed

    def close(self) -> None:
        if self._closed:
            return
        self._close_callback()
        self._closed = True

    def __exit__(
        self,
        exc_type: type[BaseException] | None,
        exc_value: BaseException | None,
        traceback: TracebackType | None,
    ) -> bool | None:
        self.close()
        return None

InstrumentationManager

Bases: AbstractContextManager['InstrumentationManager']

Source code in src/autobench/instrumentation/manager.py
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
class InstrumentationManager(AbstractContextManager["InstrumentationManager"]):
    def __init__(self, runtime: InstrumentationRuntime | None = None) -> None:
        self.runtime = InstrumentationRuntime() if runtime is None else runtime
        self._installations: dict[str, _Installation] = {}
        self._closed = False

    @property
    def installed(self) -> tuple[InstrumentorInfo, ...]:
        return tuple(
            installation.instrumentor.info for installation in self._installations.values()
        )

    def check(self, instrumentor: Instrumentor) -> Compatibility:
        declared = instrumentor.check()
        if not declared.installable:
            return declared
        package_compatibility = check_package_compatibility(instrumentor.info)
        if not package_compatibility.installable:
            return package_compatibility
        degraded_features = declared.degraded_features + package_compatibility.degraded_features
        diagnostics = declared.diagnostics + package_compatibility.diagnostics
        status = (
            CompatibilityStatus.DEGRADED
            if degraded_features or declared.status is CompatibilityStatus.DEGRADED
            else CompatibilityStatus.COMPATIBLE
        )
        return Compatibility(
            status=status,
            target_version=package_compatibility.target_version or declared.target_version,
            degraded_features=degraded_features,
            conflicts=declared.conflicts,
            diagnostics=diagnostics,
            private_seam_supported=declared.private_seam_supported,
        )

    def install(self, instrumentor: Instrumentor) -> InstrumentationHandle:
        if self._closed:
            raise InstrumentationError("instrumentation manager is closed")
        info = instrumentor.info
        existing = self._installations.get(info.id)
        if existing is not None:
            if existing.instrumentor.info.version != info.version:
                raise InstrumentationError(
                    f"instrumentor '{info.id}' version {existing.instrumentor.info.version} "
                    f"is already installed; cannot install {info.version}"
                )
            existing.references += 1
            return InstrumentationHandle(lambda: self._release(info.id), info=info)

        compatibility = self.check(instrumentor)
        if not compatibility.installable:
            detail = (
                "; ".join(compatibility.conflicts + compatibility.diagnostics)
                or compatibility.status.value
            )
            raise InstrumentationError(f"instrumentor '{info.id}' is not installable: {detail}")
        native_handle = instrumentor.install(self.runtime)
        self._installations[info.id] = _Installation(
            instrumentor=instrumentor,
            handle=native_handle,
            compatibility=compatibility,
        )
        return InstrumentationHandle(lambda: self._release(info.id), info=info)

    def close(self) -> None:
        if self._closed:
            return
        for instrumentor_id in tuple(reversed(self._installations)):
            installation = self._installations[instrumentor_id]
            installation.references = 1
            self._release(instrumentor_id)
        self.runtime.patches.close()
        self._closed = True

    def _release(self, instrumentor_id: str) -> None:
        installation = self._installations.get(instrumentor_id)
        if installation is None:
            return
        installation.references -= 1
        if installation.references > 0:
            return
        installation.handle.close()
        del self._installations[instrumentor_id]

    def __exit__(
        self,
        exc_type: type[BaseException] | None,
        exc_value: BaseException | None,
        traceback: TracebackType | None,
    ) -> bool | None:
        self.close()
        return None

InstrumentationRuntime

Source code in src/autobench/instrumentation/manager.py
 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
class InstrumentationRuntime:
    def __init__(self, patches: PatchManager | None = None) -> None:
        self.patches = PatchManager() if patches is None else patches

    def patch_method(
        self,
        info: InstrumentorInfo,
        target: type[Any],
        attribute: str,
        handler: CallHandler,
        *,
        expected_descriptor: Any = None,
    ) -> InstrumentationHandle:
        return self.patches.patch_method(
            target,
            attribute,
            owner=info.id,
            handler=handler,
            expected_descriptor=expected_descriptor,
        )

    def scope(
        self,
        info: InstrumentorInfo,
        *,
        target_version: str | None = None,
    ) -> InstrumentationScope:
        return InstrumentationScope(
            instrumentor_name=info.id,
            instrumentor_version=info.version,
            package_name=info.target_distribution or "autobench",
            package_version=target_version or info.version,
            mechanism=info.mechanism,
            layer=info.layer,
            source_convention=info.source_convention,
            source_convention_version=info.source_convention_version,
        )

    def diagnose(
        self,
        info: InstrumentorInfo,
        code: str,
        message: str,
        *,
        severity: DiagnosticSeverity = DiagnosticSeverity.WARNING,
    ) -> bool:
        active = get_context()
        if active is None:
            return False
        emitter = Emitter(
            active.collector,
            self.scope(info),
            trace_id=active.trace_id,
            execution=active.execution,
        )
        try:
            emitter.diagnostic(
                code,
                message,
                severity=severity,
                span_id=active.current_span_id,
            )
        except RuntimeError:
            return False
        return True

InstrumentationSettings

Bases: BaseModel

Shared configuration for one native Autobench instrumentor.

Source code in src/autobench/instrumentation/config.py
 8
 9
10
11
12
13
class InstrumentationSettings(BaseModel):
    """Shared configuration for one native Autobench instrumentor."""

    model_config = ConfigDict(frozen=True, extra="forbid")

    enabled: bool = True

InstrumentCall dataclass

Source code in src/autobench/instrumentation/models.py
139
140
141
142
143
144
145
146
147
@dataclass(slots=True)
class InstrumentCall:
    instance: Any | None
    args: tuple[Any, ...]
    kwargs: dict[str, Any]
    result: Any = None
    error: BaseException | None = None
    stream_item_count: int = 0
    last_stream_item: Any = None

InstrumentFactorSpec

Bases: BaseModel

Source code in src/autobench/instrumentation/models.py
169
170
171
172
173
174
175
176
177
178
179
180
181
182
class InstrumentFactorSpec(BaseModel):
    model_config = ConfigDict(arbitrary_types_allowed=True, extra="forbid")

    name: str = Field(min_length=1)
    semantic_type: SemanticType | None = None
    tags: dict[str, Any] = Field(default_factory=dict)
    value_path: str | None = None
    value_factory: Callable[[InstrumentCall], Any] | None = None

    @model_validator(mode="after")
    def validate_extractor(self) -> InstrumentFactorSpec:
        if self.value_path is None and self.value_factory is None:
            raise ValueError("instrument factors require value_path or value_factory")
        return self

InstrumentMetricSpec

Bases: BaseModel

Source code in src/autobench/instrumentation/models.py
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
class InstrumentMetricSpec(BaseModel):
    model_config = ConfigDict(arbitrary_types_allowed=True, extra="forbid")

    name: str = Field(min_length=1)
    semantic_type: SemanticType | None = None
    unit: str | None = None
    direction: Direction | None = None
    role: ObservationRole | None = None
    tags: dict[str, Any] = Field(default_factory=dict)
    value_path: str | None = None
    value_factory: Callable[[InstrumentCall], Any] | None = None

    @model_validator(mode="after")
    def validate_extractor(self) -> InstrumentMetricSpec:
        if self.value_path is None and self.value_factory is None:
            raise ValueError("instrument metrics require value_path or value_factory")
        return self

Instrumentor

Bases: Protocol

Source code in src/autobench/instrumentation/models.py
130
131
132
133
134
135
136
class Instrumentor(Protocol):
    @property
    def info(self) -> InstrumentorInfo: ...

    def check(self) -> Compatibility: ...

    def install(self, runtime: InstrumentationRuntime) -> InstrumentationHandle: ...

InstrumentorCapabilities

Bases: BaseModel

Source code in src/autobench/instrumentation/models.py
32
33
34
35
36
37
38
class InstrumentorCapabilities(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid", populate_by_name=True)

    sync: bool = True
    async_: bool = Field(default=False, alias="async")
    streaming: bool = False
    native_hooks: bool = False

InstrumentorInfo

Bases: BaseModel

Source code in src/autobench/instrumentation/models.py
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
class InstrumentorInfo(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid", populate_by_name=True)

    id: str = Field(min_length=1)
    version: str = Field(min_length=1)
    target_distribution: str | None = Field(default=None, min_length=1)
    supported_versions: str | None = Field(default=None, min_length=1)
    mechanism: CaptureMechanism
    layer: AbstractionLayer
    span_kinds: tuple[str, ...] = ()
    semantic_families: tuple[str, ...] = ()
    optional_dependencies: tuple[str, ...] = ()
    source_convention: str | None = Field(default=None, min_length=1)
    source_convention_version: str | None = Field(default=None, min_length=1)
    capabilities: InstrumentorCapabilities = Field(default_factory=InstrumentorCapabilities)

    @model_validator(mode="after")
    def validate_target_and_convention(self) -> InstrumentorInfo:
        if self.supported_versions is not None and self.target_distribution is None:
            raise ValueError("supported_versions requires target_distribution")
        if self.source_convention is None and self.source_convention_version is not None:
            raise ValueError("source_convention_version requires source_convention")
        return self

InstrumentorStatus

Bases: BaseModel

Dependency and capability report for one built-in instrumentor.

Source code in src/autobench/instrumentation/registry.py
31
32
33
34
35
36
37
38
39
40
class InstrumentorStatus(BaseModel):
    """Dependency and capability report for one built-in instrumentor."""

    model_config = ConfigDict(frozen=True, extra="forbid")

    name: InstrumentorName
    extra: str
    info: InstrumentorInfo
    compatibility: Compatibility
    capture_mode: str

OpenAIAgentsInstrumentation

Bases: InstrumentationSettings

Capture OpenAI Agents workflows through its native trace processor.

Source code in src/autobench/instrumentation/config.py
52
53
54
55
class OpenAIAgentsInstrumentation(InstrumentationSettings):
    """Capture OpenAI Agents workflows through its native trace processor."""

    kind: Literal["openai_agents"] = "openai_agents"

OpenAIInstrumentation

Bases: InstrumentationSettings

Capture official OpenAI Python client calls and streams.

Source code in src/autobench/instrumentation/config.py
46
47
48
49
class OpenAIInstrumentation(InstrumentationSettings):
    """Capture official OpenAI Python client calls and streams."""

    kind: Literal["openai"] = "openai"

PatchDiagnostic dataclass

Source code in src/autobench/instrumentation/patching.py
37
38
39
40
41
@dataclass(slots=True)
class PatchDiagnostic:
    owner: str
    target: str
    message: str

PatchManager

Source code in src/autobench/instrumentation/patching.py
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
class PatchManager:
    def __init__(self) -> None:
        self._states: WeakKeyDictionary[type[Any], dict[str, _PatchState]] = WeakKeyDictionary()
        self._diagnostics: list[PatchDiagnostic] = []

    @property
    def diagnostics(self) -> tuple[PatchDiagnostic, ...]:
        return tuple(self._diagnostics)

    def patch_method(
        self,
        target: type[Any],
        attribute: str,
        *,
        owner: str,
        handler: CallHandler,
        expected_descriptor: Any = None,
    ) -> InstrumentationHandle:
        target_states = self._states.setdefault(target, {})
        state = target_states.get(attribute)
        if state is not None:
            self._require_owned_descriptor(target, state)
            registration = state.registrations.get(owner)
            if registration is None:
                state.registrations[owner] = _PatchRegistration(owner=owner, handler=handler)
            else:
                registration.references += 1
            return InstrumentationHandle(lambda: self._release(target, attribute, owner))

        descriptor = getattr_static(target, attribute)
        if expected_descriptor is not None and descriptor is not expected_descriptor:
            raise InstrumentationConflictError(
                f"{target.__qualname__}.{attribute} does not match the expected descriptor"
            )
        descriptor_kind, original_callable = _descriptor_callable(target, attribute, descriptor)
        registrations = {owner: _PatchRegistration(owner=owner, handler=handler)}
        wrapped = _wrap_callable(original_callable, descriptor_kind, registrations)
        installed_descriptor = _bind_descriptor(wrapped, descriptor_kind)
        state = _PatchState(
            attribute=attribute,
            original_descriptor=descriptor,
            installed_descriptor=installed_descriptor,
            was_local=attribute in target.__dict__,
            registrations=registrations,
        )
        setattr(target, attribute, installed_descriptor)
        target_states[attribute] = state
        return InstrumentationHandle(lambda: self._release(target, attribute, owner))

    def close(self) -> None:
        while self._states:
            target, target_states = next(iter(self._states.items()))
            attribute, state = next(iter(target_states.items()))
            owner, registration = next(iter(state.registrations.items()))
            registration.references = 1
            self._release(target, attribute, owner)

    def _release(self, target: type[Any], attribute: str, owner: str) -> None:
        state = self._states.get(target, {}).get(attribute)
        if state is None:
            return
        registration = state.registrations.get(owner)
        if registration is None:
            return
        registration.references -= 1
        if registration.references > 0:
            return
        del state.registrations[owner]
        if not state.registrations:
            target_states = self._states[target]
            del target_states[attribute]
            if not target_states:
                del self._states[target]
            current = getattr_static(target, attribute)
            if current is not state.installed_descriptor:
                self._diagnostics.append(
                    PatchDiagnostic(
                        owner=owner,
                        target=f"{target.__module__}.{target.__qualname__}.{attribute}",
                        message="target descriptor changed after Autobench installed its wrapper",
                    )
                )
            elif state.was_local:
                setattr(target, attribute, state.original_descriptor)
            else:
                delattr(target, attribute)
        try:
            registration.handler.close()
        except Exception as exc:
            registration.handler.diagnose("close", exc)

    def _require_owned_descriptor(self, target: type[Any], state: _PatchState) -> None:
        current = getattr_static(target, state.attribute)
        if current is not state.installed_descriptor:
            raise InstrumentationConflictError(
                f"{target.__qualname__}.{state.attribute} changed after Autobench "
                "installed its wrapper"
            )

PydanticAIInstrumentation

Bases: InstrumentationSettings

Capture Pydantic AI agent, model, tool, and validation activity.

Source code in src/autobench/instrumentation/config.py
40
41
42
43
class PydanticAIInstrumentation(InstrumentationSettings):
    """Capture Pydantic AI agent, model, tool, and validation activity."""

    kind: Literal["pydantic_ai"] = "pydantic_ai"

CanonicalFact

Bases: BaseModel

Source code in src/autobench/metrics/mappings.py
126
127
128
129
130
131
132
133
134
class CanonicalFact(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    semantic_type: SemanticType
    value: SerializedValue = None
    reference: EvidenceRef | None = None
    unit: str | None = Field(default=None, min_length=1)
    authority: float = Field(default=1.0, ge=0.0, le=1.0)
    sources: tuple[SourceProvenance, ...]

CanonicalizationResult

Bases: BaseModel

Source code in src/autobench/metrics/mappings.py
165
166
167
168
169
170
171
172
173
174
class CanonicalizationResult(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    source_map_id: str = Field(min_length=1)
    source_map_version: int = Field(ge=1)
    facts: tuple[CanonicalFact, ...] = ()
    classification: SpanClassification | None = None
    diagnostics: tuple[Diagnostic, ...] = ()
    source_snapshot: SourceSnapshot
    replayed_from: str | None = Field(default=None, min_length=1)

ClassificationRule

Bases: BaseModel

Source code in src/autobench/metrics/mappings.py
66
67
68
69
70
71
class ClassificationRule(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    kind: Literal["classify"] = "classify"
    source: SourceSelector
    cases: dict[str, SpanClassification] = Field(min_length=1)

MappingStatus

Bases: StrEnum

Source code in src/autobench/metrics/mappings.py
177
178
179
class MappingStatus(StrEnum):
    AVAILABLE = "available"
    UNAVAILABLE = "unavailable"

ReferenceRule

Bases: BaseModel

Source code in src/autobench/metrics/mappings.py
74
75
76
77
78
79
80
81
82
83
84
class ReferenceRule(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    kind: Literal["reference"] = "reference"
    source: SourceSelector
    semantic_type: SemanticType
    reference_kind: ReferenceKind
    id_path: tuple[PathSegment, ...] = ()
    version_path: tuple[PathSegment, ...] | None = None
    media_type: str | None = Field(default=None, min_length=1)
    authority: float = Field(default=1.0, ge=0.0, le=1.0)

RenameRule

Bases: BaseModel

Source code in src/autobench/metrics/mappings.py
31
32
33
34
35
36
37
38
class RenameRule(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    kind: Literal["rename"] = "rename"
    sources: tuple[SourceSelector, ...] = Field(min_length=1)
    semantic_type: SemanticType
    capture: CaptureLevel | None = None
    authority: float = Field(default=1.0, ge=0.0, le=1.0)

RetainedSourceFact

Bases: BaseModel

Source code in src/autobench/metrics/mappings.py
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
class RetainedSourceFact(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    selector: SourceSelector
    value: SerializedValue = None
    reference: EvidenceRef | None = None
    available: bool
    reason: str | None = Field(default=None, min_length=1)

    @model_validator(mode="after")
    def validate_availability(self) -> RetainedSourceFact:
        if self.available and self.reason is not None:
            raise ValueError("available source facts cannot have an unavailable reason")
        if not self.available and self.reason is None:
            raise ValueError("unavailable source facts require a reason")
        return self

SourceData

Bases: BaseModel

Source code in src/autobench/metrics/mappings.py
118
119
120
121
122
123
class SourceData(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    system: str = Field(min_length=1)
    convention_version: str = Field(min_length=1)
    values: dict[str, SerializedValue] = Field(default_factory=dict)

SourceMap

Bases: BaseModel

Source code in src/autobench/metrics/mappings.py
106
107
108
109
110
111
112
113
114
115
class SourceMap(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    id: str = Field(min_length=1)
    version: int = Field(ge=1)
    source_system: str = Field(min_length=1)
    convention_version: str = Field(min_length=1)
    instrumentor: str | None = Field(default=None, min_length=1)
    instrumented_library_version: str | None = Field(default=None, min_length=1)
    rules: tuple[MappingRule, ...] = ()

SourceSelector

Bases: BaseModel

Source code in src/autobench/metrics/mappings.py
23
24
25
26
27
28
class SourceSelector(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    key: str = Field(min_length=1)
    path: tuple[PathSegment, ...] = ()
    deprecated: bool = False

SourceSnapshot

Bases: BaseModel

Source code in src/autobench/metrics/mappings.py
155
156
157
158
159
160
161
162
class SourceSnapshot(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    system: str = Field(min_length=1)
    convention_version: str = Field(min_length=1)
    source_map_id: str = Field(min_length=1)
    source_map_version: int = Field(ge=1)
    facts: tuple[RetainedSourceFact, ...] = ()

SpanClassification

Bases: BaseModel

Source code in src/autobench/metrics/mappings.py
58
59
60
61
62
63
class SpanClassification(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    operation: str = Field(min_length=1)
    kind: str = Field(min_length=1)
    sources: tuple[SourceProvenance, ...] = ()

SplitOutput

Bases: BaseModel

Source code in src/autobench/metrics/mappings.py
41
42
43
44
45
46
47
class SplitOutput(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    path: tuple[PathSegment, ...]
    semantic_type: SemanticType
    capture: CaptureLevel | None = None
    authority: float = Field(default=1.0, ge=0.0, le=1.0)

SplitRule

Bases: BaseModel

Source code in src/autobench/metrics/mappings.py
50
51
52
53
54
55
class SplitRule(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    kind: Literal["split"] = "split"
    source: SourceSelector
    outputs: tuple[SplitOutput, ...] = Field(min_length=1)

UnitConversionRule

Bases: BaseModel

Source code in src/autobench/metrics/mappings.py
87
88
89
90
91
92
93
94
95
96
97
class UnitConversionRule(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    kind: Literal["convert_unit"] = "convert_unit"
    source: SourceSelector
    semantic_type: SemanticType
    source_unit: str = Field(min_length=1)
    target_unit: str = Field(min_length=1)
    multiplier: float = 1.0
    offset: float = 0.0
    authority: float = Field(default=1.0, ge=0.0, le=1.0)

Direction

Bases: StrEnum

Source code in src/autobench/metrics/observations.py
18
19
20
21
22
class Direction(StrEnum):
    MAXIMIZE = "maximize"
    MINIMIZE = "minimize"
    TARGET = "target"
    NONE = "none"

Observation

Bases: BaseModel

Source code in src/autobench/metrics/observations.py
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
class Observation(BaseModel):
    id: str
    name: str
    kind: ObservationKind
    semantic_type: SemanticType | None = None
    value: Any
    unit: str | None = None
    direction: Direction | None = None
    role: ObservationRole | None = None
    span_id: str | None = None
    source: ObservationSource | str | None = None
    tags: dict[str, Any] = Field(default_factory=dict)
    case_id: str | None = None
    variant_id: str | None = None

    @model_validator(mode="after")
    def _validate_kind_rules(self) -> Observation:
        if self.kind is ObservationKind.FACTOR and self.direction is not None:
            raise ValueError("factor observations cannot declare direction")
        if (
            self.kind in {ObservationKind.ARTIFACT, ObservationKind.EVENT}
            and self.direction is not None
        ):
            raise ValueError("artifact and event observations cannot declare direction")
        return self

    def normalized_semantic_type(self, registry: SemanticRegistry | None = None) -> str | None:
        active_registry = registry or DEFAULT_SEMANTIC_REGISTRY
        return active_registry.normalize(self.semantic_type)

ObservationKind

Bases: StrEnum

Source code in src/autobench/metrics/observations.py
11
12
13
14
15
class ObservationKind(StrEnum):
    METRIC = "metric"
    FACTOR = "factor"
    ARTIFACT = "artifact"
    EVENT = "event"

ObservationRole

Bases: StrEnum

Source code in src/autobench/metrics/observations.py
25
26
27
28
29
class ObservationRole(StrEnum):
    OBJECTIVE = "objective"
    CONSTRAINT = "constraint"
    DIAGNOSTIC = "diagnostic"
    METADATA = "metadata"

ObservationSource

Bases: StrEnum

Source code in src/autobench/metrics/observations.py
32
33
34
35
36
37
38
class ObservationSource(StrEnum):
    SCORE = "score"
    DERIVED = "derived"
    TASK_OBSERVATION = "task_observation"
    INSTRUMENTATION = "instrumentation"
    VARIANT = "variant"
    IMPORTED = "imported"

MetricPack

Bases: BaseModel

Source code in src/autobench/metrics/packs.py
 9
10
11
12
13
14
class MetricPack(BaseModel):
    id: str
    semantic_registry_delta: SemanticRegistry = Field(default_factory=SemanticRegistry)
    scorer_factories: dict[str, str] = Field(default_factory=dict)
    default_report_metrics: tuple[MetricAggregation, ...] = ()
    feedback_extractors: tuple[str, ...] = ()

MetricPackRegistry

Bases: BaseModel

Source code in src/autobench/metrics/packs.py
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
class MetricPackRegistry(BaseModel):
    packs: dict[str, MetricPack] = Field(default_factory=dict)

    def register(self, pack: MetricPack) -> None:
        self.packs[pack.id] = pack

    def get(self, pack_id: str) -> MetricPack | None:
        return self.packs.get(pack_id)

    def require(self, pack_id: str) -> MetricPack:
        pack = self.get(pack_id)
        if pack is None:
            raise KeyError(f"Unknown metric pack: {pack_id}")
        return pack

    def names(self) -> tuple[str, ...]:
        return tuple(sorted(self.packs))

    def semantic_registry_for(self, pack_ids: list[str]) -> SemanticRegistry:
        merged = SemanticRegistry()
        for pack_id in pack_ids:
            pack = self.require(pack_id)
            merged.types.update(pack.semantic_registry_delta.types)
            merged.aliases.update(pack.semantic_registry_delta.aliases)
        return merged

ProjectedObservation

Bases: BaseModel

Source code in src/autobench/metrics/projection.py
32
33
34
35
36
class ProjectedObservation(BaseModel):
    key: ProjectionKey
    observation: Observation
    candidates: list[Observation] = Field(default_factory=list)
    ambiguous: bool = False

ProjectionKey

Bases: BaseModel

Source code in src/autobench/metrics/projection.py
21
22
23
24
25
26
27
28
29
class ProjectionKey(BaseModel):
    semantic_type: str | None
    name: str
    role: str | None
    case_id: str | None
    variant_id: str | None
    span_id: str | None = None
    measurement_scope: str | None = None
    logical_operation_id: str | None = None

ObservationQuery

Bases: BaseModel

Source code in src/autobench/metrics/query.py
 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
class ObservationQuery(BaseModel):
    model_config = ConfigDict(arbitrary_types_allowed=True)

    observations: list[Observation] = Field(default_factory=list)
    registry: SemanticRegistry = Field(
        default_factory=lambda: DEFAULT_SEMANTIC_REGISTRY.model_copy(deep=True)
    )

    def all(
        self,
        *,
        projected: bool = False,
    ) -> list[Observation]:
        if not projected:
            return list(self.observations)
        return [
            item.observation
            for item in project_observations(self.observations, registry=self.registry)
        ]

    def exact(
        self,
        semantic_type: str,
        *,
        kind: ObservationKind | tuple[ObservationKind, ...] | None = None,
        source: ObservationSource | str | None = None,
        projected: bool = True,
    ) -> list[Observation]:
        normalized = self.registry.normalize(semantic_type)
        return [
            observation
            for observation in self._iter(projected=projected)
            if observation.normalized_semantic_type(self.registry) == normalized
            and _kind_matches(observation, kind)
            and _source_matches(observation, source)
        ]

    def related(
        self,
        semantic_type: str,
        *,
        kind: ObservationKind | tuple[ObservationKind, ...] | None = None,
        source: ObservationSource | str | None = None,
        projected: bool = True,
    ) -> list[Observation]:
        return [
            observation
            for observation in self._iter(projected=projected)
            if self.registry.is_a(observation.semantic_type, semantic_type)
            and _kind_matches(observation, kind)
            and _source_matches(observation, source)
        ]

    def first_exact(
        self,
        semantic_type: str,
        *,
        kind: ObservationKind | tuple[ObservationKind, ...] | None = None,
        source: ObservationSource | str | None = None,
        projected: bool = True,
    ) -> Observation | None:
        matches = self.exact(
            semantic_type,
            kind=kind,
            source=source,
            projected=projected,
        )
        return _preferred(matches)

    def first_related(
        self,
        semantic_type: str,
        *,
        kind: ObservationKind | tuple[ObservationKind, ...] | None = None,
        source: ObservationSource | str | None = None,
        projected: bool = True,
    ) -> Observation | None:
        matches = self.related(
            semantic_type,
            kind=kind,
            source=source,
            projected=projected,
        )
        return _preferred(matches)

    def values(
        self,
        semantic_type: str,
        *,
        related: bool = False,
        kind: ObservationKind | tuple[ObservationKind, ...] | None = None,
        source: ObservationSource | str | None = None,
        projected: bool = True,
    ) -> list[Any]:
        selector = self.related if related else self.exact
        return [
            observation.value
            for observation in selector(
                semantic_type,
                kind=kind,
                source=source,
                projected=projected,
            )
        ]

    def _iter(self, *, projected: bool) -> list[Observation]:
        return self.all(projected=projected)

Semantic

Source code in src/autobench/metrics/semantics.py
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
class Semantic:
    LLM_TOKENS_INPUT: Final[str] = "llm.tokens.input"
    LLM_TOKENS_OUTPUT: Final[str] = "llm.tokens.output"
    LLM_TOKENS_TOTAL: Final[str] = "llm.tokens.total"
    LLM_TOKENS_CACHED_INPUT: Final[str] = "llm.tokens.cached_input"
    LLM_TOKENS_CACHE_WRITE: Final[str] = "llm.tokens.cache_write"
    LLM_TOKENS_REASONING_OUTPUT: Final[str] = "llm.tokens.reasoning_output"
    LLM_MODEL_NAME: Final[str] = "llm.model.name"
    LLM_MODEL_REQUESTED: Final[str] = "llm.model.requested"
    LLM_MODEL_RESPONSE: Final[str] = "llm.model.response"
    LLM_PROVIDER: Final[str] = "llm.provider"
    LLM_PROVIDER_NAME: Final[str] = "llm.provider.name"
    LLM_TEMPERATURE: Final[str] = "llm.temperature"
    LLM_OPTIMIZER_MODEL: Final[str] = "llm.optimizer.model"
    LLM_STUDENT_MODEL: Final[str] = "llm.student.model"
    LLM_REQUEST_COUNT: Final[str] = "llm.request.count"
    MONEY_COST: Final[str] = "money.cost"
    OPTIMIZATION_COST: Final[str] = "optimization.cost"
    SERVING_COST: Final[str] = "serving.cost"
    LIFETIME_COST: Final[str] = "lifetime.cost"
    TIME_LATENCY: Final[str] = "time.latency"
    TIME_FIRST_CHUNK: Final[str] = "time.first_chunk"
    TIME_CRITICAL_PATH: Final[str] = "time.critical_path"
    HTTP_REQUEST_METHOD: Final[str] = "http.request.method"
    HTTP_REQUEST_SCHEME: Final[str] = "http.request.scheme"
    HTTP_REQUEST_HOST: Final[str] = "http.request.host"
    HTTP_REQUEST_PORT: Final[str] = "http.request.port"
    HTTP_REQUEST_PATH: Final[str] = "http.request.path"
    HTTP_REQUEST_PATH_HASH: Final[str] = "http.request.path_hash"
    HTTP_REQUEST_HEADERS: Final[str] = "http.request.headers"
    HTTP_REQUEST_BODY_SIZE: Final[str] = "http.request.body.size"
    HTTP_RESPONSE_STATUS_CODE: Final[str] = "http.response.status_code"
    HTTP_RESPONSE_HEADERS: Final[str] = "http.response.headers"
    HTTP_RESPONSE_BODY_SIZE: Final[str] = "http.response.body.size"
    NETWORK_PROTOCOL_VERSION: Final[str] = "network.protocol.version"
    ERROR_TYPE: Final[str] = "error.type"
    RESULT_SUCCESS: Final[str] = "result.success"
    QUALITY_SCORE: Final[str] = "quality.score"
    QUALITY_CORRECTNESS: Final[str] = "quality.correctness"
    COVERAGE_RATIO: Final[str] = "coverage.ratio"
    AGENT_VERSION: Final[str] = "agent.version"
    AGENT_ID: Final[str] = "agent.id"
    AGENT_NAME: Final[str] = "agent.name"
    AGENT_ORCHESTRATION_QUALITY: Final[str] = "agent.orchestration.quality"
    AGENT_TOOL_NAME: Final[str] = "agent.tool.name"
    AGENT_TOOL_VERSION: Final[str] = "agent.tool.version"
    AGENT_TOOL_CALL_QUALITY: Final[str] = "agent.tool_call.quality"
    AGENT_SERVING_VOLUME: Final[str] = "agent.serving.volume"
    AGENT_TASK_COMPLETION: Final[str] = "agent.task.completion"
    AGENT_GOAL_ACCURACY: Final[str] = "agent.goal.accuracy"
    AGENT_PLAN_QUALITY: Final[str] = "agent.plan.quality"
    AGENT_PLAN_ADHERENCE: Final[str] = "agent.plan.adherence"
    AGENT_STEP_EFFICIENCY: Final[str] = "agent.step.efficiency"
    AGENT_TOOL_SELECTION_CORRECTNESS: Final[str] = "agent.tool.selection.correctness"
    AGENT_TOOL_ARGUMENT_CORRECTNESS: Final[str] = "agent.tool.argument.correctness"
    AGENT_TOOL_SEQUENCE_CORRECTNESS: Final[str] = "agent.tool.sequence.correctness"
    AGENT_OUTPUT_CORRECTNESS: Final[str] = "agent.output.correctness"
    AGENT_OUTPUT_STRUCTURE_VALIDITY: Final[str] = "agent.output.structure.validity"
    PROMPT_VERSION: Final[str] = "prompt.version"
    DATASET_VERSION: Final[str] = "dataset.version"
    TOOL_NAME: Final[str] = "tool.name"
    TOOL_TYPE: Final[str] = "tool.type"
    TOOL_VERSION: Final[str] = "tool.version"
    TOOL_DEFINITIONS: Final[str] = "tool.definitions"
    TOOL_CALL_ID: Final[str] = "tool.call.id"
    TOOL_CALL_ARGUMENTS: Final[str] = "tool.call.arguments"
    TOOL_CALL_RESULT: Final[str] = "tool.call.result"
    TOOL_CALL_QUALITY: Final[str] = "tool.call.quality"
    WORKFLOW_NAME: Final[str] = "workflow.name"
    CONVERSATION_ID: Final[str] = "conversation.id"
    RETRIEVAL_QUERY: Final[str] = "retrieval.query"
    RETRIEVAL_DOCUMENTS: Final[str] = "retrieval.documents"
    RETRIEVAL_DOCUMENTS_COUNT: Final[str] = "retrieval.documents.count"
    EVALUATION_NAME: Final[str] = "evaluation.name"
    EVALUATION_SCORE: Final[str] = "evaluation.score"
    EVALUATION_LABEL: Final[str] = "evaluation.label"
    EVALUATION_EXPLANATION: Final[str] = "evaluation.explanation"
    MESSAGE_INPUT: Final[str] = "message.input"
    MESSAGE_OUTPUT: Final[str] = "message.output"
    PROMPT_SYSTEM: Final[str] = "prompt.system"
    ARTIFACT_CONTENT: Final[str] = "artifact.content"
    OPERATION_NAME: Final[str] = "operation.name"
    OPERATION_INPUT: Final[str] = "operation.input"
    OPERATION_OUTPUT: Final[str] = "operation.output"
    STREAM_FIRST_CHUNK: Final[str] = "stream.first_chunk"
    STREAM_COMPLETED: Final[str] = "stream.completed"
    STREAM_PARTIAL: Final[str] = "stream.partial"
    STREAM_FAILED: Final[str] = "stream.failed"
    OPERATION_RETRY: Final[str] = "operation.retry"
    OPERATION_REPAIR: Final[str] = "operation.repair"
    OPERATION_DEFERRED: Final[str] = "operation.deferred"
    OPERATION_DEFERRED_RESOLVED: Final[str] = "operation.deferred.resolved"
    VALIDATION_FAILURE: Final[str] = "validation.failure"
    APPROVAL_REQUESTED: Final[str] = "approval.requested"
    TOOL_CALL_REQUESTED: Final[str] = "tool.call.requested"
    FACTOR_VALUE: Final[str] = "factor.value"
    EVENT_OCCURRENCE: Final[str] = "event.occurrence"
    DIAGNOSTIC_EVENT: Final[str] = "diagnostic.event"
    ERROR_EXCEPTION: Final[str] = "error.exception"
    OPERATION_COUNT: Final[str] = "operation.count"
    OPERATION_DEPTH_MAX: Final[str] = "operation.depth.max"
    OPERATION_FAN_OUT_MAX: Final[str] = "operation.fan_out.max"
    OPERATION_INCOMPLETE_COUNT: Final[str] = "operation.incomplete.count"
    OPERATION_PARALLELISM: Final[str] = "operation.parallelism"
    OPERATION_RETRY_COUNT: Final[str] = "operation.retry.count"
    OPERATION_RETRY_RECOVERED_COUNT: Final[str] = "operation.retry.recovered.count"
    OPERATION_FIRST_ATTEMPT_SUCCESS: Final[str] = "operation.first_attempt.success"
    VALIDATION_COUNT: Final[str] = "validation.count"
    VALIDATION_FAILURE_COUNT: Final[str] = "validation.failure.count"
    VALIDATION_FAILURE_RATE: Final[str] = "validation.failure.rate"
    APPROVAL_COUNT: Final[str] = "approval.count"
    APPROVAL_WAIT: Final[str] = "approval.wait"
    TOOL_CALL_COUNT: Final[str] = "tool.call.count"
    TOOL_CALL_SUCCESS_COUNT: Final[str] = "tool.call.success.count"
    TOOL_CALL_FAILURE_COUNT: Final[str] = "tool.call.failure.count"
    TOOL_CALL_ARGUMENTS_PRESENT_COUNT: Final[str] = "tool.call.arguments.present.count"
    ARTIFACT_REFERENCE_COUNT: Final[str] = "artifact.reference.count"
    ASSET_REFERENCE_COUNT: Final[str] = "asset.reference.count"
    MESSAGE_INPUT_COUNT: Final[str] = "message.input.count"
    MESSAGE_OUTPUT_COUNT: Final[str] = "message.output.count"
    MESSAGE_GROWTH: Final[str] = "message.growth"

SemanticAggregation

Bases: StrEnum

Source code in src/autobench/metrics/semantics.py
355
356
357
358
359
360
class SemanticAggregation(StrEnum):
    NONE = "none"
    SUM = "sum"
    MEAN = "mean"
    LATEST = "latest"
    ANY = "any"

SemanticCardinality

Bases: StrEnum

Source code in src/autobench/metrics/semantics.py
348
349
350
351
352
class SemanticCardinality(StrEnum):
    LOW = "low"
    MEDIUM = "medium"
    HIGH = "high"
    UNBOUNDED = "unbounded"

SemanticPrivacy

Bases: StrEnum

Source code in src/autobench/metrics/semantics.py
341
342
343
344
345
class SemanticPrivacy(StrEnum):
    PUBLIC = "public"
    INTERNAL = "internal"
    SENSITIVE = "sensitive"
    SECRET = "secret"

SemanticRegistry

Bases: BaseModel

Source code in src/autobench/metrics/semantics.py
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
class SemanticRegistry(BaseModel):
    version: int = 1
    types: dict[str, SemanticTypeInfo] = Field(default_factory=dict)
    aliases: dict[str, str] = Field(default_factory=dict)

    @classmethod
    def with_defaults(cls) -> SemanticRegistry:
        types = {
            Semantic.LLM_TOKENS_INPUT: SemanticTypeInfo(
                id=Semantic.LLM_TOKENS_INPUT,
                description="Total input tokens reported for one model operation.",
                unit="tokens",
                value_shape="integer",
                stability=SemanticStability.STABLE,
                privacy=SemanticPrivacy.INTERNAL,
                cardinality=SemanticCardinality.LOW,
                aggregation=SemanticAggregation.SUM,
            ),
            Semantic.LLM_TOKENS_OUTPUT: SemanticTypeInfo(
                id=Semantic.LLM_TOKENS_OUTPUT,
                description="Total output tokens reported for one model operation.",
                unit="tokens",
                value_shape="integer",
                stability=SemanticStability.STABLE,
                privacy=SemanticPrivacy.INTERNAL,
                cardinality=SemanticCardinality.LOW,
                aggregation=SemanticAggregation.SUM,
            ),
            Semantic.LLM_TOKENS_TOTAL: SemanticTypeInfo(
                id=Semantic.LLM_TOKENS_TOTAL,
                description="Provider-reported total tokens when available.",
                unit="tokens",
                value_shape="integer",
                stability=SemanticStability.STABLE,
                privacy=SemanticPrivacy.INTERNAL,
                cardinality=SemanticCardinality.LOW,
                aggregation=SemanticAggregation.SUM,
            ),
            Semantic.LLM_TOKENS_CACHED_INPUT: SemanticTypeInfo(
                id=Semantic.LLM_TOKENS_CACHED_INPUT,
                parent=Semantic.LLM_TOKENS_INPUT,
                description="Input tokens read from a provider-managed cache.",
                unit="tokens",
                value_shape="integer",
                stability=SemanticStability.EVOLVING,
                privacy=SemanticPrivacy.INTERNAL,
                cardinality=SemanticCardinality.LOW,
                aggregation=SemanticAggregation.SUM,
            ),
            Semantic.LLM_TOKENS_CACHE_WRITE: SemanticTypeInfo(
                id=Semantic.LLM_TOKENS_CACHE_WRITE,
                parent=Semantic.LLM_TOKENS_INPUT,
                description="Input tokens written to a provider-managed cache.",
                unit="tokens",
                value_shape="integer",
                stability=SemanticStability.EVOLVING,
                privacy=SemanticPrivacy.INTERNAL,
                cardinality=SemanticCardinality.LOW,
                aggregation=SemanticAggregation.SUM,
            ),
            Semantic.LLM_TOKENS_REASONING_OUTPUT: SemanticTypeInfo(
                id=Semantic.LLM_TOKENS_REASONING_OUTPUT,
                parent=Semantic.LLM_TOKENS_OUTPUT,
                description="Output tokens used for provider-reported reasoning.",
                unit="tokens",
                value_shape="integer",
                stability=SemanticStability.EVOLVING,
                privacy=SemanticPrivacy.INTERNAL,
                cardinality=SemanticCardinality.LOW,
                aggregation=SemanticAggregation.SUM,
            ),
            Semantic.LLM_MODEL_NAME: SemanticTypeInfo(
                id=Semantic.LLM_MODEL_NAME,
                description="Model identity when request and response roles are not distinguished.",
                value_shape="string",
                stability=SemanticStability.STABLE,
                privacy=SemanticPrivacy.PUBLIC,
                cardinality=SemanticCardinality.MEDIUM,
                aggregation=SemanticAggregation.LATEST,
            ),
            Semantic.LLM_MODEL_REQUESTED: SemanticTypeInfo(
                id=Semantic.LLM_MODEL_REQUESTED,
                parent=Semantic.LLM_MODEL_NAME,
                description="Model requested by the caller before provider routing.",
                value_shape="string",
                stability=SemanticStability.STABLE,
                privacy=SemanticPrivacy.PUBLIC,
                cardinality=SemanticCardinality.MEDIUM,
                aggregation=SemanticAggregation.LATEST,
            ),
            Semantic.LLM_MODEL_RESPONSE: SemanticTypeInfo(
                id=Semantic.LLM_MODEL_RESPONSE,
                parent=Semantic.LLM_MODEL_NAME,
                description="Model identity reported by the serving response.",
                value_shape="string",
                stability=SemanticStability.STABLE,
                privacy=SemanticPrivacy.PUBLIC,
                cardinality=SemanticCardinality.MEDIUM,
                aggregation=SemanticAggregation.LATEST,
            ),
            Semantic.LLM_PROVIDER: SemanticTypeInfo(
                id=Semantic.LLM_PROVIDER,
                parent=Semantic.LLM_PROVIDER_NAME,
                description="Deprecated provider identity semantic.",
                value_shape="string",
                deprecated=True,
            ),
            Semantic.LLM_PROVIDER_NAME: SemanticTypeInfo(
                id=Semantic.LLM_PROVIDER_NAME,
                description="Provider or serving platform identity.",
                value_shape="string",
                stability=SemanticStability.STABLE,
                privacy=SemanticPrivacy.PUBLIC,
                cardinality=SemanticCardinality.LOW,
                aggregation=SemanticAggregation.LATEST,
            ),
            Semantic.LLM_TEMPERATURE: SemanticTypeInfo(
                id=Semantic.LLM_TEMPERATURE,
                value_shape="number",
            ),
            Semantic.LLM_OPTIMIZER_MODEL: SemanticTypeInfo(
                id=Semantic.LLM_OPTIMIZER_MODEL,
                parent=Semantic.LLM_MODEL_NAME,
                value_shape="string",
            ),
            Semantic.LLM_STUDENT_MODEL: SemanticTypeInfo(
                id=Semantic.LLM_STUDENT_MODEL,
                parent=Semantic.LLM_MODEL_NAME,
                value_shape="string",
            ),
            Semantic.LLM_REQUEST_COUNT: SemanticTypeInfo(
                id=Semantic.LLM_REQUEST_COUNT,
                description="Direct model request count at one accounting boundary.",
                unit="requests",
                value_shape="integer",
                stability=SemanticStability.STABLE,
                privacy=SemanticPrivacy.PUBLIC,
                cardinality=SemanticCardinality.LOW,
                aggregation=SemanticAggregation.SUM,
            ),
            Semantic.MONEY_COST: SemanticTypeInfo(
                id=Semantic.MONEY_COST,
                unit="usd",
                value_shape="number",
            ),
            Semantic.OPTIMIZATION_COST: SemanticTypeInfo(
                id=Semantic.OPTIMIZATION_COST,
                parent=Semantic.MONEY_COST,
                unit="usd",
                value_shape="number",
            ),
            Semantic.SERVING_COST: SemanticTypeInfo(
                id=Semantic.SERVING_COST,
                parent=Semantic.MONEY_COST,
                unit="usd",
                value_shape="number",
            ),
            Semantic.LIFETIME_COST: SemanticTypeInfo(
                id=Semantic.LIFETIME_COST,
                parent=Semantic.MONEY_COST,
                unit="usd",
                value_shape="number",
            ),
            Semantic.TIME_LATENCY: SemanticTypeInfo(
                id=Semantic.TIME_LATENCY,
                description="Elapsed operation duration.",
                unit="s",
                value_shape="number",
                stability=SemanticStability.STABLE,
                privacy=SemanticPrivacy.PUBLIC,
                cardinality=SemanticCardinality.LOW,
                aggregation=SemanticAggregation.MEAN,
            ),
            Semantic.TIME_FIRST_CHUNK: SemanticTypeInfo(
                id=Semantic.TIME_FIRST_CHUNK,
                parent=Semantic.TIME_LATENCY,
                description="Elapsed time until the first streamed response chunk.",
                unit="s",
                value_shape="number",
                stability=SemanticStability.EVOLVING,
                privacy=SemanticPrivacy.PUBLIC,
                cardinality=SemanticCardinality.LOW,
                aggregation=SemanticAggregation.MEAN,
            ),
            Semantic.TIME_CRITICAL_PATH: SemanticTypeInfo(
                id=Semantic.TIME_CRITICAL_PATH,
                parent=Semantic.TIME_LATENCY,
                description="Observed monotonic trace makespan across complete operations.",
                unit="s",
                value_shape="number",
                stability=SemanticStability.STABLE,
                privacy=SemanticPrivacy.PUBLIC,
                cardinality=SemanticCardinality.LOW,
                aggregation=SemanticAggregation.MEAN,
            ),
            Semantic.HTTP_REQUEST_METHOD: SemanticTypeInfo(
                id=Semantic.HTTP_REQUEST_METHOD,
                description="HTTP request method.",
                value_shape="string",
                stability=SemanticStability.STABLE,
                privacy=SemanticPrivacy.PUBLIC,
                cardinality=SemanticCardinality.LOW,
                aggregation=SemanticAggregation.LATEST,
            ),
            Semantic.HTTP_REQUEST_SCHEME: SemanticTypeInfo(
                id=Semantic.HTTP_REQUEST_SCHEME,
                description="HTTP request URL scheme.",
                value_shape="string",
                stability=SemanticStability.STABLE,
                privacy=SemanticPrivacy.PUBLIC,
                cardinality=SemanticCardinality.LOW,
                aggregation=SemanticAggregation.LATEST,
            ),
            Semantic.HTTP_REQUEST_HOST: SemanticTypeInfo(
                id=Semantic.HTTP_REQUEST_HOST,
                description="HTTP request host without user information.",
                value_shape="string",
                stability=SemanticStability.STABLE,
                privacy=SemanticPrivacy.INTERNAL,
                cardinality=SemanticCardinality.MEDIUM,
                aggregation=SemanticAggregation.LATEST,
            ),
            Semantic.HTTP_REQUEST_PORT: SemanticTypeInfo(
                id=Semantic.HTTP_REQUEST_PORT,
                description="HTTP request destination port.",
                value_shape="integer",
                stability=SemanticStability.STABLE,
                privacy=SemanticPrivacy.PUBLIC,
                cardinality=SemanticCardinality.LOW,
                aggregation=SemanticAggregation.LATEST,
            ),
            Semantic.HTTP_REQUEST_PATH: SemanticTypeInfo(
                id=Semantic.HTTP_REQUEST_PATH,
                description="HTTP path captured only by explicit policy; query is excluded.",
                value_shape="string",
                stability=SemanticStability.EVOLVING,
                privacy=SemanticPrivacy.SENSITIVE,
                cardinality=SemanticCardinality.UNBOUNDED,
                aggregation=SemanticAggregation.NONE,
            ),
            Semantic.HTTP_REQUEST_PATH_HASH: SemanticTypeInfo(
                id=Semantic.HTTP_REQUEST_PATH_HASH,
                description="SHA-256 of the query-free HTTP request path.",
                value_shape="string",
                stability=SemanticStability.EVOLVING,
                privacy=SemanticPrivacy.INTERNAL,
                cardinality=SemanticCardinality.HIGH,
                aggregation=SemanticAggregation.NONE,
            ),
            Semantic.HTTP_REQUEST_HEADERS: SemanticTypeInfo(
                id=Semantic.HTTP_REQUEST_HEADERS,
                description="Explicitly selected request headers with mandatory secret redaction.",
                value_shape="mapping",
                stability=SemanticStability.EVOLVING,
                privacy=SemanticPrivacy.SENSITIVE,
                cardinality=SemanticCardinality.HIGH,
                aggregation=SemanticAggregation.NONE,
            ),
            Semantic.HTTP_REQUEST_BODY_SIZE: SemanticTypeInfo(
                id=Semantic.HTTP_REQUEST_BODY_SIZE,
                description="HTTP request body size when available without consuming a stream.",
                unit="By",
                value_shape="integer",
                stability=SemanticStability.STABLE,
                privacy=SemanticPrivacy.PUBLIC,
                cardinality=SemanticCardinality.LOW,
                aggregation=SemanticAggregation.SUM,
            ),
            Semantic.HTTP_RESPONSE_STATUS_CODE: SemanticTypeInfo(
                id=Semantic.HTTP_RESPONSE_STATUS_CODE,
                description="HTTP response status code.",
                value_shape="integer",
                stability=SemanticStability.STABLE,
                privacy=SemanticPrivacy.PUBLIC,
                cardinality=SemanticCardinality.LOW,
                aggregation=SemanticAggregation.LATEST,
            ),
            Semantic.HTTP_RESPONSE_HEADERS: SemanticTypeInfo(
                id=Semantic.HTTP_RESPONSE_HEADERS,
                description="Explicitly selected response headers with mandatory secret redaction.",
                value_shape="mapping",
                stability=SemanticStability.EVOLVING,
                privacy=SemanticPrivacy.SENSITIVE,
                cardinality=SemanticCardinality.HIGH,
                aggregation=SemanticAggregation.NONE,
            ),
            Semantic.HTTP_RESPONSE_BODY_SIZE: SemanticTypeInfo(
                id=Semantic.HTTP_RESPONSE_BODY_SIZE,
                description="Bytes consumed from an HTTP response body.",
                unit="By",
                value_shape="integer",
                stability=SemanticStability.STABLE,
                privacy=SemanticPrivacy.PUBLIC,
                cardinality=SemanticCardinality.LOW,
                aggregation=SemanticAggregation.SUM,
            ),
            Semantic.NETWORK_PROTOCOL_VERSION: SemanticTypeInfo(
                id=Semantic.NETWORK_PROTOCOL_VERSION,
                description="Transport-reported network protocol version.",
                value_shape="string",
                stability=SemanticStability.EVOLVING,
                privacy=SemanticPrivacy.PUBLIC,
                cardinality=SemanticCardinality.LOW,
                aggregation=SemanticAggregation.LATEST,
            ),
            Semantic.ERROR_TYPE: SemanticTypeInfo(
                id=Semantic.ERROR_TYPE,
                description="Exception or error type without an error message payload.",
                value_shape="string",
                stability=SemanticStability.STABLE,
                privacy=SemanticPrivacy.PUBLIC,
                cardinality=SemanticCardinality.MEDIUM,
                aggregation=SemanticAggregation.LATEST,
            ),
            Semantic.RESULT_SUCCESS: SemanticTypeInfo(
                id=Semantic.RESULT_SUCCESS,
                value_shape="boolean",
            ),
            Semantic.QUALITY_SCORE: SemanticTypeInfo(
                id=Semantic.QUALITY_SCORE,
                value_shape="number",
            ),
            Semantic.QUALITY_CORRECTNESS: SemanticTypeInfo(
                id=Semantic.QUALITY_CORRECTNESS,
                parent=Semantic.QUALITY_SCORE,
                value_shape="number",
            ),
            Semantic.COVERAGE_RATIO: SemanticTypeInfo(
                id=Semantic.COVERAGE_RATIO,
                value_shape="number",
            ),
            Semantic.AGENT_VERSION: SemanticTypeInfo(
                id=Semantic.AGENT_VERSION,
                value_shape="string",
            ),
            Semantic.AGENT_ID: SemanticTypeInfo(
                id=Semantic.AGENT_ID,
                description="Run-local or provider agent identifier.",
                value_shape="string",
                stability=SemanticStability.EVOLVING,
                privacy=SemanticPrivacy.INTERNAL,
                cardinality=SemanticCardinality.HIGH,
                aggregation=SemanticAggregation.NONE,
            ),
            Semantic.AGENT_NAME: SemanticTypeInfo(
                id=Semantic.AGENT_NAME,
                description="Human-readable agent name.",
                value_shape="string",
                stability=SemanticStability.EVOLVING,
                privacy=SemanticPrivacy.PUBLIC,
                cardinality=SemanticCardinality.MEDIUM,
                aggregation=SemanticAggregation.LATEST,
            ),
            Semantic.AGENT_TASK_COMPLETION: SemanticTypeInfo(
                id=Semantic.AGENT_TASK_COMPLETION,
                parent=Semantic.RESULT_SUCCESS,
                value_shape="boolean",
            ),
            Semantic.AGENT_GOAL_ACCURACY: SemanticTypeInfo(
                id=Semantic.AGENT_GOAL_ACCURACY,
                parent=Semantic.QUALITY_SCORE,
                value_shape="number",
            ),
            Semantic.AGENT_PLAN_QUALITY: SemanticTypeInfo(
                id=Semantic.AGENT_PLAN_QUALITY,
                parent=Semantic.QUALITY_SCORE,
                value_shape="number",
            ),
            Semantic.AGENT_PLAN_ADHERENCE: SemanticTypeInfo(
                id=Semantic.AGENT_PLAN_ADHERENCE,
                parent=Semantic.QUALITY_SCORE,
                value_shape="number",
            ),
            Semantic.AGENT_STEP_EFFICIENCY: SemanticTypeInfo(
                id=Semantic.AGENT_STEP_EFFICIENCY,
                parent=Semantic.TIME_LATENCY,
                value_shape="number",
            ),
            Semantic.AGENT_ORCHESTRATION_QUALITY: SemanticTypeInfo(
                id=Semantic.AGENT_ORCHESTRATION_QUALITY,
                parent=Semantic.QUALITY_SCORE,
                value_shape="number",
            ),
            Semantic.AGENT_TOOL_NAME: SemanticTypeInfo(
                id=Semantic.AGENT_TOOL_NAME,
                value_shape="string",
            ),
            Semantic.AGENT_TOOL_VERSION: SemanticTypeInfo(
                id=Semantic.AGENT_TOOL_VERSION,
                value_shape="string",
            ),
            Semantic.AGENT_TOOL_SELECTION_CORRECTNESS: SemanticTypeInfo(
                id=Semantic.AGENT_TOOL_SELECTION_CORRECTNESS,
                parent=Semantic.QUALITY_CORRECTNESS,
                value_shape="number",
            ),
            Semantic.AGENT_TOOL_ARGUMENT_CORRECTNESS: SemanticTypeInfo(
                id=Semantic.AGENT_TOOL_ARGUMENT_CORRECTNESS,
                parent=Semantic.QUALITY_CORRECTNESS,
                value_shape="number",
            ),
            Semantic.AGENT_TOOL_SEQUENCE_CORRECTNESS: SemanticTypeInfo(
                id=Semantic.AGENT_TOOL_SEQUENCE_CORRECTNESS,
                parent=Semantic.QUALITY_CORRECTNESS,
                value_shape="number",
            ),
            Semantic.AGENT_TOOL_CALL_QUALITY: SemanticTypeInfo(
                id=Semantic.AGENT_TOOL_CALL_QUALITY,
                parent=Semantic.QUALITY_SCORE,
                value_shape="number",
            ),
            Semantic.AGENT_SERVING_VOLUME: SemanticTypeInfo(
                id=Semantic.AGENT_SERVING_VOLUME,
                value_shape="integer",
            ),
            Semantic.AGENT_OUTPUT_CORRECTNESS: SemanticTypeInfo(
                id=Semantic.AGENT_OUTPUT_CORRECTNESS,
                parent=Semantic.QUALITY_CORRECTNESS,
                value_shape="number",
            ),
            Semantic.AGENT_OUTPUT_STRUCTURE_VALIDITY: SemanticTypeInfo(
                id=Semantic.AGENT_OUTPUT_STRUCTURE_VALIDITY,
                parent=Semantic.QUALITY_CORRECTNESS,
                value_shape="boolean",
            ),
            Semantic.PROMPT_VERSION: SemanticTypeInfo(
                id=Semantic.PROMPT_VERSION,
                value_shape="string",
            ),
            Semantic.DATASET_VERSION: SemanticTypeInfo(
                id=Semantic.DATASET_VERSION,
                value_shape="string",
            ),
            Semantic.TOOL_NAME: SemanticTypeInfo(
                id=Semantic.TOOL_NAME,
                description="Canonical tool name.",
                value_shape="string",
                stability=SemanticStability.STABLE,
                privacy=SemanticPrivacy.PUBLIC,
                cardinality=SemanticCardinality.MEDIUM,
                aggregation=SemanticAggregation.LATEST,
            ),
            Semantic.TOOL_TYPE: SemanticTypeInfo(
                id=Semantic.TOOL_TYPE,
                description="Tool execution category such as function or datastore.",
                value_shape="string",
                stability=SemanticStability.EVOLVING,
                privacy=SemanticPrivacy.PUBLIC,
                cardinality=SemanticCardinality.LOW,
                aggregation=SemanticAggregation.LATEST,
            ),
            Semantic.TOOL_VERSION: SemanticTypeInfo(
                id=Semantic.TOOL_VERSION,
                description="Tracked tool version.",
                value_shape="string",
                stability=SemanticStability.STABLE,
                privacy=SemanticPrivacy.PUBLIC,
                cardinality=SemanticCardinality.MEDIUM,
                aggregation=SemanticAggregation.LATEST,
            ),
            Semantic.TOOL_DEFINITIONS: SemanticTypeInfo(
                id=Semantic.TOOL_DEFINITIONS,
                description="Definitions made available to a model or agent.",
                value_shape="array",
                stability=SemanticStability.EVOLVING,
                privacy=SemanticPrivacy.SENSITIVE,
                cardinality=SemanticCardinality.HIGH,
                aggregation=SemanticAggregation.NONE,
            ),
            Semantic.TOOL_CALL_ID: SemanticTypeInfo(
                id=Semantic.TOOL_CALL_ID,
                description="Run-local tool call correlation identifier.",
                value_shape="string",
                stability=SemanticStability.STABLE,
                privacy=SemanticPrivacy.INTERNAL,
                cardinality=SemanticCardinality.HIGH,
                aggregation=SemanticAggregation.NONE,
            ),
            Semantic.TOOL_CALL_ARGUMENTS: SemanticTypeInfo(
                id=Semantic.TOOL_CALL_ARGUMENTS,
                description="Arguments supplied to one tool call.",
                value_shape="mapping",
                stability=SemanticStability.STABLE,
                privacy=SemanticPrivacy.SENSITIVE,
                cardinality=SemanticCardinality.UNBOUNDED,
                aggregation=SemanticAggregation.NONE,
            ),
            Semantic.TOOL_CALL_RESULT: SemanticTypeInfo(
                id=Semantic.TOOL_CALL_RESULT,
                description="Result returned by one tool call.",
                value_shape="any",
                stability=SemanticStability.STABLE,
                privacy=SemanticPrivacy.SENSITIVE,
                cardinality=SemanticCardinality.UNBOUNDED,
                aggregation=SemanticAggregation.NONE,
            ),
            Semantic.TOOL_CALL_QUALITY: SemanticTypeInfo(
                id=Semantic.TOOL_CALL_QUALITY,
                parent=Semantic.QUALITY_SCORE,
                description="Quality score assigned to one tool call.",
                value_shape="number",
                stability=SemanticStability.STABLE,
                privacy=SemanticPrivacy.INTERNAL,
                cardinality=SemanticCardinality.LOW,
                aggregation=SemanticAggregation.MEAN,
            ),
            Semantic.WORKFLOW_NAME: SemanticTypeInfo(
                id=Semantic.WORKFLOW_NAME,
                description="Human-readable workflow name.",
                value_shape="string",
                stability=SemanticStability.EVOLVING,
                privacy=SemanticPrivacy.PUBLIC,
                cardinality=SemanticCardinality.MEDIUM,
                aggregation=SemanticAggregation.LATEST,
            ),
            Semantic.CONVERSATION_ID: SemanticTypeInfo(
                id=Semantic.CONVERSATION_ID,
                description="Run-local conversation or thread correlation identifier.",
                value_shape="string",
                stability=SemanticStability.EVOLVING,
                privacy=SemanticPrivacy.INTERNAL,
                cardinality=SemanticCardinality.HIGH,
                aggregation=SemanticAggregation.NONE,
            ),
            Semantic.RETRIEVAL_QUERY: SemanticTypeInfo(
                id=Semantic.RETRIEVAL_QUERY,
                description="Query supplied to a retrieval operation.",
                value_shape="string",
                stability=SemanticStability.EVOLVING,
                privacy=SemanticPrivacy.SENSITIVE,
                cardinality=SemanticCardinality.UNBOUNDED,
                aggregation=SemanticAggregation.NONE,
            ),
            Semantic.RETRIEVAL_DOCUMENTS: SemanticTypeInfo(
                id=Semantic.RETRIEVAL_DOCUMENTS,
                description="Documents returned by a retrieval operation.",
                value_shape="array",
                stability=SemanticStability.EVOLVING,
                privacy=SemanticPrivacy.SENSITIVE,
                cardinality=SemanticCardinality.UNBOUNDED,
                aggregation=SemanticAggregation.NONE,
            ),
            Semantic.RETRIEVAL_DOCUMENTS_COUNT: SemanticTypeInfo(
                id=Semantic.RETRIEVAL_DOCUMENTS_COUNT,
                description="Number of documents returned by retrieval.",
                value_shape="integer",
                stability=SemanticStability.EVOLVING,
                privacy=SemanticPrivacy.PUBLIC,
                cardinality=SemanticCardinality.LOW,
                aggregation=SemanticAggregation.SUM,
            ),
            Semantic.EVALUATION_NAME: SemanticTypeInfo(
                id=Semantic.EVALUATION_NAME,
                description="Evaluator or metric name.",
                value_shape="string",
                stability=SemanticStability.EVOLVING,
                privacy=SemanticPrivacy.PUBLIC,
                cardinality=SemanticCardinality.MEDIUM,
                aggregation=SemanticAggregation.LATEST,
            ),
            Semantic.EVALUATION_SCORE: SemanticTypeInfo(
                id=Semantic.EVALUATION_SCORE,
                parent=Semantic.QUALITY_SCORE,
                description="Numeric evaluator result.",
                value_shape="number",
                stability=SemanticStability.EVOLVING,
                privacy=SemanticPrivacy.INTERNAL,
                cardinality=SemanticCardinality.LOW,
                aggregation=SemanticAggregation.MEAN,
            ),
            Semantic.EVALUATION_LABEL: SemanticTypeInfo(
                id=Semantic.EVALUATION_LABEL,
                description="Human-readable evaluator result label.",
                value_shape="string",
                stability=SemanticStability.EVOLVING,
                privacy=SemanticPrivacy.INTERNAL,
                cardinality=SemanticCardinality.LOW,
                aggregation=SemanticAggregation.LATEST,
            ),
            Semantic.EVALUATION_EXPLANATION: SemanticTypeInfo(
                id=Semantic.EVALUATION_EXPLANATION,
                description="Evaluator explanation or feedback.",
                value_shape="string",
                stability=SemanticStability.EVOLVING,
                privacy=SemanticPrivacy.SENSITIVE,
                cardinality=SemanticCardinality.UNBOUNDED,
                aggregation=SemanticAggregation.NONE,
            ),
            Semantic.MESSAGE_INPUT: SemanticTypeInfo(
                id=Semantic.MESSAGE_INPUT,
                description="Messages supplied to a model operation.",
                value_shape="array",
                stability=SemanticStability.EVOLVING,
                privacy=SemanticPrivacy.SENSITIVE,
                cardinality=SemanticCardinality.UNBOUNDED,
                aggregation=SemanticAggregation.NONE,
            ),
            Semantic.MESSAGE_OUTPUT: SemanticTypeInfo(
                id=Semantic.MESSAGE_OUTPUT,
                description="Messages returned by a model operation.",
                value_shape="array",
                stability=SemanticStability.EVOLVING,
                privacy=SemanticPrivacy.SENSITIVE,
                cardinality=SemanticCardinality.UNBOUNDED,
                aggregation=SemanticAggregation.NONE,
            ),
            Semantic.PROMPT_SYSTEM: SemanticTypeInfo(
                id=Semantic.PROMPT_SYSTEM,
                description="System instructions supplied to a model or agent.",
                value_shape="any",
                stability=SemanticStability.EVOLVING,
                privacy=SemanticPrivacy.SENSITIVE,
                cardinality=SemanticCardinality.UNBOUNDED,
                aggregation=SemanticAggregation.NONE,
            ),
            Semantic.ARTIFACT_CONTENT: SemanticTypeInfo(
                id=Semantic.ARTIFACT_CONTENT,
                description="Content retained as benchmark evidence.",
                value_shape="any",
                stability=SemanticStability.STABLE,
                privacy=SemanticPrivacy.SENSITIVE,
                cardinality=SemanticCardinality.UNBOUNDED,
                aggregation=SemanticAggregation.NONE,
            ),
            Semantic.OPERATION_NAME: SemanticTypeInfo(
                id=Semantic.OPERATION_NAME,
                description="Normalized runtime operation name.",
                value_shape="string",
                stability=SemanticStability.STABLE,
                privacy=SemanticPrivacy.PUBLIC,
                cardinality=SemanticCardinality.LOW,
                aggregation=SemanticAggregation.LATEST,
            ),
            Semantic.OPERATION_INPUT: SemanticTypeInfo(
                id=Semantic.OPERATION_INPUT,
                description="Input captured for a runtime operation.",
                value_shape="any",
                stability=SemanticStability.STABLE,
                privacy=SemanticPrivacy.SENSITIVE,
                cardinality=SemanticCardinality.UNBOUNDED,
                aggregation=SemanticAggregation.NONE,
            ),
            Semantic.OPERATION_OUTPUT: SemanticTypeInfo(
                id=Semantic.OPERATION_OUTPUT,
                description="Output captured for a runtime operation.",
                value_shape="any",
                stability=SemanticStability.STABLE,
                privacy=SemanticPrivacy.SENSITIVE,
                cardinality=SemanticCardinality.UNBOUNDED,
                aggregation=SemanticAggregation.NONE,
            ),
            Semantic.STREAM_FIRST_CHUNK: SemanticTypeInfo(
                id=Semantic.STREAM_FIRST_CHUNK,
                parent=Semantic.EVENT_OCCURRENCE,
                description="The first response chunk became available.",
                value_shape="event",
                stability=SemanticStability.EVOLVING,
                privacy=SemanticPrivacy.PUBLIC,
                cardinality=SemanticCardinality.HIGH,
                aggregation=SemanticAggregation.NONE,
            ),
            Semantic.STREAM_COMPLETED: SemanticTypeInfo(
                id=Semantic.STREAM_COMPLETED,
                parent=Semantic.EVENT_OCCURRENCE,
                description="A response stream completed normally.",
                value_shape="event",
                stability=SemanticStability.EVOLVING,
                privacy=SemanticPrivacy.PUBLIC,
                cardinality=SemanticCardinality.HIGH,
                aggregation=SemanticAggregation.NONE,
            ),
            Semantic.STREAM_PARTIAL: SemanticTypeInfo(
                id=Semantic.STREAM_PARTIAL,
                parent=Semantic.EVENT_OCCURRENCE,
                description="A response stream ended after producing partial evidence.",
                value_shape="event",
                stability=SemanticStability.EVOLVING,
                privacy=SemanticPrivacy.PUBLIC,
                cardinality=SemanticCardinality.HIGH,
                aggregation=SemanticAggregation.NONE,
            ),
            Semantic.STREAM_FAILED: SemanticTypeInfo(
                id=Semantic.STREAM_FAILED,
                parent=Semantic.EVENT_OCCURRENCE,
                description="A response stream failed before normal completion.",
                value_shape="event",
                stability=SemanticStability.EVOLVING,
                privacy=SemanticPrivacy.PUBLIC,
                cardinality=SemanticCardinality.HIGH,
                aggregation=SemanticAggregation.NONE,
            ),
            Semantic.OPERATION_RETRY: SemanticTypeInfo(
                id=Semantic.OPERATION_RETRY,
                parent=Semantic.EVENT_OCCURRENCE,
                description="An operation requested another attempt.",
                value_shape="event",
                stability=SemanticStability.STABLE,
                privacy=SemanticPrivacy.PUBLIC,
                cardinality=SemanticCardinality.HIGH,
                aggregation=SemanticAggregation.NONE,
            ),
            Semantic.OPERATION_REPAIR: SemanticTypeInfo(
                id=Semantic.OPERATION_REPAIR,
                parent=Semantic.OPERATION_RETRY,
                description="An operation requested a corrective attempt.",
                value_shape="event",
                stability=SemanticStability.EVOLVING,
                privacy=SemanticPrivacy.PUBLIC,
                cardinality=SemanticCardinality.HIGH,
                aggregation=SemanticAggregation.NONE,
            ),
            Semantic.OPERATION_DEFERRED: SemanticTypeInfo(
                id=Semantic.OPERATION_DEFERRED,
                parent=Semantic.EVENT_OCCURRENCE,
                description="An operation paused for external completion or approval.",
                value_shape="event",
                stability=SemanticStability.EVOLVING,
                privacy=SemanticPrivacy.PUBLIC,
                cardinality=SemanticCardinality.HIGH,
                aggregation=SemanticAggregation.NONE,
            ),
            Semantic.OPERATION_DEFERRED_RESOLVED: SemanticTypeInfo(
                id=Semantic.OPERATION_DEFERRED_RESOLVED,
                parent=Semantic.OPERATION_DEFERRED,
                description="A previously deferred operation received a result.",
                value_shape="event",
                stability=SemanticStability.EVOLVING,
                privacy=SemanticPrivacy.PUBLIC,
                cardinality=SemanticCardinality.HIGH,
                aggregation=SemanticAggregation.NONE,
            ),
            Semantic.VALIDATION_FAILURE: SemanticTypeInfo(
                id=Semantic.VALIDATION_FAILURE,
                parent=Semantic.EVENT_OCCURRENCE,
                description="Input, tool, or output validation rejected a value.",
                value_shape="event",
                stability=SemanticStability.STABLE,
                privacy=SemanticPrivacy.SENSITIVE,
                cardinality=SemanticCardinality.HIGH,
                aggregation=SemanticAggregation.NONE,
            ),
            Semantic.APPROVAL_REQUESTED: SemanticTypeInfo(
                id=Semantic.APPROVAL_REQUESTED,
                parent=Semantic.EVENT_OCCURRENCE,
                description="An operation requested external approval.",
                value_shape="event",
                stability=SemanticStability.EVOLVING,
                privacy=SemanticPrivacy.INTERNAL,
                cardinality=SemanticCardinality.HIGH,
                aggregation=SemanticAggregation.NONE,
            ),
            Semantic.TOOL_CALL_REQUESTED: SemanticTypeInfo(
                id=Semantic.TOOL_CALL_REQUESTED,
                parent=Semantic.EVENT_OCCURRENCE,
                description="A model or agent requested a tool call.",
                value_shape="event",
                stability=SemanticStability.STABLE,
                privacy=SemanticPrivacy.INTERNAL,
                cardinality=SemanticCardinality.HIGH,
                aggregation=SemanticAggregation.NONE,
            ),
            Semantic.FACTOR_VALUE: SemanticTypeInfo(
                id=Semantic.FACTOR_VALUE,
                description="Unclassified factor value that may influence an outcome.",
                value_shape="any",
                stability=SemanticStability.STABLE,
                privacy=SemanticPrivacy.INTERNAL,
                cardinality=SemanticCardinality.HIGH,
                aggregation=SemanticAggregation.NONE,
            ),
            Semantic.EVENT_OCCURRENCE: SemanticTypeInfo(
                id=Semantic.EVENT_OCCURRENCE,
                description="Unclassified runtime event occurrence.",
                value_shape="any",
                stability=SemanticStability.STABLE,
                privacy=SemanticPrivacy.INTERNAL,
                cardinality=SemanticCardinality.HIGH,
                aggregation=SemanticAggregation.NONE,
            ),
            Semantic.DIAGNOSTIC_EVENT: SemanticTypeInfo(
                id=Semantic.DIAGNOSTIC_EVENT,
                description="Diagnostic runtime event retained for analysis.",
                value_shape="any",
                stability=SemanticStability.STABLE,
                privacy=SemanticPrivacy.INTERNAL,
                cardinality=SemanticCardinality.HIGH,
                aggregation=SemanticAggregation.NONE,
            ),
            Semantic.ERROR_EXCEPTION: SemanticTypeInfo(
                id=Semantic.ERROR_EXCEPTION,
                description="Structured runtime exception evidence.",
                value_shape="mapping",
                stability=SemanticStability.STABLE,
                privacy=SemanticPrivacy.SENSITIVE,
                cardinality=SemanticCardinality.HIGH,
                aggregation=SemanticAggregation.NONE,
            ),
            Semantic.OPERATION_COUNT: SemanticTypeInfo(
                id=Semantic.OPERATION_COUNT,
                description="Number of materialized operations in a selected grouping.",
                unit="operations",
                value_shape="integer",
                stability=SemanticStability.STABLE,
                privacy=SemanticPrivacy.PUBLIC,
                cardinality=SemanticCardinality.LOW,
                aggregation=SemanticAggregation.SUM,
            ),
            Semantic.OPERATION_DEPTH_MAX: SemanticTypeInfo(
                id=Semantic.OPERATION_DEPTH_MAX,
                description="Maximum parent-child operation depth in a trace.",
                unit="levels",
                value_shape="integer",
                stability=SemanticStability.STABLE,
                privacy=SemanticPrivacy.PUBLIC,
                cardinality=SemanticCardinality.LOW,
                aggregation=SemanticAggregation.MEAN,
            ),
            Semantic.OPERATION_FAN_OUT_MAX: SemanticTypeInfo(
                id=Semantic.OPERATION_FAN_OUT_MAX,
                description="Maximum direct child and explicit fan-out count.",
                unit="operations",
                value_shape="integer",
                stability=SemanticStability.STABLE,
                privacy=SemanticPrivacy.PUBLIC,
                cardinality=SemanticCardinality.LOW,
                aggregation=SemanticAggregation.MEAN,
            ),
            Semantic.OPERATION_INCOMPLETE_COUNT: SemanticTypeInfo(
                id=Semantic.OPERATION_INCOMPLETE_COUNT,
                parent=Semantic.OPERATION_COUNT,
                description="Partial or abandoned operation count.",
                unit="operations",
                value_shape="integer",
                stability=SemanticStability.STABLE,
                privacy=SemanticPrivacy.PUBLIC,
                cardinality=SemanticCardinality.LOW,
                aggregation=SemanticAggregation.SUM,
            ),
            Semantic.OPERATION_PARALLELISM: SemanticTypeInfo(
                id=Semantic.OPERATION_PARALLELISM,
                description="Completed leaf work divided by observed trace makespan.",
                unit="ratio",
                value_shape="number",
                stability=SemanticStability.STABLE,
                privacy=SemanticPrivacy.PUBLIC,
                cardinality=SemanticCardinality.LOW,
                aggregation=SemanticAggregation.MEAN,
            ),
            Semantic.OPERATION_RETRY_COUNT: SemanticTypeInfo(
                id=Semantic.OPERATION_RETRY_COUNT,
                parent=Semantic.OPERATION_COUNT,
                description="Retry relationships observed in a trace.",
                unit="operations",
                value_shape="integer",
                stability=SemanticStability.STABLE,
                privacy=SemanticPrivacy.PUBLIC,
                cardinality=SemanticCardinality.LOW,
                aggregation=SemanticAggregation.SUM,
            ),
            Semantic.OPERATION_RETRY_RECOVERED_COUNT: SemanticTypeInfo(
                id=Semantic.OPERATION_RETRY_RECOVERED_COUNT,
                parent=Semantic.OPERATION_RETRY_COUNT,
                description="Retries that succeeded after a failed original attempt.",
                unit="operations",
                value_shape="integer",
                stability=SemanticStability.STABLE,
                privacy=SemanticPrivacy.PUBLIC,
                cardinality=SemanticCardinality.LOW,
                aggregation=SemanticAggregation.SUM,
            ),
            Semantic.OPERATION_FIRST_ATTEMPT_SUCCESS: SemanticTypeInfo(
                id=Semantic.OPERATION_FIRST_ATTEMPT_SUCCESS,
                parent=Semantic.RESULT_SUCCESS,
                description="Success ratio of original attempts in retry groups.",
                unit="ratio",
                value_shape="number",
                stability=SemanticStability.STABLE,
                privacy=SemanticPrivacy.PUBLIC,
                cardinality=SemanticCardinality.LOW,
                aggregation=SemanticAggregation.MEAN,
            ),
            Semantic.VALIDATION_COUNT: SemanticTypeInfo(
                id=Semantic.VALIDATION_COUNT,
                parent=Semantic.OPERATION_COUNT,
                unit="operations",
                value_shape="integer",
                aggregation=SemanticAggregation.SUM,
            ),
            Semantic.VALIDATION_FAILURE_COUNT: SemanticTypeInfo(
                id=Semantic.VALIDATION_FAILURE_COUNT,
                parent=Semantic.VALIDATION_COUNT,
                unit="operations",
                value_shape="integer",
                aggregation=SemanticAggregation.SUM,
            ),
            Semantic.VALIDATION_FAILURE_RATE: SemanticTypeInfo(
                id=Semantic.VALIDATION_FAILURE_RATE,
                parent=Semantic.QUALITY_SCORE,
                unit="ratio",
                value_shape="number",
                aggregation=SemanticAggregation.MEAN,
            ),
            Semantic.APPROVAL_COUNT: SemanticTypeInfo(
                id=Semantic.APPROVAL_COUNT,
                parent=Semantic.OPERATION_COUNT,
                unit="operations",
                value_shape="integer",
                aggregation=SemanticAggregation.SUM,
            ),
            Semantic.APPROVAL_WAIT: SemanticTypeInfo(
                id=Semantic.APPROVAL_WAIT,
                parent=Semantic.TIME_LATENCY,
                unit="s",
                value_shape="number",
                aggregation=SemanticAggregation.SUM,
            ),
            Semantic.TOOL_CALL_COUNT: SemanticTypeInfo(
                id=Semantic.TOOL_CALL_COUNT,
                parent=Semantic.OPERATION_COUNT,
                unit="operations",
                value_shape="integer",
                aggregation=SemanticAggregation.SUM,
            ),
            Semantic.TOOL_CALL_SUCCESS_COUNT: SemanticTypeInfo(
                id=Semantic.TOOL_CALL_SUCCESS_COUNT,
                parent=Semantic.TOOL_CALL_COUNT,
                unit="operations",
                value_shape="integer",
                aggregation=SemanticAggregation.SUM,
            ),
            Semantic.TOOL_CALL_FAILURE_COUNT: SemanticTypeInfo(
                id=Semantic.TOOL_CALL_FAILURE_COUNT,
                parent=Semantic.TOOL_CALL_COUNT,
                unit="operations",
                value_shape="integer",
                aggregation=SemanticAggregation.SUM,
            ),
            Semantic.TOOL_CALL_ARGUMENTS_PRESENT_COUNT: SemanticTypeInfo(
                id=Semantic.TOOL_CALL_ARGUMENTS_PRESENT_COUNT,
                parent=Semantic.TOOL_CALL_COUNT,
                unit="operations",
                value_shape="integer",
                aggregation=SemanticAggregation.SUM,
            ),
            Semantic.ARTIFACT_REFERENCE_COUNT: SemanticTypeInfo(
                id=Semantic.ARTIFACT_REFERENCE_COUNT,
                unit="references",
                value_shape="integer",
                aggregation=SemanticAggregation.SUM,
            ),
            Semantic.ASSET_REFERENCE_COUNT: SemanticTypeInfo(
                id=Semantic.ASSET_REFERENCE_COUNT,
                unit="references",
                value_shape="integer",
                aggregation=SemanticAggregation.SUM,
            ),
            Semantic.MESSAGE_INPUT_COUNT: SemanticTypeInfo(
                id=Semantic.MESSAGE_INPUT_COUNT,
                unit="messages",
                value_shape="integer",
                aggregation=SemanticAggregation.SUM,
            ),
            Semantic.MESSAGE_OUTPUT_COUNT: SemanticTypeInfo(
                id=Semantic.MESSAGE_OUTPUT_COUNT,
                unit="messages",
                value_shape="integer",
                aggregation=SemanticAggregation.SUM,
            ),
            Semantic.MESSAGE_GROWTH: SemanticTypeInfo(
                id=Semantic.MESSAGE_GROWTH,
                unit="messages",
                value_shape="integer",
                aggregation=SemanticAggregation.MEAN,
            ),
            "ai.codegen.spec_model": SemanticTypeInfo(
                id="ai.codegen.spec_model",
                parent=Semantic.LLM_MODEL_NAME,
                value_shape="string",
                tags={"role": "spec_generator"},
            ),
            "ai.codegen.exploration_model": SemanticTypeInfo(
                id="ai.codegen.exploration_model",
                parent=Semantic.LLM_MODEL_NAME,
                value_shape="string",
                tags={"role": "explorer"},
            ),
        }
        aliases = {
            "llm.requests": Semantic.LLM_REQUEST_COUNT,
            "quality.answer": Semantic.QUALITY_SCORE,
            "agent.tool_call.correctness": Semantic.AGENT_TOOL_CALL_QUALITY,
            "agent.task_completion": Semantic.AGENT_TASK_COMPLETION,
            "agent.goal_accuracy": Semantic.AGENT_GOAL_ACCURACY,
            "agent.tool.correctness": Semantic.AGENT_TOOL_SELECTION_CORRECTNESS,
            "agent.tool.args.correctness": Semantic.AGENT_TOOL_ARGUMENT_CORRECTNESS,
            "agent.output.valid": Semantic.AGENT_OUTPUT_STRUCTURE_VALIDITY,
            Semantic.LLM_PROVIDER: Semantic.LLM_PROVIDER_NAME,
            Semantic.AGENT_TOOL_NAME: Semantic.TOOL_NAME,
            Semantic.AGENT_TOOL_VERSION: Semantic.TOOL_VERSION,
            Semantic.AGENT_TOOL_CALL_QUALITY: Semantic.TOOL_CALL_QUALITY,
        }
        return cls(types=types, aliases=aliases)

    def info_for(self, semantic_type: str | None) -> SemanticTypeInfo | None:
        normalized = self.normalize(semantic_type)
        if normalized is None:
            return None
        return self.types.get(normalized)

    def normalize(self, semantic_type: str | None) -> str | None:
        if semantic_type is None:
            return None
        alias_target = self.aliases.get(semantic_type)
        if alias_target is not None:
            return alias_target
        info = self.types.get(semantic_type)
        if info is not None and info.deprecated and info.parent is not None:
            return str(info.parent)
        return semantic_type

    def parent_of(self, semantic_type: str | None) -> str | None:
        normalized = self.normalize(semantic_type)
        if normalized is None:
            return None
        info = self.types.get(normalized)
        if info is None or info.parent is None:
            return None
        return self.normalize(str(info.parent))

    def is_a(self, child: str | None, parent: str | None) -> bool:
        if child is None or parent is None:
            return False
        normalized_child = self.normalize(child)
        normalized_parent = self.normalize(parent)
        if normalized_child == normalized_parent:
            return True

        current = self.parent_of(normalized_child)
        while current is not None:
            if current == normalized_parent:
                return True
            current = self.parent_of(current)
        return False

SemanticStability

Bases: StrEnum

Source code in src/autobench/metrics/semantics.py
335
336
337
338
class SemanticStability(StrEnum):
    STABLE = "stable"
    EVOLVING = "evolving"
    EXPERIMENTAL = "experimental"

SemanticTypeInfo

Bases: BaseModel

Source code in src/autobench/metrics/semantics.py
363
364
365
366
367
368
369
370
371
372
373
374
375
class SemanticTypeInfo(BaseModel):
    id: str
    parent: SemanticType | None = None
    description: str | None = None
    unit: str | None = None
    value_shape: str | None = None
    aliases: list[str] = Field(default_factory=list)
    deprecated: bool = False
    stability: SemanticStability | None = None
    privacy: SemanticPrivacy | None = None
    cardinality: SemanticCardinality | None = None
    aggregation: SemanticAggregation | None = None
    tags: dict[str, str] = Field(default_factory=dict)

ArtifactRef

Bases: BaseModel

Source code in src/autobench/records/artifacts.py
 8
 9
10
11
12
13
14
class ArtifactRef(BaseModel):
    id: str
    name: str
    media_type: str | None = None
    value: Any = None
    span_id: str | None = None
    tags: dict[str, Any] = Field(default_factory=dict)

ExperimentRecord

Bases: BaseModel

Source code in src/autobench/records/recording.py
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
class ExperimentRecord(BaseModel):
    model_config = ConfigDict(frozen=True)

    record_version: int = Field(default=RECORD_VERSION, ge=1, le=RECORD_VERSION)
    experiment_id: str
    benchmark_id: str
    plan: BenchmarkPlan
    environment: EnvironmentMetadata
    semantic_registry: SemanticRegistry = Field(
        default_factory=lambda: DEFAULT_SEMANTIC_REGISTRY.model_copy(deep=True)
    )
    report_spec_data: dict[str, Any] | None = None
    spec_snapshot: dict[str, Any] | None = None
    spec_hash: str | None = None
    file_hashes: tuple[ResolvedFileHash, ...] = ()
    run_paths: tuple[str, ...] = ()
    run_count: int
    passed_count: int
    failed_count: int
    errored_count: int
    skipped_count: int

RecordingError

Bases: AutobenchError

Raised when an experiment cannot be recorded safely.

Source code in src/autobench/records/recording.py
55
56
class RecordingError(AutobenchError):
    """Raised when an experiment cannot be recorded safely."""

RecordLineage

Bases: BaseModel

Source code in src/autobench/records/recording.py
64
65
66
67
68
69
70
71
72
73
74
class RecordLineage(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    kind: ReplayKind
    parent_run_id: str
    processor: str
    processor_version: str
    source_record_version: int
    source_protocol_version: int | None = None
    source_semantic_registry_version: int | None = None
    source_maps: tuple[str, ...] = ()

ReplayKind

Bases: StrEnum

Source code in src/autobench/records/recording.py
59
60
61
class ReplayKind(StrEnum):
    EXTRACTION = "extraction"
    CANONICALIZATION = "canonicalization"

RunRecord

Bases: BaseModel

Source code in src/autobench/records/recording.py
 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
class RunRecord(BaseModel):
    model_config = ConfigDict(frozen=True)

    record_version: int = Field(default=RECORD_VERSION, ge=1, le=RECORD_VERSION)
    protocol_version: Literal[1] | None = None
    semantic_registry_version: int | None = Field(default=None, ge=1)
    run_id: str
    experiment_id: str
    benchmark_id: str
    case_id: str
    variant_id: str
    status: RunStatus
    evaluation_status: EvaluationStatus
    task_status: TaskStatus
    case: Case
    task_output: Any = None
    observations: tuple[Observation, ...] = ()
    scores: tuple[ScoreRecord, ...] = ()
    spans: tuple[SpanRecord, ...] = ()
    trace: Trace | None = None
    trace_artifact: ArtifactRef | None = None
    trace_extensions: dict[str, Any] = Field(default_factory=dict)
    artifacts: tuple[ArtifactRef, ...] = ()
    factors: tuple[FactorValue, ...] = ()
    asset_versions: tuple[AssetVersion, ...] = ()
    parent_run_id: str | None = None
    lineage: RecordLineage | None = None
    source_snapshots: tuple[SourceSnapshot, ...] = ()
    canonicalizations: tuple[CanonicalizationResult, ...] = ()
    extractions: tuple[ExtractionEvidence, ...] = ()
    extensions: dict[str, Any] = Field(default_factory=dict)
    errors: tuple[ErrorRecord, ...] = ()
    error: ErrorRecord | None = None

    @model_validator(mode="before")
    @classmethod
    def _upgrade_legacy_record(cls, raw: Any) -> Any:
        if not isinstance(raw, dict):
            return raw
        payload = dict(raw)
        if "task_status" not in payload and "status" in payload:
            payload["task_status"] = payload["status"]
        if "evaluation_status" not in payload and "status" in payload:
            payload["evaluation_status"] = payload["status"]
        if "case" not in payload and "case_id" in payload:
            payload["case"] = {"id": payload["case_id"]}
        trace = payload.get("trace")
        if payload.get("protocol_version") is None and isinstance(trace, dict):
            payload["protocol_version"] = trace.get("protocol_version", PROTOCOL_VERSION)
        if payload.get("semantic_registry_version") is None and trace is not None:
            payload["semantic_registry_version"] = DEFAULT_SEMANTIC_REGISTRY.version
        lineage = payload.get("lineage")
        if payload.get("parent_run_id") is None and isinstance(lineage, dict):
            payload["parent_run_id"] = lineage.get("parent_run_id")
        return payload

ReplayError

Bases: AutobenchError

Raised when immutable evidence cannot be replayed.

Source code in src/autobench/records/replay.py
32
33
class ReplayError(AutobenchError):
    """Raised when immutable evidence cannot be replayed."""

EnvironmentMetadata

Bases: BaseModel

Source code in src/autobench/records/storage.py
12
13
14
15
class EnvironmentMetadata(BaseModel):
    python_version: str
    platform: str
    cwd: str

BenchmarkReport

Bases: BaseModel

Source code in src/autobench/reports/reporting.py
112
113
114
115
116
117
118
119
120
121
122
class BenchmarkReport(BaseModel):
    benchmark_id: str
    experiment_id: str
    run_count: int
    status_counts: dict[str, int] = Field(default_factory=dict)
    variant_configs: list[VariantConfigRow] = Field(default_factory=list)
    leaderboard: list[LeaderboardRow]
    run_metrics: list[RunMetricRow] = Field(default_factory=list)
    case_matrix: CaseMatrix
    comparisons: list[ComparisonReport] = Field(default_factory=list)
    distributions: list[MetricDistribution] = Field(default_factory=list)

CaseMatrix

Bases: BaseModel

Source code in src/autobench/reports/reporting.py
91
92
93
class CaseMatrix(BaseModel):
    metric: str
    rows: dict[str, dict[str, Any]] = Field(default_factory=dict)

CaseMatrixReportSpec

Bases: BaseModel

Source code in src/autobench/reports/reporting.py
39
40
class CaseMatrixReportSpec(BaseModel):
    semantic_type: str = Semantic.COVERAGE_RATIO

ComparisonReport

Bases: BaseModel

Source code in src/autobench/reports/reporting.py
 96
 97
 98
 99
100
101
102
class ComparisonReport(BaseModel):
    baseline: str
    candidate: str
    run_count: int
    factor_deltas: dict[str, dict[str, Any]] = Field(default_factory=dict)
    metric_deltas: dict[str, dict[str, Any]] = Field(default_factory=dict)
    confounded: bool = False

ComparisonReportSpec

Bases: BaseModel

Source code in src/autobench/reports/reporting.py
43
44
45
46
47
48
49
50
51
class ComparisonReportSpec(BaseModel):
    baseline: str
    candidate: str
    metrics: tuple[MetricAggregation, ...] = ()

    def resolved_metrics(self) -> tuple[MetricAggregation, ...]:
        if self.metrics:
            return self.metrics
        return DEFAULT_LEADERBOARD_METRICS

DistributionReportSpec

Bases: BaseModel

Source code in src/autobench/reports/reporting.py
54
55
56
57
class DistributionReportSpec(BaseModel):
    name: str
    semantic_type: str
    summaries: tuple[AggregationFn, ...] = ("min", "median", "p95", "max")

LeaderboardReportSpec

Bases: BaseModel

Source code in src/autobench/reports/reporting.py
35
36
class LeaderboardReportSpec(BaseModel):
    metrics: tuple[MetricAggregation, ...] = ()

LeaderboardRow

Bases: BaseModel

Source code in src/autobench/reports/reporting.py
72
73
74
75
class LeaderboardRow(BaseModel):
    variant_id: str
    run_count: int
    metrics: dict[str, Any] = Field(default_factory=dict)

MetricAggregation

Bases: BaseModel

Source code in src/autobench/reports/reporting.py
29
30
31
32
class MetricAggregation(BaseModel):
    name: str
    semantic_type: str
    fn: AggregationFn

MetricDistribution

Bases: BaseModel

Source code in src/autobench/reports/reporting.py
105
106
107
108
109
class MetricDistribution(BaseModel):
    name: str
    semantic_type: str
    by_variant: dict[str, list[Any]] = Field(default_factory=dict)
    summaries: dict[str, dict[str, Any]] = Field(default_factory=dict)

ReportSpec

Bases: BaseModel

Source code in src/autobench/reports/reporting.py
60
61
62
63
64
65
66
67
68
69
class ReportSpec(BaseModel):
    leaderboard: LeaderboardReportSpec = Field(default_factory=LeaderboardReportSpec)
    case_matrix: CaseMatrixReportSpec = Field(default_factory=CaseMatrixReportSpec)
    comparisons: tuple[ComparisonReportSpec, ...] = ()
    distributions: tuple[DistributionReportSpec, ...] = ()

    def leaderboard_metrics(self) -> tuple[MetricAggregation, ...]:
        if self.leaderboard.metrics:
            return self.leaderboard.metrics
        return DEFAULT_LEADERBOARD_METRICS

RunMetricRow

Bases: BaseModel

Source code in src/autobench/reports/reporting.py
84
85
86
87
88
class RunMetricRow(BaseModel):
    case_id: str
    variant_id: str
    status: str
    metrics: dict[str, Any] = Field(default_factory=dict)

VariantConfigRow

Bases: BaseModel

Source code in src/autobench/reports/reporting.py
78
79
80
81
class VariantConfigRow(BaseModel):
    variant_id: str
    label: str | None = None
    factors: dict[str, Any] = Field(default_factory=dict)

CheckResult

Bases: BaseModel

Source code in src/autobench/runtime/context.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
class CheckResult(BaseModel):
    name: str
    passed: bool
    observation: Observation
    reason: str | None = None

    def skip(self, message: str) -> dict[str, Any]:
        return {
            "skipped": True,
            "check": self.name,
            "passed": self.passed,
            "reason": message,
        }

DurationMetricSpec

Bases: BaseModel

Source code in src/autobench/runtime/context.py
52
53
54
55
56
57
58
class DurationMetricSpec(BaseModel):
    name: str = "duration"
    semantic_type: SemanticType = Semantic.TIME_LATENCY
    unit: str = "s"
    direction: Direction | None = Direction.MINIMIZE
    role: ObservationRole | None = ObservationRole.DIAGNOSTIC
    tags: dict[str, Any] = Field(default_factory=dict)

MeasurementRecord

Bases: BaseModel

Source code in src/autobench/runtime/context.py
106
107
108
class MeasurementRecord(BaseModel):
    metrics: tuple[Observation, ...]
    samples_artifact: ArtifactRef | None = None

RunContext

Source code in src/autobench/runtime/context.py
 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
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
class RunContext:
    def __init__(
        self,
        *,
        benchmark_id: str,
        case: Case,
        variant: Variant,
        run_id: str = "run_1",
        experiment_id: str = "experiment_1",
        capture_policy: CapturePolicy | None = None,
    ) -> None:
        self.benchmark_id = benchmark_id
        self.case = case
        self.variant = variant
        self.run_id = run_id
        self.experiment_id = experiment_id
        self.observations: list[Observation] = []
        self.spans: list[SpanRecord] = []
        self.artifacts: list[ArtifactRef] = []
        self.errors: list[ErrorRecord] = []
        self.asset_versions: list[AssetVersion] = []
        self.source_snapshots: list[SourceSnapshot] = []
        self._collector = LocalCollector()
        self._capture = CaptureSession(capture_policy)
        self._execution = ExecutionRef(
            benchmark_id=benchmark_id,
            experiment_id=experiment_id,
            run_id=run_id,
            case_id=case.id,
            variant_id=variant.id,
        )
        self._emitter = Emitter(
            self._collector,
            InstrumentationScope(
                instrumentor_name="autobench.manual",
                instrumentor_version=__version__,
                package_name="autobench",
                package_version=__version__,
                mechanism=CaptureMechanism.MANUAL,
                layer=AbstractionLayer.APPLICATION,
            ),
            execution=self._execution,
        )
        root = self._emitter.start_span(
            "benchmark.run",
            kind=KnownSpanKind.TASK,
            attributes={
                "benchmark_id": benchmark_id,
                "experiment_id": experiment_id,
                "run_id": run_id,
                "case_id": case.id,
                "variant_id": variant.id,
            },
            capture=CaptureLevel.METADATA,
        )
        self._root_span_id = root.span_id
        self._legacy_to_abp: dict[str, SpanId] = {}
        self._abp_to_legacy: dict[SpanId, str] = {}
        self._span_emitters: dict[str, Emitter] = {}
        self._span_started_monotonic: dict[str, int] = {}
        self._ended_spans: set[str] = set()
        self._span_error_refs: dict[str, list[EvidenceRef]] = {}
        self._error_refs: list[EvidenceRef] = []
        self._trace: Trace | None = None
        self._observation_index = 0
        self._span_index = 0
        self._artifact_index = 0
        self._asset_version_keys: set[tuple[str, str]] = set()
        _RUN_CONTEXTS[self._emitter.trace_id] = self

    @property
    def trace(self) -> Trace:
        if self._trace is not None:
            return self._trace
        return self._collector.snapshot(self._emitter.trace_id)

    @property
    def finalized(self) -> bool:
        return self._trace is not None

    @property
    def reference_store(self) -> ReferenceStore:
        return self._capture.store

    @property
    def capture_policy(self) -> CapturePolicy:
        return self._capture.policy

    @property
    def active_context(self) -> ActiveContext:
        return ActiveContext(
            collector=self._collector,
            trace_id=self._emitter.trace_id,
            current_span_id=self._root_span_id,
            execution=self._execution,
            capture_policy=self._capture.policy,
        )

    def factor(self, name: str) -> Any:
        for factor in self.variant.factors:
            if factor.name == name:
                return factor.value
        raise KeyError(f"Unknown variant factor: {name}")

    def retain_source_snapshot(self, snapshot: SourceSnapshot) -> SourceSnapshot:
        self.source_snapshots.append(snapshot)
        return snapshot

    def span(
        self,
        name: str,
        *,
        kind: SpanKind | str = SpanKind.CUSTOM,
        input: Any = None,
        attributes: dict[str, Any] | None = None,
        usage: dict[str, Any] | None = None,
        duration_metric: DurationMetricSpec | dict[str, Any] | None = None,
        tags: dict[str, Any] | None = None,
        instrumentation_scope: InstrumentationScope | None = None,
    ) -> Span:
        metric_spec = None
        if duration_metric is not None:
            metric_spec = (
                duration_metric
                if isinstance(duration_metric, DurationMetricSpec)
                else DurationMetricSpec.model_validate(duration_metric)
            )
        return Span(
            context=self,
            name=name,
            kind=kind,
            input=input,
            attributes=attributes or {},
            usage=usage or {},
            duration_metric=metric_spec,
            tags=tags or {},
            instrumentation_scope=instrumentation_scope,
        )

    def metric(
        self,
        name: str,
        value: Any,
        *,
        semantic_type: SemanticType | None = None,
        unit: str | None = None,
        direction: Direction | None = None,
        role: ObservationRole | None = None,
        span_id: str | None = None,
        tags: dict[str, Any] | None = None,
        source: ObservationSource = ObservationSource.TASK_OBSERVATION,
    ) -> Observation:
        return self._append_observation(
            name=name,
            kind=ObservationKind.METRIC,
            value=value,
            semantic_type=semantic_type,
            unit=unit,
            direction=direction,
            role=role,
            span_id=span_id,
            tags=tags,
            source=source,
        )

    def factor_observation(
        self,
        name: str,
        value: Any,
        *,
        semantic_type: SemanticType | None = None,
        span_id: str | None = None,
        tags: dict[str, Any] | None = None,
        source: ObservationSource = ObservationSource.TASK_OBSERVATION,
    ) -> Observation:
        return self._append_observation(
            name=name,
            kind=ObservationKind.FACTOR,
            value=value,
            semantic_type=semantic_type,
            span_id=span_id,
            tags=tags,
            source=source,
        )

    def event(
        self,
        name: str,
        value: Any = True,
        *,
        semantic_type: SemanticType | None = None,
        span_id: str | None = None,
        tags: dict[str, Any] | None = None,
    ) -> Observation:
        return self._append_observation(
            name=name,
            kind=ObservationKind.EVENT,
            value=value,
            semantic_type=semantic_type,
            span_id=span_id,
            tags=tags,
        )

    def diagnostic(
        self,
        name: str,
        value: Any = True,
        *,
        semantic_type: SemanticType | None = None,
        span_id: str | None = None,
        tags: dict[str, Any] | None = None,
        source: ObservationSource = ObservationSource.TASK_OBSERVATION,
    ) -> Observation:
        return self._append_observation(
            name=name,
            kind=ObservationKind.EVENT,
            value=value,
            semantic_type=semantic_type,
            role=ObservationRole.DIAGNOSTIC,
            span_id=span_id,
            tags=tags,
            source=source,
        )

    def outcome(
        self,
        success: bool,
        *,
        name: str = "success",
        semantic_type: SemanticType = Semantic.RESULT_SUCCESS,
        span_id: str | None = None,
        tags: dict[str, Any] | None = None,
    ) -> Observation:
        return self.metric(
            name,
            success,
            semantic_type=semantic_type,
            role=ObservationRole.OBJECTIVE,
            span_id=span_id,
            tags=tags,
        )

    def skip_reason(
        self,
        reason: str,
        *,
        name: str = "skip_reason",
        span_id: str | None = None,
        tags: dict[str, Any] | None = None,
    ) -> Observation:
        return self.diagnostic(name, reason, span_id=span_id, tags=tags)

    def check(
        self,
        name: str,
        passed: bool,
        *,
        reason: str | None = None,
        semantic_type: SemanticType = Semantic.QUALITY_CORRECTNESS,
        span_id: str | None = None,
        tags: dict[str, Any] | None = None,
    ) -> CheckResult:
        observation_tags = dict(tags or {})
        if reason is not None:
            observation_tags["reason"] = reason
        observation = self.metric(
            name,
            passed,
            semantic_type=semantic_type,
            role=ObservationRole.CONSTRAINT,
            span_id=span_id,
            tags=observation_tags,
        )
        return CheckResult(name=name, passed=passed, observation=observation, reason=reason)

    def metrics(
        self,
        namespace: str,
        values: dict[str, Any],
        *,
        semantic_types: dict[str, SemanticType] | None = None,
        units: dict[str, str] | None = None,
        direction: Direction | None = None,
        role: ObservationRole | None = None,
        span_id: str | None = None,
        tags: dict[str, Any] | None = None,
    ) -> list[Observation]:
        observations: list[Observation] = []
        for key, value in values.items():
            observations.append(
                self.metric(
                    f"{namespace}.{key}",
                    value,
                    semantic_type=None if semantic_types is None else semantic_types.get(key),
                    unit=None if units is None else units.get(key),
                    direction=direction,
                    role=role,
                    span_id=span_id,
                    tags=tags,
                )
            )
        return observations

    def record_measurement(
        self,
        name: str,
        measurement: Measurement,
        *,
        semantic_type: SemanticType = Semantic.TIME_LATENCY,
        unit: str = "ms",
        direction: Direction | None = Direction.MINIMIZE,
        role: ObservationRole | None = ObservationRole.DIAGNOSTIC,
        span_id: str | None = None,
        tags: dict[str, Any] | None = None,
        include_samples_artifact: bool = True,
    ) -> MeasurementRecord:
        values = {
            "median_ms": measurement.median_ms,
            "p95_ms": measurement.p95_ms,
            "mean_ms": measurement.mean_ms,
            "min_ms": measurement.min_ms,
            "max_ms": measurement.max_ms,
            "stddev_ms": measurement.standard_deviation_ms,
            "noise_pct": measurement.range_noise_pct,
            "repetitions": measurement.repetition_count,
            "timed_out": measurement.timed_out,
        }
        measurement_semantics = {
            "median_ms": semantic_type,
            "p95_ms": f"{semantic_type}.p95",
            "mean_ms": f"{semantic_type}.mean",
            "min_ms": f"{semantic_type}.min",
            "max_ms": f"{semantic_type}.max",
        }
        metrics = tuple(
            self.metrics(
                name,
                values,
                semantic_types=measurement_semantics,
                units={
                    "median_ms": unit,
                    "p95_ms": unit,
                    "mean_ms": unit,
                    "min_ms": unit,
                    "max_ms": unit,
                    "stddev_ms": unit,
                    "noise_pct": "%",
                },
                direction=direction,
                role=role,
                span_id=span_id,
                tags=tags,
            )
        )
        samples_artifact = None
        if include_samples_artifact:
            samples_artifact = self.artifact(
                f"{name}.samples_ms",
                measurement.samples_ms,
                media_type="application/x.autobench.samples+yaml",
                span_id=span_id,
                tags=tags,
            )
        return MeasurementRecord(metrics=metrics, samples_artifact=samples_artifact)

    def error(
        self,
        error: BaseException | ErrorRecord | str,
        *,
        span_id: str | None = None,
    ) -> ErrorRecord:
        if isinstance(error, ErrorRecord):
            record = error.model_copy(update={"span_id": error.span_id or span_id})
        elif isinstance(error, BaseException):
            record = ErrorRecord.from_exception(error, span_id=span_id)
        else:
            record = ErrorRecord(error_type="Error", message=error, span_id=span_id)

        self.errors.append(record)
        error_reference = EvidenceRef(
            kind=ReferenceKind.ERROR,
            id=f"error_{len(self.errors)}",
            media_type="application/x.autobench.error+json",
        )
        self._error_refs.append(error_reference)
        abp_span_id = self._abp_span_id(span_id)
        emitter = self._emitter_for_legacy_span(span_id)
        captured = self._capture_value(
            record.model_dump(mode="json"),
            semantic_type=Semantic.ERROR_EXCEPTION,
            path=f"errors.{error_reference.id}",
            span_id=abp_span_id,
            level=CaptureLevel.REDACTED,
        )
        emitter.event(
            abp_span_id,
            record.error_type,
            Semantic.ERROR_EXCEPTION,
            body=None if captured.reference is not None else captured.value,
            reference=captured.reference,
            attributes={"error_id": error_reference.id},
        )
        emitter.reference(
            error_reference,
            span_id=abp_span_id,
            semantic_type=Semantic.ERROR_EXCEPTION,
            name=record.error_type,
        )
        if span_id is not None:
            span_record = self._span_by_id(span_id)
            if span_record is not None:
                span_record.error = record
                self._span_error_refs.setdefault(span_id, []).append(error_reference)
        return record

    def artifact(
        self,
        name: str,
        value: Any,
        *,
        media_type: str | None = None,
        span_id: str | None = None,
        tags: dict[str, Any] | None = None,
    ) -> ArtifactRef:
        artifact = ArtifactRef(
            id=self._next_artifact_id(),
            name=name,
            value=value,
            media_type=media_type,
            span_id=span_id,
            tags=tags or {},
        )
        self.artifacts.append(artifact)
        if span_id is not None:
            span_record = self._span_by_id(span_id)
            if span_record is not None:
                span_record.artifacts.append(artifact.id)
        abp_span_id = self._abp_span_id(span_id)
        emitter = self._emitter_for_legacy_span(span_id)
        captured = self._capture_value(
            value,
            semantic_type=Semantic.ARTIFACT_CONTENT,
            path=f"artifacts.{name}",
            span_id=abp_span_id,
            level=CaptureLevel.FULL,
            media_type=media_type,
        )
        reference = captured.reference
        if reference is None and not captured.omitted:
            if isinstance(captured.value, str):
                content = captured.value.encode()
                active_media_type = media_type or "text/plain"
            else:
                content = json.dumps(
                    captured.value,
                    ensure_ascii=True,
                    separators=(",", ":"),
                    sort_keys=True,
                ).encode()
                active_media_type = media_type or "application/json"
            reference = self._capture.store.add_artifact(content, media_type=active_media_type)
        if reference is not None:
            emitter.reference(
                reference,
                span_id=abp_span_id,
                semantic_type=Semantic.ARTIFACT_CONTENT,
                name=name,
                attributes={"artifact_id": artifact.id},
            )
        self._append_observation(
            name=name,
            kind=ObservationKind.ARTIFACT,
            value=artifact.id,
            span_id=span_id,
            tags=tags,
        )
        return artifact

    def attach_tracked_asset(
        self,
        target: Any,
        *,
        registry: TrackingRegistry | None = None,
        span_id: str | None = None,
    ) -> AssetVersion:
        active_registry = registry or track
        asset_version = active_registry.asset_version_of(target)
        asset_key = (asset_version.asset_id, asset_version.version)
        if asset_key not in self._asset_version_keys:
            self.asset_versions.append(asset_version)
            self._asset_version_keys.add(asset_key)
            asset = active_registry.asset_of(target)
            reference_kind = ReferenceKind.ASSET
            if asset.kind == "prompt":
                reference_kind = ReferenceKind.PROMPT
            elif asset.kind == "tool":
                reference_kind = ReferenceKind.TOOL
            elif asset.kind in {"pydantic_model", "dataclass", "typed_class", "type"}:
                reference_kind = ReferenceKind.OUTPUT_SCHEMA
            abp_span_id = self._abp_span_id(span_id)
            emitter = self._emitter_for_legacy_span(span_id)
            captured = self._capture_value(
                asset_version,
                semantic_type=asset.semantic_type,
                path=f"assets.{asset.id}",
                span_id=abp_span_id,
                asset_version=asset_version,
                reference_kind=reference_kind,
            )
            if captured.reference is not None:
                emitter.reference(
                    captured.reference,
                    span_id=abp_span_id,
                    semantic_type=asset.semantic_type,
                    name=asset.name,
                    attributes={"kind": asset.kind},
                )
        return asset_version

    def _append_observation(
        self,
        *,
        name: str,
        kind: ObservationKind,
        value: Any,
        semantic_type: SemanticType | None = None,
        unit: str | None = None,
        direction: Direction | None = None,
        role: ObservationRole | None = None,
        span_id: str | None = None,
        tags: dict[str, Any] | None = None,
        source: ObservationSource = ObservationSource.TASK_OBSERVATION,
    ) -> Observation:
        observation = Observation(
            id=self._next_observation_id(),
            name=name,
            kind=kind,
            semantic_type=semantic_type,
            value=value,
            unit=unit,
            direction=direction,
            role=role,
            span_id=span_id,
            source=source,
            tags=tags or {},
            case_id=self.case.id,
            variant_id=self.variant.id,
        )
        return self.record_observation(observation)

    def record_observation(self, observation: Observation) -> Observation:
        self.observations.append(observation)
        if observation.span_id is not None:
            span_record = self._span_by_id(observation.span_id)
            if span_record is not None:
                span_record.observations.append(observation.id)
        self._emit_observation(observation)
        return observation

    def _start_span(
        self,
        name: str,
        *,
        kind: SpanKind | str = SpanKind.CUSTOM,
        input: Any = None,
        attributes: dict[str, Any] | None = None,
        usage: dict[str, Any] | None = None,
        tags: dict[str, Any],
        instrumentation_scope: InstrumentationScope | None = None,
    ) -> tuple[SpanRecord, int]:
        if self.finalized:
            raise RuntimeError("RunContext is finalized.")
        active = get_context()
        parent_abp_id = self._root_span_id
        if (
            active is not None
            and active.collector is self._collector
            and active.trace_id == self._emitter.trace_id
            and active.current_span_id is not None
        ):
            parent_abp_id = active.current_span_id
        parent_id = self._abp_to_legacy.get(parent_abp_id)
        captured_attributes = self._capture_mapping(
            attributes or {},
            path=f"spans.{name}.attributes",
            span_id=parent_abp_id,
        )
        captured_tags = self._capture_mapping(
            tags,
            path=f"spans.{name}.tags",
            span_id=parent_abp_id,
        )
        if captured_tags:
            captured_attributes["tags"] = captured_tags
        emitter = self._emitter
        if instrumentation_scope is not None:
            emitter = Emitter(
                self._collector,
                instrumentation_scope,
                trace_id=self._emitter.trace_id,
                execution=self._execution,
            )
        start = emitter.start_span(
            name,
            parent_span_id=parent_abp_id,
            kind=str(kind),
            attributes=captured_attributes,
            capture=self._capture.policy.default_level,
        )
        span_record = SpanRecord(
            id=self._next_span_id(),
            name=name,
            kind=kind,
            parent_id=parent_id,
            started_at=start.emitted_at,
            input=input,
            attributes=attributes or {},
            usage=usage or {},
            tags=tags,
        )
        self.spans.append(span_record)
        self._legacy_to_abp[span_record.id] = start.span_id
        self._abp_to_legacy[start.span_id] = span_record.id
        self._span_emitters[span_record.id] = emitter
        self._span_started_monotonic[span_record.id] = start.monotonic_ns
        if input is not None:
            captured_input = self._capture_value(
                input,
                semantic_type=Semantic.OPERATION_INPUT,
                path=f"spans.{name}.input",
                span_id=start.span_id,
            )
            emitter.event(
                start.span_id,
                "input",
                Semantic.OPERATION_INPUT,
                body=None if captured_input.reference is not None else captured_input.value,
                reference=captured_input.reference,
            )
        return span_record, start.monotonic_ns

    def _finish_span(
        self,
        span_record: SpanRecord,
        *,
        started_at: int,
        duration_metric: DurationMetricSpec | None,
        error: BaseException | None = None,
        reason: EndReason | None = None,
        partial: bool | None = None,
    ) -> None:
        if span_record.id in self._ended_spans:
            return
        emitter = self._span_emitters[span_record.id]
        abp_span_id = self._legacy_to_abp[span_record.id]
        error_refs = tuple(self._span_error_refs.get(span_record.id, ()))
        status = SpanStatus.OK
        end_reason = EndReason.COMPLETED if reason is None else reason
        is_partial = False if partial is None else partial
        if error is not None or error_refs:
            status = SpanStatus.ERROR
            if reason is None or reason is EndReason.COMPLETED:
                end_reason = EndReason.FAILED
        if isinstance(error, asyncio.CancelledError):
            end_reason = EndReason.CANCELLED
            is_partial = True
        elif isinstance(error, TimeoutError):
            end_reason = EndReason.TIMEOUT
            is_partial = True
        captured_output = self._capture_value(
            span_record.output,
            semantic_type=Semantic.OPERATION_OUTPUT,
            path=f"spans.{span_record.name}.output",
            span_id=abp_span_id,
        )
        end = emitter.end_span(
            abp_span_id,
            attributes=self._capture_mapping(
                span_record.attributes,
                path=f"spans.{span_record.name}.attributes",
                span_id=abp_span_id,
            ),
            output=None if captured_output.reference is not None else captured_output.value,
            output_reference=captured_output.reference,
            status=status,
            reason=end_reason,
            errors=error_refs,
            partial=is_partial,
            usage=self._capture_mapping(
                span_record.usage,
                path=f"spans.{span_record.name}.usage",
                span_id=abp_span_id,
            ),
        )
        self._ended_spans.add(span_record.id)
        duration_seconds = max(0, end.monotonic_ns - started_at) / 1_000_000_000
        span_record.ended_at = end.emitted_at
        span_record.duration_seconds = duration_seconds

        if duration_metric is not None:
            self.metric(
                duration_metric.name,
                duration_seconds,
                semantic_type=duration_metric.semantic_type,
                unit=duration_metric.unit,
                direction=duration_metric.direction,
                role=duration_metric.role,
                span_id=span_record.id,
                tags=duration_metric.tags,
            )

    def finalize(
        self,
        *,
        status: SpanStatus = SpanStatus.OK,
        reason: EndReason = EndReason.COMPLETED,
        partial: bool = False,
        output: Any = None,
    ) -> Trace:
        if self._trace is not None:
            return self._trace
        for span_record in self.spans:
            if span_record.id in self._ended_spans:
                continue
            self._finish_span(
                span_record,
                started_at=self._span_started_monotonic[span_record.id],
                duration_metric=None,
                reason=EndReason.ABANDONED,
                partial=True,
            )
        if self._error_refs and status is SpanStatus.OK:
            status = SpanStatus.ERROR
            reason = EndReason.FAILED
        captured_output = self._capture_value(
            output,
            semantic_type=Semantic.OPERATION_OUTPUT,
            path="benchmark.run.output",
            span_id=self._root_span_id,
        )
        self._emitter.end_span(
            self._root_span_id,
            output=None if captured_output.reference is not None else captured_output.value,
            output_reference=captured_output.reference,
            status=status,
            reason=reason,
            errors=tuple(self._error_refs),
            partial=partial,
        )
        self._trace = self._collector.finish(
            self._emitter.trace_id,
            error=status is SpanStatus.ERROR,
        )
        return self._trace

    def _emit_observation(self, observation: Observation) -> None:
        emitter = self._emitter_for_legacy_span(observation.span_id)
        abp_span_id = self._abp_span_id(observation.span_id)
        semantic_type = observation.semantic_type
        if semantic_type is None:
            if observation.kind is ObservationKind.FACTOR:
                semantic_type = Semantic.FACTOR_VALUE
            elif observation.role is ObservationRole.DIAGNOSTIC:
                semantic_type = Semantic.DIAGNOSTIC_EVENT
            else:
                semantic_type = Semantic.EVENT_OCCURRENCE
        captured = self._capture_value(
            observation.value,
            semantic_type=semantic_type,
            path=f"observations.{observation.name}",
            span_id=abp_span_id,
        )
        attributes: dict[str, SerializedValue] = {
            "observation_id": observation.id,
            "kind": observation.kind.value,
            "source": ("unspecified" if observation.source is None else str(observation.source)),
        }
        if observation.span_id is not None:
            attributes["legacy_span_id"] = observation.span_id
        if observation.tags:
            attributes["tags"] = self._capture_mapping(
                observation.tags,
                path=f"observations.{observation.name}.tags",
                span_id=abp_span_id,
            )
        if (
            observation.kind is ObservationKind.METRIC
            and not captured.omitted
            and isinstance(captured.value, (bool, int, float))
        ):
            emitter.measurement(
                abp_span_id,
                observation.name,
                semantic_type,
                captured.value,
                unit=observation.unit,
                direction=observation.direction,
                role=observation.role,
                attributes=attributes,
            )
            return
        if captured.omitted:
            attributes["capture_omitted"] = True
        emitter.event(
            abp_span_id,
            observation.name,
            semantic_type,
            body=None if captured.reference is not None else captured.value,
            reference=captured.reference,
            attributes=attributes,
        )

    def _capture_value(
        self,
        value: Any,
        *,
        semantic_type: SemanticType | None,
        path: str,
        span_id: SpanId,
        level: CaptureLevel | None = None,
        asset_version: AssetVersion | None = None,
        reference_kind: ReferenceKind | None = None,
        media_type: str | None = None,
    ) -> CaptureResult:
        captured = self._capture.capture(
            value,
            semantic_type=semantic_type,
            path=path,
            level=level,
            asset_version=asset_version,
            reference_kind=reference_kind,
            media_type=media_type,
        )
        for diagnostic in captured.diagnostics:
            self._emitter_for_abp_span(span_id).diagnostic(
                diagnostic.code,
                diagnostic.message,
                severity=diagnostic.severity,
                span_id=span_id,
                path=diagnostic.path,
                semantic_type=diagnostic.semantic_type,
                details=diagnostic.details,
            )
        return captured

    def _capture_mapping(
        self,
        values: dict[str, Any],
        *,
        path: str,
        span_id: SpanId,
    ) -> dict[str, SerializedValue]:
        captured_values: dict[str, SerializedValue] = {}
        for name, value in values.items():
            captured = self._capture_value(
                value,
                semantic_type=name,
                path=f"{path}.{name}",
                span_id=span_id,
            )
            if captured.omitted:
                continue
            if captured.reference is None:
                captured_values[name] = captured.value
            else:
                captured_values[name] = captured.reference.model_dump(mode="json")
        return captured_values

    def _abp_span_id(self, legacy_span_id: str | None) -> SpanId:
        if legacy_span_id is not None:
            mapped = self._legacy_to_abp.get(legacy_span_id)
            if mapped is not None:
                return mapped
            return self._root_span_id
        active = get_context()
        if (
            active is not None
            and active.collector is self._collector
            and active.trace_id == self._emitter.trace_id
            and active.current_span_id is not None
        ):
            return active.current_span_id
        return self._root_span_id

    def _span_by_id(self, span_id: str) -> SpanRecord | None:
        for span in self.spans:
            if span.id == span_id:
                return span
        return None

    def _emitter_for_legacy_span(self, span_id: str | None) -> Emitter:
        if span_id is None:
            return self._emitter
        return self._span_emitters.get(span_id, self._emitter)

    def _emitter_for_abp_span(self, span_id: SpanId) -> Emitter:
        legacy_span_id = self._abp_to_legacy.get(span_id)
        return self._emitter_for_legacy_span(legacy_span_id)

    def _next_observation_id(self) -> str:
        self._observation_index += 1
        return f"obs_{self._observation_index}"

    def _next_span_id(self) -> str:
        self._span_index += 1
        return f"span_{self._span_index}"

    def _next_artifact_id(self) -> str:
        self._artifact_index += 1
        return f"artifact_{self._artifact_index}"

Span

Bases: AbstractContextManager['Span']

Source code in src/autobench/runtime/context.py
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
class Span(AbstractContextManager["Span"]):
    def __init__(
        self,
        *,
        context: RunContext,
        name: str,
        kind: SpanKind | str,
        input: Any,
        attributes: dict[str, Any],
        usage: dict[str, Any],
        duration_metric: DurationMetricSpec | None,
        tags: dict[str, Any],
        instrumentation_scope: InstrumentationScope | None,
    ) -> None:
        self._context = context
        self._name = name
        self._kind = kind
        self._input = input
        self._attributes = attributes
        self._usage = usage
        self._duration_metric = duration_metric
        self._tags = tags
        self._instrumentation_scope = instrumentation_scope
        self._record: SpanRecord | None = None
        self._started_at: int | None = None
        self._active_token: Token[ActiveContext | None] | None = None

    @property
    def id(self) -> str:
        if self._record is None:
            raise RuntimeError("Span has not started.")
        return self._record.id

    @property
    def record(self) -> SpanRecord:
        if self._record is None:
            raise RuntimeError("Span has not started.")
        return self._record

    def __enter__(self) -> Span:
        self._record, self._started_at = self._context._start_span(
            self._name,
            kind=self._kind,
            input=self._input,
            attributes=self._attributes,
            usage=self._usage,
            tags=self._tags,
            instrumentation_scope=self._instrumentation_scope,
        )
        self.resume()
        return self

    def resume(self) -> None:
        if self._record is None:
            raise RuntimeError("Span has not started.")
        if self._active_token is not None:
            return
        active = get_context()
        abp_span_id = self._context._legacy_to_abp[self._record.id]
        if (
            active is not None
            and active.collector is self._context._collector
            and active.trace_id == self._context._emitter.trace_id
        ):
            protocol_context = active.with_span(abp_span_id)
        else:
            protocol_context = self._context.active_context.with_span(abp_span_id)
        self._active_token = attach_context(protocol_context)

    def suspend(self) -> None:
        if self._active_token is None:
            return
        reset_context(self._active_token)
        self._active_token = None

    def finish(
        self,
        *,
        error: BaseException | None = None,
        reason: EndReason | None = None,
        partial: bool | None = None,
    ) -> None:
        if error is not None:
            self._context.error(error, span_id=self.id)
        try:
            if self._started_at is not None:
                self._context._finish_span(
                    self.record,
                    started_at=self._started_at,
                    duration_metric=self._duration_metric,
                    error=error,
                    reason=reason,
                    partial=partial,
                )
        finally:
            self.suspend()

    def __exit__(
        self,
        exc_type: type[BaseException] | None,
        exc_value: BaseException | None,
        traceback: TracebackType | None,
    ) -> bool | None:
        self.finish(error=exc_value)
        return None

    def __iter__(self) -> Iterator[SpanRecord]:
        yield self.record

    def set_output(self, value: Any) -> None:
        self.record.output = value

    def set_attribute(self, name: str, value: Any) -> None:
        self.record.attributes[name] = value

    def set_usage(self, name: str, value: Any) -> None:
        self.record.usage[name] = value

    def metric(
        self,
        name: str,
        value: Any,
        *,
        semantic_type: SemanticType | None = None,
        unit: str | None = None,
        direction: Direction | None = None,
        role: ObservationRole | None = None,
        tags: dict[str, Any] | None = None,
    ) -> Observation:
        return self._context.metric(
            name,
            value,
            semantic_type=semantic_type,
            unit=unit,
            direction=direction,
            role=role,
            span_id=self.id,
            tags=tags,
        )

    def factor(
        self,
        name: str,
        value: Any,
        *,
        semantic_type: SemanticType | None = None,
        tags: dict[str, Any] | None = None,
    ) -> Observation:
        return self._context.factor_observation(
            name,
            value,
            semantic_type=semantic_type,
            span_id=self.id,
            tags=tags,
        )

    def event(
        self,
        name: str,
        value: Any = True,
        *,
        semantic_type: SemanticType | None = None,
        tags: dict[str, Any] | None = None,
    ) -> Observation:
        return self._context.event(
            name,
            value,
            semantic_type=semantic_type,
            span_id=self.id,
            tags=tags,
        )

    def diagnostic(
        self,
        name: str,
        value: Any = True,
        *,
        semantic_type: SemanticType | None = None,
        tags: dict[str, Any] | None = None,
    ) -> Observation:
        return self._context.diagnostic(
            name,
            value,
            semantic_type=semantic_type,
            span_id=self.id,
            tags=tags,
        )

    def outcome(
        self,
        success: bool,
        *,
        name: str = "success",
        semantic_type: SemanticType = Semantic.RESULT_SUCCESS,
        tags: dict[str, Any] | None = None,
    ) -> Observation:
        return self._context.outcome(
            success,
            name=name,
            semantic_type=semantic_type,
            span_id=self.id,
            tags=tags,
        )

    def skip_reason(
        self,
        reason: str,
        *,
        name: str = "skip_reason",
        tags: dict[str, Any] | None = None,
    ) -> Observation:
        return self._context.skip_reason(reason, name=name, span_id=self.id, tags=tags)

    def check(
        self,
        name: str,
        passed: bool,
        *,
        reason: str | None = None,
        semantic_type: SemanticType = Semantic.QUALITY_CORRECTNESS,
        tags: dict[str, Any] | None = None,
    ) -> CheckResult:
        return self._context.check(
            name,
            passed,
            reason=reason,
            semantic_type=semantic_type,
            span_id=self.id,
            tags=tags,
        )

    def metrics(
        self,
        namespace: str,
        values: dict[str, Any],
        *,
        semantic_types: dict[str, SemanticType] | None = None,
        units: dict[str, str] | None = None,
        direction: Direction | None = None,
        role: ObservationRole | None = None,
        tags: dict[str, Any] | None = None,
    ) -> list[Observation]:
        return self._context.metrics(
            namespace,
            values,
            semantic_types=semantic_types,
            units=units,
            direction=direction,
            role=role,
            span_id=self.id,
            tags=tags,
        )

    def record_measurement(
        self,
        name: str,
        measurement: Measurement,
        *,
        semantic_type: SemanticType = Semantic.TIME_LATENCY,
        unit: str = "ms",
        direction: Direction | None = Direction.MINIMIZE,
        role: ObservationRole | None = ObservationRole.DIAGNOSTIC,
        tags: dict[str, Any] | None = None,
        include_samples_artifact: bool = True,
    ) -> MeasurementRecord:
        return self._context.record_measurement(
            name,
            measurement,
            semantic_type=semantic_type,
            unit=unit,
            direction=direction,
            role=role,
            span_id=self.id,
            tags=tags,
            include_samples_artifact=include_samples_artifact,
        )

    def error(self, error: BaseException | ErrorRecord | str) -> ErrorRecord:
        return self._context.error(error, span_id=self.id)

    def artifact(
        self,
        name: str,
        value: Any,
        *,
        media_type: str | None = None,
        tags: dict[str, Any] | None = None,
    ) -> ArtifactRef:
        return self._context.artifact(
            name,
            value,
            media_type=media_type,
            span_id=self.id,
            tags=tags,
        )

SpanKind

Bases: StrEnum

Source code in src/autobench/runtime/context.py
61
62
63
64
65
66
67
68
class SpanKind(StrEnum):
    AGENT = "agent"
    LLM = "llm"
    TOOL = "tool"
    RETRIEVER = "retriever"
    PARSER = "parser"
    WORKFLOW = "workflow"
    CUSTOM = "custom"

SpanRecord

Bases: BaseModel

Source code in src/autobench/runtime/context.py
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
class SpanRecord(BaseModel):
    model_config = ConfigDict(populate_by_name=True)

    id: str
    name: str
    kind: SpanKind | str = SpanKind.CUSTOM
    parent_id: str | None = None
    started_at: datetime
    ended_at: datetime | None = None
    duration_seconds: float | None = None
    input: Any = None
    output: Any = None
    attributes: dict[str, Any] = Field(default_factory=dict)
    usage: dict[str, Any] = Field(default_factory=dict)
    observations: list[str] = Field(default_factory=list)
    artifacts: list[str] = Field(default_factory=list)
    error: ErrorRecord | None = None
    tags: dict[str, Any] = Field(default_factory=dict)

PydanticEvalCasePayload

Bases: BaseModel

Source code in src/autobench/runtime/evals.py
19
20
21
22
23
class PydanticEvalCasePayload(BaseModel):
    name: str
    inputs: dict[str, Any]
    expected_output: dict[str, Any]
    metadata: dict[str, Any]

PydanticEvalsBridge

Build Pydantic Evals-shaped payloads without owning evaluation execution.

Source code in src/autobench/runtime/evals.py
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
class PydanticEvalsBridge:
    """Build Pydantic Evals-shaped payloads without owning evaluation execution."""

    def __init__(self, *, module_name: str = "pydantic_evals") -> None:
        self.module_name = module_name

    def is_available(self) -> bool:
        return importlib.util.find_spec(self.module_name) is not None

    def require_module(self) -> ModuleType:
        if not self.is_available():
            raise PydanticEvalsUnavailableError(
                f"Optional runtime '{self.module_name}' is not installed."
            )
        return importlib.import_module(self.module_name)

    def case_payload(self, case: Case) -> PydanticEvalCasePayload:
        return PydanticEvalCasePayload(
            name=case.id,
            inputs=case.input,
            expected_output=case.expected,
            metadata={"tags": case.tags, **case.metadata},
        )

    def dataset_payload(self, spec: BenchmarkSpec) -> PydanticEvalsDatasetPayload:
        dataset_name = spec.dataset.id or spec.benchmark.id
        return PydanticEvalsDatasetPayload(
            name=dataset_name,
            cases=[self.case_payload(case) for case in spec.dataset.cases],
        )

PydanticEvalsDatasetPayload

Bases: BaseModel

Source code in src/autobench/runtime/evals.py
26
27
28
class PydanticEvalsDatasetPayload(BaseModel):
    name: str
    cases: list[PydanticEvalCasePayload]

PydanticEvalsUnavailableError

Bases: AutobenchError

Raised when the optional pydantic-evals runtime is requested but absent.

Source code in src/autobench/runtime/evals.py
15
16
class PydanticEvalsUnavailableError(AutobenchError):
    """Raised when the optional pydantic-evals runtime is requested but absent."""

BenchmarkPlan

Bases: BaseModel

Source code in src/autobench/runtime/pipeline.py
48
49
50
51
52
53
54
55
56
57
class BenchmarkPlan(BaseModel):
    benchmark_id: str
    dataset_id: str | None = None
    dataset_version: str | None = None
    dataset_hash: str | None = None
    case_ids: tuple[str, ...] = ()
    case_count: int
    variant_count: int
    planned_run_count: int
    warnings: list[str] = Field(default_factory=list)

EvaluationStatus

Bases: StrEnum

Source code in src/autobench/runtime/pipeline.py
67
68
69
70
71
72
class EvaluationStatus(StrEnum):
    PASSED = "passed"
    FAILED = "failed"
    ERRORED = "errored"
    SKIPPED = "skipped"
    NOT_EVALUATED = "not_evaluated"

ExperimentResult

Bases: BaseModel

Source code in src/autobench/runtime/pipeline.py
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
class ExperimentResult(BaseModel):
    experiment_id: str
    benchmark_id: str
    plan: BenchmarkPlan
    runs: list[RunResult]
    environment: EnvironmentMetadata
    report_spec_data: dict[str, Any] | None = None
    semantic_registry: SemanticRegistry = Field(
        default_factory=lambda: DEFAULT_SEMANTIC_REGISTRY.model_copy(deep=True)
    )
    spec_snapshot: dict[str, Any] | None = None
    spec_hash: str | None = None

    @property
    def total_count(self) -> int:
        return len(self.runs)

    @property
    def passed_count(self) -> int:
        return self.count_status(RunStatus.PASSED)

    @property
    def failed_count(self) -> int:
        return self.count_status(RunStatus.FAILED)

    @property
    def errored_count(self) -> int:
        return self.count_status(RunStatus.ERRORED)

    @property
    def skipped_count(self) -> int:
        return self.count_status(RunStatus.SKIPPED)

    def count_status(self, status: RunStatus) -> int:
        return sum(1 for run in self.runs if run.status is status)

MatrixRunSpec

Bases: BaseModel

Source code in src/autobench/runtime/pipeline.py
75
76
77
78
79
80
81
82
class MatrixRunSpec(BaseModel):
    run_id: str
    benchmark_id: str
    experiment_id: str
    case_index: int
    variant_index: int
    case: Case
    variant: Variant

RunResult

Bases: BaseModel

Source code in src/autobench/runtime/pipeline.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
class RunResult(BaseModel):
    run_id: str
    benchmark_id: str
    experiment_id: str
    case_id: str
    variant_id: str
    status: RunStatus
    evaluation_status: EvaluationStatus
    case: Case
    task_result: TaskResult
    scores: list[ScoreRecord] = Field(default_factory=list)
    factors: list[FactorValue] = Field(default_factory=list)
    asset_versions: list[AssetVersion] = Field(default_factory=list)
    parent_run_id: str | None = None
    error: ErrorRecord | None = None
    trace: Trace | None = None
    source_snapshots: tuple[SourceSnapshot, ...] = ()

RunStatus

Bases: StrEnum

Source code in src/autobench/runtime/pipeline.py
60
61
62
63
64
class RunStatus(StrEnum):
    PASSED = "passed"
    FAILED = "failed"
    ERRORED = "errored"
    SKIPPED = "skipped"

ProgressEvent

Bases: BaseModel

Source code in src/autobench/runtime/progress.py
19
20
21
22
23
24
25
26
27
28
class ProgressEvent(BaseModel):
    kind: ProgressEventKind
    message: str
    timestamp: datetime = Field(default_factory=lambda: datetime.now(UTC))
    benchmark_id: str | None = None
    experiment_id: str | None = None
    run_id: str | None = None
    case_id: str | None = None
    variant_id: str | None = None
    data: dict[str, Any] = Field(default_factory=dict)

ProgressEventKind

Bases: StrEnum

Source code in src/autobench/runtime/progress.py
10
11
12
13
14
15
16
class ProgressEventKind(StrEnum):
    BENCHMARK_STARTED = "benchmark_started"
    BENCHMARK_FINISHED = "benchmark_finished"
    RUN_STARTED = "run_started"
    RUN_FINISHED = "run_finished"
    CANDIDATE_DECISION = "candidate_decision"
    POLICY_VIOLATION = "policy_violation"

PydanticAIUsage

Bases: BaseModel

Source code in src/autobench/runtime/pydantic_ai.py
10
11
12
13
14
15
16
17
18
class PydanticAIUsage(BaseModel):
    requests: int | None = None
    input_tokens: int | None = None
    output_tokens: int | None = None
    total_tokens: int | None = None
    cache_read_tokens: int | None = None
    cache_write_tokens: int | None = None
    model_name: str | None = None
    provider: str | None = None

TaskResult

Bases: BaseModel

Source code in src/autobench/runtime/tasks.py
29
30
31
32
33
34
35
36
class TaskResult(BaseModel):
    output: Any = None
    status: TaskStatus
    error: ErrorRecord | None = None
    errors: list[ErrorRecord] = Field(default_factory=list)
    observations: list[Observation] = Field(default_factory=list)
    spans: list[SpanRecord] = Field(default_factory=list)
    artifacts: list[ArtifactRef] = Field(default_factory=list)

TaskStatus

Bases: StrEnum

Source code in src/autobench/runtime/tasks.py
22
23
24
25
26
class TaskStatus(StrEnum):
    PASSED = "passed"
    FAILED = "failed"
    ERRORED = "errored"
    SKIPPED = "skipped"

TraceEnvelope

Bases: BaseModel

Source code in src/autobench/runtime/traces.py
22
23
24
25
26
27
28
29
30
class TraceEnvelope(BaseModel):
    trace_id: str
    name: str
    input: Any = None
    output: Any = None
    spans: tuple[SpanRecord, ...] = ()
    attributes: dict[str, Any] = Field(default_factory=dict)
    errors: tuple[ErrorRecord, ...] = ()
    raw_artifact: ArtifactRef | None = None

BenchmarkInfo

Bases: BaseModel

Source code in src/autobench/spec/__init__.py
36
37
38
class BenchmarkInfo(BaseModel):
    id: str = Field(min_length=1)
    description: str | None = None

BenchmarkSpec

Bases: BaseModel

Source code in src/autobench/spec/__init__.py
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
class BenchmarkSpec(BaseModel):
    benchmark: BenchmarkInfo
    dataset: DatasetSpec = Field(default_factory=DatasetSpec)
    task: TaskSpec | None = None
    variants: list[Variant] = Field(default_factory=list)
    scoring: list[ScoringSpec] = Field(default_factory=list)
    derive: list[DeriverSpec] = Field(default_factory=list)
    post_derive: list[PostDeriverSpec] = Field(default_factory=list)
    policies: list[PolicySpec] = Field(default_factory=list)
    reports: ReportSpec = Field(default_factory=ReportSpec)
    instrumentation: list[InstrumentationConfig] = Field(default_factory=list)
    semantic_registry: SemanticRegistry = Field(
        default_factory=lambda: DEFAULT_SEMANTIC_REGISTRY.model_copy(deep=True)
    )

    @model_validator(mode="after")
    def _validate_unique_ids(self) -> BenchmarkSpec:
        _validate_unique_ids([case.id for case in self.dataset.cases], kind="case")
        _validate_unique_ids([variant.id for variant in self.variants], kind="variant")
        _validate_unique_ids(
            [config.kind for config in self.instrumentation],
            kind="instrumentation",
        )
        if self.task is None and self.dataset.cases and self.variants:
            raise ValueError(
                "task is required when cases and variants are defined for a runnable benchmark"
            )
        return self

TaskSpec

Bases: BaseModel

Source code in src/autobench/spec/__init__.py
41
42
43
44
class TaskSpec(BaseModel):
    kind: str = Field(min_length=1)
    target: str = Field(min_length=1)
    module_search_paths: tuple[str, ...] = Field(default_factory=tuple, exclude=True)

AssetVersion

Bases: BaseModel

Source code in src/autobench/tracking/models.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
class AssetVersion(BaseModel):
    model_config = ConfigDict(frozen=True)

    asset_id: str
    version: str
    content_hash: str
    source_hash: str | None = None
    source_path: str | None = None
    git_commit: str | None = None
    parent_version: str | None = None
    metadata: dict[str, SerializedValue] = Field(default_factory=dict)

    @property
    def hash(self) -> str:
        return self.content_hash

FieldAsset

Bases: BaseModel

Source code in src/autobench/tracking/models.py
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class FieldAsset(BaseModel):
    model_config = ConfigDict(frozen=True)

    name: str
    annotation: str | None = None
    required: bool
    default: SerializedValue = None
    default_factory: str | None = None
    description: str | None = None
    examples: tuple[SerializedValue, ...] = ()
    alias: str | None = None
    constraints: dict[str, SerializedValue] = Field(default_factory=dict)
    literal_choices: tuple[SerializedValue, ...] = ()
    metadata: dict[str, SerializedValue] = Field(default_factory=dict)
    init: bool | None = None
    kw_only: bool | None = None
    compare: bool | None = None
    repr: bool | None = None

ParamAsset

Bases: BaseModel

Source code in src/autobench/tracking/models.py
26
27
28
29
30
31
32
33
34
class ParamAsset(BaseModel):
    model_config = ConfigDict(frozen=True)

    name: str
    annotation: str | None = None
    required: bool
    default: SerializedValue = None
    kind: _ParamKind
    literal_choices: tuple[SerializedValue, ...] = ()

ParamSchema

Bases: BaseModel

Source code in src/autobench/tracking/models.py
37
38
39
40
class ParamSchema(BaseModel):
    model_config = ConfigDict(frozen=True)

    params: tuple[ParamAsset, ...] = ()

ToolAsset

Bases: TrackedAsset

Source code in src/autobench/tracking/models.py
73
74
75
76
77
78
79
80
81
class ToolAsset(TrackedAsset):
    model_config = ConfigDict(frozen=True)

    qualname: str | None = None
    doc: str | None = None
    param_schema: ParamSchema = ParamSchema()
    return_annotation: str | None = None
    return_type_name: str | None = None
    return_type_asset_id: str | None = None

TrackedAsset

Bases: BaseModel

Source code in src/autobench/tracking/models.py
63
64
65
66
67
68
69
70
class TrackedAsset(BaseModel):
    model_config = ConfigDict(frozen=True)

    id: str
    kind: str
    name: str
    semantic_type: SemanticType | None = None
    metadata: dict[str, SerializedValue] = Field(default_factory=dict)

TrackedPrompt

Bases: BaseModel

Source code in src/autobench/tracking/models.py
110
111
112
113
114
115
116
117
118
119
120
121
122
class TrackedPrompt(BaseModel):
    model_config = ConfigDict(frozen=True)

    asset: TrackedAsset
    version: str
    text: str

    @property
    def raw(self) -> str:
        return self.text

    def __str__(self) -> str:
        return self.raw

TrackingRegistry

Source code in src/autobench/tracking/registry.py
 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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
class TrackingRegistry:
    def __init__(self) -> None:
        self._versions_by_target_id: dict[int, AssetVersion] = {}
        self._assets_by_target_id: dict[int, TrackedAsset] = {}
        self._assets_by_name: dict[str, TrackedAsset] = {}
        self._latest_versions_by_asset_id: dict[str, AssetVersion] = {}
        self._version_history: list[AssetVersion] = []

    @property
    def assets(self) -> dict[str, TrackedAsset]:
        return dict(self._assets_by_name)

    @property
    def versions(self) -> tuple[AssetVersion, ...]:
        return tuple(self._version_history)

    def write_assets(self, directory: Path) -> None:
        directory.mkdir(parents=True, exist_ok=True)
        assets = sorted(self._assets_by_name.values(), key=lambda asset: asset.id)
        versions = [self._version_for_asset_id(asset.id) for asset in assets]
        for asset, version in zip(assets, versions, strict=True):
            asset_path = directory / f"{_safe_filename(asset.id)}.yaml"
            existing = load_yaml(asset_path) if asset_path.exists() else None
            dump_yaml(
                asset_to_yaml_view(asset, version, existing=existing),
                asset_path,
                schema_name="asset",
            )
        dump_yaml(
            asset_index_to_yaml_view(assets, versions),
            directory / "index.yaml",
            schema_name="asset_index",
        )

    def _version_for_asset_id(self, asset_id: str) -> AssetVersion:
        try:
            return self._latest_versions_by_asset_id[asset_id]
        except KeyError as exc:
            raise KeyError(f"Asset version is missing for {asset_id}.") from exc

    def asset(
        self,
        *,
        kind: str,
        name: str,
        semantic_type: SemanticType | None = None,
        version: str | None = None,
        hash: str | None = None,
        source_path: str | Path | None = None,
        parent_version: str | None = None,
        metadata: dict[str, SerializedValue] | None = None,
        source_hash: str | None = None,
    ) -> Callable[[_T], _T]:
        def decorator(target: _T) -> _T:
            asset = TrackedAsset(
                id=f"{kind}.{name}",
                kind=kind,
                name=name,
                semantic_type=semantic_type,
                metadata=dict(metadata or {}),
            )
            content_hash = hash or _source_hash(target) or _hash_text(repr(target))
            version_record = AssetVersion(
                asset_id=asset.id,
                version=version or content_hash[:12],
                content_hash=content_hash,
                source_hash=source_hash or _source_hash(target),
                source_path=str(source_path) if source_path is not None else _source_path(target),
                parent_version=parent_version,
                metadata=dict(metadata or {}),
            )
            self._register(target, asset, version_record)
            return target

        return decorator

    @overload
    def tool(
        self,
        target: Callable[_ParamT, _ReturnT],
        *,
        name: str | None = None,
        semantic_type: SemanticType | None = Semantic.AGENT_TOOL_VERSION,
        version: str | None = None,
        source_path: str | Path | None = None,
        parent_version: str | None = None,
        metadata: dict[str, SerializedValue] | None = None,
    ) -> Callable[_ParamT, _ReturnT]: ...

    @overload
    def tool(
        self,
        target: None = None,
        *,
        name: str | None = None,
        semantic_type: SemanticType | None = Semantic.AGENT_TOOL_VERSION,
        version: str | None = None,
        source_path: str | Path | None = None,
        parent_version: str | None = None,
        metadata: dict[str, SerializedValue] | None = None,
    ) -> Callable[[Callable[_ParamT, _ReturnT]], Callable[_ParamT, _ReturnT]]: ...

    def tool(
        self,
        target: Callable[..., Any] | None = None,
        *,
        name: str | None = None,
        semantic_type: SemanticType | None = Semantic.AGENT_TOOL_VERSION,
        version: str | None = None,
        source_path: str | Path | None = None,
        parent_version: str | None = None,
        metadata: dict[str, SerializedValue] | None = None,
    ) -> Callable[..., Any] | Callable[[Callable[..., Any]], Callable[..., Any]]:
        def decorator(
            tool_target: Callable[_ParamT, _ReturnT],
        ) -> Callable[_ParamT, _ReturnT]:
            if not callable(tool_target):
                raise TypeError("@track.tool can only decorate callables.")
            tool_name = name or _callable_name(tool_target)
            tool_asset = _build_tool_asset(
                tool_target,
                name=tool_name,
                semantic_type=semantic_type,
                metadata=dict(metadata or {}),
                registry=self,
            )
            content_hash = _hash_serialized(tool_asset.model_dump(mode="python"))
            version_record = AssetVersion(
                asset_id=tool_asset.id,
                version=version or content_hash[:12],
                content_hash=content_hash,
                source_hash=_source_hash(tool_target),
                source_path=str(source_path)
                if source_path is not None
                else _source_path(tool_target),
                parent_version=parent_version,
                metadata=tool_asset.metadata,
            )
            self._register(tool_target, tool_asset, version_record)
            return tool_target

        if target is None:
            return decorator
        return decorator(target)

    @overload
    def type(
        self,
        target: _TypeT,
        *,
        name: str | None = None,
        semantic_type: SemanticType | None = None,
        version: str | None = None,
        source_path: str | Path | None = None,
        parent_version: str | None = None,
        metadata: dict[str, SerializedValue] | None = None,
    ) -> _TypeT: ...

    @overload
    def type(
        self,
        target: None = None,
        *,
        name: str | None = None,
        semantic_type: SemanticType | None = None,
        version: str | None = None,
        source_path: str | Path | None = None,
        parent_version: str | None = None,
        metadata: dict[str, SerializedValue] | None = None,
    ) -> Callable[[_TypeT], _TypeT]: ...

    def type(
        self,
        target: _TypeT | None = None,
        *,
        name: str | None = None,
        semantic_type: SemanticType | None = None,
        version: str | None = None,
        source_path: str | Path | None = None,
        parent_version: str | None = None,
        metadata: dict[str, SerializedValue] | None = None,
    ) -> _TypeT | Callable[[_TypeT], _TypeT]:
        def decorator(type_target: _TypeT) -> _TypeT:
            if not isinstance(type_target, type):
                raise TypeError("@track.type can only decorate classes.")
            type_name = name or type_target.__name__
            type_asset = _build_type_asset(
                type_target,
                name=type_name,
                semantic_type=semantic_type,
                metadata=dict(metadata or {}),
            )
            content_hash = _hash_structured_type(type_target)
            version_record = AssetVersion(
                asset_id=type_asset.id,
                version=version or content_hash[:12],
                content_hash=content_hash,
                source_hash=_source_hash(type_target),
                source_path=str(source_path)
                if source_path is not None
                else _source_path(type_target),
                parent_version=parent_version,
                metadata=type_asset.metadata,
            )
            self._register(type_target, type_asset, version_record)
            return type_target

        if target is None:
            return decorator
        return decorator(target)

    def decorate_type(
        self,
        class_decorator: TypeDecorator[_DecoratorParamT],
        /,
        *decorator_args: _DecoratorParamT.args,
        **decorator_kwargs: _DecoratorParamT.kwargs,
    ) -> Callable[[_TypeT], _TypeT]:
        decorator_metadata: dict[str, SerializedValue] = {
            "decorator": {
                "name": _callable_name(class_decorator),
                "module": (
                    class_decorator.__module__
                    if isinstance(class_decorator.__module__, str)
                    else None
                ),
                "args": [_normalize_value(value) for value in decorator_args],
                "kwargs": {
                    key: _normalize_value(value) for key, value in sorted(decorator_kwargs.items())
                },
            }
        }

        def decorator(type_target: _TypeT) -> _TypeT:
            decorated_target = class_decorator(type_target, *decorator_args, **decorator_kwargs)
            if not isinstance(decorated_target, type):
                raise TypeError(
                    "@track.decorate_type requires a class decorator that returns a class."
                )
            return self.type(decorated_target, metadata=decorator_metadata)

        return decorator

    @overload
    def dataclass(
        self,
        target: _TypeT,
        *,
        init: bool = True,
        repr: bool = True,
        eq: bool = True,
        order: bool = False,
        unsafe_hash: bool = False,
        frozen: bool = False,
        match_args: bool = True,
        kw_only: bool = False,
        slots: bool = False,
        weakref_slot: bool = False,
    ) -> _TypeT: ...

    @overload
    def dataclass(
        self,
        target: None = None,
        *,
        init: bool = True,
        repr: bool = True,
        eq: bool = True,
        order: bool = False,
        unsafe_hash: bool = False,
        frozen: bool = False,
        match_args: bool = True,
        kw_only: bool = False,
        slots: bool = False,
        weakref_slot: bool = False,
    ) -> Callable[[_TypeT], _TypeT]: ...

    @dataclass_transform(field_specifiers=(stdlib_field,))
    def dataclass(
        self,
        target: _TypeT | None = None,
        *,
        init: bool = True,
        repr: bool = True,
        eq: bool = True,
        order: bool = False,
        unsafe_hash: bool = False,
        frozen: bool = False,
        match_args: bool = True,
        kw_only: bool = False,
        slots: bool = False,
        weakref_slot: bool = False,
    ) -> _TypeT | Callable[[_TypeT], _TypeT]:
        decorator_metadata: dict[str, SerializedValue] = {
            "decorator": {
                "name": "dataclass",
                "module": "dataclasses",
                "args": [],
                "kwargs": {
                    key: _normalize_value(value)
                    for key, value in sorted(
                        {
                            "init": init,
                            "repr": repr,
                            "eq": eq,
                            "order": order,
                            "unsafe_hash": unsafe_hash,
                            "frozen": frozen,
                            "match_args": match_args,
                            "kw_only": kw_only,
                            "slots": slots,
                            "weakref_slot": weakref_slot,
                        }.items()
                    )
                },
            }
        }

        def decorator(type_target: _TypeT) -> _TypeT:
            dataclass_decorator = stdlib_dataclass(
                init=init,
                repr=repr,
                eq=eq,
                order=order,
                unsafe_hash=unsafe_hash,
                frozen=frozen,
                match_args=match_args,
                kw_only=kw_only,
                slots=slots,
                weakref_slot=weakref_slot,
            )
            decorated_target = dataclass_decorator(cast(type[Any], type_target))
            return self.type(cast(_TypeT, decorated_target), metadata=decorator_metadata)

        if target is None:
            return decorator
        return decorator(target)

    def prompt(
        self,
        *,
        name: str,
        text: str | None = None,
        source: str | Path | None = None,
        semantic_type: SemanticType | None = Semantic.PROMPT_VERSION,
        version: str | None = None,
        hash: str | None = None,
        parent_version: str | None = None,
        metadata: dict[str, SerializedValue] | None = None,
    ) -> TrackedPrompt:
        if (text is None) == (source is None):
            raise ValueError("track.prompt requires exactly one of 'text' or 'source'.")
        prompt_text = text
        prompt_source_path: str | None = None
        if source is not None:
            source_path = Path(source).expanduser().resolve()
            prompt_text = source_path.read_text(encoding="utf-8")
            prompt_source_path = str(source_path)
        assert prompt_text is not None
        prompt_metadata = dict(metadata or {})
        prompt_metadata["raw"] = prompt_text
        asset = TrackedAsset(
            id=f"prompt.{name}",
            kind="prompt",
            name=name,
            semantic_type=semantic_type,
            metadata=prompt_metadata,
        )
        content_hash = hash or _hash_text(prompt_text)
        prompt = TrackedPrompt(asset=asset, version=version or content_hash[:12], text=prompt_text)
        self._register(
            prompt,
            asset,
            AssetVersion(
                asset_id=asset.id,
                version=prompt.version,
                content_hash=content_hash,
                source_hash=content_hash if prompt_source_path is not None else None,
                source_path=prompt_source_path,
                parent_version=parent_version,
                metadata=prompt_metadata,
            ),
        )
        return prompt

    def asset_of(self, target: Any) -> TrackedAsset:
        try:
            return self._assets_by_target_id[id(target)]
        except KeyError as exc:
            raise KeyError("Object is not tracked by Autobench.") from exc

    def version_of(self, target: Any) -> str:
        return self.asset_version_of(target).version

    def asset_version_of(self, target: Any) -> AssetVersion:
        try:
            return self._versions_by_target_id[id(target)]
        except KeyError as exc:
            raise KeyError("Object is not tracked by Autobench.") from exc

    def _register(self, target: Any, asset: TrackedAsset, version: AssetVersion) -> None:
        target_id = id(target)
        self._assets_by_target_id[target_id] = asset
        self._versions_by_target_id[target_id] = version
        self._assets_by_name[asset.name] = asset
        self._latest_versions_by_asset_id[asset.id] = version
        self._version_history.append(version)

TypeAsset

Bases: TrackedAsset

Source code in src/autobench/tracking/models.py
84
85
86
87
88
89
90
class TypeAsset(TrackedAsset):
    model_config = ConfigDict(frozen=True)

    qualname: str | None = None
    doc: str | None = None
    type_kind: _StructuredTypeKind
    field_assets: tuple[FieldAsset, ...] = ()

dataset_content_hash

dataset_content_hash(dataset: DatasetSpec) -> str
Source code in src/autobench/data/datasets.py
80
81
82
83
84
85
86
87
def dataset_content_hash(dataset: DatasetSpec) -> str:
    payload = dataset.model_dump(
        mode="json",
        exclude={"source"},
        exclude_none=True,
    )
    rendered = json.dumps(payload, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(rendered.encode("utf-8")).hexdigest()

dataset_to_yaml_view

dataset_to_yaml_view(
    dataset: DatasetSpec,
) -> dict[str, Any]
Source code in src/autobench/data/datasets.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
def dataset_to_yaml_view(dataset: DatasetSpec) -> dict[str, Any]:
    dataset_view: dict[str, Any] = {
        "id": dataset.id or "inline",
        "cases": [case_to_yaml_view(case) for case in dataset.cases],
    }
    view: dict[str, Any] = {
        "record": {
            "type": "dataset",
            "version": 1,
        },
        "dataset": dataset_view,
    }
    if dataset.source is not None:
        dataset_view["source"] = dataset.source
    if dataset.version is not None:
        dataset_view["version"] = dataset.version
    if dataset.metadata:
        dataset_view["metadata"] = dataset.metadata
    defaults_view = _case_defaults_yaml_view(dataset.case_defaults)
    if defaults_view:
        dataset_view["defaults"] = defaults_view
    return view

merge_case_defaults

merge_case_defaults(
    case: Case, defaults: CaseDefaults
) -> Case
Source code in src/autobench/data/datasets.py
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
def merge_case_defaults(case: Case, defaults: CaseDefaults) -> Case:
    merged_input = _merge_value(defaults.input, case.input)
    merged_expected = _merge_value(defaults.expected, case.expected)
    merged_metadata = _merge_mapping(defaults.metadata, case.metadata)
    merged_tags = _merge_tags(defaults.tags, case.tags)
    merged_attachments = [*defaults.attachments, *case.attachments]
    return case.model_copy(
        update={
            "input": merged_input,
            "expected": merged_expected,
            "metadata": merged_metadata,
            "tags": merged_tags,
            "attachments": merged_attachments,
        }
    )

generated_batch_from_cases

generated_batch_from_cases(
    cases: list[Case],
    *,
    generator_asset_version: str | None = None,
    model_provider: str | None = None,
    model_name: str | None = None,
) -> GeneratedCaseBatch
Source code in src/autobench/data/generation.py
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
def generated_batch_from_cases(
    cases: list[Case],
    *,
    generator_asset_version: str | None = None,
    model_provider: str | None = None,
    model_name: str | None = None,
) -> GeneratedCaseBatch:
    marked_cases = tuple(
        mark_generated_case(
            case,
            generator_asset_version=generator_asset_version,
            model_provider=model_provider,
            model_name=model_name,
        )
        for case in cases
    )
    return GeneratedCaseBatch(
        generator_asset_version=generator_asset_version,
        model_provider=model_provider,
        model_name=model_name,
        cases=marked_cases,
    )

mark_generated_case

mark_generated_case(
    case: Case,
    *,
    generator_asset_version: str | None = None,
    model_provider: str | None = None,
    model_name: str | None = None,
    review_status: ReviewStatus = ReviewStatus.CANDIDATE,
) -> Case
Source code in src/autobench/data/generation.py
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
def mark_generated_case(
    case: Case,
    *,
    generator_asset_version: str | None = None,
    model_provider: str | None = None,
    model_name: str | None = None,
    review_status: ReviewStatus = ReviewStatus.CANDIDATE,
) -> Case:
    metadata = dict(case.metadata)
    metadata["source"] = "synthetic"
    metadata["review_status"] = review_status.value
    if generator_asset_version is not None:
        metadata["generator_asset_version"] = generator_asset_version
    if model_provider is not None:
        metadata["model_provider"] = model_provider
    if model_name is not None:
        metadata["model_name"] = model_name
    return case.model_copy(update={"metadata": metadata})

sample_to_case

sample_to_case(sample: ProductionSample) -> Case
Source code in src/autobench/data/ingestion.py
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
def sample_to_case(sample: ProductionSample) -> Case:
    metadata = dict(sample.metadata)
    metadata["source"] = "production"
    metadata["sample_reason"] = sample.reason.value
    metadata["review_status"] = sample.review_status.value
    if sample.timestamp is not None:
        metadata["timestamp"] = sample.timestamp.isoformat()
    if sample.privacy_tags:
        metadata["privacy_tags"] = list(sample.privacy_tags)
    if sample.trace is not None:
        metadata["trace_id"] = sample.trace.trace_id
    return Case(
        id=sample.id,
        input=sample.input,
        expected=sample.expected,
        metadata=metadata,
    )

samples_to_cases

samples_to_cases(
    samples: list[ProductionSample],
    *,
    policy: SamplingPolicy | None = None,
) -> list[Case]
Source code in src/autobench/data/ingestion.py
64
65
66
67
68
69
70
71
72
73
74
75
def samples_to_cases(
    samples: list[ProductionSample],
    *,
    policy: SamplingPolicy | None = None,
) -> list[Case]:
    active_policy = policy or SamplingPolicy()
    selected: list[ProductionSample] = [
        sample for sample in samples if sample.reason in active_policy.reasons
    ]
    if active_policy.max_samples is not None:
        selected = selected[: active_policy.max_samples]
    return [sample_to_case(sample) for sample in selected]

normalize_variant_factors

normalize_variant_factors(
    raw_factors: list[FactorValue]
    | list[dict[str, Any]]
    | dict[str, Any]
    | None,
) -> list[FactorValue]
Source code in src/autobench/data/variants.py
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
def normalize_variant_factors(
    raw_factors: list[FactorValue] | list[dict[str, Any]] | dict[str, Any] | None,
) -> list[FactorValue]:
    if raw_factors is None:
        return []

    if isinstance(raw_factors, list):
        normalized: list[FactorValue] = []
        for item in raw_factors:
            if isinstance(item, FactorValue):
                normalized.append(item)
            else:
                normalized.append(FactorValue.model_validate(item))
        return normalized

    normalized = []
    for name, raw_value in raw_factors.items():
        if isinstance(raw_value, dict):
            payload = dict(raw_value)
            payload.setdefault("name", name)
        else:
            payload = {"name": name, "value": raw_value}
        normalized.append(FactorValue.model_validate(payload))
    return normalized

action_metric_score

action_metric_score(
    expected_actions: list[ExpectedAction],
    observed_spans: list[SpanRecord],
    *,
    metric: ActionMetric,
) -> float
Source code in src/autobench/evaluation/actions.py
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
def action_metric_score(
    expected_actions: list[ExpectedAction],
    observed_spans: list[SpanRecord],
    *,
    metric: ActionMetric,
) -> float:
    required_actions = [action for action in expected_actions if action.required]
    if not required_actions:
        return 1.0
    matches = match_expected_actions(required_actions, observed_spans)
    if metric == "selection":
        return _ratio(match.target_matched for match in matches)
    if metric == "arguments":
        return _ratio(match.input_matched for match in matches if match.target_matched)
    return 1.0 if _sequence_matches(required_actions, observed_spans) else 0.0

expected_actions_from_case

expected_actions_from_case(
    case: Case,
) -> list[ExpectedAction]
Source code in src/autobench/evaluation/actions.py
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
def expected_actions_from_case(case: Case) -> list[ExpectedAction]:
    expected = case.expected
    if not isinstance(expected, dict):
        return []
    raw_actions = expected.get("actions", expected.get("tool_calls", []))
    if not isinstance(raw_actions, list):
        return []
    actions: list[ExpectedAction] = []
    for index, raw_action in enumerate(raw_actions):
        if not isinstance(raw_action, dict):
            continue
        action_payload = dict(raw_action)
        action_payload.setdefault("id", f"action_{index + 1}")
        if "tool" in action_payload and "target" not in action_payload:
            action_payload["target"] = action_payload["tool"]
        if "args" in action_payload and "input" not in action_payload:
            action_payload["input"] = action_payload["args"]
        actions.append(ExpectedAction.model_validate(action_payload))
    return actions

match_expected_actions

match_expected_actions(
    expected_actions: list[ExpectedAction],
    observed_spans: list[SpanRecord],
) -> list[ActionMatchResult]
Source code in src/autobench/evaluation/actions.py
71
72
73
74
75
76
77
78
79
def match_expected_actions(
    expected_actions: list[ExpectedAction],
    observed_spans: list[SpanRecord],
) -> list[ActionMatchResult]:
    matches: list[ActionMatchResult] = []
    for action in expected_actions:
        match = _match_action(action, observed_spans)
        matches.append(match)
    return matches

observed_action_spans

observed_action_spans(
    spans: list[SpanRecord], *, kind: str = "tool"
) -> list[SpanRecord]
Source code in src/autobench/evaluation/actions.py
63
64
65
66
67
68
def observed_action_spans(spans: list[SpanRecord], *, kind: str = "tool") -> list[SpanRecord]:
    return [
        span
        for span in spans
        if str(span.kind) == kind or (kind == "tool" and str(span.kind) == SpanKind.TOOL.value)
    ]

classify_metric_comparison

classify_metric_comparison(
    *,
    baseline: float,
    candidate: float,
    direction: Direction | None,
    threshold_pct: float = 0.0,
) -> ComparisonVerdict
Source code in src/autobench/evaluation/comparison.py
295
296
297
298
299
300
301
302
303
304
305
306
307
308
def classify_metric_comparison(
    *,
    baseline: float,
    candidate: float,
    direction: Direction | None,
    threshold_pct: float = 0.0,
) -> ComparisonVerdict:
    if _relative_delta_pct(baseline=baseline, candidate=candidate) <= threshold_pct:
        return "unchanged"
    if direction is Direction.MAXIMIZE:
        return "improved" if candidate > baseline else "regressed"
    if direction is Direction.MINIMIZE:
        return "improved" if candidate < baseline else "regressed"
    return "inconclusive"

derive_experiment_observations

derive_experiment_observations(
    post_derive: list[PostDeriverSpec],
    *,
    result: ExperimentResult,
    registry: SemanticRegistry | None = None,
) -> ExperimentResult
Source code in src/autobench/evaluation/comparison.py
72
73
74
75
76
77
78
79
80
81
82
83
84
85
def derive_experiment_observations(
    post_derive: list[PostDeriverSpec],
    *,
    result: ExperimentResult,
    registry: SemanticRegistry | None = None,
) -> ExperimentResult:
    if not post_derive:
        return result

    active_registry = registry or DEFAULT_SEMANTIC_REGISTRY
    runs = result.runs
    for spec in post_derive:
        runs = _apply_paired_baseline_deriver(spec, runs=runs, registry=active_registry)
    return result.model_copy(update={"runs": runs})

derive_observations

derive_observations(
    derive: list[DeriverSpec],
    *,
    ctx: RunContext,
    observations: list[Observation],
    registry: SemanticRegistry | None = None,
) -> list[Observation]
Source code in src/autobench/evaluation/derivation.py
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
def derive_observations(
    derive: list[DeriverSpec],
    *,
    ctx: RunContext,
    observations: list[Observation],
    registry: SemanticRegistry | None = None,
) -> list[Observation]:
    active_registry = registry or DEFAULT_SEMANTIC_REGISTRY
    derived: list[Observation] = []
    for spec in derive:
        deriver = build_deriver(spec)
        result = deriver.derive(
            ctx=ctx,
            observations=[*observations, *derived],
            registry=active_registry,
        )
        derived.extend(result)
    return derived

build_feedback_records

build_feedback_records(
    record: RunRecord,
) -> tuple[FeedbackRecord, ...]
Source code in src/autobench/evaluation/feedback.py
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
def build_feedback_records(record: RunRecord) -> tuple[FeedbackRecord, ...]:
    feedback: list[FeedbackRecord] = []
    for score in record.scores:
        passed = _score_passed(score.value)
        if passed is True:
            continue
        feedback.append(
            FeedbackRecord(
                score_name=score.name,
                semantic_type=score.semantic_type,
                score=score.value,
                passed=passed,
                reason=_score_reason(score.tags),
                failure_category=_score_failure_category(score.value, score.error is not None),
                related_spans=() if score.span_id is None else (score.span_id,),
                related_assets=tuple(asset.asset_id for asset in record.asset_versions),
            )
        )
    for error in record.errors:
        feedback.append(
            FeedbackRecord(
                reason=error.message,
                failure_category="error",
                related_spans=() if error.span_id is None else (error.span_id,),
                related_assets=tuple(asset.asset_id for asset in record.asset_versions),
            )
        )
    for observation in record.observations:
        if observation.role is ObservationRole.CONSTRAINT and observation.value is False:
            feedback.append(
                FeedbackRecord(
                    score_name=observation.name,
                    semantic_type=observation.semantic_type,
                    score=False,
                    passed=False,
                    reason=_score_reason(observation.tags),
                    failure_category="constraint",
                    related_spans=() if observation.span_id is None else (observation.span_id,),
                    related_assets=tuple(asset.asset_id for asset in record.asset_versions),
                )
            )
    return tuple(feedback)

build_optimization_feedback_input

build_optimization_feedback_input(
    record: RunRecord,
) -> OptimizationFeedbackInput
Source code in src/autobench/evaluation/feedback.py
79
80
81
82
83
84
85
86
87
88
89
90
def build_optimization_feedback_input(record: RunRecord) -> OptimizationFeedbackInput:
    return OptimizationFeedbackInput(
        run_id=record.run_id,
        case_id=record.case_id,
        variant_id=record.variant_id,
        task_status=record.task_status.value,
        evaluation_status=record.evaluation_status.value,
        factors={factor.name: factor.value for factor in record.factors},
        asset_versions={asset.asset_id: asset.version for asset in record.asset_versions},
        feedback=build_feedback_records(record),
        trace_excerpt=tuple(_span_excerpt(span) for span in record.spans),
    )

measure_callable

measure_callable(
    fn: Callable[[], MeasuredValue],
    *,
    warmup: int = 0,
    repetitions: int = 1,
    max_seconds: float | None = None,
    budget: MeasurementBudget | None = None,
    timer: MeasurementTimer[MeasuredValue] | None = None,
) -> Measurement
Source code in src/autobench/evaluation/measurement.py
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
def measure_callable(
    fn: Callable[[], MeasuredValue],
    *,
    warmup: int = 0,
    repetitions: int = 1,
    max_seconds: float | None = None,
    budget: MeasurementBudget | None = None,
    timer: MeasurementTimer[MeasuredValue] | None = None,
) -> Measurement:
    if budget is not None:
        warmup = budget.warmup
        repetitions = budget.repetitions
        max_seconds = budget.max_seconds

    if warmup < 0:
        raise ValueError("warmup cannot be negative")
    if repetitions < 1:
        raise ValueError("repetitions must be at least 1")
    if max_seconds is not None and max_seconds < 0.0:
        raise ValueError("max_seconds cannot be negative")

    active_timer = timer or perf_counter_timer
    for _ in range(warmup):
        fn()

    samples: list[float] = []
    started_at = perf_counter()
    timed_out = False
    for repetition_index in range(repetitions):
        duration_seconds = active_timer(fn)
        if duration_seconds < 0.0:
            raise ValueError("measurement timer returned a negative duration")
        samples.append(duration_seconds)

        has_more_repetitions = repetition_index < repetitions - 1
        if max_seconds is not None and has_more_repetitions:
            timed_out = perf_counter() - started_at >= max_seconds
            if timed_out:
                break

    return Measurement(
        samples_seconds=tuple(samples),
        warmup=warmup,
        requested_repetitions=repetitions,
        elapsed_seconds=perf_counter() - started_at,
        timed_out=timed_out,
    )

perf_counter_timer

perf_counter_timer(
    fn: Callable[[], MeasuredValue],
) -> float
Source code in src/autobench/evaluation/measurement.py
 98
 99
100
101
def perf_counter_timer(fn: Callable[[], MeasuredValue]) -> float:
    started_at = perf_counter()
    fn()
    return perf_counter() - started_at

apply_policies

apply_policies(
    policies: list[PolicySpec],
    *,
    result: ExperimentResult,
    registry: SemanticRegistry | None = None,
) -> ExperimentResult
Source code in src/autobench/evaluation/policies.py
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
def apply_policies(
    policies: list[PolicySpec],
    *,
    result: ExperimentResult,
    registry: SemanticRegistry | None = None,
) -> ExperimentResult:
    if not policies:
        return result

    active_registry = registry or DEFAULT_SEMANTIC_REGISTRY
    updated_runs = [
        _append_policy_observations(
            run,
            evaluate_run_policies(policies, run=run, registry=active_registry),
        )
        for run in result.runs
    ]
    return result.model_copy(update={"runs": updated_runs})

evaluate_policies

evaluate_policies(
    policies: list[PolicySpec],
    *,
    result: ExperimentResult,
    registry: SemanticRegistry | None = None,
) -> list[PolicyResult]
Source code in src/autobench/evaluation/policies.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
def evaluate_policies(
    policies: list[PolicySpec],
    *,
    result: ExperimentResult,
    registry: SemanticRegistry | None = None,
) -> list[PolicyResult]:
    active_registry = registry or DEFAULT_SEMANTIC_REGISTRY
    return [
        policy_result
        for run in result.runs
        for policy_result in evaluate_run_policies(policies, run=run, registry=active_registry)
    ]

evaluate_run_policies

evaluate_run_policies(
    policies: list[PolicySpec],
    *,
    run: RunResult,
    registry: SemanticRegistry | None = None,
) -> list[PolicyResult]
Source code in src/autobench/evaluation/policies.py
106
107
108
109
110
111
112
def evaluate_run_policies(
    policies: list[PolicySpec],
    *,
    run: RunResult,
    registry: SemanticRegistry | None = None,
) -> list[PolicyResult]:
    return [_evaluate_policy(policy, run=run, registry=registry) for policy in policies]

dump_pricing_table

dump_pricing_table(table: PricingTable, path: Path) -> str
Source code in src/autobench/evaluation/pricing.py
223
224
def dump_pricing_table(table: PricingTable, path: Path) -> str:
    return dump_yaml(pricing_table_to_yaml_view(table), path, schema_name="pricing")

load_pricing_table

load_pricing_table(path: Path) -> PricingTable
Source code in src/autobench/evaluation/pricing.py
187
188
189
190
191
192
193
194
195
196
197
198
199
def load_pricing_table(path: Path) -> PricingTable:
    raw = load_yaml(path)
    if raw is None:
        raw = {}
    if isinstance(raw, list):
        return GenAIPricesSource(_required_mapping_list(raw, str(path))).pricing_table()
    if not isinstance(raw, dict):
        raise ValueError(f"Expected pricing YAML mapping in {path}.")
    if isinstance(raw.get("prices"), list):
        return LLMPricesSource(raw).pricing_table()
    if isinstance(raw.get("pricing"), dict):
        raw = raw["pricing"]
    return _load_pricing_mapping(raw)

pricing_table_to_yaml_view

pricing_table_to_yaml_view(
    table: PricingTable,
) -> dict[str, Any]
Source code in src/autobench/evaluation/pricing.py
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
def pricing_table_to_yaml_view(table: PricingTable) -> dict[str, Any]:
    pricing_view: dict[str, Any] = {}
    if table.provider is not None:
        pricing_view["provider"] = table.provider
    if table.source is not None:
        pricing_view["source"] = table.source
    if table.updated_at is not None:
        pricing_view["updated_at"] = table.updated_at
    pricing_view["models"] = {
        model_id: _model_pricing_yaml_view(pricing)
        for model_id, pricing in _iter_pricing_entries(table)
    }
    return {
        "record": {
            "type": "pricing",
            "version": 1,
        },
        "pricing": pricing_view,
    }

resolve_dotted_path

resolve_dotted_path(
    subjects: dict[str, Any], path: str
) -> Any
Source code in src/autobench/evaluation/scoring.py
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
def resolve_dotted_path(subjects: dict[str, Any], path: str) -> Any:
    current: Any = subjects
    for part in path.split("."):
        if isinstance(current, dict):
            if part not in current:
                raise KeyError(f"Path segment '{part}' not found in mapping.")
            current = current[part]
        else:
            if not hasattr(current, part):
                raise KeyError(
                    f"Path segment '{part}' not found on object '{type(current).__name__}'."
                )
            current = getattr(current, part)
        if callable(current):
            current = current()
    return current

select_spans

select_spans(
    selector: SpanSelector | None,
    *,
    spans: list[SpanRecord],
    observations: list[Observation],
    registry: SemanticRegistry | None = None,
) -> list[SpanRecord]
Source code in src/autobench/evaluation/spans.py
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
def select_spans(
    selector: SpanSelector | None,
    *,
    spans: list[SpanRecord],
    observations: list[Observation],
    registry: SemanticRegistry | None = None,
) -> list[SpanRecord]:
    if selector is None:
        return list(spans)

    active_registry = registry or DEFAULT_SEMANTIC_REGISTRY
    selected: list[SpanRecord] = []
    for span in spans:
        if selector.kind is not None and str(span.kind) != selector.kind:
            continue
        if selector.name is not None and span.name != selector.name:
            continue
        if selector.path is not None and _span_path(span, spans=spans) != selector.path:
            continue
        if selector.tag and not _contains_tag_values(span.tags, selector.tag):
            continue
        if selector.semantic_type is not None and not _span_has_semantic(
            span,
            observations=observations,
            semantic_type=selector.semantic_type,
            registry=active_registry,
        ):
            continue
        selected.append(span)
    return selected

check_package_compatibility

check_package_compatibility(
    info: InstrumentorInfo,
) -> Compatibility
Source code in src/autobench/instrumentation/manager.py
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
def check_package_compatibility(info: InstrumentorInfo) -> Compatibility:
    distribution = info.target_distribution
    target_version = None
    if distribution is not None:
        try:
            target_version = version(distribution)
        except PackageNotFoundError:
            return Compatibility(
                status=CompatibilityStatus.UNAVAILABLE,
                diagnostics=(f"distribution '{distribution}' is not installed",),
            )
        if info.supported_versions is not None:
            try:
                supported = Version(target_version) in SpecifierSet(info.supported_versions)
            except (InvalidSpecifier, InvalidVersion) as exc:
                return Compatibility(
                    status=CompatibilityStatus.UNSUPPORTED,
                    target_version=target_version,
                    diagnostics=(f"invalid version compatibility declaration: {exc}",),
                )
            if not supported:
                return Compatibility(
                    status=CompatibilityStatus.UNSUPPORTED,
                    target_version=target_version,
                    diagnostics=(
                        f"distribution '{distribution}' {target_version} is outside "
                        f"{info.supported_versions}",
                    ),
                )

    degraded_features: list[str] = []
    diagnostics: list[str] = []
    for declaration in info.optional_dependencies:
        try:
            requirement = Requirement(declaration)
        except InvalidRequirement as exc:
            degraded_features.append(declaration)
            diagnostics.append(f"invalid optional dependency declaration '{declaration}': {exc}")
            continue
        if requirement.marker is not None and not requirement.marker.evaluate():
            continue
        try:
            dependency_version = Version(version(requirement.name))
        except (PackageNotFoundError, InvalidVersion):
            degraded_features.append(requirement.name)
            diagnostics.append(f"optional dependency '{declaration}' is unavailable")
            continue
        if requirement.specifier and dependency_version not in requirement.specifier:
            degraded_features.append(requirement.name)
            diagnostics.append(
                f"optional dependency '{requirement.name}' {dependency_version} is outside "
                f"{requirement.specifier}"
            )

    if degraded_features:
        return Compatibility(
            status=CompatibilityStatus.DEGRADED,
            target_version=target_version,
            degraded_features=tuple(degraded_features),
            diagnostics=tuple(diagnostics),
        )
    return Compatibility.compatible(target_version=target_version)

instrumentor_statuses

instrumentor_statuses() -> tuple[InstrumentorStatus, ...]

Inspect every built-in integration without importing unavailable SDKs.

Source code in src/autobench/instrumentation/registry.py
202
203
204
205
206
207
208
209
def instrumentor_statuses() -> tuple[InstrumentorStatus, ...]:
    """Inspect every built-in integration without importing unavailable SDKs."""

    manager = InstrumentationManager()
    try:
        return tuple(_inspect_instrumentor(config, manager=manager)[1] for config in _CONFIGS)
    finally:
        manager.close()

resolve_instrumentor

resolve_instrumentor(
    config: BuiltinInstrumentationConfig,
) -> Instrumentor

Build one configured instrumentor, importing only its installed integration.

Source code in src/autobench/instrumentation/registry.py
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
def resolve_instrumentor(config: BuiltinInstrumentationConfig) -> Instrumentor:
    """Build one configured instrumentor, importing only its installed integration."""

    if find_spec(_module_name(config.kind)) is None:
        raise InstrumentationError(
            f"instrumentation '{config.kind}' is unavailable; "
            f"install autobench[{_EXTRAS[config.kind]}]"
        )
    try:
        if isinstance(config, PydanticAIInstrumentation):
            from autobench.instrumentation.pydantic_ai import PydanticAI

            return PydanticAI()
        if isinstance(config, OpenAIInstrumentation):
            from autobench.instrumentation.openai import OpenAIClient

            return OpenAIClient()
        if isinstance(config, OpenAIAgentsInstrumentation):
            from autobench.instrumentation.openai_agents import OpenAIAgents

            return OpenAIAgents()

        from autobench.instrumentation.httpx import HTTPX, HTTPXCapture

        return HTTPX(capture=HTTPXCapture.model_validate(config.capture.model_dump()))
    except ImportError as error:
        raise InstrumentationError(
            f"instrumentation '{config.kind}' could not be imported: {error}"
        ) from error

resolve_instrumentors

resolve_instrumentors(
    configs: Sequence[InstrumentationConfig],
    *,
    reserved_ids: Collection[str] = (),
) -> tuple[
    tuple[Instrumentor, ...], tuple[InstrumentorStatus, ...]
]

Resolve explicit and automatically discovered built-in instrumentors.

Source code in src/autobench/instrumentation/registry.py
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
def resolve_instrumentors(
    configs: Sequence[InstrumentationConfig],
    *,
    reserved_ids: Collection[str] = (),
) -> tuple[tuple[Instrumentor, ...], tuple[InstrumentorStatus, ...]]:
    """Resolve explicit and automatically discovered built-in instrumentors."""

    explicit_names = {
        config.kind for config in configs if not isinstance(config, AutoInstrumentation)
    }
    selected: list[Instrumentor] = []
    skipped: list[InstrumentorStatus] = []
    manager = InstrumentationManager()
    try:
        for auto in configs:
            if not isinstance(auto, AutoInstrumentation) or not auto.enabled:
                continue
            for config in _CONFIGS:
                if (
                    config.kind in auto.exclude
                    or config.kind in explicit_names
                    or _INFO[config.kind].id in reserved_ids
                ):
                    continue
                instrumentor, status = _inspect_instrumentor(config, manager=manager)
                if status.compatibility.installable and instrumentor is not None:
                    selected.append(instrumentor)
                    continue
                if auto.strict:
                    detail = (
                        "; ".join(status.compatibility.conflicts + status.compatibility.diagnostics)
                        or status.compatibility.status.value
                    )
                    raise InstrumentationError(
                        f"automatic instrumentation '{status.name}' is not installable: {detail}"
                    )
                skipped.append(status)
    finally:
        manager.close()

    selected.extend(
        resolve_instrumentor(config)
        for config in configs
        if not isinstance(config, AutoInstrumentation) and config.enabled
    )
    return tuple(selected), tuple(skipped)

canonicalize

canonicalize(
    data: SourceData,
    source_map: SourceMap,
    *,
    capture: CaptureSession | None = None,
    registry: SemanticRegistry | None = None,
) -> CanonicalizationResult
Source code in src/autobench/metrics/mappings.py
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
def canonicalize(
    data: SourceData,
    source_map: SourceMap,
    *,
    capture: CaptureSession | None = None,
    registry: SemanticRegistry | None = None,
) -> CanonicalizationResult:
    session = CaptureSession() if capture is None else capture
    active_registry = DEFAULT_SEMANTIC_REGISTRY if registry is None else registry
    diagnostics: list[Diagnostic] = []
    retained: dict[SourceSelector, RetainedSourceFact] = {}

    if data.system != source_map.source_system:
        diagnostics.append(
            Diagnostic(
                code="source_system_mismatch",
                message="source data system does not match the source map",
                severity=DiagnosticSeverity.ERROR,
                details={"actual": data.system, "expected": source_map.source_system},
            )
        )
    if data.convention_version != source_map.convention_version:
        diagnostics.append(
            Diagnostic(
                code="source_version_mismatch",
                message="source convention version does not match the source map",
                severity=DiagnosticSeverity.ERROR,
                details={
                    "actual": data.convention_version,
                    "expected": source_map.convention_version,
                },
            )
        )
    if diagnostics:
        snapshot = SourceSnapshot(
            system=data.system,
            convention_version=data.convention_version,
            source_map_id=source_map.id,
            source_map_version=source_map.version,
        )
        return CanonicalizationResult(
            source_map_id=source_map.id,
            source_map_version=source_map.version,
            diagnostics=tuple(diagnostics),
            source_snapshot=snapshot,
        )

    def lookup(selector: SourceSelector) -> tuple[MappingStatus, SerializedValue]:
        available, value = resolve_source_value(data.values, selector)
        if available:
            return MappingStatus.AVAILABLE, value
        return MappingStatus.UNAVAILABLE, None

    facts, classification = _apply_source_map(
        source_map,
        lookup,
        session,
        active_registry,
        diagnostics,
        retained,
    )
    snapshot = SourceSnapshot(
        system=data.system,
        convention_version=data.convention_version,
        source_map_id=source_map.id,
        source_map_version=source_map.version,
        facts=tuple(retained.values()),
    )
    return CanonicalizationResult(
        source_map_id=source_map.id,
        source_map_version=source_map.version,
        facts=tuple(facts),
        classification=classification,
        diagnostics=tuple(diagnostics),
        source_snapshot=snapshot,
    )

recanonicalize

recanonicalize(
    snapshot: SourceSnapshot,
    source_map: SourceMap,
    *,
    capture: CaptureSession | None = None,
    registry: SemanticRegistry | None = None,
) -> CanonicalizationResult
Source code in src/autobench/metrics/mappings.py
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
def recanonicalize(
    snapshot: SourceSnapshot,
    source_map: SourceMap,
    *,
    capture: CaptureSession | None = None,
    registry: SemanticRegistry | None = None,
) -> CanonicalizationResult:
    session = CaptureSession() if capture is None else capture
    active_registry = DEFAULT_SEMANTIC_REGISTRY if registry is None else registry
    diagnostics: list[Diagnostic] = []
    retained = {fact.selector: fact for fact in snapshot.facts}

    def lookup(selector: SourceSelector) -> tuple[MappingStatus, SerializedValue]:
        fact = retained.get(selector)
        if fact is not None:
            if fact.available:
                return MappingStatus.AVAILABLE, fact.value
            diagnostics.append(
                Diagnostic(
                    code="source_fact_unavailable",
                    message="source fact was not retained in replayable form",
                    path=source_selector_label(selector),
                    details={"reason": fact.reason or "unavailable"},
                )
            )
            return MappingStatus.UNAVAILABLE, None
        for candidate in snapshot.facts:
            if (
                candidate.available
                and candidate.selector.key == selector.key
                and selector.path[: len(candidate.selector.path)] == candidate.selector.path
            ):
                suffix = selector.path[len(candidate.selector.path) :]
                available, value = resolve_nested_value(candidate.value, suffix)
                if available:
                    return MappingStatus.AVAILABLE, value
        diagnostics.append(
            Diagnostic(
                code="source_fact_unavailable",
                message="source fact was not present in the retained snapshot",
                path=source_selector_label(selector),
                details={"reason": "not_retained"},
            )
        )
        return MappingStatus.UNAVAILABLE, None

    if snapshot.system != source_map.source_system:
        diagnostics.append(
            Diagnostic(
                code="source_system_mismatch",
                message="retained source system does not match the source map",
                severity=DiagnosticSeverity.ERROR,
                details={"actual": snapshot.system, "expected": source_map.source_system},
            )
        )
    if snapshot.convention_version != source_map.convention_version:
        diagnostics.append(
            Diagnostic(
                code="source_version_mismatch",
                message="retained convention version does not match the source map",
                severity=DiagnosticSeverity.ERROR,
                details={
                    "actual": snapshot.convention_version,
                    "expected": source_map.convention_version,
                },
            )
        )
    if any(diagnostic.severity is DiagnosticSeverity.ERROR for diagnostic in diagnostics):
        return CanonicalizationResult(
            source_map_id=source_map.id,
            source_map_version=source_map.version,
            diagnostics=tuple(diagnostics),
            source_snapshot=snapshot,
            replayed_from=f"{snapshot.source_map_id}@{snapshot.source_map_version}",
        )

    facts, classification = _apply_source_map(
        source_map,
        lookup,
        session,
        active_registry,
        diagnostics,
        {},
        retain=False,
    )
    return CanonicalizationResult(
        source_map_id=source_map.id,
        source_map_version=source_map.version,
        facts=tuple(facts),
        classification=classification,
        diagnostics=tuple(diagnostics),
        source_snapshot=snapshot,
        replayed_from=f"{snapshot.source_map_id}@{snapshot.source_map_version}",
    )

resolve_nested_value

resolve_nested_value(
    value: SerializedValue, path: tuple[PathSegment, ...]
) -> tuple[bool, SerializedValue]
Source code in src/autobench/metrics/mappings.py
368
369
370
371
372
373
374
375
376
377
378
379
380
381
def resolve_nested_value(
    value: SerializedValue,
    path: tuple[PathSegment, ...],
) -> tuple[bool, SerializedValue]:
    current = value
    for segment in path:
        if isinstance(segment, str) and isinstance(current, dict) and segment in current:
            current = current[segment]
            continue
        if isinstance(segment, int) and isinstance(current, list) and 0 <= segment < len(current):
            current = current[segment]
            continue
        return False, None
    return True, current

resolve_source_value

resolve_source_value(
    values: Mapping[str, SerializedValue],
    selector: SourceSelector,
) -> tuple[bool, SerializedValue]
Source code in src/autobench/metrics/mappings.py
359
360
361
362
363
364
365
def resolve_source_value(
    values: Mapping[str, SerializedValue],
    selector: SourceSelector,
) -> tuple[bool, SerializedValue]:
    if selector.key not in values:
        return False, None
    return resolve_nested_value(values[selector.key], selector.path)

source_map_payload_from_yaml_view

source_map_payload_from_yaml_view(
    raw: Any,
) -> dict[str, Any]
Source code in src/autobench/metrics/mappings.py
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
def source_map_payload_from_yaml_view(raw: Any) -> dict[str, Any]:
    payload = raw
    if isinstance(raw, dict):
        header = raw.get("record")
        if isinstance(header, dict) and header.get("type") == "source_map":
            payload = raw.get("source_map")
    if not isinstance(payload, dict):
        raise TypeError("source_map must be a mapping")
    normalized = dict(payload)
    source = normalized.pop("source", None)
    if source is None:
        return normalized
    if not isinstance(source, dict):
        raise TypeError("source_map.source must be a mapping")
    normalized["source_system"] = source.get("system")
    normalized["convention_version"] = source.get("convention")
    if "instrumentor" in source:
        normalized["instrumentor"] = source["instrumentor"]
    if "library_version" in source:
        normalized["instrumented_library_version"] = source["library_version"]
    return normalized

source_map_to_yaml_view

source_map_to_yaml_view(
    source_map: SourceMap,
) -> dict[str, Any]
Source code in src/autobench/metrics/mappings.py
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
def source_map_to_yaml_view(source_map: SourceMap) -> dict[str, Any]:
    source: dict[str, Any] = {
        "system": source_map.source_system,
        "convention": source_map.convention_version,
    }
    if source_map.instrumentor is not None:
        source["instrumentor"] = source_map.instrumentor
    if source_map.instrumented_library_version is not None:
        source["library_version"] = source_map.instrumented_library_version
    return {
        "record": {"type": "source_map", "version": 1},
        "source_map": {
            "id": source_map.id,
            "version": source_map.version,
            "source": source,
            "rules": source_map.model_dump(mode="json")["rules"],
        },
    }

source_selector_label

source_selector_label(selector: SourceSelector) -> str
Source code in src/autobench/metrics/mappings.py
384
385
386
387
388
def source_selector_label(selector: SourceSelector) -> str:
    label = selector.key
    for segment in selector.path:
        label += f"[{segment}]" if isinstance(segment, int) else f".{segment}"
    return label

filter_observations

filter_observations(
    observations: list[Observation],
    *,
    name: str | None = None,
    kind: ObservationKind | None = None,
    role: ObservationRole | None = None,
    source: ObservationSource | str | None = None,
    semantic_type: str | None = None,
    parent_semantic_type: str | None = None,
    span_id: str | None = None,
    registry: SemanticRegistry | None = None,
) -> list[Observation]
Source code in src/autobench/metrics/observations.py
 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
def filter_observations(
    observations: list[Observation],
    *,
    name: str | None = None,
    kind: ObservationKind | None = None,
    role: ObservationRole | None = None,
    source: ObservationSource | str | None = None,
    semantic_type: str | None = None,
    parent_semantic_type: str | None = None,
    span_id: str | None = None,
    registry: SemanticRegistry | None = None,
) -> list[Observation]:
    active_registry = registry or DEFAULT_SEMANTIC_REGISTRY
    filtered: list[Observation] = []

    for observation in observations:
        if name is not None and observation.name != name:
            continue
        if kind is not None and observation.kind is not kind:
            continue
        if role is not None and observation.role is not role:
            continue
        if source is not None and observation.source != source:
            continue
        if span_id is not None and observation.span_id != span_id:
            continue
        if semantic_type is not None and observation.normalized_semantic_type(
            active_registry
        ) != active_registry.normalize(semantic_type):
            continue
        if parent_semantic_type is not None and not active_registry.is_a(
            observation.semantic_type,
            parent_semantic_type,
        ):
            continue
        filtered.append(observation)

    return filtered

builtin_metric_pack_registry

builtin_metric_pack_registry() -> MetricPackRegistry
Source code in src/autobench/metrics/packs.py
44
45
46
47
48
49
50
51
52
53
def builtin_metric_pack_registry() -> MetricPackRegistry:
    registry = MetricPackRegistry()
    for pack in (
        _agentic_pack(),
        _structured_output_pack(),
        _llm_usage_pack(),
        _performance_pack(),
    ):
        registry.register(pack)
    return registry

observation_priority

observation_priority(
    observation: Observation,
) -> tuple[int, int]
Source code in src/autobench/metrics/projection.py
44
45
46
47
def observation_priority(observation: Observation) -> tuple[int, int]:
    scope = observation.tags.get("abp.measurement_scope")
    scope_priority = 0 if scope == "aggregate" else 2 if scope == "direct" else 1
    return source_priority(observation.source), scope_priority

observation_projection_key

observation_projection_key(
    observation: Observation,
    *,
    registry: SemanticRegistry | None = None,
) -> ProjectionKey
Source code in src/autobench/metrics/projection.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
def observation_projection_key(
    observation: Observation,
    *,
    registry: SemanticRegistry | None = None,
) -> ProjectionKey:
    active_registry = registry or DEFAULT_SEMANTIC_REGISTRY
    role = observation.role.value if observation.role is not None else None
    logical_operation_id = observation.tags.get("abp.logical_operation_id")
    normalized_operation_id = (
        logical_operation_id if isinstance(logical_operation_id, str) else None
    )
    measurement_scope = observation.tags.get("abp.measurement_scope")
    normalized_scope = measurement_scope if isinstance(measurement_scope, str) else None
    return ProjectionKey(
        semantic_type=observation.normalized_semantic_type(active_registry),
        name=observation.name,
        role=role,
        case_id=observation.case_id,
        variant_id=observation.variant_id,
        span_id=None if normalized_operation_id is not None else observation.span_id,
        measurement_scope=normalized_scope,
        logical_operation_id=normalized_operation_id,
    )

project_observations

project_observations(
    observations: list[Observation],
    *,
    registry: SemanticRegistry | None = None,
) -> list[ProjectedObservation]
Source code in src/autobench/metrics/projection.py
 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
def project_observations(
    observations: list[Observation],
    *,
    registry: SemanticRegistry | None = None,
) -> list[ProjectedObservation]:
    active_registry = registry or DEFAULT_SEMANTIC_REGISTRY
    grouped: dict[
        tuple[
            str | None,
            str,
            str | None,
            str | None,
            str | None,
            str | None,
            str | None,
            str | None,
        ],
        list[Observation],
    ] = {}
    order: list[
        tuple[
            str | None,
            str,
            str | None,
            str | None,
            str | None,
            str | None,
            str | None,
            str | None,
        ]
    ] = []

    for observation in observations:
        key = observation_projection_key(observation, registry=active_registry)
        key_tuple = (
            key.semantic_type,
            key.name,
            key.role,
            key.case_id,
            key.variant_id,
            key.span_id,
            key.measurement_scope,
            key.logical_operation_id,
        )
        if key_tuple not in grouped:
            grouped[key_tuple] = []
            order.append(key_tuple)
        grouped[key_tuple].append(observation)

    projected: list[ProjectedObservation] = []
    for key_tuple in order:
        candidates = grouped[key_tuple]
        ordered_candidates = sorted(
            enumerate(candidates),
            key=lambda item: (*observation_priority(item[1]), item[0]),
        )
        best_priority = observation_priority(ordered_candidates[0][1])
        best_candidates = [
            observation
            for _, observation in ordered_candidates
            if observation_priority(observation) == best_priority
        ]
        projected.append(
            ProjectedObservation(
                key=ProjectionKey(
                    semantic_type=key_tuple[0],
                    name=key_tuple[1],
                    role=key_tuple[2],
                    case_id=key_tuple[3],
                    variant_id=key_tuple[4],
                    span_id=key_tuple[5],
                    measurement_scope=key_tuple[6],
                    logical_operation_id=key_tuple[7],
                ),
                observation=ordered_candidates[0][1],
                candidates=candidates,
                ambiguous=len(best_candidates) > 1,
            )
        )

    return projected

source_priority

source_priority(
    source: ObservationSource | str | None,
) -> int
Source code in src/autobench/metrics/projection.py
39
40
41
def source_priority(source: ObservationSource | str | None) -> int:
    normalized = source.value if isinstance(source, ObservationSource) else source
    return SOURCE_PRIORITY.get(normalized, SOURCE_PRIORITY[None])

semantic_registry_payload_from_yaml_view

semantic_registry_payload_from_yaml_view(
    raw: Any,
) -> dict[str, Any]
Source code in src/autobench/metrics/semantics.py
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
def semantic_registry_payload_from_yaml_view(raw: Any) -> dict[str, Any]:
    registry = raw
    if isinstance(raw, dict):
        record_header = raw.get("record")
        if isinstance(record_header, dict) and record_header.get("type") == "semantic_registry":
            registry = raw.get("semantic_registry")
    if not isinstance(registry, dict):
        raise TypeError("semantic_registry must be a mapping")

    raw_types = registry.get("types", {})
    raw_aliases = registry.get("aliases", {})
    if not isinstance(raw_types, dict):
        raise TypeError("semantic_registry.types must be a mapping")
    if not isinstance(raw_aliases, dict):
        raise TypeError("semantic_registry.aliases must be a mapping")

    resolved_types: dict[str, dict[str, Any]] = {}
    for semantic_id, raw_type in raw_types.items():
        if not isinstance(raw_type, dict):
            raise TypeError(f"semantic_registry.types.{semantic_id} must be a mapping")
        payload = dict(raw_type)
        payload["id"] = str(payload.get("id", semantic_id))
        if "shape" in payload and "value_shape" not in payload:
            payload["value_shape"] = payload.pop("shape")
        resolved_types[str(semantic_id)] = payload

    return {
        "version": registry.get("version", 1),
        "types": resolved_types,
        "aliases": dict(raw_aliases),
    }

semantic_registry_to_yaml_view

semantic_registry_to_yaml_view(
    registry: SemanticRegistry,
) -> dict[str, Any]
Source code in src/autobench/metrics/semantics.py
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
def semantic_registry_to_yaml_view(registry: SemanticRegistry) -> dict[str, Any]:
    types_view = {
        semantic_id: _semantic_type_yaml_view(info) for semantic_id, info in registry.types.items()
    }
    return {
        "record": {
            "type": "semantic_registry",
            "version": registry.version,
        },
        "semantic_registry": {
            "version": registry.version,
            "types": types_view,
            "aliases": dict(registry.aliases),
        },
    }

suppress_instrumentation

suppress_instrumentation(*keys: str) -> Iterator[None]
Source code in src/autobench/protocol/context.py
76
77
78
79
80
81
82
83
@contextmanager
def suppress_instrumentation(*keys: str) -> Iterator[None]:
    active = get_context()
    if active is None:
        yield
        return
    with use_context(active.suppress(*keys)):
        yield

experiment_record_payload_from_yaml_view

experiment_record_payload_from_yaml_view(
    raw: dict[str, Any],
) -> dict[str, Any]
Source code in src/autobench/records/recording.py
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
def experiment_record_payload_from_yaml_view(raw: dict[str, Any]) -> dict[str, Any]:
    record_header = raw.get("record")
    if not isinstance(record_header, dict) or record_header.get("type") != "experiment":
        return raw

    experiment = _require_mapping(raw.get("experiment"), "experiment")
    benchmark = _require_mapping(raw.get("benchmark"), "benchmark")
    runs = _require_mapping(raw.get("runs"), "runs")
    spec = benchmark.get("spec", {})
    if spec is None:
        spec = {}
    if not isinstance(spec, dict):
        raise RecordingError("benchmark.spec must be a mapping")
    raw_environment = raw.get("environment")
    raw_semantic_registry = raw.get("semantic_registry")
    plan = benchmark.get("plan")
    if plan is None:
        plan = _benchmark_plan_payload(benchmark, runs)
    spec_snapshot = _benchmark_spec_snapshot_payload(spec.get("snapshot"))

    payload = _compact(
        {
            "record_version": record_header.get("version", RECORD_VERSION),
            "experiment_id": experiment.get("id"),
            "benchmark_id": benchmark.get("id", experiment.get("benchmark")),
            "plan": plan,
            "environment": _environment_payload(raw_environment),
            "semantic_registry": (
                semantic_registry_payload_from_yaml_view(raw_semantic_registry)
                if raw_semantic_registry is not None
                else None
            ),
            "spec_snapshot": spec_snapshot,
            "spec_hash": spec.get("hash"),
            "file_hashes": _file_hashes_payload(raw.get("files")),
            "run_paths": runs.get("paths", []),
            "run_count": runs.get("count"),
            "passed_count": runs.get("passed", 0),
            "failed_count": runs.get("failed", 0),
            "errored_count": runs.get("errored", 0),
            "skipped_count": runs.get("skipped", 0),
        }
    )
    if spec_snapshot is not None:
        payload["spec_snapshot"] = spec_snapshot
    if "reports" in raw:
        payload["report_spec_data"] = raw["reports"]
    return payload

experiment_record_to_yaml_view

experiment_record_to_yaml_view(
    record: ExperimentRecord,
) -> dict[str, Any]
Source code in src/autobench/records/recording.py
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
def experiment_record_to_yaml_view(record: ExperimentRecord) -> dict[str, Any]:
    payload = _compact(
        {
            "record": {
                "type": "experiment",
                "version": record.record_version,
            },
            "experiment": {
                "id": record.experiment_id,
                "benchmark": record.benchmark_id,
            },
            "benchmark": {
                "id": record.benchmark_id,
                "dataset": _benchmark_dataset_view(record.plan),
                "cases": list(record.plan.case_ids),
                "counts": {
                    "cases": record.plan.case_count,
                    "variants": record.plan.variant_count,
                    "runs": record.plan.planned_run_count,
                },
                "warnings": list(record.plan.warnings),
                "spec": {
                    "hash": record.spec_hash,
                    "snapshot": _benchmark_spec_snapshot_view(record.spec_snapshot),
                },
            },
            "runs": {
                "count": record.run_count,
                "passed": record.passed_count,
                "failed": record.failed_count,
                "errored": record.errored_count,
                "skipped": record.skipped_count,
                "paths": list(record.run_paths),
            },
            "files": _file_hashes_view(record.file_hashes),
            "environment": _environment_yaml_view(record.environment),
            "semantic_registry": semantic_registry_to_yaml_view(record.semantic_registry)[
                "semantic_registry"
            ],
        }
    )
    if record.report_spec_data is not None:
        payload["reports"] = _to_serializable(record.report_spec_data)
    return payload

experiment_summary

experiment_summary(
    record: ExperimentRecord,
) -> dict[str, Any]
Source code in src/autobench/records/recording.py
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
def experiment_summary(record: ExperimentRecord) -> dict[str, Any]:
    return {
        "record": {
            "type": "summary",
            "version": record.record_version,
        },
        "summary": {
            "experiment": record.experiment_id,
            "benchmark": record.benchmark_id,
        },
        "runs": {
            "count": record.run_count,
            "passed": record.passed_count,
            "failed": record.failed_count,
            "errored": record.errored_count,
            "skipped": record.skipped_count,
        },
    }

record_experiment

record_experiment(
    result: ExperimentResult,
    output_dir: Path,
    *,
    source_files: list[Path] | None = None,
    path_root: Path | None = None,
    trace_inline_limit_bytes: int = TRACE_INLINE_LIMIT_BYTES,
) -> ExperimentRecord
Source code in src/autobench/records/recording.py
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
def record_experiment(
    result: ExperimentResult,
    output_dir: Path,
    *,
    source_files: list[Path] | None = None,
    path_root: Path | None = None,
    trace_inline_limit_bytes: int = TRACE_INLINE_LIMIT_BYTES,
) -> ExperimentRecord:
    if trace_inline_limit_bytes < 1:
        raise ValueError("trace_inline_limit_bytes must be at least 1")
    if (output_dir / "experiment.yaml").exists():
        raise RecordingError(f"Experiment record already exists: {output_dir}")

    output_dir.mkdir(parents=True, exist_ok=True)
    artifacts_dir = output_dir / "artifacts"
    cases_dir = output_dir / "cases"
    _ensure_record_targets_available(
        result,
        output_dir=output_dir,
        artifacts_dir=artifacts_dir,
        trace_inline_limit_bytes=trace_inline_limit_bytes,
    )
    artifacts_dir.mkdir(exist_ok=True)
    cases_dir.mkdir(exist_ok=True)

    run_paths: list[str] = []
    for run in result.runs:
        run_record = run_record_from_result(
            run,
            artifacts_dir=artifacts_dir,
            root_dir=output_dir,
            semantic_registry_version=result.semantic_registry.version,
            trace_inline_limit_bytes=trace_inline_limit_bytes,
        )
        run_path = _run_record_path(output_dir, run)
        run_path.parent.mkdir(parents=True, exist_ok=True)
        dump_yaml(run_record_to_yaml_view(run_record), run_path, schema_name="run_record")
        run_paths.append(run_path.relative_to(output_dir).as_posix())

    record = ExperimentRecord(
        experiment_id=result.experiment_id,
        benchmark_id=result.benchmark_id,
        plan=result.plan,
        environment=_recorded_environment(result.environment, path_root=path_root),
        semantic_registry=result.semantic_registry,
        report_spec_data=result.report_spec_data,
        spec_snapshot=result.spec_snapshot,
        spec_hash=result.spec_hash,
        file_hashes=tuple(
            hash_file(path, relative_to=path_root)
            for path in (source_files or [])
            if path.exists() and path.is_file()
        ),
        run_paths=tuple(run_paths),
        run_count=result.total_count,
        passed_count=result.passed_count,
        failed_count=result.failed_count,
        errored_count=result.errored_count,
        skipped_count=result.skipped_count,
    )
    dump_yaml(
        experiment_record_to_yaml_view(record),
        output_dir / "experiment.yaml",
        schema_name="experiment",
    )
    dump_yaml(experiment_summary(record), output_dir / "summary.yaml", schema_name="summary")
    return record

run_record_from_result

run_record_from_result(
    run: RunResult,
    *,
    artifacts_dir: Path,
    root_dir: Path,
    semantic_registry_version: int = DEFAULT_SEMANTIC_REGISTRY.version,
    trace_inline_limit_bytes: int = TRACE_INLINE_LIMIT_BYTES,
) -> RunRecord
Source code in src/autobench/records/recording.py
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
def run_record_from_result(
    run: RunResult,
    *,
    artifacts_dir: Path,
    root_dir: Path,
    semantic_registry_version: int = DEFAULT_SEMANTIC_REGISTRY.version,
    trace_inline_limit_bytes: int = TRACE_INLINE_LIMIT_BYTES,
) -> RunRecord:
    if trace_inline_limit_bytes < 1:
        raise ValueError("trace_inline_limit_bytes must be at least 1")
    recorded_artifacts = [
        _record_artifact(
            artifact, artifacts_dir=artifacts_dir, root_dir=root_dir, run_id=run.run_id
        )
        for artifact in run.task_result.artifacts
    ]
    errors: list[ErrorRecord] = []
    for error in [run.error, run.task_result.error, *run.task_result.errors]:
        if error is not None and error not in errors:
            errors.append(error)
    trace, trace_artifact = _record_trace(
        run.trace,
        artifacts_dir=artifacts_dir,
        root_dir=root_dir,
        run_id=run.run_id,
        inline_limit_bytes=trace_inline_limit_bytes,
    )
    return RunRecord(
        protocol_version=None if run.trace is None else run.trace.protocol_version,
        semantic_registry_version=None if run.trace is None else semantic_registry_version,
        run_id=run.run_id,
        experiment_id=run.experiment_id,
        benchmark_id=run.benchmark_id,
        case_id=run.case_id,
        variant_id=run.variant_id,
        status=run.status,
        evaluation_status=run.evaluation_status,
        task_status=run.task_result.status,
        case=run.case,
        task_output=_to_serializable(run.task_result.output),
        observations=tuple(run.task_result.observations),
        scores=tuple(run.scores),
        spans=tuple(run.task_result.spans),
        trace=trace,
        trace_artifact=trace_artifact,
        artifacts=tuple(recorded_artifacts),
        factors=tuple(run.factors),
        asset_versions=tuple(run.asset_versions),
        parent_run_id=run.parent_run_id,
        source_snapshots=run.source_snapshots,
        errors=tuple(errors),
        error=run.error,
    )

load_experiment_record

load_experiment_record(run_dir: Path) -> ExperimentRecord
Source code in src/autobench/records/replay.py
36
37
38
39
40
def load_experiment_record(run_dir: Path) -> ExperimentRecord:
    raw = load_yaml(run_dir / "experiment.yaml")
    if isinstance(raw, dict):
        raw = experiment_record_payload_from_yaml_view(raw)
    return ExperimentRecord.model_validate(raw)

load_run_record

load_run_record(
    path: Path, *, root_dir: Path | None = None
) -> RunRecord
Source code in src/autobench/records/replay.py
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
def load_run_record(path: Path, *, root_dir: Path | None = None) -> RunRecord:
    raw = load_yaml(path)
    if isinstance(raw, dict):
        raw = run_record_payload_from_yaml_view(raw)
    record = RunRecord.model_validate(raw)
    if record.trace is not None or record.trace_artifact is None:
        return record
    if not isinstance(record.trace_artifact.value, str):
        raise ReplayError("Trace artifact path must be a string.")
    active_root = _record_root(path) if root_dir is None else root_dir
    resolved_root = active_root.resolve()
    artifact_path = (resolved_root / record.trace_artifact.value).resolve()
    if not artifact_path.is_relative_to(resolved_root):
        raise ReplayError("Trace artifact path must stay inside the experiment directory.")
    if not artifact_path.is_file():
        raise ReplayError(f"Trace artifact does not exist: {artifact_path}")
    trace_raw = load_yaml(artifact_path)
    if not isinstance(trace_raw, dict):
        raise ReplayError(f"Trace artifact must contain a mapping: {artifact_path}")
    try:
        trace_payload, extensions = trace_payload_from_yaml_view(trace_raw)
        trace = Trace.model_validate(trace_payload)
    except (TypeError, ValueError) as exc:
        raise ReplayError(f"Invalid trace artifact: {artifact_path}") from exc
    return record.model_copy(
        update={
            "trace": trace,
            "trace_extensions": {**record.trace_extensions, **extensions},
        }
    )

replay_canonicalization

replay_canonicalization(
    record: RunRecord,
    source_maps: Iterable[SourceMap],
    *,
    registry: SemanticRegistry | None = None,
    run_id: str | None = None,
) -> RunRecord
Source code in src/autobench/records/replay.py
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
def replay_canonicalization(
    record: RunRecord,
    source_maps: Iterable[SourceMap],
    *,
    registry: SemanticRegistry | None = None,
    run_id: str | None = None,
) -> RunRecord:
    if not record.source_snapshots:
        raise ReplayError("Canonicalization replay requires retained source snapshots.")
    maps: dict[str, SourceMap] = {}
    for source_map in sorted(source_maps, key=lambda item: (item.id, item.version)):
        maps[source_map.id] = source_map
    missing = tuple(
        snapshot.source_map_id
        for snapshot in record.source_snapshots
        if snapshot.source_map_id not in maps
    )
    if missing:
        raise ReplayError(f"Missing source maps: {', '.join(sorted(set(missing)))}")

    active_registry = DEFAULT_SEMANTIC_REGISTRY if registry is None else registry
    results = tuple(
        recanonicalize(
            snapshot,
            maps[snapshot.source_map_id],
            registry=active_registry,
        )
        for snapshot in record.source_snapshots
    )
    observations = tuple(
        observation
        for observation in record.observations
        if observation.tags.get("replay") != ReplayKind.CANONICALIZATION
    )
    derived: list[Observation] = []
    for result_index, result in enumerate(results, start=1):
        for fact_index, fact in enumerate(result.facts, start=1):
            semantic_type = active_registry.normalize(fact.semantic_type) or fact.semantic_type
            type_info = active_registry.types.get(semantic_type)
            kind = (
                ObservationKind.METRIC
                if type_info is not None
                and type_info.value_shape in {"boolean", "integer", "number"}
                else ObservationKind.FACTOR
            )
            value = fact.value if fact.reference is None else fact.reference.model_dump(mode="json")
            derived.append(
                Observation(
                    id=f"canonical_{result_index}_{fact_index}",
                    name=fact.semantic_type,
                    kind=kind,
                    semantic_type=semantic_type,
                    value=value,
                    unit=fact.unit,
                    source=ObservationSource.IMPORTED,
                    tags={
                        "replay": ReplayKind.CANONICALIZATION,
                        "source_map_id": result.source_map_id,
                        "source_map_version": result.source_map_version,
                        "authority": fact.authority,
                    },
                    case_id=record.case_id,
                    variant_id=record.variant_id,
                )
            )

    map_versions = tuple(
        f"{source_map.id}@{source_map.version}"
        for source_map in sorted(maps.values(), key=lambda item: item.id)
    )
    return record.model_copy(
        update={
            "record_version": RECORD_VERSION,
            "run_id": run_id
            or _derived_run_id(
                record.run_id,
                ReplayKind.CANONICALIZATION,
                "source-map",
                ",".join(map_versions),
            ),
            "parent_run_id": record.run_id,
            "observations": (*observations, *derived),
            "canonicalizations": results,
            "semantic_registry_version": active_registry.version,
            "lineage": RecordLineage(
                kind=ReplayKind.CANONICALIZATION,
                parent_run_id=record.run_id,
                processor="autobench.source-map",
                processor_version="1",
                source_record_version=record.record_version,
                source_protocol_version=record.protocol_version,
                source_semantic_registry_version=record.semantic_registry_version,
                source_maps=map_versions,
            ),
        }
    )

replay_experiment

replay_experiment(run_dir: Path) -> ExperimentResult
Source code in src/autobench/records/replay.py
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
def replay_experiment(run_dir: Path) -> ExperimentResult:
    record = load_experiment_record(run_dir)
    runs = [
        _run_result_from_record(load_run_record(run_dir / run_path, root_dir=run_dir))
        for run_path in record.run_paths
    ]
    return ExperimentResult(
        experiment_id=record.experiment_id,
        benchmark_id=record.benchmark_id,
        plan=record.plan,
        runs=runs,
        environment=record.environment,
        report_spec_data=record.report_spec_data,
        semantic_registry=record.semantic_registry,
        spec_snapshot=record.spec_snapshot,
        spec_hash=record.spec_hash,
    )

replay_extraction

replay_extraction(
    record: RunRecord,
    extractor: TraceExtractor,
    *,
    registry: SemanticRegistry | None = None,
    run_id: str | None = None,
) -> RunRecord
Source code in src/autobench/records/replay.py
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
def replay_extraction(
    record: RunRecord,
    extractor: TraceExtractor,
    *,
    registry: SemanticRegistry | None = None,
    run_id: str | None = None,
) -> RunRecord:
    if record.trace is None:
        raise ReplayError("Extraction replay requires a recorded ABP trace.")
    active_registry = DEFAULT_SEMANTIC_REGISTRY if registry is None else registry
    result = extractor.extract(
        record.trace,
        registry=active_registry,
        context=ExtractionContext(
            run_id=record.run_id,
            benchmark_id=record.benchmark_id,
            experiment_id=record.experiment_id,
            case_id=record.case_id,
            variant_id=record.variant_id,
        ),
    )
    extracted_ids = {observation.id for observation in result.observations}
    extracted_ids.update(
        observation_id
        for evidence in record.extractions
        if evidence.extractor == extractor.name
        for observation_id in evidence.observation_ids
    )
    observations = (
        tuple(
            observation
            for observation in record.observations
            if observation.id not in extracted_ids
        )
        + result.observations
    )
    evidence = ExtractionEvidence(
        extractor=extractor.name,
        version=extractor.version,
        observation_ids=tuple(observation.id for observation in result.observations),
        diagnostics=result.diagnostics,
        references=result.references,
    )
    previous = tuple(item for item in record.extractions if item.extractor != extractor.name)
    return record.model_copy(
        update={
            "record_version": RECORD_VERSION,
            "run_id": run_id
            or _derived_run_id(
                record.run_id, ReplayKind.EXTRACTION, extractor.name, extractor.version
            ),
            "parent_run_id": record.run_id,
            "observations": observations,
            "extractions": (*previous, evidence),
            "semantic_registry_version": active_registry.version,
            "lineage": RecordLineage(
                kind=ReplayKind.EXTRACTION,
                parent_run_id=record.run_id,
                processor=extractor.name,
                processor_version=extractor.version,
                source_record_version=record.record_version,
                source_protocol_version=record.protocol_version,
                source_semantic_registry_version=record.semantic_registry_version,
            ),
        }
    )

capture_environment

capture_environment(
    *, cwd: Path | None = None
) -> EnvironmentMetadata
Source code in src/autobench/records/storage.py
23
24
25
26
27
28
def capture_environment(*, cwd: Path | None = None) -> EnvironmentMetadata:
    return EnvironmentMetadata(
        python_version=sys.version.split()[0],
        platform=platform.platform(),
        cwd=str(cwd or Path.cwd()),
    )

export_markdown_report

export_markdown_report(
    result: ExperimentResult,
    path: Path | None = None,
    *,
    report_spec: ReportSpec | None = None,
) -> str
Source code in src/autobench/reports/exporting.py
127
128
129
130
131
132
133
134
135
136
def export_markdown_report(
    result: ExperimentResult,
    path: Path | None = None,
    *,
    report_spec: ReportSpec | None = None,
) -> str:
    rendered = render_markdown_report(build_report(result, report_spec=report_spec))
    if path is not None:
        path.write_text(rendered, encoding="utf-8")
    return rendered

export_runs_csv

export_runs_csv(
    result: ExperimentResult, path: Path | None = None
) -> str
Source code in src/autobench/reports/exporting.py
 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
def export_runs_csv(result: ExperimentResult, path: Path | None = None) -> str:
    output = StringIO()
    fieldnames = [
        "run_id",
        "case_id",
        "variant_id",
        "status",
        *[name for name, _ in CSV_METRICS],
    ]
    writer = csv.DictWriter(output, fieldnames=fieldnames)
    writer.writeheader()
    for run in result.runs:
        row: dict[str, Any] = {
            "run_id": run.run_id,
            "case_id": run.case_id,
            "variant_id": run.variant_id,
            "status": run.status.value,
        }
        for name, semantic_type in CSV_METRICS:
            row[name] = metric_value(run, semantic_type)
        writer.writerow(row)

    rendered = output.getvalue()
    if path is not None:
        path.write_text(rendered, encoding="utf-8")
    return rendered

export_summary_yaml

export_summary_yaml(
    result: ExperimentResult,
    path: Path | None = None,
    *,
    report_spec: ReportSpec | None = None,
) -> str
Source code in src/autobench/reports/exporting.py
27
28
29
30
31
32
33
34
def export_summary_yaml(
    result: ExperimentResult,
    path: Path | None = None,
    *,
    report_spec: ReportSpec | None = None,
) -> str:
    report = build_report(result, report_spec=report_spec)
    return dump_yaml(report_to_yaml_view(report), path, schema_name="report")

report_to_yaml_view

report_to_yaml_view(
    report: BenchmarkReport,
) -> dict[str, Any]
Source code in src/autobench/reports/exporting.py
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
def report_to_yaml_view(report: BenchmarkReport) -> dict[str, Any]:
    variants = {
        row.variant_id: {
            **({"label": row.label} if row.label is not None else {}),
            **({"factors": row.factors} if row.factors else {}),
        }
        for row in report.variant_configs
    }
    leaderboard = {
        row.variant_id: {
            "runs": row.run_count,
            "metrics": row.metrics,
        }
        for row in report.leaderboard
    }
    cases: dict[str, dict[str, Any]] = {}
    for row in report.run_metrics:
        case_rows = cases.setdefault(row.case_id, {})
        case_rows[row.variant_id] = {
            "status": row.status,
            "metrics": row.metrics,
        }
    comparisons = {
        f"{comparison.baseline} -> {comparison.candidate}": {
            "runs": comparison.run_count,
            **({"confounded": True} if comparison.confounded else {}),
            **({"factors": comparison.factor_deltas} if comparison.factor_deltas else {}),
            **({"metrics": comparison.metric_deltas} if comparison.metric_deltas else {}),
        }
        for comparison in report.comparisons
    }
    distributions = {
        distribution.name: {
            "semantic": distribution.semantic_type,
            "variants": distribution.by_variant,
            "summaries": distribution.summaries,
        }
        for distribution in report.distributions
    }
    return {
        "record": {
            "type": "report",
            "version": 1,
        },
        "report": {
            "benchmark": report.benchmark_id,
            "experiment": report.experiment_id,
            "runs": report.run_count,
            "status": report.status_counts,
            "variants": variants,
            "leaderboard": leaderboard,
            "cases": cases,
            "matrix": {
                "metric": report.case_matrix.metric,
                "cases": report.case_matrix.rows,
            },
            "compare": comparisons,
            "distributions": distributions,
        },
    }

aggregate_values

aggregate_values(
    values: list[Any], fn: AggregationFn
) -> Any | None
Source code in src/autobench/reports/reporting.py
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
def aggregate_values(values: list[Any], fn: AggregationFn) -> Any | None:
    if not values:
        return None
    if fn == "count":
        return len(values)
    if fn == "ratio_true":
        return sum(1 for value in values if bool(value)) / len(values)

    numeric_values = [
        float(value)
        for value in values
        if isinstance(value, int | float) and not isinstance(value, bool)
    ]
    if not numeric_values:
        return None
    if fn == "mean":
        return sum(numeric_values) / len(numeric_values)
    if fn == "sum":
        return sum(numeric_values)
    if fn == "min":
        return min(numeric_values)
    if fn == "max":
        return max(numeric_values)
    if fn == "median":
        return median(numeric_values)
    if fn == "p95":
        return _percentile(numeric_values, 95.0)
    if fn == "stddev":
        return pstdev(numeric_values)
    if fn == "geomean":
        if any(value <= 0.0 for value in numeric_values):
            return None
        return prod(numeric_values) ** (1.0 / len(numeric_values))
    raise ValueError(f"Unsupported aggregation: {fn}")

build_case_matrix

build_case_matrix(
    result: ExperimentResult,
    *,
    semantic_type: str,
    registry: SemanticRegistry | None = None,
) -> CaseMatrix
Source code in src/autobench/reports/reporting.py
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
def build_case_matrix(
    result: ExperimentResult,
    *,
    semantic_type: str,
    registry: SemanticRegistry | None = None,
) -> CaseMatrix:
    active_registry = registry or result.semantic_registry
    rows: dict[str, dict[str, Any]] = defaultdict(dict)
    for run in result.runs:
        rows[run.case_id][run.variant_id] = metric_value(
            run,
            semantic_type,
            registry=active_registry,
        )
    return CaseMatrix(
        metric=semantic_type, rows={case_id: dict(values) for case_id, values in rows.items()}
    )

build_leaderboard

build_leaderboard(
    result: ExperimentResult,
    *,
    metrics: tuple[
        MetricAggregation, ...
    ] = DEFAULT_LEADERBOARD_METRICS,
    registry: SemanticRegistry | None = None,
) -> list[LeaderboardRow]
Source code in src/autobench/reports/reporting.py
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
def build_leaderboard(
    result: ExperimentResult,
    *,
    metrics: tuple[MetricAggregation, ...] = DEFAULT_LEADERBOARD_METRICS,
    registry: SemanticRegistry | None = None,
) -> list[LeaderboardRow]:
    active_registry = registry or result.semantic_registry
    grouped: dict[str, list[RunResult]] = defaultdict(list)
    for run in result.runs:
        grouped[run.variant_id].append(run)

    rows: list[LeaderboardRow] = []
    for variant_id in sorted(grouped):
        runs = grouped[variant_id]
        values = {
            metric.name: aggregate_values(
                [
                    value
                    for run in runs
                    if (value := metric_value(run, metric.semantic_type, registry=active_registry))
                    is not None
                ],
                metric.fn,
            )
            for metric in metrics
        }
        rows.append(
            LeaderboardRow(
                variant_id=variant_id,
                run_count=len(runs),
                metrics=values,
            )
        )
    return rows

build_metric_distribution

build_metric_distribution(
    result: ExperimentResult,
    *,
    name: str,
    semantic_type: str,
    summaries: tuple[AggregationFn, ...] = (
        "min",
        "median",
        "p95",
        "max",
    ),
    registry: SemanticRegistry | None = None,
) -> MetricDistribution
Source code in src/autobench/reports/reporting.py
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
def build_metric_distribution(
    result: ExperimentResult,
    *,
    name: str,
    semantic_type: str,
    summaries: tuple[AggregationFn, ...] = ("min", "median", "p95", "max"),
    registry: SemanticRegistry | None = None,
) -> MetricDistribution:
    active_registry = registry or result.semantic_registry
    by_variant: dict[str, list[Any]] = defaultdict(list)
    for run in result.runs:
        value = metric_value(run, semantic_type, registry=active_registry)
        if value is None:
            continue
        by_variant[run.variant_id].append(value)
    summary_by_variant: dict[str, dict[str, Any]] = {
        variant_id: {
            str(summary_name): aggregate_values(values, summary_name) for summary_name in summaries
        }
        for variant_id, values in sorted(by_variant.items())
    }
    return MetricDistribution(
        name=name,
        semantic_type=semantic_type,
        by_variant=dict(sorted(by_variant.items())),
        summaries=summary_by_variant,
    )

build_report

build_report(
    result: ExperimentResult,
    *,
    registry: SemanticRegistry | None = None,
    report_spec: ReportSpec | None = None,
) -> BenchmarkReport
Source code in src/autobench/reports/reporting.py
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
def build_report(
    result: ExperimentResult,
    *,
    registry: SemanticRegistry | None = None,
    report_spec: ReportSpec | None = None,
) -> BenchmarkReport:
    active_registry = registry or result.semantic_registry
    active_report_spec = report_spec
    if active_report_spec is None and result.report_spec_data is not None:
        active_report_spec = ReportSpec.model_validate(result.report_spec_data)
    if active_report_spec is None:
        active_report_spec = ReportSpec()
    return BenchmarkReport(
        benchmark_id=result.benchmark_id,
        experiment_id=result.experiment_id,
        run_count=result.total_count,
        status_counts=build_status_counts(result),
        variant_configs=build_variant_configs(result),
        leaderboard=build_leaderboard(
            result,
            metrics=active_report_spec.leaderboard_metrics(),
            registry=active_registry,
        ),
        run_metrics=build_run_metric_rows(result, registry=active_registry),
        case_matrix=build_case_matrix(
            result,
            semantic_type=active_report_spec.case_matrix.semantic_type,
            registry=active_registry,
        ),
        comparisons=[
            compare_variants(
                result,
                baseline=comparison.baseline,
                candidate=comparison.candidate,
                metrics=comparison.resolved_metrics(),
                registry=active_registry,
            )
            for comparison in active_report_spec.comparisons
        ],
        distributions=[
            build_metric_distribution(
                result,
                name=distribution.name,
                semantic_type=distribution.semantic_type,
                summaries=distribution.summaries,
                registry=active_registry,
            )
            for distribution in active_report_spec.distributions
        ],
    )

build_run_metric_rows

build_run_metric_rows(
    result: ExperimentResult,
    *,
    registry: SemanticRegistry | None = None,
) -> list[RunMetricRow]
Source code in src/autobench/reports/reporting.py
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
def build_run_metric_rows(
    result: ExperimentResult,
    *,
    registry: SemanticRegistry | None = None,
) -> list[RunMetricRow]:
    active_registry = registry or result.semantic_registry
    return [
        RunMetricRow(
            case_id=run.case_id,
            variant_id=run.variant_id,
            status=run.status.value,
            metrics=_run_metric_values(run, registry=active_registry),
        )
        for run in result.runs
    ]

build_status_counts

build_status_counts(
    result: ExperimentResult,
) -> dict[str, int]
Source code in src/autobench/reports/reporting.py
201
202
203
204
205
def build_status_counts(result: ExperimentResult) -> dict[str, int]:
    counts: dict[str, int] = {}
    for run in result.runs:
        counts[run.status.value] = counts.get(run.status.value, 0) + 1
    return dict(sorted(counts.items()))

build_variant_configs

build_variant_configs(
    result: ExperimentResult,
) -> list[VariantConfigRow]
Source code in src/autobench/reports/reporting.py
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
def build_variant_configs(result: ExperimentResult) -> list[VariantConfigRow]:
    grouped: dict[str, dict[str, Any]] = {}
    labels = _variant_labels(result)
    for run in result.runs:
        factor_values = grouped.setdefault(run.variant_id, {})
        for factor in run.factors:
            factor_values[factor.name] = factor.value
    return [
        VariantConfigRow(
            variant_id=variant_id,
            label=labels.get(variant_id),
            factors=grouped[variant_id],
        )
        for variant_id in sorted(grouped)
    ]

compare_variants

compare_variants(
    result: ExperimentResult,
    *,
    baseline: str,
    candidate: str,
    metrics: tuple[
        MetricAggregation, ...
    ] = DEFAULT_LEADERBOARD_METRICS,
    registry: SemanticRegistry | None = None,
) -> ComparisonReport
Source code in src/autobench/reports/reporting.py
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
def compare_variants(
    result: ExperimentResult,
    *,
    baseline: str,
    candidate: str,
    metrics: tuple[MetricAggregation, ...] = DEFAULT_LEADERBOARD_METRICS,
    registry: SemanticRegistry | None = None,
) -> ComparisonReport:
    active_registry = registry or result.semantic_registry
    baseline_runs = [run for run in result.runs if run.variant_id == baseline]
    candidate_runs = [run for run in result.runs if run.variant_id == candidate]
    factor_deltas = _factor_deltas(baseline_runs, candidate_runs)
    metric_deltas: dict[str, dict[str, Any]] = {}

    for metric in metrics:
        baseline_value = aggregate_values(
            [
                value
                for run in baseline_runs
                if (value := metric_value(run, metric.semantic_type, registry=active_registry))
                is not None
            ],
            metric.fn,
        )
        candidate_value = aggregate_values(
            [
                value
                for run in candidate_runs
                if (value := metric_value(run, metric.semantic_type, registry=active_registry))
                is not None
            ],
            metric.fn,
        )
        metric_deltas[metric.name] = {
            "baseline": baseline_value,
            "candidate": candidate_value,
            "delta": (
                float(candidate_value) - float(baseline_value)
                if isinstance(candidate_value, int | float)
                and isinstance(baseline_value, int | float)
                else None
            ),
        }

    return ComparisonReport(
        baseline=baseline,
        candidate=candidate,
        run_count=min(len(baseline_runs), len(candidate_runs)),
        factor_deltas=factor_deltas,
        metric_deltas=metric_deltas,
        confounded=len(factor_deltas) > 1,
    )

metric_observation

metric_observation(
    run: RunResult,
    semantic_type: str,
    *,
    registry: SemanticRegistry | None = None,
) -> Observation | None
Source code in src/autobench/reports/reporting.py
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
def metric_observation(
    run: RunResult,
    semantic_type: str,
    *,
    registry: SemanticRegistry | None = None,
) -> Observation | None:
    active_registry = registry or DEFAULT_SEMANTIC_REGISTRY
    normalized = active_registry.normalize(semantic_type)
    candidates = [
        observation
        for observation in run.task_result.observations
        if observation.kind is ObservationKind.METRIC
        and observation.normalized_semantic_type(active_registry) == normalized
    ]
    if not candidates:
        return None
    ordered = sorted(
        enumerate(candidates),
        key=lambda item: (*observation_priority(item[1]), item[0]),
    )
    return ordered[0][1]

metric_value

metric_value(
    run: RunResult,
    semantic_type: str,
    *,
    registry: SemanticRegistry | None = None,
) -> Any | None
Source code in src/autobench/reports/reporting.py
380
381
382
383
384
385
386
387
def metric_value(
    run: RunResult,
    semantic_type: str,
    *,
    registry: SemanticRegistry | None = None,
) -> Any | None:
    observation = metric_observation(run, semantic_type, registry=registry)
    return observation.value if observation is not None else None

render_markdown_report

render_markdown_report(report: BenchmarkReport) -> str
Source code in src/autobench/reports/reporting.py
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
def render_markdown_report(report: BenchmarkReport) -> str:
    lines = [
        f"# {report.benchmark_id}",
        "",
        f"experiment: `{report.experiment_id}`",
        f"runs: `{report.run_count}`",
        "",
        "## Leaderboard",
        "",
    ]
    metric_names = list(dict.fromkeys(name for row in report.leaderboard for name in row.metrics))
    lines.append("| variant | runs | " + " | ".join(metric_names) + " |")
    lines.append("| --- | ---: | " + " | ".join("---:" for _ in metric_names) + " |")
    for row in report.leaderboard:
        lines.append(
            f"| {row.variant_id} | {row.run_count} | "
            + " | ".join(_format_value(row.metrics.get(name)) for name in metric_names)
            + " |"
        )

    lines.extend(["", "## Case Matrix", ""])
    variants = sorted({variant for row in report.case_matrix.rows.values() for variant in row})
    lines.append("| case | " + " | ".join(variants) + " |")
    lines.append("| --- | " + " | ".join("---:" for _ in variants) + " |")
    for case_id, values in sorted(report.case_matrix.rows.items()):
        lines.append(
            f"| {case_id} | "
            + " | ".join(_format_value(values.get(variant)) for variant in variants)
            + " |"
        )

    if report.comparisons:
        lines.extend(["", "## Comparisons", ""])
        for comparison in report.comparisons:
            lines.append(f"### {comparison.baseline} vs {comparison.candidate}")
            lines.append("")
            lines.append(f"runs: `{comparison.run_count}`")
            lines.append(f"confounded: `{comparison.confounded}`")
            lines.append("")
            lines.append("| metric | baseline | candidate | delta |")
            lines.append("| --- | ---: | ---: | ---: |")
            for metric_name, delta in sorted(comparison.metric_deltas.items()):
                lines.append(
                    "| "
                    + " | ".join(
                        [
                            metric_name,
                            _format_value(delta.get("baseline")),
                            _format_value(delta.get("candidate")),
                            _format_value(delta.get("delta")),
                        ]
                    )
                    + " |"
                )
            lines.append("")

    if report.distributions:
        lines.extend(["", "## Distributions", ""])
        for distribution in report.distributions:
            lines.append(f"### {distribution.name} (`{distribution.semantic_type}`)")
            lines.append("")
            summary_names = list(
                dict.fromkeys(
                    name for summaries in distribution.summaries.values() for name in summaries
                )
            )
            lines.append("| variant | samples | " + " | ".join(summary_names) + " |")
            lines.append("| --- | ---: | " + " | ".join("---:" for _ in summary_names) + " |")
            for variant_id, values in sorted(distribution.by_variant.items()):
                summaries = distribution.summaries.get(variant_id, {})
                lines.append(
                    f"| {variant_id} | {len(values)} | "
                    + " | ".join(_format_value(summaries.get(name)) for name in summary_names)
                    + " |"
                )
    return "\n".join(lines) + "\n"

get_active_run_context

get_active_run_context() -> RunContext | None
Source code in src/autobench/runtime/instrumentation.py
172
173
def get_active_run_context() -> RunContext | None:
    return active_run_context()

instrument_method

instrument_method(
    target: type[Any],
    method_name: str,
    *,
    span: str | None = None,
    span_kind: SpanKind | str = SpanKind.CUSTOM,
    metrics: list[InstrumentMetricSpec] | None = None,
    factors: list[InstrumentFactorSpec] | None = None,
    operation_family: str | None = None,
) -> InstrumentationHandle
Source code in src/autobench/runtime/instrumentation.py
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
def instrument_method(
    target: type[Any],
    method_name: str,
    *,
    span: str | None = None,
    span_kind: SpanKind | str = SpanKind.CUSTOM,
    metrics: list[InstrumentMetricSpec] | None = None,
    factors: list[InstrumentFactorSpec] | None = None,
    operation_family: str | None = None,
) -> InstrumentationHandle:
    family = operation_family or f"{target.__module__}.{target.__qualname__}.{method_name}"
    instrumentation = _MethodInstrumentation(
        span=span,
        span_kind=span_kind,
        metrics=tuple(metrics or ()),
        factors=tuple(factors or ()),
        scope=_METHOD_RUNTIME.scope(_METHOD_INFO),
        operation_family=family,
    )
    handler = _MethodHandler(instrumentation, _METHOD_RUNTIME, _METHOD_INFO)
    owner = f"{_METHOD_INFO.id}:{next(_METHOD_OWNER_INDEX)}"
    patch_handle = _METHOD_PATCHES.patch_method(
        target,
        method_name,
        owner=owner,
        handler=handler,
    )
    return InstrumentationHandle(patch_handle.close, info=_METHOD_INFO)

expand_matrix

expand_matrix(
    spec: BenchmarkSpec, *, experiment_id: str
) -> list[MatrixRunSpec]
Source code in src/autobench/runtime/pipeline.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
def expand_matrix(
    spec: BenchmarkSpec,
    *,
    experiment_id: str,
) -> list[MatrixRunSpec]:
    return [
        MatrixRunSpec(
            run_id=stable_run_id(
                case=case, variant=variant, case_index=case_index, variant_index=variant_index
            ),
            benchmark_id=spec.benchmark.id,
            experiment_id=experiment_id,
            case_index=case_index,
            variant_index=variant_index,
            case=case,
            variant=variant,
        )
        for case_index, case in enumerate(spec.dataset.cases)
        for variant_index, variant in enumerate(spec.variants)
    ]

generate_experiment_id

generate_experiment_id(benchmark_id: str) -> str
Source code in src/autobench/runtime/pipeline.py
175
176
177
def generate_experiment_id(benchmark_id: str) -> str:
    timestamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%S%fZ")
    return f"exp_{_slug(benchmark_id)}_{timestamp}"

run_benchmark_path

run_benchmark_path(
    path: Path,
    *,
    experiment_id: str | None = None,
    concurrency_limit: int | None = 1,
    instrumentors: Sequence[Instrumentor] = (),
) -> ExperimentResult
Source code in src/autobench/runtime/pipeline.py
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
def run_benchmark_path(
    path: Path,
    *,
    experiment_id: str | None = None,
    concurrency_limit: int | None = 1,
    instrumentors: Sequence[Instrumentor] = (),
) -> ExperimentResult:
    from autobench.spec import load_benchmark_spec

    spec = load_benchmark_spec(path)
    return run_sync(
        run_benchmark_spec(
            spec,
            experiment_id=experiment_id,
            concurrency_limit=concurrency_limit,
            instrumentors=instrumentors,
        )
    )

run_benchmark_spec async

run_benchmark_spec(
    spec: BenchmarkSpec,
    *,
    experiment_id: str | None = None,
    concurrency_limit: int | None = 1,
    instrumentors: Sequence[Instrumentor] = (),
) -> ExperimentResult
Source code in src/autobench/runtime/pipeline.py
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
async def run_benchmark_spec(
    spec: BenchmarkSpec,
    *,
    experiment_id: str | None = None,
    concurrency_limit: int | None = 1,
    instrumentors: Sequence[Instrumentor] = (),
) -> ExperimentResult:
    from autobench.spec import build_benchmark_plan

    active_experiment_id = experiment_id or generate_experiment_id(spec.benchmark.id)
    plan = build_benchmark_plan(spec)
    run_specs = expand_matrix(spec, experiment_id=active_experiment_id)
    environment = capture_environment()

    configured, instrumentation_diagnostics = resolve_instrumentors(
        spec.instrumentation,
        reserved_ids={instrumentor.info.id for instrumentor in instrumentors},
    )
    active_instrumentors = [*configured, *instrumentors]
    instrumentor_ids = [instrumentor.info.id for instrumentor in active_instrumentors]
    duplicate_ids = sorted(
        instrumentor_id
        for instrumentor_id in set(instrumentor_ids)
        if instrumentor_ids.count(instrumentor_id) > 1
    )
    if duplicate_ids:
        raise InstrumentationError(
            f"duplicate instrumentors configured: {', '.join(duplicate_ids)}"
        )

    with InstrumentationManager() as instrumentation:
        for instrumentor in active_instrumentors:
            instrumentation.install(instrumentor)

        if concurrency_limit is None or concurrency_limit <= 1:
            runs = [
                await _run_matrix_item(
                    spec,
                    run_spec,
                    instrumentation_diagnostics=instrumentation_diagnostics,
                )
                for run_spec in run_specs
            ]
        else:
            semaphore = asyncio.Semaphore(concurrency_limit)
            runs = await asyncio.gather(
                *[
                    _run_matrix_item_limited(
                        spec,
                        run_spec,
                        semaphore,
                        instrumentation_diagnostics=instrumentation_diagnostics,
                    )
                    for run_spec in run_specs
                ]
            )

    result = ExperimentResult(
        experiment_id=active_experiment_id,
        benchmark_id=spec.benchmark.id,
        plan=plan,
        runs=runs,
        environment=environment,
        report_spec_data=spec.reports.model_dump(mode="json"),
        semantic_registry=spec.semantic_registry.model_copy(deep=True),
        spec_snapshot=spec.model_dump(mode="json"),
        spec_hash=_spec_hash(spec),
    )
    if spec.post_derive:
        from autobench.evaluation.comparison import derive_experiment_observations

        result = derive_experiment_observations(
            spec.post_derive,
            result=result,
            registry=spec.semantic_registry,
        )
    if spec.policies:
        from autobench.evaluation.policies import apply_policies

        result = apply_policies(
            spec.policies,
            result=result,
            registry=spec.semantic_registry,
        )
    return _refresh_run_statuses(result, registry=spec.semantic_registry)

stable_run_id

stable_run_id(
    *,
    case: Case,
    variant: Variant,
    case_index: int,
    variant_index: int,
) -> str
Source code in src/autobench/runtime/pipeline.py
163
164
165
166
167
168
169
170
171
172
def stable_run_id(
    *,
    case: Case,
    variant: Variant,
    case_index: int,
    variant_index: int,
) -> str:
    case_slug = _slug(case.id)
    variant_slug = _slug(variant.id)
    return f"run_{case_index + 1:04d}_{variant_index + 1:04d}_{case_slug}__{variant_slug}"

progress_event

progress_event(
    kind: ProgressEventKind, message: str, **data: Any
) -> ProgressEvent
Source code in src/autobench/runtime/progress.py
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
def progress_event(
    kind: ProgressEventKind,
    message: str,
    **data: Any,
) -> ProgressEvent:
    known_fields = {
        "benchmark_id",
        "experiment_id",
        "run_id",
        "case_id",
        "variant_id",
    }
    payload = {key: value for key, value in data.items() if key in known_fields}
    payload["data"] = {key: value for key, value in data.items() if key not in known_fields}
    return ProgressEvent(kind=kind, message=message, **payload)

record_pydantic_ai_usage

record_pydantic_ai_usage(
    ctx: RunContext,
    usage: PydanticAIUsage,
    *,
    span_id: str | None = None,
) -> tuple[Observation, ...]
Source code in src/autobench/runtime/pydantic_ai.py
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
def record_pydantic_ai_usage(
    ctx: RunContext,
    usage: PydanticAIUsage,
    *,
    span_id: str | None = None,
) -> tuple[Observation, ...]:
    observations: list[Observation] = []
    metric_values = {
        "requests": usage.requests,
        "input_tokens": usage.input_tokens,
        "output_tokens": usage.output_tokens,
        "total_tokens": usage.total_tokens,
        "cache_read_tokens": usage.cache_read_tokens,
        "cache_write_tokens": usage.cache_write_tokens,
    }
    semantic_types = {
        "input_tokens": Semantic.LLM_TOKENS_INPUT,
        "output_tokens": Semantic.LLM_TOKENS_OUTPUT,
        "total_tokens": Semantic.LLM_TOKENS_TOTAL,
    }
    for name, value in metric_values.items():
        if value is None:
            continue
        observations.append(
            ctx.metric(
                f"pydantic_ai.{name}",
                value,
                semantic_type=semantic_types.get(name),
                direction=Direction.MINIMIZE if name == "requests" else None,
                role=ObservationRole.DIAGNOSTIC,
                span_id=span_id,
            )
        )
    if usage.model_name is not None:
        observations.append(
            ctx.factor_observation(
                "pydantic_ai.model",
                usage.model_name,
                semantic_type=Semantic.LLM_MODEL_NAME,
                span_id=span_id,
            )
        )
    if usage.provider is not None:
        observations.append(
            ctx.factor_observation(
                "pydantic_ai.provider",
                usage.provider,
                semantic_type=Semantic.LLM_PROVIDER,
                span_id=span_id,
            )
        )
    return tuple(observations)

resolve_python_callable

resolve_python_callable(
    target: str, *, search_paths: tuple[str, ...] = ()
) -> Callable[..., Any]
Source code in src/autobench/runtime/tasks.py
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
def resolve_python_callable(
    target: str,
    *,
    search_paths: tuple[str, ...] = (),
) -> Callable[..., Any]:
    module_name, separator, attribute_name = target.partition(":")
    if not separator or not module_name or not attribute_name:
        raise TaskResolutionError("Python task targets must use 'module:function' format.")

    try:
        module = importlib.import_module(module_name)
    except Exception:
        try:
            with _temporary_sys_path(search_paths):
                module = importlib.import_module(module_name)
        except Exception as fallback_exc:
            raise TaskResolutionError(
                f"Could not import task module '{module_name}'."
            ) from fallback_exc

    try:
        task = getattr(module, attribute_name)
    except AttributeError as exc:
        raise TaskResolutionError(
            f"Task target '{target}' does not define '{attribute_name}'."
        ) from exc

    if not callable(task):
        raise TaskResolutionError(f"Task target '{target}' is not callable.")
    return task

run_python_task async

run_python_task(
    target: str,
    *,
    ctx: RunContext,
    case: Case,
    search_paths: tuple[str, ...] = (),
) -> TaskResult
Source code in src/autobench/runtime/tasks.py
 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
async def run_python_task(
    target: str,
    *,
    ctx: RunContext,
    case: Case,
    search_paths: tuple[str, ...] = (),
) -> TaskResult:
    token = set_active_run_context(ctx)
    try:
        task = resolve_python_callable(target, search_paths=search_paths)
        output = task(ctx, case)
        if isawaitable(output):
            output = await output
    except TaskResolutionError as exc:
        error = _error_for_exception(ctx, exc)
        return TaskResult(
            output=None,
            status=TaskStatus.ERRORED,
            error=error,
            errors=list(ctx.errors),
            observations=list(ctx.observations),
            spans=list(ctx.spans),
            artifacts=list(ctx.artifacts),
        )
    except Exception as exc:
        error = _error_for_exception(ctx, exc)
        return TaskResult(
            output=None,
            status=TaskStatus.FAILED,
            error=error,
            errors=list(ctx.errors),
            observations=list(ctx.observations),
            spans=list(ctx.spans),
            artifacts=list(ctx.artifacts),
        )
    finally:
        reset_active_run_context(token)

    return TaskResult(
        output=output,
        status=TaskStatus.PASSED,
        errors=list(ctx.errors),
        observations=list(ctx.observations),
        spans=list(ctx.spans),
        artifacts=list(ctx.artifacts),
    )

attach_trace

attach_trace(
    ctx: RunContext, trace: TraceEnvelope
) -> list[Observation]
Source code in src/autobench/runtime/traces.py
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
def attach_trace(ctx: RunContext, trace: TraceEnvelope) -> list[Observation]:
    existing_span_ids = {span.id for span in ctx.spans}
    for span in trace.spans:
        if span.id not in existing_span_ids:
            ctx.spans.append(span)
            existing_span_ids.add(span.id)

    if trace.raw_artifact is not None and trace.raw_artifact.id not in {
        artifact.id for artifact in ctx.artifacts
    }:
        ctx.artifacts.append(trace.raw_artifact)

    for error in trace.errors:
        ctx.errors.append(error)

    observations = trace_to_observations(
        trace,
        case_id=ctx.case.id,
        variant_id=ctx.variant.id,
        id_prefix=f"trace_{len(ctx.observations) + 1}",
    )
    ctx.observations.extend(observations)
    return observations

trace_to_observations

trace_to_observations(
    trace: TraceEnvelope,
    *,
    case_id: str | None = None,
    variant_id: str | None = None,
    id_prefix: str = "trace",
) -> list[Observation]
Source code in src/autobench/runtime/traces.py
 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
def trace_to_observations(
    trace: TraceEnvelope,
    *,
    case_id: str | None = None,
    variant_id: str | None = None,
    id_prefix: str = "trace",
) -> list[Observation]:
    observations: list[Observation] = []
    for span in trace.spans:
        observations.extend(
            _span_usage_observations(
                span,
                trace_id=trace.trace_id,
                case_id=case_id,
                variant_id=variant_id,
                id_prefix=f"{id_prefix}_{len(observations) + 1}",
            )
        )
        if span.error is not None:
            observations.append(
                _trace_event(
                    f"{id_prefix}_{len(observations) + 1}",
                    name="span_error",
                    value=span.error.message,
                    trace_id=trace.trace_id,
                    span=span,
                    case_id=case_id,
                    variant_id=variant_id,
                )
            )
    for error in trace.errors:
        observations.append(
            Observation(
                id=f"{id_prefix}_{len(observations) + 1}",
                name="trace_error",
                kind=ObservationKind.EVENT,
                value=error.message,
                role=ObservationRole.DIAGNOSTIC,
                source=ObservationSource.IMPORTED,
                tags={"trace_id": trace.trace_id, "error_type": error.error_type},
                case_id=case_id,
                variant_id=variant_id,
            )
        )
    return observations

benchmark_spec_payload_from_yaml_view

benchmark_spec_payload_from_yaml_view(
    raw: Any,
) -> dict[str, Any]
Source code in src/autobench/spec/__init__.py
77
78
79
80
81
82
83
84
85
86
87
def benchmark_spec_payload_from_yaml_view(raw: Any) -> dict[str, Any]:
    if not isinstance(raw, dict):
        raise TypeError("benchmark spec snapshot must be a mapping")

    normalized = _normalize_benchmark_dsl(dict(raw))
    if "semantic_registry" in normalized:
        normalized["semantic_registry"] = _resolve_semantic_registry_section(
            normalized["semantic_registry"]
        )
    spec = BenchmarkSpec.model_validate(normalized)
    return spec.model_dump(mode="json")

benchmark_spec_to_yaml_view

benchmark_spec_to_yaml_view(
    spec: BenchmarkSpec,
) -> dict[str, Any]
Source code in src/autobench/spec/spec.py
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
def benchmark_spec_to_yaml_view(spec: BenchmarkSpec) -> dict[str, Any]:
    body: dict[str, Any] = {}
    if spec.benchmark.description is not None:
        body["description"] = spec.benchmark.description

    body["dataset"] = _benchmark_dataset_to_yaml_view(spec.dataset)

    if spec.task is not None:
        body["run"] = _task_to_yaml_view(spec.task)
    if spec.variants:
        body["variants"] = _variants_to_yaml_view(spec.variants)
    if spec.scoring:
        body["score"] = _scoring_to_yaml_view(spec.scoring)
    if spec.derive:
        body["derive"] = [_compact_model_dump(item) for item in spec.derive]
    if spec.post_derive:
        body["post_derive"] = [_compact_model_dump(item) for item in spec.post_derive]
    if spec.policies:
        body["policies"] = [_compact_model_dump(item) for item in spec.policies]
    if spec.instrumentation:
        body["instrumentation"] = _instrumentation_to_yaml_view(spec.instrumentation)

    report_view = _report_to_yaml_view(spec.reports)
    if report_view:
        body["report"] = report_view

    semantic_registry_view = _semantic_registry_delta_to_yaml_view(spec.semantic_registry)
    if semantic_registry_view:
        body["semantic_registry"] = semantic_registry_view

    return {"benchmark": {spec.benchmark.id: body}}

build_benchmark_plan

build_benchmark_plan(spec: BenchmarkSpec) -> BenchmarkPlan
Source code in src/autobench/spec/__init__.py
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
def build_benchmark_plan(spec: BenchmarkSpec) -> BenchmarkPlan:
    case_count = len(spec.dataset.cases)
    variant_count = len(spec.variants)
    warnings: list[str] = []

    if case_count == 0:
        warnings.append("No cases defined.")
    if variant_count == 0:
        warnings.append("No variants defined.")
    if spec.task is None:
        warnings.append("No task defined.")

    return BenchmarkPlan(
        benchmark_id=spec.benchmark.id,
        dataset_id=spec.dataset.id,
        dataset_version=spec.dataset.version,
        dataset_hash=dataset_content_hash(spec.dataset),
        case_ids=tuple(case.id for case in spec.dataset.cases),
        case_count=case_count,
        variant_count=variant_count,
        planned_run_count=case_count * variant_count,
        warnings=warnings,
    )

collect_benchmark_source_files

collect_benchmark_source_files(
    path: Path,
) -> tuple[Path, ...]
Source code in src/autobench/spec/__init__.py
159
160
161
162
163
164
165
166
167
168
169
170
def collect_benchmark_source_files(path: Path) -> tuple[Path, ...]:
    raw = load_yaml(path)
    if raw is None:
        raw = {}
    if not isinstance(raw, dict):
        raise SpecValidationError(f"Expected mapping at top level in {path}")

    source_files = [path.resolve()]
    source_files.extend(
        _collect_referenced_source_files(_normalize_benchmark_dsl(raw), base_path=path)
    )
    return tuple(_dedupe_paths(source_files))

load_benchmark_spec

load_benchmark_spec(path: Path) -> BenchmarkSpec
Source code in src/autobench/spec/__init__.py
 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
def load_benchmark_spec(path: Path) -> BenchmarkSpec:
    raw = load_yaml(path)
    if raw is None:
        raw = {}
    if not isinstance(raw, dict):
        raise SpecValidationError(f"Expected mapping at top level in {path}")

    resolved_raw = _normalize_benchmark_dsl(raw)
    if "dataset" in resolved_raw:
        resolved_raw["dataset"] = _resolve_dataset_section(
            resolved_raw["dataset"],
            base_path=path,
        )
    if "variants" in resolved_raw:
        resolved_raw["variants"] = _resolve_variants_section(resolved_raw["variants"])
    if "derive" in resolved_raw:
        resolved_raw["derive"] = _resolve_derive_section(
            resolved_raw["derive"],
            base_path=path,
        )
    if "post_derive" in resolved_raw:
        resolved_raw["post_derive"] = _resolve_post_derive_section(resolved_raw["post_derive"])
    if "policies" in resolved_raw:
        resolved_raw["policies"] = _resolve_policies_section(resolved_raw["policies"])
    if "semantic_registry" in resolved_raw:
        resolved_raw["semantic_registry"] = _resolve_semantic_registry_section(
            resolved_raw["semantic_registry"]
        )

    try:
        spec = BenchmarkSpec.model_validate(resolved_raw)
    except ValidationError as exc:
        raise SpecValidationError(str(exc)) from exc

    merged_cases = [
        merge_case_defaults(case, spec.dataset.case_defaults) for case in spec.dataset.cases
    ]
    resolved_task = spec.task
    if resolved_task is not None and resolved_task.kind == "python":
        resolved_task = resolved_task.model_copy(
            update={
                "module_search_paths": _infer_module_search_paths(
                    resolved_task.target,
                    base_path=path,
                )
            }
        )
    resolved_scoring = [
        scorer.model_copy(
            update={
                "module_search_paths": _infer_module_search_paths(
                    scorer.target,
                    base_path=path,
                )
            }
        )
        if isinstance(scorer, PythonScorer)
        else scorer
        for scorer in spec.scoring
    ]
    return spec.model_copy(
        update={
            "dataset": spec.dataset.model_copy(update={"cases": merged_cases}),
            "task": resolved_task,
            "scoring": resolved_scoring,
        }
    )

asset_index_to_yaml_view

asset_index_to_yaml_view(
    assets: list[TrackedAsset], versions: list[AssetVersion]
) -> dict[str, Any]
Source code in src/autobench/tracking/history.py
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
def asset_index_to_yaml_view(
    assets: list[TrackedAsset],
    versions: list[AssetVersion],
) -> dict[str, Any]:
    return {
        "record": {
            "type": "asset_index",
            "version": 1,
        },
        "assets": {
            asset.id: {
                "kind": _asset_yaml_kind(asset),
                "name": asset.name,
                **({"semantic": asset.semantic_type} if asset.semantic_type is not None else {}),
                "current_version": version.version,
                "file": f"{_safe_filename(asset.id)}.yaml",
            }
            for asset, version in zip(assets, versions, strict=True)
        },
    }

asset_to_yaml_view

asset_to_yaml_view(
    asset: TrackedAsset,
    version: AssetVersion,
    *,
    existing: Any = None,
) -> dict[str, Any]
Source code in src/autobench/tracking/history.py
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
def asset_to_yaml_view(
    asset: TrackedAsset,
    version: AssetVersion,
    *,
    existing: Any = None,
) -> dict[str, Any]:
    existing_versions = _existing_asset_versions(existing)
    current_snapshot = _asset_version_snapshot(asset)
    previous_snapshot = _existing_asset_current_snapshot(existing)
    if previous_snapshot is None and existing_versions:
        previous_snapshot = _version_entry_snapshot(existing_versions[-1])
    version_payload = _asset_version_payload(
        version,
        current_snapshot,
        previous_snapshot=previous_snapshot,
    )
    versions = [
        entry
        for entry in existing_versions
        if isinstance(entry.get("version"), str) and entry["version"] != version.version
    ]
    versions.append(version_payload)
    return {
        "record": {
            "type": "asset",
            "version": 1,
        },
        "asset": _asset_yaml_view(asset, current_version=version.version),
        "versions": versions,
    }