Skip to content

API Reference

This reference is generated from the installed public autobench package. The root package is the supported import surface; subpackages organize implementation and extension areas.

Public Package

autobench

__version__ module-attribute

__version__ = '0.3.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
    | PydanticGEPAInstrumentation
    | OpenAIInstrumentation
    | OpenAIAgentsInstrumentation
    | HTTPXInstrumentation,
    Field(discriminator="kind"),
]

InstrumentorName module-attribute

InstrumentorName: TypeAlias = Literal[
    "pydantic_ai",
    "pydantic_gepa",
    "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()
)

RecordDurability module-attribute

RecordDurability = Literal['atomic', 'synced']

RECORD_VERSION module-attribute

RECORD_VERSION = 6

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

ExperimentPublisher module-attribute

ExperimentPublisher = Callable[
    [ExperimentResult, ExperimentRecord, Path],
    Sequence[ExperimentFile],
]

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",
]

ReportLayout module-attribute

ReportLayout = Literal['single', 'bundle', 'auto']

ReportProfile module-attribute

ReportProfile = Literal['summary', 'full', 'audit']

ProgressErrorHandler module-attribute

ProgressErrorHandler = Callable[
    [ProgressHandlerFailure], None
]

ProgressHandler module-attribute

ProgressHandler = Callable[
    [ProgressEvent], None | Awaitable[None]
]

track module-attribute

track = TrackingRegistry()

__all__ module-attribute

__all__ = (
    "AutoInstrumentation",
    "ABSTRACTION_LAYER_TAG",
    "AggregationFn",
    "ActionMatchResult",
    "ArtifactRef",
    "ArtifactError",
    "ArtifactOverflow",
    "ArtifactSink",
    "ArtifactSinkRequiredError",
    "ArtifactSource",
    "ArtifactState",
    "ArtifactTransferError",
    "AssetContentRef",
    "AssetDefinition",
    "AssetDiffRef",
    "AssetDiscoverySettings",
    "AssetProvenance",
    "AssetRepresentation",
    "AssetSensitivity",
    "AssetUse",
    "AssetVersion",
    "AutobenchError",
    "BenchContext",
    "Benchmark",
    "BenchmarkPlan",
    "BenchmarkReport",
    "BenchmarkInfo",
    "BenchmarkSpec",
    "BetweenRequirement",
    "CSV_METRICS",
    "Case",
    "CaseGenerator",
    "CaseGeneratorInput",
    "CaseMatrix",
    "CaseMatrixReportSpec",
    "CaseDefaults",
    "CandidateSummary",
    "CaptureLevel",
    "CapturePolicy",
    "CheckResult",
    "ContextEvidence",
    "Component",
    "Compatibility",
    "CompatibilityStatus",
    "CurrentSpan",
    "ComparisonVerdict",
    "ComparisonVerdictSpec",
    "ComparisonReport",
    "ComparisonReportSpec",
    "CorrelatedReportGroup",
    "CompositeExtractor",
    "DEFAULT_LEADERBOARD_METRICS",
    "DEFAULT_METRIC_PACKS",
    "DEFAULT_SEMANTIC_REGISTRY",
    "DatasetSpec",
    "DatasetSummary",
    "DerivedMetricOutput",
    "DistributionReportSpec",
    "EvaluationCaseReport",
    "EvaluationMetricReport",
    "EvaluationSummaryReport",
    "Direction",
    "DurationMetricSpec",
    "EnvironmentMetadata",
    "EndReason",
    "EngineSummary",
    "EvaluationStatus",
    "ExecutionCorrelation",
    "ExecutionSnapshot",
    "ExecutionSpec",
    "ErrorRecord",
    "EXTRACTOR_TAG",
    "EXTRACTOR_VERSION_TAG",
    "ExactScorer",
    "ExtractionContext",
    "ExtractionEvidence",
    "ExtractionResult",
    "ExpectedAction",
    "ExpectedActionScorer",
    "ExperimentRecord",
    "ExperimentFile",
    "ExperimentPublisher",
    "ExperimentResult",
    "ExperimentStart",
    "ExperimentStatus",
    "ExperimentTermination",
    "FactorValue",
    "FeedbackRecord",
    "FieldAsset",
    "FileRecordSession",
    "FileRecorder",
    "GeneratedCaseBatch",
    "GeneratedCaseRecord",
    "GeneratedCaseReview",
    "GenerationCost",
    "GenerationDeterminism",
    "GenerationError",
    "GenerationResult",
    "GenerationUsage",
    "GenerationWriteResult",
    "GenAIPricesSource",
    "HTTPXCaptureSettings",
    "HTTPXInstrumentation",
    "INSTRUMENTOR_TAG",
    "InstrumentCall",
    "InstrumentAssetSpec",
    "InstrumentFactorSpec",
    "InstrumentationConflictError",
    "InstrumentationError",
    "InstrumentationHandle",
    "InstrumentationManager",
    "InstrumentationRuntime",
    "InstrumentationConfig",
    "InstrumentationSettings",
    "InstrumentMetricSpec",
    "Instrumentor",
    "InstrumentorCapabilities",
    "InstrumentorInfo",
    "InstrumentorName",
    "InstrumentorStatus",
    "LeaderboardRow",
    "LeaderboardReportSpec",
    "LOGICAL_OPERATION_TAG",
    "LogicalRecordTarget",
    "ManifestEntry",
    "Measurement",
    "MeasurementBudget",
    "MeasurementRecord",
    "MeasurementTimer",
    "MEASUREMENT_SCOPE_TAG",
    "MetricAggregation",
    "MetricDistribution",
    "MetricPack",
    "MetricPackRegistry",
    "ModelPricing",
    "Observation",
    "ObservationQuery",
    "ObservationKind",
    "ObservationRole",
    "ObservationSource",
    "ObjectiveSummary",
    "OpenAIAgentsInstrumentation",
    "OpenAIInstrumentation",
    "OutputMetricScorer",
    "OptimizationFeedbackInput",
    "OptimizationExecution",
    "PairedBaselineDeriverSpec",
    "PairedBaselineFormula",
    "ParamAsset",
    "ParamSchema",
    "PassFailScorer",
    "PatchDiagnostic",
    "PatchManager",
    "PartialRunSnapshot",
    "PydanticAIInstrumentation",
    "PydanticGEPA",
    "PydanticGEPAEvidence",
    "PydanticGEPAInstrumentation",
    "PolicyResult",
    "PolicySpec",
    "PostDerivationMissingPolicy",
    "PriceSource",
    "PricingTable",
    "ProgressDispatchError",
    "ProgressErrorHandler",
    "ProgressErrorPolicy",
    "ProgressEvent",
    "ProgressEventKind",
    "ProgressHandler",
    "ProgressHandlerFailure",
    "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",
    "OTLPExportError",
    "OTLPExportResult",
    "OTLPSettings",
    "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",
    "SelectionSummary",
    "semantic_registry_payload_from_yaml_view",
    "semantic_registry_to_yaml_view",
    "SchemaScorer",
    "SUMMARY_TAG",
    "ScoreRecord",
    "ScoringCall",
    "SpecLoadError",
    "SpecValidationError",
    "RunContext",
    "RunRecord",
    "RunResult",
    "RunStatus",
    "RecordingError",
    "RecordDurability",
    "RecordedRunPayloads",
    "Recorder",
    "RecordSession",
    "RecordFileKind",
    "RecordManifest",
    "RecordLineage",
    "ReplayError",
    "ReplayKind",
    "RelativeThreshold",
    "RecoveredStaging",
    "ReportSpec",
    "RunMetricRow",
    "ReviewStatus",
    "SampleReason",
    "SamplingPolicy",
    "RunMatchKey",
    "RunMatchKeyKind",
    "RunPhase",
    "Span",
    "SpanKind",
    "SpanRecord",
    "SpanExtractor",
    "SpanSelector",
    "Stage",
    "SymlinkPolicy",
    "StaticPriceSource",
    "StagedCheckpoint",
    "StagedRun",
    "StagingHealth",
    "StagingInspection",
    "StagingManifest",
    "StagingState",
    "StagingStatus",
    "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",
    "archive_staging",
    "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_grouped_reports",
    "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",
    "correlation_matches",
    "classify_metric_comparison",
    "dataset_content_hash",
    "dataset_to_yaml_view",
    "derive_observations",
    "discard_staging",
    "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",
    "filter_experiments",
    "finalize_staging",
    "generated_batch_from_cases",
    "generate_dataset",
    "generate_dataset_sync",
    "generated_case_content_hash",
    "generation_request_from_yaml_view",
    "generation_request_hash",
    "generation_request_to_yaml_view",
    "generation_result_to_yaml_view",
    "generate_experiment_id",
    "get_active_run_context",
    "instrument_method",
    "instrumentor_statuses",
    "inspect_staging",
    "aggregate_values",
    "export_markdown_report",
    "export_otlp",
    "export_record_otlp",
    "export_runs_csv",
    "export_summary_yaml",
    "evaluate_policies",
    "evaluate_run_policies",
    "load_experiment_record",
    "load_pricing_table",
    "load_run_record",
    "load_benchmark_spec",
    "load_generation_request",
    "load_asset_content",
    "load_asset_diff",
    "measure_callable",
    "mark_generated_case",
    "MarkdownAssetConfig",
    "MarkdownContentConfig",
    "MarkdownExperimentPublisher",
    "MarkdownReportConfig",
    "MarkdownReportLimits",
    "MarkdownReportPublication",
    "MarkdownTraceConfig",
    "match_expected_actions",
    "merge_case_defaults",
    "merge_execution_correlation",
    "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",
    "ReportLayout",
    "ReportPublicationError",
    "ReportProfile",
    "recover_staging",
    "render_markdown_report",
    "render_markdown_bundle",
    "report_to_yaml_view",
    "resolve_dotted_path",
    "resolve_python_callable",
    "resolve_case_generator",
    "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",
    "write_generation_result",
    "write_markdown_report",
    "PublishedReportFile",
)

BenchContext

Bases: BaseModel

Source code in src/autobench/builders/components.py
45
46
47
48
49
50
51
52
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
 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
class Benchmark:
    def __init__(self, benchmark_id: str) -> None:
        self._benchmark = BenchmarkInfo(id=benchmark_id)
        self._capture: CapturePolicy | None = None
        self._execution = ExecutionSpec()
        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 capture(self, policy: CapturePolicy | Mapping[str, Any]) -> Benchmark:
        self._capture = (
            policy if isinstance(policy, CapturePolicy) else CapturePolicy.model_validate(policy)
        )
        return self

    def correlation(
        self,
        value: ExecutionCorrelation | Mapping[str, Any],
    ) -> Benchmark:
        correlation = (
            value
            if isinstance(value, ExecutionCorrelation)
            else ExecutionCorrelation.model_validate(value)
        )
        self._execution = ExecutionSpec(correlation=correlation)
        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,
                    PydanticGEPAInstrumentation,
                    OpenAIInstrumentation,
                    OpenAIAgentsInstrumentation,
                    HTTPXInstrumentation,
                ),
            ):
                self._instrumentation.append(item)
            else:
                self._instrumentors.append(item)
        return self

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

        automatic = AutoInstrumentation(
            exclude=tuple(exclude),
            strict=strict,
            assets=(None if assets is None else AssetDiscoverySettings.model_validate(assets)),
        )
        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,
            capture=self._capture,
            execution=self._execution,
            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,
        correlation: ExecutionCorrelation | None = None,
        concurrency_limit: int | None = 1,
        progress_handlers: Sequence[ProgressHandler] = (),
        progress_error_policy: ProgressErrorPolicy = ProgressErrorPolicy.STRICT,
        progress_error_handler: ProgressErrorHandler | None = None,
    ) -> ExperimentResult:
        from autobench.runtime.pipeline import run_benchmark_spec

        return await run_benchmark_spec(
            self.to_spec(),
            experiment_id=experiment_id,
            correlation=correlation,
            concurrency_limit=concurrency_limit,
            instrumentors=self._instrumentors,
            progress_handlers=progress_handlers,
            progress_error_policy=progress_error_policy,
            progress_error_handler=progress_error_handler,
        )

    def run(
        self,
        *,
        experiment_id: str | None = None,
        correlation: ExecutionCorrelation | None = None,
        concurrency_limit: int | None = 1,
        progress_handlers: Sequence[ProgressHandler] = (),
        progress_error_policy: ProgressErrorPolicy = ProgressErrorPolicy.STRICT,
        progress_error_handler: ProgressErrorHandler | None = None,
    ) -> ExperimentResult:
        return run_sync(
            self.run_async(
                experiment_id=experiment_id,
                correlation=correlation,
                concurrency_limit=concurrency_limit,
                progress_handlers=progress_handlers,
                progress_error_policy=progress_error_policy,
                progress_error_handler=progress_error_handler,
            )
        )
instrument
instrument(
    *instrumentation: InstrumentationConfig | Instrumentor,
) -> Benchmark

Add serializable settings or a custom runtime instrumentor.

Source code in src/autobench/builders/components.py
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
def instrument(
    self,
    *instrumentation: InstrumentationConfig | Instrumentor,
) -> Benchmark:
    """Add serializable settings or a custom runtime instrumentor."""

    for item in instrumentation:
        if isinstance(
            item,
            (
                AutoInstrumentation,
                PydanticAIInstrumentation,
                PydanticGEPAInstrumentation,
                OpenAIInstrumentation,
                OpenAIAgentsInstrumentation,
                HTTPXInstrumentation,
            ),
        ):
            self._instrumentation.append(item)
        else:
            self._instrumentors.append(item)
    return self
instrument_all
instrument_all(
    *,
    exclude: Collection[InstrumentorName] = (),
    strict: bool = False,
    assets: AssetDiscoverySettings
    | Mapping[str, Any]
    | None = None,
) -> Benchmark

Enable every compatible built-in instrumentor available at runtime.

Source code in src/autobench/builders/components.py
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
def instrument_all(
    self,
    *,
    exclude: Collection[InstrumentorName] = (),
    strict: bool = False,
    assets: AssetDiscoverySettings | Mapping[str, Any] | None = None,
) -> Benchmark:
    """Enable every compatible built-in instrumentor available at runtime."""

    automatic = AutoInstrumentation(
        exclude=tuple(exclude),
        strict=strict,
        assets=(None if assets is None else AssetDiscoverySettings.model_validate(assets)),
    )
    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
32
33
34
class Component(Protocol):  # pragma: no cover
    id: str
    kind: str

Stage

Bases: Protocol

Source code in src/autobench/builders/components.py
37
38
39
40
41
42
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)

CaseGenerator

Bases: Protocol

Source code in src/autobench/data/generation.py
116
117
118
119
120
121
class CaseGenerator(Protocol):
    def __call__(
        self,
        request: CaseGeneratorInput,
        /,
    ) -> GeneratedCaseBatch | Awaitable[GeneratedCaseBatch]: ...

CaseGeneratorInput

Bases: BaseModel

