AI System DesignAI System Design FundamentalsModule 11 — Architecture contracts and integration

Designing Model-Independent Prediction APIs with Uncertainty and Validity Contracts

Question 22 of 47 · Updated

On this page

Design the API around a stable domain prediction, not a model's native output. Every result must state what is being predicted, for whom or what, under which conditions, at what observation time, in which units, with what kind of uncertainty, and until when the result is eligible for use. Use typed success and abstention variants, an explicit validity and freshness contract, and trustworthy release and data provenance. A consumer must be able to reject an incompatible, stale or unsupported result without understanding the internals of a neural network, tree ensemble or external model provider. A valid estimate is evidence, not authority to execute a business action.

Original curriculum question: How would you design an AI prediction API whose responses include uncertainty, validity periods and model-independent result contracts?

ASD-081 | Module 11 — Architecture contracts and integration | Progressive learning order 9. The preceding architecture fundamentals established requirements, capacity, execution, sourcing, decision authority and topology. This lesson defines the first reusable integration contract. ASD-006 separates prediction from policy and transactional execution; this lesson specifies the prediction artifact that crosses that boundary. Existing Machine Learning confidence/uncertainty and MLOps calibration lessons explain how to estimate and assess uncertainty; the MLOps inference API evolution lesson explains consumer compatibility during version upgrades. Here we design the initial domain-owned response, including tagged uncertainty types, as-of and expiry semantics, consumer eligibility checks, invalidation and cache behavior. The later reusable answer-generation API lesson addresses factual claims, citations and answer-level abstention; it is not a generic numerical forecast contract. Cross-channel consistency and event composition receive separate lessons.

All examples, times, thresholds, forecast distributions and observed counts below are fictional teaching fixtures. They are not evidence of a calibrated production model or a recommended universal freshness limit.

1. Begin with the question the consumer actually needs answered#

Suppose a delivery product originally calls a regression model directly. The model returns a floating point value of 600. A new engineer cannot tell whether 600 is seconds remaining, total journey seconds, a Unix timestamp, a route score or a normalized feature. Nor can the engineer tell how old the underlying location was or how accurate the estimate is. If the model is replaced, every caller may need to learn a new output representation.

Instead, define a domain contract such as remaining delivery duration in seconds, conditional on information available at prediction time, for a specified order in a permitted operating population. The model implementation can change from a historical baseline to gradient boosting to a neural forecasting model without changing this meaning. The prediction should not be confused with a delivery promise or a guarantee of arrival.

For a classification API, define the positive event and the prediction horizon. "Risk = 0.8" is meaningless without knowing whether it denotes delay beyond the promised deadline, failure to deliver in the next hour, or an uncalibrated ranking score. A generic field called confidence tends to hide these differences.

Write a semantic specification before a JSON schema:

ElementExample domain contract
TargetRemaining duration until the delivery-completed event
UnitSeconds, nonnegative, relative to the declared prediction instant
EntityCanonical order ID, tenant and authorized purpose
PopulationOrders already assigned to a driver with supported route evidence
Reference assumptionsCurrent route/assignment and specified operating conditions
Point estimateConditional median of remaining duration
Uncertainty90% predictive interval from an approved method
Time basisPoint-in-time eligible observations, UTC timestamps
Use validityAt most a short approved lifetime, invalidated by relevant state changes
Unsupported inputExplicit abstention instead of invented numbers

The contract owner is the domain/application team with model and evaluation owners, not whichever runtime currently produces a score. If the median changes to a mean, the prediction target changes or the reference operating policy changes, reassess the semantic contract even if its data type stays the same.

2. Separate stable semantics from model-specific provenance#

An API should have a stable envelope with a target-specific payload. Model independence does not mean suppressing model identity or forcing every prediction into the same numeric shape. It means that consumers know the meaning of a result without inspecting an estimator class, vendor response or tensor layout.

Loading diagram…

The adapter can translate units, named class labels, tensor output, an uncertainty representation and internal failure states. It must not falsely convert a raw score to a calibrated probability, or manufacture a prediction interval if the underlying approved release lacks such evidence. If the target contract requires an interval and the candidate cannot provide one, it is not compatible for that contract.

There are several independently versioned identities:

  • Contract ID/version: externally defined syntax, semantics and supported states.
  • Target definition/version: event, outcome, horizon, unit and reference assumptions.
  • Model release: immutable approved artifact and runtime/preprocessing bundle.
  • Calibration or uncertainty release: method, artifact, evaluation population and assumptions.
  • Input snapshot: source revisions, feature definitions and observation times.
  • Prediction identity: opaque ID for one immutable issued prediction or abstention.

A model-independent client can accept releases r7 and r8 under eta/v1 when the approved compatibility registry establishes that both meet the same contract. It still records which release was used. The service need not expose proprietary feature names or the full training data; governed references can support traceability without leaking sensitive material.

3. Design a tagged response contract, not a bag of nullable values#

Use explicit variants. A predicted result contains the target and its estimate, uncertainty, time and provenance. An abstention contains a reason and scope, without pretending to contain an estimate. Transport and service failures have their own error contract. The target defines whether a particular uncertainty representation is mandatory, optional, or prohibited.

