Skip to content

2. Domain model and public API

Aggregate comparison-v3 carries report_sha3_512 in both source report identities, computed from each report's UTF-8 to_json() publication bytes. Confidence Assessment verifies both content digests alongside descriptive identity before evaluating policy. Changed timestamps or evidence therefore cannot reuse another run's comparison. Legacy comparison-v1 remains readable with absent digests, but unbound evidence yields the closed comparison_unavailable confidence result. Malformed digests and missing v2/v3 binding reject during document construction/loading. Content binding establishes report linkage, not authenticity of Consumer evidence. Comparison-v2 remains readable and eligible for correctly linked absolute assessment. Relative gates require comparison-v3, which identifies the corrected nonnegative aggregate ratio convention. Older aggregate fields cannot prove the domain of every private bootstrap result; recompute paired evidence to migrate, including when the legacy headline scores are positive.

CUDA device-event execution selects the declared device and stream before preprocessing and transfer, then records events only around model work. The callbacks retain their order and event-time exclusion; the shared context orders asynchronous preparation before model work. Inference, stream and device cleanup restore ownership without masking a primary invocation failure. This is deterministic backend contract evidence, not real-device qualification.

Paired population inference treats repeated observations of the same original case as one independent case block. Default CASE plans use the GROUP resampler internally for repeated trials, retaining all rows and Consumer aggregations or corpus callbacks; uncertainty records the group/block unit and original case count. Explicit GROUP mappings must keep all repeats of each case together. Trial-unit population resampling remains unsupported by the plan. Slice inference supports case blocks, counts original cases, and marks fewer than two cases insufficient; its facade has no explicit group-mapping policy. Consumers attest independence between case blocks or declared groups. Repeated-run variability is a separate estimand and these intervals do not establish independence of repeated rows.

Paired resampling uses stable means for default case/group reduction so finite extreme scores with a representable mean remain finite. Derived point/replicate differences and relative changes must be finite for both score and corpus APIs; unrepresentable arithmetic raises a fixed safe ValueError without clipping. Zero denominators keep relative evidence explicitly unavailable. Negative point or replicate aggregates also make the relative interval unavailable, with relative_signed_scores_unsupported; absolute effects remain valid. PairedResamplingResult and PairedDifferenceEstimate retain the optional relative_unavailable_reason. No unsupported replicate is discarded to manufacture an interval. Result construction also rejects non-finite point and interval fields before typed evidence is published.

Immutable Evaluation Reports enforce nonnegative integer elapsed time and execution counts, reconciled trial/aggregate counts, planned trial identity, bounded failure indices, and complete measurement coverage. complete requires zero failed executions even when no failure records are retained. JSON decoding reuses this publication boundary for report-v1 and report-v2. Partial and failed evidence is non-passing in Assessment. Structural consistency does not authenticate private Consumer inputs, outputs, or measurement meaning.

Canonical terms

Term Meaning in this repository
Schema One immutable, closed vocabulary accepted by a telemetry instance
Resource identity Process-level identity attached to all enabled OpenTelemetry signals
Context Immutable correlation attributes scoped with a context manager
Operation A timed unit represented as a span in production and a completion record in tests
Observation Either one metric measurement or one event
Outcome A schema-registered operation result; success is the initial value
Failure category An optional schema-registered class attached only to an error outcome
Runtime Process-owned lifecycle object containing an adapter, hooks, flush, and shutdown
Adapter A concrete implementation behind the Telemetry protocol
Collector profile A set of YAML fragments composed onto a base or standalone tier
Safety floor Name bans, cardinality restrictions, resource limits, and Collector deletion rules that consumers cannot relax
Performance Evaluation Bounded repetitions of a Consumer-owned Algorithm Candidate over private Evaluation Cases and Measurements
Evaluation Report Payload-free immutable evidence containing trial execution, Measurement summaries, uncertainty, and safe failures
Capacity Evaluation Local telemetry-delivery load harness with artifact and environment identity beyond the generic evaluation contract

Public export surface

telemetry.__init__ exports the following names.

Group Public names
Configuration BatchingConfig, CollectorConfig, CollectorProtocol, HeaderSecretReference, InstrumentationConfig, LogFormat, LoggingConfig, LoggingProcessConfig, ObservabilityConfig, ResourceConfig, SecretReference, SecretSource, SignalConfig, TelemetryConfig, TelemetryLimits
Schema and values AttributeItems, AttributeValue, EventObservation, EventSeverity, InstrumentKind, MetricObservation, MetricSpec, Observation, OperationKind, OperationSpec, ResourceIdentity, TelemetryContext, TelemetrySchema, attributes
Interfaces and runtime OperationScope, Telemetry, TelemetryRuntime
Test/no-op implementations CompletedOperation, RecordedObservation, RecordingTelemetry, NoopTelemetry, NOOP_TELEMETRY

ObservabilityConfig is an alias for TelemetryConfig; it exists for consumers migrating from the former application-owned name. The package includes py.typed, so installed type checkers treat its inline annotations as authoritative.

The telemetry.performance submodule is an independent public surface. The groups below map its main contracts and entry points; its __all__ is the exact export list, including individual default, maximum, and schema-version constants.