Source code in src/autobench/data/generation.py
105
106
107
108
109
110
111
112
113
class CaseGeneratorInput(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    seed_cases: tuple[Case, ...] = ()
    prompt: str | None = None
    prompt_asset_version: str | None = None
    seed: int | str | None = None
    settings: dict[str, SerializedValue] = Field(default_factory=dict)
    metadata: dict[str, SerializedValue] = Field(default_factory=dict)

GeneratedCaseBatch

Bases: BaseModel

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

    generator_asset_version: str | None = None
    model_provider: str | None = None
    model_name: str | None = None
    determinism: GenerationDeterminism = GenerationDeterminism.UNKNOWN
    usage: GenerationUsage = Field(default_factory=GenerationUsage)
    cost: GenerationCost | None = None
    reviews: tuple[GeneratedCaseReview, ...] = ()
    complete: bool = True
    incomplete_reason: str | None = Field(default=None, min_length=1)
    cases: tuple[Case, ...] = ()

    @model_validator(mode="after")
    def validate_batch(self) -> GeneratedCaseBatch:
        case_ids = tuple(case.id for case in self.cases)
        if len(case_ids) != len(set(case_ids)):
            raise ValueError("generated case ids must be unique")
        review_ids = tuple(review.case_id for review in self.reviews)
        if len(review_ids) != len(set(review_ids)):
            raise ValueError("generated case reviews must be unique")
        unknown = sorted(set(review_ids).difference(case_ids))
        if unknown:
            raise ValueError(
                f"generated case reviews reference unknown cases: {', '.join(unknown)}"
            )
        if self.complete and self.incomplete_reason is not None:
            raise ValueError("complete generation batches cannot have an incomplete reason")
        if not self.complete and self.incomplete_reason is None:
            raise ValueError("incomplete generation batches require a reason")
        return self

GeneratedCaseRecord

Bases: BaseModel

Source code in src/autobench/data/generation.py
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
class GeneratedCaseRecord(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    case: Case
    review_status: ReviewStatus
    rejection_reason: str | None = None
    content_hash: str = Field(pattern=r"^[0-9a-f]{64}$")

    @model_validator(mode="after")
    def validate_review(self) -> GeneratedCaseRecord:
        if self.review_status is ReviewStatus.REJECTED and self.rejection_reason is None:
            raise ValueError("rejected generated case records require a rejection reason")
        if self.review_status is not ReviewStatus.REJECTED and self.rejection_reason is not None:
            raise ValueError("only rejected generated case records may have a rejection reason")
        if generated_case_content_hash(self.case) != self.content_hash:
            raise ValueError("generated case record content hash does not match its case")
        return self

GeneratedCaseReview

Bases: BaseModel

Source code in src/autobench/data/generation.py
55
56
57
58
59
60
61
62
63
64
65
66
67
68
class GeneratedCaseReview(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    case_id: str = Field(min_length=1)
    status: ReviewStatus = ReviewStatus.CANDIDATE
    rejection_reason: str | None = Field(default=None, min_length=1)

    @model_validator(mode="after")
    def validate_rejection(self) -> GeneratedCaseReview:
        if self.status is ReviewStatus.REJECTED and self.rejection_reason is None:
            raise ValueError("rejected generated cases require a rejection reason")
        if self.status is not ReviewStatus.REJECTED and self.rejection_reason is not None:
            raise ValueError("only rejected generated cases may have a rejection reason")
        return self

GenerationCost

Bases: BaseModel

Source code in src/autobench/data/generation.py
48
49
50
51
52
class GenerationCost(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid", allow_inf_nan=False)

    amount: float = Field(ge=0)
    currency: str = Field(default="usd", min_length=1)

GenerationDeterminism

Bases: StrEnum

Source code in src/autobench/data/generation.py
32
33
34
35
class GenerationDeterminism(StrEnum):
    GUARANTEED = "guaranteed"
    NOT_GUARANTEED = "not_guaranteed"
    UNKNOWN = "unknown"

GenerationResult

Bases: BaseModel

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

    generator_id: str = Field(min_length=1)
    started_at: datetime
    completed_at: datetime
    request: CaseGeneratorInput
    request_hash: str = Field(pattern=r"^[0-9a-f]{64}$")
    batch: GeneratedCaseBatch
    generated_cases: tuple[GeneratedCaseRecord, ...]
    dataset: DatasetSpec | None = None
    dataset_hash: str | None = Field(default=None, pattern=r"^[0-9a-f]{64}$")

    @model_validator(mode="after")
    def validate_completion(self) -> GenerationResult:
        if self.completed_at < self.started_at:
            raise ValueError("generation completion cannot precede its start")
        if generation_request_hash(self.request) != self.request_hash:
            raise ValueError("generation request hash does not match its request")

        batch_case_ids = tuple(case.id for case in self.batch.cases)
        record_case_ids = tuple(record.case.id for record in self.generated_cases)
        if record_case_ids != batch_case_ids:
            raise ValueError("generated case records must match batch cases in order")
        if any(
            record.case != batch_case
            for record, batch_case in zip(self.generated_cases, self.batch.cases, strict=True)
        ):
            raise ValueError("generated case records must contain the batch case payloads")

        if self.batch.complete and (self.dataset is None or self.dataset_hash is None):
            raise ValueError("complete generation requires a frozen dataset")
        if not self.batch.complete and (self.dataset is not None or self.dataset_hash is not None):
            raise ValueError("incomplete generation cannot publish a benchmark dataset")
        if self.dataset is not None:
            included_cases = [
                record.case
                for record in self.generated_cases
                if record.review_status is not ReviewStatus.REJECTED
            ]
            if self.dataset.cases != included_cases:
                raise ValueError(
                    "generated dataset must contain every non-rejected case in generation order"
                )
            if dataset_content_hash(self.dataset) != self.dataset_hash:
                raise ValueError("generated dataset hash does not match its dataset")
        return self

GenerationUsage

Bases: BaseModel

Source code in src/autobench/data/generation.py
38
39
40
41
42
43
44
45
class GenerationUsage(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    input_tokens: int = Field(default=0, ge=0)
    output_tokens: int = Field(default=0, ge=0)
    cached_input_tokens: int = Field(default=0, ge=0)
    requests: int = Field(default=0, ge=0)
    metadata: dict[str, SerializedValue] = Field(default_factory=dict)

GenerationWriteResult

Bases: BaseModel

Source code in src/autobench/data/generation.py
192
193
194
195
196
197
class GenerationWriteResult(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    complete: bool
    dataset_path: Path | None = None
    manifest_path: Path

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
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
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,
        )

GenerationError

Bases: AutobenchError

Raised when generated dataset preparation cannot produce valid evidence.

Source code in src/autobench/errors.py
38
39
class GenerationError(AutobenchError):
    """Raised when generated dataset preparation cannot produce valid evidence."""

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

OTLPExportError

Bases: AutobenchError

Raised when immutable Autobench evidence cannot be exported through OTLP.

Source code in src/autobench/exporters/otlp.py
19
20
class OTLPExportError(AutobenchError):
    """Raised when immutable Autobench evidence cannot be exported through OTLP."""

OTLPExportResult

Bases: BaseModel

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

    experiment_id: str
    benchmark_id: str
    record_version: int
    run_count: int = Field(ge=0)
    trace_count: int = Field(ge=0)
    abp_span_count: int = Field(ge=0)
    exported_span_count: int = Field(ge=0)
    partial_run_count: int = Field(ge=0)
    partial_trace_count: int = Field(ge=0)
    endpoint: str

OTLPSettings

Bases: BaseModel

Vendor-neutral HTTP/protobuf exporter settings kept outside benchmark specs.

Source code in src/autobench/exporters/otlp.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class OTLPSettings(BaseModel):
    """Vendor-neutral HTTP/protobuf exporter settings kept outside benchmark specs."""

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

    endpoint: str | None = Field(default=None, min_length=1)
    headers: dict[str, str] = Field(default_factory=dict)
    timeout_seconds: float = Field(default=10, gt=0)
    certificate_file: Path | None = None
    service_name: str = Field(default="autobench", min_length=1)
    service_namespace: str | None = Field(default=None, min_length=1)
    resource_attributes: dict[str, OTLPResourceValue] = Field(default_factory=dict)
    include_captured_content: bool = False

    @field_validator("endpoint", "service_name", "service_namespace")
    @classmethod
    def validate_text(cls, value: str | None) -> str | None:
        if value is not None and not value.strip():
            raise ValueError("OTLP endpoint and service identifiers must not be blank")
        return value

    @field_validator("headers")
    @classmethod
    def validate_headers(cls, headers: dict[str, str]) -> dict[str, str]:
        if any(not key.strip() for key in headers):
            raise ValueError("OTLP header names must not be blank")
        return headers

    @field_validator("resource_attributes")
    @classmethod
    def validate_resource_attributes(
        cls,
        attributes: dict[str, OTLPResourceValue],
    ) -> dict[str, OTLPResourceValue]:
        for key in attributes:
            if not key.strip():
                raise ValueError("OTLP resource attribute names must not be blank")
        return attributes

AssetDiscoverySettings

Bases: BaseModel

Select automatically discovered asset representations and families.

Source code in src/autobench/instrumentation/config.py
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class AssetDiscoverySettings(BaseModel):
    """Select automatically discovered asset representations and families."""

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

    discover: bool = True
    representations: tuple[AssetRepresentation, ...] = (
        AssetRepresentation.DEFINITION,
        AssetRepresentation.EFFECTIVE,
    )
    include: tuple[str, ...] = ()

    @field_validator("representations")
    @classmethod
    def normalize_representations(
        cls,
        values: tuple[AssetRepresentation, ...],
    ) -> tuple[AssetRepresentation, ...]:
        return tuple(dict.fromkeys(values))

    @field_validator("include")
    @classmethod
    def normalize_includes(cls, values: tuple[str, ...]) -> tuple[str, ...]:
        normalized = tuple(sorted({value.strip() for value in values}))
        if any(not value for value in normalized):
            raise ValueError("asset kind names cannot be empty")
        return normalized

    def allows(self, kind: str, representation: AssetRepresentation) -> bool:
        return (
            self.discover
            and representation in self.representations
            and (not self.include or kind in self.include)
        )

AutoInstrumentation

Bases: InstrumentationSettings

Discover and install every compatible built-in instrumentor.

Source code in src/autobench/instrumentation/config.py
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
class AutoInstrumentation(InstrumentationSettings):
    """Discover and install every compatible built-in instrumentor."""

    kind: Literal["all"] = "all"
    exclude: tuple[InstrumentorName, ...] = ()
    strict: bool = False
    assets: AssetDiscoverySettings | None = Field(
        default=None,
        exclude_if=lambda value: value is None,
    )

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

CandidateSummary

Bases: BaseModel

Source code in src/autobench/instrumentation/pydantic_gepa/projection.py
47
48
49
50
51
52
53
54
55
56
57
58
class CandidateSummary(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    id: str
    fingerprint: str | None = None
    parent_ids: tuple[str, ...] = ()
    generation: int | None = Field(default=None, ge=0)
    iteration: int | None = Field(default=None, ge=0)
    status: CandidateStatus
    statuses: tuple[CandidateStatus, ...] = ()
    score: float | None = None
    component_versions: dict[str, str] = Field(default_factory=dict)

Compatibility

Bases: BaseModel

Source code in src/autobench/instrumentation/models.py
 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
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
29
30
31
32
33
34
class CompatibilityStatus(StrEnum):
    COMPATIBLE = "compatible"
    DEGRADED = "degraded"
    UNAVAILABLE = "unavailable"
    UNSUPPORTED = "unsupported"
    CONFLICT = "conflict"

CurrentSpan

Mutable view of the active Autobench span for an external backend.

Source code in src/autobench/instrumentation/manager.py
 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
class CurrentSpan:
    """Mutable view of the active Autobench span for an external backend."""

    def __init__(self, context: RunContext, span_id: str) -> None:
        self._context = context
        self._span_id = span_id

    @property
    def id(self) -> str:
        return self._span_id

    def is_recording(self) -> bool:
        record = self._context._span_by_id(self._span_id)
        return record is not None and record.ended_at is None and not self._context.finalized

    def get_attribute(self, name: str) -> Any | None:
        record = self._context._span_by_id(self._span_id)
        if record is None:
            return None
        return record.attributes.get(name)

    def set_attribute(self, name: str, value: Any) -> bool:
        record = self._context._span_by_id(self._span_id)
        if record is None or record.ended_at is not None or self._context.finalized:
            return False
        record.attributes[name] = value
        return True

    def set_usage(self, name: str, value: Any) -> bool:
        record = self._context._span_by_id(self._span_id)
        if record is None or record.ended_at is not None or self._context.finalized:
            return False
        record.usage[name] = value
        return True

    def set_output(self, value: Any) -> bool:
        record = self._context._span_by_id(self._span_id)
        if record is None or record.ended_at is not None or self._context.finalized:
            return False
        record.output = value
        return True

    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._span_id,
            tags=tags,
            source=ObservationSource.INSTRUMENTATION,
        )

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

    def link_to(
        self,
        target: CurrentSpan,
        *,
        relation: LinkRelation = LinkRelation.RUN_LINEAGE,
        attributes: dict[str, SerializedValue] | None = None,
    ) -> bool:
        if not self.is_recording() or target._context._span_by_id(target.id) is None:
            return False
        self._context._emitter_for_legacy_span(self._span_id).link(
            self._context._abp_span_id(self._span_id),
            relation,
            LinkTarget(
                trace_id=target._context._emitter.trace_id,
                span_id=target._context._abp_span_id(target.id),
            ),
            attributes=attributes,
        )
        return True

DatasetSummary

Bases: BaseModel

Source code in src/autobench/instrumentation/pydantic_gepa/projection.py
36
37
38
39
40
41
42
43
44
class DatasetSummary(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    train_count: int = Field(ge=0)
    validation_count: int = Field(ge=0)
    test_count: int = Field(ge=0)
    train_fingerprint: str | None = None
    validation_fingerprint: str | None = None
    test_fingerprint: str | None = None

EngineSummary

Bases: BaseModel

Source code in src/autobench/instrumentation/pydantic_gepa/projection.py
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
class EngineSummary(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    execution_id: str
    engine: str | None = None
    pipeline_id: str | None = None
    step_id: str | None = None
    branch_id: str | None = None
    status: PydanticGEPAStatus = "running"
    score: float | None = None
    evaluations_used: int | None = Field(default=None, ge=0)
    evaluations_limit: int | None = Field(default=None, ge=0)
    optimizer_cost_used: float | None = Field(default=None, ge=0)
    optimizer_cost_limit: float | None = Field(default=None, ge=0)
    evaluation_cost_used: float | None = Field(default=None, ge=0)
    total_cost_used: float | None = Field(default=None, ge=0)

HTTPXCaptureSettings

Bases: BaseModel

Privacy-first HTTP request and response capture settings.

Source code in src/autobench/instrumentation/config.py
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
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
145
146
147
148
149
class HTTPXInstrumentation(InstrumentationSettings):
    """Capture HTTPX calls at the public transport boundary."""

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

InstrumentAssetSpec

Bases: BaseModel

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

    kind: str = Field(min_length=1)
    local_id: str = Field(min_length=1)
    name: str | None = Field(default=None, min_length=1)
    source_locator: str | None = Field(default=None, min_length=1)
    representation: AssetRepresentation = AssetRepresentation.DEFINITION
    semantic_type: SemanticType | None = None
    scope: str | None = Field(default=None, min_length=1)
    owner_locator: str | None = Field(default=None, min_length=1)
    definition_locator: str | None = Field(default=None, min_length=1)
    aliases: tuple[str, ...] = ()
    metadata: dict[str, SerializedValue] = Field(default_factory=dict)
    sensitivity: AssetSensitivity = AssetSensitivity.INTERNAL
    many: bool = False
    value_path: str | None = None
    value_factory: Callable[[InstrumentCall], Any] | None = None
    extractor_target: str | None = Field(default=None, min_length=1)

    @model_validator(mode="after")
    def validate_extractor(self) -> InstrumentAssetSpec:
        extractor_count = sum(
            value is not None
            for value in (self.value_path, self.value_factory, self.extractor_target)
        )
        if extractor_count != 1:
            raise ValueError(
                "instrument assets require exactly one of value_path, value_factory, "
                "or extractor_target"
            )
        return self

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
25
26
class InstrumentationError(RuntimeError):
    """Raised when native instrumentation cannot be installed safely."""

InstrumentationHandle

Bases: AbstractContextManager['InstrumentationHandle']

Source code in src/autobench/instrumentation/models.py
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
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
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
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,
        )
        self.runtime._installed_ids.add(info.id)
        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]
        self.runtime._installed_ids.discard(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
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
class InstrumentationRuntime:
    def __init__(
        self,
        patches: PatchManager | None = None,
        *,
        registry: TrackingRegistry = track,
    ) -> None:
        self.patches = PatchManager() if patches is None else patches
        self.registry = registry
        self._installed_ids: set[str] = set()
        self._keyed_spans: dict[tuple[TraceId, str, str], _KeyedSpan] = {}
        self._keyed_span_lock = RLock()

    @property
    def installed_ids(self) -> tuple[str, ...]:
        return tuple(sorted(self._installed_ids))

    def is_installed(self, instrumentor_id: str) -> bool:
        return instrumentor_id in self._installed_ids

    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

    def span(
        self,
        info: InstrumentorInfo,
        operation: str,
        *,
        kind: str = "custom",
        input: Any = None,
        attributes: dict[str, Any] | None = None,
        usage: dict[str, Any] | None = None,
        tags: dict[str, Any] | None = None,
        target_version: str | None = None,
        suppression_keys: tuple[str, ...] = (),
        parent_span_id: str | None = None,
    ) -> Span | None:
        """Create an unentered span in the active benchmark run, when one exists."""

        active = get_context()
        if active is None or active.is_suppressed(info.id, *suppression_keys):
            return None

        from autobench.runtime.context import active_run_context

        run_context = active_run_context()
        if run_context is None:
            return None
        return run_context.span(
            operation,
            kind=kind,
            input=input,
            attributes=attributes,
            usage=usage,
            tags=tags,
            instrumentation_scope=self.scope(info, target_version=target_version),
            parent_span_id=parent_span_id,
        )

    def start_span(
        self,
        info: InstrumentorInfo,
        key: str,
        operation: str,
        *,
        parent_key: str | None = None,
        parent_span_id: str | None = None,
        kind: str = "custom",
        input: Any = None,
        attributes: dict[str, Any] | None = None,
        usage: dict[str, Any] | None = None,
        tags: dict[str, Any] | None = None,
        target_version: str | None = None,
        suppression_keys: tuple[str, ...] = (),
    ) -> CurrentSpan | None:
        """Start a detached span identified by an external lifecycle key."""

        if not key:
            raise ValueError("Span keys must not be empty.")
        if parent_key is not None and parent_span_id is not None:
            raise ValueError("Use parent_key or parent_span_id, not both.")
        active = get_context()
        if active is None or active.is_suppressed(info.id, *suppression_keys):
            return None

        from autobench.runtime.context import active_run_context

        run_context = active_run_context()
        if run_context is None:
            return None
        lookup = (active.trace_id, info.id, key)
        with self._keyed_span_lock:
            existing = self._keyed_spans.get(lookup)
            if existing is not None:
                self.diagnose(
                    info,
                    "keyed_span_duplicate_start",
                    f"span key '{key}' is already active",
                )
                return CurrentSpan(existing.context, existing.span.id)

            resolved_parent_id = parent_span_id
            if parent_key is not None:
                parent = self._keyed_spans.get((active.trace_id, info.id, parent_key))
                if parent is None or parent.span.record.ended_at is not None:
                    self.diagnose(
                        info,
                        "keyed_span_parent_missing",
                        f"parent span key '{parent_key}' is not active for '{key}'",
                    )
                    return None
                resolved_parent_id = parent.span.id

            span = run_context.span(
                operation,
                kind=kind,
                input=input,
                attributes=attributes,
                usage=usage,
                tags=tags,
                instrumentation_scope=self.scope(info, target_version=target_version),
                parent_span_id=resolved_parent_id,
            )
            span.start()
            self._keyed_spans[lookup] = _KeyedSpan(run_context, span)
            return CurrentSpan(run_context, span.id)

    def span_for_key(
        self,
        info: InstrumentorInfo,
        key: str,
        *,
        suppression_keys: tuple[str, ...] = (),
    ) -> CurrentSpan | None:
        active = get_context()
        if active is None or active.is_suppressed(info.id, *suppression_keys):
            return None
        lookup = (active.trace_id, info.id, key)
        with self._keyed_span_lock:
            keyed = self._keyed_spans.get(lookup)
            if keyed is None:
                return None
            if keyed.context.finalized or keyed.span.record.ended_at is not None:
                del self._keyed_spans[lookup]
                return None
            return CurrentSpan(keyed.context, keyed.span.id)

    def end_span(
        self,
        info: InstrumentorInfo,
        key: str,
        *,
        output: Any | _Unset = _Unset.VALUE,
        attributes: dict[str, Any] | None = None,
        usage: dict[str, Any] | None = None,
        error: BaseException | str | None = None,
        status: SpanStatus | None = None,
        reason: EndReason | None = None,
        partial: bool | None = None,
        suppression_keys: tuple[str, ...] = (),
    ) -> bool:
        """Finish one keyed span without changing the active context stack."""

        active = get_context()
        if active is None or active.is_suppressed(info.id, *suppression_keys):
            return False
        lookup = (active.trace_id, info.id, key)
        with self._keyed_span_lock:
            keyed = self._keyed_spans.pop(lookup, None)
        if keyed is None:
            self.diagnose(
                info,
                "keyed_span_missing_end",
                f"span key '{key}' is not active",
            )
            return False
        if keyed.context.finalized or keyed.span.record.ended_at is not None:
            self.diagnose(
                info,
                "keyed_span_duplicate_end",
                f"span key '{key}' has already ended",
            )
            return False
        if output is not _Unset.VALUE:
            keyed.span.set_output(output)
        for name, value in (attributes or {}).items():
            keyed.span.set_attribute(name, value)
        for name, value in (usage or {}).items():
            keyed.span.set_usage(name, value)
        if isinstance(error, str):
            keyed.context.error(error, span_id=keyed.span.id)
            keyed.span.finish(
                status=SpanStatus.ERROR,
                reason=EndReason.FAILED if reason is None else reason,
                partial=partial,
            )
        else:
            keyed.span.finish(error=error, status=status, reason=reason, partial=partial)
        return True

    def metric(
        self,
        info: InstrumentorInfo,
        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,
        suppression_keys: tuple[str, ...] = (),
        span_key: str | None = None,
        span_id: str | None = None,
    ) -> Observation | None:
        """Record an instrumentation observation in the active benchmark run."""

        active = get_context()
        if active is None or active.is_suppressed(info.id, *suppression_keys):
            return None

        from autobench.runtime.context import active_run_context

        run_context = active_run_context()
        if run_context is None:
            return None
        if span_key is not None and span_id is not None:
            raise ValueError("Use span_key or span_id, not both.")
        target_span_id = span_id
        if span_key is not None:
            target = self.span_for_key(info, span_key, suppression_keys=suppression_keys)
            if target is None:
                self.diagnose(
                    info,
                    "keyed_span_metric_target_missing",
                    f"span key '{span_key}' is not active",
                )
                return None
            target_span_id = target.id
        if target_span_id is None:
            target_span_id = run_context.active_span_id
        return run_context.metric(
            name,
            value,
            semantic_type=semantic_type,
            unit=unit,
            direction=direction,
            role=role,
            span_id=target_span_id,
            tags=tags,
            source=ObservationSource.INSTRUMENTATION,
        )

    def event(
        self,
        info: InstrumentorInfo,
        name: str,
        value: Any = True,
        *,
        semantic_type: SemanticType | None = None,
        tags: dict[str, Any] | None = None,
        span_key: str | None = None,
        span_id: str | None = None,
        suppression_keys: tuple[str, ...] = (),
    ) -> Observation | None:
        """Record an instrumentation event on the active or selected span."""

        active = get_context()
        if active is None or active.is_suppressed(info.id, *suppression_keys):
            return None

        from autobench.runtime.context import active_run_context

        run_context = active_run_context()
        if run_context is None:
            return None
        if span_key is not None and span_id is not None:
            raise ValueError("Use span_key or span_id, not both.")
        target_span_id = span_id
        if span_key is not None:
            target = self.span_for_key(info, span_key, suppression_keys=suppression_keys)
            if target is None:
                self.diagnose(
                    info,
                    "keyed_span_event_target_missing",
                    f"span key '{span_key}' is not active",
                )
                return None
            target_span_id = target.id
        if target_span_id is None:
            target_span_id = run_context.active_span_id
        return run_context.event(
            name,
            value,
            semantic_type=semantic_type,
            span_id=target_span_id,
            tags=tags,
            source=ObservationSource.INSTRUMENTATION,
        )

    def set_extension(
        self,
        info: InstrumentorInfo,
        name: str,
        value: JsonValue,
        *,
        suppression_keys: tuple[str, ...] = (),
    ) -> bool:
        active = get_context()
        if active is None or active.is_suppressed(info.id, *suppression_keys):
            return False

        from autobench.runtime.context import active_run_context

        run_context = active_run_context()
        if run_context is None:
            return False
        run_context.set_extension(name, value)
        return True

    def current_span(
        self,
        info: InstrumentorInfo,
        *,
        suppression_keys: tuple[str, ...] = (),
    ) -> CurrentSpan | None:
        """Return a mutable view of the active span owned by the benchmark run."""

        active = get_context()
        if active is None or active.is_suppressed(info.id, *suppression_keys):
            return None

        from autobench.runtime.context import active_run_context

        run_context = active_run_context()
        if run_context is None:
            return None
        span_id = run_context.active_span_id
        if span_id is None:
            return None
        return CurrentSpan(run_context, span_id)

    def asset(
        self,
        info: InstrumentorInfo,
        candidate: AssetCandidate,
        *,
        span_id: str | None = None,
        registry: TrackingRegistry | None = None,
    ) -> RegisteredAsset | None:
        """Register and attach one SDK-observed asset without affecting the host call."""

        active = get_context()
        if active is None or active.is_suppressed(info.id, "assets"):
            return None
        try:
            from autobench.runtime.context import active_run_context

            run_context = active_run_context()
            if run_context is None:
                return None
            active_registry = self.registry if registry is None else registry
            prepared = run_context.prepare_discovered_asset(candidate, span_id=span_id)
            registered = active_registry.register_candidate(prepared, span_id=span_id)
            run_context.attach_discovered_asset(registered)
            return registered
        except Exception as error:
            self.diagnose(
                info,
                "asset_discovery_failed",
                f"{candidate.source_locator}: {type(error).__name__}: {error}",
            )
            return None
span
span(
    info: InstrumentorInfo,
    operation: str,
    *,
    kind: str = "custom",
    input: Any = None,
    attributes: dict[str, Any] | None = None,
    usage: dict[str, Any] | None = None,
    tags: dict[str, Any] | None = None,
    target_version: str | None = None,
    suppression_keys: tuple[str, ...] = (),
    parent_span_id: str | None = None,
) -> Span | None

Create an unentered span in the active benchmark run, when one exists.

Source code in src/autobench/instrumentation/manager.py
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
def span(
    self,
    info: InstrumentorInfo,
    operation: str,
    *,
    kind: str = "custom",
    input: Any = None,
    attributes: dict[str, Any] | None = None,
    usage: dict[str, Any] | None = None,
    tags: dict[str, Any] | None = None,
    target_version: str | None = None,
    suppression_keys: tuple[str, ...] = (),
    parent_span_id: str | None = None,
) -> Span | None:
    """Create an unentered span in the active benchmark run, when one exists."""

    active = get_context()
    if active is None or active.is_suppressed(info.id, *suppression_keys):
        return None

    from autobench.runtime.context import active_run_context

    run_context = active_run_context()
    if run_context is None:
        return None
    return run_context.span(
        operation,
        kind=kind,
        input=input,
        attributes=attributes,
        usage=usage,
        tags=tags,
        instrumentation_scope=self.scope(info, target_version=target_version),
        parent_span_id=parent_span_id,
    )
start_span
start_span(
    info: InstrumentorInfo,
    key: str,
    operation: str,
    *,
    parent_key: str | None = None,
    parent_span_id: str | None = None,
    kind: str = "custom",
    input: Any = None,
    attributes: dict[str, Any] | None = None,
    usage: dict[str, Any] | None = None,
    tags: dict[str, Any] | None = None,
    target_version: str | None = None,
    suppression_keys: tuple[str, ...] = (),
) -> CurrentSpan | None

Start a detached span identified by an external lifecycle key.

Source code in src/autobench/instrumentation/manager.py
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
def start_span(
    self,
    info: InstrumentorInfo,
    key: str,
    operation: str,
    *,
    parent_key: str | None = None,
    parent_span_id: str | None = None,
    kind: str = "custom",
    input: Any = None,
    attributes: dict[str, Any] | None = None,
    usage: dict[str, Any] | None = None,
    tags: dict[str, Any] | None = None,
    target_version: str | None = None,
    suppression_keys: tuple[str, ...] = (),
) -> CurrentSpan | None:
    """Start a detached span identified by an external lifecycle key."""

    if not key:
        raise ValueError("Span keys must not be empty.")
    if parent_key is not None and parent_span_id is not None:
        raise ValueError("Use parent_key or parent_span_id, not both.")
    active = get_context()
    if active is None or active.is_suppressed(info.id, *suppression_keys):
        return None

    from autobench.runtime.context import active_run_context

    run_context = active_run_context()
    if run_context is None:
        return None
    lookup = (active.trace_id, info.id, key)
    with self._keyed_span_lock:
        existing = self._keyed_spans.get(lookup)
        if existing is not None:
            self.diagnose(
                info,
                "keyed_span_duplicate_start",
                f"span key '{key}' is already active",
            )
            return CurrentSpan(existing.context, existing.span.id)

        resolved_parent_id = parent_span_id
        if parent_key is not None:
            parent = self._keyed_spans.get((active.trace_id, info.id, parent_key))
            if parent is None or parent.span.record.ended_at is not None:
                self.diagnose(
                    info,
                    "keyed_span_parent_missing",
                    f"parent span key '{parent_key}' is not active for '{key}'",
                )
                return None
            resolved_parent_id = parent.span.id

        span = run_context.span(
            operation,
            kind=kind,
            input=input,
            attributes=attributes,
            usage=usage,
            tags=tags,
            instrumentation_scope=self.scope(info, target_version=target_version),
            parent_span_id=resolved_parent_id,
        )
        span.start()
        self._keyed_spans[lookup] = _KeyedSpan(run_context, span)
        return CurrentSpan(run_context, span.id)
end_span
end_span(
    info: InstrumentorInfo,
    key: str,
    *,
    output: Any | _Unset = _Unset.VALUE,
    attributes: dict[str, Any] | None = None,
    usage: dict[str, Any] | None = None,
    error: BaseException | str | None = None,
    status: SpanStatus | None = None,
    reason: EndReason | None = None,
    partial: bool | None = None,
    suppression_keys: tuple[str, ...] = (),
) -> bool

Finish one keyed span without changing the active context stack.

Source code in src/autobench/instrumentation/manager.py
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
def end_span(
    self,
    info: InstrumentorInfo,
    key: str,
    *,
    output: Any | _Unset = _Unset.VALUE,
    attributes: dict[str, Any] | None = None,
    usage: dict[str, Any] | None = None,
    error: BaseException | str | None = None,
    status: SpanStatus | None = None,
    reason: EndReason | None = None,
    partial: bool | None = None,
    suppression_keys: tuple[str, ...] = (),
) -> bool:
    """Finish one keyed span without changing the active context stack."""

    active = get_context()
    if active is None or active.is_suppressed(info.id, *suppression_keys):
        return False
    lookup = (active.trace_id, info.id, key)
    with self._keyed_span_lock:
        keyed = self._keyed_spans.pop(lookup, None)
    if keyed is None:
        self.diagnose(
            info,
            "keyed_span_missing_end",
            f"span key '{key}' is not active",
        )
        return False
    if keyed.context.finalized or keyed.span.record.ended_at is not None:
        self.diagnose(
            info,
            "keyed_span_duplicate_end",
            f"span key '{key}' has already ended",
        )
        return False
    if output is not _Unset.VALUE:
        keyed.span.set_output(output)
    for name, value in (attributes or {}).items():
        keyed.span.set_attribute(name, value)
    for name, value in (usage or {}).items():
        keyed.span.set_usage(name, value)
    if isinstance(error, str):
        keyed.context.error(error, span_id=keyed.span.id)
        keyed.span.finish(
            status=SpanStatus.ERROR,
            reason=EndReason.FAILED if reason is None else reason,
            partial=partial,
        )
    else:
        keyed.span.finish(error=error, status=status, reason=reason, partial=partial)
    return True
metric
metric(
    info: InstrumentorInfo,
    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,
    suppression_keys: tuple[str, ...] = (),
    span_key: str | None = None,
    span_id: str | None = None,
) -> Observation | None

Record an instrumentation observation in the active benchmark run.

Source code in src/autobench/instrumentation/manager.py
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
def metric(
    self,
    info: InstrumentorInfo,
    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,
    suppression_keys: tuple[str, ...] = (),
    span_key: str | None = None,
    span_id: str | None = None,
) -> Observation | None:
    """Record an instrumentation observation in the active benchmark run."""

    active = get_context()
    if active is None or active.is_suppressed(info.id, *suppression_keys):
        return None

    from autobench.runtime.context import active_run_context

    run_context = active_run_context()
    if run_context is None:
        return None
    if span_key is not None and span_id is not None:
        raise ValueError("Use span_key or span_id, not both.")
    target_span_id = span_id
    if span_key is not None:
        target = self.span_for_key(info, span_key, suppression_keys=suppression_keys)
        if target is None:
            self.diagnose(
                info,
                "keyed_span_metric_target_missing",
                f"span key '{span_key}' is not active",
            )
            return None
        target_span_id = target.id
    if target_span_id is None:
        target_span_id = run_context.active_span_id
    return run_context.metric(
        name,
        value,
        semantic_type=semantic_type,
        unit=unit,
        direction=direction,
        role=role,
        span_id=target_span_id,
        tags=tags,
        source=ObservationSource.INSTRUMENTATION,
    )
event
event(
    info: InstrumentorInfo,
    name: str,
    value: Any = True,
    *,
    semantic_type: SemanticType | None = None,
    tags: dict[str, Any] | None = None,
    span_key: str | None = None,
    span_id: str | None = None,
    suppression_keys: tuple[str, ...] = (),
) -> Observation | None

Record an instrumentation event on the active or selected span.

Source code in src/autobench/instrumentation/manager.py
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
def event(
    self,
    info: InstrumentorInfo,
    name: str,
    value: Any = True,
    *,
    semantic_type: SemanticType | None = None,
    tags: dict[str, Any] | None = None,
    span_key: str | None = None,
    span_id: str | None = None,
    suppression_keys: tuple[str, ...] = (),
) -> Observation | None:
    """Record an instrumentation event on the active or selected span."""

    active = get_context()
    if active is None or active.is_suppressed(info.id, *suppression_keys):
        return None

    from autobench.runtime.context import active_run_context

    run_context = active_run_context()
    if run_context is None:
        return None
    if span_key is not None and span_id is not None:
        raise ValueError("Use span_key or span_id, not both.")
    target_span_id = span_id
    if span_key is not None:
        target = self.span_for_key(info, span_key, suppression_keys=suppression_keys)
        if target is None:
            self.diagnose(
                info,
                "keyed_span_event_target_missing",
                f"span key '{span_key}' is not active",
            )
            return None
        target_span_id = target.id
    if target_span_id is None:
        target_span_id = run_context.active_span_id
    return run_context.event(
        name,
        value,
        semantic_type=semantic_type,
        span_id=target_span_id,
        tags=tags,
        source=ObservationSource.INSTRUMENTATION,
    )
current_span
current_span(
    info: InstrumentorInfo,
    *,
    suppression_keys: tuple[str, ...] = (),
) -> CurrentSpan | None

Return a mutable view of the active span owned by the benchmark run.

Source code in src/autobench/instrumentation/manager.py
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
def current_span(
    self,
    info: InstrumentorInfo,
    *,
    suppression_keys: tuple[str, ...] = (),
) -> CurrentSpan | None:
    """Return a mutable view of the active span owned by the benchmark run."""

    active = get_context()
    if active is None or active.is_suppressed(info.id, *suppression_keys):
        return None

    from autobench.runtime.context import active_run_context

    run_context = active_run_context()
    if run_context is None:
        return None
    span_id = run_context.active_span_id
    if span_id is None:
        return None
    return CurrentSpan(run_context, span_id)
asset
asset(
    info: InstrumentorInfo,
    candidate: AssetCandidate,
    *,
    span_id: str | None = None,
    registry: TrackingRegistry | None = None,
) -> RegisteredAsset | None

Register and attach one SDK-observed asset without affecting the host call.

Source code in src/autobench/instrumentation/manager.py
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
def asset(
    self,
    info: InstrumentorInfo,
    candidate: AssetCandidate,
    *,
    span_id: str | None = None,
    registry: TrackingRegistry | None = None,
) -> RegisteredAsset | None:
    """Register and attach one SDK-observed asset without affecting the host call."""

    active = get_context()
    if active is None or active.is_suppressed(info.id, "assets"):
        return None
    try:
        from autobench.runtime.context import active_run_context

        run_context = active_run_context()
        if run_context is None:
            return None
        active_registry = self.registry if registry is None else registry
        prepared = run_context.prepare_discovered_asset(candidate, span_id=span_id)
        registered = active_registry.register_candidate(prepared, span_id=span_id)
        run_context.attach_discovered_asset(registered)
        return registered
    except Exception as error:
        self.diagnose(
            info,
            "asset_discovery_failed",
            f"{candidate.source_locator}: {type(error).__name__}: {error}",
        )
        return None

InstrumentationSettings

Bases: BaseModel

Shared configuration for one native Autobench instrumentor.

Source code in src/autobench/instrumentation/config.py
46
47
48
49
50
51
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
146
147
148
149
150
151
152
153
154
@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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
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
137
138
139
140
141
142
143
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
37
38
39
40
41
42
43
44
45
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
    asset_discovery: bool = False
    asset_kinds: tuple[str, ...] = ()

InstrumentorInfo

Bases: BaseModel

Source code in src/autobench/instrumentation/models.py
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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
32
33
34
35
36
37
38
39
40
41
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

ObjectiveSummary

Bases: BaseModel

Source code in src/autobench/instrumentation/pydantic_gepa/projection.py
26
27
28
29
30
31
32
33
class ObjectiveSummary(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    name: str
    role: str
    direction: str | None = None
    semantic_type: str | None = None
    unit: str | None = None

OpenAIAgentsInstrumentation

Bases: InstrumentationSettings

Capture OpenAI Agents workflows through its native trace processor.

Source code in src/autobench/instrumentation/config.py
114
115
116
117
118
119
120
121
class OpenAIAgentsInstrumentation(InstrumentationSettings):
    """Capture OpenAI Agents workflows through its native trace processor."""

    kind: Literal["openai_agents"] = "openai_agents"
    assets: AssetDiscoverySettings | None = Field(
        default=None,
        exclude_if=lambda value: value is None,
    )

OpenAIInstrumentation

Bases: InstrumentationSettings

Capture official OpenAI Python client calls and streams.

Source code in src/autobench/instrumentation/config.py
104
105
106
107
108
109
110
111
class OpenAIInstrumentation(InstrumentationSettings):
    """Capture official OpenAI Python client calls and streams."""

    kind: Literal["openai"] = "openai"
    assets: AssetDiscoverySettings | None = Field(
        default=None,
        exclude_if=lambda value: value is None,
    )

OptimizationExecution

Bases: BaseModel

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

    execution_id: str
    run_id: str
    parent_execution_id: str | None = None
    backend: str | None = None
    engine: str | None = None
    composition: str | None = None
    pipeline_id: str | None = None
    step_id: str | None = None
    branch_id: str | None = None
    stage_id: str | None = None
    status: PydanticGEPAStatus = "running"
    objective: ObjectiveSummary | None = None
    datasets: DatasetSummary | None = None
    seed_candidate_id: str | None = None
    best_candidate_id: str | None = None
    final_candidate_id: str | None = None
    final_score: float | None = None
    evaluations_used: int = Field(default=0, ge=0)
    evaluations_limit: int | None = Field(default=None, ge=0)
    evaluations_remaining: int | None = Field(default=None, ge=0)
    optimizer_cost_used: float | None = Field(default=None, ge=0)
    optimizer_cost_limit: float | None = Field(default=None, ge=0)
    optimizer_cost_remaining: float | None = Field(default=None, ge=0)
    evaluation_cost_used: float | None = Field(default=None, ge=0)
    total_cost_used: float | None = Field(default=None, ge=0)
    candidates: tuple[CandidateSummary, ...] = ()
    engines: tuple[EngineSummary, ...] = ()
    selections: tuple[SelectionSummary, ...] = ()
    checkpoint_paths: tuple[str, ...] = ()
    stop_reason: str | None = None
    event_count: int = Field(default=0, ge=0)
    diagnostic_count: int = Field(default=0, ge=0)

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
83
84
85
86
87
88
89
90
class PydanticAIInstrumentation(InstrumentationSettings):
    """Capture Pydantic AI agent, model, tool, and validation activity."""

    kind: Literal["pydantic_ai"] = "pydantic_ai"
    assets: AssetDiscoverySettings | None = Field(
        default=None,
        exclude_if=lambda value: value is None,
    )

PydanticGEPA

Capture pydantic-gepa optimization evidence through its native event stream.

Source code in src/autobench/instrumentation/pydantic_gepa/instrumentor.py
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
class PydanticGEPA:
    """Capture pydantic-gepa optimization evidence through its native event stream."""

    def __init__(
        self,
        *,
        detail: Detail = "full",
        discovery: AssetDiscoverySettings | None = None,
    ) -> None:
        self._detail: Detail = detail
        self._discovery = discovery or AssetDiscoverySettings()
        self._info = InstrumentorInfo(
            id="autobench.pydantic_gepa",
            version=__version__,
            target_distribution="pydantic-gepa",
            supported_versions=">=0.1.0a0,<0.2",
            mechanism=CaptureMechanism.CALLBACK,
            layer=AbstractionLayer.FRAMEWORK,
            span_kinds=(
                "optimization",
                "workflow",
                "candidate",
                "evaluation",
                "reflection",
                "scorer",
            ),
            semantic_families=(
                "optimization",
                "evaluation",
                "candidate",
                "asset",
                "checkpoint",
            ),
            source_convention="pydantic-gepa",
            source_convention_version="1",
            capabilities=InstrumentorCapabilities(
                sync=True,
                async_=True,
                native_hooks=True,
                asset_discovery=True,
                asset_kinds=(
                    "prompt",
                    "tool",
                    "input_schema",
                    "output_schema",
                    "field_description",
                    "schema_description",
                    "optimization_component",
                ),
            ),
        )

    @property
    def info(self) -> InstrumentorInfo:
        return self._info

    def check(self) -> Compatibility:
        if find_spec("pydantic_gepa") is None:
            return Compatibility(
                status=CompatibilityStatus.UNAVAILABLE,
                diagnostics=(
                    "pydantic-gepa is unavailable; install Autobench with the "
                    "'pydantic-gepa' extra",
                ),
            )
        try:
            from pydantic_gepa.events import RunStarted, subscribe
        except ImportError as error:
            return Compatibility(
                status=CompatibilityStatus.UNAVAILABLE,
                diagnostics=(f"pydantic-gepa event API could not be imported: {error}",),
            )
        if not callable(subscribe) or RunStarted.model_fields["event_version"].default != "1":
            return Compatibility(
                status=CompatibilityStatus.UNSUPPORTED,
                diagnostics=("pydantic-gepa event contract v1 is required",),
            )
        try:
            target_version = version("pydantic-gepa")
        except PackageNotFoundError:
            target_version = None
        return Compatibility.compatible(target_version=target_version)

    def install(self, runtime: InstrumentationRuntime) -> InstrumentationHandle:
        from pydantic_gepa.events import subscribe

        from autobench.instrumentation.pydantic_gepa.adapter import EventAdapter
        from autobench.instrumentation.pydantic_gepa.assets import CandidateAssets

        target_version = version("pydantic-gepa")
        adapter = EventAdapter(
            runtime,
            self.info,
            CandidateAssets(
                runtime,
                self.info,
                self._discovery,
                target_version=target_version,
            ),
            detail=self._detail,
        )
        subscription = subscribe(adapter.observe, on_error="ignore")

        def close() -> None:
            subscription.close()
            adapter.close()

        return InstrumentationHandle(close, info=self.info)

PydanticGEPAEvidence

Bases: BaseModel

Source code in src/autobench/instrumentation/pydantic_gepa/projection.py
127
128
129
130
131
132
133
class PydanticGEPAEvidence(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    schema_version: Literal[1] = 1
    source_convention: Literal["pydantic-gepa"] = "pydantic-gepa"
    event_version: Literal["1"] = "1"
    executions: tuple[OptimizationExecution, ...] = ()

PydanticGEPAInstrumentation

Bases: InstrumentationSettings

Capture pydantic-gepa optimizer lifecycle, scores, budgets, and assets.

Source code in src/autobench/instrumentation/config.py
 93
 94
 95
 96
 97
 98
 99
100
101
class PydanticGEPAInstrumentation(InstrumentationSettings):
    """Capture pydantic-gepa optimizer lifecycle, scores, budgets, and assets."""

    kind: Literal["pydantic_gepa"] = "pydantic_gepa"
    detail: Literal["summary", "evaluations", "full"] = "full"
    assets: AssetDiscoverySettings | None = Field(
        default=None,
        exclude_if=lambda value: value is None,
    )

SelectionSummary

Bases: BaseModel

Source code in src/autobench/instrumentation/pydantic_gepa/projection.py
79
80
81
82
83
84
85
86
87
class SelectionSummary(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    method: str
    selected_execution_id: str
    contender_execution_ids: tuple[str, ...]
    contender_scores: tuple[float, ...]
    score: float
    reason: str | None = None

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
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
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"
    OPTIMIZATION_EVALUATIONS_USED: Final[str] = "optimization.evaluations.used"
    OPTIMIZATION_EVALUATIONS_LIMIT: Final[str] = "optimization.evaluations.limit"
    OPTIMIZATION_EVALUATIONS_REMAINING: Final[str] = "optimization.evaluations.remaining"
    OPTIMIZATION_EVALUATION_COST_USED: Final[str] = "optimization.evaluation_cost.used"
    OPTIMIZATION_OPTIMIZER_COST_USED: Final[str] = "optimization.optimizer_cost.used"
    OPTIMIZATION_OPTIMIZER_COST_LIMIT: Final[str] = "optimization.optimizer_cost.limit"
    OPTIMIZATION_OPTIMIZER_COST_REMAINING: Final[str] = "optimization.optimizer_cost.remaining"
    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"
    OUTPUT_SCHEMA_VERSION: Final[str] = "output_schema.version"
    CAPABILITY_VERSION: Final[str] = "capability.version"
    GUARDRAIL_VERSION: Final[str] = "guardrail.version"
    HANDOFF_VERSION: Final[str] = "handoff.version"
    POLICY_VERSION: Final[str] = "policy.version"
    TOOLSET_VERSION: Final[str] = "toolset.version"
    ASSET_RENDERING_VERSION: Final[str] = "asset.rendering.version"
    ASSET_EXTERNAL_VERSION: Final[str] = "asset.external.version"
    ASSET_DEPLOYMENT_LABEL: Final[str] = "asset.deployment.label"
    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
395
396
397
398
399
400
class SemanticAggregation(StrEnum):
    NONE = "none"
    SUM = "sum"
    MEAN = "mean"
    LATEST = "latest"
    ANY = "any"

SemanticCardinality

Bases: StrEnum

Source code in src/autobench/metrics/semantics.py
388
389
390
391
392
class SemanticCardinality(StrEnum):
    LOW = "low"
    MEDIUM = "medium"
    HIGH = "high"
    UNBOUNDED = "unbounded"

SemanticPrivacy

Bases: StrEnum

Source code in src/autobench/metrics/semantics.py
381
382
383
384
385
class SemanticPrivacy(StrEnum):
    PUBLIC = "public"
    INTERNAL = "internal"
    SENSITIVE = "sensitive"
    SECRET = "secret"

SemanticRegistry

Bases: BaseModel

Source code in src/autobench/metrics/semantics.py
 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
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
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
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
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.OPTIMIZATION_EVALUATIONS_USED: SemanticTypeInfo(
                id=Semantic.OPTIMIZATION_EVALUATIONS_USED,
                description="Cumulative evaluator calls consumed by an optimization scope.",
                unit="calls",
                value_shape="integer",
                stability=SemanticStability.EVOLVING,
                privacy=SemanticPrivacy.PUBLIC,
                cardinality=SemanticCardinality.LOW,
                aggregation=SemanticAggregation.LATEST,
            ),
            Semantic.OPTIMIZATION_EVALUATIONS_LIMIT: SemanticTypeInfo(
                id=Semantic.OPTIMIZATION_EVALUATIONS_LIMIT,
                description="Configured evaluator-call limit for an optimization scope.",
                unit="calls",
                value_shape="integer",
                stability=SemanticStability.EVOLVING,
                privacy=SemanticPrivacy.PUBLIC,
                cardinality=SemanticCardinality.LOW,
                aggregation=SemanticAggregation.LATEST,
            ),
            Semantic.OPTIMIZATION_EVALUATIONS_REMAINING: SemanticTypeInfo(
                id=Semantic.OPTIMIZATION_EVALUATIONS_REMAINING,
                description="Evaluator calls remaining in an optimization scope.",
                unit="calls",
                value_shape="integer",
                stability=SemanticStability.EVOLVING,
                privacy=SemanticPrivacy.PUBLIC,
                cardinality=SemanticCardinality.LOW,
                aggregation=SemanticAggregation.LATEST,
            ),
            Semantic.OPTIMIZATION_EVALUATION_COST_USED: SemanticTypeInfo(
                id=Semantic.OPTIMIZATION_EVALUATION_COST_USED,
                description="Cumulative evaluator or task-model cost consumed.",
                parent=Semantic.MONEY_COST,
                unit="usd",
                value_shape="number",
                stability=SemanticStability.EVOLVING,
                privacy=SemanticPrivacy.INTERNAL,
                cardinality=SemanticCardinality.LOW,
                aggregation=SemanticAggregation.LATEST,
            ),
            Semantic.OPTIMIZATION_OPTIMIZER_COST_USED: SemanticTypeInfo(
                id=Semantic.OPTIMIZATION_OPTIMIZER_COST_USED,
                description="Cumulative optimizer or proposer cost consumed.",
                unit="usd",
                value_shape="number",
                stability=SemanticStability.EVOLVING,
                privacy=SemanticPrivacy.INTERNAL,
                cardinality=SemanticCardinality.LOW,
                aggregation=SemanticAggregation.LATEST,
            ),
            Semantic.OPTIMIZATION_OPTIMIZER_COST_LIMIT: SemanticTypeInfo(
                id=Semantic.OPTIMIZATION_OPTIMIZER_COST_LIMIT,
                description="Configured optimizer or proposer cost limit.",
                unit="usd",
                value_shape="number",
                stability=SemanticStability.EVOLVING,
                privacy=SemanticPrivacy.INTERNAL,
                cardinality=SemanticCardinality.LOW,
                aggregation=SemanticAggregation.LATEST,
            ),
            Semantic.OPTIMIZATION_OPTIMIZER_COST_REMAINING: SemanticTypeInfo(
                id=Semantic.OPTIMIZATION_OPTIMIZER_COST_REMAINING,
                description="Optimizer or proposer cost remaining.",
                unit="usd",
                value_shape="number",
                stability=SemanticStability.EVOLVING,
                privacy=SemanticPrivacy.INTERNAL,
                cardinality=SemanticCardinality.LOW,
                aggregation=SemanticAggregation.LATEST,
            ),
            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.OUTPUT_SCHEMA_VERSION: SemanticTypeInfo(
                id=Semantic.OUTPUT_SCHEMA_VERSION,
                value_shape="string",
            ),
            Semantic.CAPABILITY_VERSION: SemanticTypeInfo(
                id=Semantic.CAPABILITY_VERSION,
                value_shape="string",
            ),
            Semantic.GUARDRAIL_VERSION: SemanticTypeInfo(
                id=Semantic.GUARDRAIL_VERSION,
                value_shape="string",
            ),
            Semantic.HANDOFF_VERSION: SemanticTypeInfo(
                id=Semantic.HANDOFF_VERSION,
                value_shape="string",
            ),
            Semantic.POLICY_VERSION: SemanticTypeInfo(
                id=Semantic.POLICY_VERSION,
                value_shape="string",
            ),
            Semantic.TOOLSET_VERSION: SemanticTypeInfo(
                id=Semantic.TOOLSET_VERSION,
                value_shape="string",
            ),
            Semantic.ASSET_RENDERING_VERSION: SemanticTypeInfo(
                id=Semantic.ASSET_RENDERING_VERSION,
                value_shape="string",
            ),
            Semantic.ASSET_EXTERNAL_VERSION: SemanticTypeInfo(
                id=Semantic.ASSET_EXTERNAL_VERSION,
                value_shape="string",
            ),
            Semantic.ASSET_DEPLOYMENT_LABEL: SemanticTypeInfo(
                id=Semantic.ASSET_DEPLOYMENT_LABEL,
                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
375
376
377
378
class SemanticStability(StrEnum):
    STABLE = "stable"
    EVOLVING = "evolving"
    EXPERIMENTAL = "experimental"

SemanticTypeInfo

Bases: BaseModel

Source code in src/autobench/metrics/semantics.py
403
404
405
406
407
408
409
410
411
412
413
414
415
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)

CapturePolicy

Bases: BaseModel

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

    default_level: CaptureLevel = CaptureLevel.METADATA
    asset_default_level: CaptureLevel = CaptureLevel.FULL
    use_semantic_defaults: bool = True
    semantic_overrides: dict[SemanticType, CaptureLevel] = Field(default_factory=dict)
    allow_semantics: tuple[str, ...] = ()
    deny_semantics: tuple[str, ...] = ()
    allow_paths: tuple[str, ...] = ()
    deny_paths: tuple[str, ...] = ()
    secret_names: frozenset[str] = frozenset(_SECRET_NAMES)
    max_inline_bytes: int = Field(default=16_384, ge=1)
    max_artifact_bytes: int = Field(default=4_194_304, ge=1)
    max_collection_items: int = Field(default=100, ge=1)
    max_string_length: int = Field(default=4_096, ge=1)
    max_depth: int = Field(default=8, ge=1)
    store_binary: bool = True
    retain_source_attributes: bool = False

    @model_validator(mode="after")
    def validate_paths(self) -> CapturePolicy:
        if any(
            not pattern.strip()
            for pattern in (
                self.allow_semantics + self.deny_semantics + self.allow_paths + self.deny_paths
            )
        ):
            raise ValueError("capture paths and semantics cannot be empty")
        return self

    @classmethod
    def none(cls, **changes: Any) -> CapturePolicy:
        changes.setdefault("asset_default_level", CaptureLevel.NONE)
        return cls(default_level=CaptureLevel.NONE, use_semantic_defaults=False, **changes)

    @classmethod
    def metadata(cls, **changes: Any) -> CapturePolicy:
        changes.setdefault("asset_default_level", CaptureLevel.METADATA)
        return cls(default_level=CaptureLevel.METADATA, use_semantic_defaults=False, **changes)

    @classmethod
    def hashed(cls, **changes: Any) -> CapturePolicy:
        changes.setdefault("asset_default_level", CaptureLevel.HASH)
        return cls(default_level=CaptureLevel.HASH, use_semantic_defaults=False, **changes)

    @classmethod
    def redacted(cls, **changes: Any) -> CapturePolicy:
        changes.setdefault("asset_default_level", CaptureLevel.REDACTED)
        return cls(default_level=CaptureLevel.REDACTED, use_semantic_defaults=False, **changes)

    @classmethod
    def full(cls, **changes: Any) -> CapturePolicy:
        changes.setdefault("asset_default_level", CaptureLevel.FULL)
        return cls(default_level=CaptureLevel.FULL, use_semantic_defaults=False, **changes)

    def level_for_asset(
        self,
        semantic_type: SemanticType | None,
        *,
        explicit: CaptureLevel | None = None,
    ) -> CaptureLevel:
        if explicit is not None:
            return explicit
        if semantic_type is not None:
            matches = tuple(
                (prefix, level)
                for prefix, level in self.semantic_overrides.items()
                if semantic_type == prefix or semantic_type.startswith(f"{prefix}.")
            )
            if matches:
                return max(matches, key=lambda match: len(match[0]))[1]
        return self.asset_default_level

    def level_for(
        self,
        semantic_type: SemanticType | None,
        value: Any,
        *,
        explicit: CaptureLevel | None = None,
    ) -> CaptureLevel:
        if explicit is not None:
            return explicit
        if semantic_type is not None:
            matches = tuple(
                (prefix, level)
                for prefix, level in self.semantic_overrides.items()
                if semantic_type == prefix or semantic_type.startswith(f"{prefix}.")
            )
            if matches:
                return max(matches, key=lambda match: len(match[0]))[1]
            if self.use_semantic_defaults and isinstance(value, bytes):
                return CaptureLevel.METADATA
            if self.use_semantic_defaults and (
                semantic_type == "environment" or semantic_type.startswith("environment.")
            ):
                return CaptureLevel.NONE
            if self.use_semantic_defaults and any(
                semantic_type == prefix or semantic_type.startswith(f"{prefix}.")
                for prefix in _HASH_SEMANTICS
            ):
                return CaptureLevel.HASH
        if self.use_semantic_defaults and isinstance(value, BaseException):
            return CaptureLevel.REDACTED
        return self.default_level

    def allows_semantic(self, semantic_type: SemanticType | None) -> tuple[bool, str]:
        def matches(pattern: str) -> bool:
            return semantic_type is not None and (
                fnmatchcase(semantic_type, pattern)
                or semantic_type == pattern
                or semantic_type.startswith(f"{pattern}.")
            )

        if any(matches(pattern) for pattern in self.deny_semantics):
            return False, "semantic_denied"
        if not self.allow_semantics or any(matches(pattern) for pattern in self.allow_semantics):
            return True, "allowed"
        return False, "semantic_not_allowed"

    def allows_path(self, path: tuple[str, ...]) -> tuple[bool, str]:
        dotted = ".".join(path)
        if any(fnmatchcase(dotted, pattern) for pattern in self.deny_paths):
            return False, "denied"
        if not self.allow_paths:
            return True, "allowed"
        for pattern in self.allow_paths:
            if (
                fnmatchcase(dotted, pattern)
                or pattern.startswith(f"{dotted}.")
                or dotted.startswith(f"{pattern}.")
            ):
                return True, "allowed"
        return False, "not_allowed"

    def is_secret(self, path: tuple[str, ...]) -> bool:
        if not path:
            return False
        name = path[-1].lower().replace("-", "_")
        return any(
            name == secret or name.startswith(f"{secret}_") or name.endswith(f"_{secret}")
            for secret in self.secret_names
        )

CaptureLevel

Bases: StrEnum

Source code in src/autobench/protocol/signals.py
44
45
46
47
48
49
class CaptureLevel(StrEnum):
    NONE = "none"
    METADATA = "metadata"
    HASH = "hash"
    REDACTED = "redacted"
    FULL = "full"

EndReason

Bases: StrEnum

Source code in src/autobench/protocol/signals.py
83
84
85
86
87
88
89
class EndReason(StrEnum):
    COMPLETED = "completed"
    FAILED = "failed"
    CANCELLED = "cancelled"
    DEFERRED = "deferred"
    TIMEOUT = "timeout"
    ABANDONED = "abandoned"

ArtifactError

Bases: AutobenchError

Raised when a file-backed artifact cannot be prepared safely.

Source code in src/autobench/records/artifacts.py
60
61
class ArtifactError(AutobenchError):
    """Raised when a file-backed artifact cannot be prepared safely."""

ArtifactOverflow

Bases: StrEnum

Source code in src/autobench/records/artifacts.py
25
26
27
class ArtifactOverflow(StrEnum):
    FAIL = "fail"
    TRUNCATE = "truncate"

ArtifactRef

Bases: BaseModel

Source code in src/autobench/records/artifacts.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class ArtifactRef(BaseModel):
    model_config = ConfigDict(frozen=True)

    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)
    source: ArtifactSource = ArtifactSource.VALUE
    state: ArtifactState = ArtifactState.COMPLETE
    sha256: str | None = Field(default=None, pattern=r"^[0-9a-f]{64}$")
    byte_count: int | None = Field(default=None, ge=0)
    filename: str | None = Field(default=None, min_length=1)
    symlink_followed: bool = False

    @model_validator(mode="after")
    def validate_payload_metadata(self) -> ArtifactRef:
        if (self.sha256 is None) != (self.byte_count is None):
            raise ValueError("artifact sha256 and byte_count must be provided together")
        if self.source is ArtifactSource.VALUE and self.state is not ArtifactState.COMPLETE:
            raise ValueError("in-memory artifacts must be complete")
        return self

ArtifactSink

Bases: Protocol

Source code in src/autobench/records/artifacts.py
 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
@runtime_checkable
class ArtifactSink(Protocol):
    def prepare_file(
        self,
        *,
        run_id: str,
        artifact_id: str,
        name: str,
        source: Path,
        media_type: str | None,
        max_bytes: int,
        overflow: ArtifactOverflow,
        symlinks: SymlinkPolicy,
        filename: str | None,
        span_id: str | None,
        tags: dict[str, Any],
    ) -> ArtifactRef: ...

    async def prepare_file_async(
        self,
        *,
        run_id: str,
        artifact_id: str,
        name: str,
        source: Path,
        media_type: str | None,
        max_bytes: int,
        overflow: ArtifactOverflow,
        symlinks: SymlinkPolicy,
        filename: str | None,
        span_id: str | None,
        tags: dict[str, Any],
    ) -> ArtifactRef: ...

    def prepare_stream(
        self,
        *,
        run_id: str,
        artifact_id: str,
        name: str,
        source: Iterable[bytes],
        media_type: str | None,
        max_bytes: int,
        overflow: ArtifactOverflow,
        filename: str | None,
        span_id: str | None,
        tags: dict[str, Any],
    ) -> ArtifactRef: ...

    async def prepare_stream_async(
        self,
        *,
        run_id: str,
        artifact_id: str,
        name: str,
        source: AsyncIterable[bytes],
        media_type: str | None,
        max_bytes: int,
        overflow: ArtifactOverflow,
        filename: str | None,
        span_id: str | None,
        tags: dict[str, Any],
    ) -> ArtifactRef: ...

    def prepared_artifact(self, *, run_id: str, artifact_id: str) -> ArtifactRef | None: ...

ArtifactSinkRequiredError

Bases: ArtifactError

Raised before a file or stream is consumed without durable recording.

Source code in src/autobench/records/artifacts.py
64
65
class ArtifactSinkRequiredError(ArtifactError):
    """Raised before a file or stream is consumed without durable recording."""

ArtifactSource

Bases: StrEnum

Source code in src/autobench/records/artifacts.py
13
14
15
16
class ArtifactSource(StrEnum):
    VALUE = "value"
    FILE = "file"
    STREAM = "stream"

ArtifactState

Bases: StrEnum

Source code in src/autobench/records/artifacts.py
19
20
21
22
class ArtifactState(StrEnum):
    COMPLETE = "complete"
    TRUNCATED = "truncated"
    PARTIAL = "partial"

ArtifactTransferError

Bases: ArtifactError

Source code in src/autobench/records/artifacts.py
68
69
70
71
class ArtifactTransferError(ArtifactError):
    def __init__(self, message: str, artifact: ArtifactRef) -> None:
        super().__init__(message)
        self.artifact = artifact

SymlinkPolicy

Bases: StrEnum

Source code in src/autobench/records/artifacts.py
30
31
32
class SymlinkPolicy(StrEnum):
    FOLLOW = "follow"
    REJECT = "reject"

ExperimentFile

Bases: BaseModel

Source code in src/autobench/records/files.py
37
38
39
40
41
42
43
44
45
46
47
48
class ExperimentFile(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    path: str = Field(min_length=1)
    content: bytes
    kind: RecordFileKind = RecordFileKind.OTHER
    identity: str = Field(min_length=1)

    @field_validator("path")
    @classmethod
    def validate_path(cls, path: str) -> str:
        return normalize_logical_path(path)

LogicalRecordTarget

Bases: BaseModel

Source code in src/autobench/records/files.py
29
30
31
32
33
34
class LogicalRecordTarget(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    path: str = Field(min_length=1)
    kind: RecordFileKind
    identity: str = Field(min_length=1)

ManifestEntry

Bases: BaseModel

Source code in src/autobench/records/files.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
class ManifestEntry(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    path: str = Field(min_length=1)
    sha256: str = Field(pattern=r"^[0-9a-f]{64}$")
    byte_count: int = Field(ge=0)
    kind: RecordFileKind
    identity: str = Field(min_length=1)

    @field_validator("path")
    @classmethod
    def validate_path(cls, value: str) -> str:
        try:
            return normalize_logical_path(value)
        except RecordingError as exc:
            raise ValueError(str(exc)) from exc

RecordFileKind

Bases: StrEnum

Source code in src/autobench/records/files.py
18
19
20
21
22
23
24
25
26
class RecordFileKind(StrEnum):
    EXPERIMENT = "experiment"
    SUMMARY = "summary"
    RUN = "run"
    TRACE = "trace"
    ARTIFACT = "artifact"
    ASSET = "asset"
    SOURCE = "source"
    OTHER = "other"

RecordManifest

Bases: BaseModel

Source code in src/autobench/records/files.py
69
70
71
72
73
74
class RecordManifest(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    version: Literal[1] = 1
    experiment_id: str = Field(min_length=1)
    files: tuple[ManifestEntry, ...]

ExperimentRecord

Bases: BaseModel

Source code in src/autobench/records/models.py
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
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
    termination: ExperimentTermination = Field(default_factory=ExperimentTermination)
    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, ...] = ()
    manifest_path: str | None = None
    run_paths: tuple[str, ...] = ()
    run_count: int
    passed_count: int
    failed_count: int
    errored_count: int
    skipped_count: int
    cancelled_count: int = 0
    correlation: ExecutionCorrelation | None = None

RecordedRunPayloads

Bases: BaseModel

Source code in src/autobench/records/models.py
138
139
140
141
142
143
class RecordedRunPayloads(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    artifacts: tuple[ArtifactRef, ...] = ()
    trace: Trace | None = None
    trace_artifact: ArtifactRef | None = None

RecordingError

Bases: AutobenchError

Raised when an experiment cannot be recorded safely.

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

RecordLineage

Bases: BaseModel

Source code in src/autobench/records/models.py
44
45
46
47
48
49
50
51
52
53
54
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/models.py
39
40
41
class ReplayKind(StrEnum):
    EXTRACTION = "extraction"
    CANONICALIZATION = "canonicalization"

RunRecord

Bases: BaseModel

Source code in src/autobench/records/models.py
 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
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
    partial: bool = False
    end_reason: EndReason = EndReason.COMPLETED
    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, ...] = ()
    asset_uses: tuple[AssetUse, ...] = ()
    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
    correlation: ExecutionCorrelation | 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"] = (
                EvaluationStatus.NOT_EVALUATED
                if payload["status"] == RunStatus.CANCELLED
                else payload["status"]
            )
        if "case" not in payload and "case_id" in payload:
            payload["case"] = {"id": payload["case_id"]}
        raw_status = payload.get("status")
        try:
            status = RunStatus(raw_status) if isinstance(raw_status, str) else None
        except ValueError:
            status = None
        if "partial" not in payload:
            payload["partial"] = status == RunStatus.CANCELLED
        if "end_reason" not in payload:
            if status is RunStatus.CANCELLED:
                payload["end_reason"] = EndReason.CANCELLED
            elif status in {RunStatus.FAILED, RunStatus.ERRORED}:
                payload["end_reason"] = EndReason.FAILED
            elif status is RunStatus.SKIPPED:
                payload["end_reason"] = EndReason.DEFERRED
            else:
                payload["end_reason"] = EndReason.COMPLETED
        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
36
37
class ReplayError(AutobenchError):
    """Raised when immutable evidence cannot be replayed."""

ExecutionSnapshot

Bases: BaseModel

Source code in src/autobench/records/staging.py
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
class ExecutionSnapshot(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    run: RunResult
    captured_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
    signal_sequence_watermark: int = Field(default=0, ge=0)

    @classmethod
    def from_result(cls, run: RunResult) -> ExecutionSnapshot:
        copied = run.model_copy(deep=True)
        watermark = (
            max(
                (signal.sequence for signal in copied.trace.signals),
                default=0,
            )
            if copied.trace is not None
            else 0
        )
        return cls(run=copied, signal_sequence_watermark=watermark)

ExperimentStart

Bases: BaseModel

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

    version: Literal[1] = STAGING_VERSION
    experiment_id: str = Field(min_length=1)
    benchmark_id: str = Field(min_length=1)
    started_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
    plan: BenchmarkPlan
    runs: tuple[MatrixRunSpec, ...]
    environment: EnvironmentMetadata
    semantic_registry: SemanticRegistry
    report_spec_data: dict[str, Any] | None = None
    spec_snapshot: dict[str, Any] | None = None
    spec_hash: str | None = None
    file_hashes: tuple[ResolvedFileHash, ...] = ()
    requires_cross_run_derivation: bool = False
    requires_policies: bool = False
    correlation: ExecutionCorrelation | None = None

    @model_validator(mode="after")
    def validate_plan(self) -> ExperimentStart:
        run_ids = tuple(run.run_id for run in self.runs)
        if len(run_ids) != len(set(run_ids)):
            raise ValueError("planned run ids must be unique")
        if self.plan.planned_run_count != len(run_ids):
            raise ValueError("plan count must match the planned runs")
        if any(run.experiment_id != self.experiment_id for run in self.runs):
            raise ValueError("planned runs must belong to the experiment")
        if any(run.benchmark_id != self.benchmark_id for run in self.runs):
            raise ValueError("planned runs must belong to the benchmark")
        if any(run.correlation != self.correlation for run in self.runs):
            raise ValueError("planned run correlation must match the experiment correlation")
        return self

FileRecorder

Source code in src/autobench/records/staging.py
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
class FileRecorder:
    def __init__(
        self,
        output_dir: Path,
        *,
        source_files: Collection[Path] = (),
        path_root: Path | None = None,
        durability: RecordDurability = "atomic",
        trace_inline_limit_bytes: int = TRACE_INLINE_LIMIT_BYTES,
        asset_registry: TrackingRegistry = track,
        experiment_publishers: Sequence[ExperimentPublisher] = (),
    ) -> None:
        if trace_inline_limit_bytes < 1:
            raise ValueError("trace_inline_limit_bytes must be at least 1")
        self.output_dir = output_dir
        self.staging_dir = output_dir.with_name(f".{output_dir.name}.staging")
        self.source_files = tuple(source_files)
        self.path_root = path_root
        self.durability: RecordDurability = durability
        self.trace_inline_limit_bytes = trace_inline_limit_bytes
        self.asset_registry = asset_registry
        self.experiment_publishers = tuple(experiment_publishers)

    async def open(self, start: ExperimentStart) -> FileRecordSession:
        return await asyncio.to_thread(self.open_sync, start)

    def open_sync(self, start: ExperimentStart) -> FileRecordSession:
        if self.output_dir.is_symlink() or (
            self.output_dir.exists()
            and (not self.output_dir.is_dir() or any(self.output_dir.iterdir()))
        ):
            raise RecordingError(f"Record target already exists: {self.output_dir}")
        if self.staging_dir.exists() or self.staging_dir.is_symlink():
            raise RecordingError(
                f"Staging target already exists; inspect or recover it first: {self.staging_dir}"
            )
        active_start = start.model_copy(
            update={
                "file_hashes": source_file_hashes(
                    self.source_files,
                    path_root=self.path_root,
                )
            }
        )
        validate_logical_targets(
            tuple(
                LogicalRecordTarget(
                    path=(
                        f"cases/{path_component(run.case.id)}/"
                        f"{path_component(run.variant.id)}/run.yaml"
                    ),
                    kind=RecordFileKind.RUN,
                    identity=run.run_id,
                )
                for run in active_start.runs
            )
        )
        self.staging_dir.mkdir(parents=True)
        try:
            state = StagingState(experiment_id=active_start.experiment_id)
            manifest = StagingManifest(experiment_id=active_start.experiment_id)
            atomic_write_text(
                self.staging_dir / STAGING_STATE_PATH,
                dump_yaml(
                    experiment_start_to_yaml_view(active_start, state),
                    schema_name="staging",
                ),
                durability=self.durability,
            )
            atomic_write_text(
                self.staging_dir / STAGING_MANIFEST_PATH,
                dump_yaml(staging_manifest_to_yaml_view(manifest), schema_name="staging_manifest"),
                durability=self.durability,
            )
        except BaseException:
            shutil.rmtree(self.staging_dir, ignore_errors=True)
            raise
        return FileRecordSession(
            recorder=self,
            start=active_start,
            state=state,
            manifest=manifest,
        )

FileRecordSession

Source code in src/autobench/records/staging.py
 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
class FileRecordSession:
    def __init__(
        self,
        *,
        recorder: FileRecorder,
        start: ExperimentStart,
        state: StagingState,
        manifest: StagingManifest,
    ) -> None:
        self.recorder = recorder
        self.start = start
        self.state = state
        self.manifest = manifest
        self.state_lock = asyncio.Lock()
        self.run_locks = {run.run_id: asyncio.Lock() for run in start.runs}
        self.prepared_artifacts: dict[tuple[str, str], tuple[ArtifactRef, Path]] = {}
        self.prepared_artifacts_lock = RLock()
        self.operations: set[asyncio.Task[Any]] = set()
        self.artifact_transfers: set[asyncio.Task[ArtifactRef]] = set()
        self.closed = False
        self.finished = False

    @property
    def artifact_sink(self) -> FileRecordSession:
        return self

    def _start_operation(
        self,
        operation: Coroutine[Any, Any, OperationResultT],
    ) -> asyncio.Task[OperationResultT]:
        task = asyncio.create_task(operation)
        self.operations.add(task)
        task.add_done_callback(self.operations.discard)
        return task

    async def _execute_operation(
        self,
        operation: Coroutine[Any, Any, OperationResultT],
        *,
        description: str,
    ) -> OperationResultT:
        task = self._start_operation(operation)
        try:
            return await asyncio.shield(task)
        except asyncio.CancelledError as cancellation:
            error = await settle_task(
                task,
                timeout_seconds=_SESSION_OPERATION_SETTLE_SECONDS,
                cancel_on_timeout=False,
                description=description,
            )
            if error is not None:
                cancellation.add_note(f"{description.lower()} did not settle: {error}")
            raise

    async def _settle_operations(self) -> None:
        while self.operations:
            active = tuple(self.operations)
            await asyncio.gather(
                *(asyncio.shield(task) for task in active),
                return_exceptions=True,
            )

    async def _settle_artifact_transfers(self) -> None:
        while self.artifact_transfers:
            active = tuple(self.artifact_transfers)
            await asyncio.gather(
                *(asyncio.shield(task) for task in active),
                return_exceptions=True,
            )

    def prepare_file(
        self,
        *,
        run_id: str,
        artifact_id: str,
        name: str,
        source: Path,
        media_type: str | None,
        max_bytes: int,
        overflow: ArtifactOverflow,
        symlinks: SymlinkPolicy,
        filename: str | None,
        span_id: str | None,
        tags: dict[str, Any],
    ) -> ArtifactRef:
        self.require_open()
        self._require_run(run_id)
        self._require_unprepared(run_id, artifact_id)
        followed = source.is_symlink()
        if followed and symlinks is SymlinkPolicy.REJECT:
            raise RecordingError(
                f"Artifact source is a symlink and symlinks are rejected: {source.name}"
            )
        try:
            resolved = source.resolve(strict=True)
        except OSError as exc:
            raise RecordingError(
                f"Artifact source does not exist or cannot be read: {source.name}"
            ) from exc
        if resolved.is_dir():
            raise RecordingError("Artifact sources must be files; directories are not supported.")
        if not resolved.is_file():
            raise RecordingError(f"Artifact source is not a regular file: {source.name}")
        active_filename = self._artifact_filename(filename or source.name)
        with resolved.open("rb") as stream:
            return self._prepare_sync_chunks(
                run_id=run_id,
                artifact_id=artifact_id,
                name=name,
                source=iter(lambda: stream.read(1024 * 1024), b""),
                media_type=media_type,
                max_bytes=max_bytes,
                overflow=overflow,
                filename=active_filename,
                span_id=span_id,
                tags=tags,
                artifact_source=ArtifactSource.FILE,
                symlink_followed=followed,
                close_source=False,
            )

    async def prepare_file_async(
        self,
        *,
        run_id: str,
        artifact_id: str,
        name: str,
        source: Path,
        media_type: str | None,
        max_bytes: int,
        overflow: ArtifactOverflow,
        symlinks: SymlinkPolicy,
        filename: str | None,
        span_id: str | None,
        tags: dict[str, Any],
    ) -> ArtifactRef:
        self.require_open()
        transfer = asyncio.create_task(
            asyncio.to_thread(
                self.prepare_file,
                run_id=run_id,
                artifact_id=artifact_id,
                name=name,
                source=source,
                media_type=media_type,
                max_bytes=max_bytes,
                overflow=overflow,
                symlinks=symlinks,
                filename=filename,
                span_id=span_id,
                tags=tags,
            )
        )
        self.artifact_transfers.add(transfer)

        def observe(completed: asyncio.Task[ArtifactRef]) -> None:
            self.artifact_transfers.discard(completed)
            if not completed.cancelled():
                completed.exception()

        transfer.add_done_callback(observe)
        return await asyncio.shield(transfer)

    def prepare_stream(
        self,
        *,
        run_id: str,
        artifact_id: str,
        name: str,
        source: Iterable[bytes],
        media_type: str | None,
        max_bytes: int,
        overflow: ArtifactOverflow,
        filename: str | None,
        span_id: str | None,
        tags: dict[str, Any],
    ) -> ArtifactRef:
        self.require_open()
        self._require_run(run_id)
        self._require_unprepared(run_id, artifact_id)
        return self._prepare_sync_chunks(
            run_id=run_id,
            artifact_id=artifact_id,
            name=name,
            source=source,
            media_type=media_type,
            max_bytes=max_bytes,
            overflow=overflow,
            filename=None if filename is None else self._artifact_filename(filename),
            span_id=span_id,
            tags=tags,
            artifact_source=ArtifactSource.STREAM,
            symlink_followed=False,
            close_source=True,
        )

    async def prepare_stream_async(
        self,
        *,
        run_id: str,
        artifact_id: str,
        name: str,
        source: AsyncIterable[bytes],
        media_type: str | None,
        max_bytes: int,
        overflow: ArtifactOverflow,
        filename: str | None,
        span_id: str | None,
        tags: dict[str, Any],
    ) -> ArtifactRef:
        self.require_open()
        self._require_run(run_id)
        self._require_unprepared(run_id, artifact_id)
        active_filename = None if filename is None else self._artifact_filename(filename)
        prototype = ArtifactRef(
            id=artifact_id,
            name=name,
            media_type=media_type,
            span_id=span_id,
            tags=tags,
            source=ArtifactSource.STREAM,
            filename=active_filename,
        )
        target = artifact_payload_path(
            self.recorder.staging_dir / "artifacts",
            run_id=run_id,
            artifact=prototype,
        )
        temporary, stream = self._open_prepared_target(target)
        digest = hashlib.sha256()
        byte_count = 0
        state = ArtifactState.COMPLETE
        failure: BaseException | None = None
        iterator: AsyncIterator[bytes] = aiter(source)
        try:
            async for chunk in iterator:
                chunk = self._artifact_chunk(chunk)
                remaining = max_bytes - byte_count
                if len(chunk) <= remaining:
                    stream.write(chunk)
                    digest.update(chunk)
                    byte_count += len(chunk)
                    continue
                if remaining:
                    prefix = chunk[:remaining]
                    stream.write(prefix)
                    digest.update(prefix)
                    byte_count += len(prefix)
                state = (
                    ArtifactState.TRUNCATED
                    if overflow is ArtifactOverflow.TRUNCATE
                    else ArtifactState.PARTIAL
                )
                if overflow is ArtifactOverflow.FAIL:
                    failure = ArtifactTransferError(
                        f"Artifact {name!r} exceeded max_bytes={max_bytes}.",
                        prototype,
                    )
                break
        except BaseException as exc:
            state = ArtifactState.PARTIAL
            failure = exc
        finally:
            try:
                if isinstance(iterator, _AsyncClosable):
                    await iterator.aclose()
                if source is not iterator and isinstance(source, _AsyncClosable):
                    await source.aclose()
            except BaseException as close_error:
                state = ArtifactState.PARTIAL
                if failure is None:
                    failure = close_error
            self._commit_prepared_stream(stream, temporary, target)
        artifact = prototype.model_copy(
            update={
                "state": state,
                "sha256": digest.hexdigest(),
                "byte_count": byte_count,
            }
        )
        self._retain_prepared(run_id, artifact, target)
        if failure is not None:
            if isinstance(failure, ArtifactTransferError):
                raise ArtifactTransferError(str(failure), artifact) from failure.__cause__
            raise failure
        return artifact

    def prepared_artifact(self, *, run_id: str, artifact_id: str) -> ArtifactRef | None:
        with self.prepared_artifacts_lock:
            prepared = self.prepared_artifacts.get((run_id, artifact_id))
            return None if prepared is None else prepared[0]

    def _prepare_sync_chunks(
        self,
        *,
        run_id: str,
        artifact_id: str,
        name: str,
        source: Iterable[bytes],
        media_type: str | None,
        max_bytes: int,
        overflow: ArtifactOverflow,
        filename: str | None,
        span_id: str | None,
        tags: dict[str, Any],
        artifact_source: ArtifactSource,
        symlink_followed: bool,
        close_source: bool,
    ) -> ArtifactRef:
        prototype = ArtifactRef(
            id=artifact_id,
            name=name,
            media_type=media_type,
            span_id=span_id,
            tags=tags,
            source=artifact_source,
            filename=filename,
            symlink_followed=symlink_followed,
        )
        target = artifact_payload_path(
            self.recorder.staging_dir / "artifacts",
            run_id=run_id,
            artifact=prototype,
        )
        temporary, stream = self._open_prepared_target(target)
        digest = hashlib.sha256()
        byte_count = 0
        state = ArtifactState.COMPLETE
        failure: BaseException | None = None
        iterator: Iterator[bytes] = iter(source)
        try:
            for chunk in iterator:
                chunk = self._artifact_chunk(chunk)
                remaining = max_bytes - byte_count
                if len(chunk) <= remaining:
                    stream.write(chunk)
                    digest.update(chunk)
                    byte_count += len(chunk)
                    continue
                if remaining:
                    prefix = chunk[:remaining]
                    stream.write(prefix)
                    digest.update(prefix)
                    byte_count += len(prefix)
                state = (
                    ArtifactState.TRUNCATED
                    if overflow is ArtifactOverflow.TRUNCATE
                    else ArtifactState.PARTIAL
                )
                if overflow is ArtifactOverflow.FAIL:
                    failure = ArtifactTransferError(
                        f"Artifact {name!r} exceeded max_bytes={max_bytes}.",
                        prototype,
                    )
                break
        except BaseException as exc:
            state = ArtifactState.PARTIAL
            failure = exc
        finally:
            try:
                if close_source and isinstance(iterator, _Closable):
                    iterator.close()
                if close_source and source is not iterator and isinstance(source, _Closable):
                    source.close()
            except BaseException as close_error:
                state = ArtifactState.PARTIAL
                if failure is None:
                    failure = close_error
            self._commit_prepared_stream(stream, temporary, target)
        artifact = prototype.model_copy(
            update={
                "state": state,
                "sha256": digest.hexdigest(),
                "byte_count": byte_count,
            }
        )
        self._retain_prepared(run_id, artifact, target)
        if failure is not None:
            if isinstance(failure, ArtifactTransferError):
                raise ArtifactTransferError(str(failure), artifact) from failure.__cause__
            raise failure
        return artifact

    def _open_prepared_target(self, target: Path) -> tuple[Path, BinaryIO]:
        if target.exists() or target.is_symlink():
            raise RecordingError(f"Prepared artifact already exists: {target.name}")
        target.parent.mkdir(parents=True, exist_ok=True)
        descriptor, temporary_name = tempfile.mkstemp(
            prefix=f".{target.name}.",
            suffix=".tmp",
            dir=target.parent,
        )
        return Path(temporary_name), os.fdopen(descriptor, "wb")

    def _commit_prepared_stream(self, stream: BinaryIO, temporary: Path, target: Path) -> None:
        try:
            stream.flush()
            if self.recorder.durability == "synced":
                os.fsync(stream.fileno())
            stream.close()
            os.replace(temporary, target)
            if self.recorder.durability == "synced":
                sync_directory(target.parent)
        except BaseException:
            stream.close()
            temporary.unlink(missing_ok=True)
            raise

    def _retain_prepared(self, run_id: str, artifact: ArtifactRef, path: Path) -> None:
        with self.prepared_artifacts_lock:
            self.prepared_artifacts[(run_id, artifact.id)] = (artifact, path)

    def _require_unprepared(self, run_id: str, artifact_id: str) -> None:
        with self.prepared_artifacts_lock:
            if (run_id, artifact_id) in self.prepared_artifacts:
                raise RecordingError(f"Prepared artifact already exists: {run_id}:{artifact_id}")

    def _require_run(self, run_id: str) -> None:
        if run_id not in self.run_locks:
            raise RecordingError(f"Run is not part of the experiment plan: {run_id}")

    @staticmethod
    def _artifact_filename(filename: str) -> str:
        if filename in {".", ".."} or "/" in filename or "\\" in filename:
            raise RecordingError(f"Artifact filename must not contain path traversal: {filename!r}")
        return filename

    @staticmethod
    def _artifact_chunk(chunk: bytes) -> bytes:
        if not isinstance(chunk, bytes):
            raise TypeError(f"Artifact streams must yield bytes, received {type(chunk).__name__}.")
        return chunk

    async def stage(self, snapshot: ExecutionSnapshot) -> None:
        await self._execute_operation(
            self._stage(snapshot),
            description=f"Run {snapshot.run.run_id} staging",
        )

    async def _stage(self, snapshot: ExecutionSnapshot) -> None:
        self.require_open()
        await self._settle_artifact_transfers()
        run = snapshot.run
        try:
            run_lock = self.run_locks[run.run_id]
        except KeyError as exc:
            raise RecordingError(f"Run is not part of the experiment plan: {run.run_id}") from exc
        run_spec = next(item for item in self.start.runs if item.run_id == run.run_id)
        if (
            run.experiment_id != self.start.experiment_id
            or run.benchmark_id != self.start.benchmark_id
            or run.case_id != run_spec.case.id
            or run.variant_id != run_spec.variant.id
            or run.correlation != self.start.correlation
        ):
            raise RecordingError(f"Run identity does not match its plan entry: {run.run_id}")
        snapshot_hash = execution_snapshot_hash(snapshot)
        async with run_lock:
            async with self.state_lock:
                existing = next(
                    (item for item in self.manifest.runs if item.run_id == run.run_id),
                    None,
                )
                if existing is None:
                    pass
                else:
                    if existing.snapshot_hash == snapshot_hash:
                        return
                    raise RecordingError(f"Run {run.run_id} was staged with different content.")
            staged = await asyncio.to_thread(
                self.write_execution_snapshot,
                snapshot,
                snapshot_hash,
            )
            async with self.state_lock:
                ordered = {item.run_id: item for item in self.manifest.runs}
                ordered[staged.run_id] = staged
                plan_order = {
                    run_spec.run_id: index for index, run_spec in enumerate(self.start.runs)
                }
                revision = self.manifest.revision + 1
                staged_paths = {entry.path for entry in staged.files}
                manifest = self.manifest.model_copy(
                    update={
                        "revision": revision,
                        "runs": tuple(
                            sorted(ordered.values(), key=lambda item: plan_order[item.run_id])
                        ),
                        "payloads": tuple(
                            entry
                            for entry in self.manifest.payloads
                            if entry.path not in staged_paths
                        ),
                    }
                )
                state = self.state.model_copy(
                    update={"revision": revision, "updated_at": datetime.now(UTC)}
                )
                await asyncio.to_thread(self.write_state_and_manifest, state, manifest)
                self.state = state
                self.manifest = manifest

    async def checkpoint(self, snapshot: PartialRunSnapshot) -> None:
        await self._execute_operation(
            self._checkpoint(snapshot),
            description=f"Checkpoint {snapshot.run_id}:{snapshot.name}",
        )

    async def _checkpoint(self, snapshot: PartialRunSnapshot) -> None:
        self.require_open()
        await self._settle_artifact_transfers()
        if snapshot.run_id not in self.run_locks:
            raise RecordingError(f"Run is not part of the experiment plan: {snapshot.run_id}")
        run_spec = next(item for item in self.start.runs if item.run_id == snapshot.run_id)
        if (
            snapshot.experiment_id != self.start.experiment_id
            or snapshot.benchmark_id != self.start.benchmark_id
            or snapshot.case_id != run_spec.case.id
            or snapshot.variant_id != run_spec.variant.id
            or snapshot.correlation != self.start.correlation
        ):
            raise RecordingError(
                f"Checkpoint identity does not match its plan entry: {snapshot.run_id}"
            )
        async with self.run_locks[snapshot.run_id]:
            active_snapshot, payload_entries = await asyncio.to_thread(
                self._materialize_checkpoint_artifacts,
                snapshot,
            )
            snapshot_hash = partial_snapshot_hash(active_snapshot)
            async with self.state_lock:
                previous = next(
                    (
                        item
                        for item in self.manifest.checkpoints
                        if item.run_id == snapshot.run_id and item.name == snapshot.name
                    ),
                    None,
                )
                if previous is None:
                    pass
                else:
                    if previous.snapshot_hash == snapshot_hash:
                        return
                    raise RecordingError(
                        f"Checkpoint {snapshot.run_id}:{snapshot.name} has conflicting content."
                    )
            path = (
                self.recorder.staging_dir
                / "checkpoints"
                / path_component(snapshot.run_id)
                / f"{path_component(snapshot.name)}.yaml"
            )
            relative_path = path.relative_to(self.recorder.staging_dir).as_posix()
            await asyncio.to_thread(
                atomic_write_text,
                path,
                dump_yaml(partial_snapshot_to_yaml_view(active_snapshot), schema_name="checkpoint"),
                durability=self.recorder.durability,
            )
            entry = manifest_entry(
                self.recorder.staging_dir,
                relative_path,
                kind=RecordFileKind.RUN,
                identity=f"{snapshot.run_id}:{snapshot.name}",
            )
            checkpoint = StagedCheckpoint(
                run_id=snapshot.run_id,
                name=snapshot.name,
                path=relative_path,
                snapshot_hash=snapshot_hash,
                captured_at=active_snapshot.captured_at,
                signal_sequence_watermark=active_snapshot.signal_sequence_watermark,
                file=entry,
            )
            async with self.state_lock:
                checkpoints = {(item.run_id, item.name): item for item in self.manifest.checkpoints}
                checkpoints[(snapshot.run_id, snapshot.name)] = checkpoint
                revision = self.manifest.revision + 1
                committed_payloads = {item.path: item for item in self.manifest.payloads}
                committed_payloads.update({item.path: item for item in payload_entries})
                manifest = self.manifest.model_copy(
                    update={
                        "revision": revision,
                        "checkpoints": tuple(
                            sorted(
                                checkpoints.values(),
                                key=lambda item: (item.run_id, item.name),
                            )
                        ),
                        "payloads": tuple(
                            committed_payloads[path] for path in sorted(committed_payloads)
                        ),
                    }
                )
                state = self.state.model_copy(
                    update={"revision": revision, "updated_at": datetime.now(UTC)}
                )
                await asyncio.to_thread(self.write_state_and_manifest, state, manifest)
                self.state = state
                self.manifest = manifest

    def _materialize_checkpoint_artifacts(
        self,
        snapshot: PartialRunSnapshot,
    ) -> tuple[PartialRunSnapshot, tuple[ManifestEntry, ...]]:
        artifacts: list[ArtifactRef] = []
        entries: dict[str, ManifestEntry] = {}
        artifacts_dir = self.recorder.staging_dir / "artifacts"
        for artifact in snapshot.artifacts:
            if artifact.source is ArtifactSource.VALUE:
                artifacts.append(artifact)
                continue
            with self.prepared_artifacts_lock:
                prepared = self.prepared_artifacts.get((snapshot.run_id, artifact.id))
            if prepared is None:
                raise RecordingError(
                    f"Prepared artifact is unavailable for checkpoint: {snapshot.run_id}:{artifact.id}"
                )
            prepared_ref, prepared_path = prepared
            payload_path = artifact_payload_path(
                artifacts_dir,
                run_id=snapshot.run_id,
                artifact=prepared_ref,
            )
            metadata_path = artifact_record_path(
                artifacts_dir,
                run_id=snapshot.run_id,
                artifact=prepared_ref,
            )
            if metadata_path.exists():
                digest, byte_count = hash_and_size(payload_path)
                if digest != prepared_ref.sha256 or byte_count != prepared_ref.byte_count:
                    raise RecordingError(
                        f"Prepared artifact changed after capture: {snapshot.run_id}:{artifact.id}"
                    )
                recorded = prepared_ref.model_copy(
                    update={"value": payload_path.relative_to(self.recorder.staging_dir).as_posix()}
                )
            else:
                recorded = record_artifact(
                    prepared_ref,
                    artifacts_dir=artifacts_dir,
                    root_dir=self.recorder.staging_dir,
                    run_id=snapshot.run_id,
                    durability=self.recorder.durability,
                    prepared_path=prepared_path,
                )
            artifacts.append(recorded)
            for path in (metadata_path, payload_path):
                relative_path = path.relative_to(self.recorder.staging_dir).as_posix()
                entries[relative_path] = manifest_entry(
                    self.recorder.staging_dir,
                    relative_path,
                    kind=RecordFileKind.ARTIFACT,
                    identity=f"{snapshot.run_id}:{artifact.id}:{path.name}",
                )
        return snapshot.model_copy(update={"artifacts": tuple(artifacts)}), tuple(
            entries[path] for path in sorted(entries)
        )

    async def finish(self, result: ExperimentResult) -> ExperimentRecord:
        return await self._execute_operation(
            self._finish(result),
            description="Recording finalization",
        )

    async def _finish(self, result: ExperimentResult) -> ExperimentRecord:
        self.require_open()
        await self._settle_artifact_transfers()
        if result.experiment_id != self.start.experiment_id:
            raise RecordingError("Experiment result does not belong to the recording session.")
        staged_ids = {item.run_id for item in self.manifest.runs}
        planned_ids = tuple(run.run_id for run in self.start.runs)
        missing = tuple(run_id for run_id in planned_ids if run_id not in staged_ids)
        if missing:
            raise RecordingError(f"Cannot finish with missing staged runs: {list(missing)}")
        finalizing = self.state.model_copy(
            update={
                "status": StagingStatus.FINALIZING,
                "updated_at": datetime.now(UTC),
                "termination": result.termination,
            }
        )
        async with self.state_lock:
            await asyncio.to_thread(self.write_state_and_manifest, finalizing, self.manifest)
            self.state = finalizing
        record = await asyncio.to_thread(self.publish_result, result)
        self.finished = True
        await asyncio.to_thread(shutil.rmtree, self.recorder.staging_dir, True)
        return record

    async def abort(self, termination: ExperimentTermination) -> None:
        if self.closed or self.finished:
            return
        await self._settle_operations()
        await self._settle_artifact_transfers()
        if self.closed or self.finished:
            return
        async with self.state_lock:
            state = self.state.model_copy(
                update={
                    "status": StagingStatus.ABORTED,
                    "updated_at": datetime.now(UTC),
                    "termination": termination,
                }
            )
            await asyncio.to_thread(self.write_state_and_manifest, state, self.manifest)
            self.state = state

    async def close(self) -> None:
        await self._settle_operations()
        await self._settle_artifact_transfers()
        self.closed = True

    def require_open(self) -> None:
        if self.closed:
            raise RecordingError("Record session is closed.")
        if self.finished:
            raise RecordingError("Record session is already finished.")

    def write_execution_snapshot(
        self,
        snapshot: ExecutionSnapshot,
        snapshot_hash: str,
    ) -> StagedRun:
        run = snapshot.run
        staging = self.recorder.staging_dir
        run_path = (
            staging
            / "cases"
            / path_component(run.case_id)
            / path_component(run.variant_id)
            / "run.yaml"
        )
        artifacts_dir = staging / "artifacts"
        asset_dir = staging / "assets" / path_component(run.run_id)
        targets = [
            LogicalRecordTarget(
                path=run_path.relative_to(staging).as_posix(),
                kind=RecordFileKind.RUN,
                identity=run.run_id,
            )
        ]
        external_trace_path: Path | None = None
        for artifact in run.task_result.artifacts:
            targets.extend(
                (
                    LogicalRecordTarget(
                        path=artifact_record_path(
                            Path("artifacts"), run_id=run.run_id, artifact=artifact
                        ).as_posix(),
                        kind=RecordFileKind.ARTIFACT,
                        identity=f"{run.run_id}:{artifact.id}:metadata",
                    ),
                    LogicalRecordTarget(
                        path=artifact_payload_path(
                            Path("artifacts"), run_id=run.run_id, artifact=artifact
                        ).as_posix(),
                        kind=RecordFileKind.ARTIFACT,
                        identity=f"{run.run_id}:{artifact.id}:payload",
                    ),
                )
            )
        if run.trace is not None and trace_size(run.trace) > self.recorder.trace_inline_limit_bytes:
            external_trace_path = trace_artifact_path(Path("artifacts"), run_id=run.run_id)
            targets.append(
                LogicalRecordTarget(
                    path=external_trace_path.as_posix(),
                    kind=RecordFileKind.TRACE,
                    identity=run.run_id,
                )
            )
        validate_logical_targets(tuple(targets))
        if run_path.exists():
            raise RecordingError(f"Uncommitted staging data already exists for run {run.run_id}.")
        with self.prepared_artifacts_lock:
            prepared_artifacts = {
                artifact_id: path
                for (prepared_run_id, artifact_id), (_, path) in self.prepared_artifacts.items()
                if prepared_run_id == run.run_id
            }
        record = run_record_from_result(
            run,
            artifacts_dir=artifacts_dir,
            root_dir=staging,
            semantic_registry_version=self.start.semantic_registry.version,
            trace_inline_limit_bytes=self.recorder.trace_inline_limit_bytes,
            durability=self.recorder.durability,
            prepared_artifacts=prepared_artifacts,
        )
        referenced_asset_ids = {version.asset_id for version in run.asset_versions}
        persisted_asset_ids = {
            asset_id
            for asset_id in referenced_asset_ids
            if self.recorder.asset_registry.has_asset(asset_id)
        }
        if persisted_asset_ids:
            self.recorder.asset_registry.write_assets(
                asset_dir,
                asset_ids=persisted_asset_ids,
                content_path=asset_dir / "content.sqlite3",
                root_dir=staging,
            )
        atomic_write_text(
            run_path,
            dump_yaml(run_record_to_yaml_view(record), schema_name="run_record"),
            durability=self.recorder.durability,
        )
        owned_paths = [run_path]
        artifact_root = artifacts_dir / path_component(run.run_id)
        if artifact_root.exists():
            owned_paths.extend(path for path in artifact_root.rglob("*") if path.is_file())
        if asset_dir.exists():
            owned_paths.extend(path for path in asset_dir.rglob("*") if path.is_file())
        files: list[ManifestEntry] = []
        for path in sorted(owned_paths):
            relative_path = path.relative_to(staging)
            if path == run_path:
                kind = RecordFileKind.RUN
            elif path.is_relative_to(asset_dir):
                kind = RecordFileKind.ASSET
            elif external_trace_path is not None and relative_path == external_trace_path:
                kind = RecordFileKind.TRACE
            else:
                kind = RecordFileKind.ARTIFACT
            files.append(
                manifest_entry(
                    staging,
                    relative_path.as_posix(),
                    kind=kind,
                    identity=run.run_id if path == run_path else f"{run.run_id}:{path.name}",
                )
            )
        return StagedRun(
            run_id=run.run_id,
            case_id=run.case_id,
            variant_id=run.variant_id,
            record_path=run_path.relative_to(staging).as_posix(),
            snapshot_hash=snapshot_hash,
            captured_at=snapshot.captured_at,
            signal_sequence_watermark=snapshot.signal_sequence_watermark,
            files=tuple(files),
        )

    def write_state_and_manifest(
        self,
        state: StagingState,
        manifest: StagingManifest,
    ) -> None:
        atomic_write_text(
            self.recorder.staging_dir / STAGING_STATE_PATH,
            dump_yaml(
                experiment_start_to_yaml_view(self.start, state),
                schema_name="staging",
            ),
            durability=self.recorder.durability,
        )
        atomic_write_text(
            self.recorder.staging_dir / STAGING_MANIFEST_PATH,
            dump_yaml(staging_manifest_to_yaml_view(manifest), schema_name="staging_manifest"),
            durability=self.recorder.durability,
        )

    def publish_result(self, result: ExperimentResult) -> ExperimentRecord:
        recovered = recover_staging(self.recorder.staging_dir)
        finalizing = create_temporary_record_directory(self.recorder.output_dir)
        try:
            copy_committed_files(recovered, finalizing)
            staged_by_id = {run.run_id: run for run in recovered.manifest.runs}
            run_paths: list[str] = []
            for run in result.runs:
                staged = staged_by_id[run.run_id]
                path = finalizing / staged.record_path
                existing = RunRecord.model_validate(
                    run_record_payload_from_yaml_view(load_yaml(path))
                )
                updated = run_record_from_result(
                    run,
                    artifacts_dir=finalizing / "artifacts",
                    root_dir=finalizing,
                    semantic_registry_version=result.semantic_registry.version,
                    trace_inline_limit_bytes=self.recorder.trace_inline_limit_bytes,
                    durability=self.recorder.durability,
                    recorded_payloads=RecordedRunPayloads(
                        artifacts=existing.artifacts,
                        trace=existing.trace,
                        trace_artifact=existing.trace_artifact,
                    ),
                )
                atomic_write_text(
                    path,
                    dump_yaml(run_record_to_yaml_view(updated), schema_name="run_record"),
                    durability=self.recorder.durability,
                )
                run_paths.append(staged.record_path)
            record = experiment_record_from_result(
                result,
                run_paths=tuple(run_paths),
                file_hashes=self.start.file_hashes,
            )
            publication_targets = self.write_experiment_files(result, record, finalizing)
            write_final_metadata(
                finalizing,
                record,
                durability=self.recorder.durability,
                extra_targets=publication_targets,
            )
            publish_record_directory(
                finalizing,
                self.recorder.output_dir,
                durability=self.recorder.durability,
            )
            return record
        finally:
            remove_temporary_record_directory(finalizing)

    def write_experiment_files(
        self,
        result: ExperimentResult,
        record: ExperimentRecord,
        root: Path,
    ) -> tuple[LogicalRecordTarget, ...]:
        files = tuple(
            file
            for publisher in self.recorder.experiment_publishers
            for file in publisher(result, record, root)
        )
        targets = validate_logical_targets(
            tuple(
                LogicalRecordTarget(path=file.path, kind=file.kind, identity=file.identity)
                for file in files
            )
        )
        for file in files:
            target = root / file.path
            if target.exists() or target.is_symlink():
                raise RecordingError(f"Experiment publication path already exists: {file.path}")
            atomic_write_bytes(
                target,
                file.content,
                durability=self.recorder.durability,
            )
        return tuple(targets[path] for path in sorted(targets))

PartialRunSnapshot

Bases: BaseModel

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

    run_id: str = Field(min_length=1)
    experiment_id: str = Field(min_length=1)
    benchmark_id: str = Field(min_length=1)
    case_id: str = Field(min_length=1)
    variant_id: str = Field(min_length=1)
    name: str = Field(min_length=1)
    phase: RunPhase
    captured_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
    task_status: TaskStatus = TaskStatus.CANCELLED
    end_reason: EndReason = EndReason.CANCELLED
    task_output: Any = None
    observations: tuple[Observation, ...] = ()
    spans: tuple[SpanRecord, ...] = ()
    artifacts: tuple[ArtifactRef, ...] = ()
    errors: tuple[ErrorRecord, ...] = ()
    asset_versions: tuple[AssetVersion, ...] = ()
    asset_uses: tuple[AssetUse, ...] = ()
    source_snapshots: tuple[SourceSnapshot, ...] = ()
    extensions: dict[str, JsonValue] = Field(default_factory=dict)
    trace: Trace | None = None
    signal_sequence_watermark: int = Field(default=0, ge=0)
    correlation: ExecutionCorrelation | None = None

Recorder

Bases: Protocol

Source code in src/autobench/records/staging.py
314
315
class Recorder(Protocol):
    async def open(self, start: ExperimentStart) -> RecordSession: ...

RecordSession

Bases: Protocol

Source code in src/autobench/records/staging.py
318
319
320
321
322
323
324
325
326
327
328
329
330
class RecordSession(Protocol):
    @property
    def artifact_sink(self) -> ArtifactSink | None: ...

    async def stage(self, snapshot: ExecutionSnapshot) -> None: ...

    async def checkpoint(self, snapshot: PartialRunSnapshot) -> None: ...

    async def finish(self, result: ExperimentResult) -> ExperimentRecord: ...

    async def abort(self, termination: ExperimentTermination) -> None: ...

    async def close(self) -> None: ...

RecoveredStaging

Bases: BaseModel

Source code in src/autobench/records/staging.py
303
304
305
306
307
308
309
310
311
class RecoveredStaging(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    start: ExperimentStart
    state: StagingState
    manifest: StagingManifest
    inspection: StagingInspection
    runs: tuple[RunRecord, ...]
    checkpoints: tuple[PartialRunSnapshot, ...] = ()

RunPhase

Bases: StrEnum

Source code in src/autobench/runtime/lifecycle.py
 6
 7
 8
 9
10
11
12
class RunPhase(StrEnum):
    RESOLVING = "resolving"
    EXECUTING = "executing"
    SCORING = "scoring"
    DERIVING = "deriving"
    POST_PROCESSING = "post_processing"
    FINALIZING = "finalizing"

StagedCheckpoint

Bases: BaseModel

Source code in src/autobench/records/staging.py
236
237
238
239
240
241
242
243
244
245
class StagedCheckpoint(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    run_id: str = Field(min_length=1)
    name: str = Field(min_length=1)
    path: str = Field(min_length=1)
    snapshot_hash: str = Field(pattern=r"^[0-9a-f]{64}$")
    captured_at: datetime
    signal_sequence_watermark: int = Field(ge=0)
    file: ManifestEntry

StagedRun

Bases: BaseModel

Source code in src/autobench/records/staging.py
223
224
225
226
227
228
229
230
231
232
233
class StagedRun(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    run_id: str = Field(min_length=1)
    case_id: str = Field(min_length=1)
    variant_id: str = Field(min_length=1)
    record_path: str = Field(min_length=1)
    snapshot_hash: str = Field(pattern=r"^[0-9a-f]{64}$")
    captured_at: datetime
    signal_sequence_watermark: int = Field(ge=0)
    files: tuple[ManifestEntry, ...]

StagingHealth

Bases: StrEnum

Source code in src/autobench/records/staging.py
132
133
134
135
136
137
class StagingHealth(StrEnum):
    COMPLETE = "complete"
    PARTIAL = "partial"
    MISSING = "missing"
    CORRUPT = "corrupt"
    CONFLICTING = "conflicting"

StagingInspection

Bases: BaseModel

Source code in src/autobench/records/staging.py
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
class StagingInspection(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    path: Path
    experiment_id: str
    health: StagingHealth
    recoverable: bool
    status: StagingStatus
    planned_run_ids: tuple[str, ...]
    complete_run_ids: tuple[str, ...] = ()
    checkpointed_run_ids: tuple[str, ...] = ()
    missing_run_ids: tuple[str, ...] = ()
    corrupt_run_ids: tuple[str, ...] = ()
    conflicting_run_ids: tuple[str, ...] = ()
    orphaned_files: tuple[str, ...] = ()
    diagnostics: tuple[str, ...] = ()

StagingManifest

Bases: BaseModel

Source code in src/autobench/records/staging.py
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
class StagingManifest(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    version: Literal[1] = STAGING_VERSION
    experiment_id: str = Field(min_length=1)
    revision: int = Field(default=0, ge=0)
    runs: tuple[StagedRun, ...] = ()
    checkpoints: tuple[StagedCheckpoint, ...] = ()
    payloads: tuple[ManifestEntry, ...] = ()

    @model_validator(mode="after")
    def validate_identities(self) -> StagingManifest:
        run_ids = tuple(run.run_id for run in self.runs)
        if len(run_ids) != len(set(run_ids)):
            raise ValueError("staging manifest contains duplicate run ids")
        checkpoint_keys = tuple((item.run_id, item.name) for item in self.checkpoints)
        if len(checkpoint_keys) != len(set(checkpoint_keys)):
            raise ValueError("staging manifest contains duplicate checkpoints")
        paths = [entry.path for run in self.runs for entry in run.files]
        paths.extend(checkpoint.file.path for checkpoint in self.checkpoints)
        paths.extend(entry.path for entry in self.payloads)
        if len(paths) != len(set(paths)):
            raise ValueError("staging manifest contains conflicting file paths")
        return self

StagingState

Bases: BaseModel

Source code in src/autobench/records/staging.py
274
275
276
277
278
279
280
281
282
class StagingState(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    version: Literal[1] = STAGING_VERSION
    experiment_id: str = Field(min_length=1)
    status: StagingStatus = StagingStatus.ACTIVE
    revision: int = Field(default=0, ge=0)
    updated_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
    termination: ExperimentTermination | None = None

StagingStatus

Bases: StrEnum

Source code in src/autobench/records/staging.py
126
127
128
129
class StagingStatus(StrEnum):
    ACTIVE = "active"
    FINALIZING = "finalizing"
    ABORTED = "aborted"

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

MarkdownExperimentPublisher

Source code in src/autobench/reports/markdown.py
 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
class MarkdownExperimentPublisher:
    def __call__(
        self,
        result: ExperimentResult,
        record: ExperimentRecord,
        experiment_root: Path,
    ) -> tuple[ExperimentFile, ...]:
        from autobench.reports.reporting import build_report

        if result.report_spec_data is None:
            return ()
        report_spec = ReportSpec.model_validate(result.report_spec_data)
        output = report_spec.markdown.output
        if output is None:
            return ()
        report = build_report(
            result,
            report_spec=report_spec,
            experiment_record=record,
            experiment_root=experiment_root,
        )
        layout = _select_layout(report, report_spec.markdown.layout)
        if layout == "single":
            link_prefix = _record_link_prefix(
                (experiment_root / output).parent,
                experiment_root,
            )
            return (
                ExperimentFile(
                    path=output.as_posix(),
                    content=render_markdown_report(
                        report,
                        record_link_prefix=link_prefix,
                    ).encode(),
                    kind=RecordFileKind.OTHER,
                    identity=f"report:{report.experiment_id}:index",
                ),
            )
        link_prefix = _record_link_prefix(experiment_root / output, experiment_root)
        return tuple(
            ExperimentFile(
                path=(output / relative_path).as_posix(),
                content=content.encode(),
                kind=RecordFileKind.OTHER,
                identity=f"report:{report.experiment_id}:{relative_path}",
            )
            for relative_path, content in render_markdown_bundle(
                report,
                record_link_prefix=link_prefix,
            ).items()
        )

ReportPublicationError

Bases: AutobenchError

Raised when a Markdown report cannot be published safely.

Source code in src/autobench/reports/markdown.py
52
53
class ReportPublicationError(AutobenchError):
    """Raised when a Markdown report cannot be published safely."""

MarkdownReportPublication

Bases: BaseModel

Source code in src/autobench/reports/models.py
131
132
133
134
135
136
class MarkdownReportPublication(BaseModel):
    profile: ReportProfile
    requested_layout: ReportLayout
    layout: Literal["single", "bundle"]
    destination: Path
    files: tuple[PublishedReportFile, ...]

PublishedReportFile

Bases: BaseModel

Source code in src/autobench/reports/models.py
125
126
127
128
class PublishedReportFile(BaseModel):
    path: Path
    sha256: str = Field(pattern=r"^[0-9a-f]{64}$")
    byte_count: int = Field(ge=0)

BenchmarkReport

Bases: BaseModel

Source code in src/autobench/reports/models.py
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
class BenchmarkReport(BaseModel):
    report_version: int = REPORT_VERSION
    markdown: MarkdownReportConfig = Field(default_factory=MarkdownReportConfig)
    benchmark_id: str
    experiment_id: str
    run_count: int
    source: SourceIdentityReport | None = None
    summary: ExecutiveSummary | None = None
    evaluation: EvaluationSummaryReport | None = None
    design: ExperimentDesignReport | None = None
    health: RunHealthReport | None = None
    metric_catalog: tuple[MetricDefinitionReport, ...] = ()
    notices: tuple[ReportNotice, ...] = ()
    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)
    run_details: tuple[RunDetailReport, ...] = ()
    failures: tuple[FailureReport, ...] = ()
    traces: TraceSummaryReport | None = None
    assets: AssetLineageReport | None = None
    artifacts: ArtifactInventoryReport | None = None
    policies: tuple[PolicyOutcomeReport, ...] = ()
    provenance: ProvenanceReport | None = None
    case_matrix: CaseMatrix
    comparisons: list[ComparisonReport] = Field(default_factory=list)
    regressions: tuple[RegressionReport, ...] = ()
    distributions: list[MetricDistribution] = Field(default_factory=list)
    optimizations: list[OptimizationRunReport] = Field(default_factory=list)
    optimization_warnings: list[str] = Field(default_factory=list)
    correlation: ExecutionCorrelation | None = None

CaseMatrix

Bases: BaseModel

Source code in src/autobench/reports/models.py
331
332
333
class CaseMatrix(BaseModel):
    metric: str
    rows: dict[str, dict[str, JsonValue]] = Field(default_factory=dict)

CaseMatrixReportSpec

Bases: BaseModel

Source code in src/autobench/reports/models.py
66
67
class CaseMatrixReportSpec(BaseModel):
    semantic_type: str = "coverage.ratio"

ComparisonReport

Bases: BaseModel

Source code in src/autobench/reports/models.py
336
337
338
339
340
341
342
343
344
345
346
347
class ComparisonReport(BaseModel):
    baseline: str
    candidate: str
    run_count: int
    factor_deltas: dict[str, dict[str, JsonValue]] = Field(default_factory=dict)
    metric_deltas: dict[str, dict[str, JsonValue]] = Field(default_factory=dict)
    confounded: bool = False
    baseline_factors: dict[str, JsonValue] = Field(default_factory=dict)
    candidate_factors: dict[str, JsonValue] = Field(default_factory=dict)
    paired_count: int = 0
    missing_pair_count: int = 0
    metric_results: tuple[MetricComparisonReport, ...] = ()

ComparisonReportSpec

Bases: BaseModel

Source code in src/autobench/reports/models.py
70
71
72
73
74
75
76
77
78
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

CorrelatedReportGroup

Bases: BaseModel

Source code in src/autobench/reports/models.py
567
568
569
570
571
class CorrelatedReportGroup(BaseModel):
    group_id: str | None = None
    attempts: tuple[int, ...] = ()
    phases: tuple[str, ...] = ()
    reports: list[BenchmarkReport] = Field(default_factory=list)

DistributionReportSpec

Bases: BaseModel

Source code in src/autobench/reports/models.py
81
82
83
84
class DistributionReportSpec(BaseModel):
    name: str
    semantic_type: str
    summaries: tuple[AggregationFn, ...] = ("min", "median", "p95", "max")

EvaluationCaseReport

Bases: BaseModel

Source code in src/autobench/reports/models.py
192
193
194
195
196
197
198
199
class EvaluationCaseReport(BaseModel):
    run_id: str
    case_id: str
    variant_id: str
    quality_pass: bool | None = None
    score: float | None = None
    metrics: dict[str, JsonValue] = Field(default_factory=dict)
    feedback: tuple[str, ...] = ()

EvaluationMetricReport

Bases: BaseModel

Source code in src/autobench/reports/models.py
179
180
181
182
183
184
185
186
187
188
189
class EvaluationMetricReport(BaseModel):
    name: str
    label: str
    kind: Literal["score", "count", "value"]
    sample_count: int
    missing_count: int
    mean: float
    median: float
    minimum: float
    maximum: float
    total: float

EvaluationSummaryReport

Bases: BaseModel

Source code in src/autobench/reports/models.py
202
203
204
205
206
207
208
209
210
211
212
213
214
215
class EvaluationSummaryReport(BaseModel):
    case_count: int
    evaluated_count: int
    passed_count: int
    failed_count: int
    unevaluated_count: int
    pass_rate: float | None = None
    score_count: int
    mean_score: float | None = None
    median_score: float | None = None
    minimum_score: float | None = None
    maximum_score: float | None = None
    metrics: tuple[EvaluationMetricReport, ...] = ()
    cases: tuple[EvaluationCaseReport, ...] = ()

LeaderboardReportSpec

Bases: BaseModel

Source code in src/autobench/reports/models.py
62
63
class LeaderboardReportSpec(BaseModel):
    metrics: tuple[MetricAggregation, ...] = ()

LeaderboardRow

Bases: BaseModel

Source code in src/autobench/reports/models.py
310
311
312
313
314
class LeaderboardRow(BaseModel):
    variant_id: str
    run_count: int
    metrics: dict[str, JsonValue] = Field(default_factory=dict)
    metric_details: tuple[LeaderboardMetricReport, ...] = ()

MarkdownAssetConfig

Bases: BaseModel

Source code in src/autobench/reports/models.py
98
99
class MarkdownAssetConfig(BaseModel):
    diffs: AssetDiffMode = "summary"

MarkdownContentConfig

Bases: BaseModel

Source code in src/autobench/reports/models.py
102
103
class MarkdownContentConfig(BaseModel):
    include_captured: bool = False

MarkdownReportConfig

Bases: BaseModel

Source code in src/autobench/reports/models.py
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
class MarkdownReportConfig(BaseModel):
    profile: ReportProfile = "full"
    layout: ReportLayout = "auto"
    output: Path | None = None
    limits: MarkdownReportLimits = Field(default_factory=MarkdownReportLimits)
    traces: MarkdownTraceConfig = Field(default_factory=MarkdownTraceConfig)
    assets: MarkdownAssetConfig = Field(default_factory=MarkdownAssetConfig)
    content: MarkdownContentConfig = Field(default_factory=MarkdownContentConfig)

    @field_validator("output")
    @classmethod
    def validate_output(cls, output: Path | None) -> Path | None:
        if output is None:
            return None
        if output.is_absolute() or ".." in output.parts:
            raise ValueError("markdown report output must be a portable relative path")
        return output

MarkdownReportLimits

Bases: BaseModel

Source code in src/autobench/reports/models.py
87
88
89
90
91
class MarkdownReportLimits(BaseModel):
    table_rows: int = Field(default=200, ge=1)
    run_details: int = Field(default=100, ge=1)
    failure_details: int = Field(default=100, ge=1)
    value_excerpt_chars: int = Field(default=2_000, ge=1)

MarkdownTraceConfig

Bases: BaseModel

Source code in src/autobench/reports/models.py
94
95
class MarkdownTraceConfig(BaseModel):
    top_slowest: int = Field(default=20, ge=1)

MetricAggregation

Bases: BaseModel

Source code in src/autobench/reports/models.py
56
57
58
59
class MetricAggregation(BaseModel):
    name: str
    semantic_type: str
    fn: AggregationFn

MetricDistribution

Bases: BaseModel

Source code in src/autobench/reports/models.py
520
521
522
523
524
class MetricDistribution(BaseModel):
    name: str
    semantic_type: str
    by_variant: dict[str, list[JsonValue]] = Field(default_factory=dict)
    summaries: dict[str, dict[str, JsonValue]] = Field(default_factory=dict)

ReportSpec

Bases: BaseModel

Source code in src/autobench/reports/models.py
139
140
141
142
143
144
145
146
147
148
149
class ReportSpec(BaseModel):
    leaderboard: LeaderboardReportSpec = Field(default_factory=LeaderboardReportSpec)
    case_matrix: CaseMatrixReportSpec = Field(default_factory=CaseMatrixReportSpec)
    comparisons: tuple[ComparisonReportSpec, ...] = ()
    distributions: tuple[DistributionReportSpec, ...] = ()
    markdown: MarkdownReportConfig = Field(default_factory=MarkdownReportConfig)

    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/models.py
324
325
326
327
328
class RunMetricRow(BaseModel):
    case_id: str
    variant_id: str
    status: str
    metrics: dict[str, JsonValue] = Field(default_factory=dict)

VariantConfigRow

Bases: BaseModel

Source code in src/autobench/reports/models.py
317
318
319
320
321
class VariantConfigRow(BaseModel):
    variant_id: str
    label: str | None = None
    factors: dict[str, JsonValue] = Field(default_factory=dict)
    factor_details: tuple[FactorReport, ...] = ()

CheckResult

Bases: BaseModel

Source code in src/autobench/runtime/context.py
121
122
123
124
125
126
127
128
129
130
131
132
133
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,
        }

ContextEvidence

Bases: BaseModel

Source code in src/autobench/runtime/context.py
141
142
143
144
145
146
147
148
149
150
151
152
153
class ContextEvidence(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    observations: tuple[Observation, ...]
    spans: tuple[SpanRecord, ...]
    artifacts: tuple[ArtifactRef, ...]
    errors: tuple[ErrorRecord, ...]
    asset_versions: tuple[AssetVersion, ...]
    asset_uses: tuple[AssetUse, ...]
    source_snapshots: tuple[SourceSnapshot, ...]
    extensions: dict[str, JsonValue] = Field(default_factory=dict)
    trace: Trace
    signal_sequence_watermark: int

DurationMetricSpec

Bases: BaseModel

Source code in src/autobench/runtime/context.py
78
79
80
81
82
83
84
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
136
137
138
class MeasurementRecord(BaseModel):
    metrics: tuple[Observation, ...]
    samples_artifact: ArtifactRef | None = None

RunContext

Source code in src/autobench/runtime/context.py
 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
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
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
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
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
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.asset_uses: list[AssetUse] = []
        self.source_snapshots: list[SourceSnapshot] = []
        self.extensions: dict[str, JsonValue] = {}
        self._evidence_lock = RLock()
        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()
        self._asset_use_keys: set[tuple[str, str, str, str | None]] = set()
        self._phase = RunPhase.RESOLVING
        self._checkpoint_output: Any = None
        self._checkpoint_handler: CheckpointHandler | None = None
        self._artifact_sink: ArtifactSink | None = None
        _RUN_CONTEXTS[self._emitter.trace_id] = self

    @property
    def trace(self) -> Trace:
        with self._evidence_lock:
            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 phase(self) -> RunPhase:
        with self._evidence_lock:
            return self._phase

    @property
    def checkpoint_output(self) -> Any:
        with self._evidence_lock:
            return self._checkpoint_output

    @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,
        )

    @property
    def active_span_id(self) -> str | None:
        """Return the legacy span identity selected by the active ABP context."""

        active = get_context()
        if (
            active is None
            or active.collector is not self._collector
            or active.trace_id != self._emitter.trace_id
            or active.current_span_id is None
        ):
            return None
        with self._evidence_lock:
            return self._abp_to_legacy.get(active.current_span_id)

    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:
        with self._evidence_lock:
            self.source_snapshots.append(snapshot)
        return snapshot

    def set_extension(self, name: str, value: JsonValue) -> None:
        """Store one integration-owned, JSON-safe run projection."""

        if not name.strip():
            raise ValueError("Extension names must not be empty.")
        with self._evidence_lock:
            self.extensions[name] = deepcopy(value)

    def snapshot_evidence(self) -> ContextEvidence:
        with self._evidence_lock:
            trace = self.trace
            return ContextEvidence(
                observations=tuple(item.model_copy(deep=True) for item in self.observations),
                spans=tuple(item.model_copy(deep=True) for item in self.spans),
                artifacts=tuple(item.model_copy(deep=True) for item in self.artifacts),
                errors=tuple(item.model_copy(deep=True) for item in self.errors),
                asset_versions=tuple(item.model_copy(deep=True) for item in self.asset_versions),
                asset_uses=tuple(item.model_copy(deep=True) for item in self.asset_uses),
                source_snapshots=tuple(
                    item.model_copy(deep=True) for item in self.source_snapshots
                ),
                extensions=deepcopy(self.extensions),
                trace=trace.model_copy(deep=True),
                signal_sequence_watermark=max(
                    (signal.sequence for signal in trace.signals),
                    default=0,
                ),
            )

    def bind_checkpoint(self, handler: CheckpointHandler) -> None:
        with self._evidence_lock:
            if self._checkpoint_handler is not None:
                raise RuntimeError("A checkpoint handler is already bound to this run context.")
            self._checkpoint_handler = handler

    def bind_artifact_sink(self, sink: ArtifactSink) -> None:
        with self._evidence_lock:
            if self._artifact_sink is not None:
                raise RuntimeError("An artifact sink is already bound to this run context.")
            self._artifact_sink = sink

    def set_phase(self, phase: RunPhase) -> None:
        with self._evidence_lock:
            self._phase = phase

    def retain_task_output(self, output: Any) -> None:
        with self._evidence_lock:
            self._checkpoint_output = output

    async def checkpoint(self, name: str) -> None:
        active_name = name.strip()
        if not active_name:
            raise ValueError("Checkpoint names must not be empty.")
        if active_name.startswith("autobench."):
            raise ValueError("Checkpoint names beginning with 'autobench.' are reserved.")
        with self._evidence_lock:
            handler = self._checkpoint_handler
            if handler is None:
                raise RuntimeError(
                    "Checkpoints require durable recording; run the benchmark with a recorder."
                )
            phase = self._phase
            output = self._checkpoint_output
            evidence = self.snapshot_evidence()
        await handler(active_name, phase, output, evidence)

    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,
        parent_span_id: str | 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,
            parent_span_id=parent_span_id,
        )

    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,
        source: ObservationSource = ObservationSource.TASK_OBSERVATION,
    ) -> Observation:
        return self._append_observation(
            name=name,
            kind=ObservationKind.EVENT,
            value=value,
            semantic_type=semantic_type,
            span_id=span_id,
            tags=tags,
            source=source,
        )

    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:
        with self._evidence_lock:
            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:
        with self._evidence_lock:
            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 artifact_file(
        self,
        name: str,
        source: Path,
        *,
        media_type: str | None = None,
        max_bytes: int | None = None,
        overflow: ArtifactOverflow = ArtifactOverflow.FAIL,
        symlinks: SymlinkPolicy = SymlinkPolicy.REJECT,
        filename: str | None = None,
        span_id: str | None = None,
        tags: dict[str, Any] | None = None,
    ) -> ArtifactRef:
        sink = self._require_artifact_sink()
        active_max_bytes = self._artifact_max_bytes(max_bytes)
        with self._evidence_lock:
            artifact_id = self._next_artifact_id()
        active_tags = dict(tags or {})
        try:
            artifact = sink.prepare_file(
                run_id=self.run_id,
                artifact_id=artifact_id,
                name=name,
                source=source,
                media_type=media_type,
                max_bytes=active_max_bytes,
                overflow=overflow,
                symlinks=symlinks,
                filename=filename,
                span_id=span_id,
                tags=active_tags,
            )
        except BaseException:
            self._retain_interrupted_artifact(sink, artifact_id, span_id=span_id)
            raise
        return self._retain_prepared_artifact(artifact)

    async def artifact_file_async(
        self,
        name: str,
        source: Path,
        *,
        media_type: str | None = None,
        max_bytes: int | None = None,
        overflow: ArtifactOverflow = ArtifactOverflow.FAIL,
        symlinks: SymlinkPolicy = SymlinkPolicy.REJECT,
        filename: str | None = None,
        span_id: str | None = None,
        tags: dict[str, Any] | None = None,
    ) -> ArtifactRef:
        sink = self._require_artifact_sink()
        active_max_bytes = self._artifact_max_bytes(max_bytes)
        with self._evidence_lock:
            artifact_id = self._next_artifact_id()
        active_tags = dict(tags or {})
        transfer = asyncio.create_task(
            sink.prepare_file_async(
                run_id=self.run_id,
                artifact_id=artifact_id,
                name=name,
                source=source,
                media_type=media_type,
                max_bytes=active_max_bytes,
                overflow=overflow,
                symlinks=symlinks,
                filename=filename,
                span_id=span_id,
                tags=active_tags,
            )
        )
        try:
            artifact = await asyncio.shield(transfer)
        except asyncio.CancelledError as cancellation:
            transfer_error = await settle_task(
                transfer,
                timeout_seconds=_ARTIFACT_TRANSFER_SETTLE_SECONDS,
                cancel_on_timeout=False,
                description=f"Artifact {artifact_id} transfer",
            )
            retained = self._retain_interrupted_artifact(
                sink,
                artifact_id,
                span_id=span_id,
            )
            if not retained:
                self._retain_prepared_artifact(
                    ArtifactRef(
                        id=artifact_id,
                        name=name,
                        media_type=media_type,
                        span_id=span_id,
                        tags=active_tags,
                        source=ArtifactSource.FILE,
                        state=ArtifactState.PARTIAL,
                        filename=filename or source.name,
                    )
                )
            if transfer_error is not None:
                cancellation.add_note(f"artifact transfer did not settle: {transfer_error}")
            raise
        except BaseException:
            self._retain_interrupted_artifact(sink, artifact_id, span_id=span_id)
            raise
        return self._retain_prepared_artifact(artifact)

    def artifact_stream(
        self,
        name: str,
        source: Iterable[bytes],
        *,
        media_type: str | None = None,
        max_bytes: int | None = None,
        overflow: ArtifactOverflow = ArtifactOverflow.FAIL,
        filename: str | None = None,
        span_id: str | None = None,
        tags: dict[str, Any] | None = None,
    ) -> ArtifactRef:
        sink = self._require_artifact_sink()
        active_max_bytes = self._artifact_max_bytes(max_bytes)
        with self._evidence_lock:
            artifact_id = self._next_artifact_id()
        try:
            artifact = sink.prepare_stream(
                run_id=self.run_id,
                artifact_id=artifact_id,
                name=name,
                source=source,
                media_type=media_type,
                max_bytes=active_max_bytes,
                overflow=overflow,
                filename=filename,
                span_id=span_id,
                tags=dict(tags or {}),
            )
        except BaseException:
            self._retain_interrupted_artifact(sink, artifact_id, span_id=span_id)
            raise
        return self._retain_prepared_artifact(artifact)

    async def artifact_stream_async(
        self,
        name: str,
        source: AsyncIterable[bytes],
        *,
        media_type: str | None = None,
        max_bytes: int | None = None,
        overflow: ArtifactOverflow = ArtifactOverflow.FAIL,
        filename: str | None = None,
        span_id: str | None = None,
        tags: dict[str, Any] | None = None,
    ) -> ArtifactRef:
        sink = self._require_artifact_sink()
        active_max_bytes = self._artifact_max_bytes(max_bytes)
        with self._evidence_lock:
            artifact_id = self._next_artifact_id()
        try:
            artifact = await sink.prepare_stream_async(
                run_id=self.run_id,
                artifact_id=artifact_id,
                name=name,
                source=source,
                media_type=media_type,
                max_bytes=active_max_bytes,
                overflow=overflow,
                filename=filename,
                span_id=span_id,
                tags=dict(tags or {}),
            )
        except BaseException:
            self._retain_interrupted_artifact(sink, artifact_id, span_id=span_id)
            raise
        return self._retain_prepared_artifact(artifact)

    def _require_artifact_sink(self) -> ArtifactSink:
        with self._evidence_lock:
            if self._artifact_sink is None:
                raise ArtifactSinkRequiredError(
                    "File and stream artifacts require an active durable recorder."
                )
            return self._artifact_sink

    def _artifact_max_bytes(self, max_bytes: int | None) -> int:
        active = self.capture_policy.max_artifact_bytes if max_bytes is None else max_bytes
        if active < 1:
            raise ValueError("max_bytes must be at least 1")
        return active

    def _retain_interrupted_artifact(
        self,
        sink: ArtifactSink,
        artifact_id: str,
        *,
        span_id: str | None,
    ) -> bool:
        artifact = sink.prepared_artifact(run_id=self.run_id, artifact_id=artifact_id)
        if artifact is None:
            return False
        self._retain_prepared_artifact(
            artifact.model_copy(update={"span_id": artifact.span_id or span_id})
        )
        return True

    def _retain_prepared_artifact(self, artifact: ArtifactRef) -> ArtifactRef:
        with self._evidence_lock:
            self.artifacts.append(artifact)
            if artifact.span_id is not None:
                span_record = self._span_by_id(artifact.span_id)
                if span_record is not None:
                    span_record.artifacts.append(artifact.id)
            abp_span_id = self._abp_span_id(artifact.span_id)
            self._emitter_for_legacy_span(artifact.span_id).reference(
                EvidenceRef(
                    kind=ReferenceKind.ARTIFACT,
                    id=artifact.id,
                    media_type=artifact.media_type,
                ),
                span_id=abp_span_id,
                semantic_type=Semantic.ARTIFACT_CONTENT,
                name=artifact.name,
                attributes={
                    "artifact_id": artifact.id,
                    "artifact_state": artifact.state.value,
                    "artifact_sha256": artifact.sha256,
                    "artifact_byte_count": artifact.byte_count,
                },
            )
            self._append_observation(
                name=artifact.name,
                kind=ObservationKind.ARTIFACT,
                value=artifact.id,
                span_id=artifact.span_id,
                tags=artifact.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 = active_registry.asset_of(target)
        with self._evidence_lock:
            self._attach_asset_reference(asset, asset_version, span_id=span_id)
            source_locator = asset.id
            use_key = (asset.id, asset_version.version, source_locator, span_id)
            if use_key not in self._asset_use_keys:
                self.asset_uses.append(
                    AssetUse(
                        asset_id=asset.id,
                        version=asset_version.version,
                        representation=AssetRepresentation.DEFINITION,
                        source_locator=source_locator,
                        span_id=span_id,
                        provenance=AssetProvenance(
                            system="autobench",
                            key=asset.id,
                            instrumentor="autobench.tracking",
                        ),
                    )
                )
                self._asset_use_keys.add(use_key)
        return asset_version

    def attach_discovered_asset(self, registered: RegisteredAsset) -> AssetUse:
        use = registered.use
        with self._evidence_lock:
            self._attach_asset_reference(registered.asset, registered.version, span_id=use.span_id)
            use_key = (use.asset_id, use.version, use.source_locator, use.span_id)
            if use_key not in self._asset_use_keys:
                self.asset_uses.append(use)
                self._asset_use_keys.add(use_key)
        return use

    def prepare_discovered_asset(
        self,
        candidate: AssetCandidate,
        *,
        span_id: str | None,
    ) -> AssetCandidate:
        fingerprint = canonical_asset_hash(candidate.canonical_content)
        level = self.capture_policy.level_for_asset(
            candidate.semantic_type,
        )
        if candidate.sensitivity is AssetSensitivity.SENSITIVE and level is CaptureLevel.METADATA:
            level = CaptureLevel.HASH
        elif candidate.sensitivity is AssetSensitivity.PUBLIC and level is CaptureLevel.METADATA:
            level = CaptureLevel.FULL
        captured = self._capture_value(
            candidate.canonical_content,
            semantic_type=candidate.semantic_type,
            path=f"assets.{candidate.source_locator}",
            span_id=self._abp_span_id(span_id),
            level=level,
        )
        content: SerializedValue
        if captured.omitted:
            content = {"omitted": True, "sha256": fingerprint}
        elif captured.reference is not None:
            content = captured.reference.model_dump(mode="json")
        else:
            content = captured.value
        return candidate.model_copy(
            update={
                "canonical_content": content,
                "content_fingerprint": fingerprint,
            }
        )

    def _attach_asset_reference(
        self,
        asset: TrackedAsset,
        asset_version: AssetVersion,
        *,
        span_id: str | None,
    ) -> None:
        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)
            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},
                )

    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:
        with self._evidence_lock:
            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,
        parent_span_id: str | None = None,
    ) -> tuple[SpanRecord, int]:
        with self._evidence_lock:
            if self.finalized:
                raise RuntimeError("RunContext is finalized.")
            if parent_span_id is not None:
                parent_record = self._span_by_id(parent_span_id)
                if parent_record is None:
                    raise ValueError(f"Unknown parent span: {parent_span_id}")
                if parent_record.ended_at is not None:
                    raise ValueError(f"Parent span has ended: {parent_span_id}")
                parent_abp_id = self._legacy_to_abp[parent_span_id]
            else:
                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,
        status: SpanStatus | None = None,
        reason: EndReason | None = None,
        partial: bool | None = None,
    ) -> None:
        with self._evidence_lock:
            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, ()))
            span_status = SpanStatus.OK if status is None else status
            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:
                span_status = SpanStatus.ERROR
                if reason is None or reason is EndReason.COMPLETED:
                    end_reason = EndReason.FAILED
            elif span_status is SpanStatus.ERROR and reason is None:
                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(
                span_id=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=span_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:
        with self._evidence_lock:
            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).try_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}"
active_span_id property
active_span_id: str | None

Return the legacy span identity selected by the active ABP context.

set_extension
set_extension(name: str, value: JsonValue) -> None

Store one integration-owned, JSON-safe run projection.

Source code in src/autobench/runtime/context.py
305
306
307
308
309
310
311
def set_extension(self, name: str, value: JsonValue) -> None:
    """Store one integration-owned, JSON-safe run projection."""

    if not name.strip():
        raise ValueError("Extension names must not be empty.")
    with self._evidence_lock:
        self.extensions[name] = deepcopy(value)

Span

Bases: AbstractContextManager['Span']

Source code in src/autobench/runtime/context.py
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
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,
        parent_span_id: str | 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._parent_span_id = parent_span_id
        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.start()
        self.resume()
        return self

    def start(self) -> Span:
        """Start this span without changing the active context stack."""

        if self._record is not None:
            raise RuntimeError("Span has already started.")
        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,
            parent_span_id=self._parent_span_id,
        )
        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,
        status: SpanStatus | 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,
                    status=status,
                    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 artifact_file(
        self,
        name: str,
        source: Path,
        *,
        media_type: str | None = None,
        max_bytes: int | None = None,
        overflow: ArtifactOverflow = ArtifactOverflow.FAIL,
        symlinks: SymlinkPolicy = SymlinkPolicy.REJECT,
        filename: str | None = None,
        tags: dict[str, Any] | None = None,
    ) -> ArtifactRef:
        return self._context.artifact_file(
            name,
            source,
            media_type=media_type,
            max_bytes=max_bytes,
            overflow=overflow,
            symlinks=symlinks,
            filename=filename,
            span_id=self.id,
            tags=tags,
        )

    async def artifact_file_async(
        self,
        name: str,
        source: Path,
        *,
        media_type: str | None = None,
        max_bytes: int | None = None,
        overflow: ArtifactOverflow = ArtifactOverflow.FAIL,
        symlinks: SymlinkPolicy = SymlinkPolicy.REJECT,
        filename: str | None = None,
        tags: dict[str, Any] | None = None,
    ) -> ArtifactRef:
        return await self._context.artifact_file_async(
            name,
            source,
            media_type=media_type,
            max_bytes=max_bytes,
            overflow=overflow,
            symlinks=symlinks,
            filename=filename,
            span_id=self.id,
            tags=tags,
        )

    def artifact_stream(
        self,
        name: str,
        source: Iterable[bytes],
        *,
        media_type: str | None = None,
        max_bytes: int | None = None,
        overflow: ArtifactOverflow = ArtifactOverflow.FAIL,
        filename: str | None = None,
        tags: dict[str, Any] | None = None,
    ) -> ArtifactRef:
        return self._context.artifact_stream(
            name,
            source,
            media_type=media_type,
            max_bytes=max_bytes,
            overflow=overflow,
            filename=filename,
            span_id=self.id,
            tags=tags,
        )

    async def artifact_stream_async(
        self,
        name: str,
        source: AsyncIterable[bytes],
        *,
        media_type: str | None = None,
        max_bytes: int | None = None,
        overflow: ArtifactOverflow = ArtifactOverflow.FAIL,
        filename: str | None = None,
        tags: dict[str, Any] | None = None,
    ) -> ArtifactRef:
        return await self._context.artifact_stream_async(
            name,
            source,
            media_type=media_type,
            max_bytes=max_bytes,
            overflow=overflow,
            filename=filename,
            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,
        )
start
start() -> Span

Start this span without changing the active context stack.

Source code in src/autobench/runtime/context.py
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
def start(self) -> Span:
    """Start this span without changing the active context stack."""

    if self._record is not None:
        raise RuntimeError("Span has already started.")
    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,
        parent_span_id=self._parent_span_id,
    )
    return self

SpanKind

Bases: StrEnum

Source code in src/autobench/runtime/context.py
87
88
89
90
91
92
93
94
95
96
97
98
class SpanKind(StrEnum):
    AGENT = "agent"
    LLM = "llm"
    TOOL = "tool"
    RETRIEVER = "retriever"
    PARSER = "parser"
    WORKFLOW = "workflow"
    OPTIMIZATION = "optimization"
    CANDIDATE = "candidate"
    EVALUATION = "evaluation"
    REFLECTION = "reflection"
    CUSTOM = "custom"

SpanRecord

Bases: BaseModel

Source code in src/autobench/runtime/context.py
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
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/models.py
103
104
105
106
107
108
109
110
111
112
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/models.py
123
124
125
126
127
128
class EvaluationStatus(StrEnum):
    PASSED = "passed"
    FAILED = "failed"
    ERRORED = "errored"
    SKIPPED = "skipped"
    NOT_EVALUATED = "not_evaluated"

ExecutionCorrelation

Bases: BaseModel

Stable metadata that groups related benchmark invocations.

Source code in src/autobench/runtime/models.py
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
class ExecutionCorrelation(BaseModel):
    """Stable metadata that groups related benchmark invocations."""

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

    group_id: str | None = None
    attempt: int | None = Field(default=None, ge=1)
    phase: str | None = None
    parent_experiment_id: str | None = None
    resumed_from_experiment_id: str | None = None
    labels: dict[str, CorrelationLabel] = Field(default_factory=dict)

    @field_validator(
        "group_id",
        "phase",
        "parent_experiment_id",
        "resumed_from_experiment_id",
    )
    @classmethod
    def validate_identifier(cls, value: str | None) -> str | None:
        if value is not None and not value.strip():
            raise ValueError("correlation identifiers must not be blank")
        return value

    @field_validator("labels")
    @classmethod
    def validate_labels(
        cls,
        labels: dict[str, CorrelationLabel],
    ) -> dict[str, CorrelationLabel]:
        for key, value in labels.items():
            if not key.strip():
                raise ValueError("correlation label names must not be blank")
            if isinstance(value, float) and not isfinite(value):
                raise ValueError("correlation label values must be finite")
        return labels

ExperimentResult

Bases: BaseModel

Source code in src/autobench/runtime/models.py
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
class ExperimentResult(BaseModel):
    experiment_id: str
    benchmark_id: str
    plan: BenchmarkPlan
    runs: list[RunResult]
    environment: EnvironmentMetadata
    termination: ExperimentTermination = Field(default_factory=ExperimentTermination)
    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
    correlation: ExecutionCorrelation | None = None

    @model_validator(mode="after")
    def validate_run_correlation(self) -> ExperimentResult:
        if any(run.correlation != self.correlation for run in self.runs):
            raise ValueError("run correlation must match the experiment correlation")
        return self

    @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)

    @property
    def cancelled_count(self) -> int:
        return self.count_status(RunStatus.CANCELLED)

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

ExperimentStatus

Bases: StrEnum

Source code in src/autobench/runtime/models.py
131
132
133
134
class ExperimentStatus(StrEnum):
    COMPLETED = "completed"
    CANCELLED = "cancelled"
    ABORTED = "aborted"

ExperimentTermination

Bases: BaseModel

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

    status: ExperimentStatus = ExperimentStatus.COMPLETED
    partial: bool = False
    cross_run_derivation_complete: bool = True
    policies_complete: bool = True
    planned_run_ids: tuple[str, ...] = ()
    recorded_run_ids: tuple[str, ...] = ()
    missing_run_ids: tuple[str, ...] = ()
    error: ErrorRecord | None = None

    @model_validator(mode="after")
    def validate_run_id_sets(self) -> ExperimentTermination:
        planned = set(self.planned_run_ids)
        recorded = set(self.recorded_run_ids)
        missing = set(self.missing_run_ids)
        if len(planned) != len(self.planned_run_ids):
            raise ValueError("planned_run_ids must be unique")
        if len(recorded) != len(self.recorded_run_ids):
            raise ValueError("recorded_run_ids must be unique")
        if len(missing) != len(self.missing_run_ids):
            raise ValueError("missing_run_ids must be unique")
        if recorded & missing:
            raise ValueError("recorded_run_ids and missing_run_ids must not overlap")
        if planned and not recorded.issubset(planned):
            raise ValueError("recorded_run_ids must belong to planned_run_ids")
        if planned and not missing.issubset(planned):
            raise ValueError("missing_run_ids must belong to planned_run_ids")
        if self.status is not ExperimentStatus.COMPLETED and not self.partial:
            raise ValueError("cancelled and aborted experiments must be partial")
        if self.missing_run_ids and not self.partial:
            raise ValueError("experiments with missing runs must be partial")
        return self

MatrixRunSpec

Bases: BaseModel

Source code in src/autobench/runtime/models.py
173
174
175
176
177
178
179
180
181
class MatrixRunSpec(BaseModel):
    run_id: str
    benchmark_id: str
    experiment_id: str
    case_index: int
    variant_index: int
    case: Case
    variant: Variant
    correlation: ExecutionCorrelation | None = None

RunResult

Bases: BaseModel

Source code in src/autobench/runtime/models.py
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
class RunResult(BaseModel):
    run_id: str
    benchmark_id: str
    experiment_id: str
    case_id: str
    variant_id: str
    status: RunStatus
    evaluation_status: EvaluationStatus
    partial: bool = False
    end_reason: EndReason = EndReason.COMPLETED
    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)
    asset_uses: list[AssetUse] = Field(default_factory=list)
    parent_run_id: str | None = None
    error: ErrorRecord | None = None
    trace: Trace | None = None
    source_snapshots: tuple[SourceSnapshot, ...] = ()
    extensions: dict[str, JsonValue] = Field(default_factory=dict)
    correlation: ExecutionCorrelation | None = None

RunStatus

Bases: StrEnum

Source code in src/autobench/runtime/models.py
115
116
117
118
119
120
class RunStatus(StrEnum):
    PASSED = "passed"
    FAILED = "failed"
    ERRORED = "errored"
    SKIPPED = "skipped"
    CANCELLED = "cancelled"

ProgressDispatchError

Bases: AutobenchError

Raised after strict progress delivery fails and lifecycle cleanup completes.

Source code in src/autobench/runtime/progress.py
60
61
62
63
64
65
66
class ProgressDispatchError(AutobenchError):
    """Raised after strict progress delivery fails and lifecycle cleanup completes."""

    def __init__(self, failures: Sequence[ProgressHandlerFailure]) -> None:
        self.failures = tuple(failures)
        count = len(self.failures)
        super().__init__(f"Progress delivery failed for {count} handler invocation(s).")

ProgressErrorPolicy

Bases: StrEnum

Source code in src/autobench/runtime/progress.py
26
27
28
class ProgressErrorPolicy(StrEnum):
    STRICT = "strict"
    BEST_EFFORT = "best_effort"

ProgressEvent

Bases: BaseModel

Source code in src/autobench/runtime/progress.py
31
32
33
34
35
36
37
38
39
40
41
42
43
class ProgressEvent(BaseModel):
    kind: ProgressEventKind
    message: str
    sequence: int = Field(default=0, ge=0)
    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
    run_status: RunStatus | None = None
    experiment_status: ExperimentStatus | None = None
    data: dict[str, Any] = Field(default_factory=dict)

ProgressEventKind

Bases: StrEnum

Source code in src/autobench/runtime/progress.py
18
19
20
21
22
23
class ProgressEventKind(StrEnum):
    BENCHMARK_STARTED = "benchmark_started"
    BENCHMARK_FINISHED = "benchmark_finished"
    RUN_STARTED = "run_started"
    RUN_FINISHED = "run_finished"
    POLICY_VIOLATION = "policy_violation"

ProgressHandlerFailure dataclass

Source code in src/autobench/runtime/progress.py
49
50
51
52
53
54
@dataclass(frozen=True, slots=True)
class ProgressHandlerFailure:
    handler_index: int
    sequence: int
    event_kind: ProgressEventKind
    error: Exception

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
31
32
33
34
35
36
37
38
39
40
class TaskResult(BaseModel):
    output: Any = None
    status: TaskStatus
    partial: bool = False
    end_reason: EndReason = EndReason.COMPLETED
    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
23
24
25
26
27
28
class TaskStatus(StrEnum):
    PASSED = "passed"
    FAILED = "failed"
    ERRORED = "errored"
    SKIPPED = "skipped"
    CANCELLED = "cancelled"

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
37
38
39
class BenchmarkInfo(BaseModel):
    id: str = Field(min_length=1)
    description: str | None = None

BenchmarkSpec

Bases: BaseModel

Source code in src/autobench/spec/__init__.py
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
class BenchmarkSpec(BaseModel):
    benchmark: BenchmarkInfo
    capture: CapturePolicy | None = None
    execution: ExecutionSpec = Field(default_factory=ExecutionSpec)
    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

ExecutionSpec

Bases: BaseModel

Source code in src/autobench/spec/__init__.py
48
49
50
51
class ExecutionSpec(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    correlation: ExecutionCorrelation | None = None

TaskSpec

Bases: BaseModel

Source code in src/autobench/spec/__init__.py
42
43
44
45
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)

AssetContentRef

Bases: BaseModel

Source code in src/autobench/tracking/models.py
144
145
146
147
148
149
class AssetContentRef(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    asset_id: str = Field(min_length=1)
    version: str = Field(min_length=1)
    path: str = Field(min_length=1)

AssetDefinition

Bases: TrackedAsset

Source code in src/autobench/tracking/models.py
 95
 96
 97
 98
 99
100
101
102
103
104
class AssetDefinition(TrackedAsset):
    model_config = ConfigDict(frozen=True)

    representation: AssetRepresentation = AssetRepresentation.DEFINITION
    canonical_content: SerializedValue
    scope: str | None = None
    owner_locator: str | None = None
    source_locators: tuple[str, ...] = ()
    aliases: tuple[str, ...] = ()
    sensitivity: AssetSensitivity = AssetSensitivity.INTERNAL

AssetDiffRef

Bases: BaseModel

Source code in src/autobench/tracking/models.py
152
153
154
155
156
157
158
class AssetDiffRef(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    asset_id: str = Field(min_length=1)
    version: str = Field(min_length=1)
    parent_version: str = Field(min_length=1)
    path: str = Field(min_length=1)

AssetProvenance

Bases: BaseModel

Source code in src/autobench/tracking/models.py
28
29
30
31
32
33
34
35
class AssetProvenance(BaseModel):
    model_config = ConfigDict(frozen=True, extra="forbid")

    system: str = Field(min_length=1)
    key: str = Field(min_length=1)
    path: tuple[str | int, ...] = ()
    instrumentor: str | None = Field(default=None, min_length=1)
    instrumented_library_version: str | None = Field(default=None, min_length=1)

AssetRepresentation

Bases: StrEnum

Source code in src/autobench/tracking/models.py
17
18
19
class AssetRepresentation(StrEnum):
    DEFINITION = "definition"
    EFFECTIVE = "effective"

AssetSensitivity

Bases: StrEnum

Source code in src/autobench/tracking/models.py
22
23
24
25
class AssetSensitivity(StrEnum):
    PUBLIC = "public"
    INTERNAL = "internal"
    SENSITIVE = "sensitive"

AssetUse

Bases: BaseModel

One run-local use of a tracked asset version.

Source code in src/autobench/tracking/discovery.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
class AssetUse(BaseModel):
    """One run-local use of a tracked asset version."""

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

    asset_id: str = Field(min_length=1)
    version: str = Field(min_length=1)
    representation: AssetRepresentation
    source_locator: str = Field(min_length=1)
    scope: str | None = Field(default=None, min_length=1)
    span_id: str | None = Field(default=None, min_length=1)
    definition_asset_id: str | None = Field(default=None, min_length=1)
    definition_version: str | None = Field(default=None, min_length=1)
    provenance: AssetProvenance
    aliases: tuple[str, ...] = ()

AssetVersion

Bases: BaseModel

Source code in src/autobench/tracking/models.py
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
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
48
49
50
51
52
53
54
55
56
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
59
60
61
62
class ParamSchema(BaseModel):
    model_config = ConfigDict(frozen=True)

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

ToolAsset

Bases: TrackedAsset

Source code in src/autobench/tracking/models.py
107
108
109
110
111
112
113
114
115
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
85
86
87
88
89
90
91
92
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
161
162
163
164
165
166
167
168
169
170
171
172
173
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
 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
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
class TrackingRegistry:
    def __init__(self) -> None:
        self._lock = RLock()
        self._versions_by_target_id: dict[int, AssetVersion] = {}
        self._assets_by_target_id: dict[int, TrackedAsset] = {}
        self._assets_by_name: dict[str, TrackedAsset] = {}
        self._assets_by_id: dict[str, TrackedAsset] = {}
        self._asset_ids_by_locator: dict[str, str] = {}
        self._latest_versions_by_asset_id: dict[str, AssetVersion] = {}
        self._version_history: list[AssetVersion] = []

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

    @property
    def definitions(self) -> tuple[TrackedAsset, ...]:
        with self._lock:
            return tuple(self._assets_by_id.values())

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

    def write_assets(
        self,
        directory: Path,
        *,
        asset_ids: Collection[str] | None = None,
        content_path: Path | None = None,
        root_dir: Path | None = None,
    ) -> None:
        directory.mkdir(parents=True, exist_ok=True)
        active_content_path = (
            directory / "content.sqlite3" if content_path is None else content_path
        )
        active_root = directory if root_dir is None else root_dir
        try:
            content_reference = active_content_path.relative_to(active_root).as_posix()
        except ValueError as exc:
            raise ValueError("asset content must be stored inside the registry root") from exc
        with self._lock:
            selected_ids = None if asset_ids is None else set(asset_ids)
            assets = sorted(
                (
                    asset
                    for asset in self._assets_by_id.values()
                    if selected_ids is None or asset.id in selected_ids
                ),
                key=lambda asset: asset.id,
            )
            versions = [self._version_for_asset_id(asset.id) for asset in assets]
        with FileLock(directory / ".write.lock"):
            active_content_path.parent.mkdir(parents=True, exist_ok=True)
            with AssetContentStore(active_content_path) as content_store:
                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
                    existing_asset = existing.get("asset") if isinstance(existing, dict) else None
                    current_version = (
                        existing_asset.get("current_version")
                        if isinstance(existing_asset, dict)
                        else None
                    )
                    previous_version = current_version if isinstance(current_version, str) else None
                    previous_snapshot = (
                        content_store.content(asset_id=asset.id, version=previous_version)
                        if previous_version is not None
                        else None
                    )
                    snapshot = _asset_version_snapshot(asset)
                    content_store.write_content(
                        asset_id=asset.id,
                        version=version.version,
                        content_hash=version.content_hash,
                        snapshot=snapshot,
                    )
                    changes = _asset_version_changes(previous_snapshot, snapshot)
                    diff = changes.get("diff")
                    if previous_version is not None and isinstance(diff, str):
                        content_store.write_diff(
                            asset_id=asset.id,
                            version=version.version,
                            parent_version=previous_version,
                            diff=diff,
                        )
                    _atomic_dump_yaml(
                        asset_to_yaml_view(
                            asset,
                            version,
                            existing=existing,
                            previous_snapshot=previous_snapshot,
                            content_path=content_reference,
                        ),
                        asset_path,
                        schema_name="asset",
                    )
            index_path = directory / "index.yaml"
            index_view = asset_index_to_yaml_view(assets, versions)
            if index_path.exists():
                existing_index = load_yaml(index_path)
                if isinstance(existing_index, dict) and isinstance(
                    existing_index.get("assets"), dict
                ):
                    index_view["assets"] = {
                        **existing_index["assets"],
                        **index_view["assets"],
                    }
            _atomic_dump_yaml(
                index_view,
                index_path,
                schema_name="asset_index",
            )

    def has_asset(self, asset_id: str) -> bool:
        with self._lock:
            return asset_id in self._assets_by_id

    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_by_id(self, asset_id: str) -> TrackedAsset:
        with self._lock:
            try:
                return self._assets_by_id[asset_id]
            except KeyError as exc:
                raise KeyError(f"Unknown Autobench asset: {asset_id}") from exc

    def version_by_asset_id(self, asset_id: str) -> AssetVersion:
        with self._lock:
            return self._version_for_asset_id(asset_id)

    def resolve_locator(self, locator: str) -> TrackedAsset:
        with self._lock:
            try:
                asset_id = self._asset_ids_by_locator[locator]
            except KeyError as exc:
                raise KeyError(f"Unknown Autobench asset locator: {locator}") from exc
            return self._assets_by_id[asset_id]

    def register_candidate(
        self,
        candidate: AssetCandidate,
        *,
        span_id: str | None = None,
    ) -> RegisteredAsset:
        with self._lock:
            resolved = self._resolve_candidate(candidate)
            if resolved is None:
                asset = self._asset_from_candidate(candidate)
                identity = self._candidate_identity(candidate)
                if identity is not None:
                    asset = asset.model_copy(update={"id": identity.id})
                    if isinstance(asset, AssetDefinition) and isinstance(identity, AssetDefinition):
                        asset = asset.model_copy(
                            update={
                                "source_locators": tuple(
                                    dict.fromkeys(
                                        (
                                            *identity.source_locators,
                                            *asset.source_locators,
                                        )
                                    )
                                ),
                                "aliases": tuple(
                                    dict.fromkeys((*identity.aliases, *asset.aliases))
                                ),
                            }
                        )
                asset_content = asset.model_dump(mode="python")
                if isinstance(asset, AssetDefinition):
                    for field_name in (
                        "canonical_content",
                        "source_locators",
                        "aliases",
                        "sensitivity",
                    ):
                        asset_content.pop(field_name)
                content_hash = _hash_serialized(
                    {
                        "asset": asset_content,
                        "content_fingerprint": (
                            candidate.content_fingerprint
                            or _hash_serialized(candidate.canonical_content)
                        ),
                    }
                )
                previous = self._latest_versions_by_asset_id.get(asset.id)
                version = AssetVersion(
                    asset_id=asset.id,
                    version=content_hash[:12],
                    content_hash=content_hash,
                    source_hash=(
                        None
                        if candidate.python_target is None
                        else _source_hash(candidate.python_target)
                    ),
                    source_path=(
                        None
                        if candidate.python_target is None
                        else _source_path(candidate.python_target)
                    ),
                    parent_version=(
                        None
                        if previous is None or previous.version == content_hash[:12]
                        else previous.version
                    ),
                    metadata={
                        "representation": candidate.representation.value,
                        "source_locator": candidate.source_locator,
                    },
                )
                self._register(candidate.python_target, asset, version)
            else:
                asset, version = resolved

            locators = (candidate.source_locator, *candidate.aliases)
            for locator in locators:
                self._asset_ids_by_locator[locator] = asset.id

            definition_asset_id: str | None = None
            definition_version: str | None = None
            if candidate.definition_locator is not None:
                definition = self._asset_for_locator(candidate.definition_locator)
                if definition is not None:
                    definition_asset_id = definition.id
                    definition_version = self._version_for_asset_id(definition.id).version

            return RegisteredAsset(
                asset=asset,
                version=version,
                use=AssetUse(
                    asset_id=asset.id,
                    version=version.version,
                    representation=candidate.representation,
                    source_locator=candidate.source_locator,
                    scope=candidate.scope,
                    span_id=span_id,
                    definition_asset_id=definition_asset_id,
                    definition_version=definition_version,
                    provenance=candidate.provenance,
                    aliases=candidate.aliases,
                ),
            )

    def _resolve_candidate(
        self,
        candidate: AssetCandidate,
    ) -> tuple[TrackedAsset, AssetVersion] | None:
        if candidate.representation is AssetRepresentation.DEFINITION:
            target = candidate.python_target
            if target is not None:
                target_asset = self._assets_by_target_id.get(id(target))
                if target_asset is not None:
                    return target_asset, self._version_for_asset_id(target_asset.id)
                python_locator = _python_locator(target)
                if python_locator is not None:
                    located = self._asset_for_locator(python_locator)
                    if located is not None:
                        return located, self._version_for_asset_id(located.id)
        return None

    def _candidate_identity(self, candidate: AssetCandidate) -> TrackedAsset | None:
        if candidate.explicit_asset_id is not None:
            explicit = self._assets_by_id.get(candidate.explicit_asset_id)
            if explicit is not None:
                return explicit
        for locator in (candidate.source_locator, *candidate.aliases):
            located = self._asset_for_locator(locator)
            if located is not None:
                return located
        return None

    def _asset_for_locator(self, locator: str) -> TrackedAsset | None:
        asset_id = self._asset_ids_by_locator.get(locator)
        return None if asset_id is None else self._assets_by_id[asset_id]

    def _asset_from_candidate(self, candidate: AssetCandidate) -> TrackedAsset:
        asset_id = candidate.explicit_asset_id or candidate.source_locator
        target = candidate.python_target
        metadata = dict(candidate.metadata)
        metadata["discovered"] = True
        if (
            candidate.representation is AssetRepresentation.DEFINITION
            and isinstance(target, type)
            and candidate.kind in {"output_schema", "type"}
        ):
            return _build_type_asset(
                target,
                name=candidate.name,
                semantic_type=candidate.semantic_type,
                metadata=metadata,
            ).model_copy(update={"id": asset_id})
        if (
            candidate.representation is AssetRepresentation.DEFINITION
            and callable(target)
            and candidate.kind == "tool"
        ):
            return _build_tool_asset(
                target,
                name=candidate.name,
                semantic_type=candidate.semantic_type,
                metadata=metadata,
                registry=self,
            ).model_copy(update={"id": asset_id})
        return AssetDefinition(
            id=asset_id,
            kind=candidate.kind,
            name=candidate.name,
            semantic_type=candidate.semantic_type,
            metadata=metadata,
            representation=candidate.representation,
            canonical_content=candidate.canonical_content,
            scope=candidate.scope,
            owner_locator=candidate.owner_locator,
            source_locators=(candidate.source_locator,),
            aliases=candidate.aliases,
            sensitivity=candidate.sensitivity,
        )

    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
        version_metadata = dict(prompt_metadata)
        version_metadata.pop("raw")
        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=version_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:
        with self._lock:
            if target is not None:
                target_id = id(target)
                self._assets_by_target_id[target_id] = asset
                self._versions_by_target_id[target_id] = version
                python_locator = _python_locator(target)
                if python_locator is not None:
                    self._asset_ids_by_locator[python_locator] = asset.id
            self._assets_by_name[asset.name] = asset
            self._assets_by_id[asset.id] = asset
            self._asset_ids_by_locator[asset.id] = asset.id
            self._latest_versions_by_asset_id[asset.id] = version
            if not any(
                item.asset_id == version.asset_id and item.version == version.version
                for item in self._version_history
            ):
                self._version_history.append(version)

TypeAsset

Bases: TrackedAsset

Source code in src/autobench/tracking/models.py
118
119
120
121
122
123
124
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,
        }
    )

generate_dataset async

generate_dataset(
    generator: CaseGenerator,
    request: CaseGeneratorInput,
    *,
    generator_id: str,
    dataset_id: str,
    version: str | None = None,
    metadata: dict[str, SerializedValue] | None = None,
) -> GenerationResult
Source code in src/autobench/data/generation.py
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
async def generate_dataset(
    generator: CaseGenerator,
    request: CaseGeneratorInput,
    *,
    generator_id: str,
    dataset_id: str,
    version: str | None = None,
    metadata: dict[str, SerializedValue] | None = None,
) -> GenerationResult:
    if not generator_id.strip():
        raise GenerationError("Generator id must not be blank.")
    if not dataset_id.strip():
        raise GenerationError("Generated dataset id must not be blank.")
    started_at = datetime.now(UTC)
    try:
        generated = generator(request)
        batch = await generated if isawaitable(generated) else generated
    except Exception as exc:
        raise GenerationError(f"Case generator {generator_id!r} failed: {exc}") from exc
    if not isinstance(batch, GeneratedCaseBatch):
        raise GenerationError("Case generators must return GeneratedCaseBatch.")

    reviews = {review.case_id: review for review in batch.reviews}
    normalized_cases: list[Case] = []
    generated_records: list[GeneratedCaseRecord] = []
    for case in batch.cases:
        review = reviews.get(case.id)
        if review is None:
            review = _review_from_case(case)
        normalized = mark_generated_case(
            case,
            generator_asset_version=batch.generator_asset_version,
            model_provider=batch.model_provider,
            model_name=batch.model_name,
            review_status=review.status,
            rejection_reason=review.rejection_reason,
        )
        content_hash = generated_case_content_hash(normalized)
        case_metadata = dict(normalized.metadata)
        case_metadata["content_hash"] = content_hash
        normalized = normalized.model_copy(update={"metadata": case_metadata})
        generated_records.append(
            GeneratedCaseRecord(
                case=normalized,
                review_status=review.status,
                rejection_reason=review.rejection_reason,
                content_hash=content_hash,
            )
        )
        if review.status is not ReviewStatus.REJECTED:
            normalized_cases.append(normalized)

    normalized_batch = batch.model_copy(
        update={"cases": tuple(record.case for record in generated_records)}
    )
    request_hash = generation_request_hash(request)
    dataset: DatasetSpec | None = None
    frozen_hash: str | None = None
    if normalized_batch.complete:
        dataset_metadata = dict(metadata or {})
        dataset_metadata["generation"] = {
            "generator": generator_id,
            "request_hash": request_hash,
            "determinism": normalized_batch.determinism.value,
        }
        dataset = DatasetSpec(
            id=dataset_id,
            version=version,
            metadata=dataset_metadata,
            cases=normalized_cases,
        )
        frozen_hash = dataset_content_hash(dataset)

    return GenerationResult(
        generator_id=generator_id,
        started_at=started_at,
        completed_at=datetime.now(UTC),
        request=request,
        request_hash=request_hash,
        batch=normalized_batch,
        generated_cases=tuple(generated_records),
        dataset=dataset,
        dataset_hash=frozen_hash,
    )

generate_dataset_sync

generate_dataset_sync(
    generator: CaseGenerator,
    request: CaseGeneratorInput,
    *,
    generator_id: str,
    dataset_id: str,
    version: str | None = None,
    metadata: dict[str, SerializedValue] | None = None,
) -> GenerationResult
Source code in src/autobench/data/generation.py
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
def generate_dataset_sync(
    generator: CaseGenerator,
    request: CaseGeneratorInput,
    *,
    generator_id: str,
    dataset_id: str,
    version: str | None = None,
    metadata: dict[str, SerializedValue] | None = None,
) -> GenerationResult:
    return run_sync(
        generate_dataset(
            generator,
            request,
            generator_id=generator_id,
            dataset_id=dataset_id,
            version=version,
            metadata=metadata,
        )
    )

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,
    determinism: GenerationDeterminism = GenerationDeterminism.UNKNOWN,
    usage: GenerationUsage | None = None,
    cost: GenerationCost | None = None,
) -> GeneratedCaseBatch
Source code in src/autobench/data/generation.py
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
def generated_batch_from_cases(
    cases: list[Case],
    *,
    generator_asset_version: str | None = None,
    model_provider: str | None = None,
    model_name: str | None = None,
    determinism: GenerationDeterminism = GenerationDeterminism.UNKNOWN,
    usage: GenerationUsage | None = None,
    cost: GenerationCost | 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,
        determinism=determinism,
        usage=usage or GenerationUsage(),
        cost=cost,
        cases=marked_cases,
    )

generated_case_content_hash

generated_case_content_hash(case: Case) -> str
Source code in src/autobench/data/generation.py
374
375
376
377
378
379
def generated_case_content_hash(case: Case) -> str:
    payload = case.model_dump(mode="json", exclude_none=True)
    metadata = dict(payload.get("metadata", {}))
    metadata.pop("content_hash", None)
    payload["metadata"] = metadata
    return _content_hash(payload)

generation_request_from_yaml_view

generation_request_from_yaml_view(
    raw: Any,
) -> CaseGeneratorInput
Source code in src/autobench/data/generation.py
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
def generation_request_from_yaml_view(raw: Any) -> CaseGeneratorInput:
    if not isinstance(raw, dict):
        raise GenerationError("Generation request YAML must contain a mapping.")
    generation = raw.get("generation", raw)
    if not isinstance(generation, dict):
        raise GenerationError("generation must be a mapping.")
    request = generation.get("request", generation)
    if not isinstance(request, dict):
        raise GenerationError("generation.request must be a mapping.")
    payload = dict(request)
    prompt = payload.pop("prompt", None)
    if prompt is not None:
        if not isinstance(prompt, dict):
            raise GenerationError("generation.request.prompt must be a mapping.")
        payload["prompt"] = prompt.get("content")
        payload["prompt_asset_version"] = prompt.get("asset_version")
    try:
        return CaseGeneratorInput.model_validate(payload)
    except ValidationError as exc:
        raise GenerationError(f"Invalid generation request: {exc}") from exc

generation_request_hash

generation_request_hash(request: CaseGeneratorInput) -> str
Source code in src/autobench/data/generation.py
370
371
def generation_request_hash(request: CaseGeneratorInput) -> str:
    return _content_hash(request.model_dump(mode="json", exclude_none=True))

generation_request_to_yaml_view

generation_request_to_yaml_view(
    request: CaseGeneratorInput,
) -> dict[str, Any]
Source code in src/autobench/data/generation.py
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
def generation_request_to_yaml_view(request: CaseGeneratorInput) -> dict[str, Any]:
    prompt = None
    if request.prompt is not None or request.prompt_asset_version is not None:
        prompt = {
            "content": request.prompt,
            "asset_version": request.prompt_asset_version,
        }
    request_view = {
        "seed": request.seed,
        "prompt": prompt,
        "settings": request.settings or None,
        "metadata": request.metadata or None,
        "seed_cases": [case_to_yaml_view(case) for case in request.seed_cases] or None,
    }
    return {
        "generation": {
            "request": {key: value for key, value in request_view.items() if value is not None}
        }
    }

generation_result_to_yaml_view

generation_result_to_yaml_view(
    result: GenerationResult,
    *,
    dataset_path: str | None = None,
) -> dict[str, Any]
Source code in src/autobench/data/generation.py
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
def generation_result_to_yaml_view(
    result: GenerationResult,
    *,
    dataset_path: str | None = None,
) -> dict[str, Any]:
    prompt_view = None
    if result.request.prompt is not None or result.request.prompt_asset_version is not None:
        prompt_view = {
            "sha256": (
                None
                if result.request.prompt is None
                else sha256(result.request.prompt.encode("utf-8")).hexdigest()
            ),
            "asset_version": result.request.prompt_asset_version,
        }
    output_view = {
        "dataset": (
            None
            if result.dataset is None
            else {
                "id": result.dataset.id,
                "version": result.dataset.version,
                "sha256": result.dataset_hash,
                "path": dataset_path,
            }
        ),
        "generated": len(result.generated_cases),
        "included": 0 if result.dataset is None else len(result.dataset.cases),
        "rejected": sum(
            1
            for generated_case in result.generated_cases
            if generated_case.review_status is ReviewStatus.REJECTED
        ),
    }
    return {
        "record": {"type": "generation", "version": GENERATION_RECORD_VERSION},
        "generation": {
            "status": "complete" if result.batch.complete else "incomplete",
            "reason": result.batch.incomplete_reason,
            "started_at": result.started_at.isoformat(),
            "completed_at": result.completed_at.isoformat(),
            "determinism": result.batch.determinism.value,
            "generator": {
                "id": result.generator_id,
                "asset_version": result.batch.generator_asset_version,
                "provider": result.batch.model_provider,
                "model": result.batch.model_name,
            },
            "request": {
                "sha256": result.request_hash,
                "seed": result.request.seed,
                "prompt": prompt_view,
                "settings": result.request.settings or None,
                "metadata": result.request.metadata or None,
                "seed_cases": [case_to_yaml_view(case) for case in result.request.seed_cases],
            },
            "usage": result.batch.usage.model_dump(mode="json"),
            "cost": (
                None if result.batch.cost is None else result.batch.cost.model_dump(mode="json")
            ),
            "output": output_view,
            "cases": [
                {
                    "id": generated_case.case.id,
                    "status": generated_case.review_status.value,
                    "rejection_reason": generated_case.rejection_reason,
                    "sha256": generated_case.content_hash,
                    "case": case_to_yaml_view(generated_case.case),
                }
                for generated_case in result.generated_cases
            ],
        },
    }

load_generation_request

load_generation_request(path: Path) -> CaseGeneratorInput
Source code in src/autobench/data/generation.py
425
426
def load_generation_request(path: Path) -> CaseGeneratorInput:
    return generation_request_from_yaml_view(load_yaml(path))

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,
    rejection_reason: str | None = None,
) -> Case
Source code in src/autobench/data/generation.py
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
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,
    rejection_reason: str | None = None,
) -> Case:
    metadata = dict(case.metadata)
    metadata["source"] = "synthetic"
    metadata["review_status"] = review_status.value
    if rejection_reason is not None:
        metadata["rejection_reason"] = rejection_reason
    else:
        metadata.pop("rejection_reason", None)
    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})

