Skip to main content

labstream_proto/
canon.rs

1//! The canonicalizer for transcript comparison.
2//!
3//! A handshake carries fields that change between runs: a UID, a clock
4//! reading, an ephemeral port, a host name, and a measured benchmark result.
5//! A transcript comparison cannot compare them directly.
6//!
7//! The rule that keeps this honest: **every placeholder carries a predicate**.
8//! A field that gets erased with no assertion is a silent hole in coverage. A
9//! rule with no predicate fails the lint in `lint()`, so the hole cannot ship.
10//!
11//! Read `CONFORMANCE-PLAN.md` risk R3.
12
13use core::fmt;
14
15/// What a canonical rule asserts about the value that it erases.
16pub enum Predicate {
17    /// The value holds a UID of this shape: 8-4-4-4-12 hexadecimal digits.
18    Uuid,
19    /// The value parses as an integer inside these bounds.
20    IntInRange(i64, i64),
21    /// The value parses as a real number inside these bounds.
22    F64InRange(f64, f64),
23    /// The value parses as a real number. Any value passes.
24    ///
25    /// This is for a measured benchmark result, whose value carries no meaning
26    /// across machines. SPEC.md 5.2.
27    F64Any,
28    /// The value holds at least one character.
29    NonEmpty,
30    /// The value holds any text, including none.
31    ///
32    /// Use this only for a field that carries no protocol meaning. State the
33    /// reason in the rule.
34    AnyText,
35}
36
37impl Predicate {
38    /// Test one value.
39    pub fn test(&self, value: &str) -> Result<(), String> {
40        match self {
41            Predicate::Uuid => {
42                let parts: Vec<&str> = value.split('-').collect();
43                let ok = parts.len() == 5
44                    && [8usize, 4, 4, 4, 12]
45                        == [
46                            parts[0].len(),
47                            parts[1].len(),
48                            parts[2].len(),
49                            parts[3].len(),
50                            parts[4].len(),
51                        ]
52                    && parts
53                        .iter()
54                        .all(|p| p.chars().all(|c| c.is_ascii_hexdigit()));
55                if ok {
56                    Ok(())
57                } else {
58                    Err(format!("{value:?} is not a UID of the shape 8-4-4-4-12"))
59                }
60            }
61            Predicate::IntInRange(lo, hi) => match value.trim().parse::<i64>() {
62                Ok(v) if v >= *lo && v <= *hi => Ok(()),
63                Ok(v) => Err(format!("{v} is outside {lo} to {hi}")),
64                Err(_) => Err(format!("{value:?} is not an integer")),
65            },
66            Predicate::F64InRange(lo, hi) => match value.trim().parse::<f64>() {
67                Ok(v) if v >= *lo && v <= *hi => Ok(()),
68                Ok(v) => Err(format!("{v} is outside {lo} to {hi}")),
69                Err(_) => Err(format!("{value:?} is not a real number")),
70            },
71            Predicate::F64Any => match value.trim().parse::<f64>() {
72                Ok(_) => Ok(()),
73                Err(_) => Err(format!("{value:?} is not a real number")),
74            },
75            Predicate::NonEmpty => {
76                if value.trim().is_empty() {
77                    Err("the value is empty".to_string())
78                } else {
79                    Ok(())
80                }
81            }
82            Predicate::AnyText => Ok(()),
83        }
84    }
85}
86
87/// One rule: a header name, a placeholder, a predicate, and the reason.
88pub struct Rule {
89    /// The header name, in lower case.
90    pub field: &'static str,
91    /// The text that replaces the value.
92    pub placeholder: &'static str,
93    /// What the rule asserts about the value that it erases.
94    pub predicate: Predicate,
95    /// Why the value cannot be compared directly.
96    pub reason: &'static str,
97}
98
99/// The rules for a feed handshake.
100///
101/// Each entry names a field that changes between runs. A field that is stable
102/// belongs in no rule, because a direct comparison is stronger.
103pub fn feed_rules() -> Vec<Rule> {
104    vec![
105        Rule {
106            field: "uid",
107            placeholder: "<UID>",
108            predicate: Predicate::Uuid,
109            reason: "a stream instance identifier is random, and it changes on every restart",
110        },
111        Rule {
112            field: "endian-performance",
113            placeholder: "<PERF>",
114            predicate: Predicate::F64Any,
115            reason: "a measured benchmark result. SPEC.md 5.2 records it as observed",
116        },
117        Rule {
118            field: "hostname",
119            placeholder: "<HOST>",
120            predicate: Predicate::AnyText,
121            reason: "a property of the machine. An empty value is legal",
122        },
123        Rule {
124            field: "source-id",
125            placeholder: "<SOURCE>",
126            predicate: Predicate::AnyText,
127            reason: "chosen by the application. An empty value is legal",
128        },
129    ]
130}
131
132/// A field that a rule erased, with the value that it held.
133#[derive(Debug, Clone, PartialEq, Eq)]
134pub struct Erased {
135    /// The header name.
136    pub field: String,
137    /// The value that the rule replaced.
138    pub value: String,
139}
140
141/// The result of canonicalizing one block.
142#[derive(Debug, Clone, PartialEq, Eq)]
143pub struct Canonical {
144    /// The text with every variable value replaced.
145    pub text: String,
146    /// Every value that a rule erased.
147    pub erased: Vec<Erased>,
148}
149
150impl fmt::Display for Canonical {
151    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
152        write!(f, "{}", self.text)
153    }
154}
155
156/// A predicate that failed on a value that a rule erased.
157#[derive(Debug, Clone, PartialEq, Eq)]
158pub struct Violation {
159    /// The header name.
160    pub field: String,
161    /// The value that failed.
162    pub value: String,
163    /// What the predicate reported.
164    pub problem: String,
165}
166
167/// Replace every variable value in a header block.
168///
169/// The function keeps the line order and the field names. It replaces only the
170/// values that a rule names.
171pub fn canonicalize(block: &str, rules: &[Rule]) -> Canonical {
172    let mut out = String::with_capacity(block.len());
173    let mut erased = Vec::new();
174
175    for line in block.split_inclusive('\n') {
176        let body = line.trim_end_matches(['\r', '\n']);
177        let mut replaced = false;
178
179        if let Some(colon) = body.find(':') {
180            let name = body[..colon].trim().to_ascii_lowercase();
181            if let Some(rule) = rules.iter().find(|r| r.field == name) {
182                let value = body[colon + 1..].trim().to_string();
183                erased.push(Erased { field: name, value });
184                out.push_str(&body[..colon + 1]);
185                out.push(' ');
186                out.push_str(rule.placeholder);
187                out.push_str("\r\n");
188                replaced = true;
189            }
190        }
191        if !replaced {
192            out.push_str(body);
193            out.push_str("\r\n");
194        }
195    }
196    Canonical { text: out, erased }
197}
198
199/// Test every erased value against the predicate of its rule.
200///
201/// A rule that erases a value must say something about it. This function is
202/// what turns a placeholder from a blind spot into an assertion.
203pub fn check(canonical: &Canonical, rules: &[Rule]) -> Vec<Violation> {
204    let mut out = Vec::new();
205    for e in &canonical.erased {
206        let rule = match rules.iter().find(|r| r.field == e.field) {
207            Some(r) => r,
208            None => continue,
209        };
210        if let Err(problem) = rule.predicate.test(&e.value) {
211            out.push(Violation {
212                field: e.field.clone(),
213                value: e.value.clone(),
214                problem,
215            });
216        }
217    }
218    out
219}
220
221/// A rule that fails the lint.
222#[derive(Debug, Clone, PartialEq, Eq)]
223pub struct LintFailure {
224    /// The header name.
225    pub field: String,
226    /// What is wrong with the rule.
227    pub problem: String,
228}
229
230/// Make sure that every rule carries a real predicate and a reason.
231///
232/// A placeholder with no assertion hides a difference. This lint is the check
233/// that risk R3 of the conformance plan asks for.
234///
235/// `Predicate::AnyText` asserts nothing, so a rule that uses it must give a
236/// reason of its own. The lint accepts it only with a reason that names why
237/// the field carries no protocol meaning.
238pub fn lint(rules: &[Rule]) -> Vec<LintFailure> {
239    let mut out = Vec::new();
240    for r in rules {
241        if r.reason.trim().is_empty() {
242            out.push(LintFailure {
243                field: r.field.to_string(),
244                problem: "the rule gives no reason".into(),
245            });
246        }
247        if r.placeholder.trim().is_empty() {
248            out.push(LintFailure {
249                field: r.field.to_string(),
250                problem: "the rule gives no placeholder".into(),
251            });
252        }
253        if matches!(r.predicate, Predicate::AnyText) && r.reason.len() < 20 {
254            out.push(LintFailure {
255                field: r.field.to_string(),
256                problem: "a rule that asserts nothing needs a reason that explains why".into(),
257            });
258        }
259    }
260    out
261}
262
263#[cfg(test)]
264mod tests {
265    use super::*;
266
267    const ANSWER: &str = "LSL/110 200 OK\r\nUID: 0b4645ec-dd4b-4582-a256-36119e117403\r\n\
268        Byte-Order: 1234\r\nSuppress-Subnormals: 0\r\nData-Protocol-Version: 110\r\n\r\n";
269
270    #[test]
271    fn every_rule_passes_the_lint() {
272        let failures = lint(&feed_rules());
273        assert!(failures.is_empty(), "the rules fail the lint: {failures:?}");
274    }
275
276    #[test]
277    fn a_rule_with_no_reason_fails_the_lint() {
278        let bad = vec![Rule {
279            field: "uid",
280            placeholder: "<UID>",
281            predicate: Predicate::Uuid,
282            reason: "",
283        }];
284        assert_eq!(lint(&bad).len(), 1);
285    }
286
287    #[test]
288    fn a_rule_that_asserts_nothing_needs_a_full_reason() {
289        let bad = vec![Rule {
290            field: "hostname",
291            placeholder: "<HOST>",
292            predicate: Predicate::AnyText,
293            reason: "varies",
294        }];
295        assert_eq!(lint(&bad).len(), 1);
296    }
297
298    #[test]
299    fn the_uid_is_replaced_and_the_rest_stays() {
300        let c = canonicalize(ANSWER, &feed_rules());
301        assert!(c.text.contains("UID: <UID>"));
302        assert!(c.text.contains("Byte-Order: 1234"));
303        assert!(c.text.contains("Data-Protocol-Version: 110"));
304        assert_eq!(c.erased.len(), 1);
305        assert_eq!(c.erased[0].value, "0b4645ec-dd4b-4582-a256-36119e117403");
306    }
307
308    #[test]
309    fn two_answers_with_different_uids_agree_after_canonicalizing() {
310        let other = ANSWER.replace(
311            "0b4645ec-dd4b-4582-a256-36119e117403",
312            "25cfa701-e55b-4e42-8fc2-103bbd2f86b6",
313        );
314        assert_eq!(
315            canonicalize(ANSWER, &feed_rules()).text,
316            canonicalize(&other, &feed_rules()).text
317        );
318    }
319
320    #[test]
321    fn the_predicate_catches_a_uid_of_the_wrong_shape() {
322        let bad = ANSWER.replace("0b4645ec-dd4b-4582-a256-36119e117403", "not-a-uid");
323        let c = canonicalize(&bad, &feed_rules());
324        let v = check(&c, &feed_rules());
325        assert_eq!(v.len(), 1);
326        assert_eq!(v[0].field, "uid");
327    }
328
329    #[test]
330    fn a_good_answer_raises_no_violation() {
331        let c = canonicalize(ANSWER, &feed_rules());
332        assert!(check(&c, &feed_rules()).is_empty());
333    }
334
335    #[test]
336    fn a_measured_value_must_still_parse() {
337        let rules = feed_rules();
338        let good = canonicalize("Endian-Performance: 12345\r\n", &rules);
339        assert!(check(&good, &rules).is_empty());
340        let bad = canonicalize("Endian-Performance: fast\r\n", &rules);
341        assert_eq!(check(&bad, &rules).len(), 1);
342    }
343
344    #[test]
345    fn a_stable_field_is_never_erased() {
346        // Byte-Order carries protocol meaning, so no rule touches it. A
347        // transcript comparison must see a change in this field.
348        let c = canonicalize(ANSWER, &feed_rules());
349        assert!(!c.erased.iter().any(|e| e.field == "byte-order"));
350        let changed = ANSWER.replace("Byte-Order: 1234", "Byte-Order: 4321");
351        assert_ne!(c.text, canonicalize(&changed, &feed_rules()).text);
352    }
353}