Performance evaluation library¶
telemetry.performance is a dependency-free module for evaluating recommendation models, retrieval
systems, ranking algorithms, rules, transformations, and other Python callables. Consumers own their
Evaluation Cases, expected values, Measurement meaning, and acceptance policy. The module owns bounded
execution, deterministic repetitions, warmups, timing, failure isolation, statistics, comparison, and
payload-free reports.
This module is separate from the repository's local telemetry capacity harness. An Evaluation Report describes one Algorithm Candidate on one Consumer-owned dataset. It is not a production SLO or a Collector-capacity claim.
ReplayableSource supplies a fresh iterator per trial; SinglePassSource rejects reuse explicitly.
StreamingMoments retains only count, finite mean, variance state, and failure count, and merges
independent states with a revision- and tolerance-checked online formula. It never retains case scores;
corpus metrics and approximate quantiles require separate explicit capabilities. StreamingPlan preflights
exact streaming, an explicitly byte-bounded corpus buffer, or a bounded approximate-quantile plan before a
Candidate consumes a source item. Exact and approximate plans cannot be compared. The optional
performance-datasketches integration is loaded only by create_kll_sketch(); its KLL adapter defaults to
k=200, records package version and normalized rank error in its payload-free identity, enforces 1 MiB per
sketch and 64 MiB preflight aggregate state, and exposes neither raw samples nor serialized sketch bytes.
Quick start¶
from telemetry.performance import (
CaseMeasurement,
EvaluationCase,
EvaluationPlan,
RandomnessPlan,
PerformanceEvaluator,
RegressionRule,
ThresholdRule,
assess,
compare_reports,
latency_measurement,
write_report,
)
from telemetry.performance.integrations.ranking import precision_at_k, recall_at_k
cases = (
EvaluationCase("case-1", "running shoes", frozenset({"p1", "p7"})),
EvaluationCase("case-2", "winter coat", frozenset({"p3"})),
)
evaluation = PerformanceEvaluator(
"search-ranking",
cases,
(
CaseMeasurement(
"precision@10",
lambda observation: precision_at_k(observation.case.expected, observation.output, 10),
),
CaseMeasurement(
"recall@10",
lambda observation: recall_at_k(observation.case.expected, observation.output, 10),
),
latency_measurement("latency.p95", percentile=95, unit="milliseconds"),
),
plan=EvaluationPlan(
repetitions=5,
warmup_runs=2,
shuffle_cases=True,
randomness=RandomnessPlan(ordering_seed=42, candidate_seed=43, resampling_seed=44),
),
)
report = evaluation.evaluate(lambda query: model.recommend(query, limit=10), candidate="model-v2")
write_report(output_path, report)
The algorithm can be a function, bound method, or callable object. It receives each case's input and
returns an arbitrary output. A CaseMeasurement receives each successful in-process observation and
reduces the per-case values using a configurable aggregation function. A CorpusMeasurement receives
all successful observations from one trial, which supports catalog coverage, diversity, calibration,
fairness slices, batch throughput, and other cross-case calculations.
Consumers can also provide any object with name, goal, unit, and an evaluate(observations)
method. No inheritance or registration is required. Measurement results must be finite numbers.
Declared slices¶
For a bounded subgroup view, register explicit SliceSpec values with an explicit dataset identity.
Predicates receive each private EvaluationCase only in process and run once before any candidate
invocation. They may overlap; each slice retains its own eligible, successful, failed, and independent
trial-unit counts. Overall Measurement results remain a separate scope.
from telemetry.performance import DatasetIdentity, SliceSpec
evaluation = PerformanceEvaluator(
"language-quality",
cases,
measurements,
dataset_identity=DatasetIdentity("consumer-eval", "2026-09", "test"),
slices=(
SliceSpec("language-fr", "r1", lambda case: case.input["language"] == "fr"),
SliceSpec("input-under-80", "r1", lambda case: len(case.input["text"]) < 80),
),
)
Report-v2 writes only the safe slice name/revision, availability, aggregate counts, scores, and uncertainty descriptors. It never writes predicate membership, case names, inputs, expected values, outputs, or exception messages. Empty and predicate-failed slices are explicitly unavailable. Slice declarations are normalized by name, and report comparison rejects a changed declaration or revision.
Comparison and acceptance¶
Reports with the same evaluation name, case-set fingerprint, complete execution plan, Measurement names, units, and goals can be compared:
comparison = compare_reports(baseline, report)
quality_change = comparison.measurement("precision@10").relative_improvement
assessment = assess(
report,
(
ThresholdRule.at_least("quality-floor", "precision@10", 0.30),
RegressionRule(
"latency-budget",
"latency.p95",
maximum_relative_regression=0.05,
),
),
baseline=baseline,
)
assert assessment.passed
ThresholdRule supplies inclusive lower and upper bounds. RegressionRule interprets regression using
the Measurement goal, so an increase improves a maximize Measurement and degrades a minimize
Measurement. Consumers may implement the structural AssessmentRule interface for significance tests,
slice policy, multiple-metric policy, or domain-specific release decisions.
Assessment.passed remains the legacy convenience boolean: it is true only if every rule passes.
Assessment.status separates the policy decision (pass, fail, or inconclusive) from candidate
and baseline execution statuses. Assessment.reason is a stable aggregate code: a failing rule wins;
otherwise unavailable or inconclusive rule evidence yields inconclusive; otherwise all rules pass.
Individual RuleResult.reason values remain available unchanged. RuleStatus.UNAVAILABLE means a
required input was missing or invalid, while RuleStatus.INCONCLUSIVE means the rule had valid but
insufficient evidence. A partial or failed candidate (or supplied baseline) returns the existing
unavailable per-rule result and an inconclusive assessment, never a pass.
assessment_outcome(assessment) is the shared presentation helper for CLI and report consumers. It
returns a closed human-facing category that distinguishes incomplete candidate or baseline execution
from unavailable policy inputs and valid-but-inconclusive evidence. AssessmentDocument.from_evidence()
creates the separate, versioned performance-evaluation/assessment-v1 JSON document. It retains only
the derived assessment outcome, bounded rule results, and SHA3-512 links to the candidate report and,
when present, the baseline report and comparison. It rejects unsupported versions, unknown fields, and
contradictory passed, status, or reason data; it does not copy report payloads or exception messages.
ConfidenceIntervalRule is a separate Consumer-owned gate for a linked
AggregateComparisonDocument, rather than an interpretation of two report-level point estimates.
For an oriented effect interval [lower, upper] and a minimum improvement d, it passes when
lower >= d, fails when upper < d, and is inconclusive otherwise. The lower-bound equality is
intentional: d=0 permits non-negative improvement but does not claim strict improvement.
ConfidenceIntervalRule.non_inferior(..., maximum_regression=r) uses d=-r, with a finite,
non-negative Consumer tolerance. Absolute rules require the Measurement's exact unit; relative
rules require the dimensionless "1" unit and their separately resampled relative interval. Missing,
mismatched, or undefined paired evidence is unavailable, never passing. Paired effects are already
oriented positive-for-improvement for both maximize and minimize Measurements.
Point-estimate gates and confidence-aware gates deliberately answer different questions. Keep existing
ThresholdRule and RegressionRule when policy is about the observed report summary. Use a linked
paired comparison document when policy requires interval evidence:
assessment = assess(
candidate_report,
(
ConfidenceIntervalRule.at_least(
"quality-improvement",
"quality",
consumer_minimum_quality_improvement,
unit="quality-unit",
),
ConfidenceIntervalRule.non_inferior(
"latency-non-inferiority",
"latency.p95",
consumer_allowed_latency_regression,
unit="milliseconds",
),
),
baseline=baseline_report,
comparison_document=paired_comparison_document,
)
All values beginning with consumer_ are Consumer policy, not library recommendations. The resulting
assessment.rule(name) retains the bounded diagnostic (interval_meets_threshold,
interval_below_threshold, interval_crosses_threshold, or an unavailable-evidence reason), and
AssessmentDocument.from_evidence(..., comparison=paired_comparison_document) links that decision to
the same payload-free comparison evidence.
Report and privacy contract¶
An Evaluation Report contains candidate/evaluation labels, timestamps, the full bounded execution plan, a SHA3-512 fingerprint of the ordered case names, aggregate counts, per-trial duration and throughput, Measurement scores, a seeded bootstrap confidence interval over trial scores, and safe failure classifications. It never serializes Evaluation Case names, inputs, expected values, algorithm outputs, or exception messages. Only exception class names are retained. Use non-sensitive, bounded labels for evaluation, candidate, Measurement, and rule names.
Measurements keep their finite-float interface. When a score is mathematically undefined, a consumer
raises MeasurementUnavailableError with its closed public reason (currently one-class ROC AUC or
constant-target R2). The trial stores no fabricated numeric value; valid peer Measurements remain
available, while the report is incomplete and cannot pass an assessment. An unexpected scorer exception
remains a measurement failure without an unavailable-reason code or serialized exception message.
For a durable dataset revision, pass an explicit DatasetIdentity(namespace, revision, split,
manifest_sha3_512=None) to PerformanceEvaluator. The optional manifest digest is Consumer-owned;
the library never hashes case inputs or expected values. This writes report-v2 while existing calls
continue writing report-v1. A report-v1 loads with dataset_identity is None, so the legacy ordered
case-name hash is never mistaken for dataset provenance. Report-v2 has a closed capability map:
provenance, execution and slices become true only when their implemented typed sections are supplied.
Execution identity and lifecycle timing scopes are opt-in; slices require explicit Consumer predicates.
The report's inference capability remains unavailable: separate paired-inference/assessment documents
do not activate a report-v2 inference section. Unrecognized flags or schema versions are rejected.
compare_reports() retains its report-v1-compatible default, which checks the ordered case-name hash
but cannot prove dataset-content identity. Use compare_reports(baseline, candidate,
strict_dataset_identity=True) for a release decision that requires equal explicit dataset namespace,
revision, split, and name alignment. A strict mismatch raises ReportCompatibilityError (a
ValueError) with a stable ReportCompatibilityReason; report-v1's missing identity rejects in this
mode rather than being inferred. The strict mode also requires explicit candidate and Measurement
identities: model/preprocessing revision may change between candidates, while scorer revision,
aggregation revision, target-transform revision, goal, and unit must match. Report-v2 identities written
before the target-transform field remain readable as explicitly unknown, but cannot satisfy strict mode.
explain_compatibility() is the payload-safe migration diagnostic for legacy and strict comparisons.
compare_reports() consumes the same analyzer and raises ReportCompatibilityError, still a
ValueError, with its ordered blocker diagnostics attached. Strict mode reports missing report-v1
identity explicitly; it never treats two unknown identities as compatible.
present_evaluation() and render_markdown() produce a deterministic local Markdown view from validated
report, comparison, and assessment objects only. Labels are escaped as text; the view adds no links,
scripts, assets, metadata, or inferred zeros. It marks report-v1 identity limits and partial execution
explicitly.
render_html() renders the same presentation model as a standalone responsive HTML document with semantic
headings and tables, inline local styles, and non-color status text. It has no JavaScript, CDN, remote
font, image, or link dependency; bounded sections are rendered rather than silently omitted.
telemetry-eval run --factory module:callable --output path is the local trusted-code seam: only this
command imports the named Consumer factory, which must return an EvaluationReport. compare reads two
validated JSON reports and never imports report-controlled names; its stdout is deterministic JSON and
diagnostics are bounded stderr. The command never mutates a baseline. assess currently reports only the
validated execution state when no Consumer policy is supplied, and returns inconclusive because it cannot
infer a policy. assess --assessment path instead accepts the existing bounded, validated
performance-evaluation/assessment-v1 evidence document and returns pass, fail, or inconclusive without
importing rule code. For a report assessment, --rules path accepts only the closed
performance-evaluation/rules-v1 JSON format: at most 64 threshold or regression rules with exact
fields and finite numeric tolerances. For example:
{"schema_version":"performance-evaluation/rules-v1","rules":[{"kind":"threshold","name":"quality-floor","measurement_name":"quality","minimum":0.9,"maximum":null}]}
Use --baseline only with a report policy when a declared regression rule needs it. Dynamic imports are
limited to run --factory; compare, assess, and render never import Consumer code. Assessment exits
are 0 (pass), 1 (policy fail), 2 (invalid input or usage), 3 (inconclusive or unavailable), and 4
(failed execution). Every error is bounded stderr JSON with one fixed error code
(invalid_usage, invalid_input, or execution_failure) and a fixed diagnostic; it never echoes report
contents, factory exceptions, credentials, or input paths. render emits the local presentation; policy
creation remains an explicit Consumer-owned operation rather than an inferred CLI rule.
When a caller needs all diagnostics instead of compare_reports() raising its first mismatch, use
explain_compatibility(baseline, candidate, strict_dataset_identity=True). Its result contains only
ordered fixed codes, fixed field paths, and warning/blocker severities—never a dataset revision, model
revision, path, case name, or other Consumer value. Candidate model and preprocessing revisions are
expected to change. Attach an explicit ExecutionIdentity (or the validated result of
collect_execution_identity()) when constructing the evaluator, then select a Consumer-owned Measurement
profile only when execution compatibility matters: hardware differences warn for quality but block timing
when a required timing control differs or is unknown. Compatibility consumes the report-attached identity;
it does not accept an untracked side-channel object.
For harness reproducibility, independently pass strict_provenance=True to compare_reports(). This
requires both reports to attach identical provenance with every code, lock, and distribution record
available. Missing, partial, or unavailable provenance never becomes verified. This deliberately does
not require equal CandidateIdentity: candidate model/preprocessing revisions may change, while the
evaluation harness evidence remains stable.
To make model and scorer provenance explicit, pass CandidateIdentity at evaluate() time and a
complete MeasurementIdentity mapping when constructing PerformanceEvaluator. Candidate model and
preprocessing revisions describe the candidate and may legitimately differ. Measurement revision,
target-transform revision, goal, unit, and aggregation revision describe scorer semantics; none is
inferred from a Python callable or configuration object. A structural custom Measurement must have one
matching mapping entry; its name, goal, and unit must agree with the object, while scorer,
target-transform, and aggregation revisions stay explicitly Consumer-attested.
RandomnessPlan owns independent ordering, candidate, and statistical-resampling base seeds. It derives
each local seed with a versioned SHA3-256 domain-separated hash, using the relevant trial, case, or
Measurement index. Changing the resampling base therefore cannot perturb case order or candidate seeds.
The effective plan and a candidate_determinism status are retained in reports; ordinary one-argument
callables remain unspecified because the library does not mutate a process-global RNG or infer a
framework's determinism. The legacy EvaluationPlan(seed=...) shorthand preserves its existing
seed + trial_index ordering behavior and expands the same base to all three retained streams.
Paired candidate execution¶
PerformanceEvaluator.evaluate_pair() runs two ordinary one-argument candidates in one bounded session.
It requires explicit DatasetIdentity, complete MeasurementIdentity records, and a distinct
CandidateIdentity for each candidate before either candidate executes. The evaluator uses each trial's
ordering seed to shuffle private case indexes (when configured) and interleave the two candidates for
each index. CandidateOrderPolicy.INTERLEAVED_BY_ORDERING_SEED names that reproducible policy.
The return value has two ordinary, schema-compatible EvaluationReport values plus ephemeral
PairedEvaluationObservation values. Each observation holds both successful private outputs for one
(trial_index, case_index) position and has no JSON or report serialization path. If one candidate
fails, its peer still executes the same private index and receives its own success/failure accounting;
that position simply has no paired observation. all_pairs_observed only reports evidence availability,
not a release decision. measurement_evidence then exposes a closed per-Measurement mode:
complete contains aligned in-process numeric CaseMeasurement scores and its original aggregation
function; incomplete and unsupported contain counts only. A missing pair, scorer failure, or a
CorpusMeasurement without an explicit private paired_resample callback (or another Measurement without
an explicit paired_score reducer) cannot supply release-comparison evidence. A corpus callback receives
only the selected in-process observations for each candidate and returns one finite scalar per resample;
it and those observations have no report or JSON representation. Ordinary aggregate reports cannot
manufacture paired uncertainty. release_evidence_available is evidence availability only, not a
Consumer release decision.
Paired case and group resampling¶
paired_resampling_interval() is a separate, dependency-free inference helper for Consumer-owned
numeric score vectors. It selects one shared case (or whole Consumer-defined group) index sequence for
both candidates, then returns their point estimates, delta, and deterministic percentile interval. It
does not accept or retain Evaluation Cases, case names, inputs, outputs, or group names: group mode uses
in-process non-negative integer positions only.
from telemetry.performance import (
PairedResamplingPlan,
ResamplingUnit,
paired_resampling_interval,
)
result = paired_resampling_interval(
baseline_scores,
candidate_scores,
groups=group_positions,
plan=PairedResamplingPlan(unit=ResamplingUnit.GROUP, seed=44),
)
The default estimand is explicitly case_weighted; group mode may instead request
ResamplingEstimand.GROUP_WEIGHTED. The helper requires at least two independent units, rejects
non-finite or unpaired scores, preserves whole-group membership, and processes one replicate at a time.
It defaults to confidence 0.95 and 10,000 resamples. Before execution it rejects (rather than
silently reducing) requested work above the fixed 100 million score-visit or one million retained
numeric-cell ceilings; callers may supply lower ceilings only. The existing EvaluationPlan bootstrap
remains a repeated-trial-variability summary and is not reinterpreted as paired case inference.
The numeric-cell preflight reserves normalized paired inputs, retained interval values, and (only for a
Consumer aggregate) one sequentially materialized selected-score vector; it never accumulates replicas.
Admission checks lengths and budget lower bounds before copying inputs, then bounds group expansion.
Relative ratios support only nonnegative point and replicate aggregates with a positive denominator.
Signed-domain or zero-denominator evidence retains absolute effects but cannot pass a relative gate.
Current aggregate comparison publication uses performance-evaluation/comparison-v3; v1/v2 documents
remain readable and bound absolute rules remain usable. Recompute private paired evidence for relative
assessment, since positive legacy summary scores cannot prove every bootstrap aggregate was nonnegative.
Slice and required-family inference support explicit corpus callbacks with aligned private observations
and repeated case blocks. Slice declaration order does not change name/revision membership identity.
Every paired result exposes a typed uncertainty descriptor. Its capability is
paired_population_interval; its provenance records the selected independent unit (case, group, or
trial), percentile-bootstrap method, confidence, resamples, independent-unit count, and fixed-seed
policy. Grouping therefore changes the declared effective count. Report MeasurementSummary.uncertainty
instead has the repeated_trial_variability capability and a trial-unit count. Repeating deterministic
cases does not inflate that count, and a corpus-level scalar never gains an invented case interval.
Quantile evidence sufficiency¶
percentile() and latency_measurement() remain descriptive summaries. A Consumer can compose a
QuantileSufficiencyRule with its ordinary value rule when a tail or slice decision needs independent
count and precision evidence. The rule links a named report Measurement to an in-process
QuantileInterval: an insufficient count, missing IID declaration, unbounded endpoint, or unmet width
policy produces an inconclusive assessment, never a pass. The report retains its descriptive value.
Consumers must declare an independently sampled unit (use a block or run for correlated arrivals), IID, and a finite width tolerance. This does not select a universal sample size, authorize adaptive stopping, or change the telemetry-capacity p99 floor.
Construct the in-process evidence from one numeric value per declared independent unit, then attach it to a rule for the matching report Measurement:
from telemetry.performance import (
IndependentUnit,
QuantilePrecisionPolicy,
QuantileSufficiencyRule,
quantile_interval,
)
tail_evidence = quantile_interval(
independent_run_latencies_ms,
quantile=0.99,
independent_unit=IndependentUnit.RUN,
iid_declared=True, # Consumer-attested sampling design
precision_policy=QuantilePrecisionPolicy(maximum_absolute_width=consumer_width_ms),
)
evidence_rule = QuantileSufficiencyRule("tail-evidence", "latency.p99", tail_evidence)
The caller supplies independent_run_latencies_ms and consumer_width_ms; these are not library
defaults. quantile_interval() uses an exact-binomial nearest-rank interval with 0.95 confidence by
default. Its finite endpoints and width must satisfy the declared policy before evidence_rule can
pass. Compose it with a value rule to assess the measured latency itself.
Slice inference diagnostics¶
assess_slice_inference() evaluates a declared slice's independent-unit count and finite interval against
a Consumer SliceInferencePolicy. Empty slices, predicate failures, unavailable Measurements, too few
independent units, unavailable intervals, and too-wide intervals have distinct non-passing statuses.
Eligible row or execution counts never replace the independent-unit count. A Consumer may suppress a
small independent count in the returned diagnostic; that diagnostic contains no row count, slice member,
input, output, or membership identity. The overall report Measurement remains descriptive even when a
required slice is inconclusive.
RequiredSliceAssessmentRule composes the bounded overall paired-improvement interval, Consumer-declared
slice name/revision/non-inferiority tolerances, slice diagnostics, and optional declared family confidence.
Every gate must pass. A supported overall or slice regression fails; missing, suppressed, insufficient, or
incomplete slice evidence is inconclusive. Supplied family evidence must match the exact required slice
revisions, rather than being relabeled as current evidence.
The contract fixture tests/contract/test_performance_slice_rules.py demonstrates a synthetic Consumer
path for pass, a hidden required-slice regression, and insufficient slice evidence. It serializes only
versioned reports, aggregate comparison evidence, and the assessment outcome; it deliberately performs
no model-promotion action.
Paired difference estimates¶
estimate_paired_differences() consumes a complete in-process PairedEvaluation, not two persisted
reports. For each Measurement it runs the original Consumer aggregation on the two sides of every shared
resample and returns an absolute improvement whose positive direction always means better. A minimize
Measurement therefore reverses the candidate-minus-baseline result and interval endpoints. Relative
improvement is a ratio calculated within every shared resample, never an absolute interval divided by one
baseline value; it is unavailable when a required denominator is zero. Difference estimates retain no
case scores and are not report serialization inputs.
AggregateComparisonDocument.from_paired_difference() is the separate, versioned exchange format for
those paired-derived aggregates. write_comparison_document() writes it atomically and
load_comparison_document() validates the closed schema. A document keeps only source report identities,
Measurement goal/unit, aggregate oriented effects and intervals, uncertainty metadata, and the explicit
relative_denominator_zero code when a relative interval is unavailable. It cannot contain case or pair
payloads, and there is intentionally no constructor that infers paired statistics from two ordinary
Evaluation Reports.
write_report() writes deterministic JSON atomically. load_report() validates the schema version,
types, finite numbers, timestamps, and a 16 MiB input bound before constructing immutable records.
EvaluationCheckpoint is a separate completed-trial restart boundary, not a Candidate-state serializer.
CheckpointIdentity.from_report() derives a safe evaluation/candidate/case-set/plan and optional
dataset, Candidate, and Measurement identity manifest. It must match before resuming any Candidate
invocation. A checkpoint retains only contiguous fully completed TrialResult numeric summaries, bounded
failure classifications, and a cursor with aggregate counts; an interrupted trial is absent and must restart
from its declared seed and setup contract. write_checkpoint() fsyncs a bounded 1 MiB deterministic JSON
temporary file before atomic replacement and directory sync; load_checkpoint() rejects truncated,
oversized, non-finite, or unknown-field documents. It never retains Evaluation Case inputs/expected values,
Candidate outputs/state, raw RNG objects, or serialized arbitrary objects. Replayable Consumers must
therefore tolerate repeated externally stateful invocations; mid-trial resume is intentionally unsupported.
ReplayableEvaluation is the only resume factory flow: it contains a frozen evaluator contract, safe
Candidate identity, and a zero-argument Consumer factory that constructs a fresh Candidate only after
the supplied checkpoint manifest has matched. resume() begins at the cursor's first absent trial,
replays that trial's warmups/setup contract and declared ordering seed, and invokes an optional checkpoint
writer only after a fully completed trial. It rejects private slice evidence and ordinary non-factory
execution because their required in-process evidence cannot be safely reconstructed. telemetry-eval run
accepts --checkpoint PATH only when its trusted --factory returns ReplayableEvaluation; it loads a
validated existing checkpoint or creates an empty one, then atomically writes each completed trial. A
crash during a trial may repeat externally stateful inference when restarted; this boundary is never
exactly-once execution.
ReportStore(root) is the optional dependency-free local history boundary for validated report documents.
It names each immutable JSON document by its SHA3-512 content digest and indexes only that digest, byte
size, creation time, and pin state in a recoverable SQLite transaction index. put() deduplicates and
never evicts automatically; get() validates both document digest and report schema; list() is
digest-ordered with a default page of 100 and a maximum of 1,000. The fixed store ceilings are 1 GiB and
10,000 records. prune() is an explicit retention action and preserves pinned baseline records, reporting
when pins prevent its requested target. The store accepts no report-derived paths, and recovery rebuilds
missing/stale index rows from valid atomic documents without a tracker or remote service.
telemetry-eval history provides the same local boundary without rerunning an Algorithm Candidate or
rewriting an Assessment: list --store root emits one bounded index page; show --store root --digest
emits the existing validated payload-free report; and export --store root --digest ... --output path
writes that validated document atomically to an explicit local destination. No history command imports
Consumer code or MLflow; remote MLflow delivery remains the separate injected-client library API. History
export reads the stored document and leaves it unchanged. prune requires a byte and/or entry target plus
exactly one mode: --preview returns the oldest-unpinned deletion plan without writing, while --target
performs that target. Pinned baselines remain retained. A target blocked by pins returns exit code 3;
invalid paths, digests, and forms return 2.
Explicit MLflow metadata export¶
export_mlflow_report(store, digest, client=..., destination=...) is a separate explicit action for a
report already retained in ReportStore. The base package does not import MLflow, discover a tracker, or
enable autologging. A Consumer supplies the destination label and an injected MlflowMetadataClient that
owns its tracking URI, credentials, and MLflow SDK call.
Only the closed MlflowReportMetadata projection leaves the process: report digest/schema, safe report
labels/status, aggregate counts, descriptive Measurement scores, and aggregate slice counts. Report JSON,
trials, failures, case names, inputs, expected values, outputs, exception classifications, and credentials
are never handed to the client. The request contains one canonical, bounded JSON artifact of precisely the
same projection and a destination/digest idempotency key for clients whose backend can use one. The bounded
policy permits at most 30 seconds and three calls. It retries only a
client-confirmed retryable failure; any uncertain acknowledgement, exception, invalid acknowledgement, or
deadline expiry becomes the explicit indeterminate result and is not retried. Export never mutates,
deletes, or pins the retained local report and does not promise exactly-once remote delivery.
Explicit evaluation telemetry linkage¶
EvaluationTelemetryAdapter has no global telemetry state or autologging. A Consumer injects its
Telemetry, closed TelemetrySchema, and an EvaluationTelemetryMapping; construction rejects every
unregistered operation, context attribute, operation attribute, or metric name before emission. The
adapter builds EvaluationDeploymentLinkage only from a SHA3-512 report digest, the report's explicit
candidate model revision, and an optional lowercase trace identifier explicitly permitted by the mapping.
The linkage identifiers are bound as context, while report schema/version status is operation metadata. They are never metric attributes. The adapter emits only four fixed execution aggregates and explicitly mapped Measurement summary scores, all with empty metric attributes; it never emits cases, inputs, expected values, outputs, failure details, exception text, or candidate names. Mapping cardinality and combined context/operation attributes remain bounded and schema-validated, and an unpermitted trace reference or absent candidate identity rejects before telemetry side effects.
LifecycleTelemetryMetrics is separately opt-in and emits only the report's total elapsed duration plus
derived warmup, measured, and failed execution counts when report-v2 carries an explicit lifecycle timing
scope. It never invents setup, reset, teardown, or per-phase durations. DelayedAggregateQualityObservation
is likewise an explicit Consumer call: each aggregate supplies its Measurement name, declared revision,
finite score, and positive count. It contains no labels, cohort, or maturity policy; the library neither
fetches labels nor decides when a cohort is mature. A configured exporter failure is contained and does
not change the already-produced candidate report. EvaluationTelemetryAdapter.disabled() is side-effect
free and imports no OpenTelemetry exporter; context bindings use ordinary context managers and restore
the caller's context across concurrent tasks.
Reference-only curation selection¶
CurationSelectionManifest is immutable Consumer-owned selection evidence, not a dataset transport. It
retains only a source report SHA3-512 digest, source model revision, selection-policy revision, opaque
Consumer dataset revision, and a bounded selected count. Its canonical JSON has a deterministic SHA3-512
identity. There are no case IDs, examples, payloads, object paths, signed URLs, dereference methods, or
network calls. Credential-shaped or URL-shaped references reject with fixed errors that do not echo the
submitted value; selection policy, dataset construction, and retrieval remain Consumer-owned.
The executable synthetic pattern in
docs/examples/consumer_curation_delayed_labels.py
shows the intended delayed-label boundary. A Consumer-owned in-process store resolves an opaque selection
reference, applies its own consent, access, retention, redaction, and label-adjudication policies, then
creates fresh EvaluationCase values and a DatasetIdentity for the test revision. Its resolver
rejects every non-test record, so curated training records cannot enter this evaluation. The selection
reference, private identifiers, raw inputs, and labels stay in the Consumer store; the resulting
Evaluation Report and optional telemetry retain only their existing payload-free aggregate evidence.
The example uses no network or paid service. Consumers must supply and operate their own durable retention
and access controls; neither a curation manifest nor the evaluator grants access to, fetches, or stores
private records.
Injected async LLM streaming observations¶
observe_llm_stream(stream, content=..., plan=...) is a dependency-free observer for a Consumer-injected
async stream; it does not import an LLM provider SDK, construct prompts, or send a request. Before the
stream is opened, LlmStreamingPlan bounds consumption to at most 4,096 chunks and 30 seconds by default
(100,000 chunks and 300 seconds are hard maximums). The observer consumes incrementally and retains no
chunk, completion text, prompt, provider error, model name, or provider object.
LlmStreamingObservation retains only a closed aggregate: chunk/nonempty-content/inter-chunk/completion
counts,
first nonempty content latency, total inter-chunk duration, completion latency, terminal status, and
classified cancellation/error counts. First-content latency is not called TTFT. A Consumer provider adapter
may pass is_provider_token_boundary; only then can true_time_to_first_token_ns be populated. Otherwise
TTFT is explicitly unknown, even if the observer saw text. LlmUsage is similarly either unknown or
Consumer-extracted provider_reported input/output units; the core never infers units from content.
On ordinary provider/adapter errors, the observer returns an error status and a fixed error count without
exception text. On timeout or chunk limit it closes the async iterator and returns the corresponding status.
On task cancellation it closes the iterator and propagates LlmStreamCancelledError (an
asyncio.CancelledError subclass) containing only the aggregate cancellation observation. The standalone
observation document is payload-free and is not an Evaluation Report evidence section or telemetry event.
Consumer-injected LLM judges¶
execute_llm_judges() calls a Consumer-injected async judge callable; it imports no provider SDK, sends no
network request itself, and performs no pricing lookup. Each LlmJudgeRequest keeps a private Consumer
payload alongside conservative per-attempt input/output-unit reservations. Its returned decision remains in
the LlmJudgeExecution.private_results channel, which deliberately has no serialization method. Only its
separate LlmJudgeEvidence is payload-free evidence suitable for persistence or presentation.
LlmJudgeIdentity declares rubric, model, and configuration revisions. These are strict comparison protocol
identity: use require_compatible_llm_judge_identity() before comparing judge-derived results. The default
plan permits one concurrent call, zero retries, a 30-second per-attempt timeout, and at most 1,000 attempted
requests. It also bounds concurrency, retries, input/output unit reservations, and optional Consumer-declared
cost. An optional LlmJudgeRateSchedule(currency, input_cost_per_unit, output_cost_per_unit) is supplied by
the Consumer; the core never obtains provider prices or exchange rates.
Every initial call and retry reserves its declared units before invocation. Once an attempt, unit, or optional
cost budget is exhausted, no later call starts; existing reserved work can complete. Provider-reported actual
units are reconciled only when every attempted call reports complete input/output usage. Missing usage or an
error makes actual usage explicitly unknown; actual usage above its reservation remains explicit
overshoot, never silently capped. Evidence contains aggregate counts, revisions, reservations, usage state,
and optional Consumer currency/cost—never judge payloads, decisions, prompts, completions, provider errors,
or configuration values.
Safe aggregate GenAI telemetry mapping¶
GenAiAggregateTelemetryAdapter is an explicit bridge from those payload-free stream and judge
aggregates to a Consumer's ordinary TelemetrySchema. The reviewed convention snapshot is pinned as
development-2026-09-20 in compatibility.toml and exposed as
GENAI_CONVENTION_REVISION. The Consumer must register the operation, the gen_ai.usage.kind operation
attribute (or its own chosen safe equivalent), and every numeric metric name. The adapter preflights that
closed vocabulary, emits no metric dimensions, and exports no prompt, completion, chunk content, rubric,
model/configuration revision, provider error, credential, or cost schedule.
Chunk counts and first-content timing stay separate from true token timing: a content chunk never becomes
a token, and the true-TTFT metric is omitted unless a provider adapter supplied an actual token boundary.
gen_ai.token.type is intentionally not used: its normalized token name violates the attribute
privacy floor and cannot be enabled by schema registration, including on another attribute surface.
Consumers may choose a safe registered name such as usage.kind, subject to the same validation.
Retrieval examples continue to use the generic duplicate-safe ranking
Measurements (precision_at_k, recall_at_k, reciprocal rank, average precision, and NDCG); the GenAI
bridge does not create a second retrieval metric model. GenAiAggregateTelemetryAdapter.disabled() is a
side-effect-free no-op and imports no OpenTelemetry or provider SDK.
Opt-in code and dependency provenance¶
collect_provenance() is a separate, explicit helper for local reproducibility evidence. It does not
run during import or import framework packages. A caller can supply its result to a report-v2 evaluator;
collection itself remains explicit, and callers select only package names in ALLOWED_DISTRIBUTIONS:
from pathlib import Path
from telemetry.performance import (
CaseMeasurement,
DatasetIdentity,
EvaluationCase,
PerformanceEvaluator,
collect_provenance,
)
provenance = collect_provenance(
repository=Path("."),
lock_file=Path("uv.lock"),
dependency_distributions=("opentelemetry-api", "sqlalchemy"),
)
report = PerformanceEvaluator(
"catalog-evaluation",
(EvaluationCase("case", "private-input", 1),),
(CaseMeasurement("score", lambda observation: float(observation.output)),),
dataset_identity=DatasetIdentity("catalog", "2026-09-20", "test"),
provenance=provenance,
).evaluate(lambda _value: 1, candidate="candidate")
assert report.provenance == provenance
The result holds a Git revision and dirty flag when Git can inspect the supplied repository, a bounded
SHA3-512 lock digest, the installed telemetry distribution version, and only the selected dependency
versions. Missing distributions, a non-Git directory, inaccessible inputs, timeouts, and an oversized
lock are classified as unavailable evidence rather than guessed values. Serialized evidence contains
no repository or lock path, lock contents, source text, Git diagnostics, or environment values.
Execution identity and Measurement compatibility¶
ExecutionIdentity is an immutable, closed, payload-free record of declared operating system and
architecture, CPU model/count, accelerator model, device class, backend/runtime, precision,
thread/batch/concurrency controls, and timing scope. Every field may be explicitly unknown (None);
the core never guesses it from a host, callable, framework import, environment variable, or device.
There are no hostname, device UUID, path, arbitrary metadata, or provider-configuration fields.
collect_execution_identity() is the opt-in companion for bounded local collection. Its
execution-identity-collection/v1 result retains a closed field list and classifies each field as
available, unavailable, or unsupported. The default reader uses only the standard library for OS,
architecture, CPU model, and CPU count. Accelerator/backend/runtime/precision evidence is collected only
from an explicitly passed framework reader, so importing this package never imports or probes a framework.
No reader means a missing GPU remains unavailable; thread count, batch size, concurrency, and timing scope
remain unsupported because Consumers must attest those execution controls explicitly. Reader diagnostics
and unknown fields are dropped, and the result neither enters telemetry nor attaches to an Evaluation
Report. Controlled fixture results are local evidence, not a hardware or hosted-environment qualification.
compare_measurement_execution(reference, candidate, profile=...) applies one closed
MeasurementCompatibilityProfile. The quality profile allows execution and hardware differences,
returning structured differences and a hardware warning rather than pretending the provenance is equal.
The timing profile requires known, equal backend, device class, precision, thread count, batch size,
concurrency, and timing scope. A missing required field or a difference is incompatible with a stable
reason code. Equal hardware does not prove that a machine was idle, and no profile is an acceptance
policy; Consumers retain ownership of both Measurement meaning and acceptance decisions.
Execution semantics and limits¶
- Cases execute serially so ordering, timing, and algorithm thread-safety remain explicit.
- Explicit
RandomnessPlanshuffling is deterministic from its domain-separated ordering stream. The legacyseedshorthand retains its establishedseed + trial_indexordering. - Warmup outputs are discarded and never passed to Measurements.
- By default, algorithm and Measurement exceptions are isolated and make the report partial. Set
continue_on_error=Falseto preserve fail-fast behavior. - A partial trial passes only successful observations to Measurements; consumers should treat report completeness as part of their release policy when missing observations could bias a score.
- The module bounds cases, Measurements, repetitions, warmups, total executions, bootstrap samples, and persisted report size. It does not attempt to kill or time out arbitrary Python callables.
- Headline Measurement scores are medians across repeated-trial scores. Reports also retain the mean, range, standard deviation, all trial scores, and a deterministic percentile-bootstrap interval. Repetitions alone establish neither independent population sampling nor independent process starts; Consumers own those experimental assumptions. The interval describes repeated-trial variability.
Opt-in execution adapters¶
evaluate_lifecycle_adapter() composes a LifecycleExecutionAdapter around an existing synchronous
adapter when a Consumer needs one warmed candidate session: setup runs once, an optional reset runs once
per trial before warmups or measured calls, and teardown runs once after successful setup. Warmups remain
discarded from Measurements and measured-call timing. Setup, reset, and teardown failures are classified
without retaining exception text; setup never invokes a case, and teardown never masks a primary error.
Ordinary evaluate(callable, ...) retains its original no-lifecycle behavior.
Sequential reuse of one LifecycleExecutionAdapter begins a fresh session: reset and reset-failure
bookkeeping is cleared at setup, and teardown closes that session even when it fails. Each trial's
Consumer reset callback therefore runs once in each session. This does not authorize concurrent reuse
or implicit mutation of Consumer model state.
When an evaluator already carries explicit report-v2 ExecutionIdentity evidence, a Consumer may pass a
closed LifecycleTimingScope to evaluate_lifecycle_adapter(). It declares whether the retained timing
means a warmed invocation or reconstruction, plus independently declared compilation (excluded,
included, or precompiled) and cache (disabled, cold, or reused) policy. The evaluator never
compiles, clears, reuses, or infers a cache; this is bounded Consumer attestation, not framework control.
The declaration writes performance-evaluation/execution-v2; execution-v1 and legacy reports remain
readable with an explicitly unknown lifecycle timing scope. A timing-profile comparison blocks a missing
or unequal scope, while a quality-profile comparison retains it as a nonblocking warning.
The existing evaluate(callable, candidate=...) interface remains the serial, dependency-free default.
evaluate_adapter(adapter, candidate=...) is the explicit synchronous alternative for a
SyncExecutionAdapter declaring candidate_randomness. SeededCallableExecutionAdapter is the
dependency-free reference adapter for a two-argument (input, context) callable; ordinary one-argument
callables continue to use evaluate() unchanged.
evaluate_batches() is the explicit Consumer batching seam: collate, predict_batch, and split
remain Consumer-owned; BatchPlan defaults to size one and retains final partial batches. Evidence keeps
whole-batch latency and aggregate cases/s separately, never a divided per-case latency. Invalid output
cardinality or a collate/predict/split failure fails every case in that batch. Padding requires an
explicit mask whose true entries equal actual cases.
ResourceSampler is an explicit injected process/device observation seam. It samples at a bounded
10–60,000ms minimum polling interval (100ms default), retaining online count/min/max/mean, scope, unit, and
device class—never UUIDs or raw samples. Permission, missing-device, and reader failures are unavailable
resource evidence and do not alter candidate quality. Short runs can miss peaks between samples. Optional
psutil, NVML, and Torch reader factories resolve their package only when explicitly requested.
These readers and the sampler are implemented, not planned stubs. Factory loading/device lookup can
fail before sampling; the Consumer owns that construction boundary. Exceptions from an injected reader
during sampling become unavailable resource evidence. Fake/injected contracts do not qualify real
devices or guarantee that an installed optional package can operate a device.
The Consumer calls sample(); there is no background scheduling. Its injected monotonic clock
admits an immediate first attempt, then skips calls before the minimum interval, including after
reader failures. Late polls perform one read without catch-up; the configured interval is not an
assertion of an exact observed cadence. Invalid or regressing clocks fail before a reader call.
For NVML, the Consumer initializes the shared session before reader construction and shuts it down
only after all readers/samplers finish. Neither the factory nor sampler initializes or shuts down
NVML, so stopping one sampler cannot close a peer's session. Construction-time missing initialization
or unsupported-device errors remain Consumer-owned; sampling failures produce unavailable evidence.
PyTorchPeakSampler is a separate explicit lifecycle boundary: it resets one declared device's peak
counters at start and returns distinct allocated and reserved device-wide summaries at stop. Ownership is
exclusive per device so concurrent resets cannot mix runs; it is not CUDA qualification evidence.
Equivalent selections such as cuda and cuda:0 resolve to the same slot when device zero is current.
The resolved index is frozen at start for reset, reads and release, independently of later current-device
changes; distinct resolved devices can proceed independently.
For each adapter invocation, the evaluator derives a candidate seed from the effective
RandomnessPlan using its trial and original case index and supplies it in immutable
ExecutionContext(trial_index, case_index, phase, candidate_seed). Consumers create local or
framework-scoped generators from that seed; the platform never mutates a process-global random generator.
The context contains no payload, expected value, output, case name, secret, or arbitrary metadata and
never enters a report or telemetry. Reports mark adapter executions as controlled candidate
determinism, meaning the seed handoff was explicit rather than a claim of universal framework determinism.
execute_sync() and execute_async() own a single setup → invoke → teardown session after
validating required capabilities before any lifecycle side effect. Teardown runs exactly once after a
successful setup, including if invocation fails. Async cancellation is cooperative: awaited teardown runs
before cancellation propagates, but the library neither starts background work nor promises to terminate
an adapter that suppresses cancellation. CallableExecutionAdapter wraps an ordinary one-argument
callable as the reference implementation, so existing candidates require no changes.
evaluate_async_candidate(adapter, values, plan=...) is the bounded in-process async companion for a
caller already inside an event loop. It never calls asyncio.run; a structured TaskGroup owns up to 256
workers and an admission queue of at most 1,024 pending private inputs. Its per-call and total deadlines
must be positive, finite, and no more than 30 seconds. A cooperative deadline produces aligned partial
evidence with an explicit per_call_timeout or total_timeout status rather than an ordinary candidate
failure. Task-group cancellation awaits adapter teardown before returning that partial evidence, while
cancellation requested by the caller propagates unchanged. Ordered result records retain only input
position, nonnegative producer admission wait, queue wait, candidate duration, private output, and a
failure class name without exception text. Candidate duration surrounds the awaited adapter call; queue and
admission wait are separate rather than mislabeled as candidate latency. Each item uses the existing async
adapter setup/invoke/teardown contract. This is not the synchronous one-session lifecycle evaluator and
does not attach warmed/reconstruction timing scope evidence it cannot establish.
Total-deadline results preserve observed time for phases that began. Running candidate duration ends
after cooperative adapter teardown, while unstarted queued work and blocked admission stop waiting at
the total-expiration boundary. Phases that never started retain zero; completed results are unchanged.
evaluate_in_spawned_child() is the opt-in direct-child containment boundary for a trusted importable
Consumer factory. A fresh spawn process constructs cases, models, and Measurements locally and returns
exactly one report as at most 16 MiB of JSON bytes over a dedicated pipe. The parent parses and validates
that report before accepting it; a missing factory, factory failure, child crash, oversized response, and
malformed response remain distinct closed outcomes. No pickle result channel or arbitrary object
deserialization is used. This is failure containment, not a security sandbox, and it does not claim to
contain descendants started by Consumer code.
This base package neither discovers nor imports PyTorch, batch engines, MLflow, or other framework
packages. The optional package registry is dependency-free and lists seven separately installable extras:
performance-pytorch, performance-sklearn, performance-resources, performance-nvml,
performance-mlflow, performance-pytest, and performance-datasketches. Call
load_optional_integration(OptionalIntegration.…) only at a Consumer's explicit integration boundary;
when its direct package is missing it reports the exact extra to install. The direct
telemetry.performance.integrations.torch module lazily loads Torch only during adapter setup. Its
PyTorchExecutionAdapter requires Consumer-established eval state (or an explicit setup callback),
uses inference mode, and in synchronized end-to-end mode synchronizes the selected CUDA device before
and after each model call, including a failing call. PyTorchTimingScope records the Consumer-declared
device, precision, stream,
preprocessing, transfer, and compilation boundary. CPU execution remains unsynchronized; neither this
adapter nor fake-backend tests qualify CUDA hardware.
For CUDA_EVENT_DEVICE_ONLY, the adapter scopes the declared device and selected stream around both
timing events and model execution, waits for the ending event, and restores the previous device/stream
on exit. A mismatched stream device rejects before model invocation. This preserves Consumer-established
eval state and preprocessing/transfer policy; deterministic stream-aware tests are not GPU qualification.
The existing preprocessing and transfer callbacks execute in that selected context, in their original
order and before the start event, so asynchronous preparation feeds the same stream as model work.
Preparation remains excluded from device-event duration. Ordinary context/event cleanup errors cannot
replace a primary model failure; preparation failures also restore the ambient contexts.
sklearn_classification_measurement() is the explicit lazy scikit-learn classification adapter:
it declares metric, ordered classes, averaging,
positive class, zero-division behavior, and optional private weights with a revision. Its identity commits
to that configuration and the installed sklearn version. Label metrics accept declared labels; ROC AUC and
average precision require finite, normalized probability vectors in declared class order. Empty and
single-class inputs remain reason-coded unavailable rather than receiving an invented favorable score.
Binary precision, recall and F1 default the positive class to the second declared class, with identical
Measurement identity for an explicit equivalent choice. Explicit first-class selection remains valid.
sklearn_regression_measurement() similarly declares MAE, RMSE, or R² with its unit, target-transform
revision, and multioutput aggregation. R² always uses sklearn's force_finite=False; a constant target
is reason-coded unavailable rather than silently becoming 0 or 1.
sklearn_calibration_measurement() declares Brier score or log loss with ordered class labels and a
Consumer-owned probability-policy revision. It accepts only finite class-ordered vectors in [0, 1]
that sum to one; vectors exist only while scoring, while the report retains the aggregate score and
digest identity.
Its reliability() companion emits class-indexed equal-width bin summaries. The default policy has 10
bins and rejects more than 100; every empty bin remains visibly unavailable. A Consumer may opt into a
count-weighted classwise ECE. The deterministic reliability identity commits to class ordering, the
probability policy, and the bin policy; it never retains case names or individual probabilities.
Other installable packages remain installation-only; adapter availability is not provider or hardware
qualification. PyTorch CUDA is explicitly
unsupported until a later feature retains real-device evidence; mocks and package presence cannot change
that classification.
The ranking helpers implement duplicate-safe precision, recall, hit rate, reciprocal rank, average precision, and graded NDCG at a positive cutoff. Consumers still own what constitutes relevance and how cases are sampled; the helpers provide mechanics, not product meaning.
Opt-in local serving sweep¶
Run the executable synthetic example with the configured local environment:
uv run python docs/examples/consumer_serving_sweep.py
ServingSweepPlan runs a bounded rate/concurrency grid against a Consumer-injected client. It records
only fixed opaque endpoint/configuration revisions, closed cold/warm labels, serving aggregate evidence,
and an explicit ExecutionIdentity resource record. The Consumer must supply the actual machine and
execution controls needed to interpret a local point: operating system/architecture, CPU or accelerator
description and count, backend, device class, precision, thread count, batch size, concurrency, and
timing scope. It must use one fixed endpoint/configuration identity across a curve. URLs, endpoint
credentials, request payloads, responses, exception messages, and arbitrary environment values are not
accepted as serving evidence.
Every declared point is retained, including failed, timed-out, dropped, and generator-limited points. The portable Markdown/HTML presentation keeps scheduled-to-completion separate from dispatch latency to avoid coordinated omission. Curves are local observations only: this feature intentionally provides no absolute heterogeneous-hardware capacity or confidence-interval gate.