resolve_case_generator

resolve_case_generator(
    target: str, *, search_paths: tuple[str, ...] = ()
) -> CaseGenerator
Source code in src/autobench/data/generation.py
362
363
364
365
366
367
def resolve_case_generator(
    target: str,
    *,
    search_paths: tuple[str, ...] = (),
) -> CaseGenerator:
    return cast(CaseGenerator, resolve_python_callable(target, search_paths=search_paths))

write_generation_result

write_generation_result(
    result: GenerationResult,
    output_path: Path,
    *,
    force: bool = False,
    durability: RecordDurability = "atomic",
) -> GenerationWriteResult
Source code in src/autobench/data/generation.py
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
def write_generation_result(
    result: GenerationResult,
    output_path: Path,
    *,
    force: bool = False,
    durability: RecordDurability = "atomic",
) -> GenerationWriteResult:
    manifest_path = output_path.with_name(
        f"{output_path.stem}.generation.yaml"
        if result.batch.complete
        else f"{output_path.stem}.incomplete.yaml"
    )
    targets = [manifest_path]
    if result.batch.complete:
        targets.append(output_path)
    elif output_path.exists():
        raise GenerationError(
            f"Incomplete generation did not replace existing dataset: {output_path}"
        )
    existing = [path for path in targets if path.exists()]
    if existing and not force:
        raise GenerationError(f"Generation output already exists: {existing[0]}")

    manifest = generation_result_to_yaml_view(
        result,
        dataset_path=output_path.name if result.batch.complete else None,
    )
    atomic_write_text(
        manifest_path,
        dump_yaml(_compact(manifest), schema_name="generation"),
        durability=durability,
    )
    if result.batch.complete:
        if result.dataset is None:
            raise GenerationError("Complete generation result is missing its dataset.")
        atomic_write_text(
            output_path,
            dump_yaml(dataset_to_yaml_view(result.dataset), schema_name="dataset"),
            durability=durability,
        )
    return GenerationWriteResult(
        complete=result.batch.complete,
        dataset_path=output_path if result.batch.complete else None,
        manifest_path=manifest_path,
    )

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

