pdfcer-model 0.188.0

pdfcer COS model layer: objects, lexer, parser, filters, xref, object streams, recovery, Document/DocumentView, the full and incremental writer, standard-handler crypto, content parsing and the page tree. Depends on nothing else in the workspace; re-exported by pdfcer-core.
Documentation
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
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
//! # The Document — pdfcer's single object model (load side)
//!
//! Ties the layers together: retained source buffer → header probe →
//! xref chain → eagerly parsed indirect objects → reference resolution.
//! Spec sources: `iso32000__s__7.5.5.md` (load algorithm),
//! `iso32000__s__7.3.10.md` (resolution semantics, dangling-ref rule),
//! `iso32000__s__7.7.2.md` (catalog) in the PDF-spec RAG. Clause
//! numbers are ISO 32000-1:2008.
//!
//! ## THE named invariant: one `Document`, both directions
//!
//! [`Document`] is simultaneously the parse result AND (from the first
//! editing Pass on) the write source
//! (docs/decisions/001-oxidize-pdf-adopt-vs-build.md §6.1 item 3). No
//! separate builder/generation model may ever be introduced — the
//! audited prior art shows exactly how that bifurcation forecloses
//! round-trip editing. Write-side machinery (dirty tracking, the
//! §7.5.6 incremental writer) lands in the first editing Pass and
//! operates on *this* type.
//!
//! ## The retained buffer
//!
//! The document owns the complete source bytes for its lifetime. Every
//! file-level [`IndirectObject`] records a
//! [`ByteSpan`](crate::span::ByteSpan) into this buffer (its full
//! `N G obj … endobj` definition), which is what makes
//! minimal-diff/incremental re-emission mechanical (ARCHITECTURE.md §5;
//! `crate::span`). Memory cost is the file size — the deliberate price
//! of the round-trip invariant, and small next to any renderer's
//! working set.
//!
//! Objects that lived **inside an object stream** (§7.5.7) have no span
//! of their own; they carry [`Provenance::ObjectStream`] instead,
//! naming the container and index. See [`Provenance`] for why that
//! distinction is a type and not a sentinel.
//!
//! ## Eager parse, strict failure (Pass 1 posture)
//!
//! `load`/`from_bytes` parse **every in-use object up front**; any
//! malformed object fails the whole load with a precise error. Rationale:
//! fail-clean over partial success (ARCHITECTURE.md §10) — a viewer
//! that opens a file "successfully" and then errors object-by-object
//! gives worse diagnostics than one clean refusal naming the offset.
//! Lazy/tolerant loading (open-what-you-can) is a deliberate later
//! feature for damaged-file recovery, driven by corpus evidence, not a
//! default.
//!
//! ### Two phases, in this order (§7.5.7 + §7.5.8.3)
//!
//! 1. **File-level objects** — every type-1 (`InUse`) xref entry is
//!    parsed at its offset.
//! 2. **Compressed objects** — every type-2 (`InStream`) entry is
//!    resolved through its container.
//!
//! The order is forced, not stylistic: a container object stream is
//! itself an ordinary file-level stream object reached through a
//! type-1 entry, so phase 2 needs phase 1 to have finished. §7.5.7
//! guarantees this terminates at two levels — an object stream may not
//! contain a stream, so a container can never live inside another
//! container, and the object supplying a container's `/Length` may not
//! be compressed either. There is no recursion to guard, only an
//! ordering to respect.
//!
//! Each container is decoded **once** and cached for the duration of
//! the load ([`ObjectStream`]); a container holding 200 objects would
//! otherwise be inflated 200 times.
//!
//! ## Resolution semantics (§7.3.10, §7.5.4)
//!
//! [`Document::get`] / [`Document::resolve`] implement, exactly:
//! - **dangling reference → null** ("shall not be considered an
//!   error") — including object numbers with no xref entry at all;
//! - **generation mismatch → null** (a stale reference; the xref
//!   entry's generation is part of the identity);
//! - **free entry → null** (§7.5.4 free-list mechanics — how deleted
//!   and hybrid-hidden objects read as absent);
//! - **reference chains are depth-guarded** ([`MAX_RESOLVE_DEPTH`],
//!   pdfcer policy — `5 0 obj 5 0 R endobj` is legal syntax and must
//!   not loop).

use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::path::Path;

use crate::linearization::{self, Linearization};
use crate::object::{Dict, IndirectObject, ObjId, Object, Provenance};
use crate::objstm::{ObjStmError, ObjectStream};
use crate::parser::{ParseError, Parser, StreamLengthPolicy, TerminatorPolicy};
use crate::recover::{self, RecoveryReport};
use crate::view::DocumentView;
use crate::xref::{self, SectionShape, XrefEntry, XrefError, XrefErrorKind, XrefTable};

mod encryption_refusal;
use crate::{PdfError, PdfVersion};
pub use encryption_refusal::EncryptedRefusal;

/// Maximum reference-chain hops [`Document::resolve`] follows before
/// declaring a cycle and yielding null.
///
/// pdfcer policy (ARCHITECTURE.md §10): the spec permits
/// reference-to-reference chains and does not bound them; legitimate
/// files use at most a handful of hops. Null (not an error) on
/// exhaustion keeps the §7.3.10 "references never hard-fail" posture
/// consistent even for hostile cycles.
pub const MAX_RESOLVE_DEPTH: usize = 32;

/// Errors from loading a document.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum DocError {
    /// File I/O failed.
    #[error("I/O error reading PDF: {0}")]
    Io(#[from] std::io::Error),
    /// The document is encrypted with a configuration pdfcer will not decrypt
    /// (§7.6). The inner error names *which* configuration and why — an
    /// unimplemented cipher, an unsourced algorithm, a different security
    /// handler, or a document no conforming reader may open at all.
    ///
    /// Those are four different facts with four different next actions, which
    /// is why this is not one flat "encrypted files are unsupported".
    #[error("{0}")]
    Encryption(#[from] crate::crypto::EncryptionUnsupported),
    /// The document is encrypted with a configuration pdfcer **can** decrypt,
    /// but no password opened it.
    ///
    /// §7.6.3.1 requires trying the empty user password first and silently, so
    /// reaching this error means the empty password was already tried and
    /// failed: the document genuinely has a non-empty user password. The
    /// caller should prompt and retry with
    /// [`Document::from_bytes_with_password`].
    ///
    /// **N6**: ISO 32000-1 states no error model here at all — no retry limit,
    /// no reporting requirement, nothing about distinguishing a wrong password
    /// from a malformed one. All of that is pdfcer policy.
    #[error("this document is password-protected; supply the user or owner password")]
    PasswordRequired,
    /// Nothing authenticated, **and** the supplied password contains
    /// characters `/R` 5's password preprocessing may have changed before
    /// hashing — so "wrong password" is not the only explanation.
    ///
    /// The Adobe supplement's step 1 applies **SASLprep** (RFC 4013) with the
    /// Normalize and BIDI options before the UTF-8 conversion. pdfcer
    /// implements the UTF-8 conversion and the 127-byte truncation exactly and
    /// does **not** implement SASLprep; neither RFC is staged in the project's
    /// spec corpus, and a stringprep dependency was not taken for a read-only
    /// increment.
    ///
    /// For an all-ASCII password SASLprep is the identity, so this error can
    /// never arise from one. pdfcer still *attempts* a non-ASCII password —
    /// SASLprep is the identity for much more than ASCII, and getting it wrong
    /// cannot open a document with a wrong key, only fail to open one with the
    /// right password. This variant exists so that failure does not
    /// masquerade as [`Self::PasswordRequired`]'s "you typed it wrong", which
    /// would send the operator to re-check a password that was correct.
    ///
    /// Reported only at `/R` 5. Password encoding below that is PDFDocEncoding
    /// (**T8**), a different unimplemented question.
    #[error(
        "this document is password-protected; the password supplied contains non-ASCII characters, \
         and pdfcer does not apply the RFC 4013 (SASLprep) normalisation that /R 5 specifies before \
         hashing — so a correct password can be rejected here"
    )]
    PasswordRequiresNormalisation,
    /// Authentication failed at handler revision **6** (AES-256 hardened),
    /// where the failure is **not** unambiguously "wrong password" (`Pass
    /// 5.4`).
    ///
    /// `/R` 6's key derivation (Algorithm 2.B) contains a genuine spec
    /// ambiguity — **A13**, the loop-exit test, which is internally
    /// inconsistent between steps (e) and (f) and produces a different digest
    /// (hence a different key, hence a failed authentication) depending on the
    /// reading. pdfcer defaults to the reading pypdf and Acrobat write
    /// ([`crate::crypto::r6::A13Reading::PerformThenTest`]); a document written
    /// by an implementation that took the other reading would fail here with a
    /// correct password. This variant names A13 so that failure is not
    /// reported as "you typed it wrong" (`R169`: a spec ambiguity is disclosed,
    /// never silently resolved). Raised only at `/R` 6.
    #[error(
        "this document is password-protected (AES-256 /R 6); authentication failed. If the password is correct, the cause may be ambiguity A13 in ISO 32000-2 Algorithm 2.B's loop-exit test -- pdfcer uses the reading pypdf and Acrobat write, and a file written under the other reading would not open"
    )]
    PasswordRequiredR6,
    /// The `%PDF-` header probe failed — not a PDF.
    #[error(transparent)]
    Header(PdfError),
    /// The cross-reference machinery failed — a damaged/unreadable
    /// xref chain, or the deliberate `/Encrypt` capability-gap refusal
    /// (`XrefErrorKind::EncryptionUnsupported`).
    #[error(transparent)]
    Xref(#[from] XrefError),
    /// An indirect object at an xref-declared offset failed to parse.
    #[error("object {id} (xref offset {offset}): {source}")]
    BadObject {
        /// The object the xref table pointed at.
        id: ObjId,
        /// The offset the xref entry gave.
        offset: u64,
        /// The underlying structural error.
        source: ParseError,
    },
    /// The object parsed at an offset doesn't match the xref entry
    /// that pointed there (wrong number or generation) — the table and
    /// body disagree; strict Pass 1 refuses rather than guessing which
    /// is right.
    #[error("object at xref offset {offset} declares {found}, xref expected {expected}")]
    ObjectIdMismatch {
        /// What the xref entry promised.
        expected: ObjId,
        /// What the bytes at the offset declared.
        found: ObjId,
        /// The offset in question.
        offset: u64,
    },
    /// A type-2 cross-reference entry (§7.5.8.3) named an object stream
    /// that is not present as a loadable file-level object.
    ///
    /// §7.5.7: "there shall be an entry for it in a cross-reference
    /// table or cross-reference stream" — so a missing container means
    /// the file's own xref contradicts itself.
    #[error("object {num} is compressed in object stream {container}, which is not present")]
    ObjectStreamMissing {
        /// The container the type-2 entry named (generation always 0).
        container: ObjId,
        /// The object that was to be read from it.
        num: u32,
    },
    /// An object stream (§7.5.7) could not be decoded or read.
    #[error("object stream {container}: {source}")]
    ObjectStream {
        /// The container object stream.
        container: ObjId,
        /// What went wrong inside it.
        source: ObjStmError,
    },
    /// The object number stored in an object stream's pair table
    /// disagrees with the object number its type-2 cross-reference
    /// entry promised — the xref and the container contradict each
    /// other, and the strict loader refuses rather than picking one
    /// (the same posture as [`DocError::ObjectIdMismatch`] for
    /// file-level objects).
    #[error(
        "object stream {container} index {index} holds object {found}, xref expected object {expected}"
    )]
    ObjectStreamIdMismatch {
        /// The container object stream.
        container: ObjId,
        /// The index within it that was read.
        index: u32,
        /// The object number the type-2 entry promised.
        expected: u32,
        /// The object number the pair table actually stored.
        found: u32,
    },
    /// The trailer has no usable `/Root` (Table 15 requires it; a
    /// conformant update trailer always repeats it — see the RAG's
    /// gotcha on why fallback-to-older-trailers is a repair heuristic,
    /// not Pass 1 behavior).
    #[error("trailer /Root missing or not a reference to a dictionary")]
    NoCatalog,
    /// Cross-reference **recovery** (decision 013) was attempted after the
    /// strict load failed, but could not produce a document — no
    /// confirmable objects, no `/Catalog`, or the entry cap. A named
    /// fail-clean refusal, never a partial/garbage document. (An encrypted
    /// recovered file is refused as [`XrefErrorKind::EncryptionUnsupported`]
    /// via [`DocError::Xref`] instead, matching the clean-path capability
    /// gap.)
    ///
    /// [`XrefErrorKind::EncryptionUnsupported`]: crate::xref::XrefErrorKind::EncryptionUnsupported
    #[error("cross-reference recovery failed: {0}")]
    Recovery(#[from] crate::recover::RecoverError),
}

