exprim 0.4.1

A concurrent, memory-bounded PDF reader and renderer: parse, extract text, and rasterize pages on an immutable document snapshot
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
//! The immutable document snapshot — the heart of the concurrency design.
//!
//! Invariants (enforced, not aspirational — see skeleton-blueprint.md §4.3):
//!
//! 1. `DocumentSnapshot` has **no** `&mut self` methods after `open()`.
//! 2. All mutable scratch (recursion tracking, budgets, local caches) lives
//!    in a worker-owned [`ParseContext`], passed `&mut` into resolution.
//! 3. Interior mutability exists only inside [`ObjectRepository`] with
//!    once-publication semantics: a slot goes from empty to an immutable
//!    `Ok`/`Err` exactly once, and both outcomes are shared.
//!
//! Resolution strategy is abstracted behind `ObjectRepository` so Phase 1
//! ships worker-local caches (plan "Design A") and Phase 3 can move to
//! shared `OnceLock` slots ("Design B") without touching callers.

use std::collections::HashMap;
use std::sync::Arc;

use crate::object::{Dictionary, NameTable, ObjectError, ObjectId, PdfObject, PdfStream};
use crate::security::{
    Cipher, EncryptDict, EncryptionScheme, Permissions, SecurityContext, SecurityError,
    StandardHandler,
};
use crate::source::PdfSource;
use crate::structure::{DocumentStructure, RecoveryEvent, StructureError};

mod links;
mod ocg;
mod outline;
mod pages;
mod resolve;
mod samples;

pub use links::{DocumentLink, DocumentLinkTarget, DocumentLinks};
pub use ocg::OcgConfig;
pub use outline::{
    DestinationFit, DocumentDestination, DocumentOutline, DocumentOutlineItem, OutlineIssue,
};
use resolve::Resolver;
pub(crate) use samples::ImageSampleSession;

/// Open-time limits. Threaded from day one, enforced as parsers land
/// (blueprint §4.4). All limits are per-document unless stated.
#[derive(Debug, Clone)]
pub struct DocumentLimits {
    pub syntax: crate::syntax::SyntaxLimits,
    /// Maximum indirect objects a single resolution chain may visit.
    pub max_reference_chain: usize,
    /// Maximum total decompressed bytes a single `ParseContext` may produce.
    pub max_decoded_bytes_per_context: usize,
    /// Maximum page count accepted (0 = unlimited).
    pub max_pages: u32,
    /// Maximum revisions (incremental updates) followed.
    pub max_revisions: usize,
    /// Maximum object number admitted to the xref map.
    pub max_objects: u32,
    /// Retain every entry each xref section declared on
    /// [`XrefSection::entries`](crate::structure::XrefSection::entries).
    /// Off by default: the render path never needs per-section entries, and
    /// retaining them costs one small record per xref entry. Audit tooling
    /// opts in to diff sections into per-object change histories.
    pub preserve_section_entries: bool,
}

impl Default for DocumentLimits {
    fn default() -> Self {
        Self {
            syntax: crate::syntax::SyntaxLimits::default(),
            max_reference_chain: 128,
            max_decoded_bytes_per_context: 1 << 30, // 1 GiB
            max_pages: 0,
            max_revisions: 4096,
            max_objects: 8 * 1024 * 1024,
            preserve_section_entries: false,
        }
    }
}