export_otlp

export_otlp(
    experiment: ExperimentRecord,
    runs: Sequence[RunRecord],
    *,
    settings: OTLPSettings | None = None,
    exporter: SpanExporter | None = None,
) -> OTLPExportResult

Export validated immutable record models without mutating their ABP evidence.

Source code in src/autobench/exporters/otlp.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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
def export_otlp(
    experiment: ExperimentRecord,
    runs: Sequence[RunRecord],
    *,
    settings: OTLPSettings | None = None,
    exporter: SpanExporter | None = None,
) -> OTLPExportResult:
    """Export validated immutable record models without mutating their ABP evidence."""

    if len(runs) != experiment.run_count:
        raise OTLPExportError(
            f"Experiment declares {experiment.run_count} runs but {len(runs)} were supplied."
        )
    run_ids: set[str] = set()
    for run in runs:
        if run.run_id in run_ids:
            raise OTLPExportError(f"Duplicate run supplied for OTLP export: {run.run_id}")
        run_ids.add(run.run_id)
        if run.experiment_id != experiment.experiment_id:
            raise OTLPExportError(f"Run {run.run_id!r} belongs to another experiment.")
        if run.benchmark_id != experiment.benchmark_id:
            raise OTLPExportError(f"Run {run.run_id!r} belongs to another benchmark.")
        if run.correlation != experiment.correlation:
            raise OTLPExportError(f"Run {run.run_id!r} has inconsistent execution correlation.")

    try:
        from autobench.exporters._otel import export_records
    except ModuleNotFoundError as exc:
        if exc.name is None or not exc.name.startswith("opentelemetry"):
            raise
        raise OTLPExportError(
            "OTLP export requires the 'autobench[otlp]' optional dependency."
        ) from exc
    try:
        return export_records(
            experiment,
            tuple(runs),
            OTLPSettings() if settings is None else settings,
            exporter,
        )
    except OTLPExportError:
        raise
    except Exception as exc:
        raise OTLPExportError(f"Could not map Autobench evidence to OTLP spans: {exc}") from exc