Group Public names
Evaluation EvaluationCase, EvaluationObservation, EvaluationPlan, RandomnessPlan, CandidateDeterminism, PerformanceEvaluator, ReplayableEvaluation, DatasetIdentity, CandidateIdentity, MeasurementIdentity
Paired evaluation PairedEvaluation, PairedEvaluationObservation, CandidateOrderPolicy
Paired resampling PairedResamplingPlan, PairedResamplingResult, ResamplingUnit, ResamplingEstimand, UncertaintyCapability, UncertaintyDescriptor, UncertaintyMethod, UncertaintyProvenance, UncertaintySeedPolicy, paired_resampling_interval
Paired difference PairedDifferenceComparison, PairedDifferenceEstimate, estimate_paired_differences
Aggregate comparison document COMPARISON_DOCUMENT_SCHEMA_VERSION, ComparisonReportIdentity, AggregateMeasurementComparison, AggregateComparisonDocument, ComparisonUnavailableReason, write_comparison_document, load_comparison_document
Compatibility diagnostics CompatibilityCode, CompatibilitySeverity, CompatibilityDiagnostic, CompatibilityExplanation, explain_compatibility
Execution adapters ExecutionCapability, ExecutionPhase, ExecutionContext, SyncExecutionAdapter, AsyncExecutionAdapter, CallableExecutionAdapter, SeededCallableExecutionAdapter, validate_execution_capabilities, execute_sync, execute_async
Bounded async candidate execution AsyncCandidatePlan, AsyncCandidateStatus, AsyncCandidateResult, AsyncCandidateEvaluation, evaluate_async_candidate
Spawned evaluation isolation IsolatedEvaluationConfig, IsolatedEvaluationStatus, IsolatedEvaluationResult, evaluate_in_spawned_child, MAX_ISOLATED_REPORT_BYTES
Batch execution BatchPlan, BatchPayload, BatchEvaluation, evaluate_batches
Batch sweep BatchSweepPlan, BatchSweepPoint, BatchSweepEvaluation, evaluate_batch_sweep
Resource evidence ResourceSampler, ResourceSample, ResourceSummary, ResourceAvailability, ResourceUnavailableReason
PyTorch peak resource evidence PyTorchPeakSampler, PyTorchPeakOwnershipError
Bounded serving arrivals ServingPlan, ServingArrivalMode, ServingRequest, ServingAccounting, ServingLatencyDistribution, ServingTiming, ServingLatencySufficiency, ServingResult, ServingEvidenceStatus, ServingInconclusiveReason, SERVING_EVIDENCE_SCHEMA_VERSION, preflight_serving, run_serving
Serving sweep ServingWorkloadIdentity, ServingSweepPlan, ServingTemperature, ServingSweepPoint, ServingSweepPointOutcome, ServingSweep, run_serving_sweep, present_serving_sweep
Candidate lifecycle LifecycleExecutionAdapter, LifecyclePhase, LifecyclePhaseError, LifecycleTimingScope, LifecycleTimingPhase, CompilationPolicy, CachePolicy, PerformanceEvaluator.evaluate_lifecycle_adapter
Execution comparison ExecutionIdentity, MeasurementCompatibilityProfile, MeasurementExecutionCompatibility, ExecutionDifference, ExecutionCompatibilityReason, LifecycleTimingCompatibilityReason, compare_measurement_execution, compare_lifecycle_timing_scope
Execution collection collect_execution_identity, ExecutionIdentityCollection, ExecutionFieldCollection, ExecutionFieldAvailability, SystemReader, FrameworkReader, EXECUTION_IDENTITY_COLLECTION_SCHEMA_VERSION
Measurements Measurement, CaseMeasurement, CorpusMeasurement, MeasurementGoal, MeasurementUnavailableError, MeasurementUnavailableReason, latency_measurement
Evidence EvaluationReport, EvaluationStatus, TrialResult, MeasurementSummary, EvaluationFailure, EvidenceCapabilities, REPORT_SCHEMA_VERSION, REPORT_SCHEMA_VERSION_V2, load_report, write_report, ReportStore, ReportStoreEntry, ReportStorePage, ReportStorePruneResult, ReportStoreError, ReportStoreCorruptionError, ReportStoreQuotaError
Execution evidence ExecutionEvidence, EXECUTION_EVIDENCE_SCHEMA_VERSION, EXECUTION_EVIDENCE_SCHEMA_VERSION_V2, TrialMeasurement
Curation selection evidence CURATION_SELECTION_MANIFEST_SCHEMA_VERSION, MAX_CURATION_SELECTION_COUNT, CurationSelectionManifest
Evaluation telemetry linkage EvaluationDeploymentLinkage, MeasurementTelemetryMetric, LifecycleTelemetryMetrics, DelayedQualityTelemetryMetric, DelayedQualityTelemetryMapping, DelayedAggregateQualityObservation, EvaluationTelemetryMapping, EvaluationTelemetryAdapter, DisabledEvaluationTelemetryAdapter, evaluation_deployment_linkage
Completed-trial checkpoints CHECKPOINT_SCHEMA_VERSION, MAX_CHECKPOINT_BYTES, CheckpointIdentity, CheckpointCursor, CompletedTrialCheckpoint, EvaluationCheckpoint, write_checkpoint, load_checkpoint
MLflow metadata export MlflowDestination, MlflowMetadataClient, MlflowExportPolicy, MlflowExportDisposition, MlflowExportState, MlflowExportRequest, MlflowExportResult, MlflowReportMetadata, export_mlflow_report, mlflow_report_metadata
Slice evidence SliceSpec, SliceAvailability, SliceResult, SliceMeasurementSummary
Slice planning and inference SliceEvidencePlan, SliceEvidenceLimits, plan_slice_evidence, validate_actual_slice_report_size, SlicePairedComparison, SliceComparisonAvailability, SliceInferenceScope, estimate_paired_slice_differences, SliceInferencePolicy, SliceInferenceEvidence, SliceInferenceStatus, assess_slice_inference
Required slice families RequiredSliceMember, RequiredSliceFamily, SliceFamilyComparison, SliceFamilyAvailability, SliceFamilyCorrection, estimate_required_slice_family, RequiredSliceTolerance, RequiredSliceDiagnostic, RequiredSliceAssessmentRule
Quantile sufficiency IndependentUnit, QuantilePrecisionPolicy, QuantileInterval, QuantileEvidenceStatus, quantile_interval, QuantileSufficiencyRule
Comparison and policy compare_reports, PerformanceComparison, MeasurementComparison, ReportCompatibilityError, ReportCompatibilityReason, AssessmentRule, AssessmentContext, ThresholdRule, RegressionRule, ConfidenceIntervalRule, EffectIntervalScope, RuleResult, RuleStatus, AssessmentStatus, AssessmentReason, AssessmentOutcome, Assessment, AssessmentDocument, ASSESSMENT_SCHEMA_VERSION, assess, assessment_outcome
Statistics mean, median, percentile, bootstrap_interval, linear_trend_interval
Presentation EvaluationPresentation, present_evaluation, render_markdown, render_html
Optional integrations OptionalIntegration, IntegrationAvailability, OptionalIntegrationSupport, OptionalIntegrationUnavailableError, OptionalIntegrationUnsupportedError, load_optional_integration, optional_integration_support
scikit-learn measurements ClassificationMetric, RegressionMetric, CalibrationMetric, ScikitLearnClassificationMeasurement, ScikitLearnRegressionMeasurement, ScikitLearnCalibrationMeasurement, CalibrationReliability, ReliabilityBin, ReliabilityBinAvailability, ReliabilityBinPolicy, calibration_reliability, sklearn_classification_measurement, sklearn_regression_measurement, sklearn_calibration_measurement
Streaming evidence ReplayableSource, SinglePassSource, StreamingMoments, StreamingCapability, StreamingPlan, KllSketchIdentity, KllDoublesSketch, preflight_streaming, create_kll_sketch, require_compatible_streaming, STREAMING_MOMENTS_REVISION
Injected LLM streaming evidence LlmStreamingPlan, LlmStreamStatus, LlmStreamCleanupStatus, LlmUsageProvenance, LlmUsage, LlmStreamingObservation, LlmStreamCancelledError, observe_llm_stream, LLM_STREAMING_OBSERVATION_SCHEMA_VERSION
Consumer-injected LLM judges LlmJudgeIdentity, LlmJudgePlan, LlmJudgeRateSchedule, LlmJudgeRequest, LlmJudgeResponse, LlmJudgePrivateResult, LlmJudgeExecution, LlmJudgeEvidence, LlmJudgeUsageState, execute_llm_judges, require_compatible_llm_judge_identity, LLM_JUDGE_EVIDENCE_SCHEMA_VERSION
Safe aggregate GenAI telemetry GENAI_CONVENTION_REVISION, GenAiStreamTelemetryMetrics, GenAiJudgeTelemetryMetrics, GenAiAggregateTelemetryMapping, GenAiAggregateTelemetryAdapter, DisabledGenAiAggregateTelemetryAdapter
Standalone provenance collect_provenance, Provenance, CodeProvenance, LockProvenance, DistributionProvenance, ProvenanceAvailability, ALLOWED_DISTRIBUTIONS, PROVENANCE_SCHEMA_VERSION