/// A loaded PDF document: retained bytes + parsed structure.
///
/// See the module docs for the three design commitments this type
/// embodies (one model, retained buffer, strict eager load).
#[derive(Debug, Clone)]
pub struct Document {
    /// The complete, untouched source bytes (the provenance substrate —
    /// every span in `objects` indexes into this).
    buf: Vec<u8>,
    /// Header-declared version (`%PDF-M.N`). Catalog `/Version`
    /// override (§7.5.5) is reconciled by [`Document::version`].
    header_version: PdfVersion,
    /// Merged, `/Size`-filtered cross-reference table.
    xref: XrefTable,
    /// The newest trailer dictionary.
    trailer: Dict,
    /// Every in-use object, parsed. Keyed by full `(num, generation)`
    /// identity.
    objects: HashMap<ObjId, IndirectObject>,
    /// The byte offset this file's own `startxref` names — the value an
    /// appended update's `/Prev` must carry (§7.5.6). Retained at load
    /// because it is not recoverable from the merged view.
    base_startxref: u64,
    /// The physical form of the newest cross-reference section, so a
    /// save can match it instead of normalizing (R33).
    section_shape: SectionShape,
    /// Annex F linearization state, detected at load (R36).
    linearization: Linearization,
    /// Highest object number the cross-reference chain mentions, before
    /// the `/Size` filter — the number a writer must allocate above.
    highest_object_number: u32,
    /// How many cross-reference entries `/Size` suppressed.
    suppressed_by_size: usize,
    /// Which objects a hybrid-reference file hides, and whether pdfcer could
    /// tell (`Pass 281.0`). Default (empty, readable) for every non-hybrid
    /// file and for a recovered base, where the concept does not apply.
    hybrid: crate::xref::HybridPartition,
    /// Every contradiction pdfcer met while loading and decided rather than
    /// refused (`Pass 283.0`). Empty for a file that says nothing twice.
    anomalies: Vec<LoadAnomaly>,
    /// `Some` when this document was loaded via **cross-reference
    /// recovery** (decision 013): the stored xref could not be parsed and
    /// the table was rebuilt by scanning. The writer reads this to force a
    /// full rewrite and refuse incremental save (the recovered-base rule);
    /// the CLI/GUI read it to disclose. `None` for every cleanly-loaded
    /// file — recovery lives entirely on the strict-load error path, so a
    /// clean file's flow never sets it.
    recovery: Option<RecoveryReport>,
    /// `Some` when this document was loaded from an **encrypted** file and
    /// successfully decrypted (§7.6, [`crate::crypto`]).
    ///
    /// Holds the configuration, which password opened it, and — privately —
    /// what an incremental save needs to append under the same handler: the
    /// file key and the source bytes as they were before decryption.
    encryption: Option<DocumentEncryption>,
}

