seedkit-core 2.1.1

Core library for SeedKit — realistic database seed data generation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
use std::borrow::Cow;

use chrono::Duration as ChronoDuration;
use rand::Rng;

use crate::classify::semantic::{CorrelationGroup, SemanticType};
use crate::generate::locale::{ascii_slug, Locale};
use crate::generate::plan::CorrelationGroupPlan;
use crate::generate::providers::{generate_localized, generate_value};
use crate::generate::value::Value;

// TODO: Phase 3 — Replace this 50-entry slice with a compressed ~40,000 US zip
// code dataset loaded via `include_bytes!`. At 50 entries, every 200th generated
// user lands in the exact same city/zip, which produces unrealistic distributions
// for high-volume performance tests.
/// Built-in US city/state/zip data for correlated address generation.
static US_LOCATIONS: &[(&str, &str, &str)] = &[
    ("New York", "New York", "10001"),
    ("Los Angeles", "California", "90001"),
    ("Chicago", "Illinois", "60601"),
    ("Houston", "Texas", "77001"),
    ("Phoenix", "Arizona", "85001"),
    ("Philadelphia", "Pennsylvania", "19101"),
    ("San Antonio", "Texas", "78201"),
    ("San Diego", "California", "92101"),
    ("Dallas", "Texas", "75201"),
    ("San Jose", "California", "95101"),
    ("Austin", "Texas", "73301"),
    ("Jacksonville", "Florida", "32099"),
    ("Fort Worth", "Texas", "76101"),
    ("Columbus", "Ohio", "43085"),
    ("Charlotte", "North Carolina", "28201"),
    ("San Francisco", "California", "94101"),
    ("Indianapolis", "Indiana", "46201"),
    ("Seattle", "Washington", "98101"),
    ("Denver", "Colorado", "80201"),
    ("Nashville", "Tennessee", "37201"),
    ("Portland", "Oregon", "97201"),
    ("Las Vegas", "Nevada", "89101"),
    ("Memphis", "Tennessee", "38101"),
    ("Louisville", "Kentucky", "40201"),
    ("Baltimore", "Maryland", "21201"),
    ("Milwaukee", "Wisconsin", "53201"),
    ("Albuquerque", "New Mexico", "87101"),
    ("Tucson", "Arizona", "85701"),
    ("Fresno", "California", "93650"),
    ("Sacramento", "California", "95814"),
    ("Mesa", "Arizona", "85201"),
    ("Atlanta", "Georgia", "30301"),
    ("Kansas City", "Missouri", "64101"),
    ("Omaha", "Nebraska", "68101"),
    ("Miami", "Florida", "33101"),
    ("Minneapolis", "Minnesota", "55401"),
    ("Cleveland", "Ohio", "44101"),
    ("Raleigh", "North Carolina", "27601"),
    ("Tampa", "Florida", "33601"),
    ("New Orleans", "Louisiana", "70112"),
    ("Pittsburgh", "Pennsylvania", "15201"),
    ("Cincinnati", "Ohio", "45201"),
    ("St. Louis", "Missouri", "63101"),
    ("Orlando", "Florida", "32801"),
    ("Boston", "Massachusetts", "02101"),
    ("Detroit", "Michigan", "48201"),
    ("Honolulu", "Hawaii", "96801"),
    ("Salt Lake City", "Utah", "84101"),
    ("Anchorage", "Alaska", "99501"),
    ("Richmond", "Virginia", "23219"),
];

/// Generate values for a correlation group.
///
/// `base_time` is the pinned wall-clock timestamp from the generation plan.
/// Temporal groups derive all dates relative to this anchor so regeneration
/// from a lockfile produces identical output regardless of when it runs.
pub fn generate_correlated_group(
    plan: &CorrelationGroupPlan,
    row_index: usize,
    rng: &mut impl Rng,
    base_time: chrono::NaiveDateTime,
    locale: Locale,
) -> Vec<(String, Value)> {
    match plan.group {
        CorrelationGroup::Address if locale.localizes(SemanticType::City) => {
            // The US table below keeps city, state, and zip consistent. A
            // locale with its own address data draws each part from it instead.
            plan.columns
                .iter()
                .map(|(col, st)| {
                    (
                        col.clone(),
                        generate_localized(locale, *st, rng, 0, &[], base_time),
                    )
                })
                .collect()
        }
        CorrelationGroup::Address => generate_address(plan, rng, base_time),
        CorrelationGroup::GeoCoordinates => generate_geo(plan, rng, base_time),
        CorrelationGroup::PersonIdentity => {
            generate_person(plan, row_index, rng, base_time, locale)
        }
        CorrelationGroup::Temporal => generate_temporal(plan, rng, base_time),
        CorrelationGroup::TemporalRange => generate_temporal_range(plan, rng, base_time),
    }
}