ResourceSampler.sample() is Consumer-polled: the injected monotonic clock enforces the configured minimum interval between reader attempts, including failures, without catch-up reads or scheduling threads. The summary's interval is a configured lower bound, not a measured cadence. NVML readers use a Consumer-owned session initialized before construction and shut down after all readers finish; sampler stop never shuts down that shared session. Device-wide readings are not process attribution or real-hardware qualification. Consumers serialize calls to each sampler; separate samplers may poll their own readers concurrently.

telemetry.performance.integrations.ranking exports duplicate-safe precision, recall, hit rate, reciprocal rank, average precision, and graded NDCG at a positive cutoff. These functions own mathematical mechanics; the Consumer owns relevance meaning, case selection, and release policy. NDCG divides exponential gains by the largest gain before summation, avoiding overflow for finite relevance and preserving discounts for positive subnormal relevance. Unrepresentable integers, negative/nonfinite values and booleans receive a fixed ValueError. Empty or all-zero relevance has NDCG one by documented convention, without claiming any relevant item was retrieved. Duplicate positions contribute zero. Independent 360-digit Decimal exponential fixtures cover ordinary, tiny-positive and overflowing unnormalized gain ranges; comparison tolerance is 2e-14 relative plus 1e-15 absolute. Analytic fixtures cover subnormal and 1e308 relevance.

Quantile ranks retain the one-million independent-unit ceiling and bounded incomplete-beta calculation, with at most 800 continued-fraction iterations per tail evaluation. Exact odd-binomial median symmetry prevents positive, even subnormal, confidence from collapsing to one rank when half-tail subtraction rounds. Nine selected Decimal PMF-recurrence fixtures check rank tails and adjacent ranks at counts 1000–1000000, probabilities from the smallest positive float to the largest float below one, and confidence 0.5–the largest float below one. The independent oracle uses 80/100 decimal digits, at most 20000 recurrence steps per direction, and a 4e-60 probability tolerance including omitted-tail bounds. Additional exact-symmetry fixtures check confidence 1e-12 and the smallest positive float at odd counts 101–999999. These selected fixtures bound tested numerical behavior; they do not establish universal accuracy, sampling independence or empirical coverage.

telemetry.performance.api is the recommended compact interface for ordinary Performance Evaluation. It exports exactly EvaluationCase, EvaluationPlan, PerformanceEvaluator, EvaluationReport, EvaluationStatus, Measurement, MeasurementGoal, CaseMeasurement, CorpusMeasurement, latency_measurement, DatasetIdentity, CandidateIdentity, MeasurementIdentity, RandomnessPlan, SliceSpec, ThresholdRule, RegressionRule, Assessment, compare_reports, assess, load_report, and write_report. It re-exports the existing objects unchanged; it neither creates a second evaluator nor deprecates root exports. Historical per-file facade proposals are not an inventory of current import routes; the source inventory lists implemented modules.

Public call surface