export_record_otlp

export_record_otlp(
    record_dir: Path,
    *,
    settings: OTLPSettings | None = None,
    exporter: SpanExporter | None = None,
) -> OTLPExportResult

Load one immutable record directory and export its evidence through OTLP.

Source code in src/autobench/exporters/otlp.py
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
def export_record_otlp(
    record_dir: Path,
    *,
    settings: OTLPSettings | None = None,
    exporter: SpanExporter | None = None,
) -> OTLPExportResult:
    """Load one immutable record directory and export its evidence through OTLP."""

    experiment = load_experiment_record(record_dir)
    runs = tuple(
        load_run_record(record_dir / run_path, root_dir=record_dir)
        for run_path in experiment.run_paths
    )
    return export_otlp(
        experiment,
        runs,
        settings=settings,
        exporter=exporter,
    )

check_package_compatibility

check_package_compatibility(
    info: InstrumentorInfo,
) -> Compatibility
Source code in src/autobench/instrumentation/manager.py
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
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
290
291
292
293
294
295
296
297
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
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
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(discovery=config.assets)
        if isinstance(config, PydanticGEPAInstrumentation):
            from autobench.instrumentation.pydantic_gepa import PydanticGEPA

            return PydanticGEPA(detail=config.detail, discovery=config.assets)
        if isinstance(config, OpenAIInstrumentation):
            from autobench.instrumentation.openai import OpenAIClient

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

            return OpenAIAgents(discovery=config.assets)

        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
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 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
                selected_config = config
                if auto.assets is not None and isinstance(
                    config,
                    (
                        PydanticAIInstrumentation,
                        PydanticGEPAInstrumentation,
                        OpenAIInstrumentation,
                        OpenAIAgentsInstrumentation,
                    ),
                ):
                    selected_config = config.model_copy(update={"assets": auto.assets})
                instrumentor, status = _inspect_instrumentor(
                    selected_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
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
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
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
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/views.py
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
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"))
    termination = experiment.get("termination")
    if termination is None:
        termination = {}
    if not isinstance(termination, dict):
        raise RecordingError("experiment.termination must be a mapping")
    post_processing = termination.get("post_processing", {})
    if post_processing is None:
        post_processing = {}
    if not isinstance(post_processing, dict):
        raise RecordingError("experiment.termination.post_processing must be a mapping")

    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),
            "termination": {
                "status": termination.get("status", "completed"),
                "partial": termination.get("partial", False),
                "cross_run_derivation_complete": post_processing.get("cross_run_derivation", True),
                "policies_complete": post_processing.get("policies", True),
                "planned_run_ids": termination.get("planned_runs", []),
                "recorded_run_ids": termination.get("recorded_runs", []),
                "missing_run_ids": termination.get("missing_runs", []),
                "error": termination.get("error"),
            },
            "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")),
            "manifest_path": raw.get("manifest"),
            "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),
            "cancelled_count": runs.get("cancelled", 0),
            "correlation": experiment.get("correlation"),
        }
    )
    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/views.py
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
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,
                "correlation": (
                    None
                    if record.correlation is None
                    else record.correlation.model_dump(mode="json", exclude_none=True)
                ),
                "termination": {
                    "status": record.termination.status.value,
                    "partial": record.termination.partial,
                    "post_processing": {
                        "cross_run_derivation": record.termination.cross_run_derivation_complete,
                        "policies": record.termination.policies_complete,
                    },
                    "planned_runs": list(record.termination.planned_run_ids),
                    "recorded_runs": list(record.termination.recorded_run_ids),
                    "missing_runs": list(record.termination.missing_run_ids),
                    "error": (
                        None
                        if record.termination.error is None
                        else record.termination.error.model_dump(mode="json")
                    ),
                },
            },
            "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,
                "cancelled": record.cancelled_count,
                "paths": list(record.run_paths),
            },
            "manifest": record.manifest_path,
            "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/views.py
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
def experiment_summary(record: ExperimentRecord) -> dict[str, Any]:
    return {
        "record": {
            "type": "summary",
            "version": record.record_version,
        },
        "summary": _compact(
            {
                "experiment": record.experiment_id,
                "benchmark": record.benchmark_id,
                "status": record.termination.status.value,
                "partial": record.termination.partial,
                "correlation": (
                    None
                    if record.correlation is None
                    else record.correlation.model_dump(mode="json", exclude_none=True)
                ),
            }
        ),
        "runs": {
            "count": record.run_count,
            "passed": record.passed_count,
            "failed": record.failed_count,
            "errored": record.errored_count,
            "skipped": record.skipped_count,
            "cancelled": record.cancelled_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,
    asset_registry: TrackingRegistry = track,
    durability: RecordDurability = "atomic",
) -> ExperimentRecord
Source code in src/autobench/records/recording.py
 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
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,
    asset_registry: TrackingRegistry = track,
    durability: RecordDurability = "atomic",
) -> ExperimentRecord:
    if trace_inline_limit_bytes < 1:
        raise ValueError("trace_inline_limit_bytes must be at least 1")
    if output_dir.is_symlink() or (
        output_dir.exists() and (not output_dir.is_dir() or any(output_dir.iterdir()))
    ):
        raise RecordingError(f"Record target already exists: {output_dir}")

    targets = validate_logical_targets(
        _logical_record_targets(result, trace_inline_limit_bytes=trace_inline_limit_bytes)
    )
    staging = create_temporary_record_directory(output_dir)
    try:
        artifacts_dir = staging / "artifacts"
        referenced_asset_ids = {
            version.asset_id for run in result.runs for version in run.asset_versions
        }
        persisted_asset_ids = {
            asset_id for asset_id in referenced_asset_ids if asset_registry.has_asset(asset_id)
        }
        if persisted_asset_ids:
            asset_registry.write_assets(
                staging / "assets",
                asset_ids=persisted_asset_ids,
                content_path=artifacts_dir / "asset-content.sqlite3",
                root_dir=staging,
            )

        run_paths: list[str] = []
        for run in result.runs:
            run_record = run_record_from_result(
                run,
                artifacts_dir=artifacts_dir,
                root_dir=staging,
                semantic_registry_version=result.semantic_registry.version,
                trace_inline_limit_bytes=trace_inline_limit_bytes,
                durability=durability,
            )
            run_path = case_run_record_path(staging, run)
            _write_yaml(
                run_record_to_yaml_view(run_record),
                run_path,
                schema_name="run_record",
                durability=durability,
            )
            run_paths.append(run_path.relative_to(staging).as_posix())

        termination = _recorded_termination(result)
        record = ExperimentRecord(
            experiment_id=result.experiment_id,
            benchmark_id=result.benchmark_id,
            plan=result.plan,
            environment=_recorded_environment(result.environment, path_root=path_root),
            termination=termination,
            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()
            ),
            manifest_path="manifest.yaml",
            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,
            cancelled_count=result.cancelled_count,
            correlation=result.correlation,
        )
        _write_yaml(
            experiment_record_to_yaml_view(record),
            staging / "experiment.yaml",
            schema_name="experiment",
            durability=durability,
        )
        _write_yaml(
            experiment_summary(record),
            staging / "summary.yaml",
            schema_name="summary",
            durability=durability,
        )
        manifest = build_manifest(staging, experiment_id=result.experiment_id, targets=targets)
        _write_yaml(
            manifest_to_yaml_view(manifest),
            staging / "manifest.yaml",
            schema_name="manifest",
            durability=durability,
        )
        validate_manifest(staging, manifest)
        publish_record_directory(staging, output_dir, durability=durability)
        return record
    finally:
        remove_temporary_record_directory(staging)

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,
    durability: RecordDurability = "atomic",
    recorded_payloads: RecordedRunPayloads | None = None,
    prepared_artifacts: Mapping[str, Path] | None = None,
) -> RunRecord
Source code in src/autobench/records/recording.py
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
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,
    durability: RecordDurability = "atomic",
    recorded_payloads: RecordedRunPayloads | None = None,
    prepared_artifacts: Mapping[str, Path] | None = None,
) -> RunRecord:
    if trace_inline_limit_bytes < 1:
        raise ValueError("trace_inline_limit_bytes must be at least 1")
    recorded_artifacts = (
        list(recorded_payloads.artifacts)
        if recorded_payloads is not None
        else [
            record_artifact(
                artifact,
                artifacts_dir=artifacts_dir,
                root_dir=root_dir,
                run_id=run.run_id,
                durability=durability,
                prepared_path=(
                    None if prepared_artifacts is None else prepared_artifacts.get(artifact.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)
    if recorded_payloads is None:
        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,
            durability=durability,
        )
    else:
        trace = recorded_payloads.trace
        trace_artifact = recorded_payloads.trace_artifact
    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,
        partial=run.partial,
        end_reason=run.end_reason,
        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),
        asset_uses=tuple(run.asset_uses),
        parent_run_id=run.parent_run_id,
        source_snapshots=run.source_snapshots,
        errors=tuple(errors),
        error=run.error,
        extensions=run.extensions,
        correlation=run.correlation,
    )

load_experiment_record

load_experiment_record(run_dir: Path) -> ExperimentRecord
Source code in src/autobench/records/replay.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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)
    record = ExperimentRecord.model_validate(raw)
    if record.manifest_path is not None:
        resolved_root = run_dir.resolve()
        manifest_path = (resolved_root / record.manifest_path).resolve()
        if not manifest_path.is_relative_to(resolved_root):
            raise ReplayError("Manifest path must stay inside the experiment directory.")
        try:
            manifest_raw = load_yaml(manifest_path)
            if isinstance(manifest_raw, dict):
                manifest_raw = manifest_payload_from_yaml_view(manifest_raw)
            manifest = RecordManifest.model_validate(manifest_raw)
            if manifest.experiment_id != record.experiment_id:
                raise ReplayError("Manifest experiment identity does not match experiment record.")
            validate_manifest(run_dir, manifest)
        except ReplayError:
            raise
        except (AutobenchError, OSError, ValueError) as exc:
            raise ReplayError(f"Invalid experiment manifest: {manifest_path}") from exc
    return record