fn generate_address(
    plan: &CorrelationGroupPlan,
    rng: &mut impl Rng,
    base_time: chrono::NaiveDateTime,
) -> Vec<(String, Value)> {
    let loc = US_LOCATIONS[rng.random_range(0..US_LOCATIONS.len())];
    let street_num = rng.random_range(100..9999);
    let streets = [
        "Main St",
        "Oak Ave",
        "Elm St",
        "Park Blvd",
        "Cedar Ln",
        "Maple Dr",
        "Pine St",
        "Washington Ave",
        "Lake Rd",
        "Hill St",
    ];
    let street = streets[rng.random_range(0..streets.len())];

    let mut values = Vec::new();
    for (col_name, st) in &plan.columns {
        let value = match st {
            SemanticType::StreetAddress => {
                Value::String(Cow::Owned(format!("{} {}", street_num, street)))
            }
            SemanticType::City => Value::String(Cow::Borrowed(loc.0)),
            SemanticType::State => Value::String(Cow::Borrowed(loc.1)),
            SemanticType::ZipCode | SemanticType::PostalCode => Value::String(Cow::Borrowed(loc.2)),
            SemanticType::Country => Value::String(Cow::Borrowed("United States")),
            SemanticType::CountryCode => Value::String(Cow::Borrowed("US")),
            // Column was swept into this group by classification but doesn't
            // match any address sub-type. Fall back to standalone generation
            // so NOT NULL columns get a real value instead of NULL.
            _ => generate_value(*st, rng, 0, &[], base_time),
        };
        values.push((col_name.clone(), value));
    }
    values
}

fn generate_geo(
    plan: &CorrelationGroupPlan,
    rng: &mut impl Rng,
    base_time: chrono::NaiveDateTime,
) -> Vec<(String, Value)> {
    // Generate realistic US coordinates
    let lat: f64 = rng.random_range(25.0_f64..48.0_f64);
    let lng: f64 = rng.random_range(-125.0_f64..-70.0_f64);

    let mut values = Vec::new();
    for (col_name, st) in &plan.columns {
        let value = match st {
            SemanticType::Latitude => Value::Float((lat * 1_000_000.0).round() / 1_000_000.0),
            SemanticType::Longitude => Value::Float((lng * 1_000_000.0).round() / 1_000_000.0),
            _ => generate_value(*st, rng, 0, &[], base_time),
        };
        values.push((col_name.clone(), value));
    }
    values
}

fn generate_person(
    plan: &CorrelationGroupPlan,
    row_index: usize,
    rng: &mut impl Rng,
    base_time: chrono::NaiveDateTime,
    locale: Locale,
) -> Vec<(String, Value)> {
    use fake::faker::name::en::*;
    use fake::Fake;

    let mut name = |semantic, english: fn(&mut _) -> String| match locale.sample(semantic, rng) {
        Some(Value::String(text)) => text.into_owned(),
        _ => english(rng),
    };
    let first = name(SemanticType::FirstName, |rng| {
        FirstName().fake_with_rng(rng)
    });
    let last = name(SemanticType::LastName, |rng| LastName().fake_with_rng(rng));
    let full_name = format!("{} {}", first, last);
    // English output is unchanged. Other locales keep emails and usernames
    // ASCII, with "user" when a name has no Latin letters.
    let (first_part, last_part) = if locale == Locale::En {
        (first.to_lowercase(), last.to_lowercase())
    } else {
        let slug = |text: &str, fallback: &str| match ascii_slug(text) {
            s if s.is_empty() => fallback.to_owned(),
            s => s,
        };
        (slug(&first, "user"), slug(&last, "seed"))
    };
    let email = format!(
        "{}.{}{}@example.com",
        first_part,
        last_part,
        if row_index > 0 {
            format!(".{}", row_index)
        } else {
            String::new()
        }
    );
    // Use first.last.index format to safely clear common minimum-length
    // constraints (many apps require LENGTH(username) >= 5).
    let username = format!("{}.{}{}", first_part, last_part, row_index);

    let mut values = Vec::new();
    for (col_name, st) in &plan.columns {
        let value = match st {
            SemanticType::FirstName => Value::String(Cow::Owned(first.clone())),
            SemanticType::LastName => Value::String(Cow::Owned(last.clone())),
            SemanticType::FullName | SemanticType::DisplayName => {
                Value::String(Cow::Owned(full_name.clone()))
            }
            SemanticType::Email => Value::String(Cow::Owned(email.clone())),
            SemanticType::Username => Value::String(Cow::Owned(username.clone())),
            _ => generate_localized(locale, *st, rng, row_index, &[], base_time),
        };
        values.push((col_name.clone(), value));
    }
    values
}

