Skip to main content

sas_plus/
random.rs

1//! Tiny deterministic random task generator for property tests across the
2//! workspace (no external RNG dependency).
3//!
4//! A seed always produces the same task, so a failing property names the seed
5//! that reproduces it.
6
7use alloc::format;
8use alloc::vec::Vec;
9
10use crate::{Axiom, Effect, Fact, Operator, State, Task, Variable};
11
12/// xorshift64* — good enough for test-case generation.
13#[derive(Clone, Debug)]
14pub struct Rng(u64);
15
16impl Rng {
17    /// A generator for `seed`; every seed, including 0, gives a usable stream.
18    #[must_use]
19    pub fn new(seed: u64) -> Self {
20        Self(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1)
21    }
22
23    /// The next 64 pseudo-random bits.
24    pub fn next_u64(&mut self) -> u64 {
25        self.0 ^= self.0 >> 12;
26        self.0 ^= self.0 << 25;
27        self.0 ^= self.0 >> 27;
28        self.0.wrapping_mul(0x2545_F491_4F6C_DD1D)
29    }
30
31    /// Uniform in `lo..=hi` (up to a negligible modulo bias).
32    ///
33    /// # Panics
34    ///
35    /// If `lo > hi`.
36    pub fn range(&mut self, lo: u64, hi: u64) -> u64 {
37        assert!(lo <= hi, "empty range {lo}..={hi}");
38        let x = self.next_u64();
39        // The full `u64` range has no modulus that fits.
40        (hi - lo).checked_add(1).map_or(x, |n| lo + x % n)
41    }
42
43    /// [`Rng::range`] for `u32` bounds; draws exactly as `range` does.
44    fn range_u32(&mut self, lo: u32, hi: u32) -> u32 {
45        let x = self.range(u64::from(lo), u64::from(hi));
46
47        u32::try_from(x).expect("a draw in u32 bounds fits in u32")
48    }
49
50    /// [`Rng::range`] for `usize` bounds; draws exactly as `range` does.
51    fn range_usize(&mut self, lo: usize, hi: usize) -> usize {
52        let x = self.range(lo as u64, hi as u64);
53
54        usize::try_from(x).expect("a draw in usize bounds fits in usize")
55    }
56
57    /// `min(k, n)` distinct variables out of `0..n`, by a partial
58    /// Fisher-Yates shuffle.
59    fn distinct_vars(&mut self, n: usize, k: usize) -> Vec<usize> {
60        let mut vars: Vec<usize> = (0..n).collect();
61        for i in 0..k.min(n) {
62            let j = self.range_usize(i, n - 1);
63            vars.swap(i, j);
64        }
65
66        vars.truncate(k.min(n));
67        vars
68    }
69
70    /// A fact on `var` with a uniform value of its domain in `variables`.
71    fn fact(&mut self, variables: &[Variable], var: usize) -> Fact {
72        Fact::new(var, self.range_u32(0, variables[var].domain_size - 1))
73    }
74
75    /// Facts on up to `k` distinct variables out of the first `n`, with
76    /// uniform values.
77    fn facts(&mut self, variables: &[Variable], n: usize, k: usize) -> Vec<Fact> {
78        self.distinct_vars(n, k)
79            .into_iter()
80            .map(|v| self.fact(variables, v))
81            .collect()
82    }
83}
84
85/// The shape of the tasks [`random_task`] generates.
86#[derive(Clone, Copy, Debug)]
87pub struct RandomTaskParams {
88    /// Number of state variables.
89    pub num_vars: usize,
90    /// Largest domain size; each variable gets 2 to `max(max_domain, 2)` values.
91    pub max_domain: u32,
92    /// Number of operators, each with 0 to 2 preconditions and 1 or 2 effects.
93    pub num_ops: usize,
94    /// Largest operator cost; costs are 1 to `max(max_cost, 1)`.
95    pub max_cost: u32,
96    /// Up to this many conditions per effect; `0` means no conditional effects.
97    pub max_conditions: usize,
98    /// Number of binary derived variables, each in its own axiom layer, with
99    /// one or two rules apiece. Goals and preconditions may then mention them.
100    pub num_derived: usize,
101}
102
103impl Default for RandomTaskParams {
104    fn default() -> Self {
105        Self {
106            num_vars: 4,
107            max_domain: 3,
108            num_ops: 10,
109            max_cost: 5,
110            max_conditions: 0,
111            num_derived: 0,
112        }
113    }
114}
115
116/// A random task of shape `p`, the same for every call with the same `seed`.
117/// The task passes [`Task::validate`].
118#[must_use]
119pub fn random_task(seed: u64, p: RandomTaskParams) -> Task {
120    let mut rng = Rng::new(seed);
121    let variables: Vec<Variable> = (0..p.num_vars)
122        .map(|i| Variable::new(format!("v{i}"), rng.range_u32(2, p.max_domain.max(2))))
123        .collect();
124    let operators = (0..p.num_ops)
125        .map(|i| random_operator(&mut rng, &p, &variables, i))
126        .collect();
127    let initial = State(
128        (0..p.num_vars)
129            .map(|v| rng.fact(&variables, v).value)
130            .collect(),
131    );
132    let n_goal = rng.range_usize(1, 2);
133    let goal = rng.facts(&variables, p.num_vars, n_goal);
134
135    let mut task = Task {
136        variables,
137        operators,
138        initial,
139        goal,
140        axioms: Vec::new(),
141    };
142
143    // Derived variables come last, so tasks without them stay the same per seed.
144    for layer in 0..p.num_derived {
145        add_derived_variable(&mut rng, &mut task, layer, p.num_ops);
146    }
147
148    task
149}
150
151/// Operator `op{index}` over `variables`, with conditional effects if
152/// `p.max_conditions` allows them.
153fn random_operator(
154    rng: &mut Rng,
155    p: &RandomTaskParams,
156    variables: &[Variable],
157    index: usize,
158) -> Operator {
159    let n_pre = rng.range_usize(0, 2);
160    let n_eff = rng.range_usize(1, 2);
161    let pre = rng.facts(variables, p.num_vars, n_pre);
162    let eff = rng
163        .distinct_vars(p.num_vars, n_eff)
164        .into_iter()
165        .map(|v| {
166            let fact = rng.fact(variables, v);
167            // No draw without conditions, so seeds keep their tasks.
168            let conditions = if p.max_conditions == 0 {
169                Vec::new()
170            } else {
171                let n = rng.range_usize(0, p.max_conditions);
172                rng.facts(variables, p.num_vars, n)
173            };
174
175            Effect { conditions, fact }
176        })
177        .collect();
178
179    Operator {
180        name: format!("op{index}"),
181        pre,
182        eff,
183        cost: rng.range_u32(1, p.max_cost.max(1)),
184    }
185}
186
187/// Appends binary derived variable `d{layer}` (default 0, in axiom layer
188/// `layer`) with one or two rules, and makes either the goal or one of the
189/// first `num_ops` operators' preconditions mention it.
190fn add_derived_variable(rng: &mut Rng, task: &mut Task, layer: usize, num_ops: usize) {
191    let var = task.variables.len();
192    for _ in 0..rng.range(1, 2) {
193        // Conditions on state variables and lower layers (at any value, which
194        // includes negation as failure).
195        let n = rng.range_usize(1, 2);
196        let conditions = rng.facts(&task.variables, var, n);
197        task.axioms.push(Axiom {
198            conditions,
199            head: Fact::new(var, 1),
200        });
201    }
202
203    task.variables.push(Variable {
204        axiom_layer: Some(u32::try_from(layer).expect("at most u32::MAX axiom layers")),
205        ..Variable::new(format!("d{layer}"), 2)
206    });
207    task.initial.0.push(0);
208
209    let derived = Fact::new(var, rng.range_u32(0, 1));
210    if rng.range(0, 1) == 0 {
211        task.goal.push(derived);
212    } else {
213        let op = rng.range_usize(0, num_ops.max(1) - 1);
214        if let Some(op) = task.operators.get_mut(op) {
215            op.pre.push(derived);
216        }
217    }
218}