đ€ SDA 11: Preserving Referential Integrity Across Synthetic Tables
How the relational generator makes synthetic tables survive the join with generated key domains, deterministic fan-out, explicit cycles, and structural validation.

An orders table can look immaculate and still point to customers who were never generated. Every amount is plausible, every timestamp is tidy, and the join returns a small, humiliating puddle of NULLs.
Thatâs the awkward part of making synthetic data table by table. A key can be fresh, unique, and perfectly formatted. It can also lead nowhere.
In SDA 06, the agent learned to recognise keys and candidate relationships.
SDA 10 made an approved plan produce a bounded Delta table.
SDA 11 ties those pieces together: the relational generator creates parent domains first, derives child references from those domains, and validates the joins before anything earns a more flattering status than âgeneratedâ.
The Row at the Other End of the Join
A Perfect Table Can Still Be Wrong
Until now, the generator has worked one table at a time.
Give synthetic_data_generator an approved plan and a row budget, and it can produce a bounded Delta table whose values are deterministic and ready for validation.
Thatâs a useful unit of work. It just isnât a relational dataset yet.
Itâs also a very easy unit of work to misunderstand. A standalone validator can prove that customer_id is unique inside customers and that order_id is unique inside orders. It canât make those two domains agree after the fact.
An anti-join can show the damage; it canât invent the missing parent rows without changing the generation decision.
A Dataset Starts With Its Edges
Generate a synthetic customers table and a synthetic orders table independently, and the two tables have never met. The orders.customer_id values have no reason to belong to the generated customers.customer_id values.
Every amount can look right and every key can be unique; the join can still return a small, humiliating puddle of NULLs. A table can be perfectly respectable on its own and still be a terrible neighbour.
Relational generation makes the edge part of the input rather than a hopeful query someone runs later. The parent domain is created first, the child assignment receives that domain, and validation checks the resulting relationship. The join is no longer a coincidence between two tables that happened to share a column name.
đ Relational generation changes the unit of work from âmake a tableâ to âmake an approved set of tables and their edgesâ.
The relationship artifact says which candidate edges were accepted. The relational plan freezes that decision together with the approved generation plan, key domains, fan-out rules, and any explicit cycle strategy.
That freeze matters. If a relationship was rejected, unresolved, stale, superseded, or calculated for a different plan fingerprint, the generator refuses to improvise.
A guessed join is just an orphan wearing a tie.
Freeze the Relationship Contract Before Generating
The Artifact Must Be Accepted
The executable contract lives in RelationalPlan and build_relational_plan. A plan must already be approved, and the graph artifact must carry matching evidence for every requested relationship.
relational = build_relational_plan(
approved_plan,
foreign_keys=(orders_to_customers,),
composite_foreign_keys=(events_to_locations,),
key_domains=(customers_domain, locations_domain),
bridge_tables=(customer_product_bridge,),
self_references=(employee_hierarchy,),
cycle_strategies=(approved_cycle_strategy,),
relationship_artifact=frozen_graph_artifact,
)
Itâs intentionally less magical than a prompt. The code sample names the foreign keys, composite relationships, bridge tables, self-reference, and cycle strategy that the run is allowed to use.
Those declarations arenât decoration: they become part of the relational fingerprint and can be rejected if the graph evidence belongs to another plan.
The Artifact Decides the Order
Before rows exist, the relational generator computes a deterministic topological order. Parents come before children. When several tables are ready, their names provide the tie-break, so an innocent change in dictionary order canât rearrange the dataset behind our backs.
The order is deliberately narrower than a promise to reproduce every feature of a source graph. SDA 11 preserves approved relational edges and the structural behaviours attached to them. It doesnât claim to reproduce global graph topology.
That distinction also explains why the order is deterministic. A topological sort can have several valid answers; sorting the ready tables by name gives the run one stable answer. Reproducibility isnât only about using the same random seed. Itâs also about refusing to let an incidental dictionary order decide which parent gets generated first.
Synthetic Key Domains, Not Production IDs
Generate the Domain Once
The key-domain registry describes the synthetic key space for each table: its ordered columns, row count, generation strategy, and a fingerprint of the domain. It doesnât store a convenient bag of production identifiers for the child generator to copy later.
synthetic_data_generator creates fresh deterministic primary keys from the approved plan and stable row coordinates. The foreign-key assignment is a separate operation: once a parent table exists, a child column is populated only from that generated parent domain. Hashing a production identifier isnât a clever shortcut here. It can preserve linkability, and it still makes the source ID the secret ingredient.
That registry is what lets the later stages talk about a domain without smuggling raw values through the workflow. A manifest can record that customers has a four-row synthetic domain, which columns define it, where the staged table lives, and which fingerprint identifies it. The child generator needs that contract, not a secret suitcase of source IDs.
Treat Composite Keys as Tuples
Composite keys are tuples with an order, not two unrelated decorations. If locations is keyed by (tenant_id, location_number), an account_events row receives the pair from one generated location. A half-populated tuple isnât treated as a mysterious new location. It fails validation, unless the relationship is explicitly nullable and the whole tuple is NULL.
The same rule keeps primary and foreign keys honest. A table can have its own unique order_id and still use customer_id as a non-unique foreign key. Mixing those roles is how a bridge table starts introducing itself as a customer.
The order matters in the manifest as well as in the rows. A composite relationship with the right two values in the wrong order is still the wrong location. The validator therefore checks the tuple as a unit, distinguishes a legitimate all-NULL optional tuple from a partial tuple, and refuses to promote the latter into a new kind of identity.
Fan-Out Without Wishful Thinking
One parent may have no children. Another may have one. A third may have an unreasonable queue that makes the first two look like a quiet Tuesday. A relational generator that assigns children round-robin will produce rows, but it will flatten the shape we asked it to preserve.
Allocate Without Making Things Up
The generator supports two explicit fan-out modes:
distribution-firstuses an approved per-parent distribution when the child total can be derived from it. If the distribution is unavailable, a deterministic fallback is recorded rather than silently invented.exact-totalreconciles the requested child total to the per-parent allocation with deterministic tie-breaks. The final counts add up, while zero-child parents remain zero when the plan says they should.
There is also a strict compatibility path for callers that already provide every child count explicitly; the distributed bundle uses the two relational allocation modes above.
Fan-out caps are structural guardrails. They can catch an allocation that turns one parent into a small civilisation, and the manifest records the resulting relationship metrics. The point isnât to pretend that a fixtureâs four parents describe the universe. Itâs to make the rule visible and testable.
In distribution-first, the approved distribution can also determine the child total when the caller has not supplied one. In exact-total, the target total is reconciled against the per-parent counts with a stable order derived from the plan fingerprint. The adjustment is recorded, so a reviewer can see that the final twelve rows were reconciled from an initial allocation rather than quietly conjured by a loop with a heroic sense of optimism.
Nulls and Capacity Are Different Rules
Optionality is handled before the relationship value is assigned. An optional foreign key may become a valid NULL; a populated value must match a generated parent. The validator reports those states separately, so âmissing by policyâ doesnât get filed as âorphan by accidentâ.
One-to-one is stricter than many-to-one. The allocator chooses parent keys without replacement and fails when the child count would exceed capacity. Thatâs less exciting than quietly assigning two profiles to one customer, but it ages better.
The same capacity logic applies to optionality. A NULL is allowed only because the relationship says itâs allowed; it isnât a spare value used when the parent domain runs out. A populated child reference must still land in the generated parent domain, which is why the validator reports optional NULLs, matched rows, and orphans as different facts.
Bridges and Hierarchies Need Their Own Rules
Many-to-Many Is Not Two Foreign Keys
A many-to-many relationship gets a bridge table with two parent references. Its primary key remains its own key. Its two foreign keys form a pair, and the pair must be unique when pair_unique is enabled. The allocator works inside the finite Cartesian capacity of the two parent domains; asking for more unique pairs than exist is a clear error, not an invitation to duplicate the same relationship with a different link_id.
That separation matters because a bridge row has three identities competing for attention: its own row key, the left parent key, and the right parent key. The bridge primary key makes the row addressable; the pair says which relationship it represents. Making the link_id unique while repeating the same parent pair would satisfy the first rule and completely miss the second. The validator checks the pair.
Hierarchies Without Time Travel
Self-referencing tables are generated by levels. Root employees receive a valid NULL manager. Later rows can point only to an earlier generated employee, which keeps the hierarchy acyclic; the local path can also enforce an optional maximum depth. The Spark fixture exercises the shared single-key and root rules. The validator checks that the reference points to the same generated key domain and that roots stay roots.
This is a deliberately modest hierarchy model. It gives roots a real place in the table, prevents a row from becoming its own ancestor by pointing only backwards, and can enforce a local depth limit. It doesnât claim to reproduce every organisational pattern in a source graph. Sometimes a tree is a tree, and sometimes a graph is waiting behind it with a fake moustache.
Cycles: Allowed, but Only With a Plan
Strategy Must Be Explicit
Some schemas contain real cycles. They arenât automatically a bug, but theyâre never a free pass. CycleStrategySpec must explicitly approve a staging, deferred, or bootstrap strategy and name executable edges. The generator can then stage or defer those assignments and validate the completed result.
Fail Closed When It Isnât
An unresolved cycle fails closed. So does a cycle whose strategy doesnât cover its edges, a rejected relationship, an incompatible key type, and a stale graph artifact. The error is part of the contract: no half-believed dataset should slip through because the graph was feeling optimistic that morning.
The important part is the word approved. A cycle isnât solved merely because someone found an ordering that makes the code stop complaining. staging and deferred strategies identify which edges can wait; bootstrap is available only when the declared strategy names the executable edges itâs allowed to establish. If the strategy leaves an edge out, the generator has no honest next step, so it stops before producing a half-relational dataset.
Validation Is a Gate, Not a Vibe
Check the Join, Then Gate the Dataset
The relational validator checks the things a join can actually prove:
- Primary and composite-key uniqueness and non-null rules.
- Child references that match a generated parent domain.
- Orphan counts through anti-join logic and matched rows through semi-join logic.
- Optional
NULLs separately from populated references. - One-to-one duplicate references.
- Bridge pair uniqueness.
- Self-reference roots and parent membership.
- Row counts and fan-out bounds.
- Per-relationship metrics and a dataset fingerprint.
The metrics are meant to leave a trail, not just a green light. A relationship report can say how many child rows were populated, how many matched a parent domain, how many were NULL by policy, how many were orphaned, and how much of the parent domain was referenced. For fan-out it can record zero-child parents, the maximum number of children, the requested and realised totals, and any deterministic adjustments.
Three States, One Deliberate Gate
The dataset lifecycle makes the distinction visible:
GENERATED_AWAITING_VALIDATION -> VALIDATED -> APPROVED
Generation produces tables and a versioned relational manifest. Validation can move the manifest to VALIDATED only after the structural checks pass. An explicit approval action can move it to APPROVED; no code path quietly publishes the dataset as a side effect.
That last transition is intentionally dull. GENERATED_AWAITING_VALIDATION means rows exist but have not earned structural trust. VALIDATED means the checks passed for this run and fingerprint. APPROVED means an explicit approval was recorded. None of those words means private, statistically faithful, or ready for publication; the manifest is keeping the bookkeeping honest, not handing out medals.
Referential integrity is useful, but it isnât a universal quality oracle. A table can pass every key and join check while having absurd values, poor distributional fidelity, or an unsuitable privacy posture. Those questions need their own evidence and their own gates.
Retry Without Multiplying the Family Tree
Give Each Run Its Own Room
Every generated table and manifest is written to a run-scoped staging namespace. The dataset fingerprint covers the relational plan, row counts, run identity, and fan-out allocation. A retry with the same inputs reuses the existing dataset instead of appending a second set of parents and children. A retry with a different fingerprint is rejected rather than mixing generations with the same cheerful table names.
Recover Without Mixing Families
Validation reports are idempotent by run. Recovery after a partial write uses the same scoped destinations, so a failed attempt can be corrected and rerun without creating a second customers population beside the first one. Temporary error fixtures are cleaned up after validation; approved staging remains identifiable by its run-scoped manifest.
The recovery path therefore has a useful memory. It can find a compatible staged manifest, compare its fingerprint with the requested dataset, and either reuse it or fail closed. It doesnât scan every table called customers and hope that the right family tree will wave from the crowd. Thatâs how retry becomes a property of the run rather than an invitation to duplicate it.
Run It Where the Tables Live
Separate Tasks, Explicit Approval
The local tests make the rules readable, but the useful argument happens in Spark. The bundle deploys the relational_generator job with separate generate_relational and validate_relational tasks. Generation must receive approved=true; validation runs after generation and can move the manifest to VALIDATED or, only with an explicit approval parameter, to APPROVED. The report and manifest are separate Delta outputs, so a green structural report is evidence rather than a mysterious side effect.
The dependency between the two tasks is part of the contract. The validator reads the run-scoped tables produced by generation, writes a separate report, and updates the corresponding manifest row. If generation fails, validation doesnât get to pretend that a missing table is an empty but healthy dataset. If validation fails, the manifest stays on the generated side of the gate.
Test the Bad News Too
The integration path is deliberately boring to operate. With the sda profile, the bundle is validated and deployed to the selected target, and the run uses a staging schema scoped by run_id. The workspace, catalog, schema, table, and task permissions are part of that deployment contract. The relational job is configured for the sda11-smoke fixture; relational_error_smoke exercises rejected and stale graph artifacts, missing cycle strategy, incompatible key types, duplicate primary keys, and orphan foreign keys. Those cases are expected failures, not embarrassing surprises discovered after publication.
The live fixture covers the join shapes that matter here: simple and ordered composite keys, parents with no children, a skewed one-to-many tail, optional references, one-to-one allocation, bridge pairs, self-referencing roots, and an explicitly staged cycle. It also covers the less photogenic parts of the journey: fingerprint mismatch, partial-write recovery, same-run retry, staging cleanup, manifest state transitions, and a second reproducible execution without duplicated rows. Thatâs enough evidence for this contract. It isnât a magical certificate that every arbitrary Spark schema will behave itself.
Let Spark Keep the Domains Distributed
Keep the Family Tree Out of the Driver
The local implementation makes the contract easy to inspect in tests. relational_spark.py carries the same ordering, allocation, assignment, and validation ideas into DataFrames. It uses Spark joins, windows, ranges, and aggregates; it doesnât call collect() to pull large key domains into the driver.
The Databricks Run Has Two Jobs
The Databricks bundle includes a relational_generator job with generation and validation tasks, plus an error-smoke path for fail-closed cases. Its fixture covers simple keys, composite keys, a zero-child parent, a skewed one-to-many tail, optional self-reference roots, a one-to-one relationship, a bridge table, and an explicitly staged cycle. The same path records generated, validated, and explicitly approved states in the manifest.
The important word is fixture. The implementation supports the declared contract, but it doesnât claim that every data type, distribution, or arbitrary schema has already been exercised. A new relationship shape still needs a plan, a test, and a validator result before it gets to join the party.
Integrity Is a Boundary, Not a Verdict
SDA 11 preserves the relationships that an approved plan actually names: parent domains, child references, composite tuples, bridge pairs, self-references, and the explicit strategy for any cycle it is allowed to handle. It doesnât preserve global graph topology â communities, connected components, path-length distributions, hubs, or other whole-graph properties. That is a different problem, and pretending otherwise would make this article considerably cleverer than the implementation.
The boundary matters just as much on the other side. A referential-integrity report is not a privacy certificate, a complete statistical-quality verdict, or an automatic publication decision. Every foreign key can land in a real generated domain while the distributions are poor, the rare combinations are risky, or the output is simply the wrong shape for the job. A join can be correct and the dataset can still be a terrible model of the source.
What the relational generator can promise is narrower and more useful: the tables are generated as a family, their declared edges can be checked together, and failures remain visible instead of being polished into a green table-shaped shrug. The validator can say where the relationship contract broke. It cannot decide whether the data should be trusted for every purpose under the sun. Even synthetic tables need boundaries; otherwise the graph starts making promises nobody asked it to keep.
đ Source Code
The SDA-11 branch contains the relational generator, Spark jobs, validation flow, and tests behind this referential-integrity contract.
