Skip to main content

hyprstream_bench/gen/
jsoncheck.rs

1//! JSON well-formedness / extraction. The `NearMiss` stratum is near-miss
2//! JSON: documents broken by exactly one classic syntax error (trailing
3//! comma, unquoted key, single quotes, missing closing brace). Validity is
4//! decided by `serde_json`, so truth is mechanical.
5
6use hyprstream_decision::Entry;
7
8use crate::family::{Family, Stratum};
9use crate::gen::stream;
10use crate::item::Item;
11
12const FAMILY: Family = Family::JsonCheck;
13
14struct Doc {
15    text: String,
16    valid: bool,
17    /// Number of injected syntax errors (0 = clean).
18    errors: usize,
19    /// The injected break (0=trailing comma, 1=unquoted key, 2=single quotes,
20    /// 3=missing brace) or 4 = valid document. Threaded through instead of
21    /// re-derived from the text — the text is the artifact, this is the truth.
22    repair: usize,
23}
24
25fn document(seed: u64, stratum: Stratum) -> Doc {
26    let mut rng = stream(seed);
27    let key = ["name", "port", "zone", "owner", "quota"][rng.below(5) as usize];
28    let value = rng.range(1, 9999);
29    let host = format!("srv-{}", rng.range(1, 99));
30    let clean = format!("{{\"{key}\": {value}, \"host\": \"{host}\"}}");
31    if stratum != Stratum::NearMiss {
32        return Doc {
33            text: clean,
34            valid: true,
35            errors: 0,
36            repair: 4,
37        };
38    }
39    // Exactly one near-miss break, chosen by stream; a fraction of the
40    // stratum stays valid so the truth labels mix.
41    let variant = rng.below(5);
42    let (text, errors) = match variant {
43        0 => (format!("{{\"{key}\": {value}, \"host\": \"{host}\",}}"), 1), // trailing comma
44        1 => (format!("{{{key}: {value}, \"host\": \"{host}\"}}"), 1),      // unquoted key
45        2 => (format!("{{\"{key}\": {value}, \"host\": '{host}'}}"), 1),    // single quotes
46        3 => (format!("{{\"{key}\": {value}, \"host\": \"{host}\""), 1),    // missing brace
47        _ => (clean, 0),
48    };
49    let valid = errors == 0;
50    debug_assert_eq!(
51        valid,
52        serde_json::from_str::<serde_json::Value>(&text).is_ok()
53    );
54    Doc {
55        text,
56        valid,
57        errors,
58        repair: if valid { 4 } else { variant as usize },
59    }
60}
61
62pub fn noul(seed: u64, stratum: Stratum) -> Item {
63    let doc = document(seed, stratum);
64    Item::noul(
65        FAMILY,
66        stratum,
67        seed,
68        Entry::Str(doc.text),
69        "Is the state a syntactically valid JSON document?",
70        doc.valid,
71    )
72}
73
74pub fn choice(seed: u64, stratum: Stratum) -> Item {
75    let mut rng = stream(seed ^ 0xC0);
76    let doc = document(seed, stratum);
77    let options = [
78        "remove the trailing comma",
79        "quote the bare object key",
80        "replace single quotes with double quotes",
81        "add the missing closing brace",
82        "the document is already valid",
83    ];
84    // Map the injected break to its repair — threaded from `document`, not
85    // re-derived by probing the text.
86    let correct = doc.repair;
87    // Shuffle options except we keep identity by value; correct rotates.
88    let order = rng.permutation(options.len());
89    let shuffled: Vec<String> = order.iter().map(|&i| options[i].to_owned()).collect();
90    let new_correct = order
91        .iter()
92        .position(|&i| i == correct)
93        .unwrap_or_else(|| unreachable!("permutation contains every index"));
94    let _ = rng;
95    Item::choice(
96        FAMILY,
97        stratum,
98        seed,
99        Entry::Str(doc.text),
100        "Which single repair makes the state a valid JSON document?",
101        shuffled,
102        new_correct,
103    )
104}
105
106pub fn score(seed: u64, stratum: Stratum) -> Item {
107    let doc = document(seed, stratum);
108    Item::score(
109        FAMILY,
110        stratum,
111        seed,
112        Entry::Str(doc.text),
113        "How many JSON syntax errors does the state contain? Levels: 0 = none, 1 = one or more.",
114        2,
115        doc.errors.min(1),
116    )
117}