An illustrative response to an authorized request for a delivery estimate:

JSON
{ "contract": "eta/v1", "prediction_id": "pred_019", "target": "remaining_delivery_seconds", "target_definition": "eta-target/v1", "subject": {"type": "order", "id": "order_17"}, "status": "predicted", "result": { "kind": "numeric_forecast", "unit": "s", "point": {"value": 600, "statistic": "median"}, "uncertainty": { "kind": "prediction_interval", "lower": 480, "upper": 850, "nominal_coverage": 0.90, "method_id": "split_conformal_v1" } }, "time": { "feature_as_of": "2026-01-15T10:00:00Z", "predicted_at": "2026-01-15T10:00:10Z", "valid_from": "2026-01-15T10:00:10Z", "valid_until": "2026-01-15T10:00:50Z" }, "provenance": { "model_release": "eta-r7", "feature_contract": "route-features/v2", "snapshot_ref": "snap_812", "uncertainty_release": "interval-r4", "evaluation_ref": "eval_2026_01", "entity_revision": "assignment-19" } }

The server derives tenant and authorization from trusted request context. A response may expose an opaque subject and scope identifier rather than the tenant's internal identifier. The consumer must validate the association with its authorized request, and the API must enforce permissions before producing or returning the prediction.

A valid abstention uses the same target semantics and temporal identity but a different tagged payload:

JSON
{ "contract": "eta/v1", "prediction_id": "pred_020", "target": "remaining_delivery_seconds", "target_definition": "eta-target/v1", "subject": {"type": "order", "id": "order_17"}, "status": "abstained", "abstention": { "reason_code": "missing_features", "retry_guidance": "after_route_update" }, "time": { "feature_as_of": "2026-01-15T10:00:00Z", "predicted_at": "2026-01-15T10:00:10Z", "valid_from": "2026-01-15T10:00:10Z", "valid_until": "2026-01-15T10:00:20Z" }, "provenance": { "model_release": "eta-r7", "feature_contract": "route-features/v2", "snapshot_ref": "snap_813", "entity_revision": "assignment-19" } }

The absence of a numeric estimate is intentional. No estimate, unknown, zero duration and an expired estimate are different states. If no feature snapshot exists, the abstention schema should permit an explicitly absent observation reference according to the reason code; never fabricate a feature timestamp to satisfy a required field. The example has a partial snapshot with missing required features.

Do not include action fields such as "refund_approved": true in a prediction contract. A separate policy or transaction API determines approval and effect. A decision consumer may compute its own permitted action, but the model result remains immutable evidence.

4. Structural schemas and semantic validators#

OpenAPI 3.1 and JSON Schema 2020-12 provide a useful way to describe tagged payloads. The following JSON Schema is a deliberately partial schema for the *result payload* of the predicted and abstained branches, not the complete response envelope:

JSON
{ "$schema": "https://json-schema.org/draft/2020-12/schema", "oneOf": [ { "type": "object", "required": ["status", "estimate_seconds", "interval"], "properties": { "status": {"const": "predicted"}, "estimate_seconds": {"type": "number", "minimum": 0}, "interval": { "type": "object", "required": ["lower", "upper", "nominal_coverage", "method_id"], "properties": { "lower": {"type": "number", "minimum": 0}, "upper": {"type": "number", "minimum": 0}, "nominal_coverage": {"const": 0.90}, "method_id": {"type": "string", "minLength": 1} }, "additionalProperties": false } }, "additionalProperties": false }, { "type": "object", "required": ["status", "reason_code"], "properties": { "status": {"const": "abstained"}, "reason_code": { "enum": ["missing_features", "unsupported_input", "insufficient_evidence"] } }, "additionalProperties": false } ] }

This compact payload representation is separate from the preceding richer illustrative HTTP envelope; a real specification must choose one canonical wire representation and implement it consistently. The schema validates structure, primitive ranges and mutually exclusive states. It does not ensure lower is no greater than upper, establish calibration, ensure a valid source timestamp or prove that the model is permitted for this tenant. Standard JSON Schema cannot express arbitrary comparisons between sibling numeric fields in a portable way. Use explicit semantic validation in producer and consumer as appropriate.

Validate timestamps with a strict RFC 3339 parser and explicit timezone handling. The JSON Schema format annotation is not universally an enforced assertion; configure validators and test actual behavior. JSON numbers cannot represent NaN or Infinity in a conforming JSON document; reject nonstandard parser extensions, overflow and invalid internal values before serialization. Avoid accepting booleans as integers in a dynamically typed language merely because its type hierarchy permits it.

Strict schemas improve predictability but complicate adding fields. Choose a documented extensibility policy: reject unknown fields for fixed security-sensitive command schemas, or explicitly allow extension fields in read-only prediction envelopes when supported clients can ignore them safely. Version major incompatible semantics; do not assume an additive field is harmless to strict clients.

5. Represent uncertainty with the right meaning#

The uncertainty field needs a discriminated type with documented units, method and interpretation. A single decimal "confidence" cannot represent every model family.

