facet-reflect 0.44.4

Build and manipulate values of arbitrary Facet types at runtime while respecting invariants - safe runtime reflection
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
use facet_core::TryFromOutcome;
use facet_path::{Path, PathStep};

use super::*;
use crate::typeplan::{DeserStrategy, TypePlanNodeKind};

////////////////////////////////////////////////////////////////////////////////////////////////////
// Misc.
////////////////////////////////////////////////////////////////////////////////////////////////////
impl<'facet, const BORROW: bool> Partial<'facet, BORROW> {
    /// Applies a closure to this Partial, enabling chaining with operations that
    /// take ownership and return `Result<Self, E>`.
    ///
    /// This is useful for chaining deserializer methods that need `&mut self`:
    ///
    /// ```ignore
    /// wip = wip
    ///     .begin_field("name")?
    ///     .with(|w| deserializer.deserialize_into(w))?
    ///     .end()?;
    /// ```
    #[inline]
    pub fn with<F, E>(self, f: F) -> Result<Self, E>
    where
        F: FnOnce(Self) -> Result<Self, E>,
    {
        f(self)
    }

    /// Returns true if the Partial is in an active state (not built or poisoned).
    ///
    /// After `build()` succeeds or after an error causes poisoning, the Partial
    /// becomes inactive and most operations will fail.
    #[inline]
    pub fn is_active(&self) -> bool {
        self.state == PartialState::Active
    }

    /// Returns the current frame count (depth of nesting)
    ///
    /// The initial frame count is 1 — `begin_field` would push a new frame,
    /// bringing it to 2, then `end` would bring it back to `1`.
    ///
    /// This is an implementation detail of `Partial`, kinda, but deserializers
    /// might use this for debug assertions, to make sure the state is what
    /// they think it is.
    #[inline]
    pub const fn frame_count(&self) -> usize {
        self.frames().len()
    }

