flpdf-cli 0.10.0

Command-line tools for flpdf, mirroring qpdf inspection and rewrite subcommands.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
//! Round-trip linearization tests using qpdf as an external oracle.
//!
//! # Test matrix
//!
//! - **(a)** `flpdf rewrite --linearize` on plain fixtures → `qpdf --check-linearization`
//!   must accept the output with **no warnings**.  Any qpdf warning causes the test to
//!   fail, keeping the oracle strict against regressions.
//! - **(b)** `flpdf rewrite` (without `--linearize`) of an already-linearized PDF must
//!   produce a *non-linearized* output.  **This sub-case MUST PASS.**
//! - **(c)** `flpdf check-linearization`'s Pass-vs-Fail verdict must agree with qpdf's.
//!   Verdict mismatches now hard-fail; a mismatch between the two checkers is
//!   always reported.
//!
//! # Known fingerprints
//! None — no shared-object hint table warnings remain in the known-warning
//! list. The list is empty, so any qpdf warning immediately hard-fails.
//!
//! When qpdf is not installed:
//! - **CI** (`CI` env var set): the test panics — qpdf is treated as a hard
//!   requirement so missing it on CI is a build failure, not a silent gap.
//!   CI installs qpdf on Linux (apt), macOS (Homebrew) and Windows (choco),
//!   so this branch normally does not fire.
//! - **Local runs**: print a diagnostic message via `eprintln!` and return
//!   early (qpdf-dependent tests skip).

use assert_cmd::Command as CargoCommand;
use std::path::{Path, PathBuf};
use std::process::Command as ShellCommand;
use tempfile::tempdir;

// ---------------------------------------------------------------------------
// Fixture directory (same as compat_matrix_tests)
// ---------------------------------------------------------------------------

const COMPAT_FIXTURE_DIR: &str = "../../tests/fixtures/compat";

fn fixture_path(name: &str) -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join(COMPAT_FIXTURE_DIR)
        .join(name)
}

// ---------------------------------------------------------------------------
// Verdict enum
// ---------------------------------------------------------------------------

/// Normalised outcome for a single linearization check.
#[derive(Debug, Clone, PartialEq, Eq)]
enum Verdict {
    /// Unambiguously valid linearized PDF.
    Pass,
    /// Valid but with recoverable warnings (e.g. hint table mismatch).
    Warn(String),
    /// Hard failure or malformed.
    Fail(String),
    /// File is not linearized at all.
    NotLinearized,
}

// ---------------------------------------------------------------------------
// Guards
// ---------------------------------------------------------------------------