Uncertainty representationMeaningConsumer caution
Calibrated binary probabilityEstimated probability of a precisely defined eventCalibration is population-dependent; not a guarantee for an individual
Class probability distributionProbabilities over a specified mutually exclusive exhaustive label setValidate class identities and normalization; distinguish unknown from a valid class
Predictive intervalRange for a future observation at stated nominal coverageCoverage assumptions and population matter; not a confidence interval for the mean
QuantilesEstimated conditional distribution percentilesCheck ordering, level definitions, units and coverage evidence
Prediction setSet of plausible class outcomes with stated method/coverageA set containing several classes is not a single confident label
Raw scoreRanking or preference signal in a defined rangeDo not use as a probability unless a validated calibration transform exists
UnavailableNo valid uncertainty estimate under the contractMust not be replaced by fabricated confidence

A calibrated binary probability p of 0.20 means that, among comparable cases assigned probabilities near 0.20, the event occurs approximately 20% of the time if calibration holds. A model might rank well while being poorly calibrated. Attach the target event, horizon, approved calibrator reference and evaluation scope. Calibration evidence is not the same as the value returned by the model. A new geography or data shift can invalidate applicability even when output numbers remain between zero and one.

If a binary model returns logits, a sigmoid can convert a logit to a number in [0,1], but this does not by itself establish empirical calibration. Platt scaling, isotonic regression or temperature scaling may be used when appropriate, with separate held-out evaluation and release controls. The specialist calibration article develops fitting and monitoring those methods; here the API must state which semantics are actually supported.

For multiple classes, return named categories and probabilities, not an undocumented array whose index order depends on the training library. If the categories are mutually exclusive and exhaustive, validate the sum against a declared numerical tolerance, not exact floating-point equality. For multilabel independent events, probabilities need not sum to one. The contract must distinguish these tasks.

Aleatoric uncertainty describes variability in outcomes conditional on available information; epistemic uncertainty describes limitations in model knowledge. Some methods estimate aspects of these separately, but a single predictive probability or entropy is insufficient to establish their decomposition. Do not advertise a separation unless the method and evidence support it.

6. Predictive intervals and coverage: a numerical example#

Suppose the ETA API predicts a median duration of 600 seconds and a nominal 90% predictive interval of [480, 850] seconds, relative to 10:00:10 UTC. The median arrival estimate is 10:10:10, with interval endpoints 10:08:10 and 10:14:20 UTC. The interval need not be symmetric around the median. A separately defined mean or point estimate is not always required to lie inside every valid prediction interval, so do not impose that constraint universally; document it when a particular interval method guarantees it.

A predictive interval concerns a future outcome. A confidence interval for a parameter or aggregate performance metric concerns uncertainty in estimation of that parameter. Neither is automatically a probability statement about one fixed realized delivery. Under suitable assumptions, a 90% frequentist prediction interval procedure has nominal coverage over repeated eligible cases. Individual conditional coverage can differ across routes, conditions and slices.

For example, on 2,000 eligible held-out deliveries, suppose 1,780 actual remaining durations fall within their issued intervals. Observed coverage is 89%. If median interval width is 370 seconds, report width as well as coverage; trivially huge ranges can achieve high coverage while providing little decision value. Evaluate coverage and width by horizon, workload, route and relevant shifts, with appropriate uncertainty and sufficient sample sizes. Do not infer guaranteed 90% coverage from an integer nominal level.

A simple split-conformal illustration: for an independently held-out calibration sample of 99 exchangeable observations, calculate absolute residual scores. For desired marginal coverage 1-alpha = 0.9, choose order statistic k = ceil((99+1)×0.9) = 90. If the 90th smallest residual is 120 seconds, a symmetric interval around a prediction of 600 is [480,720] seconds. This is a hypothetical calibration example, distinct from the asymmetric interval above. Under exchangeability and the standard split-conformal construction, the resulting interval has finite-sample marginal coverage at least the target (with usual handling of ties and the infinite quantile if k exceeds sample size). It does not guarantee conditional coverage for every order, and time-series dependence or distribution shift can invalidate the exchangeability premise. Do not treat arbitrary quantiles from a model as conformally calibrated unless an approved procedure establishes that claim.

For positive bounded quantities, use a method with appropriate domain handling. A conservative intersection with a known outcome support can preserve coverage for outcomes truly in that support, but ad hoc clipping or rescaling must be evaluated and documented. The API should not silently apply a new interval algorithm under the old method identifier.

7. Time semantics: horizon, freshness and validity are separate#

A prediction API needs at least three different clocks, and often several source times.

FieldMeaning
Event/feature as-of timeWhen the underlying facts were effective or observed
Ingested/available timeWhen information became available to the predictor, important for point-in-time correctness
Predicted atWhen the estimate was issued, its reference instant
Target window/horizonWhich future period the target refers to, if the target has one
Valid fromEarliest permitted use of the issued artifact
Valid untilExclusive upper bound on permitted use, absent earlier invalidation
Received atConsumer-observed arrival time, not a replacement for producer timestamps