/// What a successfully-decrypted document was protected with.
///
/// Reported so the shells can tell the operator the document is encrypted,
/// which cipher, and what the author's permissions ask for. It is a
/// **disclosure**, not a gate: §7.6.3.1 states plainly that "there is nothing
/// inherent in PDF encryption that enforces the document permissions", so
/// anywhere pdfcer chooses to act on a permission bit it must say so (rule 4).
/// What decrypts a document on load: a password to authenticate, or an
/// already-recovered key carried from the document a save descends from.
#[derive(Clone, Copy)]
enum Credential<'a> {
    Password(Option<&'a [u8]>),
    Reuse(&'a DocumentEncryption),
}

#[derive(Debug, Clone)]
pub struct DocumentEncryption {
    /// The parsed `/Encrypt` dictionary.
    pub config: crate::crypto::EncryptionConfig,
    /// Which password opened it. [`AuthKind::EmptyUser`] is the no-prompt
    /// case — the document had an empty user password, which every
    /// conforming reader tries silently before prompting.
    ///
    /// [`AuthKind::EmptyUser`]: crate::crypto::AuthKind::EmptyUser
    pub auth: crate::crypto::AuthKind,
    /// The Algorithm 3.13 `/Perms` verdict — **the only integrity check in
    /// PDF encryption**, and a `should`, not a `shall`.
    ///
    /// [`PermsCheck::NotApplicable`] for every `/R` ≤ 4 document, where the
    /// entry does not exist. That is the *ordinary* answer, not a failed
    /// check, and a front end must not render it as one.
    ///
    /// # Why it is here rather than acted on
    ///
    /// `/Perms` holds an encrypted copy of `/P` and `/EncryptMetadata`. The
    /// plaintext copies sit in the `/Encrypt` dictionary where anyone can edit
    /// them, with no integrity protection anywhere else in clause 7.6
    /// (**N7**). So a disagreement is the one signal PDF gives that a
    /// document's stated permissions are not the ones its encryptor recorded —
    /// and no clause says what to do about it.
    ///
    /// pdfcer reports it and **prefers neither value**:
    /// [`EncryptionConfig::permissions`] keeps returning the dictionary's
    /// `/P`, because that is what the file declares and what every other
    /// viewer shows, and this field carries the disagreement beside it.
    /// Silently substituting the decrypted copy would be pdfcer deciding, on an
    /// inference, what the operator is told — the exact shape project rule 4
    /// forbids. Refusing the document would reject files nothing else objects
    /// to, on the strength of a check the standard declines to require. See
    /// [`PermsCheck`]'s own docs (**T27**).
    ///
    /// [`PermsCheck`]: crate::crypto::PermsCheck
    /// [`PermsCheck::NotApplicable`]: crate::crypto::PermsCheck::NotApplicable
    /// [`EncryptionConfig::permissions`]: crate::crypto::EncryptionConfig::permissions
    pub perms: crate::crypto::PermsCheck,
    /// The recovered file key. Private: [`crate::writer::save_incremental`]
    /// encrypts appended objects with it (§7.6.2), so a save needs no second
    /// password prompt. Its `Debug` never prints the key.
    key: crate::crypto::FileKey,
    /// The object number of an indirect `/Encrypt` dictionary (`None` when it
    /// is direct in the trailer).
    encrypt_dict_id: Option<u32>,
    /// The file's bytes before decryption. Decryption rewrites stream data in
    /// the document's buffer, so an append must start from these instead.
    ciphertext: std::sync::Arc<[u8]>,
    /// Whether an append may keep an RC4 handler; see [`Document::set_rc4_append`].
    rc4_append: crate::writer::Rc4Append,
}

impl DocumentEncryption {
    /// The recovered file key an append encrypts under.
    pub(crate) fn file_key(&self) -> &crate::crypto::FileKey {
        &self.key
    }

    /// An indirect `/Encrypt` dictionary's object number; an append leaves it in clear.
    pub(crate) fn encrypt_dict_id(&self) -> Option<u32> {
        self.encrypt_dict_id
    }

    /// The source bytes as stored on disk — ciphertext wherever the file
    /// encrypted something.
    pub(crate) fn ciphertext(&self) -> &[u8] {
        &self.ciphertext
    }

    /// Whether an incremental save can append under this document's key.
    /// `false` for an RC4 document unless [`Document::set_rc4_append`] opted
    /// in: pdfcer never chooses RC4 (decision 190), so
    /// [`crate::writer::save_incremental`] refuses it with
    /// [`crate::writer::WriteError::Rc4AppendRefused`].
    #[must_use]
    pub fn appendable(&self) -> bool {
        !self.uses_rc4() || self.rc4_append == crate::writer::Rc4Append::Preserve
    }

    /// Whether strings or streams are encrypted with RC4 (`/V` 1–2, or a
    /// `/V` 4 crypt filter with `/CFM /V2`; ISO 32000-2 §7.6.2).
    #[must_use]
    pub fn uses_rc4(&self) -> bool {
        use crate::crypto::Cipher;
        [self.key.string_cipher(), self.key.stream_cipher()].contains(&Cipher::Rc4)
    }

    /// The RC4 append policy in force; [`Rc4Append::Refuse`] unless
    /// [`Document::set_rc4_append`] changed it.
    ///
    /// [`Rc4Append::Refuse`]: crate::writer::Rc4Append::Refuse
    #[must_use]
    pub fn rc4_append(&self) -> crate::writer::Rc4Append {
        self.rc4_append
    }

    /// Whether `bit` lets the operator who opened the document do what it
    /// governs (ISO 32000-2 Table 22). The owner password grants everything;
    /// a user (or empty-user) open is held to the declared `/P`. A bit the
    /// document's revision does not define is not granted.
    #[must_use]
    pub fn grants(&self, bit: crate::crypto::PermissionBit) -> bool {
        self.auth == crate::crypto::AuthKind::Owner
            || self.config.permissions().granted(bit) == Some(true)
    }
}

impl Document {
    /// Load a document from a file on disk.
    ///
    /// # Errors
    ///
    /// [`DocError`] — I/O, header, xref, or object-level failure; every
    /// variant carries the offending offset/object for diagnostics.
    pub fn load(path: &Path) -> Result<Self, DocError> {
        Self::from_bytes(std::fs::read(path)?)
    }

    /// Load a document from disk, supplying a password for an encrypted file.
    ///
    /// `password` is `None` to mean "no password known" — which is **not** the
    /// same as an empty password. §7.6.3.1 requires a reader to try the empty
    /// user password first and silently in *either* case, so `None` still
    /// opens a permissions-only document with no prompt; what `None` means is
    /// that if that fails, there is nothing else to try and the load returns
    /// [`DocError::PasswordRequired`].
    ///
    /// Either the user or the owner password opens the document
    /// (§7.6.3.1). Which one it was is reported by
    /// [`Document::encryption`].
    ///
    /// # Errors
    ///
    /// [`DocError`] — as [`Document::load`], plus [`DocError::Encryption`] for
    /// a configuration pdfcer will not decrypt and
    /// [`DocError::PasswordRequired`] when no supplied password authenticated.
    pub fn load_with_password(path: &Path, password: Option<&[u8]>) -> Result<Self, DocError> {
        Self::from_bytes_with_password(std::fs::read(path)?, password)
    }

    /// Load a document from disk under explicit [`LoadOptions`] — the
    /// path-shaped twin of [`Document::from_bytes_with_options`].
    ///
    /// # Why this exists as well as the bytes form
    ///
    /// `Pass 283.0` gave the loader a tolerant posture and gave the operator
    /// the other choice, but shipped the choice on the **bytes** entry point
    /// only. Every shell that opens a document opens a **file** — the GUI's
    /// open-file action, the CLI's path argument — so taking the alternative
    /// reading meant re-implementing [`Document::load`]'s `std::fs::read`
    /// at each call site. An intervention route the intended caller can only
    /// reach by rewriting the route beside it is not offered, it is merely
    /// present.
    ///
    /// The operator's ruling this discharges: *"if the user can intervene in
    /// a decision that should always be an option along with them not having
    /// to intervene."* Re-loading the same path under
    /// [`LoadOptions::new().with_duplicate_keys(DuplicateKeyPolicy::KeepFirst)`]
    /// is the whole intervention; see [`Document::load_anomalies`] for how a
    /// shell learns there was a decision to intervene in.
    ///
    /// [`LoadOptions::new().with_duplicate_keys(DuplicateKeyPolicy::KeepFirst)`]: LoadOptions::with_duplicate_keys
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use std::path::Path;
    /// use pdfcer_model::document::{Document, LoadOptions};
    /// use pdfcer_model::parser::DuplicateKeyPolicy;
    ///
    /// let path = Path::new("drawing.pdf");
    /// let doc = Document::load(path)?;
    /// if !doc.load_anomalies().is_empty() {
    ///     // Offer the operator the other reading; nothing forces them to take it.
    ///     let other = Document::load_with_options(
    ///         path,
    ///         None,
    ///         LoadOptions::new().with_duplicate_keys(DuplicateKeyPolicy::KeepFirst),
    ///     )?;
    ///     let _ = other;
    /// }
    /// # Ok::<(), pdfcer_model::document::DocError>(())
    /// ```
    ///
    /// # Errors
    ///
    /// [`DocError`] — as [`Document::load_with_password`]. Under
    /// [`LoadOptions::strict()`] this refuses every malformation `Pass 283.0`
    /// taught the loader to decide.
    pub fn load_with_options(
        path: &Path,
        password: Option<&[u8]>,
        options: LoadOptions,
    ) -> Result<Self, DocError> {
        Self::from_bytes_with_options(std::fs::read(path)?, password, options)
    }

    /// Load a document from bytes (takes ownership — the buffer is
    /// retained for the document's lifetime; see module docs).
    ///
    /// # Errors
    ///
    /// [`DocError`] — see [`Document::load`].
    pub fn from_bytes(buf: Vec<u8>) -> Result<Self, DocError> {
        Self::from_bytes_with_password(buf, None)
    }

    /// Load a COS-family file whose header is NOT `%PDF-` — a `%PPKLITE-`
    /// address book or a `%FDF-` file — reusing the exact tokenizer, classic-
    /// xref parser and object assembly the strict PDF path uses (`Pass 10.2`).
    ///
    /// `markers` are the accepted first-line tokens (e.g. `[b"%PPKLITE-"]`).
    /// Only the STRICT path runs: there is no rebuild-by-scan recovery (these
    /// files are written by Acrobat and well-formed; a malformed one is an
    /// error, not a file to guess at) and no password (a trust store carries no
    /// `/Encrypt`). The result is an ordinary [`Document`] — `get`, `trailer`,
    /// `resolve` and the [`crate::graph::ObjectGraph`] impl all work — so a
    /// reader (e.g. [`crate::trust_store`]) walks it with the normal object
    /// model instead of a bespoke parser.
    ///
    /// # Errors
    ///
    /// [`DocError::Header`] if none of `markers` matches; [`DocError::Xref`] if
    /// the cross-reference chain does not parse; other [`DocError`] object-level
    /// failures as [`from_bytes_with_password`](Self::from_bytes_with_password).
    #[doc(hidden)] // workspace-internal: called by pdfcer-core, not API
    pub fn from_cos_bytes(buf: Vec<u8>, markers: &[&[u8]]) -> Result<Self, DocError> {
        let header_version = crate::probe_cos_header(&buf, markers).map_err(DocError::Header)?;
        let loaded = xref::load_xref_chain(&buf).map_err(DocError::Xref)?;
        let hybrid = loaded.hybrid_partition();
        Self::assemble(
            buf,
            header_version,
            loaded.table,
            loaded.trailer,
            loaded.startxref,
            loaded.newest_shape,
            loaded.highest_object_number,
            loaded.suppressed_by_size,
            hybrid,
            None,
            Credential::Password(None),
            LoadOptions::default(),
        )
    }

    /// Load a document from bytes, supplying a password for an encrypted file.
    ///
    /// See [`Document::load_with_password`] for what `None` means (it is not
    /// the empty password).
    ///
    /// # Errors
    ///
    /// [`DocError`] — see [`Document::load_with_password`].
    pub fn from_bytes_with_password(
        buf: Vec<u8>,
        password: Option<&[u8]>,
    ) -> Result<Self, DocError> {
        Self::from_bytes_with_options(buf, password, LoadOptions::default())
    }

    /// Load a document, choosing how its self-contradictions are decided
    /// (`Pass 283.0`).
    ///
    /// The intervention half of the operator's ruling: a shell that has shown
    /// the operator what pdfcer chose (via [`Document::load_anomalies`]) and
    /// been told to take the other value re-loads the same bytes through here.
    /// Everything else is identical to [`Document::from_bytes_with_password`],
    /// which is this with the defaults.
    ///
    /// # Errors
    ///
    /// [`DocError`] — see [`Document::load_with_password`].
    pub fn from_bytes_with_options(
        buf: Vec<u8>,
        password: Option<&[u8]>,
        options: LoadOptions,
    ) -> Result<Self, DocError> {
        Self::from_bytes_inner(buf, Credential::Password(password), options)
    }

    /// Load `buf` — bytes produced by saving this document incrementally —
    /// decrypting under this document's file key and access, with no
    /// password. An unencrypted document loads `buf` like
    /// [`Document::from_bytes`].
    ///
    /// The contract is that `buf` keeps this document's `/Encrypt` and
    /// `/ID[0]` (an incremental save carries both, ISO 32000-2 §7.6.3); bytes
    /// from anywhere else decrypt to noise.
    ///
    /// # Errors
    ///
    /// [`DocError`] — see [`Document::load`].
    pub fn reopen_appended(&self, buf: Vec<u8>) -> Result<Self, DocError> {
        let credential = match &self.encryption {
            Some(e) => Credential::Reuse(e),
            None => Credential::Password(None),
        };
        Self::from_bytes_inner(buf, credential, LoadOptions::default())
    }

    fn from_bytes_inner(
        buf: Vec<u8>,
        credential: Credential<'_>,
        options: LoadOptions,
    ) -> Result<Self, DocError> {
        // 1. Header (§7.5.2 via the Pass 0 probe).
        match crate::probe_header(&buf) {
            // Header OK: try the strict §7.5.5 cross-reference load.
            Ok(header_version) => match xref::load_xref_chain(&buf) {
                Ok(loaded) => {
                    let hybrid = loaded.hybrid_partition();
                    Self::assemble(
                        buf,
                        header_version,
                        loaded.table,
                        loaded.trailer,
                        loaded.startxref,
                        loaded.newest_shape,
                        loaded.highest_object_number,
                        loaded.suppressed_by_size,
                        hybrid,
                        None,
                        credential,
                        options,
                    )
                }
                // The strict path failed. Decision 013: attempt
                // rebuild-by-scan recovery, but ONLY on the specific
                // failure kinds that mean the cross-reference machinery is
                // unparseable — never on the deliberate `/Encrypt`
                // capability gap, and never on a future unknown kind
                // (`recovery_reason_for` returns `None` for both).
                Err(e) => match recover::recovery_reason_for(&e.kind) {
                    None => Err(DocError::Xref(e)),
                    Some(reason) => match recover::recover(&buf, reason) {
                        Ok(rec) => Self::assemble_recovered(buf, Some(header_version), rec),
                        // A broken-xref-AND-encrypted file fails clean for
                        // the RIGHT reason (§7.6), not as a recovery error.
                        Err(recover::RecoverError::Encrypted) => Err(DocError::Xref(XrefError {
                            offset: 0,
                            kind: XrefErrorKind::EncryptionUnsupported,
                        })),
                        Err(other) => Err(DocError::Recovery(other)),
                    },
                },
            },
            // Header probe failed ("not a PDF", offset-start, leading junk).
            // Rebuild-by-scan is header-independent (absolute offsets), so
            // it also opens an offset-start file (decision 007 §10 item 6).
            // Attempt recovery, but succeed ONLY if the scan finds objects
            // AND a `/Catalog`; otherwise the ORIGINAL header error stands
            // ("not a PDF").
            Err(header_err) => match recover::recover(&buf, recover::RecoveryReason::MissingHeader)
            {
                Ok(rec) => Self::assemble_recovered(buf, None, rec),
                Err(_) => Err(DocError::Header(header_err)),
            },
        }
    }

    /// Assemble a [`Document`] from a cross-reference view (table plus
    /// trailer plus physical facts), running the §7.5.7 two-phase eager
    /// parse. Shared by the strict load path and the recovery path so the
    /// object-parse, object-stream resolution, and linearization detection
    /// are written exactly once.
    ///
    /// `recovery` is `Some` only on the rebuild-by-scan path; the writer
    /// and front ends read it (decision 013).
    #[allow(clippy::too_many_arguments)] // a private assembly seam; the
    // alternative (a builder struct) buys nothing for two call sites.
    fn assemble(
        mut buf: Vec<u8>,
        header_version: PdfVersion,
        table: XrefTable,
        trailer: Dict,
        base_startxref: u64,
        section_shape: SectionShape,
        highest_object_number: u32,
        suppressed_by_size: usize,
        hybrid: crate::xref::HybridPartition,
        recovery: Option<RecoveryReport>,
        credential: Credential<'_>,
        options: LoadOptions,
    ) -> Result<Self, DocError> {
        // Phase 1. Eagerly parse every file-level in-use object. Strict on
        // the clean path; on the recovery path the SAME `/Length`-vs-
        // `endstream` leniency `crate::recover`'s confirmation step used
        // must apply here too, or an object recovery accepted would be
        // rejected on re-parse and cost the whole document (the exact
        // failure this policy exists to close). Free entries resolve to
        // null, not to bytes; type-2 entries wait for phase 2 (module docs).
        // THE CLEAN PATH IS LENIENT TOO SINCE `Pass 283.0`, and the
        // comment above used to say the opposite.
        //
        // `RecoverFromEndstream` re-derives an extent ONLY when the stored
        // `/Length` cannot be used — absent, non-integer, unresolvable, past
        // the end of the buffer, or not landing on `endstream`. A usable
        // `/Length` is still believed, so this changes behaviour for exactly
        // one class of file: the ones that previously FAILED.
        //
        // The operator's ruling: *"we should be making pdfcer so that it opens
        // pdfs that have errors, and have a way that it manages those errors
        // such that they aren't fatal."* Losing a 46 KB drawing over a
        // `/Metadata` stream that omits `/Length` — which is what happened, on
        // the very next object after the duplicate key that motivated this
        // Pass — is the failure that ruling names.
        //
        // Every recovery is recorded as a `LoadAnomaly` and disclosed. A
        // caller that wants the old refusal has `LoadOptions`.
        let length_policy = if recovery.is_some() {
            StreamLengthPolicy::RecoverFromEndstream
        } else {
            options.stream_lengths
        };
        // The missing-`endobj` leniency travels with the length leniency,
        // and for exactly the same stated reason: an object `recover`'s
        // confirmation step accepted must not be rejected on re-parse
        // here, or the recovery costs the whole document.
        let terminator_policy = if recovery.is_some() {
            TerminatorPolicy::RecoverAtNextHeader
        } else {
            options.terminators
        };
        let mut anomalies: Vec<LoadAnomaly> = Vec::new();
        let mut objects: HashMap<ObjId, IndirectObject> = HashMap::new();
        let mut compressed: Vec<(u32, u32, u32)> = Vec::new();
        for (num, entry) in table.iter() {
            match entry {
                XrefEntry::InUse { offset, generation } => {
                    let id = ObjId::new(num, generation);
                    let parsed = parse_object_at(
                        &buf,
                        &table,
                        offset,
                        length_policy,
                        terminator_policy,
                        // THE LOADER OPTS IN; the parser's own default stays
                        // strict. A duplicate key is a malformed ENTRY in an
                        // otherwise sound file, and refusing the object cost an
                        // operator a whole 46 KB drawing every other reader
                        // opens. Which value wins is the caller's to override
                        // (`LoadOptions`), and either way it is recorded.
                        options.duplicate_keys,
                    );
                    // ONE UNREADABLE OBJECT NO LONGER COSTS THE DOCUMENT.
                    //
                    // §7.3.10 already says what a reference to an object that
                    // is not there means: it "shall be treated as a reference
                    // to the null object", and "shall not be considered an
                    // error". An object whose bytes will not parse IS
                    // undefined as far as every consumer is concerned, so
                    // omitting it produces a document the standard describes
                    // rather than one pdfcer invented.
                    //
                    // Under `strict` this is still the refusal it always was.
                    let (io, repairs) = match parsed {
                        Ok(pair) => pair,
                        Err(source) => {
                            if options.unreadable_objects == UnreadableObjectPolicy::Refuse {
                                return Err(DocError::BadObject { id, offset, source });
                            }
                            anomalies.push(LoadAnomaly::ObjectUnreadable {
                                object: id,
                                reason: source.to_string(),
                            });
                            continue;
                        }
                    };
                    if repairs.stream_lengths > 0 {
                        anomalies.push(LoadAnomaly::StreamLengthRecovered { object: id });
                    }
                    if repairs.missing_endobj > 0 {
                        anomalies.push(LoadAnomaly::MissingEndobjRecovered { object: id });
                    }
                    anomalies.extend(repairs.duplicate_keys.into_iter().map(|rec| {
                        LoadAnomaly::DuplicateDictKey {
                            object: Some(id),
                            key: rec.key,
                            kept: rec.kept,
                            discarded: rec.discarded,
                        }
                    }));
                    if io.id != id {
                        // The table and the body disagree about which object
                        // lives here. Neither is more authoritative than the
                        // other, so pdfcer does not pick: the object the table
                        // promised is treated as undefined (§7.3.10), which is
                        // the same answer as "the table pointed at nothing".
                        if options.unreadable_objects == UnreadableObjectPolicy::Refuse {
                            return Err(DocError::ObjectIdMismatch {
                                expected: id,
                                found: io.id,
                                offset,
                            });
                        }
                        anomalies.push(LoadAnomaly::ObjectUnreadable {
                            object: id,
                            reason: format!(
                                "the cross-reference table points at offset {offset}, where the file declares {} instead",
                                io.id
                            ),
                        });
                        continue;
                    }
                    objects.insert(id, io);
                }
                XrefEntry::InStream { stream_num, index } => {
                    compressed.push((num, stream_num, index));
                }
                // `XrefEntry` is #[non_exhaustive] (§7.5.8.3 reserves
                // future types); an entry kind this build does not know
                // resolves to null, which is exactly what the spec
                // prescribes for unknown types.
                _ => {}
            }
        }

        // Phase 1.5. Decrypt (7.6), if the trailer says so.
        //
        // The position of this step is load-bearing, not stylistic. It runs
        // AFTER phase 1 -- which needs only spans and `/Length`, both of which
        // are plaintext integers -- and BEFORE phase 2, which inflates object
        // streams. Decrypting here makes every object stream's data plaintext
        // by the time phase 2 reads it, and the objects phase 2 parses out of
        // that data are then correctly left alone: strings inside an object
        // stream are NOT separately encrypted (TRAP T4). Moving this after
        // phase 2 would re-apply Algorithm 1 per contained object and corrupt
        // every string in every modern file.
        let encryption = Self::decrypt_in_place(&mut buf, &trailer, &mut objects, credential)?;

        // Phase 2. Resolve compressed objects through their containers,
        // decoding each container at most once. Deterministic order so
        // that a file with several broken containers always reports the
        // same one (`iter()` over a HashMap is not ordered).
        compressed.sort_unstable();
        Self::load_compressed(
            &buf,
            &compressed,
            &mut objects,
            options.unreadable_objects,
            &mut anomalies,
        )?;

        // Annex F detection runs on the raw buffer and needs no xref
        // (F.3.3: the parameter dictionary's values are all direct and
        // it is unreferenced from the document graph), but it is done
        // here rather than in `load_xref_chain` because it is a
        // property of the *file*, not of its cross-reference machinery.
        let linearization = linearization::detect(&buf);

        Ok(Self {
            buf,
            header_version,
            xref: table,
            trailer,
            objects,
            base_startxref,
            section_shape,
            linearization,
            highest_object_number,
            suppressed_by_size,
            hybrid,
            anomalies,
            recovery,
            encryption,
        })
    }

    /// Authenticate and decrypt the loaded objects in place (7.6).
    ///
    /// Returns `Ok(None)` for an unencrypted document -- the overwhelmingly
    /// common case, and a single `contains_key` away.
    ///
    /// # What "in place" means, and its consequence for saving
    ///
    /// **Stream data is decrypted in the retained buffer.** RC4 is a stream
    /// cipher and preserves length exactly, so the plaintext fits precisely
    /// where the ciphertext was and every span, `/Length` and provenance
    /// record stays true. That is what lets this increment land without
    /// touching [`Stream`](crate::object::Stream), which holds a span rather
    /// than owning bytes. AES will not have that property -- its plaintext is
    /// shorter than its ciphertext -- so the AES increment has to solve a
    /// problem this one did not.
    ///
    /// **Strings are decrypted in the parsed objects**, because
    /// [`Object::String`] owns its bytes and a decrypted string cannot
    /// generally be re-escaped into the same number of source bytes.
    ///
    /// So after this runs, the buffer and the parsed objects **disagree**:
    /// streams are plaintext in both, strings are plaintext only in the
    /// objects. That is why a full rewrite refuses a decrypted document (its
    /// verbatim copies would put plaintext under `/Encrypt`), and why the
    /// pre-decryption bytes are kept: an incremental save appends to them,
    /// encrypting only what it writes.
    ///
    /// # Errors
    ///
    /// [`DocError::Encryption`] for a configuration pdfcer will not decrypt;
    /// [`DocError::PasswordRequired`] when nothing authenticated.
    fn decrypt_in_place(
        buf: &mut [u8],
        trailer: &Dict,
        objects: &mut HashMap<ObjId, IndirectObject>,
        credential: Credential<'_>,
    ) -> Result<Option<DocumentEncryption>, DocError> {
        use crate::crypto::{EncryptionConfig, EncryptionUnsupported, apply};

        let Some(entry) = trailer.get(b"Encrypt") else {
            return Ok(None);
        };

        // The `/Encrypt` dictionary is usually direct in the trailer, but may
        // be indirect. If it is, its object number must be remembered: its
        // `/O` and `/U` are the INPUTS to the key derivation, so decrypting
        // them with a key derived from themselves would authenticate
        // successfully and then produce a document of noise (E2/E3).
        let (encrypt_dict, encrypt_dict_id) = match entry {
            Object::Dict(d) => (d.clone(), None),
            Object::Reference(id) => match objects.get(id).map(|o| &o.value) {
                Some(Object::Dict(d)) => (d.clone(), Some(id.num)),
                _ => {
                    return Err(DocError::Encryption(EncryptionUnsupported::Malformed(
                        "/Encrypt names an object that is not a dictionary",
                    )));
                }
            },
            _ => {
                return Err(DocError::Encryption(EncryptionUnsupported::Malformed(
                    "/Encrypt is neither a dictionary nor a reference",
                )));
            }
        };

        // Resolution for indirect `/O`, `/U` and `/CF` entries. Snapshotting
        // the values a closure needs is simpler than fighting the borrow
        // checker over `objects`, which is about to be mutated.
        let snapshot: HashMap<ObjId, Object> = objects
            .iter()
            .map(|(id, io)| (*id, io.value.clone()))
            .collect();
        let resolve = move |id: ObjId| snapshot.get(&id).cloned();

        let config = EncryptionConfig::parse(&encrypt_dict, &resolve)?;

        // Algorithm 2 step (e) and Algorithm 5 step (c) hash `/ID[0]`.
        // 7.6.1 E1: trailer `/ID` strings are never encrypted and are direct
        // objects, so this reads them as-is. A file with no `/ID` hashes
        // nothing there, which an empty slice expresses exactly -- the
        // algorithm has no branch for "no ID" (SPEC AMBIGUITY A4).
        let id0: Vec<u8> = match trailer.get(b"ID") {
            Some(Object::Array(items)) => match items.first() {
                Some(Object::String(s)) => s.clone(),
                _ => Vec::new(),
            },
            _ => Vec::new(),
        };

        let authenticated = match credential {
            Credential::Password(password) => config.authenticate(password, &id0),
            Credential::Reuse(e) => Some((e.key.clone(), e.auth)),
        };
        let Some((key, auth)) = authenticated else {
            // A failed authentication is normally just a wrong password. At
            // `/R` 5 with a non-ASCII password it is ambiguous, because the
            // SASLprep step pdfcer does not implement may have been the thing
            // that mattered -- and telling the operator "wrong password" for a
            // password that was right sends them to re-check the one thing
            // that is not the problem.
            return Err(match credential {
                Credential::Password(Some(pw)) if config.password_may_need_normalisation(pw) => {
                    DocError::PasswordRequiresNormalisation
                }
                // At /R 6 a failure is not unambiguously "wrong password": the
                // A13 loop-exit ambiguity can reject a correct password for a
                // file written under the other reading. Name it (Pass 5.4).
                _ if config.revision == 6 => DocError::PasswordRequiredR6,
                _ => DocError::PasswordRequired,
            });
        };

        // Algorithm 3.13, run once, immediately after the key is recovered and
        // before a single object is decrypted -- the check needs nothing but
        // the key, and running it here means the verdict is available to the
        // shells for the whole life of the document rather than being
        // recomputed on demand from state they would have to keep.
        let perms = config.check_perms(&key);
        let ciphertext: std::sync::Arc<[u8]> = std::sync::Arc::from(&*buf);

        // Decrypt every file-level object. Order within the map does not
        // matter: each object's key depends only on its own identity
        // (Algorithm 1), never on another object's contents.
        for (id, obj) in objects.iter_mut() {
            if apply::skip(obj, encrypt_dict_id, config.encrypt_metadata).is_some() {
                continue;
            }
            if key.streams_encrypted()
                && let Object::Stream(stream) = &mut obj.value
            {
                let span = stream.data_span;
                let end = span.start.saturating_add(span.len);
                // Checked access, not an in-bounds proof: `data_span` comes
                // from a `/Length` in an untrusted file, and a stream whose
                // declared length runs past the buffer is a real thing a
                // malformed (or deliberately hostile) document contains. A
                // span that does not fit is left alone -- the object then
                // fails to decode later, with an error about the object, which
                // is the honest place for it.
                if let Some(cipher_text) = buf.get(span.start..end) {
                    let plain = key.decrypt_stream(*id, cipher_text);
                    // ** The plaintext may be SHORTER than the ciphertext. **
                    //
                    // Increment 1 asserted the opposite here -- `RC4 must
                    // preserve length` -- and guarded the copy on
                    // `plain.len() == span.len`. That was true and correct for
                    // RC4, and it is the R186 shape: a guard keyed on a
                    // property that quietly stopped holding. Under `/AESV2`
                    // the ciphertext carries a 16-byte IV plus padding (T5), so
                    // the equality is ALWAYS false, the copy would ALWAYS be
                    // skipped, and every stream in an AES document would stay
                    // ciphertext -- with no test red and no error raised.
                    //
                    // Shorter is the easy direction: the plaintext still fits
                    // at `span.start`, so only the recorded length changes.
                    // Nothing re-reads the dictionary's `/Length` after parse
                    // (it is consumed once, at parser.rs's stream read), and
                    // `data_span` is what every downstream reader actually
                    // slices -- content.rs, attachments.rs, the object-stream
                    // path, edit.rs. So shortening the span is sufficient and
                    // `Stream` needs no new field.
                    if plain.len() <= span.len
                        && let Some(slot) = buf.get_mut(span.start..span.start + plain.len())
                    {
                        slot.copy_from_slice(&plain);
                        stream.data_span.len = plain.len();
                    }
                    // A plaintext LONGER than its ciphertext is impossible for
                    // both implemented ciphers, so there is no branch for it:
                    // it would have to overwrite the following object, and
                    // silently declining is the only safe response.
                }
            }
            if key.strings_encrypted() {
                apply::decrypt_strings(&mut obj.value, *id, &key);
            }
        }

        Ok(Some(DocumentEncryption {
            config,
            auth,
            perms,
            key,
            encrypt_dict_id,
            ciphertext,
            rc4_append: crate::writer::Rc4Append::Refuse,
        }))
    }

    /// How this document was encrypted, if it was -- `None` for a plain file.
    ///
    /// A **disclosure**, not a gate. See [`DocumentEncryption`].
    #[must_use]
    pub fn encryption(&self) -> Option<&DocumentEncryption> {
        self.encryption.as_ref()
    }

    /// Choose whether an incremental save of an RC4-encrypted document keeps
    /// its RC4 handler ([`Rc4Append::Preserve`]) or is refused
    /// ([`Rc4Append::Refuse`], the default). No effect on a plain or AES
    /// document.
    ///
    /// Preserve keeps existing signatures valid, at a cost the save reports
    /// in [`SaveReport::rc4_keystream_reused`]: an edited object rewritten
    /// under its old number and generation is encrypted with the same RC4
    /// keystream as its previous revision. Decision 190.
    ///
    /// [`Rc4Append::Preserve`]: crate::writer::Rc4Append::Preserve
    /// [`Rc4Append::Refuse`]: crate::writer::Rc4Append::Refuse
    /// [`SaveReport::rc4_keystream_reused`]: crate::writer::SaveReport::rc4_keystream_reused
    pub fn set_rc4_append(&mut self, policy: crate::writer::Rc4Append) {
        if let Some(enc) = self.encryption.as_mut() {
            enc.rc4_append = policy;
        }
    }

    /// Drop this document's encryption, in memory, without re-parsing.
    ///
    /// Load already decrypted every object's strings (in the parsed values) and
    /// every stream's data (in the retained buffer) — see
    /// [`Document::decrypt_in_place`]. So a document that WAS encrypted is,
    /// object-for-object, already a plaintext document; the only things still
    /// asserting encryption are the [`encryption`](Self::encryption) field and
    /// the trailer's `/Encrypt` reference. Clearing both is all that
    /// "remove encryption" needs at the model level — the writer then emits
    /// plaintext because the bytes it re-serialises already are.
    ///
    /// `Pass 5.4`: used by `pdfcer_core::EditSession::remove_encryption` and
    /// `pdfcer_core::EditSession::set_permissions` (which re-keys, so it first
    /// clears the old state, then the writer freshly encrypts).
    #[doc(hidden)] // workspace-internal: called by pdfcer-core, not API
    pub fn clear_encryption(&mut self) {
        self.encryption = None;
        self.trailer.remove(b"Encrypt");
    }

    /// Assemble a [`Document`] from a [`recover::RecoveredXref`].
    ///
    /// The recovered document is fixed into the shape a save must take
    /// (decision 013 §3.3.4, the recovered-base rule): its section shape is
    /// a plain classic table (`xref_stm: None`) so a full rewrite emits a
    /// fresh valid classic cross-reference, and `base_startxref` is 0
    /// because incremental append onto a broken base is refused by the
    /// writer. `/Size` suppression is 0 — recovery's synthesized `/Size`
    /// already covers every recovered object.
    ///
    /// `header_override` is the header-probe version when the header parsed
    /// (the xref-failure path); `None` on the header-failure path, where
    /// the recovery's own whole-buffer version scan is authoritative.
    fn assemble_recovered(
        buf: Vec<u8>,
        header_override: Option<PdfVersion>,
        rec: recover::RecoveredXref,
    ) -> Result<Self, DocError> {
        let version = header_override.unwrap_or(rec.version);
        Self::assemble(
            buf,
            version,
            rec.table,
            rec.trailer,
            0,
            SectionShape::Classic { xref_stm: None },
            rec.highest_object_number,
            0,
            // A recovered base is rebuilt by scanning object headers, and the
            // scan sees every object equally — the §7.5.8.4 partition is not
            // recoverable from it, and `SectionShape::Classic { xref_stm: None }`
            // above already says the output is not hybrid. Default, not a
            // guess.
            crate::xref::HybridPartition::default(),
            Some(rec.report),
            // The recovery path never carries a password: `recover` refuses an
            // encrypted file outright (`RecoverError::Encrypted`), because
            // rebuild-by-scan looks for `N G obj` headers in bytes that would
            // be ciphertext. So a recovered document is never encrypted, and
            // threading a password here would be dead weight that read as
            // support.
            Credential::Password(None),
            LoadOptions::default(),
        )
    }

    /// Load phase 2: resolve every type-2 (`InStream`) cross-reference
    /// entry through its object stream, inserting the parsed objects
    /// into `objects`.
    ///
    /// `compressed` is `(object number, container object number, index
    /// within container)`, sorted. Containers are looked up in
    /// `objects` — which is why this runs strictly after phase 1 (module
    /// docs) — decoded once, and cached for the rest of the load. A
    /// container that fails is remembered too: its later members are
    /// recorded with the first failure's reason, without another decode.
    ///
    /// Every compressed object is inserted with generation **0**:
    /// §7.5.7 fixes the generation of a compressed object at zero, and a
    /// type-2 entry carries no generation field to disagree with.
    fn load_compressed(
        buf: &[u8],
        compressed: &[(u32, u32, u32)],
        objects: &mut HashMap<ObjId, IndirectObject>,
        policy: UnreadableObjectPolicy,
        anomalies: &mut Vec<LoadAnomaly>,
    ) -> Result<(), DocError> {
        let mut cache: HashMap<u32, ObjectStream> = HashMap::new();
        // Containers that could not be decoded, with the reason, so a bad
        // stream costs one decode per load rather than one per member.
        let mut failed: HashMap<u32, String> = HashMap::new();

        // A COMPRESSED OBJECT THAT CANNOT BE READ IS UNDEFINED, NOT FATAL
        // — the same §7.3.10 reading the file-level loop applies, and for the
        // same reason: five of this function's refusals were "one object is
        // broken, so you get no document."
        //
        // Each is recorded with the object it cost and why. Under `strict`
        // every one is still the error it was.
        macro_rules! give_up_on {
            ($num:expr, $reason:expr, $err:expr) => {{
                if policy == UnreadableObjectPolicy::Refuse {
                    return Err($err);
                }
                anomalies.push(LoadAnomaly::ObjectUnreadable {
                    object: ObjId::new($num, 0),
                    reason: $reason,
                });
                continue;
            }};
        }

        for &(num, stream_num, index) in compressed {
            // §7.5.7: "The generation number of an object stream and of
            // any compressed object shall be zero."
            let container = ObjId::new(stream_num, 0);

            // A container that already failed is not decoded again: its
            // members get the first failure's reason. Only reachable under
            // the lenient policy (strict returned on that first failure).
            if let Some(reason) = failed.get(&stream_num) {
                anomalies.push(LoadAnomaly::ObjectUnreadable {
                    object: ObjId::new(num, 0),
                    reason: reason.clone(),
                });
                continue;
            }
            let objstm = match cache.entry(stream_num) {
                Entry::Occupied(slot) => slot.into_mut(),
                Entry::Vacant(slot) => match decode_container(buf, objects, container, num) {
                    Ok(parsed) => slot.insert(parsed),
                    Err((reason, err)) => {
                        failed.insert(stream_num, reason.clone());
                        give_up_on!(num, reason, err)
                    }
                },
            };

            let value = match member_at(objstm, container, num, index) {
                Ok(value) => value,
                Err((reason, err)) => give_up_on!(num, reason, err),
            };

            let id = ObjId::new(num, 0);
            objects.insert(
                id,
                IndirectObject {
                    id,
                    value,
                    provenance: Provenance::ObjectStream { container, index },
                },
            );
        }
        Ok(())
    }

    /// The retained source bytes (the coordinate system every span in
    /// this document indexes into).
    #[must_use]
    pub fn bytes(&self) -> &[u8] {
        &self.buf
    }

    /// A read view of this document for the rasterizer, the vector object
    /// model and `pageops` — the file exactly as loaded.
    ///
    /// The mirror of `EditSession::view`,
    /// and the reason every read path can take one parameter type
    /// ([`DocumentView`]) instead of two overloads. A `Document` has no
    /// overlay and no staging buffer, so its view carries a
    /// [`StreamSource::Contiguous`](crate::view::StreamSource::Contiguous)
    /// over [`Document::bytes`] — meaning "render the file as it is on
    /// disk", which is exactly what `pdfcer` and the round-trip tools
    /// want — and why `pdfcer-render`'s `&Document` back-compat wrappers can
    /// build one implicitly without changing any caller's behaviour.
    ///
    /// Cheap: two borrows plus a version probe. Building one per call is
    /// the intended usage; there is nothing to cache.
    ///
    /// # Examples
    ///
    /// ```
    /// use pdfcer_model::document::Document;
    /// use pdfcer_model::graph::ObjectGraph;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let doc = Document::from_bytes(
    ///     include_bytes!("../../../fixtures/synthetic/hello.pdf").to_vec(),
    /// )?;
    /// let view = doc.view();
    /// assert_eq!(view.version(), doc.version());
    /// assert_eq!(view.catalog_id(), doc.catalog_id());
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn view(&self) -> DocumentView<'_> {
        DocumentView::new(self, self.bytes(), self.version())
    }

    /// The newest trailer dictionary (§7.5.5 Table 15).
    #[must_use]
    pub const fn trailer(&self) -> &Dict {
        &self.trailer
    }

    /// The merged cross-reference table.
    #[must_use]
    pub const fn xref(&self) -> &XrefTable {
        &self.xref
    }

    /// The document's effective version: the header's `%PDF-M.N`,
    /// upgraded by the catalog's `/Version` name if present and higher
    /// (§7.5.5: version = max of the two; the catalog entry exists so
    /// an incremental update can raise the version without touching
    /// byte 0).
    #[must_use]
    pub fn version(&self) -> PdfVersion {
        let catalog_version = self
            .catalog()
            .ok()
            .and_then(|cat| cat.get(b"Version"))
            .and_then(Object::as_name)
            .and_then(|n| parse_version_name(n.as_bytes()));
        match catalog_version {
            Some(v) if v > self.header_version => v,
            _ => self.header_version,
        }
    }

    /// Look up an indirect object by full identity, applying the
    /// §7.3.10/§7.5.4 rules (module docs): dangling, stale-generation,
    /// and free all yield `None` here — callers wanting the null-object
    /// semantics use [`Document::resolve`], which maps `None` to
    /// [`Object::Null`].
    #[must_use]
    pub fn get(&self, id: ObjId) -> Option<&IndirectObject> {
        self.objects.get(&id)
    }

    /// Resolve `obj` to a non-reference value: follow reference chains
    /// (depth-guarded), mapping every unresolvable case to the null
    /// object per §7.3.10. Non-reference objects return themselves.
    #[must_use]
    pub fn resolve<'a>(&'a self, obj: &'a Object) -> &'a Object {
        const NULL: &Object = &Object::Null;
        let mut current = obj;
        for _ in 0..MAX_RESOLVE_DEPTH {
            match current {
                Object::Reference(id) => match self.get(*id) {
                    Some(io) => current = &io.value,
                    None => return NULL,
                },
                other => return other,
            }
        }
        // Chain too deep / cyclic: null, not an error (module docs).
        NULL
    }

    /// The document catalog (§7.7.2) — the dictionary the trailer's
    /// required `/Root` reference points at.
    ///
    /// # Errors
    ///
    /// [`DocError::NoCatalog`] if `/Root` is missing, not a reference,
    /// or doesn't resolve to a dictionary.
    pub fn catalog(&self) -> Result<&Dict, DocError> {
        self.trailer
            .get(b"Root")
            .map(|root| self.resolve(root))
            .and_then(Object::as_dict)
            .ok_or(DocError::NoCatalog)
    }

    /// Number of parsed (in-use) objects.
    #[must_use]
    pub fn object_count(&self) -> usize {
        self.objects.len()
    }

    /// Iterate all parsed indirect objects (unordered).
    pub fn objects(&self) -> impl Iterator<Item = &IndirectObject> {
        self.objects.values()
    }

    /// The byte offset this file's own `startxref` names (§7.5.5).
    ///
    /// This is the value an appended update's `/Prev` must carry —
    /// §7.5.6: *"a `Prev` entry giving the location of the previous
    /// cross-reference section"*, which is the section `startxref`
    /// currently points at. Taking the base trailer's own `/Prev`
    /// instead is the classic off-by-one-revision bug: it would skip a
    /// revision and silently resurrect superseded objects.
    #[must_use]
    pub const fn base_startxref(&self) -> u64 {
        self.base_startxref
    }

    /// The physical form of the newest cross-reference section.
    ///
    /// The writer matches this rather than choosing (R33): emitting a
    /// cross-reference stream where the base file had a classic table
    /// silently raises a PDF 1.4 document's effective version to 1.5.
    /// §7.5.6 does not require the match — that is a recorded spec
    /// silence — which is exactly why pdfcer imposes it.
    #[must_use]
    pub const fn section_shape(&self) -> SectionShape {
        self.section_shape
    }

    /// Whether this file is a §7.5.8.4 **hybrid-reference** file: a
    /// classic cross-reference section whose trailer carries
    /// `/XRefStm`.
    ///
    /// Hybrid files are readable by pre-1.5 readers *and* carry the
    /// PDF 1.5 features those readers cannot see. Incremental save
    /// preserves that duality (form A: a classic update section
    /// carrying `/XRefStm` forward); a full rewrite cannot, and refuses
    /// by name rather than flattening it.
    #[must_use]
    pub const fn is_hybrid(&self) -> bool {
        matches!(
            self.section_shape,
            SectionShape::Classic { xref_stm: Some(_) }
        )
    }

    /// Every contradiction this file contained that pdfcer **decided rather
    /// than refused** (`Pass 283.0`).
    ///
    /// # The three obligations this satisfies at once
    ///
    /// The operator's ruling: *"we should be making pdfcer so that it opens
    /// pdfs that have errors, and have a way that it manages those errors such
    /// that they aren't fatal, and if the user can intervene in a decision that
    /// should always be an option along with them not having to intervene."*
    ///
    /// - **Not fatal** — the document is loaded; this list is a report about
    ///   it, not a gate in front of it.
    /// - **Intervention possible** — each entry names what pdfcer chose *and
    ///   what it chose between*, which is what a shell needs to offer the
    ///   alternative. Re-load through [`Document::from_bytes_with_options`]
    ///   with the other policy to take it.
    /// - **Intervention optional** — a caller that never reads this gets a
    ///   working document with pdfcer's documented default.
    ///
    /// Empty for a file that contains no contradiction, which is the
    /// overwhelming majority. A non-empty list is not a warning that anything
    /// is *wrong with pdfcer's output* — it is the file saying two things.
    #[must_use]
    pub fn load_anomalies(&self) -> &[LoadAnomaly] {
        &self.anomalies
    }

    /// This file's §7.5.8.4 partition — which objects it **hides** behind
    /// `/XRefStm`, and whether pdfcer could read the stream that says so
    /// (`Pass 281.0`).
    ///
    /// # Why a writer needs it, and why re-deriving it would be wrong
    ///
    /// §7.5.8.4 describes a three-part unit a writer creates "at the same
    /// time": a main classic table marking the hidden objects **free with
    /// generation 65535**, an update section, and a cross-reference stream
    /// giving their real locations. Rewriting such a file means rebuilding
    /// that unit, which means knowing which side each object belongs on.
    ///
    /// §7.5.8.4's visibility rule answers a **different question** — what a
    /// producer is *permitted* to hide. This answers what this file *did*
    /// hide. A file may legally hide less than it could, and a rewrite that
    /// re-derived the maximum would move objects the operator never touched,
    /// which is exactly the "plausible, working, wrong file" `R33` guards
    /// against.
    ///
    /// Empty and readable for every non-hybrid file. See
    /// [`crate::xref::HybridPartition::is_reproducible`] for the case that
    /// still refuses: a file that says it hides objects and whose stream
    /// pdfcer could not parse.
    #[must_use]
    pub const fn hybrid_partition(&self) -> &crate::xref::HybridPartition {
        &self.hybrid
    }

    /// The cross-reference **recovery** record, or `None` for a cleanly
    /// loaded file (decision 013).
    ///
    /// `Some` means the stored cross-reference table could not be parsed
    /// and pdfcer rebuilt it by scanning the file for `N G obj` headers
    /// (rebuild-by-scan). The returned [`RecoveryReport`] carries the
    /// counted disclosure (why the strict path failed, how many objects
    /// came from the file-level scan vs. object streams, collisions,
    /// trailer source, offset-start). This is a **reviewable fact**
    /// (fuzzy-never-sneaky, R20): the CLI prints it and forces a distinct
    /// exit status, and the GUI shows a banner. A recovered document also
    /// cannot be saved incrementally — see
    /// [`Document::save_incremental`]'s refusal.
    #[must_use]
    pub const fn recovery(&self) -> Option<&RecoveryReport> {
        self.recovery.as_ref()
    }

    /// Whether this document was loaded via cross-reference recovery
    /// (decision 013) — the shorthand the writer's incremental-save refusal
    /// and the front ends' disclosure branch on.
    #[must_use]
    pub const fn loaded_via_recovery(&self) -> bool {
        self.recovery.is_some()
    }

    /// Annex F linearization ("Fast Web View") state, detected at load.
    ///
    /// Reported so a save can warn before spending the property
    /// (F.1: an incremental update *"shall"* de-linearize). pdfcer never
    /// repairs it and never strips a stale `/Linearized` dictionary —
    /// see [`crate::linearization`].
    #[must_use]
    pub const fn linearization(&self) -> Linearization {
        self.linearization
    }

    /// Save an incremental update (§7.5.6) to `path`.
    ///
    /// This is pdfcer's **default** save mode (`ARCHITECTURE.md` §5):
    /// the existing bytes are copied untouched and a new revision is
    /// appended, which is what keeps any pre-existing digital
    /// signature's `/ByteRange` digest valid (§12.8.1 NOTE 1).
    ///
    /// `dirty` is the **save-time diff against the base revision**, and
    /// the only thing that should compute one is
    /// `pdfcer_core::edit::EditSession::dirty_set` — see
    /// `ARCHITECTURE.md` §11.1 for the "union of every command ever run"
    /// bug that a hand-built dirty set reintroduces. An empty one gives
    /// byte-identical output.
    ///
    /// ⚠️ **Incremental save structurally preserves superseded
    /// content.** The old bytes of every replaced object remain in the
    /// file by construction. Any operation whose contract is *removal*
    /// — redaction above all — must therefore use
    /// [`Document::save_full`] and must refuse this mode (R35).
    ///
    /// # Errors
    ///
    /// [`crate::writer::WriteError`] — I/O, a broken provenance span,
    /// or a cross-reference form that cannot express an entry.
    pub fn save_incremental(
        &self,
        path: &Path,
        dirty: &crate::writer::DirtySet,
        options: &crate::writer::SaveOptions,
    ) -> Result<crate::writer::SaveReport, crate::writer::WriteError> {
        let (bytes, report) = crate::writer::save_incremental(self, dirty, options)?;
        std::fs::write(path, &bytes)?;
        Ok(report)
    }

    /// Rewrite the whole document to `path` as a single revision.
    ///
    /// Every `File`-provenance object is re-emitted from its retained
    /// source bytes verbatim; only the header prefix, object offsets,
    /// the cross-reference section and the trailer are regenerated. So
    /// byte identity holds **per object definition**, never for the
    /// file as a whole (R32) — offsets legitimately move.
    ///
    /// ⚠️ **A full rewrite invalidates every existing digital
    /// signature**, because a signature covers a byte range that this
    /// mode necessarily disturbs (§12.8.1). That collides with R35's
    /// requirement that redaction use this mode; "redact a signed
    /// document" is a genuine either/or for the operator to resolve,
    /// never something pdfcer decides silently (R36, decision 007 W7).
    ///
    /// # Errors
    ///
    /// [`crate::writer::WriteError`], notably
    /// [`WriteError::HybridFullRewrite`](crate::writer::WriteError::HybridFullRewrite)
    /// for a §7.5.8.4 hybrid-reference input.
    pub fn save_full(
        &self,
        path: &Path,
        dirty: &crate::writer::DirtySet,
        options: &crate::writer::SaveOptions,
    ) -> Result<crate::writer::SaveReport, crate::writer::WriteError> {
        let (bytes, report) = crate::writer::save_full(self, dirty, options)?;
        std::fs::write(path, &bytes)?;
        Ok(report)
    }

    /// The lowest object number this document does **not** already
    /// account for — where a newly created object goes.
    ///
    /// Four sources are consulted, and taking the maximum of all four
    /// is the point:
    ///
    /// 1. **the highest number the cross-reference chain mentions before
    ///    the `/Size` filter runs.** The unfiltered number, deliberately:
    ///    `/Size` is a hard reader-side filter, so a file that
    ///    under-reports it loads with real entries invisible, and
    ///    allocating from the *filtered* view picks a number the file
    ///    already defines. That produces an update section whose entry
    ///    collides with a live object — a file that looks fine and
    ///    resolves to the wrong bytes. Found by the `writer_roundtrip`
    ///    fuzz target, on a corpus file carrying `/Size 3` over six
    ///    entries.
    ///
    ///    Free entries count too. A free number is *reusable* in
    ///    principle (§7.5.4's free list exists to be consumed), but
    ///    reusing one correctly means honouring the generation rules —
    ///    a resurrected object takes the free entry's generation — and
    ///    pdfcer has no deletion path to have created those entries in
    ///    the first place. Allocating past them is always safe;
    ///    consuming them is Pass 3.2 work.
    /// 2. every parsed object, in case the two disagree;
    /// 3. the trailer's `/Size`, so a *stale, oversized* `/Size` cannot
    ///    hand out a number that a `/Prev` revision defines and this
    ///    merged view dropped.
    /// 4. **the newest cross-reference STREAM's own object number**, when
    ///    the file has one ([`Document::section_shape`]).
    ///
    /// ## Why source 4 exists, and the bug it closes
    ///
    /// A cross-reference stream is an indirect object, and the writer
    /// **reuses its number** for the update section it emits (`R33`: match
    /// the base's section shape). But it is *the section*, not a body
    /// object — the parser never files it in `objects`, and there is no
    /// requirement anywhere that it appear in its own `/Index` or be
    /// covered by its own `/Size`.
    ///
    /// So a file can carry `75 0 obj << /Type /XRef /Size 75 /Index [9 1 29
    /// 45] >>`: object 75 exists, and every one of sources 1–3 answers 74.
    /// This function then handed out **75**, the session wrote its new
    /// object there, and the writer wrote *its own cross-reference stream*
    /// over the top of it — same object number, later in the file, so the
    /// session's object simply vanished and the reader resolved the
    /// reference to the xref stream.
    ///
    /// The failure is silent in the worst way: the file parses, opens, and
    /// renders. Only the one thing the edit added is missing. Found by
    /// `tools/embed-sweep` over the pdfium corpus
    /// (`testing/resources/annotation_stamp_with_ap.pdf`), where an embedded
    /// font program came back as a 44-byte cross-reference stream and the
    /// text it should have drawn was silently skipped.
    ///
    /// **This was never specific to font embedding.** Any command that
    /// creates an object — adding text, an image, an annotation, a form
    /// field — hits it on any file shaped this way. It survived because a
    /// collision needs a file whose xref stream is outside its own `/Size`,
    /// which no producer pdfcer's fixtures came from emits.
    ///
    /// Returns `None` only if the document already reaches
    /// [`u32::MAX`], which Annex C's implementation limits put far out
    /// of reach for any real file — reported rather than wrapped,
    /// because silently allocating object 0 would corrupt the free list.
    ///
    /// ⚠️ A caller must **also** check
    /// [`Document::suppressed_object_count`] before creating an object:
    /// a valid number is not by itself a licence to write one.
    #[must_use]
    pub fn next_object_number(&self) -> Option<u32> {
        let from_objects = self.objects.keys().map(|id| id.num).max().unwrap_or(0);
        let from_size = self
            .trailer
            .get(b"Size")
            .and_then(Object::as_int)
            .and_then(|s| u32::try_from(s.saturating_sub(1)).ok())
            .unwrap_or(0);
        // Source 4 — see this function's docs. The writer reuses this number
        // for the section it emits, so handing it out would guarantee a
        // collision rather than merely risk one.
        let from_section = match self.section_shape {
            SectionShape::Stream { id, .. } => id.num,
            // A classic table is not an object and spends no number. The
            // `_` arm is deliberate: `SectionShape` is `#[non_exhaustive]`,
            // and a shape this build does not know must not silently be
            // treated as spending a number it might.
            _ => 0,
        };
        self.highest_object_number
            .max(from_objects)
            .max(from_size)
            .max(from_section)
            .checked_add(1)
            .filter(|n| *n != 0)
    }

    /// How many cross-reference entries this file's `/Size` is hiding.
    ///
    /// ## Why anyone cares (and why it blocks object creation)
    ///
    /// Table 15 / §7.5.5 make `/Size` a hard filter: an object numbered
    /// at or above it *"shall be ignored and defined to be missing"*. A
    /// file whose `/Size` under-reports is therefore **relying on the
    /// filter** — the entries above it are invisible, and the document
    /// may only be loadable at all because they are (they can point at
    /// bytes that do not parse).
    ///
    /// Creating an object raises `/Size`. That does not merely add the
    /// new object: it **exposes every suppressed entry below the new
    /// number**, resurrecting objects the operator never touched. Two
    /// separate rules say no — §5's minimal-diff invariant (an edit must
    /// not change objects it did not name) and R27's fail-clean posture
    /// (name the refusal rather than produce a plausible wrong file).
    ///
    /// So a non-zero count means *"an edit may modify existing objects
    /// in this file, but must not create one"*. The eventual fix is to
    /// emit explicit free entries (§7.5.4, generation 65535 — the very
    /// mechanism §7.5.8.4 uses to hide an object) for the exposed range,
    /// which needs free-list writing that Pass 3.2 brings.
    ///
    /// Zero for essentially every well-formed file, which is why this is
    /// a refusal rather than a feature gap worth blocking on.
    #[must_use]
    pub const fn suppressed_object_count(&self) -> usize {
        self.suppressed_by_size
    }
}

