cleandataengineering.aiData Platform, from the big picture to the code
You are here: Start here › Tests and proof › Testing strategy

Data PlatformZoom level 2

The testing strategy: generated tests, the data twin, the tiers and the tools

A test can run every line of code and still prove nothing, because running a line does not mean the test would notice if the line were wrong. A hand-written list of cases is also only as complete as the person who wrote it. This page explains what we do about both, in the order we do it.

The guiding rule is to fail fast: find a wrong rule at the cheapest layer that can show it. Every bug the generated tests have found so far was found on a laptop, in seconds to minutes, before any workspace or real data was involved.

Where a test runs, from cheapest to most expensive

  1. A pure function on a laptop. Each silver step takes a table in and gives a table out, so it runs with no database and no cluster.
  2. The same step on a fast second engine. The same test tables run on DuckDB through SQLFrame, so a run takes seconds.
  3. The same step on local Spark. The engine the platform really runs on, on one machine.
  4. The simulated company, end to end. The data twin: a generated company writes into mock sources and every layer is judged against known answers. See The simulated company and The oracle.
  5. A real workspace. Real tables, real formats, real cost, a real catalog.
  6. Production. Data-quality rules, reconciliation and drift checks watching real data.

The first three layers are where most bugs can be found cheaply. The rest are needed too, because they show what a laptop cannot: format behavior, cost, scale and data nobody imagined.

What we had, and what was missing

Tests and proof describes three kinds of proof: table-driven cases, the simulated company with an oracle, and planted incidents. All three start from cases a person thought of. The review of 19 November 2026 found cases the list had missed, so we added a fourth kind: tests that generate the cases.

The approaches

ApproachIn plain wordsWhat it catchesState
Table-driven casesA named list of inputs and the expected outputs.Situations someone thought of, and regressions.Built: 144 stage tests.
Property tests against a reference modelGenerate hundreds of random inputs. A small, obviously correct model says what the result must be, and the real code is compared with it.Cases nobody listed.Built for SCD Type 1 and Type 2.
Metamorphic testsThe same data in another order, or split into other batches, must give the same result.Bugs that depend on order or batching.Built for SCD Type 2.
Known-bug registryEach real gap is a minimal case marked as an expected failure that is strict: when someone fixes the bug, the case fails and says to remove the mark.Bugs that are forgotten, or fixed without anyone noticing.Built: 4 cases.
Mutation testingBreak the code on purpose (change a greater-than to greater-or-equal) and check that a test fails. The share caught is the strength of the tests.Tests that run a line but would not notice if it were wrong.Planned. Not run yet.
Pairwise combinationsTest every pair of option values together in a few dozen cases, not every full combination.Settings that interact badly.Counted: 23 cases instead of 2,880. Not built.
Hostile valuesGenerate awkward numbers, dates and text for type conversion and compare with a reference parser and across two engines.The odd forms real data arrives in.Planned.
Full-copy and snapshot contractThe same idea for input that is not a change feed, with a model that compares successive copies.The inputs the declarative engine refuses today.Planned.
The data twin at scaleMany random seeds, the history rules checked every simulated day, the same day delivered in another order.Surprises that only appear end to end.Planned.
Production corpusReal batches, made anonymous, replayed on every change.Whatever no simulation imagined.Needs real data.

A worked example: how a generated test found a history bug

For history, the question is what silver must hold after a set of changes to a key arrives, in any order, possibly twice, in any number of batches. The reference model is a few lines. Order a key's changes by sequence; a new version opens when the tracked value differs from the one before; the last version is current; a version is deleted when its last change is a delete.

