Metadata-Version: 2.4
Name: benchbox-datagen
Version: 0.1.0
Classifier: Programming Language :: Rust
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Topic :: Database
License-File: LICENSE
License-File: THIRD_PARTY_LICENSES
Summary: Deterministic, high-throughput benchmark data generation for BenchBox
License-Expression: MIT
Requires-Python: >=3.11
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Repository, https://github.com/BenchBox-dev/benchbox-datagen

# benchbox-datagen

Deterministic, high-throughput benchmark data generation for
[BenchBox](https://github.com/BenchBox-dev/benchbox), written in Rust and
exposed to Python through PyO3.

The design and its validation gates are recorded in BenchBox's
`docs/internal/adr/adr-benchbox-datagen.md`.

## Scope

The library is built in stages:

1. TPC-H
2. TPC-DS, including fractional scales and refresh sets
3. SSB
4. The BenchBox synthetic generators (`h2odb`, `tsbs_devops`, `clickbench`,
   `tpch_skew`, `vector_search`, `coffeeshop`, `joinorder_synthetic`,
   `amplab`)

TPC generation depends on the upstream Apache-2.0 crates from
[`datafusion-contrib/tpcgen-rs`](https://github.com/datafusion-contrib/tpcgen-rs),
pinned by exact version. This project does not fork them: fixes go upstream, and any
patch carried until upstream releases it is listed under
[Carried upstream patches](#carried-upstream-patches).

Today the library generates TPC-H (all eight tables, any scale factor), TPC-DS (the 24 benchmark tables at scale factors below 1 and at integer scale factors of 1 or more, in `CompatMode::C`, byte-identical to the bundled patched `dsdgen`), SSB (all five tables, any scale factor), `amplab` (all three tables, any scale factor), `clickbench` (the `hits` table, any scale factor), `coffeeshop` (all three tables, any scale factor), `h2odb` (the `trips` table, any scale factor), `joinorder_synthetic` (all 21 tables, any scale factor), `tpch_skew` (all eight tables, any scale factor), `tsbs_devops` (all five tables, any scale factor), and `vector_search` (both tables, any scale factor) as
Arrow record batches or as files, and reports exact per-table row counts. Output
carries BenchBox's Arrow types (`int64`, `decimal128(15, 2)`, `date32`, `utf8`,
`NOT NULL` columns non-nullable). Delimited output is byte-identical to the
bundled `dbgen` / `dsdgen -TERMINATE n` output (no trailing `|`), for every table
(TPC-H `partsupp` and `lineitem` differ from `dbgen` only at the fractional scale factors
listed under [Carried upstream patches](#carried-upstream-patches)).
Below TPC-DS scale factor 1 the patched `dsdgen` scale model (`max(1, floor(SF 1 rows x SF))`,
six static tables) supplies every table's row counts to `tpcdsgen` through a caller-supplied
`Scaling`, so all 24 tables come from `tpcdsgen` at every scale factor.
TPC-H refresh sets (`dbgen -U`) and TPC-DS refresh sets (`dsdgen -update <n>`: the 21 `s_*`
source files, `delete_<n>.dat` and `inventory_delete_<n>.dat`) are available through
`write_refresh`, byte-identical to the bundled generators. `tpcdsgen` 4.0.0 has no refresh
generators, so the TPC-DS source tables are generated by this library's module `tpcds_update`,
ported from `dsdgen` (see [TPC-DS refresh sets](#tpc-ds-refresh-sets) for the TPC-derived files) and built on `tpcdsgen`'s public random streams, distributions and row types, seeded by the optional
`rng_seed` (`dsdgen -rngseed`). TPC-H rejects `rng_seed`. TPC-DS refresh sets are available at
scale factors below 1 and on the `dsdgen` scale grid (see below). Refresh-set generators are proposed
upstream in [datafusion-contrib/tpcgen-rs#678](https://github.com/datafusion-contrib/tpcgen-rs/issues/678).
SSB has no refresh sets and `write_refresh("ssb", ...)` raises an error.
Parquet output is written in Rust with 122,880-row row groups and the
`benchbox.parquet_writer=benchbox-datagen-<major>` key-value entry; neither
format's bytes depend on the thread count. SSB output is described under
[Deterministic synthetic generators](#deterministic-synthetic-generators).

## Python

```python
import pyarrow as pa
import benchbox_datagen

reader = pa.RecordBatchReader.from_stream(
    benchbox_datagen.generate_table("tpch", "lineitem", scale_factor=1.0, part=1, parts=4)
)
for batch in reader:
    ...
```

`generate_table` returns an object that implements the Arrow PyCapsule stream
interface (`__arrow_c_stream__`), so any Arrow-compatible library can consume
it without copying.

```python
import benchbox_datagen

counts = benchbox_datagen.row_counts("tpch", 10.0)
assert counts["lineitem"] == 59_986_052

ranges = benchbox_datagen.key_ranges("tpcds", 10.0)
assert ranges["item"]["i_item_sk"] == (1, 102_000)

ranges = benchbox_datagen.key_ranges("ssb", 10.0)
assert ranges["lineorder"]["lo_custkey"] == (1, 300_000)

files = benchbox_datagen.write_tables(
    "tpch",
    10.0,
    "out/tpch_sf10",
    format="parquet",
    compression="zstd",
    threads=8,
)
for file in files:
    print(file.table, file.path, file.rows, file.bytes)
```

`write_tables(benchmark, scale_factor, output_dir, format="parquet",
compression=None, threads=None, parts=1, seed=None)` writes one `<table>.<format>` file per
table (`format` is `"parquet"` or `"tbl"`; Parquet compression is `"none"`,
`"snappy"` (default), `"gzip"` or `"zstd"`; `.tbl` is uncompressed). With
`parts > 1` each table except `nation` and `region` is split into
`<table>.<format>.<part>` files (for example `lineitem.tbl.3`, the same shard naming BenchBox uses). `threads=None` uses every available CPU.
`generate_table` takes the same `seed`. Seeded synthetic benchmarks (such as `ssb`, `clickbench`, and the other seeded generators) default to 42;
passing a seed to an unseeded benchmark (`tpch`) raises `ValueError`.

## Deterministic synthetic generators

Every generator that is not a TPC tool follows one contract, implemented in
`benchbox-datagen-core`'s `synthetic` module. Changing any part of it changes
the output and is a generator version bump that refreezes the golden hashes.

- **Fixed blocks.** A table is produced in blocks of 65,536 rows; block `b`
  holds rows `[b * 65,536, (b + 1) * 65,536)`. A block is a pure function of
  `(benchmark, table, scale factor, seed, b)`, so any number of threads
  produces the same bytes. The existing ordered pipeline consumes blocks in
  index order, `.tbl` writes them as they arrive, and the Parquet writer
  regroups them into 122,880-row groups.
- **Independent streams.** Each block draws from its own ChaCha8 stream
  (`rand_chacha`, pinned to an exact version) keyed by `(benchmark, table,
  stream name, seed, block)`. The 256-bit key is derived with FNV-1a 64 over
  the domain string `benchbox-datagen/synthetic/v1` and the names, then over
  the seed as its own 8-byte field (so no seed can alias another stream's
  names), then a SplitMix64 finalizer over the block index. A table may use
  several named streams (SSB `lineorder` uses `fields` and `orders`).
- **Owned sampling.** Bounded integers use an unbiased widening multiply with
  Lemire rejection (32-bit draw for bounds up to 65,536, 64-bit otherwise), floats use the top 53 bits of a
  draw, choices and word lists index a slice, weighted choices search a
  cumulative integer table, and dates use integer civil-calendar arithmetic.
  Nothing depends on the platform's floating-point library; any
  transcendental function must come from the pure-Rust `libm` crate.
- **Cross-block state** (for example SSB order numbering) comes from a
  separate cheap stream that is summed over whole orders (a prefix pass built
  only up to the block being generated and checked for cancellation between
  blocks), never from sequential generation, so blocks stay independent.
- **Rows and parts.** A table implements `schema()`, `rows()` and
  `block(index) -> RecordBatch`. `parts` splits a table into contiguous row
  ranges (blocks are sliced at the range edges), so concatenating the part
  files reproduces the single file byte for byte. Small dimension tables
  (`ssb.date`) are never split.
- **Text output.** One text form per Arrow type, shared by every synthetic
  generator (the SSB bytes are unchanged). Lines end in `\n`; a null is an empty
  field. A table declares its delimited-text properties once (`Generator::text_format`):
  the delimiter (default `|`), a header row (default none) and the file
  extension (default `tbl`; the CSV preset is `csv`, with RFC 4180 quoting of
  fields that contain the delimiter, a quote or a newline, and `""` for an empty
  string so it differs from a null). A header is written on part 1 only (also for a table with no rows), so
  concatenating the parts still reproduces the single file. Nothing else is
  per-generator code.

  | Arrow type | Text | Legacy evidence |
  | :--- | :--- | :--- |
  | `int32`, `int64` | plain decimal | all eight generators |
  | `date32` | `YYYY-MM-DD` | `strftime("%Y-%m-%d")`, `date.isoformat()` in `amplab`, `clickbench`, `coffeeshop`, `tpch_skew` |
  | `timestamp[us]` | `YYYY-MM-DD HH:MM:SS`, plus `.ffffff` only when the microseconds are not zero (Python `str(datetime)`) | `strftime("%Y-%m-%d %H:%M:%S")` in `h2odb`, `tsbs_devops`, `clickbench` |
  | `float`, `double` | shortest round-trip digits in Python `repr` layout (`0.1`, `1.0`, `1e-05`, `1e+16`, `nan`, `inf`) | `h2odb` and `amplab` write Python floats through `csv`/`str` |
  | fixed-scale `double` (`Kind::Fixed(n)`; the scale travels as the field metadata `benchbox.fixed_scale`, so a table cannot forget it) | `n` decimals (`1.50`), ties to even (`0.125` is `0.12`) | `tsbs_devops` metrics and `coffeeshop` prices use `f"{x:.2f}"` |
  | trimmed `decimal128(p, s)` (`Kind::DecimalTrimmed(p, s)`; field metadata `benchbox.trimmed_decimal`) | Python `repr(float(x))`: trailing zeros dropped, at least one decimal (`2.5`, `1.0`, `-0.05`), exponent form below `1e-4` (`1e-05`) and from `1e16` | legacy `h2odb` lon/lat and `amplab` `adRevenue` decimals written as Python floats |
  | `decimal128(p, s)` | exactly `s` decimals, `-0.05`, no exponent | TPC-H style `dbgen` decimals; `h2odb`, `coffeeshop`, `amplab` declare `DECIMAL` columns |
  | `bool` | `true` / `false` | no legacy generator among the eight writes one; the form every target engine accepts |
  | `fixed_size_list<float>[n]` | `[v1,v2,...]`, each element `%.6g` | `vector_search._array_to_csv` (`f"{v:.6g}"` joined by `,`) |
  | `utf8` | raw bytes | all |

  Any other Arrow type (unsigned or 8/16-bit integers, other timestamp units or
  time zones, negative decimal scales, lists of other types) is reported as an
  error before the first byte is written. Parquet needs no text form and
  carries every type natively; it is round-trip tested for all of them.
- **Seeds.** A `u64` (`0` to `2**64 - 1`; Python raises `ValueError` outside that range), default 42. Row counts never depend on the seed.

### SSB

Tables, columns, types and value domains follow BenchBox's legacy
`random.Random(42)` generator; only the random stream changed. Row counts follow
the Star Schema Benchmark specification (O'Neil, O'Neil, Chen, "The Star Schema
Benchmark", Revision 3, 2009, Figure 1.1 and sections 2.2-2.6,
<https://www.cs.umb.edu/~poneil/StarSchemaB.PDF>) as implemented by the reference
`ssb-dbgen` (`driver.c`, `dss.h`, `build.c`; checked against
`eyalroz/ssb-dbgen` at `ae1e254` and `vadimtk/ssb-dbgen`):

| Table | Rows at scale factor `SF` | Source |
| :--- | :--- | :--- |
| `date` | 2,556 (1992-01-01 to 1998-12-30), all scale factors | paper section 2.6 ("7 years of days", no count); `vadimtk/ssb-dbgen` `driver.c` and `shared.h` (`NUM_DAYS 2556`); `eyalroz/ssb-dbgen` has 2,557 |
| `customer` | `30,000 * SF` | paper section 2.5; `driver.c` base 30000 |
| `supplier` | `2,000 * SF` | paper section 2.4; `driver.c` base 2000 |
| `part` | `200,000 * floor(1 + log2(SF))` for `SF >= 1` | paper section 2.3; `driver.c` `rowcnt = base * floor(1 + log(scale)/log(2))` |
| `lineorder` | `6,000,000 * SF` | paper section 2.2 and Figure 1.1 (`ORDERS` `SF*1,500,000`, `LO_LINENUMBER` 1-7); `driver.c` order base 150,000 x 10, `O_LCNT_MIN/MAX` 1-7 |

For `SF < 1` the reference scales every base count by `SF` (truncated, at least
1), so `part` is `200,000 * SF`; the library keeps `date` at 2,556 because the
reference's own scaling of the date base would leave foreign keys without a
parent. For non-integer `SF >= 1` the reference truncates `SF` to an integer
first; the library scales `customer`, `supplier` and `lineorder` linearly and
takes `floor(log2(SF))` of the exact `SF` (computed from the float exponent, no
libm). `lineorder` is exactly `6,000,000 * SF` rows (row counts never depend on
the seed): orders are runs of consecutive rows, each order draws 1-7 lines
uniformly, and the final order is cut at the row count, so the order count is
`1,500,000 * SF` within sampling noise. Order `n` (from 1) has
key `((n >> 3) << 5) + (n & 7)`, the reference `mk_sparse` mapping for the paper's
"first 8 of each 32 keys populated", and line numbers restart at 1. `date` is
byte-identical to legacy `date.tbl` for its 2,556 rows, apart from line endings
(the legacy writer emits CRLF) and the legacy 2,557th row.

`tools/synthetic_acceptance.py ssb ...` (config in `tools/synthetic_configs/ssb.py`)
produces the legacy-versus-library comparison,
foreign-key and uniqueness checks and the 13-query DuckDB/DataFusion agreement
that gate the frozen goldens in `crates/benchbox-datagen-core/tests/ssb.rs`.

Acceptance rules: a distribution metric passes inside the min-max of 5 legacy
seeds (42-46), inside their 99.9% prediction interval, or (boundary quantiles of
low-cardinality columns) by rank. For the date-valued `lo_orderdate` and
`lo_commitdate` the legacy statistics drop the rows whose order date is
1998-12-31, the one day the two calendars do not share, and the same rule
applies, except that the distinct count is compared instead of the distinct
ratio (the filter changes only the legacy denominator). `date` columns are compared by a digest of the shared rows. A query
that legacy never leaves empty on seeds 42-46 must never be empty in the library
on seeds 42-46. A query that legacy leaves empty on any of seeds 42-46 is judged
on 30 seeds per side (42-71) at that scale: the library fails only if its
empty-seed count is higher than legacy's with one-sided Fisher exact p < 0.001
(5 against 5 seeds cannot reach that p-value).

The seeds are fixed in `tools/synthetic_configs/base.py` (`SEEDS` = 42-46 and
`EXTENDED_SEEDS` = 42-71, the 99.9% interval constant is the Student t value for
those 4 degrees of freedom); a config cannot change them.

Every Arrow kind has a statistic. Each column is reduced to one number per row,
then summarised by null rate, distinct ratio, mean and the 1/25/50/75/99%
quantiles: strings by their length; integers, floats, decimals as the value;
booleans as 0/1; dates and timestamps as microseconds since the epoch
(`epoch_us`); vectors (`fixed_size_list<float>[n]`) as the population standard
deviation of their components, which pins the dimension and normalisation
without being sensitive to the sign pattern. Arrow type names are normalised
(`date32[day]` is `date32`) and an unmapped type raises `ValueError` rather than
being skipped. Legacy files are read by the config's `legacy_suffix` (default
`tbl`), `legacy_delimiter` (default `|`) and `legacy_header` (default false);
`tests/test_synthetic_acceptance_types.py` runs the whole statistic and compare
path on a CSV/Parquet fixture that has every kind.

`table_scales(benchmark, scale_factor)` reports each table's `id_count` and `source_rows`.
`active_locations("tpcds", scale_factor)` returns the dsqgen `rowcount()` inputs
`active_cities`, `active_counties` and `active_states` (TPC-DS only; TPC-H and SSB raise
`ValueError`). They equal what the patched `dsqgen` returns for `rowcount("active_cities")`
and friends at integer scale factors of 1 or more, and below 1 they are 1, the value the
patched `dsdgen` store, call center, warehouse and web site addresses draw from. Templates
apply `rowcount("active_x", "store")`, which is the smaller of the value and the store
`id_count`.

`key_ranges` has no entries for the six returns tables. Their order and ticket numbers
are a data-dependent subset of the matching sales range, so no exact bounds exist
without generating the returns rows; the bounds of the sales range would be only a
superset, and are left out so that every reported range is exact.

### H2ODB

One table, `trips` (22 columns, the BenchBox `h2odb` schema: `int64`, `timestamp[us]`,
`decimal128(8, 2)`, `decimal128(18, 14)` and `utf8`, every column nullable as in the
BenchBox DDL). Files are `trips.tbl` (`|`, no header, `\n`) or `trips.parquet`. The
table has exactly `10,000,000 * SF` rows (truncated, at least 1; the legacy generator
writes `int(10,000,000 * SF)`), independent of the seed, and splits into parts
like any other fixed-block table. There are no keys or foreign keys; `key_ranges` is empty.

Value domains follow BenchBox's legacy `random`-based generator
(`benchbox/core/h2odb/generator.py`) and only the random stream changed:

| Column | Rule |
| :--- | :--- |
| `pickup_datetime` | uniform day in 2015-01-01 to 2019-12-31, hour drawn with the legacy weights (0.02, 0.01, 0.01, 0.01, 0.02, 0.03, 0.05, 0.07, 0.08, 0.09, 0.09, 0.08, 0.08, 0.08, 0.08, 0.09, 0.10, 0.11, 0.10, 0.09, 0.08, 0.06, 0.04, 0.03, held as integers), minute and second uniform |
| `dropoff_datetime` | pickup plus 5 to 120 minutes, uniform |
| `vendor_id`, `rate_code_id`, `payment_type` | uniform 1-2, 1-6, 1-4 |
| `passenger_count` | 1-6 with weights 70, 15, 8, 4, 2, 1 |
| coordinates | uniform on the 6-decimal grid inside the NYC box (longitude -74.2591 to -73.7004, latitude 40.4774 to 40.9176), stored in `decimal128(18, 14)` |
| `trip_distance` | `69 * sqrt(dlat^2 + dlon^2)` rounded to cents, clamped to 0.10-50.00 (the integer coordinate differences go through one correctly rounded `f64::sqrt`) |
| `fare_amount` | `2.50 + 2.50 * trip_distance` in cents |
| `extra` | uniform 0.0, 0.5, 1.0 |
| `tip_amount` | `fare * U(0.10, 0.25)` in cents when `payment_type = 1`, otherwise 0.00 |
| `tolls_amount` | 0.00 / 5.54 / 8.50 with weights 90, 7, 3 |
| `congestion_surcharge` | 0.00 / 2.50 with weights 70, 30 |
| `mta_tax`, `improvement_surcharge` | 0.50 and 0.30 |
| `total_amount` | the exact sum of the seven fare components |
| `store_and_fwd_flag` | `Y` 5%, `N` 95% |
| `pickup_location_id`, `dropoff_location_id` | uniform 1-263 |

Timestamps are whole seconds, so the delimited form is `YYYY-MM-DD HH:MM:SS` like the
legacy `strftime`. Every decimal column is `Kind::DecimalTrimmed`, so the delimited form is the Python float text the legacy `csv` writer produced (`3.5`, `-73.912345`); the Parquet output stores exact decimals.

`tools/synthetic_acceptance.py h2odb ...` (config in `tools/synthetic_configs/h2odb.py`)
produces the legacy-versus-library comparison for the ten queries and gates the frozen
goldens in `crates/benchbox-datagen-core/tests/h2odb.rs`. The legacy table has no key, so
the duplicate check uses the natural key (`pickup_datetime` with the four coordinates).
`trips` uses `bounded_output = true` (streaming Parquet row groups incrementally and
bounding delimited buffering) and rejects scale factors whose row count would exceed
`2^53`.

### ClickBench

The synthetic `hits` table follows BenchBox's legacy `ClickBenchDataGenerator`
(`benchbox/core/clickbench`): the same 105 columns in the same order, the same
value domains and the same per-column distributions (uniform integers over the
legacy ranges, uniform picks from the legacy value lists with the legacy empty-string
padding, `EventTime`, `ClientEventTime` and `LocalEventTime` equal and
uniform over 2013-07-01 00:00:00 to 2013-07-31 23:59:59, `EventDate` their date,
`RegionID` repeated as `RefererRegionID` and `URLRegionID`, `URL` repeated as
`OriginalURL`, the resolution pair repeated as the window size, `MobilePhone`
equal to `IsMobile` and a phone model only on mobile rows); only the random stream
changed. The BenchBox Arrow schema has `int64` for every `BIGINT`, `INTEGER` and
`SMALLINT` column, `utf8` for `TEXT` and `VARCHAR`, `timestamp[us]` and `date32`,
all non-nullable.

| Table | Rows at scale factor `SF` | Source |
| :--- | :--- | :--- |
| `hits` | `max(1, floor(1,000,000 * SF))` | legacy `int(1_000_000 * scale_factor)` |

Delimited output is `hits.csv`: `|`-separated, no header, an empty string written as
`""` (legacy `quote_clickbench_field`), timestamps as `YYYY-MM-DD HH:MM:SS`, dates
as `YYYY-MM-DD`. The legacy writer ends lines with CRLF; the shared synthetic text
writer ends them with LF. `hits` has no foreign keys, so `key_ranges` is empty.
Its legacy primary key `(CounterID, EventDate, UserID, EventTime, WatchID)` is
unique with overwhelming probability rather than by construction, as in legacy.
The ClickBench queries are translated from ClickHouse SQL through
`ClickBenchBenchmark.get_queries(dialect="datafusion")` in
`tools/synthetic_configs/clickbench.py` with every column name double-quoted,
because DataFusion lowercases unquoted identifiers and the Parquet columns are
mixed case. `hits` uses 16,384-row blocks with `bounded_output = true` (streaming
Parquet row groups incrementally and bounding delimited buffering) and rejects
scale factors whose row count would exceed `u64::MAX - 16_384`.

### TPC-H skew

`tpch_skew` is the TPC-H stream of this library with the skew pass of BenchBox's
`TPCHSkewDataGenerator` applied while the rows are produced (no intermediate files).
Tables, columns, types, delimiter (`|`, `.tbl`, no header) and row counts are those of
`tpch`; every table has the TPC-H row count at every supported scale factor, and
`key_ranges` and `table_scales` equal the `tpch` values. The pass implements the legacy
default, the `moderate` preset (`skew_factor` 0.5, Zipfian, attribute and join skew on,
temporal skew off), which is what `TPCHSkewBenchmark()` uses without arguments. The
other presets (`none`, `light`, `heavy`, `extreme`, `realistic`) and custom
`SkewConfiguration` objects are not available through the library (the generator takes
only a scale factor and a seed).
TPC-H scale factors work as in `tpch`: there is no scale cap, memory does not grow with the
scale factor (see below), and `partsupp` and `lineitem` need at least four suppliers
(`int(10,000 * SF) >= 4`; smaller scale factors return `Error::TooFewSuppliers` from both
`tpch` and `tpch_skew`).

| Table | Column | Replacement (legacy `_generate_skewed_values`) |
| :--- | :--- | :--- |
| `customer` | `c_nationkey` | Zipf, exponent 1.0, over 0-24 |
| `customer` | `c_mktsegment` | Zipf, exponent 0.8, over the 5 segments |
| `part` | `p_brand` | Zipf, exponent 1.0, over `Brand#11`-`Brand#55` |
| `part` | `p_type` | Zipf, exponent 0.6, over the legacy list of 20 types |
| `orders` | `o_custkey` | Zipf, exponent 1.0, over `1..int(150,000 * SF)` |
| `orders` | `o_orderpriority` | Zipf, exponent 0.6, over the 5 priorities |
| `lineitem` | `l_partkey` | Zipf, exponent 1.0, over `1..int(200,000 * SF)` |
| `lineitem` | `l_suppkey` | Zipf, exponent 0.8, over `1..int(10,000 * SF)` |
| `lineitem` | `l_shipmode` | Zipf, exponent 0.8, over the 7 ship modes |

The Zipf exponent is twice the attribute's skew value, as in the legacy code. The
sampled rank is exact, then projected to the value range using the legacy
floating-point calculation. At some domain sizes this maps adjacent ranks to
the same key, so replacing the projection with integer addition would increase
the number of distinct keys.
Every other column, and `nation`, `region`, `supplier` and `partsupp`, are the `tpch` stream
unchanged (the four unchanged tables are byte-identical to `tpch` output).

Each skewed column draws from its own block stream (`tpch_skew`, table, column name, seed,
block); the replaced column of block `b` does not depend on any other block. The TPC-H rows
under a block come from `tpcgen-rs` chunks of about 512 driver rows (orders for
`lineitem`, parts for `partsupp`) that cover the block, so a block regenerates at most a
chunk on each side; `lineitem` chunk offsets come from one pass over the order line counts
(the same RNG that gives the exact `lineitem` row count). Zipf ranks are sampled in
constant space using rejection sampling and pure-Rust `libm` functions.

`tools/synthetic_acceptance.py tpch_skew ...` (config in
`tools/synthetic_configs/tpch_skew.py`) compares against the legacy generator run with
`SkewPreset.MODERATE` and seeds 42-46. The 22 TPC-H queries use BenchBox's default
`qgen` texts at the actual scale factor. The legacy generator's TPC-H base data is `tpch`, so base columns
need no exclusion. The tests in `crates/benchbox-datagen-core/tests/tpch_skew.rs` freeze
the golden hashes.

### Coffeeshop

Tables, columns, types, patterns and seed data are those of BenchBox's legacy
`CoffeeShopDataGenerator`, which has no random numbers at all: it spreads
orders over days, regions and locations by largest-remainder apportionment and
fills every other field from fixed repeating patterns. The library reproduces
that arithmetic in closed form, so any row is a pure function of its row index
and a block never needs the rows before it. The seed is accepted for API
uniformity and has no effect, as in the legacy generator (all five legacy
seeds give the same files). Delimited files are comma-separated CSV without a
header, like legacy, with `decimal128(8, 2)` / `decimal128(10, 2)` prices
written with two decimals; `order_time` is `utf8` (`HH:MM:SS`), the arrow type
BenchBox's converter assigns to `TIME`.

| Table | Rows at scale factor `SF` | Source |
| :--- | :--- | :--- |
| `dim_locations` | 1,000, all scale factors | vendored seed file `benchbox/data/coffeeshop/dim_locations.csv` (500 South, 250 Southeast, 250 West) |
| `dim_products` | 26, all scale factors | vendored seed file `dim_products.csv` (13 products in two availability windows, 2022-01-01..2023-02-28 and 2023-03-01..2024-12-31) |
| `order_lines` | `156 * floor(N / 100) + (lines of the first N mod 100 orders)` with `N = max(1, round(8,500,000 * SF))` | legacy `calculate_order_count` and the 100-order line-count cycle (60 x 1, 30 x 2, 5 x 3, 4 x 4, 1 x 5 lines) |

`order_lines` is `13,260,000` rows at `SF 1` (8,500,000 orders). Order `k`
(from 1) is placed on the day, region and location given by the legacy
apportionment (month weights, a linear trend from 0.85 to 1.20, region weights
1.25 / 1.10 / 0.90, equal location weights, Python 3.12 `sum` for the weight
totals), carries `ORDER_LINE`, `TIME` and per-line `SUBCATEGORY`, `QUANTITY` and
price-multiplier values from the legacy cycles indexed by order or line number,
and takes its product from a per-window, per-subcategory rotation. Unit prices
are `round(price * multiplier, 2)` computed in binary floating point exactly as
in legacy; total price is `unit price * quantity` in cents. Because nothing is
sampled, the library's `order_lines` is identical to the legacy file at every
scale factor (see `delimited_output_equals_the_legacy_files_apart_from_line_endings`)
apart from line endings: the legacy writer emits CRLF, the library `\n`.

`tools/synthetic_acceptance.py coffeeshop ...` (config in
`tools/synthetic_configs/coffeeshop.py`) produces the comparison that gates the
frozen goldens in `crates/benchbox-datagen-core/tests/coffeeshop.rs`. The
dimension files are embedded from `crates/benchbox-datagen-core/src/synthetic/coffeeshop_data/`.

The acceptance queries are BenchBox's eleven queries with default parameters; TM1
casts the stored `order_time` text with `CAST(ol.order_time AS TIME)` because the
Arrow schema carries `TIME` as `utf8`. Dual-engine verification runs at scale
factors 0.01, 0.1 and 1: at SF 10 DuckDB and DataFusion together exceed the 8 GiB
heavy-work limit, so SF 10 is covered by the row-count tests and the wall-time and
peak-RSS measurements. DuckDB and DataFusion return the same row count for every
query; their values differ only where DataFusion divides decimals at scale 6 and
where it divides integers (`SUM(quantity) / COUNT(DISTINCT order_id)` in SA3 and
QC1).

### joinorder_synthetic

Tables, columns, types, value domains and the planted golden entities follow
BenchBox's legacy `JoinOrderGenerator` (`benchbox/core/joinorder_synthetic/generator.py`,
`random.seed(42)`, schema in `benchbox/core/joinorder/schema_specs.yaml`); only the
random stream changed. The data is uniformly random with no real IMDb content.
Output is comma-delimited `.csv` with no header (`Generator::text_format` is
`TextFormat::csv(b',', false)`; a null is an empty field), as the legacy files are,
and Parquet. Every column is `int64` or `utf8`; `id` columns are nullable in the Arrow
schema because the legacy schema declares them so, `NOT NULL` columns are not.

| Table | Rows at scale factor `SF` |
| :--- | :--- |
| `kind_type`, `company_type`, `info_type`, `role_type`, `comp_cast_type`, `link_type` | 7, 4, 24, 12, 4, 18 (constant; the legacy `info_type` holds 24 rows although its row-count table says 113) |
| `title` | `trunc(500,000 * SF) + 60` |
| `name` | `trunc(800,000 * SF) + 60` |
| `company_name` | `trunc(60,000 * SF) + 60` |
| `keyword` | `trunc(24,000 * SF) + 60` |
| `char_name` | `trunc(600,000 * SF)` |
| `cast_info` | `trunc(7,000,000 * SF)` |
| `movie_companies` | `trunc(520,000 * SF)` |
| `movie_info` | `trunc(3,000,000 * SF)` |
| `movie_info_idx` | `trunc(280,000 * SF)` |
| `movie_keyword` | `trunc(1,000,000 * SF)` |
| `movie_link` | `trunc(6,000 * SF)` |
| `person_info` | `trunc(600,000 * SF)` |
| `complete_cast` | `trunc(30,000 * SF)` |
| `aka_name` | `trunc(180,000 * SF)` |
| `aka_title` | `trunc(80,000 * SF)` |

Row counts are closed-form in `SF` and never depend on the seed. The minimum
supported scale is 0.01. The maximum is constrained by signed 64-bit row IDs,
with room for the final block and planted rows.

The four entity tables end with 60 planted golden rows (ids `trunc(base * SF) + 1`
onward) that the benchmark queries target. As in legacy, the first 60 rows of
`cast_info`, `movie_companies`, `movie_info`, `movie_keyword`, `movie_link`,
`complete_cast` and `aka_name` are rewritten to point at them (a fixed function of
the row index, so blocks stay independent); the random foreign keys of every other row
draw uniformly from `1..trunc(base * SF)`, so the golden rows are never drawn by chance.
Probabilities that legacy draws as floats (`random() < 0.30`) are exact integer ratios
(`below(1000) < 300`). The `movie_info_idx` rating (`uniform(1, 10)` formatted `%.1f`) is
drawn as an integer number of tenths with the same bucket weights (1.0 and 10.0 have
half the weight of the others).

Legacy draws `person_info.info_type_id` from `1..113` although `info_type` has
only 24 rows. The library repairs this foreign key by drawing uniformly from
`1..24`. Acceptance compares this column against only legacy rows in that
domain; all other columns are compared over their complete tables. All declared
foreign keys, including nullable ones, are checked on their non-null values.
`cast_info.person_role_id` is null in 30% of rows; many columns (`imdb_index`,
`imdb_id`, `*_pcode_*`, `md5sum`, ...) are always null.
Every benchmark query is an ungrouped `MIN(...)` aggregate, so it returns exactly one
row even when no data matches; row counts cannot show an empty result for this
benchmark, and the one-row result is all `NULL` in that case.

`tools/synthetic_acceptance.py joinorder_synthetic ...` (config in
`tools/synthetic_configs/joinorder_synthetic.py`) produces the comparison with 5
legacy seeds (the legacy generator is seeded by replacing its module-level
`random` with a `random.Random(seed)`), the key checks and the 113-query
DuckDB/DataFusion agreement that gate the frozen goldens in
`crates/benchbox-datagen-core/tests/joinorder_synthetic.rs`.

### AMPLab

Tables, columns, types and value domains follow BenchBox's legacy
`AMPLabDataGenerator` (the AMPLab big data benchmark: `rankings`, `documents`,
`uservisits`, written as `|`-separated `.tbl` without header); only the random
stream changed. Row counts are the legacy `int(base * SF)` for any scale factor
(no minimum, so a scale factor below `1 / base` gives an empty table):

| Table | Rows at scale factor `SF` |
| :--- | :--- |
| `rankings` | `250,000 * SF` |
| `documents` | `125,000 * SF` |
| `uservisits` | `2,500,000 * SF` |

`pageURL` and `url` are `http://<domain>/<path>/<n>` with `n` the 1-based row
number and a uniformly drawn domain (15) and path (6), so they are unique.
`uservisits.destURL` uses the same form with `n` uniform in `1..rankings` (80%) or
`rankings+1..rankings+50,000` (20%) and its own independent domain and path draws, so,
as in legacy, it matches a `rankings.pageURL` only by coincidence of domain and path
and the tables have no foreign key. `pageRank` is `floor(10 * Pareto(1.16))` capped
at 10,000, sampled by inversion against a table built with the pinned pure-Rust
`libm` crate (`libm::pow`). `adRevenue` is `0` (90%) or a uniform amount between 0.01 and
5.00 rounded to cents (10%); `searchWord` is null for half the rows. `visitDate`
is uniform over 2000-01-01 to 2000-03-31; delimited `adRevenue` is unpadded
like legacy (`0.0`, `2.5`). The maximum scale factor leaves room for the final block
boundary and signed URL and destination ID arithmetic.

`tools/synthetic_acceptance.py amplab ...` (config in
`tools/synthetic_configs/amplab.py`) produces the legacy-versus-library
comparison and the query agreement that gate the frozen goldens in
`crates/benchbox-datagen-core/tests/amplab.rs`; the rules are those of SSB.

### TSBS DevOps

Tables, columns, types, value formulas and the comma-separated CSV layout (a
header row, `.csv` files, timestamps as `YYYY-MM-DD HH:MM:SS`, metric doubles
with two decimals) follow BenchBox's legacy `TSBSDevOpsDataGenerator`
(`benchbox/core/tsbs_devops/generator.py`, default 2 days at a 10 second
interval from 2024-01-01 00:00:00); only the random stream changed. The rows
are fixed tables whose counts are closed forms of the scale factor, with
`H = max(10, floor(100 * SF))` hosts and `T = 17,280` timestamps per series:

| Table | Rows | Series layout |
| :--- | :--- | :--- |
| `tags` | `H` | `host_0` .. `host_{H-1}`; region, datacenter and rack cycle with the host index, the other tags are drawn |
| `cpu` | `H * T` | host-major, one series per host |
| `mem` | `H * T` | host-major, one series per host |
| `disk` | `2 * H * T` | host-major, devices `sda` then `sdb` per host |
| `net` | `2 * H * T` | host-major, interfaces `eth0` then `lo` per host |

Scale factors below 0.1 all give the 10-host minimum, so `0.01` and `0.1`
have identical row counts. `cpu` and `mem` draw per-host constants (the base
CPU load, the memory size and base utilisation) from a `hosts` stream keyed by
the host index, and every row from a `fields` stream keyed by the row block.
The `disk` and `net` counters are running sums over a series, so each series
has its own stream keyed by the series index and a block replays the series
from its first step up to the last row the block needs (at most one 17,280-step
series of extra draws per block, no shared state between blocks). The diurnal
CPU factor uses the 13 constant sines `sin(k * pi / 12)` rather than a runtime
sine. Queries are the legacy `TSBSDevOpsQueryManager` queries; the acceptance
config renders them with 10 hosts, 2 days and seed 42 so that every host the
queries name exists at every scale. `key_ranges` is empty: the only keys are
hostnames and timestamps.

The CPU and memory metric doubles are rounded to two decimals when generated
(the legacy files hold `f"{x:.2f}"` text, which BenchBox's converter turns into
Parquet), so the Parquet values and the delimited text agree. `tools/synthetic_acceptance.py tsbs_devops ...` (config in
`tools/synthetic_configs/tsbs_devops.py`) produces the legacy-versus-library
comparison, the key checks and the 18-query DuckDB/DataFusion agreement that
gate the frozen goldens in `crates/benchbox-datagen-core/tests/tsbs_devops.rs`.
Only the `value_set` metric for `tags.team`, `tags.service`,
`tags.service_version`, and `tags.service_environment` is excluded when there
are exactly 10 hosts and the five legacy sets differ; every other statistic
remains gated. Native generation supports the legacy default duration, interval,
and start time only; the legacy `num_hosts`, `duration_days`,
`interval_seconds`, and `start_time` overrides cannot be expressed.
The maximum scale factor is constrained by `floor(100 * SF)` hosts and the
largest table's `34,560 * hosts` rows, with room for a final block boundary.

### vector_search

Tables, columns, types and value domains follow BenchBox's legacy
`VectorSearchDataGenerator` (`numpy.random.default_rng(42)`); only the random
stream changed.

| Table | Rows at scale factor `SF` | Columns |
| :--- | :--- | :--- |
| `vectors` | `max(1, floor(1,000,000 * SF))` | `id` (1 to N), `embedding` (`fixed_size_list<float>[128]`), `category` (`category_01` to `category_10`), `doc_id` (`doc_<id>`) |
| `vector_queries` | 100 at every scale factor | `query_id` (1 to 100), `query_vector` (`fixed_size_list<float>[128]`) |

`category` is `category_{id % 10 + 1:02d}` and `doc_id` is `doc_{id}`, exactly as
in the legacy generator; only the embeddings are random. Each vector is 128
independent standard normal draws divided by the Euclidean norm of the row (unit
length), drawn per block of 32,768 rows (`Table::block_rows`, 16 MiB of floats per block) from the `embedding` stream of its table.
The normals come from the Marsaglia polar method; its logarithm is
`libm::log`, so nothing depends on the platform's floating-point library. The
dimension is fixed at 128 (the legacy `dimensions` constructor option is not a
scale and is not supported). Delimited output is the legacy file form: `|`
delimiter, a header row, `.csv` extension, `[v1,v2,...]` vectors with each
element at `%.6g`. `vector_queries` is a single small file and is never split
into parts. The query vectors do not depend on the scale factor.

`tools/synthetic_acceptance.py vector_search ...` (config in
`tools/synthetic_configs/vector_search.py`) produces the legacy-versus-library
comparison and the DuckDB/DataFusion agreement that gate the frozen goldens in
`crates/benchbox-datagen-core/tests/vector_search.rs`. The config's queries are
engine-neutral rewrites of the six BenchBox queries (cosine and L2 scores from
`unnest` and `sum`, `id` only, because DuckDB reads Parquet vectors as lists and
the two engines share no vector function and no bit-identical float score).

## Adding a synthetic generator

A synthetic generator is one Rust module plus one registry entry (one line),
one Python config file and one schema file; nothing else is edited.

1. **Module.** Add `crates/benchbox-datagen-core/src/synthetic/<name>.rs` with a
   unit struct that implements `synthetic::Generator`: `name`, `tables`,
   `schema` (build it with `schema::build` from a column list kept in the
   module), `row_count`, `open` (returns a `Table` whose `block(index)` is a
   pure function of the block index and the seed), `key_ranges`, and, only when
   the defaults are wrong, `splittable` (default: every table splits) and
   `table_scales` (default: `id_count == source_rows == row_count`). Refresh
   sets are unsupported for every synthetic benchmark. Column types come from
   `schema::Kind` (`Int`, `Int32`, `Decimal`, `Decimal128`, `Float32`,
   `Float64`, `Fixed`, `Bool`, `Timestamp`, `Date`, `Text`, `Vector`); a table whose
   legacy files are not `|`-separated `.tbl` overrides `text_format` (see Text
   output above).

   **Block size.** Rows are generated in blocks of `Table::block_rows()` rows
   (default `synthetic::BLOCK_ROWS` = 65,536). A block is generated whole, and
   the pipeline holds up to about `2 x threads` blocks in flight, so peak memory
   is roughly that many blocks. Leave the default for narrow rows. For wide rows
   (amplab documents about 2.5 KB per row, vector_search 128 floats per row)
   override `fn block_rows(&self) -> u64` on the `Table` so one block is about
   16 MiB of Arrow data: `16 MiB / bytes per row`, for example 6,500 rows at
   2.5 KB or 32,768 rows at 512 B. Inside `block(index)` use
   `block_len_in(self.rows(), index, self.block_rows())` for the row count and
   `index * self.block_rows()` for the first row; `block_len` and `BLOCK_ROWS`
   are the default-size forms. Part slicing, the header (first part only),
   `warm` and the single-file chunking all follow the declared size. Parquet row
   groups stay at 122,880 rows whatever the block size, so a Parquet writer
   still buffers one row group of wide rows. The block size is part of the
   output only through what `block(index)` derives from the index (for example
   per-block random streams), so changing it on an existing table changes its
   data unless the table derives values from the row number.
   For a wide table whose measured default-thread peak exceeds its budget,
   override `Generator::bounded_output(table)` for that table. This streams one
   block at a time and serializes parts; Parquet uses a single incremental encoder
   with the same row-group size and writer properties. Existing tables should not
   opt in without validating their output identity and memory budgets.

   **Row counts and key ranges are closed-form functions of the scale
   factor, not of the seed**: `row_count`, `key_ranges` and `table_scales` take
   no seed, and a part is a row range of a fixed-size table. A table whose
   child count varies per parent (SSB's 1-7 `lineorder` lines per order,
   coffeeshop's `order_lines`) follows SSB: the table has a fixed row count
   (the legacy mean times the scale), the cursor that assigns rows to parents
   is seeded, and the order-structure columns are listed in the config's
   `exclusions` with a reason because legacy and library differ there by
   construction.
2. **Registry.** In `synthetic/mod.rs` add `mod <name>;` and append
   `&<name>::<Struct>` to `REGISTRY`. The registry is one entry per line, so
   parallel additions merge mechanically (the `mod` lines and the entries are the
   only shared lines, and a conflict there is resolved by keeping both); Python
   names, `table_names`, `row_counts`, `table_scales`, `key_ranges`, the seed
   default, `write_tables` and `generate_table` all follow from it.
3. **Schema file.** Add `tests/data/<name>_arrow_schemas.json`, produced with
   `tools/dump_benchbox_schemas.py <name>` from the BenchBox schema, and a
   Rust test with frozen SHA-256 goldens for `tbl` and `parquet` at the gate
   scales (see `crates/benchbox-datagen-core/tests/ssb.rs`).
4. **Config.** Add `tools/synthetic_configs/<name>.py` that defines `CONFIG =
   SyntheticConfig(...)`: tables, primary and foreign keys, `expected_rows`,
   the queries (a JSON `{id: sql}` file path or a callable), the legacy
   generator, `benchbox_schema` (for the schema dump tool), the budgets used by
   `tools/bench_budgets.py`, and the exclusions. Config files are discovered by
   file name, so no list needs editing. Every exclusion (column, whole table or
   data-dependent) needs a written reason; a blank reason raises.
   `budget_class` (`"tpch"` or `"tpcds"`, default none) judges the benchmark
   against that class's wall-time and RSS budgets from the ADR table instead of
   its own `budgets` (give one or the other; `budgets` is optional with a class): `tpch_skew` is TPC-H data with skew, so it uses the TPC-H
   budgets; every other synthetic generator keeps the synthetic budget.
   `stats_memory_limit` (default `"2GB"`) is the DuckDB memory limit of the
   legacy statistics run; statistics are computed in batches of 4 columns, so
   raise it only for very large tables.
5. **Evidence.** Run, for each scale in the config, `tools/synthetic_acceptance.py
   <name> legacy`, `library` (the same seeds), `compare` (add `*_queries`
   files for seeds 47-71 when legacy leaves a query empty) and `verify`, then
   `report`, and put the report in the PR. Required results, unchanged from
   SSB: every metric inside the legacy min-max or the 99.9% prediction
   interval of 5 legacy seeds, or, when it fails that on any library seed, not
   significantly different (two-sided Mann-Whitney U, normal approximation with
   tie correction, p >= 0.001) between the 30 legacy and 30 library values of
   seeds 42-71 (run `legacy` and `library` for seeds 42-71 and pass them as
   `compare --legacy-extended` and `--library-extended`; a missing seed stops
   with an error, and the report lists every re-judged metric with both
   30-value summaries and the p-value) (boundary quantiles of low-cardinality columns
   may pass by rank; a statistic that is identical in all 5 legacy seeds must
   be identical in the library when it is integer-valued, and equal within a
   relative 1e-9 otherwise, as is every constant mean, because summation order
   alone moves a float mean by about 1e-12 and that is numeric noise, not a
   distribution difference); queries never empty in legacy never empty in the
   library, otherwise 30 seeds per side with one-sided Fisher p >= 0.001; no
   orphan or duplicate keys (a NULL foreign key is not an orphan, so a
   nullable foreign key can be declared); every query returns the same row
   count in DuckDB and DataFusion (value differences are reported as warnings,
   and NaN on both engines agrees); wall-time and peak-RSS budgets met. Also run
   `cargo fmt`, `cargo clippy --all-targets -- -D warnings`, `cargo test`,
   `pytest tests` and `python3 tools/third_party_licenses.py --check`.
6. **Docs.** Add a section for the benchmark to this README next to SSB
   (tables, row-count rules, sources) and add it to the list at the top.

## Layout

| Crate | Role |
| :--- | :--- |
| `benchbox-datagen-core` | Generator registry, BenchBox Arrow schemas, row counts, Arrow batch streams and file output |
| `benchbox-datagen-writers` | Parquet and delimited writers |
| `benchbox-datagen-py` | The `benchbox_datagen._native` PyO3 module |

Wheels are built for CPython 3.11+ (`abi3`) on macOS arm64 and x86_64, Linux
glibc and musl (x86_64 and aarch64), and Windows x86_64 and arm64.

## Development

```bash
cargo fmt --check && cargo clippy --all-targets && cargo test
uv venv && uv pip install maturin pyarrow pytest
maturin develop --release && pytest tests
```

`tools/parity.py` compares library output with a directory of `dbgen`
output by SHA-256, and `tools/bench_budgets.py` measures the wall-time and
peak-RSS budgets from the design ADR (`--driver` measures a compiled driver
binary instead of the Python module).

## TPC-H query generation

`generate_query("tpch", ...)` is a Rust port of `qgen` covering queries 1–22 plus `15a`, `-d` default parameters, seed selection, and `:s` stream numbering. TPC-H templates and `dists.dss` stay in BenchBox and are passed at call time. `qgen -p` stream permutation is intentionally unsupported (BenchBox computes TPC-H stream order in Python) and raises `ValueError` when `permutation` is passed. Seed `0` on Q7 and Q12 raises `ValueError` instead of hanging.

## TPC-DS query generation

`generate_query("tpcds", ...)` and `generate_tpcds_streams(...)` are a Rust port of `dsqgen`. They interpret
the template language over BenchBox-supplied inputs only: the `.tpl` templates, the dialect template
(`netezza.tpl` is the only one BenchBox reaches) and the `tpcds.idx` distribution index, all passed at call
time. The port is TPC-derived code (`dsqgen/*.rs` follow the TPC-DS kit's `keywords.c`, `scaling.c`, `eval.c`, `genrand.c`, `permute.c` and `dsqgen` sources line by line), and it ships under the TPC legal notice in `THIRD_PARTY_LICENSES`; the files are listed in the table of generated and TPC-derived files under TPC-DS refresh sets. No TPC distribution file, template or query text is committed here. `rowcount()` comes
from the library scale model (sub-scale rules and `active_locations` included). `parameters=` renders explicit
values the way `DSQGenBinary.generate_with_parameters` does (it rewrites `[NAME.n]` tokens, then runs a seeded
dsqgen). The sub-SF1 `query93.tpl` override stays with the caller, as in BenchBox.

`tests/dsqgen_corpus.rs` replays the TPC-DS shards of the BenchBox query corpus (`tpcds_single`,
`tpcds_stream_template`, `tpcds_stream_all` and `tpcds_explicit`) against
the pinned `BENCHBOX_REF` checkout. `range()` and `list`/`ulist` on `text()` and `date()` are rejected with an error:
no BenchBox template uses them.

## Differences from C dsqgen

**ULIST longer than its key permutation.** `ulist(random(min, max, uniform), n)` evaluates through `EvalRandomExpr`
(`eval.c`), which shuffles a key permutation built by `makeKeyPermutation` (`permute.c`) holding `max - min + 1` keys and then
reads `n` entries with `getPermutationEntry`. When `rowcount()` makes the permutation smaller than `n`, the C tool reads past
the `malloc`ed array, so its output depends on glibc heap contents (the Q34 `-LOG` versus plain difference in the BenchBox
corpus). The library defines this case: entry `i` is entry `i % size`, so the shortest permutation repeats in order. The result is
deterministic on every platform and scale, identical across streams and runs for the same seed, and equal to C when the
permutation holds one key (the value is always the minimum).

A cell is affected wherever the available key count `n` is at least 2 and below the list length `k`. With `n` of 1 the value is always the minimum, so the wrap changes nothing and `wrapped` stays false. `n` follows `rowcount(...)` in the template, so it depends on the scale factor.

Examples, generated over the `dsdgen` scale grid (1, 10, 100, 300, 1000, 3000, 10000, 30000 and 100000), with `n` in brackets:

| Query | k | Scale factors (n) |
| :--- | ---: | :--- |
| 16 | 5 | 10 (3) |
| 27, 27a | 6 | 10 (3) |
| 34, 73 | 8 | 10 (3) |
| 36 | 8 | 10 (3) |
| 46 | 5 | 1 (2) |

No other query is affected on the grid. Scale factors off the grid vary: the API accepts any whole scale factor up to 100000, and for example Q16 at SF 6-9 (2), 50 (3), 200 (4), Q27, Q27a and Q36 at SF 6-9 (2), 2000 (5), 20000 (5), Q46 at SF 4 (3) and 7 (4) are affected too, so do not read the table as a list of every affected scale factor. `GeneratedStatement::wrapped` and `DsqgenQuery::wrapped` (the third element of `generate_query("tpcds", ...)`, the fourth of each `generate_tpcds_streams` query) say whether a draw wrapped.

The corpus replay takes the flag from the template and the scale model, not from a list. It excludes exactly the flagged cells; every other record matches. In `tpcds_explicit` only the seeded round-trip check is skipped for a flagged record, and the rewritten-template, explicit-text and alternate-seed checks still run. The C tool's values for flagged cells are not reproduced.

**qgen (TPC-H).** `qgen` seed 0 for Q7 and Q12 raises an error (the distinct-value draw never terminates in C), and a missing seed
requires `default_params=True` because `qgen`'s time-based seeding is not reproducible. BenchBox fails fast for seed 0 (PR #4558).

## TPC-DS refresh sets

Output matches the bundled `dsdgen -update <n> -terminate n` for every file a set contains.
Observed SHA-256 parity: scale factor 0.0001 (set 1), 0.003, 0.005, 0.008, 0.01 (set 1 and set
127), 1 (sets 1 to 7, and sets 1 and 2 with `rng_seed` 20260709), 10 (set 1) and 100 (set 1),
plus 0.05 and 0.5 (set 1). The hashes for scale factors 0.0001, 0.01 (sets 1 and 127), 1, 10
and 100 are committed in `tests/data/tpcds_refresh_sha256.json`; the scale factor 10 and 100
checks are opt-in (`BENCHBOX_DATAGEN_HEAVY=1 pytest tests/test_refresh.py`, under
`make heavy-run`).

Reproduce an oracle comparison with
`tools/oracle_tpcds_refresh.sh <dir with dsdgen and tpcds.idx> <scale> <sets> <out> [rng seed]`
(the optional seed is passed as `dsdgen -rngseed`) followed by
`python tools/parity_refresh.py --benchmark tpcds --dbgen-dir <out> --scale <scale> --sets <sets> [--rng-seed <seed>]`.
The comparison also fails if the oracle wrote a file the library did not.

Accepted scale factors and behaviours that follow `dsdgen`:

- Scale factors of 1 or more must be on the `dsdgen` scale grid: 1, 10, 100, 300, 1000, 3000,
  10000, 30000 or 100000. The bundled `dsdgen -update` aborts (exit 133) for every other scale
  factor of 1 or more (checked for every integer from 1 to 1100 and for 1500, 2000, 3001, 5000,
  10001, 20000, 30001, 50000, 99999, 100001 and 200000), so there is no oracle for them and
  `write_refresh` rejects them with `RefreshUnsupported` (a `ValueError` in Python) that lists
  the accepted scale factors, before creating the output directory or any file. Scale factors
  below 1 are accepted.
- A table with no rows in a set gets no file, as with `dsdgen` (which opens a file on its first
  row). At scale factor 0.0001 a set has 13 files; the `s_catalog_order`, `s_purchase`,
  `s_store_returns`, `s_web_order` and related files appear only as the scale factor grows
  (19 files at 0.003, 23 files from 0.008). The returned statistics list only the files written.
- `dsdgen` reads the calendar distribution's cumulative weights one entry past the end when
  it checks the day after 31 December in a leap year, and a missing cumulative entry reads as 0.
  The effective weight is therefore minus the set's total weight, which is non-zero, so a
  31 December date advances to 1 January instead of stepping back. Set 127 with the default seed
  hits this path (`delete_127.dat` starts `2000-12-31|2001-01-01`). The library reproduces the
  read (`Calendar::weight`); set 127 is checked against `dsdgen`.
- A failed or cancelled run removes only the files that run created; a file already at an
  output path is overwritten when the run reaches it and is never deleted.
- The generator returns errors, never panics, for out-of-range indexing or division by zero in
  scale-dependent tables.

Generated and TPC-derived files (each source file is covered by the TPC legal notice in
`THIRD_PARTY_LICENSES`, which `python tools/third_party_licenses.py --check` keeps in step with
this table; see [Licence](#licence) and BenchBox's `docs/tpc-licensing-analysis.md`):

| File | Source | Inclusion basis |
| :--- | :--- | :--- |
| `crates/benchbox-datagen-core/src/tpcds_update/columns.rs` | Generated, then formatted with `rustfmt --edition 2024`, by `python tools/gen_tpcds_columns.py <TPC-DS 4.0.0 kit>/tools/column_list.txt <out.rs>` from `column_list.txt` (the column list `mkheader` turns into dsdgen's `columns.h`: column name, table and random streams per row, numbered in file order; SHA-256 `37ffe20de438ec5cf24d3cfcfb7c141603956d715d656751688e5fce6a3867ed`). Regenerating reproduces the committed file byte for byte; do not edit by hand | Static column-index and RNG-stream table needed for byte-identical TPC-DS refresh seeding; included in this repository under the recorded distribution decision below with the TPC legal notice in `THIRD_PARTY_LICENSES` |
| `crates/benchbox-datagen-core/src/tpcds_update/dims.rs` | TPC-DS 4.0.0 `scaling.dst` row-count weights (`row_spec`, `source_table_rows`), the zip-to-GMT offset table (`GMT_OFFSETS`) and dimension source-table generators ported from `dsdgen` | Rust port of `dsdgen` refresh-set generation, covered by the TPC legal notice in `THIRD_PARTY_LICENSES` |
| `crates/benchbox-datagen-core/src/tpcds_update/scd.rs` | Slowly-changing dimension source-table generators ported from `dsdgen` | Rust port of `dsdgen` refresh-set generation, covered by the TPC legal notice in `THIRD_PARTY_LICENSES` |
| `crates/benchbox-datagen-core/src/tpcds_update/orders.rs` | Purchase, catalog order and web order source-table generators ported from `dsdgen` | Rust port of `dsdgen` refresh-set generation, covered by the TPC legal notice in `THIRD_PARTY_LICENSES` |
| `crates/benchbox-datagen-core/src/tpcds_update/plan.rs` | Update-date selection and per-day row scaling ported from `dsdgen` | Rust port of `dsdgen` refresh-set generation, covered by the TPC legal notice in `THIRD_PARTY_LICENSES` |
| `crates/benchbox-datagen-core/src/tpcds_update/calendar.rs` | Calendar and date routines ported from `dsdgen`, reading `calendar.dst` | Rust port of `dsdgen` refresh-set generation, covered by the TPC legal notice in `THIRD_PARTY_LICENSES` |
| `crates/benchbox-datagen-core/src/tpcds_update/ctx.rs` | Join-key and catalog-page routines ported from `dsdgen` | Rust port of `dsdgen` refresh-set generation, covered by the TPC legal notice in `THIRD_PARTY_LICENSES` |
| `crates/benchbox-datagen-core/src/tpcds_update/rng.rs` | Random-stream seeding by column number ported from `dsdgen` | Rust port of `dsdgen` refresh-set generation, covered by the TPC legal notice in `THIRD_PARTY_LICENSES` |
| `crates/benchbox-datagen-core/src/tpcds_update/out.rs` | Field formatting of `dsdgen`'s row printers | Rust port of `dsdgen` refresh-set generation, covered by the TPC legal notice in `THIRD_PARTY_LICENSES` |
| `crates/benchbox-datagen-core/src/tpcds_update/mod.rs` | Refresh-set file layout and delete files ported from `dsdgen` | Rust port of `dsdgen` refresh-set generation, covered by the TPC legal notice in `THIRD_PARTY_LICENSES` |
| `crates/benchbox-datagen-core/src/dsqgen/lexer.rs` | The `dsqgen` keyword table (`keywords.c` `KeyWords[]`, all 37 entries in order) and the template tokenizer, ported from the TPC-DS 4.0.0 kit | Rust port of `dsqgen` operating on caller-supplied templates and `tpcds.idx`, covered by the TPC legal notice in `THIRD_PARTY_LICENSES` |
| `crates/benchbox-datagen-core/src/dsqgen/parser.rs` | The query template grammar (`qgen.y`), ported from the TPC-DS 4.0.0 kit | Rust port of `dsqgen` operating on caller-supplied templates and `tpcds.idx`, covered by the TPC legal notice in `THIRD_PARTY_LICENSES` |
| `crates/benchbox-datagen-core/src/dsqgen/eval.rs` | Template expression evaluation (`EvalRandomExpr` and its helpers in `eval.c`), ported from the TPC-DS 4.0.0 kit | Rust port of `dsqgen` operating on caller-supplied templates and `tpcds.idx`, covered by the TPC legal notice in `THIRD_PARTY_LICENSES` |
| `crates/benchbox-datagen-core/src/dsqgen/rng.rs` | The random-number stream, `genrand_key`, `genrand_integer` and `makeKeyPermutation` (`genrand.c`, `permute.c`), ported from the TPC-DS 4.0.0 kit | Rust port of `dsqgen` operating on caller-supplied templates and `tpcds.idx`, covered by the TPC legal notice in `THIRD_PARTY_LICENSES` |
| `crates/benchbox-datagen-core/src/dsqgen/idx.rs` | The reader for the `tpcds.idx` distribution index format (`dist.c`), ported from the TPC-DS 4.0.0 kit | Rust port of `dsqgen` operating on caller-supplied templates and `tpcds.idx`, covered by the TPC legal notice in `THIRD_PARTY_LICENSES` |
| `crates/benchbox-datagen-core/src/dsqgen/date.rs` | Date parsing, Julian-day and calendar routines (`date.c`), ported from the TPC-DS 4.0.0 kit | Rust port of `dsqgen` operating on caller-supplied templates and `tpcds.idx`, covered by the TPC legal notice in `THIRD_PARTY_LICENSES` |
| `crates/benchbox-datagen-core/src/dsqgen/mod.rs` | `dsqgen` stream generation, template ordering and seeding (`qgen_main.c`), ported from the TPC-DS 4.0.0 kit | Rust port of `dsqgen` operating on caller-supplied templates and `tpcds.idx`, covered by the TPC legal notice in `THIRD_PARTY_LICENSES` |
| `crates/benchbox-datagen-core/src/qgen.rs` | `qgen` query parameter generation and the TPC-H query defaults, ported from the TPC-H kit | Rust port of `qgen` operating on caller-supplied templates and `dists.dss`, covered by the TPC legal notice in `THIRD_PARTY_LICENSES` |
| `tests/data/tpcds_dsdgen_sha256.json` | SHA-256 of the files written by the bundled `dsdgen` at scale factors 0.01, 0.1 and 1 | Parity-gate digests only; contains no TPC source or generated data text |
| `tests/data/tpch_dbgen_sha256.json` | SHA-256 of the files written by the bundled `dbgen` at scale factors 0.01 and 0.1 | Parity-gate digests only; contains no TPC source or generated data text |
| `tests/data/tpcds_rowcount_gate.json` | Row-count and active-location gate values observed from the patched `dsdgen`/`dsqgen` | Parity-gate scalar counts only; contains no TPC source or generated data text |
| `tests/data/tpcds_refresh_sha256.json` | SHA-256 of the files written by the bundled `dsdgen -update` at scale factors 0.0001, 0.01 (sets 1 and 127), 1 (sets 1 to 7, plus `-rngseed 20260709`), 10 and 100 | Parity-gate digests only; contains no TPC source or generated data text |
| `tests/data/tpch_refresh_sf0.01_sha256.json` | SHA-256 of the files written by the bundled `dbgen -U` | Parity-gate digests only; contains no TPC source or generated data text |

## Carried upstream patches

| Patch | Fork commit | Upstream PR |
| :--- | :--- | :--- |
| `tpcdsgen`: let callers supply the `Scaling` used by a `Session` (`Scaling::with_row_counts`, `SessionBuilder::with_scaling`; 73 changed lines) | [`b4b072b`](https://github.com/BenchBox-dev/tpcgen-rs/commit/b4b072b3f3ceb9f2979382beb96b3a27051b57b1) on `BenchBox-dev/tpcgen-rs` branch `v4.0.0-scaling-override` (upstream `v4.0.0` plus the PR commit and nothing else) | [datafusion-contrib/tpcgen-rs#677](https://github.com/datafusion-contrib/tpcgen-rs/pull/677) |
| `tpchgen`: keep four distinct suppliers per part at fractional scale factors (`select_part_supplier`; 65 added and 6 removed lines including tests) | [`12a75b6`](https://github.com/BenchBox-dev/tpcgen-rs/commit/12a75b68cd25dc076e0dd9f0feb360795ef3eec0) on `BenchBox-dev/tpcgen-rs` branch `v4.0.0-supplier-bridge` (upstream `v4.0.0` plus the PR commit and nothing else) | [datafusion-contrib/tpcgen-rs#679](https://github.com/datafusion-contrib/tpcgen-rs/pull/679) |

The root `Cargo.toml` pins `tpcdsgen`, `tpcdsgen-arrow` and `tpchgen` to those commits through
`[patch.crates-io]`; the library uses the first patch for TPC-DS scale factors below 1.
Building the sdist needs network access to fetch these SHA-pinned Git patches when
they are not already cached.
Rule for removal: when a released upstream `tpcdsgen` or `tpchgen` contains the change, bump
the exact version requirement, delete the `[patch.crates-io]` entries, regenerate `Cargo.lock`
and `THIRD_PARTY_LICENSES`, and re-run the TPC-DS parity matrix and the TPC-H goldens. A
carried patch stays at or below about 200 changed lines, is pinned by commit SHA and is never
merged into a divergent fork.

The `tpchgen` patch changes `partsupp` and `lineitem` (`l_suppkey`) only where the upstream
supplier step `int(S / 4) + (part - 1) / S` (`S = int(10,000 * SF)` suppliers) satisfies
`k * step % S == 0` for some `k` in 1..=3; there two of a part's four supplier slots
coincided and the table carried a duplicate `(ps_partkey, ps_suppkey)`. For those parts the
nearest step (`+1`, `-1`, `+2`, ...) with four distinct suppliers is used. Every other part
keeps its step, so every other scale factor stays byte-identical to unpatched `tpchgen` and
to the bundled `dbgen`. At or above BenchBox's minimum scale factor 0.01 only `S` in
102, 105, ..., 240 (every third value from 102 to 240, where 231, 234, 237, and 240 are
affected when `int(200,000 * SF) > 20 * S`, i.e., scale factors 0.0102 up to `< 0.0241`
with `int(10,000 * SF)` in that set) change; scale factors with `S < 100` are below that minimum.
`tpch_skew` `partsupp` follows `tpch`; its `lineitem` draws `l_suppkey` independently.
Results cached for the changed scale factors must be kept apart from results generated
without the patch.

## Publishing Python distributions

Before the first release, the owner must create the `pypi` GitHub environment
(and configure any desired protection rules), and register a pending Trusted
Publisher on PyPI for project `benchbox-datagen`: owner `BenchBox-dev`,
repository `benchbox-datagen`, workflow filename `wheels.yml`, environment
`pypi`. No PyPI API token is used. Once configured, a `vX.Y.Z` tag push runs
the wheel and sdist tests before publishing those same artifacts. The publish
job also checks the tag, package metadata, complete artifact set, and the
included `THIRD_PARTY_LICENSES` notice. Prerelease tags such as `vX.Y.Zrc1`
also publish to PyPI; configure the environment accordingly before tagging.

## Licence

MIT. See [LICENSE](LICENSE). The project's own code is MIT-licensed; the files derived from the
TPC kits (`tpcds_update/*.rs`, including `crates/benchbox-datagen-core/src/tpcds_update/columns.rs`,
`dsqgen/*.rs`, and `qgen.rs`, listed in the table under [TPC-DS refresh sets](#tpc-ds-refresh-sets))
ship under the TPC legal notice in `THIRD_PARTY_LICENSES`.

This reflects a recorded project distribution decision, not a legal conclusion (see BenchBox's
`docs/tpc-licensing-analysis.md` for the TPC EULA v2.2 analysis):

- `crates/benchbox-datagen-core/src/tpcds_update/columns.rs` and the other TPC-derived Rust modules
  remain in this MIT repository with the verbatim TPC legal notice in `THIRD_PARTY_LICENSES`,
  carried in all eight binary wheels and the source distribution. CI verifies the bundled
  `THIRD_PARTY_LICENSES` notice on every built wheel and the sdist (`tools/verify_wheel_no_pyarrow.py`),
  and the release workflow re-verifies the full artifact set before publishing
  (`tools/validate_release_artifacts.py`).
- TPC query templates (`.sql`, `.tpl`), `dists.dss`, and `tpcds.idx` are not committed to this
  repository; they remain in BenchBox, are supplied by the caller at runtime, and are fetched from
  a pinned BenchBox commit in CI.