/// Parse the indirect object at `offset`, resolving indirect `/Length`
/// values through the xref table (the §7.3.10 EXAMPLE 3 pattern: the
/// length object is itself fetched and parsed on demand — it is always
/// a plain integer object, so this nested parse cannot recurse).
///
/// `pub(crate)` so the cross-reference recovery path (`crate::recover`) can
/// reuse the exact same object-parse + indirect-`/Length` resolution the
/// normal loader uses (rule 13: no new tokenizer) when confirming scanned
/// `N G obj` candidates.
///
/// `policy` selects the `/Length`-vs-`endstream` strictness
/// ([`StreamLengthPolicy`]). It is [`StreamLengthPolicy::Strict`] on every
/// clean-load call site and [`StreamLengthPolicy::RecoverFromEndstream`]
/// only under rebuild-by-scan recovery. Returns the parsed object together
/// with the number of stream extents that had to be re-derived (always `0`
/// under `Strict`), so the caller can fold it into the counted disclosure.
///
/// Note the nested `resolve_length` parse stays **strict** regardless: a
/// `/Length` object is a plain integer (§7.3.10 EXAMPLE 3), never a stream,
/// so the policy has nothing to act on there and holding it strict keeps
/// the nested parse from recursing into extent recovery.
pub(crate) fn parse_object_at(
    buf: &[u8],
    table: &XrefTable,
    offset: u64,
    policy: StreamLengthPolicy,
    terminator: TerminatorPolicy,
    duplicates: crate::parser::DuplicateKeyPolicy,
) -> Result<(IndirectObject, ParseRepairs), ParseError> {
    let offset = usize::try_from(offset).unwrap_or(usize::MAX);
    let mut resolve_length = |id: ObjId| -> Option<i64> {
        let XrefEntry::InUse {
            offset: len_offset,
            generation,
        } = table.get(id.num)?
        else {
            return None;
        };
        if generation != id.generation {
            return None;
        }
        let len_offset = usize::try_from(len_offset).ok()?;
        let io = Parser::at(buf, len_offset)
            .parse_indirect_object(&mut |_| None)
            .ok()?;
        (io.id == id).then_some(())?;
        io.value.as_int()
    };
    let mut parser = Parser::at(buf, offset)
        .with_stream_length_policy(policy)
        .with_terminator_policy(terminator)
        .with_duplicate_key_policy(duplicates);
    let io = parser.parse_indirect_object(&mut resolve_length)?;
    Ok((
        io,
        ParseRepairs {
            duplicate_keys: parser.duplicate_keys().to_vec(),
            stream_lengths: parser.stream_lengths_recovered(),
            missing_endobj: parser.missing_endobj_recovered(),
        },
    ))
}