load_run_record

load_run_record(
    path: Path, *, root_dir: Path | None = None
) -> RunRecord
Source code in src/autobench/records/replay.py
 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
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)
    active_root = _record_root(path) if root_dir is None else root_dir
    resolved_root = active_root.resolve()
    for artifact in record.artifacts:
        if artifact.sha256 is None or artifact.byte_count is None:
            continue
        if not isinstance(artifact.value, str):
            raise ReplayError(f"Artifact payload path must be a string: {artifact.id}")
        payload_path = (resolved_root / artifact.value).resolve()
        if not payload_path.is_relative_to(resolved_root):
            raise ReplayError(f"Artifact payload path escapes the experiment: {artifact.id}")
        if not payload_path.is_file():
            raise ReplayError(f"Artifact payload does not exist: {artifact.id}")
        digest, byte_count = hash_and_size(payload_path)
        if digest != artifact.sha256:
            raise ReplayError(f"Artifact payload hash mismatch: {artifact.id}")
        if byte_count != artifact.byte_count:
            raise ReplayError(f"Artifact payload byte count mismatch: {artifact.id}")
    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.")
    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
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
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
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,
        termination=record.termination,
        report_spec_data=record.report_spec_data,
        semantic_registry=record.semantic_registry,
        spec_snapshot=record.spec_snapshot,
        spec_hash=record.spec_hash,
        correlation=record.correlation,
    )

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
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
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,
            ),
        }
    )

