openusd 0.6.0

Rust native USD library
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
//! A single scene-description layer (the Rust equivalent of C++ `SdfLayer`):
//! identity plus a backing [`AbstractData`] under a copy-on-write [`CowData`]
//! staging overlay.
//!
//! # Editing
//!
//! A layer is mutated only through [`Layer::edit`] (one layer) or [`edit_layers`]
//! (several at once, atomically): the closure authors through a [`LayerEdit`]
//! view — [`PrimSpec::new`](super::PrimSpec::new) and friends write through
//! [`LayerEdit::data_mut`] — and the whole batch commits when the closure returns
//! `Ok`, or rolls back on its error or a panic. Committing drains the overlay into
//! the backend and yields the derived [`ChangeList`] for composition
//! invalidation. [`dry_run_layers`] runs the same staging but always discards it,
//! to check an edit applies without keeping it. Reads merge staged-over-base, so
//! an in-progress edit is visible to reads inside its closure.
//!
//! # Why copy-on-write
//!
//! Staging is the primitive that makes three things the editing pipeline relies on
//! cheap and correct (the alternative is to edit the backend immediately and track
//! changes as they happen):
//!
//! - Net-effect change records. A composition invalidation should reflect the
//!   final state of an edit, not the churn along the way. Because the overlay holds
//!   the net staged state, the [`ChangeList`] derived from it at commit reflects
//!   only that final result: a field set twice records once, and a spec created
//!   then deleted within one edit records nothing — never the in-between steps an
//!   immediate-edit log would carry.
//! - Old and new values side by side. At commit the pristine base and the staged
//!   overlay both exist, so a forward log (the new values) and an inverse log (the
//!   old values, for undo) fall out directly from the diff — no need to snapshot
//!   the old value at each mutation before it is overwritten.
//! - All-or-nothing edits. A multi-step edit — or a multi-layer one, where a
//!   namespace edit must apply across several layers together — either commits
//!   whole or rolls back whole. Rolling back is just dropping the overlay, so
//!   abandoning a half-built or vetoed edit costs nothing and leaves no partial
//!   state behind.
//!
//! Loading a layer and its sublayer stack lives in
//! [`LayerRegistry`](super::LayerRegistry); cross-layer composition (references,
//! payloads) lives in [`crate::pcp`].

use std::collections::HashMap;
use std::io::Cursor;
use std::sync::atomic::{AtomicU64, Ordering};

use anyhow::{Context, Result};

use crate::ar;

use super::schema::FieldKey;
use super::{
    sink, AbstractData, AttributeSpecMut, AttributeSpecRef, ChangeList, CowData, Data, DataError, LayerData, Patch,
    Path, PrimSpecMut, PrimSpecRef, PseudoRootSpecMut, PseudoRootSpecRef, RelationshipSpecMut, RelationshipSpecRef,
    RelocateList, SpecError, SpecType, Value,
};

/// A [`sink::Id`] for a [`LayerSink`] installed on a [`Layer`].
pub type LayerSinkId = sink::Id<dyn LayerSink>;

/// Prefix marking an anonymous layer identifier (`anon:<n>:<tag>`), the single
/// source of truth shared by minting and [`Layer::is_anonymous`].
const ANONYMOUS_PREFIX: &str = "anon:";

/// Monotonic source of unique anonymous-layer identifiers (the `<n>` in
/// `anon:<n>:<tag>`). Process-global so that anonymous layers created anywhere
/// in the process never collide.
static ANONYMOUS_COUNTER: AtomicU64 = AtomicU64::new(0);

/// Monotonic source of transaction ids stamped onto every [`edit_layers`] group
/// (see [`PendingLayerChange::generation`]). Process-global so an observer can
/// tell one atomic transaction's commits from the next regardless of which layer
/// or stage they land on.
static NEXT_GENERATION: AtomicU64 = AtomicU64::new(0);

/// A single loaded layer in the composition.
pub struct Layer {
    /// Resolved, canonical identifier for this layer.
    pub identifier: String,
    /// The layer's resolved physical location when it differs from
    /// [`identifier`](Self::identifier) — the anchor for the relative asset
    /// paths it authors (C++ `SdfLayer::GetRealPath`). `None` (the common case)
    /// means it equals the identifier; a package (`.usdz`) opens under the bare
    /// package identifier while its real path is the package-relative default
    /// layer (`pkg.usdz[root.usd]`), so paths authored inside it anchor
    /// in-package against the real path rather than the identifier. Read
    /// through [`real_path`](Self::real_path), which falls back to the
    /// identifier.
    real_path: Option<String>,
    /// The parsed scene description data, under a copy-on-write [`CowData`]
    /// staging overlay. Every authoring write stages in the overlay; committing an
    /// edit derives the composition record and drains the overlay into the backend.
    /// Private so external callers reach it only through [`data`](Self::data) for
    /// reads or a [`LayerEdit`] for authoring, keeping the authoring API's
    /// bookkeeping invariants (`primChildren`, `propertyChildren`, ancestor
    /// specifiers, …) in force.
    data: CowData<LayerData>,
    /// The change record for the edit in progress, derived from the overlay at
    /// commit and handed to the layer's sinks. Owned and refilled in place each
    /// commit (reusing its buffer) rather than reallocated; empty between edits.
    changes: ChangeList,
    /// Per-layer change sinks fired at the commit seam — the low tier of the
    /// change pipeline, where a stage installs an aggregator so it stays in sync
    /// with any edit. Empty by default.
    sinks: sink::Set<dyn LayerSink>,
}

impl Layer {
    /// Construct a layer from a resolved identifier and a backing data store.
    /// Crate-private — external callers should use [`Layer::new_anonymous`]
    /// for blank in-memory layers, or open a stage (which loads layers from
    /// disk on demand) for loaded layers.
    pub(crate) fn new(identifier: impl Into<String>, data: LayerData) -> Self {
        Self::build(identifier.into(), None, data)
    }

    /// Construct a loaded layer recording its resolved physical location.
    ///
    /// The loader passes the [`real_path`](Self::real_path) it resolved the
    /// layer to: it equals `identifier` for an ordinary layer, but a package
    /// opens under its bare identifier while its real path is the
    /// package-relative default layer, so the paths it authors anchor
    /// in-package. Only a real path that differs from the identifier is stored;
    /// otherwise this is [`new`](Self::new).
    pub(crate) fn new_resolved(identifier: impl Into<String>, real_path: &ar::ResolvedPath, data: LayerData) -> Self {
        let identifier = identifier.into();
        let real_path = real_path.to_string();
        let real_path = (real_path != identifier).then_some(real_path);
        Self::build(identifier, real_path, data)
    }

    /// Shared constructor backing [`new`](Self::new) and
    /// [`new_resolved`](Self::new_resolved).
    fn build(identifier: String, real_path: Option<String>, data: LayerData) -> Self {
        Self {
            identifier,
            real_path,
            data: CowData::new(data),
            changes: ChangeList::new(),
            sinks: sink::Set::default(),
        }
    }

    /// Install a [`LayerSink`] fired at this layer's commit seam, returning its
    /// [`LayerSinkId`] for a later [`remove_sink`](Self::remove_sink). Any
    /// editor of this layer — a stage, the namespace editor, raw authoring —
    /// fires the sink, so an external observer sees every committed edit. A bare
    /// `Fn(&str, &ChangeList)` closure is a `LayerSink`, so this takes either a
    /// full sink type or a closure observer.
    pub fn add_sink<S: LayerSink + 'static>(&mut self, sink: S) -> LayerSinkId {
        self.sinks.add(Box::new(sink))
    }

    /// Remove the layer sink with `id`; a no-op if it was already removed.
    pub fn remove_sink(&mut self, id: LayerSinkId) {
        self.sinks.remove(id);
    }

    /// Borrow the layer's data as a read-only [`AbstractData`]. Reads see the
    /// staged-over-base view, so edits staged but not yet flushed are visible.
    pub fn data(&self) -> &dyn AbstractData {
        &self.data
    }

    /// Discard the layer's staged (uncommitted) edits, restoring the backend to
    /// its last-committed state. Already-committed content is unaffected. Private:
    /// staging and committing are driven only through [`edit`](Self::edit) /
    /// [`edit_layers`], which roll back automatically on failure, so a caller
    /// never sequences a rollback by hand.
    fn rollback(&mut self) {
        self.data.rollback();
    }

    /// Author a batch of edits as one atomic unit: run `f` against the layer's
    /// [`LayerEdit`] view, then commit on success, or roll back on `f`'s error, a
    /// sink veto, or a panic. Returns whether the edit produced a composition
    /// change. This is the only way to mutate a layer — the commit is the closing
    /// brace, not a separate call a caller can omit — so an edit is never left
    /// staged-but-uncommitted. Mirrors C++ scene description committing through
    /// `Sdf_ChangeManager`. To edit several of a stage's layers atomically, use
    /// [`Stage::batch_edit`](crate::usd::Stage::batch_edit).
    ///
    /// Panics if called re-entrantly on the same layer.
    ///
    /// # Example
    ///
    /// ```
    /// use openusd::sdf::{self, PrimSpec, Specifier};
    ///
    /// let mut layer = sdf::Layer::new_anonymous("example.usda");
    /// // On success the batch commits and the change record is returned.
    /// layer
    ///     .edit(|l| {
    ///         PrimSpec::new(l.data_mut(), "/World", Specifier::Def, "Xform")?;
    ///         Ok(())
    ///     })
    ///     .expect("authored and committed");
    /// assert!(layer.prim("/World").is_some());
    ///
    /// // If the closure returns an error, the whole batch rolls back — neither
    /// // spec below survives, because the second authoring call fails.
    /// let result = layer.edit(|l| {
    ///     PrimSpec::new(l.data_mut(), "/Good", Specifier::Def, "Xform")?;
    ///     PrimSpec::new(l.data_mut(), "/Good.prop", Specifier::Def, "Xform")?; // property path: invalid for a prim
    ///     Ok(())
    /// });
    /// assert!(result.is_err());
    /// assert!(layer.prim("/Good").is_none());
    /// ```
    pub fn edit(
        &mut self,
        f: impl FnOnce(&mut LayerEdit<'_>) -> Result<(), AuthoringError>,
    ) -> Result<bool, EditError> {
        edit_layers(&mut [self], |edits| f(&mut edits[0]).map_err(EditError::from))
    }

    /// Refill this layer's change record from the staged overlay against the
    /// still-pristine base, and offer it to each sink's
    /// [`before_commit`](LayerSink::before_commit) while the overlay is intact,
    /// tagged with the enclosing transaction's `generation`. A sink's rejection
    /// leaves the overlay staged for the caller to roll back. Does not touch the
    /// backend.
    fn prepare_commit(&mut self, generation: u64) -> Result<(), sink::Error> {
        self.changes.update(&self.data);
        if !self.changes.is_empty() && !self.sinks.is_empty() {
            let change = PendingLayerChange {
                layer_identifier: &self.identifier,
                base: &**self.data.base(),
                overlay: self.data.overlay(),
                change_list: &self.changes,
                generation,
            };
            self.sinks.iter().try_for_each(|sink| sink.before_commit(&change))?;
        }
        Ok(())
    }

    /// Drain the overlay into the backend — the irreversible half of a commit,
    /// run once [`prepare_commit`](Self::prepare_commit) has accepted the edit.
    /// Returns whether the edit produced any composition change. The derived
    /// record stays in [`changes`](Self::changes) for a following
    /// [`notify_after_commit`](Self::notify_after_commit).
    fn commit_data(&mut self) -> bool {
        self.data.commit();
        !self.changes.is_empty()
    }

    /// Fire each sink's [`after_commit`](LayerSink::after_commit) with the record
    /// [`prepare_commit`](Self::prepare_commit) derived. Run only after every layer
    /// in a group has committed its data, so a panicking sink cannot strand a
    /// partially committed group.
    fn notify_after_commit(&self) {
        if !self.changes.is_empty() {
            for sink in self.sinks.iter() {
                sink.after_commit(&self.identifier, &self.changes);
            }
        }
    }

    /// Whether the layer has edits staged in its overlay but not yet committed.
    /// Mirrors C++ `SdfLayer::IsDirty` for the in-flight-edit case.
    ///
    /// Conservative about staged content: any uncommitted overlay write counts,
    /// including an idempotent edit (a field re-set to the value the base already
    /// holds) whose commit would derive no composition change.
    pub fn is_dirty(&self) -> bool {
        !self.data.is_empty()
    }

    /// Commit any staged edits into the backend to keep their content, without
    /// deriving a change record or notifying sinks. Called when a layer joins a
    /// stage: its content is composed fresh by the layer-stack recompose, so a
    /// record from prior direct edits would be redundant.
    pub(crate) fn discard_changes(&mut self) {
        self.data.commit();
    }

    /// The layer's resolved, canonical identifier.
    pub fn identifier(&self) -> &str {
        &self.identifier
    }

    /// The layer's resolved physical location, the anchor for the relative
    /// asset paths it authors (C++ `SdfLayer::GetRealPath`). Equals the
    /// identifier except for a package, whose real path is its package-relative
    /// default layer.
    pub(crate) fn real_path(&self) -> &str {
        self.real_path.as_deref().unwrap_or(&self.identifier)
    }
}