/// Errors surfaced by document open and object/page resolution.
#[derive(Debug, Clone, thiserror::Error)]
pub enum DocumentError {
    #[error(transparent)]
    Structure(#[from] StructureError),
    #[error(transparent)]
    Object(#[from] ObjectError),
    #[error(transparent)]
    Security(#[from] crate::security::SecurityError),
    #[error("page index {0} out of range")]
    PageOutOfRange(u32),
    #[error("limit exceeded: {0}")]
    LimitExceeded(&'static str),
    /// Retained for later-phase stubs (Phase 1 no longer produces it).
    #[error("not implemented yet: {0} (see skeleton-blueprint.md §7)")]
    NotImplemented(&'static str),
}

/// Stable identifier of a page within one snapshot.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PageIndex(pub u32);

/// Annotation flag bit: hidden in every rendering mode (ISO 32000-1 Table
/// 165 bit 2).
pub const ANNOT_FLAG_HIDDEN: u32 = 1 << 1;
/// Annotation flag bit: printed but not displayed on screen (bit 6).
pub const ANNOT_FLAG_NOVIEW: u32 = 1 << 5;

/// `/C` annotation color, retained in its authored device color space.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum AnnotationColor {
    Gray(f32),
    Rgb([f32; 3]),
    Cmyk([f32; 4]),
}

/// One annotation of a page, resolved at open to exactly what static
/// appearance-stream rendering needs (ISO 32000-1 §12.5), plus the neutral
/// provenance facts read-only tooling needs (`/NM`, dates, authorship).
/// `/Popup` annotations are dropped at parse time — PDFium's `CPDF_AnnotList`
/// never even lists them (cpdf_annotlist.cpp).
#[derive(Debug, Clone)]
pub struct PageAnnotation {
    /// `/Subtype`, interned in the snapshot's name table. `None` when absent
    /// or unreadable (the annotation is kept: an `/AP` can still paint).
    pub subtype: Option<crate::object::NameId>,
    /// The `/Annots` entry this annotation was resolved from, when it is (as
    /// the spec requires) an indirect reference; `None` for a direct inline
    /// annotation dictionary. Rendering never needs it, but provenance
    /// tooling keys revisions and identity off it.
    pub source: Option<ObjectId>,
    /// `/Rect` in default user space, corner-normalized. Degenerate rects are
    /// preserved as-is; rendering skips them.
    pub rect: [f64; 4],
    /// `/F` annotation flags (0 when absent, per spec).
    pub flags: u32,
    /// The raw `/AP` value (usually a `Reference` to the appearance
    /// dictionary), unresolved so the snapshot stays cheap to build.
    pub appearance: Option<PdfObject>,
    /// The `/AS` appearance-state name, selecting among `/N` sub-states.
    pub appearance_state: Option<crate::object::NameId>,
    /// A link annotation's direct `/Dest`, retained unresolved for semantic
    /// extraction. Non-link annotations commonly omit it.
    pub destination: Option<PdfObject>,
    /// A link annotation's `/A` action dictionary, retained unresolved for
    /// semantic extraction. Rendering does not interpret actions.
    pub action: Option<PdfObject>,
    /// `/QuadPoints`, grouped in the PDF text-markup Z order
    /// (top-left, top-right, bottom-left, bottom-right).
    pub quad_points: std::sync::Arc<[[f64; 8]]>,
    /// `/C` text-markup color. Missing or malformed colors remain `None`, so
    /// the renderer can apply the subtype's conventional default.
    pub color: Option<AnnotationColor>,
    /// `/CA` constant opacity, clamped to `[0,1]` (default 1).
    pub opacity: f32,
    /// `/Contents` text, decoded lossy. The annotation's human-readable body.
    pub contents: Option<String>,
    /// `/NM` annotation name: the writer-assigned identifier meant to be
    /// unique within the document.
    pub name: Option<String>,
    /// `/M` last-modification date, verbatim and unparsed. A writer's claim,
    /// not an observation.
    pub modified: Option<String>,
    /// `/CreationDate`, verbatim and unparsed. Like [`Self::modified`], a
    /// claim by whatever wrote the annotation.
    pub creation_date: Option<String>,
    /// `/T` text label — for markup annotations, the author. Verbatim.
    pub author: Option<String>,
    /// `/Subj` subject: a short description of the annotation. Verbatim.
    pub subject: Option<String>,
    /// `/IT` intent name (e.g. `FreeTextTypewriter`), as authored.
    pub intent: Option<String>,
}

impl PageAnnotation {
    /// Whether screen rendering (PDFium `bPrinting=false` display pass) must
    /// skip this annotation: `Hidden` or `NoView` set.
    pub fn hidden_for_display(&self) -> bool {
        self.flags & (ANNOT_FLAG_HIDDEN | ANNOT_FLAG_NOVIEW) != 0
    }
}

/// A resolved page-tree leaf with inherited attributes flattened.
/// Built during open so page lookup never walks the tree again (and never
/// re-resolves `/Parent` chains concurrently).
#[derive(Debug, Clone)]
pub struct PageRef {
    pub index: PageIndex,
    /// The page's own object id when it is (as the spec requires) an indirect
    /// reference; `None` for a *direct* inline page dict in `/Kids` (malformed
    /// but rendered by PDFium) and for synthesized blank placeholders. Rendering
    /// never needs it — it reads `contents`/`resources`/`annotations` — but the
    /// `exprim::doctor` doctor re-resolves the page dict through it and skips when it
    /// is absent.
    pub object: Option<ObjectId>,
    /// MediaBox after inheritance, in default user space units.
    pub media_box: [f64; 4],
    /// CropBox after inheritance, clamped to MediaBox; equals media_box if
    /// absent.
    pub crop_box: [f64; 4],
    /// BleedBox, clamped to MediaBox; equals crop_box if absent. Read from
    /// the page's own dictionary — unlike MediaBox/CropBox it does not
    /// inherit (ISO 32000-1 §14.11.2).
    pub bleed_box: [f64; 4],
    /// TrimBox — the finished page after trimming — clamped to MediaBox;
    /// equals crop_box if absent. Non-inheritable, like `bleed_box`.
    pub trim_box: [f64; 4],
    /// ArtBox — the author-declared meaningful content extent — clamped to
    /// MediaBox; equals crop_box if absent. Non-inheritable, like `bleed_box`.
    pub art_box: [f64; 4],
    /// Normalized rotation in {0, 90, 180, 270}.
    pub rotate: u16,
    /// The page's raw /Resources value (possibly inherited): usually a
    /// `Reference`, but direct dictionaries are common in the wild, so the
    /// unresolved value is preserved rather than an `ObjectId`.
    pub resources: Option<PdfObject>,
    /// The raw /Contents value: a `Reference` to a single stream, or an
    /// array of references (or a direct array — same rationale as
    /// `resources`).
    pub contents: Option<PdfObject>,
    /// The page's `/Annots`, resolved at open (minus `/Popup`, PDFium
    /// parity). Shared so cloning a `PageRef` per compile job stays cheap.
    pub annotations: Arc<[PageAnnotation]>,
}

/// Immutable index of all pages, built once at open.
#[derive(Debug, Default)]
pub struct PageTreeIndex {
    pages: Box<[PageRef]>,
}

impl PageTreeIndex {
    pub fn from_pages(pages: Box<[PageRef]>) -> Self {
        Self { pages }
    }
    pub fn page_count(&self) -> u32 {
        self.pages.len() as u32
    }
    pub fn page(&self, index: PageIndex) -> Option<&PageRef> {
        self.pages.get(index.0 as usize)
    }
    pub fn iter(&self) -> impl Iterator<Item = &PageRef> {
        self.pages.iter()
    }

    pub fn index_for_object(&self, object: ObjectId) -> Option<PageIndex> {
        self.pages
            .iter()
            .find(|page| page.object == Some(object))
            .map(|page| page.index)
    }
}

/// Worker-owned mutable state for parsing/resolution. One per worker (or per
/// page-compilation job); never shared, never global.
#[derive(Debug)]
pub struct ParseContext {
    /// Objects currently being resolved on this chain — cycle detection.
    recursion: Vec<ObjectId>,
    /// Budget accounting against `DocumentLimits`.
    pub decoded_bytes_used: usize,
    pub objects_visited: usize,
    #[cfg(feature = "profiling")]
    pub object_cache_hits: usize,
    #[cfg(feature = "profiling")]
    pub object_cache_misses: usize,
    #[cfg(feature = "profiling")]
    pub object_stream_cache_hits: usize,
    #[cfg(feature = "profiling")]
    pub object_stream_inflates: usize,
    /// Worker-local parsed-object cache (Design A). Keyed by full id so a
    /// stale-generation lookup never aliases a live object.
    cache: HashMap<ObjectId, Arc<PdfObject>>,
    /// Worker-local decompressed object-stream containers: N members cost
    /// one inflate per worker, not N.
    objstm: HashMap<u32, Arc<ObjStmCached>>,
    /// Bytes accounted to `cache` and `objstm` (see [`Self::cached_bytes`]).
    cache_bytes: usize,
    /// Entries of `cache` whose decrypted body exceeds
    /// [`LARGE_OWNED_STREAM_BYTES`]: kept for the job that resolved them,
    /// dropped at the next [`Self::begin_job`].
    large_entries: Vec<ObjectId>,
    /// Above this many accounted bytes, the next [`Self::begin_job`] empties
    /// both caches (see [`DEFAULT_PARSE_CACHE_BUDGET`]).
    cache_budget: usize,
    /// Repairs performed during resolution *by this worker* (wrong-offset
    /// fixes, stream-length repairs discovered lazily). Open-time repairs
    /// live on the snapshot's recovery log instead; post-open the snapshot
    /// is immutable, so lazy repairs surface here — observable, per-worker.
    pub recovery: Vec<RecoveryEvent>,
    /// Optional cooperative cancellation shared with the caller that owns this
    /// worker. Kept out of document-global state so independent page jobs can
    /// be cancelled without affecting one another.
    cancellation: Option<Arc<std::sync::atomic::AtomicBool>>,
}

/// Default byte budget of a [`ParseContext`]'s worker-local caches.
///
/// Persistent workers (the read seam keeps one context per thread for a
/// document's lifetime) would otherwise retain every object they resolved.
/// For an encrypted document that includes every decrypted stream body (an
/// `Owned` copy, images included), so a long document grew a worker's
/// context without bound (B8). The budget is generous: it only ever takes
/// effect between page jobs, and a miss after it does only re-parses or
/// re-decrypts, so output cannot change.
pub const DEFAULT_PARSE_CACHE_BUDGET: usize = 256 << 20;

/// A decrypted (`Owned`) stream body larger than this is cached for the job
/// that resolved it only, never across jobs.
///
/// On an encrypted document every resolved stream carries its decrypted
/// body, so under the budget alone each persistent worker could keep up to
/// [`DEFAULT_PARSE_CACHE_BUDGET`] of image, content and embedded-file bodies
/// alive between jobs — several GiB across a scheduler's workers — although
/// such bodies are rarely resolved again by a later job of the *same*
/// worker (decoded image samples are shared at the document level, fonts are
/// cached resolved). Within a job they stay cached: a page that draws one
/// image many times resolves its stream once per draw. Re-reading and
/// re-decrypting a body at this size costs well under a millisecond; the
/// small bodies that stay — form and pattern streams, functions, ICC
/// profiles, CMaps — are what successive pages share.
pub const LARGE_OWNED_STREAM_BYTES: usize = 64 << 10;

/// Fixed per-entry charge for a cached object: map slot, `Arc` header and a
/// small object's own size. Only a rough floor; stream bodies and object
/// stream containers are charged their real byte length on top.
const CACHE_ENTRY_BYTES: usize = 64;

/// Whether `value` is a stream holding a decrypted body over
/// [`LARGE_OWNED_STREAM_BYTES`].
fn is_large_owned_stream(value: &PdfObject) -> bool {
    matches!(value, PdfObject::Stream(stream)
        if matches!(&stream.data, crate::object::StreamData::Owned(bytes)
            if bytes.len() > LARGE_OWNED_STREAM_BYTES))
}

/// Bytes charged for caching `value`.
fn cached_object_bytes(value: &PdfObject) -> usize {
    match value {
        PdfObject::Stream(stream) => match &stream.data {
            crate::object::StreamData::Owned(bytes) => CACHE_ENTRY_BYTES + bytes.len(),
            crate::object::StreamData::InSource { .. } => CACHE_ENTRY_BYTES,
        },
        _ => CACHE_ENTRY_BYTES,
    }
}

/// Bytes charged for caching an object-stream container.
fn cached_objstm_bytes(entry: &ObjStmCached) -> usize {
    CACHE_ENTRY_BYTES + entry.data.len()
}

/// A decompressed object-stream container plus its parsed pair table.
#[derive(Debug)]
pub(crate) struct ObjStmCached {
    pub(crate) data: Vec<u8>,
    pub(crate) layout: crate::structure::objstm::ObjectStreamLayout,
}

impl ParseContext {
    pub fn new() -> Self {
        Self {
            recursion: Vec::with_capacity(16),
            decoded_bytes_used: 0,
            objects_visited: 0,
            #[cfg(feature = "profiling")]
            object_cache_hits: 0,
            #[cfg(feature = "profiling")]
            object_cache_misses: 0,
            #[cfg(feature = "profiling")]
            object_stream_cache_hits: 0,
            #[cfg(feature = "profiling")]
            object_stream_inflates: 0,
            cache: HashMap::new(),
            objstm: HashMap::new(),
            cache_bytes: 0,
            large_entries: Vec::new(),
            cache_budget: DEFAULT_PARSE_CACHE_BUDGET,
            recovery: Vec::new(),
            cancellation: None,
        }
    }

    /// A context whose worker-local caches are emptied at the next job
    /// boundary once they hold more than `bytes` (see
    /// [`DEFAULT_PARSE_CACHE_BUDGET`]).
    pub fn with_cache_budget(bytes: usize) -> Self {
        let mut context = Self::new();
        context.cache_budget = bytes;
        context
    }

    /// Bytes currently accounted to the worker-local object and object-stream
    /// caches: decrypted stream bodies and decompressed object-stream
    /// containers at their length, every other entry at a small fixed charge.
    pub fn cached_bytes(&self) -> usize {
        self.cache_bytes
    }

    /// Start a new page-compilation job while retaining worker-local caches.
    ///
    /// Persistent viewer workers reuse one context across pages so parsed
    /// objects and decompressed object streams stay hot. Budget counters,
    /// recursion state, profiling counters, and recovery events are
    /// job-scoped and must not leak into the next page.
    pub fn begin_job(&mut self) {
        self.recursion.clear();
        self.decoded_bytes_used = 0;
        self.objects_visited = 0;
        #[cfg(feature = "profiling")]
        {
            self.object_cache_hits = 0;
            self.object_cache_misses = 0;
            self.object_stream_cache_hits = 0;
            self.object_stream_inflates = 0;
        }
        self.recovery.clear();
        self.cancellation = None;
        // The cache budget is enforced here, between jobs, never inside
        // `resolve`: a job never thrashes, and nothing a caller of the
        // previous job still holds is invalidated (entries are `Arc`s).
        if self.cache_bytes > self.cache_budget {
            self.cache.clear();
            self.objstm.clear();
            self.cache_bytes = 0;
            self.large_entries.clear();
        }
        // Large decrypted bodies were for the job that just ended (see
        // `LARGE_OWNED_STREAM_BYTES`); a later job that needs one resolves it
        // again, reading the same bytes.
        for id in std::mem::take(&mut self.large_entries) {
            if self
                .cache
                .get(&id)
                .is_some_and(|v| is_large_owned_stream(v))
                && let Some(old) = self.cache.remove(&id)
            {
                self.cache_bytes = self.cache_bytes.saturating_sub(cached_object_bytes(&old));
            }
        }
    }

    pub fn set_cancellation_flag(
        &mut self,
        cancellation: Option<Arc<std::sync::atomic::AtomicBool>>,
    ) {
        self.cancellation = cancellation;
    }

    pub fn is_cancelled(&self) -> bool {
        self.cancellation
            .as_ref()
            .is_some_and(|cancelled| cancelled.load(std::sync::atomic::Ordering::Acquire))
    }

    fn cache_get(&self, id: ObjectId) -> Option<Arc<PdfObject>> {
        self.cache.get(&id).cloned()
    }

    fn cache_put(&mut self, id: ObjectId, value: Arc<PdfObject>) {
        if is_large_owned_stream(&value) {
            self.large_entries.push(id);
        }
        self.cache_bytes = self.cache_bytes.saturating_add(cached_object_bytes(&value));
        if let Some(old) = self.cache.insert(id, value) {
            self.cache_bytes = self.cache_bytes.saturating_sub(cached_object_bytes(&old));
        }
    }

    fn objstm_get(&self, container: u32) -> Option<Arc<ObjStmCached>> {
        self.objstm.get(&container).cloned()
    }

    fn objstm_put(&mut self, container: u32, entry: Arc<ObjStmCached>) {
        self.cache_bytes = self.cache_bytes.saturating_add(cached_objstm_bytes(&entry));
        if let Some(old) = self.objstm.insert(container, entry) {
            self.cache_bytes = self.cache_bytes.saturating_sub(cached_objstm_bytes(&old));
        }
    }

    /// RAII-free cycle guard: push before resolving `id`, pop after.
    pub fn enter(&mut self, id: ObjectId, limits: &DocumentLimits) -> Result<(), DocumentError> {
        if self.recursion.contains(&id) {
            return Err(ObjectError::ReferenceCycle(id).into());
        }
        if self.recursion.len() >= limits.max_reference_chain {
            return Err(DocumentError::LimitExceeded("max_reference_chain"));
        }
        self.recursion.push(id);
        Ok(())
    }

    pub fn exit(&mut self, id: ObjectId) {
        debug_assert_eq!(self.recursion.last(), Some(&id));
        self.recursion.pop();
    }

    /// Record a lazy, worker-local recovery — e.g. a page content stream that
    /// failed to decode and was skipped so the page still renders. Surfaced on
    /// this worker's `recovery` log, keeping the deviation observable rather
    /// than silent (blueprint §4.5).
    pub fn note_recovery(&mut self, message: String) {
        self.recovery.push(RecoveryEvent::Other(message));
    }
}

impl Default for ParseContext {
    fn default() -> Self {
        Self::new()
    }
}

/// Canonical object access. `&self` resolution against immutable structure;
/// all scratch goes through the caller's `ParseContext`.
///
/// The interior strategy (worker-local vs shared once-published) is an
/// implementation detail behind this type — see module docs.
#[derive(Debug)]
pub struct ObjectRepository {
    // Phase 1 (Design A): stateless here; caching in ParseContext.
    // Phase 3 (Design B): slots: Box<[OnceLock<Result<Arc<PdfObject>, Arc<ObjectError>>>]>.
}

impl ObjectRepository {
    pub fn new() -> Self {
        Self {}
    }

    /// Resolve an indirect object to its parsed value, following the xref,
    /// parsing on demand, and publishing/caching per the active strategy.
    ///
    /// Reference chains are followed (with the context's chain limit);
    /// references to free or undefined objects resolve to `Null` per
    /// ISO 32000-1 §7.3.10.
    pub fn resolve(
        &self,
        snapshot: &DocumentSnapshot,
        id: ObjectId,
        ctx: &mut ParseContext,
    ) -> Result<Arc<PdfObject>, DocumentError> {
        snapshot.resolver().resolve(id, ctx)
    }
}

impl Default for ObjectRepository {
    fn default() -> Self {
        Self::new()
    }
}

/// The immutable snapshot of an open document. `Send + Sync`; every field is
/// either immutable or internally once-published. Cloning is cheap (`Arc`s).
#[derive(Debug, Clone)]
pub struct DocumentSnapshot {
    inner: Arc<SnapshotInner>,
}

#[derive(Debug)]
struct SnapshotInner {
    source: Arc<dyn PdfSource>,
    structure: DocumentStructure,
    names: NameTable,
    pages: PageTreeIndex,
    objects: ObjectRepository,
    security: Option<SecurityContext>,
    limits: DocumentLimits,
    /// The `/OCProperties /D` default optional-content configuration
    /// (default: everything visible).
    ocg: OcgConfig,
    /// Document-scoped side caches owned by higher layers (see
    /// [`DocumentSnapshot::extension`]).
    extensions: ExtensionMap,
}

/// Type-erased, lazily created document-scoped slots. A higher layer (the
/// content compiler, a renderer) keys a cache by its own private type and gets
/// one instance per snapshot, shared by every worker and page of that
/// document, without this crate learning what the cache holds.
#[derive(Default)]
struct ExtensionMap {
    slots: std::sync::Mutex<HashMap<std::any::TypeId, Arc<dyn std::any::Any + Send + Sync>>>,
}

impl std::fmt::Debug for ExtensionMap {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let count = self
            .slots
            .lock()
            .map(|slots| slots.len())
            .unwrap_or_else(|poisoned| poisoned.into_inner().len());
        f.debug_struct("ExtensionMap")
            .field("slots", &count)
            .finish()
    }
}

impl DocumentSnapshot {
    /// Open a document: read all structural information, apply recovery,
    /// build the page index, and freeze. This is the only phase allowed to
    /// mutate document-level state.
    pub fn open(source: Arc<dyn PdfSource>, limits: DocumentLimits) -> Result<Self, DocumentError> {
        Self::open_with_password(source, limits, None)
    }

    /// [`DocumentSnapshot::open`] with an optional user/owner password for
    /// encrypted documents. The empty user password is always tried first
    /// (permissions-only encryption, the overwhelmingly common case);
    /// `password` is consulted only when that fails. A wrong password fails
    /// typed ([`crate::security::SecurityError::IncorrectPassword`]); an
    /// encrypted document opened with no password and a non-empty user
    /// password fails with `PasswordRequired`. Which password authenticated
    /// is exposed via `snapshot.security().and_then(|s| s.password_role())`.
    pub fn open_with_password(
        source: Arc<dyn PdfSource>,
        limits: DocumentLimits,
        password: Option<&str>,
    ) -> Result<Self, DocumentError> {
        let names = NameTable::new();
        let structure_limits = crate::structure::StructureLimits {
            syntax: limits.syntax.clone(),
            max_revisions: limits.max_revisions,
            max_objects: limits.max_objects,
            max_decoded_bytes: limits.max_decoded_bytes_per_context,
            preserve_section_entries: limits.preserve_section_entries,
        };
        // Establish the security context *before* building the page tree (page
        // strings/streams are encrypted and decrypt as they resolve; `/Encrypt`
        // itself is read through a handler-less resolver), then walk the tree
        // and parse OCG config. Factored so the whole thing can be re-run
        // against a rebuilt structure below.
        type Parts = (
            Option<SecurityContext>,
            PageTreeIndex,
            ocg::OcgConfig,
            pages::WalkStats,
        );
        let build_parts = |structure: &DocumentStructure,

                           ctx: &mut ParseContext|

         -> Result<Parts, DocumentError> {
            let security = {
                let plain = Resolver {
                    source: source.as_ref(),
                    structure,
                    names: &names,
                    limits: &limits,
                    security: None,
                };
                build_security(&plain, structure, &names, ctx, password)?
            };
            let resolver = Resolver {
                source: source.as_ref(),
                structure,
                names: &names,
                limits: &limits,
                security: security.as_ref(),
            };
            let (pages, stats) = pages::build_page_tree(&resolver, ctx)?;
            let ocg = ocg::parse_ocproperties(&resolver, ctx);
            Ok((security, pages, ocg, stats))
        };

        // One open attempt against a given structure: build security + page
        // tree with its own resolution context (whose repairs fold into the
        // snapshot's recovery log below; post-open, repairs go to each worker's
        // own context instead — the snapshot is frozen).
        let try_build = |structure: DocumentStructure|
         -> Result<(DocumentStructure, ParseContext, Parts), DocumentError> {
            let mut ctx = ParseContext::new();
            let parts = build_parts(&structure, &mut ctx)?;
            Ok((structure, ctx, parts))
        };
        let rebuild =
            || crate::structure::load_structure_rebuilt(source.as_ref(), &names, &structure_limits);

        // Load the xref chain and build. If *either* step fails structurally —
        // an unfindable `/Root` (leading garbage before `%PDF`, a truncated
        // trailer) or a dangling object the xref mislocated — fall back to a
        // forced full-file reconstruction (PDFium/mupdf `RebuildCrossRef`:
        // scan for every object and `/Type /Catalog`). Surface the original
        // error only when the rebuild path cannot open it either.
        let (
            mut structure,
            mut ctx,
            (mut security, mut pages, mut ocg, mut stats),
            rebuilt_already,
        ) = match crate::structure::load_structure(source.as_ref(), &names, &structure_limits) {
            Ok(s) => match try_build(s) {
                Ok((s, c, p)) => (s, c, p, false),
                Err(build_err) => match rebuild() {
                    Ok(r) => match try_build(r) {
                        Ok((s, c, p)) => (s, c, p, true),
                        Err(_) => return Err(build_err),
                    },
                    Err(_) => return Err(build_err),
                },
            },
            Err(load_err) => match rebuild() {
                Ok(r) => match try_build(r) {
                    Ok((s, c, p)) => (s, c, p, true),
                    Err(_) => return Err(load_err.into()),
                },
                Err(_) => return Err(load_err.into()),
            },
        };

        // A cleanly loaded chain can still contain stale offsets below a valid
        // catalog. Any page-tree subtree that was provably lost warrants one
        // full reconstruction, including a *partial* tree: otherwise pages
        // after a mid-tree hole remain shifted. Adopt only a strict structural
        // improvement, so genuinely truncated files keep their usable chain.
        if !rebuilt_already
            && stats.lost_subtrees > 0
            && let Ok(rebuilt) = rebuild()
        {
            let mut ctx2 = ParseContext::new();
            if let Ok((sec2, pages2, ocg2, stats2)) = build_parts(&rebuilt, &mut ctx2) {
                let (pages2, candidate_stats) = if stats2.real_pages == 0 {
                    let resolver = Resolver {
                        source: source.as_ref(),
                        structure: &rebuilt,
                        names: &names,
                        limits: &limits,
                        security: sec2.as_ref(),
                    };
                    let orphans = pages::recover_orphan_pages(&resolver, &mut ctx2);
                    if orphans.page_count() > 0 {
                        let orphan_count = orphans.page_count() as usize;
                        (
                            orphans,
                            pages::WalkStats {
                                real_pages: orphan_count,
                                lost_subtrees: 0,
                            },
                        )
                    } else {
                        (pages2, stats2)
                    }
                } else {
                    (pages2, stats2)
                };
                let improves = candidate_stats.real_pages > stats.real_pages
                    || (candidate_stats.real_pages == stats.real_pages
                        && candidate_stats.lost_subtrees < stats.lost_subtrees);
                if improves {
                    structure = rebuilt;
                    security = sec2;
                    pages = pages2;
                    ocg = ocg2;
                    ctx = ctx2;
                    stats = candidate_stats;
                }
            }
        }

        // If the initial fallback path already rebuilt the xref but its tree
        // still yielded zero real pages, there is no second structure to try.
        // Scan that rebuilt live-object view for explicit orphan page leaves.
        if rebuilt_already && stats.real_pages == 0 {
            let resolver = Resolver {
                source: source.as_ref(),
                structure: &structure,
                names: &names,
                limits: &limits,
                security: security.as_ref(),
            };
            let orphans = pages::recover_orphan_pages(&resolver, &mut ctx);
            if orphans.page_count() > 0 {
                pages = orphans;
            }
        }

        if !ctx.recovery.is_empty() {
            let mut all = structure.recovery.into_vec();
            all.append(&mut ctx.recovery);
            structure.recovery = all.into_boxed_slice();
        }

        let mut snapshot = Self::from_parts(source, structure, names, pages, security, limits);
        // `from_parts` is the shared (test-visible) constructor; the parsed
        // OCG config is attached before the snapshot is ever shared.
        if let Some(inner) = Arc::get_mut(&mut snapshot.inner) {
            inner.ocg = ocg;
        }
        Ok(snapshot)
    }

    /// Open a document and return a structured timing report. This API exists
    /// only in profiling builds so ordinary applications neither pay for an
    /// `Instant` nor acquire a profiling dependency.
    #[cfg(feature = "profiling")]
    pub fn open_profiled(
        source: Arc<dyn PdfSource>,
        limits: DocumentLimits,
    ) -> Result<(Self, crate::profiling::ProfileReport), DocumentError> {
        let start = std::time::Instant::now();
        let snapshot = Self::open(source, limits)?;
        let mut profile = crate::profiling::ProfileReport::new();
        profile.add_duration("document.open", start.elapsed());
        profile.increment("document.pages", snapshot.page_count() as u64);
        profile.increment(
            "document.recovery_events",
            snapshot.recovery_events().len() as u64,
        );
        Ok((snapshot, profile))
    }

    fn resolver(&self) -> Resolver<'_> {
        Resolver {
            source: self.inner.source.as_ref(),
            structure: &self.inner.structure,
            names: &self.inner.names,
            limits: &self.inner.limits,
            security: self.inner.security.as_ref(),
        }
    }

    /// Decode a stream's body through its `/Filter` chain, charging the
    /// worker context's decompression budget.
    pub fn decode_stream_data(
        &self,
        stream: &PdfStream,
        ctx: &mut ParseContext,
    ) -> Result<Vec<u8>, DocumentError> {
        self.resolver().decode_stream_data(stream, ctx)
    }

    /// Decode a stream's body up to (not through) an image-codec filter;
    /// see [`resolve::Resolver::decode_stream_data_to_codec`].
    pub fn decode_stream_data_to_codec(
        &self,
        stream: &PdfStream,
        ctx: &mut ParseContext,
    ) -> Result<(Vec<u8>, Option<String>), DocumentError> {
        self.resolver().decode_stream_data_to_codec(stream, ctx)
    }

    /// Test-only constructor for exercising downstream layers before the
    /// parser exists.
    pub fn from_parts(
        source: Arc<dyn PdfSource>,
        structure: DocumentStructure,
        names: NameTable,
        pages: PageTreeIndex,
        security: Option<SecurityContext>,
        limits: DocumentLimits,
    ) -> Self {
        Self {
            inner: Arc::new(SnapshotInner {
                source,
                structure,
                names,
                pages,
                objects: ObjectRepository::new(),
                security,
                limits,
                ocg: OcgConfig::default(),
                extensions: ExtensionMap::default(),
            }),
        }
    }

    /// The document-scoped slot for `T`, created with `T::default()` on first
    /// use and shared (by `Arc`) with every later caller on any thread for as
    /// long as this snapshot lives.
    ///
    /// This is how a layer above the document keeps per-document state that
    /// outlives one page compile — a resolved-font cache, say — when callers
    /// construct a fresh compiler and [`ParseContext`] per page (the scheduler's
    /// `make` closure does exactly that). The slot is keyed by `T`'s type, so
    /// a private newtype gives a crate a slot nothing else can reach; the
    /// snapshot stays immutable document structure and never interprets the
    /// contents.
    pub fn extension<T: Default + Send + Sync + 'static>(&self) -> Arc<T> {
        let mut slots = self
            .inner
            .extensions
            .slots
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        let slot = slots
            .entry(std::any::TypeId::of::<T>())
            .or_insert_with(|| Arc::new(T::default()));
        match Arc::clone(slot).downcast::<T>() {
            Ok(typed) => typed,
            // Unreachable: the slot was inserted under `TypeId::of::<T>()`.
            // Replace rather than panic so a page can never fail here.
            Err(_) => {
                let fresh: Arc<T> = Arc::new(T::default());
                *slot = Arc::clone(&fresh) as Arc<dyn std::any::Any + Send + Sync>;
                fresh
            }
        }
    }

    /// Whether the optional-content group with object id `id` is visible
    /// under the document's `/OCProperties /D` default configuration
    /// (default-visibility semantics: visible unless configured off).
    pub fn ocg_visible(&self, id: ObjectId) -> bool {
        self.inner.ocg.visible(id)
    }

    pub fn source(&self) -> &Arc<dyn PdfSource> {
        &self.inner.source
    }
    pub fn structure(&self) -> &DocumentStructure {
        &self.inner.structure
    }
    pub fn names(&self) -> &NameTable {
        &self.inner.names
    }
    pub fn page_count(&self) -> u32 {
        self.inner.pages.page_count()
    }
    pub fn page(&self, index: PageIndex) -> Result<&PageRef, DocumentError> {
        self.inner
            .pages
            .page(index)
            .ok_or(DocumentError::PageOutOfRange(index.0))
    }

    /// Parse and flatten the document's bookmark tree.
    ///
    /// The operation is recovery-driven: malformed nodes and unsupported
    /// actions are reported in `issues` while usable siblings remain
    /// available to the viewer.
    pub fn outline(&self, ctx: &mut ParseContext) -> DocumentOutline {
        outline::extract(self, ctx)
    }

    /// Extract all usable internal and URI link annotations in one document
    /// pass. Keeping this document-level avoids rebuilding the named-
    /// destination tree for every independently compiled page.
    pub fn links(&self, ctx: &mut ParseContext) -> DocumentLinks {
        links::extract(self, ctx)
    }
    pub fn objects(&self) -> &ObjectRepository {
        &self.inner.objects
    }
    pub fn security(&self) -> Option<&SecurityContext> {
        self.inner.security.as_ref()
    }
    pub fn limits(&self) -> &DocumentLimits {
        &self.inner.limits
    }
    /// Structural repairs applied during open — observable, never silent.
    pub fn recovery_events(&self) -> &[RecoveryEvent] {
        &self.inner.structure.recovery
    }
}

/// Build the document's [`SecurityContext`] from its `/Encrypt` dictionary.
///
/// Returns `Ok(None)` for an unencrypted document, `Ok(Some(_))` once the
/// standard handler is derived, and an `UnsupportedScheme` error for schemes
/// the handler declines (AES-256 / revision 6) — never a silent
/// "rendered blank". The `/Encrypt` dictionary is resolved through the given
/// `resolver`, which must have **no** security handler installed (the dict is
/// never itself encrypted).
fn build_security(
    resolver: &Resolver<'_>,
    structure: &DocumentStructure,
    names: &NameTable,
    ctx: &mut ParseContext,
    password: Option<&str>,
) -> Result<Option<SecurityContext>, DocumentError> {
    // The trailer carries `/Encrypt` as an indirect reference in the common
    // case; a direct dictionary is rare but legal.
    let encrypt_obj = match structure.trailer.encrypt {
        Some(id) => resolver.resolve(id, ctx)?,
        None => match structure.trailer.dict.get(names.known.encrypt) {
            Some(PdfObject::Dictionary(d)) => Arc::new(PdfObject::Dictionary(Arc::clone(d))),
            _ => return Ok(None),
        },
    };
    let Some(dict) = encrypt_obj.as_dict() else {
        return Ok(None);
    };

    let file_id = structure
        .trailer
        .file_id
        .as_ref()
        .map(|id| id[0].as_bytes().to_vec())
        .unwrap_or_default();
    let (enc, scheme) = parse_encrypt_dict(dict, file_id, names);

    // Revisions beyond what the standard handler implements: typed decline,
    // never a password prompt for a scheme we could not honor anyway.
    let v5 = enc.r == 5 || enc.r == 6 || enc.v == 5;
    if !v5 && (enc.r > 6 || enc.v > 5) {
        return Err(SecurityError::UnsupportedScheme(scheme).into());
    }

    // Empty user password first (permissions-only encryption — essentially
    // every encrypted PDF in the wild), then the caller-supplied password.
    let authenticated = StandardHandler::with_password(&enc, "")
        .or_else(|| password.and_then(|pw| StandardHandler::with_password(&enc, pw)));
    if let Some((handler, role)) = authenticated {
        // V5 `/Perms` integrity cross-check — report-only: the content key is
        // demonstrably right (validated against `/U`/`/O`), so a tampered or
        // non-conforming permissions block is surfaced as a recovery note,
        // never a refusal (PDFium's AES256_CheckPerms hard-fails here; that
        // strictness would blank otherwise-openable wild documents).
        if let Some(mismatch) = handler.verify_perms(&enc) {
            ctx.note_recovery(format!("encryption /Perms cross-check failed: {mismatch}"));
        }
        return Ok(Some(
            SecurityContext::standard(scheme, Permissions(enc.p as u32), handler)
                .with_password_role(role),
        ));
    }

    // Identity crypt filter: decryption is a no-op regardless of the derived
    // key, so a malformed `/U` must not block opening (legacy lenient path).
    if matches!(scheme, EncryptionScheme::None)
        && let Some(handler) = StandardHandler::open(&enc)
    {
        return Ok(Some(SecurityContext::standard(
            scheme,
            Permissions(enc.p as u32),
            handler,
        )));
    }

    Err(match password {
        Some(_) => SecurityError::IncorrectPassword.into(),
        None => SecurityError::PasswordRequired.into(),
    })
}

/// The crypt-filter method a `/V 4` document uses for its streams.
enum CryptFilterMethod {
    V2,
    AesV2,
    AesV3,
    Identity,
}

/// Parse the raw `/Encrypt` fields into a [`EncryptDict`] plus the scheme it
/// names (used for the declined-scheme error). Public so read-only tooling
/// (`exprim::doctor`) can run password checks against the same parsed form the
/// open path uses.
pub fn parse_encrypt_dict(
    dict: &Dictionary,
    file_id: Vec<u8>,
    names: &NameTable,
) -> (EncryptDict, EncryptionScheme) {
    let get_int = |key: &[u8]| {
        names
            .lookup(key)
            .and_then(|id| dict.get(id))
            .and_then(PdfObject::as_int)
    };
    let get_bytes = |key: &[u8]| -> Vec<u8> {
        names
            .lookup(key)
            .and_then(|id| dict.get(id))
            .and_then(|o| match o {
                PdfObject::String(s) => Some(s.as_bytes().to_vec()),
                _ => None,
            })
            .unwrap_or_default()
    };
    let get_bool = |key: &[u8]| {
        names
            .lookup(key)
            .and_then(|id| dict.get(id))
            .and_then(|o| match o {
                PdfObject::Boolean(b) => Some(*b),
                _ => None,
            })
    };

    let v = get_int(b"V").unwrap_or(0);
    let r = get_int(b"R").unwrap_or(0);
    let length_bits = get_int(b"Length").unwrap_or(40);
    let rc4_key_bytes = (length_bits.clamp(40, 128) / 8) as usize;

    let (cipher, key_bytes, scheme) = match v {
        1 => (Cipher::Rc4, 5, EncryptionScheme::Rc4 { key_bits: 40 }),
        2 | 3 => (
            Cipher::Rc4,
            rc4_key_bytes,
            EncryptionScheme::Rc4 {
                key_bits: (rc4_key_bytes * 8) as u16,
            },
        ),
        4 => match crypt_filter_method(dict, names) {
            CryptFilterMethod::AesV2 => (Cipher::Aes128, 16, EncryptionScheme::Aes128),
            CryptFilterMethod::V2 => (
                Cipher::Rc4,
                rc4_key_bytes,
                EncryptionScheme::Rc4 {
                    key_bits: (rc4_key_bytes * 8) as u16,
                },
            ),
            CryptFilterMethod::Identity => (Cipher::None, rc4_key_bytes, EncryptionScheme::None),
            // AESV3 under /V 4 is malformed; report as AES-256 so the handler
            // declines rather than mis-deriving a key.
            CryptFilterMethod::AesV3 => (Cipher::Aes128, 32, EncryptionScheme::Aes256),
        },
        // /V 5 (AES-256) and any unknown version: the handler declines.
        _ => (Cipher::Aes128, 32, EncryptionScheme::Aes256),
    };

    let enc = EncryptDict {
        v,
        r,
        o: get_bytes(b"O"),
        u: get_bytes(b"U"),
        // `/UE` (V5 only) — the user key-encryption entry the handler AES-256-
        // decrypts to recover the file key. Empty (and unused) for RC4/AES-128.
        ue: get_bytes(b"UE"),
        // `/OE` — owner-side counterpart of `/UE`, consumed by the
        // password APIs (`StandardHandler::with_password`). [Stream C
        // integration hookup: keep this line when merging.]
        oe: get_bytes(b"OE"),
        p: get_int(b"P").unwrap_or(0) as i32,
        // `/Perms` (V5) — permissions-integrity block, cross-checked
        // report-only after authentication.
        perms: get_bytes(b"Perms"),
        key_bytes,
        encrypt_metadata: get_bool(b"EncryptMetadata").unwrap_or(true),
        cipher,
        file_id,
    };
    (enc, scheme)
}

/// Resolve the `/CFM` of the stream crypt filter (`/StmF` → `/CF`) for `/V 4`.
fn crypt_filter_method(dict: &Dictionary, names: &NameTable) -> CryptFilterMethod {
    let name_is = |id, s: &[u8]| &*names.resolve(id) == s;

    let Some(stmf) = names
        .lookup(b"StmF")
        .and_then(|id| dict.get(id))
        .and_then(PdfObject::as_name)
    else {
        return CryptFilterMethod::Identity;
    };
    // `/Identity` is the distinguished "not encrypted" filter name.
    if name_is(stmf, b"Identity") {
        return CryptFilterMethod::Identity;
    }
    let Some(cf) = names
        .lookup(b"CF")
        .and_then(|id| dict.get(id))
        .and_then(PdfObject::as_dict)
    else {
        return CryptFilterMethod::Identity;
    };
    let Some(entry) = cf.get(stmf).and_then(PdfObject::as_dict) else {
        return CryptFilterMethod::Identity;
    };
    let Some(cfm) = names
        .lookup(b"CFM")
        .and_then(|id| entry.get(id))
        .and_then(PdfObject::as_name)
    else {
        return CryptFilterMethod::Identity;
    };
    if name_is(cfm, b"AESV2") {
        CryptFilterMethod::AesV2
    } else if name_is(cfm, b"AESV3") {
        CryptFilterMethod::AesV3
    } else if name_is(cfm, b"V2") {
        CryptFilterMethod::V2
    } else {
        CryptFilterMethod::Identity
    }
}

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