archive_staging

archive_staging(
    path: Path,
    destination: Path,
    *,
    durability: RecordDurability = "atomic",
) -> Path
Source code in src/autobench/records/staging.py
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
def archive_staging(
    path: Path,
    destination: Path,
    *,
    durability: RecordDurability = "atomic",
) -> Path:
    load_staging_state(path)
    temporary = create_temporary_record_directory(destination)
    try:
        shutil.copytree(path, temporary, dirs_exist_ok=True)
        publish_record_directory(temporary, destination, durability=durability)
    finally:
        remove_temporary_record_directory(temporary)
    return destination

discard_staging

discard_staging(path: Path) -> None
Source code in src/autobench/records/staging.py
1662
1663
1664
def discard_staging(path: Path) -> None:
    load_staging_state(path)
    shutil.rmtree(path)

finalize_staging

finalize_staging(
    path: Path,
    output_dir: Path,
    *,
    allow_partial: bool = False,
    durability: RecordDurability = "atomic",
) -> ExperimentRecord
Source code in src/autobench/records/staging.py
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
def finalize_staging(
    path: Path,
    output_dir: Path,
    *,
    allow_partial: bool = False,
    durability: RecordDurability = "atomic",
) -> ExperimentRecord:
    recovered = recover_staging(path)
    complete_by_id = {run.run_id: run for run in recovered.runs}
    latest_checkpoints: dict[str, PartialRunSnapshot] = {}
    for checkpoint in recovered.checkpoints:
        current = latest_checkpoints.get(checkpoint.run_id)
        if current is None or checkpoint.captured_at > current.captured_at:
            latest_checkpoints[checkpoint.run_id] = checkpoint
    run_records: dict[str, RunRecord] = dict(complete_by_id)
    run_paths = {
        run.run_id: staged.record_path
        for run, staged in zip(
            recovered.runs,
            recovered.manifest.runs,
            strict=True,
        )
    }
    for run_spec in recovered.start.runs:
        checkpoint = latest_checkpoints.get(run_spec.run_id)
        if run_spec.run_id in run_records or checkpoint is None:
            continue
        record = checkpoint_run_record(
            checkpoint,
            run_spec=run_spec,
            semantic_registry_version=recovered.start.semantic_registry.version,
        )
        run_records[run_spec.run_id] = record
        run_paths[run_spec.run_id] = (
            f"cases/{path_component(run_spec.case.id)}/"
            f"{path_component(run_spec.variant.id)}/run.yaml"
        )
    planned_ids = tuple(run.run_id for run in recovered.start.runs)
    recorded_ids = tuple(run_id for run_id in planned_ids if run_id in run_records)
    missing = tuple(run_id for run_id in planned_ids if run_id not in run_records)
    post_processing_incomplete = (
        len(complete_by_id) != len(recovered.start.runs)
        or recovered.start.requires_cross_run_derivation
        or recovered.start.requires_policies
    )
    partial = bool(missing or post_processing_incomplete)
    if partial and not allow_partial:
        raise RecordingError(
            "Staging is incomplete; pass allow_partial=True to publish explicit partial evidence."
        )
    partial_status = ExperimentStatus.ABORTED
    if (
        recovered.state.termination is not None
        and recovered.state.termination.status is ExperimentStatus.CANCELLED
    ):
        partial_status = ExperimentStatus.CANCELLED
    termination = ExperimentTermination(
        status=partial_status if partial else ExperimentStatus.COMPLETED,
        partial=partial,
        cross_run_derivation_complete=not recovered.start.requires_cross_run_derivation,
        policies_complete=not recovered.start.requires_policies,
        planned_run_ids=planned_ids,
        recorded_run_ids=recorded_ids,
        missing_run_ids=missing,
        error=recovered.state.termination.error
        if recovered.state.termination is not None
        else None,
    )
    ordered_records = tuple(run_records[run_id] for run_id in recorded_ids)
    ordered_paths = tuple(run_paths[run_id] for run_id in recorded_ids)
    record = experiment_record_from_recovery(
        recovered,
        termination=termination,
        runs=ordered_records,
        run_paths=ordered_paths,
    )
    finalizing = create_temporary_record_directory(output_dir)
    try:
        copy_committed_files(recovered, finalizing)
        for run_record, run_path in zip(ordered_records, ordered_paths, strict=True):
            target = finalizing / run_path
            target.parent.mkdir(parents=True, exist_ok=True)
            atomic_write_text(
                target,
                dump_yaml(run_record_to_yaml_view(run_record), schema_name="run_record"),
                durability=durability,
            )
        write_final_metadata(finalizing, record, durability=durability)
        publish_record_directory(finalizing, output_dir, durability=durability)
        return record
    finally:
        remove_temporary_record_directory(finalizing)

inspect_staging

inspect_staging(path: Path) -> StagingInspection
Source code in src/autobench/records/staging.py
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
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
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
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
def inspect_staging(path: Path) -> StagingInspection:
    start, state = load_staging_state(path)
    planned_ids = tuple(run.run_id for run in start.runs)
    try:
        manifest = load_staging_manifest(path)
    except (RecordingError, ValidationError) as exc:
        return StagingInspection(
            path=path,
            experiment_id=start.experiment_id,
            health=StagingHealth.CONFLICTING,
            recoverable=False,
            status=state.status,
            planned_run_ids=planned_ids,
            missing_run_ids=planned_ids,
            diagnostics=(str(exc),),
        )
    corrupt: list[str] = []
    conflicting: list[str] = []
    diagnostics: list[str] = []
    complete: list[str] = []
    plan_by_id = {run.run_id: run for run in start.runs}
    if manifest.experiment_id != start.experiment_id:
        diagnostics.append(
            "staging manifest experiment does not match staging state: "
            f"{manifest.experiment_id!r} != {start.experiment_id!r}"
        )
        conflicting.extend(planned_ids)
    if manifest.revision != state.revision:
        diagnostics.append(
            "staging state and manifest revisions differ; only manifest-committed evidence "
            f"will be recovered ({state.revision} != {manifest.revision})"
        )
    expected_paths = {STAGING_STATE_PATH, STAGING_MANIFEST_PATH}
    for staged in manifest.runs:
        run_spec = plan_by_id.get(staged.run_id)
        if run_spec is None:
            conflicting.append(staged.run_id)
            diagnostics.append(f"staged run is not in the experiment plan: {staged.run_id}")
        elif staged.case_id != run_spec.case.id or staged.variant_id != run_spec.variant.id:
            conflicting.append(staged.run_id)
            diagnostics.append(f"staged run identity does not match its plan: {staged.run_id}")
        if staged.record_path not in {entry.path for entry in staged.files}:
            conflicting.append(staged.run_id)
            diagnostics.append(
                f"staged run record is not committed by its file list: {staged.run_id}"
            )
        invalid = validate_staged_entries(path, staged.files, diagnostics=diagnostics)
        if invalid:
            corrupt.append(staged.run_id)
        else:
            try:
                record = RunRecord.model_validate(
                    run_record_payload_from_yaml_view(load_yaml(path / staged.record_path))
                )
            except (OSError, RecordingError, ValidationError) as exc:
                corrupt.append(staged.run_id)
                diagnostics.append(f"invalid staged run record {staged.run_id}: {exc}")
            else:
                if (
                    record.run_id != staged.run_id
                    or record.experiment_id != start.experiment_id
                    or record.benchmark_id != start.benchmark_id
                    or record.case_id != staged.case_id
                    or record.variant_id != staged.variant_id
                ):
                    conflicting.append(staged.run_id)
                    diagnostics.append(
                        f"staged run payload identity does not match its manifest: {staged.run_id}"
                    )
                else:
                    complete.append(staged.run_id)
        expected_paths.update(entry.path for entry in staged.files)
    checkpointed: list[str] = []
    for checkpoint in manifest.checkpoints:
        run_spec = plan_by_id.get(checkpoint.run_id)
        if run_spec is None:
            conflicting.append(checkpoint.run_id)
            diagnostics.append(f"checkpoint run is not in the experiment plan: {checkpoint.run_id}")
        if checkpoint.path != checkpoint.file.path:
            conflicting.append(checkpoint.run_id)
            diagnostics.append(
                f"checkpoint path is not committed by its file entry: {checkpoint.run_id}:{checkpoint.name}"
            )
        if validate_staged_entries(path, (checkpoint.file,), diagnostics=diagnostics):
            corrupt.append(checkpoint.run_id)
        else:
            try:
                snapshot = partial_snapshot_from_yaml_view(load_yaml(path / checkpoint.path))
            except (OSError, RecordingError, ValidationError) as exc:
                corrupt.append(checkpoint.run_id)
                diagnostics.append(
                    f"invalid staged checkpoint {checkpoint.run_id}:{checkpoint.name}: {exc}"
                )
            else:
                if (
                    snapshot.run_id != checkpoint.run_id
                    or snapshot.name != checkpoint.name
                    or snapshot.experiment_id != start.experiment_id
                    or snapshot.benchmark_id != start.benchmark_id
                    or (
                        run_spec is not None
                        and (
                            snapshot.case_id != run_spec.case.id
                            or snapshot.variant_id != run_spec.variant.id
                        )
                    )
                ):
                    conflicting.append(checkpoint.run_id)
                    diagnostics.append(
                        "staged checkpoint payload identity does not match its manifest: "
                        f"{checkpoint.run_id}:{checkpoint.name}"
                    )
                else:
                    checkpointed.append(checkpoint.run_id)
        expected_paths.add(checkpoint.file.path)
    if validate_staged_entries(path, manifest.payloads, diagnostics=diagnostics):
        corrupt.extend(
            entry.identity.partition(":")[0]
            for entry in manifest.payloads
            if entry.identity.partition(":")[0] in plan_by_id
        )
    expected_paths.update(entry.path for entry in manifest.payloads)
    actual_paths = {
        item.relative_to(path).as_posix()
        for item in path.rglob("*")
        if item.is_file() and not item.name.endswith(".tmp")
    }
    orphaned = tuple(sorted(actual_paths - expected_paths))
    missing = tuple(run_id for run_id in planned_ids if run_id not in complete)
    fatal_conflict = bool(conflicting)
    if corrupt:
        health = StagingHealth.CORRUPT
    elif fatal_conflict or orphaned or manifest.revision != state.revision:
        health = StagingHealth.CONFLICTING
        if orphaned:
            diagnostics.append("staging contains uncommitted files; recovery will ignore them")
    elif not missing:
        health = StagingHealth.COMPLETE
    elif complete or checkpointed:
        health = StagingHealth.PARTIAL
    else:
        health = StagingHealth.MISSING
    return StagingInspection(
        path=path,
        experiment_id=start.experiment_id,
        health=health,
        recoverable=not corrupt and not fatal_conflict,
        status=state.status,
        planned_run_ids=planned_ids,
        complete_run_ids=tuple(run_id for run_id in planned_ids if run_id in complete),
        checkpointed_run_ids=tuple(dict.fromkeys(checkpointed)),
        missing_run_ids=missing,
        corrupt_run_ids=tuple(dict.fromkeys(corrupt)),
        conflicting_run_ids=tuple(dict.fromkeys(conflicting)),
        orphaned_files=orphaned,
        diagnostics=tuple(diagnostics),
    )

recover_staging

recover_staging(path: Path) -> RecoveredStaging
Source code in src/autobench/records/staging.py
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
def recover_staging(path: Path) -> RecoveredStaging:
    inspection = inspect_staging(path)
    if not inspection.recoverable:
        raise RecordingError(
            f"Staging evidence is {inspection.health.value}: {list(inspection.diagnostics)}"
        )
    start, state = load_staging_state(path)
    manifest = load_staging_manifest(path)
    runs = tuple(
        RunRecord.model_validate(
            run_record_payload_from_yaml_view(load_yaml(path / staged.record_path))
        )
        for staged in manifest.runs
    )
    checkpoints = tuple(
        partial_snapshot_from_yaml_view(load_yaml(path / checkpoint.path))
        for checkpoint in manifest.checkpoints
    )
    return RecoveredStaging(
        start=start,
        state=state,
        manifest=manifest,
        inspection=inspection,
        runs=runs,
        checkpoints=checkpoints,
    )

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
154
155
156
157
158
159
160
161
162
163
164
def export_markdown_report(
    result: ExperimentResult,
    path: Path | None = None,
    *,
    report_spec: ReportSpec | None = None,
) -> str:
    report = build_report(result, report_spec=report_spec)
    rendered = render_markdown_report(report)
    if path is not None:
        write_markdown_report(report, path, layout="single", overwrite=True)
    return rendered

export_runs_csv

export_runs_csv(
    result: ExperimentResult, path: Path | None = None
) -> str
Source code in src/autobench/reports/exporting.py
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
def export_runs_csv(result: ExperimentResult, path: Path | None = None) -> str:
    output = StringIO()
    fieldnames = [
        "run_id",
        "case_id",
        "variant_id",
        "status",
        "correlation_group_id",
        "correlation_attempt",
        "correlation_phase",
        *[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,
            "correlation_group_id": (None if run.correlation is None else run.correlation.group_id),
            "correlation_attempt": None if run.correlation is None else run.correlation.attempt,
            "correlation_phase": None if run.correlation is None else run.correlation.phase,
        }
        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
28
29
30
31
32
33
34
35
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
 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
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
    }
    optimizations = [
        {
            "run": optimization.benchmark_run_id,
            "case": optimization.case_id,
            "variant": optimization.variant_id,
            "execution": optimization.execution.model_dump(mode="json", exclude_none=True),
        }
        for optimization in report.optimizations
    ]
    return {
        "record": {
            "type": "report",
            "version": 1,
        },
        "report": {
            "benchmark": report.benchmark_id,
            "experiment": report.experiment_id,
            "correlation": (
                None
                if report.correlation is None
                else report.correlation.model_dump(mode="json", exclude_none=True)
            ),
            "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,
            **({"optimizations": optimizations} if optimizations else {}),
            **(
                {"optimization_warnings": report.optimization_warnings}
                if report.optimization_warnings
                else {}
            ),
        },
    }

render_markdown_bundle

render_markdown_bundle(
    report: BenchmarkReport, *, record_link_prefix: str = ""
) -> dict[str, str]
Source code in src/autobench/reports/markdown.py
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
def render_markdown_bundle(
    report: BenchmarkReport,
    *,
    record_link_prefix: str = "",
) -> dict[str, str]:
    pages: dict[str, str] = {}
    include_technical_pages = report.markdown.profile == "audit"
    case_paths = {
        case_id: f"cases/{_page_slug(case_id)}.md"
        for case_id in sorted({run.case_id for run in report.run_details})
    }
    variant_paths = {
        variant.variant_id: f"variants/{_page_slug(variant.variant_id)}.md"
        for variant in sorted(report.variant_configs, key=lambda item: item.variant_id)
    }
    run_paths = (
        {
            run.run_id: f"runs/{_page_slug(run.run_id)}.md"
            for run in sorted(report.run_details, key=lambda item: item.run_id)
        }
        if include_technical_pages
        else {}
    )
    asset_ids = (
        () if report.assets is None else sorted({item.asset_id for item in report.assets.versions})
    )
    asset_paths = (
        {asset_id: f"assets/{_page_slug(asset_id)}.md" for asset_id in asset_ids}
        if include_technical_pages
        else {}
    )
    all_paths = [
        "index.md",
        *case_paths.values(),
        *variant_paths.values(),
        *run_paths.values(),
        *asset_paths.values(),
    ]
    if len(all_paths) != len(set(all_paths)):
        raise ReportPublicationError("Normalized Markdown bundle paths collide.")

    index = _render_markdown_document(
        report,
        record_link_prefix=record_link_prefix,
        bundle_index=True,
    ).rstrip()
    page_groups = (
        ("Cases", case_paths),
        ("Variants", variant_paths),
        ("Runs", run_paths),
        ("Assets", asset_paths),
    )
    index_lines = [index, "", "## Report Pages", ""]
    for title, paths in page_groups:
        if not paths:
            continue
        index_lines.extend((f"### {title}", ""))
        index_lines.extend(
            f"- [{_text(identity)}]({_link_target(page)})" for identity, page in paths.items()
        )
        index_lines.append("")
    pages["index.md"] = "\n".join(index_lines).rstrip() + "\n"
    pages.update(
        (page, _render_case_page(report, case_id, run_paths))
        for case_id, page in case_paths.items()
    )
    pages.update(
        (page, _render_variant_page(report, variant_id, run_paths))
        for variant_id, page in variant_paths.items()
    )
    if run_paths:
        run_link_prefix = (PurePosixPath("..") / record_link_prefix).as_posix()
        pages.update(
            (page, _render_run_page(report, run_id, record_link_prefix=run_link_prefix))
            for run_id, page in run_paths.items()
        )
    pages.update(
        (page, _render_asset_page(report, asset_id)) for asset_id, page in asset_paths.items()
    )
    return dict(sorted(pages.items()))