Owner Signature Result
Telemetry bind(context: TelemetryContext) Context manager yielding None
Telemetry operation(spec: OperationSpec) Context manager yielding OperationScope
Telemetry observe(observation: Observation) -> None Validates and records/emits one metric or event
OperationScope set_outcome(outcome: str, failure_category: str | None = None) -> None Selects the operation result
TelemetrySchema metric(name: str) -> MetricSpec Returns a registered metric or raises ValueError
TelemetrySchema validate_context/resource/operation/metric/event/outcome(...) Returns None (or the metric spec) on success; raises ValueError on violation
RecordingTelemetry operations() -> tuple[CompletedOperation, ...] Locked immutable snapshot
RecordingTelemetry observations() -> tuple[RecordedObservation, ...] Locked immutable snapshot
TelemetryRuntime create(config, *, schema, identity, logging_profile=None, environment=None, adapter_factory=None) No-op or enabled runtime
TelemetryRuntime telemetry Active Telemetry implementation
TelemetryRuntime instrument_fastapi(app), instrument_engine(engine) Installs owned hooks when applicable
TelemetryRuntime wrap_thread_target(callback) Original or context-capturing zero-argument callback
TelemetryRuntime force_flush() -> bool, shutdown() -> None Bounded lifecycle operations

TelemetryRuntime is also a context manager: __enter__ returns the runtime and __exit__ invokes shutdown() without suppressing an exception from the caller's block.

Performance evaluation call surface

PerformanceEvaluator(name, cases, measurements, plan=..., dataset_identity=None, measurement_identities=None, provenance=None) validates and freezes one bounded evaluation contract. evaluate(algorithm, candidate=...) passes only each case input to the callable, presents successful in-process observations to Measurements, and returns an immutable Evaluation Report.

SyncExecutionAdapter and AsyncExecutionAdapter are opt-in structural contracts for later evaluator execution modes. Each receives the private input and a validated, payload-free ExecutionContext, and owns setup, invoke, and teardown methods. execute_sync() and execute_async() validate their closed capability requirements before setup or invocation, then call teardown exactly once after a successful setup. Async cancellation remains cooperative and is propagated after awaited teardown. Async candidate evaluation classifies a candidate-raised TimeoutError from setup, invocation, or teardown as failed with only its exception class. Per-call and total timeout statuses require expiration of the corresponding evaluator-owned deadline. CallableExecutionAdapter is the dependency-free reference adapter for the existing one-argument callable shape; PerformanceEvaluator.evaluate() retains that existing signature and behavior.

run_serving(client, plan=...) is a separate, local injected-client harness. Its constant and seeded Poisson modes are explicitly open-loop; closed_loop_concurrency is a distinct arrival mode and is not throughput evidence. Plans preflight duration times rate, use fixed queue/in-flight/arrival limits, and create fixed workers rather than one task per offered request. The aggregate result keeps only bounded counts: scheduled/offered, admitted/sent/completed, success/failure/timeout/drop, and peak in-flight. It separately summarizes schedule lag, scheduled-to-completion, and dispatch-to-completion timings, so queue delay cannot be hidden by measuring only dispatched requests. Successful completion rate is reported against the declared duration. Any error, timeout, or drop leaves latency evidence explicitly insufficient; a Poisson or closed-loop generator reaching its declared arrival cap is inconclusive. Its fixed performance-serving/v1 schema identity is not a Collector capacity-report schema. PerformanceEvaluator.evaluate_adapter() accepts a synchronous adapter that explicitly advertises the candidate_randomness capability. SeededCallableExecutionAdapter supplies each two-argument (input, context) callable a derived local candidate seed. It is the Consumer's responsibility to use that seed with a local/framework-scoped generator; the platform never seeds process-global randomness.

DatasetIdentity is an explicit Consumer-supplied namespace, revision, split, and optional opaque manifest SHA3-512 digest. Supplying it makes a report use performance-evaluation/report-v2; callers without it continue to receive report-v1. The ordered case-name digest remains an alignment check only: it is not dataset-content identity and the library never derives an identity from private inputs or expected values. A caller may attach an explicitly collected or supplied Provenance record only to report-v2; it activates the closed provenance capability and retains the nested performance-evaluation/provenance-v1 version. Report-v1 has no provenance field, and readers reject unknown section flags or provenance versions during loading.

CandidateIdentity records Consumer-attested model and preprocessing revisions plus an optional opaque artifact digest. MeasurementIdentity records the Measurement name, implementation revision, goal, unit, aggregation revision, and target-transform revision. Both are optional: missing records remain explicitly unknown and are never inferred from callable names or source. Candidate revisions may differ between comparable reports; measurement identity establishes the Consumer-owned scorer contract. A structural custom Measurement uses an explicit mapping entry that matches its name, goal, and unit; scorer, target-transform, and aggregation revisions are never inferred from Consumer code.

Consumer curation and delayed labels remain outside this public model. A Consumer may resolve an opaque selection reference only in its own process and, after its own consent, redaction, retention, and access checks, construct fresh EvaluationCase values for a declared DatasetIdentity. It must declare a separate test split and reject training records from that flow. The evaluator never dereferences curation references or retains cases, inputs, expected values, labels, or raw selection identifiers in reports or telemetry. docs/examples/consumer_curation_delayed_labels.py is a synthetic executable boundary example; it requires no network or paid API.

observe_llm_stream() observes a Consumer-injected async stream incrementally under a declared chunk and duration bound. It retains only closed aggregate timings, counts, terminal status, and explicit usage-unit provenance; no prompt, chunk, output text, provider exception text, model identifier, or provider object enters its observation document. First nonempty content latency is distinct from true time-to-first-token: the latter remains unknown unless a Consumer provider adapter explicitly declares a provider token boundary. Usage remains unknown unless that adapter explicitly supplies provider-reported input/output units. Timeout, limit, and error outcomes are aggregate states; task cancellation closes the stream and propagates a LlmStreamCancelledError, preserving cancellation semantics. This observer is neither an LLM SDK nor an Evaluation Report/telemetry evidence extension. Stream observation v2 includes the separate LlmStreamCleanupStatus outcome. max_cleanup_seconds defaults to 0.1 and must be finite and positive, with a non-relaxable 1-second ceiling. Closure runs once in the observer task under its own timeout; no closure task is detached. The consumption limit remains separate: cooperative elapsed completion includes consumption plus cleanup and scheduling overhead. Closure success, failure, timeout, unsupported closure and caller cancellation remain distinct from the consumption status. Caller cancellation still carries aggregate cancellation evidence when closure stalls or fails. This bound cannot forcibly interrupt blocking or cancellation-resistant Consumer code, or prove that remote provider work stopped.

