🤖 SDA 10: Bounded Synthetic Tables
How SDA turns an approved plan into a bounded Delta table in Databricks, with repeatable values and a separate check on the output.

In SDA 09, we decided where the agent should keep its approvals and run state. The next question is wonderfully simple. Can an approved plan make a table we can inspect?
Twenty-five customers. One Delta table. synthetic_data_generator writes the rows from the plan, and a separate job checks the result.
After nine articles of preparation, the agent finally had a table of its own.
Start With 25 Customers
What the Plan Had to Say
“Make some realistic customers” is a perfectly reasonable request until you have to turn it into job parameters.
How many rows?
What can go in each column?
Which table can the job replace?
Once those choices are explicit, the Databricks generate_spark.py job reconstructs the approved plan from its parameters and checks the plan’s fingerprint before writing.
It invokes synthetic_data_generator for the bounded row generation. The fingerprint covers the requested row count, so changing 25 to 26 changes what we’re asking the job to do.
The plan carries the target scope, the row cap, the column strategies, the seed, and references to the source snapshot and upstream artifacts. Profiling, relationship discovery, and pattern detection happen upstream. The generator can write without opening the source tables.
As the plan grows, it can pin profile, pattern, and rule versions, spell out column treatments and privacy choices, and record scale, validation, and retry policies. Any change to approved instructions belongs in a new plan version.
What We Put in the Table
Our standalone customers table shows what an explicit plan can produce in Databricks. Four columns tell most of the story:
customer_idis a deterministic identifier.lifetime_valuecomes from a bounded numeric range.signup_atis a deterministic timestamp string.tax_idis a deterministic prefixed string.
The first Databricks table uses four strategies. The generator’s broader strategy surface includes empirical samples, weighted categories, format signatures, dates and timestamps, and null rates. Profile-backed distributions and richer dependencies remain outside this first table.
From Plan to Delta
The path from an approved plan to a table is short, but every gate earns its place. The writer checks the request, builds the rows, and leaves a receipt behind.
- Check the approval flag, requested row count, and row cap.
- Reconstruct the plan from the job parameters and verify its fingerprint.
- Generate bounded, deterministic Python rows from the declared strategies.
- Create the target schema if needed and build the Spark DataFrame.
- Create or replace the configured Unity Catalog Delta table.
- Print the generation receipt and manifest.
In Databricks, the writer checks the approval flag before it touches the target table. Workspace and target permissions still apply.
What the Validator Can Tell Us
A separate job reads the Delta table, checks the expected row count and required columns, and saves a validation report.
Give all 25 customers the same lifetime spend and those checks can still pass. The report would be correct. The table would be ridiculous.
Local tests cover identifier uniqueness within one table. Distributional fidelity, conditional drift, referential integrity, topology, noise, privacy, and publication are later checks. The quality decision belongs to SDA 14.
What a Rerun Does
Give the job the same approved plan again and it replaces the target Delta table in a fresh attempt. Append, fail-if-exists, artifact reuse, and recovery after a partial failure are still open.
The receipt records the plan identity and fingerprint, row count, output fingerprint, and generator version. The manifest adds the run, target table, seed, source snapshot and artifact references, and output columns. The output fingerprint lets us compare the rows the generator produced. Delta may lay out the files differently.
The job prints the receipt and manifest. Storing the manifest in Delta and connecting the writer to Lakebase for approvals and run state are future integrations.
A fuller manifest could record per-column strategies and seeds, profile details, timezone and fallback decisions, warnings, errors, and runtime and write metrics.
Where the Values Come From
Give Each Row a Stable Coordinate
When the job makes a customer_id, it has the approved plan and a row position. It can derive an identifier from those inputs and the column identity. The same coordinate can drive categories, null placement, numbers, strings, and timestamps. It’s internal to generation and can stay out of the published schema.
The job builds the rows in Python. For a distributed design, Spark can create the row coordinates and give them a name the rest of the pipeline understands.
spark.range(target_rows)
.withColumnRenamed("id", "synthetic_row_id")
A Seed Needs Company
Suppose we add one field to a distributed sampler. We’d like the other fields to keep their assignments where the plan’s policy allows it. A separate random stream per column makes that possible. One design could derive the stream from these inputs.
run_seed, synthetic_row_id, column_name, strategy_version
Spark’s rand(seed) generates values uniformly in [0, 1). Spark documents the function as non-deterministic in general, so exact row replay needs a stable coordinate.
Spark’s xxhash64 uses a fixed internal seed of 42. The run seed would go in as an input, with each column getting its own namespace. The hash can assign a row to a probability bucket. It is useful for stable assignment, but it is not a uniqueness or anonymisation guarantee. We return to those boundaries when we discuss identifiers and privacy.
Ten Percent of Twenty-Five
Put 10% of our 25 customers in one category and the plan has to decide what to do with half a customer.
Probabilistic sampling gives each row a 10% chance. With enough rows the proportion approaches the target. Exact allocation needs a rule for rounding to an integer, followed by a stable row order. Largest-remainder allocation with deterministic tie-breaks is one way to make rounded category counts add up to the total.
The same distinction matters for contractual null rates, required rare categories, point masses like zero, and tail events. The plan should settle that policy before the job runs.
What a Range Can Tell Us
The Shape Inside the Bounds
The range for lifetime_value tells us where a value can land. SDA 05 gives us more to work with for a future profile-backed sampler. It measured percentiles, histogram counts, skew, sign proportions, zeros, repeated values, and candidate outliers.
Say 6% of transaction amounts are exactly zero and only 1% are very large. Uniform sampling between the lowest and highest values would flatten the dense part, fill the sparse part, and lose the pile of exact zeros. The minimum and maximum could both look impeccable.
A profile-backed sampler would separate point masses first, then pick a histogram or quantile interval at its observed weight. Inside that interval we can interpolate within the bounds or pick an approved discrete value. The final step applies the planned type, precision, scale, and destination checks.
A higher accuracy argument in Spark’s percentile_approx costs more memory. If we use approximate anchors, the manifest should carry the method, accuracy, source snapshot, and boundaries.
Give the Tail Its Own Treatment
Integers have valid increments. Prices can cluster around .00 and .99. A continuous sample followed by a cast can flatten both effects or shift the share of zero, negative, and positive values. For DECIMAL(p, s), round at the approved scale and cast to the declared type.
The lower and upper tails can get their own weights and intervals. A rare value might be valid, a mistake, or something the plan needs to generalise, cap, transform, or exclude. The profiler gives us the evidence to make that call.
Keep the Category Weights
Suppose we add a membership tier. Its approved profile might look like this.
BASIC: 68%
PREMIUM: 24%
ENTERPRISE: 7%
UNKNOWN: 1%
Give all four categories equal odds and UNKNOWN suddenly accounts for a quarter of the table. At least the mistake is easy to count.
Weighted sampling gives each category an interval of the right size and maps a row’s deterministic draw into it. Keep the declared types too. A boolean can stay boolean, an integer-coded tier can stay numeric, and a label can stay text.
Which Values Are Safe to Reuse?
Statuses, countries, currencies, and product families can come from approved vocabularies. High-cardinality or sensitive fields need more care.
Use a synthetic vocabulary, preserve the family or format, or group rare values into an approved residual category. Identifier-like fields can get fresh values from templates. Unsupported ones need an explicit decision in the plan.
The profile is useful for signatures, cardinalities, and frequency bands. For an email-shaped field, the signature is enough to give us the shape. The production addresses can stay where they are. And if clean mode invents PROBABLY_ACTIVE, file a bug. Misspellings and invalid codes can wait for the noise-injection stage.
Make a New Value With a Familiar Shape
Formats and Identifiers
Our tax_id uses a prefix. For richer formats, table_profiler gives us lengths, character classes, casing, separators, safe prefixes and suffixes, parsing success, and approved vocabularies.
A signature like AAA-###### asks for three letters, a hyphen, and six digits. The same idea can shape a postal code, phone number, email address, or internal reference without copying the original value.
A row coordinate can produce a sequential key, a fixed-width code like CUS-00000124, or a deterministic UUID or token. Check any uniqueness requirement explicitly. Hashing an existing production ID can leave it linkable across tables, which is a pseudonymisation decision with its own risks.
For unsupported text, binary, JSON, or nested fields, the plan needs to choose exclusion, a safe placeholder, a specialised generator, or failure. A cast to STRING can make an unsupported field look suspiciously well supported.
What Time of Day Belongs in the Table?
In the example, signup_at is a deterministic timestamp string. If we want the timing to resemble the source, we need the calendar patterns from SDA 05. Sampling uniformly from the first signup to the last loses growth, weekday effects, busy hours, idle periods, midnight defaults, and month-end spikes.
A profile-backed strategy could pick a period at its observed weight, choose a valid date within it, then sample the time of day when it matters. A birth date doesn’t need an hourly model. A transaction timestamp might. Keep the relevant calendar dependencies and the plan’s bounds, including its rules for future dates.
In Databricks, TIMESTAMP (also called TIMESTAMP_LTZ) represents an instant whose calendar fields depend on the session timezone. TIMESTAMP_NTZ keeps local wall-clock time.
Changing the timezone can move a late-night event into another weekday. A temporal strategy should record the source type, profiling and generation timezones, conversion policy, and handling of daylight-saving gaps and overlaps. That lets it preserve the instant or the local time as appropriate.
Nulls Have Reasons
Missing Can Mean Several Things
A value can be SQL NULL, empty, whitespace, NaN, an approved UNKNOWN, or a legacy date like 1900-01-01. It might also be a parsing failure. SDA 05 taught us to count those cases separately. Now we have to decide which ones to reproduce.
A per-column null rate can be applied deterministically. A global rate gives each row a chance of being null. If a plan needs an exact count, it also needs an allocation rule. The null decision comes before generating the populated value. The manifest should eventually record the allocation method, what the plan asked for, and what the output got.
Apply Conditional Null Models First
A global rate can be technically correct and still put missing values on the wrong rows. SDA 07 gives us the questions we’d want the plan to answer.
P(closed_at IS NULL | account_status)
P(tax_id IS NULL | customer_type, country)
P(cancellation_timestamp IS NULL | status)
Conditional null generation is future work. With an approved model, the generator would work through these steps in order:
- Generate driver columns like
statusorcountry. - Select the most specific supported null model.
- Generate the null indicator.
- Generate the dependent value only for rows that should have one.
If a segment is too small, a fallback to a broader segment or global rate needs to be approved and recorded. Destination constraints and approved rules take precedence over the observed frequencies.
If active accounts require closed_at IS NULL, historical exceptions are evidence to record in the plan. The output should follow the approved rule.
What Changes When We Ask for More Rows?
Agree on a Count Before Running
The job checks the approved count against its cap before generating. For a future scale-factor request, resolve the count up front. Record the source count and snapshot, the rounding rule, the output cap, and the threshold for approval.
target_rows = approved_rounding(profiled_source_rows × scale_factor)
A larger batch needs fresh row coordinates and values generated from the approved model. Repeat our batch until you have ten million rows and you’ll still have 25 customers. The row count will be impeccable.
Small batches have their own problem. At a probability of 0.01%, a thousand rows give an expected count of 0.1. The rare category usually won’t turn up in a batch that size. The plan can allow that, require a representative, enlarge the sample, or use an approved residual group. Forcing in every rare case changes the proportions you see.
Let Spark Keep the Rows at Scale
At 25 rows, a bounded Python collection is easy to inspect and pass to Spark. A larger design would build the skeleton in Spark, generate columns with dependency-aware expressions or joins, and write directly to Delta.
Keep compact category weights, histogram boundaries, and format definitions on the driver when safe. Calling collect() on the generated table would pull the rows back into driver memory.
Where the Job Lives
The bundle calls a Python entry point from the sda package structure we set up in SDA 03.
├── databricks.yml
├── bundle/
│ └── resources.yml
├── src/sda/
│ ├── generation.py
│ └── job_entrypoints/
│ ├── generate_spark.py
│ └── validate_generated_spark.py
└── tests/
└── test_generation.py
The jobs use spark_python_task.
- The generator entrypoint writes the table.
- The validator entrypoint checks it.
- The generation module holds the bounded strategies.
A notebook can call the same sda package for a walkthrough or debugging. The bundle also supports wheel tasks as a deployment option.
As the strategy set grows, a distributed registry could give numeric samplers, weighted categories, identifiers, signatures, temporal histograms, constants, and null models the same contract. Each would validate its configuration, declare dependencies, produce a Spark expression or transformation, and report how it ran.
The plan should handle excluded and unsupported fields explicitly and reject dependency cycles before writing. If a strategy name is wrong, failing the job is a lot easier to explain than a column full of whatever came out of the random number generator.
The First Table Still Has to Join Something
A column can have the right percentiles, categories, formats, and null rate. Put it next to the others and you can still get a cancelled order with no cancellation timestamp or a purchase dated before the customer signed up. Those are failures in how values go together.
Fresh values still need privacy checks. A generator can recreate a rare combination or produce a row too close to the source without copying it directly.
We can make customers now. In SDA 11, we’ll use the relationship graph to generate parents before children, reuse their keys, and reproduce fan-out.
An order can have a plausible amount, a plausible date, and a perfectly formatted customer_id. It’ll still need a customer at the other end of the join.
🔗 Source Code
The SDA-10 branch contains the generator and bundle jobs behind this bounded flow.
