Skip to main content

rust_anything/
pin.rs

1//! Pinned clock and random numbers (`record --pin-clock`), so units that read them can be
2//! recorded and diffed.
3//!
4//! The setting lives in `pinned.json` next to the recording. While it is there, `record`, `diff`,
5//! `fuzz` and `gate` start the original and the port with `RUST_ANYTHING_NOW_MS`,
6//! `RUST_ANYTHING_SEED` and `TZ=UTC`. The JS and Python drivers replace the clock (`Date.now()`,
7//! `new Date()`; `time.time`, `datetime.now`) with that instant and the random numbers
8//! (`Math.random`; the `random` module) with mulberry32 from that seed. Before each case they
9//! restart the generator and set `RUST_ANYTHING_CASE`, so a case's numbers do not depend on the
10//! cases before it. The port reproduces both with the helper in [`HELPER`].
11
12use std::path::{Path, PathBuf};
13use std::process::Command;
14
15use anyhow::{Context, Result, bail};
16use serde::{Deserialize, Serialize};
17
18use crate::bridge::{Kind, Manifest};
19use crate::lang::Lang;
20
21pub const FILE: &str = "pinned.json";
22pub const NOW_MS: &str = "RUST_ANYTHING_NOW_MS";
23pub const SEED: &str = "RUST_ANYTHING_SEED";
24pub const CASE: &str = "RUST_ANYTHING_CASE";
25/// Where `record --pin-clock` writes the port's helper (`mod pinned;` in `port.rs`).
26pub const HELPER: &str = "src/port/pinned.rs";
27
28#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
29pub struct Pin {
30    /// Milliseconds since the Unix epoch that every clock read returns.
31    pub now_ms: i64,
32    /// The mulberry32 seed every case starts from.
33    pub seed: u32,
34}
35
36impl Default for Pin {
37    fn default() -> Self {
38        Self {
39            now_ms: 1_700_000_000_000,
40            seed: 1,
41        }
42    }
43}
44
45/// Whether pinning reaches this crate's original and port: the Node and Python drivers, with a
46/// native port that can read environment variables.
47pub fn supported(m: &Manifest) -> bool {
48    match m.language {
49        Lang::Python => true,
50        Lang::Ts => m.kind == Kind::Napi,
51        _ => false,
52    }
53}
54
55/// The crate's pinned values, if it records with a pinned clock.
56pub fn load(crate_dir: &Path) -> Result<Option<Pin>> {
57    let path = crate_dir.join(FILE);
58    let Ok(text) = std::fs::read_to_string(&path) else {
59        return Ok(None);
60    };
61    serde_json::from_str(&text)
62        .map(Some)
63        .with_context(|| format!("reading {} (`now_ms`, `seed`)", path.display()))
64}
65
66/// Turns pinning on (keeping values already chosen) or off. Turning it on writes the port's
67/// helper when the crate has none yet, and returns its path then.
68pub fn set(crate_dir: &Path, on: bool) -> Result<Option<PathBuf>> {
69    let path = crate_dir.join(FILE);
70    if !on {
71        if path.exists() {
72            std::fs::remove_file(&path).with_context(|| format!("removing {}", path.display()))?;
73        }
74        return Ok(None);
75    }
76    let manifest = Manifest::load(crate_dir)?;
77    if !supported(&manifest) {
78        bail!(
79            "`--pin-clock` covers TS/JS units with the napi bridge and Python units; this crate is \
80             {:?} with the {:?} bridge",
81            manifest.language,
82            manifest.kind
83        );
84    }
85    let pin = load(crate_dir)?.unwrap_or_default();
86    std::fs::write(&path, serde_json::to_string_pretty(&pin)? + "\n")
87        .with_context(|| format!("writing {}", path.display()))?;
88    let helper = crate_dir.join(HELPER);
89    if helper.exists() {
90        return Ok(None);
91    }
92    std::fs::create_dir_all(helper.parent().unwrap_or(crate_dir))?;
93    std::fs::write(&helper, HELPER_RS).with_context(|| format!("writing {}", helper.display()))?;
94    Ok(Some(helper))
95}
96
97/// Sets the pinned environment on a driver command, or clears it when the crate is not pinned,
98/// so a variable left in the caller's shell cannot change a recording.
99pub fn apply(cmd: &mut Command, crate_dir: &Path) -> Result<()> {
100    match load(crate_dir)? {
101        Some(pin) => {
102            cmd.env(NOW_MS, pin.now_ms.to_string())
103                .env(SEED, pin.seed.to_string())
104                .env("TZ", "UTC")
105                .env_remove(CASE);
106        }
107        None => {
108            cmd.env_remove(NOW_MS).env_remove(SEED).env_remove(CASE);
109        }
110    }
111    Ok(())
112}
113
114/// Installed in the Node record and diff scripts after the codec: a fixed `Date` and a seeded
115/// `Math.random` when `RUST_ANYTHING_NOW_MS` is set, and `pinCase(index)` to call before each case.
116pub const PIN_JS: &str = r#"
117const pinCase = (() => {
118  const now = process.env.RUST_ANYTHING_NOW_MS
119  if (now === undefined) return () => {}
120  const nowMs = Number(now)
121  const seed = Number(process.env.RUST_ANYTHING_SEED ?? 0) >>> 0
122  let state = seed
123  const RealDate = Date
124  class PinnedDate extends RealDate {
125    constructor(...args) { super(...(args.length === 0 ? [nowMs] : args)) }
126    static now() { return nowMs }
127    static [Symbol.hasInstance](v) { return v instanceof RealDate }
128  }
129  globalThis.Date = new Proxy(PinnedDate, { apply: () => new RealDate(nowMs).toString() })
130  Math.random = () => {
131    state = (state + 0x6D2B79F5) >>> 0
132    let t = state
133    t = Math.imul(t ^ (t >>> 15), t | 1)
134    t ^= t + Math.imul(t ^ (t >>> 7), t | 61)
135    return ((t ^ (t >>> 14)) >>> 0) / 4294967296
136  }
137  return (index) => {
138    state = seed
139    process.env.RUST_ANYTHING_CASE = String(index)
140  }
141})()
142"#;
143
144/// The port's side: `src/port/pinned.rs`, declared with `mod pinned;` in `port.rs`.
145pub const HELPER_RS: &str = r#"//! The clock and random numbers the original saw while rust-anything recorded it.
146//!
147//! Written by `rust-anything record --pin-clock`. Declare it with `mod pinned;` in `port.rs`,
148//! then call `pinned::now_ms()` where the original reads the clock and `pinned::random()` where
149//! it draws a random number. While `record`, `diff`, `fuzz` and `gate` run, the clock is fixed at
150//! `RUST_ANYTHING_NOW_MS` (time zone UTC) and the numbers come from mulberry32 seeded with
151//! `RUST_ANYTHING_SEED`, restarted at every case (the drivers change `RUST_ANYTHING_CASE` between
152//! cases). Without those variables (in production) the real clock and a clock seed are used.
153//!
154//! The generator, as the drivers run it, on wrapping `u32` arithmetic:
155//!
156//! ```text
157//! state = state + 0x6D2B79F5
158//! t = (state ^ (state >> 15)) * (state | 1)
159//! t = t ^ (t + (t ^ (t >> 7)) * (t | 61))
160//! next_u32 = t ^ (t >> 14)
161//! ```
162//!
163//! JS `Math.random()` and Python `random.random()` are `next_u32() / 2^32`. Python's
164//! `getrandbits(k)` is `next_u32() >> (32 - k)` up to 32 bits and fills wider values 32 bits at a
165//! time from the low end; `randint`, `choice`, `shuffle` and the other `random` functions are
166//! CPython's own on top of those two, drawing indexes with `randbelow`. `random.seed()` does
167//! nothing while pinned. `Date.now()`, `new Date()` and `Date()` read `now_ms()`; `time.time()`,
168//! `datetime.now()`, `datetime.utcnow()` and `date.today()` read `now_secs()`.
169
170#![allow(dead_code)]
171
172use std::cell::Cell;
173use std::time::{SystemTime, UNIX_EPOCH};
174
175thread_local! {
176    static STATE: Cell<(Option<u64>, u32, bool)> = const { Cell::new((None, 0, false)) };
177}
178
179fn var<T: std::str::FromStr>(name: &str) -> Option<T> {
180    std::env::var(name).ok()?.parse().ok()
181}
182
183fn real_ms() -> f64 {
184    SystemTime::now()
185        .duration_since(UNIX_EPOCH)
186        .map_or(0.0, |d| d.as_secs_f64() * 1000.0)
187}
188
189/// Milliseconds since the Unix epoch, like JS `Date.now()`.
190pub fn now_ms() -> f64 {
191    var::<i64>("RUST_ANYTHING_NOW_MS").map_or_else(|| real_ms().floor(), |ms| ms as f64)
192}
193
194/// Seconds since the Unix epoch, like Python `time.time()`.
195pub fn now_secs() -> f64 {
196    var::<i64>("RUST_ANYTHING_NOW_MS").map_or_else(|| real_ms() / 1000.0, |ms| ms as f64 / 1000.0)
197}
198
199/// The next 32 random bits.
200pub fn next_u32() -> u32 {
201    let seed = var::<u32>("RUST_ANYTHING_SEED");
202    let case = var::<u64>("RUST_ANYTHING_CASE");
203    STATE.with(|cell| {
204        let (last_case, mut state, started) = cell.get();
205        if !started || (seed.is_some() && case != last_case) {
206            state = seed.unwrap_or_else(|| real_ms().to_bits() as u32);
207        }
208        state = state.wrapping_add(0x6D2B_79F5);
209        let mut t = (state ^ (state >> 15)).wrapping_mul(state | 1);
210        t ^= t.wrapping_add((t ^ (t >> 7)).wrapping_mul(t | 61));
211        cell.set((case, state, true));
212        t ^ (t >> 14)
213    })
214}
215
216/// A float in `[0, 1)`, like JS `Math.random()` and Python `random.random()`.
217pub fn random() -> f64 {
218    f64::from(next_u32()) / 4_294_967_296.0
219}
220
221/// Python's `random.getrandbits(k)`, for `k` up to 64.
222pub fn getrandbits(k: u32) -> u64 {
223    assert!(k <= 64, "getrandbits takes at most 64 bits here");
224    match k {
225        0 => 0,
226        1..=32 => u64::from(next_u32() >> (32 - k)),
227        _ => {
228            let low = u64::from(next_u32());
229            low | (u64::from(next_u32() >> (64 - k)) << 32)
230        }
231    }
232}
233
234/// CPython's `Random._randbelow(n)`: an integer in `[0, n)`, as `randint`, `randrange`,
235/// `choice` and `shuffle` draw them.
236pub fn randbelow(n: u64) -> u64 {
237    if n == 0 {
238        return 0;
239    }
240    let k = 64 - n.leading_zeros();
241    loop {
242        let r = getrandbits(k);
243        if r < n {
244            return r;
245        }
246    }
247}
248"#;
249
250#[cfg(test)]
251mod tests {
252    use super::*;
253
254    fn mulberry32(seed: u32, n: usize) -> Vec<u32> {
255        let mut state = seed;
256        (0..n)
257            .map(|_| {
258                state = state.wrapping_add(0x6D2B_79F5);
259                let mut t = (state ^ (state >> 15)).wrapping_mul(state | 1);
260                t ^= t.wrapping_add((t ^ (t >> 7)).wrapping_mul(t | 61));
261                t ^ (t >> 14)
262            })
263            .collect()
264    }
265
266    #[test]
267    fn the_js_generator_is_mulberry32_and_restarts_per_case() {
268        if std::process::Command::new("node")
269            .arg("--version")
270            .output()
271            .is_err()
272        {
273            return;
274        }
275        let script = format!(
276            "{PIN_JS}\npinCase(0)\nconst a = [Math.random(), Math.random(), Math.random()]\n\
277             pinCase(1)\nconst b = Math.random()\n\
278             console.log(JSON.stringify({{ a: a.map(x => x * 4294967296), b: b * 4294967296, \
279             now: Date.now(), date: new Date().getTime(), iso: new Date(0).toISOString(), \
280             s: typeof Date(), inst: new Date() instanceof Date, \
281             case: process.env.RUST_ANYTHING_CASE }}))"
282        );
283        let out = std::process::Command::new("node")
284            .args(["--input-type=module", "-e", &script])
285            .env(NOW_MS, "1700000000000")
286            .env(SEED, "7")
287            .output()
288            .unwrap();
289        assert!(
290            out.status.success(),
291            "{}",
292            String::from_utf8_lossy(&out.stderr)
293        );
294        let v: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
295        let want = mulberry32(7, 3);
296        let got: Vec<u64> = v["a"]
297            .as_array()
298            .unwrap()
299            .iter()
300            .map(|x| x.as_f64().unwrap() as u64)
301            .collect();
302        assert_eq!(got, want.iter().map(|&x| u64::from(x)).collect::<Vec<_>>());
303        assert_eq!(v["b"].as_f64().unwrap() as u32, want[0]);
304        assert_eq!(v["now"], 1_700_000_000_000_i64);
305        assert_eq!(v["date"], 1_700_000_000_000_i64);
306        assert_eq!(v["iso"], "1970-01-01T00:00:00.000Z");
307        assert_eq!(v["s"], "string");
308        assert_eq!(v["inst"], true);
309        assert_eq!(v["case"], "1");
310    }
311}