fn qpdf_available() -> bool {
    ShellCommand::new("qpdf")
        .arg("--version")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

/// Skip-if-missing helper for qpdf-dependent tests.  Returns `true` when the
/// caller should *return early* (qpdf is missing AND this environment is
/// allowed to skip).
///
/// On CI (`CI` env var set) missing qpdf is a hard failure on every runner:
/// the oracle tests are the only thing that catches regressions in flpdf's
/// hint stream against an external tool, so silently skipping them would
/// leave a blind spot.  CI installs qpdf on Linux (apt), macOS (Homebrew)
/// and Windows (choco).
///
/// Locally (no `CI` env var) a missing qpdf is allowed: a `skipping: ...`
/// line is emitted on stderr and the test exits without exercising qpdf.
#[must_use]
fn skip_if_qpdf_missing() -> bool {
    if qpdf_available() {
        return false;
    }
    let on_ci = std::env::var_os("CI").is_some();
    if on_ci {
        panic!(
            "qpdf is required for cli_linearize_qpdf tests on CI; \
             install qpdf in the workflow before running this test suite"
        );
    }
    eprintln!(
        "skipping: qpdf not available (target_os={}, CI={})",
        std::env::consts::OS,
        on_ci
    );
    true
}

// ---------------------------------------------------------------------------
// qpdf helpers
// ---------------------------------------------------------------------------

/// Run `qpdf --check-linearization <path>` and return `(exit_code, combined_output)`.
fn run_qpdf_check(path: &Path) -> (i32, String) {
    let out = ShellCommand::new("qpdf")
        .args(["--check-linearization", path.to_str().unwrap()])
        .output()
        .expect("failed to spawn qpdf");

    let code = out.status.code().unwrap_or(-1);
    let stdout = String::from_utf8_lossy(&out.stdout).to_string();
    let stderr = String::from_utf8_lossy(&out.stderr).to_string();
    let combined = format!("{stdout}{stderr}");
    (code, combined)
}

/// Classify a `(exit_code, combined_output)` pair from qpdf.
///
/// qpdf exit codes:
///   0  → OK (may still print "is not linearized")
///   2  → hard error
///   3  → warnings only (operation succeeded with warnings)
fn qpdf_verdict(exit: i32, output: &str) -> Verdict {
    if output.contains("is not linearized") {
        return Verdict::NotLinearized;
    }
    match exit {
        0 => {
            if output.contains("no linearization errors") || output.trim().is_empty() {
                Verdict::Pass
            } else {
                // unexpected content on exit 0
                Verdict::Warn(output.to_string())
            }
        }
        3 => Verdict::Warn(output.to_string()),
        _ => Verdict::Fail(output.to_string()),
    }
}

/// Classify a `qpdf --check-linearization` result for a linearized file.
///
/// Returns `None` when the file is simply "not linearized".
fn qpdf_linearization_verdict(path: &Path) -> Verdict {
    let (code, output) = run_qpdf_check(path);
    qpdf_verdict(code, &output)
}

/// Run `qpdf --linearize <input> <output>` to produce a qpdf-linearized fixture.
fn qpdf_linearize(input: &Path, output: &Path) {
    let status = ShellCommand::new("qpdf")
        .args([
            "--linearize",
            input.to_str().unwrap(),
            output.to_str().unwrap(),
        ])
        .status()
        .expect("failed to spawn qpdf --linearize");
    assert!(status.success(), "qpdf --linearize failed");
}

// ---------------------------------------------------------------------------
// flpdf helpers
// ---------------------------------------------------------------------------

/// Run `flpdf rewrite --linearize <input> <output>`.
///
/// Returns `true` if the command succeeded (exit 0).
fn linearize_via_flpdf(input: &Path, output: &Path) -> bool {
    CargoCommand::cargo_bin("flpdf")
        .unwrap()
        .args([
            "rewrite",
            "--linearize",
            input.to_str().unwrap(),
            output.to_str().unwrap(),
        ])
        .output()
        .map(|o| o.status.success())
        .expect("failed to spawn flpdf")
}

/// Run `flpdf rewrite <input> <output>` (without --linearize).
///
/// Returns `true` if the command succeeded (exit 0).
fn rewrite_via_flpdf(input: &Path, output: &Path) -> bool {
    CargoCommand::cargo_bin("flpdf")
        .unwrap()
        .args(["rewrite", input.to_str().unwrap(), output.to_str().unwrap()])
        .output()
        .map(|o| o.status.success())
        .expect("failed to spawn flpdf")
}

/// Run `flpdf check-linearization <path>` and return `(exit_code, combined_output)`.
fn flpdf_check(path: &Path) -> (i32, String) {
    let out = CargoCommand::cargo_bin("flpdf")
        .unwrap()
        .args(["check-linearization", path.to_str().unwrap()])
        .output()
        .expect("failed to spawn flpdf check-linearization");

    let code = out.status.code().unwrap_or(-1);
    let stdout = String::from_utf8_lossy(&out.stdout).to_string();
    let stderr = String::from_utf8_lossy(&out.stderr).to_string();
    let combined = format!("{stdout}{stderr}");
    (code, combined)
}

/// Classify flpdf's check-linearization result.
fn flpdf_verdict(path: &Path) -> Verdict {
    let (code, output) = flpdf_check(path);
    match code {
        0 => Verdict::Pass,
        1 => {
            if output.contains("not a linearized PDF") {
                Verdict::NotLinearized
            } else {
                Verdict::Fail(output)
            }
        }
        _ => Verdict::Fail(output),
    }
}

// ---------------------------------------------------------------------------
// Categorised result tracking
// ---------------------------------------------------------------------------

/// A single categorised test result.
struct CaseResult {
    label: String,
    status: CaseStatus,
    reason: String,
}

enum CaseStatus {
    Pass,
    Fail,
    KnownIssue,
}

impl CaseResult {
    fn pass(label: impl Into<String>) -> Self {
        Self {
            label: label.into(),
            status: CaseStatus::Pass,
            reason: String::new(),
        }
    }

    fn fail(label: impl Into<String>, reason: impl Into<String>) -> Self {
        Self {
            label: label.into(),
            status: CaseStatus::Fail,
            reason: reason.into(),
        }
    }

    fn known(label: impl Into<String>, issue: &str, detail: impl Into<String>) -> Self {
        Self {
            label: label.into(),
            status: CaseStatus::KnownIssue,
            reason: format!("known: {issue} — {}", detail.into()),
        }
    }
}

/// Classify a qpdf `Warn` message in the (a) matrix into a [`CaseResult`].
///
/// Only **explicitly enumerated** warning fingerprints are accepted as known
/// issues; any other warning text surfaces as a `Fail` so the oracle keeps
/// catching new regressions instead of silently absorbing them under a
/// previously accepted label. Each known fingerprint has an explicit
/// description in this test.
fn classify_qpdf_warning(label: &str, msg: &str) -> CaseResult {
    const KNOWN: &[(&str, &str, &str)] = &[
        // All  shared-object hint table warnings have been fixed:
        // - "shared object N length mismatch" — fixed by including part2 entries
        //   in shared_hints and using them for location/length back-patching.
        // - "unable to get object for item in shared objects hint table" — fixed
        //   by the same change (table now starts at page dict = part2[0]).
        // - "overflow reading bit stream" / "hint table length mismatch" — fixed
        //   upstream by the convergence loop and proper back-patching.
        // - "space before first xref item (/T) mismatch" — fixed upstream.
        //
        // No KNOWN fingerprints remain.  Any qpdf warning will hard-fail the test.
    ];

    for (needle, issue, detail) in KNOWN {
        if msg.contains(needle) {
            return CaseResult::known(label.to_string(), issue, *detail);
        }
    }

    CaseResult::fail(label.to_string(), format!("unexpected qpdf warning: {msg}"))
}

fn print_summary(results: &[CaseResult]) {
    println!();
    println!("=== cli_linearize_qpdf test summary ===");
    for r in results {
        let tag = match r.status {
            CaseStatus::Pass => "OK         ",
            CaseStatus::Fail => "FAIL       ",
            CaseStatus::KnownIssue => "KNOWN-ISSUE",
        };
        if r.reason.is_empty() {
            println!("  [{tag}] {}", r.label);
        } else {
            println!("  [{tag}] {} — {}", r.label, r.reason);
        }
    }
    println!("=======================================");
    println!();
}

// ---------------------------------------------------------------------------
// (a) flpdf --linearize → qpdf --check-linearization
// ---------------------------------------------------------------------------

#[test]
fn linearize_qpdf_check_matrix() {
    if skip_if_qpdf_missing() {
        return;
    }

    let fixtures: &[(&str, &str)] = &[
        ("one-page.pdf", "(a) single-page"),
        ("two-page.pdf", "(a) multi-page (2 pages)"),
        ("three-page.pdf", "(a) multi-page (3 pages)"),
    ];

    let tmp = tempdir().unwrap();
    let mut results: Vec<CaseResult> = Vec::new();

    for (fixture_name, label) in fixtures {
        let input = fixture_path(fixture_name);
        let output = tmp.path().join(format!("linearized-{fixture_name}"));

        let success = linearize_via_flpdf(&input, &output);
        if !success {
            results.push(CaseResult::fail(
                *label,
                "flpdf --linearize exited with non-zero status",
            ));
            continue;
        }

        let verdict = qpdf_linearization_verdict(&output);
        match &verdict {
            Verdict::Pass => {
                results.push(CaseResult::pass(*label));
            }
            Verdict::Warn(msg) => results.push(classify_qpdf_warning(label, msg)),
            Verdict::Fail(msg) => {
                results.push(CaseResult::fail(*label, format!("qpdf hard fail: {msg}")));
            }
            Verdict::NotLinearized => {
                results.push(CaseResult::fail(
                    *label,
                    "flpdf output is not recognized as linearized",
                ));
            }
        }
    }

    print_summary(&results);

    // All (a) cases must produce linearized output, even if warnings.
    // Hard failures must not be silently classified as NotLinearized.
    let hard_failures: Vec<&CaseResult> = results
        .iter()
        .filter(|r| matches!(r.status, CaseStatus::Fail))
        .collect();

    if !hard_failures.is_empty() {
        let msgs: Vec<_> = hard_failures.iter().map(|r| r.label.as_str()).collect();
        panic!(
            "(a) hard failures that are not categorised as known issues: {:?}",
            msgs
        );
    }
}

// ---------------------------------------------------------------------------
// (b) Non-linear collapse: flpdf rewrite (no --linearize) of qpdf-linearized
//     PDF must produce a NON-linearized output.  MUST PASS.
// ---------------------------------------------------------------------------

#[test]
fn non_linear_collapse_from_qpdf_linearized() {
    if skip_if_qpdf_missing() {
        return;
    }

    let tmp = tempdir().unwrap();
    let source = fixture_path("one-page.pdf");

    // First, produce a qpdf-linearized intermediate.
    let qpdf_linearized = tmp.path().join("qpdf-linearized.pdf");
    qpdf_linearize(&source, &qpdf_linearized);

    // Sanity: qpdf's own output must be valid.
    let (check_exit, check_output) = run_qpdf_check(&qpdf_linearized);
    assert_eq!(
        check_exit, 0,
        "(b) pre-condition: qpdf --linearize output should be valid, got: {check_output}"
    );
    assert!(
        !check_output.contains("is not linearized"),
        "(b) pre-condition: qpdf --linearize output must be linearized"
    );

    // Then, run flpdf rewrite WITHOUT --linearize.
    let flpdf_out = tmp.path().join("flpdf-collapsed.pdf");
    let rewrite_ok = rewrite_via_flpdf(&qpdf_linearized, &flpdf_out);
    assert!(rewrite_ok, "(b) flpdf rewrite exited with non-zero status");

    // Finally, qpdf must say "is not linearized".
    let (qpdf_exit, qpdf_output) = run_qpdf_check(&flpdf_out);
    let verdict = qpdf_verdict(qpdf_exit, &qpdf_output);

    assert_eq!(
        verdict,
        Verdict::NotLinearized,
        "(b) MUST PASS: flpdf rewrite (no --linearize) of qpdf-linearized PDF \
         must produce a non-linearized output.\n\
         qpdf exit={qpdf_exit}, output={qpdf_output}"
    );

    println!("(b) non-linear collapse from qpdf-linearized: OK");

    // The canonical rewrite emits a fresh non-linearized document. A semantic
    // qpdf check is used here rather than a raw-byte scan of the input prefix.
}

// ---------------------------------------------------------------------------
// (c) Verdict match: flpdf check-linearization vs qpdf --check-linearization
// ---------------------------------------------------------------------------

#[test]
fn verdict_match_flpdf_vs_qpdf() {
    if skip_if_qpdf_missing() {
        return;
    }

    let fixtures = &["one-page.pdf", "two-page.pdf", "three-page.pdf"];

    let tmp = tempdir().unwrap();
    let mut results: Vec<CaseResult> = Vec::new();

    for fixture_name in fixtures {
        let input = fixture_path(fixture_name);
        let linearized = tmp.path().join(format!("lin-{fixture_name}"));

        // produce flpdf-linearized file
        let success = linearize_via_flpdf(&input, &linearized);
        if !success {
            results.push(CaseResult::fail(
                format!("(c) {fixture_name}"),
                "flpdf linearize failed, cannot compare verdicts",
            ));
            continue;
        }

        let fv = flpdf_verdict(&linearized);
        let qv = qpdf_linearization_verdict(&linearized);

        // Normalise to a simple Pass/Fail binary for comparison.
        let fv_pass = matches!(fv, Verdict::Pass | Verdict::Warn(_));
        let qv_pass = matches!(qv, Verdict::Pass | Verdict::Warn(_));

        let label = format!("(c) verdict match — {fixture_name}");
        if fv_pass == qv_pass {
            results.push(CaseResult::pass(label));
        } else {
            // The validator must not be more lenient than the oracle. A verdict
            // mismatch is now a real regression — neither checker should
            // accept what the other rejects.
            let detail = format!(
                "flpdf={} qpdf={}",
                if fv_pass { "Pass/Warn" } else { "Fail" },
                if qv_pass { "Pass/Warn" } else { "Fail" }
            );
            results.push(CaseResult::fail(
                label,
                format!("verdict mismatch between flpdf and qpdf: {detail}"),
            ));
        }
    }

    print_summary(&results);

    // Mismatches must surface as failures so the oracle catches divergence
    // between the two implementations.
    let mismatches: Vec<&CaseResult> = results
        .iter()
        .filter(|r| matches!(r.status, CaseStatus::Fail))
        .collect();
    if !mismatches.is_empty() {
        let msgs: Vec<_> = mismatches.iter().map(|r| r.label.as_str()).collect();
        panic!(
            "(c) verdict mismatches between flpdf and qpdf (regressions): {:?}",
            msgs
        );
    }
}

// ---------------------------------------------------------------------------
// (b) Additional: two-page and three-page collapse
// ---------------------------------------------------------------------------

#[test]
fn non_linear_collapse_multi_page() {
    if skip_if_qpdf_missing() {
        return;
    }

    let tmp = tempdir().unwrap();
    let mut results: Vec<CaseResult> = Vec::new();

    let fixtures = &["two-page.pdf", "three-page.pdf"];

    for fixture_name in fixtures {
        let source = fixture_path(fixture_name);
        let qpdf_linearized = tmp.path().join(format!("qpdf-lin-{fixture_name}"));
        let flpdf_out = tmp.path().join(format!("flpdf-collapsed-{fixture_name}"));

        qpdf_linearize(&source, &qpdf_linearized);
        let success = rewrite_via_flpdf(&qpdf_linearized, &flpdf_out);

        if !success {
            results.push(CaseResult::fail(
                format!("(b) multi-page collapse — {fixture_name}"),
                "flpdf rewrite exited with non-zero status",
            ));
            continue;
        }

        let (qpdf_exit, qpdf_output) = run_qpdf_check(&flpdf_out);
        let verdict = qpdf_verdict(qpdf_exit, &qpdf_output);

        let label = format!("(b) non-linear collapse — {fixture_name}");
        if verdict == Verdict::NotLinearized {
            results.push(CaseResult::pass(label));
        } else {
            results.push(CaseResult::fail(
                label,
                format!("expected NotLinearized, got {:?}", verdict),
            ));
        }
    }

    print_summary(&results);

    // (b) multi-page collapse MUST PASS as well.
    let failures: Vec<_> = results
        .iter()
        .filter(|r| matches!(r.status, CaseStatus::Fail))
        .map(|r| r.label.as_str())
        .collect();

    assert!(
        failures.is_empty(),
        "(b) non-linear collapse MUST PASS for all fixtures, failing: {:?}",
        failures
    );
}

// ---------------------------------------------------------------------------
// Test-of-test: classification of qpdf warnings
// ---------------------------------------------------------------------------

/// Asserts that an *unknown* qpdf warning is classified as Fail, not as a
/// known issue.  Without this discipline the oracle silently swallows
/// regressions — an unknown warning must not be silently accepted.
#[test]
fn classify_unknown_warning_fails() {
    let r = classify_qpdf_warning("(a) test", "some unrelated qpdf warning text");
    assert!(
        matches!(r.status, CaseStatus::Fail),
        "unknown qpdf warning must be CaseStatus::Fail, got {:?}",
        r.reason
    );
    assert!(
        r.reason.contains("unexpected qpdf warning"),
        "reason text should name it as unexpected, got: {}",
        r.reason
    );
}

/// Asserts that the "hint table length mismatch" fingerprint is not exempted —
/// all such warnings must now hard-fail.
/// This confirms the KNOWN list is truly empty and the oracle is strict.
#[test]
fn classify_hint_table_warning_is_known() {
    let r = classify_qpdf_warning(
        "(a) test",
        "WARNING: file: hint table length mismatch detected",
    );
    // "hint table length mismatch" is not a known issue. Any qpdf warning
    // (including this one) must now Fail.
    assert!(
        matches!(r.status, CaseStatus::Fail),
        "hint-table-length-mismatch is no longer a known issue — must be Fail"
    );
}

// ---------------------------------------------------------------------------
// Page Offset Hint Table per-page content_length must be non-zero
// ---------------------------------------------------------------------------

/// Returns the `content_length:` values per page from `qpdf --show-linearization`.
fn qpdf_show_linearization_content_lengths(path: &Path) -> Vec<u64> {
    let out = ShellCommand::new("qpdf")
        .args(["--show-linearization", path.to_str().unwrap()])
        .output()
        .expect("failed to spawn qpdf --show-linearization");
    // Without this check a qpdf crash would silently produce an empty Vec, and
    // the caller would fail at "no content_length entries" — masking the real
    // qpdf error.  Assert success and surface exit code + stderr first.
    assert!(
        out.status.success(),
        "qpdf --show-linearization failed: exit={:?}, stderr={}, stdout={}",
        out.status.code(),
        String::from_utf8_lossy(&out.stderr),
        String::from_utf8_lossy(&out.stdout)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    stdout
        .lines()
        .filter_map(|line| {
            let trimmed = line.trim_start();
            trimmed
                .strip_prefix("content_length:")
                .map(|rest| rest.trim().parse::<u64>().expect("parse content_length"))
        })
        .collect()
}

/// After linearizing, every page's content_length in the page-offset
/// hint table must be non-zero.  qpdf reuses page-length as content-length
/// (Adobe implementation note 127), so we mirror that — pages with body bytes
/// must report a positive content_length to give fast-web-view readers a usable
/// initial-rendering hint.
#[test]
fn linearize_populates_per_page_content_length() {
    if skip_if_qpdf_missing() {
        return;
    }

    let tmp = tempdir().unwrap();
    for fixture_name in &["one-page.pdf", "two-page.pdf", "three-page.pdf"] {
        let input = fixture_path(fixture_name);
        let output = tmp.path().join(format!("lin-{fixture_name}"));

        let ok = linearize_via_flpdf(&input, &output);
        assert!(ok, "flpdf --linearize {fixture_name} failed");

        // qpdf --check-linearization must still accept the output.
        assert_eq!(
            qpdf_linearization_verdict(&output),
            Verdict::Pass,
            "qpdf --check-linearization regressed on {fixture_name}"
        );

        let lengths = qpdf_show_linearization_content_lengths(&output);
        assert!(
            !lengths.is_empty(),
            "qpdf --show-linearization on {fixture_name} produced no \
             content_length entries"
        );
        for (i, &len) in lengths.iter().enumerate() {
            assert!(
                len > 0,
                "page {i} of {fixture_name} has content_length=0; \
                 expected a positive content_length, got {lengths:?}"
            );
        }
    }
}

// ---------------------------------------------------------------------------
// (d) Failure-path stderr parity
// ---------------------------------------------------------------------------

/// qpdf reaches these two linearization failures through different C++ paths,
/// and each shapes its message differently.
///
/// * `QPDF_linearization.cc:1190` calls `stopOnError`, which raises a
///   `qpdf_e_damaged_pdf` exception carrying the input name and the source's
///   last read offset (`QPDF.cc:2590-2592,2625-2628`), so the line reads
///   `qpdf: <file> (offset N): <message>`.
/// * `QPDFWriter.cc:2524` throws a plain `std::runtime_error`, which carries
///   no source context and no category prefix, so the message stands alone.
///
/// Compare the whole stderr against qpdf, normalising only the program name.
#[test]
fn linearize_failure_stderr_matches_qpdf() {
    if skip_if_qpdf_missing() {
        return;
    }
    let tmp = tempdir().unwrap();
    for fixture in [
        // stopOnError: input name and offset
        "adbe-orphan-url.pdf",
        "compressible-stale-generation-alias.pdf",
        // std::runtime_error: bare message
        "null-visible-stale-generation.pdf",
    ] {
        let input = fixture_path(fixture);
        let theirs = tmp.path().join("qpdf-out.pdf");
        let ours = tmp.path().join("flpdf-out.pdf");

        let expected = ShellCommand::new("qpdf")
            .args(["--deterministic-id", "--linearize"])
            .arg(&input)
            .arg(&theirs)
            .output()
            .expect("qpdf runs");
        assert_eq!(
            expected.status.code(),
            Some(2),
            "{fixture}: qpdf must fail to linearize this fixture"
        );

        let actual = CargoCommand::cargo_bin("flpdf")
            .unwrap()
            .args(["--deterministic-id", "--linearize"])
            .arg(&input)
            .arg(&ours)
            .output()
            .expect("flpdf runs");

        assert_eq!(
            actual.status.code(),
            expected.status.code(),
            "{fixture}: exit code must match qpdf"
        );
        let expected_stderr = String::from_utf8_lossy(&expected.stderr).replace("qpdf:", "<prog>:");
        let actual_stderr = String::from_utf8_lossy(&actual.stderr).replace("flpdf:", "<prog>:");
        assert_eq!(
            actual_stderr, expected_stderr,
            "{fixture}: stderr must match qpdf apart from the program name"
        );
    }
}