execute_llm_judges() is the corresponding Consumer-injected judge seam. LlmJudgeRequest payloads and LlmJudgeResponse decisions are explicitly private in-process values; LlmJudgeExecution.private_results has no serialization surface. Its separate LlmJudgeEvidence records only closed identity revisions, aggregate attempted/completed/error/budget/retry counts, reservations, actual-usage state, and optional Consumer-supplied currency/cost aggregates. Every initial/retry attempt reserves its declared units before invocation, so exhausted budgets admit no new calls. Incomplete provider usage makes actual totals unknown; known totals above reservation are an explicit overshoot. There is no provider/pricing import or lookup. Judge evidence v2 distinguishes budget_exhausted_count (requests never invoked) from retry_budget_exhausted_count (a subset of terminal errors whose next attempt was refused). A refused retry preserves an ERROR private result, its attempt count and retry_budget_exhausted flag; it starts no provider call. Request totals remain completed + error + never-started; invocation totals remain completed + error + retry. Failed attempts keep actual usage unknown, including cost. Judge comparison requires equal rubric, model, and configuration revisions through require_compatible_llm_judge_identity().

compare_reports(..., strict_provenance=True) requires attached provenance on both reports, requires every code, lock, and distribution record to be available, and then requires exact equality. A missing, partial, or unavailable record is a stable ReportCompatibilityError; it never becomes verified merely because both reports are unknown. This guards evaluator/scorer harness reproducibility independently of CandidateIdentity, whose model and preprocessing revisions may legitimately differ.

SliceSpec(name, revision, predicate) is an explicit Consumer-owned subgroup declaration. Predicates run once on private Evaluation Cases before candidate execution, may overlap, and never serialize their membership. With explicit DatasetIdentity, report-v2 retains only normalized slice declarations, availability, bounded aggregate execution counts, Measurement scores, and uncertainty descriptors. Empty or predicate-failed slices remain unavailable; the overall Measurement scope remains separate. Paired declaration reconciliation is independent of declaration order while preserving exact slice name/revision identity and private membership. Corpus slice and family inference use the declared private paired_resample callback on aligned selected observations, preserving repeated case blocks; they never fabricate per-case scores from a corpus aggregate. Measured lifecycle reset failures use the same slice-failure accounting as invocation failures: every selected scope retains eligible = successful + failed across trials, including overlapping slices. Warmup failures retain their lifecycle stage without adding measured executions. Default continue-on-error produces safe failed evidence; strict error propagation remains unchanged.

compare_reports() keeps its legacy default compatibility checks for report-v1 readers. Pass strict_dataset_identity=True to require both reports to carry equal DatasetIdentity namespace, revision, and split; equal Measurement implementation, aggregation, goal, and unit identity; the existing case-name alignment hash; and explicit candidate identity. Candidate model and preprocessing revisions intentionally may differ. Strict failures are ReportCompatibilityError, a ValueError subclass with a stable ReportCompatibilityReason for missing identity or a dataset/protocol mismatch.

explain_compatibility() is the pure alternative for callers that need every safe mismatch rather than the first compare_reports() exception. It returns ordered, fixed code/path/severity diagnostics and never includes Consumer values. Strict identity mode requires explicit dataset, candidate, and Measurement identity but intentionally allows candidate model and preprocessing revisions to differ. Execution identity is a typed, versioned report-v2 section when explicitly supplied to the evaluator: quality-profile hardware divergence is a warning, while timing-profile unknown controls or differences are blockers.

Assessment.passed remains true exactly when every Rule Result passes. Its derived Assessment.status is separately pass, fail, or inconclusive, so Evaluation Report execution status is never mistaken for an acceptance decision. A failing rule dominates; otherwise unavailable or inconclusive evidence produces an inconclusive assessment. Assessment.reason uses the closed AssessmentReason codes, while each Rule Result retains its original reason. Partial and failed reports retain the legacy unavailable Rule Result behavior and can never yield a passing Assessment.

AssessmentDocument is an independent performance-evaluation/assessment-v1 JSON envelope. It contains only bounded Rule Results, the derived Assessment state, and SHA3-512 links to the candidate report plus an optional matched baseline-report/comparison pair. It validates exact known fields and rejects any supplied status or reason that contradicts the Rule Results. assessment_outcome() provides the single public presentation category, distinguishing candidate/baseline execution incompleteness from unavailable and inconclusive policy evidence.

ConfidenceIntervalRule consumes only an AggregateComparisonDocument linked to the candidate and baseline reports passed to assess(). It evaluates an already oriented paired absolute or relative effect interval against a Consumer-supplied finite threshold: lower bound at least the threshold passes, upper bound below it fails, and every other valid interval is inconclusive. non_inferior() encodes a finite non-negative allowed regression as a threshold of -r. Absolute rules require the exact Measurement unit; relative rules use only the dimensionless "1" unit and a defined relative interval. The comparison document's paired-population inference scope is the only accepted source; missing, unlinked, unit-mismatched, or undefined relative evidence is unavailable and cannot pass. SliceFamilyComparison also binds exact baseline_report_identity and candidate_report_identity. Required-slice assessment compares those bindings to the current linked overall comparison. SliceInferenceEvidence retains its declared policy and measurement_name in process so sufficiency can be recomputed against the current candidate slice. Legacy unbound family/diagnostic objects are non-passing; the diagnostic's payload-free serialized projection is unchanged. Point-estimate ThresholdRule and RegressionRule remain unchanged and do not become confidence claims; Consumers choose explicitly between report-summary gates and linked paired-interval gates. The bounded per-rule result is retained in Assessment and its optional linked AssessmentDocument evidence.