    /// Returns the shape of the current frame.
    ///
    /// # Panics
    ///
    /// Panics if the Partial has been poisoned or built, or if there are no frames
    /// (which indicates a bug in the Partial implementation).
    #[inline]
    pub fn shape(&self) -> &'static Shape {
        if self.state != PartialState::Active {
            panic!(
                "Partial::shape() called on non-active Partial (state: {:?})",
                self.state
            );
        }
        self.frames()
            .last()
            .expect("Partial::shape() called but no frames exist - this is a bug")
            .allocated
            .shape()
    }

    /// Returns the shape of the current frame, or `None` if the Partial is
    /// inactive (poisoned or built) or has no frames.
    ///
    /// This is useful for debugging/logging where you want to inspect the state
    /// without risking a panic.
    #[inline]
    pub fn try_shape(&self) -> Option<&'static Shape> {
        if self.state != PartialState::Active {
            return None;
        }
        self.frames().last().map(|f| f.allocated.shape())
    }

    /// Returns the TypePlanCore for this Partial.
    ///
    /// This provides access to the arena-based type plan data, useful for
    /// resolving field lookups and accessing precomputed metadata.
    #[inline]
    pub fn type_plan_core(&self) -> &crate::typeplan::TypePlanCore {
        &self.root_plan
    }

    /// Returns the precomputed StructPlan for the current frame, if available.
    ///
    /// This provides O(1) or O(log n) field lookup instead of O(n) linear scanning.
    /// Returns `None` if:
    /// - The Partial is not active
    /// - The current frame has no TypePlan (e.g., custom deserialization frames)
    /// - The current type is not a struct
    #[inline]
    pub fn struct_plan(&self) -> Option<&crate::typeplan::StructPlan> {
        if self.state != PartialState::Active {
            return None;
        }
        let frame = self.frames().last()?;
        self.root_plan.struct_plan_by_id(frame.type_plan)
    }

    /// Returns the precomputed EnumPlan for the current frame, if available.
    ///
    /// This provides O(1) or O(log n) variant lookup instead of O(n) linear scanning.
    /// Returns `None` if:
    /// - The Partial is not active
    /// - The current type is not an enum
    #[inline]
    pub fn enum_plan(&self) -> Option<&crate::typeplan::EnumPlan> {
        if self.state != PartialState::Active {
            return None;
        }
        let frame = self.frames().last()?;
        self.root_plan.enum_plan_by_id(frame.type_plan)
    }

    /// Returns the precomputed field plans for the current frame.
    ///
    /// This provides access to precomputed validators and default handling without
    /// runtime attribute scanning.
    ///
    /// Returns `None` if the current type is not a struct or enum variant.
    #[inline]
    pub fn field_plans(&self) -> Option<&[crate::typeplan::FieldPlan]> {
        use crate::typeplan::TypePlanNodeKind;
        let frame = self.frames().last().unwrap();
        let node = self.root_plan.node(frame.type_plan);
        match &node.kind {
            TypePlanNodeKind::Struct(struct_plan) => {
                Some(self.root_plan.fields(struct_plan.fields))
            }
            TypePlanNodeKind::Enum(enum_plan) => {
                // For enums, we need the variant index from the tracker
                if let crate::partial::Tracker::Enum { variant_idx, .. } = &frame.tracker {
                    self.root_plan
                        .variants(enum_plan.variants)
                        .get(*variant_idx)
                        .map(|v| self.root_plan.fields(v.fields))
                } else {
                    None
                }
            }
            _ => None,
        }
    }

    /// Returns the precomputed TypePlanNode for the current frame.
    ///
    /// This provides access to the precomputed deserialization strategy and
    /// other metadata computed at Partial allocation time.
    ///
    /// Returns `None` if:
    /// - The Partial is not active
    /// - There are no frames
    #[inline]
    pub fn plan_node(&self) -> Option<&crate::typeplan::TypePlanNode> {
        if self.state != PartialState::Active {
            return None;
        }
        let frame = self.frames().last()?;
        Some(self.root_plan.node(frame.type_plan))
    }

    /// Returns the node ID for the current frame's type plan.
    ///
    /// Returns `None` if:
    /// - The Partial is not active
    /// - There are no frames
    #[inline]
    pub fn plan_node_id(&self) -> Option<crate::typeplan::NodeId> {
        if self.state != PartialState::Active {
            return None;
        }
        let frame = self.frames().last()?;
        Some(frame.type_plan)
    }

    /// Returns the precomputed deserialization strategy for the current frame.
    ///
    /// This tells facet-format exactly how to deserialize the current type without
    /// runtime inspection of Shape/Def/vtable. The strategy is computed once at
    /// TypePlan build time.
    ///
    /// If the current node is a BackRef (recursive type), this automatically
    /// follows the reference to return the target node's strategy.
    ///
    /// Returns `None` if:
    /// - The Partial is not active
    /// - There are no frames
    #[inline]
    pub fn deser_strategy(&self) -> Option<&DeserStrategy> {
        let node = self.plan_node()?;
        // Resolve BackRef if needed - resolve_backref returns the node unchanged if not a BackRef
        let resolved = self.root_plan.resolve_backref(node);
        Some(&resolved.strategy)
    }

    /// Returns the precomputed proxy nodes for the current frame's type.
    ///
    /// These contain TypePlan nodes for all proxies (format-agnostic and format-specific)
    /// on this type, allowing runtime lookup based on format namespace.
    #[inline]
    pub fn proxy_nodes(&self) -> Option<&crate::typeplan::ProxyNodes> {
        let node = self.plan_node()?;
        let resolved = self.root_plan.resolve_backref(node);
        Some(&resolved.proxies)
    }

    /// Returns true if the current frame is building a smart pointer slice (Arc<\[T\]>, Rc<\[T\]>, Box<\[T\]>).
    ///
    /// This is used by deserializers to determine if they should deserialize as a list
    /// rather than recursing into the smart pointer type.
    #[inline]
    pub fn is_building_smart_ptr_slice(&self) -> bool {
        if self.state != PartialState::Active {
            return false;
        }
        self.frames()
            .last()
            .is_some_and(|f| matches!(f.tracker, Tracker::SmartPointerSlice { .. }))
    }

    /// Returns the current path in deferred mode (for debugging/tracing).
    #[inline]
    pub fn current_path(&self) -> Option<facet_path::Path> {
        if self.is_deferred() {
            Some(self.derive_path())
        } else {
            None
        }
    }

    /// Checks if the current frame should be stored for deferred processing.
    ///
    /// This determines whether a frame can safely be stored and re-entered later
    /// in deferred mode. A frame should be stored if:
    /// 1. It's a re-entrant type (struct, enum, collection, Option)
    /// 2. It has storable ownership (Field or Owned)
    /// 3. It doesn't have a SmartPointer parent that needs immediate completion
    ///
    /// Returns `true` if the frame should be stored, `false` if it should be
    /// validated immediately.
    fn should_store_frame_for_deferred(&self) -> bool {
        // In deferred mode, all frames have stable memory and can be stored.
        // PR #2019 added stable storage for all container elements (ListRope for Vec,
        // pending_entries for Map, pending_inner for Option).
        true
    }

    /// Enables deferred materialization mode with the given Resolution.
    ///
    /// When deferred mode is enabled:
    /// - `end()` stores frames instead of validating them
    /// - Re-entering a path restores the stored frame with its state intact
    /// - `finish_deferred()` performs final validation and materialization
    ///
    /// This allows deserializers to handle interleaved fields (e.g., TOML dotted
    /// keys, flattened structs) where nested fields aren't contiguous in the input.
    ///
    /// # Use Cases
    ///
    /// - TOML dotted keys: `inner.x = 1` followed by `count = 2` then `inner.y = 3`
    /// - Flattened structs where nested fields appear at the parent level
    /// - Any format where field order doesn't match struct nesting
    ///
    /// # Errors
    ///
    /// Returns an error if already in deferred mode.
    #[inline]
    pub fn begin_deferred(mut self) -> Result<Self, ReflectError> {
        // Cannot enable deferred mode if already in deferred mode
        if self.is_deferred() {
            return Err(self.err(ReflectErrorKind::InvariantViolation {
                invariant: "begin_deferred() called but already in deferred mode",
            }));
        }

        // Take the stack out of Strict mode and wrap in Deferred mode
        let FrameMode::Strict { stack } = core::mem::replace(
            &mut self.mode,
            FrameMode::Strict { stack: Vec::new() }, // temporary placeholder
        ) else {
            unreachable!("just checked we're not in deferred mode");
        };

        let start_depth = stack.len();
        self.mode = FrameMode::Deferred {
            stack,
            start_depth,
            stored_frames: BTreeMap::new(),
        };
        Ok(self)
    }

    /// Finishes deferred mode: validates all stored frames and finalizes.
    ///
    /// This method:
    /// 1. Validates that all stored frames are fully initialized
    /// 2. Processes frames from deepest to shallowest, updating parent ISets
    /// 3. Validates the root frame
    ///
    /// # Errors
    ///
    /// Returns an error if any required fields are missing or if the partial is
    /// not in deferred mode.
    pub fn finish_deferred(mut self) -> Result<Self, ReflectError> {
        // Check if we're in deferred mode first, before extracting state
        if !self.is_deferred() {
            return Err(self.err(ReflectErrorKind::InvariantViolation {
                invariant: "finish_deferred() called but deferred mode is not enabled",
            }));
        }

        // Extract deferred state, transitioning back to Strict mode
        let FrameMode::Deferred {
            stack,
            mut stored_frames,
            ..
        } = core::mem::replace(&mut self.mode, FrameMode::Strict { stack: Vec::new() })
        else {
            unreachable!("just checked is_deferred()");
        };

        // Restore the stack to self.mode
        self.mode = FrameMode::Strict { stack };

        // Sort paths by depth (deepest first) so we process children before parents.
        // For equal-depth paths, we need stable ordering for list elements:
        // Index(0) must be processed before Index(1) to maintain insertion order.
        let mut paths: Vec<_> = stored_frames.keys().cloned().collect();
        paths.sort_by(|a, b| {
            // Primary: deeper paths first
            let depth_cmp = b.len().cmp(&a.len());
            if depth_cmp != core::cmp::Ordering::Equal {
                return depth_cmp;
            }
            // Secondary: for same-depth paths, compare step by step
            // This ensures Index(0) comes before Index(1) for the same parent
            for (step_a, step_b) in a.steps.iter().zip(b.steps.iter()) {
                let step_cmp = step_a.cmp(step_b);
                if step_cmp != core::cmp::Ordering::Equal {
                    return step_cmp;
                }
            }
            core::cmp::Ordering::Equal
        });

        trace!(
            "finish_deferred: Processing {} stored frames in order: {:?}",
            paths.len(),
            paths
        );

        // Process each stored frame from deepest to shallowest
        for path in paths {
            let mut frame = stored_frames.remove(&path).unwrap();

            trace!(
                "finish_deferred: Processing frame at {:?}, shape {}, tracker {:?}",
                path,
                frame.allocated.shape(),
                frame.tracker.kind()
            );

            // Special handling for SmartPointerSlice: convert builder to Arc<[T]> before validation
            if let Tracker::SmartPointerSlice { vtable, .. } = &frame.tracker {
                let vtable = *vtable;
                let current_shape = frame.allocated.shape();

                // Convert the builder to Arc<[T]>
                let builder_ptr = unsafe { frame.data.assume_init() };
                let arc_ptr = unsafe { (vtable.convert_fn)(builder_ptr) };

                trace!(
                    "finish_deferred: Converting SmartPointerSlice builder to {}",
                    current_shape
                );

                // Handle different ownership cases
                match frame.ownership {
                    FrameOwnership::Field { field_idx } => {
                        // Arc<[T]> is a field in a struct
                        // Find the parent frame and write the Arc to the field location
                        let parent_path = facet_path::Path {
                            shape: path.shape,
                            steps: path.steps[..path.steps.len() - 1].to_vec(),
                        };

                        // Paths are absolute from the root, so the parent frame lives at
                        // stack[parent_path.steps.len()] when it's still on the stack.
                        let parent_frame_opt =
                            if let Some(parent_frame) = stored_frames.get_mut(&parent_path) {
                                Some(parent_frame)
                            } else {
                                self.frames_mut().get_mut(parent_path.steps.len())
                            };

                        if let Some(parent_frame) = parent_frame_opt {
                            // Get the field to find its offset
                            if let Type::User(UserType::Struct(struct_type)) =
                                parent_frame.allocated.shape().ty
                            {
                                let field = &struct_type.fields[field_idx];

                                // Calculate where the Arc should be written (parent.data + field.offset)
                                let field_location =
                                    unsafe { parent_frame.data.field_uninit(field.offset) };

                                // Write the Arc to the parent struct's field location
                                if let Ok(arc_layout) = current_shape.layout.sized_layout() {
                                    let arc_size = arc_layout.size();
                                    unsafe {
                                        core::ptr::copy_nonoverlapping(
                                            arc_ptr.as_byte_ptr(),
                                            field_location.as_mut_byte_ptr(),
                                            arc_size,
                                        );
                                    }

                                    // Free the staging allocation from convert_fn
                                    unsafe {
                                        ::alloc::alloc::dealloc(
                                            arc_ptr.as_byte_ptr() as *mut u8,
                                            arc_layout,
                                        );
                                    }

                                    // Update the frame to point to the correct field location and mark as initialized
                                    frame.data = field_location;
                                    frame.tracker = Tracker::Scalar;
                                    frame.is_init = true;

                                    trace!(
                                        "finish_deferred: SmartPointerSlice converted and written to field {}",
                                        field_idx
                                    );
                                }
                            }
                        }
                    }
                    FrameOwnership::Owned => {
                        // Arc<[T]> is the root - write in place
                        if let Ok(arc_layout) = current_shape.layout.sized_layout() {
                            let arc_size = arc_layout.size();
                            // Allocate new memory for the Arc
                            let new_ptr = facet_core::alloc_for_layout(arc_layout);
                            unsafe {
                                core::ptr::copy_nonoverlapping(
                                    arc_ptr.as_byte_ptr(),
                                    new_ptr.as_mut_byte_ptr(),
                                    arc_size,
                                );
                            }
                            // Free the staging allocation
                            unsafe {
                                ::alloc::alloc::dealloc(
                                    arc_ptr.as_byte_ptr() as *mut u8,
                                    arc_layout,
                                );
                            }
                            frame.data = new_ptr;
                            frame.tracker = Tracker::Scalar;
                            frame.is_init = true;
                        }
                    }
                    _ => {}
                }
            }

            // Fill in defaults for unset fields that have defaults
            if let Err(e) = frame.fill_defaults() {
                // Before cleanup, clear the parent's iset bit for the frame that failed.
                // This prevents the parent from trying to drop this field when Partial is dropped.
                Self::clear_parent_iset_for_path(&path, self.frames_mut(), &mut stored_frames);
                // If this is a MapValue/Deref/OptionSome frame, a parent tracker holds
                // a pointer to our frame's memory (pending_entries / pending_inner). Clear
                // that pointer before we dealloc, so the parent's deinit won't double-drop.
                Self::sever_parent_pending_for_path(&path, self.frames_mut(), &mut stored_frames);
                frame.deinit();
                frame.dealloc();
                // Clean up remaining stored frames safely (deepest first, clearing parent isets)
                Self::cleanup_stored_frames_on_error(stored_frames, self.frames_mut());
                return Err(self.err(e));
            }

            // Validate the frame is fully initialized
            if let Err(e) = frame.require_full_initialization() {
                // Before cleanup, clear the parent's iset bit for the frame that failed.
                // This prevents the parent from trying to drop this field when Partial is dropped.
                Self::clear_parent_iset_for_path(&path, self.frames_mut(), &mut stored_frames);
                // If this is a MapValue/Deref/OptionSome frame, a parent tracker holds
                // a pointer to our frame's memory (pending_entries / pending_inner). Clear
                // that pointer before we dealloc, so the parent's deinit won't double-drop.
                Self::sever_parent_pending_for_path(&path, self.frames_mut(), &mut stored_frames);
                frame.deinit();
                frame.dealloc();
                // Clean up remaining stored frames safely (deepest first, clearing parent isets)
                Self::cleanup_stored_frames_on_error(stored_frames, self.frames_mut());
                return Err(self.err(e));
            }

            // Update parent's ISet to mark this field as initialized.
            // The parent lives either in stored_frames (if it was ended during deferred mode)
            // or on the frames stack at index parent_path.steps.len() (paths are absolute).
            if let Some(last_step) = path.steps.last() {
                // Construct parent path (same shape, all steps except the last one)
                let parent_path = facet_path::Path {
                    shape: path.shape,
                    steps: path.steps[..path.steps.len() - 1].to_vec(),
                };

                // Special handling for Option inner values: when path ends with OptionSome,
                // the parent is an Option frame and we need to complete the Option by
                // writing the inner value into the Option's memory.
                if matches!(last_step, PathStep::OptionSome) {
                    // Find the Option frame (parent)
                    let option_frame =
                        if let Some(parent_frame) = stored_frames.get_mut(&parent_path) {
                            Some(parent_frame)
                        } else {
                            self.frames_mut().get_mut(parent_path.steps.len())
                        };

                    if let Some(option_frame) = option_frame {
                        // The frame contains the inner value - write it into the Option's memory
                        Self::complete_option_frame(option_frame, frame);
                        // Frame data has been transferred to Option - don't drop it
                        continue;
                    }
                }

                // Special handling for SmartPointer inner values: when path ends with Deref,
                // the parent is a SmartPointer frame and we need to complete it by
                // creating the SmartPointer from the inner value.
                if matches!(last_step, PathStep::Deref) {
                    // Find the SmartPointer frame (parent)
                    let smart_ptr_frame =
                        if let Some(parent_frame) = stored_frames.get_mut(&parent_path) {
                            Some(parent_frame)
                        } else {
                            self.frames_mut().get_mut(parent_path.steps.len())
                        };

                    if let Some(smart_ptr_frame) = smart_ptr_frame {
                        // The frame contains the inner value - create the SmartPointer from it
                        Self::complete_smart_pointer_frame(smart_ptr_frame, frame);
                        // Frame data has been transferred to SmartPointer - don't drop it
                        continue;
                    }
                }

                // Special handling for Inner values: when path ends with Inner,
                // the parent is a transparent wrapper (NonZero, ByteString, etc.) and we need
                // to convert the inner value to the parent type using try_from.
                if matches!(last_step, PathStep::Inner) {
                    // Find the parent frame (Inner wrapper)
                    let parent_frame =
                        if let Some(parent_frame) = stored_frames.get_mut(&parent_path) {
                            Some(parent_frame)
                        } else {
                            self.frames_mut().get_mut(parent_path.steps.len())
                        };

                    if let Some(inner_wrapper_frame) = parent_frame {
                        // The frame contains the inner value - convert to parent type using try_from
                        Self::complete_inner_frame(inner_wrapper_frame, frame);
                        // Frame data has been transferred - don't drop it
                        continue;
                    }
                }

                // Special handling for Proxy values: when path ends with Proxy,
                // the parent is the target type (e.g., Inner) and we need to convert
                // the proxy value (e.g., InnerProxy) using the proxy's convert_in.
                if matches!(last_step, PathStep::Proxy) {
                    // Find the parent frame (the proxy target)
                    let parent_frame =
                        if let Some(parent_frame) = stored_frames.get_mut(&parent_path) {
                            Some(parent_frame)
                        } else {
                            self.frames_mut().get_mut(parent_path.steps.len())
                        };

                    if let Some(target_frame) = parent_frame {
                        Self::complete_proxy_frame(target_frame, frame);
                        continue;
                    }
                }

                // Special handling for List/SmartPointerSlice element values: when path ends with Index,
                // the parent is a List or SmartPointerSlice frame and we need to push the element into it.
                // RopeSlot frames are already stored in the rope and will be drained during
                // validation - pushing them here would duplicate the elements.
                if matches!(last_step, PathStep::Index(_))
                    && !matches!(frame.ownership, FrameOwnership::RopeSlot)
                {
                    // Find the parent frame (List or SmartPointerSlice)
                    let parent_frame =
                        if let Some(parent_frame) = stored_frames.get_mut(&parent_path) {
                            Some(parent_frame)
                        } else {
                            self.frames_mut().get_mut(parent_path.steps.len())
                        };

                    if let Some(parent_frame) = parent_frame {
                        // Check if parent is a SmartPointerSlice (e.g., Arc<[T]>)
                        if matches!(parent_frame.tracker, Tracker::SmartPointerSlice { .. }) {
                            Self::complete_smart_pointer_slice_item_frame(parent_frame, frame);
                            // Frame data has been transferred to slice builder - don't drop it
                            continue;
                        }
                        // Otherwise try List handling
                        Self::complete_list_item_frame(parent_frame, frame);
                        // Frame data has been transferred to List - don't drop it
                        continue;
                    }
                }

                // Special handling for Map key values: when path ends with MapKey,
                // the parent is a Map frame and we need to transition it to PushingValue state.
                if matches!(last_step, PathStep::MapKey(_)) {
                    // Find the Map frame (parent)
                    let map_frame = if let Some(parent_frame) = stored_frames.get_mut(&parent_path)
                    {
                        Some(parent_frame)
                    } else {
                        self.frames_mut().get_mut(parent_path.steps.len())
                    };

                    if let Some(map_frame) = map_frame {
                        // Transition the Map from PushingKey to PushingValue state
                        Self::complete_map_key_frame(map_frame, frame);
                        continue;
                    }
                }

                // Special handling for Map value values: when path ends with MapValue,
                // the parent is a Map frame and we need to add the entry to pending_entries.
                if matches!(last_step, PathStep::MapValue(_)) {
                    // Find the Map frame (parent)
                    let map_frame = if let Some(parent_frame) = stored_frames.get_mut(&parent_path)
                    {
                        Some(parent_frame)
                    } else {
                        self.frames_mut().get_mut(parent_path.steps.len())
                    };

                    if let Some(map_frame) = map_frame {
                        // Add the key-value pair to pending_entries
                        Self::complete_map_value_frame(map_frame, frame);
                        continue;
                    }
                }

                // Only mark field initialized if the step is actually a Field
                if let PathStep::Field(field_idx) = last_step {
                    let field_idx = *field_idx as usize;
                    // Paths are absolute from the root, so the parent frame lives at
                    // stack[parent_path.steps.len()] when it's still on the stack.
                    let parent_frame =
                        if let Some(parent_frame) = stored_frames.get_mut(&parent_path) {
                            Some(parent_frame)
                        } else {
                            self.frames_mut().get_mut(parent_path.steps.len())
                        };
                    if let Some(parent_frame) = parent_frame {
                        Self::mark_field_initialized_by_index(parent_frame, field_idx);
                    }
                }
            }

            // Frame is validated and parent is updated - dealloc if needed
            frame.dealloc();
        }

        // Invariant check: we must have at least one frame after finish_deferred
        if self.frames().is_empty() {
            // No need to poison - returning Err consumes self, Drop will handle cleanup
            return Err(self.err(ReflectErrorKind::InvariantViolation {
                invariant: "finish_deferred() left Partial with no frames",
            }));
        }

        // Fill defaults and validate the root frame is fully initialized
        if let Some(frame) = self.frames_mut().last_mut() {
            // Fill defaults - this can fail if a field has #[facet(default)] but no default impl
            if let Err(e) = frame.fill_defaults() {
                return Err(self.err(e));
            }
            // Root validation failed. At this point, all stored frames have been
            // processed and their parent isets updated.
            // No need to poison - returning Err consumes self, Drop will handle cleanup
            if let Err(e) = frame.require_full_initialization() {
                return Err(self.err(e));
            }
        }

        Ok(self)
    }

    /// Mark a field as initialized in a frame's tracker by index
    fn mark_field_initialized_by_index(frame: &mut Frame, idx: usize) {
        crate::trace!(
            "mark_field_initialized_by_index: idx={}, frame shape={}, tracker={:?}",
            idx,
            frame.allocated.shape(),
            frame.tracker.kind()
        );

        // If the tracker is Scalar but this is a struct type, upgrade to Struct tracker.
        // This can happen if the frame was deinit'd (e.g., by a failed set_default)
        // which resets the tracker to Scalar.
        if matches!(frame.tracker, Tracker::Scalar)
            && let Type::User(UserType::Struct(struct_type)) = frame.allocated.shape().ty
        {
            frame.tracker = Tracker::Struct {
                iset: ISet::new(struct_type.fields.len()),
                current_child: None,
            };
        }

        match &mut frame.tracker {
            Tracker::Struct { iset, .. } => {
                crate::trace!("mark_field_initialized_by_index: setting iset for struct");
                iset.set(idx);
            }
            Tracker::Enum { data, .. } => {
                crate::trace!(
                    "mark_field_initialized_by_index: setting data for enum, before={:?}",
                    data
                );
                data.set(idx);
                crate::trace!(
                    "mark_field_initialized_by_index: setting data for enum, after={:?}",
                    data
                );
            }
            Tracker::Array { iset, .. } => {
                crate::trace!("mark_field_initialized_by_index: setting iset for array");
                iset.set(idx);
            }
            _ => {
                crate::trace!(
                    "mark_field_initialized_by_index: no match for tracker {:?}",
                    frame.tracker.kind()
                );
            }
        }
    }

    /// Clear a parent frame's iset bit for a given path.
    /// The parent could be on the stack or in stored_frames.
    fn clear_parent_iset_for_path(
        path: &Path,
        stack: &mut [Frame],
        stored_frames: &mut ::alloc::collections::BTreeMap<Path, Frame>,
    ) {
        let Some(&PathStep::Field(field_idx)) = path.steps.last() else {
            return;
        };
        let field_idx = field_idx as usize;
        let parent_path = Path {
            shape: path.shape,
            steps: path.steps[..path.steps.len() - 1].to_vec(),
        };

        // Paths are absolute from the root; the frame at a given path lives at
        // stack[path.steps.len()], so the parent lives at stack[parent_path.steps.len()].
        let parent_frame = if let Some(parent_frame) = stored_frames.get_mut(&parent_path) {
            Some(parent_frame)
        } else {
            stack.get_mut(parent_path.steps.len())
        };
        if let Some(parent_frame) = parent_frame {
            Self::unset_field_in_tracker(&mut parent_frame.tracker, field_idx);
        }
    }

    /// Sever parent/child pointer ownership when a stored child frame fails validation
    /// in `finish_deferred`.
    ///
    /// When a child frame is stored for deferred processing, the parent may keep a
    /// pointer to the child's buffer so it can finalize later (Map's `pending_entries`,
    /// SmartPointer's / Option's `pending_inner`). If the child then fails validation
    /// and its buffer is deallocated, that parent pointer would dangle and cause a
    /// double-free when the parent is subsequently deinited.
    ///
    /// This helper clears the relevant parent field so the parent's own cleanup leaves
    /// the buffer alone.
    fn sever_parent_pending_for_path(
        path: &Path,
        stack: &mut [Frame],
        stored_frames: &mut ::alloc::collections::BTreeMap<Path, Frame>,
    ) {
        let Some(last_step) = path.steps.last() else {
            return;
        };
        if !matches!(
            last_step,
            PathStep::MapValue(_) | PathStep::Deref | PathStep::OptionSome
        ) {
            return;
        }

        let parent_path = Path {
            shape: path.shape,
            steps: path.steps[..path.steps.len() - 1].to_vec(),
        };

        // Paths are absolute from the root; the frame at a given path lives at
        // stack[path.steps.len()], so the parent lives at stack[parent_path.steps.len()].
        let parent_frame = if let Some(parent_frame) = stored_frames.get_mut(&parent_path) {
            Some(parent_frame)
        } else {
            stack.get_mut(parent_path.steps.len())
        };

        let Some(parent_frame) = parent_frame else {
            return;
        };

        let parent_shape = parent_frame.allocated.shape();

        match (&mut parent_frame.tracker, last_step) {
            (
                Tracker::Map {
                    pending_entries, ..
                },
                PathStep::MapValue(_),
            ) => {
                // The pending entry held both (key_ptr, value_ptr). The value buffer is
                // about to be freed by the caller via frame.dealloc(). The key buffer,
                // however, is solely owned by this pending entry — if we just pop it
                // without dropping, both the key's in-place contents and its allocation
                // leak.
                if let Some((key_ptr, _value_ptr)) = pending_entries.pop()
                    && let Def::Map(map_def) = parent_shape.def
                {
                    unsafe {
                        map_def.k().call_drop_in_place(key_ptr.assume_init());
                    }
                    if let Ok(key_layout) = map_def.k().layout.sized_layout()
                        && key_layout.size() > 0
                    {
                        unsafe {
                            ::alloc::alloc::dealloc(key_ptr.as_mut_byte_ptr(), key_layout);
                        }
                    }
                }
                trace!(
                    "sever_parent_pending_for_path: popped & dropped map pending_entry for failed MapValue at {:?}",
                    path,
                );
            }
            (
                Tracker::SmartPointer {
                    building_inner,
                    pending_inner,
                },
                PathStep::Deref,
            ) => {
                *pending_inner = None;
                *building_inner = true;
                parent_frame.is_init = false;
                trace!(
                    "sever_parent_pending_for_path: cleared SmartPointer pending_inner for failed Deref at {:?}",
                    path,
                );
            }
            (
                Tracker::Option {
                    building_inner,
                    pending_inner,
                },
                PathStep::OptionSome,
            ) => {
                *pending_inner = None;
                *building_inner = true;
                parent_frame.is_init = false;
                trace!(
                    "sever_parent_pending_for_path: cleared Option pending_inner for failed OptionSome at {:?}",
                    path,
                );
            }
            _ => {}
        }
    }

    /// Helper to unset a field index in a tracker's iset
    fn unset_field_in_tracker(tracker: &mut Tracker, field_idx: usize) {
        match tracker {
            Tracker::Struct { iset, .. } => {
                iset.unset(field_idx);
            }
            Tracker::Enum { data, .. } => {
                data.unset(field_idx);
            }
            Tracker::Array { iset, .. } => {
                iset.unset(field_idx);
            }
            _ => {}
        }
    }

    /// Safely clean up stored frames on error in finish_deferred.
    ///
    /// This mirrors the cleanup logic in Drop: process frames deepest-first and
    /// clear parent's iset bits before deiniting children to prevent double-drops.
    fn cleanup_stored_frames_on_error(
        mut stored_frames: ::alloc::collections::BTreeMap<Path, Frame>,
        stack: &mut [Frame],
    ) {
        // Sort by depth (deepest first) so children are processed before parents
        let mut paths: Vec<_> = stored_frames.keys().cloned().collect();
        paths.sort_by_key(|p| core::cmp::Reverse(p.steps.len()));

        trace!(
            "cleanup_stored_frames_on_error: {} frames to clean, paths: {:?}",
            paths.len(),
            paths
        );

        for path in &paths {
            if let Some(frame) = stored_frames.get(path) {
                trace!(
                    "cleanup: processing path={:?}, shape={}, tracker={:?}, is_init={}, ownership={:?}",
                    path,
                    frame.allocated.shape(),
                    frame.tracker.kind(),
                    frame.is_init,
                    frame.ownership,
                );
                // Dump iset contents for struct/enum trackers
                match &frame.tracker {
                    Tracker::Struct { iset: _iset, .. } => {
                        trace!("cleanup:   Struct iset = {:?}", _iset);
                    }
                    Tracker::Enum {
                        variant: _variant,
                        data: _data,
                        ..
                    } => {
                        trace!("cleanup:   Enum {:?} data = {:?}", _variant.name, _data);
                    }
                    _ => {}
                }
            }
        }

        for path in paths {
            if let Some(mut frame) = stored_frames.remove(&path) {
                trace!(
                    "cleanup: REMOVING path={:?}, shape={}, tracker={:?}",
                    path,
                    frame.allocated.shape(),
                    frame.tracker.kind(),
                );
                // Before dropping this frame, clear the parent's iset bit so the
                // parent won't try to drop this field again.
                Self::clear_parent_iset_for_path(&path, stack, &mut stored_frames);
                // If this frame's buffer is also tracked by a parent Map/SmartPointer/Option
                // pending pointer, clear that reference too — otherwise the parent will try to
                // drop the same buffer we're about to dealloc.
                Self::sever_parent_pending_for_path(&path, stack, &mut stored_frames);
                trace!("cleanup: calling deinit() on path={:?}", path,);
                frame.deinit();
                frame.dealloc();
            }
        }
    }

    /// Complete an Option frame by writing the inner value and marking it initialized.
    /// Used in finish_deferred when processing a stored frame at a path ending with "Some".
    fn complete_option_frame(option_frame: &mut Frame, inner_frame: Frame) {
        if let Def::Option(option_def) = option_frame.allocated.shape().def {
            // Use the Option vtable to initialize Some(inner_value)
            let init_some_fn = option_def.vtable.init_some;

            // The inner frame contains the inner value
            let inner_value_ptr = unsafe { inner_frame.data.assume_init() };

            // Initialize the Option as Some(inner_value)
            unsafe {
                init_some_fn(option_frame.data, inner_value_ptr);
            }

            // Deallocate the inner value's memory since init_some_fn moved it
            if let FrameOwnership::Owned = inner_frame.ownership
                && let Ok(layout) = inner_frame.allocated.shape().layout.sized_layout()
                && layout.size() > 0
            {
                unsafe {
                    ::alloc::alloc::dealloc(inner_frame.data.as_mut_byte_ptr(), layout);
                }
            }

            // Mark the Option as initialized
            option_frame.tracker = Tracker::Option {
                building_inner: false,
                pending_inner: None,
            };
            option_frame.is_init = true;
        }
    }

    fn complete_smart_pointer_frame(smart_ptr_frame: &mut Frame, inner_frame: Frame) {
        if let Def::Pointer(smart_ptr_def) = smart_ptr_frame.allocated.shape().def {
            // Use the SmartPointer vtable to create the smart pointer from the inner value
            if let Some(new_into_fn) = smart_ptr_def.vtable.new_into_fn {
                // Sized pointee case: use new_into_fn
                let _ = unsafe { inner_frame.data.assume_init() };

                // Create the SmartPointer with the inner value
                unsafe {
                    new_into_fn(
                        smart_ptr_frame.data,
                        PtrMut::new(inner_frame.data.as_mut_byte_ptr()),
                    );
                }

                // Deallocate the inner value's memory since new_into_fn moved it
                if let FrameOwnership::Owned = inner_frame.ownership
                    && let Ok(layout) = inner_frame.allocated.shape().layout.sized_layout()
                    && layout.size() > 0
                {
                    unsafe {
                        ::alloc::alloc::dealloc(inner_frame.data.as_mut_byte_ptr(), layout);
                    }
                }

                // Mark the SmartPointer as initialized
                smart_ptr_frame.tracker = Tracker::SmartPointer {
                    building_inner: false,
                    pending_inner: None,
                };
                smart_ptr_frame.is_init = true;
            } else if let Some(pointee) = smart_ptr_def.pointee()
                && pointee.is_shape(str::SHAPE)
                && inner_frame.allocated.shape().is_shape(String::SHAPE)
            {
                // Unsized pointee case: String -> Arc<str>/Box<str>/Rc<str> conversion
                use ::alloc::{rc::Rc, string::String, sync::Arc};
                use facet_core::KnownPointer;

                let Some(known) = smart_ptr_def.known else {
                    return;
                };

                // Read the String value from the inner frame
                let string_ptr = inner_frame.data.as_mut_byte_ptr() as *mut String;
                let string_value = unsafe { core::ptr::read(string_ptr) };

                // Convert to the appropriate smart pointer type
                match known {
                    KnownPointer::Box => {
                        let boxed: ::alloc::boxed::Box<str> = string_value.into_boxed_str();
                        unsafe {
                            core::ptr::write(
                                smart_ptr_frame.data.as_mut_byte_ptr()
                                    as *mut ::alloc::boxed::Box<str>,
                                boxed,
                            );
                        }
                    }
                    KnownPointer::Arc => {
                        let arc: Arc<str> = Arc::from(string_value.into_boxed_str());
                        unsafe {
                            core::ptr::write(
                                smart_ptr_frame.data.as_mut_byte_ptr() as *mut Arc<str>,
                                arc,
                            );
                        }
                    }
                    KnownPointer::Rc => {
                        let rc: Rc<str> = Rc::from(string_value.into_boxed_str());
                        unsafe {
                            core::ptr::write(
                                smart_ptr_frame.data.as_mut_byte_ptr() as *mut Rc<str>,
                                rc,
                            );
                        }
                    }
                    _ => return,
                }

                // Deallocate the String's memory (we moved the data out via ptr::read)
                if let FrameOwnership::Owned = inner_frame.ownership
                    && let Ok(layout) = inner_frame.allocated.shape().layout.sized_layout()
                    && layout.size() > 0
                {
                    unsafe {
                        ::alloc::alloc::dealloc(inner_frame.data.as_mut_byte_ptr(), layout);
                    }
                }

                // Mark the SmartPointer as initialized
                smart_ptr_frame.tracker = Tracker::SmartPointer {
                    building_inner: false,
                    pending_inner: None,
                };
                smart_ptr_frame.is_init = true;
            }
        }
    }

    /// Complete an Inner frame by converting the inner value to the parent type using try_from
    /// (for deferred finalization)
    fn complete_inner_frame(inner_wrapper_frame: &mut Frame, inner_frame: Frame) {
        let wrapper_shape = inner_wrapper_frame.allocated.shape();
        let inner_ptr = PtrConst::new(inner_frame.data.as_byte_ptr());
        let inner_shape = inner_frame.allocated.shape();

        // Handle Direct and Indirect vtables - both return TryFromOutcome
        let result = match wrapper_shape.vtable {
            facet_core::VTableErased::Direct(vt) => {
                if let Some(try_from_fn) = vt.try_from {
                    unsafe {
                        try_from_fn(
                            inner_wrapper_frame.data.as_mut_byte_ptr() as *mut (),
                            inner_shape,
                            inner_ptr,
                        )
                    }
                } else {
                    return;
                }
            }
            facet_core::VTableErased::Indirect(vt) => {
                if let Some(try_from_fn) = vt.try_from {
                    let ox_uninit =
                        facet_core::OxPtrUninit::new(inner_wrapper_frame.data, wrapper_shape);
                    unsafe { try_from_fn(ox_uninit, inner_shape, inner_ptr) }
                } else {
                    return;
                }
            }
        };

        match result {
            TryFromOutcome::Converted => {
                crate::trace!(
                    "complete_inner_frame: converted {} to {}",
                    inner_shape,
                    wrapper_shape
                );
            }
            TryFromOutcome::Unsupported | TryFromOutcome::Failed(_) => {
                crate::trace!(
                    "complete_inner_frame: conversion failed from {} to {}",
                    inner_shape,
                    wrapper_shape
                );
                return;
            }
        }

        // Deallocate the inner value's memory (try_from consumed it)
        if let FrameOwnership::Owned = inner_frame.ownership
            && let Ok(layout) = inner_frame.allocated.shape().layout.sized_layout()
            && layout.size() > 0
        {
            unsafe {
                ::alloc::alloc::dealloc(inner_frame.data.as_mut_byte_ptr(), layout);
            }
        }

        // Mark the wrapper as initialized
        inner_wrapper_frame.tracker = Tracker::Scalar;
        inner_wrapper_frame.is_init = true;
    }

    /// Complete a proxy conversion during deferred finalization.
    ///
    /// This handles proxy types (e.g., `#[facet(proxy = InnerProxy)]`) that were
    /// deferred during flatten deserialization. The proxy frame's children (e.g.,
    /// `Vec<f64>` fields) have already been materialized (ropes drained), so it's
    /// now safe to run the conversion.
    fn complete_proxy_frame(target_frame: &mut Frame, proxy_frame: Frame) {
        // Get the convert_in function from the proxy stored on the frame
        let Some(proxy_def) = proxy_frame.shape_level_proxy else {
            crate::trace!(
                "complete_proxy_frame: no shape_level_proxy on frame {}",
                proxy_frame.allocated.shape()
            );
            return;
        };
        let convert_in = proxy_def.convert_in;

        let _proxy_shape = proxy_frame.allocated.shape();
        let _target_shape = target_frame.allocated.shape();

        crate::trace!(
            "complete_proxy_frame: converting {} to {}",
            _proxy_shape,
            _target_shape
        );

        unsafe {
            let inner_value_ptr = proxy_frame.data.assume_init().as_const();
            let res = (convert_in)(inner_value_ptr, target_frame.data);

            match res {
                Ok(rptr) => {
                    if rptr.as_uninit() != target_frame.data {
                        crate::trace!(
                            "complete_proxy_frame: convert_in returned unexpected pointer"
                        );
                        return;
                    }
                }
                Err(_message) => {
                    crate::trace!("complete_proxy_frame: conversion failed: {}", _message);
                    return;
                }
            }
        }

        // Deallocate the proxy frame's memory (convert_in consumed it via ptr::read)
        if let FrameOwnership::Owned = proxy_frame.ownership
            && let Ok(layout) = proxy_frame.allocated.shape().layout.sized_layout()
            && layout.size() > 0
        {
            unsafe {
                ::alloc::alloc::dealloc(proxy_frame.data.as_mut_byte_ptr(), layout);
            }
        }

        // Mark the target as initialized
        target_frame.is_init = true;
    }

    /// Complete a List frame by pushing an element into it (for deferred finalization)
    fn complete_list_item_frame(list_frame: &mut Frame, element_frame: Frame) {
        if let Def::List(list_def) = list_frame.allocated.shape().def
            && let Some(push_fn) = list_def.push()
        {
            // The element frame contains the element value
            let element_ptr = PtrMut::new(element_frame.data.as_mut_byte_ptr());

            // Use push to add element to the list
            unsafe {
                push_fn(PtrMut::new(list_frame.data.as_mut_byte_ptr()), element_ptr);
            }

            crate::trace!(
                "complete_list_item_frame: pushed element into {}",
                list_frame.allocated.shape()
            );

            // Deallocate the element's memory since push moved it
            if let FrameOwnership::Owned = element_frame.ownership
                && let Ok(layout) = element_frame.allocated.shape().layout.sized_layout()
                && layout.size() > 0
            {
                unsafe {
                    ::alloc::alloc::dealloc(element_frame.data.as_mut_byte_ptr(), layout);
                }
            }
        }
    }

    /// Complete a SmartPointerSlice element frame by pushing the element into the slice builder
    /// (for deferred finalization)
    fn complete_smart_pointer_slice_item_frame(
        slice_frame: &mut Frame,
        element_frame: Frame,
    ) -> bool {
        if let Tracker::SmartPointerSlice { vtable, .. } = &slice_frame.tracker {
            let vtable = *vtable;
            // The slice frame's data pointer IS the builder pointer
            let builder_ptr = slice_frame.data;

            // Push the element into the builder
            unsafe {
                (vtable.push_fn)(
                    PtrMut::new(builder_ptr.as_mut_byte_ptr()),
                    PtrMut::new(element_frame.data.as_mut_byte_ptr()),
                );
            }

            crate::trace!(
                "complete_smart_pointer_slice_item_frame: pushed element into builder for {}",
                slice_frame.allocated.shape()
            );

            // Deallocate the element's memory since push moved it
            if let FrameOwnership::Owned = element_frame.ownership
                && let Ok(layout) = element_frame.allocated.shape().layout.sized_layout()
                && layout.size() > 0
            {
                unsafe {
                    ::alloc::alloc::dealloc(element_frame.data.as_mut_byte_ptr(), layout);
                }
            }
            return true;
        }
        false
    }

    /// Complete a Map key frame by transitioning the Map from PushingKey to PushingValue state
    /// (for deferred finalization)
    fn complete_map_key_frame(map_frame: &mut Frame, key_frame: Frame) {
        if let Tracker::Map { insert_state, .. } = &mut map_frame.tracker
            && let MapInsertState::PushingKey { key_ptr, .. } = insert_state
        {
            // Transition to PushingValue state, keeping the key pointer.
            // key_frame_stored = false because the key frame is being finalized here,
            // so after this the Map owns the key buffer.
            *insert_state = MapInsertState::PushingValue {
                key_ptr: *key_ptr,
                value_ptr: None,
                value_initialized: false,
                value_frame_on_stack: false,
                key_frame_stored: false,
            };

            crate::trace!(
                "complete_map_key_frame: transitioned {} to PushingValue",
                map_frame.allocated.shape()
            );

            // Deallocate the key frame's memory (the key data lives at key_ptr which Map owns)
            if let FrameOwnership::Owned = key_frame.ownership
                && let Ok(layout) = key_frame.allocated.shape().layout.sized_layout()
                && layout.size() > 0
            {
                unsafe {
                    ::alloc::alloc::dealloc(key_frame.data.as_mut_byte_ptr(), layout);
                }
            }
        }
    }

    /// Complete a Map value frame by adding the key-value pair to pending_entries
    /// (for deferred finalization)
    fn complete_map_value_frame(map_frame: &mut Frame, value_frame: Frame) {
        if let Tracker::Map {
            insert_state,
            pending_entries,
            ..
        } = &mut map_frame.tracker
            && let MapInsertState::PushingValue {
                key_ptr,
                value_ptr: Some(value_ptr),
                ..
            } = insert_state
        {
            // Add the key-value pair to pending_entries
            pending_entries.push((*key_ptr, *value_ptr));

            crate::trace!(
                "complete_map_value_frame: added entry to pending_entries for {}",
                map_frame.allocated.shape()
            );

            // Reset to idle state
            *insert_state = MapInsertState::Idle;

            // Deallocate the value frame's memory (the value data lives at value_ptr which Map owns)
            if let FrameOwnership::Owned = value_frame.ownership
                && let Ok(layout) = value_frame.allocated.shape().layout.sized_layout()
                && layout.size() > 0
            {
                unsafe {
                    ::alloc::alloc::dealloc(value_frame.data.as_mut_byte_ptr(), layout);
                }
            }
        }
    }

    /// Pops the current frame off the stack, indicating we're done initializing the current field
    pub fn end(mut self) -> Result<Self, ReflectError> {
        // FAST PATH: Handle the common case of ending a simple scalar field in a struct.
        // This avoids all the edge-case checks (SmartPointerSlice, deferred mode, custom
        // deserialization, etc.) that dominate the slow path.
        if self.frames().len() >= 2 && !self.is_deferred() {
            let frames = self.frames_mut();
            let top_idx = frames.len() - 1;
            let parent_idx = top_idx - 1;

            // Check if this is a simple scalar field being returned to a struct parent
            if let (
                Tracker::Scalar,
                true, // is_init
                FrameOwnership::Field { field_idx },
                false, // not using custom deserialization
            ) = (
                &frames[top_idx].tracker,
                frames[top_idx].is_init,
                frames[top_idx].ownership,
                frames[top_idx].using_custom_deserialization,
            ) && let Tracker::Struct {
                iset,
                current_child,
            } = &mut frames[parent_idx].tracker
            {
                // Fast path: just update parent's iset and pop
                iset.set(field_idx);
                *current_child = None;
                frames.pop();
                return Ok(self);
            }
        }

        // SLOW PATH: Handle all the edge cases

        // Strategic tracing: show the frame stack state
        #[cfg(feature = "tracing")]
        {
            use ::alloc::string::ToString;
            let frames = self.frames();
            let stack_desc: Vec<_> = frames
                .iter()
                .map(|f| ::alloc::format!("{}({:?})", f.allocated.shape(), f.tracker.kind()))
                .collect();
            let path = if self.is_deferred() {
                ::alloc::format!("{:?}", self.derive_path())
            } else {
                "N/A".to_string()
            };
            crate::trace!(
                "end() SLOW PATH: stack=[{}], deferred={}, path={}",
                stack_desc.join(" > "),
                self.is_deferred(),
                path
            );
        }

        // Special handling for SmartPointerSlice - convert builder to Arc
        // Check if the current (top) frame is a SmartPointerSlice that needs conversion
        let needs_slice_conversion = {
            let frames = self.frames();
            if frames.is_empty() {
                false
            } else {
                let top_idx = frames.len() - 1;
                matches!(
                    frames[top_idx].tracker,
                    Tracker::SmartPointerSlice {
                        building_item: false,
                        ..
                    }
                )
            }
        };

        if needs_slice_conversion {
            // In deferred mode, don't convert immediately - let finish_deferred handle it.
            // Set building_item = true and return early (matching non-deferred behavior).
            // The next end() call will store the frame.
            if self.is_deferred() {
                let frames = self.frames_mut();
                let top_idx = frames.len() - 1;
                if let Tracker::SmartPointerSlice { building_item, .. } =
                    &mut frames[top_idx].tracker
                {
                    *building_item = true;
                }
                return Ok(self);
            } else {
                // Get shape info upfront to avoid borrow conflicts
                let current_shape = self.frames().last().unwrap().allocated.shape();

                let frames = self.frames_mut();
                let top_idx = frames.len() - 1;

                if let Tracker::SmartPointerSlice { vtable, .. } = &frames[top_idx].tracker {
                    // Convert the builder to Arc<[T]>
                    let vtable = *vtable;
                    let builder_ptr = unsafe { frames[top_idx].data.assume_init() };
                    let arc_ptr = unsafe { (vtable.convert_fn)(builder_ptr) };

                    match frames[top_idx].ownership {
                        FrameOwnership::Field { field_idx } => {
                            // Arc<[T]> is a field in a struct
                            // The field frame's original data pointer was overwritten with the builder pointer,
                            // so we need to reconstruct where the Arc should be written.

                            // Get parent frame and field info
                            let parent_idx = top_idx - 1;
                            let parent_frame = &frames[parent_idx];

                            // Get the field to find its offset
                            let field = if let Type::User(UserType::Struct(struct_type)) =
                                parent_frame.allocated.shape().ty
                            {
                                &struct_type.fields[field_idx]
                            } else {
                                return Err(self.err(ReflectErrorKind::InvariantViolation {
                                invariant: "SmartPointerSlice field frame parent must be a struct",
                            }));
                            };

                            // Calculate where the Arc should be written (parent.data + field.offset)
                            let field_location =
                                unsafe { parent_frame.data.field_uninit(field.offset) };

                            // Write the Arc to the parent struct's field location
                            let arc_layout = match current_shape.layout.sized_layout() {
                                Ok(layout) => layout,
                                Err(_) => {
                                    return Err(self.err(ReflectErrorKind::Unsized {
                                    shape: current_shape,
                                    operation: "SmartPointerSlice conversion requires sized Arc",
                                }));
                                }
                            };
                            let arc_size = arc_layout.size();
                            unsafe {
                                core::ptr::copy_nonoverlapping(
                                    arc_ptr.as_byte_ptr(),
                                    field_location.as_mut_byte_ptr(),
                                    arc_size,
                                );
                            }

                            // Free the staging allocation from convert_fn (the Arc was copied to field_location)
                            unsafe {
                                ::alloc::alloc::dealloc(
                                    arc_ptr.as_byte_ptr() as *mut u8,
                                    arc_layout,
                                );
                            }

                            // Update the frame to point to the correct field location and mark as initialized
                            frames[top_idx].data = field_location;
                            frames[top_idx].tracker = Tracker::Scalar;
                            frames[top_idx].is_init = true;

                            // Return WITHOUT popping - the field frame will be popped by the next end() call
                            return Ok(self);
                        }
                        FrameOwnership::Owned => {
                            // Arc<[T]> is the root type or owned independently
                            // The frame already has the allocation, we just need to update it with the Arc

                            // The frame's data pointer is currently the builder, but we allocated
                            // the Arc memory in the convert_fn. Update to point to the Arc.
                            frames[top_idx].data = PtrUninit::new(arc_ptr.as_byte_ptr() as *mut u8);
                            frames[top_idx].tracker = Tracker::Scalar;
                            frames[top_idx].is_init = true;
                            // Keep Owned ownership so Guard will properly deallocate

                            // Return WITHOUT popping - the frame stays and will be built/dropped normally
                            return Ok(self);
                        }
                        FrameOwnership::TrackedBuffer
                        | FrameOwnership::BorrowedInPlace
                        | FrameOwnership::External
                        | FrameOwnership::RopeSlot => {
                            return Err(self.err(ReflectErrorKind::InvariantViolation {
                            invariant: "SmartPointerSlice cannot have TrackedBuffer/BorrowedInPlace/External/RopeSlot ownership after conversion",
                        }));
                        }
                    }
                }
            }
        }

        if self.frames().len() <= 1 {
            // Never pop the last/root frame - this indicates a broken state machine
            // No need to poison - returning Err consumes self, Drop will handle cleanup
            return Err(self.err(ReflectErrorKind::InvariantViolation {
                invariant: "Partial::end() called with only one frame on the stack",
            }));
        }

        // In deferred mode, cannot pop below the start depth
        if let Some(start_depth) = self.start_depth()
            && self.frames().len() <= start_depth
        {
            // No need to poison - returning Err consumes self, Drop will handle cleanup
            return Err(self.err(ReflectErrorKind::InvariantViolation {
                invariant: "Partial::end() called but would pop below deferred start depth",
            }));
        }

        // Require that the top frame is fully initialized before popping.
        // In deferred mode, tracked frames (those that will be stored for re-entry)
        // defer validation to finish_deferred(). All other frames validate now
        // using the TypePlan's FillRule (which knows what's Required vs Defaultable).
        let requires_full_init = if !self.is_deferred() {
            true
        } else {
            // If this frame will be stored, defer validation to finish_deferred().
            // Otherwise validate now.
            !self.should_store_frame_for_deferred()
        };

        if requires_full_init {
            // Try the optimized path using precomputed FieldInitPlan
            // Extract frame info first (borrows only self.mode)
            let frame_info = self.mode.stack().last().map(|frame| {
                let variant_idx = match &frame.tracker {
                    Tracker::Enum { variant_idx, .. } => Some(*variant_idx),
                    _ => None,
                };
                (frame.type_plan, variant_idx)
            });

            // Look up plans from the type plan node - need to resolve NodeId to get the actual node
            let plans_info = frame_info.and_then(|(type_plan_id, variant_idx)| {
                let type_plan = self.root_plan.node(type_plan_id);
                match &type_plan.kind {
                    TypePlanNodeKind::Struct(struct_plan) => Some(struct_plan.fields),
                    TypePlanNodeKind::Enum(enum_plan) => {
                        let variants = self.root_plan.variants(enum_plan.variants);
                        variant_idx.and_then(|idx| variants.get(idx).map(|v| v.fields))
                    }
                    _ => None,
                }
            });

            if let Some(plans_range) = plans_info {
                // Resolve the SliceRange to an actual slice
                let plans = self.root_plan.fields(plans_range);
                // Now mutably borrow mode.stack to get the frame
                // (root_plan borrow of `plans` is still active but that's fine -
                // mode and root_plan are separate fields)
                let frame = self.mode.stack_mut().last_mut().unwrap();
                frame
                    .fill_and_require_fields(plans, plans.len(), &self.root_plan)
                    .map_err(|e| self.err(e))?;
            } else {
                // Fall back to the old path if optimized path wasn't available
                if let Some(frame) = self.frames_mut().last_mut() {
                    frame.fill_defaults().map_err(|e| self.err(e))?;
                }

                let frame = self.frames_mut().last_mut().unwrap();
                let result = frame.require_full_initialization();
                if result.is_err() {
                    crate::trace!(
                        "end() VALIDATION FAILED: {} ({:?}) is_init={} - {:?}",
                        frame.allocated.shape(),
                        frame.tracker.kind(),
                        frame.is_init,
                        result
                    );
                }
                result.map_err(|e| self.err(e))?
            }
        }

        // In deferred mode, check if we should store this frame for potential re-entry.
        // We need to compute the storage path BEFORE popping so we can check it.
        //
        // Store frames that can be re-entered in deferred mode.
        // This includes structs, enums, collections, and Options (which need to be
        // stored so finish_deferred can find them when processing their inner values).
        let deferred_storage_info = if self.is_deferred() {
            let should_store = self.should_store_frame_for_deferred();

            if should_store {
                // Compute the "field-only" path for storage by finding all Field steps
                // from PARENT frames only. The frame being ended shouldn't contribute to
                // its own path (its current_child points to ITS children, not to itself).
                //
                // Note: We include ALL frames in the path computation (including those
                // before start_depth) because they contain navigation info. The start_depth
                // only determines which frames we STORE, not which frames contribute to paths.
                //
                // Get the root shape for the Path from the first frame
                let root_shape = self
                    .frames()
                    .first()
                    .map(|f| f.allocated.shape())
                    .unwrap_or_else(|| <() as facet_core::Facet>::SHAPE);

                let mut field_path = facet_path::Path::new(root_shape);
                let frames_len = self.frames().len();
                // Iterate over all frames EXCEPT the last one (the one being ended)
                for (frame_idx, frame) in self.frames().iter().enumerate() {
                    // Skip the frame being ended
                    if frame_idx == frames_len - 1 {
                        continue;
                    }
                    // Extract navigation steps from frames
                    // This MUST match derive_path() for consistency
                    match &frame.tracker {
                        Tracker::Struct {
                            current_child: Some(idx),
                            ..
                        } => {
                            field_path.push(PathStep::Field(*idx as u32));
                        }
                        Tracker::Enum {
                            current_child: Some(idx),
                            ..
                        } => {
                            field_path.push(PathStep::Field(*idx as u32));
                        }
                        Tracker::List {
                            current_child: Some(idx),
                            ..
                        } => {
                            field_path.push(PathStep::Index(*idx as u32));
                        }
                        Tracker::Array {
                            current_child: Some(idx),
                            ..
                        } => {
                            field_path.push(PathStep::Index(*idx as u32));
                        }
                        Tracker::Option {
                            building_inner: true,
                            ..
                        } => {
                            // Option with building_inner contributes OptionSome to path
                            field_path.push(PathStep::OptionSome);
                        }
                        Tracker::SmartPointer {
                            building_inner: true,
                            ..
                        } => {
                            // SmartPointer with building_inner contributes Deref to path
                            field_path.push(PathStep::Deref);
                        }
                        Tracker::SmartPointerSlice {
                            current_child: Some(idx),
                            ..
                        } => {
                            // SmartPointerSlice with current_child contributes Index to path
                            field_path.push(PathStep::Index(*idx as u32));
                        }
                        Tracker::Inner {
                            building_inner: true,
                        } => {
                            // Inner with building_inner contributes Inner to path
                            field_path.push(PathStep::Inner);
                        }
                        Tracker::Map {
                            current_entry_index: Some(idx),
                            building_key,
                            ..
                        } => {
                            // Map with active entry contributes MapKey or MapValue with entry index
                            if *building_key {
                                field_path.push(PathStep::MapKey(*idx as u32));
                            } else {
                                field_path.push(PathStep::MapValue(*idx as u32));
                            }
                        }
                        _ => {}
                    }

                    // If the next frame on the stack is a proxy frame, add a Proxy
                    // path step. This distinguishes the proxy frame (and its children)
                    // from the parent frame that the proxy writes into, preventing path
                    // collisions in deferred mode where both frames are stored.
                    if frame_idx + 1 < frames_len
                        && self.frames()[frame_idx + 1].using_custom_deserialization
                    {
                        field_path.push(PathStep::Proxy);
                    }
                }

                if !field_path.is_empty() {
                    Some(field_path)
                } else {
                    None
                }
            } else {
                None
            }
        } else {
            None
        };

        // Pop the frame and save its data pointer for SmartPointer handling
        let mut popped_frame = self.frames_mut().pop().unwrap();

        // In non-deferred mode, proxy frames are processed immediately.
        // In deferred mode, proxy frames are stored (with a PathStep::Proxy
        // distinguishing them from their parent) and the conversion is handled
        // by finish_deferred after children have been fully materialized.
        if popped_frame.using_custom_deserialization && deferred_storage_info.is_none() {
            // First check the proxy stored in the frame (used for format-specific proxies
            // and container-level proxies), then fall back to field-level proxy.
            // This ordering is important because format-specific proxies store their
            // proxy in shape_level_proxy, and we want them to take precedence over
            // the format-agnostic field.proxy().
            let deserialize_with: Option<facet_core::ProxyConvertInFn> =
                popped_frame.shape_level_proxy.map(|p| p.convert_in);

            // Fall back to field-level proxy (format-agnostic)
            let deserialize_with = deserialize_with.or_else(|| {
                self.parent_field()
                    .and_then(|f| f.proxy().map(|p| p.convert_in))
            });

            if let Some(deserialize_with) = deserialize_with {
                // Get parent shape upfront to avoid borrow conflicts
                let parent_shape = self.frames().last().unwrap().allocated.shape();
                let parent_frame = self.frames_mut().last_mut().unwrap();

                trace!(
                    "Detected custom conversion needed from {} to {}",
                    popped_frame.allocated.shape(),
                    parent_shape
                );

                unsafe {
                    let res = {
                        let inner_value_ptr = popped_frame.data.assume_init().as_const();
                        (deserialize_with)(inner_value_ptr, parent_frame.data)
                    };
                    let popped_frame_shape = popped_frame.allocated.shape();

                    // Note: We do NOT call deinit() here because deserialize_with uses
                    // ptr::read to take ownership of the source value. Calling deinit()
                    // would cause a double-free. We mark is_init as false to satisfy
                    // dealloc()'s assertion, then deallocate the memory.
                    popped_frame.is_init = false;
                    popped_frame.dealloc();
                    let parent_data = parent_frame.data;
                    match res {
                        Ok(rptr) => {
                            if rptr.as_uninit() != parent_data {
                                return Err(self.err(
                                    ReflectErrorKind::CustomDeserializationError {
                                        message:
                                            "deserialize_with did not return the expected pointer"
                                                .into(),
                                        src_shape: popped_frame_shape,
                                        dst_shape: parent_shape,
                                    },
                                ));
                            }
                        }
                        Err(message) => {
                            return Err(self.err(ReflectErrorKind::CustomDeserializationError {
                                message,
                                src_shape: popped_frame_shape,
                                dst_shape: parent_shape,
                            }));
                        }
                    }
                    // Re-borrow parent_frame after potential early returns
                    let parent_frame = self.frames_mut().last_mut().unwrap();
                    parent_frame.mark_as_init();
                }
                return Ok(self);
            }
        }

        // If we determined this frame should be stored for deferred re-entry, do it now
        if let Some(storage_path) = deferred_storage_info {
            trace!(
                "end(): Storing frame for deferred path {:?}, shape {}",
                storage_path,
                popped_frame.allocated.shape()
            );

            if let FrameMode::Deferred {
                stack,
                stored_frames,
                ..
            } = &mut self.mode
            {
                // Mark the field as initialized in the parent frame.
                // This is important because the parent might validate before
                // finish_deferred runs (e.g., parent is an array element that
                // isn't stored). Without this, the parent's validation would
                // fail with "missing field".
                if let FrameOwnership::Field { field_idx } = popped_frame.ownership
                    && let Some(parent_frame) = stack.last_mut()
                {
                    Self::mark_field_initialized_by_index(parent_frame, field_idx);
                }

                // For BorrowedInPlace DynamicValue frames (e.g., re-entered pending entries),
                // flush pending_elements/pending_entries and return without storing.
                // These frames point to memory that's already tracked in the parent's
                // pending_entries - storing them would overwrite the entry.
                if matches!(popped_frame.ownership, FrameOwnership::BorrowedInPlace) {
                    crate::trace!(
                        "end(): BorrowedInPlace frame, flushing pending items and returning"
                    );
                    if let Err(kind) = popped_frame.require_full_initialization() {
                        return Err(ReflectError::new(kind, storage_path));
                    }
                    return Ok(self);
                }

                // Handle Map state transitions even when storing frames.
                // The Map needs to transition states so that subsequent operations work:
                // - PushingKey -> PushingValue: so begin_value() can be called
                // - PushingValue -> Idle: so begin_key() can be called for the next entry
                // The frames are still stored for potential re-entry and finalization.
                if let Some(parent_frame) = stack.last_mut() {
                    if let Tracker::Map {
                        insert_state,
                        pending_entries,
                        ..
                    } = &mut parent_frame.tracker
                    {
                        match insert_state {
                            MapInsertState::PushingKey { key_ptr, .. } => {
                                // Transition to PushingValue state.
                                // key_frame_stored = true because the key frame is being stored,
                                // so the stored frame will handle cleanup (not the Map's deinit).
                                *insert_state = MapInsertState::PushingValue {
                                    key_ptr: *key_ptr,
                                    value_ptr: None,
                                    value_initialized: false,
                                    value_frame_on_stack: false,
                                    key_frame_stored: true,
                                };
                                crate::trace!(
                                    "end(): Map transitioned to PushingValue while storing key frame"
                                );
                            }
                            MapInsertState::PushingValue {
                                key_ptr,
                                value_ptr: Some(value_ptr),
                                ..
                            } => {
                                // Add entry to pending_entries and reset to Idle
                                pending_entries.push((*key_ptr, *value_ptr));
                                *insert_state = MapInsertState::Idle;
                                crate::trace!(
                                    "end(): Map added entry to pending_entries while storing value frame"
                                );
                            }
                            _ => {}
                        }
                    }

                    // Handle Set element insertion immediately.
                    // Set elements have no path identity (no index), so they can't be stored
                    // and re-entered. We must insert them into the Set now.
                    if let Tracker::Set { current_child } = &mut parent_frame.tracker
                        && *current_child
                        && parent_frame.is_init
                        && let Def::Set(set_def) = parent_frame.allocated.shape().def
                    {
                        let insert = set_def.vtable.insert;
                        let element_ptr = PtrMut::new(popped_frame.data.as_mut_byte_ptr());
                        unsafe {
                            insert(
                                PtrMut::new(parent_frame.data.as_mut_byte_ptr()),
                                element_ptr,
                            );
                        }
                        crate::trace!("end(): Set element inserted immediately in deferred mode");
                        // Insert moved out of popped_frame - don't store it
                        popped_frame.tracker = Tracker::Scalar;
                        popped_frame.is_init = false;
                        popped_frame.dealloc();
                        *current_child = false;
                        // Don't store this frame - return early
                        return Ok(self);
                    }

                    // Handle DynamicValue object entry - add to pending_entries for deferred insertion.
                    // Like Map entries, we store the key-value pair and insert during finalization.
                    if let Tracker::DynamicValue {
                        state:
                            DynamicValueState::Object {
                                insert_state,
                                pending_entries,
                            },
                    } = &mut parent_frame.tracker
                        && let DynamicObjectInsertState::BuildingValue { key } = insert_state
                    {
                        // Take ownership of the key from insert_state
                        let key = core::mem::take(key);

                        // Finalize the child Value before adding to pending_entries.
                        // The child might have its own pending_entries/pending_elements
                        // that need to be inserted first.
                        if let Err(kind) = popped_frame.require_full_initialization() {
                            return Err(ReflectError::new(kind, storage_path.clone()));
                        }

                        // Add to pending_entries for deferred insertion
                        pending_entries.push((key, popped_frame.data));
                        crate::trace!(
                            "end(): DynamicValue object entry added to pending_entries in deferred mode"
                        );

                        // The value frame's data is now owned by pending_entries
                        // Mark frame as not owning the data so it won't be deallocated
                        popped_frame.tracker = Tracker::Scalar;
                        popped_frame.is_init = false;
                        // Don't dealloc - pending_entries owns the pointer now

                        // Reset insert state to Idle so more entries can be added
                        *insert_state = DynamicObjectInsertState::Idle;

                        // Don't store this frame - return early
                        return Ok(self);
                    }

                    // Handle DynamicValue array element - add to pending_elements for deferred insertion.
                    if let Tracker::DynamicValue {
                        state:
                            DynamicValueState::Array {
                                building_element,
                                pending_elements,
                            },
                    } = &mut parent_frame.tracker
                        && *building_element
                    {
                        // Finalize the child Value before adding to pending_elements.
                        // The child might have its own pending_entries/pending_elements
                        // that need to be inserted first.
                        if let Err(kind) = popped_frame.require_full_initialization() {
                            return Err(ReflectError::new(kind, storage_path.clone()));
                        }

                        // Add to pending_elements for deferred insertion
                        pending_elements.push(popped_frame.data);
                        crate::trace!(
                            "end(): DynamicValue array element added to pending_elements in deferred mode"
                        );

                        // The element frame's data is now owned by pending_elements
                        // Mark frame as not owning the data so it won't be deallocated
                        popped_frame.tracker = Tracker::Scalar;
                        popped_frame.is_init = false;
                        // Don't dealloc - pending_elements owns the pointer now

                        // Reset building_element so more elements can be added
                        *building_element = false;

                        // Don't store this frame - return early
                        return Ok(self);
                    }

                    // For List elements stored in a rope (RopeSlot ownership), we need to
                    // mark the element as initialized in the rope. When the List frame is
                    // deinited, the rope will drop all initialized elements.
                    if matches!(popped_frame.ownership, FrameOwnership::RopeSlot)
                        && let Tracker::List {
                            rope: Some(rope), ..
                        } = &mut parent_frame.tracker
                    {
                        rope.mark_last_initialized();
                    }

                    // Clear building_item for SmartPointerSlice so the next element can be added
                    if let Tracker::SmartPointerSlice { building_item, .. } =
                        &mut parent_frame.tracker
                    {
                        *building_item = false;
                        crate::trace!(
                            "end(): SmartPointerSlice building_item cleared while storing element"
                        );
                    }
                }

                stored_frames.insert(storage_path, popped_frame);

                // Clear parent's current_child tracking
                if let Some(parent_frame) = stack.last_mut() {
                    parent_frame.tracker.clear_current_child();
                }
            }

            return Ok(self);
        }

        // Update parent frame's tracking when popping from a child
        // Get parent shape upfront to avoid borrow conflicts
        let parent_shape = self.frames().last().unwrap().allocated.shape();
        let is_deferred_mode = self.is_deferred();
        let parent_frame = self.frames_mut().last_mut().unwrap();

        crate::trace!(
            "end(): Popped {} (tracker {:?}), Parent {} (tracker {:?})",
            popped_frame.allocated.shape(),
            popped_frame.tracker.kind(),
            parent_shape,
            parent_frame.tracker.kind()
        );

        // Check if we need to do a conversion - this happens when:
        // 1. The parent frame has a builder_shape or inner type that matches the popped frame's shape
        // 2. The parent frame has try_from
        // 3. The parent frame is not yet initialized
        // 4. The parent frame's tracker is Scalar or Inner (not Option, SmartPointer, etc.)
        //    This ensures we only do conversion when begin_inner was used, not begin_some
        let needs_conversion = !parent_frame.is_init
            && matches!(
                parent_frame.tracker,
                Tracker::Scalar | Tracker::Inner { .. }
            )
            && ((parent_shape.builder_shape.is_some()
                && parent_shape.builder_shape.unwrap() == popped_frame.allocated.shape())
                || (parent_shape.inner.is_some()
                    && parent_shape.inner.unwrap() == popped_frame.allocated.shape()))
            && match parent_shape.vtable {
                facet_core::VTableErased::Direct(vt) => vt.try_from.is_some(),
                facet_core::VTableErased::Indirect(vt) => vt.try_from.is_some(),
            };

        if needs_conversion {
            trace!(
                "Detected implicit conversion needed from {} to {}",
                popped_frame.allocated.shape(),
                parent_shape
            );

            // The conversion requires the source frame to be fully initialized
            // (we're about to call assume_init() and pass to try_from)
            if let Err(e) = popped_frame.require_full_initialization() {
                // Deallocate the memory since the frame wasn't fully initialized
                if let FrameOwnership::Owned = popped_frame.ownership
                    && let Ok(layout) = popped_frame.allocated.shape().layout.sized_layout()
                    && layout.size() > 0
                {
                    trace!(
                        "Deallocating uninitialized conversion frame memory: size={}, align={}",
                        layout.size(),
                        layout.align()
                    );
                    unsafe {
                        ::alloc::alloc::dealloc(popped_frame.data.as_mut_byte_ptr(), layout);
                    }
                }
                return Err(self.err(e));
            }

            // Perform the conversion
            let inner_ptr = unsafe { popped_frame.data.assume_init().as_const() };
            let inner_shape = popped_frame.allocated.shape();

            trace!("Converting from {} to {}", inner_shape, parent_shape);

            // Handle Direct and Indirect vtables - both return TryFromOutcome
            let outcome = match parent_shape.vtable {
                facet_core::VTableErased::Direct(vt) => {
                    if let Some(try_from_fn) = vt.try_from {
                        unsafe {
                            try_from_fn(
                                parent_frame.data.as_mut_byte_ptr() as *mut (),
                                inner_shape,
                                inner_ptr,
                            )
                        }
                    } else {
                        return Err(self.err(ReflectErrorKind::OperationFailed {
                            shape: parent_shape,
                            operation: "try_from not available for this type",
                        }));
                    }
                }
                facet_core::VTableErased::Indirect(vt) => {
                    if let Some(try_from_fn) = vt.try_from {
                        // parent_frame.data is uninitialized - we're writing the converted
                        // value into it
                        let ox_uninit =
                            facet_core::OxPtrUninit::new(parent_frame.data, parent_shape);
                        unsafe { try_from_fn(ox_uninit, inner_shape, inner_ptr) }
                    } else {
                        return Err(self.err(ReflectErrorKind::OperationFailed {
                            shape: parent_shape,
                            operation: "try_from not available for this type",
                        }));
                    }
                }
            };

            // Handle the TryFromOutcome, which explicitly communicates ownership semantics:
            // - Converted: source was consumed, conversion succeeded
            // - Unsupported: source was NOT consumed, caller retains ownership
            // - Failed: source WAS consumed, but conversion failed
            match outcome {
                facet_core::TryFromOutcome::Converted => {
                    trace!("Conversion succeeded, marking parent as initialized");
                    parent_frame.is_init = true;
                    // Reset Inner tracker to Scalar after successful conversion
                    if matches!(parent_frame.tracker, Tracker::Inner { .. }) {
                        parent_frame.tracker = Tracker::Scalar;
                    }
                }
                facet_core::TryFromOutcome::Unsupported => {
                    trace!("Source type not supported for conversion - source NOT consumed");

                    // Source was NOT consumed, so we need to drop it properly
                    if let FrameOwnership::Owned = popped_frame.ownership
                        && let Ok(layout) = popped_frame.allocated.shape().layout.sized_layout()
                        && layout.size() > 0
                    {
                        // Drop the value, then deallocate
                        unsafe {
                            popped_frame
                                .allocated
                                .shape()
                                .call_drop_in_place(popped_frame.data.assume_init());
                            ::alloc::alloc::dealloc(popped_frame.data.as_mut_byte_ptr(), layout);
                        }
                    }

                    return Err(self.err(ReflectErrorKind::TryFromError {
                        src_shape: inner_shape,
                        dst_shape: parent_shape,
                        inner: facet_core::TryFromError::UnsupportedSourceType,
                    }));
                }
                facet_core::TryFromOutcome::Failed(e) => {
                    trace!("Conversion failed after consuming source: {e:?}");

                    // Source WAS consumed, so we only deallocate memory (don't drop)
                    if let FrameOwnership::Owned = popped_frame.ownership
                        && let Ok(layout) = popped_frame.allocated.shape().layout.sized_layout()
                        && layout.size() > 0
                    {
                        trace!(
                            "Deallocating conversion frame memory after failure: size={}, align={}",
                            layout.size(),
                            layout.align()
                        );
                        unsafe {
                            ::alloc::alloc::dealloc(popped_frame.data.as_mut_byte_ptr(), layout);
                        }
                    }

                    return Err(self.err(ReflectErrorKind::TryFromError {
                        src_shape: inner_shape,
                        dst_shape: parent_shape,
                        inner: facet_core::TryFromError::Generic(e.into_owned()),
                    }));
                }
            }

            // Deallocate the inner value's memory since try_from consumed it
            if let FrameOwnership::Owned = popped_frame.ownership
                && let Ok(layout) = popped_frame.allocated.shape().layout.sized_layout()
                && layout.size() > 0
            {
                trace!(
                    "Deallocating conversion frame memory: size={}, align={}",
                    layout.size(),
                    layout.align()
                );
                unsafe {
                    ::alloc::alloc::dealloc(popped_frame.data.as_mut_byte_ptr(), layout);
                }
            }

            return Ok(self);
        }

        // For Field-owned frames, reclaim responsibility in parent's tracker
        // Only mark as initialized if the child frame was actually initialized.
        // This prevents double-free when begin_inner/begin_some drops a value via
        // prepare_for_reinitialization but then fails, leaving the child uninitialized.
        //
        // We use require_full_initialization() rather than just is_init because:
        // - Scalar frames use is_init as the source of truth
        // - Struct/Array/Enum frames use their iset/data as the source of truth
        //   (is_init may never be set to true for these tracker types)
        if let FrameOwnership::Field { field_idx } = popped_frame.ownership {
            // In deferred mode, fill defaults on the child frame before checking initialization.
            // Fill defaults for child frame before checking if it's fully initialized.
            // This handles structs/enums with optional fields that should auto-fill.
            if let Err(e) = popped_frame.fill_defaults() {
                return Err(self.err(e));
            }
            let child_is_initialized = popped_frame.require_full_initialization().is_ok();
            match &mut parent_frame.tracker {
                Tracker::Struct {
                    iset,
                    current_child,
                } => {
                    if child_is_initialized {
                        iset.set(field_idx); // Parent reclaims responsibility only if child was init
                    }
                    *current_child = None;
                }
                Tracker::Array {
                    iset,
                    current_child,
                } => {
                    if child_is_initialized {
                        iset.set(field_idx); // Parent reclaims responsibility only if child was init
                    }
                    *current_child = None;
                }
                Tracker::Enum {
                    data,
                    current_child,
                    ..
                } => {
                    crate::trace!(
                        "end(): Enum field {} child_is_initialized={}, data before={:?}",
                        field_idx,
                        child_is_initialized,
                        data
                    );
                    if child_is_initialized {
                        data.set(field_idx); // Parent reclaims responsibility only if child was init
                    }
                    *current_child = None;
                }
                _ => {}
            }
            return Ok(self);
        }

        // For BorrowedInPlace DynamicValue frames (e.g., re-entered pending entries),
        // flush any pending_elements/pending_entries that were accumulated during
        // this re-entry. This is necessary because BorrowedInPlace frames aren't
        // stored for deferred processing - they modify existing memory in-place.
        if matches!(popped_frame.ownership, FrameOwnership::BorrowedInPlace)
            && let Err(e) = popped_frame.require_full_initialization()
        {
            return Err(self.err(e));
        }

        match &mut parent_frame.tracker {
            Tracker::SmartPointer {
                building_inner,
                pending_inner,
            } => {
                crate::trace!(
                    "end() SMARTPTR: popped {} into parent {} (building_inner={}, deferred={})",
                    popped_frame.allocated.shape(),
                    parent_frame.allocated.shape(),
                    *building_inner,
                    is_deferred_mode
                );
                // We just popped the inner value frame for a SmartPointer
                if *building_inner {
                    if matches!(parent_frame.allocated.shape().def, Def::Pointer(_)) {
                        // Check if we're in deferred mode - if so, store the inner value pointer
                        if is_deferred_mode {
                            // Store the inner value pointer for deferred new_into_fn.
                            *pending_inner = Some(popped_frame.data);
                            *building_inner = false;
                            parent_frame.is_init = true;
                            crate::trace!(
                                "end() SMARTPTR: stored pending_inner, will finalize in finish_deferred"
                            );
                        } else {
                            // Not in deferred mode - complete immediately
                            if let Def::Pointer(_) = parent_frame.allocated.shape().def {
                                if let Err(e) = popped_frame.require_full_initialization() {
                                    popped_frame.deinit();
                                    popped_frame.dealloc();
                                    return Err(self.err(e));
                                }

                                // Use complete_smart_pointer_frame which handles both:
                                // - Sized pointees (via new_into_fn)
                                // - Unsized pointees like str (via String conversion)
                                Self::complete_smart_pointer_frame(parent_frame, popped_frame);
                                crate::trace!(
                                    "end() SMARTPTR: completed smart pointer via complete_smart_pointer_frame"
                                );

                                // Change tracker to Scalar so the next end() just pops it
                                parent_frame.tracker = Tracker::Scalar;
                            }
                        }
                    } else {
                        return Err(self.err(ReflectErrorKind::OperationFailed {
                            shape: parent_shape,
                            operation: "SmartPointer frame without SmartPointer definition",
                        }));
                    }
                } else {
                    // building_inner is false - shouldn't happen in normal flow
                    return Err(self.err(ReflectErrorKind::OperationFailed {
                        shape: parent_shape,
                        operation: "SmartPointer end() called with building_inner = false",
                    }));
                }
            }
            Tracker::List {
                current_child,
                rope,
                ..
            } if parent_frame.is_init => {
                if current_child.is_some() {
                    // We just popped an element frame, now add it to the list
                    if let Def::List(list_def) = parent_shape.def {
                        // Check which storage mode we used
                        if matches!(popped_frame.ownership, FrameOwnership::RopeSlot) {
                            // Rope storage: element lives in a stable chunk.
                            // Mark it as initialized; we'll drain to Vec when the list frame pops.
                            if let Some(rope) = rope {
                                rope.mark_last_initialized();
                            }
                            // No dealloc needed - memory belongs to rope
                        } else {
                            // Fallback: element is in separate heap buffer, use push to copy
                            let Some(push_fn) = list_def.push() else {
                                return Err(self.err(ReflectErrorKind::OperationFailed {
                                    shape: parent_shape,
                                    operation: "List missing push function",
                                }));
                            };

                            // The child frame contained the element value
                            let element_ptr = PtrMut::new(popped_frame.data.as_mut_byte_ptr());

                            // Use push to add element to the list
                            unsafe {
                                push_fn(
                                    PtrMut::new(parent_frame.data.as_mut_byte_ptr()),
                                    element_ptr,
                                );
                            }

                            // Push moved out of popped_frame
                            popped_frame.tracker = Tracker::Scalar;
                            popped_frame.is_init = false;
                            popped_frame.dealloc();
                        }

                        *current_child = None;
                    }
                }
            }
            Tracker::Map {
                insert_state,
                pending_entries,
                ..
            } if parent_frame.is_init => {
                match insert_state {
                    MapInsertState::PushingKey { key_ptr, .. } => {
                        // Fill defaults on the key frame before considering it done.
                        // This handles metadata containers and other structs with Option fields.
                        if let Err(e) = popped_frame.fill_defaults() {
                            return Err(self.err(e));
                        }

                        // We just popped the key frame - mark key as initialized and transition
                        // to PushingValue state. key_frame_on_stack = false because the frame
                        // was just popped, so Map now owns the key buffer.
                        *insert_state = MapInsertState::PushingValue {
                            key_ptr: *key_ptr,
                            value_ptr: None,
                            value_initialized: false,
                            value_frame_on_stack: false, // No value frame yet
                            key_frame_stored: false,     // Key frame was popped, Map owns key
                        };
                    }
                    MapInsertState::PushingValue {
                        key_ptr, value_ptr, ..
                    } => {
                        // Fill defaults on the value frame before considering it done.
                        // This handles structs with Option fields.
                        if let Err(e) = popped_frame.fill_defaults() {
                            return Err(self.err(e));
                        }

                        // We just popped the value frame.
                        // Instead of inserting immediately, add to pending_entries.
                        // This keeps the buffers alive for deferred processing.
                        // Actual insertion happens in require_full_initialization.
                        if let Some(value_ptr) = value_ptr {
                            pending_entries.push((*key_ptr, *value_ptr));

                            // Reset to idle state
                            *insert_state = MapInsertState::Idle;
                        }
                    }
                    MapInsertState::Idle => {
                        // Nothing to do
                    }
                }
            }
            Tracker::Set { current_child } if parent_frame.is_init => {
                if *current_child {
                    // We just popped an element frame, now insert it into the set
                    if let Def::Set(set_def) = parent_frame.allocated.shape().def {
                        let insert = set_def.vtable.insert;

                        // The child frame contained the element value
                        let element_ptr = PtrMut::new(popped_frame.data.as_mut_byte_ptr());

                        // Use insert to add element to the set
                        unsafe {
                            insert(
                                PtrMut::new(parent_frame.data.as_mut_byte_ptr()),
                                element_ptr,
                            );
                        }

                        // Insert moved out of popped_frame
                        popped_frame.tracker = Tracker::Scalar;
                        popped_frame.is_init = false;
                        popped_frame.dealloc();

                        *current_child = false;
                    }
                }
            }
            Tracker::Option {
                building_inner,
                pending_inner,
            } => {
                crate::trace!(
                    "end(): matched Tracker::Option, building_inner={}",
                    *building_inner
                );
                // We just popped the inner value frame for an Option's Some variant
                if *building_inner {
                    if matches!(parent_frame.allocated.shape().def, Def::Option(_)) {
                        // Store the inner value pointer for deferred init_some.
                        // This keeps the inner value's memory stable for deferred processing.
                        // Actual init_some() happens in require_full_initialization().
                        *pending_inner = Some(popped_frame.data);

                        // Mark that we're no longer building the inner value
                        *building_inner = false;
                        crate::trace!("end(): stored pending_inner, set building_inner to false");
                        // Mark the Option as initialized (pending finalization)
                        parent_frame.is_init = true;
                        crate::trace!("end(): set parent_frame.is_init to true");
                    } else {
                        return Err(self.err(ReflectErrorKind::OperationFailed {
                            shape: parent_shape,
                            operation: "Option frame without Option definition",
                        }));
                    }
                } else {
                    // building_inner is false - the Option was already initialized but
                    // begin_some was called again. The popped frame was not used to
                    // initialize the Option, so we need to clean it up.
                    popped_frame.deinit();
                    if let FrameOwnership::Owned = popped_frame.ownership
                        && let Ok(layout) = popped_frame.allocated.shape().layout.sized_layout()
                        && layout.size() > 0
                    {
                        unsafe {
                            ::alloc::alloc::dealloc(popped_frame.data.as_mut_byte_ptr(), layout);
                        }
                    }
                }
            }
            Tracker::Result {
                is_ok,
                building_inner,
            } => {
                crate::trace!(
                    "end(): matched Tracker::Result, is_ok={}, building_inner={}",
                    *is_ok,
                    *building_inner
                );
                // We just popped the inner value frame for a Result's Ok or Err variant
                if *building_inner {
                    if let Def::Result(result_def) = parent_frame.allocated.shape().def {
                        // The popped frame contains the inner value
                        let inner_value_ptr = unsafe { popped_frame.data.assume_init() };

                        // Initialize the Result as Ok(inner_value) or Err(inner_value)
                        if *is_ok {
                            let init_ok_fn = result_def.vtable.init_ok;
                            unsafe {
                                init_ok_fn(parent_frame.data, inner_value_ptr);
                            }
                        } else {
                            let init_err_fn = result_def.vtable.init_err;
                            unsafe {
                                init_err_fn(parent_frame.data, inner_value_ptr);
                            }
                        }

                        // Deallocate the inner value's memory since init_ok/err_fn moved it
                        if let FrameOwnership::Owned = popped_frame.ownership
                            && let Ok(layout) = popped_frame.allocated.shape().layout.sized_layout()
                            && layout.size() > 0
                        {
                            unsafe {
                                ::alloc::alloc::dealloc(
                                    popped_frame.data.as_mut_byte_ptr(),
                                    layout,
                                );
                            }
                        }

                        // Mark that we're no longer building the inner value
                        *building_inner = false;
                        crate::trace!("end(): set building_inner to false");
                        // Mark the Result as initialized
                        parent_frame.is_init = true;
                        crate::trace!("end(): set parent_frame.is_init to true");
                    } else {
                        return Err(self.err(ReflectErrorKind::OperationFailed {
                            shape: parent_shape,
                            operation: "Result frame without Result definition",
                        }));
                    }
                } else {
                    // building_inner is false - the Result was already initialized but
                    // begin_ok/begin_err was called again. The popped frame was not used to
                    // initialize the Result, so we need to clean it up.
                    popped_frame.deinit();
                    if let FrameOwnership::Owned = popped_frame.ownership
                        && let Ok(layout) = popped_frame.allocated.shape().layout.sized_layout()
                        && layout.size() > 0
                    {
                        unsafe {
                            ::alloc::alloc::dealloc(popped_frame.data.as_mut_byte_ptr(), layout);
                        }
                    }
                }
            }
            Tracker::Scalar => {
                // the main case here is: the popped frame was a `String` and the
                // parent frame is an `Arc<str>`, `Box<str>` etc.
                match &parent_shape.def {
                    Def::Pointer(smart_ptr_def) => {
                        let pointee = match smart_ptr_def.pointee() {
                            Some(p) => p,
                            None => {
                                return Err(self.err(ReflectErrorKind::InvariantViolation {
                                    invariant: "pointer type doesn't have a pointee",
                                }));
                            }
                        };

                        if !pointee.is_shape(str::SHAPE) {
                            return Err(self.err(ReflectErrorKind::InvariantViolation {
                                invariant: "only T=str is supported when building SmartPointer<T> and T is unsized",
                            }));
                        }

                        if !popped_frame.allocated.shape().is_shape(String::SHAPE) {
                            return Err(self.err(ReflectErrorKind::InvariantViolation {
                                invariant: "the popped frame should be String when building a SmartPointer<T>",
                            }));
                        }

                        if let Err(e) = popped_frame.require_full_initialization() {
                            return Err(self.err(e));
                        }

                        // if the just-popped frame was a SmartPointerStr, we have some conversion to do:
                        // Special-case: SmartPointer<str> (Box<str>, Arc<str>, Rc<str>) via SmartPointerStr tracker
                        // Here, popped_frame actually contains a value for String that should be moved into the smart pointer.
                        // We convert the String into Box<str>, Arc<str>, or Rc<str> as appropriate and write it to the parent frame.
                        use ::alloc::{rc::Rc, string::String, sync::Arc};

                        let Some(known) = smart_ptr_def.known else {
                            return Err(self.err(ReflectErrorKind::OperationFailed {
                                shape: parent_shape,
                                operation: "SmartPointerStr for unknown smart pointer kind",
                            }));
                        };

                        parent_frame.deinit();

                        // Interpret the memory as a String, then convert and write.
                        let string_ptr = popped_frame.data.as_mut_byte_ptr() as *mut String;
                        let string_value = unsafe { core::ptr::read(string_ptr) };

                        match known {
                            KnownPointer::Box => {
                                let boxed: Box<str> = string_value.into_boxed_str();
                                unsafe {
                                    core::ptr::write(
                                        parent_frame.data.as_mut_byte_ptr() as *mut Box<str>,
                                        boxed,
                                    );
                                }
                            }
                            KnownPointer::Arc => {
                                let arc: Arc<str> = Arc::from(string_value.into_boxed_str());
                                unsafe {
                                    core::ptr::write(
                                        parent_frame.data.as_mut_byte_ptr() as *mut Arc<str>,
                                        arc,
                                    );
                                }
                            }
                            KnownPointer::Rc => {
                                let rc: Rc<str> = Rc::from(string_value.into_boxed_str());
                                unsafe {
                                    core::ptr::write(
                                        parent_frame.data.as_mut_byte_ptr() as *mut Rc<str>,
                                        rc,
                                    );
                                }
                            }
                            _ => {
                                return Err(self.err(ReflectErrorKind::OperationFailed {
                                    shape: parent_shape,
                                    operation: "Don't know how to build this pointer type",
                                }));
                            }
                        }

                        parent_frame.is_init = true;

                        popped_frame.tracker = Tracker::Scalar;
                        popped_frame.is_init = false;
                        popped_frame.dealloc();
                    }
                    _ => {
                        // This can happen if begin_inner() was called on a type that
                        // has shape.inner but isn't a SmartPointer (e.g., Option).
                        // In this case, we can't complete the conversion, so return error.
                        return Err(self.err(ReflectErrorKind::OperationFailed {
                            shape: parent_shape,
                            operation: "end() called but parent has Uninit/Init tracker and isn't a SmartPointer",
                        }));
                    }
                }
            }
            Tracker::SmartPointerSlice {
                vtable,
                building_item,
                ..
            } => {
                if *building_item {
                    // We just popped an element frame, now push it to the slice builder
                    let element_ptr = PtrMut::new(popped_frame.data.as_mut_byte_ptr());

                    // Use the slice builder's push_fn to add the element
                    crate::trace!("Pushing element to slice builder");
                    unsafe {
                        let parent_ptr = parent_frame.data.assume_init();
                        (vtable.push_fn)(parent_ptr, element_ptr);
                    }

                    popped_frame.tracker = Tracker::Scalar;
                    popped_frame.is_init = false;
                    popped_frame.dealloc();

                    if let Tracker::SmartPointerSlice {
                        building_item: bi, ..
                    } = &mut parent_frame.tracker
                    {
                        *bi = false;
                    }
                }
            }
            Tracker::DynamicValue {
                state:
                    DynamicValueState::Array {
                        building_element, ..
                    },
            } => {
                if *building_element {
                    // Check that the element is initialized before pushing
                    if !popped_frame.is_init {
                        // Element was never set - clean up and return error
                        let shape = parent_frame.allocated.shape();
                        popped_frame.dealloc();
                        *building_element = false;
                        // No need to poison - returning Err consumes self, Drop will handle cleanup
                        return Err(self.err(ReflectErrorKind::OperationFailed {
                            shape,
                            operation: "end() called but array element was never initialized",
                        }));
                    }

                    // We just popped an element frame, now push it to the dynamic array
                    if let Def::DynamicValue(dyn_def) = parent_frame.allocated.shape().def {
                        // Get mutable pointers - both array and element need PtrMut
                        let array_ptr = unsafe { parent_frame.data.assume_init() };
                        let element_ptr = unsafe { popped_frame.data.assume_init() };

                        // Use push_array_element to add element to the array
                        unsafe {
                            (dyn_def.vtable.push_array_element)(array_ptr, element_ptr);
                        }

                        // Push moved out of popped_frame
                        popped_frame.tracker = Tracker::Scalar;
                        popped_frame.is_init = false;
                        popped_frame.dealloc();

                        *building_element = false;
                    }
                }
            }
            Tracker::DynamicValue {
                state: DynamicValueState::Object { insert_state, .. },
            } => {
                if let DynamicObjectInsertState::BuildingValue { key } = insert_state {
                    // Check that the value is initialized before inserting
                    if !popped_frame.is_init {
                        // Value was never set - clean up and return error
                        let shape = parent_frame.allocated.shape();
                        popped_frame.dealloc();
                        *insert_state = DynamicObjectInsertState::Idle;
                        // No need to poison - returning Err consumes self, Drop will handle cleanup
                        return Err(self.err(ReflectErrorKind::OperationFailed {
                            shape,
                            operation: "end() called but object entry value was never initialized",
                        }));
                    }

                    // We just popped a value frame, now insert it into the dynamic object
                    if let Def::DynamicValue(dyn_def) = parent_frame.allocated.shape().def {
                        // Get mutable pointers - both object and value need PtrMut
                        let object_ptr = unsafe { parent_frame.data.assume_init() };
                        let value_ptr = unsafe { popped_frame.data.assume_init() };

                        // Use insert_object_entry to add the key-value pair
                        unsafe {
                            (dyn_def.vtable.insert_object_entry)(object_ptr, key, value_ptr);
                        }

                        // Insert moved out of popped_frame
                        popped_frame.tracker = Tracker::Scalar;
                        popped_frame.is_init = false;
                        popped_frame.dealloc();

                        // Reset insert state to Idle
                        *insert_state = DynamicObjectInsertState::Idle;
                    }
                }
            }
            _ => {}
        }

        Ok(self)
    }

    /// Returns a path representing the current traversal in the builder.
    ///
    /// The returned [`facet_path::Path`] can be formatted as a human-readable string
    /// using [`Path::format_with_shape()`](facet_path::Path::format_with_shape),
    /// e.g., `fieldName[index].subfield`.
    pub fn path(&self) -> Path {
        use facet_path::PathStep;

        let root_shape = self
            .frames()
            .first()
            .expect("Partial must have at least one frame")
            .allocated
            .shape();
        let mut path = Path::new(root_shape);

        for frame in self.frames().iter() {
            match frame.allocated.shape().ty {
                Type::User(user_type) => match user_type {
                    UserType::Struct(_struct_type) => {
                        // Add field step if we're currently in a field
                        if let Tracker::Struct {
                            current_child: Some(idx),
                            ..
                        } = &frame.tracker
                        {
                            path.push(PathStep::Field(*idx as u32));
                        }
                    }
                    UserType::Enum(enum_type) => {
                        // Add variant and optional field step
                        if let Tracker::Enum {
                            variant,
                            current_child,
                            ..
                        } = &frame.tracker
                        {
                            // Find the variant index by comparing pointers
                            if let Some(variant_idx) = enum_type
                                .variants
                                .iter()
                                .position(|v| core::ptr::eq(v, *variant))
                            {
                                path.push(PathStep::Variant(variant_idx as u32));
                            }
                            if let Some(idx) = *current_child {
                                path.push(PathStep::Field(idx as u32));
                            }
                        }
                    }
                    UserType::Union(_) => {
                        // No structural path steps for unions
                    }
                    UserType::Opaque => {
                        // Opaque types might be lists (e.g., Vec<T>)
                        if let Tracker::List {
                            current_child: Some(idx),
                            ..
                        } = &frame.tracker
                        {
                            path.push(PathStep::Index(*idx as u32));
                        }
                    }
                },
                Type::Sequence(facet_core::SequenceType::Array(_array_def)) => {
                    // Add index step if we're currently in an element
                    if let Tracker::Array {
                        current_child: Some(idx),
                        ..
                    } = &frame.tracker
                    {
                        path.push(PathStep::Index(*idx as u32));
                    }
                }
                Type::Sequence(_) => {
                    // Other sequence types (Slice, etc.) - no index tracking
                }
                Type::Pointer(_) => {
                    path.push(PathStep::Deref);
                }
                _ => {
                    // No structural path for scalars, etc.
                }
            }
        }

        path
    }

    /// Returns the root shape for path formatting.
    ///
    /// Use this together with [`path()`](Self::path) to format the path:
    /// ```ignore
    /// let path_str = partial.path().format_with_shape(partial.root_shape());
    /// ```
    pub fn root_shape(&self) -> &'static Shape {
        self.frames()
            .first()
            .expect("Partial should always have at least one frame")
            .allocated
            .shape()
    }

    /// Create a [`ReflectError`] with the current path context.
    ///
    /// This is a convenience method for constructing errors inside `Partial` methods
    /// that automatically captures the current traversal path.
    #[inline]
    pub fn err(&self, kind: ReflectErrorKind) -> ReflectError {
        ReflectError::new(kind, self.path())
    }

    /// Get the field for the parent frame
    pub fn parent_field(&self) -> Option<&Field> {
        self.frames()
            .iter()
            .rev()
            .nth(1)
            .and_then(|f| f.get_field())
    }

    /// Gets the field for the current frame
    pub fn current_field(&self) -> Option<&Field> {
        self.frames().last().and_then(|f| f.get_field())
    }

    /// Gets the nearest active field when nested wrapper frames are involved.
    ///
    /// This walks frames from innermost to outermost and returns the first frame
    /// that currently points at a struct/enum field.
    pub fn nearest_field(&self) -> Option<&Field> {
        self.frames().iter().rev().find_map(|f| f.get_field())
    }

    /// Returns a const pointer to the current frame's data.
    ///
    /// This is useful for validation - after deserializing a field value,
    /// validators can read the value through this pointer.
    ///
    /// # Safety
    ///
    /// The returned pointer is valid only while the frame exists.
    /// The caller must ensure the frame is fully initialized before
    /// reading through this pointer.
    #[deprecated(note = "use initialized_data_ptr() instead, which checks initialization")]
    pub fn data_ptr(&self) -> Option<facet_core::PtrConst> {
        if self.state != PartialState::Active {
            return None;
        }
        self.frames().last().map(|f| {
            // SAFETY: We're in active state, so the frame is valid.
            // The caller is responsible for ensuring the data is initialized.
            unsafe { f.data.assume_init().as_const() }
        })
    }

    /// Returns a const pointer to the current frame's data, but only if fully initialized.
    ///
    /// This is the safe way to get a pointer for validation - it verifies that
    /// the frame is fully initialized before returning the pointer.
    ///
    /// Returns `None` if:
    /// - The partial is not in active state
    /// - The current frame is not fully initialized
    #[allow(unsafe_code)]
    pub fn initialized_data_ptr(&mut self) -> Option<facet_core::PtrConst> {
        if self.state != PartialState::Active {
            return None;
        }
        let frame = self.frames_mut().last_mut()?;

        // Check if fully initialized (may drain rope for lists)
        if frame.require_full_initialization().is_err() {
            return None;
        }

        // SAFETY: We've verified the partial is active and the frame is fully initialized.
        Some(unsafe { frame.data.assume_init().as_const() })
    }

    /// Returns a typed reference to the current frame's data if:
    /// 1. The partial is in active state
    /// 2. The current frame is fully initialized
    /// 3. The shape matches `T::SHAPE`
    ///
    /// This is the safe way to read a value from a Partial for validation purposes.
    #[allow(unsafe_code)]
    pub fn read_as<T: facet_core::Facet<'facet>>(&mut self) -> Option<&T> {
        if self.state != PartialState::Active {
            return None;
        }
        let frame = self.frames_mut().last_mut()?;

        // Check if fully initialized (may drain rope for lists)
        if frame.require_full_initialization().is_err() {
            return None;
        }

        // Check shape matches
        if frame.allocated.shape() != T::SHAPE {
            return None;
        }

        // SAFETY: We've verified:
        // 1. The partial is active (frame is valid)
        // 2. The frame is fully initialized
        // 3. The shape matches T::SHAPE
        unsafe {
            let ptr = frame.data.assume_init().as_const();
            Some(&*ptr.as_ptr::<T>())
        }
    }
}