rhwp 0.9.0

HWP/HWPX document engine for Rust applications, WebAssembly, and CLI automation
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
//! Physical-row geometry for paragraph layout.

use crate::renderer::style_resolver::storage::{Storage, Unbounded};
use std::ops::Range;

use crate::model::paragraph::{LineSeg, SpaceMetric};

const SEGMENT_BOUNDARY_TAGS: u32 = LineSeg::TAG_FIRST_SEGMENT | LineSeg::TAG_LAST_SEGMENT;
const MINIMUM_USABLE_INTERVAL_HWP: i32 = 1_440;
/// The column solver's unconditional inline-extent quantum.
///
/// The recovered column-solver trace records this as a third quantization above
/// the paragraph grid: for equal-width columns the solver truncates the full width
/// with `÷4×4` before the paragraph builder sees it. It is not `snapToGrid` and
/// it does not ceil/floor the paragraph's post-margin edges. #1440 demonstrates
/// the ordering: column width `38268` stays `38268`, then 850-unit left/right
/// margins produce stored `850..37418`. Snapping those edges independently
/// produced the false `852..37416` cache mismatch.
///
/// `SectionDef::char_grid` and the paragraph `snapToGrid` gate remain the
/// separate, unimplemented §2.12 builder/fill pitches.
///
/// The value 4 stays measured rather than derived: over 455 corpus documents
/// and 160,069 complete single-segment stored rows, the difference between our
/// column box and HWP's stored right edge is exactly `body_width % 4` in
/// 160,052 of them — `(delta 0, bw%4 0): 106,674`, `(1,1): 423`,
/// `(2,2): 52,835`, `(3,3): 120`, 17 exceptions. That is a snap-down to a
/// 4-HWPUNIT grid, not a constant inset, which is why a flat `-2` fixed the
/// `bw%4==2` documents and broke the `bw%4==0` ones.
///
pub(crate) const COLUMN_WIDTH_QUANTUM_HWP: i32 = 4;

/// Snap a base edge down to `pitch`.
///
/// `pitch <= 0` is the identity, which is what §2.5's gated arm produces.
///
/// `rem_euclid` floors negative values (`-2001` becomes `-2004`). Current
/// callers provide non-negative column origins and margins; widening that input
/// domain requires an explicit rounding decision.
fn snap_base_right(edge: i32, pitch: i32) -> i32 {
    match edge.checked_rem_euclid(pitch) {
        Some(remainder) => edge - remainder,
        None => edge,
    }
}

/// Snap a base edge up to `pitch`.
///
/// Saturating, unlike the plain `+` this replaced: it was the only arithmetic
/// in this module that could overflow, two functions from a `checked_add`. See
/// [`snap_base_right`] for the zero-pitch and rounding notes.
fn snap_base_left(edge: i32, pitch: i32) -> i32 {
    match edge.checked_rem_euclid(pitch) {
        Some(0) | None => edge,
        Some(remainder) => edge.saturating_add(pitch - remainder),
    }
}

/// The horizontal box one paragraph flow is given, **and the coordinate system
/// it is in**.
///
/// A width alone cannot say this, and that is the whole reason this type
/// exists. The two constructors are not a formatting preference; they are two
/// different coordinate systems, and a caller that cannot name its own cannot
/// be handed a correct box:
///
/// - [`ParagraphBox::column`] carries an **origin**. HWP stores `column_start`
///   relative to the column, not to the paragraph, so a body paragraph's box is
///   `[margin_left, column_width - margin_right]` and its published record must
///   say so. [`ParagraphBox::body`] first applies the column solver's width
///   quantum, then applies these paragraph margins.
/// - [`ParagraphBox::content`] belongs to a flow that has no column of its own —
///   a table cell, a footnote, a header, a caption, a text box. Its origin is
///   that flow's own left edge. Its width was already resolved by that owner,
///   so the body column solver must not touch it.
///
/// Both `column_start` and `segment_width` of every published `LineSeg` come out
/// of [`ParagraphBox::effective`], so the record a reflow writes and the box the
/// frame carves can no longer disagree — before this type they were computed in
/// two places from two different quantities.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParagraphBox {
    horizontal: Range<i32>,
    origin_is_derivable: bool,
}
crate::storage::clone_fields!(ParagraphBox, {horizontal, origin_is_derivable});

impl ParagraphBox {
    /// A column-relative box: `[margin_left, column_width - margin_right]`, the
    /// same range the render sites hand `LayoutFrame`.
    pub(crate) fn column(horizontal: Range<i32>) -> Self {
        Self {
            horizontal,
            origin_is_derivable: true,
        }
    }

    /// The column box of a body paragraph — the column's own edges inset by the
    /// resolved paragraph margins.
    ///
    /// This is the one expression the edit path and the three render sites
    /// share. One paragraph must not get two different boxes depending on which
    /// route reached it, and having a single constructor is what makes "the same
    /// frame" structural rather than a comment kept true by hand.
    ///
    /// The origin is right in general: `column_start ==
    /// px_to_hwpunit(margin_left)` on **189,576 of 191,057** corpus rows
    /// carrying authentic stored `LINE_SEG`s (99.22%). See
    /// [`ParagraphBox::with_derivable_origin`] for the residual.
    pub(crate) fn body(
        column_width_px: f64,
        margin_left_px: f64,
        margin_right_px: f64,
        dpi: f64,
    ) -> Self {
        // The column solver quantizes the full inline extent before paragraph
        // margins are applied. This is the unconditional ÷4×4 lane recovered
        // in the column solver, distinct from the paragraph's optional character
        // grid. Snapping the post-margin edges would incorrectly turn
        // 850..37418 into 852..37416 (#1440).
        let column_width_hwp = snap_base_right(
            crate::renderer::px_to_hwpunit(column_width_px, dpi),
            COLUMN_WIDTH_QUANTUM_HWP,
        );
        let margin_left_hwp = crate::renderer::px_to_hwpunit(margin_left_px, dpi);
        let margin_right_hwp = crate::renderer::px_to_hwpunit(margin_right_px, dpi);
        Self::column(margin_left_hwp..column_width_hwp.saturating_sub(margin_right_hwp))
    }

    /// [`ParagraphBox::body`] for a paragraph whose resolved style is known.
    ///
    /// Reads `head_type` so the list blocker in
    /// [`ParagraphBox::with_derivable_origin`] is applied in one place instead of
    /// being remembered at each body call site.
    pub(crate) fn body_for_style(
        column_width_px: f64,
        style: Option<&crate::renderer::style_resolver::ResolvedParaStyle>,
        dpi: f64,
    ) -> Self {
        use crate::model::style::HeadType;
        let margin_left = style.map(|s| s.margin_left).unwrap_or(0.0);
        let margin_right = style.map(|s| s.margin_right).unwrap_or(0.0);
        let head_type = style.map(|s| s.head_type).unwrap_or(HeadType::None);
        Self::body(column_width_px, margin_left, margin_right, dpi)
            .with_derivable_origin(matches!(head_type, HeadType::None | HeadType::Outline))
    }

    /// Declare whether this box's **origin** may be published, or only its width.
    ///
    /// `false` is a **named blocker**, and it is temporary. The residual 0.78% of
    /// the measurement on [`ParagraphBox::body`] is one class, not noise: a
    /// numbered or bulleted marker hangs *left* of `margin_left`, so HWP stores a
    /// smaller `column_start` (deltas `-2000`, `-2500`, `-2252` — 731 rows).
    /// `para-head-num-2.hwp` paragraph 0.1 has ParaShape `margin_left = 4000` and
    /// stored `cs = 2000`, with `cs + sw = 42520` exactly the column width.
    ///
    /// The reason to withhold the origin is **not** that it cannot be computed —
    /// the paragraph's own stored record has it. It is that the render side
    /// cannot yet consume it for an *empty* list paragraph. The
    /// `issue_1329_bullet_caret` fixture records the decisive contrast:
    ///
    /// | paragraph | stored record | offset-0 caret |
    /// | --- | --- | --- |
    /// | 0.1, pristine, has text | `cs=2000 sw=40520` | 164.1 |
    /// | 0.2, split, empty | `cs=2000 sw=40520` | **190.7** |
    ///
    /// Identical records, 26.6px apart. A non-empty list line starts at
    /// `column_start` (140.1px) and its body run lands at 164.1; the empty line's
    /// marker run is emitted at `col_area.x + margin_left` = 166.7px with width
    /// 24.0 (`paragraph_layout.rs`), so `cursor_rect.rs`'s `marker_end_x`
    /// fallback reports 190.7. Publishing a truthful origin makes those two
    /// disagree by exactly one marker advance, which is what
    /// `issue_1329_bullet_caret` pins.
    ///
    /// So a list paragraph publishes `column_start = 0` for now: the pre-existing
    /// value, wrong in the way it has always been wrong, and consistent between
    /// the record and the frame. **The width lane is not withheld** —
    /// `segment_width` still comes from the column box and still takes the
    /// geometry pitch, which is the exposure Task 3 measured. Fixing the
    /// empty-list marker placement is the prerequisite for removing this.
    pub(crate) fn with_derivable_origin(self, origin_is_derivable: bool) -> Self {
        Self {
            origin_is_derivable: self.origin_is_derivable && origin_is_derivable,
            ..self
        }
    }

