Skip to content
Tech Interview Prep
Technical interview guide

Model Versioning & Registries

Tracking every trained model artifact alongside the data and code that produced it, so results are reproducible.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v5
Editorial status
Reviewed
Relevant for
MLOps Engineer

Scope: MLflow, SageMaker AI, Vertex AI, Azure Machine Learning, and NIST AI RMF guidance current 2026-09-01.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

What is a model registry, and why is standard code version control (such as Git) insufficient for versioning machine learning models in production?

Answer

The 90-second answer. A model registry is the system of record for deployable models. It holds three things Git does not: the artifact bytes themselves; the metadata that makes them loadable and reproducible (training run, dataset snapshot, hyperparameters, input/output signature, dependency lockfile); and mutable deployment pointers, aliases like champion or staging, that move between immutable versions without touching code. Git versions text deterministically. A model is a non-deterministic binary whose identity depends on data and environment as much as on code, and whose promotion is an operational act, not a code change. Assume the team already has CI on Git and a training pipeline; the open question is where the trained artifact and its serving state live.

1. Size and storage topography. A trained artifact is an opaque binary: a 14 GB LLM checkpoint, an 800 MB gradient-boosted tree ensemble. Git stores a full blob per version, so twenty weekly retrains of that 14 GB checkpoint put roughly 280 GB into the object store, and every clone that checks out the branch pays for it. Git LFS moves the bytes to a separate store but keeps a pointer file in the tree and still smudges on checkout, so a fresh CI runner materializes gigabytes before it can run a single test. Serving runtimes don't want a checkout at all; they pull from object storage with a presigned URL or an S3/GCS API call.

2. Non-determinism and lineage. In software, commit C1 compiles to binary B1: same input, same output. In ML, the same commit trained on a different data partition, seed, or CUDA version produces different weights. Git's SHA identifies the code, not the artifact, so it cannot answer "which dataset and hyperparameters produced the model that is serving right now?" A registry binds the artifact to its run_id, dataset snapshot digest, hyperparameters, and evaluation metrics, which is what makes an incident review or a rollback decision possible.

3. Contract enforcement. Git cannot validate a model's signature. If training writes user_age as int64 and the serving path sends a float or a string, nothing in the repository catches it; the mismatch surfaces as a 500 on the first request. A registry records the input/output signature and the dependency lockfile next to the artifact, so the serving container can be built and its payload validated before rollout. Detect it at the gateway: a signature mismatch should be a 4xx naming the offending field, not a 500 from inside the model.

4. Promotion is not a merge. Git expresses state through branches and tags, which tie deployment intent to a code commit. Promoting a validated model changes operational intent without changing the artifact. Moving alias champion from version 11 to version 12 is a metadata write; rolling back is moving it back. Doing the same in Git means a commit or tag that describes nothing about the artifact, plus a rebuild that may not reproduce the same weights.

Comparison: Git vs. Model Registry

DimensionGit / Git LFSDedicated Model Registry (MLflow / SageMaker / Vertex)
Primary assetSource code, human-readable text diffsPackaged binary artifacts, tokenizer/preprocessing, runtime environments
IdentityTree hash / commit SHAModel name, integer version, artifact content digest (SHA-256)
Metadata trackedCommit message, author, timestampTraining run ID, dataset snapshot hash, hyperparameters, validation metrics
Model interfaceNoneEnforced input/output signature (tensors/columns) and dependency lockfile
Lifecycle controlBranch merges, PR approvalsDeployment aliases (champion/challenger), approval states (Pending, Approved)

Minimal MLflow model representation

When a model is registered, MLflow writes an MLmodel contract next to the artifact linking the loader, the environment, and the exact schema (abridged, MLflow 2.x):

YAML
artifact_path: model
flavors:
  python_function:
    env:
      conda: conda.yaml
      virtualenv: python_env.yaml
    loader_module: mlflow.sklearn
    model_path: model.pkl
    python_version: 3.11.8
  sklearn:
    pickled_model: model.pkl
    serialization_format: cloudpickle
    sklearn_version: 1.3.2
mlflow_version: 2.9.2
run_id: 8a7f09d8e52a46c1b3c9489a2bf405e1
signature:
  inputs: '[{"name": "user_age", "type": "integer"}, {"name": "spend_30d", "type": "double"}]'
  outputs: '[{"type": "float"}]'
utc_time_created: '2025-02-15 10:24:01.320110'

The registry API is what makes this queryable: list versions, diff validation metrics across them, and reassign a serving target without rewriting repository history.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-2

Define what constitutes one model version.

Answer

The 60-second answer

A model version is the immutable, content-addressed identity of every artifact that can change what the model predicts. The test is behavioral: if two deployments can return different outputs for the same input, they are different versions. Whatever the version string says. So the version boundary is the prediction-affecting boundary.

Concretely, one version pins: weights, preprocessing and postprocessing code, the inference/serving code, the input/output signature or schema, the tokenizer or feature contract, the dependency lock, and the runtime image digest. You hash that set into a content digest and store it under a registry namespace. Any change to any member (a new weight, a bumped numpy, a reordered feature list) produces a new digest and therefore a new version.

Assumptions: you have a registry that can store and address artifacts by digest, and you control the serving path so the digest is what actually loads.

What's in and what's out

In artifact identityOut (mutable, audited)
weights, tokenizer/feature contractdescription, owner, tags
pre/postprocessing + inference codealias like prod or latest
signature/schema, dependency lockrollout percentage, traffic split
runtime image digestevaluation reports, approval state

Aliases and descriptions move; the digest doesn't. That split is the point: prod is a pointer you can repoint, the digest is the thing you can reproduce.

Alternatives and when to pick them

Two axes. First, monolithic vs component-level versioning. A single bundle digest is simple and makes rollback atomic: you redeploy one digest. Component-level versioning (version the tokenizer separately from the weights) lets you reuse a tokenizer across many models and patch one piece, but now deployed behavior is a composition, and you must record the exact component graph and digests so it resolves deterministically. Pick monolithic when the pieces ship together and rollback speed matters; pick component-level when many models share a stable preprocessor and the reuse is worth the resolution complexity.

Second, content digest vs semantic versioning. SemVer (2.3.1) is human-readable and orders releases, but it's a claim, not a proof: nothing stops two 2.3.1 builds from differing. Content digests are verifiable and collision-resistant but opaque. Most registries use both: SemVer for humans, digest for identity, and the digest is what the serving layer loads.

Failure modes and detection

  • Training-serving skew from an unversioned preprocessor: the training pipeline normalizes features one way, serving another. Detected by logging the preprocessor digest alongside every prediction and comparing training vs serving feature distributions; a parity test on a fixed input batch catches it before rollout.
  • Non-reproducible rollback: you "roll back" to a tag that now points at a different build. Detected by a rollback drill: redeploy the previous digest and diff outputs against a golden set; if the digest isn't pinned, the drill fails.
  • Silent dependency drift: the image is rebuilt and pulls a newer transitive dependency. Detected by verifying the image digest at load and failing closed on mismatch.

The one-line rule: if it can change a prediction, it's in the version; if it can't, it's metadata.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

Build end-to-end lineage for a registered model.

Answer

Lineage for a registered model is a resolvable path from the model version back to the exact code, data, config and environment that produced it. Every edge carries an immutable identifier (a SHA, a snapshot ID, a digest) not a name that can be reassigned. If any edge is mutable, the lineage is decoration.

Assume MLflow Model Registry, a Delta or Iceberg table for training data, Git for code, and a container image for the runtime. The pattern transfers to SageMaker Model Registry or Vertex, which store the same fields under different keys.

What to capture, and where it lives

EdgeFieldConcrete sourceImmutable?
model version → runrun_idregister_model sets sourceyes
run → codecommit SHA + dirty flagmlflow.source.git.commit; git status --porcelainSHA yes, dirty flag is a warning
run → datasnapshot URIDelta versionAsOf=42, Iceberg snapshot-id, S3 VersionIdyes
run → featuresfeature-view definition hashFeast feature_view plus the feast apply commithash
run → envimage digestdocker inspect --format='{{index .RepoDigests 0}}'sha256
run → seedsseed, framework determinism flagslogged paramsint
run → base modelregistry name + versionmodels:/llama-3-8b/3version int
run → whomlflow.userset by tracking serverstring

Registration fails unless git.commit, data.snapshot, image.digest and seed are present and non-empty. The metadata is enforced, not aspirational.

Python
import mlflow, subprocess
mlflow.set_tracking_uri("http://mlflow.internal:5000")
REQUIRED = {"git.commit", "data.snapshot", "image.digest", "seed"}

with mlflow.start_run() as run:
    commit = subprocess.check_output(["git", "rev-parse", "HEAD"]).decode().strip()
    dirty = subprocess.check_output(["git", "status", "--porcelain"]).decode().strip()
    mlflow.set_tags({
        "git.commit": commit,
        "git.dirty": "true" if dirty else "false",
        "data.snapshot": "s3://lake/train@version=42",
        "image.digest": "sha256:9f2c...",
    })
    mlflow.log_params({"seed": 1337, "lr": 3e-4})
    mlflow.log_metric("val_auc", 0.913)
    mlflow.log_artifact("model.pkl")

    missing = REQUIRED - run.data.tags.keys()
    if missing:
        raise RuntimeError(f"refusing to register, missing lineage: {missing}")
    mlflow.register_model(f"runs:/{run.info.run_id}/model", "fraud-clf")

Rebuild check. Take version 7, read its run_id, resolve the commit and snapshot, re-run in a fresh container from the same image digest. Compare val_auc and the artifact hash. In a worked example on the same GPU and driver, with torch.use_deterministic_algorithms(True) and CUBLAS_WORKSPACE_CONFIG=:4096:8, the metric matched to 1e-6 relative and the artifact hash matched exactly. Across a different GPU architecture, expect drift around 1e-3: set the tolerance there and record which side of it you landed on. A rebuild that cannot resolve the snapshot is a failed rebuild, not a pass.

Failure modes. A dirty working tree means the commit does not describe the code that ran; tag it and refuse production promotion. A latest tag on the base model or a mutable S3 key means the rebuild silently trains on different bytes: detect it by hashing the resolved dataset and comparing to the logged hash. Unpinned pip dependencies drift the environment; the image digest catches that only if you rebuild from the digest, not from the Dockerfile. When an input is genuinely gone (a deleted bucket, an expired snapshot) record data.snapshot=unavailable and the reason as a risk on the model version. Filling that field with a mutable table name is worse than leaving it empty, because it looks like lineage and is not.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Choose between promoting artifacts and promoting training code.

