Test Case Design and Edge Case Analysis Questions
Systematically deriving the cases, inputs, and conditions most likely to expose defects. Covers formal test-design techniques (equivalence partitioning, boundary value analysis, decision tables, state transitions, and pairwise/combinatorial design) and writing clear, maintainable test cases with documented expected results. Also covers the edge-case mindset: boundary conditions, invalid and unexpected inputs, corner cases, and the attention to detail that anticipates failures when validating complex behavior.
You own a service computing distributed quantiles for telemetry. Discuss edge cases that arise from floating-point rounding, extremely skewed distributions, and merging partial aggregates. Propose unit/property tests, tolerance margins, and strategies (e.g., use KLL vs t-digest) to ensure correctness across scale and input skew.
Sample Answer
Direct answer
Testing a distributed quantile-computation service needs to target three distinct edge-case sources: floating-point summation order changing the result when partial aggregates from different shards are merged in different orders, extreme skew in the input distribution making a single global tolerance margin wrong for both the largest and smallest magnitude buckets simultaneously, and the merge algorithm itself (KLL or t-digest, two different sketch data structures for approximate quantiles) having its own accuracy-vs-memory trade-off that the test tolerance has to be calibrated against, not assumed away. Both numeric findings below are from actual executed code.
Structured elaboration
Floating-point rounding in merges. IEEE-754 addition is not associative: (a + b) + c can differ from a + (b + c) in the last bits, which matters specifically because merging partial aggregates from different shards can happen in different orders depending on which shards report first, race conditions in a distributed merge, or a retry re-ordering inputs. A test suite needs to assert the merge is either provably order-INDEPENDENT (a design property, not just an observed one) or, if it is not, that the ORDER-DEPENDENT variance stays within an explicitly stated and tested tolerance, rather than silently assuming associativity holds.
Extremely skewed distributions. A quantile service handling both a very large-magnitude bucket (e.g. aggregate latency across a huge fleet) and a very small-magnitude one (e.g. a rarely-hit endpoint) in the same merge cannot use a single absolute epsilon sized for the large bucket, because that same absolute epsilon is enormous relative to the small bucket's own scale; the tolerance margin needs to be relative (proportional to the value's own magnitude), not a single global absolute number, exactly the finding demonstrated below.
Merging partial aggregates. The correctness property to test is not "the merged result exactly matches summing everything from scratch" (true for exact floating-point summation only under math.fsum-style compensated summation, not ordinary running sums), but "the merged result matches a REFERENCE exact computation within an explicitly stated tolerance," and that tolerance needs its own justification (derived from the sketch algorithm's documented error bound, or from the floating-point precision limit of the numeric type in use), not picked arbitrarily.
KLL vs t-digest. KLL (the Karnin-Lang-Liberty sketch, introduced by Karnin, Lang, and Liberty at FOCS 2016) gives a provable, distribution-independent error bound on quantile estimates for a fixed sketch size; t-digest gives good empirical accuracy, especially at extreme quantiles (very close to 0 or 1), but its error bound is not as uniformly provable across the whole distribution. The test-design implication: if the service's SLA (service-level agreement, a committed accuracy or latency guarantee) requires a provable worst-case bound regardless of input distribution shape, KLL's guarantee is the one to test against explicitly (generate adversarial distributions and confirm the bound holds, not just typical ones); if the service instead needs to be very accurate specifically at extreme quantiles like p99.9 (99.9th percentile) on typical traffic patterns, t-digest's empirical accuracy at the tails is the property worth the bulk of the test budget, since its worst-case guarantee is weaker.
Worked example (executed)
import math
huge = 1.0e16
small_values = [1.0] * 10 # ten unit weights, same shape as merging count-weighted centroids
sum_huge_first = huge
for v in small_values: sum_huge_first += v
sum_small_first = 0.0
for v in small_values: sum_small_first += v
sum_small_first += huge
print(sum_huge_first) # 1e+16
print(sum_small_first) # 1.000000000000001e+16 <- different from huge_first!
Actual output: merging huge-shard-first lost all 10 of the small weights to rounding (sum_huge_first == 1e+16 exactly, unchanged from huge alone), while merging small-shards-first preserved them (sum_small_first == 1.000000000000001e+16, matching math.fsum's exact ground truth). This is a genuine, reproducible non-associativity, not a hypothetical: merge order changed the result by exactly 10.0 units, confirming that a merge implementation using plain running sums is order-DEPENDENT and needs either compensated summation (Kahan/Neumaier-style, which math.fsum uses) or an explicit, tested tolerance for order-induced variance.
The skew case constructed two merges sharing the SAME absolute tolerance (abs_tol = 5.0, sized to be reasonable for a large-magnitude bucket) against a deliberately buggy merge that drops the smallest partial sum: for large_bucket_parts = [5000000.0007, 5000000.0009, 4.0], the buggy merge (drops the 4.0 part) produced an absolute error of 4.0, which passes the abs_tol=5.0 check (correctly, since 4.0 truly is small relative to a 10-million-scale bucket). For small_bucket_parts = [0.0007, 0.0009, 0.0004] (the SAME buggy logic, dropping the smallest of the three), the absolute error was 0.0004000000000000002, which ALSO passes the same abs_tol=5.0 check, despite being a 20.0% relative error against the correct total of 0.002. The identical bug (a dropped shard) is correctly caught as significant on the large bucket's own scale and incorrectly waved through as insignificant on the small bucket's scale, using one shared absolute tolerance, which is exactly why a quantile service spanning orders of magnitude needs a relative tolerance (or a tolerance explicitly scaled per-bucket-magnitude), not one global epsilon.
Trade-offs and pitfalls
The most common mistake is asserting exact equality between a merged result and a from-scratch recomputation, which will intermittently fail from ordinary floating-point non-associativity even when the merge logic is completely correct, teaching the team to distrust or disable the assertion rather than fixing the actual issue (the tolerance should be explicit and justified, not zero). The skew-tolerance finding above is the second, subtler pitfall: a single passing tolerance check across a whole test suite can hide a real bug specifically in the low-magnitude buckets, which is disproportionately dangerous for a quantile service because the SMALL-magnitude bucket is often the rare, high-value signal (e.g. a low-traffic but business-critical endpoint) that a uniform-tolerance test suite is least equipped to protect. A third pitfall is picking KLL or t-digest based on general reputation rather than which specific accuracy property (uniform worst-case bound vs strong tail accuracy) the service's actual SLA requires, since the wrong choice can pass every "typical" test case and only fail exactly where the SLA is measured.
How do you reason about whether your test suite sufficiently covers edge cases for a critical 25-step revenue calculation pipeline? Describe metrics and heuristics you would use (mutation testing, boundary-value analysis, code coverage, property-based tests) and actions you would take when gaps are found.
Sample Answer
Direct answer
Coverage adequacy for a long calculation pipeline is a layered question, not a single metric: statement/branch coverage tells you the code ran, boundary value analysis (BVA) tells you the numerically dangerous points were exercised, and mutation testing tells you whether the assertions would actually NOTICE if the logic were wrong. A pipeline can hit 100% branch coverage while a wrong constant or an off-by-one comparison sits undetected in production, and mutation testing is the heuristic that specifically surfaces that gap.
Structured elaboration
Each metric answers a narrower question than the last:
- Code (branch) coverage answers "did every decision point in the pipeline execute both outcomes at least once?" It is necessary and cheap to measure, but it says nothing about whether the test that exercised a branch actually checked the RESULT was correct; a test with a weak or missing assertion still counts toward coverage.
- Boundary value analysis answers "were the specific numeric thresholds in each of the 25 steps (rounding cutoffs, tier boundaries, currency-conversion rate edges, zero/negative-value handling) tested at their exact edges, not just with a generic middle value?" A revenue pipeline is dense with exactly these thresholds, so BVA should be applied step-by-step, not just once at the pipeline's overall input.
- Mutation testing answers the harder question directly: "if a specific piece of logic were subtly wrong, would the test suite fail?" It works by introducing small, mechanical changes (mutants) to the code, such as flipping a comparison operator or changing a constant, and re-running the existing suite against each mutant. A mutant that SURVIVES (the suite still passes) means the suite has a real gap at that exact line, regardless of what the coverage percentage says.
- Property-based tests answer a different question again: "does an INVARIANT that should hold across every valid input actually hold, not just for the handful of example inputs I thought to write by hand?" Instead of asserting one exact output for one hand-picked input, a property test generates many random inputs (from a pinned seed, so failures are reproducible) and checks a general rule, e.g. "a discount pipeline can never increase revenue above the input gross amount." This is complementary to mutation testing: mutation testing tells you the SUITE is strong; property-based testing widens the INPUT SPACE the suite actually exercises, and a property violation on some randomly generated input the team never thought to hand-write is exactly the kind of edge case a 25-step pipeline is large enough to hide.
Worked example
A small stand-in for one stage of a longer revenue pipeline (a tiered volume-and-membership discount), with a test suite achieving 100% statement and 100% branch coverage, run for real:
def net_revenue(gross, units, tier):
if units >= 100:
gross = gross * 0.90 # volume discount at 100+ units
if tier == 'bulk':
gross = gross * 0.95
elif tier == 'enterprise':
gross = gross * 0.85
return round(gross, 2)
The 4-case suite, the four mutants, and the tier='unknown' check, made real and run for real
suite = [
((1000, 10, 'standard'), 1000.0),
((1000, 100, 'standard'), 900.0),
((1000, 10, 'bulk'), 950.0),
((1000, 10, 'enterprise'), 850.0),
]
def run_suite(fn, suite):
for args, expected in suite:
if fn(*args) != expected:
return False # KILLED
return True # SURVIVED
def mutant_boundary(gross, units, tier):
if units > 100: # mutated: >= to >
gross = gross * 0.90
if tier == 'bulk':
gross = gross * 0.95
elif tier == 'enterprise':
gross = gross * 0.85
return round(gross, 2)
def mutant_constant(gross, units, tier):
if units >= 100:
gross = gross * 0.91 # mutated: 0.90 to 0.91
if tier == 'bulk':
gross = gross * 0.95
elif tier == 'enterprise':
gross = gross * 0.85
return round(gross, 2)
def mutant_operator(gross, units, tier):
if units >= 100:
gross = gross * 1.10 # mutated: 0.90 to 1.10 (discount becomes surcharge)
if tier == 'bulk':
gross = gross * 0.95
elif tier == 'enterprise':
gross = gross * 0.85
return round(gross, 2)
def mutant_condition_broadened(gross, units, tier):
if units >= 100:
gross = gross * 0.90
if tier != 'standard' and tier != 'enterprise': # mutated: was `if tier == 'bulk'`
gross = gross * 0.95
elif tier == 'enterprise':
gross = gross * 0.85
return round(gross, 2)
mutants = [
("Boundary", mutant_boundary),
("Constant", mutant_constant),
("Operator", mutant_operator),
("Condition broadened", mutant_condition_broadened),
]
for name, fn in mutants:
print(name, "->", "SURVIVED" if run_suite(fn, suite) else "KILLED")
for tier in ['standard', 'bulk', 'enterprise']:
print(f"tier={tier!r}: original={net_revenue(1000, 10, tier)} mutant={mutant_condition_broadened(1000, 10, tier)}")
print(f"net_revenue(1000, 10, 'unknown') = {net_revenue(1000, 10, 'unknown')}")
print(f"mutant_condition_broadened(1000, 10, 'unknown') = {mutant_condition_broadened(1000, 10, 'unknown')}")
Test suite (4 cases, each hitting a different branch outcome, achieving full branch coverage): (1000, 10, 'standard') -> 1000.0, (1000, 100, 'standard') -> 900.0, (1000, 10, 'bulk') -> 950.0, (1000, 10, 'enterprise') -> 850.0. All 4 pass against the original function.
Four hand-written mutants (standard operator classes: boundary, constant, arithmetic operator, condition) were run against this same suite:
| Mutant | Change | Result against the coverage-satisfied suite |
|---|---|---|
| Boundary | units >= 100 to units > 100 | KILLED (suite fails, difference detected) |
| Constant | 0.90 to 0.91 | KILLED |
| Operator | 0.90 to 1.10 (discount becomes a surcharge) | KILLED |
| Condition broadened | if tier == 'bulk' to if tier != 'standard' and tier != 'enterprise' | SURVIVED (suite still passes) |
Mutation score =3/4=75%, even though branch coverage on this same suite was already 100% before any mutant existed. (Correction: an earlier draft of this answer described the fourth mutant as elif tier == 'enterprise' negated to elif tier != 'enterprise'; run against the actual 4-case suite, that specific mutant is KILLED, not survived, because negating that elif makes tier='enterprise' skip its own 0.85 multiplier and fail the suite's enterprise-tier assertion. Execution confirmed it: mutant(1000, 10, 'enterprise') returns 1000.0 under that mutation, not the suite's expected 850.0. The mutant shown in the table above is the one that actually survives.) The surviving mutant is not a fluke: tracing through why it survives shows it produces IDENTICAL output to the original for every value of tier the suite actually tests ('standard', 'bulk', 'enterprise'): 'bulk' is already consumed by the first if before the rewritten condition is ever reached, and 'standard'/'enterprise' are explicitly excluded from it, so the rewrite changes nothing for any tested input. What it reveals is a genuine gap: the suite has no equivalence-partition case for an unrecognized or malformed tier value (e.g. 'unknown' or None), where the broadened condition WOULD now incorrectly apply a 0.95 discount that the original never applied; verified directly: net_revenue(1000, 10, 'unknown') returns 1000.0 while the mutant returns 950.0, a real behavior difference on an input the 4-case suite never exercises. This ties the mutation-testing signal directly back to an equivalence-partitioning gap, not a coincidence.
A property-based test against the SAME function, 5,000 randomly generated trials (seed=2024, gross uniform in [0, 1{,}000{,}000], units uniform integer in [0, 500], tier chosen uniformly from the three valid values), checking the invariant "net_revenue can never exceed the input gross amount, within a 1-cent tolerance":
import random
def property_test(fn, seed, trials, tolerance=0.01):
rng = random.Random(seed)
violations = 0
for _ in range(trials):
gross = rng.uniform(0, 1_000_000)
units = rng.randint(0, 500)
tier = rng.choice(['standard', 'bulk', 'enterprise'])
if fn(gross, units, tier) > gross + tolerance:
violations += 1
return violations
Running the property test with and without tolerance, and against the buggy mutant, for real
def property_test_no_tolerance(fn, seed, trials):
rng = random.Random(seed)
violations = 0
for _ in range(trials):
gross = rng.uniform(0, 1_000_000)
units = rng.randint(0, 500)
tier = rng.choice(['standard', 'bulk', 'enterprise'])
if fn(gross, units, tier) > gross:
violations += 1
return violations
no_tol = property_test_no_tolerance(net_revenue, seed=2024, trials=5000)
print(f"no-tolerance violations against the correct function: {no_tol} / 5000")
with_tol = property_test(net_revenue, seed=2024, trials=5000)
print(f"1-cent-tolerance violations against the correct function: {with_tol} / 5000")
buggy_violations = property_test(mutant_operator, seed=2024, trials=5000)
print(f"1-cent-tolerance violations against the operator-swap mutant: {buggy_violations} / 5000 ({buggy_violations/5000*100:.0f}%)")
The 1-cent tolerance matters and is not cosmetic: checking result > gross with NO tolerance against the correct function finds 143 false-positive "violations" out of 5,000, all of them Python's round() rounding a discounted value up by a fraction of a cent (e.g. round(gross, 2) can land 0.001 to 0.005 above the exact unrounded gross on the 'standard'/units<100 no-discount path). With the 1-cent tolerance in place, matching how a real acceptance check for currency should be written, the correct function has 0 violations out of 5,000 trials. The SAME property test run against a deliberately buggy variant (the operator-swap mutant from earlier, 0.90 changed to 1.10 so the volume "discount" becomes a surcharge): 2,700 violations out of 5,000 trials (54%). This is the concrete case for property-based testing here: it does not need a hand-picked example input to catch this bug, the invariant itself, checked across a wide random input space, catches it on the majority of trials, and it also shows why the tolerance itself needs to be a deliberate design choice, not an afterthought, since a property test written too strictly flags rounding noise as a false failure.
Actions when gaps are found: a killed mutant needs no action, it proves the suite would catch that class of bug. A SURVIVED mutant is a work item: either add a test that distinguishes the mutant from the original (here: a tier='unknown' case), or, rarely, conclude the mutant is behaviorally impossible to distinguish (a true equivalent mutant) and document why, rather than chasing an unreachable 100% score. Track mutation score as a trend over time on the pipeline's highest-risk stages (the ones handling money, percentages, or rounding), not as a single pass/fail gate on the whole 25-step pipeline, since running full mutation testing on all 25 steps on every commit is usually too slow to be part of a fast feedback loop; run it on a schedule (nightly) or on files that changed in a given pull request.
Trade-offs and pitfalls
The most common mistake is treating branch coverage as the finish line because it is the number the CI dashboard shows; a revenue pipeline can look fully covered and still have a wrong tax constant sitting in a branch that always runs but is never asserted precisely. A second mistake is running mutation testing exhaustively across a large pipeline and getting buried in surviving mutants without prioritization; focus first on the steps with the highest financial blast radius (rounding, currency conversion, tier boundaries) rather than treating every mutant as equally urgent. Finally, an "equivalent mutant" (one that can never be killed because it cannot possibly change behavior for any valid input) is a real phenomenon that inflates the denominator of a mutation score without representing a real gap; distinguishing a genuinely uncovered case from a truly equivalent mutant requires human judgment, which is why mutation testing is a heuristic pointing at where to look, not a fully automatic pass/fail signal.
Write a Python function validate_record(record: dict, schema: dict) -> List[str] that verifies required fields, primitive types (int, float, str), and non-null constraints. Return a list of human-readable error strings for failing fields. Include how you'd handle optional fields and nested dicts, and briefly describe unit tests for edge cases such as missing keys, wrong types, and null values.
Sample Answer
Direct answer
validate_record should walk a schema field by field, distinguishing three independent failure axes per field (missing/required, null/non-nullable, wrong primitive type), recurse for nested dicts by treating a nested schema as its own field type rather than a special case, and return every failing field as one human-readable string rather than raising on the first problem, since a caller fixing a bad payload wants the whole list of errors in one round trip.
Structured elaboration
- Required vs. optional: a schema entry marks
required(default true if unspecified); a missing key on a required field is an error, a missing key on an optional field is silently fine and short-circuits the rest of that field's checks. - Nullable vs. non-nullable: independent of required/optional, since a field can be required-but-nullable (must be present,
Noneis an acceptable value) or required-and-non-nullable (must be present and notNone). Checking these as two separate boolean flags avoids conflating "absent" with "explicitly null," which are different failure states with different causes upstream. - Type checking, including the Python bool/int trap:
boolis a subclass ofintin Python, soisinstance(True, int)isTrue. A schema declaring"int"that uses a bareisinstancecheck will silently acceptTrue/Falseas valid integers unless explicitly guarded against, and a schema declaring"bool"needs the inverse guard so a plain2is not accepted as a boolean. - Nested dicts: represented by making the schema value itself a nested schema dict rather than a type-name string; detect this with
isinstance(field_type, dict)and recursevalidate_recordon the nested value with the nested schema, then prefix the returned error messages with the parent field name (e.g.'address.city' is required but missing) so a caller can locate the error in a deeply nested payload without re-deriving the path themselves.
Worked example (executed)
def validate_record(record, schema):
errors = []
for field, rule in schema.items():
required = rule.get("required", True)
nullable = rule.get("nullable", False)
field_type = rule["type"]
if field not in record:
if required:
errors.append(f"'{field}' is required but missing")
continue
value = record[field]
if value is None:
if not nullable:
errors.append(f"'{field}' is null but non-nullable")
continue
if isinstance(field_type, dict):
if not isinstance(value, dict):
errors.append(f"'{field}' must be an object, got {type(value).__name__}")
else:
for e in validate_record(value, field_type):
errors.append(f"'{field}.{e[1:]}")
continue
expected = {"int": int, "float": (int, float), "str": str, "bool": bool}[field_type]
if field_type == "int" and isinstance(value, bool):
errors.append(f"'{field}' must be int, got bool")
elif field_type == "bool" and not isinstance(value, bool):
errors.append(f"'{field}' must be bool, got {type(value).__name__}")
elif not isinstance(value, expected):
errors.append(f"'{field}' must be {field_type}, got {type(value).__name__}")
return errors
Unit tests for the edge cases named in the question (executed with pytest against a schema with user_id: int, email: str, age: int optional/nullable, is_active: bool, address: nested {city: str required}):
test_missing_required_key PASSED -> ["'user_id' is required but missing"]
test_wrong_type PASSED -> ["'user_id' must be int, got str"]
test_null_on_non_nullable_field PASSED -> ["'email' is null but non-nullable"]
test_null_on_nullable_field_is_valid PASSED -> []
test_optional_field_omitted_is_valid PASSED -> []
test_bool_int_cross_matching_rejected PASSED -> ["'user_id' must be int, got bool"]
test_nested_dict_valid PASSED -> []
test_nested_dict_missing_field PASSED -> ["'address.city' is required but missing"]
test_nested_dict_wrong_container_type PASSED -> ["'address' must be an object, got str"]
test_empty_record_reports_all_missing_required PASSED -> all 4 required-field messages (user_id, email, is_active, address; age is excluded since it is optional)
10 passed in 0.02s
Trade-offs and pitfalls
The bool/int cross-matching trap is the single most common bug in a naive implementation of this function; a reviewer should specifically ask "what does isinstance(True, int) return" if the candidate's type-check does not visibly guard against it. A second pitfall is raising on the first error instead of collecting all of them, which forces a caller into a slow fix-one-error-at-a-time loop against a payload that may have five independent problems. A third is float-accepting-int without deciding whether that widening is intentional (this design accepts it, since 5 is a perfectly valid value for a float-typed field, but the reverse, an int-typed field receiving 5.0, is correctly rejected, and a test suite should cover both directions explicitly rather than assuming symmetry). For nested dicts, forgetting to guard against a non-dict value being passed where a nested schema is expected (this implementation checks isinstance(value, dict) before recursing) causes a confusing AttributeError deep inside the recursive call instead of a clean, field-named error.
You are QA for a service that sorts large datasets and returns paged results (millions of records). What edge cases and test scenarios would you create to validate correctness and robustness: duplicate sort keys, stable vs unstable sorting, null/absent keys, comparator exceptions, inconsistent ordering across pages, serialization differences, and memory pressure? Define unit, integration, and end-to-end tests, and describe data generation approaches for large and pathological datasets.
Sample Answer
Direct answer
For a sort-and-page service over millions of records, the edge cases split into two families: correctness of the ordering itself (duplicate sort keys, stable versus unstable sorting, null/absent keys, comparator exceptions) and correctness of the PAGINATION on top of that ordering (inconsistent ordering across pages, serialization differences, memory pressure at scale). The single most dangerous edge case, and the one a code review will not catch by inspection, is heavy duplication in the sort key combined with offset-based paging: without an explicit tiebreaker, the exact same dataset can silently drop or duplicate rows across a page walk, even though each individual page looks correct in isolation.
Structured elaboration
Unit-level (comparator/ordering) tests
- Duplicate sort keys: many rows sharing the same key value. Stability matters here: a STABLE sort preserves the original relative order of equal-key rows across repeated runs on the same input; an UNSTABLE sort (a plain quicksort, or many distributed-engine parallel sorts) does not guarantee this, and the client-visible symptom is that two consecutive page requests for the same query can return duplicated-key rows in a DIFFERENT relative order, which breaks the natural expectation that "page 2 continues exactly where page 1 left off."
- Null/absent keys: decide and test an explicit placement rule (nulls first or nulls last), since most SQL and sort libraries default to a specific, sometimes surprising, placement that differs across databases and languages.
- Comparator exceptions: a custom comparator that assumes a specific type (e.g. always numeric) will raise on a heterogeneous or malformed value; test that the exception surfaces as a clear, typed validation error at ingestion time, not a raw crash deep inside the sort call during a customer-facing request.
Integration-level (pagination-consistency) tests
- Inconsistent ordering across pages: walk ALL pages of a query, concatenate every returned ID, and assert the concatenated set exactly equals the known full ID set for that dataset (no duplicates, no omissions), rather than eyeballing individual pages.
- Serialization differences: if the API paginates via an opaque cursor token, confirm the cursor's meaning is stable across a service redeploy (a cursor encoding a raw row offset breaks if the underlying storage is repartitioned; a cursor encoding a stable sort-key value plus a tiebreaker id survives it).
- Memory pressure: for millions of records, assert the service streams/paginates from the underlying store rather than materializing the full sorted result in memory before paging; a targeted test can seed a dataset sized to exceed a deliberately small memory limit in a test environment and confirm the service still completes without an out-of-memory failure, rather than asserting a specific memory number.
End-to-end tests
- A full client-simulated walk (as in the worked example below) over a realistic dataset shape, verifying the concatenated, deduplicated result matches an independent full-sort oracle.
Data generation for large and pathological datasets
- Generate at multiple scales (thousand, million-row smoke tests) with a FIXED seed for reproducibility.
- Deliberately skew the generator toward pathological shapes: a large fraction of rows sharing one sort-key value (the duplicate-key stress case), a long tail of unique keys, explicit NULL injection at a known rate, and adversarial comparator inputs (mixed types if the schema technically allows it).
Worked example (executed): duplicate-sort-key pagination bug, caught and fixed
import random
random.seed(42)
rows = [{"id": i, "score": i % 4} for i in range(500)] # 500 rows, only 4 distinct sort-key values
def unstable_source_page(all_rows, offset, limit, rng):
grouped = {}
for r in all_rows: grouped.setdefault(r["score"], []).append(r)
ordered = []
for k in sorted(grouped):
bucket = grouped[k][:]; rng.shuffle(bucket) # ties reordered on every call, simulating a real DB with no tiebreaker
ordered.extend(bucket)
return ordered[offset: offset + limit]
def stable_source_page(all_rows, offset, limit):
ordered = sorted(all_rows, key=lambda r: (r["score"], r["id"])) # explicit tiebreaker
return ordered[offset: offset + limit]
def walk_all(page_fn, total, limit):
seen = []
for offset in range(0, total, limit):
seen.extend(r["id"] for r in page_fn(offset, limit))
return seen
LIMIT = 37
rng = random.Random(7)
unstable_ids = walk_all(lambda o, l: unstable_source_page(rows, o, l, rng), 500, LIMIT)
stable_ids = walk_all(lambda o, l: stable_source_page(rows, o, l), 500, LIMIT)
expected = set(r["id"] for r in rows)
print(len(unstable_ids), len(set(unstable_ids)), len(unstable_ids) - len(set(unstable_ids)), len(expected - set(unstable_ids)))
print(len(stable_ids), len(set(stable_ids)), len(stable_ids) - len(set(stable_ids)), len(expected - set(stable_ids)))
Executed output: the unstable (no-tiebreaker) walk fetched 500 rows total but only 353 unique ids, 147 duplicated across page boundaries and 147 missing entirely from the walk, on the exact same 500-row dataset. The tiebreaker-stabilized walk fetched 500 rows, 500 unique, 0 duplicates, 0 missing. This is not a contrived pathological case, it is what happens on ANY dataset where the sort key alone does not uniquely order the rows and pagination crosses a tie boundary.
Trade-offs & pitfalls
The most common mistake is trusting that "the database sorts consistently" without an explicit tiebreaker column; many query engines make NO ordering guarantee for tied rows across separate query executions, especially under parallel execution plans, so relying on incidental stability is a latent bug that a small-scale manual test will not surface (the bug only shows up once ties outnumber a single page, which small test datasets rarely do). A second pitfall is testing pagination correctness only at the unit level (one page looks right) without the end-to-end concatenate-and-diff check across the FULL walk, which is the only way this class of bug is actually visible. Third, testing memory pressure by asserting a fixed byte count is fragile across environments; asserting that the operation SUCCEEDS under an artificially constrained limit, and that the service degrades to a documented, bounded failure mode (not an unbounded materialization) rather than crashing, is the more durable test design.
You're building a CSV ingestion pipeline for production. List and explain the edge cases you would proactively detect and handle (for example: missing header row, variable column counts, different encodings/BOM, quoted newlines, empty file, trailing delimiters, mismatched column types, and embedded separators). For each case describe detection technique, automated remediation or rejection policy, and how you'd alert engineers and consumers.
Sample Answer
Direct answer
A production comma-separated values (CSV) ingestion pipeline must treat malformed input as the expected case, not the exception, because CSV has no enforced schema: missing headers, inconsistent column counts, encoding differences, quoted newlines, empty files, trailing delimiters, mismatched types, and embedded separators are all valid ways for a file to be technically well-formed text and still not what the pipeline expects. Each needs an explicit detection step and a stated policy (reject the file, quarantine the row, or coerce with a logged warning), because silently guessing is how bad data reaches downstream consumers.
Structured elaboration
| Edge case | Detection technique | Remediation or rejection policy | Alerting |
|---|---|---|---|
| Missing header row | Compare the first row's values against the expected schema's column names; if they parse as data-typed values (e.g. all numeric) rather than the expected header labels, the header is likely absent | Reject the file outright; a header-less file cannot be safely mapped to columns without risking a silent off-by-one field shift | Page the ingestion on-call with the file name and the mismatch reason, since this usually means an upstream format change, not a one-off bad file |
| Variable column counts | Count delimiter-separated fields per row (accounting for quoting) and compare against the header's column count | Quarantine rows with too few fields (do not pad with nulls silently, which hides which field is actually missing); reject rows with too many fields rather than truncating, which can silently drop the wrong field | Emit a per-file summary count of quarantined rows so a slow drift (an upstream system starting to add a column) is visible in aggregate, not just per-row |
| Different encodings and Byte Order Mark (BOM) | Sniff the first bytes for a BOM signature (UTF-8, UTF-16 LE/BE have distinct byte sequences) before decoding; if no BOM is present, do not assume UTF-8 blindly, attempt decode and catch the decode error | Strip a detected BOM before parsing; on an undetectable or unsupported encoding, reject the file rather than decoding with errors="replace", which silently corrupts characters | Alert with the detected (or failed) encoding so a recurring wrong-encoding source can be identified and fixed upstream |
| Quoted newlines | Use a proper CSV parser (one that tracks open/closed quote state across physical lines) rather than a naive per-line split; a naive line-based split will break a multi-line quoted field into two malformed rows | Never attempt to auto-repair a mismatched quote count; a file with an odd number of quote characters is genuinely ambiguous and should be rejected for manual review | Flag ambiguous quoting distinctly from other malformed-row cases, since it usually indicates a source system exporting the same field inconsistently |
| Empty file | Check byte length is zero before attempting to parse | Reject with a specific empty_file reason, distinct from a parse failure; an empty file may be legitimate (e.g. a scheduled export with genuinely no new rows that day) and should not be treated identically to a corrupt file | Do not alert loudly on every empty file if it is an expected, low-severity case for that particular source; alert only if a source that normally has volume suddenly sends empty files repeatedly |
| Trailing delimiters | Detect a trailing delimiter as an extra empty trailing field per row; decide once, as policy, whether that represents an intentional empty last column or an export artifact | If the schema does not expect a trailing empty column, strip it consistently rather than treating it as a column-count mismatch that quarantines otherwise-valid rows | Not typically alert-worthy once the policy is codified; log at debug level only |
| Mismatched column types | After column-count validation passes, attempt to cast each value to its declared type (integer, float, string, date) and collect per-field cast failures | Quarantine the specific row with the specific failing field named, not the whole file, so one bad row does not block an entire day's data | Summarize cast-failure counts per column per file; a single column suddenly failing casts across many rows usually means an upstream schema change, not row-level noise |
| Embedded separators | Rely on the CSV parser's quoting rules (a comma inside properly quoted text is not a delimiter) rather than a naive string split on the delimiter character; test specifically with an unquoted embedded delimiter, which is genuinely ambiguous | An unquoted embedded delimiter that produces an unexpected column count should fall under the variable-column-count policy above (quarantine), since it cannot be resolved without guessing which field absorbed the extra separator | Same as variable column counts |
Worked example
Consider a file with the declared schema [user_id: int, name: str, notes: str] and this row: 42,"Jones, Robert","Called, said ""will follow up"" next week". A naive split on comma produces five fields (42, "Jones, Robert", "Called, ...) and would incorrectly quarantine this row as a column-count mismatch. A quote-aware parser correctly resolves it to exactly three fields, because it tracks that the commas inside "Jones, Robert" and inside the doubled-quote-escaped notes field are data, not delimiters. This is the concrete reason "use a real CSV parser" is not a stylistic preference: a naive split is measurably wrong on any row containing both an embedded separator and a quoted field, which is common in free-text columns like notes.
Trade-offs and pitfalls
The most common wrong turn is silently coercing ambiguous cases (padding missing fields with null, truncating extra fields, decoding with a lossy fallback encoding) because it keeps the pipeline running without alerts; this trades a visible failure for an invisible data-quality problem that surfaces much later and is far harder to trace back to its source file. A second pitfall is alerting at the same severity for every case: an empty file from a source that legitimately has quiet days is not the same signal as a header row that vanished, and treating them identically trains the on-call rotation to ignore alerts. A third is testing only single-row malformed cases and never a file that combines several edge cases at once (a BOM-prefixed file with variable column counts AND a quoted-newline row), which is closer to what a real bad upstream export actually looks like.
Unlock Full Question Bank
Get access to all 15 Test Case Design and Edge Case Analysis interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.