    // The load-bearing assertion of the whole architecture: the snapshot is
    // freely shareable across worker threads.
    const fn assert_send_sync<T: Send + Sync>() {}
    const _: () = assert_send_sync::<DocumentSnapshot>();

    #[test]
    fn parse_context_detects_cycles_and_depth() {
        let limits = DocumentLimits {
            max_reference_chain: 2,
            ..Default::default()
        };
        let mut ctx = ParseContext::new();
        let a = ObjectId::new(1, 0);
        let b = ObjectId::new(2, 0);
        ctx.enter(a, &limits).unwrap();
        assert!(matches!(
            ctx.enter(a, &limits),
            Err(DocumentError::Object(ObjectError::ReferenceCycle(_)))
        ));
        ctx.enter(b, &limits).unwrap();
        assert!(matches!(
            ctx.enter(ObjectId::new(3, 0), &limits),
            Err(DocumentError::LimitExceeded(_))
        ));
        ctx.exit(b);
        ctx.exit(a);
    }

    #[test]
    fn begin_job_resets_job_state_but_keeps_worker_caches() {
        let mut ctx = ParseContext::new();
        let id = ObjectId::new(7, 0);
        ctx.recursion.push(id);
        ctx.decoded_bytes_used = 123;
        ctx.objects_visited = 9;
        ctx.recovery
            .push(RecoveryEvent::Other("previous page".into()));
        ctx.cache.insert(id, Arc::new(PdfObject::Null));

        ctx.begin_job();

        assert!(ctx.recursion.is_empty());
        assert_eq!(ctx.decoded_bytes_used, 0);
        assert_eq!(ctx.objects_visited, 0);
        assert!(ctx.recovery.is_empty());
        assert!(ctx.cache.contains_key(&id));
    }