Measurements still return finite floats. A Measurement may instead raise MeasurementUnavailableError with a closed MeasurementUnavailableReason for a mathematically undefined score. The evaluator keeps valid peers, retains no artificial numeric score for the unavailable Measurement, and records only the bounded reason; unexpected scorer errors remain separate failures.

ExecutionIdentity is a separate Consumer-attested, immutable provenance record. It has only the allowlisted OS/architecture, CPU, accelerator, backend/runtime, precision, thread/batch/concurrency, device-class, and timing-scope fields, each of which may be explicitly unknown. It contains no hostname, device UUID, path, arbitrary metadata, or provider configuration. compare_measurement_execution() selects a closed quality or timing profile: quality allows hardware differences with structured warnings; timing requires known, equal backend, device class, precision, thread count, batch size, concurrency, and timing scope. A report-v2 can retain it only as the exact performance-evaluation/execution-v1 section with the matching execution capability. A later known performance-evaluation/execution-v2 keeps that exact identity and adds a closed LifecycleTimingScope: warmed or reconstruction phase plus declared compilation and cache policy. Execution-v1 and legacy reports remain readable with lifecycle scope explicitly unknown; they cannot fabricate it. Timing-profile compatibility blocks unknown or unequal lifecycle scope, while quality-profile diagnostics remain warnings.

collect_execution_identity() is an explicit, dependency-free companion for bounded local evidence. Its versioned result classifies every closed field as available, unavailable, or unsupported. The standard-library system reader collects only OS/architecture, CPU model, and CPU count. An optional framework reader is injected by the Consumer and called only when supplied; the base package never imports or probes an accelerator framework. Missing GPU evidence remains unavailable, while batch size, concurrency, thread count, and timing scope remain Consumer-attested rather than inferred. Reader output is normalized through the existing safe identity validation and unknown keys are not retained. A Consumer may explicitly pass this validated collection result to an evaluator, which stores only its safe identity in the versioned report section. Collection does not qualify a machine, provider, or hosted environment. Collection constructors require the immutable, exactly ordered 13-field classification tuple and a validated identity. A field is available exactly when its value is present; unavailable and unsupported both require None. A classification describes availability, not the truth of an attestation or hardware equivalence. Supplying Consumer-attested controls is separate from the default collector, which deliberately leaves them unsupported.

Execution compatibility has this fixed policy:

Identity fields Timing profile Quality profile
backend, device class, precision, thread count, batch size, concurrency, timing scope Unknown or unequal values block compatibility Differences remain diagnostic
OS, architecture, CPU model/count, accelerator model Differences remain diagnostic and do not block Known differences warn hardware_difference; missing hardware warns hardware_provenance_unknown
runtime Differences remain diagnostic and do not block Differences remain diagnostic

Device class is also part of quality hardware warnings. Timing compatibility means only that the seven declared controls are known and equal; it does not establish equal hardware, OS, runtime versions, host idleness or provenance truth. The differences list records unequal fields, including known/unknown transitions. Matching None values create no difference row but remain unknown, never observed equality. Timing's unknown_required_timing_fields covers only its required controls. Consumers needing stricter host/runtime equivalence must explicitly reject unknown or unequal values under their own policy, independently of this compatibility flag. The existing timing policy is preserved, not strengthened.

collect_provenance(repository=..., lock_file=..., dependency_distributions=...) is a separately invoked local helper, not an evaluator default and not report serialization. It uses bounded local Git queries and importlib.metadata lookups for only ALLOWED_DISTRIBUTIONS, and returns classified unavailable evidence when the selected repository, lock, or installed metadata cannot provide a truthful value. The record contains no paths, source text, lock contents, environment values, or Git diagnostics. A later report-schema owner may attach this typed evidence only with an explicit versioned report contract.

RandomnessPlan(ordering_seed, candidate_seed, resampling_seed) declares independent integer stream bases. Its deterministic methods use a versioned SHA3-256 domain-separated hash and bounded positional indices; booleans are rejected as seeds. Reports retain the effective three-stream plan and state whether candidate determinism is controlled or unspecified. This base evaluator always reports unspecified for its ordinary one-argument callable interface; it never mutates process-global random state. EvaluationPlan.seed remains the compatibility shorthand and preserves its additive ordering stream when no explicit plan is supplied.

PerformanceEvaluator.evaluate_pair(candidate_a, candidate_b, candidate_a_name=..., candidate_a_identity=..., candidate_b_name=..., candidate_b_identity=...) runs both ordinary one-argument candidates in one bounded session. It requires DatasetIdentity, complete MeasurementIdentity records, and a CandidateIdentity for each candidate before either invocation. The effective ordering seed shuffles private case indexes when configured and chooses a reproducible per-index candidate order; CandidateOrderPolicy.INTERLEAVED_BY_ORDERING_SEED records that policy. The return value contains two ordinary Evaluation Reports plus non-serializable in-process PairedEvaluationObservations. An observation exists only when both candidates succeeded at the same original (trial_index, case_index); failure of one candidate never suppresses its peer's execution or report accounting.

PairedEvaluation.measurement_evidence is an in-process-only, typed bridge to paired statistical estimation. A CaseMeasurement with every successful pair is complete and retains aligned finite numeric scores plus its Consumer-owned aggregation function; incomplete (including any missing pair or scorer failure) and unsupported (including CorpusMeasurement without an explicit private paired_resample callback and Measurements without an explicit paired_score reducer) retain counts only. A supplied corpus callback receives only selected in-process observations and never acquires a report or JSON serialization path. Consequently, old or aggregate-only Evaluation Reports cannot be used to fabricate paired uncertainty, and release_evidence_available remains false until every pair and Measurement evidence is complete.