    /// 원본의 가시 목록 줄이 실제 문단 여백 원점을 사용하면 그 물리 상자를 복원한다.
    /// 빈 목록과 편집 줄의 원점 발행 차단은 유지하며, 저장 폭·모든 행의 원점·
    /// 텍스트 유효성은 이후 공통 프레임 수용 검사가 그대로 검증한다.
    pub(crate) fn for_stored_body_rows(self, para: &crate::model::paragraph::Paragraph) -> Self {
        let has_original_origin = !self.origin_is_derivable
            && para.text.chars().any(|ch| !ch.is_whitespace())
            && !para.stored_text_partition_is_dirty()
            && para
                .line_segs
                .first()
                .is_some_and(|line| line.column_start == self.horizontal.start)
            && para
                .line_segs
                .iter()
                .all(|line| line.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0);
        if has_original_origin {
            Self {
                origin_is_derivable: true,
                ..self
            }
        } else {
            self
        }
    }

    /// A box in a nested flow's own coordinates. Pass the real inset when the
    /// caller has one; `0..width` when the flow's left edge *is* the origin.
    pub(crate) fn content(horizontal: Range<i32>) -> Self {
        Self {
            horizontal,
            origin_is_derivable: true,
        }
    }

    /// A nested flow's content box given as a width in pixels.
    ///
    /// Public because the cell rebuild it feeds
    /// (`composer::recompose_cell_lines_in_frame`) is public, and a caller that
    /// cannot name its own coordinate system cannot use that entry at all.
    ///
    /// [#7412] 한/글은 셀 안 줄 폭도 본문 단과 같은 4 HWPUNIT 격자에 내려서 저장한다.
    /// `samples/**/*.hwpx` 56문서의 `hp:lineseg/@horzsize` 19,837개 중 19,766개(99.64%)가
    /// 4의 배수이고, 예외는 단일 차트 합성 fixture 뿐이다. 그래서 내용 상자의 오른쪽 끝을
    /// 같은 격자로 내린다(원점 0 은 이미 격자 위). `80168_regulatory_analysis` p121
    /// 「7.규제내용」 셀(내용 폭 34626 HU)은 34624 HU 로 줄을 나눠야 한/글 2022·2024 PDF 와
    /// 같이 「…시ㆍ도조 / 례로…」에서 끊긴다.
    pub fn content_width_px(width_px: f64, dpi: f64) -> Self {
        Self::content(
            0..snap_base_right(
                crate::renderer::px_to_hwpunit(width_px, dpi),
                COLUMN_WIDTH_QUANTUM_HWP,
            ),
        )
    }

    /// [#7407] 중첩 흐름의 내용 상자에 문단 자체의 양쪽 여백을 반영한다.
    ///
    /// `content_width_px`는 원점 0에서 흐름의 전체 안쪽 폭을 준다. 이는 문단에
    /// 양쪽 여백이 없을 때만 맞는다. 셀 문단에도 본문과 같은 `margin_left`와
    /// `margin_right`가 있으므로 이를 빼먹으면 같은 문단이 호출 경로에 따라
    /// 다른 상자를 갖게 된다. [`ParagraphBox::body`]와 같은 상자 계약을 쓴다.
    ///
    /// `samples/issue6639/issue6639-hancom-160.hwpx`의 셀 31에서 확인했다.
    /// 문단 10개는 `paraPr 18`을 공유한다. IR의 2배 단위에서 양쪽 여백은
    /// 각각 1600이며 실제로는 각각 800 HWPUNIT이다.
    ///
    /// | | 줄 폭 | 줄 원점 |
    /// | --- | ---: | ---: |
    /// | 한/글 저장 `hp:lineseg` | `39208` | `800` |
    /// | `content_width_px` | `40808` | `0` |
    /// | stage30의 구 구현 | `39206` | `800` |
    ///
    /// 여분 1600 HWPUNIT에 줄마다 글자가 하나 더 들어가면서 같은 셀의
    /// 줄 수가 기준 출력보다 세 줄 줄어들었다.
    ///
    /// 셀 내용 폭도 저장 줄의 4 HWPUNIT 격자를 따른다(#7412). 여백을 뺀 두
    /// 끝점을 각각 스냅하지 않고, `content_width_px`와 같은 원래 내용 폭을
    /// 먼저 스냅해 문단의 실제 왼쪽 원점을 보존한다.
    pub(crate) fn content_for_style(
        content_width_px: f64,
        style: Option<&crate::renderer::style_resolver::ResolvedParaStyle>,
        dpi: f64,
    ) -> Self {
        use crate::model::style::HeadType;
        let margin_left = style.map(|s| s.margin_left).unwrap_or(0.0);
        let margin_right = style.map(|s| s.margin_right).unwrap_or(0.0);
        let head_type = style.map(|s| s.head_type).unwrap_or(HeadType::None);
        let width_hwp = snap_base_right(
            crate::renderer::px_to_hwpunit(content_width_px, dpi),
            COLUMN_WIDTH_QUANTUM_HWP,
        );
        let margin_left_hwp = crate::renderer::px_to_hwpunit(margin_left, dpi);
        let margin_right_hwp = crate::renderer::px_to_hwpunit(margin_right, dpi);
        Self::content(margin_left_hwp..width_hwp.saturating_sub(margin_right_hwp))
            .with_derivable_origin(matches!(head_type, HeadType::None | HeadType::Outline))
    }

    /// The box after the geometry pitch — the single source for both the
    /// published record and the carved frame.
    pub(crate) fn effective(&self) -> Range<i32> {
        if self.origin_is_derivable {
            self.horizontal.clone()
        } else {
            0..self.horizontal.end.saturating_sub(self.horizontal.start)
        }
    }

    pub(crate) fn width_hwp(&self) -> i32 {
        let effective = self.effective();
        effective.end.saturating_sub(effective.start)
    }

    /// Whether this box can carry a row at all — **the one rule, for every
    /// route**.
    ///
    /// False when the resolved margins meet or cross: a paragraph whose
    /// `margin_left` reaches `column_width - margin_right` has no usable width,
    /// which is legal input (a large left indent inside a narrow column, or a
    /// multi-column layout whose spacing eats the body). Measured on
    /// `effective()`, so it also catches a box the geometry pitch itself
    /// inverted — `snap_base_left(1)..snap_base_right(3)` is `4..0`.
    ///
    /// **Refusal, not a floor, and the distinction is load-bearing.** The
    /// narrow-base fallback that would discard paragraph margins and create a
    /// minimum-width row is not implemented. Flooring here would invent a
    /// different third behavior and hide that missing owner.
    ///
    /// A floor is also what hid this: the retired
    /// `(col_width - margin_left - margin_right).max(1.0)` turned an impossible
    /// box into a 75-HWPUNIT one, which reflows to one token per line and looks
    /// like a valid record. Refusing keeps HWP's own record, which is the same
    /// rule the frame already follows for a row it cannot reproduce (#4779),
    /// and it leaves the narrow-base fallback a live decision rather than
    /// something that has to displace a fabricated number.
    pub(crate) fn is_usable(&self) -> bool {
        self.width_hwp() > 0
    }

    pub(crate) fn width_px(&self, dpi: f64) -> f64 {
        crate::renderer::hwpunit_to_px(self.width_hwp(), dpi)
    }

    /// The frame this box describes, carrying the caller's wrap geometry.
    ///
    /// Built from `effective()` so the frame and the published record cannot
    /// drift. The picture band is routed through the same box rather than
    /// deriving another horizontal range: two expressions for one quantity are
    /// what previously let the band and body disagree.
    pub(crate) fn frame_with(&self, top: i32, exclusions: Vec<FrameExclusion>) -> LayoutFrame {
        let mut frame = LayoutFrame::new(self.effective(), top, exclusions);
        // [#7408] `effective()` 가 원점을 접었으면 그 사실을 프레임이 알아야 한다.
        // 모르면 저장 행의 **참 원점**을 접힌 0 과 그대로 견주어 반드시 어긋난다.
        frame.origin_is_authoritative = self.origin_is_derivable;
        frame
    }

    /// [`ParagraphBox::frame_with`] for a flow that models no wrap geometry.
    ///
    /// Every body call site is here today, which is why `models_exclusions()`
    /// is false on the stored-row route — see
    /// `line_breaking::stored_rows_reproduce_frame_expectation`.
    pub(crate) fn frame(&self, top: i32) -> LayoutFrame {
        self.frame_with(top, Vec::new())
    }
}
/// The vertical values shared by every horizontal segment in one physical row.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct FrameRowMetrics {
    pub(crate) vertical_pos: i32,
    pub(crate) line_height: i32,
    pub(crate) text_height: i32,
    pub(crate) baseline_distance: i32,
    pub(crate) line_spacing: i32,
}
crate::storage::clone_copy!(FrameRowMetrics);

/// One horizontal part of a physical row before it is flattened into a
/// `LineSeg`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct RowSegment {
    pub(crate) text_range: Range<u32>,
    pub(crate) horizontal: Range<i32>,
    /// The source tag retains provenance and line properties. Projection owns
    /// the FIRST/LAST boundary bits because they describe this row's group.
    pub(crate) source_tag: u32,
    /// Metric selected when this interval was filled; not a serialized tag.
    pub(crate) space_metric: SpaceMetric,
}
crate::storage::clone_fields!(RowSegment, {text_range, horizontal, source_tag, space_metric});

impl RowSegment {
    pub(crate) fn new(text_range: Range<u32>, horizontal: Range<i32>, source_tag: u32) -> Self {
        Self {
            text_range,
            horizontal,
            source_tag: source_tag & !SEGMENT_BOUNDARY_TAGS,
            space_metric: SpaceMetric::Stored,
        }
    }
}

