Debugging and Testing ML Systems Questions
Finding, diagnosing, and fixing problems in ML code, data, and models, and building tests that catch these problems before they reach users. Covers common ML pitfalls (data leakage, shape mismatches, silent training bugs, mis-specified loss or metrics), root-cause analysis of model regressions and production incidents (accuracy drops, calibration drift, intermittent or hard-to-reproduce failures), distributed-training-specific failures (multi-GPU divergence, intermittent OOM, precision-related instability), and the diagnostic tooling that supports it (reproducibility artifacts, structured logging, instrumentation). Also covers testing ML systems directly: unit tests for data and feature pipelines, validation checks for datasets and features, test oracles and acceptance criteria for probabilistic or non-deterministic model outputs, and integration and regression tests that catch model or pipeline regressions before deployment. Emphasizes the engineering rigor that keeps ML systems correct and maintainable.
During code review you find a pull request that caches computed features without any invalidation logic, risking stale predictions being served. How do you evaluate the safety of this change, what tests and mitigations would you require before approving it, and how would you communicate your concerns to the author and the product owner? Sketch a short, concrete PR review comment you would leave.
Sample Answer
Direct answer
A feature cache with no invalidation logic is not a performance optimization with a minor rough edge, it is a correctness bug that will serve stale predictions for as long as the cached value's underlying source can change without the cache noticing, which for most real feature sources is constantly. I would not approve this pull request (PR) as written; I would evaluate it by asking one question, "under what conditions does this cache's value stop matching the true current value of the feature, and how long can that mismatch last," and require a concrete answer plus a test proving the answer, before approving.
Structured elaboration
Evaluating the safety of the change. Three questions determine how dangerous the missing invalidation actually is:
- How often does the underlying feature actually change? A cached value for a feature that is truly immutable (a user's signup country, say) needs no invalidation at all; the risk is proportional to how mutable the cached thing really is, not to the mere presence of a cache.
- What is the blast radius of a stale value? A stale low-stakes UI hint is a different risk than a stale value feeding a pricing or fraud decision. The review should ask what the model does with this specific feature, not evaluate the cache in the abstract.
- Is there any bound on staleness at all, even an implicit one? No time-to-live (TTL) and no explicit invalidation call means the bound is unbounded: a value cached once can live forever, surviving the underlying record's entire subsequent lifetime.
Tests and mitigations required before approving.
- A regression test that updates the underlying source after a value is cached and asserts the cache reflects the update, not the stale value, the same shape as the worked example below. Its absence is itself a review finding: a caching PR with no test for the not-stale case has not demonstrated the cache is safe, only that it is fast.
- A concrete invalidation mechanism, not "we'll add it later": either a hard TTL (bounds staleness to a known window, works even when the write path forgets to signal a change) or an explicit version/watermark bump on every write to the source (correct immediately, but only as reliable as every write path remembering to bump it) or, ideally, both together, the version bump for the common case and the TTL as a backstop for the write paths nobody remembered.
- A monitoring signal for cache age or staleness rate in production, since a cache bug that only appears at scale or after enough time has passed is exactly the kind of thing that will not show up in a small PR-time test.
Communicating the concern to the author and the product owner. These are two different conversations because they need different information:
- To the author, be specific and solution-oriented in the code review itself: name the exact scenario that breaks (a user's tier changes, the cache does not know), point at the missing mechanism (no TTL, no invalidation hook), and propose the concrete fix rather than only flagging the absence of one. A vague "this needs invalidation" comment produces a vague follow-up PR; a comment naming the failure mode produces a fix that actually closes it.
- To the product owner, frame it in terms of impact and decision, not implementation: what decision or user-facing outcome could be wrong, for how long, and what is the concrete cost of adding a TTL (a small, boundable increase in cache-miss rate and recomputation cost) versus the cost of shipping stale predictions. This is a trade-off the product owner should get to weigh in on if the blast radius is real, not something the reviewer decides alone.
Worked example
The code under review, an "unsafe" cache with no invalidation path at all:
class UnsafeFeatureCache:
def __init__(self, compute_fn):
self._compute_fn = compute_fn
self._store = {}
def get(self, key):
if key not in self._store:
self._store[key] = self._compute_fn(key)
return self._store[key]
Demonstrating the actual failure, a user's account tier changes after it is first cached:
upstream_source = {"user_42": "free"}
compute_calls = []
def compute_feature(user_id):
compute_calls.append(user_id)
return upstream_source[user_id]
unsafe = UnsafeFeatureCache(compute_feature)
before = unsafe.get("user_42")
upstream_source["user_42"] = "paid" # the user upgrades
after = unsafe.get("user_42")
print(f"before upgrade: {before}")
print(f"upstream now says: {upstream_source['user_42']}")
print(f"cache still returns (STALE): {after}")
print(f"prediction served with wrong tier: {after != upstream_source['user_42']}")
Output:
before upgrade: free
upstream now says: paid
cache still returns (STALE): free
prediction served with wrong tier: True
The requested fix, a version-keyed cache with a TTL as backstop, so a write-path version bump invalidates immediately and a hard TTL catches any write path that forgets to bump it:
import time
class VersionedFeatureCache:
def __init__(self, compute_fn, ttl_seconds=300):
self._compute_fn = compute_fn
self._ttl = ttl_seconds
self._store = {} # (key, version) -> (value, cached_at)
def get(self, key, source_version):
cache_key = (key, source_version)
entry = self._store.get(cache_key)
now = time.monotonic()
if entry is not None and (now - entry[1]) < self._ttl:
return entry[0]
value = self._compute_fn(key)
self._store[cache_key] = (value, now)
return value
The same scenario against the fixed version, where the write path bumps source_version on every upstream change. The compute_calls counter is there deliberately: a "cache" that simply recomputed every time would also return the correct value after the upgrade, so the demonstration has to prove a cache HIT happens as well as proving the invalidation works, or it is not testing the cache at all. The last two lines exercise the TTL backstop on its own, at an unchanged version, so both invalidation paths are shown firing rather than just described:
upstream_source["user_42"] = "free"
compute_calls.clear()
fixed = VersionedFeatureCache(compute_feature, ttl_seconds=300)
before_v = fixed.get("user_42", source_version=1)
repeat_v = fixed.get("user_42", source_version=1) # same version: must be a HIT
hits_so_far = 2 - len(compute_calls)
upstream_source["user_42"] = "paid" # the user upgrades
after_v = fixed.get("user_42", source_version=2) # bumped version: must be a MISS
expired = VersionedFeatureCache(compute_feature, ttl_seconds=0)
expired.get("user_42", source_version=2)
n_before = len(compute_calls)
expired.get("user_42", source_version=2) # same version, but the TTL backstop fires
ttl_forced_recompute = len(compute_calls) > n_before
print(f"before upgrade (version=1): {before_v}")
print(f"second read at version=1 served from cache, no recompute: {hits_so_far == 1}")
print(f"upstream now says: {upstream_source['user_42']}")
print(f"after upgrade (version=2): {after_v}")
print(f"cache correctly reflects the update: {after_v == upstream_source['user_42']}")
print(f"TTL backstop alone forces a recompute at an unchanged version: {ttl_forced_recompute}")
Output:
before upgrade (version=1): free
second read at version=1 served from cache, no recompute: True
upstream now says: paid
after upgrade (version=2): paid
cache correctly reflects the update: True
TTL backstop alone forces a recompute at an unchanged version: True
The PR review comment I would leave:
This cache has no invalidation path: once a value is stored for a key, it lives forever, even after the underlying feature changes (I checked, a user tier change after caching still returns the pre-change value indefinitely). Given this feeds [the pricing/eligibility decision], that is a correctness bug, not a performance trade-off. Before I can approve: (1) key the cache on a source version so a write bumps it and invalidates automatically, with a TTL as a backstop for write paths that don't; (2) add a test that updates the source after caching and asserts the cache reflects the update; (3) let's loop in [product owner] on the acceptable staleness window, since that's a product call, not an engineering one. Happy to pair on the version-bump plumbing if that's the blocker.
Trade-offs and pitfalls
- A pure TTL without a version bump trades correctness for simplicity, and vice versa. A TTL alone is correct only up to the TTL window; a version bump alone is correct immediately but only as reliable as every write path remembering to call it. In a codebase with multiple write paths (a batch job and an online update, say), relying on version bumps alone is fragile precisely because it is easy for a new write path to forget.
- The most common reviewer mistake here is accepting "we'll add invalidation in a follow-up." A cache PR without invalidation is not a partial win that can ship now and be completed later; until invalidation exists, the cache is actively wrong some fraction of the time, and shipping it starts that clock immediately.
- Do not conflate "this is now correct" with "this is now cheap." Adding a TTL and a version check increases cache-miss rate and recomputation cost relative to the unsafe version; that cost is the actual trade-off worth surfacing to the product owner, not a reason to skip the fix.
- Watch for a cache invalidated on read instead of on write. A tempting shortcut is to check staleness lazily only when a value happens to be read again; if a stale entry is never read again after the underlying value changes, it can still be read once more downstream (a batch scoring job, an audit query) before it would ever get refreshed, so invalidation needs to be tied to the write, not deferred entirely to the next read.
Describe a safe strategy for managing feature-schema migrations in a production ML system, so a new schema version can roll out without breaking either model serving or training. Include how you would version schemas, how you would write and test transformation functions between versions, and what contract tests would give you confidence the migration didn't silently change any feature's meaning.
Sample Answer
Direct answer
Roll out a feature-schema migration the same way you would roll out any breaking API change: version the schema explicitly, write an explicit transformation function between the old and new version rather than mutating the field in place, and gate the migration behind a contract test that proves the transform preserves the feature's actual meaning, not just its type. Serve both schema versions side by side during a transition window (old readers get the old shape, new readers get the new shape, both backed by the same underlying data) so training and serving never briefly disagree about which version is current.
Structured elaboration
Versioning the schema. Attach an explicit version identifier to the schema itself (a schema_version field on the record, or a versioned table/topic name), never rely on "whatever the code currently produces" as the implicit definition of the current schema. Every consumer, the training pipeline and the serving pipeline alike, should read the version explicitly and know which transformation, if any, it needs to apply, rather than assuming the shape it happens to receive matches what it expects.
Writing and testing transformation functions between versions. Write one pure, explicit function per version transition (v1_to_v2, not a general-purpose "migrate to latest" that tries to handle every version pair at once), so each transform is small enough to reason about and test in isolation. Test it two ways: with concrete example-based unit tests on a handful of known records, and with a property-based test (using a library such as Hypothesis) asserting an invariant that must hold for every valid input, not just the examples you happened to write by hand. The property-based layer is what catches the transform being correct on your fixtures but wrong in general.
Contract tests that catch a silent meaning change. The specific risk this question names, a migration that changes what a feature means without anyone noticing, needs a test built around a round-trip or an equivalence invariant, not just a type check. A type check confirms the output is a float; it says nothing about whether that float still represents the same underlying quantity. A round-trip contract test converts the migrated value back to the old representation and asserts it reconstructs the original exactly (up to the precision the two representations can express), which catches a transform that is well-typed but computes the wrong thing, for example applying the wrong unit conversion.
Worked example
A concrete migration: a price_cents integer field (v1) becomes a price_dollars float field (v2).
def transform_v1_to_v2(record_v1: dict) -> dict:
return {
"user_id": record_v1["user_id"],
"price_dollars": record_v1["price_cents"] / 100.0,
}
def contract_test_price_preserved(v1_record: dict, transform) -> bool:
'''Contract: the migrated value, converted back to cents and rounded,
must equal the original v1 value.'''
v2 = transform(v1_record)
reconstructed_cents = round(v2["price_dollars"] * 100)
return reconstructed_cents == v1_record["price_cents"]
A plausible but wrong migration, included specifically to show what the contract test is catching, forgets the unit conversion:
def BUGGY_transform_v1_to_v2(record_v1: dict) -> dict:
return {
"user_id": record_v1["user_id"],
"price_dollars": float(record_v1["price_cents"]), # missing the /100
}
On one concrete record:
sample = {"user_id": "u1", "price_cents": 2599}
print(contract_test_price_preserved(sample, transform_v1_to_v2)) # True
print(contract_test_price_preserved(sample, BUGGY_transform_v1_to_v2)) # False
print(transform_v1_to_v2(sample)) # {'user_id': 'u1', 'price_dollars': 25.99}
print(BUGGY_transform_v1_to_v2(sample)) # {'user_id': 'u1', 'price_dollars': 2599.0}
The buggy output is off by a factor of 100, silently, no exception, no type error, exactly the class of "meaning changed, shape didn't" bug the contract test exists to catch.
The property-based version of the same contract, checking the invariant for every valid price_cents value, not just the one example above, using Hypothesis:
from hypothesis import given, strategies as st
@given(st.integers(min_value=0, max_value=10_000_000))
def check_correct_transform_always_round_trips(price_cents):
record = {"user_id": "u", "price_cents": price_cents}
assert contract_test_price_preserved(record, transform_v1_to_v2), \
f"round-trip failed for price_cents={price_cents}"
Running both the correct and buggy transforms through this property test:
correct transform: round-trips for all generated integer cent values (no counterexample found)
buggy transform: correctly REJECTED by the contract test on first counterexample: round-trip failed for price_cents=1
The correct transform survives Hypothesis's generated inputs with no counterexample; the buggy one fails immediately, on the smallest possible input Hypothesis could find (price_cents=1), which is Hypothesis's shrinking behavior working as intended, it always reports the minimal failing case rather than whatever random large value it happened to try first.
Trade-offs and pitfalls
- A round-trip invariant is not available for every migration. The price example above has a natural inverse (dollars back to cents); a migration that genuinely discards information (rounding a precise timestamp down to a date, say) has no exact round-trip to check. For those, the contract test needs a different invariant. an approximate-equality bound, or a check that the discarded information was intentionally out of scope, stated and reviewed explicitly, not silently assumed safe.
- Testing the transform function in isolation does not prove training and serving agree during the transition window. Both pipelines need to apply the identical transform, ideally the same shared code path, not two independently written implementations that happen to agree on your test fixtures; a genuinely shared library function closes this gap, two parallel reimplementations do not.
- Versioning the schema is only useful if every consumer actually checks the version rather than assuming it. A consumer that silently accepts whatever shape arrives, without verifying the version field, reintroduces the exact risk the whole scheme exists to prevent, the first time an unexpected version shows up.
- The transition window itself is a real operational cost, not a formality. Serving both schema versions simultaneously means running (and monitoring, and eventually decommissioning) two code paths at once; keep the window as short as the migration's risk tolerance allows, and have an explicit, dated plan for removing the old path, or "temporary" dual-serving quietly becomes permanent.
Write a Python-based smoke-test harness for an inference service that validates: (1) deterministic responses for a fixed set of seeded inputs, (2) response time under a threshold, and (3) memory usage within a limit. Describe the specific checks your harness makes and provide a simple example you would run as part of continuous integration before every deploy.
Sample Answer
Direct answer
A smoke-test harness for an inference service runs three independent checks against a small, fixed set of seeded inputs every time before a deploy is allowed to proceed: the service returns byte-identical output for the same input across repeated calls, each call's response time stays under a fixed latency threshold, and the process's memory usage stays within a fixed limit (a ceiling on growth) over the run. Any one check failing blocks the deploy; the harness exits non-zero and the continuous integration (CI, the automated system that runs checks on every code change) pipeline treats that as a hard gate, not a warning.
Structured elaboration
The three checks, and why each one matters. Determinism catches the class of bug where a model's forward pass has picked up hidden nondeterminism, an unseeded random call, a race in batched inference, a floating-point reduction that depends on thread scheduling, which silently breaks anything downstream that assumes the same input always yields the same prediction (reproducible debugging, fair A/B comparisons, cache-ability). Latency, the service's response time per call, catches a regression that would otherwise only surface once real traffic hits the new deploy, when it is far more expensive to roll back. Memory catches a leak that would not show up in a single request but accumulates over the service's uptime until it gets killed out-of-memory (OOM) under sustained load, a failure mode a single quick manual check would never see.
What the harness actually does. A fixed list of seeded input payloads (not randomly regenerated per run, so results are comparable run over run) is scored twice per input for the determinism check, and timed on every call for the latency check. Memory is measured once for the whole run rather than per call, since a leak is a cumulative effect across many calls, not a property of any single one; the harness reads the process's resident memory (RSS, the resident set size, meaning the physical memory the process currently holds) before the run starts and after it ends, and asserts the growth stays within a fixed memory limit (a ceiling on how much it is allowed to grow).
Complexity. For n seeded inputs, the harness makes 2n prediction calls for the determinism check plus n more for the latency check, so 3n calls total, linear in the number of seeded inputs; memory is checked with two fixed-cost reads regardless of n. This is intentionally cheap: a smoke test that takes as long as the full model-quality evaluation suite defeats the purpose of a fast pre-deploy gate.
Edge cases the harness has to account for. A cold first call can be genuinely slower than steady-state calls (model loading, just-in-time compilation, cache warmup), so a real harness issues one untimed warmup call per input before the timed pass, otherwise the very first seeded input looks like a false latency failure every single run. A model that is intentionally stochastic (temperature-based sampling, dropout left on at inference time by mistake) needs its own sampling seed pinned inside the request payload or the service's inference call, not just the harness's own random state, since the harness's determinism check has no way to distinguish "the service is broken" from "the service is doing exactly what it was asked to do, non-deterministically" without that. Seeded inputs also need to be realistically sized, not trivially small, since a harness that only ever times a nearly-empty payload will never catch a latency regression that only appears on production-sized requests.
Wiring it into CI. The script below is written to be called directly as a CI step (python3 smoke_test.py, or invoked as a pytest module); its process exit code is what actually gates the deploy, not a human reading its printed output. Pointing it at a real deployed service instead of an in-process mock is a one-line change: replace the mock model's predict call with requests.post(ENDPOINT, json=input, timeout=...).json(), timed and checked exactly the same way, everything else in the harness is unchanged.
Worked example
"""
Smoke-test harness for an inference service, run as a CI gate before every deploy.
Three checks, each independent and each producing a clear pass/fail line:
1. Determinism: the same seeded input produces byte-identical output across repeated calls.
2. Latency: each call completes under a fixed threshold.
3. Memory: process resident memory does not grow past a fixed ceiling across the run.
The "inference service" here is an in-process stand-in with the same predict(input) -> dict
contract a real deployed model would expose over HTTP; swapping MODEL.predict for a
requests.post(ENDPOINT, json=input).json() call is the only change needed to point this at a
real running service. Everything else (seeds, thresholds, assertions) is unchanged.
"""
import random
import time
import sys
import psutil # third-party: pip install psutil
import os
LATENCY_THRESHOLD_S = 0.15 # 150 ms per-call budget for this smoke test
MEMORY_CEILING_MB = 50 # RSS growth budget across the whole smoke-test run
SEEDED_INPUTS = [
{"id": i, "features": [((i * 37 + j * 13) % 97) / 97 for j in range(8)]}
for i in range(10)
]
_LEAK_SINK = [] # only the "broken" model writes here; simulates an accidental global cache
class GoodModel:
"""A deterministic, well-behaved mock model."""
def predict(self, x):
s = sum(f * (idx + 1) for idx, f in enumerate(x["features"]))
time.sleep(0.02) # pinned synthetic inference delay, well under threshold
return {"id": x["id"], "score": round(s, 6)}
class BrokenModel:
"""A mock model with three injected defects: non-deterministic output (unseeded
randomness in the forward pass), a latency regression, and a memory leak."""
def predict(self, x):
s = sum(f * (idx + 1) for idx, f in enumerate(x["features"]))
s += random.random() * 0.001 # defect 1: unseeded noise breaks determinism
time.sleep(0.30) # defect 2: pinned synthetic delay over threshold
_LEAK_SINK.append(bytearray(2_000_000)) # defect 3: ~2 MB retained per call, never freed
return {"id": x["id"], "score": round(s, 6)}
def run_smoke_test(model, label):
print(f"\n=== smoke test: {label} ===")
proc = psutil.Process(os.getpid())
rss_start_mb = proc.memory_info().rss / (1024 * 1024)
# 1. Determinism: call twice per seeded input, compare exactly.
determinism_failures = []
for inp in SEEDED_INPUTS:
out1 = model.predict(inp)
out2 = model.predict(inp)
if out1 != out2:
determinism_failures.append((inp["id"], out1, out2))
det_pass = len(determinism_failures) == 0
print(f"[determinism] {'PASS' if det_pass else 'FAIL'} "
f"({len(determinism_failures)}/{len(SEEDED_INPUTS)} inputs mismatched)")
for fid, o1, o2 in determinism_failures[:3]:
print(f" input {fid}: {o1} != {o2}")
# 2. Latency: time each call, assert under threshold.
latencies = []
for inp in SEEDED_INPUTS:
t0 = time.perf_counter()
model.predict(inp)
latencies.append(time.perf_counter() - t0)
max_latency = max(latencies)
lat_pass = max_latency < LATENCY_THRESHOLD_S
print(f"[latency] {'PASS' if lat_pass else 'FAIL'} "
f"(max={max_latency*1000:.1f} ms, threshold={LATENCY_THRESHOLD_S*1000:.0f} ms)")
# 3. Memory: RSS growth across the whole run.
rss_end_mb = proc.memory_info().rss / (1024 * 1024)
rss_growth_mb = rss_end_mb - rss_start_mb
mem_pass = rss_growth_mb < MEMORY_CEILING_MB
print(f"[memory] {'PASS' if mem_pass else 'FAIL'} "
f"(rss_growth={rss_growth_mb:.1f} MB, ceiling={MEMORY_CEILING_MB} MB)")
overall = det_pass and lat_pass and mem_pass
print(f"RESULT: {'PASS' if overall else 'FAIL'} for {label}")
return overall
if __name__ == "__main__":
random.seed(87) # seeds the process RNG; GoodModel never touches it, BrokenModel does
good_ok = run_smoke_test(GoodModel(), "GoodModel (expected PASS)")
_LEAK_SINK.clear()
broken_ok = run_smoke_test(BrokenModel(), "BrokenModel (expected FAIL)")
print("\n=== summary ===")
print(f"GoodModel passed all checks: {good_ok}")
print(f"BrokenModel passed all checks: {broken_ok}")
# The exit code, not the printed text, is what gates the deploy. It is echoed
# here only so the line below is visible in this transcript.
exit_code = 0 if (good_ok and not broken_ok) else 1
print(f"EXIT CODE: {exit_code}")
sys.exit(exit_code)
Actual output from running this script (python3 smoke_test.py). Every value below is exactly reproducible except the two wall-clock latency figures, which move by a few tenths of a millisecond between runs because they measure real elapsed time:
=== smoke test: GoodModel (expected PASS) ===
[determinism] PASS (0/10 inputs mismatched)
[latency] PASS (max=30.0 ms, threshold=150 ms)
[memory] PASS (rss_growth=0.0 MB, ceiling=50 MB)
RESULT: PASS for GoodModel (expected PASS)
=== smoke test: BrokenModel (expected FAIL) ===
[determinism] FAIL (10/10 inputs mismatched)
input 0: {'id': 0, 'score': 22.51561} != {'id': 0, 'score': 22.515653}
input 1: {'id': 1, 'score': 15.248262} != {'id': 1, 'score': 15.247963}
input 2: {'id': 2, 'score': 16.979662} != {'id': 2, 'score': 16.979717}
[latency] FAIL (max=310.4 ms, threshold=150 ms)
[memory] FAIL (rss_growth=57.8 MB, ceiling=50 MB)
RESULT: FAIL for BrokenModel (expected FAIL)
=== summary ===
GoodModel passed all checks: True
BrokenModel passed all checks: False
EXIT CODE: 0
The run against GoodModel clears all three checks, and the run against BrokenModel, which has all three defects deliberately injected, fails all three, with the determinism failures printed individually so a reading engineer sees which exact input diverged and by how much. That the harness produces genuinely different output for a genuinely broken service, not the same PASS regardless of what it is pointed at, is what makes it a real gate rather than a check that would rubber-stamp anything. (The bottom driver here runs both models to prove the harness discriminates; a real CI step calls run_smoke_test once, against the actual candidate deploy, and uses only its return value to set the process exit code.)
Trade-offs and pitfalls
- An in-process check is not the same test as a real deploy gate. This example calls
model.predictdirectly to stay self-contained; a production version should call the actual serving endpoint over the network, since network and serialization overhead are exactly the kind of thing a latency smoke test exists to catch, and an in-process check that skips them can pass while the real endpoint fails. - Thresholds are environment-specific. A latency threshold calibrated against a developer laptop will be wrong for the CI runner's actual hardware and wrong again for production hardware; calibrate the threshold against the CI runner itself, and treat it as a regression gate (did this change make it slower than before) more than an absolute performance claim.
- A single-sample memory reading is noisy. Python's own garbage collector and unrelated background activity can shift RSS by a few megabytes between runs; a stricter version of this check would force a
gc.collect()immediately before each RSS read and average over a couple of repetitions rather than trusting one sample, to avoid a flaky false failure blocking a genuinely fine deploy. - The most common way this kind of harness fails in practice is not a bug in the harness, it is nobody wiring its exit code to actually block the deploy. A smoke test that only prints results to a log nobody reads before merging provides none of the protection it was built for; the exit code has to be a hard CI gate, not a dashboard.
A subtle off-by-one shift in feature timestamps affected a small fraction of users (well under 1%) and degraded downstream metrics in a way that existing tests didn't catch. Describe a thorough root-cause investigation plan to find a bug this narrow, propose detection rules that would have caught it earlier, and outline automated checks you would add to the feature-store and backfill process to prevent a recurrence of this specific class of bug.
Sample Answer
Direct answer
A bug this narrow (well under 1 percent of users) survived existing tests precisely because it is narrow: aggregate metrics and typical spot-checks are built to catch large, obvious shifts, and an off-by-one timestamp shift affecting a small slice moves the aggregate by an amount easily lost in ordinary day-to-day noise. Finding it requires narrowing from "downstream metrics look slightly off" down to the specific affected cohort using a boundary-checkpoint search through the pipeline, then, separately, building detection that specifically targets narrow-slice anomalies rather than only aggregate drift, since that is exactly the class of check that was missing.
Structured elaboration
Root-cause investigation plan for a bug this narrow. Aggregate statistics will not localize this; you need to find the affected rows first and reason from them backward.
- Isolate the affected slice. Since you know downstream metrics degraded, work backward from the symptom to identify which specific users or records are behaving anomalously, using whatever ground-truth or downstream signal is available (a business outcome that should correlate with the feature but does not, for the affected group).
- Once you have even a handful of confirmed-affected examples, add temporary checksums or stage tags at each boundary of the pipeline (raw ingestion, parsing, enrichment, feature-store write) for those specific records, and re-run them through the pipeline with verbose logging. The first stage where the affected records' timestamp diverges from a manually-verified-correct value is where the bug lives.
- At that stage, look specifically for the classic off-by-one shapes: an inclusive-versus-exclusive range boundary, a timezone conversion applied to an already-converted value (double conversion) or not applied at all, daylight-saving-time transition handling, a truncation or rounding operation (floor instead of round, or vice versa) at a unit boundary, or an integer-division truncation on a timestamp arithmetic expression.
- Check what changed around the time the bug's effects began: a deployment, a config change, a library upgrade, or a schema change to an upstream source, since a subtle bug like this usually has an identifiable introduction point rather than having always been present.
- Once you have a hypothesis, write a minimal, deterministic test that reproduces the shift on the specific boundary condition (for example, an event timestamp exactly at a daylight-saving-time transition, or exactly at midnight) and confirm the fix resolves it there before rolling out broadly.
Detection rules that would have caught it earlier. The unifying idea is: build a check whose false-positive rate under NORMAL operation is low enough that even a small number of genuinely anomalous rows stands out clearly, rather than only building checks that look at aggregate distribution moments.
- A per-record invariant check: the computed feature timestamp should fall within a defined, small allowed skew of the source event timestamp (for example, no more than a few seconds for near-real-time features). Count and alert on the RAW NUMBER and rate of rows violating this invariant, not just an aggregate statistic about the whole column, since a rate-based alert with too loose a threshold is exactly what would miss a "well under 1 percent" bug.
- A percentile-drift alert on the distribution of (feature timestamp minus event timestamp), watching the tail percentiles specifically (95th, 99th), not just the mean, since a narrow-slice bug can leave the mean nearly unchanged while still producing a detectable tail.
- A boundary-specific canary: since off-by-one bugs concentrate at boundaries (day changes, daylight-saving-time transitions, timezone-offset edges), a synthetic test record deliberately placed at each such boundary, run through the live pipeline on a schedule, with an assertion on its expected output, catches this class of bug independent of real traffic volume at all.
Automated checks for the feature-store and backfill process to prevent recurrence of this specific class of bug.
- A pre-write validator on the feature store that enforces the same per-record timestamp-skew invariant described above at write time, rejecting or quarantining (routing to a separate location for review rather than silently dropping) any row that violates it, with detailed logging of which record and which invariant failed.
- Property-based testing (generating a wide range of timestamp inputs, including boundary values, rather than a small fixed set of examples) specifically for any timestamp-transformation function, asserting the skew invariant holds across the generated inputs, not just a handful of hand-picked ones.
- For backfills specifically: a mandatory dry-run mode that computes a diff report (row counts, a sample of before-and-after timestamp deltas, and the invariant-violation rate) before any backfill writes are committed, plus a rate limit requiring human sign-off when the diff shows more than a small threshold of rows changing timestamps unexpectedly.
- Continuous integration checks: run a small, representative synthetic dataset covering the boundary cases above through the pipeline on every change to timestamp-handling or timezone-related code, and fail the build if the skew invariant is violated on any of them.
Worked example
Suppose the affected fraction is confirmed at roughly 0.3 percent of daily events. On a pipeline processing 2,000,000 events per day, that is 0.003×2,000,000=6,000 affected rows per day, a small fraction of traffic but a large absolute count. If the per-record timestamp-skew invariant check described above had been running, with a normal-operation baseline violation rate close to zero (say, under 0.01 percent from ordinary transient issues), the rule would have two arms rather than one: alert if violations exceed 0.05 percent of daily volume OR exceed 500 rows in a day, whichever fires first. On this incident both arms fire and neither is close: 6,000 violating rows out of 2,000,000 is 0.3 percent, six times the rate arm (0.05 percent of this volume is 1,000 rows) and twelve times the 500-row absolute floor, well before the bug accumulated enough downstream impact to show up as a business-metric degradation.
The absolute arm is not decoration, and the way to see it is a milder variant of the same defect: suppose the off-by-one had only caught records at one specific timezone offset, 0.04 percent of that same 2,000,000-row day. That is 800 rows a day silently corrupted. The rate arm stays quiet, because 0.04 percent is under the 0.05 percent threshold, while the absolute floor fires at 800 against 500. A percentage-only threshold, tuned loose enough not to be noisy on ordinary days, is exactly what lets that variant run indefinitely, and it is why the summary below says a two-armed threshold rather than a rate.
This is the concrete case for why a per-record invariant with a low, two-armed (rate and absolute-count) threshold catches what an aggregate mean-based check misses: the mean of (feature timestamp minus event timestamp) across all 2,000,000 rows, dominated by the 99.7 percent of unaffected rows, would move by only a small fraction of the shift actually experienced by the affected 0.3 percent, easily within normal day-to-day noise for a mean-based alert.
Trade-offs and pitfalls
The most common wrong turn is setting invariant-check alert thresholds as a PERCENTAGE only, without also considering absolute row counts. On a high-volume pipeline, a percentage threshold tuned to avoid noisy false alarms on a low-volume day can silently allow a large absolute number of affected rows to pass on a high-volume day. Alert on both the rate and the absolute count, and use whichever fires first.
A second pitfall is quarantining violating rows without a clear, monitored release path. A pre-write validator that silently drops bad rows can itself become a hidden source of data loss (real, if imperfect, feature data quietly disappearing) that is just as hard to detect as the original bug; route quarantined rows somewhere visible, with metrics on quarantine volume, so a spike in quarantining is itself a signal rather than a silent sink.
A third pitfall in the backfill dry-run process specifically: a diff report that only checks the count of rows changed, without sampling actual before-and-after values, will not catch this exact bug, since an off-by-one timestamp shift changes every affected row's VALUE but does not necessarily change the total ROW COUNT. Make sure the dry-run diff includes a value-level sample comparison, not just row-count and schema checks, or the safeguard specifically built for this incident would not have caught it either.
A deployed ML model interacts closely with a downstream business rule engine, and a change to the rules recently caused a user-visible regression even though the model itself didn't change. How would you design contract tests and integration tests between the model and the rule engine, and what deployment gating would you add so a future rule change can't cause the same kind of regression again?
Sample Answer
Direct answer
The regression happened because the model and the rule engine share an implicit contract, what the model's output means and how the rule engine is supposed to interpret it, and nothing tested that contract directly; each side's own test suite only tested itself in isolation. The fix is a contract test that pins the expected end-to-end decision distribution the rule engine produces from a fixed, frozen sample of model outputs, an integration test that exercises the two systems wired together rather than either one alone, and a deployment gate that runs this contract test automatically on every change to the rule engine, not just changes to the model.
Structured elaboration
Why unit-testing each side alone was not enough. The model's own test suite verifies the model produces sensible scores; the rule engine's own test suite verifies it correctly implements its threshold logic given a score. Neither one asks the actual question that broke: "given the score distribution my model actually produces, does a change to the rule engine's thresholds change the resulting decisions in a way anyone intended?" That question only exists at the seam between the two systems, so it needs a test that lives at the seam, not inside either system's own suite.
Contract tests: pin the interface's meaning, not just its shape. A contract test for this boundary should assert two different things, and both matter:
- Shape/type contract: the model always emits a float in [0, 1], the rule engine always accepts exactly that range and always returns one of a known, enumerated set of decision labels. This catches an obvious breaking change (the model starts emitting scores outside [0, 1], or the rule engine adds a new decision label the model-facing dashboard does not know how to render) but does not catch the actual incident described here, since neither side's shape changed.
- Behavioral/golden-master contract: freeze a representative sample of model outputs once, and pin the expected decision distribution the rule engine currently produces from that fixed sample. Any future change, to either side, that shifts the resulting decision distribution beyond a tolerance fails the test, whether the change came from the model or the rule engine. This is the check that actually catches the incident: a threshold change in the rule engine alone is enough to fail it, with no change to the model required.
Integration tests: the two systems wired together, not mocked. Run the real rule-engine code path against real (or realistically sampled) model outputs in CI (continuous integration, the automated pipeline that runs checks on every proposed change), rather than each side testing against a hand-written stub of the other. A stub of the rule engine that a model-side test maintains tends to reflect what the model team believes the rule engine does, which is exactly the assumption that silently went stale here.
Deployment gating so it cannot happen again. Two changes close the gap: run the contract test automatically on every pull request that touches the rule engine, not only on model changes (the rule engine team likely has no visibility into "this affects a model contract" without an explicit gate telling them so), and stage the rule-engine change behind a canary that compares the live decision distribution against the pre-change baseline before full rollout, with an automatic block if the divergence between the two exceeds a threshold, the same discipline a model deployment would use for a metric regression, applied here to a non-model system that happens to sit downstream of one.
Worked example
A contract test using total variation distance (a simple, interpretable measure of how far apart two categorical distributions are, ranging from 0 for identical distributions to 1 for no overlap at all) between the frozen golden-master decision distribution and the distribution a candidate rule engine produces on the same frozen input sample:
import numpy as np
rng = np.random.default_rng(seed=5)
reference_scores = rng.beta(2, 2, size=5000) # frozen model-output sample, fixed once
def rule_engine_v1(score):
if score < 0.3: return "no_discount"
elif score < 0.7: return "small_discount"
else: return "large_discount"
def rule_engine_v2(score):
# the PR under review: raises the large_discount cutoff from 0.7 to 0.85
if score < 0.3: return "no_discount"
elif score < 0.85: return "small_discount"
else: return "large_discount"
def decision_distribution(scores, rule_engine):
decisions = [rule_engine(s) for s in scores]
# sorted(), not set(), because set iteration order for strings depends on the
# per-process hash seed: without this the printed distribution changes between
# runs, which is not a property you want in a golden-master test's output.
return {d: decisions.count(d) / len(decisions) for d in sorted(set(decisions))}
def total_variation_distance(dist_a, dist_b):
keys = set(dist_a) | set(dist_b)
return 0.5 * sum(abs(dist_a.get(k, 0.0) - dist_b.get(k, 0.0)) for k in keys)
# The golden master is CAPTURED by running the current rule engine, not hand-typed.
GOLDEN_MASTER = decision_distribution(reference_scores, rule_engine_v1)
CONTRACT_TOLERANCE = 0.02
def contract_test(rule_engine, label):
dist = decision_distribution(reference_scores, rule_engine)
tvd = total_variation_distance(GOLDEN_MASTER, dist)
verdict = "PASS" if tvd <= CONTRACT_TOLERANCE else "FAIL"
print(f"{label}:")
print(f" distribution: {dist}")
print(f" total variation distance from golden master = {tvd:.4f} -> {verdict}")
return verdict
print("Golden master, captured by running rule_engine_v1 against the frozen reference sample:")
print(GOLDEN_MASTER)
print()
contract_test(rule_engine_v1, "rule_engine_v1 (unchanged, sanity check)")
contract_test(rule_engine_v2, "rule_engine_v2 (PR under review)")
Running it, with the golden master captured from rule_engine_v1 as a sanity check, then evaluated against rule_engine_v2, the PR under review:
Golden master, captured by running rule_engine_v1 against the frozen reference sample:
{'large_discount': 0.217, 'no_discount': 0.2152, 'small_discount': 0.5678}
rule_engine_v1 (unchanged, sanity check):
distribution: {'large_discount': 0.217, 'no_discount': 0.2152, 'small_discount': 0.5678}
total variation distance from golden master = 0.0000 -> PASS
rule_engine_v2 (PR under review):
distribution: {'large_discount': 0.0652, 'no_discount': 0.2152, 'small_discount': 0.7196}
total variation distance from golden master = 0.1518 -> FAIL
The sanity check confirms the test is measuring something real, an unchanged rule engine trivially matches its own golden master exactly, so a FAIL on the second arm cannot be explained by the harness failing everything. The PR under review moves large_discount from 21.7% of decisions to 6.5% of decisions and small_discount up from 56.8% to 72.0%, a 0.1518 total variation distance, well past the 0.02 tolerance, and fails automatically with no model change involved at all, which is exactly the class of regression the incident described. Note that no_discount is identical (21.52%) in both, since the PR only moved the upper cutoff: a contract test that had watched only the aggregate approval rate rather than the full decision distribution would have seen nothing wrong.
Trade-offs and pitfalls
- The tolerance in a behavioral contract test is a real design decision, not a formality. Too tight, and it fails on every legitimate rule refinement; too loose, and it misses exactly the kind of regression in this scenario. Set it from the business impact of a shifted decision (how much does a 5-percentage-point swing in
large_discountactually cost), not from a default like "whatever number makes today's test pass." - A golden master captured once goes stale the moment a rule change is legitimate and intended. The test needs an explicit, reviewed process for updating the golden master (a human approves that this shift is the intended new behavior), or the team will eventually just bump the tolerance until the test stops complaining, which defeats the point.
- This test protects against decision-distribution drift, not against every possible rule-engine bug. A rule engine that starts throwing exceptions on a valid input, or that has a bug affecting only a rare score value the frozen sample happens not to cover, will not be caught by this specific check; it needs to sit alongside, not instead of, the rule engine's own correctness tests.
- Canarying a rule-engine change needs the same rollback discipline as canarying a model. A common mistake is to treat rule-engine changes as "just config" and skip the staged rollout that a model deployment would automatically get, which is precisely how this class of regression reaches every user at once instead of a small canary slice first.
Unlock Full Question Bank
Get access to all Debugging and Testing ML Systems interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.