    fn owned_stream(len: usize) -> Arc<PdfObject> {
        Arc::new(PdfObject::Stream(Arc::new(crate::object::PdfStream {
            dict: crate::object::Dictionary::default(),
            data: crate::object::StreamData::Owned(Arc::from(vec![7u8; len])),
        })))
    }

    /// B8: owned stream bodies are charged their length; a context over its
    /// budget empties its caches at the next job boundary, one under it
    /// keeps them.
    #[test]
    fn begin_job_enforces_the_cache_budget() {
        let mut ctx = ParseContext::with_cache_budget(10_000);
        ctx.cache_put(ObjectId::new(1, 0), owned_stream(4_000));
        ctx.cache_put(ObjectId::new(2, 0), Arc::new(PdfObject::Null));
        assert_eq!(ctx.cached_bytes(), 4_000 + 2 * CACHE_ENTRY_BYTES);
        // Replacing an entry releases its old charge.
        ctx.cache_put(ObjectId::new(1, 0), owned_stream(5_000));
        assert_eq!(ctx.cached_bytes(), 5_000 + 2 * CACHE_ENTRY_BYTES);
        ctx.begin_job();
        assert_eq!(ctx.cache.len(), 2, "under budget: kept");

        ctx.objstm_put(
            9,
            Arc::new(ObjStmCached {
                data: vec![0; 6_000],
                layout: crate::structure::objstm::ObjectStreamLayout {
                    members: Vec::new(),
                },
            }),
        );
        assert!(ctx.cached_bytes() > 10_000);
        // Still usable within the job that went over.
        assert!(ctx.cache_get(ObjectId::new(1, 0)).is_some());
        ctx.begin_job();
        assert_eq!(ctx.cached_bytes(), 0);
        assert!(ctx.cache.is_empty() && ctx.objstm.is_empty());
    }