/// A completed physical row. Its vertical values are recorded once, while its
/// horizontal segments retain their left-to-right order until projection.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct PhysicalRow {
    metrics: FrameRowMetrics,
    segments: Vec<RowSegment>,
}
crate::storage::clone_fields!(PhysicalRow, {metrics, segments});

/// Whether a stored row is the row this frame expected.
///
/// Exact equality covers interval count, `column_start`, and `segment_width`.
///
/// Stored geometry is reusable only when the current Frame reproduces it. Row
/// metrics (`vertical_pos`, height, baseline, spacing, and overhangs) are a
/// separate lane and do not widen this cache key. There is no geometry
/// tolerance.
///
/// Two things this predicate must therefore **not** absorb, because a
/// difference here is a bug in our carve or a gap in our inputs, and hiding it
/// destroys the evidence:
///
/// - Glyph shaping and kerning line-boundary differences → #4439.
/// - Column-solver quantization belongs in `ParagraphBox::body`, before
///   paragraph margins. This predicate must not absorb it a second time.
///
/// 원점을 보류한 경우를 제외하면 프레임의 원점이 확정되므로 `origin_shift`는
/// `0`이다. [`LayoutFrame::origin_is_authoritative`]를 참조한다. 이동량이 0이면
/// 위 규칙대로 `column_start`와 `segment_width`가 허용 오차 없이 같아야 한다.
fn stored_row_matches_frame_expectation(
    expected: &Range<i32>,
    stored: &LineSeg,
    origin_shift: i32,
) -> bool {
    let Some(start) = expected.start.checked_add(origin_shift) else {
        return false;
    };
    let Some(end) = expected.end.checked_add(origin_shift) else {
        return false;
    };
    start == stored.column_start
        && stored
            .column_start
            .checked_add(stored.segment_width)
            .is_some_and(|stored_end| end == stored_end)
}

/// The side-wrap choices represented by this physical-row frame. This is
/// layout geometry, rather than a mirror of model `TextFlow`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum FrameExclusionPolicy {
    BothSides,
    LargestSide,
    LeftSide,
    RightSide,
}
crate::storage::clone_copy!(FrameExclusionPolicy);

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct FrameExclusion {
    pub(crate) horizontal: Range<i32>,
    pub(crate) vertical: Range<i32>,
    pub(crate) policy: FrameExclusionPolicy,
}
crate::storage::clone_fields!(FrameExclusion, {horizontal, vertical, policy});

/// Mutable geometry of one layout flow.
///
/// A carve is tentative. It may move the candidate row to an exact geometry
/// event, but it does not commit text or advance past a completed row.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct LayoutFrame {
    pub(crate) horizontal: Range<i32>,
    pub(crate) top: i32,
    pub(crate) exclusions: Vec<FrameExclusion>,
    pub(crate) current_intervals: Vec<Range<i32>>,
    pub(crate) next_geometry_event: Option<i32>,
    pub(crate) minimum_width: i32,
    /// 저장 HWPX의 KoPub 양쪽 정렬 줄은 공백을 글꼴 전진폭까지 줄일 수 있다.
    pub(crate) kopub_justified_space: bool,
    /// [#7408] horizontal.start가 이 문단의 실제 원점인지 나타낸다.
    /// ParagraphBox가 목록 문단 원점을 보류하면 effective()는 0..width로 접지만,
    /// 저장 LineSeg는 실제 column_start를 유지한다. 같은 폭을 원점 차이로 기각하면
    /// 한컴 저장 줄 대신 새 줄바꿈을 사용하게 된다.
    /// 원점을 보류한 프레임은 폭과 슬롯 간격으로 비교하고 실제 원점을 새로 공표하지 않는다.
    origin_is_authoritative: bool,
    /// 이 프레임에 확정된 물리 줄. 가로 범위는 생성자가 이미 격자를 적용한 값이다 —
    /// 본문은 [`ParagraphBox::body`]가 단 폭을, 셀 등 내용 흐름은
    /// [`ParagraphBox::content_width_px`]가 내용 폭을 4 HWPUNIT 격자로 내린다(#7412).
    rows: Vec<PhysicalRow>,
}
crate::storage::clone_fields!(LayoutFrame, {horizontal, top, exclusions, current_intervals, next_geometry_event, minimum_width, kopub_justified_space, origin_is_authoritative, rows});

/// Snapshot for operations that only carve geometry and append physical rows.
/// Previously committed rows and immutable frame geometry remain in the frame.
/// Use only before the success-only whitespace absorption step.
pub(crate) struct FrameAppendCheckpoint {
    top: i32,
    intervals: Vec<Range<i32>>,
    next_geometry_event: Option<i32>,
    row_count: usize,
}

impl LayoutFrame {
    /// Start a paragraph-local physical frame at a known horizontal extent.
    pub(crate) fn new(horizontal: Range<i32>, top: i32, exclusions: Vec<FrameExclusion>) -> Self {
        Self {
            horizontal,
            top,
            exclusions,
            current_intervals: Vec::new(),
            next_geometry_event: None,
            minimum_width: MINIMUM_USABLE_INTERVAL_HWP,
            kopub_justified_space: false,
            origin_is_authoritative: true,
            rows: Vec::new(),
        }
    }

    pub(crate) fn append_checkpoint(&self) -> FrameAppendCheckpoint {
        match self.try_append_checkpoint(&crate::renderer::style_resolver::storage::Unbounded) {
            Ok(checkpoint) => checkpoint,
            Err(never) => match never {},
        }
    }
    pub(crate) fn try_append_checkpoint<S: crate::renderer::style_resolver::storage::Storage>(
        &self,
        storage: &S,
    ) -> Result<FrameAppendCheckpoint, S::Error> {
        let mut intervals: Vec<Range<i32>> = storage.vec(self.current_intervals.len())?;
        intervals.extend(self.current_intervals.iter().cloned());
        Ok(FrameAppendCheckpoint {
            top: self.top,
            intervals,
            next_geometry_event: self.next_geometry_event,
            row_count: self.rows.len(),
        })
    }
    pub(crate) fn restore_append_checkpoint(&mut self, checkpoint: &FrameAppendCheckpoint) {
        match self.try_restore_append_checkpoint(
            checkpoint,
            &crate::renderer::style_resolver::storage::Unbounded,
        ) {
            Ok(()) => (),
            Err(never) => match never {},
        }
    }
    pub(crate) fn try_restore_append_checkpoint<
        S: crate::renderer::style_resolver::storage::Storage,
    >(
        &mut self,
        checkpoint: &FrameAppendCheckpoint,
        storage: &S,
    ) -> Result<(), S::Error> {
        // Reserve before mutating semantic state. A failed reservation leaves
        // both the previous rows and the current trial available to the caller.
        let additional = checkpoint
            .intervals
            .len()
            .saturating_sub(self.current_intervals.len());
        storage.reserve(&mut self.current_intervals, additional)?;
        self.rows.truncate(checkpoint.row_count);
        self.top = checkpoint.top;
        self.current_intervals.clear();
        self.current_intervals
            .extend(checkpoint.intervals.iter().cloned());
        self.next_geometry_event = checkpoint.next_geometry_event;
        Ok(())
    }

    pub(crate) fn restore_owned_append_checkpoint(&mut self, checkpoint: FrameAppendCheckpoint) {
        self.rows.truncate(checkpoint.row_count);
        self.top = checkpoint.top;
        self.current_intervals = checkpoint.intervals;
        self.next_geometry_event = checkpoint.next_geometry_event;
    }

    /// Carve the current physical row into ordered horizontal intervals.
    pub(crate) fn carve(&mut self, band_height: i32) -> &[Range<i32>] {
        match self.try_carve(band_height, &Unbounded) {
            Ok(intervals) => intervals,
            Err(never) => match never {},
        }
    }