impl Layer {
    /// Write this layer to `filename`, choosing the format from the filename's
    /// extension (C++ `SdfLayer::Export`). This writes a copy; the layer's own
    /// identifier is unchanged.
    ///
    /// `.usda` writes text, `.usdc` writes the binary crate, `.usd` writes
    /// binary (the C++ `USD_WRITE_NEW_USD_FILES_AS_BINARY` default), and
    /// `.usdz` writes an archive wrapping one crate-encoded layer. The reader
    /// auto-detects the format regardless of extension, so text written to a
    /// `.usd` path still reads back correctly.
    pub fn export(&self, filename: impl AsRef<str>) -> Result<()> {
        let filename = filename.as_ref();
        let ext = std::path::Path::new(filename)
            .extension()
            .and_then(|e| e.to_str())
            .unwrap_or_default();
        let format = super::LayerRegistry::find_by_extension(ext).ok_or_else(|| match ext {
            "" => anyhow::anyhow!("layer path {filename} has no extension; cannot choose format"),
            other => anyhow::anyhow!("unsupported layer extension {other:?} (expected usda/usdc/usd/usdz)"),
        })?;
        if !format.caps().can_write() {
            anyhow::bail!("file format {} does not support writing", format.format_id());
        }
        let mut file = std::fs::File::create(filename).with_context(|| format!("failed to create {filename}"))?;
        format.write(self.data(), &mut file)
    }

    /// Serialize this layer to a `usda` text string (C++ `ExportToString`).
    ///
    /// Always emits text, the canonical human-readable form, regardless of the
    /// layer's on-disk format. Named to avoid confusion with the infallible
    /// [`ToString::to_string`].
    pub fn export_to_string(&self) -> Result<String> {
        let format = super::LayerRegistry::find_by_id("usda").expect("usda is a built-in format");
        let mut buf = Cursor::new(Vec::new());
        format.write(self.data(), &mut buf)?;
        String::from_utf8(buf.into_inner()).context("usda writer produced invalid UTF-8")
    }

    /// Write this layer to its own [`identifier`](Self::identifier), choosing
    /// the format from the identifier's extension (C++ `SdfLayer::Save`).
    ///
    /// The identifier must be an absolute filesystem path — the canonical form
    /// the resolver produces for layers loaded from disk.
    /// Anonymous layers ([`is_anonymous`](Self::is_anonymous)) and layers whose
    /// identifier is a relative path or a non-filesystem asset identifier (e.g.
    /// `scheme://…`) have no persistent location here; save them with
    /// [`export`](Self::export) and an explicit destination instead.
    pub fn save(&self) -> Result<()> {
        anyhow::ensure!(!self.is_anonymous(), "cannot save anonymous layer {}", self.identifier);
        let path = std::path::Path::new(&self.identifier);
        anyhow::ensure!(
            path.is_absolute(),
            "cannot save layer {}: identifier is not an absolute file path; use Layer::export(path) to choose a destination",
            self.identifier
        );
        // Saving overwrites the layer's own file in place, so the format must
        // support in-place editing — unlike `export`, which only writes a copy.
        // A package format (usdz) is writable as a fresh archive but not
        // editable in place: a loaded package's other assets (textures, sibling
        // layers) are not held by the layer, so saving over it would discard
        // them. An unknown extension is left for `export` to reject.
        let ext = path.extension().and_then(|e| e.to_str()).unwrap_or_default();
        if let Some(format) = super::LayerRegistry::find_by_extension(ext) {
            anyhow::ensure!(
                format.caps().can_edit(),
                "cannot save layer {} in place: the {} format is not editable; use Layer::export(path) to write a new copy",
                self.identifier,
                format.format_id()
            );
        }
        // TODO(layer-registry): save writes to `identifier` as a literal
        // filesystem path. A layer loaded through a custom resolver may carry a
        // logical identifier (e.g. `scheme://…`); save should resolve it through
        // the owning resolver and write via a resolver write API. The
        // absolute-path guard above refuses such identifiers for now.
        // TODO(layer-registry): save re-selects the format from the identifier's
        // extension, so a textual `.usd` layer is rewritten as binary. Once the
        // load path records the FileFormat a layer was read with (C++
        // `_fileFormat`), save should reuse it to preserve the original encoding.
        self.export(&self.identifier)
    }
}

