Skip to main content

sql_splitter/generate/
seed.rs

1//! Stable, deterministic seed derivation for synthetic data generation.
2//!
3//! Every value the generator produces must be reproducible from a single
4//! root seed, independent of *when* or in what order it is requested during a
5//! traversal. We get that by deriving a dedicated RNG stream per logical
6//! identity (a table, a column, a planner, or an operator invocation) via
7//! SHA-256 over a fixed, length-prefixed byte layout.
8//!
9//! [`std::collections::hash_map::DefaultHasher`] and `ahash` are deliberately
10//! not used here: neither publishes a stability guarantee across Rust or
11//! crate versions, so a toolchain upgrade could silently reshuffle every
12//! generated dataset. SHA-256 is a fixed, versioned algorithm we control.
13
14use rand_chacha::rand_core::SeedableRng;
15use rand_chacha::ChaCha8Rng;
16use sha2::{Digest, Sha256};
17
18/// Domain-separation prefix mixed into every derived seed. Bumping the
19/// trailing version number is the only sanctioned way to change the
20/// derivation algorithm, since it invalidates every previously generated
21/// dataset's reproducibility.
22const SEED_DOMAIN: &[u8] = b"sql-splitter.generate.seed.v1\0";
23
24/// Derive a 32-byte seed from a root value and an ordered list of identity
25/// parts.
26///
27/// The hash is over the domain prefix, the little-endian root, then each
28/// part's length (as a little-endian `u64`) followed by its bytes. Length
29/// prefixing prevents ambiguity between e.g. `["ab", "c"]` and `["a", "bc"]`.
30pub fn derive_seed(root: u64, parts: &[&str]) -> [u8; 32] {
31    let mut hash = Sha256::new();
32    hash.update(SEED_DOMAIN);
33    hash.update(root.to_le_bytes());
34    for part in parts {
35        hash.update((part.len() as u64).to_le_bytes());
36        hash.update(part.as_bytes());
37    }
38    hash.finalize().into()
39}
40
41/// Identity of a single deterministic RNG stream.
42///
43/// Stream identity is built from normalized table, column/planner, and
44/// operator names only. A traversal index (row number, retry count, visit
45/// order) must never enter the hash: the same logical identity has to
46/// rederive the same stream no matter how many other streams were derived
47/// before it in a given run.
48#[derive(Debug, Clone, PartialEq, Eq, Hash)]
49pub struct StreamId {
50    kind: &'static str,
51    parts: Vec<String>,
52}
53
54impl StreamId {
55    /// Stream for table-level decisions (e.g. row count planning).
56    pub fn table(table: impl Into<String>) -> Self {
57        Self {
58            kind: "table",
59            parts: vec![table.into()],
60        }
61    }
62
63    /// Stream for a single column's value generation.
64    pub fn column(
65        table: impl Into<String>,
66        column: impl Into<String>,
67        operator: impl Into<String>,
68    ) -> Self {
69        Self {
70            kind: "column",
71            parts: vec![table.into(), column.into(), operator.into()],
72        }
73    }
74
75    /// Stream for planner decisions scoped to a table (row counts, child
76    /// distributions, and similar structural choices).
77    pub fn planner(table: impl Into<String>) -> Self {
78        Self {
79            kind: "planner",
80            parts: vec![table.into()],
81        }
82    }
83
84    /// Stream for a table's stochastic row-count rounding decision.
85    ///
86    /// The row compiler resolves an exact integer count per table; when the
87    /// resolved target is fractional (e.g. a `--scale` that lands on 1.5), the
88    /// remainder is rounded up with probability equal to the fraction. Keying
89    /// the stream on the table name (behind the `rows.rounding` prefix) keeps
90    /// that decision stable and independent of every other stream in the run.
91    pub fn rounding(table: impl Into<String>) -> Self {
92        Self {
93            kind: "rows.rounding",
94            parts: vec![table.into()],
95        }
96    }
97
98    /// Stream for a specific generator operator invocation, independent of
99    /// any particular column (e.g. a shared lookup pool).
100    pub fn operator(
101        table: impl Into<String>,
102        column: impl Into<String>,
103        operator: impl Into<String>,
104    ) -> Self {
105        Self {
106            kind: "operator",
107            parts: vec![table.into(), column.into(), operator.into()],
108        }
109    }
110
111    /// The byte-string parts hashed for this stream, in order, prefixed by
112    /// the stream kind so different constructors never collide even when
113    /// given identical string arguments.
114    fn hash_parts(&self) -> Vec<&str> {
115        let mut parts = Vec::with_capacity(self.parts.len() + 1);
116        parts.push(self.kind);
117        parts.extend(self.parts.iter().map(String::as_str));
118        parts
119    }
120}
121
122/// A run's single root seed, from which every deterministic stream is
123/// derived.
124#[derive(Debug, Clone, Copy, PartialEq, Eq)]
125pub struct SeedRoot {
126    root: u64,
127}
128
129impl SeedRoot {
130    /// Create a new root from a plain `u64` seed value.
131    pub fn new(root: u64) -> Self {
132        Self { root }
133    }
134
135    /// Derive a fresh, deterministic RNG for the given stream identity.
136    pub fn stream(&self, id: StreamId) -> ChaCha8Rng {
137        let seed = derive_seed(self.root, &id.hash_parts());
138        ChaCha8Rng::from_seed(seed)
139    }
140}
141
142#[cfg(test)]
143mod tests {
144    use super::*;
145
146    #[test]
147    fn derive_seed_is_deterministic_for_the_same_inputs() {
148        let a = derive_seed(1, &["a", "b"]);
149        let b = derive_seed(1, &["a", "b"]);
150        assert_eq!(a, b);
151    }
152
153    #[test]
154    fn derive_seed_distinguishes_part_boundaries() {
155        // Without length prefixing, ["ab", "c"] and ["a", "bc"] would hash
156        // identically once concatenated.
157        let a = derive_seed(1, &["ab", "c"]);
158        let b = derive_seed(1, &["a", "bc"]);
159        assert_ne!(a, b);
160    }
161
162    #[test]
163    fn derive_seed_distinguishes_roots() {
164        let a = derive_seed(1, &["same"]);
165        let b = derive_seed(2, &["same"]);
166        assert_ne!(a, b);
167    }
168
169    /// Checked-in golden for `derive_seed(42, ["users", "email", "internet.email"])`.
170    /// If this ever changes, the derivation algorithm changed and every
171    /// previously generated dataset would silently diverge - bump
172    /// [`SEED_DOMAIN`]'s version and update this golden deliberately.
173    #[test]
174    fn seed_golden_hex_matches_checked_in_value() {
175        let golden = "122016424915fd14795335972fba7c8cc3f69d38deffd59c49e22a4f477ce584";
176        let actual = hex::encode(derive_seed(42, &["users", "email", "internet.email"]));
177        assert_eq!(actual, golden);
178    }
179}