For a binary delay-risk estimate, an event horizon might be "delay beyond the contractual delivery deadline during the next two hours." The validity period may be only two minutes because route information changes quickly. For remaining-duration forecasts, define the reference instant and intended use horizon separately; the actual arrival may occur after the artifact's validity expires. A validity deadline is not an upper prediction interval endpoint or a promise that the event will occur by that time.

Treat valid_until as an exclusive bound: at exactly that instant the result must not be used as a current estimate. Consumers evaluate freshness when they act or display, not only when the service issued the prediction. Do not recompute expiry on a cache hit.

A timestamp saying feature_as_of is recent can hide old component inputs. For a composite snapshot, retain source-specific observation times, revision/watermark and freshness rules. The domain may define a conservative aggregate time, but a recent weather reading does not refresh a stale driver location. In offline evaluation, ensure features available only after prediction time do not leak future information.

A production system should derive validity using approved domain limits and relevant source or artifact constraints. For example:

valid_until = minimum(
    predicted_at + approved_prediction_lifetime,
    feature_as_of + maximum_feature_age,
    applicable_source_expiry,
    approved_release_use_until,
    applicable_consumer_horizon_end
)

Only include constraints that apply to this contract. If the minimum is not later than the permitted start, abstain or return an explicit unavailable result. An approved validity window is a maximum eligibility interval, not a guarantee that assumptions remain true throughout it. Event-driven invalidation may terminate usability earlier.

Consider feature_as_of 10:00:00, predicted_at 10:00:10, a 40-second prediction lifetime and 60-second maximum feature age. The respective deadlines are 10:00:50 and 10:01:00. Absent other restrictions, expiry is 10:00:50. At 10:00:49 an otherwise valid response has one second of remaining life; a consumer with a five-second minimum remaining-validity requirement must refresh or abstain. At 10:00:50 it is expired. If the driver is reassigned at 10:00:25, the old result may be invalid even earlier.

Clock skew deserves explicit handling. Use trusted UTC wall clocks for interoperable timestamps and monotonic clocks for local elapsed deadlines. Define a bounded skew budget and conservative validation for future-issued artifacts. Do not assume producer and consumer clocks are perfectly synchronized. Apply the stricter relevant deadline when uncertainty is material. The executable example uses integer epoch-like timestamps and rejects future issue times; no clock synchronization is simulated.

8. Invalidation and consumer lifecycle#

Loading diagram…

The state belongs to the consumer's assessment of a particular immutable artifact. A refresh creates a new prediction identity; it does not change the original result's issuance time or contents. A previously issued prediction can be retained as historical evidence after expiry if retention and current authorization permit. It must not be presented as a current estimate.

Examples of invalidating events include an entity revision change, feature-source correction, model-release withdrawal, scope or policy change, and loss of current resource authorization. Some consumers need immediate invalidation; other use cases can tolerate bounded lag. A cache TTL alone does not guarantee instant revocation. For consequential decisions, obtain a current revision or authorization check at the required enforcement boundary. ASD-006 handles the authority and commitment layer.

The consumer should carry the prediction ID and its provenance through later actions or evaluations, but not treat the model ID as a permission token. Distinguish a corrected estimate (new artifact replaces an earlier estimate for the same context) from a new forecast based on new input. The later user-interface and cross-channel lessons will address presentation and reconciliation of superseded artifacts in more depth.

9. Caching without extending validity#

Caching is useful when multiple authorized requests need the same prediction under the same context. A cache key must represent semantic equivalence, not just entity ID.

A conceptual key includes tenant/authorized visibility scope, target contract, entity ID and revision, feature snapshot or canonical input fingerprint, reference horizon, relevant options, approved model/calibration release or permitted release set, and policy/cache namespace version. Do not use a raw prompt or sensitive record as a shared key. A hash of low-entropy personal information is not anonymization. Include authorization-sensitive boundaries and minimize stored contents.

Define how the API resolves a model alias: either cache is bound to a specific approved release selected for this request or a contract explicitly permits reuse from compatible approved releases. Release withdrawal must invalidate applicable cache records. Never serve an old cache hit merely because the schema matches.

For a sensitive per-user prediction, Cache-Control: private, no-store may be the conservative HTTP policy; private, max-age with explicit revalidation can be appropriate for approved data. RFC 9111 distinguishes freshness and validation; an HTTP freshness lifetime is separate from domain eligibility. HTTP cache directives cannot replace application-layer authorization and expiry checks. Avoid shared caching of protected responses without a reviewed explicit contract.

If the artifact expires in 40 seconds and data freshness allows 50 seconds, the effective cache lifetime is at most 40 seconds, possibly shorter for revocation, skew and policy. If a cache hit occurs 25 seconds later, the remaining eligibility is at most 15 seconds, not a new 40 seconds. In a retry after expiry, obtain new evidence and issue a new prediction identity.

Use request coalescing for identical authorized refreshes where safe. Bound lock wait, avoid stampedes and distinguish negative/abstention caching from successful predictions. Cache an abstention only when its reason and validity allow; a transient missing feature may become available sooner than the ordinary prediction lifetime. Authorization failure must not be cached across different principals in a way that leaks or incorrectly denies access.