Answer

Assumptions: one model artifact per release; a registry (OCI, or MLflow / SageMaker / Vertex model registry) is the source of truth; the path is dev → staging → prod; residency constraints are known up front.

Core answer (say this first). Default to artifact promotion: build and evaluate once, then move the same immutable bytes through every environment. Switch to code/pipeline promotion only when the evaluated artifact is invalid in the destination: the destination's data, identity, or infrastructure changes the model, or the artifact cannot legally cross the boundary. The deciding question is "is the thing I evaluated still the thing I want to serve?" Yes → promote the artifact. No → promote the pipeline and re-evaluate there.

Why digest verification holds. An OCI digest is sha256: over the manifest, which covers the config and every layer digest; any byte change changes the digest. So an admission policy that pins image@sha256:… and verifies a signature binds the deployed bytes to the reviewed bytes. That is the whole reason artifact promotion gives evaluation equivalence: the thing you measured is the thing you run. Keyless verification with cosign v2:

Shell
cosign verify \
  --certificate-oidc-issuer=https://token.actions.githubusercontent.com \
  --certificate-identity-regexp='^https://github\.com/acme/train/\.github/workflows/release\.yml@refs/tags/v[0-9.]+$' \
  ghcr.io/acme/model@sha256:9f2c1a…

Why retraining breaks evaluation equivalence. Training is not bit-reproducible in general: nondeterministic GPU kernels (cuDNN benchmark mode, atomic adds), a different hardware topology changing float reduction order, unpinned library versions, and, the big one, the data. If the training set is a live table, the rows at retrain time differ from the rows at evaluation time, so the retrained model is a different function and its metrics must be re-measured. Approval does not transfer.

SignalPromote artifactPromote code/pipeline
Evaluated bytes still valid in destinationyes—
Model must track recent data (fraud, ranking)—yes
Weights derived from data that can't leave the region—yes
Evaluation is expensive, artifact is portableyes—

Failure modes and detection.

  • Tag mutability. :prod gets retagged to bytes nobody evaluated. Detect with an admission controller (Kyverno, OPA Gatekeeper) that rejects any reference lacking @sha256: and fails cosign verify; alert on verify failure.
  • Retrained-model drift. The retrained model scores 0.77 AUC on the frozen holdout against 0.81 for the evaluated one, and you shipped it because approval was inherited. Detect by gating promotion on re-evaluation against the same frozen holdout and blocking on a delta threshold (say >0.01 AUC).
  • Cross-boundary movement. Weights trained on EU PII copied to a US region. Detect with a provenance policy check on where the training data lived before allowing the copy.

Cost arithmetic (hypothetical, list prices): promoting a 7B fp16 model is 7e9 × 2 B = 14 GB; at ~$0.09/GB egress that is ~$1.26 per hop. Retraining the same model on 8×A100 for 6 h is 48 A100-hours, ~$100–150 on demand. Roughly two orders of magnitude, which is why you promote artifacts when you can and only pay for retraining when the destination genuinely requires it.

What would change the decision: if the model must reflect data that arrives after evaluation, the artifact is stale by construction and you must promote the pipeline; if the artifact cannot leave the boundary, same answer. Otherwise promote the artifact and keep the pipeline as the thing that produced it.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-24

Several training pipelines publish to the same registered model at the same time. Walk me through how the registry allocates version numbers without races, whether registration is idempotent, and how a rejected or duplicate registration reaches the caller.

Answer

First thing I'd pin down: what is the identity key, and who allocates the version. In every mainstream registry the key is (registered model name, version), and the version is either server-allocated (MLflow, Vertex AI) or caller-supplied (Azure ML, optionally SageMaker). That choice decides the whole concurrency story.

If the server allocates, the registry is the single writer for that model's counter. Two safe implementations:

  1. Per-model counter row locked for the duration of the insert: SELECT ... FOR UPDATE on the registered-model row, compute max(version)+1, insert, commit. Serializes registrations per model, which is fine: you register a handful of models per hour, not per second.
  2. Optimistic: compute the next version, insert, and let a unique index on (name, version) reject the loser. Catch the integrity error and retry with jittered backoff. Lock-free, but under a burst of N concurrent registrations you get O(N²) retries in the worst case.

Trace of the lock version, two pipelines publishing to fraud-clf:

T1 BEGIN T1 SELECT version FROM models WHERE name='fraud-clf' FOR UPDATE; -- 7 T2 BEGIN T2 SELECT ... FOR UPDATE; -- blocks T1 INSERT INTO model_versions(name,version,run_id,digest) VALUES ('fraud-clf',8,'run-a','sha256:aa…'); T1 COMMIT T2 -- lock released, re-reads 7, computes 8 T2 INSERT ... VALUES ('fraud-clf',9,'run-b','sha256:bb…'); T2 COMMIT

Both commit, versions 8 and 9, no gap. Gaps only appear if you allocate from a DB sequence or identity column (rollback burns the number) or if you allocate in one transaction and insert in another. Gap-free is achievable; whether you want it is a separate question: monotonic and never-reused is the property that matters, and gaps are harmless.

Idempotency is not the same as conflict detection. A retried HTTP call must not create a second version. Key the registration on content: a unique index on (name, source_digest) where the digest covers artifact bytes plus the run/config identity. Same digest, same model → return 200 with the existing version object. MLflow does not do this, registering the same run twice yields two versions, so if you're on MLflow you either dedupe in the client or add the index yourself.

Surfacing conflicts to the caller:

situationstatusbodycaller action
duplicate content, same idempotency key200existing versiontreat as success
lost the allocation race409current max versionretry with backoff
alias CAS precondition failed412current alias targetre-read, re-decide
caller-supplied version already taken409existing versionpick a new version or accept existing

Mutable pointers (aliases, stages, "champion") need compare-and-swap, not read-modify-write:

sql UPDATE model_aliases SET version = 9 WHERE name='fraud-clf' AND alias='champion' AND version = 8; -- 0 rows affected → someone else moved it → 412

Failure modes worth naming. Hard-deleting v7 and then allocating max(version)+1 reissues 7; a deployment pinned to "v7" now serves different weights. Detect it with a registry invariant that version numbers are never reissued, and store the artifact digest in deployment records, not just the version. Cross-region: two writers in different regions both read max=7 and both insert 8. Allocate in one region, or put a global unique constraint behind it, and read the counter from the primary, not a lagging replica. And if you let callers supply versions (Azure ML, SageMaker), you've moved the collision policy to them; the registry can only reject duplicates, not order them.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Design registry metadata schemas and quality controls.

Answer

Assumptions. The registry gates automation: a deploy job, a feature backfill, or a downstream consumer reads it and decides whether to proceed. If nothing automated reads it, you are building a catalog, not a gate, and most of this is waste. I also assume the store is Postgres and the payload contracts live in an Avro or Protobuf schema registry.

Core answer. Design the schema around the gate, not around documentation. Three tiers with different write rules:

  1. Immutable facts: written once at registration, never updated: artifact digest, code commit, data snapshot ID, container image digest, signature.
  2. Append-only decisions: approval, rejection, deprecation, expiry extension. One row per event, never an UPDATE.
  3. Editable descriptions: owner, use case, limitations, tags. Free to change, never read by automation.
SQL
CREATE TABLE model_version (
  id              bigserial PRIMARY KEY,
  model_name      text NOT NULL,
  version         int  NOT NULL,
  artifact_sha256 bytea NOT NULL CHECK (octet_length(artifact_sha256) = 32),
  code_commit     text NOT NULL,
  data_snapshot   text NOT NULL,
  image_digest    text NOT NULL,
  signature       jsonb NOT NULL,  -- {inputs:[{name,type}], outputs:[...]}
  created_at      timestamptz NOT NULL DEFAULT now(),
  UNIQUE (model_name, version)
);

CREATE TABLE decision (            -- append-only
  id               bigserial PRIMARY KEY,
  model_version_id bigint NOT NULL REFERENCES model_version(id),
  kind             text NOT NULL CHECK (kind IN ('approve','reject','deprecate','expire')),
  actor            text NOT NULL,
  evidence_uri     text NOT NULL,
  decided_at       timestamptz NOT NULL DEFAULT now()
);
REVOKE UPDATE, DELETE ON decision FROM app_role;

CREATE VIEW current_state AS
SELECT DISTINCT ON (model_version_id) model_version_id, kind, actor, decided_at
FROM decision ORDER BY model_version_id, decided_at DESC;

The deploy job runs SELECT kind FROM current_state WHERE model_version_id = $1 and proceeds only on 'approve'. It never touches the description columns.

Why it behaves this way. The digest is the join key between registry and artifact store; keying on model_name alone means a re-upload silently changes what "v1" refers to. The append-only decision table turns "who approved this, on what evidence" into a query instead of a Slack search, and REVOKE UPDATE makes tampering a permissions error rather than a silent edit. The immutable/editable split means renaming an owner cannot invalidate an approval.

Quality controls.

  • Validate on registration, fail closed. Reject if the digest does not match the artifact store, if signature is absent, or if data_snapshot does not resolve. A missing required fact blocks registration; it never defaults to approved.
  • Referential integrity to evidence. evidence_uri should be a foreign key into an evidence table (evaluation run, test report), not a free string. A string lets a typo pass validation.
  • Tag governance. Constrain keys to a controlled vocabulary table and values to a regex or enum. Without it you get env, Env, and environment as three keys and every query misses two.
  • Monitor three states. Missing (versions with no decision row), stale (latest decision older than the retraining cadence), conflicting (two approvals citing different evidence).
  • Sample against source. A nightly job re-hashes N artifacts and compares to artifact_sha256; alert on mismatch.

Failure modes. Automation inferring approval from prose ("approved by Alice" in a description field) bypasses the gate: detect by grepping the deploy path for reads of description columns. Schema migration without versioning breaks old rows under new validation: use Avro BACKWARD compatibility or an explicit schema_version column with a backfill. Registry/artifact drift shows up as digest mismatch, caught by the nightly re-hash.

What would change the decision. If no automation reads the registry, drop the decision table and the digest. If the org already runs DataHub or OpenMetadata, extend their metadata model rather than standing up a parallel store.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Design model cards and intended-use evidence in a registry.

Answer