src/dataplatform/silver/history_model.py:35The reference model for SCD Type 2. It is not used to build silver. It is what silver is compared with.
def type2_versions(changes: Iterable[Change]) -> list[Version]:
    """One pass per key, in sequence order. A change that is not a delete opens a version when its value differs from the
    current version's, and otherwise joins it. A delete never opens a version and never changes one's value: it marks the
    version it falls in. The one exception is a key's first change: a delete for a key with no version makes the deleted
    version from its own row. A version is deleted when its last change is a delete."""
    by_key: dict[str, list[Change]] = defaultdict(list)
    for c in _distinct(changes):
        by_key[c[0]].append(c)
    out: list[Version] = []
    for key in sorted(by_key):
        versions: list[list] = []  # [value, start sequence, last op]
        for _, value, seq, op in sorted(by_key[key], key=lambda c: c[2]):
            if op == "D":
                if not versions:
                    versions.append([value, seq, "D"])
                else:
                    versions[-1][2] = "D"
            elif versions and versions[-1][0] == value:
                versions[-1][2] = op
            else:
                versions.append([value, seq, op])
        out += [(key, v[0], v[1], i == len(versions) - 1, v[2] == "D") for i, v in enumerate(versions)]
    return out

The test generates a history (changes to a few keys, delivered out of order, some twice, split into batches anywhere), builds silver from it, and compares the result with the model. It also checks the history rules: at most one current version per key, and no overlap.

tests/dataplatform/test_silver_properties.py:167The property test. One test covers every generated history.
@SETTINGS
@given(h=histories())
def test_scd2_matches_the_reference_model(spark, h):
    hypothesis.assume(not known_gap(h))
    with example_session(spark) as session:
        silver = _apply(session, plan(**SCD2), batches_of(h))
        got = rows(silver, "id", "v", "_seq_from", "_is_current", "_is_deleted")
        assert got == model_type2(h), explain(h) + difference(got, model_type2(h))

Hypothesis found a history of seven changes that made silver disagree with the model. It shrinks a failure to the smallest history that still fails. Here that is two changes: an update, then a delete that carries a newer value than the stored version. The delete arrives first, so it overwrites the stored value in place, and when the missing update arrives later the earlier history cannot be rebuilt.

