flpdf 0.4.0

A pure-Rust PDF toolkit modeled on qpdf — read, rewrite, linearize, and inspect PDFs.
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
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
//! `LinearizationPlan` — pure data model for PDF linearization layout.
//!
//! A `LinearizationPlan` partitions all objects in a document into the four
//! body parts defined by ISO 32000-1 Annex F, and carries the raw inputs needed
//! to build the Page-offset hint table and the Shared-object hint table.
//!
//! The plan is intentionally a dumb data struct: no I/O, no serialization.
//! Higher-level subtasks (e.g. the hint-table byte-builder and the linearized
//! writer) consume this struct and fill in the placeholders.
//!
//! # Part layout (Annex F summary)
//!
//! | Part | Contents |
//! |------|----------|
//! | 1    | Linearization parameter dictionary + first-page xref/trailer |
//! | 2    | First-page objects (page dict, resources, content streams) |
//! | 3    | Non-first-page shared objects (catalog, font programs, etc.) |
//! | 4    | Remaining (non-first-page) objects |
//!
//! # Object closure algorithm (subtask 2.2)
//!
//! `from_pdf` now computes the transitive closure of objects reachable from the
//! first page (`/Pages /Kids[0]`) and partitions them:
//!
//! * **Part 2** — objects reachable from page 1 and *not* shared with other pages.
//! * **Part 3** — objects reachable from page 1 *and also* reachable from page 2..N
//!   (shared objects).
//! * **Part 4** — everything else (objects only reachable from pages 2..N, or from
//!   the catalog root but not from any page).
//!
//! The four parts are always disjoint (invariant preserved by construction).

use crate::linearization::renumber::RenumberMap;
use crate::object::MAX_INLINE_DEPTH;
use crate::writer::object_streams::{
    collect_indirect_objstm_length_refs, eligibility_context, is_eligible_for_objstm,
    ObjectStreamMode, PlannerConfig,
};
use crate::{Object, ObjectRef, Pdf, Result};
use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::io::{Read, Seek};

// ---------------------------------------------------------------------------
// Supporting types
// ---------------------------------------------------------------------------

/// Per-page entry for the **Page-offset hint table** (Annex F.3).
///
/// Byte-length and exact object indices are filled in as placeholders (zeros)
/// at construction time; a downstream writer pass must back-patch them once the
/// real file positions are known.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PageHintEntry {
    /// Indirect reference to the page's dictionary object.
    pub page_ref: ObjectRef,
    /// Index (0-based) of the first object belonging to this page in the
    /// object order that the linearized file will use.
    pub first_object_index: u32,
    /// Number of objects directly belonging to this page.
    pub object_count: u32,
    /// Byte length of all objects belonging to this page (placeholder: 0).
    pub byte_length: u64,
}

impl PageHintEntry {
    /// Construct a placeholder entry for `page_ref`.
    pub fn placeholder(page_ref: ObjectRef) -> Self {
        Self {
            page_ref,
            first_object_index: 0,
            object_count: 0,
            byte_length: 0,
        }
    }
}

/// Per-object entry for the **Shared-object hint table** (Annex F.4).
///
/// Annex F.4 keys shared objects by object index (within the linearized body
/// ordering), not by `ObjectRef`.  The `referencing_pages` field lists the
/// 0-based page indices (not `ObjectRef`s) that reference this shared object.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SharedObjectHintEntry {
    /// The shared object.
    pub object_ref: ObjectRef,
    /// 0-based indices of the pages that reference this object.
    pub referencing_pages: Vec<u32>,
}

impl SharedObjectHintEntry {
    /// Construct a shared-object entry that has no page references yet.
    pub fn new(object_ref: ObjectRef) -> Self {
        Self {
            object_ref,
            referencing_pages: Vec::new(),
        }
    }
}

// ---------------------------------------------------------------------------
// Closure helpers
// ---------------------------------------------------------------------------

/// Collect all `ObjectRef` values directly referenced by `obj`.
///
/// Walks arrays, dictionaries, and stream dictionaries (but NOT stream data
/// bytes). A `Reference(r)` is pushed to `out` as-is.  The caller is
/// responsible for cycle detection and transitive expansion.
fn collect_direct_refs(obj: &Object, depth: usize, out: &mut Vec<ObjectRef>) -> Result<()> {
    if depth > MAX_INLINE_DEPTH {
        return Err(crate::Error::Unsupported(format!(
            "linearization plan: inline object nesting exceeds maximum of {MAX_INLINE_DEPTH}"
        )));
    }
    match obj {
        Object::Reference(r) => out.push(*r),
        Object::Array(arr) => {
            for elem in arr {
                collect_direct_refs(elem, depth + 1, out)?;
            }
        }
        Object::Dictionary(dict) => {
            for (_k, v) in dict.iter() {
                collect_direct_refs(v, depth + 1, out)?;
            }
        }
        Object::Stream(s) => {
            // Only walk the stream dictionary; do not scan raw data bytes.
            // Skip /Length: it only ever points to an integer holder, and qpdf
            // directizes every emitted stream's /Length before computing the
            // linearization object-user map, so a /Length holder is never
            // page-reachable. Following it would pull a holder kept alive by a
            // separate edge (e.g. a catalog reference) into the first-page
            // closure, misrouting its ObjStm container to the first half. Other
            // indirect stream-dict values (/ColorSpace, /SMask, /Mask,
            // /Alternates, ...) remain genuinely reachable and are followed.
            for (k, v) in s.dict.iter() {
                if k == b"Length" {
                    continue;
                }
                collect_direct_refs(v, depth + 1, out)?;
            }
        }
        // Scalar types cannot contain refs.
        _ => {}
    }
    Ok(())
}

/// Like [`collect_direct_refs`] but tracks whether each ref was discovered
/// inside an array element (`true`) or a dictionary value (`false`).
///
/// Array-element null-resolving refs survive as `null` in the writer output;
/// dictionary-value null-resolving refs cause the key to be dropped entirely.
/// `compute_closure` uses this to restrict resurrectable-null admission to refs
/// actually reached via a surviving array edge rather than a dropped dict edge.
fn collect_direct_refs_with_context(
    obj: &Object,
    depth: usize,
    in_array: bool,
    out: &mut Vec<(ObjectRef, bool)>,
) -> Result<()> {
    if depth > MAX_INLINE_DEPTH {
        return Err(crate::Error::Unsupported(format!(
            "linearization plan: inline object nesting exceeds maximum of {MAX_INLINE_DEPTH}"
        )));
    }
    match obj {
        Object::Reference(r) => out.push((*r, in_array)),
        Object::Array(arr) => {
            for elem in arr {
                collect_direct_refs_with_context(elem, depth + 1, true, out)?;
            }
        }
        Object::Dictionary(dict) => {
            for (_k, v) in dict.iter() {
                collect_direct_refs_with_context(v, depth + 1, false, out)?;
            }
        }
        Object::Stream(s) => {
            for (k, v) in s.dict.iter() {
                if k == b"Length" {
                    continue;
                }
                collect_direct_refs_with_context(v, depth + 1, false, out)?;
            }
        }
        _ => {}
    }
    Ok(())
}

/// Returns whether a resolved object is a page-tree node we must not descend
/// into during a subtree expansion (a `/Type /Page` leaf or `/Type /Pages`
/// interior node). Used to stop a `/Resources` subtree walk from pulling in
/// sibling pages if a resource value cross-links back into the page tree.
fn is_page_tree_node(obj: &Object) -> bool {
    matches!(obj, Object::Dictionary(d)
        if matches!(d.get("Type"), Some(Object::Name(n))
            if n.as_slice() == b"Pages" || n.as_slice() == b"Page"))
}

/// Compute the transitive closure of objects reachable from `root`.
///
/// Returns the list in discovery order (root first). The walk is breadth-first
/// over the object graph in general, with one exception for page leaves: a
/// page's `/Resources` subtree is expanded depth-first and placed ahead of its
/// `/Contents`. This reproduces qpdf's physical ordering for the first-page
/// section, where the Resources dictionary (and the fonts/XObjects it points
/// at) precede the content stream.
///
/// ### `/Parent` / `/Kids` handling
///
/// When the walker enters a node whose `/Type` is `Pages` (an intermediate
/// page-tree node), it follows all dictionary entries **except `/Kids`**.
/// This means page-tree interior nodes (and their inherited `/Resources`) are
/// included in the closure, but the *sibling pages* hanging off `/Kids` are
/// not pulled in. The `/Parent` chain is therefore followed at most until the
/// root Pages node without capturing other pages.
fn compute_closure<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    root: ObjectRef,
    live: &BTreeSet<ObjectRef>,
    resurrectable: &BTreeSet<ObjectRef>,
) -> crate::Result<Vec<ObjectRef>> {
    let mut visited: BTreeSet<ObjectRef> = BTreeSet::new();
    let mut order: Vec<ObjectRef> = Vec::new();
    // Each entry carries (ref, via_array): whether the ref was enqueued via an
    // array element (true) or a dictionary value (false).  Used at dequeue time
    // to admit resurrectable null refs only when the reaching edge is a
    // surviving array slot — matching qpdf's object-user classification, which
    // excludes dict-value edges that the writer drops entirely.
    let mut queue: VecDeque<(ObjectRef, bool)> = VecDeque::from([(root, false)]);
    // Resurrectable refs that were not admissible at dequeue time (seen_as_array
    // did not yet contain them — the live object holding the array edge had not
    // been expanded yet).  After the full BFS completes, seen_as_array is
    // exhaustive; we then admit each deferred ref that appears there.  This
    // handles the "revorder" case: resurrectable ref number < live descendant
    // number, so sort-at-enqueue puts the resurrectable ref in the queue before
    // the live object that would reveal the array edge.
    let mut deferred_resurrect: BTreeSet<ObjectRef> = BTreeSet::new();
    // Tracks every ref that has been enqueued (or pushed to the Resources DFS
    // stack) via an array-element edge within this closure walk.  A resurrectable
    // ref that appears in *both* a dict-value slot (dropped by the writer) and an
    // array slot (survives as null) within the same page's closure must still be
    // admitted: the dict-value tuple (r, false) may be dequeued before the
    // array-edge tuple (r, true), but `seen_as_array` lets the dequeue check
    // consult all edges discovered so far, not just the one in the current tuple.
    let mut seen_as_array: BTreeSet<ObjectRef> = BTreeSet::new();

    // Object 0 (free-list head / null singleton, ISO 32000-1 §7.3.10) and all
    // null-resolving references have no ordinary body here. The holding dict key
    // is dropped, while an array keeps the indirect null identity only through
    // the `resurrectable` path below. Keeping other nulls in `visited` but out of
    // `order` avoids a stray numbered body and an inflated first-page count.
    //
    // Exception: null-resolving refs reached via a surviving array edge in this
    // page's object graph are resurrectable (see `resurrectable_null_refs`). qpdf
    // classifies them as first-page users when reached from a first-page object,
    // giving them HIGH object numbers inside Part 2. A null ref reached only via
    // a dict value is dropped (not resurrectable), so it stays excluded.
    let admits_body_object = |r: ObjectRef| -> bool { r.number != 0 && live.contains(&r) };

    while let Some((current, via_array)) = queue.pop_front() {
        if !visited.insert(current) {
            continue;
        }
        if resurrectable.contains(&current) {
            // Null-resolving ref: the writer preserves array-element slots as
            // null but drops dict-value slots (the key is omitted entirely). Only
            // admit to the closure when an array edge exists — a ref reached
            // solely via dict-value edges has no surviving body object in the
            // first-page section, matching qpdf's object-user map which does not
            // count dropped dict-value edges as page uses.
            // `via_array` covers the common case; `seen_as_array` covers the case
            // where the same ref appears in both a dict-value slot and an array
            // slot in the same closure (the dict-value tuple may be dequeued first,
            // but the array edge was already recorded at enqueue time).
            // `deferred_resurrect` handles the "revorder" case: resurrectable ref
            // number < live descendant number, so the resurrectable ref is dequeued
            // before seen_as_array is populated.  Deferred refs are re-checked
            // after the full BFS completes.
            if via_array || seen_as_array.contains(&current) {
                order.push(current);
            } else {
                deferred_resurrect.insert(current);
            }
            continue;
        }
        if !admits_body_object(current) {
            continue;
        }
        order.push(current);

        let obj = pdf.resolve(current)?;

        // Determine whether this is a Pages node (intermediate page-tree node)
        // or a Page leaf node.
        let is_pages_node = matches!(&obj, Object::Dictionary(d)
            if matches!(d.get("Type"), Some(Object::Name(n)) if n.as_slice() == b"Pages"));
        let is_page_leaf = matches!(&obj, Object::Dictionary(d)
            if matches!(d.get("Type"), Some(Object::Name(n)) if n.as_slice() == b"Page"));

        if is_pages_node || is_page_leaf {
            if let Some(dict) = obj.as_dict() {
                // For a page leaf, expand the `/Resources` subtree depth-first
                // and append it to `order` *before* the generic key loop runs.
                // flpdf's `Dictionary` is a `BTreeMap`, so a plain key walk
                // would visit `/Contents` (alphabetically first) before
                // `/Resources`; qpdf instead numbers the Resources dictionary
                // and the fonts/XObjects it references ahead of the content
                // stream. Reproducing that order here is what makes the
                // first-page object numbering match qpdf (e.g. one-page:
                // Page, Resources, Font, Content). The depth-first walk is
                // required because the content stream sits at depth 1 while a
                // font hangs at depth 2 under `/Resources`; a breadth-first
                // pass would otherwise emit the content stream first.
                if is_page_leaf {
                    if let Some(resources) = dict.get("Resources") {
                        let mut seeds: Vec<(ObjectRef, bool)> = Vec::new();
                        collect_direct_refs_with_context(resources, 0, false, &mut seeds)?;
                        for &(r, va) in &seeds {
                            if va {
                                seen_as_array.insert(r); // cov:ignore: fires only when /Resources is an inline dict/array with array-element refs; normal PDFs use an indirect /Resources ref, so seeds come from collect_direct_refs_with_context on a Reference (va=false)
                            }
                        }
                        // DFS via an explicit stack (no recursion) so deeply
                        // nested resource graphs cannot overflow the stack.
                        // The visited set bounds cycles; `is_page_tree_node`
                        // stops the walk if a resource value cross-links back
                        // into the page tree, so we never pull in sibling pages.
                        let mut stack: Vec<(ObjectRef, bool)> = seeds.into_iter().rev().collect();
                        while let Some((r, via_array)) = stack.pop() {
                            if !visited.insert(r) {
                                continue;
                            }
                            if resurrectable.contains(&r) {
                                // Same edge-type rule as the main BFS: admit the
                                // null body object only when an array edge exists.
                                // Defer if seen_as_array not yet populated (revorder
                                // case); the post-BFS pass will re-check.
                                if via_array || seen_as_array.contains(&r) {
                                    order.push(r);
                                } else {
                                    // cov:ignore-start: fires when a resurrectable ref is reachable via dict-value in the Resources subtree before the array edge in the same subtree is discovered; requires two resource objects cross-referencing the same xref-absent object via different edge types, which is extremely contrived
                                    deferred_resurrect.insert(r);
                                } // cov:ignore-end
                                continue;
                            }
                            if !admits_body_object(r) {
                                // Null-resolving resource ref (object 0 / missing
                                // xref): no body object, same as the main loop.
                                continue;
                            }
                            let child = pdf.resolve(r)?;
                            // Stop at a page-tree boundary BEFORE adding `r` to
                            // the closure: a resource that malformedly cross-links
                            // to a sibling `/Page` or the `/Pages` node must be
                            // kept in `visited` (so it is never revisited) but
                            // excluded from the first-page closure entirely — per
                            // the page-closure boundary rule, we neither descend
                            // into it nor pull the boundary node itself into
                            // Part 2/3.
                            if is_page_tree_node(&child) {
                                continue;
                            }
                            order.push(r);
                            let mut child_refs: Vec<(ObjectRef, bool)> = Vec::new();
                            collect_direct_refs_with_context(&child, 0, false, &mut child_refs)?;
                            // Push in reverse so the first reference is popped
                            // first, preserving left-to-right discovery order.
                            for cr in child_refs.into_iter().rev() {
                                if cr.1 {
                                    seen_as_array.insert(cr.0);
                                }
                                if !visited.contains(&cr.0) {
                                    stack.push(cr);
                                }
                            }
                        }
                    }
                } // cov:ignore: llvm-cov attributes 0 to this `if is_page_leaf` closing brace; the block body (the /Resources DFS) runs and is covered above.
                let mut refs_raw: Vec<(ObjectRef, bool)> = Vec::new();
                for (k, v) in dict.iter() {
                    if k == b"Kids" {
                        // Pages → sibling pages — never follow.
                        continue;
                    }
                    if k == b"Thumb" {
                        // qpdf gives thumbnail objects the separate ou_thumb
                        // user (not a page user), so page closures never
                        // include /Thumb targets. Skipping here ensures
                        // thumbnail objects land in part4_rest (part 9)
                        // rather than the per-page private/shared sections.
                        continue;
                    }
                    if k == b"Parent" {
                        // Walk the /Parent chain up to the root Pages node so
                        // inherited /Resources, /MediaBox, /Rotate, etc. from
                        // any ancestor (not just the immediate parent) end up
                        // in this page's closure. Without iterating to the
                        // root, a `/Page → /Pages → /Pages` tree with the
                        // inherited resource attached to the grandparent
                        // would leave that resource unreachable from any
                        // page's closure and land it in `part4_rest`,
                        // misclassifying it relative to qpdf's part7/8/9
                        // partition.
                        //
                        // The ancestor /Pages dicts themselves are NOT added
                        // to this page's closure — adding them would inflate
                        // the page's object_count beyond what qpdf computes
                        // from the linearized layout. We follow each
                        // ancestor's non-/Kids, non-/Parent entries and let
                        // the queue traverse into ref targets normally.
                        let mut to_visit: Vec<ObjectRef> = Vec::new();
                        let mut seen_parents: BTreeSet<ObjectRef> = BTreeSet::new();
                        collect_direct_refs(v, 0, &mut to_visit)?;

                        while let Some(parent_ref) = to_visit.pop() {
                            if !seen_parents.insert(parent_ref) {
                                continue;
                            }
                            // Resolve the parent. Genuine resolve failures
                            // (I/O or parse errors) propagate via `?` instead
                            // of silently degrading the closure — mirroring
                            // the main BFS loop's `pdf.resolve_borrowed(current)?`.
                            let parent_dict = match pdf.resolve_borrowed(parent_ref)? {
                                Object::Dictionary(dict) => dict,
                                // A /Parent that indirects through a plain
                                // reference object: follow the chain so the
                                // real ancestor still joins the closure, as
                                // the main BFS loop does via collect_direct_refs.
                                // seen_parents bounds any reference cycle.
                                Object::Reference(r) => {
                                    to_visit.push(*r);
                                    continue;
                                }
                                // Any other non-dictionary parent (a free or
                                // missing object resolving to Null, etc.) is
                                // tolerated: the walk just climbs past it.
                                _ => continue,
                            };
                            for (pk, pv) in parent_dict.iter() {
                                if pk == b"Kids" {
                                    continue;
                                }
                                if pk == b"Parent" {
                                    // Climb to the next ancestor instead of
                                    // stopping at one level.
                                    collect_direct_refs(pv, 0, &mut to_visit)?;
                                    continue;
                                }
                                let mut refs: Vec<(ObjectRef, bool)> = Vec::new();
                                collect_direct_refs_with_context(pv, 0, false, &mut refs)?;
                                for (r, va) in refs {
                                    if va {
                                        seen_as_array.insert(r); // cov:ignore: fires when an ancestor /Pages node has a value with array-element refs (e.g. inherited /ColorSpace [X 0 R]); rare in practice and hard to construct as a minimal fixture
                                    }
                                    if !visited.contains(&r) {
                                        queue.push_back((r, va));
                                    }
                                }
                            }
                        }
                        continue;
                    }
                    collect_direct_refs_with_context(v, 0, false, &mut refs_raw)?;
                }
                for &(r, va) in &refs_raw {
                    if va {
                        seen_as_array.insert(r);
                    }
                }
                // Sort by original object number: qpdf assigns first-page slots in
                // ascending original-number order regardless of dict key alphabetical
                // order (empirically verified; see discriminator-fixture analysis).
                refs_raw.sort_by_key(|(r, _)| r.number);
                for (r, va) in refs_raw {
                    if !visited.contains(&r) {
                        queue.push_back((r, va));
                    }
                }
            }
        } else {
            let mut refs: Vec<(ObjectRef, bool)> = Vec::new();
            collect_direct_refs_with_context(&obj, 0, false, &mut refs)?;
            for &(r, va) in &refs {
                if va {
                    seen_as_array.insert(r);
                }
            }
            // Same number-ordering rule as the page-dict loop above: qpdf enqueues
            // a non-page object's children in ascending original-object-number order,
            // not in dict-key (alphabetical) order.
            refs.sort_by_key(|(r, _)| r.number);
            for (r, va) in refs {
                if !visited.contains(&r) {
                    queue.push_back((r, va));
                }
            }
        }
    }

    // Sort the non-page tail (order[1..]) by original object number.  qpdf emits
    // first-page objects in ascending original-number order, with the Page leaf
    // always in the first slot.  Two discriminator fixtures confirm this:
    // (a) Resources(5)/Font(6) at higher numbers than Content(4) → numeric order
    //     wins over Resources-DFS-first order;
    // (b) Page(orig 10) with Content(orig 3) → Page stays first despite having a
    //     higher original number, so a fully-global sort would misplace it.
    // Sorting only order[1..] satisfies both invariants simultaneously.
    if order.len() > 1 {
        order[1..].sort_by_key(|r| r.number);
    }
    // Deferred resurrectable refs: now that the full BFS is complete and
    // seen_as_array is exhaustive, admit those that turn out to be reachable
    // via an array edge (i.e. they appear in seen_as_array).  Insert each at
    // the numerically correct position in the already-sorted non-page tail so
    // the Page leaf remains first and the overall tail ordering stays ascending.
    // BTreeSet iterates in ascending order, so each insertion preserves the
    // invariant for subsequent entries.
    for r in deferred_resurrect {
        if seen_as_array.contains(&r) {
            let tail_pos = order[1..].partition_point(|existing| existing.number < r.number);
            order.insert(1 + tail_pos, r);
        } // cov:ignore: false branch = deferred ref that has no array edge in the entire closure; qpdf correctly drops it (same as the dict-value-only drop path). Requires a resurrectable ref that appears *only* in a dict-value slot with no array counterpart anywhere in the closure — correctly exercised by the existing behaviour but the closing brace hits only the zero-count path.
    }

    Ok(order)
}

// ---------------------------------------------------------------------------
// LinearizationPlan
// ---------------------------------------------------------------------------

/// Retained qpdf-style object-user signals for ObjStm routing.
#[derive(Debug, Clone)]
pub(crate) struct LinearizationRoutingUsers {
    first_page: BTreeSet<ObjectRef>,
    thumbnails: BTreeSet<ObjectRef>,
    outlines: BTreeSet<ObjectRef>,
    outlines_in_first_page: bool,
    open_document: BTreeSet<ObjectRef>,
    document_other: BTreeSet<ObjectRef>,
}

/// Partition of a PDF document's objects into the four linearization parts
/// defined by ISO 32000-1 Annex F, together with the raw inputs for the
/// page-offset and shared-object hint tables.
///
/// Constructed from a [`Pdf`] handle via [`LinearizationPlan::from_pdf`].
/// This struct owns all data it needs and holds no reference into the source
/// document.
///
/// # Object disjointness
///
/// The four part lists are disjoint by construction.  `from_pdf` computes the
/// first-page closure, partitions it into Part 2 (exclusive) and Part 3
/// (shared with other pages), and removes the moved objects from Part 4 so
/// the invariant is always maintained.  The free-list head at object 0 is
/// excluded from Part 4 entirely (ISO 32000-1 §7.5.4).
#[derive(Debug, Clone)]
pub struct LinearizationPlan {
    // ------------------------------------------------------------------
    // Part membership
    // ------------------------------------------------------------------
    /// Part 1: linearization parameter dictionary and its xref stream.
    /// Populated by the writer subtask (2.3/2.4); empty as a placeholder.
    pub part1_objects: Vec<ObjectRef>,
    /// Part 2: first-page objects (page dict, resources, content streams).
    /// Computed by `from_pdf` using the first-page closure algorithm.
    pub part2_objects: Vec<ObjectRef>,
    /// Part 3: non-first-page shared objects (objects referenced by both
    /// page 1 and at least one other page).
    /// Computed by `from_pdf`.
    pub part3_objects: Vec<ObjectRef>,
    /// qpdf part7: objects private to exactly one other page (pages 2..N).
    ///
    /// Ordered by page index, then by BFS closure order within each page.
    pub part4_other_pages_private: Vec<ObjectRef>,
    /// qpdf part8: objects shared by two or more other pages (pages 2..N),
    /// but NOT reachable from page 1.
    pub part4_other_pages_shared: Vec<ObjectRef>,
    /// qpdf part9: all Part-4 objects that are not in part7 or part8.
    /// Includes the Pages tree, Info dict, lc_other objects, and any objects
    /// not reachable from any page closure (trailer-only refs, etc.).
    pub part4_rest: Vec<ObjectRef>,

    // ------------------------------------------------------------------
    // Document summary (copied from the source at construction time)
    // ------------------------------------------------------------------
    /// Total number of objects as reported by the xref table.
    pub total_object_count: u32,
    /// `/Root` reference from the trailer, if present.
    pub root_ref: Option<ObjectRef>,
    /// `/Pages` tree root reference (catalog's `/Pages` entry).
    ///
    /// Promoted into the renumber map's reserved prefix so the resulting
    /// object number matches qpdf's `part9` head (qpdf assigns the pages
    /// tree to object 1). May be `None` for malformed inputs missing this
    /// entry; in that case no promotion happens.
    pub pages_tree_ref: Option<ObjectRef>,
    /// `/Info` reference from the trailer, if present.
    ///
    /// Promoted into the renumber map's reserved prefix to mirror qpdf's
    /// `lc_other` ordering (Info follows pages tree in the second-half
    /// renumber pass).
    pub info_ref: Option<ObjectRef>,

    // ------------------------------------------------------------------
    // Hint table inputs
    // ------------------------------------------------------------------
    /// Page-offset hint table inputs (one entry per page).
    ///
    /// Entry 0 has `object_count` set to the number of Part-2 objects and
    /// `first_object_index` set to 0.  `byte_length` remains a placeholder (0)
    /// for back-patching by the writer.
    pub page_hints: Vec<PageHintEntry>,
    /// Shared-object hint table inputs.
    ///
    /// One entry per Part-3 object; `referencing_pages` lists the 0-based
    /// page indices (across all pages) that reach this object.
    pub shared_hints: Vec<SharedObjectHintEntry>,

    /// Per-page private object lists for byte-length computation.
    ///
    /// `per_page_private_objects[i]` is the list of objects that belong
    /// exclusively to page `i` (not shared with any other page):
    ///
    /// * For page 0: equal to `part2_objects`.
    /// * For pages 1..N: the objects in that page's closure that are
    ///   **not** in Part 2 or Part 3 (i.e. they are private to this page
    ///   within Part 4).
    ///
    /// The writer uses these lists to compute `page_hints[i].byte_length`
    /// and to populate the Page Offset Hint Table's `page_length_minus_least`
    /// and `least_page_length` fields.
    pub per_page_private_objects: Vec<Vec<ObjectRef>>,

    /// Full object → referencing-page inverse map: `all_referenced_pages[r]` is
    /// the set of 0-based page users assigned to `r` by qpdf's ordered
    /// `updateObjectMaps` traversal.
    ///
    /// Used to compute a shared ObjStm container's referencing pages from its
    /// FULL membership — the global even split can place a page's *private*
    /// object inside a container in another section (the first-page part6
    /// container or a part8 shared container), and the page then references that
    /// container as a shared object. Keyed by original ref.
    pub all_referenced_pages: BTreeMap<ObjectRef, BTreeSet<u32>>,

    /// Outline objects routed to the first-page section (part6) when the catalog
    /// specifies `/PageMode /UseOutlines`, in emitted order (root first, then items
    /// in traversal order). Empty when the predicate is false.
    ///
    /// Ordered to match qpdf's `lc_outlines` traversal order so that `shared_hints`
    /// entries are in the same sequence as physically emitted objects.
    /// Used by `page0_object_count_with_objstm` to include the outline ObjStm
    /// container in the page-0 object count (qpdf counts all part6 objects in
    /// `entries.at(0).nobjects`, including outlines placed there when
    /// `outlines_in_first_page` is set).
    pub(crate) outline_first_page_members: Vec<ObjectRef>,

    /// Outline objects for the classic (non-ObjStm) linearize path when
    /// `/PageMode` is NOT `/UseOutlines`.  Extracted from `part4_rest` and
    /// assigned consecutive second-half object numbers (between `pages_tree`
    /// and `info/param_dict` in the renumber map), then emitted after /E.
    /// Matches qpdf's `lc_outlines` (part9) placement.  Empty when
    /// `UseOutlines` is active or when there are no outlines.
    pub(crate) part9_outline_objects: Vec<ObjectRef>,

    /// Outline objects for the classic (non-ObjStm) linearize path when
    /// `/PageMode /UseOutlines` is set.  Extracted from `part4_rest` and
    /// given first-half numbers (after Part 3 in the renumber map), then
    /// emitted **before** /E (between Part 3 and the /E boundary).  Matches
    /// qpdf's `lc_outlines` (part6) placement.  Empty when `UseOutlines` is
    /// not set or when there are no outlines.
    pub(crate) part6_outline_objects: Vec<ObjectRef>,

    /// Open-document objects (qpdf part4 = `lc_open_document`) emitted as plain
    /// indirect objects in the pre-/O region, immediately after the Catalog, in
    /// ascending source object number order.
    ///
    /// In disable/preserve mode this holds the FULL open-document set — every
    /// object reachable from the catalog open-document keys (`/OpenAction`,
    /// `/AcroForm`, `/PageMode`, `/Threads`, `/ViewerPreferences`) and trailer
    /// `/Encrypt`. In generate mode it holds only the ObjStm-ineligible subset
    /// (e.g. stream objects such as `/AP /N` appearance streams that cannot be
    /// ObjStm members); the eligible ones are packed into the open-document ObjStm
    /// container instead.
    ///
    /// Empty only when the document has no open-document objects (or, in generate
    /// mode, when all of them are ObjStm-eligible).
    pub part4_open_document_plain: Vec<ObjectRef>,

    /// Retained qpdf-style object-user signals used to route generated and
    /// preserved ObjStm containers without re-reading the PDF.
    pub(crate) routing_users: Option<LinearizationRoutingUsers>,

    /// Live source generations that qpdf drops while planning generated or
    /// preserved object streams. References to these objects are rewritten as
    /// qpdf-null values even though the source xref entry itself is live.
    pub(crate) removed_refs: BTreeSet<ObjectRef>,

    /// Object-stream mode whose traversal and stale-generation rules produced
    /// this plan. The writer reconciles a legacy boolean plan with its final
    /// [`WriteOptions`](crate::WriteOptions) mode before using the plan's
    /// partitions and renumbering.
    pub(crate) object_stream_mode: crate::writer::ObjectStreamMode,
}

impl LinearizationPlan {
    /// Construct a `LinearizationPlan` from a parsed PDF document.
    ///
    /// This method:
    ///
    /// 1. Collects all known object refs into Part 4.
    /// 2. Computes the transitive closure of objects reachable from page 1
    ///    (`/Pages /Kids[0]`).
    /// 3. Computes closures for pages 2..N to identify shared objects.
    /// 4. Partitions the page-1 closure into Part 2 (exclusive) and Part 3
    ///    (shared), removing them from Part 4.
    /// 5. Fills `page_hints[0]` with the correct `object_count`; all
    ///    `byte_length` fields remain 0 (back-patched by the writer).
    /// 6. Fills `shared_hints` with one entry per Part-3 object, listing
    ///    every page index that references it.
    ///
    /// # Errors
    ///
    /// Propagates any error from [`crate::pages::page_refs`] when collecting the
    /// document's page references (e.g. a malformed or unresolvable `/Pages`
    /// tree). Also propagates any error from resolving objects while computing
    /// each page's reachability closure (via [`Pdf::resolve`] /
    /// [`Pdf::resolve_borrowed`]) — typically an [`crate::Error::Io`] or
    /// [`crate::Error::Parse`] on a truncated or malformed object. Before any
    /// of that, this also pushes inherited page attributes down the `/Pages`
    /// tree, which propagates the same object-resolution errors and returns
    /// [`crate::Error::Unsupported`] if the tree exceeds the page-tree depth
    /// bound.
    pub fn from_pdf<R: Read + Seek>(
        pdf: &mut Pdf<R>,
        use_generate_objstm: bool,
    ) -> crate::Result<Self> {
        let mode = if use_generate_objstm {
            crate::writer::ObjectStreamMode::Generate
        } else {
            crate::writer::ObjectStreamMode::Disable
        };
        Self::from_pdf_with_object_stream_mode(pdf, mode)
    }

    /// Construct a mode-aware linearization plan.
    ///
    /// Unlike the historical boolean API, this distinguishes standard
    /// Preserve from source-ObjStm Preserve. qpdf runs its
    /// `getCompressibleObjGens` stale-generation removal only for Generate and
    /// when Preserve actually consumes source object streams.
    pub fn from_pdf_with_object_stream_mode<R: Read + Seek>(
        pdf: &mut Pdf<R>,
        object_stream_mode: crate::writer::ObjectStreamMode,
    ) -> crate::Result<Self> {
        let use_generate_objstm = matches!(
            object_stream_mode,
            crate::writer::ObjectStreamMode::Generate
        );
        // Push inherited page attributes (/MediaBox /CropBox /Resources
        // /Rotate) down to /Page leaves and strip them from interior /Pages
        // nodes, mirroring qpdf's pushInheritedAttributesToPage — this always
        // runs for linearized output (QPDF_linearization.cc:127-130, called
        // only from QPDFWriter::writeLinearized). Must run before every step
        // below: closure computation and object-ref collection both need to
        // see the already-pushed tree, and any newly minted object must
        // already exist by the time `pdf.object_refs()` is captured.
        crate::linearization::inherited_attrs::push_inherited_attributes_to_pages(pdf)?;

        // ----------------------------------------------------------------
        // Step 1: collect all known object refs (Part 4 initial state).
        // The free-list head at object 0 is excluded per ISO 32000-1 §7.5.4.
        // ----------------------------------------------------------------
        // Drop the source's structural containers (`/Type /ObjStm`, `/Type
        // /XRef`) from the live object set. qpdf rebuilds the cross-reference
        // and repacks ObjStm members into fresh containers, so the source
        // containers are never live body objects (their members survive as
        // individual objects via the compressed xref entries). Carrying them
        // through would shift every offset and make qpdf's linearization
        // length-calc reject them ("found unknown object"). This mirrors the
        // plain rewrite path's emission-time skip (see
        // [`crate::writer::is_source_structural_container`]).
        // qpdf garbage-collects objects unreachable from the trailer roots (it
        // only enqueues reachable objects). The plain full-rewrite path does this
        // via CatalogFirstRenumber's trailer-seeded BFS; the linearize universe
        // must too, or re-linearizing an already-linearized source leaks its old
        // /Linearized parameter dict + hint stream — both unreachable structural
        // artifacts — into the second half (flpdf-phfu).
        //
        // `skip_length = true`: the linearized writer always emits a direct
        // `/Length` — re-encoded and lone-`/FlateDecode`-verbatim streams alike,
        // and `renumber_object` substitutes a direct length for a dropped holder's
        // dangling reference — so a stream's indirect `/Length` edge is dead in the
        // output regardless of object-stream mode. Not following it drops a holder
        // reachable only through it, matching qpdf's reachability GC.
        let reachable = crate::rewrite_renumber::reachable_object_set(pdf, true)?;
        let object_refs = pdf.object_refs();
        let mut all_refs: Vec<ObjectRef> = Vec::with_capacity(object_refs.len());
        for r in object_refs {
            if r.number == 0 {
                continue;
            }
            if crate::writer::is_source_structural_container(pdf.resolve_borrowed(r)?) {
                continue;
            }
            if !reachable.contains(&r) {
                // Unreachable from the trailer roots — qpdf drops it. This also
                // drops an orphaned indirect `/Length` holder: the reachability
                // walk does not follow the dead `/Length` edge, so a holder
                // reachable only through it is absent from `reachable`.
                continue;
            }
            all_refs.push(r);
        }

        // Resurrect null-resolving references reached via a surviving (array)
        // edge that have NO xref entry (truly missing). Free entries are already
        // admitted above — they are in `object_refs()` (CacheEntry::Deleted) and
        // pass the `reachable` filter — so add only the missing ones. qpdf treats
        // a missing array ref exactly like a free one: a renumbered `null` body
        // object the array points at (verified byte-identical, /ID masked). The
        // set is drop-aware (a null ref reached only as a dict value is omitted),
        // so a dict-only missing ref stays dropped, not resurrected.
        // `all_refs` is sorted (it filters the sorted `object_refs()` in order),
        // so a binary search rejects the already-admitted (free) refs without
        // allocating a temporary set.
        //
        // `resurrectable` is kept alive to pass to `compute_closure`, which
        // includes these refs in the page closure they're first reached from.
        // qpdf classifies them as first-page section objects (Part 2) when reached
        // from the first page, giving them HIGH object numbers. Without this, they
        // land in part4_rest with LOW numbers (flpdf-o9im).
        let source_had_compressed_objects =
            pdf.source_xref_entries()
                .iter()
                .any(|(_reference, offset)| {
                    matches!(offset, crate::xref::XrefOffset::Compressed { .. })
                });
        let operation_removes_stale_generations = use_generate_objstm
            || (matches!(
                object_stream_mode,
                crate::writer::ObjectStreamMode::Preserve
            ) && source_had_compressed_objects);
        let removed_refs = if operation_removes_stale_generations {
            crate::writer::object_streams::compressible_objgens_qpdf_plan(pdf)?.removed_refs
        } else {
            BTreeSet::new()
        };
        all_refs.retain(|reference| !removed_refs.contains(reference));
        let resurrectable =
            crate::rewrite_renumber::resurrectable_null_refs_excluding(pdf, &removed_refs)?;
        let mut resurrected: Vec<ObjectRef> = resurrectable
            .iter()
            .filter(|r| all_refs.binary_search(r).is_err())
            .copied()
            .collect();
        if !resurrected.is_empty() {
            all_refs.append(&mut resurrected);
            // Keep source-object-number order (object_refs() is already sorted);
            // the resurrected refs slot in at their numeric position.
            all_refs.sort();
        }

        let total_object_count = all_refs.len() as u32;
        let root_ref = pdf.root_ref();
        let info_ref = pdf.trailer().get_ref("Info");
        let pages_tree_ref = root_ref
            .and_then(|r| pdf.resolve_borrowed(r).ok())
            .and_then(|obj| match obj {
                Object::Dictionary(d) => d.get_ref("Pages"),
                _ => None,
            });

        // ----------------------------------------------------------------
        // Step 2: collect page references.
        // Propagate page-tree errors so a malformed /Pages does not silently
        // produce an empty page_hints (which would corrupt downstream hint tables).
        // ----------------------------------------------------------------
        let page_refs: Vec<ObjectRef> = crate::pages::page_refs(pdf)?;

        // The live object set is invariant across every page's closure; compute it
        // once so the per-page `compute_closure` calls below do not each re-scan
        // the whole xref table (which would be O(pages × objects)).
        let live: BTreeSet<ObjectRef> = pdf.live_object_refs().into_iter().collect();
        let page_tree = page_tree_node_refs(pdf)?;
        let page_object_users = page_object_users(pdf, &page_refs)?;
        let mut all_referenced_pages: BTreeMap<ObjectRef, BTreeSet<u32>> = BTreeMap::new();
        for (page_idx, users) in page_object_users.page.iter().enumerate() {
            for &object_ref in users {
                all_referenced_pages
                    .entry(object_ref)
                    .or_default()
                    .insert(page_idx as u32);
            }
        }
        let first_page_users = page_object_users.page.first().cloned().unwrap_or_default();
        let open_document_set = open_document_set_with_context(pdf, &page_tree)?;
        let all_outline_refs = outlines_set_with_context(pdf, &page_tree)?;
        let document_other_set = document_other_set_with_context(pdf, &page_tree)?;
        let elig_ctx = if use_generate_objstm {
            Some(eligibility_context(pdf)?)
        } else {
            None
        };

        // ----------------------------------------------------------------
        // Step 3: compute first-page closure
        // ----------------------------------------------------------------
        let mut first_page_closure: Vec<ObjectRef> = if let Some(&first_page) = page_refs.first() {
            compute_closure(pdf, first_page, &live, &resurrectable)?
        } else {
            Vec::new()
        };
        if let Some(users) = page_object_users.page.first() {
            first_page_closure.retain(|object_ref| users.contains(object_ref));
        } // cov:ignore: llvm-cov attributes this executed closure's terminator to the uninstrumented brace (the retain call on line 890 records hits)

        // compute_closure does not follow a stream dict's /Length (qpdf directizes
        // /Length before computing object users), so a stream's indirect /Length
        // holder never enters a page closure: an orphan holder (referenced only via
        // /Length) is GC'd by the all_refs filter above, and a kept holder is
        // reached only via its other (e.g. catalog) edge and partitions from there
        // (flpdf-hwx0 / flpdf-2vfg).
        let first_page_set: BTreeSet<ObjectRef> = first_page_closure.iter().copied().collect();

        // ----------------------------------------------------------------
        // Step 4: compute closures for pages 2..N and find shared objects
        // ----------------------------------------------------------------
        // Build a full inverse map: (object_ref → set of page indices) across
        // ALL pages (0..N).  This is used to determine which objects are shared
        // between multiple pages regardless of whether they appear in the
        // first-page closure.
        //
        // `shared_page_indices` retains the old semantics for Part 3 partitioning
        // (only first-page-set objects that also appear in other pages).
        // `all_referenced_pages` was derived above from the exact qpdf-style
        // page-user traversal and is the sole retained object-to-page inverse
        // map. Closures here remain the authoritative ordered inputs for page
        // partitioning and hint construction.
        let mut shared_page_indices: BTreeMap<ObjectRef, BTreeSet<u32>> = BTreeMap::new();
        let mut other_page_closures: Vec<Vec<ObjectRef>> =
            Vec::with_capacity(page_refs.len().saturating_sub(1));

        for (page_idx, &page_ref) in page_refs.iter().enumerate().skip(1) {
            let mut closure = compute_closure(pdf, page_ref, &live, &resurrectable)?;
            closure.retain(|object_ref| page_object_users.page[page_idx].contains(object_ref));
            for obj_ref in &closure {
                // Track cross-page sharing for first-page objects (used by Part 3 partition).
                if first_page_set.contains(obj_ref) {
                    shared_page_indices
                        .entry(*obj_ref)
                        .or_default()
                        .insert(page_idx as u32);
                }
            }
            other_page_closures.push(closure);
        }

        // ----------------------------------------------------------------
        // Step 4b: thumb-set for the first-page private/shared split.
        // ----------------------------------------------------------------
        // qpdf gives a page's /Thumb descendants the separate `ou_thumb` user
        // while sharing the page traversal's one ordered `visited` set
        // (QPDF_optimization.cc:261-337). The same exact map supplies ordinary
        // page membership above and thumbnail membership here.
        let thumbnail_user_set = page_object_users.thumbnail_set();

        // ----------------------------------------------------------------
        // Step 5: partition into Part 2 (exclusive) and Part 3 (shared)
        // ----------------------------------------------------------------
        // Maintain closure discovery order from first_page_closure for Part 2
        // (page dict first, then its `/Resources` subtree, then `/Contents`,
        // matching qpdf's first-page object numbering).
        //
        // The page-1 dictionary itself is pinned to Part 2 even if another
        // page directly references it; the linearization layout requires
        // that the first page object live at the start of Part 2 (it is the
        // anchor reached via /O in the parameter dict).  Without this pin
        // a circular page-tree reference (or a deliberately-shared page
        // dict) would silently demote the page object into Part 3.
        let first_page_ref = page_refs.first().copied();
        let mut part2_objects: Vec<ObjectRef> = Vec::new();
        let mut part3_objects: Vec<ObjectRef> = Vec::new();

        for obj_ref in &first_page_closure {
            // qpdf: in_open_document takes precedence over in_first_page in EVERY
            // object-stream mode. Objects reachable from catalog open-document keys
            // (/AcroForm, /OpenAction, etc.) are placed in the open-document section
            // (part4, first half, before /O) even when they also appear in the
            // first-page closure, so peel them out of Part 2/3 here:
            //   - generate: eligible ones pack into the open-document ObjStm
            //     container (route_objstm_containers -> ContainerPart::OpenDocument);
            //     ineligible streams emit plain pre-/O (part4_open_document_plain).
            //   - disable/preserve: all are emitted plain pre-/O.
            // Verified against qpdf 11.9.0: acroform-widget-page0-5-10 in disable
            // mode places the AcroForm dict + widgets in part4, NOT the first-page
            // section (the 12 first-page objects there are the page dict + content
            // + 10 Fonts, not the widgets).
            //
            // in_outlines outranks in_first_page the same way (and outranks
            // in_open_document, so check it first): an object reached from both the
            // first page and /Outlines is lc_outlines (second-half part9, or part6
            // under /UseOutlines), never part2/part3. Peel it here so the part4
            // outline extraction in Step 8 can place it. Verified against qpdf
            // 11.9.0: outlines-shared-page-80-80's /Extra-referenced font is the
            // last second-half object, not a first-page-shared object (flpdf-q2zw).
            if all_outline_refs.contains(obj_ref) || open_document_set.contains(obj_ref) {
                continue;
            }
            if Some(*obj_ref) == first_page_ref {
                part2_objects.push(*obj_ref);
            } else if shared_page_indices.contains_key(obj_ref)
                || document_other_set.contains(obj_ref)
                || thumbnail_user_set.contains(obj_ref)
            {
                // lc_first_page_shared: in_first_page AND (other_pages>0 ||
                // others>0 || thumbs>0). `shared_page_indices` supplies
                // other_pages (another page's closure); `document_other_set`
                // supplies others (a document-level reference such as a Catalog
                // key); `thumbnail_user_set` supplies thumbs (a page's /Thumb
                // target). Any of these makes the object shared
                // (QPDF_linearization.cc:1124-1127), so it sorts after the
                // first-page-private objects in part 6.
                part3_objects.push(*obj_ref);
            } else {
                part2_objects.push(*obj_ref);
            }
        }
        // qpdf packs first-half shared objects in ascending source object number
        // order (observed against qpdf 11.9.0: ObjStm member ordering matches
        // source number order, not the BFS discovery order which follows dict key
        // alphabetical order). Mirror the same sort used in `fold_pages_tree_into_first_half`.
        part3_objects.sort_unstable_by_key(|r| r.number);
        // qpdf numbers the first-page section (qpdf part6) as: the first-page
        // object first, then the remaining first-page-private objects in
        // ascending source object number order — NOT compute_closure's
        // /Resources-DFS discovery order, which only coincides when resource
        // streams are numbered below the page's content stream. Pin the page
        // dict first (qpdf pushes the first-page object explicitly) and sort the
        // rest by source number. Oracle: qpdf 11.9.0 on a 1-page image fixture
        // orders Page, Contents, Image when Contents < Image by source number
        // (and Page, Image, Contents when Image < Contents), in both generate
        // and disable mode.
        part2_objects.sort_unstable_by_key(|r| (Some(*r) != first_page_ref, r.number));

        // ----------------------------------------------------------------
        // Step 6: build Part 4 by removing Part 2 and Part 3 objects.
        //
        // Provisional list — the final order (per-page private groups
        // contiguous, then leftover globally-shared) is computed below in
        // Step 7 once we know which objects belong to which page.
        let moved: BTreeSet<ObjectRef> = part2_objects
            .iter()
            .chain(&part3_objects)
            .copied()
            .collect();
        let part4_provisional: Vec<ObjectRef> = all_refs
            .into_iter()
            .filter(|r| !moved.contains(r))
            .collect();

        // ----------------------------------------------------------------
        // Step 7: build page_hints and per_page_private_objects
        // ----------------------------------------------------------------
        let mut page_hints: Vec<PageHintEntry> = page_refs
            .iter()
            .map(|&r| PageHintEntry::placeholder(r))
            .collect();

        // For quick membership checks across all pages.
        let part2_set: BTreeSet<ObjectRef> = part2_objects.iter().copied().collect();
        let part3_set: BTreeSet<ObjectRef> = part3_objects.iter().copied().collect();

        // Page 0: private objects = Part 2 objects.
        let page0_private = part2_objects.clone();

        // Fill page-0 hint: first_object_index = 0; object_count = Part 2 +
        // Part 3 (shared) objects, since the first-page section physically
        // contains both before /E.  qpdf's hint-table checker validates
        // object_count[0] against the count of objects in [first_page_offset,
        // /E), which equals |Part 2| + |Part 3|.
        if !page_hints.is_empty() {
            page_hints[0].first_object_index = 0;
            page_hints[0].object_count = (page0_private.len() + part3_objects.len()) as u32;
        }

        // Per-page private object lists, page 0 first.
        let mut per_page_private_objects: Vec<Vec<ObjectRef>> = Vec::with_capacity(page_refs.len());
        per_page_private_objects.push(page0_private);

        // Pages 1..N: private objects = closure(i) ∩ (reachable from exactly
        // 1 page).  Excluding only part2_set / part3_set is too narrow:
        // globally-shared objects like the Catalog or /Pages tree intermediate
        // nodes are reachable from EVERY page, including page 0 (via the
        // /Parent chain), so they sit in our part4_objects rather than
        // part3_objects.  qpdf's per-page object_count and page_length only
        // count objects exclusive to one page (it walks the file body forward
        // from the page object and stops at the first non-exclusive object),
        // so we mirror that by checking page-reach-count == 1.
        let mut all_closures: Vec<Vec<ObjectRef>> = Vec::with_capacity(page_refs.len());
        all_closures.push(first_page_closure.clone());
        all_closures.extend(other_page_closures.iter().cloned());
        let mut page_reach: BTreeMap<ObjectRef, u32> = BTreeMap::new();
        for closure in &all_closures {
            let unique: BTreeSet<ObjectRef> = closure.iter().copied().collect();
            for r in unique {
                *page_reach.entry(r).or_insert(0) += 1;
            }
        }

        for (i, closure) in other_page_closures.into_iter().enumerate() {
            let page_idx = i + 1; // skip(1) above started page indexing at 1
            let private: Vec<ObjectRef> = closure
                .into_iter()
                .filter(|r| {
                    if part2_set.contains(r) || part3_set.contains(r) {
                        return false;
                    }
                    // Open-document objects (AcroForm widgets, etc.) that happen
                    // to be exclusive to one later page must NOT be counted as
                    // page-private: qpdf routes them to the pre-/O open-document
                    // section (not the per-page section) in every mode, so they are
                    // absent from the second-half page objects and should not
                    // inflate page_hints[page_idx].object_count.  Excluding them
                    // here also keeps them out of per_page_private_objects, so the
                    // part7 pre-pass below never captures them and they remain
                    // available for OD routing in the part8/part9 loop.
                    if open_document_set.contains(r) {
                        return false;
                    }
                    // Outline objects (in_outlines) outrank other-page-private the
                    // same way: keep them out of the per-page-private set so the
                    // part7 pre-pass never claims them and they stay available for
                    // outline routing in the part8/part9 loop (flpdf-q2zw).
                    if all_outline_refs.contains(r) {
                        return false;
                    }
                    // qpdf routes a non-first-page object to lc_other_page_private
                    // (part7) ONLY when others==0 (QPDF_linearization.cc:1128). An
                    // object also reached by a document-level `others` reference
                    // (a Catalog non-open-document key, or a trailer key other than
                    // /Root,/Encrypt) is lc_other (part9) even at other_pages==1.
                    // Keep it out of the per-page-private set so it is neither placed
                    // in part7 nor counted in this page's part7 object_count hint; it
                    // flows through part4_provisional into the part8/part9 loop and
                    // lands in part4_rest (part9) (flpdf-zda0).
                    if document_other_set.contains(r) {
                        return false;
                    }
                    // qpdf's lc_other_page_private predicate also requires
                    // thumbs==0. A normal page object that is another page's
                    // thumbnail belongs to part9, not part7.
                    if thumbnail_user_set.contains(r) {
                        return false;
                    }
                    page_reach.get(r).copied() == Some(1)
                })
                .collect();
            if page_idx < page_hints.len() {
                // Use private count; guarantee at least 1 so hint table isn't all zeros.
                let count = private.len().max(1) as u32;
                page_hints[page_idx].object_count = count;
            }
            per_page_private_objects.push(private);
        }

        // ----------------------------------------------------------------
        // Step 6b: partition Part 4 into qpdf part7 / part8 / part9.
        //
        // qpdf numbers objects in the second half (Part 4) as:
        //   part7 (other pages' private): objects reached by exactly ONE
        //     other page (pages 2..N), iterated page by page in closure order.
        //   part8 (other pages' shared): objects reached by TWO OR MORE
        //     other pages (but NOT page 1), in plan order.
        //   part9 (rest): everything else — Pages tree, Info, lc_other, and
        //     objects not reached from any page closure (trailer-only refs).
        //
        // The renumber pass uses these three sub-partitions directly.
        // `part4_objects` is then built as part7 ++ part8 ++ part9 so the
        // writer (which iterates `part4_objects`) emits bytes in the same
        // order as the renumber map.

        // page_reach counts how many of (first_page_closure, other_page_closures...)
        // contain the object.  For an object NOT in first_page_set:
        //   - page_reach == 1 → exactly one other page → part7
        //   - page_reach >= 2 → two or more other pages → part8
        //   - page_reach == 0 → no page closure → part9
        let provisional_set: BTreeSet<ObjectRef> = part4_provisional.iter().copied().collect();
        // `all_outline_refs` (qpdf's `in_outlines` set) was computed in Step 1c and
        // already peeled out of part2/part3 (Step 5) and the per-page-private sets
        // (Step 7); the loop below routes its members to part4_rest with top
        // precedence so the Step 8 outline extraction places them.
        let mut part4_other_pages_private: Vec<ObjectRef> = Vec::new();
        let mut part4_other_pages_shared: Vec<ObjectRef> = Vec::new();
        let mut part4_rest: Vec<ObjectRef> = Vec::new();
        let mut part4_open_document_plain: Vec<ObjectRef> = Vec::new();
        // Track which objects are already in part7 (private) to build in page order.
        let mut placed_private: BTreeSet<ObjectRef> = BTreeSet::new();

        // part7: iterate pages 2..N in order, closure order within each page.
        // Use per_page_private_objects[1..] — these are already private (reach==1).
        for privates in per_page_private_objects.iter().skip(1) {
            for &r in privates {
                if provisional_set.contains(&r) && placed_private.insert(r) {
                    part4_other_pages_private.push(r);
                }
            }
        }

        // part8 and part9: iterate provisional in original order.
        for &r in &part4_provisional {
            if placed_private.contains(&r) {
                // Already in part7.
                continue;
            }
            // in_outlines has top precedence (QPDF_linearization.cc:1120, above
            // in_open_document and in_first_page). Route every outline object to
            // part4_rest so the Step 8 extraction lifts it into the outline section
            // (part6 under /UseOutlines, else part9). They were peeled from
            // part2/part3 (Step 5) and the per-page-private sets (Step 7), so they
            // reach this loop via part4_provisional even when first-page-reachable.
            if all_outline_refs.contains(&r) {
                part4_rest.push(r);
                continue;
            }
            let reach = page_reach.get(&r).copied().unwrap_or(0);
            // OD+first-page objects were peeled out of Part 2/3 by Step 5 in
            // every mode, so they ARE present in part4_provisional and must not be
            // treated as first-page here — they flow to the OD routing below. A
            // genuine first-page object reaching this point is skipped defensively.
            let in_first_page = first_page_set.contains(&r) && !open_document_set.contains(&r);
            if in_first_page {
                // Should have been in Part 2 or Part 3 — skip (defensive).
                continue;
            }
            // Route open-document objects to part4 (first half, before /O) in
            // EVERY mode — qpdf's part4 = [lc_root] ++ lc_open_document. Outline
            // objects (which qpdf orders above in_open_document) were already
            // routed above, so anything reaching here that is in open_document_set
            // is a genuine lc_open_document object.
            if open_document_set.contains(&r) {
                if let Some(ctx) = elig_ctx.as_ref() {
                    // generate mode: an OD object eligible for ObjStm packing goes
                    // to part4_rest (the batch planner packs it into the
                    // open-document container); an ineligible stream (e.g. an /AP /N
                    // appearance stream, which cannot be an ObjStm member) emits
                    // plain pre-/O.  Oracle: qpdf --object-streams=generate places
                    // such a Form XObject at a lower object number than the OD
                    // ObjStm, physically before the hint stream.
                    let obj = pdf.resolve_borrowed(r)?;
                    if is_eligible_for_objstm(r, obj, ctx) {
                        part4_rest.push(r);
                    } else {
                        part4_open_document_plain.push(r);
                    }
                } else {
                    // disable/preserve mode: no ObjStm, so every OD object is a
                    // plain pre-/O (part4) object emitted between the Catalog and
                    // the hint stream.
                    part4_open_document_plain.push(r);
                }
                continue;
            }
            // What remains: non-outline, non-open-document objects. Partition by
            // page reach (qpdf's other_pages count): two or more other pages →
            // lc_other_page_shared (part8); otherwise lc_other (part9).
            if reach >= 2 {
                part4_other_pages_shared.push(r);
            } else {
                // reach == 0 (trailer-/document-only), or reach == 1 with others>0
                // (excluded from per_page_private above, so it is lc_other not
                // lc_other_page_private — QPDF_linearization.cc:1128, flpdf-zda0).
                // Both are qpdf part9.
                part4_rest.push(r);
            }
        }

        debug_assert_eq!(
            part4_other_pages_private.len()
                + part4_other_pages_shared.len()
                + part4_rest.len()
                + part4_open_document_plain.len(),
            part4_provisional.len(),
            "Part-4 sub-partition must preserve membership"
        );

        // qpdf builds part4 as [lc_root] ++ lc_open_document, where
        // lc_open_document is a std::set<QPDFObjGen> — i.e. ascending
        // (object number, generation) (QPDF_linearization.cc:1179-1182). The
        // Catalog (lc_root) is placed separately by the renumber map's root_ref
        // promote, so order part4_open_document_plain to match. Sort by the full
        // ObjectRef (its derived Ord is number-then-generation, mirroring
        // QPDFObjGen) rather than the object number alone, so refs that share an
        // object number across generations keep qpdf's tie-break order.
        part4_open_document_plain.sort_unstable();

        // ----------------------------------------------------------------
        // Step 8: build shared_hints
        // ----------------------------------------------------------------
        // The Shared Object Hint Table covers ALL objects in the first-page
        // section (Part 2 + Part 3) plus any Part-4 shared objects.
        //
        // qpdf always lists all objects in the first-page section in the SO
        // hint table, even for single-page PDFs where no objects are truly
        // shared across pages.  We match this behaviour unconditionally:
        // shared_hints is always non-empty whenever part2_objects is non-empty.
        //
        // Layout of shared_hints (in file order):
        //   [part2 entries]   - first-page section private objects (page 0 owns
        //                       them by physical position; referencing_pages = [])
        //   [part3 entries]   - first-page section shared objects (also owned by
        //                       page 0 physically; referencing_pages lists pages
        //                       1..N that also use them, NOT page 0)
        //   [outline entries] - outline objects routed to the first-page section
        //                       when /PageMode /UseOutlines is set; physically
        //                       owned by page 0 via layout (referencing_pages = [])
        //   [part4_shared]    - Part-4 shared objects (after /E; owned by no
        //                       page via physical position; referencing_pages lists
        //                       ALL pages that reference them)

        // Outline objects routed to the first-page section when
        // /PageMode /UseOutlines is set (QPDF_linearization.cc:1031-1043).
        // Must be built before shared_hints so they can be included in it.
        //
        // For the classic (non-ObjStm) linearize path, outlines in part4_rest
        // need to be extracted into dedicated fields so the renumber map can
        // assign them the correct half:
        //   part6_outline_objects — UseOutlines: first-half numbers, emitted before /E
        //   part9_outline_objects — !UseOutlines: second-half numbers, emitted after /E
        let outlines_in_first_page = outlines_in_first_page_predicate(pdf)?;
        // `all_outline_refs` is computed once above (step 6b), before the
        // open-document routing that defers to it.
        // Outline root reference: placed first in the extracted vectors so the
        // renumber map assigns it the lowest new unit among outline objects,
        // matching qpdf's lc_outlines traversal-from-root order (used by
        // compute_outline_hint_info's first_object).
        let outline_root_ref: Option<ObjectRef> = pdf
            .root_ref()
            .and_then(|r| pdf.resolve_borrowed(r).ok()?.as_dict()?.get_ref("Outlines"));

        let extract_outlines = |src: &[ObjectRef]| -> Vec<ObjectRef> {
            let mut v: Vec<ObjectRef> = src
                .iter()
                .filter(|r| all_outline_refs.contains(r))
                .copied()
                .collect();
            // Rotate root to front so it receives the lowest consecutive new number.
            if let Some(root) = outline_root_ref {
                if let Some(pos) = v.iter().position(|&r| r == root) {
                    v[..=pos].rotate_right(1);
                }
            }
            v
        };

        let (part6_outline_objects, part9_outline_objects): (Vec<ObjectRef>, Vec<ObjectRef>) =
            if outlines_in_first_page {
                (extract_outlines(&part4_rest), vec![])
            } else {
                (vec![], extract_outlines(&part4_rest))
            };
        // Remove extracted outlines from part4_rest to avoid double assignment.
        let outline_extract_set: BTreeSet<ObjectRef> = part6_outline_objects
            .iter()
            .chain(&part9_outline_objects)
            .copied()
            .collect();
        part4_rest.retain(|r| !outline_extract_set.contains(r));

        // For UseOutlines: outlines are emitted before /E and count toward page 0.
        if outlines_in_first_page && !page_hints.is_empty() {
            page_hints[0].object_count += part6_outline_objects.len() as u32;
        }

        // Use part6_outline_objects (already root-first, only objects actually
        // extracted from part4_rest) so that shared_hints iteration order matches
        // the physical emitted order and objects also reachable from a page closure
        // are not double-counted in shared_hints.
        let outline_first_page_members: Vec<ObjectRef> = if outlines_in_first_page {
            part6_outline_objects.clone()
        } else {
            vec![]
        };

        let part2_entries = part2_objects.iter().map(|&obj_ref| SharedObjectHintEntry {
            object_ref: obj_ref,
            referencing_pages: vec![],
        });
        let part3_entries = part3_objects.iter().map(|&obj_ref| {
            let pages: Vec<u32> = shared_page_indices
                .get(&obj_ref)
                .map(|s| s.iter().copied().collect())
                .unwrap_or_default();
            // Do NOT add page 0: Part-3 shared objects are in the first-page
            // section, so page 0 implicitly owns them by physical layout.
            SharedObjectHintEntry {
                object_ref: obj_ref,
                referencing_pages: pages,
            }
        });
        // Outline objects are in the first-page section (physically owned by
        // page 0), so page 0 is not listed in referencing_pages.
        let outline_entries =
            outline_first_page_members
                .iter()
                .map(|&obj_ref| SharedObjectHintEntry {
                    object_ref: obj_ref,
                    referencing_pages: vec![],
                });
        // Part-4 shared objects: referenced by ≥ 2 pages but NOT in the
        // first-page closure.  These live after /E (not physically owned
        // by any page via layout), so ALL referencing pages are listed.
        let part4_shared_entries = part4_other_pages_shared.iter().map(|&obj_ref| {
            let pages: Vec<u32> = all_referenced_pages
                .get(&obj_ref)
                .map(|s| s.iter().copied().collect())
                .unwrap_or_default();
            SharedObjectHintEntry {
                object_ref: obj_ref,
                referencing_pages: pages,
            }
        });
        let shared_hints: Vec<SharedObjectHintEntry> = part2_entries
            .chain(part3_entries)
            .chain(outline_entries)
            .chain(part4_shared_entries)
            .collect();

        Ok(Self {
            part1_objects: Vec::new(),
            part2_objects,
            part3_objects,
            part4_other_pages_private,
            part4_other_pages_shared,
            part4_rest,
            part4_open_document_plain,
            total_object_count,
            root_ref,
            pages_tree_ref,
            info_ref,
            page_hints,
            shared_hints,
            per_page_private_objects,
            all_referenced_pages,
            outline_first_page_members,
            part9_outline_objects,
            part6_outline_objects,
            object_stream_mode,
            removed_refs,
            routing_users: Some(LinearizationRoutingUsers {
                first_page: first_page_users,
                thumbnails: thumbnail_user_set,
                outlines: all_outline_refs,
                outlines_in_first_page,
                open_document: open_document_set,
                document_other: document_other_set,
            }),
        })
    }

    /// Return the set of all objects assigned to at least one part.
    ///
    /// Part-4 body objects (Annex F Part 5), in the order the writer emits them.
    ///
    /// This is a derived view: the ordered concatenation of
    /// [`part4_other_pages_private`](Self::part4_other_pages_private),
    /// [`part4_other_pages_shared`](Self::part4_other_pages_shared), and
    /// [`part4_rest`](Self::part4_rest). Callers that previously read a
    /// `part4_objects` field should call this getter instead — it cannot
    /// drift from the three sub-partitions because there is no separate
    /// backing storage.
    pub fn part4_objects(&self) -> Vec<ObjectRef> {
        self.part4_other_pages_private
            .iter()
            .chain(&self.part4_other_pages_shared)
            .chain(&self.part9_outline_objects)
            .chain(&self.part4_rest)
            .copied()
            .collect()
    }

    /// Fold first-page-section ObjStm members into their containers to match
    /// qpdf's shared-object hint list.
    ///
    /// When the first-page shared dicts are packed into a first-half ObjStm
    /// container, qpdf lists the *container* (one entry) in the shared-object
    /// hint table — not each compressed member.  This rewrites
    /// [`shared_hints`](Self::shared_hints): every member present in
    /// `member_to_container` is replaced by a single entry for its container
    /// (with the `referencing_pages` of all that container's members unioned),
    /// and the second-and-later members of the same container are dropped.
    /// Non-member entries are kept verbatim.
    ///
    /// The first-page section of the result is then emitted in **ascending
    /// physical object-number order**.  qpdf's `checkHSharedObject` walks the
    /// first-page shared entries positionally, starting from the first page
    /// object, so the hint list must follow the order in which
    /// [`RenumberMap::place_objstm_members_per_half`](crate::linearization::renumber::RenumberMap::place_objstm_members_per_half)
    /// numbers the first half (plain objects first, then containers, then
    /// compressed members).  A plain (ineligible) shared stream can therefore be
    /// numbered *before* the container of the eligible dicts even when the
    /// container appeared earlier in `shared_hints`; the sort restores the
    /// physical order.  Part-8 entries (`part4_other_pages_shared`, after /E)
    /// are left in place.
    ///
    /// The container entry's `object_ref` carries the container's *new* object
    /// number with generation `u16::MAX` — a sentinel no live object uses,
    /// marking it as a synthetic container entry rather than a resolvable PDF
    /// object.  A plain entry carries an original ref whose physical number is
    /// resolved through `renumber`; a synthetic container entry already carries
    /// its new number, so it is never resolved through the
    /// [`RenumberMap`].
    ///
    /// ObjStm container object numbers that are qpdf **part8** (other-page-shared)
    /// objects: their members reach two or more pages but none is a first-page
    /// (Part-2 / Part-3) object.
    ///
    /// The global even split can fill such a container entirely with objects that
    /// are individually page-*private* (one page's privates co-located with
    /// another's), so the container does not appear in `shared_hints` (built from
    /// the per-object part2/part3/part4_shared partition) even though it is a
    /// shared object that belongs in the shared-object hint table. This enumerates
    /// those containers so the table and its entry counts include them.
    pub(crate) fn part8_container_nums(
        &self,
        member_to_container: &BTreeMap<ObjectRef, (u32, u32)>,
    ) -> BTreeSet<u32> {
        let first_page: BTreeSet<ObjectRef> = self
            .part2_objects
            .iter()
            .chain(&self.part3_objects)
            .copied()
            .collect();
        let part4_shared: BTreeSet<ObjectRef> =
            self.part4_other_pages_shared.iter().copied().collect();

        let mut all_containers: BTreeSet<u32> = BTreeSet::new();
        let mut container_pages: BTreeMap<u32, BTreeSet<u32>> = BTreeMap::new();
        let mut has_first_page_member: BTreeSet<u32> = BTreeSet::new();
        let mut has_shared_member: BTreeSet<u32> = BTreeSet::new();
        for (member, &(cnum, _)) in member_to_container {
            all_containers.insert(cnum);
            if first_page.contains(member) {
                has_first_page_member.insert(cnum);
            }
            // A reach-≥2 (part4_other_pages_shared) member makes the container a
            // shared object directly — used when `all_referenced_pages` is absent
            // (e.g. manually-built plans) and as a robust signal otherwise.
            if part4_shared.contains(member) {
                has_shared_member.insert(cnum);
            }
            if let Some(pages) = self.all_referenced_pages.get(member) {
                container_pages
                    .entry(cnum)
                    .or_default()
                    .extend(pages.iter().copied().filter(|&p| p != 0));
            }
        }
        // A container is part8 when no member is a first-page object AND it is
        // shared — either it holds an explicitly-shared (reach-≥2) member, or its
        // members span two or more pages (the even split co-located two pages'
        // privates).
        all_containers
            .into_iter()
            .filter(|cnum| {
                !has_first_page_member.contains(cnum)
                    && (has_shared_member.contains(cnum)
                        || container_pages.get(cnum).is_some_and(|p| p.len() >= 2))
            })
            .collect()
    }

    /// ObjStm container new-numbers routed to part9 (Rest) by qpdf's outline
    /// priority (QPDF_linearization.cc:1118-1122): every container carrying a
    /// `part9_outline_objects` member.
    ///
    /// Such a container is placed in the second half even when the global even
    /// split co-locates a `part4_other_pages_shared` object in it, and it is NOT
    /// a shared object in qpdf's Shared Object Hint Table. Both
    /// [`Self::canonical_shared_hints`] (the Part-8 main-loop guard and the
    /// `part8_container_nums` enumeration tail) and
    /// `SharedObjectHintTable::from_plan` (the Part-8 entry COUNT, which feeds
    /// `first_page_entries`) must exclude it, or the table's entry list and its
    /// header counts disagree.
    ///
    /// A member reachable from BOTH `/Outlines` and ≥2 non-first pages stays in
    /// `part4_other_pages_shared` rather than `part9_outline_objects`, so a
    /// container carrying ONLY such a member (no other `part9_outline_objects`
    /// member) is missed here. That can only happen across a 2+-container even
    /// split, which is blocked by the page-dict-erasure boundary divergence
    /// (flpdf-g1eu); the robust fix (keying on the actual Rest routing) lands with
    /// that issue's 2-container fixture. `part9_outline_objects` is small, so look
    /// each up in `member_to_container` rather than scanning all members.
    pub(crate) fn rest_container_nums(
        &self,
        member_to_container: &BTreeMap<ObjectRef, (u32, u32)>,
    ) -> BTreeSet<u32> {
        self.part9_outline_objects
            .iter()
            .filter_map(|member| member_to_container.get(member).map(|&(cnum, _)| cnum))
            .collect()
    }

    /// An empty `member_to_container` yields a clone of `shared_hints` (the
    /// no-ObjStm / classic path is unchanged).
    pub(crate) fn canonical_shared_hints(
        &self,
        member_to_container: &BTreeMap<ObjectRef, (u32, u32)>,
        renumber: &RenumberMap,
        second_half_container_nums: &BTreeSet<u32>,
        open_document_container_nums: &BTreeSet<u32>,
    ) -> Vec<SharedObjectHintEntry> {
        if member_to_container.is_empty() {
            return self.shared_hints.clone();
        }

        // The first-page section of `shared_hints` is the leading part2 ++ part3
        // ++ outline entries; trailing entries are Part-8 (`part4_other_pages_shared`,
        // after /E).
        // Invariant: this split is only correct because `Self::new` builds
        // `shared_hints` as exactly `part2_entries ++ part3_entries ++
        // outline_entries ++ part4_shared_entries` (one entry per object, no filter).
        // Keep the two in lockstep — reordering the construction there silently
        // breaks this boundary.
        let first_page_input = self.part2_objects.len()
            + self.part3_objects.len()
            + self.outline_first_page_members.len();

        // Containers routed to part9 (Rest) by qpdf's outline priority: never
        // shared objects in the SOHT, so skip them in the Part-8 section here AND
        // in the `part8_container_nums` enumeration tail below. The first-page
        // section is already covered by the `second_half_container_nums` guard
        // (it skips ALL second-half containers there); in the Part-8 section that
        // guard cannot be reused because it would also drop legitimate part8
        // containers. See [`Self::rest_container_nums`].
        let rest_container_nums = self.rest_container_nums(member_to_container);

        // Position (index into the output list) at which each container was
        // first emitted, so later members of the same container fold into it.
        let mut container_pos: BTreeMap<u32, usize> = BTreeMap::new();
        let mut out: Vec<SharedObjectHintEntry> = Vec::with_capacity(self.shared_hints.len());
        let mut first_page_out_end: Option<usize> = None;

        for (input_idx, entry) in self.shared_hints.iter().enumerate() {
            if input_idx == first_page_input {
                // Crossed into the Part-8 region: freeze the first-page boundary.
                first_page_out_end = Some(out.len());
            }
            match member_to_container.get(&entry.object_ref) {
                Some(&(container_num, _idx)) => {
                    // Open-document containers live in the pre-/O region (before
                    // the first-page section and before /E), so qpdf excludes
                    // them from the SOHT unconditionally — regardless of whether
                    // the triggering entry is in the first-page section or in the
                    // Part-8 section.
                    if open_document_container_nums.contains(&container_num) {
                        continue;
                    }
                    // Within the first-page section: skip second-half
                    // (outline-routed) ObjStm containers placed after /E.
                    if input_idx < first_page_input
                        && second_half_container_nums.contains(&container_num)
                    {
                        continue;
                    }
                    // Within the Part-8 section: skip part9 (Rest) containers that
                    // qpdf's outline priority placed in the second half. The
                    // first-page guard above cannot fire here (input_idx is past
                    // the boundary), and `second_half_container_nums` would wrongly
                    // also drop legitimate part8 containers — so key on the
                    // part9-only `rest_container_nums` instead.
                    if input_idx >= first_page_input && rest_container_nums.contains(&container_num)
                    {
                        continue;
                    }
                    if let Some(&pos) = container_pos.get(&container_num) {
                        // Fold into the already-emitted container entry: union
                        // the referencing pages (dedup, keep ascending order).
                        let merged: &mut Vec<u32> = &mut out[pos].referencing_pages;
                        for &p in &entry.referencing_pages {
                            if let Err(insert_at) = merged.binary_search(&p) {
                                merged.insert(insert_at, p);
                            }
                        }
                    } else {
                        // First member of this container: emit one entry for the
                        // container, carrying its new object number. The
                        // generation is the sentinel `u16::MAX`: no live object
                        // ever uses it, so consumers can identify this synthetic
                        // container entry unambiguously — even when `container_num`
                        // coincides with a surviving original object's number,
                        // which would otherwise resolve through a `RenumberMap`.
                        let mut pages = entry.referencing_pages.clone();
                        pages.sort_unstable();
                        pages.dedup();
                        container_pos.insert(container_num, out.len());
                        out.push(SharedObjectHintEntry {
                            object_ref: ObjectRef::new(container_num, u16::MAX),
                            referencing_pages: pages,
                        });
                    }
                }
                None => out.push(entry.clone()),
            }
        }

        // Reorder the first-page section to ascending physical object number —
        // the order qpdf's `checkHSharedObject` walks (positionally from the
        // first page object). `place_objstm_members_per_half` numbers the first
        // half as plain… then containers…, so a plain ObjStm-ineligible shared
        // stream is numbered BEFORE the container of the eligible dicts. A
        // folded container entry carries its new number with the sentinel
        // generation `u16::MAX`; a plain entry carries an original ref resolved
        // through `renumber`. Part-8 entries (after the boundary) stay in place.
        let boundary = first_page_out_end.unwrap_or(out.len());
        let new_number = |e: &SharedObjectHintEntry| -> u32 {
            if e.object_ref.generation == u16::MAX {
                e.object_ref.number
            } else {
                // A malformed source can carry a reserved/dangling reference
                // (object number 0, any generation) into the first-page closure
                // and thus into `shared_hints`; `place_objstm_members_per_half`
                // rebuilds the forward renumber index while dropping object
                // number 0 (it doubles as the reserved-slot sentinel), so such an
                // entry has no mapping here. Sort it deterministically last
                // instead of panicking — the writer's shared-hint back-patch
                // (`new_for_original(..).ok_or_else(Err)`, gated only on a
                // non-empty `shared_hints` and run before any output) then
                // surfaces the planner/renumber inconsistency as a structured
                // error. For a well-formed PDF every shared-hint object has a
                // mapping, so this fallback never triggers and the order is
                // unchanged. Mirrors `SharedObjectHintTable::from_plan`'s
                // `new_for_original(..).map_or(0, ..)` graceful handling.
                renumber
                    .new_for_original(e.object_ref)
                    .map_or(u32::MAX, |r| r.number)
            }
        };
        out[..boundary].sort_unstable_by_key(&new_number);

        // Append any qpdf part8 (other-page-shared) ObjStm container that the
        // even split filled entirely with page-PRIVATE objects: such a container
        // never appears in `shared_hints` (no part2/part3/part4_shared member) but
        // IS a shared object in qpdf's hint table. Skip containers already folded
        // into `out` (those carry a part4_shared member). Then order the whole
        // Part-8 section by physical object number, matching qpdf's ObjGen-keyed
        // `lc_other_page_shared`.
        for cnum in self.part8_container_nums(member_to_container) {
            // Open-document containers live in the pre-/O region (before the
            // first-page section), so qpdf excludes them from the SOHT even
            // when their members span multiple later pages (which would
            // otherwise qualify them as Part-8 shared containers via the
            // `container_pages.len() >= 2` criterion in `part8_container_nums`).
            //
            // A part9 (Rest) container routed there by outline priority must also
            // be excluded here, not just in the main loop above. `part8_container_nums`
            // keys on page reachability (`!has_first_page_member && shared/≥2 pages`),
            // so when the co-located part9 container has NO ObjStm-eligible
            // first-page member (e.g. page 0 carries no compressible private object)
            // it satisfies that predicate and would be re-added as a Part-8 entry —
            // re-introducing exactly the SOHT divergence the main-loop guard removes.
            if !container_pos.contains_key(&cnum)
                && !open_document_container_nums.contains(&cnum)
                && !rest_container_nums.contains(&cnum)
            {
                out.push(SharedObjectHintEntry {
                    object_ref: ObjectRef::new(cnum, u16::MAX),
                    referencing_pages: Vec::new(), // recomputed below
                });
            }
        }
        out[boundary..].sort_unstable_by_key(&new_number);

        // Recompute each entry's referencing pages from its FULL membership via
        // `all_referenced_pages` (excluding page 0, which owns the first-page
        // section and lists no shared identifiers). The fold above unions only
        // the `shared_hints` inputs (part2/part3/part4_shared); the global even
        // split can also place a page's PRIVATE object inside a shared container
        // (the first-page part6 container, or a part8 container co-locating two
        // pages' privates), and the page then references that container through
        // the private object — a reference the input entries do not record. This
        // is a no-op for documents whose containers hold only shared_hints
        // objects (the union is identical).
        if !self.all_referenced_pages.is_empty() {
            let mut container_members: BTreeMap<u32, Vec<ObjectRef>> = BTreeMap::new();
            for (&member, &(cnum, _)) in member_to_container {
                container_members.entry(cnum).or_default().push(member);
            }
            let pages_excluding_first = |refs: &mut dyn Iterator<Item = ObjectRef>| -> Vec<u32> {
                let mut pages: BTreeSet<u32> = BTreeSet::new();
                for r in refs {
                    if let Some(ps) = self.all_referenced_pages.get(&r) {
                        pages.extend(ps.iter().copied().filter(|&p| p != 0));
                    }
                }
                pages.into_iter().collect()
            };
            for entry in &mut out {
                entry.referencing_pages = if entry.object_ref.generation == u16::MAX {
                    let members = container_members
                        .get(&entry.object_ref.number)
                        .cloned()
                        .unwrap_or_default();
                    pages_excluding_first(&mut members.into_iter())
                } else {
                    pages_excluding_first(&mut std::iter::once(entry.object_ref))
                };
            }
        }

        out
    }

    /// Useful for callers that want to verify the disjoint invariant.
    /// Uses the three fine-grained Part-4 sub-partitions as the canonical
    /// source of truth.
    pub fn all_assigned_refs(&self) -> BTreeSet<ObjectRef> {
        self.part1_objects
            .iter()
            .chain(&self.part2_objects)
            .chain(&self.part3_objects)
            .chain(&self.part4_other_pages_private)
            .chain(&self.part4_other_pages_shared)
            .chain(&self.part4_rest)
            .copied()
            .collect()
    }

    /// The refs that [`RenumberMap::from_plan`] assigns a renumber slot
    /// (`by_original` key set).
    ///
    /// This is the exact union of the parts `from_plan` walks
    /// (`crates/flpdf/src/linearization/renumber.rs`): part2, part3, the two
    /// Part-4 page sets, part4_rest (which subsumes the promoted pages-tree /
    /// info / catalog refs), the two outline sets, and the open-document plain
    /// set. `part1_objects` is deliberately excluded — `from_plan` never maps
    /// it (and it is always empty today).
    ///
    /// A generated ObjStm may only batch members drawn from this set: an
    /// ObjStm member that lacks a renumber slot makes
    /// [`RenumberMap::place_objstm_members_per_half`] panic. The
    /// `renumber_assigned_refs_match_from_plan` test pins this set to
    /// `from_plan`'s `by_original` keys so the two cannot drift apart.
    pub(crate) fn renumber_assigned_refs(&self) -> BTreeSet<ObjectRef> {
        self.part2_objects
            .iter()
            .chain(&self.part3_objects)
            .chain(&self.part4_other_pages_private)
            .chain(&self.part4_other_pages_shared)
            .chain(&self.part4_rest)
            .chain(&self.part6_outline_objects)
            .chain(&self.part9_outline_objects)
            .chain(&self.part4_open_document_plain)
            .copied()
            .collect()
    }

    /// Return `true` if every object appears in **at most** one part.
    /// Uses the three fine-grained Part-4 sub-partitions as the canonical
    /// source of truth.
    pub fn parts_are_disjoint(&self) -> bool {
        let mut seen = BTreeSet::new();
        for r in self
            .part1_objects
            .iter()
            .chain(&self.part2_objects)
            .chain(&self.part3_objects)
            .chain(&self.part4_other_pages_private)
            .chain(&self.part4_other_pages_shared)
            .chain(&self.part6_outline_objects)
            .chain(&self.part9_outline_objects)
            .chain(&self.part4_rest)
            .chain(&self.part4_open_document_plain)
        {
            if !seen.insert(*r) {
                return false;
            }
        }
        true
    }
}

impl Default for LinearizationPlan {
    /// Construct a blank plan with no objects in any part.
    ///
    /// Useful in test fixtures via `LinearizationPlan { part2_objects: ...,
    /// ..Default::default() }` to avoid repeating empty-vec boilerplate for
    /// fields that are not under test.
    fn default() -> Self {
        Self {
            part1_objects: Vec::new(),
            part2_objects: Vec::new(),
            part3_objects: Vec::new(),
            part4_other_pages_private: Vec::new(),
            part4_other_pages_shared: Vec::new(),
            part4_rest: Vec::new(),
            part4_open_document_plain: Vec::new(),
            total_object_count: 0,
            root_ref: None,
            pages_tree_ref: None,
            info_ref: None,
            page_hints: Vec::new(),
            shared_hints: Vec::new(),
            per_page_private_objects: Vec::new(),
            all_referenced_pages: BTreeMap::new(),
            outline_first_page_members: Vec::new(),
            part9_outline_objects: Vec::new(),
            part6_outline_objects: Vec::new(),
            routing_users: None,
            removed_refs: BTreeSet::new(),
            object_stream_mode: crate::writer::ObjectStreamMode::Disable,
        }
    }
}

// ---------------------------------------------------------------------------
// ObjStm batch planning
// ---------------------------------------------------------------------------

/// Part-tagged ObjStm batch plan produced by `LinearizationPlan::objstm_batches`.
///
/// Each inner `Vec<ObjectRef>` describes one ObjStm container; the contained
/// refs are still **original** (pre-renumber) object references.  Renumbering
/// and actual container-object allocation happen in downstream subtasks (5.8.2+).
///
/// # Part constraints
///
/// * `open_document_batches` — containers qpdf categorizes `in_open_document`
///   (qpdf part4: the open-document objects placed FIRST in the first half,
///   right after the Catalog and before the first-page section). A container
///   lands here when any member is reachable from the catalog's `/OpenAction`,
///   `/AcroForm`, `/ViewerPreferences`, `/PageMode`, `/Threads`, or the
///   trailer's `/Encrypt`.
/// * `part3_batches` — containers that belong in the first-page section
///   (ISO 32000-1 Annex F Part 3 = qpdf part6: shared/catalog objects).
/// * `part4_batches` — containers that belong after `/E` (Part 4 = qpdf
///   part7/8/9: remaining document objects from `part4_other_pages_private`,
///   `part4_other_pages_shared`, and `part4_rest`).
///
/// Every ObjStm container has one union-derived route. Its members may have
/// different classic per-object parts, but the container itself is emitted
/// wholly in that one qpdf-selected part. Page dictionaries and the Catalog
/// are never placed in any batch list.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub(crate) struct ObjStmBatchPlan {
    /// ObjStm batches for qpdf part4 (open-document objects). Numbered and
    /// emitted in the first half, before the first-page section.
    pub(crate) open_document_batches: Vec<Vec<ObjectRef>>,
    /// ObjStm batches for Part 3 (shared/catalog) objects.
    pub(crate) part3_batches: Vec<Vec<ObjectRef>>,
    /// ObjStm batches for Part 4 (rest-of-document) objects.
    pub(crate) part4_batches: Vec<RoutedObjStmBatch>,
}

// These items are consumed by the upcoming ObjStm linearized writer (5.8.2+);
// suppress dead_code until that code lands.
#[allow(dead_code)]
impl LinearizationPlan {
    /// Build a Part-tagged ObjStm packing plan from this `LinearizationPlan`.
    ///
    /// # Mode behaviour
    ///
    /// | Mode | Result |
    /// |------|--------|
    /// | `Disable` | Both batch lists are empty (no ObjStms emitted). |
    /// | `Generate` | Eligible Part-3 (first-page shared) objects are packed into `part3_batches`; eligible Part-4 objects are packed into `part4_batches`. The membership is qpdf-canonical by construction (a global even split with the page dictionaries and `/Catalog` erased), so no post-packing reshape is applied. |
    /// | `Preserve` | Each surviving source ObjStm is retained as one container and routed once from the union of its members' users. Page dictionaries, the `/Catalog`, unassigned objects, and ineligible members are removed; `/Pages` and `/Info` stay with their source container. The configured Generate batch cap is ignored because qpdf Preserve neither splits nor re-chunks source containers. If the source document contained no ObjStms, all batch lists are empty. |
    ///
    /// **Note:** the `/Pages` tree and `/Info` dictionary are not relocated.
    /// qpdf's `preserveObjectStreams` copies the source object->stream
    /// assignment and the linearized pass only erases the `/Page` dictionaries
    /// and the `/Catalog` (QPDFWriter.cc:1939, 2141-2161); the `/Pages` tree and
    /// `/Info` stay in their source container. Preserve mirrors that by routing
    /// them into their source container's first-half batch, so the resulting
    /// container membership matches qpdf.
    ///
    /// # Invariants
    ///
    /// * No page dictionary or Catalog ref appears in any batch.
    /// * Ineligible objects (streams, gen > 0, encryption dict, linearization
    ///   param dict, `/Type /ObjStm`, `/Type /XRef`) are excluded via the
    ///   shared [`is_eligible_for_objstm`] predicate.
    /// * Generate uses qpdf's fixed even split; Preserve retains source
    ///   container boundaries regardless of the configured planner cap.
    ///
    /// # Snapshot contract
    ///
    /// For Generate and Preserve, construct this plan with [`Self::from_pdf`]
    /// from the same `Pdf` passed here, and pass `true` to `from_pdf` exactly
    /// for Generate mode. Both modes classify their container-member unions
    /// from that one retained object-user snapshot. A hand-built plan without
    /// the snapshot is accepted only in Disable mode.
    pub(crate) fn objstm_batches<R: Read + Seek>(
        &self,
        pdf: &mut Pdf<R>,
        config: &PlannerConfig,
    ) -> crate::Result<ObjStmBatchPlan> {
        if config.mode == ObjectStreamMode::Disable {
            return Ok(ObjStmBatchPlan::default());
        }

        let routing_users = self.routing_users.as_ref().ok_or_else(|| {
            crate::Error::Unsupported(
                "linearization plan: missing object-user routing snapshot".to_string(),
            )
        })?;

        let ctx = eligibility_context(pdf)?;
        let length_exclusions = collect_indirect_objstm_length_refs(pdf)?;

        let plan = match config.mode {
            ObjectStreamMode::Disable => unreachable!(),
            ObjectStreamMode::Generate => {
                // The Generate path reproduces qpdf's linearized
                // `generateObjectStreams` directly: a GLOBAL even split over the
                // compressible set, with the page dictionaries + root Catalog
                // erased and `/Info` / the `/Pages` tree kept as ordinary
                // members. That membership is already qpdf-canonical, so no
                // post-packing reshape is applied.
                self.objstm_batches_generate(pdf, config, &ctx, &length_exclusions, routing_users)?
            }
            ObjectStreamMode::Preserve => {
                self.objstm_batches_preserve(pdf, config, &ctx, &length_exclusions, routing_users)?
            }
        };

        Ok(plan)
    }

    /// Generate mode: reproduce qpdf's linearized `generateObjectStreams`.
    ///
    /// A GLOBAL even split over the compressible set
    /// ([`objstm_membership_linearized`]), with the page dictionaries + root
    /// Catalog erased, then each container routed to a linearization part by the
    /// union of its members' page users ([`route_objstm_containers`]). Containers
    /// routed to part 6 ([`ContainerPart::FirstPagePrivate`],
    /// [`ContainerPart::FirstPageShared`], or
    /// [`ContainerPart::FirstPageOutlines`]) become first-half
    /// (`part3_batches`); every other container becomes second-half
    /// (`part4_batches`). Within a container, members are ordered by ascending
    /// source object number (qpdf's `object_stream_to_objects` is a
    /// `std::set<QPDFObjGen>`).
    ///
    /// This replaces flpdf's earlier per-part greedy chunking, which diverged
    /// from qpdf at `>cap` (see `docs/plans/2026-06-17-objstm-generate-linearized-phase2.md`).
    ///
    /// The `config` / `ctx` / `length_exclusions` arguments are unused: the
    /// compressible-set traversal applies qpdf's own eligibility and a fixed
    /// 100-per-stream split (not the planner cap).
    fn objstm_batches_generate<R: Read + Seek>(
        &self,
        pdf: &mut Pdf<R>,
        _config: &PlannerConfig,
        _ctx: &crate::writer::object_streams::EligibilityContext,
        _length_exclusions: &BTreeSet<ObjectRef>,
        routing_users: &LinearizationRoutingUsers,
    ) -> crate::Result<ObjStmBatchPlan> {
        // `objstm_membership_linearized` filters its containers to the plan's
        // renumber-assigned set BEFORE the even split, so a trailer-only ref with
        // no slot neither inflates the split boundary nor reaches
        // `place_objstm_members_per_half` without a slot (which would panic).
        // Dangling/missing refs (e.g. `/Info 99 0 R` with no xref entry) are
        // already excluded upstream by `compressible_objgens`. For a well-formed
        // PDF every member is assigned, so the filter is a no-op and the batches
        // stay byte-identical.
        let assigned = self.renumber_assigned_refs();
        let containers = objstm_membership_linearized(pdf, &assigned)?;
        let routes =
            route_objstm_containers(routing_users, &self.all_referenced_pages, &containers);

        let mut open_document_batches: Vec<Vec<ObjectRef>> = Vec::new();
        // qpdf part 6 is private, shared, then outline containers. Preserve
        // first-encounter order within each bucket.
        let mut part3_private: Vec<Vec<ObjectRef>> = Vec::new();
        let mut part3_shared: Vec<Vec<ObjectRef>> = Vec::new();
        let mut part3_outlines: Vec<Vec<ObjectRef>> = Vec::new();
        // Second-half containers, grouped by part so they can be emitted in qpdf's
        // strict part order (part7, then part8, then part9 — QPDF_linearization.cc:1342).
        // qpdf's file layout writes lc_other_page_private, lc_other_page_shared, then
        // lc_other/lc_outlines; the even-split (DFS) order a container arrives in is
        // NOT that order (a DFS-early /Outlines container routes to part9 yet precedes
        // a part8 shared-font container in the split). Bucketing into three vectors and
        // concatenating them (like the part3 regular/outlines split below) reorders only
        // ACROSS parts, leaving within-part even-split arrival order intact.
        //
        // For part8 that within-part order is provably qpdf's: lc_other_page_shared
        // is a std::set keyed on container objgen, and a generate-mode container's
        // objgen comes from makeIndirectObject in even-split order — so set order ==
        // even-split order. part7 (page order) and part9 (pages-tree / outlines /
        // lc_other sub-order) only have one container each in the fixtures seen so
        // far, so their within-part multi-container order is untested (see flpdf-g1eu
        // follow-up); if such a case ever arises a finer per-part sort may be needed.
        let mut part4_private: Vec<RoutedObjStmBatch> = Vec::new();
        let mut part4_shared: Vec<RoutedObjStmBatch> = Vec::new();
        let mut part4_rest: Vec<RoutedObjStmBatch> = Vec::new();
        for (mut members, route) in containers.into_iter().zip(routes) {
            members.sort_unstable_by_key(|r| r.number);
            push_routed_objstm_batch(
                members,
                route,
                None,
                &mut open_document_batches,
                &mut part3_private,
                &mut part3_shared,
                &mut part3_outlines,
                &mut part4_private,
                &mut part4_shared,
                &mut part4_rest,
            );
        }
        // Concatenate the buckets in part order (part7, part8, part9).
        let mut part4_batches = part4_private;
        part4_batches.extend(part4_shared);
        part4_batches.extend(part4_rest);

        // qpdf part 6 order: private, shared, then outlines.
        let mut part3_batches = part3_private;
        part3_batches.extend(part3_shared);
        part3_batches.extend(part3_outlines);

        Ok(ObjStmBatchPlan {
            open_document_batches,
            part3_batches,
            part4_batches,
        })
    }

    /// Preserve mode: retain each surviving source ObjStm and route its member-user union.
    fn objstm_batches_preserve<R: Read + Seek>(
        &self,
        pdf: &mut Pdf<R>,
        _config: &PlannerConfig,
        ctx: &crate::writer::object_streams::EligibilityContext,
        length_exclusions: &BTreeSet<ObjectRef>,
        routing_users: &LinearizationRoutingUsers,
    ) -> crate::Result<ObjStmBatchPlan> {
        use crate::XrefOffset;

        let entries = pdf.source_xref_entries();

        // Build source ObjStm groups: container_number → [(index, ref)]
        let mut groups: BTreeMap<u32, Vec<(u32, ObjectRef)>> = BTreeMap::new();
        for (obj_ref, offset) in &entries {
            if let XrefOffset::Compressed { stream, index } = offset {
                groups.entry(*stream).or_default().push((*index, *obj_ref));
            }
        }

        let assigned = self.renumber_assigned_refs();
        let page_dicts: BTreeSet<ObjectRef> = crate::pages::page_refs(pdf)?.into_iter().collect();
        let catalog = self.root_ref;
        let mut containers: Vec<Vec<ObjectRef>> = Vec::new();
        let mut source_container_numbers: Vec<u32> = Vec::new();

        // Iterate containers in ascending source-container number and retain
        // their member-index order. qpdf erases page dictionaries and the
        // Catalog from the source mapping, but otherwise classifies the
        // surviving container as a unit.
        for (container_num, mut members) in groups {
            members.sort_by_key(|(idx, _)| *idx);
            let mut surviving = Vec::new();
            for (_idx, obj_ref) in members {
                if page_dicts.contains(&obj_ref) || Some(obj_ref) == catalog {
                    continue;
                }
                if length_exclusions.contains(&obj_ref) || !assigned.contains(&obj_ref) {
                    continue;
                }
                let eligible = {
                    let obj = pdf.resolve_borrowed(obj_ref)?;
                    is_eligible_for_objstm(obj_ref, obj, ctx)
                };
                if eligible && !crate::writer::object_streams::is_qpdf_signature_dict(pdf, obj_ref)?
                {
                    surviving.push(obj_ref);
                }
            }
            if !surviving.is_empty() {
                source_container_numbers.push(container_num);
                containers.push(surviving);
            }
        }

        let routes =
            route_objstm_containers(routing_users, &self.all_referenced_pages, &containers);
        let mut open_document_batches = Vec::new();
        let mut part3_private = Vec::new();
        let mut part3_shared = Vec::new();
        let mut part3_outlines = Vec::new();
        let mut part4_private = Vec::new();
        let mut part4_shared = Vec::new();
        let mut part4_rest = Vec::new();

        for ((members, route), source_container_number) in containers
            .into_iter()
            .zip(routes)
            .zip(source_container_numbers)
        {
            push_routed_objstm_batch(
                members,
                route,
                Some(source_container_number),
                &mut open_document_batches,
                &mut part3_private,
                &mut part3_shared,
                &mut part3_outlines,
                &mut part4_private,
                &mut part4_shared,
                &mut part4_rest,
            );
        }

        let mut part3_batches = part3_private;
        part3_batches.extend(part3_shared);
        part3_batches.extend(part3_outlines);
        let mut part4_batches = part4_private;
        part4_batches.extend(part4_shared);
        part4_batches.extend(part4_rest);

        Ok(ObjStmBatchPlan {
            open_document_batches,
            part3_batches,
            part4_batches,
        })
    }
}

// ---------------------------------------------------------------------------
// Linearized generate-mode ObjStm membership + container part routing
//
// These mirror qpdf 11.9.0's linearized `--object-streams=generate` pipeline:
//   * `objstm_membership_linearized` = `generateObjectStreams` (global even
//     split over `getCompressibleObjGens`) then the linearized erasure of every
//     page dictionary and the root Catalog (QPDFWriter.cc:2141-2161).
//   * `route_objstm_containers` = `filterCompressedObjects`
//     (QPDF_optimization.cc:340-380) folding each member's obj_users onto its
//     container, then `calculateLinearizationData`'s `lc_*` categorization
//     (QPDF_linearization.cc:963-1200) applied to the container's union.
// ---------------------------------------------------------------------------

/// Linearization part a generate-mode ObjStm container is routed to, by the
/// union of its members' object users.
///
/// `OpenDocument` is qpdf part 4 (open-document objects, first half), the three
/// `FirstPage*` variants are part 6 (first-page section),
/// `OtherPagePrivate` is part 7, `OtherPageShared` is part 8, and `Rest` is part
/// 9. qpdf checks outlines, open-document objects, and first-page objects in
/// that precedence order; [`route_objstm_containers`] retains it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ContainerPart {
    /// qpdf part 4 — the container holds at least one open-document object
    /// (reachable from the catalog's `/OpenAction`, `/AcroForm`,
    /// `/ViewerPreferences`, `/PageMode`, `/Threads`, or the trailer's
    /// `/Encrypt`). Takes precedence over every page category.
    OpenDocument,
    /// qpdf part 6 — every container member user is compatible with
    /// `lc_first_page_private`.
    FirstPagePrivate,
    /// qpdf part 6 — the container reaches the first page and also has a
    /// document-other, non-first-page, or thumbnail user.
    FirstPageShared,
    /// qpdf part 6 — an outline container when `/PageMode /UseOutlines`.
    FirstPageOutlines,
    /// qpdf part 7 — the container's members are private to exactly one
    /// non-first page.
    OtherPagePrivate,
    /// qpdf part 8 — the container's members are shared by two or more
    /// non-first pages.
    OtherPageShared,
    /// qpdf part 9 — the container reaches no page (trailer-only members).
    Rest,
}

/// One second-half ObjStm batch paired with qpdf's canonical container route.
///
/// Keeping the route beside the members prevents the writer from reclassifying
/// the container from per-object classic partitions after qpdf's member-user
/// union has already selected its part.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct RoutedObjStmBatch {
    pub(crate) members: Vec<ObjectRef>,
    pub(crate) route: ContainerPart,
    /// Original ObjStm object number in Preserve mode. Generate mode creates a
    /// fresh container after the source objects, so it uses `None`.
    pub(crate) source_container_number: Option<u32>,
}

#[allow(clippy::too_many_arguments)]
fn push_routed_objstm_batch(
    members: Vec<ObjectRef>,
    route: ContainerPart,
    source_container_number: Option<u32>,
    open_document_batches: &mut Vec<Vec<ObjectRef>>,
    part3_private: &mut Vec<Vec<ObjectRef>>,
    part3_shared: &mut Vec<Vec<ObjectRef>>,
    part3_outlines: &mut Vec<Vec<ObjectRef>>,
    part4_private: &mut Vec<RoutedObjStmBatch>,
    part4_shared: &mut Vec<RoutedObjStmBatch>,
    part4_rest: &mut Vec<RoutedObjStmBatch>,
) {
    match route {
        ContainerPart::OpenDocument => open_document_batches.push(members),
        ContainerPart::FirstPagePrivate => part3_private.push(members),
        ContainerPart::FirstPageShared => part3_shared.push(members),
        ContainerPart::FirstPageOutlines => part3_outlines.push(members),
        ContainerPart::OtherPagePrivate => part4_private.push(RoutedObjStmBatch {
            members,
            route,
            source_container_number,
        }),
        ContainerPart::OtherPageShared => part4_shared.push(RoutedObjStmBatch {
            members,
            route,
            source_container_number,
        }),
        ContainerPart::Rest => part4_rest.push(RoutedObjStmBatch {
            members,
            route,
            source_container_number,
        }),
    }
}

impl std::ops::Deref for RoutedObjStmBatch {
    type Target = [ObjectRef];

    fn deref(&self) -> &Self::Target {
        &self.members
    }
}

/// Compute the linearized generate-mode ObjStm membership.
///
/// Runs qpdf's `generateObjectStreams` even split
/// ([`compressible_objgens`](crate::writer::object_streams::compressible_objgens)
/// →
/// [`even_split_into_streams`](crate::writer::object_streams::even_split_into_streams),
/// hard-coded 100 per stream — *not* the planner cap) over the whole document,
/// then erases every page dictionary and the root Catalog from the resulting
/// containers (qpdf's linearized exclusion at QPDFWriter.cc:2141-2161; the
/// `/Pages` tree node and `/Info` dictionary are *not* erased — they stay ObjStm
/// members). Containers are returned in even-split order; each inner vector is
/// one container's surviving members in even-split (DFS) order. A container left
/// empty by the erasure is dropped.
///
/// `assigned` is the set of refs that receive a renumber slot
/// ([`LinearizationPlan::renumber_assigned_refs`]). A live, reachable object that
/// [`compressible_objgens`](crate::writer::object_streams::compressible_objgens)
/// admits but the linearization plan places in no part — a trailer-only object
/// with no slot — is dropped **before** the even split, so it cannot inflate the
/// split boundary and scatter real members across separate ObjStms. (Dangling /
/// missing refs are already excluded upstream by `compressible_objgens`, which
/// qpdf treats as null, so they never reach this retain.) The page dictionaries
/// and root Catalog are in `assigned`, so they still consume split positions and
/// are erased afterwards, exactly as qpdf does.
///
/// # Errors
///
/// Propagates reader errors from the compressible-set traversal or the page-tree
/// walk used to build the erase set.
pub(crate) fn objstm_membership_linearized<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    assigned: &BTreeSet<ObjectRef>,
) -> crate::Result<Vec<Vec<ObjectRef>>> {
    // qpdf's DFS already preserves the indirect identity of null-resolving
    // references reached from arrays. Do not append `resurrectable_null_refs`
    // here: that set remains a planner/all-refs aid, and appending it would give
    // array-null objects duplicate ObjStm membership.
    let mut eligible = crate::writer::object_streams::compressible_objgens(pdf)?;
    // Drop refs without a renumber slot before the split (see doc above).
    eligible.retain(|r| assigned.contains(r));
    let streams = crate::writer::object_streams::even_split_into_streams(&eligible);

    // Erase set: every page dictionary plus the root Catalog. qpdf cannot place
    // a page dict in an ObjStm (the linearization layout addresses pages by
    // file offset) and never compresses the Catalog in a linearized file.
    let mut erase: BTreeSet<ObjectRef> = crate::pages::page_refs(pdf)?.into_iter().collect();
    if let Some(root) = pdf.root_ref() {
        erase.insert(root);
    }

    Ok(streams
        .into_iter()
        .map(|stream| {
            stream
                .into_iter()
                .filter(|r| !erase.contains(r))
                .collect::<Vec<ObjectRef>>()
        })
        .filter(|container| !container.is_empty())
        .collect())
}

/// Catalog keys qpdf treats as `open_document_keys` in
/// `calculateLinearizationData` (QPDF_linearization.cc:1045-1050): a catalog
/// reference through one of these is `in_open_document`, while a reference
/// through any OTHER catalog key (except `/Outlines`) increments `others`.
/// Shared by [`open_document_set`] (which collects them) and
/// [`document_other_set`] (which collects the complement) so the partition
/// stays a single source of truth.
const OPEN_DOCUMENT_CATALOG_KEYS: [&[u8]; 5] = [
    b"ViewerPreferences",
    b"PageMode",
    b"Threads",
    b"OpenAction",
    b"AcroForm",
];

/// Compute the set of objects qpdf categorizes `in_open_document`.
///
/// Mirrors qpdf's `optimize()` open-document object users
/// (QPDF_optimization.cc:91-110) followed by the `open_document_keys` test in
/// `calculateLinearizationData` (QPDF_linearization.cc:1045-1097): every
/// indirect object reachable from the document catalog's `/ViewerPreferences`,
/// `/PageMode`, `/Threads`, `/OpenAction`, or `/AcroForm` entries, or from the
/// trailer's `/Encrypt` entry.
///
/// The traversal mirrors `updateObjectMapsInternal`
/// (QPDF_optimization.cc:271-337): it records every indirect object it reaches
/// but STOPS at a `/Page` leaf (a page boundary), so an `/OpenAction` destination
/// like `[page /Fit]` drops the page and keeps only the non-page objects. A
/// single shared `visited` set is sufficient because the result is the union
/// over all keys.
///
/// qpdf categorizes `in_open_document` with HIGHER precedence than
/// `in_first_page`, so [`route_objstm_containers`] tests this set before the
/// page categories.
///
/// # Errors
///
/// Propagates reader errors from resolving the catalog, the trailer values, or
/// any reached object.
#[cfg_attr(not(test), allow(dead_code))]
fn open_document_set<R: Read + Seek>(pdf: &mut Pdf<R>) -> crate::Result<BTreeSet<ObjectRef>> {
    let page_tree = page_tree_node_refs(pdf)?;
    open_document_set_with_context(pdf, &page_tree)
}

fn open_document_set_with_context<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    page_tree: &BTreeSet<ObjectRef>,
) -> crate::Result<BTreeSet<ObjectRef>> {
    // Seed refs: the indirect refs inside each open-document key's value, with
    // array-edge context. A ref that is an array ELEMENT of an OD key's value
    // (e.g. `/OpenAction [99 0 R]`) is resurrectable and must enter
    // open_document_set; a ref that is a dict-value (e.g. `/OpenAction 99 0 R`)
    // for an absent ref is dropped and must not. `collect_direct_refs_with_context`
    // records this distinction as the bool in each `(ObjectRef, bool)` pair so
    // `closure_from_seeds` can honour it.
    let mut seeds: Vec<(ObjectRef, bool)> = Vec::new();
    if let Some(enc) = pdf.trailer().get("Encrypt") {
        // cov:ignore-start: /Encrypt is only meaningful for encrypted+linearized
        // output (deferred to flpdf-j4ph); the linearize write path rejects
        // encrypted input (`reject_encrypted_write`) before this helper runs, so
        // it only ever sees plaintext documents (no trailer /Encrypt).
        collect_direct_refs_with_context(enc, 0, false, &mut seeds)?;
        // cov:ignore-end
    }
    // Resolve the catalog, propagating real read errors. `Pdf::open` guarantees
    // a `/Root`, so the `Option` is `Some` in practice; a `/Root` that resolves
    // to a non-dictionary (malformed) simply yields no open-document seeds.
    let catalog = pdf
        .root_ref()
        .map(|root| pdf.resolve_borrowed(root))
        .transpose()?;
    if let Some(Object::Dictionary(catalog)) = catalog {
        for key in OPEN_DOCUMENT_CATALOG_KEYS {
            if let Some(v) = catalog.get(key) {
                collect_direct_refs_with_context(v, 0, false, &mut seeds)?;
            }
        }
    }

    closure_from_seeds(pdf, seeds, page_tree)
}

/// Compute the set of objects qpdf categorizes with a non-zero `others` count:
/// objects reachable from a document-level reference that is neither an
/// open-document key, `/Outlines`, the page tree, nor the trailer `/Root` /
/// `/Encrypt`.
///
/// Mirrors qpdf's `optimize()` `ou_trailer_key` / `ou_root_key` users
/// (QPDF_optimization.cc:92-110) and the `++others` arms of
/// `calculateLinearizationData` (QPDF_linearization.cc:1077-1096): a catalog key
/// other than [`OPEN_DOCUMENT_CATALOG_KEYS`] and `/Outlines`, or a trailer key
/// other than `/Root` (`ou_root`) and `/Encrypt` (`in_open_document`),
/// increments `others`. A first-page object that also appears here is therefore
/// `lc_first_page_shared` (QPDF_linearization.cc:1124-1127), not
/// `lc_first_page_private`, and so sorts after the private objects in part 6.
///
/// `/Pages` IS seeded (qpdf records `ou_root_key("/Pages")` like any other root
/// key), so a first-page object reached via a custom extension key on a `/Pages`
/// node is correctly `others`. [`closure_from_seeds`] reproduces qpdf's
/// post-`pushInheritedAttributesToPage` tree by skipping the inherited
/// attributes on `/Pages` nodes, so the page tree's `/Resources` etc. do NOT
/// over-classify first-page resources. Cross-page sharing is still handled
/// separately by the per-page closures (`shared_page_indices`).
///
/// # Errors
///
/// Propagates reader errors from resolving the catalog, the trailer values, or
/// any reached object.
#[cfg_attr(not(test), allow(dead_code))]
fn document_other_set<R: Read + Seek>(pdf: &mut Pdf<R>) -> crate::Result<BTreeSet<ObjectRef>> {
    let page_tree = page_tree_node_refs(pdf)?;
    document_other_set_with_context(pdf, &page_tree)
}

fn document_other_set_with_context<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    page_tree: &BTreeSet<ObjectRef>,
) -> crate::Result<BTreeSet<ObjectRef>> {
    let mut seeds: Vec<(ObjectRef, bool)> = Vec::new();
    // Trailer keys except /Root (ou_root, the catalog) and /Encrypt
    // (in_open_document, already seeded by open_document_set).
    {
        let trailer = pdf.trailer();
        for (key, v) in trailer.iter() {
            if key != b"Root" && key != b"Encrypt" {
                collect_direct_refs_with_context(v, 0, false, &mut seeds)?;
            }
        }
    }
    // Catalog keys except the open-document keys (in_open_document) and
    // /Outlines (in_outlines). /Pages IS included: closure_from_seeds skips the
    // inherited attributes qpdf strips from /Pages nodes, so only genuine custom
    // keys on the page tree contribute `others`.
    let catalog = pdf
        .root_ref()
        .map(|root| pdf.resolve_borrowed(root))
        .transpose()?;
    if let Some(Object::Dictionary(catalog)) = catalog {
        for (key, v) in catalog.iter() {
            if !OPEN_DOCUMENT_CATALOG_KEYS.contains(&key) && key != b"Outlines" {
                collect_direct_refs_with_context(v, 0, false, &mut seeds)?;
            }
        }
    }

    closure_from_seeds(pdf, seeds, page_tree)
}

/// The inheritable page attributes (ISO 32000-1 Table 30) that qpdf's
/// `pushInheritedAttributesToPage` (QPDF_optimization.cc:165-205) removes from
/// interior `/Pages` nodes before the object-user maps are built.
/// [`closure_from_seeds`] skips them so an object reached ONLY through an
/// inherited attribute on a `/Pages` node is not recorded as a document-level
/// user (it would already be reached, post-push, from its `/Page` leaf instead).
const INHERITABLE_PAGE_KEYS: [&[u8]; 4] = [b"MediaBox", b"CropBox", b"Resources", b"Rotate"];

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum PageObjectUser {
    Page,
    Thumbnail,
}

/// Exact qpdf-style page and thumbnail users, indexed by page number.
///
/// `updateObjectMaps` starts with a fresh `visited` set for each page, walks
/// dictionary keys in lexical order, and switches the active user to
/// `ou_thumb` only while descending that page's `/Thumb` value. Both users share
/// the one `visited` set, so whichever edge reaches an indirect object first
/// owns it for that page.
#[derive(Debug, Default)]
struct PageObjectUsers {
    page: Vec<BTreeSet<ObjectRef>>,
    thumbnail: Vec<BTreeSet<ObjectRef>>,
}

impl PageObjectUsers {
    fn thumbnail_set(&self) -> BTreeSet<ObjectRef> {
        self.thumbnail
            .iter()
            .flat_map(|users| users.iter().copied())
            .collect()
    }
}

/// Clone the already-materialized leaf dictionary for ordered user traversal.
///
/// [`LinearizationPlan::from_pdf`] runs qpdf's real-`/Kids`-tree
/// `pushInheritedAttributesToPage` equivalent before this function. Following
/// the leaf's own `/Parent` here would trust a detached or bogus chain that qpdf
/// explicitly skips in `updateObjectMaps`.
fn page_dictionary_for_user_traversal<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    page_ref: ObjectRef,
) -> crate::Result<crate::Dictionary> {
    let Object::Dictionary(page) = pdf.resolve(page_ref)? else {
        // cov:ignore-start: page_refs runs immediately before page_object_users and only yields refs that resolve to dictionaries with /Type /Page; no mutation occurs between the two resolutions
        return Err(crate::Error::Unsupported(format!(
            "linearization plan: page {page_ref} is not a dictionary"
        )));
        // cov:ignore-end
    };
    Ok(page)
}

/// Reproduce qpdf 11.9.0's ordered per-page `updateObjectMaps` traversal.
///
/// Direct arrays and dictionaries are traversed in place, so indirect
/// descendants of a direct `/Thumb` value receive the thumbnail user. Indirect
/// references are the only visited nodes; direct containers do not erase the
/// active user. A non-top `/Page` is a boundary and is neither recorded nor
/// descended. Stream `/Length` is skipped because the linearized writer
/// directizes it before qpdf computes object users.
///
fn page_object_users<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    page_refs: &[ObjectRef],
) -> crate::Result<PageObjectUsers> {
    let mut result = PageObjectUsers {
        page: Vec::with_capacity(page_refs.len()),
        thumbnail: Vec::with_capacity(page_refs.len()),
    };

    for &page_ref in page_refs {
        let page_dict = page_dictionary_for_user_traversal(pdf, page_ref)?;
        let mut visited = BTreeSet::from([page_ref]);
        let mut page_users = BTreeSet::new();
        let mut thumbnail_users = BTreeSet::new();
        page_users.insert(page_ref);

        // (object, active user, top page, immediate array edge, inline depth)
        let mut stack = vec![(
            Object::Dictionary(page_dict),
            PageObjectUser::Page,
            true,
            false,
            0usize,
        )];
        while let Some((object, user, top, via_array, depth)) = stack.pop() {
            // cov:ignore-start: reachable_object_set runs before page_object_users in LinearizationPlan::from_pdf and rejects the same MAX_INLINE_DEPTH overflow, so parsed public inputs cannot reach this duplicate defensive bound
            if depth > MAX_INLINE_DEPTH {
                return Err(crate::Error::Unsupported(format!(
                    "linearization plan: inline object nesting exceeds maximum of {MAX_INLINE_DEPTH}"
                )));
            }
            // cov:ignore-end

            match object {
                Object::Reference(object_ref) => {
                    let users = match user {
                        PageObjectUser::Page => &mut page_users,
                        PageObjectUser::Thumbnail => &mut thumbnail_users,
                    };
                    if crate::qpdf_null::value_is_null(pdf, &Object::Reference(object_ref))? {
                        // qpdf's dictionary getKeys() hides null-resolving
                        // values, while arrays preserve an indirect null's
                        // identity as an object user. Indirect identity still
                        // enters the per-page shared visited set before user
                        // registration, so `/Thumb` versus ordinary page
                        // traversal remains first-edge-wins for nulls too.
                        if !visited.insert(object_ref) {
                            continue;
                        }
                        if via_array && object_ref.number > 0 {
                            users.insert(object_ref);
                        }
                        continue;
                    }
                    let resolved = pdf.resolve(object_ref)?;
                    let is_page = matches!(&resolved, Object::Dictionary(dict)
                        if matches!(dict.get("Type"), Some(Object::Name(name))
                            if name.as_slice() == b"Page"));
                    if is_page && !top {
                        continue;
                    }
                    if !visited.insert(object_ref) {
                        continue;
                    }

                    users.insert(object_ref);
                    stack.push((resolved, user, top, false, 0));
                }
                Object::Array(items) => {
                    for item in items.into_iter().rev() {
                        stack.push((item, user, false, true, depth + 1));
                    }
                }
                Object::Dictionary(dict) => {
                    let is_page = matches!(dict.get("Type"), Some(Object::Name(name))
                        if name.as_slice() == b"Page");
                    if is_page && !top {
                        continue;
                    }
                    let mut children = Vec::new();
                    let entries = crate::qpdf_null::snapshot_entries(&dict, false);
                    for (key, value) in crate::qpdf_null::visible_entries(pdf, entries)? {
                        if is_page && key == b"Parent" {
                            continue;
                        }
                        let child_user = if is_page && key == b"Thumb" {
                            PageObjectUser::Thumbnail
                        } else {
                            user
                        };
                        children.push((value, child_user));
                    }
                    for (value, child_user) in children.into_iter().rev() {
                        stack.push((value, child_user, false, false, depth + 1));
                    }
                }
                Object::Stream(stream) => {
                    let mut children = Vec::new();
                    let entries = crate::qpdf_null::snapshot_entries(&stream.dict, true);
                    for (_key, value) in crate::qpdf_null::visible_entries(pdf, entries)? {
                        children.push(value);
                    }
                    for value in children.into_iter().rev() {
                        stack.push((value, user, false, false, depth + 1));
                    }
                }
                Object::Null
                | Object::Boolean(_)
                | Object::Integer(_)
                | Object::Real(_)
                | Object::RealLiteral { .. }
                | Object::Name(_)
                | Object::String(_) => {}
            }
        }
        result.page.push(page_users);
        result.thumbnail.push(thumbnail_users);
    }

    Ok(result)
}

/// The indirect refs of the interior `/Type /Pages` nodes of the catalog's
/// actual page tree (reachable from `/Root` → `/Pages` → `/Kids`).
///
/// qpdf's `pushInheritedAttributesToPage` (QPDF_optimization.cc:159-235) strips
/// inheritable attributes from EXACTLY these nodes — it walks only `/Root`
/// `/Pages` — so [`closure_from_seeds`] must restrict its inherited-key skip to
/// this set. An unrelated `/Type /Pages` dictionary reached from some other
/// document-level structure is left intact by qpdf and so must be descended in
/// full (including its `/Resources`). The traversal is iterative and bounded by
/// `visited`, so a cyclic or adversarial `/Kids` graph terminates.
///
/// # Errors
///
/// Propagates reader errors from resolving the catalog or a page-tree node.
fn page_tree_node_refs<R: Read + Seek>(pdf: &mut Pdf<R>) -> crate::Result<BTreeSet<ObjectRef>> {
    let mut out: BTreeSet<ObjectRef> = BTreeSet::new();
    let pages_ref = match pdf
        .root_ref()
        .map(|root| pdf.resolve_borrowed(root))
        .transpose()?
    {
        Some(Object::Dictionary(d)) => d.get_ref("Pages"),
        _ => None,
    };
    let Some(pages_ref) = pages_ref else {
        return Ok(out);
    };
    let mut visited: BTreeSet<ObjectRef> = BTreeSet::new();
    let mut queue: VecDeque<ObjectRef> = VecDeque::new();
    queue.push_back(pages_ref);
    while let Some(r) = queue.pop_front() {
        if !visited.insert(r) {
            continue;
        }
        let Object::Dictionary(d) = pdf.resolve_borrowed(r)? else {
            continue;
        };
        // Only interior `/Pages` nodes are stripped; a `/Page` leaf (or any
        // non-`/Pages` dict reached via a malformed `/Kids`) is not collected.
        if !matches!(d.get("Type"), Some(Object::Name(n)) if n.as_slice() == b"Pages") {
            continue;
        }
        out.insert(r);
        if let Some(kids) = d.get("Kids") {
            let mut kid_refs = Vec::new();
            collect_direct_refs(kids, 0, &mut kid_refs)?;
            for kr in kid_refs {
                if !visited.contains(&kr) {
                    queue.push_back(kr);
                }
            }
        }
    }
    Ok(out)
}

/// Transitive closure of indirect objects reachable from `seeds`, stopping at
/// `/Page` leaves and skipping inherited attributes on page-tree `/Pages` nodes.
///
/// Mirrors qpdf's `updateObjectMapsInternal` (QPDF_optimization.cc:271-337) used
/// to record a document-level key's object users, run on the tree AFTER
/// `pushInheritedAttributesToPage` (QPDFWriter calls `optimize(allow_changes=true)`):
/// it records every indirect object it reaches but
/// - neither records nor descends a non-top `/Page` leaf (a page boundary), so a
///   destination like `[page /Fit]` drops the page; and
/// - on an interior `/Pages` node THAT IS IN THE PAGE TREE (`page_tree`), skips
///   the [`INHERITABLE_PAGE_KEYS`] (which qpdf has stripped) while still
///   following `/Kids` and any custom keys, so a first-page resource reached only
///   via an inherited `/Resources` on a page-tree node is NOT mistaken for a
///   document-level user, whereas a genuine custom extension key on such a node
///   still is. An unrelated `/Type /Pages` dict outside `page_tree` is descended
///   in full (qpdf does not strip it).
///
/// `page_tree` is [`page_tree_node_refs`]. A single shared `visited` set suffices
/// because the result is the union over all seeds.
///
/// # Errors
///
/// Propagates reader errors from resolving any reached object.
fn closure_from_seeds<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    seeds: Vec<(ObjectRef, bool)>,
    page_tree: &BTreeSet<ObjectRef>,
) -> crate::Result<BTreeSet<ObjectRef>> {
    let mut visited: BTreeSet<ObjectRef> = BTreeSet::new();
    let mut out: BTreeSet<ObjectRef> = BTreeSet::new();
    let mut queue: VecDeque<(ObjectRef, bool)> = seeds.into();
    while let Some((r, via_array)) = queue.pop_front() {
        if crate::qpdf_null::value_is_null(pdf, &Object::Reference(r))? {
            // qpdf dictionary keys whose values resolve to null are absent.
            // Arrays preserve the indirect identity as an object user.
            if via_array && r.number > 0 {
                out.insert(r);
            }
            continue;
        }
        if !visited.insert(r) {
            continue;
        }
        let obj = pdf.resolve(r)?;
        let mut children: Vec<(ObjectRef, bool)> = Vec::new();
        match &obj {
            // Page boundary: qpdf neither records nor descends a non-top `/Page`
            // leaf reached while tracing a document-level key.
            Object::Dictionary(d) if matches!(d.get("Type"), Some(Object::Name(n)) if n.as_slice() == b"Page") =>
            {
                continue;
            }
            // Page-tree interior `/Pages` node: skip the inherited attributes
            // qpdf has stripped, but follow `/Kids` (→ the `/Page` leaves above)
            // and any custom extension keys. Restricted to `page_tree` — a
            // `/Type /Pages` dict outside the real page tree is NOT stripped by
            // qpdf, so it falls through to the `_` arm and is descended in full.
            Object::Dictionary(d) if page_tree.contains(&r) => {
                for (k, v) in d.iter() {
                    if !INHERITABLE_PAGE_KEYS.contains(&k) {
                        collect_direct_refs_with_context(v, 0, false, &mut children)?;
                    }
                }
            }
            _ => collect_direct_refs_with_context(&obj, 0, false, &mut children)?,
        }
        out.insert(r);
        for (cr, via_array) in children {
            if !visited.contains(&cr) {
                queue.push_back((cr, via_array));
            }
        }
    }
    Ok(out)
}

/// Compute the set of objects qpdf categorizes `in_outlines`.
///
/// Mirrors qpdf's `optimize()` ou_root_key "/Outlines" users
/// (QPDF_optimization.cc:103-110) and the `in_outlines` test in
/// `calculateLinearizationData` (QPDF_linearization.cc:1092-1093): every indirect
/// object reachable from the document catalog's `/Outlines` entry, with the same
/// `/Page`-boundary traversal as [`open_document_set`].
///
/// qpdf categorizes `in_outlines` with HIGHER precedence than both
/// `in_open_document` and `in_first_page` (QPDF_linearization.cc:1118-1122).
///
/// # Errors
///
/// Propagates reader errors from resolving the catalog or any reached object.
pub(crate) fn outlines_set<R: Read + Seek>(pdf: &mut Pdf<R>) -> crate::Result<BTreeSet<ObjectRef>> {
    let page_tree = page_tree_node_refs(pdf)?;
    outlines_set_with_context(pdf, &page_tree)
}

fn outlines_set_with_context<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    page_tree: &BTreeSet<ObjectRef>,
) -> crate::Result<BTreeSet<ObjectRef>> {
    let mut seeds: Vec<(ObjectRef, bool)> = Vec::new();
    let catalog = pdf
        .root_ref()
        .map(|root| pdf.resolve_borrowed(root))
        .transpose()?;
    if let Some(Object::Dictionary(catalog)) = catalog {
        if let Some(v) = catalog.get("Outlines") {
            collect_direct_refs_with_context(v, 0, false, &mut seeds)?;
        }
    }
    closure_from_seeds(pdf, seeds, page_tree)
}

/// Returns `true` when the catalog specifies `/PageMode /UseOutlines` AND has
/// an `/Outlines` entry (QPDF_linearization.cc:1031-1043).
///
/// When `true`, outline objects are routed to the first-page section (part6)
/// rather than part9 by [`route_objstm_containers`].
fn outlines_in_first_page_predicate<R: Read + Seek>(pdf: &mut Pdf<R>) -> crate::Result<bool> {
    let Some(root) = pdf.root_ref() else {
        return Ok(false); // cov:ignore: root_ref None ⇒ from_pdf fails earlier via catalog()?
    };
    let Object::Dictionary(cat) = pdf.resolve(root)? else {
        return Ok(false); // cov:ignore: non-dictionary catalog unreachable on valid linearizable PDF
    };
    if cat.get("Outlines").is_none() {
        return Ok(false);
    }
    match cat.get("PageMode") {
        Some(Object::Name(n)) => Ok(n == b"UseOutlines"),
        // cov:ignore-start: /PageMode as indirect reference; structurally identical to
        // the direct-name arm; exercising requires a dedicated fixture with indirect PageMode
        Some(Object::Reference(r)) => {
            let r = *r;
            Ok(matches!(pdf.resolve(r)?, Object::Name(n) if n == b"UseOutlines"))
        }
        // cov:ignore-end
        _ => Ok(false),
    }
}

/// Route each ObjStm container to a linearization part by the union of its
/// members' object users.
///
/// Mirrors qpdf's `filterCompressedObjects` (the container inherits the union of
/// every member's obj_users) followed by the `lc_*` categorization. In qpdf's
/// precedence order: a container holding any outline object is part 6
/// ([`ContainerPart::FirstPageOutlines`]) when `/PageMode /UseOutlines` is set,
/// or part 9 ([`ContainerPart::Rest`]) otherwise; a container holding any
/// [`open_document_set`] object is part 4 ([`ContainerPart::OpenDocument`]).
/// A remaining container holding a first-page object is private only when its
/// union has no non-first-page, document-other, or thumbnail user; otherwise it
/// is shared. Containers without a first-page object route to part 7 / part 8 /
/// part 9 by the number of *distinct non-first* pages their members reach (one →
/// [`ContainerPart::OtherPagePrivate`], two or more →
/// [`ContainerPart::OtherPageShared`], none → [`ContainerPart::Rest`]). The
/// one-page case is part 7 ONLY when the member union has neither a
/// document-level `others` object nor a thumbnail user
/// (QPDF_linearization.cc:1128 gates lc_other_page_private on `others==0` and
/// `thumbs==0`); either signal demotes it to part 9
/// ([`ContainerPart::Rest`]). The two-or-more case is part 8 regardless of
/// `others` or thumbnails (QPDF_linearization.cc:1130).
///
/// The retained routing snapshot comes from [`LinearizationPlan::from_pdf`].
/// This classifier does not resolve objects or read the PDF.
///
/// # Deviation
///
/// **Multiple open-document containers (verified, flpdf-699x):** qpdf assigns
/// container `ObjGen`s sequentially in even-split order, so its
/// `std::set<QPDFObjGen>` (used for `lc_open_document`) iterates them in the
/// same DFS / even-split order that this function preserves.  The ordering is
/// therefore byte-identical to qpdf for ≥2 open-document containers; verified
/// with `objstm-lin-openaction-multi-od` (two OD containers whose min-member
/// numbers are non-ascending in DFS order).
///
pub(crate) fn route_objstm_containers(
    users: &LinearizationRoutingUsers,
    referenced_pages: &BTreeMap<ObjectRef, BTreeSet<u32>>,
    containers: &[Vec<ObjectRef>],
) -> Vec<ContainerPart> {
    // in_outlines takes precedence over in_open_document and in_first_page
    // (QPDF_linearization.cc:1118-1122).
    containers
        .iter()
        .map(|members| {
            // in_outlines is checked first (QPDF_linearization.cc:1118-1122).
            if members.iter().any(|m| users.outlines.contains(m)) {
                return if users.outlines_in_first_page {
                    ContainerPart::FirstPageOutlines
                } else {
                    ContainerPart::Rest
                };
            }
            // in_open_document takes precedence over every page category.
            if members.iter().any(|m| users.open_document.contains(m)) {
                return ContainerPart::OpenDocument;
            }
            if members.iter().any(|m| users.first_page.contains(m)) {
                let has_other_page = members.iter().any(|member| {
                    referenced_pages
                        .get(member)
                        .is_some_and(|pages| pages.iter().any(|&page| page != 0))
                });
                let has_document_other = members.iter().any(|m| users.document_other.contains(m));
                let has_thumbnail = members.iter().any(|m| users.thumbnails.contains(m));
                return if has_other_page || has_document_other || has_thumbnail {
                    ContainerPart::FirstPageShared
                } else {
                    ContainerPart::FirstPagePrivate
                };
            }
            let mut other_pages: BTreeSet<u32> = BTreeSet::new();
            for m in members {
                if let Some(pages) = referenced_pages.get(m) {
                    other_pages.extend(pages.iter().copied().filter(|&p| p != 0));
                }
            }
            match other_pages.len() {
                0 => ContainerPart::Rest,
                // other_pages==1 is lc_other_page_private (part7) ONLY when the
                // union has others==0 (QPDF_linearization.cc:1128). A member in
                // `document_other_set` makes others>0, so the container is
                // lc_other (part9) instead (flpdf-zda0 gate, generate path).
                1 if members
                    .iter()
                    .any(|m| users.document_other.contains(m) || users.thumbnails.contains(m)) =>
                {
                    ContainerPart::Rest
                }
                1 => ContainerPart::OtherPagePrivate,
                // other_pages>1 is lc_other_page_shared (part8) regardless of
                // others (QPDF_linearization.cc:1130), so no gate here.
                _ => ContainerPart::OtherPageShared,
            }
        })
        .collect()
}

// ---------------------------------------------------------------------------
// Unit tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::object::MAX_INLINE_DEPTH;
    use std::io::Cursor;

    fn route_with_plan(
        plan: &LinearizationPlan,
        containers: &[Vec<ObjectRef>],
    ) -> Vec<ContainerPart> {
        route_objstm_containers(
            plan.routing_users
                .as_ref()
                .expect("test plan must have routing users"),
            &plan.all_referenced_pages,
            containers,
        )
    }

    #[test]
    fn null_visible_generate_container_routes_to_rest() {
        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("../../tests/fixtures/compat/null-visible-matrix.pdf");
        let mut pdf =
            Pdf::open(std::io::BufReader::new(std::fs::File::open(path).unwrap())).unwrap();
        let plan = LinearizationPlan::from_pdf(&mut pdf, true).unwrap();
        let assigned = plan.renumber_assigned_refs();
        let containers = objstm_membership_linearized(&mut pdf, &assigned).unwrap();
        let routes = route_with_plan(&plan, &containers);
        let users = plan.routing_users.as_ref().unwrap();

        assert_eq!(
            routes,
            vec![ContainerPart::Rest],
            "containers={containers:?}, first_page={:?}, document_other={:?}, pages={:?}",
            users.first_page,
            users.document_other,
            plan.all_referenced_pages,
        );
    }

    // -----------------------------------------------------------------------
    // Inline-depth guard
    // -----------------------------------------------------------------------

    fn nested_arrays(depth: usize) -> Object {
        let mut o = Object::Null;
        for _ in 0..depth {
            o = Object::Array(vec![o]);
        }
        o
    }

    #[test]
    fn collect_direct_refs_errors_on_excessive_nesting() {
        let mut out = Vec::new();
        let err = collect_direct_refs(&nested_arrays(MAX_INLINE_DEPTH + 5), 0, &mut out);
        assert!(matches!(err, Err(crate::Error::Unsupported(_))));
    }

    #[test]
    fn collect_direct_refs_accepts_nesting_up_to_the_limit() {
        let mut out = Vec::new();
        // Bury one Reference so it is visited at exactly inline depth
        // MAX_INLINE_DEPTH (the deepest accepted level under the strict `>`
        // guard); it must be collected, not errored.
        let mut o = Object::Array(vec![Object::Reference(ObjectRef::new(4, 0))]);
        for _ in 0..(MAX_INLINE_DEPTH - 1) {
            o = Object::Array(vec![o]);
        }
        collect_direct_refs(&o, 0, &mut out).unwrap();
        assert_eq!(out, vec![ObjectRef::new(4, 0)]);
    }

    #[test]
    fn collect_direct_refs_with_context_errors_on_excessive_nesting() {
        let mut out = Vec::new();
        let err = collect_direct_refs_with_context(
            &nested_arrays(MAX_INLINE_DEPTH + 5),
            0,
            false,
            &mut out,
        );
        assert!(matches!(err, Err(crate::Error::Unsupported(_))));
    }

    // -----------------------------------------------------------------------
    // Fixture builders
    // -----------------------------------------------------------------------

    /// Build a minimal single-page PDF in memory.
    ///
    /// Object layout:
    ///   1 0 obj – Catalog   (/Root)
    ///   2 0 obj – Pages node
    ///   3 0 obj – Page dict  (Kids[0])
    fn tiny_pdf_bytes() -> Vec<u8> {
        let mut pdf = Vec::new();
        pdf.extend_from_slice(b"%PDF-1.4\n");

        // Object 1: Catalog
        let off1 = pdf.len() as u64;
        pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");

        // Object 2: Pages
        let off2 = pdf.len() as u64;
        pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n");

        // Object 3: Page
        let off3 = pdf.len() as u64;
        pdf.extend_from_slice(
            b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>\nendobj\n",
        );

        // xref table
        let xref_start = pdf.len() as u64;
        let xref_section = format!(
            "xref\n0 4\n0000000000 65535 f \n{:010} 00000 n \n{:010} 00000 n \n{:010} 00000 n \n",
            off1, off2, off3,
        );
        pdf.extend_from_slice(xref_section.as_bytes());

        // Trailer
        let trailer = format!(
            "trailer\n<< /Size 4 /Root 1 0 R >>\nstartxref\n{}\n%%EOF\n",
            xref_start,
        );
        pdf.extend_from_slice(trailer.as_bytes());

        pdf
    }

    fn open_tiny_pdf() -> Pdf<Cursor<Vec<u8>>> {
        let bytes = tiny_pdf_bytes();
        Pdf::open(Cursor::new(bytes)).expect("tiny PDF should parse")
    }

    /// Build a two-page PDF with a shared font.
    ///
    /// Object layout:
    ///   1 0 obj – Catalog
    ///   2 0 obj – Pages node  (Kids: [3 0 R, 4 0 R])
    ///   3 0 obj – Page 1 dict  → references 5 0 R (Resources), 6 0 R (Contents)
    ///   4 0 obj – Page 2 dict  → references 5 0 R (Resources), 7 0 R (Contents)
    ///   5 0 obj – Resources dict  → /Font << /F1 8 0 R >>
    ///   6 0 obj – Content stream (page 1 only)
    ///   7 0 obj – Content stream (page 2 only)
    ///   8 0 obj – Font dict (shared by both pages via Resources)
    fn two_page_shared_font_bytes() -> Vec<u8> {
        let mut pdf = Vec::new();
        pdf.extend_from_slice(b"%PDF-1.4\n");

        let off1 = pdf.len() as u64;
        pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");

        let off2 = pdf.len() as u64;
        pdf.extend_from_slice(
            b"2 0 obj\n<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>\nendobj\n",
        );

        let off3 = pdf.len() as u64;
        pdf.extend_from_slice(b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources 5 0 R /Contents 6 0 R >>\nendobj\n");

        let off4 = pdf.len() as u64;
        pdf.extend_from_slice(b"4 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources 5 0 R /Contents 7 0 R >>\nendobj\n");

        // Shared resources (font dict)
        let off5 = pdf.len() as u64;
        pdf.extend_from_slice(b"5 0 obj\n<< /Font << /F1 8 0 R >> >>\nendobj\n");

        // Page 1 content stream
        let off6 = pdf.len() as u64;
        pdf.extend_from_slice(b"6 0 obj\n<< /Length 5 >>\nstream\nBT ET\nendstream\nendobj\n");

        // Page 2 content stream
        let off7 = pdf.len() as u64;
        pdf.extend_from_slice(b"7 0 obj\n<< /Length 5 >>\nstream\nBT ET\nendstream\nendobj\n");

        // Font (shared)
        let off8 = pdf.len() as u64;
        pdf.extend_from_slice(
            b"8 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>\nendobj\n",
        );

        let xref_start = pdf.len() as u64;
        let xref_section = format!(
            "xref\n0 9\n\
            0000000000 65535 f \n\
            {:010} 00000 n \n\
            {:010} 00000 n \n\
            {:010} 00000 n \n\
            {:010} 00000 n \n\
            {:010} 00000 n \n\
            {:010} 00000 n \n\
            {:010} 00000 n \n\
            {:010} 00000 n \n",
            off1, off2, off3, off4, off5, off6, off7, off8,
        );
        pdf.extend_from_slice(xref_section.as_bytes());

        let trailer = format!(
            "trailer\n<< /Size 9 /Root 1 0 R >>\nstartxref\n{}\n%%EOF\n",
            xref_start,
        );
        pdf.extend_from_slice(trailer.as_bytes());

        pdf
    }

    fn open_two_page_shared_font() -> Pdf<Cursor<Vec<u8>>> {
        let bytes = two_page_shared_font_bytes();
        Pdf::open(Cursor::new(bytes)).expect("two-page PDF should parse")
    }

    /// Build a two-page PDF whose shared font is ALSO referenced by an outline
    /// item (via a non-standard `/Extra` key), reproducing flpdf-q2zw in miniature.
    /// With `use_outlines`, the catalog also sets `/PageMode /UseOutlines` so the
    /// outline section routes to part6 (first half) instead of part9.
    ///
    /// Object layout (extends [`two_page_shared_font_bytes`]):
    ///   1 0 obj – Catalog  (/Pages 2 0 R, /Outlines 9 0 R [, /PageMode /UseOutlines])
    ///   2 0 obj – Pages node  (Kids: [3 0 R, 4 0 R])
    ///   3 0 obj – Page 1  → /Resources 5 0 R, /Contents 6 0 R
    ///   4 0 obj – Page 2  → /Resources 5 0 R, /Contents 7 0 R
    ///   5 0 obj – Resources  → /Font << /F1 8 0 R >>
    ///   6 0 obj – Content stream (page 1 only)
    ///   7 0 obj – Content stream (page 2 only)
    ///   8 0 obj – Font  (shared by both pages AND reached from the outline)
    ///   9 0 obj – Outlines dict  (/First 10 0 R, /Last 10 0 R)
    ///  10 0 obj – Outline item  (/Extra 8 0 R → the font)
    fn two_page_shared_font_outline_ref_bytes(use_outlines: bool) -> Vec<u8> {
        let mut pdf = Vec::new();
        pdf.extend_from_slice(b"%PDF-1.4\n");

        let off1 = pdf.len() as u64;
        if use_outlines {
            pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R /Outlines 9 0 R /PageMode /UseOutlines >>\nendobj\n");
        } else {
            pdf.extend_from_slice(
                b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R /Outlines 9 0 R >>\nendobj\n",
            );
        }

        let off2 = pdf.len() as u64;
        pdf.extend_from_slice(
            b"2 0 obj\n<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>\nendobj\n",
        );

        let off3 = pdf.len() as u64;
        pdf.extend_from_slice(b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources 5 0 R /Contents 6 0 R >>\nendobj\n");

        let off4 = pdf.len() as u64;
        pdf.extend_from_slice(b"4 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources 5 0 R /Contents 7 0 R >>\nendobj\n");

        let off5 = pdf.len() as u64;
        pdf.extend_from_slice(b"5 0 obj\n<< /Font << /F1 8 0 R >> >>\nendobj\n");

        let off6 = pdf.len() as u64;
        pdf.extend_from_slice(b"6 0 obj\n<< /Length 5 >>\nstream\nBT ET\nendstream\nendobj\n");

        let off7 = pdf.len() as u64;
        pdf.extend_from_slice(b"7 0 obj\n<< /Length 5 >>\nstream\nBT ET\nendstream\nendobj\n");

        let off8 = pdf.len() as u64;
        pdf.extend_from_slice(
            b"8 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>\nendobj\n",
        );

        let off9 = pdf.len() as u64;
        pdf.extend_from_slice(
            b"9 0 obj\n<< /Type /Outlines /First 10 0 R /Last 10 0 R /Count 1 >>\nendobj\n",
        );

        let off10 = pdf.len() as u64;
        pdf.extend_from_slice(
            b"10 0 obj\n<< /Title (Item) /Parent 9 0 R /Extra 8 0 R >>\nendobj\n",
        );

        let xref_start = pdf.len() as u64;
        let xref_section = format!(
            "xref\n0 11\n\
            0000000000 65535 f \n\
            {off1:010} 00000 n \n\
            {off2:010} 00000 n \n\
            {off3:010} 00000 n \n\
            {off4:010} 00000 n \n\
            {off5:010} 00000 n \n\
            {off6:010} 00000 n \n\
            {off7:010} 00000 n \n\
            {off8:010} 00000 n \n\
            {off9:010} 00000 n \n\
            {off10:010} 00000 n \n",
        );
        pdf.extend_from_slice(xref_section.as_bytes());

        let trailer =
            format!("trailer\n<< /Size 11 /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n",);
        pdf.extend_from_slice(trailer.as_bytes());

        pdf
    }

    fn open_two_page_shared_font_outline_ref() -> Pdf<Cursor<Vec<u8>>> {
        let bytes = two_page_shared_font_outline_ref_bytes(false);
        Pdf::open(Cursor::new(bytes)).expect("two-page outline-ref PDF should parse")
    }

    fn open_two_page_shared_font_outline_ref_use_outlines() -> Pdf<Cursor<Vec<u8>>> {
        let bytes = two_page_shared_font_outline_ref_bytes(true);
        Pdf::open(Cursor::new(bytes)).expect("two-page UseOutlines outline-ref PDF should parse")
    }

    /// Build a PDF where the page's Resources dictionary references objects in
    /// a cycle: A → B → A (both are XObject-style objects hanging off /Resources).
    ///
    /// Object layout:
    ///   1 0 obj – Catalog
    ///   2 0 obj – Pages node
    ///   3 0 obj – Page dict  → /Resources 4 0 R
    ///   4 0 obj – Resources  → /XObject << /ImA 5 0 R >>
    ///   5 0 obj – XObject A  → /SomeRef 6 0 R
    ///   6 0 obj – XObject B  → /SomeRef 5 0 R   (cycle: B → A)
    fn cycle_pdf_bytes() -> Vec<u8> {
        let mut pdf = Vec::new();
        pdf.extend_from_slice(b"%PDF-1.4\n");

        let off1 = pdf.len() as u64;
        pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");

        let off2 = pdf.len() as u64;
        pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n");

        let off3 = pdf.len() as u64;
        pdf.extend_from_slice(
            b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources 4 0 R >>\nendobj\n",
        );

        let off4 = pdf.len() as u64;
        pdf.extend_from_slice(b"4 0 obj\n<< /XObject << /ImA 5 0 R >> >>\nendobj\n");

        // XObject A -> references B
        let off5 = pdf.len() as u64;
        pdf.extend_from_slice(b"5 0 obj\n<< /SomeRef 6 0 R >>\nendobj\n");

        // XObject B -> references A (cycle)
        let off6 = pdf.len() as u64;
        pdf.extend_from_slice(b"6 0 obj\n<< /SomeRef 5 0 R >>\nendobj\n");

        let xref_start = pdf.len() as u64;
        let xref_section = format!(
            "xref\n0 7\n\
            0000000000 65535 f \n\
            {:010} 00000 n \n\
            {:010} 00000 n \n\
            {:010} 00000 n \n\
            {:010} 00000 n \n\
            {:010} 00000 n \n\
            {:010} 00000 n \n",
            off1, off2, off3, off4, off5, off6,
        );
        pdf.extend_from_slice(xref_section.as_bytes());

        let trailer = format!(
            "trailer\n<< /Size 7 /Root 1 0 R >>\nstartxref\n{}\n%%EOF\n",
            xref_start,
        );
        pdf.extend_from_slice(trailer.as_bytes());

        pdf
    }

    fn open_cycle_pdf() -> Pdf<Cursor<Vec<u8>>> {
        let bytes = cycle_pdf_bytes();
        Pdf::open(Cursor::new(bytes)).expect("cycle PDF should parse")
    }

    // -----------------------------------------------------------------------
    // 1. from_pdf does not panic on a well-formed document
    // -----------------------------------------------------------------------
    #[test]
    fn from_pdf_does_not_panic() {
        let mut pdf = open_tiny_pdf();
        let plan =
            LinearizationPlan::from_pdf(&mut pdf, false).expect("plan construction must succeed");
        assert!(plan.total_object_count > 0);
    }

    // -----------------------------------------------------------------------
    // 2. Struct fields have expected types / accessors
    // -----------------------------------------------------------------------
    #[test]
    fn plan_fields_accessible() {
        let mut pdf = open_tiny_pdf();
        let plan = LinearizationPlan::from_pdf(&mut pdf, false).unwrap();

        // root_ref should be Some(1 0 R)
        assert_eq!(plan.root_ref, Some(ObjectRef::new(1, 0)));

        // page_hints should have exactly 1 entry
        assert_eq!(plan.page_hints.len(), 1);
        assert_eq!(plan.page_hints[0].page_ref, ObjectRef::new(3, 0));
        assert_eq!(plan.page_hints[0].first_object_index, 0);
        assert_eq!(plan.page_hints[0].byte_length, 0); // placeholder
    }

    // -----------------------------------------------------------------------
    // 3. Single-page fixture: Part 2 non-empty, Part 3 empty
    // -----------------------------------------------------------------------
    #[test]
    fn single_page_part2_non_empty_part3_empty() {
        let mut pdf = open_tiny_pdf();
        let plan = LinearizationPlan::from_pdf(&mut pdf, false).unwrap();

        // Part 2 must contain the page dict (object 3) and the Pages node
        // (reached via /Parent).
        assert!(
            !plan.part2_objects.is_empty(),
            "Part 2 must contain first-page objects"
        );

        // With a single page, nothing is shared → Part 3 must be empty.
        assert!(
            plan.part3_objects.is_empty(),
            "Part 3 must be empty for a single-page document"
        );

        // The page object (3 0 R) must be in Part 2.
        let page_ref = ObjectRef::new(3, 0);
        assert!(
            plan.part2_objects.contains(&page_ref),
            "page dict must be in Part 2"
        );

        // Part 1 stays empty (populated by a later subtask).
        assert!(plan.part1_objects.is_empty());

        // qpdf always populates shared_hints with all first-page section
        // objects (Part 2 + Part 3), even for single-page PDFs.
        // shared_hints = part2_objects (Part 3 is empty for single-page).
        assert_eq!(
            plan.shared_hints.len(),
            plan.part2_objects.len(),
            "shared_hints must contain all part2 objects for single-page PDF"
        );
        for hint in &plan.shared_hints {
            assert!(
                plan.part2_objects.contains(&hint.object_ref),
                "single-page shared_hint {:?} must be a Part-2 object",
                hint.object_ref
            );
            assert!(
                hint.referencing_pages.is_empty(),
                "Part-2 shared hint must have empty referencing_pages (page 0 owns by layout)"
            );
        }
    }

    /// One-page PDF whose Catalog references a first-page object (the Font, obj
    /// 5) via a non-open-document key (/Ref2), mirroring the
    /// `catalog-firstpage-shared-one-page.pdf` byte fixture. The page reaches the
    /// same Font through /Resources -> obj 4 -> /F1.
    fn catalog_firstpage_shared_pdf_bytes() -> Vec<u8> {
        let mut pdf = Vec::new();
        pdf.extend_from_slice(b"%PDF-1.4\n");
        let mut offs = [0u64; 7];
        let mut push = |pdf: &mut Vec<u8>, n: usize, body: &str| {
            offs[n] = pdf.len() as u64;
            pdf.extend_from_slice(format!("{n} 0 obj\n{body}\nendobj\n").as_bytes());
        };
        push(&mut pdf, 1, "<< /Type /Catalog /Pages 2 0 R /Ref2 5 0 R >>");
        push(&mut pdf, 2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>");
        push(
            &mut pdf,
            3,
            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] \
             /Resources << /Font 4 0 R >> /Contents 6 0 R >>",
        );
        push(&mut pdf, 4, "<< /F1 5 0 R >>");
        push(
            &mut pdf,
            5,
            "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
        );
        push(&mut pdf, 6, "<< /Length 2 >>\nstream\nBT\nendstream");
        let xref_start = pdf.len() as u64;
        let mut xref = String::from("xref\n0 7\n0000000000 65535 f \n");
        for off in offs.iter().skip(1) {
            xref.push_str(&format!("{off:010} 00000 n \n"));
        }
        pdf.extend_from_slice(xref.as_bytes());
        pdf.extend_from_slice(
            format!("trailer\n<< /Size 7 /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n")
                .as_bytes(),
        );
        pdf
    }

    // Non-gated integration guard for the Step-5 document-`others` route: the
    // Font reached from the Catalog /Ref2 key must land in Part 3 (shared), not
    // Part 2 (private), so it sorts after the first-page-private Content. This
    // pins the classification independently of the qpdf-zlib-compat byte tests.
    #[test]
    fn document_other_ref_routes_first_page_object_to_part3() {
        let mut pdf = Pdf::open(Cursor::new(catalog_firstpage_shared_pdf_bytes())).unwrap();
        let plan = LinearizationPlan::from_pdf(&mut pdf, false).unwrap();
        let font = ObjectRef::new(5, 0); // shared via Catalog /Ref2
        assert!(
            plan.part3_objects.contains(&font),
            "Font reached via Catalog /Ref2 must be Part 3 (lc_first_page_shared); part3={:?}",
            plan.part3_objects
        );
        assert!(
            !plan.part2_objects.contains(&font),
            "the shared Font must not also be in Part 2"
        );
        // The page dict, its /Resources Font dict (obj 4), and the Content stream
        // (obj 6) stay first-page-private (Part 2).
        for r in [
            ObjectRef::new(3, 0),
            ObjectRef::new(4, 0),
            ObjectRef::new(6, 0),
        ] {
            assert!(
                plan.part2_objects.contains(&r),
                "first-page-private object {r:?} must be in Part 2"
            );
        }
    }

    /// Two-page PDF where obj 5 (an image XObject) is BOTH a first-page resource
    /// (page0 `/Resources /XObject /Im0`) AND page1's `/Thumb` target. qpdf gives
    /// obj 5 an `ou_page(0)` user and an `ou_thumb(1)` user, so `thumbs > 0`
    /// classifies it as `lc_first_page_shared` (Part 3), not first-page-private.
    /// Obj 5 is numbered below the page-0 content (obj 6) so private/shared
    /// changes the emission ordering.
    fn thumb_first_page_shared_pdf_bytes() -> Vec<u8> {
        let mut pdf = Vec::new();
        pdf.extend_from_slice(b"%PDF-1.4\n");
        let mut offs = [0u64; 8];
        let mut push = |pdf: &mut Vec<u8>, n: usize, body: &str| {
            offs[n] = pdf.len() as u64;
            pdf.extend_from_slice(format!("{n} 0 obj\n{body}\nendobj\n").as_bytes());
        };
        push(&mut pdf, 1, "<< /Type /Catalog /Pages 2 0 R >>");
        push(
            &mut pdf,
            2,
            "<< /Type /Pages /Count 2 /Kids [3 0 R 4 0 R] >>",
        );
        push(
            &mut pdf,
            3,
            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] \
             /Resources << /XObject << /Im0 5 0 R >> >> /Contents 6 0 R >>",
        );
        push(
            &mut pdf,
            4,
            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] \
             /Contents 7 0 R /Thumb 5 0 R >>",
        );
        push(
            &mut pdf,
            5,
            "<< /Type /XObject /Subtype /Image /Width 1 /Height 1 \
             /ColorSpace /DeviceGray /BitsPerComponent 8 /Length 1 >>\nstream\nA\nendstream",
        );
        push(&mut pdf, 6, "<< /Length 2 >>\nstream\nBT\nendstream");
        push(&mut pdf, 7, "<< /Length 2 >>\nstream\nBT\nendstream");
        let xref_start = pdf.len() as u64;
        let mut xref = String::from("xref\n0 8\n0000000000 65535 f \n");
        for off in offs.iter().skip(1) {
            xref.push_str(&format!("{off:010} 00000 n \n"));
        }
        pdf.extend_from_slice(xref.as_bytes());
        pdf.extend_from_slice(
            format!("trailer\n<< /Size 8 /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n")
                .as_bytes(),
        );
        pdf
    }

    /// Variant of [`thumb_first_page_shared_pdf_bytes`] where page 1's
    /// `/Thumb` value is a direct dictionary whose `/Image` entry reaches obj 5.
    /// qpdf recursively walks that direct value as `ou_thumb(1)`, so obj 5 has
    /// both `ou_page(0)` and `ou_thumb(1)` users.
    fn direct_thumb_descendant_first_page_shared_pdf_bytes() -> Vec<u8> {
        let mut bytes = thumb_first_page_shared_pdf_bytes();
        let indirect = b"/Thumb 5 0 R";
        let direct = b"/Thumb << /Image 5 0 R >>";
        let offset = bytes
            .windows(indirect.len())
            .position(|window| window == indirect)
            .expect("base fixture must contain indirect /Thumb");
        bytes.splice(offset..offset + indirect.len(), direct.iter().copied());

        // Rebuild the xref after changing the page dictionary length.
        let xref_offset = bytes
            .windows(b"xref\n".len())
            .position(|window| window == b"xref\n")
            .expect("base fixture must contain xref");
        let objects = bytes[..xref_offset].to_vec();
        let mut rebuilt = objects;
        let mut offsets = [0u64; 8];
        for (number, object_offset) in offsets.iter_mut().enumerate().skip(1) {
            let marker = format!("{number} 0 obj\n");
            *object_offset = rebuilt
                .windows(marker.len())
                .position(|window| window == marker.as_bytes())
                .expect("fixture object must exist") as u64;
        }
        let new_xref_offset = rebuilt.len() as u64;
        rebuilt.extend_from_slice(b"xref\n0 8\n0000000000 65535 f \n");
        for offset in offsets.iter().skip(1) {
            rebuilt.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
        }
        rebuilt.extend_from_slice(
            format!("trailer\n<< /Size 8 /Root 1 0 R >>\nstartxref\n{new_xref_offset}\n%%EOF\n")
                .as_bytes(),
        );
        rebuilt
    }

    /// One-page PDF where `/Thumb` sorts before `/Zzz`, and both edges reach
    /// obj 5. qpdf's shared per-page `visited` set gives the first edge the only
    /// user, so obj 5 is thumbnail-only rather than a first-page object.
    fn thumb_before_ordinary_first_edge_wins_pdf_bytes() -> Vec<u8> {
        let mut pdf = Vec::new();
        pdf.extend_from_slice(b"%PDF-1.4\n");
        let mut offs = [0u64; 6];
        let mut push = |pdf: &mut Vec<u8>, n: usize, body: &str| {
            offs[n] = pdf.len() as u64;
            pdf.extend_from_slice(format!("{n} 0 obj\n{body}\nendobj\n").as_bytes());
        };
        push(&mut pdf, 1, "<< /Type /Catalog /Pages 2 0 R >>");
        push(&mut pdf, 2, "<< /Type /Pages /Count 1 /Kids [3 0 R] >>");
        push(
            &mut pdf,
            3,
            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] \
             /Contents 4 0 R /Thumb 5 0 R /Zzz 5 0 R >>",
        );
        push(&mut pdf, 4, "<< /Length 2 >>\nstream\nBT\nendstream");
        push(&mut pdf, 5, "<< /Marker /thumbnail-first >>");
        let xref_start = pdf.len() as u64;
        let mut xref = String::from("xref\n0 6\n0000000000 65535 f \n");
        for off in offs.iter().skip(1) {
            xref.push_str(&format!("{off:010} 00000 n \n"));
        }
        pdf.extend_from_slice(xref.as_bytes());
        pdf.extend_from_slice(
            format!("trailer\n<< /Size 6 /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n")
                .as_bytes(),
        );
        pdf
    }

    #[test]
    fn direct_thumb_descendant_routes_first_page_object_to_part3() {
        let mut pdf = Pdf::open(Cursor::new(
            direct_thumb_descendant_first_page_shared_pdf_bytes(),
        ))
        .unwrap();
        let plan = LinearizationPlan::from_pdf(&mut pdf, false).unwrap();
        let image = ObjectRef::new(5, 0);
        assert!(
            plan.part3_objects.contains(&image),
            "direct /Thumb descendant must add an ou_thumb user; part2={:?} part3={:?}",
            plan.part2_objects,
            plan.part3_objects
        );
        assert!(!plan.part2_objects.contains(&image));
    }

    #[test]
    fn thumb_before_later_ordinary_edge_keeps_object_out_of_first_page() {
        let mut pdf = Pdf::open(Cursor::new(
            thumb_before_ordinary_first_edge_wins_pdf_bytes(),
        ))
        .unwrap();
        let plan = LinearizationPlan::from_pdf(&mut pdf, false).unwrap();
        let thumbnail = ObjectRef::new(5, 0);
        assert!(
            plan.part4_rest.contains(&thumbnail),
            "/Thumb wins before /Zzz, so the thumbnail-only object belongs to part 9; \
             part2={:?} part3={:?} part4_rest={:?}",
            plan.part2_objects,
            plan.part3_objects,
            plan.part4_rest
        );
        assert!(!plan.part2_objects.contains(&thumbnail));
        assert!(!plan.part3_objects.contains(&thumbnail));
        assert_eq!(plan.page_hints[0].object_count, 2);
    }

    // Non-gated integration guard for the Step-4b thumb-set route: a first-page
    // object (obj 5) that is also another page's /Thumb target has thumbs>0 and
    // must land in Part 3 (lc_first_page_shared), NOT Part 2 (private). This pins
    // the classification independently of the qpdf-zlib-compat byte tests.
    #[test]
    fn thumb_target_that_is_first_page_object_is_part3_shared() {
        let mut pdf = Pdf::open(Cursor::new(thumb_first_page_shared_pdf_bytes())).unwrap();
        let plan = LinearizationPlan::from_pdf(&mut pdf, false).unwrap();
        let x = ObjectRef::new(5, 0);
        assert!(
            plan.part3_objects.contains(&x),
            "X (first-page object that is also page1's /Thumb) must be Part 3 \
             (lc_first_page_shared); part2={:?} part3={:?}",
            plan.part2_objects,
            plan.part3_objects
        );
        assert!(
            !plan.part2_objects.contains(&x),
            "shared X must not also be Part 2"
        );
    }

    /// Two-page PDF where obj 5 is page0's own `/Resources /XObject /Im0` AND
    /// page0's OWN `/Thumb`; page1 has no `/Thumb`. qpdf traverses `/Thumb` after
    /// the page's other ref-bearing keys with a shared `visited`, so obj 5 gets no
    /// `ou_thumb` beyond its own `ou_page(0)` — thumbs stays 0 and it remains
    /// `lc_first_page_private` (Part 2). Objects 1,2,5,6,7 match
    /// [`thumb_first_page_shared_pdf_bytes`].
    fn self_thumb_first_page_private_pdf_bytes() -> Vec<u8> {
        let mut pdf = Vec::new();
        pdf.extend_from_slice(b"%PDF-1.4\n");
        let mut offs = [0u64; 8];
        let mut push = |pdf: &mut Vec<u8>, n: usize, body: &str| {
            offs[n] = pdf.len() as u64;
            pdf.extend_from_slice(format!("{n} 0 obj\n{body}\nendobj\n").as_bytes());
        };
        push(&mut pdf, 1, "<< /Type /Catalog /Pages 2 0 R >>");
        push(
            &mut pdf,
            2,
            "<< /Type /Pages /Count 2 /Kids [3 0 R 4 0 R] >>",
        );
        push(
            &mut pdf,
            3,
            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] \
             /Resources << /XObject << /Im0 5 0 R >> >> /Contents 6 0 R /Thumb 5 0 R >>",
        );
        push(
            &mut pdf,
            4,
            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 7 0 R >>",
        );
        push(
            &mut pdf,
            5,
            "<< /Type /XObject /Subtype /Image /Width 1 /Height 1 \
             /ColorSpace /DeviceGray /BitsPerComponent 8 /Length 1 >>\nstream\nA\nendstream",
        );
        push(&mut pdf, 6, "<< /Length 2 >>\nstream\nBT\nendstream");
        push(&mut pdf, 7, "<< /Length 2 >>\nstream\nBT\nendstream");
        let xref_start = pdf.len() as u64;
        let mut xref = String::from("xref\n0 8\n0000000000 65535 f \n");
        for off in offs.iter().skip(1) {
            xref.push_str(&format!("{off:010} 00000 n \n"));
        }
        pdf.extend_from_slice(xref.as_bytes());
        pdf.extend_from_slice(
            format!("trailer\n<< /Size 8 /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n")
                .as_bytes(),
        );
        pdf
    }

    // Guard for the same-page self-thumb case: obj 5, reached by page0 both as a
    // resource and as its own /Thumb, must STAY Part 2 (private) — a page never
    // grants ou_thumb to an object already in its own ou_page closure.
    #[test]
    fn self_thumb_first_page_object_stays_part2_private() {
        let mut pdf = Pdf::open(Cursor::new(self_thumb_first_page_private_pdf_bytes())).unwrap();
        let plan = LinearizationPlan::from_pdf(&mut pdf, false).unwrap();
        let x = ObjectRef::new(5, 0);
        assert!(
            plan.part2_objects.contains(&x),
            "self-thumb X must stay Part 2 (private)"
        );
        assert!(
            !plan.part3_objects.contains(&x),
            "self-thumb X must NOT be Part 3"
        );
    }

    /// Build a two-page PDF where page 2's font (obj 6) is reached ONLY by page 2
    /// AND by a Catalog non-open-document key (`/Ref2`).  Layout:
    ///   1 – Catalog  (/Pages 2 0 R, /Ref2 6 0 R)
    ///   2 – Pages node  (Kids: [3 0 R, 4 0 R])
    ///   3 – Page 1  → /Resources << /Font << /F1 5 0 R >> >>, /Contents 7 0 R
    ///   4 – Page 2  → /Resources << /Font << /F2 6 0 R >> >>, /Contents 8 0 R
    ///   5 – Font  (page-1-private, first-page)
    ///   6 – Font  (page-2-private AND Catalog /Ref2 → others>0)
    ///   7 – Content stream (page 1 only)
    ///   8 – Content stream (page 2 only)
    /// No `/Info` in the trailer, mirroring the compat fixture.
    fn two_page_catalog_otherpage_other_bytes() -> Vec<u8> {
        let mut pdf = Vec::new();
        pdf.extend_from_slice(b"%PDF-1.4\n");
        let mut offs = [0u64; 9];
        let mut push = |pdf: &mut Vec<u8>, n: usize, body: &[u8]| {
            offs[n] = pdf.len() as u64;
            pdf.extend_from_slice(format!("{n} 0 obj\n").as_bytes());
            pdf.extend_from_slice(body);
            pdf.extend_from_slice(b"\nendobj\n");
        };
        push(
            &mut pdf,
            1,
            b"<< /Type /Catalog /Pages 2 0 R /Ref2 6 0 R >>",
        );
        push(
            &mut pdf,
            2,
            b"<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>",
        );
        push(&mut pdf, 3, b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 5 0 R >> >> /Contents 7 0 R >>");
        push(&mut pdf, 4, b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F2 6 0 R >> >> /Contents 8 0 R >>");
        push(
            &mut pdf,
            5,
            b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Name /F1 >>",
        );
        push(
            &mut pdf,
            6,
            b"<< /Type /Font /Subtype /Type1 /BaseFont /Times-Roman /Name /F2 >>",
        );
        push(&mut pdf, 7, b"<< /Length 5 >>\nstream\nBT ET\nendstream");
        push(&mut pdf, 8, b"<< /Length 5 >>\nstream\nBT ET\nendstream");

        let xref_start = pdf.len() as u64;
        let mut xref = String::from("xref\n0 9\n0000000000 65535 f \n");
        for off in offs.iter().skip(1) {
            xref.push_str(&format!("{off:010} 00000 n \n"));
        }
        pdf.extend_from_slice(xref.as_bytes());
        pdf.extend_from_slice(
            format!("trailer\n<< /Size 9 /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n")
                .as_bytes(),
        );
        pdf
    }

    // Non-gated integration guard for the Step-6b `others` route (flpdf-zda0): a
    // non-first-page object reached by exactly one other page AND by a Catalog
    // non-open-document key (others>0) must land in `part4_rest` (qpdf part9 /
    // lc_other), NOT `part4_other_pages_private` (part7). qpdf gates part7 on
    // others==0 (QPDF_linearization.cc:1128). Pins the classification and the
    // page's part7 `object_count` hint independently of the qpdf-zlib-compat byte
    // test.
    #[test]
    fn document_other_ref_routes_other_page_object_to_part9() {
        let mut pdf = Pdf::open(Cursor::new(two_page_catalog_otherpage_other_bytes())).unwrap();
        let plan = LinearizationPlan::from_pdf(&mut pdf, false).unwrap();
        let font = ObjectRef::new(6, 0); // page-2-private AND Catalog /Ref2 (others>0)

        assert!(
            plan.part4_rest.contains(&font),
            "others>0 other-page object must be part4_rest (part9 / lc_other); \
             part4_rest={:?}",
            plan.part4_rest
        );
        assert!(
            !plan.part4_other_pages_private.contains(&font),
            "others>0 other-page object must NOT be part7 (other_pages_private); \
             part4_other_pages_private={:?}",
            plan.part4_other_pages_private
        );
        // The page-2 content stream (obj 8) is genuinely page-2-private (others==0)
        // and stays in part7, so the routing is object-specific, not blanket.
        let page2_content = ObjectRef::new(8, 0);
        assert!(
            plan.part4_other_pages_private.contains(&page2_content),
            "page-2-private content (others==0) must remain part7"
        );
        // Hint effect: page 2's part7 object_count excludes the demoted font — the
        // page dict + its content stream only (oracle: qpdf page-1 nobjects==2).
        assert_eq!(
            plan.page_hints[1].object_count, 2,
            "page 2 object_count must exclude the others>0 font (page dict + content)"
        );
    }

    // -----------------------------------------------------------------------
    // 4. Part 4 receives objects not in Part 2 or 3
    // -----------------------------------------------------------------------
    #[test]
    fn part4_contains_only_remaining_objects() {
        let mut pdf = open_tiny_pdf();
        let plan = LinearizationPlan::from_pdf(&mut pdf, false).unwrap();

        // No object should appear in both Part 4 and Part 2/3.
        let part4_set: BTreeSet<_> = plan.part4_objects().into_iter().collect();
        for r in &plan.part2_objects {
            assert!(
                !part4_set.contains(r),
                "Part-2 object {r} must not appear in Part 4"
            );
        }
        for r in &plan.part3_objects {
            assert!(
                !part4_set.contains(r),
                "Part-3 object {r} must not appear in Part 4"
            );
        }
    }

    // -----------------------------------------------------------------------
    // 5. Disjoint invariant holds after from_pdf
    // -----------------------------------------------------------------------
    #[test]
    fn parts_are_disjoint_after_closure() {
        let mut pdf = open_tiny_pdf();
        let plan = LinearizationPlan::from_pdf(&mut pdf, false).unwrap();
        assert!(
            plan.parts_are_disjoint(),
            "object refs must appear in at most one part"
        );
    }

    // -----------------------------------------------------------------------
    // 6. Two-page, shared font: font in Part 3; page-1 content in Part 2;
    //    page-2 content in Part 4.
    // -----------------------------------------------------------------------
    #[test]
    fn two_page_shared_font_partitioned_correctly() {
        let mut pdf = open_two_page_shared_font();
        let plan = LinearizationPlan::from_pdf(&mut pdf, false).unwrap();

        // Resources (5 0 R) and Font (8 0 R) are shared → Part 3.
        let shared_ref_resources = ObjectRef::new(5, 0);
        let shared_ref_font = ObjectRef::new(8, 0);
        assert!(
            plan.part3_objects.contains(&shared_ref_resources),
            "shared Resources dict must be in Part 3"
        );
        assert!(
            plan.part3_objects.contains(&shared_ref_font),
            "shared Font must be in Part 3"
        );

        // Page-1 content stream (6 0 R) is exclusive to page 1 → Part 2.
        let page1_content = ObjectRef::new(6, 0);
        assert!(
            plan.part2_objects.contains(&page1_content),
            "page-1-only content stream must be in Part 2"
        );

        // Page-2 content stream (7 0 R) is only reachable from page 2 → Part 4.
        let page2_content = ObjectRef::new(7, 0);
        assert!(
            plan.part4_objects().contains(&page2_content),
            "page-2-only content stream must be in Part 4"
        );

        // Disjoint invariant must hold.
        assert!(plan.parts_are_disjoint());
    }

    // -----------------------------------------------------------------------
    // 6b. Outline-referenced shared font: in_outlines outranks in_first_page,
    //     so a font referenced by BOTH pages AND an outline item is lc_outlines
    //     (part9, !UseOutlines) — NOT first-page-shared (part3). qpdf
    //     categorization QPDF_linearization.cc:1120-1126 (flpdf-q2zw).
    // -----------------------------------------------------------------------
    #[test]
    fn outline_referenced_shared_font_routes_to_outline_section_not_first_page() {
        let mut pdf = open_two_page_shared_font_outline_ref();
        let plan = LinearizationPlan::from_pdf(&mut pdf, false).unwrap();

        let font = ObjectRef::new(8, 0);
        let outline_root = ObjectRef::new(9, 0);
        let outline_item = ObjectRef::new(10, 0);

        // The font is reached from page 0, page 1, AND the outline. in_outlines
        // wins, so it must be in the outline section, peeled out of the first-page
        // section (part2/part3) and never captured as other-page-private (part7).
        assert!(
            plan.part9_outline_objects.contains(&font),
            "outline-referenced font must be in part9_outline_objects, got {:?}",
            plan.part9_outline_objects
        );
        assert!(
            !plan.part2_objects.contains(&font) && !plan.part3_objects.contains(&font),
            "outline-referenced font must be peeled out of the first-page section"
        );
        assert!(
            !plan.part4_other_pages_private.contains(&font),
            "outline-referenced font must not be captured as other-page-private"
        );

        // pushOutlinesToPart emits the root first, then the remaining outline
        // objects in ascending source-object-number order
        // (QPDF_linearization.cc:1426-1431): [root 9] ++ [font 8, item 10].
        assert_eq!(
            plan.part9_outline_objects,
            vec![outline_root, font, outline_item],
            "outline order must be [root] ++ ascending source number"
        );

        assert!(plan.parts_are_disjoint());
    }

    // -----------------------------------------------------------------------
    // 6c. Symmetric UseOutlines case: the same page+outline-shared font flows
    //     through the part6 (first-half) outline branch instead of part9. qpdf
    //     routes lc_outlines to part6 under /PageMode /UseOutlines
    //     (QPDF_linearization.cc:1214-1216) and counts those objects toward
    //     page 0 (line 1222). Byte parity for this combination needs a dedicated
    //     fixture (filed as a follow-up); this pins flpdf's internal accounting.
    // -----------------------------------------------------------------------
    #[test]
    fn outline_referenced_shared_font_routes_to_part6_under_use_outlines() {
        let mut pdf = open_two_page_shared_font_outline_ref_use_outlines();
        let plan = LinearizationPlan::from_pdf(&mut pdf, false).unwrap();

        let font = ObjectRef::new(8, 0);
        let outline_root = ObjectRef::new(9, 0);
        let outline_item = ObjectRef::new(10, 0);

        // /UseOutlines → outline objects (including the page-shared font) move to
        // the first-half part6 outline section, not part9.
        assert!(
            plan.part6_outline_objects.contains(&font),
            "UseOutlines: outline-referenced font must be in part6_outline_objects, got {:?}",
            plan.part6_outline_objects
        );
        assert!(
            plan.part9_outline_objects.is_empty(),
            "UseOutlines: part9 outlines must be empty"
        );
        assert_eq!(
            plan.part6_outline_objects,
            vec![outline_root, font, outline_item],
            "UseOutlines outline order must be [root] ++ ascending source number"
        );
        assert!(
            !plan.part2_objects.contains(&font) && !plan.part3_objects.contains(&font),
            "outline-referenced font must be peeled out of the first-page section"
        );

        // part6 outline objects are emitted before /E and count toward page 0
        // (QPDF_linearization.cc:1222): object_count = part2 + part3 + part6_outline.
        let expected_page0 = (plan.part2_objects.len()
            + plan.part3_objects.len()
            + plan.part6_outline_objects.len()) as u32;
        assert_eq!(
            plan.page_hints[0].object_count, expected_page0,
            "page-0 object_count must include the part6 outline objects"
        );

        assert!(plan.parts_are_disjoint());
    }

    // -----------------------------------------------------------------------
    // 7. Shared font hint entries include page 1 but NOT page 0.
    //
    //    Per qpdf's Annex F layout, the shared hint table starts with all
    //    first-page section (part2) objects (referencing_pages = []) followed
    //    by the truly shared (part3) objects that carry cross-page references.
    //    Part3 entries must reference pages 1..N that use them; page 0 owns
    //    them by physical position so it must NOT appear in referencing_pages.
    // -----------------------------------------------------------------------
    #[test]
    fn shared_hints_reference_correct_pages() {
        let mut pdf = open_two_page_shared_font();
        let plan = LinearizationPlan::from_pdf(&mut pdf, false).unwrap();

        let part2_len = plan.part2_objects.len();

        // Part2 entries (indices 0..part2_len) must have empty referencing_pages.
        for hint in &plan.shared_hints[..part2_len] {
            assert!(
                hint.referencing_pages.is_empty(),
                "part2 shared hint for {} must have empty referencing_pages",
                hint.object_ref
            );
        }

        // Part3 entries (indices part2_len..) must reference page 1 but NOT page 0.
        for hint in &plan.shared_hints[part2_len..] {
            assert!(
                !hint.referencing_pages.contains(&0),
                "part3 shared hint for {} must NOT reference page 0 (physical ownership via first-page section)",
                hint.object_ref
            );
            assert!(
                hint.referencing_pages.contains(&1),
                "part3 shared hint for {} must reference page 1 (second page)",
                hint.object_ref
            );
        }
    }

    // -----------------------------------------------------------------------
    // 8. Cycle fixture: BFS must terminate without panicking.
    // -----------------------------------------------------------------------
    #[test]
    fn cycle_does_not_loop_forever() {
        let mut pdf = open_cycle_pdf();
        let plan = LinearizationPlan::from_pdf(&mut pdf, false)
            .expect("cycle PDF must not cause infinite loop");

        // Basic sanity: we got a plan with objects in Part 2.
        assert!(!plan.part2_objects.is_empty(), "Part 2 must be non-empty");

        // The cyclic XObjects (5 0 R and 6 0 R) must each appear in exactly
        // one part (BFS visited-set prevents duplication).
        assert!(plan.parts_are_disjoint());

        let xobj_a = ObjectRef::new(5, 0);
        let xobj_b = ObjectRef::new(6, 0);
        let in_part2_a = plan.part2_objects.contains(&xobj_a);
        let in_part2_b = plan.part2_objects.contains(&xobj_b);
        // Both should be reachable from page 1 (single page → no sharing).
        assert!(in_part2_a, "XObject A must be in Part 2");
        assert!(in_part2_b, "XObject B must be in Part 2");
    }

    // -----------------------------------------------------------------------
    // 8b. First-page closure /Resources DFS — defensive branch coverage.
    //
    // The page-leaf `/Resources` subtree walk (a) dedups via the visited set
    // when the same object is reached twice before it is popped, and (b) stops
    // at any page-tree node a resource value cross-links to, so it never pulls
    // in sibling pages. These fixtures exercise both guards directly.
    // -----------------------------------------------------------------------

    /// Page whose inline `/Resources` lists the SAME object ref twice, so the
    /// DFS stack holds two copies of obj 4 before either is popped — exercising
    /// the `visited.insert` dedup `continue` in the subtree walk.
    fn resources_duplicate_ref_pdf_bytes() -> Vec<u8> {
        let mut pdf = Vec::new();
        pdf.extend_from_slice(b"%PDF-1.4\n");
        let off1 = pdf.len() as u64;
        pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
        let off2 = pdf.len() as u64;
        pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n");
        let off3 = pdf.len() as u64;
        pdf.extend_from_slice(
            b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792]               /Resources << /A 4 0 R /B 4 0 R >> >>\nendobj\n",
        );
        let off4 = pdf.len() as u64;
        pdf.extend_from_slice(b"4 0 obj\n<< /Font /Helvetica >>\nendobj\n");
        let xref_start = pdf.len() as u64;
        pdf.extend_from_slice(
            format!(
                "xref\n0 5\n0000000000 65535 f \n{off1:010} 00000 n \n{off2:010} 00000 n \n                 {off3:010} 00000 n \n{off4:010} 00000 n \n"
            )
            .as_bytes(),
        );
        pdf.extend_from_slice(
            format!("trailer\n<< /Size 5 /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n")
                .as_bytes(),
        );
        pdf
    }

    /// Page whose `/Resources` value cross-links back to the `/Pages` node, so
    /// the subtree walk must STOP there (the `is_page_tree_node` guard) instead
    /// of pulling the page tree into the first-page closure.
    fn resources_crosslink_page_tree_pdf_bytes() -> Vec<u8> {
        let mut pdf = Vec::new();
        pdf.extend_from_slice(b"%PDF-1.4\n");
        let off1 = pdf.len() as u64;
        pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
        let off2 = pdf.len() as u64;
        pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n");
        let off3 = pdf.len() as u64;
        // /Resources references obj 2 (the Pages node) — a malformed cross-link.
        pdf.extend_from_slice(
            b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792]               /Resources << /Bad 2 0 R >> >>\nendobj\n",
        );
        let xref_start = pdf.len() as u64;
        pdf.extend_from_slice(
            format!(
                "xref\n0 4\n0000000000 65535 f \n{off1:010} 00000 n \n{off2:010} 00000 n \n                 {off3:010} 00000 n \n"
            )
            .as_bytes(),
        );
        pdf.extend_from_slice(
            format!("trailer\n<< /Size 4 /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n")
                .as_bytes(),
        );
        pdf
    }

    #[test]
    fn resources_subtree_dedups_duplicate_ref() {
        let mut pdf = Pdf::open(Cursor::new(resources_duplicate_ref_pdf_bytes()))
            .expect("duplicate-ref PDF must parse");
        let plan = LinearizationPlan::from_pdf(&mut pdf, false).expect("plan");
        // The doubly-referenced resource object appears exactly once across all
        // parts (the visited-set dedup prevents a duplicate).
        assert!(plan.parts_are_disjoint());
        let res = ObjectRef::new(4, 0);
        assert!(
            plan.part2_objects.contains(&res),
            "the resource object must be in the first-page section exactly once"
        );
        assert_eq!(
            plan.part2_objects.iter().filter(|r| **r == res).count(),
            1,
            "duplicate /Resources ref must not duplicate the object in Part 2"
        );
    }

    #[test]
    fn resources_subtree_stops_at_page_tree_crosslink() {
        let mut pdf = Pdf::open(Cursor::new(resources_crosslink_page_tree_pdf_bytes()))
            .expect("crosslink PDF must parse");
        let plan = LinearizationPlan::from_pdf(&mut pdf, false).expect("plan");
        // The walk reaches the /Pages node via the bad /Resources link but does
        // not descend into it (no sibling-page content pulled in); the plan is
        // still well-formed and disjoint.
        assert!(plan.parts_are_disjoint());
        // The page itself is the first-page anchor.
        assert!(
            plan.part2_objects.contains(&ObjectRef::new(3, 0)),
            "the page leaf must anchor the first-page section"
        );
        // The cross-linked /Pages node (obj 2) must be EXCLUDED from the
        // first-page closure entirely — it is a page-tree boundary, so it is
        // kept in `visited` but neither descended into nor added to Part 2/3.
        // (Before the boundary check moved ahead of `order.push`, the node was
        // wrongly pulled into Part 2.)
        let pages_node = ObjectRef::new(2, 0);
        assert!(
            !plan.part2_objects.contains(&pages_node) && !plan.part3_objects.contains(&pages_node),
            "the cross-linked /Pages node must not be pulled into the first-page section"
        );
    }

    #[test]
    fn objstm_batches_generate_routes_page_tree_crosslink_user_to_first_half() {
        let mut pdf = Pdf::open(Cursor::new(resources_crosslink_page_tree_pdf_bytes()))
            .expect("crosslink PDF must parse");
        let plan = LinearizationPlan::from_pdf(&mut pdf, true).expect("plan");
        let pages_node = ObjectRef::new(2, 0);

        let batch_plan = plan
            .objstm_batches(&mut pdf, &generate_config())
            .expect("Generate mode must succeed");

        assert!(
            batch_plan
                .part3_batches
                .iter()
                .any(|batch| batch.contains(&pages_node)),
            "qpdf's page-object user traversal gives the cross-linked /Pages node \
             a first-page user, so its generated ObjStm must route to the first half"
        );
        assert!(
            batch_plan
                .part4_batches
                .iter()
                .all(|batch| !batch.contains(&pages_node)),
            "the cross-linked /Pages node must not be routed to the second half"
        );
    }

    // -----------------------------------------------------------------------
    // 9. Page-1 hint entry has correct object_count after closure.
    //
    //    object_count[0] must include both Part-2 (page-0 private) and
    //    Part-3 (shared) objects, because both live in the first-page section
    //    (before /E) in the linearized file layout.
    // -----------------------------------------------------------------------
    #[test]
    fn page1_hint_object_count_matches_part2_plus_part3() {
        let mut pdf = open_tiny_pdf();
        let plan = LinearizationPlan::from_pdf(&mut pdf, false).unwrap();

        assert_eq!(
            plan.page_hints[0].object_count,
            (plan.part2_objects.len() + plan.part3_objects.len()) as u32,
            "page-0 hint object_count must match Part-2 + Part-3 length (all objects in first-page section)"
        );
    }

    // -----------------------------------------------------------------------
    // 10. Hint table inputs are well-formed even when populated only by placeholders
    // -----------------------------------------------------------------------
    #[test]
    fn hint_table_inputs_well_formed_empty() {
        let mut pdf = open_tiny_pdf();
        let plan = LinearizationPlan::from_pdf(&mut pdf, false).unwrap();

        // Each PageHintEntry must reference a non-zero object number.
        for entry in &plan.page_hints {
            assert_ne!(entry.page_ref.number, 0);
        }

        // SharedObjectHintEntry objects must be non-zero.
        for entry in &plan.shared_hints {
            assert_ne!(entry.object_ref.number, 0);
        }
    }

    // -----------------------------------------------------------------------
    // Multi-level /Parent inheritance: a /Resources attached to the grandparent
    // /Pages node must end up in the page's closure (so it is partitioned as a
    // shared object or first-page private, not stranded in part4_rest).
    // -----------------------------------------------------------------------

    fn two_level_pages_inherited_resources_bytes() -> Vec<u8> {
        // Object layout:
        //   1 0 obj — Catalog
        //   2 0 obj — Outer /Pages (Kids [3 0 R]) with inherited /Resources 6 0 R
        //   3 0 obj — Inner /Pages (Parent 2 0 R, Kids [4 0 R, 5 0 R])
        //   4 0 obj — Page 1 (Parent 3 0 R) — NO own /Resources, inherits 6 0 R
        //   5 0 obj — Page 2 (Parent 3 0 R) — NO own /Resources, inherits 6 0 R
        //   6 0 obj — Shared /Resources (inherited via the outer /Pages)
        let mut pdf = Vec::new();
        pdf.extend_from_slice(b"%PDF-1.4\n");

        let off1 = pdf.len() as u64;
        pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");

        let off2 = pdf.len() as u64;
        pdf.extend_from_slice(
            b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 2 /Resources 6 0 R >>\nendobj\n",
        );

        let off3 = pdf.len() as u64;
        pdf.extend_from_slice(
            b"3 0 obj\n<< /Type /Pages /Parent 2 0 R /Kids [4 0 R 5 0 R] /Count 2 >>\nendobj\n",
        );

        let off4 = pdf.len() as u64;
        pdf.extend_from_slice(
            b"4 0 obj\n<< /Type /Page /Parent 3 0 R /MediaBox [0 0 612 792] >>\nendobj\n",
        );

        let off5 = pdf.len() as u64;
        pdf.extend_from_slice(
            b"5 0 obj\n<< /Type /Page /Parent 3 0 R /MediaBox [0 0 612 792] >>\nendobj\n",
        );

        let off6 = pdf.len() as u64;
        pdf.extend_from_slice(b"6 0 obj\n<< /Font << /F1 7 0 R >> >>\nendobj\n");

        // Font referenced by the inherited Resources, so the closure walker
        // also has a deeper reachable object beyond the grandparent.
        let off7 = pdf.len() as u64;
        pdf.extend_from_slice(
            b"7 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>\nendobj\n",
        );

        let xref_start = pdf.len() as u64;
        let xref_section = format!(
            "xref\n0 8\n\
            0000000000 65535 f \n\
            {:010} 00000 n \n\
            {:010} 00000 n \n\
            {:010} 00000 n \n\
            {:010} 00000 n \n\
            {:010} 00000 n \n\
            {:010} 00000 n \n\
            {:010} 00000 n \n",
            off1, off2, off3, off4, off5, off6, off7,
        );
        pdf.extend_from_slice(xref_section.as_bytes());
        let trailer = format!(
            "trailer\n<< /Size 8 /Root 1 0 R >>\nstartxref\n{}\n%%EOF\n",
            xref_start,
        );
        pdf.extend_from_slice(trailer.as_bytes());
        pdf
    }

    /// Without ancestor-walking, the shared /Resources attached to the outer
    /// /Pages (2 0 R) would never appear in any page's closure: the leaf page
    /// (4 0 R) only walks one level up to 3 0 R, which has no /Resources of
    /// its own. The resource (6 0 R) and its referenced font (7 0 R) would
    /// then fall into part4_rest, causing qpdf-divergent renumbering.
    ///
    /// With the fix, both pages reach the inherited resource and font, so
    /// the resource and font are classified as Part-3 (shared between both
    /// pages) — not stranded in part4_rest.
    #[test]
    fn multilevel_pages_inherited_resources_join_page_closure() {
        let bytes = two_level_pages_inherited_resources_bytes();
        let mut pdf = Pdf::open(Cursor::new(bytes)).expect("multi-level Pages PDF should parse");
        let plan = LinearizationPlan::from_pdf(&mut pdf, false).unwrap();

        let resources_ref = ObjectRef::new(6, 0);
        let font_ref = ObjectRef::new(7, 0);
        let all_refs = plan.all_assigned_refs();
        assert!(
            all_refs.contains(&resources_ref),
            "inherited /Resources (6 0 R) must be reachable from page closures, \
             not stranded outside every part"
        );
        assert!(
            all_refs.contains(&font_ref),
            "/Font (7 0 R) reached via inherited /Resources must be classified"
        );
        // The /Resources is referenced by both pages, so it is a Part-3 (shared)
        // object — not in part4_rest where the pre-fix code would have placed it.
        assert!(
            plan.part3_objects.contains(&resources_ref),
            "shared inherited /Resources must end up in Part 3"
        );
        assert!(
            !plan.part4_rest.contains(&resources_ref),
            "shared inherited /Resources must NOT end up in part4_rest"
        );
    }

    /// `LinearizationPlan::from_pdf` mutates the `Pdf` in place (pushing
    /// inherited attributes). `writer.rs`'s `force_version_below_1_5` path
    /// calls it a second time on the same `Pdf` to rebuild the plan in disable
    /// mode — the second call must be a no-op for the push step: no new
    /// objects minted, same plan membership.
    #[test]
    fn from_pdf_push_step_is_idempotent_across_two_calls() {
        let bytes = two_level_pages_inherited_resources_bytes();
        let mut pdf = Pdf::open(Cursor::new(bytes)).expect("multi-level Pages PDF should parse");

        let first = LinearizationPlan::from_pdf(&mut pdf, false).expect("first plan");
        let count_after_first = pdf.object_refs().len();

        let second = LinearizationPlan::from_pdf(&mut pdf, false).expect("second plan");
        let count_after_second = pdf.object_refs().len();

        assert_eq!(
            count_after_first, count_after_second,
            "a second from_pdf call on the same Pdf must not mint any new object"
        );
        assert_eq!(
            first.all_assigned_refs(),
            second.all_assigned_refs(),
            "a second from_pdf call must produce the same set of assigned refs"
        );
    }

    // -----------------------------------------------------------------------
    // flpdf-ws2: compute_closure's /Parent-chain walk must propagate
    // pdf.resolve errors instead of swallowing them.
    // -----------------------------------------------------------------------

    /// Build a single-page PDF whose page `/Parent` points at a stream object
    /// with a `/Length` that overshoots its payload.
    ///
    /// `page_refs` walks `/Kids` downward only, so it never resolves object 4;
    /// the only code path that resolves it is the `/Parent`-chain walk inside
    /// `compute_closure`. Resolving object 4 yields a genuine parse error
    /// (not `Ok(Null)`), so a correct walker must surface that error.
    fn page_parent_resolve_error_bytes() -> Vec<u8> {
        let mut pdf = Vec::new();
        pdf.extend_from_slice(b"%PDF-1.4\n");

        let off1 = pdf.len() as u64;
        pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");

        let off2 = pdf.len() as u64;
        pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n");

        // Page leaf: /Parent deliberately points at the malformed object 4,
        // not the Pages node. page_refs collects this page via /Kids without
        // ever touching /Parent, so object 4 is resolved exclusively by
        // compute_closure's ancestor walk.
        let off3 = pdf.len() as u64;
        pdf.extend_from_slice(
            b"3 0 obj\n<< /Type /Page /Parent 4 0 R /MediaBox [0 0 612 792] >>\nendobj\n",
        );

        // Object 4: a stream whose /Length (9) overshoots the 2-byte payload,
        // so parse_indirect_object_detailed rejects it and resolve returns Err.
        let off4 = pdf.len() as u64;
        pdf.extend_from_slice(b"4 0 obj\n<< /Length 9 >>\nstream\nab\nendstream\nendobj\n");

        let xref_start = pdf.len() as u64;
        let xref_section = format!(
            "xref\n0 5\n\
            0000000000 65535 f \n\
            {:010} 00000 n \n\
            {:010} 00000 n \n\
            {:010} 00000 n \n\
            {:010} 00000 n \n",
            off1, off2, off3, off4,
        );
        pdf.extend_from_slice(xref_section.as_bytes());

        let trailer = format!(
            "trailer\n<< /Size 5 /Root 1 0 R >>\nstartxref\n{}\n%%EOF\n",
            xref_start,
        );
        pdf.extend_from_slice(trailer.as_bytes());

        pdf
    }

    /// `compute_closure`'s `/Parent`-chain walk must
    /// propagate `pdf.resolve` errors rather than swallowing them with
    /// `let Ok(..) else { continue }`. A swallowed error lets `from_pdf`
    /// return a degraded plan (truncated closure / hint tables) for a
    /// malformed document, which a downstream writer would then emit as an
    /// invalid linearized PDF.
    #[test]
    fn from_pdf_propagates_parent_chain_resolve_error() {
        let bytes = page_parent_resolve_error_bytes();
        let mut pdf = Pdf::open(Cursor::new(bytes)).expect("fixture xref/trailer must parse");
        let result = LinearizationPlan::from_pdf(&mut pdf, false);
        assert!(
            result.is_err(),
            "from_pdf must propagate a /Parent-chain resolve error, got Ok"
        );
    }

    /// Build a single-page PDF whose page `/Parent` indirects through a plain
    /// reference object (`4 0 obj  5 0 R  endobj`) before reaching the real
    /// ancestor `/Pages` node (object 5), which carries an inherited
    /// `/Resources`.
    ///
    /// PDF allows an indirect object to hold a bare reference, so a bogus leaf
    /// `/Parent` can point through a reference chain to a detached `/Pages`
    /// dictionary. qpdf's ordered page-user traversal still skips the leaf
    /// `/Parent`; resources reachable only through this chain are not page
    /// users.
    fn reference_chain_parent_bytes() -> Vec<u8> {
        let mut pdf = Vec::new();
        pdf.extend_from_slice(b"%PDF-1.4\n");

        let off1 = pdf.len() as u64;
        pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");

        // Real page tree used by page_refs (walks /Kids downward only).
        let off2 = pdf.len() as u64;
        pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n");

        // Page leaf: /Parent points at object 4, a reference-chain hop.
        let off3 = pdf.len() as u64;
        pdf.extend_from_slice(
            b"3 0 obj\n<< /Type /Page /Parent 4 0 R /MediaBox [0 0 612 792] >>\nendobj\n",
        );

        // Object 4: a plain indirect reference to object 5 — resolve(4 0 R)
        // returns Object::Reference(5 0 R), not a dictionary.
        let off4 = pdf.len() as u64;
        pdf.extend_from_slice(b"4 0 obj\n5 0 R\nendobj\n");

        // Object 5: a detached /Pages node carrying /Resources. It is not in
        // the Catalog /Pages -> /Kids tree and is therefore not an inheritance
        // source for the page-user walk.
        let off5 = pdf.len() as u64;
        pdf.extend_from_slice(b"5 0 obj\n<< /Type /Pages /Resources 6 0 R >>\nendobj\n");

        let off6 = pdf.len() as u64;
        pdf.extend_from_slice(b"6 0 obj\n<< /Font << /F1 7 0 R >> >>\nendobj\n");

        let off7 = pdf.len() as u64;
        pdf.extend_from_slice(
            b"7 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>\nendobj\n",
        );

        let xref_start = pdf.len() as u64;
        let xref_section = format!(
            "xref\n0 8\n\
            0000000000 65535 f \n\
            {:010} 00000 n \n\
            {:010} 00000 n \n\
            {:010} 00000 n \n\
            {:010} 00000 n \n\
            {:010} 00000 n \n\
            {:010} 00000 n \n\
            {:010} 00000 n \n",
            off1, off2, off3, off4, off5, off6, off7,
        );
        pdf.extend_from_slice(xref_section.as_bytes());

        let trailer = format!(
            "trailer\n<< /Size 8 /Root 1 0 R >>\nstartxref\n{}\n%%EOF\n",
            xref_start,
        );
        pdf.extend_from_slice(trailer.as_bytes());

        pdf
    }

    /// A detached leaf `/Parent` stays excluded from page users even when its
    /// first object resolves to another bare `Object::Reference`.
    #[test]
    fn from_pdf_ignores_reference_chain_leaf_parent_for_page_users() {
        let bytes = reference_chain_parent_bytes();
        let mut pdf = Pdf::open(Cursor::new(bytes)).expect("fixture must parse");
        pdf.set_object(
            ObjectRef::new(4, 0),
            Object::Reference(ObjectRef::new(5, 0)),
        );
        let plan = LinearizationPlan::from_pdf(&mut pdf, false).unwrap();

        let resources_ref = ObjectRef::new(6, 0);
        let font_ref = ObjectRef::new(7, 0);
        assert!(
            !plan.part2_objects.contains(&resources_ref)
                && !plan.part3_objects.contains(&resources_ref),
            "detached /Resources reached only through leaf /Parent must not be a page user"
        );
        assert!(
            !plan.part2_objects.contains(&font_ref) && !plan.part3_objects.contains(&font_ref),
            "a font below detached /Resources must not be a page user"
        );
    }

    // -----------------------------------------------------------------------
    // 12. Three-page PDF where pages 2 and 3 share a content stream.
    //
    // This tests that objects referenced by 2+ pages but NOT by page 1
    // (i.e., part4_other_pages_shared) are included in shared_hints.
    //
    // Object layout:
    //   1 0 obj – Catalog
    //   2 0 obj – Pages node  (Kids: [3, 4, 5])
    //   3 0 obj – Page 1 dict (unique content 6 0 R, resources 7 0 R)
    //   4 0 obj – Page 2 dict (shared content 8 0 R, resources 7 0 R)
    //   5 0 obj – Page 3 dict (shared content 8 0 R, resources 7 0 R)
    //   6 0 obj – Content stream (page 1 only)
    //   7 0 obj – Resources dict (shared by pages 1, 2, 3 → Part 3)
    //   8 0 obj – Content stream shared by pages 2 and 3 (NOT page 1)
    //            → part4_other_pages_shared
    //
    // Expected:
    //   Part 2: [3 0 R, 6 0 R, ...] (page 1 exclusive)
    //   Part 3: [7 0 R]             (first-page shared: resources)
    //   part4_other_pages_shared: [8 0 R]  (non-first-page shared)
    //   shared_hints contains 8 0 R with referencing_pages = [1, 2] or [2, 3]
    //   depending on 0-based page indices.
    // -----------------------------------------------------------------------

    fn three_page_shared_content_bytes() -> Vec<u8> {
        let mut pdf = Vec::new();
        pdf.extend_from_slice(b"%PDF-1.4\n");

        let off1 = pdf.len() as u64;
        pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");

        let off2 = pdf.len() as u64;
        pdf.extend_from_slice(
            b"2 0 obj\n<< /Type /Pages /Kids [3 0 R 4 0 R 5 0 R] /Count 3 >>\nendobj\n",
        );

        let off3 = pdf.len() as u64;
        pdf.extend_from_slice(b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources 7 0 R /Contents 6 0 R >>\nendobj\n");

        let off4 = pdf.len() as u64;
        pdf.extend_from_slice(b"4 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources 7 0 R /Contents 8 0 R >>\nendobj\n");

        let off5 = pdf.len() as u64;
        pdf.extend_from_slice(b"5 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources 7 0 R /Contents 8 0 R >>\nendobj\n");

        // Page 1 content stream (unique)
        let off6 = pdf.len() as u64;
        pdf.extend_from_slice(b"6 0 obj\n<< /Length 5 >>\nstream\nBT ET\nendstream\nendobj\n");

        // Shared resources (pages 1, 2, 3) → Part 3
        let off7 = pdf.len() as u64;
        pdf.extend_from_slice(b"7 0 obj\n<< /Font << /F1 9 0 R >> >>\nendobj\n");

        // Content stream shared by pages 2 and 3 (NOT page 1) → part4_other_pages_shared
        let off8 = pdf.len() as u64;
        pdf.extend_from_slice(b"8 0 obj\n<< /Length 5 >>\nstream\nBT ET\nendstream\nendobj\n");

        // Font shared via resources
        let off9 = pdf.len() as u64;
        pdf.extend_from_slice(
            b"9 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>\nendobj\n",
        );

        let xref_start = pdf.len() as u64;
        let xref_section = format!(
            "xref\n0 10\n\
            0000000000 65535 f \n\
            {:010} 00000 n \n\
            {:010} 00000 n \n\
            {:010} 00000 n \n\
            {:010} 00000 n \n\
            {:010} 00000 n \n\
            {:010} 00000 n \n\
            {:010} 00000 n \n\
            {:010} 00000 n \n\
            {:010} 00000 n \n",
            off1, off2, off3, off4, off5, off6, off7, off8, off9,
        );
        pdf.extend_from_slice(xref_section.as_bytes());
        let trailer = format!(
            "trailer\n<< /Size 10 /Root 1 0 R >>\nstartxref\n{}\n%%EOF\n",
            xref_start,
        );
        pdf.extend_from_slice(trailer.as_bytes());
        pdf
    }

    /// Non-first-page shared objects (pages 2..N share content stream 8 0 R)
    /// must appear in shared_hints and part4_other_pages_shared.
    ///
    /// This validates the fix for the "in computed list but not hint table"
    /// qpdf warning that occurred when shared objects were only tracked for
    /// objects also reachable from page 1.
    #[test]
    fn non_first_page_shared_objects_in_shared_hints() {
        let bytes = three_page_shared_content_bytes();
        let mut pdf = Pdf::open(Cursor::new(bytes)).expect("three-page PDF should parse");
        let plan = LinearizationPlan::from_pdf(&mut pdf, false).unwrap();

        // The shared content stream (8 0 R) is referenced by pages 2 and 3
        // (0-based: pages 1 and 2) but NOT page 1 (0-based: page 0).
        let shared_content = ObjectRef::new(8, 0);

        // It must land in part4_other_pages_shared (not part4_rest).
        assert!(
            plan.part4_other_pages_shared.contains(&shared_content),
            "content stream shared by pages 2 and 3 must be in part4_other_pages_shared"
        );
        assert!(
            !plan.part4_rest.contains(&shared_content),
            "content stream shared by pages 2 and 3 must NOT be in part4_rest"
        );

        // It must appear in shared_hints.
        let in_shared_hints = plan
            .shared_hints
            .iter()
            .any(|h| h.object_ref == shared_content);
        assert!(
            in_shared_hints,
            "content stream shared by pages 2 and 3 must appear in shared_hints"
        );

        // Its referencing_pages must include pages 1 and 2 (0-based).
        let hint = plan
            .shared_hints
            .iter()
            .find(|h| h.object_ref == shared_content)
            .unwrap();
        assert!(
            hint.referencing_pages.contains(&1),
            "shared content stream must reference page 1 (0-based)"
        );
        assert!(
            hint.referencing_pages.contains(&2),
            "shared content stream must reference page 2 (0-based)"
        );
        assert!(
            !hint.referencing_pages.contains(&0),
            "shared content stream must NOT reference page 0 (not reachable from page 1)"
        );

        // Disjoint invariant must hold.
        assert!(plan.parts_are_disjoint());
    }

    // =======================================================================
    // Tests for ObjStmBatchPlan (flpdf-9hc.5.8.1)
    // =======================================================================

    /// Config helpers
    fn generate_config() -> PlannerConfig {
        PlannerConfig {
            mode: ObjectStreamMode::Generate,
            batch_size_cap: std::num::NonZeroUsize::new(100).unwrap(),
        }
    }

    fn preserve_config() -> PlannerConfig {
        PlannerConfig {
            mode: ObjectStreamMode::Preserve,
            batch_size_cap: std::num::NonZeroUsize::new(100).unwrap(),
        }
    }

    fn disable_config() -> PlannerConfig {
        PlannerConfig {
            mode: ObjectStreamMode::Disable,
            batch_size_cap: std::num::NonZeroUsize::new(100).unwrap(),
        }
    }

    // -----------------------------------------------------------------------
    // (d) Disable mode: empty plan
    // -----------------------------------------------------------------------
    #[test]
    fn objstm_batches_disable_yields_empty_plan() {
        let bytes = three_page_shared_content_bytes();
        let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
        let plan = LinearizationPlan::from_pdf(&mut pdf, false).unwrap();

        let batch_plan = plan.objstm_batches(&mut pdf, &disable_config()).unwrap();
        assert!(
            batch_plan.part3_batches.is_empty(),
            "Disable must produce no part3 batches"
        );
        assert!(
            batch_plan.part4_batches.is_empty(),
            "Disable must produce no part4 batches"
        );
    }

    #[test]
    fn objstm_batches_generate_rejects_missing_routing_snapshot() {
        let bytes = three_page_shared_content_bytes();
        let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
        let err = LinearizationPlan::default()
            .objstm_batches(&mut pdf, &generate_config())
            .expect_err("hand-built Generate plan must require a routing snapshot");

        assert!(matches!(
            err,
            crate::Error::Unsupported(ref message)
                if message == "linearization plan: missing object-user routing snapshot"
        ));
    }

    #[test]
    fn objstm_batches_default_disable_succeeds_without_routing_snapshot() {
        let bytes = three_page_shared_content_bytes();
        let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();

        let batch_plan = LinearizationPlan::default()
            .objstm_batches(&mut pdf, &disable_config())
            .expect("hand-built Disable plan must not require a routing snapshot");

        assert!(batch_plan.part3_batches.is_empty());
        assert!(batch_plan.part4_batches.is_empty());
    }

    #[test]
    fn objstm_batches_default_preserve_rejects_missing_routing_snapshot() {
        let bytes = three_page_shared_content_bytes();
        let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
        let err = LinearizationPlan::default()
            .objstm_batches(&mut pdf, &preserve_config())
            .expect_err("hand-built Preserve plan must require a routing snapshot");

        assert!(matches!(
            err,
            crate::Error::Unsupported(ref message)
                if message == "linearization plan: missing object-user routing snapshot"
        ));
    }

    // -----------------------------------------------------------------------
    // (a) Generate: part3/part4 eligible objects end up in correct batches
    // -----------------------------------------------------------------------
    #[test]
    fn objstm_batches_generate_assigns_part3_and_part4() {
        // three_page_shared_content fixture:
        //   Part 3: 7 0 R (Resources dict, shared) → eligible non-stream dict
        //   Part 4 (part4_other_pages_shared): 8 0 R (content stream) → INELIGIBLE (stream)
        //   Part 4 (part4_rest): 1 0 R (Catalog), 2 0 R (Pages node)
        //
        // Eligible in Part 3: 7 0 R (dict, gen 0)
        // Ineligible in Part 3: none
        // Eligible in Part 4: those among part4_* that are plain dicts (1 0 R Catalog, 2 0 R Pages)
        // Ineligible in Part 4: 8 0 R (stream), page dicts (streams? no they're dicts),
        //   page dicts 4 0 R, 5 0 R are plain dicts → eligible
        //   9 0 R (Font dict) → eligible (in part3)
        let bytes = three_page_shared_content_bytes();
        let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
        let plan = LinearizationPlan::from_pdf(&mut pdf, false).unwrap();

        let batch_plan = plan.objstm_batches(&mut pdf, &generate_config()).unwrap();

        // Every part3_object that is eligible must appear in part3_batches.
        let all_part3_batched: std::collections::BTreeSet<ObjectRef> = batch_plan
            .part3_batches
            .iter()
            .flat_map(|b| b.iter().copied())
            .collect();
        let all_part4_batched: std::collections::BTreeSet<ObjectRef> = batch_plan
            .part4_batches
            .iter()
            .flat_map(|b| b.iter().copied())
            .collect();

        // qpdf 11.9.0 packs the first-page shared dicts into a first-half
        // ObjStm: the Resources dict (7 0 R) and the Font it references are
        // Part-3 objects and MUST appear in part3_batches.  The /Pages tree
        // (2 0 R) is folded into the same first-half batch; the /Catalog
        // (1 0 R) stays standalone.
        let resources_ref = ObjectRef::new(7, 0);
        assert!(
            all_part3_batched.contains(&resources_ref),
            "Part-3 Resources dict 7 0 R must be packed into part3_batches"
        );
        let pages_tree = plan.pages_tree_ref.expect("fixture has a /Pages tree");
        assert!(
            all_part3_batched.contains(&pages_tree),
            "the /Pages tree ({pages_tree}) must be folded into the first-half batch"
        );
        let catalog = plan.root_ref.expect("fixture has a /Catalog");
        assert!(
            !all_part3_batched.contains(&catalog) && !all_part4_batched.contains(&catalog),
            "the /Catalog ({catalog}) must stay standalone (in no batch)"
        );
        assert!(
            !all_part4_batched.contains(&resources_ref),
            "Part-3 object 7 0 R must never be misrouted into part4_batches"
        );

        // Part4 objects that are plain dicts (page 2: 4 0 R, page 3: 5 0 R) → part4_batches.
        // 8 0 R is a stream → ineligible, must NOT be in any batch.
        let shared_content = ObjectRef::new(8, 0);
        assert!(
            !all_part3_batched.contains(&shared_content),
            "stream 8 0 R must NOT be in part3_batches"
        );
        assert!(
            !all_part4_batched.contains(&shared_content),
            "stream 8 0 R must NOT be in part4_batches (streams are ineligible)"
        );

        // No batch object should come from part3 AND part4 at the same time.
        let intersection: Vec<_> = all_part3_batched.intersection(&all_part4_batched).collect();
        assert!(
            intersection.is_empty(),
            "part3_batches and part4_batches must be disjoint; overlap: {intersection:?}"
        );
    }

    // -----------------------------------------------------------------------
    // (b) part2_objects must NEVER appear in any batch (all modes)
    // -----------------------------------------------------------------------
    #[test]
    fn objstm_batches_generate_never_places_part2_in_batches() {
        let bytes = three_page_shared_content_bytes();
        let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
        let plan = LinearizationPlan::from_pdf(&mut pdf, false).unwrap();

        let batch_plan = plan.objstm_batches(&mut pdf, &generate_config()).unwrap();

        let part2_set: std::collections::BTreeSet<ObjectRef> =
            plan.part2_objects.iter().copied().collect();

        let all_batched: Vec<ObjectRef> = batch_plan
            .part3_batches
            .iter()
            .flat_map(|b| b.iter().copied())
            .chain(
                batch_plan
                    .part4_batches
                    .iter()
                    .flat_map(|b| b.members.iter().copied()),
            )
            .collect();

        for r in &all_batched {
            assert!(
                !part2_set.contains(r),
                "part2 object {r} must never appear in any ObjStm batch"
            );
        }
    }

    // -----------------------------------------------------------------------
    // (b) same for two-page fixture in Generate mode
    // -----------------------------------------------------------------------
    #[test]
    fn objstm_batches_two_page_generate_part2_not_in_batches() {
        let bytes = two_page_shared_font_bytes();
        let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
        let plan = LinearizationPlan::from_pdf(&mut pdf, false).unwrap();

        let batch_plan = plan.objstm_batches(&mut pdf, &generate_config()).unwrap();

        let part2_set: std::collections::BTreeSet<ObjectRef> =
            plan.part2_objects.iter().copied().collect();
        let all_batched: Vec<ObjectRef> = batch_plan
            .part3_batches
            .iter()
            .flat_map(|b| b.iter().copied())
            .chain(
                batch_plan
                    .part4_batches
                    .iter()
                    .flat_map(|b| b.members.iter().copied()),
            )
            .collect();

        for r in &all_batched {
            assert!(
                !part2_set.contains(r),
                "part2 object {r} must never appear in any ObjStm batch (two-page fixture)"
            );
        }
    }

    // -----------------------------------------------------------------------
    // (c) Ineligible objects excluded (streams, gen>0, etc.)
    // -----------------------------------------------------------------------
    #[test]
    fn objstm_batches_generate_excludes_ineligible_objects() {
        // two_page_shared_font fixture:
        //   6 0 R content stream (part2)   → excluded by part2 rule + stream ineligibility
        //   7 0 R content stream (part4)   → ineligible (stream), must not be in any batch
        //   8 0 R font (part3)             → eligible plain dict
        let bytes = two_page_shared_font_bytes();
        let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
        let plan = LinearizationPlan::from_pdf(&mut pdf, false).unwrap();

        let batch_plan = plan.objstm_batches(&mut pdf, &generate_config()).unwrap();

        let all_batched: std::collections::BTreeSet<ObjectRef> = batch_plan
            .part3_batches
            .iter()
            .flat_map(|b| b.iter().copied())
            .chain(
                batch_plan
                    .part4_batches
                    .iter()
                    .flat_map(|b| b.members.iter().copied()),
            )
            .collect();

        // 6 0 R: content stream (page 1 only) → part2 + stream ineligible
        let page1_content = ObjectRef::new(6, 0);
        assert!(
            !all_batched.contains(&page1_content),
            "stream 6 0 R (page-1 content, part2) must not be in any batch"
        );

        // 7 0 R: content stream (page 2 only) → part4 but stream ineligible
        let page2_content = ObjectRef::new(7, 0);
        assert!(
            !all_batched.contains(&page2_content),
            "stream 7 0 R (page-2 content, part4) must not be in any batch"
        );
    }

    // -----------------------------------------------------------------------
    // (e) Preserve mode on fixture with no source ObjStms → empty plan
    //     (no fall-through to Generate)
    // -----------------------------------------------------------------------
    #[test]
    fn objstm_batches_preserve_no_source_objstms_yields_empty_plan() {
        // two_page_shared_font_bytes is a PDF-1.4 with traditional xref table.
        // No source ObjStms → Preserve must yield empty batches.
        let bytes = two_page_shared_font_bytes();
        let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
        let plan = LinearizationPlan::from_pdf(&mut pdf, false).unwrap();

        let batch_plan = plan.objstm_batches(&mut pdf, &preserve_config()).unwrap();
        assert!(
            batch_plan.part3_batches.is_empty(),
            "Preserve with no source ObjStms must produce no part3 batches (no fall-through to Generate)"
        );
        assert!(
            batch_plan.part4_batches.is_empty(),
            "Preserve with no source ObjStms must produce no part4 batches"
        );
    }

    // -----------------------------------------------------------------------
    // (f) Preserve mode with source ObjStms — the primary behaviour under test.
    //
    // Fixture (PDF-1.5, two ObjStms, two pages):
    //
    //   Object layout:
    //     0          free
    //     1 0 obj    Catalog (plain indirect)
    //     2 0 obj    Pages node (compressed in ObjStm 7, index 0)
    //     3 0 obj    Page 1 dict (compressed in ObjStm 7, index 1)  ← Part 2, EXCLUDED
    //     4 0 obj    Page 2 dict (compressed in ObjStm 8, index 0)
    //     5 0 obj    Shared Resources dict (compressed in ObjStm 7, index 2) ← Part 3
    //     6 0 obj    Ineligible dict /Type /XRef (compressed in ObjStm 8, index 1) ← EXCLUDED (ineligible)
    //     7 0 obj    ObjStm #1  (plain indirect stream)
    //     8 0 obj    ObjStm #2  (plain indirect stream)
    //     9 0 obj    XRef stream (plain indirect)
    //
    //   LinearizationPlan partition:
    //     Part 2: [3 0 R, ...]        (first-page closure exclusives)
    //     Part 3: [5 0 R]             (shared resources — first-page AND page 2)
    //     Part 4: [2 0 R, 4 0 R, ...]  (everything else)
    //
    //   Preserve batches expected:
    //     ObjStm 7 members eligible for Part 3:  [5 0 R]   → part3_batches
    //     ObjStm 7 members eligible for Part 4:  [2 0 R]   → part4_batches
    //     ObjStm 8 members eligible for Part 4:  [4 0 R]   → part4_batches
    //     3 0 R excluded (Part 2), 6 0 R excluded (ineligible /Type /XRef)
    // -----------------------------------------------------------------------

    /// Build a zlib-compressed ObjStm payload from (object-number, raw-bytes) pairs.
    /// Returns (compressed_bytes, first_offset_in_body).
    /// Mirrors the private helper in `writer/object_streams.rs`.
    fn build_objstm_payload_plan(members: &[(u32, &[u8])]) -> (Vec<u8>, usize) {
        use flate2::write::ZlibEncoder;
        use flate2::Compression;
        use std::io::Write;

        let mut header = String::new();
        let mut body = Vec::new();
        for (index, (number, object_data)) in members.iter().enumerate() {
            let offset = body.len();
            header.push_str(&format!("{} {} ", number, offset));
            body.extend_from_slice(object_data);
            if index + 1 < members.len() {
                body.push(b'\n');
            }
        }
        let mut decoded = Vec::new();
        decoded.extend_from_slice(header.as_bytes());
        decoded.extend_from_slice(&body);

        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
        enc.write_all(&decoded).unwrap();
        let encoded = enc.finish().unwrap();
        (encoded, header.len())
    }

    fn append_u24_be_plan(bytes: &mut Vec<u8>, value: u32) {
        let b = value.to_be_bytes();
        bytes.extend_from_slice(&b[1..]);
    }

    /// Append a 1+3+1 xref stream entry (W=[1 3 1]).
    fn append_xref_entry_plan(entries: &mut Vec<u8>, entry_type: u8, field1: u32, field2: u8) {
        entries.push(entry_type);
        append_u24_be_plan(entries, field1);
        entries.push(field2);
    }

    /// Build a 2-page PDF-1.5 with two source ObjStms.
    ///
    /// Object layout:
    ///   0: free
    ///   1: Catalog (plain indirect)
    ///   2: Pages node (ObjStm 7, idx 0)
    ///   3: Page 1 dict (ObjStm 7, idx 1) — Part 2 (excluded from ObjStm batches)
    ///   4: Page 2 dict (ObjStm 8, idx 0) — Part 4 private
    ///   5: Shared Resources dict (ObjStm 7, idx 2) — Part 3
    ///   6: Ineligible dict /Type /XRef (ObjStm 8, idx 1) — excluded (ineligible)
    ///   7: ObjStm stream containing [2, 3, 5] in source-index order [0, 1, 2]
    ///   8: ObjStm stream containing [4, 6] in source-index order [0, 1]
    ///   9: XRef stream
    fn two_page_two_objstm_pdf_bytes() -> Vec<u8> {
        let mut bytes = b"%PDF-1.5\n".to_vec();

        // Object 1: Catalog (plain indirect)
        let catalog_offset = bytes.len() as u32;
        bytes.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");

        // ObjStm #7: members [2=Pages, 3=Page1, 5=Resources] at indices [0, 1, 2]
        let objstm1_members: &[(u32, &[u8])] = &[
            (2, b"<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>"),
            (
                3,
                b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources 5 0 R >>",
            ),
            (
                5,
                b"<< /Font << /F1 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> >> >>",
            ),
        ];
        let (stream1_data, first1) = build_objstm_payload_plan(objstm1_members);
        let n1 = objstm1_members.len() as u32;
        let objstm1_offset = bytes.len() as u32;
        bytes.extend_from_slice(
            format!(
                "7 0 obj\n<< /Type /ObjStm /N {n1} /First {first1} /Length {} /Filter /FlateDecode >>\nstream\n",
                stream1_data.len()
            )
            .as_bytes(),
        );
        bytes.extend_from_slice(&stream1_data);
        bytes.extend_from_slice(b"\nendstream\nendobj\n");

        // ObjStm #8: members [4=Page2, 6=ineligible /Type /XRef dict] at indices [0, 1]
        let objstm2_members: &[(u32, &[u8])] = &[
            (
                4,
                b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources 5 0 R >>",
            ),
            (6, b"<< /Type /XRef >>"),
        ];
        let (stream2_data, first2) = build_objstm_payload_plan(objstm2_members);
        let n2 = objstm2_members.len() as u32;
        let objstm2_offset = bytes.len() as u32;
        bytes.extend_from_slice(
            format!(
                "8 0 obj\n<< /Type /ObjStm /N {n2} /First {first2} /Length {} /Filter /FlateDecode >>\nstream\n",
                stream2_data.len()
            )
            .as_bytes(),
        );
        bytes.extend_from_slice(&stream2_data);
        bytes.extend_from_slice(b"\nendstream\nendobj\n");

        // XRef stream (object 9)
        let xref_offset = bytes.len() as u32;
        // W=[1 3 1]: 10 objects (0..=9)
        let mut xref_entries: Vec<u8> = Vec::new();
        // 0: free
        append_xref_entry_plan(&mut xref_entries, 0, 0, 0);
        // 1: Catalog at catalog_offset
        append_xref_entry_plan(&mut xref_entries, 1, catalog_offset, 0);
        // 2: Pages in ObjStm 7, index 0
        append_xref_entry_plan(&mut xref_entries, 2, 7, 0);
        // 3: Page1 in ObjStm 7, index 1
        append_xref_entry_plan(&mut xref_entries, 2, 7, 1);
        // 4: Page2 in ObjStm 8, index 0
        append_xref_entry_plan(&mut xref_entries, 2, 8, 0);
        // 5: Resources in ObjStm 7, index 2
        append_xref_entry_plan(&mut xref_entries, 2, 7, 2);
        // 6: Ineligible in ObjStm 8, index 1
        append_xref_entry_plan(&mut xref_entries, 2, 8, 1);
        // 7: ObjStm #1 at objstm1_offset
        append_xref_entry_plan(&mut xref_entries, 1, objstm1_offset, 0);
        // 8: ObjStm #2 at objstm2_offset
        append_xref_entry_plan(&mut xref_entries, 1, objstm2_offset, 0);
        // 9: XRef stream at xref_offset
        append_xref_entry_plan(&mut xref_entries, 1, xref_offset, 0);

        bytes.extend_from_slice(
            format!(
                "9 0 obj\n<< /Type /XRef /Size 10 /Root 1 0 R /W [1 3 1] /Index [0 10] /Length {} >>\nstream\n",
                xref_entries.len()
            )
            .as_bytes(),
        );
        bytes.extend_from_slice(&xref_entries);
        bytes.extend_from_slice(b"\nendstream\nendobj\n");
        bytes.extend_from_slice(format!("startxref\n{xref_offset}\n%%EOF\n").as_bytes());
        bytes
    }

    /// Build a one-page PDF whose `/Resources` cross-link points back to the
    /// `/Pages` node, with that node as the sole member of a source ObjStm.
    fn resources_crosslink_page_tree_objstm_pdf_bytes() -> Vec<u8> {
        let mut bytes = b"%PDF-1.5\n".to_vec();

        let catalog_offset = bytes.len() as u32;
        bytes.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");

        let page_offset = bytes.len() as u32;
        bytes.extend_from_slice(
            b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] \
              /Resources << /Bad 2 0 R >> >>\nendobj\n",
        );

        let objstm_members: &[(u32, &[u8])] = &[(2, b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>")];
        let (stream_data, first) = build_objstm_payload_plan(objstm_members);
        let objstm_offset = bytes.len() as u32;
        bytes.extend_from_slice(
            format!(
                "4 0 obj\n<< /Type /ObjStm /N 1 /First {first} /Length {} \
                 /Filter /FlateDecode >>\nstream\n",
                stream_data.len()
            )
            .as_bytes(),
        );
        bytes.extend_from_slice(&stream_data);
        bytes.extend_from_slice(b"\nendstream\nendobj\n");

        let xref_offset = bytes.len() as u32;
        let mut xref_entries = Vec::new();
        append_xref_entry_plan(&mut xref_entries, 0, 0, 0);
        append_xref_entry_plan(&mut xref_entries, 1, catalog_offset, 0);
        append_xref_entry_plan(&mut xref_entries, 2, 4, 0);
        append_xref_entry_plan(&mut xref_entries, 1, page_offset, 0);
        append_xref_entry_plan(&mut xref_entries, 1, objstm_offset, 0);
        append_xref_entry_plan(&mut xref_entries, 1, xref_offset, 0);

        bytes.extend_from_slice(
            format!(
                "5 0 obj\n<< /Type /XRef /Size 6 /Root 1 0 R /W [1 3 1] \
                 /Index [0 6] /Length {} >>\nstream\n",
                xref_entries.len()
            )
            .as_bytes(),
        );
        bytes.extend_from_slice(&xref_entries);
        bytes.extend_from_slice(b"\nendstream\nendobj\n");
        bytes.extend_from_slice(format!("startxref\n{xref_offset}\n%%EOF\n").as_bytes());
        bytes
    }

    #[test]
    fn objstm_batches_preserve_routes_page_tree_crosslink_user_to_first_half() {
        let bytes = resources_crosslink_page_tree_objstm_pdf_bytes();
        let mut pdf = Pdf::open(Cursor::new(bytes)).expect("crosslink ObjStm PDF should parse");
        let plan = LinearizationPlan::from_pdf(&mut pdf, false).expect("plan");
        let pages_node = ObjectRef::new(2, 0);

        let batch_plan = plan
            .objstm_batches(&mut pdf, &preserve_config())
            .expect("Preserve mode must succeed");

        assert!(
            batch_plan
                .part3_batches
                .iter()
                .any(|batch| batch.contains(&pages_node)),
            "qpdf's page-object user traversal gives the cross-linked /Pages node \
             a first-page user, so its preserved ObjStm must route to the first half"
        );
        assert!(
            batch_plan
                .part4_batches
                .iter()
                .all(|batch| !batch.contains(&pages_node)),
            "the cross-linked /Pages node must not be routed to the second half"
        );
    }

    /// Preserve mode keeps each source ObjStm intact after qpdf-compatible
    /// filtering and routes the surviving member-user union once.
    #[test]
    fn objstm_batches_preserve_source_objstm_grouping_and_union_route() {
        let bytes = two_page_two_objstm_pdf_bytes();
        let mut pdf = Pdf::open(Cursor::new(bytes)).expect("two-ObjStm PDF should parse");
        let plan = LinearizationPlan::from_pdf(&mut pdf, false).unwrap();

        // Verify the partition is what the fixture was designed to produce.
        // Part 2 must contain page 1 dict (3 0 R).
        let page1_ref = ObjectRef::new(3, 0);
        assert!(
            plan.part2_objects.contains(&page1_ref),
            "page 1 dict (3 0 R) must be in Part 2"
        );

        // Resources dict (5 0 R) must be in Part 3 (shared by both pages).
        let resources_ref = ObjectRef::new(5, 0);
        assert!(
            plan.part3_objects.contains(&resources_ref),
            "shared Resources dict (5 0 R) must be in Part 3"
        );

        // Page 2 dict (4 0 R) must be in Part 4.
        let page2_ref = ObjectRef::new(4, 0);
        assert!(
            plan.part4_objects().contains(&page2_ref),
            "page 2 dict (4 0 R) must be in Part 4"
        );

        // Now call objstm_batches in Preserve mode.
        let batch_plan = plan
            .objstm_batches(&mut pdf, &preserve_config())
            .expect("Preserve mode must succeed");

        let all_part3_batched: BTreeSet<ObjectRef> = batch_plan
            .part3_batches
            .iter()
            .flat_map(|b| b.iter().copied())
            .collect();
        let all_part4_batched: BTreeSet<ObjectRef> = batch_plan
            .part4_batches
            .iter()
            .flat_map(|b| b.iter().copied())
            .collect();

        // ── Invariant 1: page dictionaries never appear in a batch ─────────
        assert!(
            !all_part3_batched.contains(&page1_ref) && !all_part4_batched.contains(&page1_ref),
            "first-page dictionary {page1_ref} must remain standalone"
        );
        assert!(
            !all_part3_batched.contains(&page2_ref) && !all_part4_batched.contains(&page2_ref),
            "other-page dictionary {page2_ref} must remain standalone"
        );

        // ── Invariant 2: Ineligible object (6 0 R, /Type /XRef dict) excluded ──
        let ineligible_ref = ObjectRef::new(6, 0);
        assert!(
            !all_part3_batched.contains(&ineligible_ref),
            "ineligible /Type /XRef dict (6 0 R) must not appear in part3_batches"
        );
        assert!(
            !all_part4_batched.contains(&ineligible_ref),
            "ineligible /Type /XRef dict (6 0 R) must not appear in part4_batches"
        );

        // ── Invariant 3: Part-3 first-page shared objects ARE packed ──────────
        // qpdf 11.9.0 packs the first-page shared Resources dict (5 0 R) into a
        // first-half ObjStm; the /Pages tree (2 0 R) is folded into the same
        // first-half batch.  5 0 R must appear in part3_batches and NOT be
        // misrouted into part4_batches.
        assert!(
            all_part3_batched.contains(&resources_ref),
            "Part-3 Resources dict 5 0 R must be packed into part3_batches"
        );
        assert!(
            !all_part4_batched.contains(&resources_ref),
            "Part-3 object 5 0 R must NOT be misrouted into part4_batches"
        );

        // ── Invariant 4: /Pages tree is routed to the first-half batch ────────
        // 2 0 R (Pages) and 5 0 R (Resources) are members of source ObjStm 7.
        // Their union route is first-page, so the source container remains
        // intact in part3. Page dictionary 4 0 R is removed before routing.
        let pages_ref = ObjectRef::new(2, 0);
        assert!(
            all_part3_batched.contains(&pages_ref),
            "the /Pages tree (2 0 R) must be routed into part3_batches"
        );
        assert!(
            !all_part4_batched.contains(&pages_ref),
            "the /Pages tree (2 0 R) must NOT remain in part4_batches"
        );
        assert!(
            batch_plan
                .part3_batches
                .iter()
                .any(|batch| batch.contains(&pages_ref) && batch.contains(&resources_ref)),
            "source ObjStm members 2 0 R and 5 0 R must remain in one first-half batch"
        );

        // ── Invariant 5: /Catalog stays standalone ────────────────────────────
        // qpdf keeps the document /Catalog uncompressed; it must appear in no
        // batch.  (In this fixture the Catalog 1 0 R was not in any source
        // ObjStm, but the canonicalisation guards against it regardless.)
        let catalog_ref = plan.root_ref.expect("fixture has a /Catalog");
        assert!(
            !all_part3_batched.contains(&catalog_ref) && !all_part4_batched.contains(&catalog_ref),
            "the /Catalog ({catalog_ref}) must stay standalone (in no batch)"
        );

        // ── Invariant 7: No overlap between part3_batches and part4_batches ────
        let overlap: Vec<ObjectRef> = all_part3_batched
            .intersection(&all_part4_batched)
            .copied()
            .collect();
        assert!(
            overlap.is_empty(),
            "part3_batches and part4_batches must be disjoint; overlap: {overlap:?}"
        );

        // ── Invariant 8: Every batched ref is eligible ──────────────────────────
        use crate::writer::object_streams::{eligibility_context, is_eligible_for_objstm};
        let ctx = eligibility_context(&mut pdf).unwrap();
        for r in all_part3_batched.iter().chain(all_part4_batched.iter()) {
            let obj = pdf.resolve_borrowed(*r).unwrap();
            assert!(
                is_eligible_for_objstm(*r, obj, &ctx),
                "batched object {r} must be eligible for ObjStm"
            );
        }

        // ── Invariant 9: Every batched ref has a linearization-plan slot ──────
        // A batched object must live in the plan's Part-3 or Part-4 set; an
        // eligible source-ObjStm member that is not in any part has no
        // RenumberMap entry and would crash ObjStmLayout::build with "has no
        // renumber entry". Guards the preserve-mode part4_set filter.
        let part3_set: BTreeSet<ObjectRef> = plan.part3_objects.iter().copied().collect();
        let part4_set: BTreeSet<ObjectRef> = plan
            .part4_other_pages_private
            .iter()
            .chain(&plan.part4_other_pages_shared)
            .chain(&plan.part4_rest)
            .copied()
            .collect();
        for r in all_part3_batched.iter().chain(all_part4_batched.iter()) {
            assert!(
                part3_set.contains(r) || part4_set.contains(r),
                "batched object {r} has no linearization-plan slot \
                 (not in Part-3 or Part-4) — would break ObjStmLayout::build"
            );
        }
    }

    /// Preserve mode ignores the Generate planner cap and retains source ObjStm
    /// boundaries, matching qpdf's `preserveObjectStreams`.
    #[test]
    fn objstm_batches_preserve_ignores_generate_cap() {
        // Source ObjStm 7 holds the first-page shared Resources dict (5 0 R) and
        // the /Pages tree (2 0 R), both routed to the first half; ObjStm 8
        // contains Page 2 (4 0 R), which qpdf removes from object streams.
        // Even with cap=1, source ObjStm 7 remains one two-member container.
        let bytes = two_page_two_objstm_pdf_bytes();
        let mut pdf = Pdf::open(Cursor::new(bytes)).expect("two-ObjStm PDF should parse");
        let plan = LinearizationPlan::from_pdf(&mut pdf, false).unwrap();

        let cap1_config = PlannerConfig {
            mode: crate::writer::object_streams::ObjectStreamMode::Preserve,
            batch_size_cap: std::num::NonZeroUsize::new(1).unwrap(),
        };

        let batch_plan = plan
            .objstm_batches(&mut pdf, &cap1_config)
            .expect("Preserve with cap=1 must succeed");

        assert!(
            batch_plan.part3_batches.iter().any(|batch| {
                batch.contains(&ObjectRef::new(2, 0))
                    && batch.contains(&ObjectRef::new(5, 0))
                    && batch.len() == 2
            }),
            "cap=1 must not split source ObjStm 7: {:?}",
            batch_plan.part3_batches
        );

        // All previously expected objects must still appear.
        let all_batched: BTreeSet<ObjectRef> = batch_plan
            .part3_batches
            .iter()
            .flat_map(|b| b.iter().copied())
            .chain(
                batch_plan
                    .part4_batches
                    .iter()
                    .flat_map(|b| b.members.iter().copied()),
            )
            .collect();

        let resources_ref = ObjectRef::new(5, 0);
        let pages_ref = ObjectRef::new(2, 0);
        let page2_ref = ObjectRef::new(4, 0);
        assert!(
            !batch_plan.part3_batches.is_empty(),
            "Part-3 (5 0 R) is packed into the first-half ObjStm; part3_batches must be non-empty"
        );
        assert!(
            all_batched.contains(&resources_ref),
            "Part-3 Resources dict 5 0 R must be batched (packed into the first-half ObjStm)"
        );
        assert!(
            all_batched.contains(&pages_ref),
            "2 0 R (/Pages tree, routed to the first-half batch) must be batched even with cap=1"
        );
        assert!(
            !all_batched.contains(&page2_ref),
            "page dictionary 4 0 R must be removed from preserved ObjStms"
        );
    }

    /// One source ObjStm whose **two** members both land in Part 4 (they are
    /// eligible plain dicts reachable from neither page-1 nor any other page,
    /// so `from_pdf` keeps them in `part4_rest`).  This is the fixture the
    /// source-container retention path needs: a single source ObjStm
    /// contributing two eligible members to the same union route.
    ///
    /// The members are referenced from a neutral catalog key (`/Aux`) so they
    /// survive `from_pdf`'s reachability GC (flpdf-phfu) — `/Aux` is neither a
    /// page nor an open-document key, so they stay out of every page closure and
    /// land in `part4_rest`.
    fn objstm_two_part4_members_pdf_bytes() -> Vec<u8> {
        let mut bytes = b"%PDF-1.5\n".to_vec();

        let catalog_offset = bytes.len() as u32;
        bytes.extend_from_slice(
            b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R /Aux [10 0 R 11 0 R] >>\nendobj\n",
        );

        let pages_offset = bytes.len() as u32;
        bytes.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n");

        let page1_offset = bytes.len() as u32;
        bytes.extend_from_slice(
            b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>\nendobj\n",
        );

        // ObjStm #7: members [10, 11] — two eligible plain dicts referenced only
        // by the catalog's neutral /Aux key, so both are reachable (survive the
        // reachability GC) yet land in part4_rest (same part, same source ObjStm).
        let objstm_members: &[(u32, &[u8])] =
            &[(10, b"<< /Marker 10 >>"), (11, b"<< /Marker 11 >>")];
        let (stream_data, first) = build_objstm_payload_plan(objstm_members);
        let n = objstm_members.len() as u32;
        let objstm_offset = bytes.len() as u32;
        bytes.extend_from_slice(
            format!(
                "7 0 obj\n<< /Type /ObjStm /N {n} /First {first} /Length {} /Filter /FlateDecode >>\nstream\n",
                stream_data.len()
            )
            .as_bytes(),
        );
        bytes.extend_from_slice(&stream_data);
        bytes.extend_from_slice(b"\nendstream\nendobj\n");

        let xref_offset = bytes.len() as u32;
        let mut xref_entries: Vec<u8> = Vec::new();
        // 0..=11 plus xref stream obj 12 → Size 13.
        append_xref_entry_plan(&mut xref_entries, 0, 0, 0); // 0 free
        append_xref_entry_plan(&mut xref_entries, 1, catalog_offset, 0); // 1
        append_xref_entry_plan(&mut xref_entries, 1, pages_offset, 0); // 2
        append_xref_entry_plan(&mut xref_entries, 1, page1_offset, 0); // 3
        for _ in 4..=6 {
            append_xref_entry_plan(&mut xref_entries, 0, 0, 0); // 4..6 free
        }
        append_xref_entry_plan(&mut xref_entries, 1, objstm_offset, 0); // 7 ObjStm
        for _ in 8..=9 {
            append_xref_entry_plan(&mut xref_entries, 0, 0, 0); // 8..9 free
        }
        append_xref_entry_plan(&mut xref_entries, 2, 7, 0); // 10 in ObjStm 7 idx 0
        append_xref_entry_plan(&mut xref_entries, 2, 7, 1); // 11 in ObjStm 7 idx 1
        append_xref_entry_plan(&mut xref_entries, 1, xref_offset, 0); // 12 XRef

        bytes.extend_from_slice(
            format!(
                "12 0 obj\n<< /Type /XRef /Size 13 /Root 1 0 R /W [1 3 1] /Index [0 13] /Length {} >>\nstream\n",
                xref_entries.len()
            )
            .as_bytes(),
        );
        bytes.extend_from_slice(&xref_entries);
        bytes.extend_from_slice(b"\nendstream\nendobj\n");
        bytes.extend_from_slice(format!("startxref\n{xref_offset}\n%%EOF\n").as_bytes());
        bytes
    }

    /// A source ObjStm with two same-route members remains one container for
    /// every configured planner cap.
    #[test]
    fn objstm_batches_preserve_cap_never_splits_source_container() {
        let bytes = objstm_two_part4_members_pdf_bytes();
        let mut pdf = Pdf::open(Cursor::new(bytes)).expect("fixture should parse");
        let plan = LinearizationPlan::from_pdf(&mut pdf, false).unwrap();

        let m10 = ObjectRef::new(10, 0);
        let m11 = ObjectRef::new(11, 0);

        // Both members are Part-4 (not in any page closure → part4_rest).
        let part4: BTreeSet<ObjectRef> = plan
            .part4_other_pages_private
            .iter()
            .chain(&plan.part4_other_pages_shared)
            .chain(&plan.part4_rest)
            .copied()
            .collect();
        assert!(
            part4.contains(&m10) && part4.contains(&m11),
            "fixture invariant: 10 0 R and 11 0 R must both be Part-4"
        );

        // cap=1: both members remain in their one source container.
        let cap1 = PlannerConfig {
            mode: crate::writer::object_streams::ObjectStreamMode::Preserve,
            batch_size_cap: std::num::NonZeroUsize::new(1).unwrap(),
        };
        let bp1 = plan
            .objstm_batches(&mut pdf, &cap1)
            .expect("Preserve cap=1 must succeed");
        let b10 = bp1.part4_batches.iter().position(|b| b.contains(&m10));
        let b11 = bp1.part4_batches.iter().position(|b| b.contains(&m11));
        assert!(
            b10.is_some() && b11.is_some(),
            "both members must be batched at cap=1; part4_batches={:?}",
            bp1.part4_batches
        );
        assert_eq!(
            b10, b11,
            "cap=1 must not split 10 0 R and 11 0 R from their source ObjStm"
        );

        // cap=2 produces the identical preserved-container plan.
        let cap2 = PlannerConfig {
            mode: crate::writer::object_streams::ObjectStreamMode::Preserve,
            batch_size_cap: std::num::NonZeroUsize::new(2).unwrap(),
        };
        let bp2 = plan
            .objstm_batches(&mut pdf, &cap2)
            .expect("Preserve cap=2 must succeed");
        let same_batch = bp2
            .part4_batches
            .iter()
            .any(|b| b.contains(&m10) && b.contains(&m11));
        assert!(
            same_batch,
            "cap=2: 10 0 R and 11 0 R must share one batch; part4_batches={:?}",
            bp2.part4_batches
        );
        assert_eq!(
            bp1, bp2,
            "Preserve source-container membership must be independent of planner cap"
        );
    }

    // -----------------------------------------------------------------------
    // Generate: part3 objects go only to part3_batches, part4 to part4_batches
    // -----------------------------------------------------------------------
    #[test]
    fn objstm_batches_generate_cross_part_placement() {
        // Use two-page fixture: Part3 = Resources (5 0 R) + Font (8 0 R)
        //                       Part4 = page 2 dict (4 0 R) + content stream (7 0 R ineligible)
        let bytes = two_page_shared_font_bytes();
        let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
        let plan = LinearizationPlan::from_pdf(&mut pdf, false).unwrap();

        let batch_plan = plan.objstm_batches(&mut pdf, &generate_config()).unwrap();

        let all_part3_batched: std::collections::BTreeSet<ObjectRef> = batch_plan
            .part3_batches
            .iter()
            .flat_map(|b| b.iter().copied())
            .collect();
        let all_part4_batched: std::collections::BTreeSet<ObjectRef> = batch_plan
            .part4_batches
            .iter()
            .flat_map(|b| b.iter().copied())
            .collect();

        // The first-half (Part-3) batch holds the Part-3 objects (Resources
        // 5 0 R + Font 8 0 R) PLUS the /Pages tree (2 0 R), folded in by the
        // qpdf member-set canonicalisation.  No /Info in this fixture.
        let part3_set: std::collections::BTreeSet<ObjectRef> =
            plan.part3_objects.iter().copied().collect();
        let pages_tree = plan
            .pages_tree_ref
            .expect("two-page fixture has a /Pages tree");
        for r in &all_part3_batched {
            assert!(
                part3_set.contains(r) || *r == pages_tree,
                "object {r} in part3_batches must be a Part-3 object or the folded /Pages tree"
            );
        }
        // The /Pages tree was folded into the first-half batch.
        assert!(
            all_part3_batched.contains(&pages_tree),
            "the /Pages tree ({pages_tree}) must be folded into the first-half batch"
        );
        // No Part-3 object, the /Pages tree, or the /Catalog may appear in
        // part4_batches (Catalog stays standalone; Pages migrates to part3).
        let catalog = plan.root_ref.expect("fixture has a /Catalog");
        for r in &all_part4_batched {
            assert!(
                !part3_set.contains(r),
                "part3 object {r} must not appear in part4_batches"
            );
            assert_ne!(
                *r, pages_tree,
                "the /Pages tree must not remain in part4_batches"
            );
            assert_ne!(
                *r, catalog,
                "the /Catalog must stay standalone, not in part4_batches"
            );
        }
    }

    /// Single-page Generate (no first-page shared objects, so `part3_batches` is
    /// empty): the document `/Catalog` must still be excluded from the Part-4
    /// ObjStm batches, because qpdf never compresses the Catalog (the linearized
    /// `generateObjectStreams` erases it from the compressible set).  Guards the
    /// Catalog exclusion against regressing for the no-first-half-batch case.
    #[test]
    fn objstm_batches_generate_keeps_catalog_standalone_single_page() {
        let mut pdf = open_tiny_pdf();
        let plan = LinearizationPlan::from_pdf(&mut pdf, false).unwrap();

        // Single page → no first-page SHARED objects → no first-half batch.
        let batch_plan = plan.objstm_batches(&mut pdf, &generate_config()).unwrap();
        assert!(
            batch_plan.part3_batches.is_empty(),
            "single-page document has no first-page shared objects (no Part-3 batch)"
        );

        let all_part3_batched: std::collections::BTreeSet<ObjectRef> = batch_plan
            .part3_batches
            .iter()
            .flat_map(|b| b.iter().copied())
            .collect();
        let all_part4_batched: std::collections::BTreeSet<ObjectRef> = batch_plan
            .part4_batches
            .iter()
            .flat_map(|b| b.iter().copied())
            .collect();

        let catalog = plan.root_ref.expect("fixture has a /Catalog");
        assert!(
            !all_part3_batched.contains(&catalog) && !all_part4_batched.contains(&catalog),
            "the /Catalog ({catalog}) must stay standalone (in no ObjStm batch), \
             even when there is no first-half Part-3 batch"
        );

        // The /Pages tree is an eligible plain dict in Part-4 here (it is not
        // folded into the first half without a Part-3 batch), so it remains
        // batched — confirming only the Catalog was filtered out, not the whole
        // batch.
        let pages_tree = ObjectRef::new(2, 0);
        assert!(
            all_part4_batched.contains(&pages_tree),
            "the /Pages tree (2 0 R) must remain in part4_batches when there is \
             no first-half batch to fold it into"
        );
    }

    // -----------------------------------------------------------------------
    // canonical_shared_hints: fold first-page ObjStm members into a container
    // -----------------------------------------------------------------------

    /// Two members of the same first-half container that reference DIFFERENT
    /// pages must fold into ONE container entry whose `referencing_pages` is the
    /// sorted union of both members' pages (exercises the merge-insert path).
    #[test]
    fn canonical_shared_hints_folds_members_and_unions_pages() {
        let page = ObjectRef::new(3, 0);
        let content = ObjectRef::new(9, 0);
        let font_dict = ObjectRef::new(1, 0);
        let font = ObjectRef::new(2, 0);
        let plan = LinearizationPlan {
            part2_objects: vec![page, content],
            part3_objects: vec![font_dict, font],
            shared_hints: vec![
                SharedObjectHintEntry {
                    object_ref: page,
                    referencing_pages: vec![],
                },
                SharedObjectHintEntry {
                    object_ref: content,
                    referencing_pages: vec![],
                },
                // font_dict referenced by page 1; font by page 2 — different
                // pages, so the union must contain both (forces the insert).
                SharedObjectHintEntry {
                    object_ref: font_dict,
                    referencing_pages: vec![1],
                },
                SharedObjectHintEntry {
                    object_ref: font,
                    referencing_pages: vec![2],
                },
            ],
            ..Default::default()
        };

        // Both font_dict and font live in container 12 (the first-half ObjStm).
        let mut m2c: BTreeMap<ObjectRef, (u32, u32)> = BTreeMap::new();
        m2c.insert(font_dict, (12, 0));
        m2c.insert(font, (12, 1));

        // The first-page section is ordered by physical object number. With
        // this plan `RenumberMap::from_plan` assigns page=3, content=4 (Part 2),
        // and the container is numbered 12, so the post-sort order is
        // [page, content, container].
        let renumber = RenumberMap::from_plan(&plan);
        let folded =
            plan.canonical_shared_hints(&m2c, &renumber, &Default::default(), &Default::default());
        // page, content, and ONE container entry = 3 entries (members folded).
        assert_eq!(
            folded.len(),
            3,
            "members must fold into one container entry"
        );
        assert_eq!(folded[0].object_ref, page);
        assert_eq!(folded[1].object_ref, content);
        // The container entry carries the container's new number (12) with the
        // sentinel generation u16::MAX (so it is never mistaken for a real
        // object numbered 12).
        assert_eq!(folded[2].object_ref, ObjectRef::new(12, u16::MAX));
        // Its referencing_pages is the sorted union {1, 2}.
        assert_eq!(
            folded[2].referencing_pages,
            vec![1, 2],
            "container entry must union both members' referencing pages"
        );
    }

    /// A shared-hint entry with no `RenumberMap` mapping must not panic the
    /// first-page sort. A malformed source can carry a reserved/dangling ref
    /// (object number 0, any generation) into the first-page closure and thus
    /// into `shared_hints`; `place_objstm_members_per_half` rebuilds the forward
    /// index while dropping object number 0 (it doubles as the reserved-slot
    /// sentinel), so such an entry has no mapping here. The sort must place it
    /// deterministically last instead of aborting — the writer's shared-hint
    /// back-patch then reports the planner/renumber inconsistency as a
    /// structured error before any bytes are emitted.
    #[test]
    fn canonical_shared_hints_missing_renumber_entry_sorts_last_without_panic() {
        let page = ObjectRef::new(3, 0);
        let missing = ObjectRef::new(0, 0);
        let font_dict = ObjectRef::new(1, 0);
        let plan = LinearizationPlan {
            part2_objects: vec![page, missing],
            part3_objects: vec![font_dict],
            shared_hints: vec![
                SharedObjectHintEntry {
                    object_ref: missing,
                    referencing_pages: vec![],
                },
                SharedObjectHintEntry {
                    object_ref: page,
                    referencing_pages: vec![],
                },
                SharedObjectHintEntry {
                    object_ref: font_dict,
                    referencing_pages: vec![1],
                },
            ],
            ..Default::default()
        };

        // font_dict packs into a first-half ObjStm container; `missing` and
        // `page` stay plain. The container is folded to one entry numbered 12.
        let mut m2c: BTreeMap<ObjectRef, (u32, u32)> = BTreeMap::new();
        m2c.insert(font_dict, (12, 0));

        let mut renumber = RenumberMap::from_plan(&plan);
        renumber.place_objstm_members_per_half(
            &[],
            &[vec![font_dict]],
            &[],
            &[],
            &Default::default(),
            &Default::default(),
        );
        // Relocation drops object number 0 from the forward index, so the
        // reserved ref has no mapping — the precondition for the regression.
        assert!(
            renumber.new_for_original(missing).is_none(),
            "ObjStm relocation must drop object number 0 from the renumber map"
        );

        let folded =
            plan.canonical_shared_hints(&m2c, &renumber, &Default::default(), &Default::default());

        // No panic, and the unmapped entry sorts last (key u32::MAX) behind the
        // real page object and the folded container (new #12, sentinel gen).
        assert_eq!(folded.len(), 3);
        assert_eq!(folded[0].object_ref, page);
        assert_eq!(folded[1].object_ref, ObjectRef::new(12, u16::MAX));
        assert_eq!(folded[2].object_ref, missing);
    }

    /// With an empty member-to-container map (no ObjStm packing) the folded list
    /// is a verbatim clone of `shared_hints` (classic path unchanged).
    #[test]
    fn canonical_shared_hints_empty_map_is_identity() {
        let page = ObjectRef::new(3, 0);
        let plan = LinearizationPlan {
            part2_objects: vec![page],
            shared_hints: vec![SharedObjectHintEntry {
                object_ref: page,
                referencing_pages: vec![],
            }],
            ..Default::default()
        };
        // The empty-map branch returns before using `renumber`, so any map works.
        let renumber = RenumberMap::from_plan(&plan);
        let folded = plan.canonical_shared_hints(
            &BTreeMap::new(),
            &renumber,
            &Default::default(),
            &Default::default(),
        );
        assert_eq!(folded, plan.shared_hints);
    }

    /// A Part-8 entry (`part4_other_pages_shared`, after /E) is NOT sorted into
    /// the first-page section: only the leading part2 ++ part3 entries are
    /// reordered by physical object number. Here a plain ineligible shared
    /// stream (`image`), physically numbered BEFORE the container, must sort
    /// BEFORE the folded container within the first-page section, while the
    /// trailing Part-8 entry stays last regardless of its physical number.
    #[test]
    fn canonical_shared_hints_orders_first_page_and_keeps_part8_last() {
        let page = ObjectRef::new(8, 0);
        let content = ObjectRef::new(9, 0);
        let image = ObjectRef::new(10, 0);
        let font_dict = ObjectRef::new(1, 0);
        let other_shared = ObjectRef::new(7, 0);
        let plan = LinearizationPlan {
            // part2 ++ part3 form the first-page section; font_dict is the only
            // ObjStm-eligible member (folded into container 11).
            part2_objects: vec![page, content, image],
            part3_objects: vec![font_dict],
            // Part-8: one other-pages shared object.
            part4_other_pages_shared: vec![other_shared],
            shared_hints: vec![
                SharedObjectHintEntry {
                    object_ref: page,
                    referencing_pages: vec![],
                },
                SharedObjectHintEntry {
                    object_ref: content,
                    referencing_pages: vec![],
                },
                // font_dict is eligible → folds into container 11, which is
                // physically numbered AFTER the plain `image` stream.
                SharedObjectHintEntry {
                    object_ref: font_dict,
                    referencing_pages: vec![1],
                },
                SharedObjectHintEntry {
                    object_ref: image,
                    referencing_pages: vec![1],
                },
                // Part-8 entry (after /E): must remain last after the sort.
                SharedObjectHintEntry {
                    object_ref: other_shared,
                    referencing_pages: vec![2],
                },
            ],
            ..Default::default()
        };

        // font_dict lives in container 11 (the first-half ObjStm).
        let mut m2c: BTreeMap<ObjectRef, (u32, u32)> = BTreeMap::new();
        m2c.insert(font_dict, (11, 0));

        let renumber = RenumberMap::from_plan(&plan);
        let folded =
            plan.canonical_shared_hints(&m2c, &renumber, &Default::default(), &Default::default());

        // 3 plain first-page entries (page, content, image) + 1 folded
        // container + 1 Part-8 entry = 5 (only font_dict folded away).
        assert_eq!(folded.len(), 5, "only the eligible member folds");
        // First-page section ordered by physical number: page, content come
        // first (Part 2), then `image` (last Part 2), then the container 11.
        assert_eq!(folded[0].object_ref, page);
        assert_eq!(folded[1].object_ref, content);
        assert_eq!(folded[2].object_ref, image);
        assert_eq!(folded[3].object_ref, ObjectRef::new(11, u16::MAX));
        // Part-8 entry stays last (not pulled into the first-page sort).
        assert_eq!(folded[4].object_ref, other_shared);
    }

    /// A second-half (outline-routed, Part-4) ObjStm container that appears in
    /// the first-page section of `shared_hints` must be skipped entirely when
    /// `second_half_container_nums` contains its number.  qpdf does not emit
    /// these containers in the Shared Object Hint Table's first-page section.
    #[test]
    fn canonical_shared_hints_skips_second_half_container_in_first_page_section() {
        let page = ObjectRef::new(3, 0);
        let content = ObjectRef::new(9, 0);
        let font_dict = ObjectRef::new(1, 0);
        let plan = LinearizationPlan {
            part2_objects: vec![page, content],
            part3_objects: vec![font_dict],
            shared_hints: vec![
                SharedObjectHintEntry {
                    object_ref: page,
                    referencing_pages: vec![],
                },
                SharedObjectHintEntry {
                    object_ref: content,
                    referencing_pages: vec![],
                },
                SharedObjectHintEntry {
                    object_ref: font_dict,
                    referencing_pages: vec![1],
                },
            ],
            ..Default::default()
        };

        // font_dict lives in container 20, which is a second-half (Part-4) container.
        let mut m2c: BTreeMap<ObjectRef, (u32, u32)> = BTreeMap::new();
        m2c.insert(font_dict, (20, 0));

        // Mark container 20 as second-half so it should be skipped.
        let mut second_half: BTreeSet<u32> = BTreeSet::new();
        second_half.insert(20);

        let renumber = RenumberMap::from_plan(&plan);
        let folded =
            plan.canonical_shared_hints(&m2c, &renumber, &second_half, &Default::default());

        // The second-half container entry must be absent from the result.
        // Only the two plain first-page entries (page, content) survive;
        // font_dict's container is skipped entirely (not folded, not emitted).
        assert_eq!(
            folded.len(),
            2,
            "second-half container must be excluded from first-page section"
        );
        assert_eq!(folded[0].object_ref, page);
        assert_eq!(folded[1].object_ref, content);
        // Confirm the second-half container sentinel is absent.
        assert!(
            folded
                .iter()
                .all(|e| e.object_ref != ObjectRef::new(20, u16::MAX)),
            "container 20 sentinel must not appear"
        );
    }

    /// An open-document (before /O) ObjStm container that appears in the
    /// first-page section of `shared_hints` must be skipped entirely when
    /// `open_document_container_nums` contains its number.  Objects placed before
    /// /O are not part of the first-page [/O,/E) section and must not appear in
    /// the Shared Object Hint Table's first-page entries.
    #[test]
    fn canonical_shared_hints_skips_open_document_container_in_first_page_section() {
        let page = ObjectRef::new(3, 0);
        let content = ObjectRef::new(9, 0);
        let font_dict = ObjectRef::new(1, 0);
        let plan = LinearizationPlan {
            part2_objects: vec![page, content],
            part3_objects: vec![font_dict],
            shared_hints: vec![
                SharedObjectHintEntry {
                    object_ref: page,
                    referencing_pages: vec![],
                },
                SharedObjectHintEntry {
                    object_ref: content,
                    referencing_pages: vec![],
                },
                SharedObjectHintEntry {
                    object_ref: font_dict,
                    referencing_pages: vec![1],
                },
            ],
            ..Default::default()
        };

        // font_dict lives in container 30, which is an open-document (before /O) container.
        let mut m2c: BTreeMap<ObjectRef, (u32, u32)> = BTreeMap::new();
        m2c.insert(font_dict, (30, 0));

        // Mark container 30 as open-document so it should be skipped.
        let mut open_doc: BTreeSet<u32> = BTreeSet::new();
        open_doc.insert(30);

        let renumber = RenumberMap::from_plan(&plan);
        let folded = plan.canonical_shared_hints(&m2c, &renumber, &Default::default(), &open_doc);

        // The open-document container entry must be absent from the result.
        // Only the two plain first-page entries (page, content) survive;
        // font_dict's container is skipped entirely (not folded, not emitted).
        assert_eq!(
            folded.len(),
            2,
            "open-document container must be excluded from first-page section"
        );
        assert_eq!(folded[0].object_ref, page);
        assert_eq!(folded[1].object_ref, content);
        // Confirm the open-document container sentinel is absent.
        assert!(
            folded
                .iter()
                .all(|e| e.object_ref != ObjectRef::new(30, u16::MAX)),
            "container 30 sentinel must not appear"
        );
    }

    /// A part9 (Rest) ObjStm container routed there by qpdf's outline priority
    /// (it co-locates an in_outlines `!UseOutlines` member with a
    /// `part4_other_pages_shared` member via the even split) must be skipped in
    /// the Part-8 section of the Shared Object Hint Table — while a *legitimate*
    /// part8 container is kept. This locks the narrow part9-only exclusion: a
    /// naive `second_half_container_nums`-wide skip in the Part-8 section would
    /// wrongly drop the legitimate part8 container's referencing pages too.
    /// Mirrors the `objstm-lin-outlines-otherpage` byte fixture (flpdf-7aek).
    #[test]
    fn canonical_shared_hints_skips_part9_outline_container_in_part8_section() {
        // Container A (20): a part9 container — holds an in_outlines member
        // (`outline`, in `part9_outline_objects`), a `part4_other_pages_shared`
        // member (`shared_a`), and a first-page-private member (`fp_priv`). The
        // first-page member keeps A out of `part8_container_nums` (so the
        // enumeration tail cannot re-add it), exactly as the single-container
        // byte fixture's container carries page-0's private fonts.
        let fp_priv = ObjectRef::new(2, 0);
        let outline = ObjectRef::new(6, 0);
        let shared_a = ObjectRef::new(7, 0);
        // Container B (21): a legitimate part8 (other-page-shared) container.
        let shared_b = ObjectRef::new(8, 0);
        let plan = LinearizationPlan {
            part3_objects: vec![fp_priv],
            part4_other_pages_shared: vec![shared_a, shared_b],
            // `outline` is routed to part9 (Rest) by the !UseOutlines priority.
            part9_outline_objects: vec![outline],
            shared_hints: vec![
                // first-page section (input_idx < first_page_input = 1):
                SharedObjectHintEntry {
                    object_ref: fp_priv,
                    referencing_pages: vec![],
                },
                // Part-8 section (input_idx >= first_page_input):
                SharedObjectHintEntry {
                    object_ref: shared_a,
                    referencing_pages: vec![1],
                },
                SharedObjectHintEntry {
                    object_ref: shared_b,
                    referencing_pages: vec![2],
                },
            ],
            ..Default::default()
        };

        let mut m2c: BTreeMap<ObjectRef, (u32, u32)> = BTreeMap::new();
        m2c.insert(fp_priv, (20, 0));
        m2c.insert(outline, (20, 1));
        m2c.insert(shared_a, (20, 2));
        m2c.insert(shared_b, (21, 0));

        // Both A and B are Part-4 (second-half) containers.
        let mut second_half: BTreeSet<u32> = BTreeSet::new();
        second_half.insert(20);
        second_half.insert(21);

        let renumber = RenumberMap::from_plan(&plan);
        let folded =
            plan.canonical_shared_hints(&m2c, &renumber, &second_half, &Default::default());

        // Container A (20, part9) must be absent.
        assert!(
            folded
                .iter()
                .all(|e| e.object_ref != ObjectRef::new(20, u16::MAX)),
            "part9 outline-routed container 20 must be skipped in the Part-8 section"
        );
        // Container B (21, part8) must be kept AND carry the pages folded from its
        // `shared_hints` member (the union from the main loop, NOT the empty list
        // a naive skip + enumeration re-add would leave). `all_referenced_pages`
        // is empty here, so the recompute tail is a no-op and this distinguishes
        // the correct fold from a naive `second_half`-wide skip.
        let b_entry = folded
            .iter()
            .find(|e| e.object_ref == ObjectRef::new(21, u16::MAX))
            .expect("legitimate part8 container 21 must be kept");
        assert_eq!(
            b_entry.referencing_pages,
            vec![2],
            "part8 container 21 must keep its folded referencing page (not be \
             dropped and re-added empty by a naive second_half-wide skip)"
        );
    }

    /// A part9 (Rest) container with NO first-page member (e.g. page 0 carries no
    /// ObjStm-eligible private object) is dropped by the main-loop guard, but
    /// `part8_container_nums` (keyed on page reachability) would otherwise re-add
    /// it in the enumeration tail. The tail's `rest_container_nums` guard must
    /// prevent that re-add. Covers the `objstm-lin-outlines-otherpage-0-60-20`
    /// byte fixture (flpdf-7aek, Codex P2).
    #[test]
    fn canonical_shared_hints_part9_container_not_re_added_by_part8_enumeration() {
        let outline = ObjectRef::new(6, 0);
        let shared_a = ObjectRef::new(7, 0);
        let plan = LinearizationPlan {
            // No part2/part3: the first page contributes no shared/private ObjStm
            // member, so container 20 has no first-page member.
            part4_other_pages_shared: vec![shared_a],
            part9_outline_objects: vec![outline],
            shared_hints: vec![SharedObjectHintEntry {
                object_ref: shared_a,
                referencing_pages: vec![1, 2],
            }],
            ..Default::default()
        };

        // Container 20 holds the in_outlines member (→ part9) and the shared font.
        let mut m2c: BTreeMap<ObjectRef, (u32, u32)> = BTreeMap::new();
        m2c.insert(outline, (20, 0));
        m2c.insert(shared_a, (20, 1));
        let mut second_half: BTreeSet<u32> = BTreeSet::new();
        second_half.insert(20);

        let renumber = RenumberMap::from_plan(&plan);
        let folded =
            plan.canonical_shared_hints(&m2c, &renumber, &second_half, &Default::default());

        // `part8_container_nums` classifies 20 as part8 (no first-page member, has
        // a shared member), but the enumeration-tail guard must keep it out.
        assert!(
            plan.part8_container_nums(&m2c).contains(&20),
            "precondition: part8_container_nums would otherwise re-add container 20"
        );
        assert!(
            folded
                .iter()
                .all(|e| e.object_ref != ObjectRef::new(20, u16::MAX)),
            "part9 container 20 (no first-page member) must not be re-added by the \
             part8 enumeration tail"
        );
    }

    // -- Linearized generate-mode membership + container part routing --------
    //
    // These exercise `objstm_membership_linearized` + `route_objstm_containers`
    // against the qpdf-11.9.0-measured ground truth (the Rust builders below are
    // ports of docs/plans/tools/gen_mixed_shared.py and gen_three_page_shared.py;
    // the routing assertions match `qpdf --linearize --object-streams=generate`).

    /// Serialize objects (sorted by number) into a classic-xref PDF body with a
    /// `/Root 1 0 R /Info 6 0 R`-style trailer. `info_obj` is the /Info object
    /// number; `max_obj` is the highest object number present.
    fn assemble_classic_pdf(bodies: Vec<(u32, String)>, info_obj: u32, max_obj: u32) -> Vec<u8> {
        let mut bodies = bodies;
        bodies.sort_by_key(|(n, _)| *n);
        let mut pdf: Vec<u8> = Vec::new();
        pdf.extend_from_slice(b"%PDF-1.5\n%\xe2\xe3\xcf\xd3\n");
        let mut offsets: BTreeMap<u32, u64> = BTreeMap::new();
        for (n, body) in &bodies {
            offsets.insert(*n, pdf.len() as u64);
            pdf.extend_from_slice(format!("{n} 0 obj\n{body}\nendobj\n").as_bytes());
        }
        let xref_start = pdf.len() as u64;
        let size = max_obj + 1;
        let mut xref = format!("xref\n0 {size}\n0000000000 65535 f \n");
        for n in 1..size {
            xref.push_str(&format!("{:010} 00000 n \n", offsets[&n]));
        }
        pdf.extend_from_slice(xref.as_bytes());
        pdf.extend_from_slice(
            format!(
                "trailer\n<< /Size {size} /Root 1 0 R /Info {info_obj} 0 R >>\n\
                 startxref\n{xref_start}\n%%EOF\n"
            )
            .as_bytes(),
        );
        pdf
    }

    /// Port of `gen_mixed_shared.py s p`: 2 pages, page 0 references `s` shared
    /// fonts, page 1 references those `s` shared fonts plus `p` page-1-only fonts,
    /// trailer carries /Info. Layout: 1=Catalog 2=Pages 3=Page0 4=Page1 5=Info,
    /// 6..=5+s shared fonts, then `p` page-1-only fonts, then the two content
    /// streams. Font keys `/S#`,`/P#` sort lexically (matching the python).
    fn mixed_shared_pdf_bytes(s: u32, p: u32) -> Vec<u8> {
        let shared0 = 6u32;
        let p1only0 = shared0 + s;
        let c0 = p1only0 + p;
        let c1 = c0 + 1;
        let shared_res: String = (0..s)
            .map(|i| format!("/S{} {} 0 R", i + 1, shared0 + i))
            .collect::<Vec<_>>()
            .join(" ");
        let p1_extra: String = (0..p)
            .map(|i| format!("/P{} {} 0 R", i + 1, p1only0 + i))
            .collect::<Vec<_>>()
            .join(" ");
        let mut bodies: Vec<(u32, String)> = vec![
            (1, "<< /Type /Catalog /Pages 2 0 R >>".to_string()),
            (2, "<< /Type /Pages /Count 2 /Kids [ 3 0 R 4 0 R ] >>".to_string()),
            (5, "<< /Producer (flpdf-g6hb mixed fixture) >>".to_string()),
            (3, format!(
                "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << {shared_res} >> >> /Contents {c0} 0 R >>"
            )),
            (4, format!(
                "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << {shared_res} {p1_extra} >> >> /Contents {c1} 0 R >>"
            )),
        ];
        for i in 0..s {
            let n = shared0 + i;
            bodies.push((
                n,
                format!(
                    "<< /Type /Font /Subtype /Type1 /BaseFont /S{} /Mark {n} >>",
                    i + 1
                ),
            ));
        }
        for i in 0..p {
            let n = p1only0 + i;
            bodies.push((
                n,
                format!(
                    "<< /Type /Font /Subtype /Type1 /BaseFont /P{} /Mark {n} >>",
                    i + 1
                ),
            ));
        }
        for (cnum, label) in [(c0, "Page0"), (c1, "Page1")] {
            let stream = format!("BT /S1 12 Tf 72 720 Td ({label}) Tj ET");
            bodies.push((
                cnum,
                format!(
                    "<< /Length {} >>\nstream\n{stream}\nendstream",
                    stream.len()
                ),
            ));
        }
        assemble_classic_pdf(bodies, 5, c1)
    }

    /// Port of `gen_three_page_shared.py p0 g`: 3 pages, page 0 references `p0`
    /// private fonts, pages 1 AND 2 both reference the same `g` shared fonts
    /// (reach {1,2}, never page 0). Layout: 1=Catalog 2=Pages 3=Page0 4=Page1
    /// 5=Page2 6=Info, 7..=6+p0 page-0 fonts, then `g` shared fonts, then three
    /// content streams.
    fn three_page_shared_pdf_bytes(p0: u32, g: u32) -> Vec<u8> {
        let p0_0 = 7u32;
        let g0 = p0_0 + p0;
        let c0 = g0 + g;
        let c1 = c0 + 1;
        let c2 = c1 + 1;
        let p0_res: String = (0..p0)
            .map(|i| format!("/A{} {} 0 R", i + 1, p0_0 + i))
            .collect::<Vec<_>>()
            .join(" ");
        let g_res: String = (0..g)
            .map(|i| format!("/G{} {} 0 R", i + 1, g0 + i))
            .collect::<Vec<_>>()
            .join(" ");
        let mut bodies: Vec<(u32, String)> = vec![
            (1, "<< /Type /Catalog /Pages 2 0 R >>".to_string()),
            (2, "<< /Type /Pages /Count 3 /Kids [ 3 0 R 4 0 R 5 0 R ] >>".to_string()),
            (6, "<< /Producer (flpdf-g6hb three-page shared fixture) >>".to_string()),
            (3, format!(
                "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << {p0_res} >> >> /Contents {c0} 0 R >>"
            )),
            (4, format!(
                "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << {g_res} >> >> /Contents {c1} 0 R >>"
            )),
            (5, format!(
                "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << {g_res} >> >> /Contents {c2} 0 R >>"
            )),
        ];
        for i in 0..p0 {
            let n = p0_0 + i;
            bodies.push((
                n,
                format!(
                    "<< /Type /Font /Subtype /Type1 /BaseFont /A{} /Mark {n} >>",
                    i + 1
                ),
            ));
        }
        for i in 0..g {
            let n = g0 + i;
            bodies.push((
                n,
                format!(
                    "<< /Type /Font /Subtype /Type1 /BaseFont /G{} /Mark {n} >>",
                    i + 1
                ),
            ));
        }
        for (cnum, label) in [(c0, "Page0"), (c1, "Page1"), (c2, "Page2")] {
            let stream = format!("BT /A1 12 Tf 72 720 Td ({label}) Tj ET");
            bodies.push((
                cnum,
                format!(
                    "<< /Length {} >>\nstream\n{stream}\nendstream",
                    stream.len()
                ),
            ));
        }
        assemble_classic_pdf(bodies, 6, c2)
    }

    #[test]
    fn linearized_membership_even_splits_then_erases_page_dicts_and_root() {
        // gen_mixed_shared 60 70: 135 eligible => 2 streams (68 + 67); erase
        // Catalog + Page0 + Page1 (all in stream 0) => 65 + 67 members.
        let mut pdf = Pdf::open(Cursor::new(mixed_shared_pdf_bytes(60, 70))).unwrap();
        let assigned = LinearizationPlan::from_pdf(&mut pdf, true)
            .unwrap()
            .renumber_assigned_refs();
        let containers = objstm_membership_linearized(&mut pdf, &assigned).unwrap();
        assert_eq!(
            containers.len(),
            2,
            "135 eligible => 2 even-split containers"
        );
        assert_eq!(
            containers[0].len(),
            65,
            "stream 0 loses Catalog+Page0+Page1"
        );
        assert_eq!(containers[1].len(), 67, "stream 1 untouched by the erasure");
        // No page dict or root survives in any container.
        let root = pdf.root_ref().unwrap();
        let pages: BTreeSet<ObjectRef> = crate::pages::page_refs(&mut pdf)
            .unwrap()
            .into_iter()
            .collect();
        for c in &containers {
            for m in c {
                assert!(*m != root && !pages.contains(m), "{m:?} must be erased");
            }
        }
    }

    #[test]
    fn linearized_routes_mixed_shared_first_page_then_other_page_private() {
        // qpdf measured: stream 0 (shared fonts + Pages + Info) => part6;
        // stream 1 (page-1-only fonts) => part7.
        let mut pdf = Pdf::open(Cursor::new(mixed_shared_pdf_bytes(60, 70))).unwrap();
        let plan = LinearizationPlan::from_pdf(&mut pdf, true).unwrap();
        let assigned = plan.renumber_assigned_refs();
        let containers = objstm_membership_linearized(&mut pdf, &assigned).unwrap();
        let routes = route_with_plan(&plan, &containers);
        assert_eq!(
            routes,
            vec![
                ContainerPart::FirstPageShared,
                ContainerPart::OtherPagePrivate
            ]
        );
    }

    #[test]
    fn linearized_routes_three_page_shared_first_page_then_other_page_shared() {
        // qpdf measured: stream 0 (page-0-private fonts + Pages + Info) => part6;
        // stream 1 (fonts shared by pages 1 & 2, reach {1,2}) => part8.
        let mut pdf = Pdf::open(Cursor::new(three_page_shared_pdf_bytes(2, 120))).unwrap();
        let plan = LinearizationPlan::from_pdf(&mut pdf, true).unwrap();
        let assigned = plan.renumber_assigned_refs();
        let containers = objstm_membership_linearized(&mut pdf, &assigned).unwrap();
        let routes = route_with_plan(&plan, &containers);
        assert_eq!(
            routes,
            vec![
                ContainerPart::FirstPageShared,
                ContainerPart::OtherPageShared
            ]
        );
    }

    #[test]
    fn route_objstm_containers_distinguishes_first_page_private_and_shared() {
        let mut pdf = Pdf::open(Cursor::new(thumb_first_page_shared_pdf_bytes())).unwrap();
        let plan = LinearizationPlan::from_pdf(&mut pdf, true).unwrap();
        let routes = route_with_plan(
            &plan,
            &[vec![ObjectRef::new(6, 0)], vec![ObjectRef::new(5, 0)]],
        );
        assert_eq!(
            routes,
            vec![
                ContainerPart::FirstPagePrivate,
                ContainerPart::FirstPageShared,
            ]
        );
    }

    #[test]
    fn from_pdf_retains_routing_users_consistent_with_page_map() {
        let mut pdf = Pdf::open(Cursor::new(thumb_first_page_shared_pdf_bytes())).unwrap();
        let plan = LinearizationPlan::from_pdf(&mut pdf, true).unwrap();
        let users = plan
            .routing_users
            .as_ref()
            .expect("from_pdf must retain object-user routing data");

        let page_zero: BTreeSet<ObjectRef> = plan
            .all_referenced_pages
            .iter()
            .filter_map(|(&object_ref, pages)| pages.contains(&0).then_some(object_ref))
            .collect();

        assert_eq!(users.first_page, page_zero);
        assert!(
            users.thumbnails.contains(&ObjectRef::new(5, 0)),
            "the fixture's /Thumb target must retain a thumbnail user"
        );
        assert!(
            users.first_page.contains(&ObjectRef::new(6, 0)),
            "the fixture's first-page-private object must retain page 0"
        );
    }

    #[test]
    fn route_objstm_containers_keeps_same_page_self_thumb_private() {
        let mut pdf = Pdf::open(Cursor::new(self_thumb_first_page_private_pdf_bytes())).unwrap();
        let plan = LinearizationPlan::from_pdf(&mut pdf, true).unwrap();
        let routes = route_with_plan(&plan, &[vec![ObjectRef::new(5, 0)]]);
        assert_eq!(routes, vec![ContainerPart::FirstPagePrivate]);
    }

    #[test]
    fn route_objstm_containers_follows_direct_thumb_descendants() {
        let mut pdf = Pdf::open(Cursor::new(
            direct_thumb_descendant_first_page_shared_pdf_bytes(),
        ))
        .unwrap();
        let plan = LinearizationPlan::from_pdf(&mut pdf, true).unwrap();
        let routes = route_with_plan(&plan, &[vec![ObjectRef::new(5, 0)]]);
        assert_eq!(routes, vec![ContainerPart::FirstPageShared]);
    }

    #[test]
    fn route_objstm_containers_honors_thumb_first_edge_wins() {
        let mut pdf = Pdf::open(Cursor::new(
            thumb_before_ordinary_first_edge_wins_pdf_bytes(),
        ))
        .unwrap();
        let plan = LinearizationPlan::from_pdf(&mut pdf, true).unwrap();
        let routes = route_with_plan(&plan, &[vec![ObjectRef::new(5, 0)]]);
        assert_eq!(routes, vec![ContainerPart::Rest]);
    }

    #[test]
    fn route_objstm_containers_demotes_one_other_page_plus_thumbnail_to_rest() {
        let mut pdf =
            Pdf::open(Cursor::new(one_other_page_plus_thumbnail_user_pdf_bytes())).unwrap();
        let plan = LinearizationPlan::from_pdf(&mut pdf, true).unwrap();
        let routes = route_with_plan(&plan, &[vec![ObjectRef::new(6, 0)]]);
        assert_eq!(
            routes,
            vec![ContainerPart::Rest],
            "one non-first page user plus one thumbnail user is qpdf Part 9"
        );
    }

    #[test]
    fn linearized_routes_trailer_only_container_to_rest() {
        // A container whose members reach no page (here /Info, which is
        // trailer-only and not in any page closure) is qpdf part 9 — lc_other.
        // This does not arise from the even split on a font corpus (/Info is
        // DFS-early and co-located with first-page objects), but the routing is
        // exercised directly here.
        let mut pdf = Pdf::open(Cursor::new(mixed_shared_pdf_bytes(60, 70))).unwrap();
        let info_ref = pdf.trailer().get_ref("Info").unwrap();
        let synthetic = vec![vec![info_ref]];
        let plan = LinearizationPlan::from_pdf(&mut pdf, true).unwrap();
        let routes = route_with_plan(&plan, &synthetic);
        assert_eq!(routes, vec![ContainerPart::Rest]);
    }

    /// Three pages and one synthetic compressible member:
    ///
    /// - page 0 does not reach object 6;
    /// - page 1 reaches object 6 through `/Resources`;
    /// - page 2 reaches object 6 only through a direct `/Thumb` dictionary.
    ///
    /// The member union therefore has exactly `other_pages == 1`, `thumbs == 1`,
    /// and `others == 0`.
    fn one_other_page_plus_thumbnail_user_pdf_bytes() -> Vec<u8> {
        let mut pdf = Vec::new();
        pdf.extend_from_slice(b"%PDF-1.4\n");
        let mut offsets = [0u64; 7];
        let mut push = |number: usize, body: &[u8]| {
            offsets[number] = pdf.len() as u64;
            pdf.extend_from_slice(format!("{number} 0 obj\n").as_bytes());
            pdf.extend_from_slice(body);
            pdf.extend_from_slice(b"\nendobj\n");
        };
        push(1, b"<< /Type /Catalog /Pages 2 0 R >>");
        push(2, b"<< /Type /Pages /Count 3 /Kids [3 0 R 4 0 R 5 0 R] >>");
        push(
            3,
            b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>",
        );
        push(
            4,
            b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] \
              /Resources << /Font << /F1 6 0 R >> >> >>",
        );
        push(
            5,
            b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] \
              /Thumb << /Image 6 0 R >> >>",
        );
        push(6, b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>");
        let xref_start = pdf.len() as u64;
        pdf.extend_from_slice(b"xref\n0 7\n0000000000 65535 f \n");
        for offset in offsets.iter().skip(1) {
            pdf.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
        }
        pdf.extend_from_slice(
            format!("trailer\n<< /Size 7 /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n")
                .as_bytes(),
        );
        pdf
    }

    /// Build a two-page PDF whose FIRST page is fontless (no first-page
    /// compressible object) and whose SECOND page carries two private fonts:
    ///   1 – Catalog  (/Pages 2 0 R, /Ref2 6 0 R)
    ///   2 – Pages node  (Kids: [3 0 R, 4 0 R])
    ///   3 – Page 1  → /Contents 7 0 R              (fontless)
    ///   4 – Page 2  → /Resources << /Font << /FA 5 0 R /FB 6 0 R >> >>, /Contents 8 0 R
    ///   5 – Font  (page-2-private, others==0)       → lc_other_page_private (part7)
    ///   6 – Font  (page-2-private AND Catalog /Ref2) → others>0 → lc_other (part9)
    ///   7 – Content stream (page 1 only)
    ///   8 – Content stream (page 2 only)
    /// No `/Info`. With page 1 fontless, the generate-mode even split yields a
    /// single container {Pages(2), FA(5), FB(6)} with no first-page member, so it
    /// reaches the other-page arm — exactly the shape the compat golden would use.
    fn two_page_otherpage_others_and_private_bytes() -> Vec<u8> {
        let mut pdf = Vec::new();
        pdf.extend_from_slice(b"%PDF-1.4\n");
        let mut offs = [0u64; 9];
        let mut push = |pdf: &mut Vec<u8>, n: usize, body: &[u8]| {
            offs[n] = pdf.len() as u64;
            pdf.extend_from_slice(format!("{n} 0 obj\n").as_bytes());
            pdf.extend_from_slice(body);
            pdf.extend_from_slice(b"\nendobj\n");
        };
        push(
            &mut pdf,
            1,
            b"<< /Type /Catalog /Pages 2 0 R /Ref2 6 0 R >>",
        );
        push(
            &mut pdf,
            2,
            b"<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>",
        );
        push(
            &mut pdf,
            3,
            b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 7 0 R >>",
        );
        push(&mut pdf, 4, b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /FA 5 0 R /FB 6 0 R >> >> /Contents 8 0 R >>");
        push(
            &mut pdf,
            5,
            b"<< /Type /Font /Subtype /Type1 /BaseFont /Courier /Name /FA >>",
        );
        push(
            &mut pdf,
            6,
            b"<< /Type /Font /Subtype /Type1 /BaseFont /Times-Roman /Name /FB >>",
        );
        push(&mut pdf, 7, b"<< /Length 5 >>\nstream\nBT ET\nendstream");
        push(&mut pdf, 8, b"<< /Length 5 >>\nstream\nBT ET\nendstream");

        let xref_start = pdf.len() as u64;
        let mut xref = String::from("xref\n0 9\n0000000000 65535 f \n");
        for off in offs.iter().skip(1) {
            xref.push_str(&format!("{off:010} 00000 n \n"));
        }
        pdf.extend_from_slice(xref.as_bytes());
        pdf.extend_from_slice(
            format!("trailer\n<< /Size 9 /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n")
                .as_bytes(),
        );
        pdf
    }

    // Generate-path sibling of the classic `document_other_ref_routes_other_page
    // _object_to_part9` (flpdf-zda0 / flpdf-pn7h): `route_objstm_containers` must
    // gate the `other_pages==1` (part7) arm on others==0
    // (QPDF_linearization.cc:1128). A container whose member union includes a
    // `document_other_set` object is lc_other (part9 / Rest), not part7.
    #[test]
    fn generate_route_others_gate_demotes_other_page_container_to_rest() {
        let mut pdf =
            Pdf::open(Cursor::new(two_page_otherpage_others_and_private_bytes())).unwrap();
        let plan = LinearizationPlan::from_pdf(&mut pdf, true).unwrap();
        let fa = ObjectRef::new(5, 0); // page-2-private, others==0
        let fb = ObjectRef::new(6, 0); // page-2-private AND Catalog /Ref2 (others>0)

        // A container holding ONLY the others==0 page-2 font stays part7 (the
        // surviving `1 => OtherPagePrivate` arm).
        let routes = route_with_plan(&plan, &[vec![fa]]);
        assert_eq!(
            routes,
            vec![ContainerPart::OtherPagePrivate],
            "others==0 other-page container is lc_other_page_private (part7)"
        );

        // Add the /Ref2 font: the union now has others>0, so the whole container
        // is demoted to Rest (part9) — the gate under test.
        let routes = route_with_plan(&plan, &[vec![fb], vec![fa, fb]]);
        assert_eq!(
            routes,
            vec![ContainerPart::Rest, ContainerPart::Rest],
            "any document-`others` member (Catalog /Ref2) demotes part7 to part9"
        );

        // Integration: the real generate-mode even split (page 1 fontless) yields
        // a single container {Pages(2), FA(5), FB(6)} with no first-page member;
        // it routes to Rest because the union has others>0 (the Pages node via
        // /Pages and FB via /Ref2). Mirrors qpdf's part9 for this shape.
        let assigned = plan.renumber_assigned_refs();
        let containers = objstm_membership_linearized(&mut pdf, &assigned).unwrap();
        assert_eq!(
            containers.len(),
            1,
            "3 eligible => a single even-split container"
        );
        let routes = route_with_plan(&plan, &containers);
        assert_eq!(
            routes,
            vec![ContainerPart::Rest],
            "the {{Pages, FA, FB}} container is lc_other (part9); containers={containers:?}"
        );
    }

    /// A catalog `/OpenAction` whose action's `/D` destination reaches a `/Page`
    /// leaf (`[3 0 R /Fit]`) and whose `/Next` reaches a dict that references one
    /// object twice. Exercises [`open_document_set`]'s page-boundary stop (the
    /// page is dropped) and the `visited`-dedup short-circuit (the twice-referenced
    /// object is queued twice but recorded once).
    fn open_action_page_dest_pdf_bytes() -> Vec<u8> {
        let mut pdf = Vec::new();
        pdf.extend_from_slice(b"%PDF-1.5\n");
        let mut offs = [0u64; 7];
        let mut push = |pdf: &mut Vec<u8>, n: usize, body: &str| {
            offs[n] = pdf.len() as u64;
            pdf.extend_from_slice(format!("{n} 0 obj\n{body}\nendobj\n").as_bytes());
        };
        push(
            &mut pdf,
            1,
            "<< /Type /Catalog /OpenAction 5 0 R /Pages 2 0 R >>",
        );
        push(&mut pdf, 2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>");
        push(
            &mut pdf,
            3,
            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>",
        );
        // Referenced only from the action's /Next; references object 6 twice.
        push(&mut pdf, 4, "<< /A 6 0 R /B 6 0 R >>");
        // The action: /D reaches the page (boundary), /Next reaches object 4.
        push(
            &mut pdf,
            5,
            "<< /Type /Action /S /GoTo /D [3 0 R /Fit] /Next 4 0 R >>",
        );
        push(&mut pdf, 6, "<< /Leaf true >>");

        let xref_start = pdf.len() as u64;
        let mut xref = String::from("xref\n0 7\n0000000000 65535 f \n");
        for off in offs.iter().skip(1) {
            xref.push_str(&format!("{off:010} 00000 n \n"));
        }
        pdf.extend_from_slice(xref.as_bytes());
        pdf.extend_from_slice(
            format!("trailer\n<< /Size 7 /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n")
                .as_bytes(),
        );
        pdf
    }

    #[test]
    fn open_document_set_stops_at_page_and_dedups() {
        let mut pdf = Pdf::open(Cursor::new(open_action_page_dest_pdf_bytes())).unwrap();
        let set = open_document_set(&mut pdf).unwrap();
        // The action (5), its /Next dict (4), and the twice-referenced leaf (6)
        // are open-document; the /Page leaf (3) is dropped at the boundary and
        // the /Pages tree (2) is never reached (not an open-document key).
        let r = |n: u32| ObjectRef::new(n, 0);
        assert_eq!(
            set,
            [r(4), r(5), r(6)].into_iter().collect::<BTreeSet<_>>(),
            "open-document set = {{action, /Next dict, leaf}}; page leaf dropped"
        );
    }

    /// A catalog whose keys span every [`document_other_set`] / [`closure_from_seeds`]
    /// branch: included keys (`/Names`, `/Custom`), excluded keys (`/Outlines`,
    /// `/OpenAction`), the `/Pages` tree, a trailer `/Info`, and a `/Fake` key
    /// aliasing a `/Type /Pages` dict OUTSIDE the real page tree. The real page
    /// tree node carries an inherited `/Resources` (obj 10, SKIPPED like qpdf's
    /// stripped tree) plus a custom `/Ext` key (obj 11, FOLLOWED); the fake
    /// out-of-tree `/Pages` dict (obj 12) is NOT stripped, so its `/Resources`
    /// (obj 13) IS followed. `/Custom` references one object twice for `visited`
    /// dedup.
    fn document_other_pdf_bytes() -> Vec<u8> {
        let mut pdf = Vec::new();
        pdf.extend_from_slice(b"%PDF-1.5\n");
        let mut offs = [0u64; 14];
        let mut push = |pdf: &mut Vec<u8>, n: usize, body: &str| {
            offs[n] = pdf.len() as u64;
            pdf.extend_from_slice(format!("{n} 0 obj\n{body}\nendobj\n").as_bytes());
        };
        // /Outlines, /OpenAction are excluded; /Names, /Custom, the /Pages custom
        // key, and /Fake (an out-of-tree /Pages alias) are `others`.
        push(
            &mut pdf,
            1,
            "<< /Type /Catalog /Pages 2 0 R /Outlines 7 0 R /OpenAction 8 0 R \
             /Names 4 0 R /Custom 5 0 R /Fake 12 0 R >>",
        );
        // Real page-tree node: inherited /Resources (-> 10, skipped) + custom /Ext
        // (-> 11, followed); /Kids reaches the page leaf (dropped at the boundary).
        push(
            &mut pdf,
            2,
            "<< /Type /Pages /Kids [3 0 R] /Count 1 /Resources << /Inh 10 0 R >> /Ext 11 0 R >>",
        );
        push(
            &mut pdf,
            3,
            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>",
        );
        push(&mut pdf, 4, "<< /X 6 0 R >>"); // /Names target -> 6
        push(&mut pdf, 5, "<< /A 6 0 R /B 6 0 R >>"); // /Custom target -> 6 twice
        push(&mut pdf, 6, "<< /Leaf true >>");
        push(&mut pdf, 7, "<< /Type /Outlines >>"); // excluded (/Outlines)
        push(&mut pdf, 8, "<< /Type /Action /S /GoTo /D [3 0 R /Fit] >>"); // excluded (open-doc)
        push(&mut pdf, 9, "<< /Producer (x) >>"); // trailer /Info -> included
        push(&mut pdf, 10, "<< /InheritedResource true >>"); // page-tree /Resources -> SKIPPED
        push(&mut pdf, 11, "<< /CustomExtension true >>"); // page-tree /Ext -> FOLLOWED
                                                           // Out-of-tree /Type /Pages dict (reached via /Fake, not /Root/Pages/Kids):
                                                           // qpdf does NOT strip it, so its /Resources target (13) is followed.
        push(
            &mut pdf,
            12,
            "<< /Type /Pages /Resources << /FakeRes 13 0 R >> >>",
        );
        push(&mut pdf, 13, "<< /NotStripped true >>");
        let xref_start = pdf.len() as u64;
        let mut xref = String::from("xref\n0 14\n0000000000 65535 f \n");
        for off in offs.iter().skip(1) {
            xref.push_str(&format!("{off:010} 00000 n \n"));
        }
        pdf.extend_from_slice(xref.as_bytes());
        pdf.extend_from_slice(
            format!(
                "trailer\n<< /Size 14 /Root 1 0 R /Info 9 0 R >>\nstartxref\n{xref_start}\n%%EOF\n"
            )
            .as_bytes(),
        );
        pdf
    }

    #[test]
    fn document_other_set_excludes_doc_keys_and_stops_at_page() {
        let mut pdf = Pdf::open(Cursor::new(document_other_pdf_bytes())).unwrap();
        let set = document_other_set(&mut pdf).unwrap();
        let r = |n: u32| ObjectRef::new(n, 0);
        // Included: /Names (4) + target (6), /Custom (5) + the same target (6,
        // recorded once), trailer /Info (9), the real /Pages node (2) + its custom
        // /Ext target (11), and the out-of-tree /Fake /Pages dict (12) + its
        // /Resources target (13, NOT stripped since 12 is outside the page tree).
        // Excluded: /Outlines (7), /OpenAction (8), catalog/Root (1), the page
        // leaf (3, boundary), and the page-tree node's inherited /Resources target
        // (10, skipped like qpdf's stripped tree).
        assert_eq!(
            set,
            [r(2), r(4), r(5), r(6), r(9), r(11), r(12), r(13)]
                .into_iter()
                .collect::<BTreeSet<_>>(),
            "others = {{/Names, /Custom, /Info, page-tree node + custom /Ext, \
             out-of-tree /Pages + its /Resources}}; inherited /Resources (10), \
             page leaf (3), and doc keys excluded"
        );
    }

    /// A catalog `/Outlines` -> outline dict -> one item. [`outlines_set`] must
    /// collect the outline dict + item and exclude the page tree.
    fn outlines_pdf_bytes() -> Vec<u8> {
        let mut pdf = Vec::new();
        pdf.extend_from_slice(b"%PDF-1.5\n");
        let mut offs = [0u64; 7];
        let mut push = |pdf: &mut Vec<u8>, n: usize, body: &str| {
            offs[n] = pdf.len() as u64;
            pdf.extend_from_slice(format!("{n} 0 obj\n{body}\nendobj\n").as_bytes());
        };
        push(
            &mut pdf,
            1,
            "<< /Type /Catalog /Outlines 5 0 R /Pages 2 0 R >>",
        );
        push(&mut pdf, 2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>");
        push(
            &mut pdf,
            3,
            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>",
        );
        // 4 is unused (keeps numbering parallel to the other crafted fixtures).
        push(&mut pdf, 4, "<< /Unused true >>");
        push(
            &mut pdf,
            5,
            "<< /Type /Outlines /First 6 0 R /Last 6 0 R /Count 1 >>",
        );
        push(&mut pdf, 6, "<< /Title (Item) /Parent 5 0 R >>");
        let xref_start = pdf.len() as u64;
        let mut xref = String::from("xref\n0 7\n0000000000 65535 f \n");
        for off in offs.iter().skip(1) {
            xref.push_str(&format!("{off:010} 00000 n \n"));
        }
        pdf.extend_from_slice(xref.as_bytes());
        pdf.extend_from_slice(
            format!("trailer\n<< /Size 7 /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n")
                .as_bytes(),
        );
        pdf
    }

    #[test]
    fn outlines_set_collects_outline_tree_and_excludes_pages() {
        let mut pdf = Pdf::open(Cursor::new(outlines_pdf_bytes())).unwrap();
        let set = outlines_set(&mut pdf).unwrap();
        let r = |n: u32| ObjectRef::new(n, 0);
        assert_eq!(
            set,
            [r(5), r(6)].into_iter().collect::<BTreeSet<_>>(),
            "outlines set = {{outline dict, item}}; pages tree excluded"
        );
    }

    #[test]
    fn outlines_set_empty_when_no_outlines() {
        // The two-page fixture has no /Outlines key, so the set is empty (no /O).
        let mut pdf = Pdf::open(Cursor::new(two_page_shared_font_bytes())).unwrap();
        assert!(outlines_set(&mut pdf).unwrap().is_empty());
    }

    #[test]
    fn outlines_set_empty_for_non_dictionary_catalog() {
        // A /Root resolving to a non-dictionary yields no outline seeds (the
        // `if let Some(Object::Dictionary(..))` does not match).
        let mut pdf = Pdf::open(Cursor::new(non_dictionary_root_pdf_bytes())).unwrap();
        assert!(outlines_set(&mut pdf).unwrap().is_empty());
    }

    // Builds a variant of outlines_pdf_bytes() with /PageMode injected into
    // the catalog. Rebuilds the xref table so offsets remain valid.
    fn outlines_pdf_bytes_with_page_mode(mode: &[u8]) -> Vec<u8> {
        let mut pdf = Vec::new();
        pdf.extend_from_slice(b"%PDF-1.5\n");
        let mut offs = [0u64; 7];
        let mut push = |pdf: &mut Vec<u8>, n: usize, body: &[u8]| {
            offs[n] = pdf.len() as u64;
            pdf.extend_from_slice(format!("{n} 0 obj\n").as_bytes());
            pdf.extend_from_slice(body);
            pdf.extend_from_slice(b"\nendobj\n");
        };
        let catalog = format!(
            "<< /Type /Catalog /PageMode /{} /Outlines 5 0 R /Pages 2 0 R >>",
            std::str::from_utf8(mode).unwrap()
        );
        push(&mut pdf, 1, catalog.as_bytes());
        push(&mut pdf, 2, b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>");
        push(
            &mut pdf,
            3,
            b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>",
        );
        push(&mut pdf, 4, b"<< /Unused true >>");
        push(
            &mut pdf,
            5,
            b"<< /Type /Outlines /First 6 0 R /Last 6 0 R /Count 1 >>",
        );
        push(&mut pdf, 6, b"<< /Title (Item) /Parent 5 0 R >>");
        let xref_start = pdf.len() as u64;
        let mut xref = String::from("xref\n0 7\n0000000000 65535 f \n");
        for off in offs.iter().skip(1) {
            xref.push_str(&format!("{off:010} 00000 n \n"));
        }
        pdf.extend_from_slice(xref.as_bytes());
        pdf.extend_from_slice(
            format!("trailer\n<< /Size 7 /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n")
                .as_bytes(),
        );
        pdf
    }

    #[test]
    fn outlines_in_first_page_predicate_true_when_use_outlines_and_outlines_present() {
        let mut pdf = Pdf::open(Cursor::new(outlines_pdf_bytes_with_page_mode(
            b"UseOutlines",
        )))
        .unwrap();
        assert!(
            outlines_in_first_page_predicate(&mut pdf).unwrap(),
            "/PageMode /UseOutlines + /Outlines => predicate must be true"
        );
    }

    #[test]
    fn outlines_in_first_page_predicate_false_without_page_mode() {
        let mut pdf = Pdf::open(Cursor::new(outlines_pdf_bytes())).unwrap();
        assert!(
            !outlines_in_first_page_predicate(&mut pdf).unwrap(),
            "/Outlines with no /PageMode => predicate must be false"
        );
    }

    #[test]
    fn outlines_in_first_page_predicate_false_when_page_mode_not_use_outlines() {
        let mut pdf = Pdf::open(Cursor::new(outlines_pdf_bytes_with_page_mode(
            b"FullScreen",
        )))
        .unwrap();
        assert!(
            !outlines_in_first_page_predicate(&mut pdf).unwrap(),
            "/PageMode /FullScreen (not UseOutlines) => predicate must be false"
        );
    }

    #[test]
    fn outlines_in_first_page_predicate_false_when_no_outlines() {
        // two_page_shared_font_bytes has no /Outlines in the catalog.
        let mut pdf = Pdf::open(Cursor::new(two_page_shared_font_bytes())).unwrap();
        assert!(
            !outlines_in_first_page_predicate(&mut pdf).unwrap(),
            "catalog without /Outlines => predicate must be false"
        );
    }

    #[test]
    fn linearized_routes_open_document_container_before_page_categories() {
        // A container holding an open-document member routes to part 4
        // (OpenDocument) even when it ALSO holds a first-page member — qpdf checks
        // in_open_document before in_first_page.
        let mut pdf = Pdf::open(Cursor::new(open_action_page_dest_pdf_bytes())).unwrap();
        let plan = LinearizationPlan::from_pdf(&mut pdf, true).unwrap();
        // Object 5 is open-document; object 3 is the (first) page. A container
        // with both must route to OpenDocument (open-document precedence).
        let synthetic = vec![vec![ObjectRef::new(3, 0), ObjectRef::new(5, 0)]];
        let routes = route_with_plan(&plan, &synthetic);
        assert_eq!(routes, vec![ContainerPart::OpenDocument]);
    }

    #[test]
    fn route_objstm_containers_outlines_first_page_routes_to_first_page() {
        // Outline container routes to FirstPageOutlines when /PageMode /UseOutlines is set.
        // Object 5 = outline dict, object 6 = outline item in outlines_pdf_bytes.
        let mut pdf = Pdf::open(Cursor::new(outlines_pdf_bytes_with_page_mode(
            b"UseOutlines",
        )))
        .unwrap();
        let plan = LinearizationPlan::from_pdf(&mut pdf, true).unwrap();
        let outline_ref = ObjectRef::new(5, 0); // outline dict
        let synthetic = vec![vec![outline_ref]];
        let routes = route_with_plan(&plan, &synthetic);
        assert_eq!(
            routes,
            vec![ContainerPart::FirstPageOutlines],
            "outline container must route to FirstPageOutlines when /PageMode /UseOutlines"
        );
    }

    #[test]
    fn route_objstm_containers_outlines_no_use_outlines_routes_to_rest() {
        // Without /PageMode /UseOutlines, outline containers stay in Rest (part9).
        let mut pdf = Pdf::open(Cursor::new(outlines_pdf_bytes())).unwrap();
        let plan = LinearizationPlan::from_pdf(&mut pdf, true).unwrap();
        let outline_ref = ObjectRef::new(5, 0); // outline dict
        let synthetic = vec![vec![outline_ref]];
        let routes = route_with_plan(&plan, &synthetic);
        assert_eq!(
            routes,
            vec![ContainerPart::Rest],
            "outline container must route to Rest when no /PageMode /UseOutlines"
        );
    }

    /// A `/Root` that resolves to a NON-dictionary (a malformed catalog) yields
    /// no open-document seeds — the `if let Some(Object::Dictionary(..))` does not
    /// match and the helper returns an empty set. `Pdf::open` tolerates this (the
    /// catalog-type error only surfaces during page enumeration).
    fn non_dictionary_root_pdf_bytes() -> Vec<u8> {
        let mut pdf = Vec::new();
        pdf.extend_from_slice(b"%PDF-1.5\n");
        let mut offs = [0u64; 4];
        let mut push = |pdf: &mut Vec<u8>, n: usize, body: &str| {
            offs[n] = pdf.len() as u64;
            pdf.extend_from_slice(format!("{n} 0 obj\n{body}\nendobj\n").as_bytes());
        };
        push(&mut pdf, 1, "42"); // /Root points here — an integer, not a dict
        push(&mut pdf, 2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>");
        push(
            &mut pdf,
            3,
            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>",
        );
        let xref_start = pdf.len() as u64;
        let mut xref = String::from("xref\n0 4\n0000000000 65535 f \n");
        for off in offs.iter().skip(1) {
            xref.push_str(&format!("{off:010} 00000 n \n"));
        }
        pdf.extend_from_slice(xref.as_bytes());
        pdf.extend_from_slice(
            format!("trailer\n<< /Size 4 /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n")
                .as_bytes(),
        );
        pdf
    }

    #[test]
    fn open_document_set_empty_for_non_dictionary_catalog() {
        let mut pdf = Pdf::open(Cursor::new(non_dictionary_root_pdf_bytes())).unwrap();
        let set = open_document_set(&mut pdf).unwrap();
        assert!(
            set.is_empty(),
            "a non-dictionary catalog must yield no open-document objects, got {set:?}"
        );
    }

    #[test]
    fn document_other_set_empty_for_non_dictionary_catalog() {
        // /Root resolves to an integer (not a dict), so the catalog-key arm is
        // skipped; the trailer has only /Root and /Size, so no `others` seeds.
        let mut pdf = Pdf::open(Cursor::new(non_dictionary_root_pdf_bytes())).unwrap();
        let set = document_other_set(&mut pdf).unwrap();
        assert!(
            set.is_empty(),
            "a non-dictionary catalog must yield no document-other objects, got {set:?}"
        );
    }

    /// A page tree exercising every [`page_tree_node_refs`] branch: a `/Page`
    /// leaf (3), a nested childless `/Pages` node listed TWICE (4 — queued twice,
    /// so the second pop hits the `visited` short-circuit, and it has no `/Kids`
    /// so the `if let Some(kids)` is skipped), and a malformed non-dictionary
    /// `/Kids` entry (5).
    fn nested_page_tree_pdf_bytes() -> Vec<u8> {
        let mut pdf = Vec::new();
        pdf.extend_from_slice(b"%PDF-1.5\n");
        let mut offs = [0u64; 6];
        let mut push = |pdf: &mut Vec<u8>, n: usize, body: &str| {
            offs[n] = pdf.len() as u64;
            pdf.extend_from_slice(format!("{n} 0 obj\n{body}\nendobj\n").as_bytes());
        };
        push(&mut pdf, 1, "<< /Type /Catalog /Pages 2 0 R >>");
        // Root /Pages /Kids: leaf (3), nested /Pages (4) listed twice, non-dict (5).
        push(
            &mut pdf,
            2,
            "<< /Type /Pages /Kids [3 0 R 4 0 R 4 0 R 5 0 R] /Count 1 >>",
        );
        push(
            &mut pdf,
            3,
            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>",
        );
        push(&mut pdf, 4, "<< /Type /Pages /Parent 2 0 R /Count 0 >>"); // no /Kids
        push(&mut pdf, 5, "42"); // malformed non-dictionary /Kids entry -> skipped
        let xref_start = pdf.len() as u64;
        let mut xref = String::from("xref\n0 6\n0000000000 65535 f \n");
        for off in offs.iter().skip(1) {
            xref.push_str(&format!("{off:010} 00000 n \n"));
        }
        pdf.extend_from_slice(xref.as_bytes());
        pdf.extend_from_slice(
            format!("trailer\n<< /Size 6 /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n")
                .as_bytes(),
        );
        pdf
    }

    #[test]
    fn page_tree_node_refs_collects_interior_pages_only() {
        let mut pdf = Pdf::open(Cursor::new(nested_page_tree_pdf_bytes())).unwrap();
        let set = page_tree_node_refs(&mut pdf).unwrap();
        let r = |n: u32| ObjectRef::new(n, 0);
        // The two interior /Pages nodes (2, 4); the /Page leaf (3) and the
        // non-dictionary /Kids entry (5) are excluded. Node 4 is listed twice but
        // recorded once.
        assert_eq!(
            set,
            [r(2), r(4)].into_iter().collect::<BTreeSet<_>>(),
            "page tree = interior /Pages nodes only (leaf + non-dict kid excluded)"
        );
    }

    #[test]
    fn page_tree_node_refs_empty_for_non_dictionary_catalog() {
        // /Root is an integer, so there is no /Pages entry: empty page tree.
        let mut pdf = Pdf::open(Cursor::new(non_dictionary_root_pdf_bytes())).unwrap();
        assert!(page_tree_node_refs(&mut pdf).unwrap().is_empty());
    }

    /// One-page PDF whose catalog `/OpenAction` reaches a JavaScript action (obj
    /// 5) whose `/JS` stream (obj 6) has an INDIRECT `/Length` (`7 0 R`). The
    /// holder (obj 7) is reachable only via that `/Length` edge. flpdf-2vfg.
    fn od_indirect_length_pdf_bytes() -> Vec<u8> {
        let bodies: &[(u32, &[u8])] = &[
            (1, b"<< /Type /Catalog /Pages 2 0 R /OpenAction 5 0 R >>"),
            (2, b"<< /Type /Pages /Count 1 /Kids [ 3 0 R ] >>"),
            (
                3,
                b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R >>",
            ),
            (4, b"<< /Length 5 >>\nstream\nBT ET\nendstream"),
            (5, b"<< /Type /Action /S /JavaScript /JS 6 0 R >>"),
            (
                6,
                b"<< /Length 7 0 R >>\nstream\napp.alert('hi');\nendstream",
            ),
            (7, b"16"),
        ];
        let mut out: Vec<u8> = b"%PDF-1.7\n%\xe2\xe3\xcf\xd3\n".to_vec();
        let total = bodies.len() as u32 + 1;
        let mut offsets = vec![0usize; total as usize];
        for (num, body) in bodies {
            offsets[*num as usize] = out.len();
            out.extend_from_slice(format!("{num} 0 obj\n").as_bytes());
            out.extend_from_slice(body);
            out.extend_from_slice(b"\nendobj\n");
        }
        let xref_start = out.len();
        out.extend_from_slice(format!("xref\n0 {total}\n0000000000 65535 f \n").as_bytes());
        for off in offsets.iter().skip(1) {
            out.extend_from_slice(format!("{off:010} 00000 n \n").as_bytes());
        }
        out.extend_from_slice(format!("trailer\n<< /Size {total} /Root 1 0 R >>\n").as_bytes());
        out.extend_from_slice(format!("startxref\n{xref_start}\n%%EOF\n").as_bytes());
        out
    }

    #[test]
    fn generate_plan_drops_orphan_indirect_length_holder_and_writes() {
        let bytes = od_indirect_length_pdf_bytes();
        let mut pdf = Pdf::open(Cursor::new(bytes.clone())).unwrap();
        let plan = LinearizationPlan::from_pdf(&mut pdf, true).unwrap();

        // The /Length holder (obj 7), reachable only via the OD stream's indirect
        // /Length, must be excluded from the plan: every stream is written with a
        // direct /Length, so the holder orphans and qpdf garbage-collects it.
        assert!(
            !plan.all_assigned_refs().contains(&ObjectRef::new(7, 0)),
            "orphaned /Length holder must not be assigned to any linearization part"
        );

        // Writing must succeed: the now-dangling `7 0 R` /Length is direct-ized at
        // renumber time (before this fix it errored "no entry in RenumberMap").
        let renumber = RenumberMap::from_plan(&plan);
        let mut pdf2 = Pdf::open(Cursor::new(bytes)).unwrap();
        let opts = crate::WriteOptions {
            object_streams: crate::ObjectStreamMode::Generate,
            deterministic_id: true,
            newline_before_endstream: crate::NewlineBeforeEndstream::Never,
            ..Default::default()
        };
        let mut doc =
            crate::linearization::writer::write_linearized(&plan, &renumber, &mut pdf2, &opts)
                .expect("linearized write must succeed with the orphan holder dropped");
        doc.back_patch().expect("back-patch must succeed");
        // No stream may carry an indirect /Length in the output: every /Length is
        // direct, so the dropped holder is unreferenced.
        let out = doc.bytes;
        assert!(
            !out.windows(b"/Length 7 0 R".len())
                .any(|w| w == b"/Length 7 0 R"),
            "the OD stream's /Length must be direct-ized, not left as an indirect ref"
        );
    }

    /// Two-page PDF whose SECOND page's `/Contents` stream (obj 6) has an
    /// indirect `/Length` (`7 0 R`); the holder (obj 7) is reachable only via
    /// that page-2 closure edge. flpdf-2vfg / Codex review on PR #400.
    fn page2_contents_indirect_length_pdf_bytes() -> Vec<u8> {
        let bodies: &[(u32, &[u8])] = &[
            (1, b"<< /Type /Catalog /Pages 2 0 R >>"),
            (2, b"<< /Type /Pages /Count 2 /Kids [ 3 0 R 4 0 R ] >>"),
            (
                3,
                b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 5 0 R /Resources << >> >>",
            ),
            (
                4,
                b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 6 0 R /Resources << >> >>",
            ),
            (5, b"<< /Length 5 >>\nstream\nBT ET\nendstream"),
            (6, b"<< /Length 7 0 R >>\nstream\nBT ET\nendstream"),
            (7, b"5"),
        ];
        let mut out: Vec<u8> = b"%PDF-1.7\n%\xe2\xe3\xcf\xd3\n".to_vec();
        let total = bodies.len() as u32 + 1;
        let mut offsets = vec![0usize; total as usize];
        for (num, body) in bodies {
            offsets[*num as usize] = out.len();
            out.extend_from_slice(format!("{num} 0 obj\n").as_bytes());
            out.extend_from_slice(body);
            out.extend_from_slice(b"\nendobj\n");
        }
        let xref_start = out.len();
        out.extend_from_slice(format!("xref\n0 {total}\n0000000000 65535 f \n").as_bytes());
        for off in offsets.iter().skip(1) {
            out.extend_from_slice(format!("{off:010} 00000 n \n").as_bytes());
        }
        out.extend_from_slice(format!("trailer\n<< /Size {total} /Root 1 0 R >>\n").as_bytes());
        out.extend_from_slice(format!("startxref\n{xref_start}\n%%EOF\n").as_bytes());
        out
    }

    #[test]
    fn generate_plan_drops_orphan_length_holder_reached_via_later_page_closure() {
        // The holder (obj 7) is reached only through page 2's /Contents stream
        // /Length. It must be dropped from the later-page closure too, not just
        // the Part-4 universe — otherwise it lands in the per-page (part7) set.
        let mut pdf = Pdf::open(Cursor::new(page2_contents_indirect_length_pdf_bytes())).unwrap();
        let plan = LinearizationPlan::from_pdf(&mut pdf, true).unwrap();
        assert!(
            !plan.all_assigned_refs().contains(&ObjectRef::new(7, 0)),
            "a page-reachable orphaned /Length holder must not be assigned to any part"
        );
    }

    #[test]
    fn non_generate_plan_also_drops_orphan_indirect_length_holder() {
        // The orphan-holder pruning is NOT gated on generate mode: the linearized
        // writer emits a direct /Length in every object-stream mode, so qpdf GCs
        // the holder for plain `--linearize` (preserve) and `--object-streams=
        // disable` runs too. `use_generate_objstm = false` must still drop it.
        let mut pdf = Pdf::open(Cursor::new(od_indirect_length_pdf_bytes())).unwrap();
        let plan = LinearizationPlan::from_pdf(&mut pdf, false).unwrap();
        assert!(
            !plan.all_assigned_refs().contains(&ObjectRef::new(7, 0)),
            "orphaned /Length holder must be dropped in non-generate mode too"
        );
    }

    /// Single-page PDF whose trailer references a missing `/Info` object
    /// (`99 0 R`, no xref entry). `compressible_objgens` excludes the dangling
    /// ref from the compressible set (qpdf treats a missing ref as null), so it
    /// never reaches the linearized ObjStm membership or the generate renumber
    /// walk. Mirrors the Codex Security PoC (`flpdf-4vpi`).
    fn missing_trailer_info_pdf_bytes() -> Vec<u8> {
        let mut pdf = Vec::new();
        pdf.extend_from_slice(b"%PDF-1.4\n");
        let off1 = pdf.len() as u64;
        pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
        let off2 = pdf.len() as u64;
        pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n");
        let off3 = pdf.len() as u64;
        pdf.extend_from_slice(
            b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>\nendobj\n",
        );
        let xref_start = pdf.len() as u64;
        let xref = format!(
            "xref\n0 4\n0000000000 65535 f \n{off1:010} 00000 n \n{off2:010} 00000 n \n{off3:010} 00000 n \n",
        );
        pdf.extend_from_slice(xref.as_bytes());
        // /Info 99 0 R has no object 99 in the body or xref.
        pdf.extend_from_slice(
            format!("trailer\n<< /Size 100 /Root 1 0 R /Info 99 0 R >>\nstartxref\n{xref_start}\n%%EOF\n")
                .as_bytes(),
        );
        pdf
    }

    /// Single-page PDF with a real `/Info` (obj 4) whose trailer also carries `n`
    /// missing `/Junk` refs (objects `10..10+n`, none with an xref entry). qpdf
    /// drops each dangling ref before it can enter the compressible set, so it
    /// emits one ObjStm holding only the real members. `compressible_objgens`
    /// excludes the missing refs the same way: were they admitted, with `n` large
    /// enough they would cross the 100-member even-split boundary and scatter the
    /// two real members (the `/Info` dict and the `/Pages` tree) into separate
    /// containers (Codex review on PR #421). Byte-identical to
    /// `tests/fixtures/compat/objstm-lin-split-boundary.pdf`.
    fn info_and_missing_junk_pdf_bytes(n: u32) -> Vec<u8> {
        let mut junk = String::new();
        for i in 0..n {
            junk.push_str(&format!("/J{i} {} 0 R ", 10 + i));
        }
        let mut pdf = Vec::new();
        pdf.extend_from_slice(b"%PDF-1.4\n");
        let off1 = pdf.len() as u64;
        pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
        let off2 = pdf.len() as u64;
        pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n");
        let off3 = pdf.len() as u64;
        pdf.extend_from_slice(
            b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>\nendobj\n",
        );
        let off4 = pdf.len() as u64;
        pdf.extend_from_slice(b"4 0 obj\n<< /Producer (flpdf-test) >>\nendobj\n");
        let xref_start = pdf.len() as u64;
        let xref = format!(
            "xref\n0 5\n0000000000 65535 f \n{off1:010} 00000 n \n{off2:010} 00000 n \n{off3:010} 00000 n \n{off4:010} 00000 n \n",
        );
        pdf.extend_from_slice(xref.as_bytes());
        pdf.extend_from_slice(
            format!("trailer\n<< /Size 110 /Root 1 0 R /Info 4 0 R {junk}>>\nstartxref\n{xref_start}\n%%EOF\n")
                .as_bytes(),
        );
        pdf
    }

    /// Drive a linearized generate write end-to-end and return the back-patched
    /// bytes, asserting neither the planner nor the writer panics.
    fn write_linearized_generate(bytes: &[u8]) -> Vec<u8> {
        let mut pdf = Pdf::open(Cursor::new(bytes.to_vec())).unwrap();
        let plan = LinearizationPlan::from_pdf(&mut pdf, true).unwrap();
        let renumber = RenumberMap::from_plan(&plan);
        let opts = crate::WriteOptions {
            object_streams: crate::ObjectStreamMode::Generate,
            deterministic_id: true,
            newline_before_endstream: crate::NewlineBeforeEndstream::Never,
            ..Default::default()
        };
        let mut doc =
            crate::linearization::writer::write_linearized(&plan, &renumber, &mut pdf, &opts)
                .expect("linearized generate write must not panic on unplanned refs");
        doc.back_patch().expect("back-patch must succeed");
        doc.bytes
    }

    /// A missing trailer-only `/Info 99 0 R` must not receive a renumber slot or
    /// be batched into an ObjStm: `compressible_objgens` excludes the dangling
    /// ref, so it never reaches `place_objstm_members_per_half` without a slot
    /// (which would panic). End-to-end guard for the Codex Security PoC
    /// (`flpdf-4vpi`).
    #[test]
    fn objstm_batches_generate_drops_missing_trailer_only_ref() {
        let bytes = missing_trailer_info_pdf_bytes();
        let mut pdf = Pdf::open(Cursor::new(bytes.clone())).unwrap();
        let plan = LinearizationPlan::from_pdf(&mut pdf, true).unwrap();
        let missing = ObjectRef::new(99, 0);
        assert!(
            !plan.renumber_assigned_refs().contains(&missing),
            "missing /Info 99 0 R must not receive a renumber slot"
        );

        let batch_plan = plan.objstm_batches(&mut pdf, &generate_config()).unwrap();
        assert!(
            !batch_plan
                .open_document_batches
                .iter()
                .chain(&batch_plan.part3_batches)
                .map(Vec::as_slice)
                .chain(
                    batch_plan
                        .part4_batches
                        .iter()
                        .map(|batch| batch.members.as_slice()),
                )
                .any(|batch| batch.contains(&missing)),
            "missing /Info 99 0 R must not be batched into a generated ObjStm"
        );

        // End-to-end: previously panicked at renumber.rs:place_objstm_members_per_half.
        write_linearized_generate(&bytes);
    }

    /// 100 missing `/Junk` refs must not inflate the even split. Dropping them
    /// from membership BEFORE the split keeps the two real members — the `/Info`
    /// dict (obj 4) and the `/Pages` tree (obj 2) — in a SINGLE container, the
    /// way qpdf does (one `/N 2` ObjStm). Filtering only AFTER the split would
    /// leave the inflated boundary in place and scatter them into two `/N 1`
    /// ObjStms (Codex review on PR #421).
    #[test]
    fn objstm_membership_keeps_real_members_together_despite_missing_refs() {
        let mut pdf = Pdf::open(Cursor::new(info_and_missing_junk_pdf_bytes(100))).unwrap();
        let assigned = LinearizationPlan::from_pdf(&mut pdf, true)
            .unwrap()
            .renumber_assigned_refs();

        let containers = objstm_membership_linearized(&mut pdf, &assigned).unwrap();

        let info = ObjectRef::new(4, 0);
        let pages = ObjectRef::new(2, 0);
        assert_eq!(
            containers.len(),
            1,
            "missing /Junk refs must not split the two real members across containers"
        );
        let members = &containers[0];
        assert!(
            members.contains(&info) && members.contains(&pages),
            "the single container must hold both real members (/Info + /Pages)"
        );
        assert!(
            !members.iter().any(|r| (10..110).contains(&r.number)),
            "no missing /Junk ref may survive into membership"
        );
    }
}