Loading diagram…

This is a conceptual flow, not an atomic guarantee across distributed caches and authorization services. Define the consistency and revocation semantics of actual resources, and recheck at the protected action boundary.

10. Distinguish domain outcomes from transport errors#

A caller needs to distinguish a successful prediction, a successful request that produced a legitimate abstention, a permanent unsupported contract and a temporary infrastructure failure. Otherwise retries and fallback can create false predictions.

SituationExample API treatment
Valid issued prediction200 with predicted variant
Eligible request but inadequate predictive evidence200 with abstained variant and stable reason
Malformed request400 or an appropriate documented validation status
Unauthenticated or forbidden resource401 or 403, or resource-hiding behavior consistent with policy
Unsupported contract/targetDocumented 4xx problem response; not silently defaulted
Rate limit429 with appropriate retry guidance
Temporarily unavailable dependency503 or appropriate 5xx problem response
Durable asynchronous work accepted202 with status reference; not a completed prediction

These status choices are an illustrative design, not the only possible HTTP API. Use RFC 9457 problem details for error responses where suitable, with stable type identifiers, safe titles, correlation IDs and documented retryability. Do not return stack traces, protected entity existence or internal model details to unauthorized callers.

A legitimate abstention should not automatically be retried in a tight loop. Retry when relevant conditions change, or with an approved bounded backoff. For a read-only prediction request, repeated compute may still incur charges; if an API promises deduplication across retries, define a scoped idempotency key and immutable artifact semantics. Once an artifact has expired, a new request for a current estimate is a different use of the contract, not permission to relabel the old result as fresh.

Async prediction jobs must pin or explicitly negotiate target, model compatibility and relevant input snapshot. At completion, validity is based on the actual evidence and intended use; a long queue delay must not magically refresh input observations. A completed job can contain a stale or abstained prediction, so job success and prediction eligibility are separate states.

11. Worked scenario: binary probability API#

A merchant operates an inventory monitoring tool. The stable target is the probability of a stockout during the next 24 hours under a specified reference replenishment policy. A model estimates 0.20; an approved calibrator maps its raw output to the published probability scale.

A result payload may be:

JSON
{ "kind": "binary_event_probability", "event": "stockout", "reference_policy": "scheduled_replenishment/v1", "horizon_seconds": 86400, "probability": 0.20, "calibration_ref": "stockout-calibration/r3" }

The time envelope must define the horizon start and exclusive end (or another documented boundary convention) so 86400 seconds is unambiguous. If the consumer changes the intervention policy, the estimate may not describe the counterfactual outcome under that intervention. Do not interpret it as the effect of a new stock transfer.

Suppose 500 comparable cases have forecasts near 0.20 and 110 actually stock out under the reference policy. The observed fraction is 22%, a two-percentage-point difference from 20%. That does not alone establish a calibration failure; examine sampling uncertainty, bin definitions, maturity and selection. A Brier score is the mean squared error between forecast probability and binary observation; log loss measures probabilistic predictive accuracy and penalizes highly confident wrong predictions. Evaluate appropriate metrics with representative mature labels and slice-level evidence. The contract should link to the approved evaluation, not embed a made-up per-case certainty statement.

A downstream inventory tool may present the probability as an advisory estimate. A procurement service may use it with current costs and resource constraints. Neither should interpret 0.20 as a universal trigger or automatic order authority. If the probability is stale or the release is withdrawn, the consumer must refresh or use an approved bounded alternative. Raw model scores must remain clearly typed and cannot substitute for calibrated probabilities in expected-loss calculations.

12. Practical implementation: enforce usability of a numerical result#

The following standard-library Python example is a small typed *consumer-side* validator for a single domain contract, eta/v1. It demonstrates approved release membership, scope correlation, time ordering, exclusive expiry, independent feature freshness, explicit abstention and a required predictive-interval type. It is not a server, calibration algorithm, JSON decoder, authentication implementation or cache.

The example adds horizon_end as an explicitly defined maximum permitted *use-context boundary* for this fixture; it is not an upper bound on the realized delivery time or the predictive interval. In a real fixed-window event forecast, use a separate named target window for the event being predicted rather than overload the use-context boundary. Integer times here are synthetic seconds on one common clock. The source is assumed to be trusted, normalized and already parsed; a real service must validate the full external wire schema and provenance.