    pub(crate) fn try_carve<S: Storage>(
        &mut self,
        band_height: i32,
        storage: &S,
    ) -> Result<&[Range<i32>], S::Error> {
        let old_max = self.next_geometry_event.map(|_| {
            self.current_intervals
                .iter()
                .map(|interval| interval.end - interval.start)
                .max()
                .unwrap_or(0)
        });
        let mut candidate_top = self.top;

        loop {
            let bottom = candidate_top.saturating_add(band_height.max(0));
            let base = self.horizontal.clone();
            let mut intervals = storage.collect([base.clone()])?;
            let mut next_geometry_event = None;
            let minimum_width = self.minimum_width.max(0);
            let mut adequate = base.end - base.start >= minimum_width;

            for exclusion in &self.exclusions {
                if exclusion.vertical.start >= bottom || candidate_top >= exclusion.vertical.end {
                    continue;
                }

                let left = exclusion.horizontal.start;
                let right = exclusion.horizontal.end;
                let mut carved = storage.vec(intervals.len())?;

                for interval in &intervals {
                    if interval.end <= left || right <= interval.start {
                        storage.push(&mut carved, interval.clone())?;
                    } else if interval.start < left && right < interval.end {
                        let left_interval = interval.start..left;
                        let right_interval = right..interval.end;
                        if exclusion.policy == FrameExclusionPolicy::LeftSide {
                            storage.push(&mut carved, left_interval)?;
                        } else if exclusion.policy == FrameExclusionPolicy::RightSide {
                            storage.push(&mut carved, right_interval)?;
                        } else if exclusion.policy == FrameExclusionPolicy::LargestSide {
                            let left_width = left_interval.end - left_interval.start;
                            let right_width = right_interval.end - right_interval.start;
                            // HWP's `LargestOnly` choice normally keeps the
                            // widest side, ties left, and has one recovered
                            // narrow-lane exception: a 1,440-HWP left lane
                            // chooses the right side even when it is shorter.
                            if left_width == MINIMUM_USABLE_INTERVAL_HWP || left_width < right_width
                            {
                                storage.push(&mut carved, right_interval)?;
                            } else {
                                storage.push(&mut carved, left_interval)?;
                            }
                        } else {
                            storage.push(&mut carved, left_interval)?;
                            storage.push(&mut carved, right_interval)?;
                        }
                    } else if interval.start < left
                        && exclusion.policy != FrameExclusionPolicy::RightSide
                    {
                        storage.push(&mut carved, interval.start..left)?;
                    } else if right < interval.end
                        && exclusion.policy != FrameExclusionPolicy::LeftSide
                    {
                        storage.push(&mut carved, right..interval.end)?;
                    } else {
                        storage.push(&mut carved, interval.start..interval.start)?;
                    }
                }

                let changed = intervals != carved;
                intervals = carved;
                if changed {
                    next_geometry_event = Some(
                        next_geometry_event.map_or(exclusion.vertical.end, |event: i32| {
                            event.min(exclusion.vertical.end)
                        }),
                    );
                }

                adequate = intervals
                    .iter()
                    .any(|interval| interval.end - interval.start >= minimum_width);
                if !adequate {
                    break;
                }
            }

            let mut index = 0;
            while intervals.len() > 1 && index < intervals.len() {
                if intervals[index].end - intervals[index].start < minimum_width {
                    intervals.remove(index);
                } else {
                    index += 1;
                }
            }

            let retry = if !adequate {
                next_geometry_event.filter(|event| *event > candidate_top)
            } else {
                let new_max = intervals
                    .iter()
                    .map(|interval| interval.end - interval.start)
                    .max()
                    .unwrap_or(0);
                old_max
                    .filter(|previous| *previous > new_max)
                    .and(next_geometry_event)
                    .filter(|event| *event > candidate_top)
            };

            if let Some(event) = retry {
                candidate_top = event;
                continue;
            }

            self.top = candidate_top;
            self.current_intervals = intervals;
            self.next_geometry_event = next_geometry_event;
            return Ok(&self.current_intervals);
        }
    }

    /// Admit stored rows only where this frame's own carve already expects
    /// them, so the strict reflow can be skipped without ceding ownership.
    ///
    /// The order is frame first. `carve()` computes what the frame expects the
    /// row to be — its vertical band and its left-to-right intervals — and by
    /// #4755 §2 it neither fills text nor produces a `LineSeg`. That is the
    /// cheap half. The stored row is then compared against that expectation on
    /// equality.
    ///
    /// **What the answer does, exactly.** It is the production cache-admission
    /// gate. A match leaves the frame's recomputed rows committed and permits
    /// the stored text partition to stand. A mismatch restores the exact entry
    /// checkpoint and the caller attempts strict reflow. Text staleness remains
    /// an independent invalidator even when this geometry key matches.
    ///
    /// #4755 §1 bounds what the stored row may contribute: its horizontal
    /// extent is only ever compared, never adopted — the committed segment is
    /// the carved interval.
    ///
    /// Row metrics come from `metrics_for`, not from the stored record.
    /// §1.4.1 recomputes `vertical_pos`, `line_height`, `text_height`,
    /// `baseline_distance` and `line_spacing` on both arms, so the frame must
    /// never read them. The provider is given one FIRST..LAST group and returns
    /// that row's metrics; the resulting `line_height` is what `carve()` is
    /// asked to band.
    ///
    /// **Known divergence from §1.4.1 — the accept-arm write-back is not
    /// implemented, and this is deliberate.** §1.4.1 does not stop at
    /// recomputing: on accept it writes the recomputed metrics back over every
    /// segment in the physical row. We compute the metrics into
    /// `commit_carved_row` and leave them there; on the admitted arm
    /// `recompose_stored_lines_in_frame` returns `None`, so
    /// `project_line_segs()` never runs and the frame's metrics have **no
    /// outward path at all**. What flows on instead is the stored record, via
    /// `compose_lines`, which copies `line_height`, `baseline_distance` and
    /// `line_spacing` straight off the `LineSeg`.
    ///
    /// The reader does see a different value. On `samples/field-01.hwp` page 0
    /// (`export-render-tree`), 25 admissions hit `project_line_segs` 0 times,
    /// and 3 of the 25 rows computed `line_spacing = 450` against a stored
    /// `452`; `TypesetEngine::format_paragraph` then read `line_spacing = 452`
    /// into `corrected_line_metrics_for_source`. §2.14's metricCtx settlement
    /// is the residual — the stored value is Hancom's, ours is the
    /// approximation §1.4.2 warns about ("the real bug is … an inexact
    /// COMPUTE").
    ///
    /// Implementing it was measured, not assumed. Publishing the projection on
    /// the admitted arm exactly as the reflowed arm already does took the suite
    /// from 5983 passed / 2 failed to **5979 passed / 6 failed**: two
    /// Hancom-PDF oracle pins (`issue_1116`'s `lh=17.3 ls=10.4`,
    /// `used=874.5px`), one SVG golden (`svg_snapshot::issue_157_page_1`), and
    /// `issue_4576`'s negative control, which stopped seeing the composition
    /// corruption it deliberately injects because the recompute healed it.
    /// This cache-admission change activates §5 item 5c. It deliberately does
    /// not activate the separate accept-arm metric write-back.
    ///
    /// Note also that §1.4.1's prose and its own pseudocode disagree about
    /// which lanes the accept branch writes: the prose names `vertical_pos`,
    /// `line_height`, `text_height`, `baseline_distance`, `line_spacing` and
    /// the overhangs, while the pseudocode writes `+0x04` and `+0x4c…+0x58` —
    /// i.e. `vertical_pos` and the overhang block, but **not** the `+0x08…+0x14`
    /// row-metric lanes that §1.3 maps to `line_height`/`text_height`/
    /// `baseline`/`line_spacing`. The lanes rhwp's render path can actually
    /// write (`ComposedLine` carries `line_height`, `baseline_distance`,
    /// `line_spacing`) are the ones the pseudocode omits, and the two it does
    /// list are unreachable from here — `vertical_pos` and `text_height` are
    /// read off `para.line_segs`, which the render path holds by shared
    /// reference. Treat the `file:line` and offset citations per §1.5 item 3 /
    /// §6.C24.
    ///
    /// A mismatch restores the exact entry state, so the frame is left exactly
    /// as the caller handed it in and a later pass may reuse it.
    pub(crate) fn try_admit_stored_rows(
        &mut self,
        line_segs: &[LineSeg],
        metrics_for: impl Fn(&[LineSeg]) -> Option<FrameRowMetrics>,
    ) -> bool {
        match self.try_admit_stored_rows_with_storage(line_segs, metrics_for, &Unbounded) {
            Ok(admitted) => admitted,
            Err(never) => match never {},
        }
    }

    pub(crate) fn try_admit_stored_rows_with_storage<S: Storage>(
        &mut self,
        line_segs: &[LineSeg],
        metrics_for: impl Fn(&[LineSeg]) -> Option<FrameRowMetrics>,
        storage: &S,
    ) -> Result<bool, S::Error> {
        let checkpoint = self.try_append_checkpoint(storage)?;
        // The frame owns the column quantum. A stored width equal to the raw
        // pre-quantized width is still a cache miss, not permission to widen
        // the frame (#7168). Hancom's 43202-unit page stores a 36000-unit row.
        let admitted = self.admit_stored_rows(line_segs, metrics_for, storage);
        if !matches!(admitted, Ok(Some(()))) {
            // Consume the already-owned checkpoint: rollback must also work
            // after a sticky request failure, without another allocation.
            self.restore_owned_append_checkpoint(checkpoint);
        }
        admitted.map(|value| value.is_some())
    }