/// How to load a document that contradicts itself (`Pass 283.0`).
///
/// # Why this type exists rather than a global setting
///
/// The operator's ruling has two halves that pull in opposite directions:
/// a file with errors must open **without intervention**, and intervening must
/// **always be possible**. A default plus this struct is how both hold at once
/// — [`Default`] is what every existing caller already gets, and a shell that
/// wants to offer the operator a choice re-loads the same bytes with a
/// different policy and shows the difference.
///
/// Re-loading rather than patching in place is deliberate: a decision made
/// during parsing is not a value that can be edited afterwards, because the
/// discarded one was never built into the document. Carrying both would make
/// every dictionary lookup ambiguous for the life of the session to serve a
/// case that is one keystroke away from being re-read.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct LoadOptions {
    /// Which value wins when one dictionary names a key twice (§7.3.7).
    ///
    /// Defaults to [`crate::parser::DuplicateKeyPolicy::KeepLast`] — see that
    /// type for why last, and [`Document::load_anomalies`] for how a caller
    /// learns a choice was made at all.
    pub duplicate_keys: crate::parser::DuplicateKeyPolicy,
    /// What to do when a stream's `/Length` cannot be used (§7.3.8.2).
    ///
    /// Defaults to [`StreamLengthPolicy::RecoverFromEndstream`], which only
    /// acts when the stored value is unusable. Set
    /// [`StreamLengthPolicy::Strict`] to refuse such a file instead.
    pub stream_lengths: StreamLengthPolicy,
    /// What to do when an indirect object's `endobj` is missing (§7.3.10).
    ///
    /// Defaults to [`TerminatorPolicy::RecoverAtNextHeader`].
    pub terminators: TerminatorPolicy,
    /// What to do when one object cannot be loaded at all.
    ///
    /// Defaults to [`UnreadableObjectPolicy::TreatAsUndefined`] — §7.3.10's
    /// own answer for an object that is not there.
    pub unreadable_objects: UnreadableObjectPolicy,
}