PYTHON
from dataclasses import dataclass, replace from math import isfinite @dataclass(frozen=True) class Interval: lower: float upper: float level: float method: str @dataclass(frozen=True) class Result: contract: str prediction_id: str scope: str target: str feature_as_of: int predicted_at: int valid_until: int horizon_end: int model_release: str status: str estimate: float | None = None interval: Interval | None = None reason: str | None = None def finite_number(x): return type(x) in (int, float) and isfinite(x) def usable(r, *, scope, now, approved_releases): if (r.contract != 'eta/v1' or r.target != 'remaining_delivery_seconds' or r.scope != scope or not r.prediction_id or r.model_release not in approved_releases): return 'REJECT' times = (r.feature_as_of, r.predicted_at, r.valid_until, r.horizon_end, now) if any(type(t) is not int or t < 0 for t in times): return 'REJECT' if not r.feature_as_of <= r.predicted_at < r.valid_until <= r.horizon_end: return 'REJECT' if r.predicted_at > now: return 'REJECT' # eta/v1 limits feature age to 60 seconds, even on cache reads. if now >= r.valid_until or now - r.feature_as_of > 60: return 'REFRESH' if r.status == 'abstained': return ('ABSTAIN' if r.estimate is None and r.interval is None and r.reason in {'missing_features', 'unsupported_input'} else 'REJECT') if r.status != 'predicted' or r.reason is not None: return 'REJECT' if not finite_number(r.estimate) or r.estimate < 0: return 'REJECT' i = r.interval if (not isinstance(i, Interval) or not all(finite_number(x) for x in (i.lower, i.upper, i.level)) or not 0 <= i.lower <= i.upper or i.level != .9 or i.method != 'split_conformal_v1'): return 'REJECT' return 'USE_ESTIMATE' # not authorization to act r = Result('eta/v1', 'p1', 'tenant-a/order-17', 'remaining_delivery_seconds', 1000, 1010, 1050, 1600, 'r7', 'predicted', 600, Interval(480, 850, .9, 'split_conformal_v1')) def check(result=r, now=1020, scope='tenant-a/order-17', releases=('r7', 'r8')): return usable(result, scope=scope, now=now, approved_releases=releases) assert check() == 'USE_ESTIMATE' assert check(replace(r, model_release='r8')) == 'USE_ESTIMATE' assert check(replace(r, model_release='r9')) == 'REJECT' assert check(scope='tenant-b/order-17') == 'REJECT' assert check(now=1050) == 'REFRESH' assert check(replace(r, valid_until=1100), now=1061) == 'REFRESH' assert check(now=1009) == 'REJECT' assert check(replace(r, feature_as_of=1011)) == 'REJECT' assert check(replace(r, valid_until=1601)) == 'REJECT' assert check(replace(r, estimate=float('nan'))) == 'REJECT' assert check(replace(r, estimate=True)) == 'REJECT' assert check(replace(r, interval=Interval(900, 800, .9, 'split_conformal_v1'))) == 'REJECT' assert check(replace(r, interval=Interval(480, 850, .95, 'split_conformal_v1'))) == 'REJECT' assert check(replace(r, interval=None)) == 'REJECT' a = replace(r, status='abstained', estimate=None, interval=None, reason='missing_features') assert check(a) == 'ABSTAIN' assert check(replace(a, estimate=0)) == 'REJECT' assert check(replace(r, target='delivery_risk')) == 'REJECT' assert check(replace(r, contract='eta/v2')) == 'REJECT' print('18 checks passed')

Observed execution with Python 3.13.5:

18 checks passed

The checks demonstrate:

  • Two approved model releases can satisfy the same consumer-facing contract.
  • An unknown model release, wrong tenant/entity scope, wrong target or wrong contract is rejected.
  • Equality at valid_until triggers REFRESH, and independent feature age can trigger refresh before an incorrectly long expiry.
  • Future prediction times and impossible time ordering are rejected.
  • NaN, Boolean-as-number, inverted bounds, mismatched nominal coverage and absent required uncertainty are rejected.
  • A valid abstention does not contain a numeric estimate; inserting zero into that branch is invalid.

The validator uses a strict no-skew rule and a fixed 60-second feature age limit. That limit and 90% coverage are hypothetical eta/v1 requirements, not model performance claims. The code deliberately checks temporal eligibility before the status payload, so an expired malformed payload may return REFRESH rather than a structural error. Production boundary validation should independently validate the complete structure first, with typed rejection reasons for telemetry. The toy checks membership in a caller-supplied approved release collection; it cannot prove a response was actually produced by the claimed model. Authentication, signature or transport integrity as appropriate, trusted release manifests, current entity revisions, source-specific freshness and current resource authorization must be checked elsewhere.

The interval need not contain the point value because the generic definition does not impose that invariant; a specific method can require it. The code does not train or evaluate a conformal model; the method ID and interval values are fixtures. It only confirms that the declared method matches the contract. Real coverage depends on validated evidence and assumptions. The validator performs fixed-size field operations plus release membership lookup (O(R) for a tuple of R approved releases; expected O(1) for a suitable hash set). No GPU or network benchmark is implied.

A complete API should add producer-side normalization and validation, schema conformance tests, authenticated consumer integration, event-driven invalidation, privacy-safe telemetry, and real model-evaluation gates.

13. Design the compatibility and release registry#

Model-independent does not mean any model can serve a contract. Keep a compatibility manifest mapping each approved target contract to a particular model, preprocessing, uncertainty/calibration, source feature and runtime bundle. The release owner verifies the actual target semantics, output types and evaluation evidence.

A release registry might record:

contract: eta/v1
target: remaining_delivery_seconds
target_definition: eta-target/v1
unit: seconds
point_statistic: median
required_uncertainty: prediction_interval / nominal 0.90
permitted_method: split_conformal_v1
feature_contract: route-features/v2
maximum_feature_age_seconds: 60
maximum_prediction_lifetime_seconds: 40
approved_bundles:
  - model: eta-r7
    uncertainty_release: interval-r4
    evidence: evaluation-ref-7
  - model: eta-r8
    uncertainty_release: interval-r5
    evidence: evaluation-ref-8

This is conceptual configuration, not a ready-to-deploy manifest. Define the registry's authorization, immutable identity and revocation mechanism. Both releases must independently satisfy the domain contract; sharing a field layout does not establish equivalent quality. A model which produces mean duration rather than median needs an independently validated transformation or a different contract. A provider that cannot supply the required interval cannot silently emit null with a high confidence score.

Test old and new clients and rollback combinations according to the existing MLOps evolution lesson. The emphasis here is on the initial semantic contract and approved evidence registry. Avoid repeating expand-contract mechanics for every artifact; maintain shared version governance. Consumers can negotiate supported contracts; unknown major versions must not be interpreted by guessing. Never remove a supported required uncertainty field merely because the latest model no longer supports it.

If a model is withdrawn due to a correctness or security incident, define whether previously issued predictions remain valid for historical audit only or may continue to be used under specified circumstances. A short cache TTL is not a replacement for revocation when the requirement is immediate.

14. Downstream consumer integration#

A good API gives consumers a consistent sequence for interpretation:

  1. Authenticate the source and establish current authorized subject scope.
  2. Parse the declared contract version and validate the typed payload.
  3. Verify target, unit, prediction horizon and reference assumptions.
  4. Verify provenance and approval of the release bundle; verify subject and input context correlation.
  5. Check current time, source freshness and invalidating revisions.
  6. Interpret the uncertainty type according to its semantics, including explicit abstention.
  7. Use the result as evidence in the permitted product workflow, or refresh/escalate/abstain according to policy.
  8. Record the prediction identity used for any subsequent decision or historical evaluation.

For a display client receiving the ETA at 10:00:30, the predicted arrival 10:10:10 is unchanged: the duration was relative to 10:00:10. It would be incorrect to add 600 seconds to 10:00:30 and display 10:10:30. If the UI chooses to show a remaining countdown, it can derive 580 seconds from the same arrival estimate at that instant, provided the contract permits such display and the prediction remains eligible. It must not reissue that estimate or hide the original prediction time. At expiry, refresh or visibly mark it historical/unavailable. A countdown is not newly predicted evidence.

For a workflow consumer, reject a score if its target or horizon differs from the decision's required target. A prediction that remains valid for a display may not satisfy a tighter operational freshness or minimum remaining-lifetime constraint. A decision service can impose stricter eligibility limits, but cannot loosen mandatory producer validity. Never call a protected effect solely because the response passed structural and temporal checks.

For a scheduled analysis, retain issued predictions and outcome linkage at their original event and prediction times. Historical evaluation may legitimately examine expired predictions; do not overwrite them with freshly generated forecasts using future information. Separate historical use and live eligibility, and distinguish model versions, populations, reference policy and label maturity.

15. Observability and evaluation of the contract#

Monitor the API as an integration product, not just inference throughput.

MeasurementWhy it matters
Eligible offered requests and valid predictionsCoverage, including abstentions and failures
Abstention by reason and workload sliceUnsupported or missing evidence, not a fabricated zero
Schema/semantic rejection rateProducer and consumer contract health
Age at issue and age at consumptionFreshness from actual use, not simply generation
Expired cache hits prevented and refresh rateTemporal enforcement and load
Revision invalidation lagStale evidence exposure risk
Per-release compatibility rejectsMisconfiguration or unapproved deployment
Empirical calibration / interval coverage and widthQuality of uncertainty semantics
Missing labels and delayed outcome maturityValidity of evaluation evidence
End-to-end latency, valid-result goodput and costWhole-consumer service objectives

A forecast API can have 99.99% HTTP success while producing excessive abstentions or expired results. For example, among 10,000 eligible offered tasks, 8,900 valid predictions, 900 explicit abstentions and 200 technical failures yield 89% valid prediction coverage, 9% abstention and 2% technical failure. If 100 of the 8,900 predictions expire before intended use, the number usable at that use point is 8,800, or 88% of all offered tasks, assuming no other rejection and one use per task. Count the relevant unit rather than multiply unrelated marginal ratios.

Measure interval quality separately from coverage of automated predictions. A model that abstains on difficult cases may show better conditional calibration while leaving many users unresolved. Report conditional performance together with selection, subgroup coverage and overall task outcomes. Do not compare candidate models only on the subset where both happen to return answers without reporting pairing coverage.

Use prediction IDs to join mature outcomes under authorized governance. A changed business action can alter the outcome; preserve the reference policy and actual intervention metadata when relevant. Avoid leaking future labels into historical features. Do not store raw inputs, sensitive source records or personal data unnecessarily in traces. Protect the evidence registry and use controlled references for deeper audit.