Assumptions. You already have a registry that versions artifacts and resolves a deployable alias to a version: MLflow, SageMaker and Vertex all do this, and MLflow deprecated registry stages in 2.9 in favour of aliases and tags. So the design question isn't what a card contains; it's what binds a card to the thing that is actually serving.

Core answer. A model card is an immutable, append-only record keyed by the artifact digest, not the model name. Intended-use evidence is the set of claims inside it, each pointing at a versioned artefact: an eval run, a dataset snapshot hash, an approval record. Promotion is gated on a join between the alias target and a card whose digest matches. That join is what stops drift; everything else is fields. Key the card on (model, version, artifact_digest). Hang it off "fraud-scorer" instead and v13 and v14 share one description that silently becomes wrong the moment the alias moves. Renewing a card writes a new row; the superseded row stays for audit.

fieldexamplewhy
card_id / model / version / artifact_digestMC-1042, fraud-scorer, 13, sha256:9f2c…the binding
intended_use / out_of_scope_use"real-time card auth scoring" / "not for credit-limit decisions"the claim an auditor tests
population + slice definitionsUS cardholders 2023-01..2024-06; slices new_account<90d, thin_filemakes slice metrics reproducible
metrics + evidence_refAUC 0.81 overall, 0.74 thin_file; eval_run:EV-3391claim → artefact
data_provenancesnapshot hash, collection window, consent basis
limitations / human_oversightdegrades past 30d account-age gap; analyst reviews score <500
risk_tier / approvals / ownerhigh; approver:jdoe 2025-02-14; owner:risk-ml
review_by / evidence_max_age_days2026-02-14 / 180expiry

Worked trace: the promotion gate.

Python
def promote(model, version, target_env):
    digest = registry.artifact_digest(model, version)
    card = registry.card_for(model, version)      # latest card row for this version
    if card is None or card.artifact_digest != digest:
        return block("no card bound to this artifact")
    # evidence_age_days() = days since the newest evidence_ref timestamp
    if card.review_by < today() or card.evidence_age_days() > card.evidence_max_age_days:
        return block("card expired")
    if target_env == "prod" and card.risk_tier == "high" and not card.approvals:
        return block("high-risk card needs a named approver")
    registry.set_alias(model, target_env, version)
    return ok(card.card_id)

Trace promote("fraud-scorer", 13, "prod") on 2025-08-01, with prod currently aliased to v12. artifact_digest resolves to sha256:9f2c…; card_for returns MC-1042, whose artifact_digest is also sha256:9f2c…, so the binding holds. review_by is 2026-02-14, later than today, so the first clause is false. The newest evidence_ref is eval_run:EV-3391 dated 2025-01-05 (208 days old, over the 180-day cap) so the second clause fires and the call returns block("card expired"). The alias stays on v12. Nothing about the model changed; the evidence aged out.

Trade-off: advisory vs hard gate. Advisory cards warn and let the deploy through; hard gates block promotion. The deciding criteria are blast radius and regulatory exposure. A model scoring internal ticket routing gets an advisory card and a 24-month review. A model touching credit, employment or safety gets a hard gate, because EU AI Act technical documentation for Annex III high-risk systems (obligations phasing in from 2 August 2026) and ISO/IEC 42001 audit expectations both assume you can produce the evidence on demand. Hard gates cost you something real: a stale card blocks an urgent hotfix. The escape is a break-glass exception recording who accepted the risk, why, and an expiry: leaving the historical card untouched.

Failure modes. Alias drift: alias on v14, card describes v13; caught by the digest join, and the cost is that incident response reads the wrong limitations (card says "English only" while v14 added Spanish, so the on-call debugs the wrong slice). Family card: one card for the whole family quoting v9 slice metrics for v13; caught by evidence hash mismatch. Rubber-stamp renewal: review_by bumped with no new evidence; caught by evidence_ref timestamps not advancing across renewals. Unenforced prohibitions: the card says "not for credit decisions" and nothing checks it; enforce at the gateway by rejecting requests whose use_case header is in out_of_scope_use.

Expiry arithmetic. With 40 registered models, 8 high-risk at a 12-month review and 32 at 24 months, that's 8 + 16 = 24 reviews a year, two a month: one reviewer holds it. Set evidence_max_age_days shorter than the review interval (180 vs 365) so the metrics, not the paperwork, expire first.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

How do model aliases and tags enable zero-downtime progressive delivery compared to legacy stage transitions in modern model registries?

Answer