/// What to do when one indirect object cannot be loaded (`Pass 283.0`).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum UnreadableObjectPolicy {
    /// Load the document without it, and record a
    /// [`LoadAnomaly::ObjectUnreadable`].
    ///
    /// §7.3.10: an indirect reference to an undefined object *"shall not be
    /// considered an error by a conforming reader; it shall be treated as a
    /// reference to the null object."* An object whose bytes will not parse is
    /// undefined as far as every consumer is concerned, so this is the
    /// standard's own answer applied to the state the file is in — not a
    /// repair, and nothing invented.
    #[default]
    TreatAsUndefined,
    /// Refuse the document, as pdfcer did before `Pass 283.0`.
    Refuse,
}

impl Default for LoadOptions {
    /// NOT the derived default. `DuplicateKeyPolicy`'s own `Default` is
    /// `Refuse`, which is right for a parser and wrong for a loader: deriving
    /// here would make `LoadOptions::default()` refuse the very files this
    /// Pass exists to open, and the two types would silently disagree about
    /// what "default" means.
    fn default() -> Self {
        Self::new()
    }
}

impl LoadOptions {
    /// The defaults: open the file, decide the contradictions, report them.
    #[must_use]
    pub fn new() -> Self {
        Self {
            duplicate_keys: crate::parser::DuplicateKeyPolicy::KeepLast,
            stream_lengths: StreamLengthPolicy::RecoverFromEndstream,
            terminators: TerminatorPolicy::RecoverAtNextHeader,
            unreadable_objects: UnreadableObjectPolicy::TreatAsUndefined,
        }
    }

