Case study 2

Same PDF, different text every run

khpdf read the same UNDP report 20 times and gave four different answers. The Khmer code was fine. The cause was a race inside the PDF library, set off by a file that had been saved four times. The first fix made the answer stable but wrong; the second made it right.

4 outputsfrom 20 runs of the same command on the same file
4 copiesof page 3 inside the file, from three save sessions within six minutes
8 of 11pages wrong after the first fix, which made every run identical
The symptom

Run it again

The file is the Khmer edition of UNDP's 2024 Asia-Pacific Human Development Report overview, 11 pages made in InDesign. Each button press below replays one of 20 real runs of khpdf built the old way, in the order they happened. The fingerprint is a checksum of the whole JSON output: same fingerprint, same output.

Run 0 of 20 no output yet
page 1page 11
page matches what PDF viewers show page read from an older save

Real outputs of khpdf -f json samples/undp-hdr-2024.pdf, 20 runs with lopdf's default (parallel) loading and without the fix. Page 3 is the overview's first page; its printed page number is 2.

Four different outputs. The differences weren't random noise either: whole Khmer lines appeared and disappeared, such as the page header ទិដ្ឋភាពទូទៅ ("Overview"), and page 3 had five, six or seven fonts depending on the run.

The suspects

Not the refactor, not the Khmer

Suspect 1: the code had just been reorganized. The obvious guess was a bug introduced by that refactor. But rebuilding the first commit, from before it, and running it 12 times on the same file gives 4 different outputs too. The bug is older than the refactor.

Suspect 2: the Khmer processing. The differences weren't in how letters were decoded. They were in what there was to decode: whole lines missing, and a different list of fonts for the same page. A page's fonts are written in the page's own record inside the PDF, before any Khmer processing starts. So the question became: why would the same file give different records for page 3?

In plain words: when a program gives different answers to the same question, look for the thing that isn't the same each time. Here it wasn't khpdf's logic, it was which version of a page the PDF library handed to it.
Inside the file

A file saved four times

In plain words: a PDF can be edited without rewriting it. The new versions of changed pages are added at the end, like corrections stuck to the back of a notebook, together with a new index saying where the current version of everything is. The old versions stay in the file. A reader is supposed to follow the newest index.

This file ends four times (it contains four %%EOF markers): the original export and three incremental updates. Pages 2 to 10 were saved again in the second part, page 3 again in the third, and page 10 again in the fourth. The pages' own timestamps run from 17:06 to 17:14 on 15 February 2024, eight minutes from first to last.

byte 0

Copies, fonts and timestamps read from the file's object streams. Which copy each parallel run used is read off that run's output; the two copies saved in part 2 are identical, so they count as one. Page 2 is left out: its copies produce the same text.

The race

First come, first kept

PDFs compress small records, like a page's description, into object streams: bundles of many records. In this file the record for page 3 sits in four bundles, one from each save, and only the newest index knows which one is current.

khpdf uses the Rust library lopdf (version 0.35) to read the file. By default lopdf unpacks all bundles at the same time on several threads. Each thread adds its records to one shared list when it finishes. Afterwards, lopdf walks that list and keeps the first copy of each record it meets, ignoring later ones. So the copy of page 3 that wins is the one whose bundle happened to finish unpacking first. That depends on thread timing, which changes from run to run.

16650 · part 1 · 19 records
16853 · part 2 · 9 records
16854 · part 2 · 9 records
16857 · part 3 · page 3
16862 · part 4 · page 10
One shared list, in the order the threads finish
Keep the first copy of each record; later copies are dropped

The five bundles in this file that hold page records (it has 17 bundles in all). Unpacking happens on whichever threads are free, so the finishing order, and with it the winner, varies.

Technical detail: the code in lopdf 0.35

