ifc_lite_geometry/test_support.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//! Test-harness helpers shared by the termination/deadlock suites.
6//!
7//! Compiled only under `cfg(test)` or the `test-support` feature, which no
8//! shipping build enables (same shape as `triangulation-alt`). The feature
9//! exists so `ifc-lite-processing`'s integration tests can reach
10//! [`recv_or_diagnose`] too — the alternative was a seventh hand-written copy
11//! of the same two-arm match.
12
13use std::sync::mpsc::{Receiver, RecvTimeoutError};
14use std::time::Duration;
15
16/// Undirected edges NOT shared by exactly two triangles, vertices keyed by
17/// exact f32 bits: 0 on a closed 2-manifold whose coincident vertices share
18/// bit patterns (the extrusion and T-junction repair tests, #5313).
19#[cfg(test)]
20pub(crate) fn open_edges(m: &crate::Mesh) -> usize {
21 use crate::mesh_check::{Degenerate, EdgeLedger, VertexKey};
22 EdgeLedger::build(m, VertexKey::Bits, Degenerate::SkipEdge).undirected_defects()
23}
24
25/// Receive one value from a watchdogged worker, or panic with the diagnosis
26/// that actually fits what happened.
27///
28/// `recv_timeout` returns `Err` for BOTH `Timeout` and `Disconnected`, so a
29/// harness that tests `is_ok()` — or collapses the two `Err` arms into one —
30/// reports a worker PANIC as a hang. That is a confident wrong diagnosis: it
31/// sends the reader after a termination guard that is working fine, while the
32/// real panic scrolls past unread (#2945).
33///
34/// The two states therefore get two messages, chosen by the caller:
35/// - `Timeout` — nothing arrived and the sender is still alive: a real hang.
36/// Panics with `hung_msg`.
37/// - `Disconnected` — the sender was dropped without sending, which for these
38/// suites means the worker unwound. Panics with `panicked_msg`.
39///
40/// The match is exhaustive by variant with no wildcard arm, so a future third
41/// `RecvTimeoutError` state fails to compile here rather than being silently
42/// folded into one of the existing diagnoses.
43///
44/// Note the honest limit of `Disconnected`: it says the sender is gone, not
45/// why. A worker that returns early without sending is reported as a panic.
46/// Every caller here sends on its last line, so the two coincide.
47#[track_caller]
48pub fn recv_or_diagnose<T>(
49 rx: &Receiver<T>,
50 timeout: Duration,
51 hung_msg: &str,
52 panicked_msg: &str,
53) -> T {
54 match rx.recv_timeout(timeout) {
55 Ok(value) => value,
56 Err(RecvTimeoutError::Timeout) => panic!("{hung_msg}"),
57 Err(RecvTimeoutError::Disconnected) => panic!("{panicked_msg}"),
58 }
59}
60
61#[cfg(test)]
62mod tests {
63 use super::*;
64
65 const HUNG: &str = "WORKER HUNG (walk did not terminate)";
66 const PANICKED: &str = "WORKER PANICKED (not a hang)";
67
68 /// A genuine hang must never be diagnosed as a hang for only ~0.2s of
69 /// wall clock, so the meta-tests use a deliberately tiny timeout. The
70 /// production call sites use 5-180s; the helper's behaviour does not
71 /// depend on the magnitude.
72 const SHORT: Duration = Duration::from_millis(200);
73
74 /// Run `f`, returning the panic message it produced (panic output
75 /// suppressed so a passing meta-test does not print a scary backtrace).
76 fn panic_message(f: impl FnOnce() + std::panic::UnwindSafe) -> String {
77 let prev = std::panic::take_hook();
78 std::panic::set_hook(Box::new(|_| {}));
79 let payload = std::panic::catch_unwind(f);
80 std::panic::set_hook(prev);
81 let payload = payload.expect_err("the helper was expected to panic");
82 payload
83 .downcast_ref::<String>()
84 .cloned()
85 .or_else(|| payload.downcast_ref::<&str>().map(|s| (*s).to_string()))
86 .expect("panic payload should be a string")
87 }
88
89 /// Direction 1 — a worker that PANICS must be diagnosed as a panic.
90 ///
91 /// This is the #2945 defect itself: the worker's `tx` is dropped by the
92 /// unwind, `recv_timeout` returns `Disconnected`, and a harness that does
93 /// not split the two `Err` variants blames a hang.
94 #[test]
95 fn a_panicking_worker_is_diagnosed_as_a_panic_not_a_hang() {
96 let (tx, rx) = std::sync::mpsc::channel::<u32>();
97 let worker = std::thread::spawn(move || {
98 let _tx = tx;
99 std::panic::panic_any("worker exploded");
100 });
101
102 // A long timeout: if this were reported as a hang it could only be
103 // because the variants were conflated, not because time ran out.
104 let msg = panic_message(|| {
105 recv_or_diagnose(&rx, Duration::from_secs(30), HUNG, PANICKED);
106 });
107
108 assert_eq!(msg, PANICKED, "a dropped sender must read as a worker panic");
109 assert_ne!(msg, HUNG, "a panicking worker must NOT be called a hang");
110 let _ = worker.join();
111 }
112
113 /// Direction 2 — a worker that genuinely HANGS must be diagnosed as a
114 /// hang. The mirror of the test above, and the half that is usually
115 /// missing: a fix that simply renamed every `Err` to "PANICKED" would
116 /// pass direction 1 and be just as wrong.
117 #[test]
118 fn a_hanging_worker_is_diagnosed_as_a_hang_not_a_panic() {
119 let (tx, rx) = std::sync::mpsc::channel::<u32>();
120 // Sender kept ALIVE and never used: the channel stays connected, so
121 // the only reachable `Err` is `Timeout`.
122 let _keep_alive = tx;
123
124 let msg = panic_message(|| {
125 recv_or_diagnose(&rx, SHORT, HUNG, PANICKED);
126 });
127
128 assert_eq!(msg, HUNG, "a live sender that never sends must read as a hang");
129 assert_ne!(msg, PANICKED, "a genuine hang must NOT be called a panic");
130 }
131
132 /// The success path returns the value and panics with neither message.
133 #[test]
134 fn a_worker_that_answers_returns_its_value() {
135 let (tx, rx) = std::sync::mpsc::channel();
136 let worker = std::thread::spawn(move || {
137 let _ = tx.send(7_u32);
138 });
139 assert_eq!(recv_or_diagnose(&rx, Duration::from_secs(30), HUNG, PANICKED), 7);
140 let _ = worker.join();
141 }
142}