Modern registry workflows (such as MLflow model aliases and Vertex AI Model Registry version aliases) decouple the immutable numerical model version from the deployment role. In legacy registry models (such as MLflow's original model stages (None, Staging, Production, Archived)) promotion required mutating a single state field on the version itself.

The Operational Constraint of Stages

Stages enforce a rigid, single-property lifecycle state. This causes operational friction during progressive delivery (e.g., canary, blue/green, or A/B testing):

  1. State exclusivity: In legacy stage models, transitioning a version to Production either forced the existing production model to demote immediately or allowed multiple versions to share the same stage string without clear semantics on who receives live traffic.
  2. Conflating build state with routing: Moving a version to Production in the registry signaled both that the model was approved and that it was live. This tightly coupled the governance record to runtime traffic shifting, making staged rollouts (e.g., 5% canary) awkward to represent without bespoke external state stores.

Decoupled Routing via Aliases and Tags

Modern registries resolve this by treating the registered version (its artifact URI, schema/signature, and environment definition) as immutable once created, using two distinct metadata layers:

  • Aliases: Named, mutable pointers (e.g., @champion, @challenger, @canary-10pct) that resolve to exactly one version number at any time within a registered model. A version can carry multiple aliases simultaneously.
  • Tags: Arbitrary key-value metadata (e.g., git_commit: 8c3b1a, eval_dataset: 2026_q1, compliance_status: passed) used for search, filtering, and lineage, but not as direct resolution targets for deployment.
MechanismLegacy Stages (e.g., MLflow Stages)Modern Aliases & Tags (e.g., MLflow, Vertex AI)
Model-to-Role MappingVersion's stage property is mutated (Staging -> Production).Alias pointer (@champion) is updated to target a version integer.
Multi-Version ServingAmbiguous; required external orchestration to track canary vs. production.Distinct aliases co-exist: @champion -> v12, @canary -> v13.
Runtime ResolutionDeployments query stage='Production', which may match multiple versions or lag behind cutovers.Deployments resolve models:/fraud-detect@canary to a concrete version ID (v13) before loading.

Progressive Delivery Pattern

Registry State:
  Registered Model: "fraud-detector"
    ├── Version 12 (URI: s3://bucket/v12) <--- Alias: @champion
    └── Version 13 (URI: s3://bucket/v13) <--- Alias: @canary, Tag: eval_f1=0.942

Runtime Serving (e.g., KServe / Envoy / Triton):
  Traffic Ingress
     │
     ├── 90% ──> Pod Pool A (Loads Version 12 via URI resolved from @champion)
     └── 10% ──> Pod Pool B (Loads Version 13 via URI resolved from @canary)
  1. Pre-warming & Validation: The orchestrator resolves models:/fraud-detect@canary to v13, spins up Pod Pool B, pulls the artifact URI, loads the weights into memory, and passes health/readiness checks before any live requests hit it.
  2. Traffic Shift: Ingress shifts traffic gradually (e.g., 10% -> 50% -> 100%) to Pod Pool B. The model registry state does not change during this network shift.
  3. Atomic Cutover: Once validation passes, CI/CD calls the registry API to assign @champion to v13. The @canary alias is removed or reassigned to a test candidate.
  4. Rollback: If error or latency budgets breach during ramp-up, the routing layer shifts 100% of traffic back to Pod Pool A. Because v12 remained fully loaded and unaffected, rollback is an instant network route change rather than an artifact download or registry rollback.

Failure Modes

  • Runtime Alias Polling Drift: If worker nodes independently poll @champion directly to decide what model to serve, staggered polling intervals cause nodes within the same pool to serve different model versions simultaneously. Fix: Deployments must resolve the alias to an immutable version ID at deployment or orchestration time; runtime workers bind to the resolved version, never to a floating alias directly.
  • Dangling Alias Deletion: Deleting a model version while an alias still points to it causes deployment pipelines resolving that alias to fail. Registries prevent this by requiring aliases to be unassigned before version deletion or by rejecting deletion requests on aliased versions.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

Use model aliases safely in deployment workflows.

Answer

Assumptions. MLflow 2.x model registry (aliases arrived in 2.3; stages were deprecated in 2.9), one registered model per environment, promotion driven by CI, and a nightly batch scorer that reads the registry. Vertex AI and SageMaker differ in detail: Vertex has version aliases (gcloud ai models versions set-aliases), SageMaker endpoints reference a specific model-package version ARN, so pinning is already the default there, but the failure mode is the same.

Core answer. An alias is a mutable pointer to an immutable version. champion is not an identity; it is a lookup that returns a different answer after a promotion. So resolve the alias exactly once, at promotion time, in a controlled job, then persist the immutable identity (version number plus source URI or digest) into the endpoint config, the batch job's run record, and the change ticket. Nothing that serves traffic or scores data should resolve an alias at request time or per partition.

Mechanism. In MLflow, versions are immutable once created; set_registered_model_alias is a metadata write, not a copy, and MLflow keeps no history of alias assignments: the audit trail is yours to write. There is also no conditional write: the call is last-write-wins.

Python
from mlflow import MlflowClient
c = MlflowClient()

mv = c.get_model_version_by_alias("fraud-model-prod", "champion")
assert mv.version == expected_version, f"champion moved to {mv.version}"
c.set_registered_model_alias("fraud-model-prod", "champion", new_version)
# record: alias=champion, from=expected_version, to=new_version, source=mv.source

The assert narrows the race window but does not close it. Serialize promotions through one CI job with a required reviewer, or take a lock, if two pipelines can promote concurrently.

The failure this prevents. A scorer that resolves inside the loop:

Python
for part in partitions:                       # 100 partitions
    model = load(c.get_model_version_by_alias("fraud-model-prod", "champion"))
    write(model.predict(part))

Trace it: the job starts at 13:50 and finishes partitions 1–40 by 14:02. At 14:02 a promotion moves champion from v7 to v8. Partition 41 loads v8. The run emits one output file in which rows 1–40 were scored by v7 and 41–100 by v8, and one audit line that says only champion. Scores are not comparable across the split, and nothing in the record says why. Resolving once before the loop and logging mv.version and mv.source makes the run replayable.

Trade-offs.

choicebuyscosts
Pin version/digest in the endpointdeterministic rollback, exact replaya promotion PR per environment per retrain
Follow the alias at serve timeretrains reach prod with no config changeevery consumer must record the resolved version or replay is ambiguous
One registered model, env-suffixed aliasesfewer objectsa staging flip can be read by prod code asking for the wrong alias
Separate registered model per environmentblast radius containedduplicated metadata and promotion tooling

Failure modes and detection. Mid-job flip: log the resolved version per run and assert one version per output file; alert when a run's output spans two. Lost update on concurrent promotion: compare the change record's expected-current against the alias after the write. Deleted or renamed alias: get_model_version_by_alias raises, so a serving path that resolves at request time returns 500s. Resolve at startup and fail the deploy instead. Registry/runtime drift: reconcile nightly by diffing the version recorded in each endpoint's config against the registry's current alias target.

Decision criteria. If you must replay last quarter's scores or roll back in one step, pin the version and treat the alias as a promotion convenience only. If retrains must reach production without a config change, follow the alias, but write the resolved version into every run record, and keep the previous assignment so rollback is a pointer move you can audit.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Design registry organization across dev, staging, and production.

Answer

The first thing I'd pin down is what "registry" means here and where the trust boundary sits. I'll assume one registry product, MLflow or SageMaker Model Registry, and that the real question is how a model earns the right to serve production traffic. My answer: three separate registries, one per environment, not one registry with environment labels. The label is the thing that fails.

Stages and tags are mutable metadata on a single object. If dev, staging and prod share one registry, then any principal that can call the transition API can move a version into production: the only thing stopping them is a policy you hope is right. Separate registries turn that into an IAM boundary: a training job in the dev account cannot write to the prod registry because it holds no role that can.

Concretely with MLflow: three tracking servers, each with its own backend store and artifact root. s3://ml-artifacts-dev, -staging, -prod. MLflow deprecated stages in favor of aliases as of 2.9, so I'd use aliases: @latest in dev, @candidate in staging, @champion in prod. The serving endpoint resolves @champion, never a raw version number. If it's SageMaker instead, that's three model package groups (fraud-dev, fraud-staging, fraud-prod) in three accounts, with ModelApprovalStatus as the gate: PendingManualApproval until a human or a CI policy approves, and a resource policy on the prod group for cross-account promotion.

Walk one promotion. A training job in dev writes version 42 to the dev registry; the artifact digest is sha256:9f2c…. A promotion job reads that version, copies the artifact to the staging bucket, recomputes the digest and refuses to register if it doesn't match. Staging registers it as version 7, tags @candidate, and runs the integration suite against a shadow endpoint. On pass, the prod promotion job, the only principal with write access to the prod registry, copies the artifact again, re-verifies the digest, registers prod version 3, and moves @champion to it. The endpoint picks up @champion on the next rollout.

Three failure modes I'd watch. Alias drift: someone with prod write access moves @champion by hand. Detect it by alerting on registry mutation calls from any principal that isn't the promotion job: CloudTrail for SageMaker, Databricks audit logs for a Unity Catalog registry. Artifact mismatch: prod serves weights that differ from what staging tested, usually because the copy was skipped and the endpoint pulled from the dev bucket. Detect by logging the artifact digest at model load and comparing it to the registered digest; a mismatch pages. ACL copy: someone clones the dev role into prod and now training jobs can write prod. Detect with IAM Access Analyzer plus a canary job that attempts a prod write and must fail.

Retention and residency differ per environment and should be explicit: dev keeps the last 50 versions or 30 days, staging 90 days, prod indefinite, or seven years if the model sits in a regulated decision path. If data can't leave the EU, the prod registry and its artifact bucket live in an EU region and an SCP blocks cross-region writes.

The cost is real: three backend stores, three buckets, and a promotion pipeline you own and test. That's the price of making "this model is allowed to serve" an access-control fact rather than a convention.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Design model promotion and approval gates.

Answer

The 90-second version

A promotion gate is not a checklist, it is a state machine over an immutable artifact. Pin the model by digest, sha256 of the serialized artifact, and make promotion a compare-and-set on a named alias: champion in MLflow, or the Approved status on a model package in SageMaker Model Registry. The write only succeeds if the alias still holds the digest the approver actually reviewed. Everything else hangs off that one property.

Then pick the risk tier, because it decides how heavy the gates are. Tier 1 (payments, anything medical, anything user-facing and slow to reverse): approver must be a different person from the trainer, artifact signed, full lineage. Tier 3 (internal ranking, one-line revert): automated gates, one reviewer, no ceremony. The mistake is running the Tier 1 pipeline on Tier 3 models: people route around a gate that costs them an hour for a model that costs them nothing to roll back.

The gates and what each one catches

GateTier 1Tier 3Catches
Artifactcosign signature + SLSA provenance, verified at deploydigest recordedswapped or tampered artifact
Lineagedata snapshot hash, commit, hyperparamscommit + data versionunreproducible model
Schemainput/output diff vs serving contractsamefeature drift breaking the endpoint
Evalfrozen holdout, its hash checked against the training manifestsametest leakage
Slicesworst-slice AUC within 0.02 of championoverall metric onlya good average hiding a broken segment
Approvalnamed human ≠ trainer, expires in 90 daysautomated + one reviewerrubber stamping, stale approval

Why compare-and-set, specifically

A mutable pointer can be retagged by anyone with write access. The audit log shows the retag but not whether the approver ever saw that digest, so "approved" and "deployed" can drift apart silently. Binding the approval record to {digest, evidence_hash, expiry} and making the alias write conditional on the current value closes that gap: a promotion that races another promotion fails loudly instead of overwriting it.

Failure modes, and how you'd see them

  • Retag bypass. Alert when an alias changes to a digest with no approval record in the last N minutes. Cost: noise if you promote often; tune N to your release cadence.
  • Stale approval. A model approved 90 days ago may be fine, but the input distribution moved. Expiry timestamp plus a drift monitor on the serving inputs.
  • Rubber stamping. Measure time from approval request to decision. If the median across many approvals is under a minute, the gate is theater and you should automate it instead of pretending.
  • Canary flapping. Guardrail auto-rollback fires, someone re-promotes, loop. Count rollbacks per digest; more than one means the guardrail threshold is wrong, not the model.

Canary sizing, because "run a canary" is not a plan

To detect an error rate doubling from 2% to 4% at 95% confidence and 80% power you need roughly 1,140 requests per arm. At 100 rps that is ~11 seconds of traffic; at 1 rps it is ~19 minutes. A five-minute canary on a low-traffic endpoint cannot see that regression: it will pass everything and tell you nothing.

The promotion trace

  1. Trainer registers v42, digest d7f3….
  2. CI runs eval, writes metrics and slice report as an evidence artifact.
  3. Approver reviews, signs {digest: d7f3…, evidence_hash, expiry}.
  4. Promote: CAS champion from the expected digest to d7f3…; fails if the alias moved.
  5. Canary at 5% traffic, guardrails on p99 latency and error rate.
  6. After the window, CAS to 100%.

An expired or failed gate is not overridable by the same person who owns the model. A scoped exception (named approver, reason, expiry) is fine; a silent override is how you end up explaining a bad model in an incident review.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Handle a registry alias that disagrees with the production endpoint.

Answer

Core answer (say this first)

A registry alias is a control-plane indirection: a stable name that resolves to a set of endpoints. The disagreement is that the alias resolves to set A while production traffic is served by set B. The registry is the control plane, the endpoint is the data plane, and they converge asynchronously, so the first rule is to read the data plane, not the registry, to find out what is actually serving.

Assumptions I'd state up front: I have read access to the registry, the data plane and the audit log; production is live; I can freeze deploys but not traffic.

Three moves, in order:

  1. Freeze promotion, not traffic. Stop new deploys so the picture stops moving.
  2. Establish ground truth from the endpoint itself (TLS cert SAN, /healthz build SHA, container image digest) and compare it against what the alias claims.
  3. Pull the alias write history and the audit log with timestamps.

Then classify the cause before touching anything.

Classify before you act

CauseDetection signalAction
Reconciliation lagalias write is younger than the convergence window; registry index advanced, data plane stalewait one window, re-read
Incomplete rolloutendpoint set holds two versionsfinish or roll back the deploy
Unauthorized mutationaudit log shows a write from an unexpected principal, no matching deploy eventsecurity incident: freeze, rotate, restore
Rollbackdeploy history shows a rollback; alias still points at the pre-rollback versionre-point the alias

Why lag looks like drift

A registry write is a control-plane event; the data plane converges on its own schedule. kube-proxy rewrites its rules on a 30s sync period, Consul agents anti-entropy sync every 60s, and Envoy gets an xDS push from istiod. A write at T is visible in the registry at T but not in the data plane until T+window. Inside that window the alias and the endpoint legitimately disagree, and "fixing" it makes things worse.

Trace

Shell
# what the registry claims
$ kubectl get svc checkout -o jsonpath='{.spec.externalName}'
checkout-v2.internal

# what is actually serving
$ kubectl get endpointslice -l kubernetes.io/service-name=checkout \
    -o jsonpath='{range .items[*].endpoints[*]}{.addresses[0]}{"\n"}{end}'
10.0.4.11
10.0.4.12
10.0.4.13

$ for ip in 10.0.4.11 10.0.4.12 10.0.4.13; do
    curl -s "http://$ip:8080/healthz" | jq -r '"\(.build_sha) \(.version)"'
  done
a1b2c3d v2.4.0
a1b2c3d v2.4.0
9f8e7d6 v2.3.1   # one endpoint still on the old build

Two of three endpoints run v2.4.0 and one still runs v2.3.1: that is an incomplete rollout, not drift. If all three had matched the alias, I would re-read after one convergence window before calling it anything.

Trade-off: fast flip vs reviewed change

Criteria: is the serving endpoint known-good and approved, and is user impact active? If the serving endpoint is the previous known-good and users are erroring, flipping the alias back is the right fast move: it reverts to a state that already passed review, so it needs no new review. If the serving endpoint is unvetted (unknown digest, no approval) do not flip to it; restore the intended version through a reviewed change. Editing the registry record to match reality without a change record is never right: it destroys the audit trail and hides the drift.

Failure modes

  • Flipping to the wrong endpoint because you trusted the registry. Detect: 5xx rate after the flip.
  • Two writers racing: a pipeline and a human. Detect: interleaved writes in the audit log. Fix: compare-and-set on the registry's modify index (Consul ModifyIndex, Kubernetes resourceVersion).
  • Blast radius: if the alias fronts N endpoints and M are wrong, M/N of traffic is affected. 3 of 12 tasks is 25%.

Close by preserving the timeline for audit, and notifying owners if unapproved behavior served.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Design a safe registry-backed rollback.

Answer

What I'd say first (60–120s)

Assume "registry-backed" means both the serving image and the model artifact live in an OCI registry and are addressed by digest, not tag. Rollback is then a redeploy of a previously verified digest, not a retrain, not a re-export.

Four parts:

  1. Every release records the resolved digests (image + model) in a release manifest, and the workload pins them: image: registry/serve@sha256:....
  2. The registry enforces tag immutability so a digest can't be overwritten, and admission control verifies the cosign signature before the pod starts.
  3. Rollback re-applies the recorded manifest; traffic shifts back through the same canary mechanism used forward.
  4. Data is the hard part. Code rolls back, schema and caches don't, so migrations must be expand/contract and cache keys must include the model digest.

Mechanism

A tag is a mutable pointer; sha256:... is the hash of the manifest, so pulling by digest is byte-identical to what was tested. Roll back by tag :prod and a push over that tag silently gives you a different artifact: the classic rollback failure. ECR's image tag immutability setting, Artifact Registry and Harbor all let you forbid the overwrite.

Cosign stores the signature as an OCI artifact beside the image. A policy controller (Sigstore policy-controller, or Kyverno verifyImages) rejects unsigned or wrong-key images at admission. Cost: if the signing key is rotated or the Rekor entry is unreachable, rollback is blocked, so version the verification policy's key set and rehearse rollback in staging.

With Argo Rollouts, kubectl argo rollouts set image plus setWeight steps 10→25→50→100. In-flight requests drain via preStop and terminationGracePeriodSeconds.

Three things don't roll back: DB schema, feature-store contents, caches. Expand/contract means add column, dual-write, backfill, and drop the old column only after the old version is outside the rollback window. Cache keys must include the model digest, or the old model serves the new model's cached outputs.

Failure modes and detection

failuresignal
tag moved / mutableresolved digest ≠ recorded digest; admission denies
signature or key mismatchadmission webhook rejection events, FailedCreate
feature schema driftsmoke test on a production feature sample fails; 5xx on predict
stale cachehigh hit rate but shifted output distribution; digest absent from key
non-backward-compatible migrationerror spike on one specific query after rollback
registry unavailableImagePullBackOff; mitigate with a pull-through cache

Trade-offs

  • Digest-pinned redeploy: correct, slow. Example: a 1.2 GB image at 100 MB/s ≈ 12 s pull, + ~15 s scheduling and start, + 10 s readiness ≈ 40 s to first healthy pod. Use when the change is in the artifact.
  • Feature-flag kill switch: seconds, no redeploy, but only works if the bad behavior sits behind a flag and that path is tested. Use for model-selection changes.
  • Blue/green with both versions warm: fastest cutover, double the capacity cost. Use when the rollback window is minutes, not hours.

Deciding criterion is how long the bad version can serve: seconds → flag, minutes → blue/green, tens of minutes → digest-pinned redeploy.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Design registry support for online and batch deployments.

Answer

Core answer. Assume one registry (MLflow Model Registry or SageMaker Model Registry) backing both a real-time endpoint and a scheduled batch job, and that both must trace to the same approved artifact. The design is: one immutable, content-addressed model package; two thin deployment records that reference it; alias resolution frozen at submission time.

The registry stores a model version as (name, version:int, digest, signature, preprocessing ref, dependency lock, approval status). The digest is sha256 over the artifact tarball, e.g. sha256:4b1e...; container images are pinned the same way (repo@sha256:...), never by tag. MLflow 2.9 deprecated stages in favour of aliases (@champion), which is what you want here: an alias is a movable pointer, a version+digest is not. SageMaker gives the same shape: a ModelPackageGroup holds ModelPackages with an ApprovalStatus, and both a real-time endpoint config and a batch transform job reference the same ModelPackageArn.

Then two deployment records:

fieldonline deploymentbatch deployment
model refname@version + digestname@version + digest
resolved atdeploy timejob submission
envimage digest, feature service versionimage digest, input snapshot URI
shapeinstance type, min/max replicas, traffic splitpartition count, output path
approvalsame approval scopesame approval scope

The key rule: the batch job resolves @champion to a concrete version+digest once, at submission, and writes it into the job record. MLflow's models:/fraud@champion resolves at load time, so a 6-hour job that loads lazily would pick up a mid-run alias move. Resolve eagerly:

Python
# MLflow 2.x
client = MlflowClient()
mv = client.get_model_version_by_alias("fraud", "champion")   # concrete version
v  = client.get_model_version("fraud", mv.version)
digest = v.tags["sha256"]
job_spec = {"model_uri": f"models:/fraud/{mv.version}", "digest": digest}

Equivalence. Before promotion, run both paths over a frozen golden set (say 10k rows) and compare. For regression assert max|online - batch| <= 1e-6; for classification assert identical argmax and max|score diff| <= 1e-5. Differences come from float32 vs float64 accumulation, BLAS thread count, and batch padding: document the ones you accept rather than hiding them.

Divergence. Tag every prediction log with the model digest and log score mean/p50/p99 and null rate per mode. Alert when PSI between the online and batch score distributions exceeds 0.2.

Rollback. Because both records pin a digest, rollback is repointing the alias or redeploying the previous digest: independent per mode.

Trade-off. One shared package vs separate online/batch artifacts. Share when preprocessing is identical and deps overlap: one approval, one equivalence test, no drift. Split the packaging (lean online image, batch with Spark/TFRecord readers) but keep the weights digest identical when batch needs distributed readers online cannot load. Deciding criterion: does the batch path need a dependency the online path cannot ship?

Failure modes. Alias moved mid-batch → job silently switches models; detect by asserting the loaded digest equals the job record's digest at start and end. Silent preprocessing skew → online uses the feature service, batch reads raw parquet; detect with the golden-set equivalence test in CI. Unpinned image tag → latest re-pulled; detect by rejecting deploys whose image ref lacks @sha256:.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Version models that depend on an online feature store.

Answer

The core answer: a model version is not just the weights. It is the weights plus the exact feature computation that produced its inputs. If you version the model but not the features, a feature change can silently alter what the model sees at serving time, and your offline metrics will not predict online behavior.

Assume an online feature store like Feast, Tecton, or Vertex AI Feature Store, with an offline store for training and an online store for serving. Assume the model is already trained and you are deploying it.

What a strong candidate says in the first 90 seconds: you need to version the feature definitions, transformations, source schemas, and the feature-store contract together with the model. In practice, that means a feature view version or a feature service version that pins the exact transformation logic. For example, Tecton feature services pin specific feature view versions; Feast versions feature views by name or git ref and references them in a feature service; Vertex AI Feature Store has feature view versions you can pin. The deployment record stores the model digest plus the feature service version or config hash. That way, rolling back the model also rolls back the feature path.

Why does this matter? Offline, you do point-in-time correct joins to build training data. Online, you serve the latest value. If the transformation logic changes: say, the window for a rolling average changes from 7 days to 30 days, or a null-handling default changes from 0 to -1: the model's input distribution shifts. That is training-serving skew. You detect it by logging online feature vectors and comparing their distribution to the offline training set, or by running a shadow pipeline that computes features both ways and diffs them.

Strict pinning is not always right. If you pin every feature view version forever, you accumulate technical debt and cannot benefit from bug fixes. The deciding criteria: how sensitive is the model to feature distribution? A fraud model may need strict pinning; a recommendation model may tolerate minor changes. You can use a compatibility policy: semantic versioning for feature views, where a major version bump requires a new model, a minor version bump is backward-compatible (e.g., adding a new feature), and a patch is a bug fix that does not change semantics. Or you can allow automatic upgrades if you have strong online-offline parity tests and canary deployments.

Concrete failure modes: missing feature at serving time (online store returns null, offline filled a default; stale feature) online store has not been updated, offline used fresh data; backfilled feature. Offline training data was backfilled after a bug fix, but online store still has old values; schema change. A feature type changes from int to float, and the model expects int. Detect these with freshness monitoring, null-rate alerts, and schema validation at write time. Rollback: if you roll back the model, you must also roll back the feature service version, or prove the current feature service is compatible with the old model. That proof is a compatibility test: run the old model against the current online features and compare outputs to the old model against the old features.

StoreVersioning mechanismPin in deployment
FeastFeature view name or git ref; feature service references viewsFeature service name + git SHA
TectonFeature view versions; feature service pins versionsFeature service version
Vertex AI Feature StoreFeature view versionsFeature view version ID

Hypothetical: model M trained on feature F_v1: avg_order_value_7d = sum(orders)/count(orders) over 7 days ending at event time. At serving, F_v2 changed to 30 days. For a user with 10 orders in 7 days and 40 in 30 days, offline training saw 10/7=1.43, online serving sees 40/30=1.33. The model's decision boundary shifts.

So the answer is: version the feature computation with the model, pin it in the deployment record, test for skew, and have a rollback that restores both.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Version a fine-tuned foundation model and adapters.

Answer

Core answer (first 90 seconds)

Version the composition, not the file. A served model is a tuple: base checkpoint revision, tokenizer, adapter, merge/quantization step, chat template, and inference runtime. Pin each by content digest, record the tuple in a signed manifest, and have the serving path recompute digests before loading: refuse to serve on mismatch.

Assumptions: the base lives in a Git-backed model repo (HF Hub or an internal registry), adapters are PEFT/LoRA, serving is vLLM or llama.cpp.

Why digests, not tags

A tag or branch is a pointer. main moves when someone pushes a continued-pretrain checkpoint; a tag can be force-pushed. revision=<40-hex commit sha> plus sha256 of each safetensors shard is immutable. Adapters are deltas on specific weight matrices: a LoRA trained on base revision A applies ΔW to W_A. Load it against W_B and the delta lands on different weights: no error, just worse output. Tokenizer changes are worse: adding tokens shifts embedding row indices, so adapter rows trained for token id 32000 now point at a different token.

JSON
{
  "base": {"repo": "meta-llama/Llama-3.1-8B", "revision": "<40-hex commit sha>",
           "shards_sha256": ["<sha256>", "..."]},
  "tokenizer_sha256": "<sha256>",
  "adapter": {"type": "lora", "rank": 16, "alpha": 32,
              "target_modules": ["q_proj", "v_proj"], "sha256": "<sha256>"},
  "merge": {"tool": "peft 0.12.0", "dtype": "bfloat16"},
  "quant": {"format": "gguf", "scheme": "Q4_K_M"},
  "chat_template_sha256": "<sha256>",
  "runtime": "vllm 0.6.2",
  "eval": {"suite": "internal-v3", "score": 0.81, "base_score": 0.74}
}

Sign it with cosign/sigstore and store it beside the artifact in the registry.

Merge vs adapter-on-the-fly

merged weightsadapter at serve time
artifact size (8B)~16 GB bf16 per variantbase 16 GB + ~0.4 MB adapter (rank 16, q/v only)
servingany runtimeneeds LoRA support (vLLM, llama.cpp)
multi-tenantone full copy eachhot-swap per request
quantizationquantize after mergequantize base, apply adapter in quantized domain

Merge when you ship one variant to a runtime without adapter support, or when you must quantize. Keep adapters separate when many tenants share one base: 0.4 MB vs 16 GB per tenant. The adapter path is wrong when your runtime has no LoRA kernel: you pay per-request overhead or silently fall back to the base.

Failure modes and detection

  • Moving base alias: loader recomputes shard hashes and fails, or eval drops. Cost: a silent quality regression you cannot attribute to a commit.
  • Chat template mismatch: adapter trained with a system-prompt template, served with the default. Detect with a golden-prompt suite asserting exact token ids.
  • Quantization drift: bf16 eval 0.81, Q4_K_M 0.78. Detect by evaluating the quantized artifact, not the bf16 one.
  • Wrong merge dtype: fp16 merge of a bf16 base overflows. Detect by diffing logits on a fixed prompt.

Rollback: keep the previous manifest and artifacts; rollback repoints the alias to the prior digest, it does not re-merge.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Register and govern an ensemble model.

Answer

An ensemble isn't a model, it's a dependency graph. So I'd register the graph and treat the members as pinned dependencies, not as things the serving layer looks up by alias at request time.

Assumptions I'd state up front: members live in a model registry (MLflow Model Registry, SageMaker Model Registry, or W&B artifacts), serving is containerized, and members get retrained on their own cadence, which is exactly why the ensemble needs its own version.

The core move: one immutable manifest.

YAML
ensemble: fraud-ensemble
version: 14
members:
  - {name: xgb-a, uri: "models:/fraud-xgb/12", digest: "sha256:9f2c...", weight: 0.4}
  - {name: nn-b,  uri: "models:/fraud-nn/7",   digest: "sha256:41ab...", weight: 0.6}
routing: weighted_sum
preprocess: features-v3
schema_hash: "sha256:7d10..."
serving_image: "fraud-serve@sha256:c0de..."

Every field is a digest or a version, never an alias. Approval is on this manifest; deploy and monitor are keyed by its digest. A member promotion in the registry changes nothing until someone cuts ensemble v15.

Why the alternatives lose. Registering members separately and pointing serving at models:/fraud-xgb@champion is cheap and common, but the ensemble version becomes implicit: a teammate promoting a member silently changes what the ensemble is, and you can't reproduce last Tuesday's predictions. Flattening everything into one serialized artifact (a single TorchScript or pickle) is trivial to serve but throws away per-member lineage and makes partial retraining impossible. The manifest is the middle: reproducible, per-member lineage intact, at the cost of a re-approval whenever any member moves.

Failure modes and how you'd catch them.

  • Member missing at load. The pod 500s on its first request. Catch it with a startup smoke test that resolves every digest before the instance joins the load balancer.
  • Schema drift. A member was trained on features-v3 but the manifest pins features-v2; values are silently wrong, not crashing. Catch it by hashing the feature vector at serving and comparing to schema_hash.
  • Correlated errors. This is the one that quietly kills ensemble value. Variance reduction assumes members fail on different rows. If two members share a feature pipeline or training slice, their errors correlate, and the ensemble's accuracy collapses toward the single-member number. Measure pairwise error correlation on the eval set; ρ ≈ 0.9 between two members means the second is nearly redundant.
  • Silent routing edits. Someone tweaks weights in the serving config; the manifest digest is unchanged but behavior isn't. Hash the whole config into the manifest so this is impossible.

The arithmetic, illustrative: five members at 92% accuracy with independent errors give a majority vote of about 99.5%. Correlate two of them at ρ = 0.9 and the effective independent count drops; the ensemble lands somewhere between 92% and 99.5%, and you only find out by measuring ρ, not by counting members.

Rollback restores the manifest digest, which restores the graph and every pinned member digest. Rolling back a member alias does not roll back the ensemble: that's the whole reason the manifest exists.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Handle non-deterministic training in registry reproducibility.

Answer

The thing to say first: on GPU training you cannot promise byte-identical reruns, and a registry that gates promotion on artifact-hash equality gets bypassed within a month. What you can promise is that every controllable input is pinned and recorded, and that the metric gap between two runs of the same recorded config is bounded by a tolerance you measured rather than guessed. I'll assume one team, one registry (MLflow or equivalent), NVIDIA GPUs with cuDNN and NCCL, and a promotion gate that CI or a human has to pass.

Split the inputs into what you can pin and what you can only bound.

InputPinned howResidual nondeterminism
Codegit SHA logged as a run tagnone
Data and featuresDVC dvc.lock md5 per pipeline outputnone, if the pipeline is hermetic
EnvironmentOCI image digest sha256:..., never the :latest tagnone
CUDA / cuDNN / NCCLversions baked into the image; CUBLAS_WORKSPACE_CONFIG=:4096:8, torch.use_deterministic_algorithms(True), cudnn.benchmark=Falsekernel selection still varies with GPU model and driver
SeedsPYTHONHASHSEED, torch and numpy seeds, per-worker loader seedsnone at a fixed world size
Parallelismworld size and NCCL_ALGO recordedallreduce order changes with world size and topology: the one you cannot pin away

That last row is why the registry stores the artifact you evaluated, not a rebuild of it. The digest is authoritative for what shipped; it is not a claim that a rebuild would match.

To turn tolerance into a number instead of a vibe, rerun the same recorded config five times on the same hardware. Say validation AUC comes back 0.812, 0.814, 0.811, 0.813, 0.812. Mean 0.8124, sample std about 0.0011, so a ±3σ band is roughly ±0.0033. A candidate at 0.8095 is inside noise; one at 0.805 is a real regression. Do this per slice too: a rare-class slice with 200 examples will have a far wider band, and that is the number that stops you shipping a model that quietly got worse for one segment.

Three ways this breaks in practice. First, the band is set from a single rerun, so it is too tight and the gate fails on noise; engineers learn to click override and the gate stops meaning anything. Detect it by logging override rate per week, if it sits above a few percent, the band is wrong, not the model. Second, the image is pinned by tag, someone rebuilds pytorch:2.3-cuda12.1 upstream, cuDNN changes, and every metric shifts by 0.004 overnight. Detect with a CI check that fails when the resolved digest differs from the recorded one. Third, the job reproduces at 8 GPUs and not at 16 because NCCL's reduction order changed; detect by running the reproducibility job at two world sizes. The cost is one extra training run per release, which is cheap next to defending an artifact you cannot reproduce in an audit.

The trade-off is throughput: use_deterministic_algorithms(True) disables the fastest kernels, and the penalty is workload-dependent. Often double-digit percent on attention-heavy models. Don't pay it for a research sweep. Pay it for the artifact you are about to promote, and record that you did.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Reconstruct which model produced a disputed historical prediction.

Answer

The 90-second answer

"Which model" means the immutable artifact, not the name it answers to today. Registries version models immutably but expose mutable aliases (champion, Production, default) so resolving the alias now tells you what serves traffic now, not what served that request. Assume the prediction log carries a request id; if it doesn't, you're doing forensics rather than lookup, and you should say that up front.

The reconstruction is a join. Take the request id from the prediction log, find the deployment record it was served under, and read the model version pinned in that record.

EvidenceWhere it livesWhat it pins
request id, timestamp, variantprediction log (Parquet on S3, BigQuery, CloudWatch)the row to join on
endpoint config + variant weightsSageMaker DescribeEndpointConfig, Kubernetes Deployment revisionwhich version got the traffic
model version + artifact URIMLflow models:/fraud/9, SageMaker ModelPackage ARN, Vertex Model idthe immutable version
artifact digestS3 ETag (MD5 for single-part uploads) or an additional SHA-256 checksumthat the bytes served match the registry entry
feature vectorFeast feature logging, online-store snapshotwhat the model actually saw

Trace: request id 8f3c → prediction log row names endpoint fraud-ep, variant canary → endpoint config revision 14 shows canary weight 10% pointing at ModelPackage fraud-9 → s3://models/fraud/9/model.tar.gz ETag matches the digest recorded at registration. That is the model.

Three routes, and when each wins

  1. Provenance join (above). Exact and cheap. Requires the log to carry the variant or version. This is the only route that produces evidence rather than inference.
  2. Re-inference replay. Re-run the logged input through each candidate version and compare outputs. Use when the log has inputs but no version. Costs a full replay, and it is ambiguous when two versions emit identical outputs: common for small model deltas.
  3. Artifact forensics. Hash the artifact actually served (container image layer, model file) and match it against registry digests. Use when you have the artifact but lost the log. It cannot tell you which request it served.

Failure modes

  • Alias drift. MLflow's registry does not retain alias history by default; champion today is v12, at prediction time it was v9. Detect by diffing your CI/CD deploy log against the registry. Cost: you name the wrong model in the incident report.
  • Canary without a variant field. 10% of traffic to v9, log has no variant column → 10% of predictions are unattributable. Detect by comparing per-variant prediction counts against configured weights; a 90/10 config with a 100/0 log split means the field is missing.
  • Feature skew. Offline replay reads the offline store; serving read the online store. Feast's get_online_features and get_historical_features can disagree after a late-arriving event. Detect with feature logging at serve time.
  • Nondeterminism. GPU kernel selection, unseeded sampling, temperature > 0. Detect by replaying one input twice and diffing; if outputs differ, replay cannot identify the version.

Preserve the join key and the digest, redact the input, and if the log lacks the variant, that gap is the finding: fix the logging before the next incident.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

How do you implement cryptographic signing and verification for model artifacts stored in a registry?

Answer

The 90-second version

First I'd pin down the trust boundary, because "sign the model" is ambiguous. The unit you sign is a content digest, never a path or URL. The signer is the CI job that passed the eval gate, identified by its OIDC identity, not a long-lived key in a shared secret. The verifier is the deployment admission path, not the inference process: by the time the model server has downloaded the tarball, a malicious pickle has already had its chance to run.

Assumptions I'd state out loud: artifacts live in an OCI registry or S3 with a model registry on top; CI runs on GitHub Actions or similar with OIDC; serving is on Kubernetes. Given that, the shape is: canonicalize, sign the digest, verify at admission, re-verify bytes at load.

Canonicalize. A model is usually a tree, not a file: weights, MLmodel, requirements.txt. Hash each file with SHA-256, write them into an ordered manifest, hash the manifest. That root digest is what you sign. Or push the tree as an OCI artifact and use the OCI manifest digest; same idea, and you get registry-side immutability for free.

Shell
tar -czf model.tar.gz ./model_dir
oras push registry.internal/models/churn-risk:v1.4.0 \
  --artifact-type application/vnd.acme.model.v1 \
  model.tar.gz:application/vnd.acme.model.layer.v1+tar
# -> pushed registry.internal/models/churn-risk@sha256:7c8b09f...

Sign. Keyless Sigstore: the CI job's OIDC token goes to Fulcio, which issues a short-lived certificate binding the signature to the workflow identity, and the signature is recorded in Rekor.

Shell
cosign sign --yes \
  --oidc-provider https://token.actions.githubusercontent.com \
  registry.internal/models/churn-risk@sha256:7c8b09f...
cosign attest --yes --type custom --predicate eval_metrics.json \
  registry.internal/models/churn-risk@sha256:7c8b09f...

On SageMaker Model Registry the equivalent is an AWS KMS asymmetric key (kms:Sign) over the artifact digest, with the signature stored in CustomerMetadataProperties and the key policy restricted to the build role.

Verify. An admission controller (Kyverno, OPA Gatekeeper) resolves the alias to a digest, checks the signature against an allowlist of pipeline identities, and pins the digest into the pod spec. Then an init container verifies file hashes against the manifest before anything deserializes.

What I'd push back on. Signing s3://bucket/model.tar.gz is the common mistake. The URI is mutable, and the ETag isn't a content hash either: for multipart uploads it's <md5-of-part-md5s>-<partcount>, so it changes with part size rather than content.

Failure modes. Alias TOCTOU: you verify @production, someone repoints it, you deploy a different digest. Resolve once and pin. "Signature valid" is not "authorized signer": any GitHub repo can obtain a Fulcio cert, so you must check the certificate SAN and issuer against your pipeline, not just that cosign exited 0. Rekor or Fulcio outage must fail closed, or you've built a bypass. And hash verification proves provenance, not safety: a signed pickle is still a pickle; the eval gate is what makes the artifact trustworthy, the signature only makes it attributable.

What would change my answer: if the registry never leaves one trust domain, KMS plus IAM is simpler than Sigstore. If you need offline or air-gapped verification, keyless with Rekor doesn't work: you need a pinned public key.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Secure a model registry against supply-chain compromise.

Answer

Let me clarify what we're protecting. A model registry stores model artifacts (weights, configs) and maps aliases like production to a specific version. I'll assume training and serving run in separate trust domains, and the registry is internal. The core answer: treat the registry as a supply-chain boundary. Every artifact must be content-addressed and signed, and promotion to a production alias must require a separate identity that verifies the signature and provenance. Verification must happen at load time, not just upload.

Why? Because a model file is not passive data. A pickle file can execute arbitrary code when loaded. If an attacker can get a malicious model into the registry and have a serving job load it, they get code execution in the serving environment. The registry is a high-value target because serving jobs trust it implicitly.

So the controls bind to that threat. First, identity separation. Use short-lived OIDC workload identities for each action: upload, metadata update, approval, alias change, deployment, deletion. For example, a training job gets an AWS IAM Roles for Service Accounts token scoped to s3:PutObject on a specific prefix. It cannot change aliases. A separate approval service, with its own identity, verifies the artifact's signature and provenance before setting the alias. No long-lived keys.

Second, artifact integrity. Store artifacts in an OCI registry with a sha256 digest. Sign with Sigstore cosign using keyless signing tied to the workload identity. Attach in-toto attestations for provenance (who built it, from what commit). Verify signature and attestation at registration, promotion, and load. If verification fails, the load fails.

Third, safe loading. Prefer safetensors or ONNX over pickle. If pickle is unavoidable, load in a gVisor or Firecracker microVM with no network, read-only filesystem, and seccomp. This contains the blast radius if a malicious pickle executes.

Fourth, network and logging. Restrict registry access to known CIDRs or a private endpoint. Log every read and mutation to an independent sink, e.g., CloudTrail to S3 with Object Lock. Alert on unusual download patterns (a training job downloading a production model) or alias changes outside a change window.

Tradeoffs. Keyless signing with OIDC requires the registry to trust the OIDC provider; if that provider is compromised, signing is compromised. An alternative is long-lived keys in an HSM, but rotation is harder. Safe loaders may not support all architectures; converting to ONNX can lose custom ops. Sandboxing adds latency, Firecracker cold start is on the order of 100-200 ms, and operational complexity. Strict verification at load can break rollback if an old model was signed with a now-revoked key; you need a revocation policy and a way to re-sign.

Failure modes. Credential compromise: attacker steals a training job's OIDC token. Detection: anomalous upload from unexpected IP or at unusual time. Mitigation: short token lifetime (e.g., 15 minutes) and scoped permissions. Artifact tampering: attacker modifies artifact in storage. Detection: digest mismatch at load. Mitigation: content-addressed storage with immutability (S3 Object Lock, OCI immutable tags). Alias swap: attacker changes production alias to a malicious model. Detection: audit log alert on alias change. Mitigation: two-person approval for alias changes. Dependency confusion: malicious package in training environment. Detection: dependency scanning (Trivy, pip-audit) and egress restrictions. Mitigation: pin dependencies with hashes, use a private package index.

Here's a trace of an attack. An attacker compromises a training job's OIDC token. They upload a malicious model as version 2. They try to set alias production to version 2, but the token lacks alias:write. Instead, they modify the training job to write a malicious dependency into the next legitimate model. That dependency exfiltrates the signing key from the build environment. The attacker signs a malicious model with the stolen key and uploads it. The registry accepts it because the signature is valid. The serving job loads it. If it's a pickle, code executes. If it's safetensors, the code doesn't execute, but the weights may be backdoored. Detection: audit log shows a signing event from an unexpected IP; a canary deployment shows degraded accuracy.

A table of controls:

ThreatControlDetection
Malicious pickleSafe loader (safetensors) or sandboxLoad-time digest mismatch, sandbox escape alerts
Alias swapSeparate approval identity, two-person ruleAudit log alert on alias change
Signing key theftKeyless OIDC or HSM-backed keysAnomalous signing events
Dependency confusionPrivate index, hash pinningEgress alerts, dependency scan

The key is to make the attacker's job require compromising multiple independent identities and to detect any single compromise before it reaches production.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Design the authorization model for a model registry: which identities may register a version, move an alias, or delete a version, and how do you stop one team from promoting or deleting another team's model?

Answer

Four actions, four different blast radii: register a version, change approval status, move an alias, delete a version. In MLflow, Vertex AI and SageMaker the alias or approval status is what the serving path reads, so moving an alias is a production deploy wearing a metadata costume. The identity that trains the model must never hold it.

Start from that split and the matrix falls out:

IdentityRegisterMove alias (dev)Move alias (prod)Delete
Training pipeline SA, per teamown model group onlynonono
Promotion SA (CI)noyesnono
Release manager, per teamnoyesown group onlyno
Registry admin (platform)nobreak-glass, loggedbreak-glass, loggedyes, after reference check
Retention job SAnonononon-aliased versions only

Scoping is per resource, never per project. On SageMaker the training SA gets sagemaker:CreateModelPackage on arn:aws:sagemaker:us-east-1:111122223333:model-package/recs/* and nothing else; cross-account sharing goes through a resource policy on the model group, not a broad role. Vertex AI lets you set an IAM policy on an individual Model resource, so a team holds aiplatform.models.update on its own model instead of project-wide aiplatform.admin. Azure ML registries carry registry-scoped roles for the same reason. OSS MLflow is the awkward one: its registry REST API has no per-model ACL, so authorization has to sit in the tracking server's auth layer or a reverse proxy in front of it, if you self-host and skip that, every authenticated caller can move every alias.

Add an explicit deny so a broader attached policy cannot widen the grant:

{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "sagemaker:CreateModelPackage", "Resource": "arn:aws:sagemaker:us-east-1:111122223333:model-package/recs/" }, { "Effect": "Deny", "Action": ["sagemaker:UpdateModelPackage", "sagemaker:DeleteModelPackage"], "Resource": "" } ] }

For teams that share one promotion role, tag-based conditions keep them apart: allow the alias move only when aws:ResourceTag/team equals aws:PrincipalTag/team. That is what stops team A's pipeline from promoting team B's model without minting a role per team.

Audit is the other half. Every alias move or approval flip is an event carrying actor, model, version, previous target and new target. CloudTrail captures SageMaker's UpdateModelPackage; Vertex AI writes alias changes to Cloud Audit Logs; a self-hosted MLflow needs the proxy to log it, because the registry will not. Alert on the two shapes that matter: an alias move whose actor is the same identity that registered the version (self-approval), and any sts:AssumeRole into the promotion role lacking an OIDC subject or ExternalId condition (confused deputy). Review grants quarterly against the team roster: NIST AI RMF's Map function expects documented roles and responsibilities, and a reorg is where orphaned prod-promote grants hide.

Failure modes worth naming: a pipeline holding both create and alias-move, so a bad eval gate promotes itself; deletion of a version an endpoint still serves, which SageMaker and Vertex AI will happily allow. Block it with a reconciliation job that checks alias and endpoint references before the retention job runs; and break-glass that is never revoked. Detect all three from the audit stream, not from a runbook.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Plan cross-account or cross-region model sharing.

Answer

Clarify two things before designing anything: is the consumer in another account in the same Region, or in another Region? And does it train (reads the artifact once) or serve (an endpoint loads it on every scale-out)? Those answers pick the design.

Assumptions: AWS; SageMaker Model Registry holds the model package; S3 holds artifacts; KMS encrypts them; both accounts sit in one AWS Organization with an SCP layer.

Core recommendation. Same Region, cross-account: share, don't copy. Put the model group in an AWS RAM resource share and grant the consumer's execution role read on the artifact prefix with a bucket policy. One source of truth, and revocation is one API call. Cross-Region: you must copy, because SageMaker requires the model artifact bucket to be in the same Region as the endpoint. Replicate the artifact, re-register the model package in the destination Region, and attach a lineage manifest carrying the source model package ARN and the SHA-256 of the artifact.

Why the digest and not the version number: model group version numbers are per-account counters. Source version 7 arrives as version 1 in the destination group. The number proves nothing across the boundary; the digest is the only thing that shows the bytes are identical.

JSON
{
  "Version": "2012-10-17",
  "Statement": [{
    "Sid": "ConsumerReadOnly",
    "Effect": "Allow",
    "Principal": {"AWS": "arn:aws:iam::222222222222:root"},
    "Action": ["s3:GetObject", "s3:GetObjectVersion"],
    "Resource": "arn:aws:s3:::prod-models-us-east-1/approved/ranker/*",
    "Condition": {
      "StringEquals": {"aws:PrincipalOrgID": "o-abc123"},
      "Bool": {"aws:SecureTransport": "true"}
    }
  }]
}

Encryption is where cross-Region copies break. A single-Region KMS key cannot decrypt ciphertext in another Region. Trace it: source object in us-east-1 under alias/model-artifacts, S3 Cross-Region Replication to eu-west-1. The replication role needs kms:Decrypt on the source key to read the object and kms:GenerateDataKey on the destination key to write it. Miss either and the object never lands: replication status goes FAILED, visible as the OperationsFailedReplication metric and the s3:Replication:OperationFailedReplication EventBridge event. Even when both succeed, the destination object is under the eu-west-1 key, so a consumer handed the source key ARN gets AccessDeniedException from KMS at model load. Fix: a KMS multi-Region key, same key ID and material in both Regions, so the ciphertext is portable. Also note replication only covers objects written after the rule exists: the versions already in the bucket need S3 Batch Replication, and S3 RTC commits to 99.99% of objects within 15 minutes.

Trade-off.

Share (RAM + bucket policy)Copy (CRR + re-register)
Regionssame Region onlyany
Source of truthonetwo, drift possible
Revocationnext authorization checkyou must delete the copy
Blast radiusproducer bucket outage hits consumerisolated
Costno storage duplicationstorage + egress + a second approval

Choose copy when residency or Region forces it, or when the consumer must survive a producer outage. Choose share when both accounts are in one Region and you want revocation to actually mean something.

Failure modes and how you see them.

  • Revocation doesn't stop a running endpoint. Deleting the RAM share blocks the next CreateModel or DescribeModelPackage, but an endpoint that already loaded the model keeps serving. Detect by enumerating endpoints that reference the shared package and deleting them; CloudTrail sagemaker:InvokeEndpoint from the consumer account after revocation is the tell.
  • A consumer caches the artifact. IAM is evaluated per request, so revoking the bucket policy stops new reads, not the copy already on disk. Detect with S3 data events in CloudTrail: a GetObject from the consumer after revocation means the policy didn't take.
  • Deletion is blocked by retention. If the artifact bucket uses S3 Object Lock in compliance mode, a "delete the model everywhere" request fails with AccessDenied and the retention cannot be shortened, even by root. Check s3:GetObjectRetention before promising a deletion date.
  • Region drift. An SCP denying sagemaker:CreateModelPackage and s3:PutObject outside approved Regions (StringNotEquals on aws:RequestedRegion) is what stops a team from quietly standing the model up in a Region legal never approved.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Manage model deprecation, retention, and deletion.

Answer

What I'd say first

Deprecation, retention and deletion are three different clocks, and conflating them is the usual mistake. Deprecation is a notice: the version still works, but nobody new should build on it. Retention is how long you must keep evidence. Deletion is when the bytes go. A model can be deprecated for a year, retained for six, and its payload deleted tomorrow because of an erasure request.

Assumptions I'd state: the registry assigns immutable version IDs; artifacts live in an object store keyed by that ID; serving and batch logs record the version ID per prediction. If logs don't record the version, you cannot answer "who is still using this," and the rest is guesswork.

Deprecation

Publish a dated notice with owner, reason, replacement version, and a hard cutoff. In MLflow 2.9+ stages are deprecated in favour of aliases, so the mechanism is: move the production alias to the replacement, tag the old version deprecated=true, deprecation_date, replacement_version. New deployments are blocked by policy on the alias, not by deleting anything. Then watch residual use: count predictions per version ID in the serving logs. A version that still shows traffic after the cutoff is a consumer you missed.

Retention vs deletion

Split the store. Keep the registry record and lineage (which data, which code commit, which metrics) for the audit window; delete the payload (training data, PII in features) on the erasure clock. GDPR Article 12(3) gives you one month to act on an erasure request; HIPAA keeps documentation six years; SEC 17a-4 keeps records six years with the first two readily accessible. Those are the numbers that decide the retention period, not engineering preference.

Hard deletion of an encrypted artifact is cheapest as crypto-shredding: delete the KMS key. AWS KMS ScheduleKeyDeletion has a 7–30 day pending window (default 30), so plan the erasure request against that, not against the S3 delete.

Failure modes

  1. A nightly batch job pinned to a deleted version. It fails at 02:00 with a registry 404, or worse, falls back to a default model and silently scores wrong. Detect by alerting on "version referenced but not found" at scoring time, and by a canary that runs the job against the tombstone before you delete.
  2. Deleting the artifact but keeping the registry record. Reproducibility breaks: a retraining pipeline that reads the artifact 404s. Detect by a periodic job that resolves every non-deleted version's artifact URI.
  3. Deleting the KMS key before the audit window closes. You can't recover even with the ciphertext. Detect by gating key deletion on the retention tag.

Trade-off

Soft delete (tombstone: keep the record, mark deleted) vs hard delete. Tombstone when the reason is internal cleanup: lineage queries keep working. Hard delete when the reason is a legal erasure: the record itself may be personal data. Deciding criterion: does the record contain or point to personal data? If yes, hard delete plus crypto-shred; if no, tombstone.

Worked trace

Version 42, deprecated 2024-03-01, cutoff 2024-06-01.

dateactioncheck
2024-03-01alias moved to v43, v42 tagged deprecatednew deploys blocked
2024-06-01cutoff; serving log shows 0 predictions/day for v42residual use = 0
2024-06-02tombstone v42, keep lineageartifact URI still resolves
2024-07-15erasure request for a training rowpayload delete + KMS key scheduled
2024-08-14KMS key deleted (30-day window)ciphertext unrecoverable

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Design registry governance for emergency model promotion.

Answer

Let me clarify the assumptions first. The model registry is the source of truth for model versions and stages: think MLflow Model Registry or SageMaker Model Registry. Normal promotion requires offline evaluation, shadow deployment, canary, and two approvals. An emergency is a production incident where the current model causes harm (e.g., toxic outputs, a security vulnerability, or a business KPI drop > 5%) and waiting the normal two-week lead time is unacceptable.

The core answer: add an emergency promotion path to the registry that is time-boxed, gated by automated checks, and produces an immutable audit record. The path uses a break-glass role, a mandatory incident ticket ID, and a TTL. For example, set TTL to 4 hours. The registry enforces three things before any promotion: candidate identity is immutable (content hash of artifact + config), lineage is complete (training data snapshot, code commit, hyperparameters), and a minimum smoke gate passes (e.g., 100 requests, no PII leakage, p99 latency < 200 ms). If gates pass, the registry issues a signed promotion token with max traffic (e.g., 5%) and expiry. The serving layer enforces the token. A canary runs with hard rollback thresholds: error rate > 0.5% or business KPI drop > 2% triggers automatic revert within 90 seconds. Two-person approval is required if available; otherwise break-glass with post-hoc review within 24 hours. All bypasses are recorded as events with rationale, approver, and expiry. Notify risk and service owners via PagerDuty. Monitor intensively: model-specific dashboards, drift, and business KPIs. After TTL, either full evaluation completes and the model is promoted normally, or it auto-reverts. Post-incident: review why normal lead time failed, rotate break-glass credentials, and never edit history.

Mechanism: the registry stores each model version as an immutable record. Promotion is a state transition that requires a signed approval token. The emergency path uses a separate policy that relaxes approval count but tightens TTL and monitoring. The registry's API enforces gates: a webhook to CI runs smoke tests; if pass, it returns a token. The token includes expiry and max traffic. The serving layer reads the token and enforces traffic split. Rollback is automatic if metrics breach thresholds, triggered by a monitor that calls the registry to revert.

Trade-offs: emergency path reduces time-to-mitigate but increases risk of an unvetted model. Alternatives: hotfix the existing model in place (bad. Loses lineage), or roll back to the previous version (good if the regression is model-caused). When not to use: if the incident is not model-caused, or if a simple rollback suffices. Failure modes: break-glass abuse (detected by audit log anomaly), gate bypass due to a misconfigured webhook (detected by missing token), TTL expiry during an ongoing incident (detected by alert). Concrete failure: if the smoke test only checks 100 requests, a rare failure mode (e.g., 1 in 10,000) may slip through; detect by canary error rate.

Artefacts:

GateThresholdAction on fail
LineageAll required fields presentBlock
Smoke test100 requests, no PII, p99 < 200 msBlock
Canary error rate> 0.5% over 5 minAuto-rollback
Business KPIDrop > 2% vs baselineAuto-rollback
TTL4 hoursAuto-revert

Trace: Incident INC-1234 declared. Engineer requests break-glass. Registry checks lineage: pass. Runs smoke test: pass. Issues token: max traffic 5%, expiry 4h. Serving layer applies to 5% of 10,000 QPS = 500 QPS. Monitor sees error rate 0.8% (4 errors/sec) > 0.5% (2.5 errors/sec). Auto-rollback in 90 seconds. Incident ticket updated.

Arithmetic: 5% of 10,000 QPS = 500 QPS. 0.5% error threshold = 2.5 errors/sec. Observed 4 errors/sec = 0.8% > 0.5%, so rollback.

What would change the decision: if the incident is a security vulnerability, you might skip canary and go to 100% with a hotfix, but then you need a security review within 1 hour. If the model is not the cause, don't use this path.

Curated: · Written: · Reviewed:

Difficulty: Hard