paired_resampling_interval(baseline_scores, candidate_scores, groups=None, plan=None, measurement_count=1) is an independent, in-process paired-inference seam. It accepts only equal-length finite score vectors and optional non-negative integer group positions, never case or group labels. Case and trial modes sample one row at a time; group mode samples each complete group as a unit. Both candidate estimates use the same selected positions for every replicate. PairedResamplingPlan defaults to 10,000 resamples, 0.95 confidence, case-weighted estimation, and fixed maximum work of 100 million score visits and one million ephemeral numeric cells; its configurable ceilings can only be lowered. Two independent units are required, and the helper returns a typed result rather than a report-v2 section.

PairedResamplingResult.uncertainty separates a paired population-interval claim from its typed sampling provenance: resampling unit, percentile-bootstrap method, confidence, resample count, independent-unit count, and fixed-seed policy. MeasurementSummary.uncertainty labels the existing report interval as repeated-trial variability with a derived-per-Measurement seed policy. Its independent count is the number of trial scores, not the number of cases; it is therefore not population-quality inference for opaque CorpusMeasurement scalars.

estimate_paired_differences() accepts only an in-process PairedEvaluation with complete Measurement evidence. It applies the original Consumer aggregation to each shared resample and returns positive-oriented absolute improvement (candidate minus baseline for maximize, reversed for minimize) with its direct interval. Relative improvement is also calculated as a ratio within each shared resample; it is unavailable if any required denominator is zero or either aggregate is negative at the point or any replicate. Neither reports nor separate score intervals can manufacture this evidence, and the result retains no case score payloads.

AggregateComparisonDocument.from_paired_difference() is the only public construction path for a versioned, atomically written paired-comparison document. It preserves report identities and aggregate effect/interval/uncertainty fields, but not report summaries, private paired vectors, resamples, case names, inputs, outputs, failures, or scorer payloads. It has no report-only inference path: persisted Evaluation Reports are descriptive evidence and cannot be combined to create a paired confidence claim. When a relative interval is unavailable because a required resample denominator is zero, the document retains the closed relative_denominator_zero reason instead of a fabricated ratio. Readers enforce the additional closed relative_signed_scores_unsupported reason for unsupported signed ratios and the closed schema, bounded count, valid uncertainty method, and finite JSON numbers.

OptionalIntegration is a closed dependency-free registry for the separately declared PyTorch CPU, scikit-learn, psutil, NVML, MLflow, and pytest extras. load_optional_integration() imports only the explicitly selected direct package and reports its exact extra if absent. Installability does not assert a working adapter, provider, or hardware qualification. The CUDA entry is intentionally unsupported until real-device evidence is retained by its implementation owner.

The lazy scikit-learn calibration adapter reduces declared class-ordered probability vectors to Brier or log-loss scores only after finite, range, shape, and normalization validation. Probability scoring uses the same validated class-to-column ordinal mapping as probability classification. Binary ROC AUC encodes membership in the declared positive class; multiclass ROC, average precision and calibration encode targets by declared ordinal, preserving probability columns regardless of lexical label order. Scorer identity commits to declared-ordinal-v1 encoding as well as declaration order and dependency version, so evidence from the earlier label interpretation cannot share the corrected scorer identity. Omitted averaging resolves to macro for ROC AUC and average precision, and binary for label metrics. Probability metrics support micro, macro and weighted; single-label precision/recall/F1 also support binary for two declared classes. Unsupported averaging rejects at construction before optional imports. Identity records the resolved policy, so an omitted policy and its explicit equivalent agree. For binary precision, recall and F1, an omitted positive class resolves to the second declared class, matching binary probability metrics. Explicit declared positive classes retain their meaning; omission and the equivalent explicit choice produce the same Measurement identity. The reliability companion retains bounded class-indexed bin counts, means, and observed frequencies—not labels, cases, or raw probabilities. The fixed default is 10 equal-width bins and the maximum is 100; empty bins are explicit unavailable evidence. Optional count-weighted classwise ECE and the deterministic identity both commit to the declared bin policy and probability-policy revision.

export_mlflow_report(store, digest, client=..., destination=...) is an explicit optional boundary, not an evaluator side effect. It obtains one digest-validated local report from ReportStore and gives the injected Consumer-owned client only a fixed metadata projection: report identity/version, safe report labels/status, aggregate execution counts, descriptive Measurement score metadata, and aggregate slice counts. The request also contains one canonical, bounded JSON artifact of exactly that projection. It never sends report JSON, trials, failures, case names, inputs, expected values, outputs, exception classifications, tracking URIs, or credentials. Destinations are bounded non-secret labels; the injected client owns endpoint and credentials, must respect the supplied deadline, and may use the destination/digest idempotency key when its backend supports it. The policy has a 30-second maximum and three-attempt maximum. Confirmed retryable failures may retry, while exceptions, expiry, malformed client responses, and uncertain acknowledgements are explicitly indeterminate and are not retried. Export does not mutate, remove, or pin the local report and makes no exactly-once delivery claim.

The dependency-free telemetry-eval history CLI opens only an existing ReportStore. Its list and show actions read validated local evidence; export writes a digest-validated report to an explicit local output path without importing code; and prune requires a byte/entry target and exactly one explicit --preview or --target mode. ReportStore.preview_prune() produces the same oldest-unpinned plan as prune() without deleting a document. These commands neither invoke an Algorithm Candidate nor create, update, or infer an Assessment. run --factory remains the CLI's sole dynamic-import seam; remote MLflow delivery remains the separate injected-client library API.

