ifc_lite_geometry/
output_policy_generation.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Mutation generation for the process-global output policy (PR #9614 review
6//! 2, R2-1; writer serialisation from review 3, R3-2).
7//!
8//! Comparing policy VALUES before and after a pass cannot see a change that is
9//! undone before the pass ends (A -> B -> A): products meshed under B, and the
10//! result would be stored under A's key. Every policy setter instead runs
11//! through [`mutate`], which advances this counter to odd before its store and
12//! to even after it, seqlock style. A reader that sees the same even value
13//! before and after a window knows no setter ran during it, however many
14//! times a value flipped.
15//!
16//! Ordering: a setter's first increment is sequenced before its `Release`
17//! store; a pipeline thread that observes the new value through an `Acquire`
18//! load synchronizes with that store, and the caller joins the pipeline's
19//! threads before it reads the counter again, so the increment is visible to
20//! that read. Environment knobs are read once per process (`OnceLock`), so
21//! they cannot change inside a window at all.
22
23use std::sync::atomic::{AtomicU64, Ordering};
24use std::sync::Mutex;
25
26static GENERATION: AtomicU64 = AtomicU64::new(0);
27
28/// Serialises writers (PR #9614 review 3, R3-2). With two writers each doing
29/// their own increment, both "before" bumps could land first and leave the
30/// counter EVEN while both stores were still pending, so a reader would
31/// accept a window in which the policy changed. One writer at a time keeps
32/// the protocol a true single-writer seqlock: odd exactly while a store is in
33/// progress, and every completed store moves it by two.
34static WRITER: Mutex<()> = Mutex::new(());
35
36/// Returns the counter to even even if `store` unwinds, so a panicking setter
37/// cannot leave every later reader refusing to cache.
38struct Close;
39
40impl Drop for Close {
41    fn drop(&mut self) {
42        GENERATION.fetch_add(1, Ordering::SeqCst);
43    }
44}
45
46/// Run one policy store between the two generation bumps, holding the writer
47/// lock across both.
48pub(crate) fn mutate<T>(store: impl FnOnce() -> T) -> T {
49    let _writer = WRITER.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
50    GENERATION.fetch_add(1, Ordering::SeqCst);
51    let _close = Close;
52    store()
53}
54
55/// The current mutation generation. Odd while a setter is mid-store.
56pub fn policy_generation() -> u64 {
57    GENERATION.load(Ordering::SeqCst)
58}
59
60/// A coherent policy: read between two equal, even generations. `None` when
61/// setters kept racing the read (eight attempts); the caller must not cache.
62pub fn coherent_output_policy() -> Option<(u64, super::OutputPolicy)> {
63    for _ in 0..8 {
64        let before = policy_generation();
65        if before % 2 == 1 {
66            std::hint::spin_loop();
67            continue;
68        }
69        let policy = super::effective_output_policy();
70        if policy_generation() == before {
71            return Some((before, policy));
72        }
73    }
74    None
75}
76
77#[cfg(test)]
78mod tests {
79    use super::*;
80    use std::sync::{mpsc, Arc, Barrier};
81    use std::time::{Duration, Instant};
82
83    /// R3-2, the reviewer's schedule: writer A is inside its store when writer
84    /// B starts. At 32d3c1a3 B's first bump landed beside A's, the counter read
85    /// even (2) with both stores pending, and a reader accepted that window.
86    /// Now B waits for A, the counter stays odd while A is inside, and no
87    /// coherent policy can be read until A finishes. The stores here are
88    /// no-ops, so no other test sees a changed policy.
89    #[test]
90    fn overlapping_writers_never_expose_an_even_generation_mid_store() {
91        let start = policy_generation();
92        let inside = Arc::new(Barrier::new(2));
93        let (release_tx, release_rx) = mpsc::channel::<()>();
94        let a = {
95            let inside = inside.clone();
96            std::thread::spawn(move || {
97                mutate(|| {
98                    inside.wait();
99                    release_rx.recv().unwrap();
100                })
101            })
102        };
103        inside.wait();
104        // Writer B also stays inside its store once it gets there. Before the
105        // fix it got there at once, beside A, and the two first bumps left the
106        // counter even with both stores pending. Now it waits for A's lock.
107        let (b_started_tx, b_started_rx) = mpsc::channel::<()>();
108        let (b_release_tx, b_release_rx) = mpsc::channel::<()>();
109        let b = std::thread::spawn(move || {
110            b_started_tx.send(()).unwrap();
111            mutate(|| {
112                b_release_rx.recv().unwrap();
113            });
114        });
115        b_started_rx.recv().unwrap();
116        let deadline = Instant::now() + Duration::from_millis(300);
117        while Instant::now() < deadline {
118            assert_eq!(policy_generation() % 2, 1, "generation went even while a writer was mid-store");
119            std::thread::yield_now();
120        }
121        assert!(coherent_output_policy().is_none(), "a coherent policy was read during a store");
122        release_tx.send(()).unwrap();
123        a.join().unwrap();
124        b_release_tx.send(()).unwrap();
125        b.join().unwrap();
126        assert!(policy_generation() >= start + 4, "each completed store moves the generation by two");
127    }
128
129    /// Without the unwind guard a panicking store would leave the counter odd
130    /// for good, and no later reader could ever read a coherent policy.
131    #[test]
132    fn a_panicking_store_still_closes_the_generation() {
133        let _ = std::panic::catch_unwind(|| mutate(|| panic!("setter failed")));
134        let deadline = Instant::now() + Duration::from_secs(5);
135        while coherent_output_policy().is_none() {
136            assert!(Instant::now() < deadline, "generation stuck odd after a panicking store");
137            std::thread::yield_now();
138        }
139    }
140}