tests/dataplatform/test_silver_stages.py:510The minimal case, kept as a strict known bug: it is expected to fail, and a fix turns it into a failure that says to remove the mark.
        "a delete that arrives before the update it follows keeps the earlier history",
        [[("b", 3, "x", 21, U, 0, 1)], [("b", 1, "x", 36, D, 5, 2)], [("b", 1, "x", 34, I, 9, 3)]],
        [("b", 3, 21, False, False), ("b", 1, 34, True, True)],
        marks=_known_bug("a delete is stored as a flag on the version it fell in, without its sequence. When the update "
                         "it follows arrives later, a new version opens after the older one, but the delete stays on the "
                         "older version: history is kept, the key looks live (found by test_silver_properties, "
                         "23 Nov 2026; needs the delete's sequence stored)"), id="delete-before-its-update"),
    pytest.param(
        "the same delete twice in one batch is one deleted version",

What the generated tests found in SCD Type 2

#What silver doesWhy it matters
1A delete that arrives before the update it follows overwrites the stored version's value, and the earlier history is lost for good.Silent loss of history
2The same delete sent twice in one batch becomes two versions of the key.Duplicate rows
3A late change that lands inside a run of same-value changes makes the later change forgotten. (Found by review on 19 Nov, before the generated tests.)A lost change
4A key deleted and then changed back to the same value is one live version when the two arrive in separate batches, and two versions when they arrive in one batch.The result depends on how the feed was split

The SCD Type 1 property test passed every generated history. One question is still open and is a decision for the owner, not a bug: what a second delete of an already deleted key means. Silver keeps two deleted versions today and the contract does not say.

How this joins the data twin

The twin (The simulated company) is a generated company with a record of the truth. Today it judges counts, sums and digests. The new approaches plug into parts it already has: the oracle, the runner's checks, the world file's incident list, the learning loop that turns a failed run into a scenario file, and the release gate that compares a changed copy with production.

ApproachWhere it plugs into the twinWhat is new to build
The reference modelThe oracle. Today it judges counts and sums. It would also judge versions, worked out from the company's own change log.Move the model into the platform code so tests and twin share it. Done.
Invariant checks (one current version, no overlap)The runner's silver checks, every simulated day.A few checks in the existing list.
The four found gapsPlanted incident kinds in the world file, so each exists end to end.Four incident entries with their expected results.
Random seeds and shrinkingThe world's seed, and the learning loop that turns a failed run into a pending scenario file.A seed loop on the fast engine, and a bridge from the shrinker to the loop.
Reordered, split and repeated deliveryThe release gate's clone-and-compare: two copies, the same input delivered differently, silver must match.A delivery shaper.
Hostile valuesA new incident kind with parameters. The company knows exactly which rows it made unconvertible.The shaper and the expected quarantine count.
Pairwise variantsVariant copies of the slice, each of which must equal the oracle.A generator of option combinations.

None of the plug-ins is built yet except the shared model. One honest limit: a simulated company generates what its author imagines. The learning loop, and eventually real batches, are what stop the twin from only testing the author's own ideas.

The tiers

TierGoalDone so farStill to doRuns on
0Foundations: tests run the same everywhereDeclared test dependencies, make targets, tests on UTC, a clean static scan, the scan covering the Databricks code tooPinned versions, a nightly property run, one test-adequacy pageLaptop
1Known gaps: make them visible, then fix themThe shared model, four strict known-bug casesThree owner decisions, then the fixesLaptop
2Stronger tests for each stepProperty and metamorphic tests for SCD Type 1 and 2Mutation testing, hostile values, the other stages, the snapshot contractLaptop
3Configuration coverageThe count of pairwise casesGenerate and run them; refusal testsLaptop, then workspace
4The data twin does the same end to endNothing yetVersion-level oracle, daily invariants, incident kinds, seeds, shapersLaptop
5Proof on the real platformDeployment gates, benchmark and maintenance probes (built, not run)The runs on a workspaceWorkspace
6Production feedbackThe learning loop for planted incidentsA real-data corpus; real failures becoming scenariosNeeds real data

Order: tier 0, then tier 1 once the owner has decided the three open questions (a second delete of a deleted key, a delete whose value differs from the stored version, and whether the same changes must give the same silver however the feed is split), then mutation testing from tier 2, then tiers 3 and 4 together, then 5 and 6.

The open-source tools

ToolWhat it is forWhere it is used
pytest, pytest-covRunning tests and measuring coverageEverywhere. Coverage has a floor of 80%.
HypothesisProperty-based testing: generates the inputs and shrinks a failure to a minimal caseThe property tests.
PySpark with delta-sparkThe engine the stages run onStage and gold tests.
SQLFrame on DuckDBThe same DataFrame code on a fast local engineThe same stage tests run on a second engine; the property tests run here for speed.
delta-rs, pyarrow, psycopgReading and writing tables and PostgreSQL locallyLocal tables and sources.
motoA fake AWS for S3 and KinesisThe cloud adapter tests.
allpairspyGenerates pairwise casesUsed once to count the cases. Not yet a part of the suite.
ruff, mypy, bandit, semgrep, sqlfluffStyle, types, security patterns and SQL lintEvery pull request.
gitleaks, pip-audit, cyclonedx-bomKeys in the history, vulnerable dependencies, a software bill of materialsEvery pull request.
pyspark-antipattern, sparkdoctor, complexipySpark-specific and complexity rulesThrough the project's own static-analysis bundle.

Not open source but used: CodeQL and SonarCloud as services in the pipeline. Considered and not adopted: a mutation-testing tool (none chosen yet), Great Expectations and Soda for data quality (the platform's own rules run as its own stages), and PyDeequ (used only in a teaching scene). Licences are as the authors state them; check each before adopting a tool.

ExampleHow to run them
make test-model      # the reference model against every contract case (plain Python, seconds)
make test-props      # the generated tests on the fast engine; HYPOTHESIS_MAX_EXAMPLES=300 for more
python3 scripts/preflight.py --gate G0     # tools, checkout, no keys in git (see the Deploy page)
Not built yet, or known gaps
  • No test proves the other tests are complete. These approaches raise confidence and show where it is weak.
  • Mutation testing has not been run, so there is no strength score for any file yet.
  • The reference model encodes the contract as read today. Where the contract is silent, the model's choice is not a ruling.
  • The generated tests cover change-feed input only. Full-copy and snapshot input, and the declarative engine, have none.
  • The data twin does not yet use any of the new approaches, apart from the shared model.
  • The test dependencies are declared in one file but not yet pinned to exact versions.