From src/reader.rs. The closure runs for every cross-reference entry; for object streams it extends a shared vector under a mutex. With the rayon feature (on by default) the entries are processed by par_iter(). Afterwards each object is inserted only if no entry for it exists yet. The authors had flagged the question in a comment, "TODO: Is insert and replace intended behavior?", pointing to lopdf issue #160.

lopdf 0.35 · src/reader.rs (abridged)
if stream.dict.has_type(b"ObjStm") {
    let obj_stream = ObjectStream::new(stream).ok()?;
    let mut object_streams = object_streams.lock().unwrap();
    object_streams.extend(obj_stream.objects);
}
// ...
#[cfg(feature = "rayon")]
self.document.objects = self.document.reference_table.entries
    .par_iter().filter_map(entries_filter_map).collect();
// ...
// Only add entries, but never replace entries
for (id, entry) in object_streams.into_inner().unwrap() {
    self.document.objects.entry(id).or_insert(entry);
}
First fix

Stable, and stably wrong

If threads cause the randomness, remove the threads. Turning off lopdf's rayon feature makes it unpack bundles one at a time, in order of their object number. The output became identical on every run. But "the same every time" isn't "correct": bundle 16650, from the original export, has the lowest number, so it now always won. Every page record with several copies came from the first save.

page 1page 11

One-thread loading, 5 runs, one fingerprint. Pages 3 to 10 differ from what viewers show. Page 3 has 5 fonts instead of 7: three of its five Kantumruy Pro Type0 fonts (C2_0 to C2_2), no ទិដ្ឋភាពទូទៅ header, and a footer that is just the page number.

This would pass any "same output every time" check. Comparing with an independent reader shows the problem: pypdf finds seven fonts on page 3, this build finds five. A repeatable answer is not necessarily a right one.

Second fix

Ask the index

The file already says which copy is current. Its newest cross-reference table (the index) records, for every compressed record, the bundle that holds the live version: page 3 is in bundle 16857, page 10 in 16862, the other pages in 16854. After loading, khpdf goes through that table and re-reads each compressed record from the bundle it names, replacing whatever lopdf kept.

Technical detail: the fix in khpdf

From src/pdf/objects.rs, called right after Document::load_mem. lopdf stays on one thread (default-features = false in Cargo.toml), so even loading is repeatable.

src/pdf/objects.rs (abridged)
pub(crate) fn prefer_xref_object_versions(doc: &mut LopdfDoc) {
    // Group compressed objects by the container the xref names.
    for (&id, entry) in &doc.reference_table.entries {
        if let XrefEntry::Compressed { container, .. } = entry {
            by_container.entry(*container).or_default().push(id);
        }
    }
    // Re-read each object from that container, replacing lopdf's pick.
    for (container, ids) in by_container {
        let objstm = ObjectStream::new(&mut stream)?;
        for id in ids {
            if let Some(obj) = objects.remove(&(id, 0)) {
                doc.objects.insert((id, 0), obj);
            }
        }
    }
}
page 1page 11

khpdf with the fix, 5 runs, one fingerprint (fingerprints on this page are from the builds used for this study; later versions mark a few unreadable glyphs differently, so today's checksum differs). As an independent check, pypdf resolves the same file to the same records: page 3 from bundle 16857 with 7 fonts, page 10 from 16862.

The output is now the same on every run and matches what PDF viewers display. A regression test reads pages 2 and 3 of this file and checks that the ទិដ្ឋភាពទូទៅ header is there.

Takeaways

What to keep

  • Run it twice. Comparing two runs of the same input is cheap, and it was the only signal here.
  • Stable isn't correct. The first fix passed a "same output every time" check while 8 of 11 pages came from an outdated save.
  • Check against an independent reader. pypdf and the file's own index agreed on which copy is current; that settled it.
  • Edited PDFs are common. Any file saved with incremental updates can hold several versions of a page, so this matters well beyond Khmer.

Everything on this page was re-run for it: the old builds were reconstructed in a scratch copy (lopdf with default features, without the fix), and the file's structure was read with Python. More problems khpdf handles are on the Problems page.