    fn admit_stored_rows<S: Storage>(
        &mut self,
        line_segs: &[LineSeg],
        metrics_for: impl Fn(&[LineSeg]) -> Option<FrameRowMetrics>,
        storage: &S,
    ) -> Result<Option<()>, S::Error> {
        // Text order is a structural precondition: the rows are consumed in
        // sequence and a rewind means the records do not describe one flow.
        //
        // `vertical_pos` is deliberately **not** here. §1.3/§1.4.1: the native
        // validator never compares it — it is recomputed every pass and written
        // back over the stored record — so it cannot take part in the decision.
        if line_segs.is_empty()
            || line_segs
                .windows(2)
                .any(|pair| pair[0].text_start > pair[1].text_start)
        {
            return Ok(None);
        }

        let mut consumed = 0usize;
        while consumed < line_segs.len() {
            if !line_segs[consumed].is_first_segment() {
                return Ok(None);
            }
            // One physical row is FIRST..LAST, however many slots that spans.
            let Some(last) = line_segs[consumed..]
                .iter()
                .position(LineSeg::is_last_segment)
            else {
                return Ok(None);
            };
            let count = last + 1;
            let stored_row = &line_segs[consumed..consumed + count];

            let Some(metrics) = metrics_for(stored_row) else {
                return Ok(None);
            };
            if metrics.line_height <= 0 {
                return Ok(None);
            }

            let candidate_top = self.top;
            let intervals = storage.collect(
                self.try_carve(metrics.line_height, storage)?
                    .iter()
                    .cloned(),
            )?;
            if self.top != candidate_top {
                // The carve moved to a geometry event, so the frame does not
                // expect a row here at all.
                return Ok(None);
            }

            // §1.4.1's three quantities: interval COUNT, then horzpos and
            // horzsize per slot, all by exact equality.
            //
            // [#7408] 원점을 보류한 경우 첫 슬롯에서 이동량을 정한다.
            // 폭과 슬롯 사이 간격은 여전히 정확히 비교한다. 알 수 없다고 선언한
            // 원점을 문서의 저장 기록을 기각하는 근거로 사용하지 않는다.
            let origin_shift = if self.origin_is_authoritative {
                0
            } else {
                match (intervals.first(), stored_row.first()) {
                    (Some(expected), Some(stored)) => {
                        stored.column_start.saturating_sub(expected.start)
                    }
                    _ => 0,
                }
            };
            if intervals.len() != count
                || intervals.iter().zip(stored_row).any(|(expected, stored)| {
                    !stored_row_matches_frame_expectation(expected, stored, origin_shift)
                })
            {
                return Ok(None);
            }

            // The committed geometry is the frame's own carve, never the stored
            // extent — they are equal here, and equality is the point.
            let segments =
                storage.collect(intervals.iter().zip(stored_row).map(|(expected, stored)| {
                    RowSegment::new(
                        stored.text_start..stored.text_start,
                        expected.clone(),
                        stored.tag,
                    )
                }))?;
            if self
                .try_commit_carved_row(metrics, segments, storage)?
                .is_none()
            {
                return Ok(None);
            }
            consumed += count;
        }
        Ok(Some(()))
    }

    /// Whether the intervals from the last `carve()` can carry a row.
    ///
    /// **The one validity rule, for both arms.** A carve can return an interval
    /// that no row can occupy: an exclusion covering a whole interval leaves
    /// `start..start`, and a base rect narrower than the geometry pitch comes
    /// back inverted (`snap_base_left(1)..snap_base_right(3)` is `4..0`). The
    /// minimum-width prune does not remove either, because it never deletes the
    /// last interval, so the final validity check must reject zero/inverted
    /// geometry explicitly.
    ///
    /// Both arms reach this through [`LayoutFrame::commit_carved_row`], which
    /// every committed row passes. `layout_paragraph_in_frame` also asks
    /// *before* filling text, but only as an optimization — it is the same
    /// question, not a second rule. The admitted arm asked nothing at all
    /// before this, so a degenerate carve could commit a row and
    /// `project_line_segs` would emit it: `segment_width` comes from
    /// `end.saturating_sub(start)`, which does not clamp at zero, so an
    /// inverted interval published a negative width — the same corrupt record
    /// `ParagraphBox::is_usable` refuses upstream.
    pub(crate) fn carved_row_is_usable(&self) -> bool {
        !self.current_intervals.is_empty()
            && self
                .current_intervals
                .iter()
                .all(|interval| interval.start < interval.end)
    }

    /// Commit the row carved at the current frame position.
    ///
    /// The caller supplies exactly one text result for every interval returned
    /// by `carve`. The frame gives all of them one vertical position, retains
    /// them as one physical row, then advances exactly once.
    pub(crate) fn commit_carved_row(
        &mut self,
        metrics: FrameRowMetrics,
        segments: Vec<RowSegment>,
    ) -> Option<usize> {
        match self.try_commit_carved_row(metrics, segments, &Unbounded) {
            Ok(index) => index,
            Err(never) => match never {},
        }
    }

    pub(crate) fn try_commit_carved_row<S: Storage>(
        &mut self,
        mut metrics: FrameRowMetrics,
        segments: Vec<RowSegment>,
        storage: &S,
    ) -> Result<Option<usize>, S::Error> {
        if !self.carved_row_is_usable()
            || segments.len() != self.current_intervals.len()
            || segments
                .iter()
                .zip(&self.current_intervals)
                .any(|(segment, interval)| segment.horizontal != *interval)
        {
            return Ok(None);
        }

        metrics.vertical_pos = self.top;
        let row_index = self.rows.len();
        storage.push(&mut self.rows, PhysicalRow { metrics, segments })?;
        self.top = self
            .top
            .saturating_add(metrics.line_height)
            .saturating_add(metrics.line_spacing);
        // A carved interval belongs only to the row just committed. Requiring
        // a new carve prevents a caller from advancing this frame twice with
        // stale geometry.
        self.current_intervals.clear();
        Ok(Some(row_index))
    }

    /// Whether this frame models any wrap geometry at all.
    ///
    /// The body call site constructs its frame with an empty exclusion list:
    /// a float anchored in another paragraph never reaches `para.controls`,
    /// and neither consumer can name the float set today (the render path has
    /// a `WrapAnchorRef` and does not forward it; the measurement path loses
    /// it at the `format_paragraph` boundary). A frame in that state can carve
    /// exactly one full-width interval, so it has nothing to say about rows
    /// that some geometry it cannot see has split.
    pub(crate) fn models_exclusions(&self) -> bool {
        !self.exclusions.is_empty()
    }

    /// [#7160] 공백만인 줄을 앞 줄이 흡수한다 — 한/글은 말미 공백에 줄상자를 주지 않는다.
    ///
    /// 저장 `PARA_LINE_SEG` 전수(`samples/` HWP5 614파일·문단 436,267)에서 말미가 공백인
    /// 여러 줄 문단 5,786건 중 **공백만인 마지막 줄은 0건**이다(강제 개행 0x0D 제외). 앞 줄의
    /// 마지막 조각이 그 공백까지 덮게 범위를 늘리고 그 줄을 뗀 뒤, 뒤 줄들을 그만큼 끌어올린다.
    ///
    /// 강제 개행이 든 줄은 한/글도 줄을 끝내는 자리라 대상이 아니다.
    pub(crate) fn absorb_whitespace_only_rows(&mut self, text: &str, first_row: usize) -> usize {
        match self.try_absorb_whitespace_only_rows(text, first_row, &Unbounded) {
            Ok(count) => count,
            Err(never) => match never {},
        }
    }

    pub(crate) fn try_absorb_whitespace_only_rows<S: Storage>(
        &mut self,
        text: &str,
        first_row: usize,
        storage: &S,
    ) -> Result<usize, S::Error> {
        let chars = storage.collect(text.chars())?;
        let is_absorbable = |row: &PhysicalRow| -> bool {
            let mut saw_char = false;
            for segment in &row.segments {
                for index in segment.text_range.start as usize..segment.text_range.end as usize {
                    let Some(ch) = chars.get(index) else {
                        return false;
                    };
                    if *ch == '\r' || *ch == '\n' {
                        return false;
                    }
                    if !ch.is_whitespace() {
                        return false;
                    }
                    saw_char = true;
                }
            }
            saw_char
        };

        let mut absorbed = 0usize;
        let mut index = self.rows.len();
        while index > first_row.saturating_add(1) {
            index -= 1;
            if !is_absorbable(&self.rows[index]) {
                continue;
            }
            let row = self.rows.remove(index);
            let shift = row
                .metrics
                .line_height
                .saturating_add(row.metrics.line_spacing);
            let end = row
                .segments
                .last()
                .map(|segment| segment.text_range.end)
                .unwrap_or(0);
            if let Some(previous) = self.rows.get_mut(index - 1) {
                if let Some(last) = previous.segments.last_mut() {
                    last.text_range.end = last.text_range.end.max(end);
                }
            }
            for later in self.rows.iter_mut().skip(index) {
                later.metrics.vertical_pos = later.metrics.vertical_pos.saturating_sub(shift);
            }
            self.top = self.top.saturating_sub(shift);
            absorbed += 1;
        }
        Ok(absorbed)
    }

    pub(crate) fn row_count(&self) -> usize {
        self.rows.len()
    }

    /// Flatten retained physical rows at the document boundary.
    pub(crate) fn project_line_segs(&self) -> Vec<LineSeg> {
        self.project_line_segs_since(0)
    }

    pub(crate) fn try_project_line_segs_since<S: Storage>(
        &self,
        first_row: usize,
        storage: &S,
    ) -> Result<Vec<LineSeg>, S::Error> {
        let count = self
            .rows
            .iter()
            .skip(first_row)
            .map(|row| row.segments.len())
            .sum();
        let mut projected = storage.vec(count)?;

        for row in self.rows.iter().skip(first_row) {
            let last_segment = row.segments.len().saturating_sub(1);
            for (segment_index, segment) in row.segments.iter().enumerate() {
                let mut tag = segment.source_tag & !SEGMENT_BOUNDARY_TAGS;
                if segment_index == 0 {
                    tag |= LineSeg::TAG_FIRST_SEGMENT;
                }
                if segment_index == last_segment {
                    tag |= LineSeg::TAG_LAST_SEGMENT;
                }
                projected.push(LineSeg {
                    text_start: segment.text_range.start,
                    vertical_pos: row.metrics.vertical_pos,
                    line_height: row.metrics.line_height,
                    text_height: row.metrics.text_height,
                    baseline_distance: row.metrics.baseline_distance,
                    line_spacing: row.metrics.line_spacing,
                    column_start: segment.horizontal.start,
                    segment_width: segment
                        .horizontal
                        .end
                        .saturating_sub(segment.horizontal.start),
                    tag,
                });
            }
        }

        Ok(projected)
    }