/// Errors raised by [`Layer`]'s authoring methods.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum AuthoringError {
    /// The target spec rejected an edit.
    #[error(transparent)]
    Spec(#[from] SpecError),

    /// Reading a field from the source data failed (e.g. a lazy backend could
    /// not decode an authored value while copying it).
    #[error(transparent)]
    Data(#[from] DataError),

    /// The given path is not valid for the requested authoring operation.
    /// Prim authoring requires an absolute, non-root, non-property path;
    /// property authoring requires a property path.
    #[error("path {path} is not valid here: {reason}")]
    InvalidPath {
        /// The offending path.
        path: Path,
        /// A short, human-readable reason describing what was expected.
        reason: &'static str,
    },
}

/// An error from [`Layer::edit`]: the closure's authoring error, or a sink's
/// rejection of the staged edit.
#[derive(Debug, thiserror::Error)]
pub enum EditError {
    /// The edit closure failed to author; nothing was committed.
    #[error(transparent)]
    Author(#[from] AuthoringError),

    /// A [`LayerSink`] rejected the staged edit from its
    /// [`before_commit`](LayerSink::before_commit).
    #[error(transparent)]
    Rejected(#[from] sink::Error),
}

/// An observer of a single [`Layer`]'s committed edits — the low tier of the
/// change pipeline, fired synchronously at the layer's commit seam so a sink
/// sees every edit, by any editor, the moment it lands. A [`Stage`](crate::usd::Stage)
/// installs an aggregating sink on each layer it owns to stay in sync;
/// composition-level observation lives one tier up on the stage.
///
/// Both methods default to doing nothing, so a sink implements only the phase it
/// cares about. Sinks fire in installation order.
pub trait LayerSink {
    /// Inspect a staged edit before it commits. Returning `Err` rolls the edit
    /// back: the overlay is discarded and the error surfaces to the author. The
    /// pristine base and the staged overlay are both visible, which is what lets
    /// a sink derive an inverse (undo) record here.
    fn before_commit(&self, change: &PendingLayerChange<'_>) -> Result<(), sink::Error> {
        let _ = change;
        Ok(())
    }

    /// Observe a committed edit, after the overlay has drained into the backend.
    /// `layer` is the committing layer's identifier and `changes` the record
    /// derived from the edit.
    fn after_commit(&self, layer: &str, changes: &ChangeList) {
        let _ = (layer, changes);
    }
}

/// A bare closure is a [`LayerSink`] that only observes committed edits — the
/// ergonomic "just record commits" case, installed straight through
/// [`Layer::add_sink`] with no wrapper type. `Fn` (not `FnMut`) because a sink is
/// invoked through a shared `&self`; capture interior-mutable state to accumulate.
impl<F: Fn(&str, &ChangeList)> LayerSink for F {
    fn after_commit(&self, layer: &str, changes: &ChangeList) {
        self(layer, changes);
    }
}

/// A staged, not-yet-committed edit on one layer, handed to
/// [`LayerSink::before_commit`]: the pre-edit base, the staged overlay, and the
/// derived change record — enough for a sink to derive a forward or inverse
/// [`Edit`](crate::usd::Edit) log without committing.
pub struct PendingLayerChange<'a> {
    /// Canonical identifier of the edited layer.
    pub layer_identifier: &'a str,
    /// The layer's pre-edit values (the overlay's base).
    pub base: &'a dyn AbstractData,
    /// The staged changes keyed by path — the new values, as [`Patch`]es.
    pub overlay: &'a HashMap<Path, Patch>,
    /// The composition record derived from this layer's overlay. A sink that
    /// needs to retain it past the callback clones it ([`ChangeList`] is
    /// [`Clone`]).
    pub change_list: &'a ChangeList,
    /// The id of the atomic transaction ([`edit_layers`] group) this commit
    /// belongs to: one id shared by every layer the transaction commits, distinct
    /// from the next transaction's, and monotonically increasing. An observer
    /// keys per-transaction state on it (see [`crate::usd::UndoStage`]).
    pub generation: u64,
}

/// Identity, persistence, and typed-view lookups. Spec authoring lives on the
/// views themselves ([`PrimSpec::new`](crate::sdf::PrimSpec::new) and friends,
/// mirroring C++ `Sdf*Spec::New`); they write through [`LayerEdit::data_mut`], so
/// every edit stages in the layer's overlay for the next flush to record.
///
/// The typed-view lookups ([`Layer::prim`], [`Layer::attribute`],
/// [`Layer::relationship`], [`Layer::pseudo_root`]) operate through the
/// [`AbstractData`] field interface, so they work uniformly on any backend —
/// in-memory [`Data`] or a file-loaded reader — matching C++
/// `SdfLayer::GetPrimAtPath`.
impl Layer {
    /// Create a blank in-memory writable layer with a unique anonymous
    /// identifier of the form `anon:<n>:<tag>`, mirroring C++
    /// `SdfLayer::CreateAnonymous`. `tag` is a human-readable hint, not an
    /// address: two calls with the same tag get distinct identifiers, so
    /// independent anonymous layers never alias (see [`Layer::is_anonymous`]).
    ///
    /// The layer's pseudo-root spec is pre-populated so layer-level metadata
    /// (`defaultPrim`, `subLayers`, time codes, …) can be authored via
    /// [`LayerEdit::pseudo_root_mut`] immediately.
    pub fn new_anonymous(tag: impl std::fmt::Display) -> Self {
        let n = ANONYMOUS_COUNTER.fetch_add(1, Ordering::Relaxed);
        Self::new_in_memory(format!("{ANONYMOUS_PREFIX}{n}:{tag}"))
    }

    /// Create a blank in-memory writable layer with the given verbatim
    /// identifier and a pre-populated pseudo-root spec. Backs
    /// [`new_anonymous`](Self::new_anonymous) and, within the crate, composes
    /// layers whose identifiers must match an authored `subLayers` entry.
    pub(crate) fn new_in_memory(identifier: impl Into<String>) -> Self {
        let mut data = Data::new();
        data.create_spec(Path::abs_root(), SpecType::PseudoRoot);
        Self::new(identifier, Box::new(data))
    }

    /// Whether this layer's identifier is anonymous (the `anon:` prefix minted
    /// by [`new_anonymous`](Self::new_anonymous)). Mirrors C++
    /// `SdfLayer::IsAnonymous`; an anonymous layer has no asset-resolvable
    /// location.
    pub fn is_anonymous(&self) -> bool {
        Self::is_anonymous_identifier(&self.identifier)
    }

    /// Whether `identifier` is an anonymous-layer identifier (the `anon:` prefix),
    /// without needing the layer itself. Mirrors C++
    /// `SdfLayer::IsAnonymousLayerIdentifier`; the prefix is the single source of
    /// truth for anonymity.
    pub fn is_anonymous_identifier(identifier: &str) -> bool {
        identifier.starts_with(ANONYMOUS_PREFIX)
    }

    /// Look up a prim spec at `path`. Returns `None` if no spec exists or the
    /// spec is not a prim.
    pub fn prim(&self, path: impl Into<Path>) -> Option<PrimSpecRef<'_>> {
        PrimSpecRef::get(self.data(), path.into())
    }

    /// Look up an attribute spec at a property path.
    pub fn attribute(&self, path: impl Into<Path>) -> Option<AttributeSpecRef<'_>> {
        AttributeSpecRef::get(self.data(), path.into())
    }

    /// Look up a relationship spec at a property path.
    pub fn relationship(&self, path: impl Into<Path>) -> Option<RelationshipSpecRef<'_>> {
        RelationshipSpecRef::get(self.data(), path.into())
    }

    /// View this layer's root pseudo-spec, which carries layer-wide metadata
    /// (`defaultPrim`, `subLayers`, time codes, …).
    pub fn pseudo_root(&self) -> Option<PseudoRootSpecRef<'_>> {
        PseudoRootSpecRef::get(self.data())
    }

    /// The list of namespace relocations authored in this layer's metadata,
    /// or an empty list when none are authored. Mirrors C++
    /// `SdfLayer::GetRelocates`. Reads through the backing [`AbstractData`], so
    /// it works on both in-memory and file-loaded layers.
    pub fn relocates(&self) -> RelocateList {
        self.pseudo_root().and_then(|root| root.relocates()).unwrap_or_default()
    }

    /// Whether this layer's metadata carries any `relocates` opinion, including
    /// an explicit empty list (an opinion that *there should be no* relocates).
    /// Mirrors C++ `SdfLayer::HasRelocates`.
    pub fn has_relocates(&self) -> bool {
        self.has_root_field(FieldKey::LayerRelocates)
    }

    /// The layer's `startTimeCode`, or `0.0` when unauthored. Mirrors C++
    /// `SdfLayer::GetStartTimeCode`.
    pub fn start_time_code(&self) -> f64 {
        self.pseudo_root()
            .and_then(|root| root.start_time_code())
            .unwrap_or(0.0)
    }

    /// Whether this layer authors a `startTimeCode` opinion. Mirrors C++
    /// `SdfLayer::HasStartTimeCode`.
    pub fn has_start_time_code(&self) -> bool {
        self.has_root_field(FieldKey::StartTimeCode)
    }

    /// The layer's `endTimeCode`, or `0.0` when unauthored. Mirrors C++
    /// `SdfLayer::GetEndTimeCode`.
    pub fn end_time_code(&self) -> f64 {
        self.pseudo_root().and_then(|root| root.end_time_code()).unwrap_or(0.0)
    }

    /// Whether this layer authors an `endTimeCode` opinion. Mirrors C++
    /// `SdfLayer::HasEndTimeCode`.
    pub fn has_end_time_code(&self) -> bool {
        self.has_root_field(FieldKey::EndTimeCode)
    }

    /// The layer's `timeCodesPerSecond`. Falls back to the authored
    /// `framesPerSecond`, then to `24.0`, when unauthored. Mirrors C++
    /// `SdfLayer::GetTimeCodesPerSecond`.
    pub fn time_codes_per_second(&self) -> f64 {
        let root = self.pseudo_root();
        root.as_ref()
            .and_then(|root| root.time_codes_per_second())
            .or_else(|| root.as_ref().and_then(|root| root.frames_per_second()))
            .unwrap_or(24.0)
    }

    /// Whether this layer authors a `timeCodesPerSecond` opinion. Mirrors C++
    /// `SdfLayer::HasTimeCodesPerSecond`.
    pub fn has_time_codes_per_second(&self) -> bool {
        self.has_root_field(FieldKey::TimeCodesPerSecond)
    }

    /// The layer's `framesPerSecond`, or `24.0` when unauthored. Mirrors C++
    /// `SdfLayer::GetFramesPerSecond`.
    pub fn frames_per_second(&self) -> f64 {
        self.pseudo_root()
            .and_then(|root| root.frames_per_second())
            .unwrap_or(24.0)
    }

    /// Whether this layer authors a `framesPerSecond` opinion. Mirrors C++
    /// `SdfLayer::HasFramesPerSecond`.
    pub fn has_frames_per_second(&self) -> bool {
        self.has_root_field(FieldKey::FramesPerSecond)
    }

    /// The layer's `framePrecision`, or `3` when unauthored. Mirrors C++
    /// `SdfLayer::GetFramePrecision`.
    pub fn frame_precision(&self) -> i32 {
        self.pseudo_root().and_then(|root| root.frame_precision()).unwrap_or(3)
    }

    /// Whether this layer authors a `framePrecision` opinion. Mirrors C++
    /// `SdfLayer::HasFramePrecision`.
    pub fn has_frame_precision(&self) -> bool {
        self.has_root_field(FieldKey::FramePrecision)
    }

    /// Whether the pseudo-root spec authors `key`, including an explicit
    /// opinion that carries an "empty"/default value.
    fn has_root_field(&self, key: FieldKey) -> bool {
        self.data.has_field(&Path::abs_root(), key.as_str())
    }
}

/// The authoring view of a [`Layer`] handed to an [`edit`](Layer::edit) closure
/// — the only surface through which a layer is mutated.
///
/// Derefs to the [`Layer`] for reads, and exposes the layer's authoring
/// operations directly. A layer's `commit` and `rollback` are deliberately absent:
/// the edit commits when the closure returns and rolls back on its error or a
/// panic, so an edit can never be left staged-but-uncommitted, and a multi-layer
/// edit stays atomic across its layers.
pub struct LayerEdit<'a> {
    layer: &'a mut Layer,
}

impl std::ops::Deref for LayerEdit<'_> {
    type Target = Layer;

    fn deref(&self) -> &Layer {
        &*self.layer
    }
}