fn generate_temporal(
    plan: &CorrelationGroupPlan,
    rng: &mut impl Rng,
    base_time: chrono::NaiveDateTime,
) -> Vec<(String, Value)> {
    let created_days_ago = rng.random_range(30..365);
    let created = base_time - ChronoDuration::days(created_days_ago);
    let updated = created + ChronoDuration::days(rng.random_range(1..created_days_ago));
    // Always a timestamp. Whether the row is soft-deleted (NULL) is the
    // column's null rate, applied by the engine: never for NOT NULL, 80% by
    // default for a nullable `deleted_at`, or the configured `null_rate`.
    let deleted = updated + ChronoDuration::days(rng.random_range(1..30));

    let mut values = Vec::new();
    for (col_name, st) in &plan.columns {
        let value = match st {
            SemanticType::CreatedAt => Value::Timestamp(created),
            SemanticType::UpdatedAt => Value::Timestamp(updated),
            SemanticType::DeletedAt => Value::Timestamp(deleted),
            _ => generate_value(*st, rng, 0, &[], base_time),
        };
        values.push((col_name.clone(), value));
    }
    values
}

fn generate_temporal_range(
    plan: &CorrelationGroupPlan,
    rng: &mut impl Rng,
    base_time: chrono::NaiveDateTime,
) -> Vec<(String, Value)> {
    let today = base_time.date();
    let start_offset = rng.random_range(-30..60);
    let start = today + ChronoDuration::days(start_offset);
    let duration = rng.random_range(1..90);
    let end = start + ChronoDuration::days(duration);

    let mut values = Vec::new();
    for (col_name, st) in &plan.columns {
        let value = match st {
            SemanticType::StartDate => Value::Date(start),
            SemanticType::EndDate => Value::Date(end),
            _ => generate_value(*st, rng, 0, &[], base_time),
        };
        values.push((col_name.clone(), value));
    }
    values
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::generate::locale::Locale;
    use rand::SeedableRng;

    fn test_base_time() -> chrono::NaiveDateTime {
        chrono::NaiveDateTime::new(
            chrono::NaiveDate::from_ymd_opt(2025, 6, 15).unwrap(),
            chrono::NaiveTime::from_hms_opt(12, 0, 0).unwrap(),
        )
    }

    #[test]
    fn localized_people_keep_ascii_emails_and_usernames() {
        let plan = CorrelationGroupPlan {
            group: CorrelationGroup::PersonIdentity,
            columns: vec![
                ("last_name".to_string(), SemanticType::LastName),
                ("email".to_string(), SemanticType::Email),
                ("username".to_string(), SemanticType::Username),
            ],
        };
        let mut rng = rand::rngs::StdRng::seed_from_u64(42);
        let mut localized = false;
        for row in 0..20 {
            let values =
                generate_correlated_group(&plan, row, &mut rng, test_base_time(), Locale::JaJp);
            let text = |name: &str| {
                values
                    .iter()
                    .find(|(c, _)| c == name)
                    .unwrap()
                    .1
                    .as_string()
                    .unwrap()
                    .to_owned()
            };
            localized |= !text("last_name").is_ascii();
            let (email, username) = (text("email"), text("username"));
            assert!(
                email.is_ascii() && email.ends_with("@example.com"),
                "{email}"
            );
            assert!(username.is_ascii() && username.len() >= 5, "{username}");
        }
        assert!(localized, "Japanese last names expected");
    }

    #[test]
    fn test_address_correlation() {
        let plan = CorrelationGroupPlan {
            group: CorrelationGroup::Address,
            columns: vec![
                ("city".to_string(), SemanticType::City),
                ("state".to_string(), SemanticType::State),
                ("zip".to_string(), SemanticType::ZipCode),
            ],
        };
        let mut rng = rand::rngs::StdRng::seed_from_u64(42);
        let values = generate_correlated_group(&plan, 0, &mut rng, test_base_time(), Locale::En);

        assert_eq!(values.len(), 3);
        // All values should be non-null strings
        for (_, v) in &values {
            assert!(matches!(v, Value::String(_)));
        }
    }

    #[test]
    fn test_person_correlation() {
        let plan = CorrelationGroupPlan {
            group: CorrelationGroup::PersonIdentity,
            columns: vec![
                ("first_name".to_string(), SemanticType::FirstName),
                ("last_name".to_string(), SemanticType::LastName),
                ("email".to_string(), SemanticType::Email),
            ],
        };
        let mut rng = rand::rngs::StdRng::seed_from_u64(42);
        let values = generate_correlated_group(&plan, 0, &mut rng, test_base_time(), Locale::En);

        // Email should contain first.last
        let email = values
            .iter()
            .find(|(n, _)| n == "email")
            .map(|(_, v)| v.clone())
            .unwrap();
        if let Value::String(e) = email {
            assert!(e.contains('@'));
            assert!(e.contains('.'));
        }
    }

    #[test]
    fn test_temporal_determinism() {
        let plan = CorrelationGroupPlan {
            group: CorrelationGroup::Temporal,
            columns: vec![
                ("created_at".to_string(), SemanticType::CreatedAt),
                ("updated_at".to_string(), SemanticType::UpdatedAt),
            ],
        };
        let bt = test_base_time();
        let mut rng1 = rand::rngs::StdRng::seed_from_u64(42);
        let mut rng2 = rand::rngs::StdRng::seed_from_u64(42);

        let v1 = generate_correlated_group(&plan, 0, &mut rng1, bt, Locale::En);
        let v2 = generate_correlated_group(&plan, 0, &mut rng2, bt, Locale::En);

        // Same seed + same base_time must produce identical timestamps.
        for ((_, a), (_, b)) in v1.iter().zip(v2.iter()) {
            assert_eq!(a, b);
        }
    }

    #[test]
    fn test_unmatched_column_falls_back_to_provider() {
        let plan = CorrelationGroupPlan {
            group: CorrelationGroup::Address,
            columns: vec![
                ("city".to_string(), SemanticType::City),
                ("notes".to_string(), SemanticType::Paragraph),
            ],
        };
        let mut rng = rand::rngs::StdRng::seed_from_u64(42);
        let values = generate_correlated_group(&plan, 0, &mut rng, test_base_time(), Locale::En);

        // "notes" doesn't match any address sub-type but should NOT be Null.
        let notes = values.iter().find(|(n, _)| n == "notes").unwrap();
        assert!(
            !matches!(notes.1, Value::Null),
            "Unmatched column in correlation group should fall back to provider, not Null"
        );
    }

    #[test]
    fn test_username_minimum_length() {
        let plan = CorrelationGroupPlan {
            group: CorrelationGroup::PersonIdentity,
            columns: vec![
                ("first_name".to_string(), SemanticType::FirstName),
                ("last_name".to_string(), SemanticType::LastName),
                ("username".to_string(), SemanticType::Username),
            ],
        };
        let mut rng = rand::rngs::StdRng::seed_from_u64(42);
        let values = generate_correlated_group(&plan, 0, &mut rng, test_base_time(), Locale::En);

        let username = values.iter().find(|(n, _)| n == "username").unwrap();
        if let Value::String(u) = &username.1 {
            assert!(u.len() >= 5, "Username '{}' should be >= 5 chars", u);
        }
    }
}