16. Failure scenarios and design trade-offs#

FailureCorrect architectural response
Provider returns probability as 82 instead of 0.82Reject or convert only via an approved adapter with documented source semantics
Model returns a raw score under a probability fieldFail semantic contract; do not pretend it is calibrated
Feature snapshot is stale despite a fresh response timestampReject/refresh or explicitly abstain
Model is approved but entity revision changedInvalidate according to domain contract and obtain current evidence
Expiry passed during network transitConsumer rejects for current use
Prediction interval coverage degrades under shiftInvestigate representative outcomes, contain affected scopes or withdraw bundle according to approved gates
Required interval unavailableAbstain or use a separately approved contract, not invented uncertainty
Cache hit from another tenantTreat as security failure, contain and investigate
Old supported client sees unknown enumApply negotiated compatible response or explicit version; test parser behavior
Clock moves backwardEnforce trusted time/skew policy; avoid artificially extending eligibility
Authenticated consumer lacks current resource accessDeny access independently of model output or cache identity
Consumer asks model for an authorization decisionPreserve authority boundary and route to deterministic policy

A universal API envelope makes common integration easier but may erase crucial semantics if every result is coerced into one "score/confidence" object. Use reusable common metadata and target-specific typed payloads. Broad compatibility constraints may limit model substitution; this is a real product trade-off, not a reason to misstate outputs.

Short validity limits reduce staleness but increase cache misses, compute and potential unavailability; long limits may increase wrong decisions. Set limits from source dynamics and task risk, not a universal TTL. Prediction intervals can improve transparency but wider intervals may be unhelpful, and computing uncertainty can add latency and resource cost. Evaluate useful outcomes and interval quality, not only nominal coverage.

Centralized normalization reduces duplicated provider-specific code; domain-owned target definitions prevent a platform team from inadvertently standardizing away meaning. Keep the actual authority for each domain with accountable owners, and instrument producer and consumer separately.

17. Production acceptance plan#

Before allowing a release to satisfy a prediction contract, define evidence gates for the exact target and supported consumer population:

  • Wire and schema tests: valid tagged variants, invalid numeric values, missing required fields, unknown contract, known compatibility policy.
  • Semantic golden cases: class identity, units, point statistic, horizon and reference conditions, interval bounds and coverage type.
  • Temporal tests: exclusive expiry, clock skew, stale feature despite recent issue, delayed delivery, invalidation, and cache reuse with unchanged validity.
  • Authorization and integrity tests: wrong subject/tenant, invalid producer, withdrawn release, revoked grants, unauthorized cache access.
  • Uncertainty evaluation: appropriate held-out calibration, proper scoring rules, interval coverage and width, subgroup/shift checks and documented assumptions.
  • Consumer integration: display, historical evaluation and business-policy consumption, with explicit handling of abstentions and infrastructure errors.
  • Reliability: dependency outage, bounded refresh, retry amplification, release rollback and observation of actual usable-result goodput.

A release gate must distinguish missing evidence from passing evidence. Unit tests of a schema or consumer validator cannot establish empirical calibration, secure authorization, distributed clock correctness or real service availability. Test these independently under representative conditions.

18. Interview-ready answer#

I would begin by defining a stable domain target: what event or quantity is predicted, unit, reference assumptions, horizon, subject and supported population. I would expose a versioned prediction envelope with a tagged target-specific result and explicit abstention, rather than a generic model-specific score. The uncertainty variant would distinguish calibrated probabilities, predictive intervals, quantiles, prediction sets and raw scores, with method and evidence references.

I would record source observation time, prediction time, validity start and exclusive expiry, and any target window independently. I would derive validity from approved freshness and lifetime limits, invalidate on relevant state or release changes, and require consumers to validate time at use. Cached results would retain their original timestamps and identity, be scoped by authorization and compatible inputs, and never extend validity on a hit.

I would use a model adapter and approved compatibility registry so independent models can satisfy the same contract only after semantic and quality evidence. I would validate structural and cross-field invariants, separate legitimate abstention from transport failures, and provide precise error and retry semantics. Downstream consumers would use the result only as evidence under their own permitted workflow, not as authorization. Finally I would test compatibility, empirical uncertainty, freshness, invalidation, security and end-to-end usability and monitor the actual outcomes.

The core design principle is that a prediction is a versioned, time-bounded, uncertain domain artifact, not simply a number emitted by a model.

References and research transparency#

The authorized offline research exception was applied. These references identify established specifications, primary research and risk/provenance guidance; current link availability and live contents and the Supabase changelog were not verified. Three Mermaid diagrams use standard triple-backtick fences and received structural review only; parser execution and live frontend rendering were not tested. The exact Python block was executed locally using Python 3.13.5 with 18 assertions passing. No trained model, real calibration or conformal experiment, HTTP service, distributed cache, production authorization or clock-skew test was performed. The JSON examples are illustrative representations and the schema is intentionally partial; they were not run through a JSON Schema validator. All numerical scenarios and thresholds are hypothetical.

Related questions

Explore other topics:Forward Deployed EngineeringMachine LearningMLOpsPython