Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / pdf / src / main / rust / src / differential_tests.rs

differential_tests.rs347 lines · 11.9 KiBRaw
1//! Differential tests: invariant and metamorphic checks that do not need an
2//! oracle.
3//!
4//! Why this module exists. Rounds 1 and 2 verified ~90 fixes by reading ISO
5//! 32000-1 and asserting what we concluded. That process cannot catch a bug
6//! where the code is SELF-CONSISTENT but our reading of the spec was WRONG,
7//! because the tests assert the same belief the code implements — they agree
8//! with us by construction. Two families of check escape that trap without
9//! needing a second implementation:
10//!
11//! * INVARIANTS that must hold whatever the right answer is. Rendering the same
12//! page twice must produce identical primitives; rendering page N must not
13//! depend on whether page M was rendered first. These are true of every
14//! conforming renderer and of every non-conforming one, so they are immune to
15//! a mistaken spec reading. They are exactly the checks that catch leaking
16//! shared state — see the `FontCacheScope` thread-local in `fonts.rs`.
17//! * METAMORPHIC relations, where a transformation of the input implies a
18//! predictable transformation of the output. We need not know where a mark
19//! belongs on a `/Rotate 90` page to know that turning the page four times
20//! must put it back where it started, or that prepending a `cm` translation
21//! must move it by exactly that vector.
22//!
23//! A reference renderer was investigated and none was usable here; see the
24//! module-level note in the report. These checks are what remains valuable
25//! regardless, and were wanted even if a reference had been found.
26//!
27//! House style follows `golden_tests.rs`: build with `lopdf`, run the real
28//! pipeline. Unlike `golden_tests.rs` this module deliberately compares EXACT
29//! fingerprints rather than meaning, because the property under test is
30//! bit-level reproducibility — a "close enough" comparison would let precisely
31//! the cache-staleness bugs being hunted slip through.
32
33use crate::*;
34use lopdf::content::{Content, Operation};
35use lopdf::{dictionary, Object, Stream};
36
37// ---------------------------------------------------------------------------
38// Exact fingerprinting of a rendered page
39//
40// `Prim` deliberately derives nothing — not `Debug`, not `PartialEq` — so the
41// determinism checks need their own total projection. Every field of every
42// variant is matched by name with no `..` rest pattern, which means adding a
43// field to `Prim` breaks THIS FILE at compile time. That is intentional: a new
44// field silently excluded from the fingerprint would quietly weaken every test
45// below into a vacuous pass.
46
47fn fnv1a(bytes: &[u8]) -> u64 {
48 let mut h: u64 = 0xcbf2_9ce4_8422_2325;
49 for &b in bytes {
50 h ^= b as u64;
51 h = h.wrapping_mul(0x100_0000_01b3);
52 }
53 h
54}
55
56/// Floats go in as raw bits, never as formatted decimals. Two renders that
57/// differ by one ULP are a determinism bug, and `{:?}` would round them into
58/// agreement and hide it. Bit equality also distinguishes `0.0` from `-0.0`.
59fn f32b(v: f32) -> String {
60 format!("{:08x}", v.to_bits())
61}
62
63fn f64b(v: f64) -> String {
64 format!("{:016x}", v.to_bits())
65}
66
67fn fp_mat(m: &Mat) -> String {
68 m.iter().map(|v| f64b(*v)).collect::<Vec<_>>().join(",")
69}
70
71fn fp_pts(pts: &[(f32, f32)]) -> String {
72 let mut s = String::with_capacity(pts.len() * 18);
73 for (x, y) in pts {
74 s.push_str(&f32b(*x));
75 s.push(':');
76 s.push_str(&f32b(*y));
77 s.push(';');
78 }
79 s
80}
81
82fn fp_path_ops(ops: &Option<Vec<PathOp>>) -> String {
83 match ops {
84 None => "none".to_string(),
85 Some(v) => v
86 .iter()
87 .map(|o| match o {
88 PathOp::Move(a, b) => format!("M{}:{}", f32b(*a), f32b(*b)),
89 PathOp::Line(a, b) => format!("L{}:{}", f32b(*a), f32b(*b)),
90 PathOp::Cubic(a, b, c, d, e, f) => format!(
91 "C{}:{}:{}:{}:{}:{}",
92 f32b(*a),
93 f32b(*b),
94 f32b(*c),
95 f32b(*d),
96 f32b(*e),
97 f32b(*f)
98 ),
99 PathOp::Close => "Z".to_string(),
100 })
101 .collect::<Vec<_>>()
102 .join(","),
103 }
104}
105
106/// A total, exact projection of one primitive to a string.
107///
108/// Bulk pixel payloads are hashed rather than inlined — a page with a 4 MB
109/// image would otherwise produce an 8 MB fingerprint per render — but the hash
110/// covers every byte, so a single differing pixel still changes the result.
111fn fp_prim(p: &Prim) -> String {
112 match p {
113 Prim::Text {
114 x,
115 y,
116 size,
117 argb,
118 text,
119 stroke_argb,
120 stroke_width,
121 advance,
122 render_mode,
123 blend,
124 is_bold,
125 is_italic,
126 font_family,
127 outline,
128 h_scale,
129 } => format!(
130 "Text|{}|{}|{}|{:08x}|{}|{:?}|{:?}|{}|{}|{}|{}|{}|{}|{}|{}",
131 f32b(*x),
132 f32b(*y),
133 f32b(*size),
134 argb,
135 text.escape_debug(),
136 stroke_argb,
137 stroke_width.map(f32b),
138 f32b(*advance),
139 render_mode,
140 *blend as u8,
141 is_bold,
142 is_italic,
143 font_family,
144 outline,
145 f32b(*h_scale)
146 ),
147 Prim::Fill { argb, even_odd, contours, blend } => format!(
148 "Fill|{:08x}|{}|{}|{}",
149 argb,
150 even_odd,
151 contours.iter().map(|c| fp_pts(c)).collect::<Vec<_>>().join("/"),
152 *blend as u8
153 ),
154 Prim::Stroke { argb, width, dash, dash_phase, cap, join, miter, pts, blend } => format!(
155 "Stroke|{:08x}|{}|{}|{}|{}|{}|{}|{}|{}",
156 argb,
157 f32b(*width),
158 dash.iter().map(|d| f32b(*d)).collect::<Vec<_>>().join(","),
159 f32b(*dash_phase),
160 cap,
161 join,
162 f32b(*miter),
163 fp_pts(pts),
164 *blend as u8
165 ),
166 Prim::Image { ctm, w, h, format, data, alpha, blend } => format!(
167 "Image|{}|{}|{}|{}|{}|{:016x}|{}|{}",
168 fp_mat(ctm),
169 w,
170 h,
171 format,
172 data.len(),
173 fnv1a(data),
174 f32b(*alpha),
175 *blend as u8
176 ),
177 Prim::ImageTiled {
178 ctm,
179 w,
180 h,
181 data,
182 xstep,
183 ystep,
184 i0,
185 j0,
186 nx,
187 ny,
188 alpha,
189 blend,
190 } => format!(
191 "ImageTiled|{}|{}|{}|{}|{:016x}|{}|{}|{}|{}|{}|{}|{}|{}",
192 fp_mat(ctm),
193 w,
194 h,
195 data.len(),
196 fnv1a(data),
197 f32b(*xstep),
198 f32b(*ystep),
199 i0,
200 j0,
201 nx,
202 ny,
203 f32b(*alpha),
204 *blend as u8
205 ),
206 Prim::ClipPush { even_odd, pts, path_ops } => {
207 format!("ClipPush|{}|{}|{}", even_odd, fp_pts(pts), fp_path_ops(path_ops))
208 }
209 Prim::ClipPop => "ClipPop".to_string(),
210 Prim::TextClipApply => "TextClipApply".to_string(),
211 Prim::GroupPush { isolated, knockout, alpha, blend } => format!(
212 "GroupPush|{}|{}|{}|{}",
213 isolated,
214 knockout,
215 f32b(*alpha),
216 *blend as u8
217 ),
218 Prim::GroupPop => "GroupPop".to_string(),
219 Prim::SoftMaskPush { mask_type } => format!("SoftMaskPush|{}", mask_type),
220 Prim::SoftMaskTransfer(lut) => format!("SoftMaskTransfer|{:016x}", fnv1a(&lut[..])),
221 Prim::SoftMaskContent => "SoftMaskContent".to_string(),
222 Prim::SoftMaskPop => "SoftMaskPop".to_string(),
223 }
224}
225
226/// Order-sensitive fingerprint of a whole rendered page, dimensions included.
227/// Order matters because primitive order IS the paint order; a renderer that
228/// emitted the same set in a different sequence would draw a different page.
229fn fingerprint(page: &PageData) -> String {
230 let mut s = format!("{}x{}\n", f32b(page.width), f32b(page.height));
231 for (i, p) in page.prims.iter().enumerate() {
232 s.push_str(&format!("{i}:{}\n", fp_prim(p)));
233 }
234 s
235}
236
237/// Where the fingerprints first diverge, for a failure message that names the
238/// offending primitive instead of dumping two multi-kilobyte blobs.
239fn first_difference(a: &str, b: &str) -> String {
240 let (mut la, mut lb) = (a.lines(), b.lines());
241 let mut n = 0;
242 loop {
243 match (la.next(), lb.next()) {
244 (None, None) => return "identical".to_string(),
245 (x, y) if x == y => n += 1,
246 (x, y) => return format!("line {n}:\n first: {x:?}\n second: {y:?}"),
247 }
248 }
249}
250
251// ---------------------------------------------------------------------------
252// Fixture builders (mirrors of the `golden_tests.rs` helpers, which are private
253// to that module)
254
255fn assemble_with_contents(
256 doc: &mut Document,
257 contents: Object,
258 resources: Dictionary,
259 page: &mut Dictionary,
260 catalog: Dictionary,
261) -> ObjectId {
262 let pages_id = doc.new_object_id();
263 page.set("Type", Object::Name(b"Page".to_vec()));
264 page.set("Parent", pages_id);
265 page.set("Resources", resources);
266 if !matches!(contents, Object::Null) {
267 page.set("Contents", contents);
268 }
269 if page.get(b"MediaBox").is_err() {
270 page.set("MediaBox", vec![0.into(), 0.into(), 612.into(), 792.into()]);
271 }
272 let page_id = doc.add_object(page.clone());
273 doc.objects.insert(
274 pages_id,
275 Object::Dictionary(dictionary! {
276 "Type" => "Pages", "Kids" => vec![page_id.into()], "Count" => 1,
277 }),
278 );
279 let mut cat = catalog;
280 cat.set("Type", Object::Name(b"Catalog".to_vec()));
281 cat.set("Pages", pages_id);
282 let catalog_id = doc.add_object(cat);
283 doc.trailer.set("Root", catalog_id);
284 page_id
285}
286
287fn assemble(
288 doc: &mut Document,
289 content: Vec<u8>,
290 resources: Dictionary,
291 mut page: Dictionary,
292) -> ObjectId {
293 let content_id = doc.add_object(Stream::new(dictionary! {}, content));
294 assemble_with_contents(
295 doc,
296 Object::Reference(content_id),
297 resources,
298 &mut page,
299 dictionary! {},
300 )
301}
302
303fn page_from_ops(doc: &mut Document, ops: Vec<Operation>, resources: Dictionary) -> ObjectId {
304 let bytes = Content { operations: ops }.encode().unwrap();
305 assemble(doc, bytes, resources, dictionary! {})
306}
307
308/// Build a many-page document. `per_page` supplies the operator list and the
309/// resource dictionary for page `i`, so callers can give each page a distinct
310/// font object — the arrangement that would expose a font cache keyed on the
311/// resource NAME rather than the font object's id.
312fn multi_page_doc<F>(n: usize, mut per_page: F) -> (Document, Vec<ObjectId>)
313where
314 F: FnMut(&mut Document, usize) -> (Vec<Operation>, Dictionary),
315{
316 let mut doc = Document::with_version("1.5");
317 let pages_id = doc.new_object_id();
318 let mut page_ids = Vec::new();
319 for i in 0..n {
320 let (ops, resources) = per_page(&mut doc, i);
321 let content_id =
322 doc.add_object(Stream::new(dictionary! {}, Content { operations: ops }.encode().unwrap()));
323 let page_id = doc.add_object(dictionary! {
324 "Type" => "Page",
325 "Parent" => pages_id,
326 "MediaBox" => vec![0.into(), 0.into(), 300.into(), 200.into()],
327 "Contents" => content_id,
328 "Resources" => resources,
329 });
330 page_ids.push(page_id);
331 }
332 doc.objects.insert(
333 pages_id,
334 Object::Dictionary(dictionary! {
335 "Type" => "Pages",
336 "Kids" => page_ids.iter().map(|id| Object::Reference(*id)).collect::<Vec<_>>(),
337 "Count" => n as i64,
338 }),
339 );
340 let catalog_id = doc.add_object(dictionary! { "Type" => "Catalog", "Pages" => pages_id });
341 doc.trailer.set("Root", catalog_id);
342 (doc, page_ids)
343}
344
345include!("differential_tests_part1.rs");
346include!("differential_tests_part2.rs");
347include!("differential_tests_part3.rs");