write_markdown_report

write_markdown_report(
    report: BenchmarkReport,
    path: Path,
    *,
    layout: ReportLayout | None = None,
    overwrite: bool = False,
    immutable_root: Path | None = None,
) -> MarkdownReportPublication
Source code in src/autobench/reports/markdown.py
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 write_markdown_report(
    report: BenchmarkReport,
    path: Path,
    *,
    layout: ReportLayout | None = None,
    overwrite: bool = False,
    immutable_root: Path | None = None,
) -> MarkdownReportPublication:
    requested_layout = report.markdown.layout if layout is None else layout
    selected_layout = _select_layout(report, requested_layout)
    _validate_destination(path, immutable_root=immutable_root)
    if path.is_symlink():
        raise ReportPublicationError(f"Markdown report destination cannot be a symlink: {path}")
    if selected_layout == "single":
        if path.exists() and (path.is_dir() or not overwrite):
            raise ReportPublicationError(f"Markdown report destination already exists: {path}")
        content = render_markdown_report(
            report,
            record_link_prefix=_record_link_prefix(path.parent, immutable_root),
        )
        atomic_write_text(path, content)
        digest, byte_count = hash_and_size(path)
        files = (PublishedReportFile(path=path, sha256=digest, byte_count=byte_count),)
    else:
        files = _write_bundle(
            report,
            path,
            overwrite=overwrite,
            record_link_prefix=_record_link_prefix(path, immutable_root),
        )
    return MarkdownReportPublication(
        profile=report.markdown.profile,
        requested_layout=requested_layout,
        layout=selected_layout,
        destination=path,
        files=files,
    )

aggregate_values

aggregate_values(
    values: list[Any], fn: AggregationFn
) -> Any | None
Source code in src/autobench/reports/reporting.py
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
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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
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_grouped_reports

build_grouped_reports(
    results: Sequence[ExperimentResult],
    *,
    correlation: ExecutionCorrelation | None = None,
) -> list[CorrelatedReportGroup]
Source code in src/autobench/reports/reporting.py
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
def build_grouped_reports(
    results: Sequence[ExperimentResult],
    *,
    correlation: ExecutionCorrelation | None = None,
) -> list[CorrelatedReportGroup]:
    selected = (
        list(results)
        if correlation is None
        else filter_experiments(
            results,
            correlation=correlation,
        )
    )
    grouped: dict[str | None, list[ExperimentResult]] = {}
    for result in selected:
        group_id = None if result.correlation is None else result.correlation.group_id
        grouped.setdefault(group_id, []).append(result)
    return [
        CorrelatedReportGroup(
            group_id=group_id,
            attempts=tuple(
                sorted(
                    {
                        result.correlation.attempt
                        for result in group_results
                        if result.correlation is not None and result.correlation.attempt is not None
                    }
                )
            ),
            phases=tuple(
                sorted(
                    {
                        result.correlation.phase
                        for result in group_results
                        if result.correlation is not None and result.correlation.phase is not None
                    }
                )
            ),
            reports=[build_report(result) for result in group_results],
        )
        for group_id, group_results in grouped.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
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
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: dict[str, Any] = {}
        details: list[LeaderboardMetricReport] = []
        for metric in metrics:
            samples = [
                value
                for run in runs
                if (value := metric_value(run, metric.semantic_type, registry=active_registry))
                is not None
            ]
            value = aggregate_values(samples, metric.fn)
            values[metric.name] = value
            direction, unit, role = _metric_metadata(
                runs,
                metric.semantic_type,
                registry=active_registry,
            )
            details.append(
                LeaderboardMetricReport(
                    name=metric.name,
                    semantic_type=active_registry.normalize(metric.semantic_type)
                    or metric.semantic_type,
                    value=value,
                    sample_count=len(samples),
                    missing_count=len(runs) - len(samples),
                    unit=unit,
                    direction=direction,
                    role=role,
                )
            )
        rows.append(
            LeaderboardRow(
                variant_id=variant_id,
                run_count=len(runs),
                metrics=values,
                metric_details=tuple(details),
            )
        )
    return _mark_leaderboard_bests(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
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
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,
    experiment_record: ExperimentRecord | None = None,
    experiment_root: Path | None = None,
) -> BenchmarkReport
Source code in src/autobench/reports/reporting.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
156
157
158
159
160
161
162
163
164
165
166
167
168
def build_report(
    result: ExperimentResult,
    *,
    registry: SemanticRegistry | None = None,
    report_spec: ReportSpec | None = None,
    experiment_record: ExperimentRecord | None = None,
    experiment_root: Path | 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()
    optimizations, optimization_warnings = build_optimization_runs(result)
    metric_catalog, report_notices = build_metric_catalog(
        result,
        report_spec=active_report_spec,
        registry=active_registry,
    )
    artifact_inventory, artifact_notices = build_artifact_inventory(
        result,
        experiment_root=experiment_root,
        experiment_record=experiment_record,
    )
    include_tracebacks = (
        active_report_spec.markdown.profile == "audit"
        and active_report_spec.markdown.content.include_captured
    )
    comparisons = [
        compare_variants(
            result,
            baseline=comparison.baseline,
            candidate=comparison.candidate,
            metrics=comparison.resolved_metrics(),
            registry=active_registry,
        )
        for comparison in active_report_spec.comparisons
    ]
    report = BenchmarkReport(
        benchmark_id=result.benchmark_id,
        experiment_id=result.experiment_id,
        run_count=result.total_count,
        markdown=active_report_spec.markdown,
        source=build_source_identity(result, experiment_record=experiment_record),
        evaluation=build_evaluation_summary(result),
        design=build_experiment_design(result),
        health=build_run_health(result),
        metric_catalog=metric_catalog,
        notices=(*report_notices, *artifact_notices),
        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),
        run_details=build_run_details(result, markdown=active_report_spec.markdown),
        failures=build_failures(result, include_tracebacks=include_tracebacks),
        traces=build_trace_summary(
            result,
            top_slowest=active_report_spec.markdown.traces.top_slowest,
        ),
        assets=build_asset_lineage(
            result,
            experiment_root=experiment_root,
            markdown=active_report_spec.markdown,
        ),
        artifacts=artifact_inventory,
        policies=build_policy_outcomes(result, registry=active_registry),
        provenance=build_provenance(result, markdown=active_report_spec.markdown),
        case_matrix=build_case_matrix(
            result,
            semantic_type=active_report_spec.case_matrix.semantic_type,
            registry=active_registry,
        ),
        comparisons=comparisons,
        regressions=build_regressions(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
        ],
        optimizations=optimizations,
        optimization_warnings=optimization_warnings,
        correlation=result.correlation,
    )
    return report.model_copy(update={"summary": build_executive_summary(report)})

build_run_metric_rows

build_run_metric_rows(
    result: ExperimentResult,
    *,
    registry: SemanticRegistry | None = None,
) -> list[RunMetricRow]
Source code in src/autobench/reports/reporting.py
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
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
277
278
279
280
281
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
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
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],
            factor_details=tuple(
                FactorReport(
                    name=factor.name,
                    value=factor.value,
                    semantic_type=factor.semantic_type,
                    optimize=factor.optimize,
                )
                for factor in next(
                    run.factors for run in result.runs if run.variant_id == 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
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
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]] = {}
    metric_results: list[MetricComparisonReport] = []
    baseline_by_case = {run.case_id: run for run in baseline_runs}
    candidate_by_case = {run.case_id: run for run in candidate_runs}
    paired_case_ids = tuple(sorted(set(baseline_by_case) & set(candidate_by_case)))
    all_case_ids = set(baseline_by_case) | set(candidate_by_case)

    for metric in metrics:
        baseline_samples = [
            value
            for run in baseline_runs
            if (value := metric_value(run, metric.semantic_type, registry=active_registry))
            is not None
        ]
        candidate_samples = [
            value
            for run in candidate_runs
            if (value := metric_value(run, metric.semantic_type, registry=active_registry))
            is not None
        ]
        baseline_value = aggregate_values(
            baseline_samples,
            metric.fn,
        )
        candidate_value = aggregate_values(
            candidate_samples,
            metric.fn,
        )
        delta = _numeric_delta(baseline_value, candidate_value)
        metric_deltas[metric.name] = {
            "baseline": baseline_value,
            "candidate": candidate_value,
            "delta": delta,
        }
        direction, unit, _ = _metric_metadata(
            [*baseline_runs, *candidate_runs],
            metric.semantic_type,
            registry=active_registry,
        )
        wins, ties, losses, paired_metric_count = _paired_outcomes(
            paired_case_ids,
            baseline_by_case=baseline_by_case,
            candidate_by_case=candidate_by_case,
            semantic_type=metric.semantic_type,
            direction=direction,
            registry=active_registry,
        )
        metric_results.append(
            MetricComparisonReport(
                name=metric.name,
                semantic_type=active_registry.normalize(metric.semantic_type)
                or metric.semantic_type,
                aggregation=metric.fn,
                baseline=baseline_value,
                candidate=candidate_value,
                delta=delta,
                relative_delta=_relative_delta(baseline_value, delta),
                direction=direction,
                unit=unit,
                outcome=_comparison_outcome(delta, direction),
                baseline_count=len(baseline_samples),
                candidate_count=len(candidate_samples),
                paired_count=paired_metric_count,
                missing_pair_count=len(paired_case_ids) - paired_metric_count,
                wins=wins,
                ties=ties,
                losses=losses,
            )
        )

    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,
        baseline_factors=_factor_map(baseline_runs),
        candidate_factors=_factor_map(candidate_runs),
        paired_count=len(paired_case_ids),
        missing_pair_count=len(all_case_ids) - len(paired_case_ids),
        metric_results=tuple(metric_results),
    )

correlation_matches

correlation_matches(
    actual: ExecutionCorrelation | None,
    expected: ExecutionCorrelation,
) -> bool
Source code in src/autobench/reports/reporting.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
def correlation_matches(
    actual: ExecutionCorrelation | None,
    expected: ExecutionCorrelation,
) -> bool:
    supplied = expected.model_fields_set
    if actual is None:
        return not supplied
    if "group_id" in supplied and actual.group_id != expected.group_id:
        return False
    if "attempt" in supplied and actual.attempt != expected.attempt:
        return False
    if "phase" in supplied and actual.phase != expected.phase:
        return False
    if (
        "parent_experiment_id" in supplied
        and actual.parent_experiment_id != expected.parent_experiment_id
    ):
        return False
    if (
        "resumed_from_experiment_id" in supplied
        and actual.resumed_from_experiment_id != expected.resumed_from_experiment_id
    ):
        return False
    return "labels" not in supplied or all(
        actual.labels.get(key) == value for key, value in expected.labels.items()
    )

filter_experiments

filter_experiments(
    results: Sequence[ExperimentResult],
    *,
    correlation: ExecutionCorrelation,
) -> list[ExperimentResult]
Source code in src/autobench/reports/reporting.py
225
226
227
228
229
230
def filter_experiments(
    results: Sequence[ExperimentResult],
    *,
    correlation: ExecutionCorrelation,
) -> list[ExperimentResult]:
    return [result for result in results if correlation_matches(result.correlation, correlation)]

metric_observation

metric_observation(
    run: RunResult,
    semantic_type: str,
    *,
    registry: SemanticRegistry | None = None,
) -> Observation | None
Source code in src/autobench/reports/reporting.py
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
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
    ]
    candidates.extend(
        score.to_observation(
            observation_id=f"{run.run_id}_report_score_{index}",
            case_id=run.case_id,
            variant_id=run.variant_id,
        )
        for index, score in enumerate(run.scores)
        if active_registry.normalize(score.semantic_type) == 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
528
529
530
531
532
533
534
535
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, *, record_link_prefix: str = ""
) -> str
Source code in src/autobench/reports/markdown.py
109
110
111
112
113
114
115
116
117
118
def render_markdown_report(
    report: BenchmarkReport,
    *,
    record_link_prefix: str = "",
) -> str:
    return _render_markdown_document(
        report,
        record_link_prefix=record_link_prefix,
        bundle_index=False,
    )

get_active_run_context

get_active_run_context() -> RunContext | None
Source code in src/autobench/runtime/instrumentation.py
182
183
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,
    assets: list[InstrumentAssetSpec] | None = None,
    operation_family: str | None = None,
) -> InstrumentationHandle
Source code in src/autobench/runtime/instrumentation.py
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
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,
    assets: list[InstrumentAssetSpec] | 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 ()),
        assets=tuple(assets 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,
    correlation: ExecutionCorrelation | None = None,
) -> list[MatrixRunSpec]
Source code in src/autobench/runtime/pipeline.py
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
def expand_matrix(
    spec: BenchmarkSpec,
    *,
    experiment_id: str,
    correlation: ExecutionCorrelation | None = None,
) -> 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,
            correlation=correlation,
        )
        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
152
153
154
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}"

merge_execution_correlation

merge_execution_correlation(
    base: ExecutionCorrelation | None,
    override: ExecutionCorrelation | None,
) -> ExecutionCorrelation | None

Merge explicitly supplied invocation fields without erasing YAML defaults.

Source code in src/autobench/runtime/models.py
 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
def merge_execution_correlation(
    base: ExecutionCorrelation | None,
    override: ExecutionCorrelation | None,
) -> ExecutionCorrelation | None:
    """Merge explicitly supplied invocation fields without erasing YAML defaults."""

    if override is None:
        return None if base is None else base.model_copy(deep=True)
    current = base or ExecutionCorrelation()
    supplied = override.model_fields_set
    labels = dict(current.labels)
    if "labels" in supplied:
        labels.update(override.labels)
    merged = ExecutionCorrelation(
        group_id=override.group_id if "group_id" in supplied else current.group_id,
        attempt=override.attempt if "attempt" in supplied else current.attempt,
        phase=override.phase if "phase" in supplied else current.phase,
        parent_experiment_id=(
            override.parent_experiment_id
            if "parent_experiment_id" in supplied
            else current.parent_experiment_id
        ),
        resumed_from_experiment_id=(
            override.resumed_from_experiment_id
            if "resumed_from_experiment_id" in supplied
            else current.resumed_from_experiment_id
        ),
        labels=labels,
    )
    if (
        merged.group_id is None
        and merged.attempt is None
        and merged.phase is None
        and merged.parent_experiment_id is None
        and merged.resumed_from_experiment_id is None
        and not merged.labels
    ):
        return None
    return merged

run_benchmark_path

run_benchmark_path(
    path: Path,
    *,
    experiment_id: str | None = None,
    correlation: ExecutionCorrelation | None = None,
    concurrency_limit: int | None = 1,
    instrumentors: Sequence[Instrumentor] = (),
    recorder: Recorder | None = None,
    progress_handlers: Sequence[ProgressHandler] = (),
    progress_error_policy: ProgressErrorPolicy = ProgressErrorPolicy.STRICT,
    progress_error_handler: ProgressErrorHandler
    | None = None,
) -> ExperimentResult
Source code in src/autobench/runtime/pipeline.py
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
def run_benchmark_path(
    path: Path,
    *,
    experiment_id: str | None = None,
    correlation: ExecutionCorrelation | None = None,
    concurrency_limit: int | None = 1,
    instrumentors: Sequence[Instrumentor] = (),
    recorder: Recorder | None = None,
    progress_handlers: Sequence[ProgressHandler] = (),
    progress_error_policy: ProgressErrorPolicy = ProgressErrorPolicy.STRICT,
    progress_error_handler: ProgressErrorHandler | None = None,
) -> ExperimentResult:
    from autobench.spec import load_benchmark_spec

    spec = load_benchmark_spec(path)
    return run_sync(
        run_benchmark_spec(
            spec,
            experiment_id=experiment_id,
            correlation=correlation,
            concurrency_limit=concurrency_limit,
            instrumentors=instrumentors,
            recorder=recorder,
            progress_handlers=progress_handlers,
            progress_error_policy=progress_error_policy,
            progress_error_handler=progress_error_handler,
        )
    )

run_benchmark_spec async

run_benchmark_spec(
    spec: BenchmarkSpec,
    *,
    experiment_id: str | None = None,
    correlation: ExecutionCorrelation | None = None,
    concurrency_limit: int | None = 1,
    instrumentors: Sequence[Instrumentor] = (),
    recorder: Recorder | None = None,
    progress_handlers: Sequence[ProgressHandler] = (),
    progress_error_policy: ProgressErrorPolicy = ProgressErrorPolicy.STRICT,
    progress_error_handler: ProgressErrorHandler
    | None = None,
) -> ExperimentResult
Source code in src/autobench/runtime/pipeline.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
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
async def run_benchmark_spec(
    spec: BenchmarkSpec,
    *,
    experiment_id: str | None = None,
    correlation: ExecutionCorrelation | None = None,
    concurrency_limit: int | None = 1,
    instrumentors: Sequence[Instrumentor] = (),
    recorder: Recorder | None = None,
    progress_handlers: Sequence[ProgressHandler] = (),
    progress_error_policy: ProgressErrorPolicy = ProgressErrorPolicy.STRICT,
    progress_error_handler: ProgressErrorHandler | None = None,
) -> ExperimentResult:
    from autobench.spec import build_benchmark_plan

    active_experiment_id = experiment_id or generate_experiment_id(spec.benchmark.id)
    active_correlation = merge_execution_correlation(
        spec.execution.correlation,
        correlation,
    )
    plan = build_benchmark_plan(spec)
    run_specs = expand_matrix(
        spec,
        experiment_id=active_experiment_id,
        correlation=active_correlation,
    )
    environment = capture_environment()
    session: RecordSession | None = None
    recording: _RecordOperations | None = None
    staged_run_ids: list[str] = []
    started_run_ids: list[str] = []
    completed_runs: dict[str, RunResult] = {}
    cancelled_run_ids: set[str] = set()
    policy_violations: list[PolicyResult] = []
    cross_run_derivation_complete = not bool(spec.post_derive)
    policies_complete = not bool(spec.policies)
    dispatcher = _ProgressDispatcher(
        progress_handlers,
        error_policy=progress_error_policy,
        error_handler=progress_error_handler,
    )
    if recorder is not None:
        from autobench.records.staging import ExperimentStart

        session = await recorder.open(
            ExperimentStart(
                experiment_id=active_experiment_id,
                benchmark_id=spec.benchmark.id,
                plan=plan,
                runs=tuple(run_specs),
                environment=environment,
                semantic_registry=spec.semantic_registry.model_copy(deep=True),
                report_spec_data=spec.reports.model_dump(mode="json"),
                spec_snapshot=spec.model_dump(mode="json"),
                spec_hash=_spec_hash(spec),
                requires_cross_run_derivation=bool(spec.post_derive),
                requires_policies=bool(spec.policies),
                correlation=active_correlation,
            )
        )
        recording = _RecordOperations(session)

    try:
        await dispatcher.emit(
            ProgressEventKind.BENCHMARK_STARTED,
            f"Benchmark {spec.benchmark.id} started.",
            benchmark_id=spec.benchmark.id,
            experiment_id=active_experiment_id,
            case_count=plan.case_count,
            variant_count=plan.variant_count,
            planned_run_count=plan.planned_run_count,
        )
        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 = []
                for run_spec in run_specs:
                    run = await _run_matrix_item_observed(
                        spec,
                        run_spec,
                        dispatcher=dispatcher,
                        started_run_ids=started_run_ids,
                        completed_runs=completed_runs,
                        cancelled_run_ids=cancelled_run_ids,
                        instrumentation_diagnostics=instrumentation_diagnostics,
                        recording=recording,
                        staged_run_ids=staged_run_ids,
                    )
                    runs.append(run)
            else:
                semaphore = asyncio.Semaphore(concurrency_limit)
                runs = await _run_concurrent_matrix(
                    [
                        _run_matrix_item_limited(
                            spec,
                            run_spec,
                            semaphore,
                            dispatcher=dispatcher,
                            started_run_ids=started_run_ids,
                            completed_runs=completed_runs,
                            cancelled_run_ids=cancelled_run_ids,
                            instrumentation_diagnostics=instrumentation_diagnostics,
                            recording=recording,
                            staged_run_ids=staged_run_ids,
                        )
                        for run_spec in run_specs
                    ],
                )

        result = ExperimentResult(
            experiment_id=active_experiment_id,
            benchmark_id=spec.benchmark.id,
            plan=plan,
            runs=runs,
            environment=environment,
            termination=ExperimentTermination(
                status=ExperimentStatus.COMPLETED,
                cross_run_derivation_complete=cross_run_derivation_complete,
                policies_complete=policies_complete,
                planned_run_ids=tuple(run_spec.run_id for run_spec in run_specs),
                recorded_run_ids=tuple(run.run_id for run in runs),
            ),
            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),
            correlation=active_correlation,
        )
        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,
            )
            cross_run_derivation_complete = True
        if spec.policies:
            from autobench.evaluation.policies import apply_policies, evaluate_policies

            policy_violations = [
                policy
                for policy in evaluate_policies(
                    spec.policies,
                    result=result,
                    registry=spec.semantic_registry,
                )
                if not policy.passed
            ]
            result = apply_policies(
                spec.policies,
                result=result,
                registry=spec.semantic_registry,
            )
            policies_complete = True
        result = _refresh_run_statuses(result, registry=spec.semantic_registry)
        result = result.model_copy(
            update={
                "termination": result.termination.model_copy(
                    update={
                        "cross_run_derivation_complete": cross_run_derivation_complete,
                        "policies_complete": policies_complete,
                    }
                )
            }
        )
        completed_runs.update((run.run_id, run) for run in result.runs)
        if recording is not None:
            await recording.execute(
                recording.session.finish(result),
                description="Recording finalization",
            )
            await recording.execute(
                recording.session.close(),
                description="Recording close",
            )
    except BaseException as exc:
        if recording is not None:
            abort_error = await _finish_cleanup_task(
                asyncio.create_task(
                    _abort_recording(
                        recording,
                        run_specs=run_specs,
                        staged_run_ids=staged_run_ids,
                        cross_run_derivation_complete=cross_run_derivation_complete,
                        policies_complete=policies_complete,
                        failure=exc,
                    )
                ),
                cancel_on_timeout=False,
                description="Recording abort and close",
            )
            if abort_error is not None:
                exc.add_note(f"recording abort failed: {abort_error}")
        progress_error = await _finish_cleanup_task(
            asyncio.create_task(
                _emit_completion_progress(
                    dispatcher,
                    benchmark_id=spec.benchmark.id,
                    experiment_id=active_experiment_id,
                    run_specs=run_specs,
                    started_run_ids=started_run_ids,
                    completed_runs=completed_runs,
                    cancelled_run_ids=cancelled_run_ids,
                    policy_violations=policy_violations,
                    experiment_status=(
                        ExperimentStatus.CANCELLED
                        if isinstance(exc, asyncio.CancelledError)
                        else ExperimentStatus.ABORTED
                    ),
                    error=exc,
                )
            )
        )
        if progress_error is not None:
            exc.add_note(f"progress terminal delivery failed: {progress_error}")
        dispatch_error = dispatcher.error()
        if dispatch_error is not None:
            exc.add_note(str(dispatch_error))
        raise
    await _emit_completion_progress(
        dispatcher,
        benchmark_id=spec.benchmark.id,
        experiment_id=active_experiment_id,
        run_specs=run_specs,
        started_run_ids=started_run_ids,
        completed_runs=completed_runs,
        cancelled_run_ids=cancelled_run_ids,
        policy_violations=policy_violations,
        experiment_status=ExperimentStatus.COMPLETED,
    )
    dispatcher.raise_if_failed()
    return result

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
140
141
142
143
144
145
146
147
148
149
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,
    *,
    sequence: int = 0,
    run_status: RunStatus | None = None,
    experiment_status: ExperimentStatus | None = None,
    **data: Any,
) -> ProgressEvent
Source code in src/autobench/runtime/progress.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
def progress_event(
    kind: ProgressEventKind,
    message: str,
    *,
    sequence: int = 0,
    run_status: RunStatus | None = None,
    experiment_status: ExperimentStatus | None = None,
    **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,
        sequence=sequence,
        run_status=run_status,
        experiment_status=experiment_status,
        **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
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 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
 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
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,
            end_reason=EndReason.FAILED,
            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,
            end_reason=EndReason.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
86
87
88
89
90
91
92
93
94
95
96
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
58
59
60
61
62
63
64
65
66
67
68
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.capture is not None:
        body["capture"] = spec.capture.model_dump(mode="json", exclude_defaults=True)

    if spec.execution.correlation is not None:
        body["execution"] = {
            "correlation": spec.execution.correlation.model_dump(
                mode="json",
                exclude_none=True,
            )
        }

    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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
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
168
169
170
171
172
173
174
175
176
177
178
179
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
 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
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
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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,
    previous_snapshot: dict[str, Any] | None = None,
    content_path: str = "content.sqlite3",
) -> dict[str, Any]
Source code in src/autobench/tracking/history.py
 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
def asset_to_yaml_view(
    asset: TrackedAsset,
    version: AssetVersion,
    *,
    existing: Any = None,
    previous_snapshot: dict[str, Any] | None = None,
    content_path: str = "content.sqlite3",
) -> dict[str, Any]:
    existing_versions = _existing_asset_versions(existing)
    current_snapshot = _asset_version_snapshot(asset)
    prior_snapshot = (
        previous_snapshot
        if previous_snapshot is not None
        else _existing_asset_current_snapshot(existing)
    )
    existing_asset = existing.get("asset") if isinstance(existing, dict) else None
    current_version = (
        existing_asset.get("current_version") if isinstance(existing_asset, dict) else None
    )
    previous_version = current_version if isinstance(current_version, str) else None
    if prior_snapshot is None and existing_versions:
        prior_snapshot = _version_entry_snapshot(existing_versions[-1])
    if (
        version.parent_version is None
        and previous_version is not None
        and previous_version != version.version
    ):
        version = version.model_copy(update={"parent_version": previous_version})
    content_ref = AssetContentRef(
        asset_id=asset.id,
        version=version.version,
        path=content_path,
    )
    diff_ref = (
        AssetDiffRef(
            asset_id=asset.id,
            version=version.version,
            parent_version=version.parent_version,
            path=content_path,
        )
        if prior_snapshot is not None and version.parent_version is not None
        else None
    )
    existing_version_payload = next(
        (entry for entry in existing_versions if entry.get("version") == version.version),
        None,
    )
    version_payload = (
        existing_version_payload
        if previous_version == version.version and existing_version_payload is not None
        else _asset_version_payload(
            version,
            current_snapshot,
            previous_snapshot=prior_snapshot,
            content_ref=content_ref,
            diff_ref=diff_ref,
        )
    )
    versions = [
        entry
        for entry in existing_versions
        if isinstance(entry.get("version"), str) and entry["version"] != version.version
    ]
    versions.append(version_payload)
    asset_view = _asset_yaml_view(
        asset,
        current_version=version.version,
        content_ref=content_ref,
    )
    if isinstance(asset, AssetDefinition) and isinstance(existing, dict):
        existing_asset = existing.get("asset")
        if isinstance(existing_asset, dict):
            for field_name in ("source_locators", "aliases"):
                previous_values = existing_asset.get(field_name)
                current_values = asset_view.get(field_name)
                merged_values = tuple(
                    dict.fromkeys(
                        (
                            *(previous_values if isinstance(previous_values, list) else []),
                            *(current_values if isinstance(current_values, list) else []),
                        )
                    )
                )
                if merged_values:
                    asset_view[field_name] = list(merged_values)
    return {
        "record": {
            "type": "asset",
            "version": 2,
        },
        "asset": asset_view,
        "versions": versions,
    }

load_asset_content

load_asset_content(
    path: Path, *, asset_id: str, version: str
) -> dict[str, SerializedValue]
Source code in src/autobench/tracking/store.py
182
183
184
185
186
187
188
189
190
191
192
193
194
def load_asset_content(
    path: Path,
    *,
    asset_id: str,
    version: str,
) -> dict[str, SerializedValue]:
    if not path.is_file():
        raise FileNotFoundError(path)
    with AssetContentStore(path, read_only=True) as store:
        snapshot = store.content(asset_id=asset_id, version=version)
    if snapshot is None:
        raise KeyError(f"Unknown Autobench asset content: {asset_id}@{version}")
    return snapshot

load_asset_diff

load_asset_diff(
    path: Path,
    *,
    asset_id: str,
    version: str,
    parent_version: str,
) -> str
Source code in src/autobench/tracking/store.py
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
def load_asset_diff(
    path: Path,
    *,
    asset_id: str,
    version: str,
    parent_version: str,
) -> str:
    if not path.is_file():
        raise FileNotFoundError(path)
    with AssetContentStore(path, read_only=True) as store:
        diff = store.diff(
            asset_id=asset_id,
            version=version,
            parent_version=parent_version,
        )
    if diff is None:
        raise KeyError(f"Unknown Autobench asset diff: {asset_id}@{parent_version}..{version}")
    return diff

Progress Runtime

  • ProgressEvent carries a monotonic sequence, stable benchmark/run identity, event-specific data, and typed run_status or experiment_status terminal fields.
  • ProgressEventKind defines benchmark start/finish, run start/finish, and actual policy violation events. Candidate decisions belong to Autoptimize rather than the benchmark lifecycle.
  • ProgressHandler accepts synchronous and asynchronous observers.
  • ProgressErrorPolicy selects strict library delivery or explicit best-effort delivery.
  • ProgressHandlerFailure identifies the handler index, event sequence/kind, and original error.
  • ProgressDispatchError is raised after strict delivery failure, terminal notification attempts, and durable recorder cleanup.

run_benchmark_spec(), run_benchmark_path(), Benchmark.run(), and Benchmark.run_async() all accept progress_handlers, progress_error_policy, and progress_error_handler.

Public Areas

Area Representative symbols
Definition Benchmark, BenchmarkSpec, TaskSpec, load_benchmark_spec
Data Case, DatasetSpec, Variant, FactorValue, production helpers, typed generated-dataset preparation and provenance
Runtime RunContext, RunPhase, Span, ExperimentResult, run_benchmark_spec; durable await ctx.checkpoint(name) and cooperative cancellation
Semantics Observation, Semantic, SemanticRegistry, queries and projection
Evaluation scorers, derivers, policies, expected actions, measurement, feedback
Protocol ABP signals, traces, capture, emitter, collector and context
Instrumentation settings, manager, instrumentors, method instrumentation, diagnostics, CurrentSpan, keyed InstrumentationRuntime.start_span() / end_span(), and external backend composition
Tracking track, asset models, discovery candidates, registry and history views
Records RunRecord, ExperimentRecord, ExperimentTermination, RecordManifest, FileRecorder, frozen staging snapshots, inspection/recovery, atomic/synced publication, and replay helpers
Reports report models, builders, Rich renderers and exporters
Telemetry export OTLPSettings, OTLPExportResult, export_otlp, and export_record_otlp

ExecutionCorrelation is the public invocation metadata model. It is accepted by the full spec, fluent builder, run functions, and CLI; persisted on results and records; and consumed by correlation_matches(), filter_experiments(), and build_grouped_reports(). It remains separate from replay lineage and application workflow state.

Prefer root imports for application code:

from autobench import Benchmark, Case, RunContext, Semantic

Native pydantic-gepa integration also exposes PydanticGEPAInstrumentation, PydanticGEPA, and the replay-safe PydanticGEPAEvidence projection from the root package. Its full contract is documented in Pydantic-GEPA Instrumentation.

Import a submodule when implementing an extension against that subsystem, such as a custom native instrumentor or source-map adapter.