    /// Metric provenance follows exactly the same row/segment order as LineSeg.
    pub(crate) fn project_space_metrics(&self) -> Vec<(u32, SpaceMetric)> {
        self.project_space_metrics_since(0)
    }

    pub(crate) fn project_space_metrics_since(&self, first_row: usize) -> Vec<(u32, SpaceMetric)> {
        match self.try_project_space_metrics_since(first_row, &Unbounded) {
            Ok(metrics) => metrics,
            Err(never) => match never {},
        }
    }

    pub(crate) fn try_project_space_metrics_since<S: Storage>(
        &self,
        first_row: usize,
        storage: &S,
    ) -> Result<Vec<(u32, SpaceMetric)>, S::Error> {
        storage.collect(self.rows.iter().skip(first_row).flat_map(|row| {
            row.segments
                .iter()
                .map(|segment| (segment.text_range.start, segment.space_metric))
        }))
    }

    /// Flatten only rows appended after a paragraph-local checkpoint.
    pub(crate) fn project_line_segs_since(&self, first_row: usize) -> Vec<LineSeg> {
        match self.try_project_line_segs_since(first_row, &Unbounded) {
            Ok(lines) => lines,
            Err(never) => match never {},
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn metrics(line_height: i32, line_spacing: i32) -> FrameRowMetrics {
        FrameRowMetrics {
            vertical_pos: -1,
            line_height,
            text_height: line_height - 10,
            baseline_distance: line_height - 20,
            line_spacing,
        }
    }

    /// Test provider: the fixtures encode the row size they intend in the
    /// stored record, so echo it back. Production supplies computed metrics.
    fn echo_metrics(row: &[LineSeg]) -> Option<FrameRowMetrics> {
        let first = row.first()?;
        Some(FrameRowMetrics {
            vertical_pos: first.vertical_pos,
            line_height: first.line_height,
            text_height: first.text_height,
            baseline_distance: first.baseline_distance,
            line_spacing: first.line_spacing,
        })
    }

    fn frame(horizontal: Range<i32>, top: i32, exclusions: Vec<FrameExclusion>) -> LayoutFrame {
        LayoutFrame {
            horizontal,
            top,
            exclusions,
            current_intervals: Vec::new(),
            next_geometry_event: None,
            minimum_width: 1,
            kopub_justified_space: false,
            origin_is_authoritative: true,
            rows: Vec::new(),
        }
    }

    /// **Every body route builds the same box for the same paragraph.**
    ///
    /// The origin blocker lives in `body_for_style`, so a route calling bare
    /// `body` skips it. For a list paragraph with `margin_left > 0` that is not
    /// a cosmetic difference: the edit route publishes `column_start = 0` while
    /// the render route's frame carves at `snap_base_left(margin_left)`, and
    /// `stored_row_matches_frame_expectation` compares by exact equality — so
    /// every row of an edited list paragraph fails admission, systematically.
    /// `with_derivable_origin`'s own doc claims the withheld origin stays
    /// "consistent between the record and the frame"; that was true on one
    /// route and false on four.
    ///
    /// The width lane is deliberately *not* withheld, and this pins that too:
    /// both boxes are the same width, so only the origin is at stake and no
    /// route can be wrapping to a different measure.
    fn every_body_route_builds_one_box_for_one_paragraph() {
        use crate::model::style::HeadType;
        use crate::renderer::style_resolver::ResolvedParaStyle;

        let dpi = crate::renderer::HWPUNIT_PER_INCH; // 1 px == 1 HWPUNIT
        let listed = |head_type| ResolvedParaStyle {
            margin_left: 2_000.0,
            margin_right: 1_000.0,
            head_type,
            ..Default::default()
        };

        for head_type in [
            HeadType::None,
            HeadType::Outline,
            HeadType::Number,
            HeadType::Bullet,
        ] {
            let style = listed(head_type);
            // The edit route's box, and what the render sites used to build.
            let edit = ParagraphBox::body_for_style(42_520.0, Some(&style), dpi);
            let render_before = ParagraphBox::body(42_520.0, 2_000.0, 1_000.0, dpi);

            // Width never diverged and must not start.
            assert_eq!(
                edit.width_hwp(),
                render_before.width_hwp(),
                "{head_type:?}: the width lane is not withheld"
            );

            match head_type {
                // No marker hangs left, so the origin is publishable and both
                // constructors already agreed.
                HeadType::None | HeadType::Outline => {
                    assert_eq!(edit.effective(), render_before.effective());
                    assert_eq!(edit.effective().start, 2_000);
                }
                // A marker hangs left, so `body_for_style` withholds the origin.
                // A route calling bare `body` would publish 2_000 against the
                // edit route's 0 — this is the divergence, named.
                HeadType::Number | HeadType::Bullet => {
                    assert_eq!(edit.effective().start, 0, "{head_type:?}");
                    assert_ne!(
                        edit.effective(),
                        render_before.effective(),
                        "{head_type:?}: bare `body` is not the same box"
                    );
                }
            }
        }
    }

    /// **The column solver quantizes before paragraph margins.**
    ///
    /// This is the scoping claim — the load-bearing one, and the one nothing
    /// checked. Every other pitch test here exercises the snap's *arithmetic*;
    /// this one exercises where the snap is allowed to reach, which is what
    /// fails if the pitch is ever applied to the wrong coordinate system.
    ///
    /// The contrast is one misaligned full column width with a one-unit left
    /// paragraph margin. Native first truncates the full width `1002 → 1000`,
    /// then applies the margin, producing `1..1000`. It does not independently
    /// snap those post-margin edges to `4..1000`. An explicit `content()` range
    /// is published exactly as stated; a cell width handed over in pixels
    /// (`content_width_px`) takes the same full-width truncation `1002 → 1000`
    /// that Hancom applies to stored cell rows (#7412).
    fn the_column_solver_quantizes_before_paragraph_margins() {
        let misaligned = 1..1_002;
        let column = ParagraphBox::column(misaligned.clone());
        let content = ParagraphBox::content(misaligned.clone());

        // `column()` and `content()` both accept an already-resolved range.
        assert_eq!(column.effective(), misaligned);
        assert_eq!(
            content.effective(),
            1..1_002,
            "a content box is published exactly as the caller stated it"
        );

        // The frame boundary. Both lanes of a published record come from the
        // box, so the carve must agree with `effective()` or the record and the
        // frame have drifted again.
        let carved = |paragraph_box: &ParagraphBox| paragraph_box.frame(0).carve(100).to_vec();
        assert_eq!(carved(&column), vec![misaligned.clone()]);
        assert_eq!(carved(&content), vec![misaligned.clone()]);

        // The production body constructor owns the column-solver quantization.
        let body = ParagraphBox::body(1_002.0, 1.0, 0.0, crate::renderer::HWPUNIT_PER_INCH);
        assert_eq!(body.effective(), 1..1_000);
        assert_eq!(carved(&body), vec![1..1_000]);
        let cell = ParagraphBox::content_width_px(1_002.0, crate::renderer::HWPUNIT_PER_INCH);
        assert_eq!(
            cell.effective(),
            0..1_000,
            "content_width_px() truncates the full cell width to the 4-unit grid (#7412)"
        );
        assert_eq!(carved(&cell), vec![0..1_000]);

        // Withholding the origin still changes only the origin.
        let width_only = ParagraphBox::column(misaligned).with_derivable_origin(false);
        assert_eq!(width_only.effective(), 0..1_001);
    }

    /// The snap must be total over its whole domain, including the two points
    /// its previous form was not defined at: **pitch zero**, the value §2.5's
    /// gated arm produces and the one `rem_euclid` panicked on, and an edge at
    /// `i32::MAX`, where the ceil added without checking.
    ///
    /// Neither is reachable through today's call sites — the column quantum is
    /// positive and `px_to_hwpunit` saturates well below `i32::MAX`. They are
    /// pinned because pitch zero is the shape a future paragraph-grid gate
    /// takes, and
    /// because the `i32::MAX` case was a debug-build panic waiting on anyone
    /// widening the input range.
    fn the_snap_is_total_over_its_own_domain() {
        let up = |edge| snap_base_left(edge, COLUMN_WIDTH_QUANTUM_HWP);
        let down = |edge| snap_base_right(edge, COLUMN_WIDTH_QUANTUM_HWP);

        // Ceil and floor, on and off the grid, including negatives.
        assert_eq!((up(0), down(0)), (0, 0));
        assert_eq!((up(1), down(1)), (4, 0));
        assert_eq!((up(3), down(3)), (4, 0));
        assert_eq!((up(4), down(4)), (4, 4));
        assert_eq!((up(-1), down(-1)), (0, -4));

        // Pitch zero is the identity, not a division by zero.
        for edge in [-7, -1, 0, 1, 7, i32::MAX, i32::MIN] {
            assert_eq!(snap_base_left(edge, 0), edge, "pitch 0 ceil {edge}");
            assert_eq!(snap_base_right(edge, 0), edge, "pitch 0 floor {edge}");
        }

        // The ceil saturates rather than overflowing. `i32::MAX % 4 == 3`, so
        // this is the one input that used to wrap.
        assert_eq!(up(i32::MAX), i32::MAX);
        assert_eq!(down(i32::MIN), i32::MIN);

        // Every snapped edge lands on the grid, and the snap only ever moves
        // inward and by less than one pitch — the properties the carve depends
        // on. This fails if the pitch value changes without the carve's
        // consumers being revisited.
        for edge in -64..64 {
            let (left, right) = (up(edge), down(edge));
            assert_eq!(left.rem_euclid(COLUMN_WIDTH_QUANTUM_HWP), 0, "left {edge}");
            assert_eq!(
                right.rem_euclid(COLUMN_WIDTH_QUANTUM_HWP),
                0,
                "right {edge}"
            );
            assert!(left >= edge && right <= edge, "inward {edge}");
            assert!(left - edge < COLUMN_WIDTH_QUANTUM_HWP, "left bound {edge}");
            assert!(
                edge - right < COLUMN_WIDTH_QUANTUM_HWP,
                "right bound {edge}"
            );
        }
    }

    /// A carve that produces no occupiable interval must be refused on **both**
    /// arms, by the same rule.
    ///
    /// Two shapes reach `current_intervals` and survive the minimum-width
    /// prune, which never deletes the last interval: a zero-width base
    /// (`0..0`), and a base the geometry pitch inverted — `1..3` snaps to
    /// `4..0`, which is `snap_base_left(1)..snap_base_right(3)`.
    ///
    /// The admitted arm is the one this fixes. It asked nothing, and the
    /// stored-row predicate is satisfiable by a degenerate row: `0..0` matches
    /// a stored `cs=0 sw=0` exactly, and `4..0` matches `cs=4 sw=-4`. The
    /// retired `retain_preserved_single_segment_rows` refused those with a
    /// `segment_width > 0` precondition that was dropped when the comparison
    /// replaced it. Committing one publishes `segment_width` from
    /// `end.saturating_sub(start)`, which does not clamp at zero.
    fn a_carve_with_no_occupiable_interval_commits_on_neither_arm() {
        let degenerate = [
            (0..0, 0, 0, "zero-width base"),
            // A future grid pitch can invert a narrow positive-width base.
            (
                snap_base_left(1, COLUMN_WIDTH_QUANTUM_HWP)
                    ..snap_base_right(3, COLUMN_WIDTH_QUANTUM_HWP),
                4,
                -4,
                "pitch-inverted base",
            ),
        ];

        for (horizontal, column_start, segment_width, what) in degenerate {
            assert!(
                horizontal.start >= horizontal.end,
                "{what}: fixture must be degenerate"
            );

            // Direct commit: the frame refuses the row outright.
            let mut direct = frame(horizontal.clone(), 0, Vec::new());
            let carved = direct.carve(100).to_vec();
            assert_eq!(
                carved,
                vec![horizontal.clone()],
                "{what}: carve is unpruned"
            );
            assert!(!direct.carved_row_is_usable(), "{what}");
            assert_eq!(
                direct.commit_carved_row(
                    metrics(100, 10),
                    vec![RowSegment::new(
                        0..0,
                        horizontal.clone(),
                        LineSeg::TAG_SINGLE_SEGMENT_LINE,
                    )],
                ),
                None,
                "{what}: a degenerate row must not commit"
            );
            assert_eq!(direct.row_count(), 0, "{what}");

            // Admitted arm: a stored row that matches the degenerate carve
            // exactly is still refused, and the frame is left untouched.
            let original = frame(horizontal.clone(), 0, Vec::new());
            let mut admitting = original.clone();
            let stored = [LineSeg {
                line_height: 100,
                column_start,
                segment_width,
                tag: LineSeg::TAG_SINGLE_SEGMENT_LINE,
                ..Default::default()
            }];
            assert!(
                stored_row_matches_frame_expectation(&horizontal, &stored[0], 0),
                "{what}: precondition — the predicate alone would admit this"
            );
            assert!(
                !admitting.try_admit_stored_rows(&stored, echo_metrics),
                "{what}: admission must refuse it anyway"
            );
            assert_eq!(admitting, original, "{what}: and roll back exactly");
        }
    }

    #[test]
    fn taller_candidate_recarves_before_the_row_is_committed() {
        every_body_route_builds_one_box_for_one_paragraph();
        the_column_solver_quantizes_before_paragraph_margins();
        the_snap_is_total_over_its_own_domain();
        a_carve_with_no_occupiable_interval_commits_on_neither_arm();
        a_row_split_from_first_to_last_is_compared_slot_by_slot();
        a_vertical_rewind_does_not_block_admission();
        any_horizontal_difference_falls_through_to_the_strict_reflow();
        a_later_rejected_row_rolls_back_partial_admission_on_a_shared_frame();
        let mut frame = frame(
            0..100,
            0,
            vec![FrameExclusion {
                horizontal: 0..60,
                vertical: 1_000..3_000,
                policy: FrameExclusionPolicy::BothSides,
            }],
        );

        let carved = frame.carve(900);
        assert_eq!(carved.len(), 1);
        assert_eq!(carved[0], 0..100);
        assert_eq!(frame.top, 0);

        let carved = frame.carve(2_000);
        assert_eq!(carved.len(), 1);
        assert_eq!(carved[0], 60..100);
        assert_eq!(frame.next_geometry_event, Some(3_000));

        frame.top = 3_000;
        let carved = frame.carve(2_000);
        assert_eq!(carved.len(), 1);
        assert_eq!(carved[0], 0..100);
        assert_eq!(frame.top, 3_000);
    }

    #[test]
    fn committed_row_projects_one_complete_lineseg_group_and_advances_once() {
        let mut frame = frame(10..110, 500, Vec::new());
        let carved = frame.carve(900);
        assert_eq!(carved.len(), 1);
        assert_eq!(carved[0], 10..110);

        assert_eq!(
            frame.commit_carved_row(
                metrics(900, 100),
                vec![RowSegment::new(
                    7..31,
                    10..110,
                    LineSeg::TAG_IMPLEMENTATION_PROPERTY | LineSeg::TAG_FIRST_SEGMENT,
                )],
            ),
            Some(0)
        );
        assert_eq!(frame.top, 1_500);
        assert_eq!(frame.row_count(), 1);
        assert_eq!(frame.commit_carved_row(metrics(900, 100), Vec::new()), None);
        assert_eq!(frame.top, 1_500);

        let projected = frame.project_line_segs();
        assert_eq!(projected.len(), 1);
        assert_eq!(projected[0].text_start, 7);
        assert_eq!(projected[0].vertical_pos, 500);
        assert_eq!(projected[0].column_start, 10);
        assert_eq!(projected[0].segment_width, 100);
        assert!(projected[0].is_first_segment());
        assert!(projected[0].is_last_segment());
        assert_ne!(projected[0].tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY, 0);
    }

    #[test]
    fn stored_rows_equal_to_the_frames_expectation_are_admitted() {
        let stored = [
            LineSeg {
                text_start: 0,
                vertical_pos: 100,
                line_height: 300,
                text_height: 280,
                baseline_distance: 250,
                line_spacing: 20,
                column_start: 10,
                segment_width: 100,
                tag: LineSeg::TAG_SINGLE_SEGMENT_LINE,
            },
            LineSeg {
                text_start: 12,
                vertical_pos: 420,
                line_height: 300,
                text_height: 280,
                baseline_distance: 250,
                line_spacing: 20,
                column_start: 10,
                segment_width: 100,
                tag: LineSeg::TAG_SINGLE_SEGMENT_LINE | LineSeg::TAG_IMPLEMENTATION_PROPERTY,
            },
        ];
        let mut frame = frame(10..110, 100, Vec::new());

        assert!(frame.try_admit_stored_rows(&stored, echo_metrics));
        assert_eq!(frame.row_count(), 2);
        assert_eq!(frame.top, 740);
        let projected = frame.project_line_segs();
        assert_eq!(projected.len(), 2);
        assert_eq!(projected[1].text_start, 12);
        assert_eq!(projected[1].vertical_pos, 420);
        // The committed geometry is the carve's, which equals the stored
        // extent — that equality is the admission test (#4755 §1).
        assert!(projected
            .iter()
            .all(|segment| segment.column_start == 10 && segment.segment_width == 100));
    }

    /// Pins a branch that **no production caller can reach today**, and that is
    /// deliberate rather than an oversight: `ParagraphBox::frame` builds every
    /// body frame with an empty exclusion list, so `models_exclusions()` is
    /// false at the only call site and `resolve_stored_line_segs_in_frame`
    /// turns split rows away before this comparison sees them. The multi-slot
    /// path becomes live the moment a float set reaches a body frame; until
    /// then this test is the only thing holding it correct.
    fn a_row_split_from_first_to_last_is_compared_slot_by_slot() {
        // §1.4.1 compares interval COUNT and then horzpos/horzsize per slot.
        // A FIRST..LAST row is one physical row spanning several slots, and it
        // is preserved when the carve reproduces every one of them — refusing
        // to compare it was our departure, not the native rule.
        let stored = [
            LineSeg {
                vertical_pos: 200,
                line_height: 400,
                segment_width: 35,
                tag: LineSeg::TAG_FIRST_SEGMENT,
                ..Default::default()
            },
            LineSeg {
                text_start: 4,
                vertical_pos: 200,
                line_height: 400,
                column_start: 65,
                segment_width: 35,
                tag: LineSeg::TAG_LAST_SEGMENT,
                ..Default::default()
            },
        ];
        let original = frame(
            0..100,
            200,
            vec![FrameExclusion {
                horizontal: 35..65,
                vertical: 0..1_000,
                policy: FrameExclusionPolicy::BothSides,
            }],
        );

        let mut frame = original.clone();
        assert!(frame.try_admit_stored_rows(&stored, echo_metrics));
        assert_eq!(frame.row_count(), 1, "two slots are one physical row");
        let projected = frame.project_line_segs();
        assert_eq!(projected.len(), 2);
        assert_eq!(
            (projected[0].column_start, projected[0].segment_width),
            (0, 35)
        );
        assert_eq!(
            (projected[1].column_start, projected[1].segment_width),
            (65, 35)
        );
    }

    fn a_vertical_rewind_does_not_block_admission() {
        // HWP restarts `vertical_pos` when a paragraph continues on the next
        // page. §1.3/§1.4.1: the native validator never compares that field —
        // it recomputes it every pass and writes it back — so it must not
        // take part in the decision. Text order still must not rewind.
        let original = frame(0..100, 200, Vec::new());
        let row = |text_start, vertical_pos| LineSeg {
            text_start,
            vertical_pos,
            line_height: 400,
            segment_width: 100,
            tag: LineSeg::TAG_SINGLE_SEGMENT_LINE,
            ..Default::default()
        };

        let mut rewound = original.clone();
        assert!(rewound.try_admit_stored_rows(&[row(0, 200), row(4, 0)], echo_metrics));

        let mut backwards_text = original.clone();
        assert!(!backwards_text.try_admit_stored_rows(&[row(4, 200), row(0, 600)], echo_metrics));
        assert_eq!(backwards_text, original);
    }

    fn any_horizontal_difference_falls_through_to_the_strict_reflow() {
        // The predicate is exact equality today and is an open question
        // (`stored_row_matches_frame_expectation`). Both directions are
        // rejections: a stored row wider than the frame's expectation and one
        // narrower than it are equally "not the row the frame expected".
        let original = frame(0..100, 200, Vec::new());
        let row = |segment_width| {
            [LineSeg {
                vertical_pos: 200,
                line_height: 400,
                segment_width,
                tag: LineSeg::TAG_SINGLE_SEGMENT_LINE,
                ..Default::default()
            }]
        };

        let mut wider = original.clone();
        assert!(!wider.try_admit_stored_rows(&row(120), echo_metrics));
        assert_eq!(wider, original);

        let mut narrower = original.clone();
        assert!(!narrower.try_admit_stored_rows(&row(98), echo_metrics));
        assert_eq!(narrower, original);

        let mut exact = original.clone();
        assert!(exact.try_admit_stored_rows(&row(100), echo_metrics));
    }

    fn a_later_rejected_row_rolls_back_partial_admission_on_a_shared_frame() {
        let mut shared = frame(0..100, 50, Vec::new());
        let full_width = 0..100;
        assert_eq!(shared.carve(100), std::slice::from_ref(&full_width));
        assert_eq!(
            shared.commit_carved_row(
                metrics(100, 10),
                vec![RowSegment::new(
                    0..7,
                    0..100,
                    LineSeg::TAG_SINGLE_SEGMENT_LINE,
                )],
            ),
            Some(0)
        );
        let entry_checkpoint = shared.clone();
        let stored = [
            LineSeg {
                text_start: 7,
                vertical_pos: 160,
                line_height: 100,
                text_height: 90,
                baseline_distance: 80,
                line_spacing: 10,
                column_start: 0,
                segment_width: 100,
                tag: LineSeg::TAG_SINGLE_SEGMENT_LINE,
            },
            LineSeg {
                text_start: 20,
                vertical_pos: 270,
                line_height: 100,
                text_height: 90,
                baseline_distance: 80,
                line_spacing: 10,
                column_start: 0,
                segment_width: 130,
                tag: LineSeg::TAG_SINGLE_SEGMENT_LINE,
            },
        ];

        let mut first_row_probe = entry_checkpoint.clone();
        assert!(first_row_probe.try_admit_stored_rows(&stored[..1], echo_metrics));
        assert_eq!(
            first_row_probe.row_count(),
            entry_checkpoint.row_count() + 1
        );
        assert_eq!(first_row_probe.top, 270);

        assert!(!shared.try_admit_stored_rows(&stored, echo_metrics));
        assert_eq!(shared, entry_checkpoint);
    }

    #[test]
    fn one_physical_row_projects_each_carved_interval_with_shared_metrics() {
        let mut frame = frame(
            0..100,
            200,
            vec![FrameExclusion {
                horizontal: 35..65,
                vertical: 0..1_000,
                policy: FrameExclusionPolicy::BothSides,
            }],
        );
        assert_eq!(frame.carve(400), &[0..35, 65..100]);

        assert_eq!(
            frame.commit_carved_row(
                metrics(400, 50),
                vec![
                    RowSegment::new(0..4, 0..35, LineSeg::TAG_FIRST_SEGMENT),
                    RowSegment::new(
                        4..9,
                        65..100,
                        LineSeg::TAG_LAST_SEGMENT | LineSeg::TAG_IMPLEMENTATION_PROPERTY,
                    ),
                ],
            ),
            Some(0)
        );
        assert_eq!(frame.top, 650);

        let projected = frame.project_line_segs();
        assert_eq!(projected.len(), 2);
        assert_eq!(projected[0].vertical_pos, 200);
        assert_eq!(projected[1].vertical_pos, 200);
        assert_eq!(projected[0].line_height, projected[1].line_height);
        assert!(projected[0].is_first_segment());
        assert!(!projected[0].is_last_segment());
        assert!(!projected[1].is_first_segment());
        assert!(projected[1].is_last_segment());
        assert_eq!(projected[0].column_start, 0);
        assert_eq!(projected[0].segment_width, 35);
        assert_eq!(projected[1].column_start, 65);
        assert_eq!(projected[1].segment_width, 35);
    }

    #[test]
    fn both_sides_four_physical_rows_project_eight_segments() {
        // `pic2` has two floating Pictures and is intentionally rejected by
        // the one-Picture transaction. This independent frame proof keeps the
        // core's ordinary two-interval physical-row behavior explicit.
        let mut frame = frame(
            0..100,
            0,
            vec![FrameExclusion {
                horizontal: 35..65,
                vertical: 0..1_000,
                policy: FrameExclusionPolicy::BothSides,
            }],
        );

        for row in 0..4 {
            assert_eq!(frame.carve(100), &[0..35, 65..100]);
            assert_eq!(
                frame.commit_carved_row(
                    metrics(100, 0),
                    vec![
                        RowSegment::new(
                            (row * 2) as u32..(row * 2 + 1) as u32,
                            0..35,
                            LineSeg::TAG_FIRST_SEGMENT,
                        ),
                        RowSegment::new(
                            (row * 2 + 1) as u32..(row * 2 + 2) as u32,
                            65..100,
                            LineSeg::TAG_LAST_SEGMENT,
                        ),
                    ],
                ),
                Some(row)
            );
        }

        let projected = frame.project_line_segs();
        assert_eq!(projected.len(), 8);
        for (row, pair) in projected.chunks_exact(2).enumerate() {
            assert_eq!(pair[0].vertical_pos, (row * 100) as i32);
            assert_eq!(pair[1].vertical_pos, pair[0].vertical_pos);
            assert_eq!(
                (pair[0].column_start, pair[0].segment_width),
                (0, 35),
                "row {row} left interval"
            );
            assert_eq!(
                (pair[1].column_start, pair[1].segment_width),
                (65, 35),
                "row {row} right interval"
            );
            assert!(pair[0].is_first_segment());
            assert!(!pair[0].is_last_segment());
            assert!(!pair[1].is_first_segment());
            assert!(pair[1].is_last_segment());
        }
    }

    #[test]
    fn largest_side_carve_chooses_the_wider_right_lane() {
        let mut frame = frame(
            0..100,
            0,
            vec![FrameExclusion {
                horizontal: 20..60,
                vertical: 0..1_000,
                policy: FrameExclusionPolicy::LargestSide,
            }],
        );

        let expected = 60..100;
        assert_eq!(frame.carve(100), std::slice::from_ref(&expected));
    }

    #[test]
    fn largest_side_carve_breaks_a_tie_to_the_left_lane() {
        let mut frame = frame(
            0..100,
            0,
            vec![FrameExclusion {
                horizontal: 30..70,
                vertical: 0..1_000,
                policy: FrameExclusionPolicy::LargestSide,
            }],
        );

        let expected = 0..30;
        assert_eq!(frame.carve(100), std::slice::from_ref(&expected));
    }

    #[test]
    fn largest_side_carve_moves_a_1440_hwp_left_lane_to_the_right() {
        let mut frame = frame(
            0..10_000,
            0,
            vec![FrameExclusion {
                horizontal: 1_440..9_000,
                vertical: 0..1_000,
                policy: FrameExclusionPolicy::LargestSide,
            }],
        );

        let expected = 9_000..10_000;
        assert_eq!(frame.carve(100), std::slice::from_ref(&expected));
    }

    #[test]
    fn live_frame_retries_when_the_1440_exception_selects_an_unusable_right_lane() {
        let mut frame = LayoutFrame::new(
            0..10_000,
            0,
            vec![FrameExclusion {
                horizontal: 1_440..9_000,
                vertical: 0..1_000,
                policy: FrameExclusionPolicy::LargestSide,
            }],
        );

        let expected = 0..10_000;
        assert_eq!(frame.carve(100), std::slice::from_ref(&expected));
        assert_eq!(frame.top, 1_000);
        assert_eq!(frame.next_geometry_event, None);
    }
}