    /// Refuse every malformation instead of deciding it — the pre-`Pass 283.0`
    /// behaviour, kept reachable.
    ///
    /// For a caller whose job is to say whether a file is well-formed rather
    /// than to open it: a conformance checker, a fuzz harness, a gate.
    #[must_use]
    pub const fn strict() -> Self {
        Self {
            duplicate_keys: crate::parser::DuplicateKeyPolicy::Refuse,
            stream_lengths: StreamLengthPolicy::Strict,
            terminators: TerminatorPolicy::Strict,
            unreadable_objects: UnreadableObjectPolicy::Refuse,
        }
    }

    /// Take the OTHER value for every duplicated key — the operator's
    /// intervention, applied by re-loading the same bytes.
    #[must_use]
    pub const fn with_duplicate_keys(mut self, policy: crate::parser::DuplicateKeyPolicy) -> Self {
        self.duplicate_keys = policy;
        self
    }
}

/// One thing the file said that contradicted itself, and what pdfcer decided
/// about it (`Pass 283.0`).
///
/// # The operator ruling this exists to satisfy
///
/// > *"We should be making pdfcer so that it opens pdfs that have errors, and
/// > have a way that it manages those errors such that they aren't fatal, and
/// > if the user can intervene in a decision that should always be an option
/// > along with them not having to intervene."*
///
/// Three obligations in one sentence, and this type carries all three:
///
/// 1. **Not fatal** — the document loads.
/// 2. **Intervention is possible** — the record names the object, the key, the
///    value kept and the value discarded, which is everything a shell needs to
///    offer the operator the other choice and re-load with it
///    ([`crate::parser::DuplicateKeyPolicy`]).
/// 3. **Intervention is not required** — pdfcer already picked, the default is
///    documented, and a caller that never reads this list gets a working
///    document.
///
/// It is a *disclosure*, not a prompt: project rule 4 as narrowed by decision
/// 059 — the inferred value is live document state, and what pdfcer guessed is
/// reported off to the side rather than gating the open.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum LoadAnomaly {
    /// One dictionary named the same key twice (§7.3.7) and pdfcer kept one of
    /// the values.
    ///
    /// Both values are carried, not just the winner. A count would say *that*
    /// pdfcer chose; a shell offering the operator the choice needs to show
    /// **what it chose between**, and a report that cannot answer "what was the
    /// other one?" makes the intervention theoretical.
    DuplicateDictKey {
        /// The object whose dictionary contradicted itself. `None` when the
        /// dictionary is the trailer, which is not an indirect object.
        object: Option<ObjId>,
        /// The repeated key, e.g. `PageMode`.
        key: Vec<u8>,
        /// The value pdfcer KEPT — the last occurrence under the default
        /// policy.
        kept: Object,
        /// The value pdfcer DISCARDED. A caller offering the choice presents
        /// this as the alternative; a caller re-loading under
        /// [`crate::parser::DuplicateKeyPolicy::KeepFirst`] gets it instead.
        discarded: Object,
    },
    /// A stream's `/Length` was absent, non-integer, unresolvable or simply
    /// wrong, and pdfcer re-derived the data extent by scanning to
    /// `endstream` (§7.3.8.1).
    ///
    /// `/Length` is REQUIRED by §7.3.8.2 Table 5, so this is a `shall`
    /// violation — and one every reader recovers from, because the keyword
    /// that ends the data is right there in the file. Refusing costs the whole
    /// document to preserve a number the file itself contradicts.
    ///
    /// There is no operator choice to offer here, and that is not an
    /// oversight: the alternative to the scanned extent is **no object at
    /// all**. The record exists so the operator learns the file is damaged,
    /// not so a decision can be re-taken.
    StreamLengthRecovered {
        /// The object whose stream extent was re-derived.
        object: ObjId,
    },
    /// An indirect object's `endobj` keyword was missing and pdfcer accepted
    /// the definition anyway, ending it at the next object header (§7.3.10).
    ///
    /// Same shape as [`Self::StreamLengthRecovered`]: a required keyword the
    /// file omits, an unambiguous end, and no second reading to choose
    /// between.
    MissingEndobjRecovered {
        /// The object accepted without its terminator.
        object: ObjId,
    },
    /// One object could not be loaded at all, and the document was loaded
    /// **without it**.
    ///
    /// # Why this is continuing rather than guessing
    ///
    /// §7.3.10 already defines what a reference to an object that is not
    /// there means: *"An indirect reference to an undefined object shall not
    /// be considered an error by a conforming reader; it shall be treated as
    /// a reference to the null object."* An object whose bytes will not parse
    /// **is** an undefined object as far as every consumer is concerned — so
    /// omitting it is not a liberty pdfcer takes, it is the behaviour the
    /// standard prescribes for the state the file is in.
    ///
    /// That is the whole difference between this and a repair: nothing is
    /// invented, and the resulting document is one the standard describes.
    ///
    /// # What it replaces
    ///
    /// `DocError::BadObject`, `ObjectIdMismatch`, `ObjectStreamMissing`,
    /// `ObjectStream` and `ObjectStreamIdMismatch` — five ways one bad object
    /// used to cost the whole document. They survive as errors under
    /// [`LoadOptions::strict`].
    ///
    /// There is no alternative to offer here either. The choice is between
    /// this object and no document, and `reason` is carried so the operator
    /// can see WHICH object and WHY rather than being told a count.
    ObjectUnreadable {
        /// The object that could not be loaded.
        object: ObjId,
        /// Why, in the loader's own words — the error that would have been
        /// returned.
        reason: String,
    },
}

impl LoadAnomaly {
    /// The object this anomaly is about, when it has one.
    #[must_use]
    pub const fn object(&self) -> Option<ObjId> {
        match self {
            Self::DuplicateDictKey { object, .. } => *object,
            Self::StreamLengthRecovered { object }
            | Self::MissingEndobjRecovered { object }
            | Self::ObjectUnreadable { object, .. } => Some(*object),
        }
    }

    /// A short stable token for machine-readable output.
    #[must_use]
    pub const fn kind(&self) -> &'static str {
        match self {
            Self::DuplicateDictKey { .. } => "duplicate_dict_key",
            Self::StreamLengthRecovered { .. } => "stream_length_recovered",
            Self::MissingEndobjRecovered { .. } => "missing_endobj_recovered",
            Self::ObjectUnreadable { .. } => "object_unreadable",
        }
    }
}

/// How much repair a single object's parse needed.
///
/// Every field counts a place where the file contradicted itself or
/// omitted something §7.3.10 requires, and pdfcer chose to continue rather
/// than refuse. **All of them are zero under the strict policies**, so a
/// non-zero total is proof the file was damaged — which is why these are
/// carried out to the recovery report and disclosed (R20,
/// fuzzy-never-sneaky) instead of being absorbed silently.
#[derive(Debug, Clone, Default, PartialEq)]
pub(crate) struct ParseRepairs {
    /// Dictionary keys that appeared twice and were resolved to the LAST
    /// value rather than refusing the object
    /// ([`crate::parser::DuplicateKeyPolicy::KeepLast`], `Pass 283.0`).
    ///
    /// Unlike its two siblings this one is **non-zero on the clean path**,
    /// because the clean loader opts into the tolerant policy — the whole
    /// point of the Pass was that a file every other reader opens must not
    /// cost pdfcer the whole document. It is still a repair and still
    /// disclosed.
    pub duplicate_keys: Vec<crate::parser::DuplicateKeyRecord>,
    /// Stream extents re-derived from `endstream` because `/Length` was
    /// unusable ([`StreamLengthPolicy::RecoverFromEndstream`]).
    pub stream_lengths: usize,
    /// Definitions accepted with no `endobj` keyword
    /// ([`TerminatorPolicy::RecoverAtNextHeader`]).
    pub missing_endobj: usize,
}

/// Parse a catalog `/Version` name (`1.7`, `2.0`) into a version pair.
fn parse_version_name(name: &[u8]) -> Option<PdfVersion> {
    let text = std::str::from_utf8(name).ok()?;
    let (major, minor) = text.split_once('.')?;
    Some(PdfVersion {
        major: major.parse().ok()?,
        minor: minor.parse().ok()?,
    })
}

/// Member `num` at `index` of a decoded object stream, or the anomaly
/// reason and the strict-policy error.
fn member_at(
    objstm: &ObjectStream,
    container: ObjId,
    num: u32,
    index: u32,
) -> Result<Object, (String, DocError)> {
    let idx = usize::try_from(index).unwrap_or(usize::MAX);
    let (found, value) = objstm.object_at(idx).map_err(|source| {
        (
            format!("index {index} of object stream {container} could not be read: {source}"),
            DocError::ObjectStream { container, source },
        )
    })?;
    if found != num {
        return Err((
            format!(
                "object stream {container} stores object {found} at index {index}, where the cross-reference table promised {num}"
            ),
            DocError::ObjectStreamIdMismatch {
                container,
                index,
                expected: num,
                found,
            },
        ));
    }
    Ok(value)
}