impl LayerEdit<'_> {
    /// Borrow the layer's backing data mutably for authoring; the write stages in
    /// the copy-on-write overlay and commits with the enclosing edit. The typed
    /// spec constructors ([`PrimSpec::new`](crate::sdf::PrimSpec::new) and friends)
    /// write through this.
    pub fn data_mut(&mut self) -> &mut dyn AbstractData {
        &mut self.layer.data
    }

    /// Remove the spec at `path`. Removing a prim also erases its descendant specs
    /// and drops the leaf name from the owning prim's child-name list. Returns
    /// `Ok(true)` when a spec was present and removed.
    pub fn remove_spec(&mut self, path: &Path) -> Result<bool, AuthoringError> {
        super::spec::remove_spec(self.data_mut(), path)
    }

    /// Mutably look up the prim spec at `path`.
    pub fn prim_mut(&mut self, path: impl Into<Path>) -> Option<PrimSpecMut<'_>> {
        PrimSpecMut::get(self.data_mut(), path.into())
    }

    /// Mutably look up the attribute spec at a property path.
    pub fn attribute_mut(&mut self, path: impl Into<Path>) -> Option<AttributeSpecMut<'_>> {
        AttributeSpecMut::get(self.data_mut(), path.into())
    }

    /// Mutably look up the relationship spec at a property path.
    pub fn relationship_mut(&mut self, path: impl Into<Path>) -> Option<RelationshipSpecMut<'_>> {
        RelationshipSpecMut::get(self.data_mut(), path.into())
    }

    /// Mutably view the root pseudo-spec, which carries layer-wide metadata
    /// (`defaultPrim`, `subLayers`, time codes, …). The spec is created on first
    /// access if missing.
    pub fn pseudo_root_mut(&mut self) -> Result<PseudoRootSpecMut<'_>, AuthoringError> {
        let root = Path::abs_root();
        match self.layer.data().spec_type(&root) {
            Some(SpecType::PseudoRoot) => {}
            Some(_) => {
                return Err(AuthoringError::InvalidPath {
                    path: root,
                    reason: "root spec exists with non-PseudoRoot SpecType",
                })
            }
            None => self.data_mut().create_spec(root, SpecType::PseudoRoot),
        }
        Ok(PseudoRootSpecMut::get(self.data_mut()).expect("just ensured a pseudo-root spec"))
    }

    /// Set the layer's `defaultPrim` metadata to `name`, a USD identifier or
    /// nested prim path without a leading `/` (e.g. `"World/Char"`). Mirrors C++
    /// `SdfLayer::SetDefaultPrim`, validating the name; the spec-tier
    /// [`PseudoRootSpecMut::set_default_prim`] is the unvalidated escape hatch.
    pub fn set_default_prim(&mut self, name: impl Into<String>) -> Result<(), AuthoringError> {
        let name = name.into();
        if name.is_empty() || name.starts_with('/') || Path::new(&format!("/{name}")).is_err() {
            return Err(AuthoringError::InvalidPath {
                path: Path::abs_root(),
                reason: "defaultPrim must be a relative prim identifier or nested prim path",
            });
        }
        self.pseudo_root_mut()?.set_default_prim(name);
        Ok(())
    }

    /// Remove the layer's `defaultPrim` metadata. No-op when no pseudo-root spec
    /// exists.
    pub fn clear_default_prim(&mut self) -> Result<(), AuthoringError> {
        self.clear_root_field(FieldKey::DefaultPrim)
    }

    /// Set the layer's entire list of namespace relocations. An empty list authors
    /// an explicit "no relocates" opinion; use [`clear_relocates`](Self::clear_relocates)
    /// to remove the opinion entirely.
    pub fn set_relocates(&mut self, relocates: RelocateList) -> Result<(), AuthoringError> {
        self.pseudo_root_mut()?.set_relocates(relocates);
        Ok(())
    }

    /// Clear the layer's `relocates` opinion. No-op when no pseudo-root spec exists.
    pub fn clear_relocates(&mut self) -> Result<(), AuthoringError> {
        self.clear_root_field(FieldKey::LayerRelocates)
    }

    /// Replace the layer's `expressionVariables` dictionary, the values an
    /// `${VAR}` expression resolves against (see
    /// [`PseudoRootSpec::set_expression_variables`](crate::sdf::PseudoRootSpec::set_expression_variables)).
    pub fn set_expression_variables(&mut self, vars: HashMap<String, Value>) -> Result<(), AuthoringError> {
        self.pseudo_root_mut()?.set_expression_variables(vars);
        Ok(())
    }

    /// Clear the layer's `expressionVariables` opinion. No-op when no pseudo-root spec exists.
    pub fn clear_expression_variables(&mut self) -> Result<(), AuthoringError> {
        self.clear_root_field(FieldKey::ExpressionVariables)
    }

    /// Set the layer's `startTimeCode`.
    pub fn set_start_time_code(&mut self, time: f64) -> Result<(), AuthoringError> {
        self.pseudo_root_mut()?.set_start_time_code(time);
        Ok(())
    }

    /// Clear the layer's `startTimeCode` opinion. No-op when no pseudo-root spec exists.
    pub fn clear_start_time_code(&mut self) -> Result<(), AuthoringError> {
        self.clear_root_field(FieldKey::StartTimeCode)
    }

    /// Set the layer's `endTimeCode`.
    pub fn set_end_time_code(&mut self, time: f64) -> Result<(), AuthoringError> {
        self.pseudo_root_mut()?.set_end_time_code(time);
        Ok(())
    }

    /// Clear the layer's `endTimeCode` opinion. No-op when no pseudo-root spec exists.
    pub fn clear_end_time_code(&mut self) -> Result<(), AuthoringError> {
        self.clear_root_field(FieldKey::EndTimeCode)
    }

    /// Set the layer's `timeCodesPerSecond`.
    pub fn set_time_codes_per_second(&mut self, rate: f64) -> Result<(), AuthoringError> {
        self.pseudo_root_mut()?.set_time_codes_per_second(rate);
        Ok(())
    }

    /// Clear the layer's `timeCodesPerSecond` opinion. No-op when no pseudo-root spec exists.
    pub fn clear_time_codes_per_second(&mut self) -> Result<(), AuthoringError> {
        self.clear_root_field(FieldKey::TimeCodesPerSecond)
    }

    /// Set the layer's `framesPerSecond`.
    pub fn set_frames_per_second(&mut self, rate: f64) -> Result<(), AuthoringError> {
        self.pseudo_root_mut()?.set_frames_per_second(rate);
        Ok(())
    }

    /// Clear the layer's `framesPerSecond` opinion. No-op when no pseudo-root spec exists.
    pub fn clear_frames_per_second(&mut self) -> Result<(), AuthoringError> {
        self.clear_root_field(FieldKey::FramesPerSecond)
    }

    /// Set the layer's `framePrecision`.
    pub fn set_frame_precision(&mut self, precision: i32) -> Result<(), AuthoringError> {
        self.pseudo_root_mut()?.set_frame_precision(precision);
        Ok(())
    }

    /// Clear the layer's `framePrecision` opinion. No-op when no pseudo-root spec exists.
    pub fn clear_frame_precision(&mut self) -> Result<(), AuthoringError> {
        self.clear_root_field(FieldKey::FramePrecision)
    }

    /// Remove a metadata field from the pseudo-root spec, if that spec exists. No-op
    /// otherwise — clearing what isn't there must not materialize state.
    fn clear_root_field(&mut self, key: FieldKey) -> Result<(), AuthoringError> {
        // `erase_field` is a no-op when the pseudo-root spec is absent.
        self.data_mut().erase_field(&Path::abs_root(), key.as_str());
        Ok(())
    }
}

impl std::fmt::Debug for Layer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Layer")
            .field("identifier", &self.identifier)
            .finish_non_exhaustive()
    }
}