    /// Large decrypted bodies serve the job that resolved them and are gone
    /// after the next job boundary; small ones stay across jobs.
    #[test]
    fn large_decrypted_bodies_do_not_outlive_their_job() {
        let mut ctx = ParseContext::new();
        let large = ObjectId::new(1, 0);
        let small = ObjectId::new(2, 0);
        ctx.cache_put(large, owned_stream(LARGE_OWNED_STREAM_BYTES + 1));
        ctx.cache_put(small, owned_stream(LARGE_OWNED_STREAM_BYTES));
        assert!(ctx.cache_get(large).is_some(), "cached within its job");
        let before = ctx.cached_bytes();
        ctx.begin_job();
        assert!(ctx.cache_get(large).is_none());
        assert!(ctx.cache_get(small).is_some());
        assert_eq!(
            ctx.cached_bytes(),
            before - (CACHE_ENTRY_BYTES + LARGE_OWNED_STREAM_BYTES + 1)
        );
        // Replaced by a small value within a job: that one is kept.
        ctx.cache_put(large, owned_stream(LARGE_OWNED_STREAM_BYTES + 1));
        ctx.cache_put(large, Arc::new(PdfObject::Null));
        ctx.begin_job();
        assert!(ctx.cache_get(large).is_some());
        assert_eq!(
            ctx.cached_bytes(),
            2 * CACHE_ENTRY_BYTES + LARGE_OWNED_STREAM_BYTES
        );
    }

    #[test]
    fn begin_job_clears_a_previous_jobs_cancellation_flag() {
        let cancelled = Arc::new(std::sync::atomic::AtomicBool::new(true));
        let mut context = ParseContext::new();
        context.set_cancellation_flag(Some(cancelled));
        assert!(context.is_cancelled());

        context.begin_job();
        assert!(!context.is_cancelled());
    }
}