/// Decode the object stream `container` for member `num`, or return the
/// anomaly reason and the strict-policy error. §7.5.7.
fn decode_container(
    buf: &[u8],
    objects: &HashMap<ObjId, IndirectObject>,
    container: ObjId,
    num: u32,
) -> Result<ObjectStream, (String, DocError)> {
    let Some(io) = objects.get(&container) else {
        return Err((
            format!("its object stream {container} is not in the file"),
            DocError::ObjectStreamMissing { container, num },
        ));
    };
    let Object::Stream(stream) = &io.value else {
        return Err((
            format!("object {container} is named as its container but is not a stream"),
            DocError::ObjectStream {
                container,
                source: ObjStmError::NotAStream,
            },
        ));
    };
    let Some(raw) = stream.data_span.slice(buf) else {
        return Err((
            format!("its object stream {container} declares data outside the file"),
            DocError::ObjectStream {
                container,
                source: ObjStmError::DataOutOfRange,
            },
        ));
    };
    #[cfg(test)]
    tests::OBJSTM_DECODES.with(|n| n.set(n.get() + 1));
    ObjectStream::parse(&stream.dict, raw).map_err(|source| {
        (
            format!("its object stream {container} could not be decoded: {source}"),
            DocError::ObjectStream { container, source },
        )
    })
}

#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    clippy::indexing_slicing
)]
mod tests {
    use super::*;

    thread_local! {
        /// Object-stream decodes attempted on this thread (X039 counter).
        pub(super) static OBJSTM_DECODES: std::cell::Cell<usize> =
            const { std::cell::Cell::new(0) };
    }

    /// Build a small, offset-consistent classic PDF from parts: each
    /// entry in `objects` is (object number, body text); generation 0.
    /// Returns the complete file bytes.
    fn build_pdf(objects: &[(u32, &str)], trailer_extra: &str) -> Vec<u8> {
        let mut buf = b"%PDF-1.4\n".to_vec();
        let mut offsets: Vec<(u32, usize)> = Vec::new();
        for (num, body) in objects {
            offsets.push((*num, buf.len()));
            buf.extend_from_slice(format!("{num} 0 obj\n{body}\nendobj\n").as_bytes());
        }
        let xref_at = buf.len();
        let max_num = objects.iter().map(|(n, _)| *n).max().unwrap_or(0);
        buf.extend_from_slice(format!("xref\n0 {}\n", max_num + 1).as_bytes());
        buf.extend_from_slice(b"0000000000 65535 f\r\n");
        for num in 1..=max_num {
            match offsets.iter().find(|(n, _)| *n == num) {
                Some((_, off)) => {
                    buf.extend_from_slice(format!("{off:010} 00000 n\r\n").as_bytes());
                }
                None => buf.extend_from_slice(b"0000000000 65535 f\r\n"),
            }
        }
        buf.extend_from_slice(
            format!(
                "trailer\n<< /Size {} /Root 1 0 R {trailer_extra}>>\nstartxref\n{xref_at}\n%%EOF\n",
                max_num + 1
            )
            .as_bytes(),
        );
        buf
    }

    fn minimal_doc() -> Vec<u8> {
        build_pdf(
            &[
                (1, "<< /Type /Catalog /Pages 2 0 R >>"),
                (2, "<< /Type /Pages /Kids [] /Count 0 >>"),
            ],
            "",
        )
    }

    #[test]
    fn loads_minimal_document() {
        let doc = Document::from_bytes(minimal_doc()).unwrap();
        assert_eq!(doc.object_count(), 2);
        assert_eq!(doc.version().to_string(), "1.4");
        let cat = doc.catalog().unwrap();
        assert_eq!(
            cat.get(b"Type").unwrap().as_name().unwrap().as_bytes(),
            b"Catalog"
        );
    }

    #[test]
    fn resolve_follows_references_and_nulls_dangling() {
        let doc = Document::from_bytes(minimal_doc()).unwrap();
        let cat = doc.catalog().unwrap();
        // /Pages resolves through the reference to the Pages dict.
        let pages = doc.resolve(cat.get(b"Pages").unwrap());
        assert_eq!(
            pages.as_dict().unwrap().get(b"Count").unwrap().as_int(),
            Some(0)
        );
        // §7.3.10: dangling → null, not an error.
        let dangling = Object::Reference(ObjId::new(17, 0));
        assert_eq!(*doc.resolve(&dangling), Object::Null);
        // Stale generation → null too.
        let stale = Object::Reference(ObjId::new(2, 9));
        assert_eq!(*doc.resolve(&stale), Object::Null);
    }

    #[test]
    fn reference_cycle_resolves_to_null() {
        // `3 0 obj 3 0 R endobj` — legal syntax, must not loop.
        let doc = Document::from_bytes(build_pdf(
            &[
                (1, "<< /Type /Catalog /Pages 2 0 R >>"),
                (2, "<< /Type /Pages /Kids [] /Count 0 >>"),
                (3, "3 0 R"),
            ],
            "",
        ))
        .unwrap();
        let cyc = Object::Reference(ObjId::new(3, 0));
        assert_eq!(*doc.resolve(&cyc), Object::Null);
    }

    #[test]
    fn provenance_spans_recover_source_bytes() {
        // The whole point of the retained buffer: every object's span
        // slices back to its exact definition bytes.
        let doc = Document::from_bytes(minimal_doc()).unwrap();
        let io = doc.get(ObjId::new(1, 0)).unwrap();
        let raw = io.file_span().unwrap().slice(doc.bytes()).unwrap();
        assert!(raw.starts_with(b"1 0 obj"));
        assert!(raw.ends_with(b"endobj"));
    }

    #[test]
    fn catalog_version_upgrades_header() {
        // §7.5.5: effective version = max(header, catalog /Version).
        let doc = Document::from_bytes(build_pdf(
            &[
                (1, "<< /Type /Catalog /Pages 2 0 R /Version /1.7 >>"),
                (2, "<< /Type /Pages /Kids [] /Count 0 >>"),
            ],
            "",
        ))
        .unwrap();
        assert_eq!(doc.version().to_string(), "1.7");
    }

    #[test]
    fn catalog_version_cannot_downgrade_header() {
        let mut bytes = build_pdf(
            &[
                (1, "<< /Type /Catalog /Pages 2 0 R /Version /1.2 >>"),
                (2, "<< /Type /Pages /Kids [] /Count 0 >>"),
            ],
            "",
        );
        // Bump the header to 1.6; catalog says 1.2; max wins.
        let pos = bytes.windows(3).position(|w| w == b"1.4").unwrap();
        bytes[pos..pos + 3].copy_from_slice(b"1.6");
        let doc = Document::from_bytes(bytes).unwrap();
        assert_eq!(doc.version().to_string(), "1.6");
    }

    /// AMENDED BY `Pass 283.0`, and the old assertion is kept as the second
    /// half rather than deleted.
    ///
    /// This test was right for its time: it asserted that a cross-reference
    /// entry pointing at the wrong object refuses the whole document, *"rather
    /// than guessing which is right"*. pdfcer still does not guess — what
    /// changed is that not-guessing no longer means not-opening. The object
    /// the table promised is treated as **undefined** (§7.3.10), which is the
    /// standard's own answer for an object that is not there, and the operator
    /// is told which one was lost.
    ///
    /// The strict refusal survives by name under [`LoadOptions::strict`], and
    /// the second half of this test is the old one unchanged.
    #[test]
    fn an_object_id_mismatch_is_recorded_by_default_and_refused_under_strict() {
        // Corrupt the xref so object 2's entry points at object 1's offset.
        let bytes = minimal_doc();
        let text = String::from_utf8(bytes.clone()).unwrap();
        let obj1_off = text.find("1 0 obj").unwrap();
        let obj2_off = text.find("2 0 obj").unwrap();
        let entry = format!("{obj2_off:010} 00000 n");
        let entry_pos = text.find(&entry).unwrap();
        let mut corrupted = bytes;
        corrupted[entry_pos..entry_pos + 10].copy_from_slice(format!("{obj1_off:010}").as_bytes());

        // Default: the document opens, object 2 is absent, and the loss is
        // named.
        let doc = Document::from_bytes(corrupted.clone())
            .expect("a table/body disagreement about ONE object is not an unreadable file");
        assert!(doc.get(ObjId::new(2, 0)).is_none());
        assert!(
            doc.load_anomalies().iter().any(|a| matches!(
                a,
                LoadAnomaly::ObjectUnreadable { object, .. } if *object == ObjId::new(2, 0)
            )),
            "{:?}",
            doc.load_anomalies()
        );

        // Strict: the original assertion, unchanged.
        let err =
            Document::from_bytes_with_options(corrupted, None, LoadOptions::strict()).unwrap_err();
        assert!(matches!(err, DocError::ObjectIdMismatch { .. }));
    }

    #[test]
    fn missing_root_is_no_catalog() {
        let mut buf = b"%PDF-1.4\n".to_vec();
        let xref_at = buf.len();
        buf.extend_from_slice(b"xref\n0 1\n0000000000 65535 f\r\n");
        buf.extend_from_slice(
            format!("trailer\n<< /Size 1 >>\nstartxref\n{xref_at}\n%%EOF\n").as_bytes(),
        );
        let doc = Document::from_bytes(buf).unwrap();
        assert!(matches!(doc.catalog(), Err(DocError::NoCatalog)));
    }

    #[test]
    fn stream_with_indirect_length_loads_end_to_end() {
        // §7.3.10 EXAMPLE 3 through the full Document path.
        let doc = Document::from_bytes(build_pdf(
            &[
                (1, "<< /Type /Catalog /Pages 2 0 R >>"),
                (2, "<< /Type /Pages /Kids [] /Count 0 >>"),
                (3, "<< /Length 4 0 R >>\nstream\nhello wo\nendstream"),
                (4, "8"),
            ],
            "",
        ))
        .unwrap();
        let io = doc.get(ObjId::new(3, 0)).unwrap();
        let Object::Stream(s) = &io.value else {
            panic!("not a stream");
        };
        assert_eq!(s.data_span.slice(doc.bytes()).unwrap(), b"hello wo");
    }

    /// A file whose only object stream (object 3, an unknown filter) holds
    /// objects 4..=13, all listed in an uncompressed cross-reference stream.
    fn bad_objstm_with_ten_members() -> Vec<u8> {
        let mut buf = b"%PDF-1.5
"
        .to_vec();
        let bodies = [
            (1, "<< /Type /Catalog /Pages 2 0 R >>".to_string()),
            (2, "<< /Type /Pages /Kids [] /Count 0 >>".to_string()),
            (
                3,
                "<< /Type /ObjStm /N 10 /First 0 /Filter /NoSuchFilter /Length 4 >>
stream
xxxx
endstream"
                    .to_string(),
            ),
        ];
        let mut offsets = Vec::new();
        for (num, body) in &bodies {
            offsets.push(buf.len());
            buf.extend_from_slice(
                format!(
                    "{num} 0 obj
{body}
endobj
"
                )
                .as_bytes(),
            );
        }
        let xref_at = buf.len();
        // /W [1 4 2]: type, field 2, field 3.
        let mut rows: Vec<u8> = Vec::new();
        let mut row = |t: u8, f2: u32, f3: u16| {
            rows.push(t);
            rows.extend_from_slice(&f2.to_be_bytes());
            rows.extend_from_slice(&f3.to_be_bytes());
        };
        row(0, 0, 0xFFFF);
        for off in &offsets {
            row(1, u32::try_from(*off).unwrap(), 0);
        }
        for i in 0..10u16 {
            row(2, 3, i);
        }
        row(1, u32::try_from(xref_at).unwrap(), 0);
        buf.extend_from_slice(
            format!(
                "14 0 obj
<< /Type /XRef /Size 15 /W [1 4 2] /Root 1 0 R /Length {} >>
stream
",
                rows.len()
            )
            .as_bytes(),
        );
        buf.extend_from_slice(&rows);
        buf.extend_from_slice(
            format!(
                "
endstream
endobj
startxref
{xref_at}
%%EOF
"
            )
            .as_bytes(),
        );
        buf
    }

    #[test]
    fn a_failed_object_stream_is_decoded_once_per_load() {
        OBJSTM_DECODES.with(|n| n.set(0));
        let doc = Document::from_bytes(bad_objstm_with_ten_members())
            .expect("one bad object stream is not an unreadable file");
        assert_eq!(OBJSTM_DECODES.with(std::cell::Cell::get), 1);

        let reasons: Vec<(u32, &str)> = doc
            .load_anomalies()
            .iter()
            .filter_map(|a| match a {
                LoadAnomaly::ObjectUnreadable { object, reason } => {
                    Some((object.num, reason.as_str()))
                }
                _ => None,
            })
            .collect();
        assert_eq!(
            reasons.iter().map(|r| r.0).collect::<Vec<_>>(),
            (4..=13).collect::<Vec<_>>(),
            "{reasons:?}"
        );
        assert!(reasons[0].1.contains("could not be decoded"), "{reasons:?}");
        assert!(reasons.iter().all(|r| r.1 == reasons[0].1), "{reasons:?}");

        // Strict: the first failure is still the error.
        let err = Document::from_bytes_with_options(
            bad_objstm_with_ten_members(),
            None,
            LoadOptions::strict(),
        )
        .unwrap_err();
        assert!(matches!(err, DocError::ObjectStream { .. }), "{err:?}");
    }
}