/// Author across several layers as one atomic transaction: run `f` to stage
/// edits into every layer through its [`LayerEdit`] view, then commit them
/// together. Commit is two-phase — every layer's
/// [`before_commit`](LayerSink::before_commit) runs first, and only once all
/// accept does any layer's overlay drain into its backend — so a single vetoing
/// sink, an authoring error from `f`, or a panic rolls every layer back, leaving
/// none partially applied. Returns whether any layer's edit produced a
/// composition change. Each committed layer fires its sinks, so the change records
/// reach a stage through its aggregator rather than through this return.
///
/// [`Layer::edit`] is the single-layer case of this.
pub(crate) fn edit_layers<E: From<sink::Error>>(
    layers: &mut [&mut Layer],
    f: impl FnOnce(&mut [LayerEdit<'_>]) -> Result<(), E>,
) -> Result<bool, E> {
    let mut guard = GroupEditGuard {
        layers,
        committed: false,
    };
    {
        let mut edits: Vec<LayerEdit<'_>> = guard.layers.iter_mut().map(|layer| LayerEdit { layer }).collect();
        f(&mut edits)?;
        // `edits` drops at the block end, releasing the per-layer borrows for the
        // commit phase below.
    }
    // One id for the whole atomic group, so an observer sees every layer this
    // transaction commits under a single transaction id.
    let generation = NEXT_GENERATION.fetch_add(1, Ordering::Relaxed);
    // Phase 1: refill each layer's record and offer it to that layer's
    // `before_commit`; a veto aborts before any layer commits.
    for layer in guard.layers.iter_mut() {
        layer.prepare_commit(generation)?;
    }
    // Phase 2: every layer accepted, so drain each overlay into its backend. Commit
    // all layers before notifying any, so the whole group's data lands even if a
    // later `after_commit` panics.
    let mut changed = false;
    for layer in guard.layers.iter_mut() {
        changed |= layer.commit_data();
    }
    // The group is committed, so the guard's drop leaves every overlay in place.
    guard.committed = true;
    // Phase 3: deliver each layer's `after_commit`. A panic here interrupts only
    // notification — the group's data is already committed.
    for layer in guard.layers.iter() {
        layer.notify_after_commit();
    }
    Ok(changed)
}

/// Stage edits across `layers` to verify they apply, then discard them all — the
/// dry-run counterpart of [`edit_layers`]. Returns `f`'s authoring result while
/// committing nothing and firing no sink, so a caller can check that an edit is
/// valid (e.g. a namespace edit's `can_apply`) without mutating the layers or
/// notifying observers.
pub(crate) fn dry_run_layers<E>(
    layers: &mut [&mut Layer],
    f: impl FnOnce(&mut [LayerEdit<'_>]) -> Result<(), E>,
) -> Result<(), E> {
    // `committed` stays false, so the guard rolls every layer back on the way out,
    // whether `f` succeeds or fails — a dry run leaves no staged state behind.
    let guard = GroupEditGuard {
        layers,
        committed: false,
    };
    let mut edits: Vec<LayerEdit<'_>> = guard.layers.iter_mut().map(|layer| LayerEdit { layer }).collect();
    f(&mut edits)
}

/// Rolls every layer in an [`edit_layers`] group back unless the group commits —
/// on an authoring error, a sink veto, or a panic — so a failed multi-layer edit
/// strands no layer with a half-applied overlay.
struct GroupEditGuard<'a, 'b> {
    layers: &'b mut [&'a mut Layer],
    committed: bool,
}

impl Drop for GroupEditGuard<'_, '_> {
    fn drop(&mut self) {
        if self.committed {
            return;
        }
        for layer in self.layers.iter_mut() {
            layer.rollback();
        }
    }
}

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

    /// Author through the layer's `edit` API and commit, for tests that build a
    /// layer's content or metadata directly.
    fn edit_layer(layer: &mut Layer, f: impl FnOnce(&mut LayerEdit<'_>)) {
        layer
            .edit(|e| {
                f(e);
                Ok(())
            })
            .expect("authored");
    }

    /// `new_anonymous` mints a unique `anon:<n>:<tag>` identifier each call, so
    /// two layers given the same tag never alias; `is_anonymous` recognizes them
    /// while a verbatim `new_in_memory` layer is not anonymous.
    #[test]
    fn anonymous_identifiers_unique() {
        let a = Layer::new_anonymous("scene.usda");
        let b = Layer::new_anonymous("scene.usda");
        assert_ne!(a.identifier(), b.identifier());
        assert!(a.identifier().ends_with(":scene.usda"));
        assert!(a.is_anonymous() && b.is_anonymous());
        assert!(!Layer::new_in_memory("scene.usda").is_anonymous());
    }

    /// `set_relocates` / `relocates` round-trip the authored pairs, and the
    /// pairs land under the pseudo-root's `layerRelocates` field.
    #[test]
    fn relocates_round_trip() {
        let mut layer = Layer::new_anonymous("test.usda");
        assert!(!layer.has_relocates());
        assert!(layer.relocates().is_empty());

        let pairs = vec![
            (Path::from("/Rig/Model"), Path::from("/Group/Model")),
            (Path::from("/Rig/Dead"), Path::from("")),
        ];
        edit_layer(&mut layer, |e| {
            e.set_relocates(pairs.clone()).unwrap();
        });

        assert!(layer.has_relocates());
        assert_eq!(layer.relocates(), pairs);
    }

    /// An explicit empty list is still an opinion (`HasRelocates` is true), while
    /// `clear_relocates` removes the opinion entirely.
    #[test]
    fn empty_opinion_vs_cleared() {
        let mut layer = Layer::new_anonymous("test.usda");

        edit_layer(&mut layer, |e| {
            e.set_relocates(RelocateList::new()).unwrap();
        });
        assert!(layer.has_relocates());
        assert!(layer.relocates().is_empty());

        edit_layer(&mut layer, |e| {
            e.clear_relocates().unwrap();
        });
        assert!(!layer.has_relocates());
        assert!(layer.relocates().is_empty());
    }

    /// The five time-code fields round-trip through set/get and report the
    /// documented unauthored defaults before any opinion is written.
    #[test]
    fn time_code_round_trip() {
        let mut layer = Layer::new_anonymous("test.usda");
        assert!(!layer.has_start_time_code());
        assert_eq!(layer.start_time_code(), 0.0);
        assert_eq!(layer.end_time_code(), 0.0);
        assert_eq!(layer.frame_precision(), 3);

        edit_layer(&mut layer, |e| {
            e.set_start_time_code(1.0).unwrap();
            e.set_end_time_code(48.0).unwrap();
            e.set_frame_precision(6).unwrap();
        });

        assert!(layer.has_start_time_code());
        assert_eq!(layer.start_time_code(), 1.0);
        assert_eq!(layer.end_time_code(), 48.0);
        assert_eq!(layer.frame_precision(), 6);
    }

    /// `timeCodesPerSecond` falls back to the authored `framesPerSecond`, then
    /// to `24.0`, when no `timeCodesPerSecond` opinion is authored.
    #[test]
    fn tcps_fps_fallback() {
        let mut layer = Layer::new_anonymous("test.usda");
        assert_eq!(layer.time_codes_per_second(), 24.0);
        assert_eq!(layer.frames_per_second(), 24.0);

        edit_layer(&mut layer, |e| {
            e.set_frames_per_second(30.0).unwrap();
        });
        assert_eq!(layer.time_codes_per_second(), 30.0);

        edit_layer(&mut layer, |e| {
            e.set_time_codes_per_second(48.0).unwrap();
        });
        assert_eq!(layer.time_codes_per_second(), 48.0);
    }

    /// `clear_*` removes the opinion so `has_*` reports false and the getter
    /// returns the unauthored default again.
    #[test]
    fn clear_time_code() {
        let mut layer = Layer::new_anonymous("test.usda");
        edit_layer(&mut layer, |e| {
            e.set_start_time_code(5.0).unwrap();
        });
        assert!(layer.has_start_time_code());

        edit_layer(&mut layer, |e| {
            e.clear_start_time_code().unwrap();
        });
        assert!(!layer.has_start_time_code());
        assert_eq!(layer.start_time_code(), 0.0);
    }

    /// `edit` commits the batch and returns the recorded `ChangeList`.
    #[test]
    fn edit_commits() {
        use crate::sdf::{PrimSpec, Specifier};
        let mut layer = Layer::new_anonymous("test.usda");
        let changed = layer
            .edit(|l| {
                PrimSpec::new(l.data_mut(), "/World", Specifier::Def, "Xform")?;
                Ok(())
            })
            .expect("no error or veto");
        assert!(changed);
        assert!(layer.prim(Path::from("/World")).is_some());
    }

    /// `edit` rolls the batch back when the closure returns an error, leaving the
    /// layer untouched and reusable.
    #[test]
    fn edit_rolls_back_on_error() {
        use crate::sdf::{PrimSpec, Specifier};
        let mut layer = Layer::new_anonymous("test.usda");
        let result: Result<bool, EditError> = layer.edit(|l| {
            PrimSpec::new(l.data_mut(), "/A", Specifier::Def, "Xform")?;
            Err(AuthoringError::InvalidPath {
                path: Path::abs_root(),
                reason: "test",
            })
        });
        assert!(result.is_err());
        assert!(layer.prim(Path::from("/A")).is_none(), "the staged edit rolled back");
        assert!(!layer.is_dirty());
    }

    /// A panic mid-`edit` unwinds cleanly: the guard rolls the staged edits back,
    /// so the layer is reusable afterwards.
    #[test]
    fn edit_recovers_on_panic() {
        use crate::sdf::{PrimSpec, Specifier};
        use std::panic::{catch_unwind, AssertUnwindSafe};

        let mut layer = Layer::new_anonymous("test.usda");
        let panicked = catch_unwind(AssertUnwindSafe(|| {
            let _: Result<bool, EditError> = layer.edit(|l| {
                PrimSpec::new(l.data_mut(), "/A", Specifier::Def, "Xform").expect("authored");
                panic!("boom");
            });
        }));
        assert!(panicked.is_err(), "the panic propagates");
        assert!(layer.prim(Path::from("/A")).is_none(), "the staged edit rolled back");
        assert!(!layer.is_dirty(), "no staged edits or recorded changes remain");

        // The layer is still usable afterwards.
        let changed = layer
            .edit(|l| {
                PrimSpec::new(l.data_mut(), "/B", Specifier::Def, "Xform")?;
                Ok(())
            })
            .expect("no error");
        assert!(changed);
        assert!(layer.prim(Path::from("/B")).is_some());
    }

    /// A panicking `after_commit` cannot strand a partially committed group:
    /// `edit_layers` commits every layer's data before notifying any sink, so both
    /// layers land even when one's `after_commit` unwinds.
    #[test]
    fn group_commit_atomic_on_panic() {
        use crate::sdf::{PrimSpec, Specifier};
        use std::panic::{catch_unwind, AssertUnwindSafe};

        let mut a = Layer::new_anonymous("a.usda");
        let mut b = Layer::new_anonymous("b.usda");
        a.add_sink(|_: &str, _: &ChangeList| panic!("boom"));

        let panicked = catch_unwind(AssertUnwindSafe(|| {
            let _ = edit_layers(&mut [&mut a, &mut b], |edits| {
                PrimSpec::new(edits[0].data_mut(), "/A", Specifier::Def, "Xform").expect("authored a");
                PrimSpec::new(edits[1].data_mut(), "/B", Specifier::Def, "Xform").expect("authored b");
                Ok::<(), EditError>(())
            });
        }));
        assert!(panicked.is_err(), "the after_commit panic propagates");
        assert!(
            a.prim(Path::from("/A")).is_some(),
            "layer a committed despite the panic"
        );
        assert!(
            b.prim(Path::from("/B")).is_some(),
            "layer b committed despite the panic"
        );
    }

    /// `discard_changes` keeps committed content in the backend and leaves the
    /// layer non-dirty, so a layer joining a stage is composed fresh with no stale
    /// change record.
    #[test]
    fn discard_changes_keeps_content() {
        use crate::sdf::{PrimSpec, Specifier};

        let mut layer = Layer::new_anonymous("test.usda");
        edit_layer(&mut layer, |e| {
            PrimSpec::new(e.data_mut(), "/World", Specifier::Def, "Xform").unwrap();
        });

        layer.discard_changes();
        assert!(!layer.is_dirty());
        assert!(
            layer.prim(Path::from("/World")).is_some(),
            "the authored content survives"
        );
    }

    /// Authoring layer metadata on a backend that lacks a pseudo-root spec
    /// materializes the pseudo-root, so a follow-up read sees the field; clearing
    /// the opinion removes it again.
    #[test]
    fn metadata_on_rootless_backend() {
        let root = Path::abs_root();
        let default_prim = FieldKey::DefaultPrim.as_str();

        let mut layer = Layer::new("rootless.usda", Box::new(Data::new()));
        edit_layer(&mut layer, |e| {
            e.set_default_prim("World").unwrap();
        });
        assert!(layer.data().has_field(&root, default_prim));

        edit_layer(&mut layer, |e| {
            e.clear_default_prim().unwrap();
        });
        assert!(!layer.data().has_field(&root, default_prim));
    }

    /// A recording [`LayerSink`] for the tests below.
    #[derive(Default)]
    struct Recorder {
        before: std::cell::Cell<u32>,
        after: std::cell::Cell<u32>,
        veto: bool,
    }

    impl LayerSink for std::rc::Rc<Recorder> {
        fn before_commit(&self, _change: &PendingLayerChange<'_>) -> Result<(), sink::Error> {
            self.before.set(self.before.get() + 1);
            if self.veto {
                return Err(sink::Error::new("vetoed"));
            }
            Ok(())
        }
        fn after_commit(&self, _layer: &str, _changes: &ChangeList) {
            self.after.set(self.after.get() + 1);
        }
    }

    /// A committed edit fires the layer sink's `before_commit` then
    /// `after_commit` once, with the edit landed.
    #[test]
    fn layer_sink_fires() {
        use crate::sdf::{PrimSpec, Specifier};
        let mut layer = Layer::new_anonymous("test.usda");
        let rec = std::rc::Rc::new(Recorder::default());
        layer.add_sink(rec.clone());

        layer
            .edit(|l| {
                PrimSpec::new(l.data_mut(), "/World", Specifier::Def, "Xform")?;
                Ok(())
            })
            .expect("sink accepts");

        assert_eq!((rec.before.get(), rec.after.get()), (1, 1));
        assert!(layer.prim(Path::from("/World")).is_some());
    }

    /// A `before_commit` rejection rolls the edit back: `after_commit` never
    /// fires and the backend is untouched.
    #[test]
    fn layer_sink_veto_rolls_back() {
        use crate::sdf::{PrimSpec, Specifier};
        let mut layer = Layer::new_anonymous("test.usda");
        let rec = std::rc::Rc::new(Recorder {
            veto: true,
            ..Default::default()
        });
        layer.add_sink(rec.clone());

        let result = layer.edit(|l| {
            PrimSpec::new(l.data_mut(), "/World", Specifier::Def, "Xform")?;
            Ok(())
        });
        assert!(matches!(result, Err(EditError::Rejected(_))), "the sink vetoes");

        assert_eq!((rec.before.get(), rec.after.get()), (1, 0), "after_commit never fired");
        assert!(layer.prim(Path::from("/World")).is_none(), "the edit rolled back");
        assert!(!layer.is_dirty());
    }

    /// A removed sink no longer fires.
    #[test]
    fn layer_sink_removed() {
        use crate::sdf::{PrimSpec, Specifier};
        let mut layer = Layer::new_anonymous("test.usda");
        let rec = std::rc::Rc::new(Recorder::default());
        let id = layer.add_sink(rec.clone());
        layer.remove_sink(id);

        layer
            .edit(|l| {
                PrimSpec::new(l.data_mut(), "/World", Specifier::Def, "Xform")?;
                Ok(())
            })
            .expect("no sink");
        assert_eq!((rec.before.get(), rec.after.get()), (0, 0));
    }

    #[test]
    fn export_dispatches_on_extension() -> Result<()> {
        use crate::sdf::{self, SpecType};

        let mut data = sdf::Data::new();
        let root = sdf::Path::abs_root();
        let ps = data.create_spec(root, SpecType::PseudoRoot);
        ps.add("primChildren", sdf::Value::TokenVec(vec!["Foo".into()]));
        let foo = sdf::path("/Foo")?;
        let sp = data.create_spec(foo, SpecType::Prim);
        sp.add("specifier", sdf::Value::Specifier(sdf::Specifier::Def));
        sp.add("typeName", sdf::Value::Token("Xform".into()));

        let layer = sdf::Layer::new("test://layer", Box::new(data));
        let dir = tempfile::tempdir()?;

        let usda_path = dir.path().join("layer-save.usda");
        let usdc_path = dir.path().join("layer-save.usdc");
        let usdz_path = dir.path().join("layer-save.usdz");

        layer.export(usda_path.to_str().unwrap())?;
        layer.export(usdc_path.to_str().unwrap())?;
        layer.export(usdz_path.to_str().unwrap())?;

        assert!(std::fs::metadata(&usda_path)?.len() > 0);
        assert!(std::fs::metadata(&usdc_path)?.len() > 0);
        assert!(std::fs::metadata(&usdz_path)?.len() > 0);

        // The usdz should contain an entry we can read back.
        let archive = crate::usdz::Archive::open(&usdz_path)?;
        let name = archive.first_layer_name().expect("usdz has a layer");
        assert!(name.ends_with(".usdc"));
        Ok(())
    }

    #[test]
    fn export_usd_writes_binary() -> Result<()> {
        use crate::sdf::{self, SpecType};

        let mut data = sdf::Data::new();
        let root = sdf::Path::abs_root();
        let ps = data.create_spec(root, SpecType::PseudoRoot);
        ps.add("primChildren", sdf::Value::TokenVec(vec!["Bar".into()]));
        let bar = sdf::path("/Bar")?;
        let sp = data.create_spec(bar.clone(), SpecType::Prim);
        sp.add("specifier", sdf::Value::Specifier(sdf::Specifier::Def));
        sp.add("typeName", sdf::Value::Token("Cube".into()));

        let layer = sdf::Layer::new("test://layer-usd", Box::new(data));
        let dir = tempfile::tempdir()?;
        let path = dir.path().join("layer-save.usd");
        layer.export(path.to_str().unwrap())?;

        // Writer chose binary for `.usd` — first bytes must be the USDC magic.
        let bytes = std::fs::read(&path)?;
        assert!(
            bytes.starts_with(crate::usdc::MAGIC),
            "writer should emit binary for .usd, got magic {:?}",
            &bytes[..crate::usdc::MAGIC.len().min(bytes.len())],
        );

        // The registry's content-sniff must accept it as binary.
        let round = sdf::LayerRegistry::default()
            .open(path.to_str().unwrap())?
            .expect("the layer opens");
        assert_eq!(round.spec_type(&bar), Some(SpecType::Prim));
        assert_eq!(
            round.get_field(&bar, "typeName").unwrap().into_owned(),
            sdf::Value::Token("Cube".into())
        );
        Ok(())
    }

    #[test]
    fn export_rejects_unknown_ext() {
        use crate::sdf::{self, SpecType};
        let mut data = sdf::Data::new();
        data.create_spec(sdf::Path::abs_root(), SpecType::PseudoRoot);
        let layer = sdf::Layer::new("test://layer", Box::new(data));
        let err = layer.export("/tmp/openusd-bad.xyz").unwrap_err();
        assert!(err.to_string().contains("unsupported"));
    }

    #[test]
    fn save_writes_identifier() -> Result<()> {
        use crate::sdf::{self, SpecType};

        let mut data = sdf::Data::new();
        data.create_spec(sdf::Path::abs_root(), SpecType::PseudoRoot);

        let dir = tempfile::tempdir()?;
        let path = dir.path().join("by-identifier.usda");
        let layer = sdf::Layer::new(path.to_str().unwrap(), Box::new(data));
        layer.save()?;

        let bytes = std::fs::read(&path)?;
        assert!(
            bytes.starts_with(b"#usda"),
            "save() should write text to a .usda identifier"
        );
        Ok(())
    }

    #[test]
    fn save_rejects_anonymous() {
        let layer = sdf::Layer::new_anonymous("scratch");
        let err = layer.save().unwrap_err();
        assert!(err.to_string().contains("anonymous"));
    }

    #[test]
    fn save_rejects_non_file_identifier() {
        use crate::sdf::{self, SpecType};
        let mut data = sdf::Data::new();
        data.create_spec(sdf::Path::abs_root(), SpecType::PseudoRoot);
        // A non-anonymous layer whose identifier is not an absolute file path
        // (a scheme-style asset identifier) cannot be saved to its identifier.
        let layer = sdf::Layer::new("scheme://host/x.usda", Box::new(data));
        let err = layer.save().unwrap_err();
        assert!(err.to_string().contains("absolute file path"));
    }

    #[test]
    fn save_rejects_usdz_in_place() {
        use crate::sdf::{self, SpecType};
        let mut data = sdf::Data::new();
        data.create_spec(sdf::Path::abs_root(), SpecType::PseudoRoot);
        // usdz is writable as a new copy but not editable in place: saving over
        // a package would discard its other assets, so save() must refuse it.
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("pkg.usdz");
        let layer = sdf::Layer::new(path.to_str().unwrap(), Box::new(data));
        let err = layer.save().unwrap_err();
        assert!(err.to_string().contains("not editable"));
    }

    #[test]
    fn export_to_string_is_usda() -> Result<()> {
        use crate::sdf::{self, SpecType};

        let mut data = sdf::Data::new();
        let ps = data.create_spec(sdf::Path::abs_root(), SpecType::PseudoRoot);
        ps.add("primChildren", sdf::Value::TokenVec(vec!["Foo".into()]));
        let sp = data.create_spec(sdf::path("/Foo")?, SpecType::Prim);
        sp.add("specifier", sdf::Value::Specifier(sdf::Specifier::Def));

        // A binary identifier must not influence the textual form.
        let layer = sdf::Layer::new("scratch.usdc", Box::new(data));
        let text = layer.export_to_string()?;
        assert!(text.starts_with("#usda"), "export_to_string must emit usda text");
        assert!(text.contains("\"Foo\""), "export_to_string must include the prim");
        Ok(())
    }

    // -----------------------------------------------------------------------
    // Authoring API
    // -----------------------------------------------------------------------

    #[test]
    fn create_prim_basic() -> Result<()> {
        let mut layer = sdf::Layer::new_anonymous("anon.usda");
        edit_layer(&mut layer, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/World", sdf::Specifier::Def, "Xform")
                .unwrap()
                .set_kind("group");
        });

        let world = layer.prim("/World").expect("prim authored");
        assert_eq!(world.type_name().as_deref(), Some("Xform"));
        assert_eq!(world.specifier(), Some(sdf::Specifier::Def));
        assert_eq!(world.kind().as_deref(), Some("group"));
        Ok(())
    }

    #[test]
    fn auto_ancestor_chain() -> Result<()> {
        let mut layer = sdf::Layer::new_anonymous("anon.usda");
        edit_layer(&mut layer, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/A/B/C", sdf::Specifier::Def, "Mesh").unwrap();
        });

        // Leaf is Def; ancestors are Over.
        assert_eq!(
            layer.prim("/A/B/C").and_then(|p| p.specifier()),
            Some(sdf::Specifier::Def)
        );
        assert_eq!(
            layer.prim("/A/B").and_then(|p| p.specifier()),
            Some(sdf::Specifier::Over)
        );
        assert_eq!(layer.prim("/A").and_then(|p| p.specifier()), Some(sdf::Specifier::Over));
        Ok(())
    }

    #[test]
    fn prim_children() -> Result<()> {
        let mut layer = sdf::Layer::new_anonymous("anon.usda");
        edit_layer(&mut layer, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/World", sdf::Specifier::Def, "Xform").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/World/Mesh", sdf::Specifier::Def, "Mesh").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/World/Cube", sdf::Specifier::Def, "Cube").unwrap();
        });

        let root = layer.pseudo_root().expect("pseudo-root present");
        let root_children = root.prim_children().unwrap();
        let root_children: Vec<&str> = root_children.iter().map(|t| t.as_str()).collect();
        assert_eq!(root_children, ["World"]);

        let world = layer.prim("/World").expect("prim");
        let world_children = world.prim_children().unwrap();
        let world_children: Vec<&str> = world_children.iter().map(|t| t.as_str()).collect();
        assert_eq!(world_children, ["Mesh", "Cube"]);
        Ok(())
    }

    #[test]
    fn property_children() -> Result<()> {
        let mut layer = sdf::Layer::new_anonymous("anon.usda");
        edit_layer(&mut layer, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Mesh", sdf::Specifier::Def, "Mesh").unwrap();
            sdf::AttributeSpec::new(
                e.data_mut(),
                "/Mesh.points",
                "point3f[]",
                sdf::Variability::Varying,
                false,
            )
            .unwrap();
            sdf::AttributeSpec::new(
                e.data_mut(),
                "/Mesh.normals",
                "normal3f[]",
                sdf::Variability::Varying,
                false,
            )
            .unwrap();
            sdf::RelationshipSpec::new(e.data_mut(), "/Mesh.material:binding", sdf::Variability::Varying, false)
                .unwrap();
        });

        let mesh = layer.prim("/Mesh").expect("prim");
        let props = mesh.property_children().unwrap();
        let props: Vec<&str> = props.iter().map(|t| t.as_str()).collect();
        assert_eq!(props, ["points", "normals", "material:binding"]);
        Ok(())
    }

    #[test]
    fn relationship_variability() -> Result<()> {
        let mut layer = sdf::Layer::new_anonymous("anon.usda");
        edit_layer(&mut layer, |e| {
            sdf::RelationshipSpec::new(e.data_mut(), "/Mesh.material:binding", sdf::Variability::Uniform, false)
                .unwrap();
        });

        let rel = layer.relationship("/Mesh.material:binding").expect("relationship");
        assert_eq!(rel.variability(), sdf::Variability::Uniform);

        edit_layer(&mut layer, |e| {
            sdf::RelationshipSpec::new(e.data_mut(), "/Mesh.material:binding", sdf::Variability::Varying, false)
                .unwrap();
        });
        let rel = layer.relationship("/Mesh.material:binding").expect("relationship");
        assert_eq!(rel.variability(), sdf::Variability::Varying);
        assert!(rel.field(sdf::FieldKey::Variability.as_str()).ok().flatten().is_none());
        Ok(())
    }

    #[test]
    fn bad_prim_children_errors() {
        let mut layer = sdf::Layer::new_anonymous("anon.usda");
        edit_layer(&mut layer, |e| {
            e.data_mut().set_field(
                &sdf::Path::abs_root(),
                sdf::ChildrenKey::PrimChildren.as_str(),
                sdf::Value::String("bad".into()),
            );
        });

        let err = layer
            .edit(|e| {
                sdf::PrimSpec::new(e.data_mut(), "/A", sdf::Specifier::Def, "Xform")?;
                Ok(())
            })
            .unwrap_err();
        assert!(matches!(
            err,
            sdf::EditError::Author(sdf::AuthoringError::InvalidPath { .. })
        ));

        let value = layer
            .data()
            .get_field(&sdf::Path::abs_root(), sdf::ChildrenKey::PrimChildren.as_str())
            .unwrap()
            .into_owned();
        assert!(matches!(value, sdf::Value::String(value) if value == "bad"));
    }

    #[test]
    fn bad_property_children_errors() -> Result<()> {
        let mut layer = sdf::Layer::new_anonymous("anon.usda");
        edit_layer(&mut layer, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Mesh", sdf::Specifier::Def, "Mesh").unwrap();
            e.data_mut().set_field(
                &sdf::path("/Mesh").unwrap(),
                sdf::ChildrenKey::PropertyChildren.as_str(),
                sdf::Value::String("bad".into()),
            );
        });

        let err = layer
            .edit(|e| {
                sdf::RelationshipSpec::new(e.data_mut(), "/Mesh.material:binding", sdf::Variability::Varying, false)?;
                Ok(())
            })
            .unwrap_err();
        assert!(matches!(
            err,
            sdf::EditError::Author(sdf::AuthoringError::InvalidPath { .. })
        ));

        assert!(!layer.data().has_spec(&sdf::path("/Mesh.material:binding").unwrap()));
        let value = layer
            .data()
            .get_field(
                &sdf::path("/Mesh").unwrap(),
                sdf::ChildrenKey::PropertyChildren.as_str(),
            )
            .unwrap()
            .into_owned();
        assert!(matches!(value, sdf::Value::String(value) if value == "bad"));
        Ok(())
    }

    #[test]
    fn attr_samples() -> Result<()> {
        let mut layer = sdf::Layer::new_anonymous("anon.usda");
        edit_layer(&mut layer, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Sphere", sdf::Specifier::Def, "Sphere").unwrap();
            let mut radius = sdf::AttributeSpec::new(
                e.data_mut(),
                "/Sphere.radius",
                "double",
                sdf::Variability::Varying,
                false,
            )
            .unwrap();
            radius.set_default(sdf::Value::Double(2.5));
            radius.set_time_sample(0.0, sdf::Value::Double(1.0));
            radius.set_time_sample(10.0, sdf::Value::Double(3.0));
            // Out-of-order insert lands in sorted position.
            radius.set_time_sample(5.0, sdf::Value::Double(2.0));
        });

        let read = layer.attribute("/Sphere.radius").expect("attr");
        assert_eq!(read.type_name().as_deref(), Some("double"));
        assert_eq!(read.default(), Some(sdf::Value::Double(2.5)));
        let samples = read.time_samples().expect("samples authored");
        let times: Vec<f64> = samples.iter().map(|(t, _)| *t).collect();
        assert_eq!(times, vec![0.0, 5.0, 10.0]);
        Ok(())
    }

    #[test]
    fn wrong_ancestor_type() {
        let mut layer = sdf::Layer::new_anonymous("anon.usda");
        // Plant a non-Prim spec at a prim-shaped path through the data API.
        edit_layer(&mut layer, |e| {
            e.data_mut()
                .create_spec(sdf::path("/A").unwrap(), sdf::SpecType::Attribute);
        });

        let err = layer
            .edit(|e| {
                sdf::PrimSpec::new(e.data_mut(), "/A/B", sdf::Specifier::Def, "Xform")?;
                Ok(())
            })
            .unwrap_err();
        assert!(matches!(
            err,
            sdf::EditError::Author(sdf::AuthoringError::InvalidPath { .. })
        ));
        let err = layer
            .edit(|e| {
                sdf::AttributeSpec::new(e.data_mut(), "/A.x", "double", sdf::Variability::Varying, false)?;
                Ok(())
            })
            .unwrap_err();
        assert!(matches!(
            err,
            sdf::EditError::Author(sdf::AuthoringError::InvalidPath { .. })
        ));
    }

    #[test]
    fn failed_prim_chain_creation_is_atomic() {
        let mut layer = sdf::Layer::new_anonymous("anon.usda");
        let bad_child = sdf::path("/A/B").unwrap();
        edit_layer(&mut layer, |e| {
            e.data_mut().create_spec(bad_child, sdf::SpecType::Attribute);
        });

        let err = layer
            .edit(|e| {
                sdf::PrimSpec::new(e.data_mut(), "/A/B", sdf::Specifier::Def, "Xform")?;
                Ok(())
            })
            .unwrap_err();
        assert!(matches!(
            err,
            sdf::EditError::Author(sdf::AuthoringError::InvalidPath { .. })
        ));

        assert!(!layer.data().has_spec(&sdf::path("/A").unwrap()));
        assert!(layer
            .data()
            .try_field(&sdf::Path::abs_root(), sdf::ChildrenKey::PrimChildren.as_str())
            .unwrap()
            .is_none());
    }

    #[test]
    fn nan_time_sample() -> Result<()> {
        let mut layer = sdf::Layer::new_anonymous("anon.usda");
        edit_layer(&mut layer, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Sphere", sdf::Specifier::Def, "Sphere").unwrap();
            let mut r = sdf::AttributeSpec::new(
                e.data_mut(),
                "/Sphere.radius",
                "double",
                sdf::Variability::Varying,
                false,
            )
            .unwrap();
            r.set_time_sample(1.0, sdf::Value::Double(1.0));
            r.set_time_sample(f64::NAN, sdf::Value::Double(99.0));
            r.set_time_sample(2.0, sdf::Value::Double(2.0));
        });
        // NaN does not collide with finite samples — both finite values survive.
        let samples = layer
            .attribute("/Sphere.radius")
            .unwrap()
            .time_samples()
            .unwrap()
            .to_vec();
        let finite: Vec<f64> = samples.iter().map(|(t, _)| *t).filter(|t| t.is_finite()).collect();
        assert_eq!(finite, vec![1.0, 2.0]);

        // erase_time_sample(NaN) can find the NaN entry via total_cmp.
        let mut erased = false;
        edit_layer(&mut layer, |e| {
            erased = e.attribute_mut("/Sphere.radius").unwrap().erase_time_sample(f64::NAN);
        });
        assert!(erased);
        let times: Vec<f64> = layer
            .attribute("/Sphere.radius")
            .unwrap()
            .time_samples()
            .unwrap()
            .iter()
            .map(|(t, _)| *t)
            .collect();
        assert_eq!(times, vec![1.0, 2.0]);
        Ok(())
    }

    #[test]
    fn override_prim() -> Result<()> {
        let mut layer = sdf::Layer::new_anonymous("anon.usda");
        edit_layer(&mut layer, |e| {
            sdf::PrimSpec::over(e.data_mut(), "/A/B").unwrap();
        });

        assert_eq!(layer.prim("/A").and_then(|p| p.specifier()), Some(sdf::Specifier::Over));
        assert_eq!(
            layer.prim("/A/B").and_then(|p| p.specifier()),
            Some(sdf::Specifier::Over)
        );

        // override_prim on an existing def leaves the specifier untouched.
        edit_layer(&mut layer, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Defined", sdf::Specifier::Def, "Xform").unwrap();
            sdf::PrimSpec::over(e.data_mut(), "/Defined").unwrap();
        });
        assert_eq!(
            layer.prim("/Defined").and_then(|p| p.specifier()),
            Some(sdf::Specifier::Def)
        );
        Ok(())
    }

    #[test]
    fn pseudo_root_metadata() -> Result<()> {
        let mut layer = sdf::Layer::new_anonymous("anon.usda");
        edit_layer(&mut layer, |e| {
            let mut root = e.pseudo_root_mut().expect("writable");
            root.set_default_prim("World");
            root.set_documentation("auto-generated");
            root.set_start_time_code(1.0);
            root.set_end_time_code(24.0);
            root.add_sublayer("./over.usda");
            root.add_sublayer("./over.usda");
        });
        let root = layer.pseudo_root().expect("present");
        assert_eq!(root.default_prim().as_deref(), Some("World"));
        assert_eq!(root.documentation().as_deref(), Some("auto-generated"));
        assert_eq!(root.start_time_code(), Some(1.0));
        assert_eq!(root.end_time_code(), Some(24.0));
        assert_eq!(
            root.sublayers(),
            Some(vec!["./over.usda".to_string(), "./over.usda".to_string()])
        );
        Ok(())
    }

    #[test]
    fn invalid_paths() {
        let mut layer = sdf::Layer::new_anonymous("anon.usda");
        // Whether authoring `f` fails with an `InvalidPath` authoring error.
        fn invalid(
            layer: &mut sdf::Layer,
            f: impl FnOnce(&mut sdf::LayerEdit<'_>) -> Result<(), sdf::AuthoringError>,
        ) -> bool {
            matches!(
                layer.edit(f).unwrap_err(),
                sdf::EditError::Author(sdf::AuthoringError::InvalidPath { .. })
            )
        }
        assert!(invalid(&mut layer, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/", sdf::Specifier::Def, "Xform")?;
            Ok(())
        }));
        assert!(invalid(&mut layer, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/A.foo", sdf::Specifier::Def, "Xform")?;
            Ok(())
        }));
        assert!(invalid(&mut layer, |e| {
            sdf::AttributeSpec::new(e.data_mut(), "/A", "double", sdf::Variability::Varying, false)?;
            Ok(())
        }));
        // Relative property paths must error, not panic in ensure_prim_chain.
        assert!(invalid(&mut layer, |e| {
            sdf::AttributeSpec::new(e.data_mut(), "A.foo", "double", sdf::Variability::Varying, false)?;
            Ok(())
        }));
        assert!(invalid(&mut layer, |e| {
            sdf::RelationshipSpec::new(e.data_mut(), "A.foo", sdf::Variability::Varying, false)?;
            Ok(())
        }));
        // Root-level property paths (`/.foo`) must also error, not panic.
        assert!(invalid(&mut layer, |e| {
            sdf::AttributeSpec::new(e.data_mut(), "/.foo", "double", sdf::Variability::Varying, false)?;
            Ok(())
        }));
        // Target-bracket property paths slip past `is_property_path` because the
        // tail after the last `.` is alphanumeric — split_property_path must reject them.
        assert!(invalid(&mut layer, |e| {
            sdf::AttributeSpec::new(
                e.data_mut(),
                "/A.rel[/Target].attr",
                "double",
                sdf::Variability::Varying,
                false,
            )?;
            Ok(())
        }));
        // Well-formed variant selections are authorable (they build the variant
        // set / variant scaffolding), but malformed ones — here an empty
        // selection — must still be rejected.
        assert!(invalid(&mut layer, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/A{x=}child", sdf::Specifier::Def, "Xform")?;
            Ok(())
        }));
    }

    /// Authoring a prim inside a variant builds the full variant set / variant
    /// scaffolding with correct spec types and child registration.
    #[test]
    fn variant_authoring() -> Result<()> {
        let mut layer = sdf::Layer::new_anonymous("variants.usda");
        edit_layer(&mut layer, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Prim", sdf::Specifier::Def, "Xform").unwrap();
            sdf::PrimSpec::new(e.data_mut(), "/Prim{set=sel}child", sdf::Specifier::Def, "Scope").unwrap();
        });

        assert_eq!(layer.data().spec_type(&sdf::path("/Prim")?), Some(sdf::SpecType::Prim));
        assert_eq!(
            layer.data().spec_type(&sdf::path("/Prim{set=}")?),
            Some(sdf::SpecType::VariantSet)
        );
        assert_eq!(
            layer.data().spec_type(&sdf::path("/Prim{set=sel}")?),
            Some(sdf::SpecType::Variant)
        );
        assert_eq!(
            layer.data().spec_type(&sdf::path("/Prim{set=sel}child")?),
            Some(sdf::SpecType::Prim)
        );

        let token_vec = |path: &str, key: sdf::ChildrenKey| -> Result<Vec<String>> {
            match layer.data().get_field(&sdf::path(path)?, key.as_str())?.into_owned() {
                sdf::Value::TokenVec(v) => Ok(v.into_iter().map(Into::into).collect()),
                other => panic!("expected TokenVec at {path}, got {other:?}"),
            }
        };
        assert_eq!(token_vec("/Prim", sdf::ChildrenKey::VariantSetChildren)?, vec!["set"]);
        assert_eq!(
            token_vec("/Prim{set=}", sdf::ChildrenKey::VariantChildren)?,
            vec!["sel"]
        );
        assert_eq!(
            token_vec("/Prim{set=sel}", sdf::ChildrenKey::PrimChildren)?,
            vec!["child"]
        );
        Ok(())
    }

    /// A bare variant-selection leaf isn't a prim, so prim authoring rejects it
    /// (rather than panicking on the `PrimSpecMut` downcast or writing prim
    /// fields onto the variant spec).
    #[test]
    fn prim_authoring_rejects_variant_leaf() -> Result<()> {
        let mut layer = sdf::Layer::new_anonymous("variants.usda");
        edit_layer(&mut layer, |e| {
            sdf::PrimSpec::new(e.data_mut(), "/Prim", sdf::Specifier::Def, "Xform").unwrap();
        });
        assert!(matches!(
            layer
                .edit(|e| {
                    sdf::PrimSpec::new(e.data_mut(), "/Prim{set=sel}", sdf::Specifier::Def, "Xform")?;
                    Ok(())
                })
                .unwrap_err(),
            sdf::EditError::Author(sdf::AuthoringError::InvalidPath { .. })
        ));
        assert!(matches!(
            layer
                .edit(|e| {
                    sdf::PrimSpec::over(e.data_mut(), "/Prim{set=sel}")?;
                    Ok(())
                })
                .unwrap_err(),
            sdf::EditError::Author(sdf::AuthoringError::InvalidPath { .. })
        ));
        // The rejected calls must not have authored a variant spec.
        assert_eq!(layer.data().spec_type(&sdf::path("/Prim{set=sel}")?), None);
        Ok(())
    }

    #[test]
    fn usda_roundtrip() -> Result<()> {
        let mut layer = sdf::Layer::new_anonymous("scene.usda");
        let material = sdf::path("/World/Material")?;
        edit_layer(&mut layer, |e| {
            e.pseudo_root_mut().unwrap().set_default_prim("World");
            sdf::PrimSpec::new(e.data_mut(), "/World", sdf::Specifier::Def, "Xform").unwrap();
            let mut sphere = sdf::PrimSpec::new(e.data_mut(), "/World/Sphere", sdf::Specifier::Def, "Sphere").unwrap();
            sphere.set_kind("component");
            let mut radius = sdf::AttributeSpec::new(
                e.data_mut(),
                "/World/Sphere.radius",
                "double",
                sdf::Variability::Varying,
                false,
            )
            .unwrap();
            radius.set_default(sdf::Value::Double(1.5));
            sdf::PrimSpec::new(e.data_mut(), &material, sdf::Specifier::Def, "Material").unwrap();
            let mut binding = sdf::RelationshipSpec::new(
                e.data_mut(),
                "/World/Sphere.material:binding",
                sdf::Variability::Varying,
                false,
            )
            .unwrap();
            binding.add_target(material.clone());
            let mut surface = sdf::AttributeSpec::new(
                e.data_mut(),
                "/World/Sphere.inputs:surface",
                "token",
                sdf::Variability::Varying,
                false,
            )
            .unwrap();
            surface.set_connection_paths([sdf::path("/World/Material.outputs:surface").unwrap()]);
        });

        let tmp = std::env::temp_dir().join("openusd_authoring_roundtrip.usda");
        layer.export(tmp.to_str().unwrap())?;

        let parsed = usda::read_file(&tmp)?;
        assert_eq!(parsed.spec_type(&sdf::path("/World")?), Some(sdf::SpecType::Prim));
        assert_eq!(
            parsed.spec_type(&sdf::path("/World/Sphere")?),
            Some(sdf::SpecType::Prim)
        );
        assert_eq!(
            parsed.spec_type(&sdf::path("/World/Sphere.radius")?),
            Some(sdf::SpecType::Attribute)
        );
        assert_eq!(
            parsed
                .get_field(&sdf::Path::abs_root(), sdf::FieldKey::DefaultPrim.as_str())?
                .into_owned(),
            sdf::Value::Token("World".into())
        );
        let targets = parsed
            .get_field(
                &sdf::path("/World/Sphere.material:binding")?,
                sdf::FieldKey::TargetPaths.as_str(),
            )?
            .into_owned()
            .try_as_path_list_op()
            .expect("relationship targets as PathListOp");
        assert!(targets.explicit);
        assert_eq!(targets.explicit_items, vec![material]);
        let connections = parsed
            .get_field(
                &sdf::path("/World/Sphere.inputs:surface")?,
                sdf::FieldKey::ConnectionPaths.as_str(),
            )?
            .into_owned()
            .try_as_path_list_op()
            .expect("connection paths as PathListOp");
        assert!(connections.explicit);
        assert_eq!(
            connections.explicit_items,
            vec![sdf::path("/World/Material.outputs:surface")?]
        );
        let _ = std::fs::remove_file(&tmp);
        Ok(())
    }
}