CaseMeasurement maps each observation to a finite score and reduces those scores with a Consumer- selectable aggregation function. CorpusMeasurement calculates one score from all successful observations in a trial. Any structurally compatible object can implement Measurement; registration and inheritance are not required. Repetitions produce repeated-trial scores, and the headline score is their median with a deterministic bootstrap interval describing repeated-trial variability. Repeated execution does not prove independent population sampling or independent process starts; Consumers own the experimental unit and independence assumptions.

compare_reports() accepts only complete reports with compatible evaluation names, case-set fingerprints, execution plans, Measurement names, goals, and units. assess() applies structural custom rules or the built-in absolute threshold and objective-aware baseline-regression rules. Missing or partial evidence remains unavailable, never a pass.

Type relationships

Serving sweeps continue every declared point after ordinary client-factory failure. Such a point is failed with result=None; its timing/rate evidence is unavailable, never fabricated as zero requests or latency. Presentation uses the closed text client construction failed, without exception or endpoint data. The Consumer factory owns resources acquired before returning a client; each completed point finishes the existing serving-run ownership scope before the next factory call. Cancellation and interrupts propagate. A synthetic one-request point makes no population-tail claim.

Evaluation presentation escapes literal backslashes, pipes, and backticks for Markdown. The HTML table renderer decodes those escapes and text entities before HTML escaping each cell, preserving complete labels and numeric column alignment. It introduces no scripts, remote assets, or automatic links.

classDiagram
    class TelemetrySchema {
      +str version
      +str instrumentation_scope
      +frozenset operations
      +frozenset events
      +tuple metrics
      +validate_*()
    }
    class MetricSpec {
      +str name
      +InstrumentKind instrument
      +str unit
      +str description
      +frozenset dimensions
    }
    class ResourceIdentity {
      +str service_name
      +str service_version
      +str instance_id
      +str deployment_environment
      +AttributeItems attributes
    }
    class TelemetryContext {
      +AttributeItems attributes
      +merged(child)
    }
    class OperationSpec {
      +str name
      +OperationKind kind
      +AttributeItems attributes
    }
    class MetricObservation {
      +str name
      +float value
      +AttributeItems attributes
    }
    class EventObservation {
      +str name
      +EventSeverity severity
      +AttributeItems attributes
    }
    class Telemetry {
      <<protocol>>
      +bind(context)
      +operation(spec)
      +observe(observation)
    }
    class OperationScope {
      <<protocol>>
      +set_outcome(outcome, failure_category)
    }

    TelemetrySchema "1" *-- "0..256" MetricSpec
    Telemetry --> TelemetryContext
    Telemetry --> OperationSpec
    Telemetry --> MetricObservation
    Telemetry --> EventObservation
    Telemetry --> OperationScope

All public record classes shown above are frozen dataclasses. Schema collections must use the exact immutable container declared by the API: tuples for metrics and attribute pairs, and frozenset for sets of names.

Envelopes

Attribute values

AttributeValue is str | bool | int | float | tuple[str, ...]. AttributeItems is a tuple of (name, value) tuples. The attributes() helper accepts a mapping or iterable, validates every pair, rejects duplicate names, sorts pairs by name, and returns the immutable tuple.

Direct dataclass construction also validates AttributeItems, but does not sort them. Ordering is therefore deterministic when callers use attributes() and caller-controlled when they pass a valid tuple directly.

Operations

OperationSpec contains a registered name, one of server, internal, or client, and operation attributes. Telemetry.operation() returns a context manager whose scope accepts set_outcome(). Operations start with outcome success.

On normal exit, the selected outcome is retained. On exceptional exit, the outcome becomes failure, the exception class name is recorded or emitted as exception.type, and the original exception is never suppressed. Exception messages are not captured.

Observations

A MetricObservation has a registered metric name, one finite numeric value, and only dimensions registered for that metric. Boolean values are rejected even though Python booleans are integers.

An EventObservation has a registered event name, an EventSeverity (DEBUG, INFO, WARNING, ERROR, or CRITICAL), and registered event attributes.

Context semantics

Contexts are stored in a per-telemetry-instance ContextVar. Binding merges the current context with the child by attribute name. Child values replace parent values, the merged pairs are sorted, and exit restores the prior value through the ContextVar token.

sequenceDiagram
    participant Caller
    participant Context as Telemetry context
    participant Operation
    participant Observation

    Caller->>Context: bind({job.id: outer})
    Caller->>Operation: enter operation
    Operation->>Context: snapshot current context
    Caller->>Context: bind({job.id: inner})
    Caller->>Observation: observe event
    Observation->>Context: read current context = inner
    Caller-->>Context: exit inner binding
    Caller-->>Operation: exit operation
    Note over Operation: operation retains outer snapshot

Operation context is captured on operation entry. Observations read context when they are observed. In the production adapter, operation attributes overlay same-named context attributes when the span is created. Metric measurements do not inherit telemetry context. Events become log records and the log handler merges current context into their exported attributes.

Adapter behavior

RecordingTelemetry

This deterministic test adapter validates input strictly and raises ValueError on schema violations. It uses one lock for its global sequence and captured lists. Each observation or completed operation gets the next sequence number. operations() and observations() return immutable tuple snapshots.

CompletedOperation contains the sequence, original OperationSpec, context captured at entry, outcome, optional failure category, and exception class name. RecordedObservation contains the sequence, original observation, and context captured at observation time.

NoopTelemetry

The no-op adapter performs no validation and no side effects. Its bind and operation context managers do nothing, set_outcome() does nothing, and exceptions pass through. NOOP_TELEMETRY is a shared instance typed as Telemetry.

Production adapter

The production OpenTelemetry adapter validates the same schema but catches conversion failures after startup. Invalid bind, operation, outcome, metric, or event calls emit a bounded local diagnostic once per category and otherwise leave business execution unchanged. Chapter 6 specifies the signal mapping.