openusd 0.7.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
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
//! Value clips (spec 12.3.4): the explicit clip-set metadata model, the
//! stage-to-clip time mapping, and the value resolution that reads them during
//! attribute composition (the [`ClipCache`] entity, C++ `Usd_Clips`).
//!
//! A clip set is a named group of value clips that partition an attribute's
//! time samples across external clip layers. The set is described by a
//! dictionary-valued `clips` metadata field; the `clipSets` field orders the
//! sets by strength. Only the explicit form is modelled here — template clips
//! (spec 12.3.4.1.3) are resolved to explicit metadata elsewhere and are not
//! parsed by [`ClipSet::parse`].
//!
//! Which attributes a set sources is decided by its manifest (spec
//! 12.3.4.1.1.2). A set that authors no `manifestAssetPath` gets one
//! synthesized from its clips by [`clip_manifest`](super::clip_manifest), so
//! resolution has a single rule for every set.
//!
//! A `` `${VAR}` `` in `assetPaths`, `templateAssetPath` or `manifestAssetPath`
//! is evaluated before a set is parsed, so those fields arrive carrying an
//! evaluated path ([`sdf::AssetPath::asset_path`]). C++ does not do this —
//! `clipSetDefinition.cpp` reads the three raw, and
//! `UsdStage::_MakeResolvedAssetPaths` never descends into a `VtDictionary` —
//! but the Sdf variable-expression documentation promises support in
//! asset-valued metadata, which these are. `PrimIndex::resolve_clip_sets` runs
//! the evaluation and carries the same note.

use std::collections::{HashMap, HashSet};

use crate::gf;
use crate::sdf::schema::FieldKey;
use crate::sdf::{self, AssetPath, LayerOffset, Path, Value};
use crate::tf;

use super::asset_resolve::{self, AssetSite};
use super::clip_manifest::{self, ClipSetKey};
use super::diagnostics::Diagnostics;
use super::index_cache::block_to_none;
use super::layer_graph::LayerGraph;
use super::prim_graph::Node;
use super::value_resolve::ValueState;
use super::{ClipLoad, CompositionDiagnostic, LayerId, LayerStackId, QueryError};

/// Dictionary keys inside a single clip set's metadata (spec 12.3.4.1).
pub(crate) mod keys {
    /// Ordered asset paths to the clips holding time-varying data (explicit).
    pub const ASSET_PATHS: &str = "assetPaths";
    /// Asset path of the layer indexing the attributes carried by the clips.
    pub const MANIFEST_ASSET_PATH: &str = "manifestAssetPath";
    /// Prim path substituted for the stage prim's path when querying clips.
    pub const PRIM_PATH: &str = "primPath";
    /// `(stageTime, assetIndex)` pairs selecting the active clip over time.
    pub const ACTIVE: &str = "active";
    /// `(stageTime, clipTime)` pairs forming the stage-to-clip timing curve.
    pub const TIMES: &str = "times";
    /// `bool` — interpolate across surrounding clips for an attribute whose
    /// active clip has a gap, instead of falling to the manifest default
    /// (spec 12.3.4.6-7).
    pub const INTERPOLATE_MISSING: &str = "interpolateMissingClipValues";

    // ── Template clip keys (spec 12.3.4.1.3) ──────────────────────────────
    /// `#`-pattern asset path expanded into explicit `assetPaths`.
    pub const TEMPLATE_ASSET_PATH: &str = "templateAssetPath";
    /// Inclusive start of the time range searched for template clips.
    pub const TEMPLATE_START_TIME: &str = "templateStartTime";
    /// Inclusive end of the time range searched for template clips.
    pub const TEMPLATE_END_TIME: &str = "templateEndTime";
    /// Step between successive template clip times.
    pub const TEMPLATE_STRIDE: &str = "templateStride";
    /// Offset applied to each clip's active stage time.
    pub const TEMPLATE_ACTIVE_OFFSET: &str = "templateActiveOffset";
}

/// The fields whose presence makes a prim author value-clip metadata.
///
/// Read both by the cached answer
/// ([`PrimIndex::authors_clips`](super::PrimIndex::authors_clips)) and by the
/// change classifier that invalidates it, so the two cannot name different
/// fields.
pub(crate) const CLIP_FIELDS: [FieldKey; 2] = [FieldKey::Clips, FieldKey::ClipSets];

/// Whether `field` is one of [`CLIP_FIELDS`].
///
/// Authoring or removing one forces a prim-index rebuild, where changing its
/// value in place does not: the cached answer records only that the metadata
/// exists, and what it holds is composed live on each clip query. C++
/// `Pcp_EntryRequiresPrimIndexChange` draws the same line for `clips` by testing
/// whether either side of the edit is empty; `clipSets` joins it here because
/// the cached answer reads both, so that field appearing on a prim with no
/// `clips` still flips it.
pub(crate) fn is_clip_field(field: &str) -> bool {
    CLIP_FIELDS.iter().any(|key| key.as_str() == field)
}

/// A single explicit clip set: a named group of value clips with sequencing
/// and timing metadata (spec 12.3.4.1).
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct ClipSet {
    /// Clip set name — the key in the `clips` dictionary.
    pub name: String,
    /// Prim path substituted for the stage prim's path when querying clip
    /// layers (spec 12.3.4.1.1.1). `None` means use the stage prim's own path.
    pub prim_path: Option<Path>,
    /// Asset path of the manifest layer (spec 12.3.4.1.1.2), if authored.
    pub manifest_asset: Option<String>,
    /// Ordered clip asset paths holding time-varying data (an `asset[]`,
    /// C++ `VtArray<SdfAssetPath>`).
    pub asset_paths: Vec<AssetPath>,
    /// `(stageTime, assetIndex)` pairs, sorted by stage time. Each entry marks
    /// the clip active from its stage time up to the next entry (spec 12.3.4.3).
    pub active: Vec<(f64, usize)>,
    /// `(stageTime, clipTime)` knots (`gf::Vec2d`), sorted by stage time,
    /// forming the timing curve (spec 12.3.4.4). Duplicate stage times encode
    /// jump discontinuities (spec 12.3.4.8).
    pub times: Vec<gf::Vec2d>,
    /// When `true`, a gap in the active clip is filled by interpolating across
    /// the nearest surrounding clips rather than by the manifest default
    /// (spec 12.3.4.6-7).
    pub interpolate_missing: bool,
}

/// A parsed clip set plus the site that introduced it.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct ResolvedClipSet {
    pub set: ClipSet,
    pub source: ClipAnchor,
    pub manifest_layer: Option<LayerId>,
    /// Offset of the node that authored `active`, already applied to the set's
    /// schedule. A manifest is read straight off its layer, so this maps its
    /// authored times into the same stage frame the schedule now uses.
    pub active_offset: LayerOffset,
}

impl ResolvedClipSet {
    /// This set's identity as composed on `anchor`.
    pub(super) fn key(&self, anchor: &Path) -> ClipSetKey {
        ClipSetKey {
            prim: anchor.clone(),
            clip_set: self.set.name.clone(),
        }
    }

    /// Whether `other` resolves to the same clips this set does, so anything
    /// derived from it stays good.
    ///
    /// Authored identity is not enough on its own: `AssetPath` equality compares
    /// the authored path alone, so two sets whose expressions evaluate to
    /// different clips compare equal. The paths the clips are actually opened
    /// through settle it. Deliberately cheap — no asset path is resolved to an
    /// identifier — because value resolution asks this on every clipped
    /// attribute read.
    pub(super) fn same_resolution(&self, other: &Self) -> bool {
        self == other && self.set.resolution_paths().eq(other.set.resolution_paths())
    }
}

/// The site a clip set was introduced at: the strongest opinion on its clip
/// asset paths, which is what C++ anchors a set to (`Usd_ClipSetDefinition`'s
/// `sourceLayerStack` / `sourcePrimPath` /
/// `indexOfLayerWhereAssetPathsFound`). A set whose remaining fields come from
/// weaker layers is still introduced here.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct ClipAnchor {
    /// The layer that authored the asset paths (C++ `sourceLayer`): both the
    /// anchor a relative clip path resolves against and the layer value
    /// resolution consults the set at.
    pub layer: LayerId,
    /// The prim path, in [`stack`](Self::stack)'s namespace, the set was
    /// authored on.
    pub prim_path: Path,
    /// Layer stack of the node that introduced the set, whose composed
    /// `expressionVariables` every value the set sources evaluates against —
    /// the clips' and the manifest's alike, since one set has one introducing
    /// node. Neither layer belongs to a stack of its own.
    pub stack: LayerStackId,
}

impl ClipAnchor {
    /// Whether a set introduced here is consulted at the `(node, layer)` site
    /// value resolution has reached: C++ `_ClipsApplyToNode` — the node's own
    /// stack and a prim path at or under the anchor's — together with the
    /// `sourceLayer` test its caller applies per layer.
    pub(super) fn applies_at(&self, node: &Node, layer: LayerId) -> bool {
        self.layer == layer && node.layer_stack_id() == self.stack && node.path().has_prefix(&self.prim_path)
    }
}

impl ClipSet {
    /// The path each clip is opened through: the evaluated form where a
    /// `` `${VAR}` `` was substituted, else the authored one. Distinct from the
    /// set's `PartialEq`, which is authored identity.
    pub(super) fn resolution_paths(&self) -> impl Iterator<Item = &str> {
        self.asset_paths.iter().map(AssetPath::asset_path)
    }

    /// Parses every explicit clip set from a composed `clips` dictionary value.
    ///
    /// `clip_sets_order` is the resolved `clipSets` field, when authored: it
    /// orders the returned sets strongest-first. Without it, sets are returned
    /// sorted by name for determinism. Sets lacking explicit `assetPaths`
    /// (e.g. template-only sets) are skipped.
    pub(crate) fn parse(clips: &Value, clip_sets_order: Option<&[String]>) -> Vec<ClipSet> {
        let Value::Dictionary(sets) = clips else {
            return Vec::new();
        };

        effective_set_names(sets, clip_sets_order)
            .into_iter()
            .filter_map(|name| match sets.get(name) {
                Some(Value::Dictionary(set)) => Self::parse_set(name, set),
                _ => None,
            })
            .collect()
    }

    /// Parses a single clip set from its metadata dictionary. Returns `None`
    /// when the set declares neither explicit `assetPaths` nor a usable
    /// `templateAssetPath`.
    ///
    /// Template sets (spec 12.3.4.1.3) authoring `templateAssetPath` +
    /// `templateStartTime` / `templateEndTime` / `templateStride` (and
    /// optionally `templateActiveOffset`) are expanded here into the explicit
    /// `assetPaths` / `active` / `times` form before resolution, so the rest
    /// of the pipeline only ever sees explicit clip sets. Explicit
    /// `assetPaths`, when authored, take precedence over the template form.
    fn parse_set(name: &str, set: &HashMap<String, Value>) -> Option<ClipSet> {
        let prim_path = set
            .get(keys::PRIM_PATH)
            .and_then(Value::as_str)
            .and_then(|s| Path::new(s).ok());
        let manifest_asset = asset_input(set, keys::MANIFEST_ASSET_PATH).map(str::to_owned);

        // Explicit form wins; otherwise expand a template set — see
        // [`explicit_asset_paths`]. `active` / `times` are a strict `double2[]`,
        // so each extracts through `get` (exact `TryFrom`) rather than `cast`.
        let (asset_paths, active, times) = match explicit_asset_paths(set) {
            Some(asset_paths) => {
                // A malformed activation makes the whole schedule untrustworthy,
                // so the set is rejected rather than partly resolved (C++
                // `Usd_ClipSetDefinition` validation).
                let mut active: Vec<(f64, usize)> = get::<Vec<gf::Vec2d>>(set, keys::ACTIVE)
                    .unwrap_or_default()
                    .into_iter()
                    .map(|p| Some((p.x.is_finite().then_some(p.x)?, clip_index(p.y)?)))
                    .collect::<Option<_>>()?;
                active.sort_by(|a, b| a.0.total_cmp(&b.0));

                let mut times = get::<Vec<gf::Vec2d>>(set, keys::TIMES).unwrap_or_default();
                // A non-finite knot has no place on the timing curve, and would
                // also defeat every later equality test on the set.
                if times.iter().any(|k| !k.x.is_finite() || !k.y.is_finite()) {
                    return None;
                }
                times.sort_by(|a, b| a.x.total_cmp(&b.x));
                (asset_paths, active, times)
            }
            None => expand_template(set)?,
        };

        let interpolate_missing = get::<bool>(set, keys::INTERPOLATE_MISSING).unwrap_or(false);

        // An activation naming an index no `assetPaths` entry has cannot select a
        // clip. Dropping just that entry would silently widen the preceding
        // clip's window over a span the author scheduled something else for, so
        // the set is rejected whole, as C++ does.
        if active.iter().any(|&(_, index)| index >= asset_paths.len()) {
            return None;
        }

        Some(ClipSet {
            name: name.to_string(),
            prim_path,
            manifest_asset,
            asset_paths,
            active,
            times,
            interpolate_missing,
        })
    }

    /// The prim path this set's clips are queried under: its own `primPath`
    /// when authored, else `anchor`, the prim the metadata is composed on
    /// (spec 12.3.4.1.1.1).
    pub(crate) fn clip_prim_path(&self, anchor: &Path) -> Path {
        self.prim_path.clone().unwrap_or_else(|| anchor.clone())
    }

    /// Returns the `active` entry — its activation stage time and index into
    /// [`Self::asset_paths`] — selecting the clip active at `stage_time` (spec
    /// 12.3.4.3). The first entry is active for all earlier times and the last
    /// entry for all later times. Returns `None` when no `active` entries are
    /// authored.
    pub(crate) fn active_entry(&self, stage_time: f64) -> Option<(f64, usize)> {
        let mut chosen = *self.active.first()?;
        for &entry in &self.active {
            if entry.0 <= stage_time {
                chosen = entry;
            } else {
                break;
            }
        }
        Some(chosen)
    }

    /// Maps `stage_time` to clip time through the `times` timing curve
    /// (spec 12.3.4.4). With no `times` authored, the stage time is returned
    /// unchanged.
    pub(crate) fn map_stage_to_clip(&self, stage_time: f64) -> f64 {
        map_stage_to_clip(&self.times, stage_time)
    }

    /// Retimes the schedule through `offset`, shifting the stage component of
    /// every `active` and `times` entry while leaving the clip-time targets and
    /// asset paths untouched. A template-derived schedule is produced in clip
    /// time and brought into stage time here; explicit `active`/`times` are
    /// retimed as they compose.
    pub(crate) fn retime_stage_times(&mut self, offset: LayerOffset) {
        if offset.is_identity() {
            return;
        }
        for (stage, _) in &mut self.active {
            *stage = offset.apply(*stage);
        }
        for knot in &mut self.times {
            knot.x = offset.apply(knot.x);
        }
        // A positive scale preserves the existing stage ordering; only a
        // negative scale (time reversal) needs a re-sort.
        if offset.scale < 0.0 {
            self.active.sort_by(|a, b| a.0.total_cmp(&b.0));
            self.times.sort_by(|a, b| a.x.total_cmp(&b.x));
        }
    }

    /// The stage times at which a clipped attribute's value changes under this
    /// set (the clip half of `UsdAttribute::GetTimeSamples`). `per_clip[i]` is
    /// the in-clip sample times the clip at `asset_paths[i]` authors for the
    /// attribute; an active entry referencing an index past `per_clip` is
    /// treated as authoring none.
    ///
    /// For each clip active over a stage interval, the result gathers the
    /// timing-curve knots in the interval and the clip's in-clip sample times
    /// mapped to stage time through [`Self::stage_times_for_clip_time`] and
    /// clamped to the interval, plus the stage time the clip activates at. The
    /// first active entry is active from negative infinity (spec 12.3.4.3,
    /// matching [`Self::active_entry`]), so its interval has no lower bound; each
    /// later entry's stage time bounds its interval. Returns the union sorted
    /// ascending; empty when no clip is active.
    ///
    /// Every clip contributes the stage time it activates at, whether or not it
    /// authors a sample there, mirroring C++ `Usd_Clip::ListTimeSamplesForPath`.
    /// The activation time isolates a clip from its neighbours, so a sample-time
    /// query is answered from the active clip alone. Whether the set sources the
    /// attribute at all is decided by the caller's participation check before
    /// this routine runs.
    pub(crate) fn stage_sample_times(&self, per_clip: &[Vec<f64>]) -> Vec<f64> {
        let mut out: Vec<f64> = Vec::new();
        for (k, &(start, clip_index)) in self.active.iter().enumerate() {
            let samples = per_clip.get(clip_index).map_or(&[][..], Vec::as_slice);
            let end = self.active.get(k + 1).map(|next| next.0);
            // The first entry is active from negative infinity; later entries
            // start at `start`.
            let lower = (k > 0).then_some(start);
            let in_interval = |t: f64| lower.is_none_or(|l| t >= l) && end.is_none_or(|e| t < e);

            out.push(start);
            out.extend(self.times.iter().map(|knot| knot.x).filter(|&x| in_interval(x)));
            for &clip_time in samples {
                out.extend(
                    self.stage_times_for_clip_time(clip_time)
                        .into_iter()
                        .filter(|&t| in_interval(t)),
                );
            }
        }
        // Drop non-finite times before dedup: a clip may author a NaN time-
        // sample key, and `dedup` (PartialEq) would not collapse repeated NaNs.
        out.retain(|t| t.is_finite());
        out.sort_by(f64::total_cmp);
        out.dedup();
        out
    }

    /// Whether this set's active-clip schedule alone can make the value vary
    /// over time, the clip-schedule half of
    /// [`UsdAttribute::ValueMightBeTimeVarying`]. True when more than one clip
    /// window is active, since switching the active clip can change the value.
    /// A conservative over-approximation: it does not check whether the windows
    /// resolve to distinct values (matching the "might" in the C++ name), and
    /// time variation within a single window is reported through the sample-time
    /// count instead.
    ///
    /// [`UsdAttribute::ValueMightBeTimeVarying`]: crate::usd::Attribute::value_might_be_time_varying
    pub(crate) fn may_be_time_varying(&self) -> bool {
        self.active.len() > 1
    }

    /// The stage times mapping to clip time `clip_time` — the inverse of
    /// [`Self::map_stage_to_clip`] over the timing curve. With no `times`
    /// authored the mapping is identity (the clip time is its own stage time).
    /// Each linear segment that crosses `clip_time` contributes one stage time;
    /// a constant segment (no clip-time change) contributes none, since the
    /// value is held there and only the activation boundary marks a change.
    fn stage_times_for_clip_time(&self, clip_time: f64) -> Vec<f64> {
        if self.times.is_empty() {
            return vec![clip_time];
        }
        self.times
            .windows(2)
            .filter_map(|seg| {
                let (sa, ca) = (seg[0].x, seg[0].y);
                let (sb, cb) = (seg[1].x, seg[1].y);
                let (lo, hi) = if ca <= cb { (ca, cb) } else { (cb, ca) };
                if ca == cb || clip_time < lo || clip_time > hi {
                    return None;
                }
                Some(sa + (clip_time - ca) / (cb - ca) * (sb - sa))
            })
            .collect()
    }
}

/// The `assetPaths` index an `active` entry's second component names, or `None`
/// when it is not a whole non-negative number. `active` is a `double2[]`, so the
/// index arrives as a double: a negative, fractional or NaN value is a malformed
/// schedule, and a bare `as usize` would saturate it onto a real clip.
fn clip_index(value: f64) -> Option<usize> {
    (value.is_finite() && value >= 0.0 && value.fract() == 0.0).then_some(value as usize)
}

/// Maps `stage_time` to clip time through a sorted `(stageTime, clipTime)`
/// timing curve made of linear segments (spec 12.3.4.4). Duplicate stage times
/// encode a jump discontinuity (spec 12.3.4.8): the earlier entry's clip time
/// applies up to that stage time, the later entry's at and after it. Out-of-
/// range stage times clamp to the first or last clip time.
fn map_stage_to_clip(times: &[gf::Vec2d], stage_time: f64) -> f64 {
    let (Some(first), Some(last)) = (times.first(), times.last()) else {
        return stage_time;
    };
    if stage_time < first.x {
        return first.y;
    }
    if stage_time >= last.x {
        return last.y;
    }

    // Index of the last entry whose stage time does not exceed `stage_time`.
    // For a duplicated stage time this lands on the right-hand entry, so a
    // query exactly at the jump uses the "at and after" clip time.
    let lo = times.iter().rposition(|knot| knot.x <= stage_time).unwrap_or(0);
    let (lo_knot, hi_knot) = (times[lo], times[lo + 1]);
    let (stage0, clip0) = (lo_knot.x, lo_knot.y);
    let (stage1, clip1) = (hi_knot.x, hi_knot.y);

    if stage0 == stage1 {
        return clip1;
    }
    if stage_time == stage0 {
        return clip0;
    }
    let ratio = (stage_time - stage0) / (stage1 - stage0);
    gf::lerp(clip0, clip1, ratio)
}

/// Derived `(assetPaths, active, times)` from a template clip set.
type TemplateExpansion = (Vec<AssetPath>, Vec<(f64, usize)>, Vec<gf::Vec2d>);

/// Expand a template clip set (spec 12.3.4.1.3) into explicit
/// `(assetPaths, active, times)`.
///
/// Iterates clip times from `templateStartTime` to `templateEndTime`
/// (inclusive) by `templateStride`, substituting each time into the
/// `#`-pattern `templateAssetPath`. Each generated clip `i` contributes
/// `assetPaths[i]`, an `active` entry `(stageTime, i)`, and a `times`
/// entry `(clipTime, clipTime)`. `templateActiveOffset`, when authored,
/// shifts each clip's active stage time to `clipTime + offset` and adds
/// boundary knots to `times` at `start - |offset|` and `end + |offset|`.
///
/// Returns `None` when the required template fields are missing or
/// invalid (non-positive stride, `end < start`, `|activeOffset| > stride`,
/// or an unparseable pattern).
///
/// Times are scaled by a fixed promotion factor during iteration so a
/// fractional `stride` accumulates without binary-float drift, matching
/// C++ `Usd_ClipSetDefinition` template derivation.
fn expand_template(set: &HashMap<String, Value>) -> Option<TemplateExpansion> {
    let template = asset_input(set, keys::TEMPLATE_ASSET_PATH).map(str::to_owned)?;
    // Template timing is `double`, read strictly like C++ `IsHolding<double>`.
    let start = get::<f64>(set, keys::TEMPLATE_START_TIME)?;
    let end = get::<f64>(set, keys::TEMPLATE_END_TIME)?;
    let stride = get::<f64>(set, keys::TEMPLATE_STRIDE)?;
    let active_offset = get::<f64>(set, keys::TEMPLATE_ACTIVE_OFFSET);

    if stride.is_nan() || stride <= 0.0 || end < start {
        return None;
    }
    // Spec 12.3.4.1.3: the active offset magnitude may not exceed the stride.
    if active_offset.is_some_and(|off| off.abs() > stride) {
        return None;
    }

    let pattern = HashPattern::parse(&template)?;

    // Promote to integers so a fractional stride doesn't accumulate float
    // drift across the loop (C++ uses the same trick).
    const PROMOTION: f64 = 10000.0;
    let end_p = end * PROMOTION;
    let stride_p = stride * PROMOTION;

    let mut asset_paths = Vec::new();
    let mut active = Vec::new();
    let mut times = Vec::new();

    // An active offset lets a query reach `|offset|` before the first clip and
    // after the last. Author timing knots at those expanded boundaries so the
    // lead/trail range maps linearly to clip time instead of clamping to the
    // first or last clip time (spec 12.3.4.1.3, matching C++ derivation).
    if let Some(off) = active_offset {
        let front = start - off.abs();
        times.push(gf::vec2d(front, front));
    }

    let mut t = start * PROMOTION;
    let mut index = 0usize;
    // `+ 0.5` keeps the inclusive endpoint despite residual rounding.
    while t <= end_p + 0.5 {
        let clip_time = t / PROMOTION;
        asset_paths.push(pattern.format(clip_time).into());
        times.push(gf::vec2d(clip_time, clip_time));
        let stage_time = match active_offset {
            Some(off) => (t + off * PROMOTION) / PROMOTION,
            None => clip_time,
        };
        active.push((stage_time, index));
        index += 1;
        t += stride_p;
    }

    if let Some(off) = active_offset {
        let back = end + off.abs();
        times.push(gf::vec2d(back, back));
    }

    if asset_paths.is_empty() {
        return None;
    }
    active.sort_by(|a, b| a.0.total_cmp(&b.0));
    times.sort_by(|a, b| a.x.total_cmp(&b.x));
    Some((asset_paths, active, times))
}

/// A parsed `templateAssetPath` pattern: a prefix, one or two adjacent
/// `#`-groups (integer, optionally followed by a subinteger group), and
/// a suffix. Per spec the groups must be adjacent and number one or two.
struct HashPattern {
    prefix: String,
    int_width: usize,
    /// Width of the subinteger group, when the pattern has two groups.
    frac_width: Option<usize>,
    suffix: String,
}

impl HashPattern {
    /// Parse `path/basename.###.usd` or `path/basename.##.##.usd`.
    /// Returns `None` when there is no `#`-group, more than two groups,
    /// or stray `#` outside the (adjacent) groups.
    fn parse(template: &str) -> Option<HashPattern> {
        let first = template.find('#')?;
        let prefix = template[..first].to_string();
        let rest = &template[first..];

        // First (integer) group.
        let int_width = rest.chars().take_while(|&c| c == '#').count();
        let after_int = &rest[int_width..];

        // Optional `.<##...>` subinteger group immediately following.
        let (frac_width, suffix) = if let Some(dot_rest) = after_int.strip_prefix('.') {
            if dot_rest.starts_with('#') {
                let frac_width = dot_rest.chars().take_while(|&c| c == '#').count();
                (Some(frac_width), dot_rest[frac_width..].to_string())
            } else {
                (None, after_int.to_string())
            }
        } else {
            (None, after_int.to_string())
        };

        // Spec: hash groups must be adjacent and number one or two — any
        // further `#` in the suffix means a malformed (3+ group) pattern.
        if suffix.contains('#') {
            return None;
        }

        Some(HashPattern {
            prefix,
            int_width,
            frac_width,
            suffix,
        })
    }

    /// Substitute `time` into the pattern. Integer group zero-pads to the
    /// hash count (widening when the value needs more digits); the
    /// subinteger group is fixed-width fractional precision.
    fn format(&self, time: f64) -> String {
        let body = match self.frac_width {
            // Two groups: `<int>.<frac>` at the given widths (spec example
            // `foo.#.###.usd` @ 1.15 -> `foo.1.150.usd`).
            Some(frac_width) => {
                let rendered = format!("{:.*}", frac_width, time);
                let (int_part, frac_part) = rendered.split_once('.').unwrap_or((rendered.as_str(), ""));
                let neg = int_part.starts_with('-');
                let digits = int_part.trim_start_matches('-');
                let padded = format!("{:0>width$}", digits, width = self.int_width);
                let sign = if neg { "-" } else { "" };
                format!("{sign}{padded}.{frac_part}")
            }
            // One group: zero-padded integer, truncating the clip time toward
            // zero like the C++ `int(time)` cast (spec example `foo.###.usd`
            // @ 12 -> `foo.012.usd`).
            None => format!("{:0width$}", time as i64, width = self.int_width),
        };
        format!("{}{}{}", self.prefix, body, self.suffix)
    }
}

/// Reads `key` from a clip-set dictionary and extracts it strictly as `T` — the
/// exact-variant [`TryFrom`] tier — yielding `None` when the key is absent or
/// the authored type does not match. Mirrors C++ `Usd_ClipSetDefinition`'s
/// `IsHolding<T>` reads, which likewise treat a type mismatch as unauthored.
fn get<T: TryFrom<Value>>(set: &HashMap<String, Value>, key: &str) -> Option<T> {
    set.get(key).cloned().and_then(|v| T::try_from(v).ok())
}

/// Value-clip resolution state owned by
/// [`IndexCache`](super::index_cache::IndexCache): the lazily-loaded clip and
/// manifest layers, plus the per-anchor clip-value and participation queries the
/// cache's clip orchestration delegates to (C++ `Usd_Clips`). Clip layers never
/// enter the composition [`LayerGraph`](super::layer_graph::LayerGraph) (spec
/// 12.3.4); they are held here, keyed by resolved identifier.
///
/// Every clip set resolves through a manifest: the one its `manifestAssetPath`
/// names, or — for a set that authors none — one synthesized from the clips its
/// `active` schedule names and memoized by [`ClipSetKey`]. A synthesized
/// manifest is an anonymous layer and joins `clip_layers` under its own
/// identifier, so both kinds are read the same way.
#[derive(Default)]
pub(crate) struct ClipCache {
    clip_layers: HashMap<String, sdf::Layer>,
    /// Manifests synthesized for clip sets that author none: one entry per
    /// (prim, clip set), superseded in place whenever the set it was generated
    /// from no longer matches.
    manifests: HashMap<ClipSetKey, ManifestEntry>,
    /// The clip and manifest identifiers each clip set names, recorded as the
    /// set is offered to value resolution — whether or not any of them opened,
    /// since an identifier that resolves to nothing today is exactly the one a
    /// later join must be noticed at.
    ///
    /// The forward half of the dependency: it exists so a set that re-resolves
    /// (an expression variable stepped to another clip) can retract precisely
    /// what it registered before.
    ///
    /// Nested so a lookup borrows `(anchor, set name)` rather than building an
    /// owned key: the probe below runs on every clipped attribute read, and only
    /// a set that actually re-resolved should allocate.
    set_sources: HashMap<Path, HashMap<String, SetSources>>,
    /// Reverse of it: the clip sets each layer identifier feeds. A synthesized
    /// manifest needs no registration of its own — it is generated from the very
    /// clips its set already names, and only for a set that authors no manifest
    /// of its own, so its sources are exactly that set's.
    ///
    /// TODO(perf): a registration is retracted when its set re-resolves, which
    /// leaves the entries of an anchor whose index was dropped and never queried
    /// again. Bounding it needs the cache to tell this one what it evicted.
    dependents: HashMap<String, HashSet<ClipSetKey>>,
}

/// The identifiers one clip set names, with the resolved set they were derived
/// from so an unchanged set is recognized without resolving an asset path.
struct SetSources {
    /// The set as resolved when the identifiers were computed.
    from: ResolvedClipSet,
    /// The clip and manifest layer identifiers it named.
    identifiers: HashSet<String>,
}

/// A synthesized manifest and the clip set it was generated from.
struct ManifestEntry {
    /// The set as resolved when the manifest was generated; a lookup reuses the
    /// manifest only while the set still compares equal.
    generated_from: ResolvedClipSet,
    /// Identifier the manifest layer is held under in `clip_layers`.
    layer: String,
    /// Whether every clip the schedule names was read. An incomplete manifest
    /// is still recorded, so its layer is freed when the next generation
    /// supersedes it, but it is never reused: the next lookup regenerates and
    /// picks up a clip that has since become readable.
    complete: bool,
}

/// The attribute a clip query resolves, plus the `anchor` prim its clip sets
/// were composed on (an ancestor of `attr_prim`, or `attr_prim` itself). Bundles
/// the three path arguments threaded together through the per-anchor
/// [`ClipCache`] queries.
pub(crate) struct ClipQuery<'a> {
    /// The prim the queried clip sets were composed on.
    pub anchor: &'a Path,
    /// The prim owning the attribute being resolved.
    pub attr_prim: &'a Path,
    /// The attribute's property suffix (e.g. `.size`).
    pub suffix: &'a str,
}

impl ClipCache {
    /// Resolves a value-clip value for `query` at `time` from `resolved` — one
    /// of the clip sets composed on `query.anchor` — or `None` when that set
    /// does not source the attribute. An authored value block presents as
    /// `Some(Value::ValueBlock)` so the caller stops fall-through to weaker
    /// sources.
    ///
    /// TODO: the stage-to-clip mapping is applied to the query time only, so
    /// every value returned here — a clip sample, a manifest default, an
    /// interpolated gap value — comes back in clip time. A `timecode` among
    /// them is a time coordinate in the clip's own frame and needs the inverse
    /// mapping applied on the way out, the way
    /// [`sdf::LayerOffset::apply_to_value`] maps a composed value out of its
    /// layer's frame (C++ `Usd_Clip::_TranslateTimeToExternal`, which is also
    /// why C++ skips the layer-offset transform for clip-sourced samples).
    pub(super) fn value_in_set(
        &mut self,
        graph: &LayerGraph,
        diagnostics: &mut Diagnostics,
        resolved: &ResolvedClipSet,
        query: &ClipQuery<'_>,
        time: f64,
        interp: &dyn Fn(&sdf::TimeSampleMap, f64) -> Option<Value>,
    ) -> Result<Option<Value>, QueryError> {
        let set = &resolved.set;
        // With no active schedule no clip is ever selected, so the set
        // sources nothing and needs no manifest.
        let Some((activation, active)) = set.active_entry(time) else {
            return Ok(None);
        };
        let clip_path = clip_attr_path(query, &set.clip_prim_path(query.anchor))?;

        // The manifest declares which attributes the clips provide, and
        // resolves once here because its default fills a gap further down
        // (spec 12.3.4.6). A set whose manifest does not declare this
        // attribute is skipped; a set that *does* declare it owns the
        // attribute's time-varying value, so a gap in the active clip
        // resolves to a manifest default or a value block, never to a
        // weaker value source.
        let manifest = self.manifest_id(graph, diagnostics, resolved, query.anchor)?;
        if !self.manifest_declares(graph, manifest.as_deref(), &clip_path)? {
            return Ok(None);
        }

        let Some(asset) = set.asset_paths.get(active) else {
            return Ok(None);
        };
        let clip_time = set.map_stage_to_clip(time);

        // A manifest block at the active clip's activation time states the
        // clip carries no samples for the attribute, so the read goes
        // straight to the gap below without opening it. Consulted on the
        // same terms as the gap search itself, which is what keeps the two
        // agreeing about what a clip contributes (C++
        // `Usd_ClipSet::_ClipContributesTimeSamples`).
        let contributes = !set.interpolate_missing
            || !self.manifest_blocks(graph, resolved, manifest.as_deref(), &clip_path, activation);
        if contributes
            && let Some((clip_id, value)) =
                self.clip_sample_at(graph, resolved, asset.asset_path(), &clip_path, clip_time, interp)?
        {
            return Ok(Some(self.resolve_asset_in(
                graph,
                diagnostics,
                &clip_id,
                resolved,
                &clip_path,
                value,
            )));
        }

        // The active clip has no sample at `clip_time`, and this set owns
        // the attribute, so it answers for the gap:
        //
        // (a) Manifest default: synthesize a sample at the clip's active
        //     time (spec 12.3.4.6). A synthesized manifest carries no
        //     defaults, so only an authored one reaches here.
        if let Some(manifest) = manifest.as_deref()
            && let Some(value) = self.manifest_default(graph, manifest, &clip_path)?
        {
            return Ok(Some(self.resolve_asset_in(
                graph,
                diagnostics,
                manifest,
                resolved,
                &clip_path,
                value,
            )));
        }

        // (b) interpolateMissingClipValues: interpolate the gap across the
        //     nearest surrounding clips (spec 12.3.4.7).
        if set.interpolate_missing
            && let Some(value) = self.interpolate_missing_value(
                graph,
                diagnostics,
                resolved,
                manifest.as_deref(),
                &clip_path,
                time,
                interp,
            )?
        {
            return Ok(Some(value));
        }

        // (c) No default and nothing to interpolate: the manifest-declared
        //     attribute is authoritatively absent — a value block — which
        //     must not fall through to weaker sources (spec 12.3.4.6).
        Ok(Some(Value::ValueBlock))
    }

    /// The layer a property-stack query lists for `resolved` at `time`: the
    /// active clip when it authors samples for the property, else the set's
    /// manifest — whichever the value would come from, a clip sample or the
    /// manifest default filling a gap (C++
    /// `_PropertyStackResolver::ProcessClips`). Paired with the property's path
    /// inside that layer.
    ///
    /// `None` when the set does not source the property at `time`.
    pub(super) fn clip_spec_site_in_set(
        &mut self,
        graph: &LayerGraph,
        diagnostics: &mut Diagnostics,
        resolved: &ResolvedClipSet,
        query: &ClipQuery<'_>,
        time: f64,
    ) -> Result<Option<(String, Path)>, QueryError> {
        let set = &resolved.set;
        let Some((activation, active)) = set.active_entry(time) else {
            return Ok(None);
        };
        let clip_path = clip_attr_path(query, &set.clip_prim_path(query.anchor))?;
        let manifest = self.manifest_id(graph, diagnostics, resolved, query.anchor)?;
        if !self.manifest_declares(graph, manifest.as_deref(), &clip_path)? {
            return Ok(None);
        }
        let Some(asset) = set.asset_paths.get(active) else {
            return Ok(None);
        };
        // The clip contributes on exactly the terms the value read applies: a
        // manifest block at its activation time states it carries no samples for
        // the attribute, and the value then comes from the manifest or from the
        // clips surrounding the gap, so the clip is not the spec to report.
        let contributes = !set.interpolate_missing
            || !self.manifest_blocks(graph, resolved, manifest.as_deref(), &clip_path, activation);
        if contributes
            && let Some((clip_id, samples)) =
                self.clip_time_samples(graph, asset.asset_path(), resolved.source.layer, &clip_path)?
            && !samples.is_empty()
        {
            return Ok(Some((clip_id, clip_path)));
        }
        Ok(manifest.map(|id| (id, clip_path)))
    }

    /// What `resolved` contributes to a query that names no time: whether it
    /// sources the property at all, and whether it can supply a value anywhere.
    ///
    /// The timeless counterpart of [`Self::value_in_set`], deciding on the same
    /// terms — a set that owns the property but whose clips author nothing for
    /// it, and whose manifest carries no default to fill the gap, blocks it at
    /// every time (spec 12.3.4.6) rather than supplying a value.
    pub(super) fn untimed_answer_in_set(
        &mut self,
        graph: &LayerGraph,
        diagnostics: &mut Diagnostics,
        resolved: &ResolvedClipSet,
        query: &ClipQuery<'_>,
    ) -> Result<ValueState, QueryError> {
        let clip_path = clip_attr_path(query, &resolved.set.clip_prim_path(query.anchor))?;
        let Some(per_clip) = self.clip_set_participates(graph, diagnostics, resolved, query.anchor, &clip_path)? else {
            return Ok(ValueState::Absent);
        };
        if per_clip.iter().any(|times| !times.is_empty()) {
            return Ok(ValueState::Present);
        }
        let manifest = self.manifest_id(graph, diagnostics, resolved, query.anchor)?;
        let default = match manifest.as_deref() {
            Some(manifest) => self.manifest_default(graph, manifest, &clip_path)?,
            None => None,
        };
        match default {
            Some(_) => Ok(ValueState::Present),
            None => Ok(ValueState::Blocked),
        }
    }

    /// The value-clip introspection `resolved` (composed on `query.anchor`)
    /// contributes when it participates in sourcing the attribute: its stage
    /// sample times (spec 12.3.4) and whether its schedule alone can vary the
    /// value ([`ClipSet::may_be_time_varying`]). `None` when it does not
    /// participate.
    pub(super) fn clip_introspection_in_set(
        &mut self,
        graph: &LayerGraph,
        diagnostics: &mut Diagnostics,
        resolved: &ResolvedClipSet,
        query: &ClipQuery<'_>,
    ) -> Result<Option<(Vec<f64>, bool)>, QueryError> {
        let clip_path = clip_attr_path(query, &resolved.set.clip_prim_path(query.anchor))?;
        let Some(per_clip) = self.clip_set_participates(graph, diagnostics, resolved, query.anchor, &clip_path)? else {
            return Ok(None);
        };
        let set = &resolved.set;
        Ok(Some((set.stage_sample_times(&per_clip), set.may_be_time_varying())))
    }

    /// Generates a manifest for `resolved` from the clips its `active` schedule
    /// names, queried under `clip_prim_path` (C++
    /// `UsdClipsAPI::GenerateClipManifest`). `write_blocks` authors a value
    /// block at each clip's activation time for the attributes that clip
    /// carries no samples for; `tag` names the anonymous layer produced.
    ///
    /// Also reports whether every scheduled clip opened. A clip that fails to
    /// resolve or parse contributes nothing rather than failing the whole
    /// manifest — one damaged file in a sequence must not make the prim
    /// unreadable at every time — so the result is provisional and the caller
    /// decides whether it may be cached.
    ///
    /// Opening the clips is the cost here — the schedule is walked in order so
    /// a clip activated twice contributes twice, matching the sequence value
    /// resolution reads.
    pub(super) fn generate_manifest(
        &mut self,
        graph: &LayerGraph,
        resolved: &ResolvedClipSet,
        prim: &Path,
        tag: &str,
        write_blocks: bool,
    ) -> Result<(sdf::Layer, Diagnostics), QueryError> {
        let mut scheduled: Vec<(String, Option<f64>)> = Vec::with_capacity(resolved.set.active.len());
        let mut unread = Diagnostics::default();
        for &(stage_time, index) in &resolved.set.active {
            let Some(asset) = resolved.set.asset_paths.get(index) else {
                continue;
            };
            let reason = match self.ensure_clip_layer(graph, asset.asset_path(), resolved.source.layer) {
                Ok(Some(id)) => {
                    scheduled.push((id, write_blocks.then_some(stage_time)));
                    continue;
                }
                Ok(None) => "asset path did not resolve".to_owned(),
                Err(error) => tf::error_chain(&error),
            };
            unread.report(CompositionDiagnostic::UnreadableClip {
                asset_path: asset.asset_path().to_owned(),
                clip_set: resolved.set.name.clone(),
                prim_path: prim.clone(),
                reason,
            });
        }
        let clips: Vec<(&sdf::Layer, Option<f64>)> = scheduled
            .iter()
            .filter_map(|(id, active)| self.layer(graph, id).map(|layer| (layer, *active)))
            .collect();
        let clip_prim_path = resolved.set.clip_prim_path(prim);
        Ok((clip_manifest::generate_manifest(&clips, &clip_prim_path, tag)?, unread))
    }

    /// The identifier of the manifest layer backing `resolved`, queried under
    /// `clip_prim_path`: the layer its `manifestAssetPath` names, or a
    /// synthesized one for a set that authors none (C++ `Usd_ClipSet`'s
    /// generated manifest). `None` only when an authored manifest asset fails
    /// to resolve, which leaves the set sourcing nothing.
    ///
    /// Synthesis is memoized per (prim, clip set) — the pair identifying the
    /// authored set, rather than the clip-internal prim path several prims may
    /// share — and validated against the resolved set it was generated from, so
    /// any re-authoring of the set supersedes the manifest and frees the layer
    /// it replaces. The probe compares the set in place, resolving no asset
    /// paths, because value resolution reaches here on every clipped attribute
    /// read.
    ///
    /// A manifest generated while a scheduled clip could not be read is recorded
    /// but never reused, so the next read regenerates and picks that clip up
    /// once it becomes readable; the clips that failed are reported into
    /// `diagnostics`.
    fn manifest_id(
        &mut self,
        graph: &LayerGraph,
        diagnostics: &mut Diagnostics,
        resolved: &ResolvedClipSet,
        prim: &Path,
    ) -> Result<Option<String>, QueryError> {
        if let Some(asset) = resolved.set.manifest_asset.as_deref() {
            let anchor = resolved.manifest_layer.unwrap_or(resolved.source.layer);
            return self.ensure_clip_layer(graph, asset, anchor);
        }

        let key = resolved.key(prim);
        if let Some(entry) = self.manifests.get(&key)
            && entry.complete
            && entry.generated_from.same_resolution(resolved)
        {
            return Ok(Some(entry.layer.clone()));
        }

        // A synthesized manifest never carries value blocks: they exist to save
        // a reader from opening a clip, and generating them here would have
        // opened it already.
        let (manifest, unread) =
            self.generate_manifest(graph, resolved, prim, clip_manifest::GENERATED_MANIFEST_TAG, false)?;
        let layer = manifest.identifier().to_owned();
        self.clip_layers.insert(layer.clone(), manifest);
        let entry = ManifestEntry {
            generated_from: resolved.clone(),
            layer: layer.clone(),
            complete: unread.is_empty(),
        };
        diagnostics.extend(unread);
        if let Some(superseded) = self.manifests.insert(key, entry) {
            self.clip_layers.remove(&superseded.layer);
        }
        Ok(Some(layer))
    }

    /// Records the clip and manifest layers the set `resolved` reads, so a
    /// change to one of them can find its way back here.
    ///
    /// Called as the set is offered to value resolution, before any of its
    /// layers is opened: an identifier that resolves to nothing right now is
    /// precisely the one that must be noticed when a layer later joins the
    /// graph under it. Registering at the offer also leaves out the sets a
    /// stronger opinion kept resolution from ever consulting.
    ///
    /// Re-registration replaces the set's previous sources outright, so an
    /// expression that steps a clip path from one asset to another stops
    /// depending on the one it left.
    pub(super) fn register_set_sources(&mut self, graph: &LayerGraph, anchor: &Path, resolved: &ResolvedClipSet) {
        // Value resolution reaches here on every clipped attribute read, so the
        // unchanged case must resolve no asset path and build no key: the probe
        // borrows both halves of the identity out of the nested map.
        if self
            .set_sources
            .get(anchor)
            .and_then(|sets| sets.get(&resolved.set.name))
            .is_some_and(|registered| registered.from.same_resolution(resolved))
        {
            return;
        }

        let identifiers = Self::set_identifiers(graph, resolved);
        let key = resolved.key(anchor);
        let previous = self
            .set_sources
            .entry(anchor.clone())
            .or_default()
            .insert(
                resolved.set.name.clone(),
                SetSources {
                    from: resolved.clone(),
                    identifiers: identifiers.clone(),
                },
            )
            .map(|entry| entry.identifiers)
            .unwrap_or_default();
        Self::rewire_dependents(&mut self.dependents, &key, &previous, &identifiers);
    }

    /// The clip and manifest layer identifiers `resolved` reads: every scheduled
    /// clip, plus the manifest it authors if it authors one.
    fn set_identifiers(graph: &LayerGraph, resolved: &ResolvedClipSet) -> HashSet<String> {
        let mut identifiers: HashSet<String> = resolved
            .set
            .resolution_paths()
            .map(|path| clip_identifier(graph, path, resolved.source.layer))
            .collect();
        if let Some(asset) = resolved.set.manifest_asset.as_deref() {
            let anchor_layer = resolved.manifest_layer.unwrap_or(resolved.source.layer);
            identifiers.insert(clip_identifier(graph, asset, anchor_layer));
        }
        identifiers
    }

    /// Everything a change to the layer `identifier` invalidates: the clip sets
    /// that read it, returned as the anchor prims whose composed values may have
    /// moved, having first dropped the synthesized manifests generated from its
    /// content.
    ///
    /// A synthesized manifest is derived from what its source clips declare, so
    /// an edit to one restales it; an authored manifest and the clips
    /// themselves are read live and need no eviction. The dependents are
    /// snapshotted before anything is dropped, since dropping mutates the very
    /// map the answer is read from.
    pub(super) fn invalidate_layer(&mut self, identifier: &str) -> Vec<Path> {
        let Some(dependents) = self.dependents.get(identifier) else {
            return Vec::new();
        };
        let keys: Vec<ClipSetKey> = dependents.iter().cloned().collect();
        // Two clip sets on one prim reading the same layer name one anchor: the
        // restale walks that prim's subtree, so a repeat would walk it twice.
        let mut anchors: Vec<Path> = keys.iter().map(|key| key.prim.clone()).collect();
        anchors.sort();
        anchors.dedup();
        for key in &keys {
            self.drop_generated_manifest(key);
        }
        anchors
    }

    /// Whether any clip set has registered sources at all — the cheap gate a
    /// caller checks before deriving an identifier to ask about.
    pub(super) fn has_clip_sources(&self) -> bool {
        !self.dependents.is_empty()
    }

    /// Discards the synthesized manifest generated for `key`, freeing its layer,
    /// so the next read of the set regenerates it from what the clips now
    /// declare. A set that authored its own manifest has none and is untouched.
    fn drop_generated_manifest(&mut self, key: &ClipSetKey) {
        if let Some(entry) = self.manifests.remove(key) {
            self.clip_layers.remove(&entry.layer);
        }
    }

    /// Moves `key`'s reverse registrations from `previous` to `current`:
    /// identifiers it no longer names drop it, the ones it gained take it on,
    /// and an identifier nothing depends on any more leaves the map.
    ///
    /// Always called with the forward entry already replaced, so the two halves
    /// cannot end up disagreeing about what a set reads.
    fn rewire_dependents(
        dependents: &mut HashMap<String, HashSet<ClipSetKey>>,
        key: &ClipSetKey,
        previous: &HashSet<String>,
        current: &HashSet<String>,
    ) {
        for identifier in previous.difference(current) {
            let Some(entry) = dependents.get_mut(identifier) else {
                continue;
            };
            entry.remove(key);
            if entry.is_empty() {
                dependents.remove(identifier);
            }
        }
        for identifier in current.difference(previous) {
            dependents.entry(identifier.clone()).or_default().insert(key.clone());
        }
    }

    /// Whether the manifest layer `manifest` declares the attribute at
    /// `clip_path` as clip-sourced: an attribute spec whose variability is
    /// `varying` (C++ `Usd_ClipSet::ContainsValueForAttribute`). A `uniform`
    /// declaration is inert — a clip never sources a uniform attribute.
    ///
    /// A set whose manifest does not declare the attribute never sources it; one
    /// that does owns it authoritatively (spec 12.3.4.6), gap-filling rather
    /// than falling through to weaker sources.
    fn manifest_declares(
        &self,
        graph: &LayerGraph,
        manifest: Option<&str>,
        clip_path: &Path,
    ) -> Result<bool, sdf::PathParseError> {
        let Some(layer) = manifest.and_then(|id| self.layer(graph, id)) else {
            return Ok(false);
        };
        Ok(layer
            .attribute(clip_path)?
            .is_some_and(|attr| attr.variability() == sdf::Variability::Varying))
    }

    /// Whether the manifest layer blocks `clip_path` at `stage_time`, the time a
    /// clip activates — the author's assertion that the clip carries no samples
    /// for the attribute (C++ `Usd_ClipSet::_ClipContributesTimeSamples`). Lets
    /// a read skip the clip without opening it.
    ///
    /// The manifest is read straight off its layer, so its sample times are in
    /// the frame the clip metadata was authored in, while `resolved`'s schedule
    /// has already been retimed into stage time. Each block time is mapped
    /// through the same offset before comparing, so the two meet in stage time.
    fn manifest_blocks(
        &self,
        graph: &LayerGraph,
        resolved: &ResolvedClipSet,
        manifest: Option<&str>,
        clip_path: &Path,
        stage_time: f64,
    ) -> bool {
        let Some(layer) = manifest.and_then(|id| self.layer(graph, id)) else {
            return false;
        };
        let Ok(Some(field)) = layer.data().try_field(clip_path, FieldKey::TimeSamples.as_str()) else {
            return false;
        };
        let Value::TimeSamples(samples) = &*field else {
            return false;
        };
        samples.iter().any(|(time, value)| {
            *value == Value::ValueBlock
                && sdf::compare_sample_times(resolved.active_offset.apply(*time), stage_time).is_eq()
        })
    }

    /// Loads a value-clip or manifest layer referenced by `asset_path`,
    /// anchored to the layer `anchor_layer` (the layer that authored the
    /// clip metadata), and returns the identifier it is cached under. Layers are
    /// loaded on demand through the graph's resolver; clip layers never enter
    /// the composition [`LayerGraph`] (spec 12.3.4).
    ///
    /// Returns `Ok(None)` when the asset path cannot be resolved.
    fn ensure_clip_layer(
        &mut self,
        graph: &LayerGraph,
        asset_path: &str,
        anchor_layer: LayerId,
    ) -> Result<Option<String>, QueryError> {
        let clip_id = clip_identifier(graph, asset_path, anchor_layer);
        // A layer already reachable needs no open at all. The graph is checked
        // first and by identifier alone: an in-memory or anonymous layer used as
        // a clip has no asset the registry could open, so opening first would
        // fail the whole clip where a live layer is sitting right there.
        if graph.id_of(&clip_id).is_none() && !self.clip_layers.contains_key(&clip_id) {
            let opened = graph
                .layer_registry()
                .open(&clip_id)
                .map_err(|error| ClipLoad::new(clip_id.clone(), error))?;
            let Some((resolved, data)) = opened else {
                return Ok(None);
            };
            // Built with the location it resolved to, not just the identifier:
            // that is what anchors the relative asset paths the clip authors, and
            // for a package it is the package-relative default layer.
            self.clip_layers.insert(
                clip_id.clone(),
                sdf::Layer::new_resolved(clip_id.clone(), &resolved, data),
            );
        }
        Ok(Some(clip_id))
    }

    /// The clip or manifest layer `id` names: the graph's, when the identifier
    /// is interned there, else the copy this cache opened.
    ///
    /// The graph is preferred on every lookup rather than once at load, so a
    /// clip that a later sublayer or reference interns is read live from that
    /// moment — the two would otherwise drift, since edits reach the graph's
    /// layer and a re-open would read the file rather than the edited layer.
    ///
    /// TODO: `clip_layers` is only evicted when a synthesized manifest is
    /// superseded, so a session that steps an expression variable through many
    /// values retains one layer per value visited. Bounding it needs the cache
    /// to drop layers no live set names.
    //
    // TODO: a clip layer no graph layer shares is reachable by nobody — the
    // registry hands out a fresh `sdf::Layer` per open, so the copy below is the
    // only one and no edit can arrive for it. Closing that needs
    // `sdf::LayerRegistry` find-or-open dedup, after which this cache and the
    // graph would share one layer whatever brought it in.
    fn layer<'a>(&'a self, graph: &'a LayerGraph, id: &str) -> Option<&'a sdf::Layer> {
        match graph.id_of(id) {
            Some(interned) => Some(graph.layer(interned)),
            None => self.clip_layers.get(id),
        }
    }

    /// Whether the resolved clip `set` participates in sourcing the attribute at
    /// `clip_path`, returning each clip's in-clip authored sample times when it
    /// does and `None` when it does not. A set participates when its manifest —
    /// authored or synthesized — declares the attribute. The single
    /// participation predicate behind [`Self::clip_introspection_in_sets`].
    ///
    /// Participation tracks what [`Self::value_in_sets`] can reach: it selects a
    /// clip only through [`ClipSet::active_entry`], so a set with no `active`
    /// schedule sources nothing, and a synthesized manifest indexes only the
    /// clips that schedule names — an authored-but-unscheduled clip is never
    /// read.
    fn clip_set_participates(
        &mut self,
        graph: &LayerGraph,
        diagnostics: &mut Diagnostics,
        resolved: &ResolvedClipSet,
        prim: &Path,
        clip_path: &Path,
    ) -> Result<Option<Vec<Vec<f64>>>, QueryError> {
        let set = &resolved.set;
        // With no active schedule no clip is ever selected, so the set sources
        // nothing regardless of what its clips author.
        if set.active.is_empty() {
            return Ok(None);
        }
        let manifest = self.manifest_id(graph, diagnostics, resolved, prim)?;
        if !self.manifest_declares(graph, manifest.as_deref(), clip_path)? {
            return Ok(None);
        }
        let mut per_clip: Vec<Vec<f64>> = Vec::with_capacity(set.asset_paths.len());
        for asset in &set.asset_paths {
            per_clip.push(self.clip_in_clip_times(graph, asset.asset_path(), resolved.source.layer, clip_path)?);
        }
        Ok(Some(per_clip))
    }

    /// The in-clip authored sample times for `clip_path` in a single clip layer,
    /// or empty when the layer is unresolved or authors no samples there.
    fn clip_in_clip_times(
        &mut self,
        graph: &LayerGraph,
        asset: &str,
        anchor_layer: LayerId,
        clip_path: &Path,
    ) -> Result<Vec<f64>, QueryError> {
        Ok(self
            .clip_time_samples(graph, asset, anchor_layer, clip_path)?
            .map(|(_, samples)| samples.iter().map(|(t, _)| *t).collect())
            .unwrap_or_default())
    }

    /// Reads the `timeSamples` map authored for `clip_path` in a single clip
    /// layer, with the identifier the clip resolved to, or `None` when the layer
    /// is unresolved or authors no samples there. The shared read behind
    /// [`Self::clip_sample_at`] (which interpolates) and
    /// [`Self::clip_in_clip_times`] (which lists the times).
    ///
    /// The identifier travels with the samples because resolving an `asset`
    /// value out of them anchors on that same clip, and re-deriving it would
    /// repeat the resolver's filesystem work.
    fn clip_time_samples(
        &mut self,
        graph: &LayerGraph,
        asset: &str,
        anchor_layer: LayerId,
        clip_path: &Path,
    ) -> Result<Option<(String, sdf::TimeSampleMap)>, QueryError> {
        let Some(id) = self.ensure_clip_layer(graph, asset, anchor_layer)? else {
            return Ok(None);
        };
        let Some(layer) = self.layer(graph, &id) else {
            return Ok(None);
        };
        Ok(
            match layer.data().try_field(clip_path, FieldKey::TimeSamples.as_str())? {
                Some(value) => match value.into_owned() {
                    Value::TimeSamples(samples) => Some((id, samples)),
                    _ => None,
                },
                None => None,
            },
        )
    }

    /// Reads the time samples for `clip_path` from a single clip layer and
    /// interpolates at `clip_time`, returning the value with the identifier of
    /// the clip that sourced it. `None` when the layer is unresolved or the
    /// attribute has no time samples there.
    ///
    /// The value comes back unresolved so the caller can resolve only what it
    /// keeps: a gap fill reads both brackets but returns one, and resolving the
    /// discarded one would report its expression failures for a value nobody
    /// sees. The identifier is what anchors it once kept
    /// ([`Self::resolve_asset_in`]).
    fn clip_sample_at(
        &mut self,
        graph: &LayerGraph,
        resolved: &ResolvedClipSet,
        asset: &str,
        clip_path: &Path,
        clip_time: f64,
        interp: &dyn Fn(&sdf::TimeSampleMap, f64) -> Option<Value>,
    ) -> Result<Option<(String, Value)>, QueryError> {
        let Some((clip_id, samples)) = self.clip_time_samples(graph, asset, resolved.source.layer, clip_path)? else {
            return Ok(None);
        };
        Ok(interp(&samples, clip_time).map(|value| (clip_id, value)))
    }

    /// Anchors and evaluates an `asset` value read out of the clip or manifest
    /// layer `identifier` (C++ `UsdStage::_GetAssetPathContext` takes the layer
    /// from the active clip, or from the manifest when the clip has no authored
    /// values).
    ///
    /// Called on each value the set returns, with the identifier of the layer
    /// that sourced *that* value — never on one the set read but discarded, so a
    /// failed expression is reported only for a value a caller sees.
    fn resolve_asset_in(
        &mut self,
        graph: &LayerGraph,
        diagnostics: &mut Diagnostics,
        identifier: &str,
        resolved: &ResolvedClipSet,
        clip_path: &Path,
        value: Value,
    ) -> Value {
        // Checked before the site is built: that copies the layer's location and
        // identifier, which an ordinary numeric clip sample has no use for.
        if !value.is_asset_valued() {
            return value;
        }
        let Some(layer) = self.layer(graph, identifier) else {
            return value;
        };
        let site = AssetSite::in_clip(layer, resolved.source.stack, clip_path);
        asset_resolve::resolve_values(graph, value, Some(&site), diagnostics)
    }

    /// Reads the authored `default` for `clip_path` from the manifest layer
    /// `manifest` (spec 12.3.4.6): when the active clip has a gap, the manifest
    /// default stands in as the sample value. Returns `None` when the manifest
    /// holds no usable default for the attribute — as a synthesized one never
    /// does, since generation copies declarations only.
    fn manifest_default(
        &self,
        graph: &LayerGraph,
        manifest: &str,
        clip_path: &Path,
    ) -> Result<Option<Value>, QueryError> {
        let Some(layer) = self.layer(graph, manifest) else {
            return Ok(None);
        };
        Ok(layer
            .data()
            .try_field(clip_path, FieldKey::Default.as_str())?
            .map(|value| value.into_owned())
            .and_then(block_to_none))
    }

    /// Fills a gap in the active clip by interpolating across the nearest
    /// surrounding clips that contribute a value (spec 12.3.4.7). Each
    /// contributing clip is anchored on the stage timeline at the active stage
    /// time it owns and valued by its sample there; `interp` then brackets
    /// `time` between the nearest such anchors, exactly as if the clips' samples
    /// formed one virtual sample map. The forward bracket is the next
    /// contributing clip's start time and the backward bracket the previous
    /// one's, matching the C++ resolver. When only one side contributes, its
    /// value is held across the gap.
    ///
    /// The value comes back resolved, anchored on whichever surrounding clip
    /// supplied it — an `asset` path holds rather than blends, so a bracketed
    /// gap keeps the earlier clip's value and its anchor.
    ///
    /// A clip the manifest blocks at its activation time is skipped without
    /// being opened: the block is the author's statement that it carries no
    /// samples for the attribute (C++
    /// `Usd_ClipSet::_ClipContributesTimeSamples`).
    // TODO: the clip context (graph, diagnostics, resolved set, manifest) is
    // threaded through eight `ClipCache` methods, six of which only pass it on
    // to reach `manifest_id`. Bundling it into a `ClipEval<'_>` — the shape
    // `ClipProbe` already has one layer up — would collapse the arity here and
    // at every one of them.
    #[allow(clippy::too_many_arguments)]
    fn interpolate_missing_value(
        &mut self,
        graph: &LayerGraph,
        diagnostics: &mut Diagnostics,
        resolved: &ResolvedClipSet,
        manifest: Option<&str>,
        clip_path: &Path,
        time: f64,
        interp: &dyn Fn(&sdf::TimeSampleMap, f64) -> Option<Value>,
    ) -> Result<Option<Value>, QueryError> {
        let set = &resolved.set;
        // Position of the active clip among the `active` entries at `time`.
        let active_pos = set.active.iter().rposition(|&(stage, _)| stage <= time).unwrap_or(0);

        // Forward: nearest later clip that contributes, anchored at its start.
        let mut upper = None;
        for &(stage, idx) in set.active.iter().skip(active_pos + 1) {
            if self.manifest_blocks(graph, resolved, manifest, clip_path, stage) {
                continue;
            }
            if let Some(asset) = set.asset_paths.get(idx) {
                let clip_time = set.map_stage_to_clip(stage);
                if let Some(sample) =
                    self.clip_sample_at(graph, resolved, asset.asset_path(), clip_path, clip_time, interp)?
                {
                    upper = Some((stage, sample));
                    break;
                }
            }
        }

        // Backward: nearest earlier clip that contributes, anchored at its start.
        let mut lower = None;
        for &(stage, idx) in set.active[..active_pos].iter().rev() {
            if self.manifest_blocks(graph, resolved, manifest, clip_path, stage) {
                continue;
            }
            if let Some(asset) = set.asset_paths.get(idx) {
                let clip_time = set.map_stage_to_clip(stage);
                if let Some(sample) =
                    self.clip_sample_at(graph, resolved, asset.asset_path(), clip_path, clip_time, interp)?
                {
                    lower = Some((stage, sample));
                    break;
                }
            }
        }

        // Only the bracket that survives is resolved: resolving the discarded one
        // would report its expression failures for a value nobody sees.
        //
        // An `asset` path cannot be blended, so a bracketed gap holds the earlier
        // clip's value. That is decided here rather than read back off `interp`'s
        // result, because the anchor has to follow the value that survives and
        // this layer stays free of whichever interpolation policy the caller
        // injected.
        Ok(match (lower, upper) {
            (Some((lt, (lid, lv))), Some((ut, (_, uv)))) => {
                if lv.is_asset_valued() || uv.is_asset_valued() {
                    Some(self.resolve_asset_in(graph, diagnostics, &lid, resolved, clip_path, lv))
                } else {
                    interp(&vec![(lt, lv), (ut, uv)], time)
                }
            }
            (Some((_, (id, value))), None) | (None, Some((_, (id, value)))) => {
                Some(self.resolve_asset_in(graph, diagnostics, &id, resolved, clip_path, value))
            }
            (None, None) => None,
        })
    }
}

/// Whether a set authors explicit `assetPaths` as a strict `asset[]`, mirroring
/// C++ `IsHolding<VtArray<SdfAssetPath>>` so a wrongly-typed opinion reads as
/// unauthored.
///
/// The one authority on whether a set is explicit, and so on which of its asset
/// fields are read at all: an explicit set never reads its `templateAssetPath`,
/// and a template set never reads its `assetPaths`. The evaluation pass consults
/// this for the same reason it must not evaluate a field nobody reads — an
/// expression there is nobody's error.
pub(crate) fn has_explicit_assets(set: &HashMap<String, Value>) -> bool {
    matches!(set.get(keys::ASSET_PATHS), Some(Value::AssetPathVec(_)))
}

/// The explicit `assetPaths` of a set [`has_explicit_assets`] accepts.
fn explicit_asset_paths(set: &HashMap<String, Value>) -> Option<Vec<AssetPath>> {
    has_explicit_assets(set).then(|| get::<Vec<AssetPath>>(set, keys::ASSET_PATHS))?
}

/// The clip sets that participate, strongest first: those the composed
/// `clipSets` ordering names, or every set sorted by name when it is unauthored.
/// A name the ordering lists but no set defines contributes nothing. Shared
/// with the pre-parse evaluation pass, so both exclude the same sets.
pub(crate) fn effective_set_names<'a, T>(sets: &'a HashMap<String, T>, order: Option<&'a [String]>) -> Vec<&'a String> {
    if let Some(order) = order {
        return order.iter().filter(|name| sets.contains_key(*name)).collect();
    }
    let mut names: Vec<&String> = sets.keys().collect();
    names.sort();
    names
}

/// A scalar asset-valued `clips` field as an [`sdf::AssetPath`], whatever type
/// the layer declared it.
///
/// C++ authors `templateAssetPath` as a `std::string`
/// (`UsdClipsAPI::SetClipTemplateAssetPath`) and `manifestAssetPath` as an
/// `SdfAssetPath`, so the two arrive differently typed from the same writer.
/// Coercing here lets one rule cover both: the evaluation pass walks the
/// asset-bearing `Value` variants, which a string-typed field is not one of, so
/// a `` `${VAR}` `` in a C++-authored template would otherwise reach
/// [`HashPattern::parse`](HashPattern::parse) unevaluated.
pub(crate) fn as_asset_field(value: Value) -> Value {
    match value {
        Value::String(path) => Value::AssetPath(AssetPath::new(path)),
        Value::Token(path) => Value::AssetPath(AssetPath::new(path.as_str())),
        other => other,
    }
}

/// An asset-valued clip field as the path to resolve: the evaluated form when a
/// `` `${VAR}` `` was substituted, else the authored one (`AssetPath::asset_path`).
/// A field authored as a plain string still reads through, since a dictionary
/// value's type is whatever the layer declared.
pub(crate) fn asset_input<'a>(set: &'a HashMap<String, Value>, field: &str) -> Option<&'a str> {
    match set.get(field)? {
        Value::AssetPath(asset) => Some(asset.asset_path()),
        other => other.as_str(),
    }
}

/// The identifier a clip or manifest `asset_path` is keyed under: the anchored
/// canonical form, or — when the graph already interns the layer that path names
/// — the identifier the graph knows it by.
///
/// Anchoring against `anchor_layer`, the layer that authored the clip metadata,
/// is what makes a relative path resolve like any other dependency, and it is
/// tried first so a relative path against a filesystem-backed layer never
/// resolves to an unrelated layer that merely happens to be interned under the
/// bare string. An in-memory layer has no location to anchor against, so the
/// graph's own [`LayerGraph::find_relative`] settles the rest: keying such a
/// clip by its anchored form would leave it unreadable, and would key its
/// registrations under a name no edit to it is ever reported with.
fn clip_identifier(graph: &LayerGraph, asset_path: &str, anchor_layer: LayerId) -> String {
    let anchor = graph.anchor_location(Some(anchor_layer));
    let anchored = graph.layer_registry().create_identifier(asset_path, anchor.as_ref());
    if graph.id_of(&anchored).is_some() {
        return anchored;
    }
    match graph.find_relative(asset_path, anchor_layer) {
        Some(interned) => graph.identifier(interned).to_owned(),
        None => anchored,
    }
}

/// The attribute's path inside a clip set's namespace: the `attr_prim + suffix`
/// path with the clip `anchor` prim replaced by the set's `base` prim (spec
/// 12.3.4.1.1.1). `query.anchor` is an ancestor of `query.attr_prim`, so the
/// replacement lands on a path boundary; the fallback keeps the path unchanged
/// if it ever is not a prefix.
fn clip_attr_path(query: &ClipQuery<'_>, base: &Path) -> Result<Path, QueryError> {
    let attr = Path::new(&format!("{}{}", query.attr_prim, query.suffix))?;
    Ok(attr.replace_prefix(query.anchor, base).unwrap_or(attr))
}

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

    /// `ClipCache::clip_layer` loads a clip layer relative to the authoring
    /// layer, caches it (clip layers never enter the composition stack), and
    /// reports an unresolvable path as `None`. The cache resolves clips through
    /// an independently-owned [`ClipCache`], so this exercises it without an
    /// [`IndexCache`](super::super::index_cache::IndexCache).
    #[test]
    fn loads_and_caches_clip_layer() -> crate::Result<()> {
        let root = format!(
            "{}vendor/core-spec-supplemental-release_dec2025/value_resolution/tests/assets/clip_basic/usda/root.usda",
            env!("CARGO_WORKSPACE_DIR")
        );
        let registry = sdf::LayerRegistry::default();
        let id = registry.create_identifier(&root, None);
        let (_, data) = registry.open(&root).expect("open root").expect("root resolves");
        let graph = LayerGraph::from_layers(vec![sdf::Layer::new(id, data)], 0, registry);
        let root_id = graph.root_id().expect("root layer");

        let mut clips = ClipCache::default();
        let id = clips
            .ensure_clip_layer(&graph, "./clip.usda", root_id)?
            .expect("clip resolves");
        {
            let clip = clips.layer(&graph, &id).expect("the clip is held");
            assert!(clip.identifier.contains("clip.usda"));
            assert!(clip.data().has_spec(&sdf::path("/Model.size")?));
        }

        // Second lookup is a cache hit; a bogus path resolves to None.
        assert!(clips.ensure_clip_layer(&graph, "./clip.usda", root_id)?.is_some());
        assert!(
            clips
                .ensure_clip_layer(&graph, "./does_not_exist.usda", root_id)?
                .is_none()
        );
        Ok(())
    }

    /// A clip the graph already holds is found through the graph, whatever it is
    /// interned under. An in-memory layer has no location to anchor a relative
    /// path against, so keying the clip by its anchored form would send the
    /// lookup to a file that does not exist and leave the clip unreadable.
    #[test]
    fn in_memory_clip_resolves() -> crate::Result<()> {
        let root = format!(
            "{}/fixtures/clip_manifestless_held/root.usda",
            std::env::var("CARGO_MANIFEST_DIR").unwrap()
        );
        let registry = sdf::LayerRegistry::default();
        let id = registry.create_identifier(&root, None);
        let (_, data) = registry.open(&root).expect("open root").expect("root resolves");
        // A second layer interned under a bare name, as an in-memory layer is.
        let clip = sdf::Layer::new_in_memory("in_memory_clip.usda");
        let graph = LayerGraph::from_layers(vec![sdf::Layer::new(id, data), clip], 0, registry);
        let root_id = graph.root_id().expect("root layer");

        let identifier = clip_identifier(&graph, "in_memory_clip.usda", root_id);
        assert_eq!(
            graph.id_of(&identifier),
            graph.id_of("in_memory_clip.usda"),
            "the clip must be keyed under the identifier the graph interns it by",
        );

        let mut clips = ClipCache::default();
        assert_eq!(
            clips
                .ensure_clip_layer(&graph, "in_memory_clip.usda", root_id)?
                .as_deref(),
            Some(identifier.as_str()),
            "resolving must find the interned layer rather than opening a file",
        );
        assert!(
            clips.layer(&graph, &identifier).is_some(),
            "and reading it must reach the graph's layer",
        );
        Ok(())
    }
    /// A set that authors no manifest gets one synthesized, and repeat queries
    /// reuse it: the memo returns the same anonymous layer rather than minting
    /// one — and growing `clip_layers` without bound — per query.
    #[test]
    fn synthesized_manifest_is_memoized() -> crate::Result<()> {
        let root = format!(
            "{}/fixtures/clip_manifestless_held/root.usda",
            std::env::var("CARGO_MANIFEST_DIR").unwrap()
        );
        let registry = sdf::LayerRegistry::default();
        let id = registry.create_identifier(&root, None);
        let (_, data) = registry.open(&root).expect("open root").expect("root resolves");
        let graph = LayerGraph::from_layers(vec![sdf::Layer::new(id, data)], 0, registry);
        let root_id = graph.root_id().expect("root layer");

        let model = sdf::path("/Model")?;
        let resolved = ResolvedClipSet {
            set: ClipSet {
                name: "default".into(),
                prim_path: Some(model.clone()),
                manifest_asset: None,
                asset_paths: vec![AssetPath::new("./clip0.usda"), AssetPath::new("./clip1.usda")],
                active: vec![(0.0, 0), (10.0, 1)],
                times: Vec::new(),
                interpolate_missing: false,
            },
            source: ClipAnchor {
                layer: root_id,
                prim_path: model.clone(),
                stack: LayerStackId::ROOT,
            },
            manifest_layer: None,
            active_offset: LayerOffset::IDENTITY,
        };

        let mut clips = ClipCache::default();
        let first = clips
            .manifest_id(&graph, &mut Diagnostics::default(), &resolved, &model)?
            .expect("synthesized");
        let layers = clips.clip_layers.len();
        assert_eq!(
            clips
                .manifest_id(&graph, &mut Diagnostics::default(), &resolved, &model)?
                .as_deref(),
            Some(&*first)
        );
        assert_eq!(clips.clip_layers.len(), layers);

        // clip0 samples `size`, so the synthesized manifest declares it as
        // varying and the set owns the attribute.
        assert!(clips.manifest_declares(&graph, Some(&first), &sdf::path("/Model.size")?)?);
        assert!(!clips.manifest_declares(&graph, Some(&first), &sdf::path("/Model.absent")?)?);

        // Re-authoring the set supersedes the manifest — an edit that only moves
        // an activation time, or one that only changes the clip-internal prim
        // path — and frees the one it replaces, so an editing session does not
        // accumulate a layer per edit.
        let mut retimed = resolved.clone();
        retimed.set.active = vec![(0.0, 0), (5.0, 1)];
        let second = clips
            .manifest_id(&graph, &mut Diagnostics::default(), &retimed, &model)?
            .expect("synthesized");
        assert_ne!(second, first);
        assert!(!clips.clip_layers.contains_key(&first));
        assert_eq!(clips.clip_layers.len(), layers);

        let mut repathed = retimed.clone();
        repathed.set.prim_path = Some(sdf::path("/Other")?);
        let third = clips
            .manifest_id(&graph, &mut Diagnostics::default(), &repathed, &model)?
            .expect("synthesized");
        assert_ne!(third, second);
        assert!(!clips.clip_layers.contains_key(&second));
        assert_eq!(clips.clip_layers.len(), layers);

        // Two prims naming the same clip-internal prim path hold separate
        // manifests: the memo is keyed by the prim carrying the set, so their
        // lookups cannot evict one another.
        let other_prim = sdf::path("/Other")?;
        let mut elsewhere = resolved.clone();
        elsewhere.set.asset_paths = vec![AssetPath::new("./clip1.usda")];
        elsewhere.set.active = vec![(0.0, 0)];
        let mine = clips
            .manifest_id(&graph, &mut Diagnostics::default(), &resolved, &model)?
            .expect("synthesized");
        let theirs = clips
            .manifest_id(&graph, &mut Diagnostics::default(), &elsewhere, &other_prim)?
            .expect("synthesized");
        assert_ne!(mine, theirs);
        assert_eq!(
            clips
                .manifest_id(&graph, &mut Diagnostics::default(), &resolved, &model)?
                .as_deref(),
            Some(&*mine)
        );
        assert_eq!(
            clips
                .manifest_id(&graph, &mut Diagnostics::default(), &elsewhere, &other_prim)?
                .as_deref(),
            Some(&*theirs)
        );
        Ok(())
    }

    /// Builds a `double2[]` knot list (`active` / `times`) from `(x, y)` pairs.
    fn knots(pairs: &[(f64, f64)]) -> Vec<gf::Vec2d> {
        pairs.iter().map(|&(x, y)| gf::vec2d(x, y)).collect()
    }

    // Template hash substitution (clipsAPI.h doc examples).

    #[test]
    fn hash_substitution_integer() {
        // foo.##.usd  @ 12  => foo.12.usd
        assert_eq!(HashPattern::parse("foo.##.usd").unwrap().format(12.0), "foo.12.usd");
        // foo.###.usd @ 12  => foo.012.usd
        assert_eq!(HashPattern::parse("foo.###.usd").unwrap().format(12.0), "foo.012.usd");
        // foo.#.usd   @ 333 => foo.333.usd
        assert_eq!(HashPattern::parse("foo.#.usd").unwrap().format(333.0), "foo.333.usd");
        // Fractional clip times truncate toward zero, not round:
        // foo.#.usd @ 1.6 => foo.1.usd.
        assert_eq!(HashPattern::parse("foo.#.usd").unwrap().format(1.6), "foo.1.usd");
    }

    #[test]
    fn hash_substitution_subinteger() {
        // foo.#.###.usd @ 1.15 => foo.1.150.usd
        assert_eq!(
            HashPattern::parse("foo.#.###.usd").unwrap().format(1.15),
            "foo.1.150.usd"
        );
        // foo.#.##.usd  @ 1.1  => foo.1.10.usd
        assert_eq!(HashPattern::parse("foo.#.##.usd").unwrap().format(1.1), "foo.1.10.usd");
    }

    #[test]
    fn hash_pattern_rejects_three_groups() {
        assert!(HashPattern::parse("foo.#.#.#.usd").is_none());
        assert!(HashPattern::parse("foo.usd").is_none());
    }

    #[test]
    fn template_expands_to_explicit_clip_set() {
        use std::collections::HashMap;
        let mut set = HashMap::new();
        set.insert(
            keys::TEMPLATE_ASSET_PATH.to_string(),
            Value::AssetPath("clip.##.usd".into()),
        );
        set.insert(keys::TEMPLATE_START_TIME.to_string(), Value::Double(101.0));
        set.insert(keys::TEMPLATE_END_TIME.to_string(), Value::Double(103.0));
        set.insert(keys::TEMPLATE_STRIDE.to_string(), Value::Double(1.0));

        let parsed = ClipSet::parse_set("default", &set).expect("template set");
        assert_eq!(
            parsed.asset_paths,
            vec![
                "clip.101.usd".to_string(),
                "clip.102.usd".to_string(),
                "clip.103.usd".to_string()
            ],
        );
        assert_eq!(parsed.active, vec![(101.0, 0), (102.0, 1), (103.0, 2)]);
        assert_eq!(parsed.times, knots(&[(101.0, 101.0), (102.0, 102.0), (103.0, 103.0)]));
    }

    #[test]
    fn template_active_offset_shifts_active_times() {
        use std::collections::HashMap;
        let mut set = HashMap::new();
        set.insert(
            keys::TEMPLATE_ASSET_PATH.to_string(),
            Value::AssetPath("c.#.usd".into()),
        );
        set.insert(keys::TEMPLATE_START_TIME.to_string(), Value::Double(0.0));
        set.insert(keys::TEMPLATE_END_TIME.to_string(), Value::Double(2.0));
        set.insert(keys::TEMPLATE_STRIDE.to_string(), Value::Double(1.0));
        set.insert(keys::TEMPLATE_ACTIVE_OFFSET.to_string(), Value::Double(-0.5));

        let parsed = ClipSet::parse_set("default", &set).expect("template set");
        // Active stage times shift by the offset; `times` keeps the clip-time
        // knots plus boundary knots expanded by |offset| at each end.
        assert_eq!(parsed.active, vec![(-0.5, 0), (0.5, 1), (1.5, 2)]);
        assert_eq!(
            parsed.times,
            knots(&[(-0.5, -0.5), (0.0, 0.0), (1.0, 1.0), (2.0, 2.0), (2.5, 2.5)])
        );
    }

    #[test]
    fn template_rejects_invalid_metadata() {
        use std::collections::HashMap;
        let base = |off: f64, stride: f64| {
            let mut set = HashMap::new();
            set.insert(
                keys::TEMPLATE_ASSET_PATH.to_string(),
                Value::AssetPath("c.#.usd".into()),
            );
            set.insert(keys::TEMPLATE_START_TIME.to_string(), Value::Double(0.0));
            set.insert(keys::TEMPLATE_END_TIME.to_string(), Value::Double(2.0));
            set.insert(keys::TEMPLATE_STRIDE.to_string(), Value::Double(stride));
            set.insert(keys::TEMPLATE_ACTIVE_OFFSET.to_string(), Value::Double(off));
            set
        };
        // |activeOffset| > stride is rejected (spec 12.3.4.1.3).
        assert!(ClipSet::parse_set("default", &base(2.0, 1.0)).is_none());
        // Non-positive stride is rejected.
        assert!(ClipSet::parse_set("default", &base(0.0, 0.0)).is_none());
    }

    /// An activation that cannot name a clip rejects the whole set, as C++ does.
    /// Dropping just that entry would silently widen the preceding clip over the
    /// window, and a bare `as usize` would land a negative or NaN index on clip
    /// 0 — both serve a clip the author never scheduled there.
    #[test]
    fn active_rejects_unusable_index() {
        use std::collections::HashMap;
        let parse = |active: Vec<gf::Vec2d>| {
            let mut set = HashMap::new();
            set.insert(
                keys::ASSET_PATHS.to_string(),
                Value::AssetPathVec(vec!["a.usd".into(), "b.usd".into()]),
            );
            set.insert(keys::ACTIVE.to_string(), Value::Vec2dVec(active));
            ClipSet::parse_set("default", &set)
        };

        assert_eq!(
            parse(knots(&[(0.0, 0.0), (10.0, 1.0)])).expect("valid set").active,
            vec![(0.0, 0), (10.0, 1)]
        );
        // Past the end, negative, fractional, NaN index, and a NaN stage time.
        assert!(parse(knots(&[(0.0, 0.0), (5.0, 7.0)])).is_none());
        assert!(parse(knots(&[(0.0, 0.0), (5.0, -1.0)])).is_none());
        assert!(parse(knots(&[(0.0, 0.0), (5.0, 0.5)])).is_none());
        assert!(parse(vec![gf::vec2d(0.0, f64::NAN)]).is_none());
        assert!(parse(vec![gf::vec2d(f64::NAN, 0.0)]).is_none());
    }

    #[test]
    fn explicit_asset_paths_win_over_template() {
        use std::collections::HashMap;
        let mut set = HashMap::new();
        set.insert(
            keys::ASSET_PATHS.to_string(),
            Value::AssetPathVec(vec!["explicit.usd".into()]),
        );
        set.insert(
            keys::TEMPLATE_ASSET_PATH.to_string(),
            Value::AssetPath("c.#.usd".into()),
        );
        set.insert(keys::TEMPLATE_START_TIME.to_string(), Value::Double(0.0));
        set.insert(keys::TEMPLATE_END_TIME.to_string(), Value::Double(2.0));
        set.insert(keys::TEMPLATE_STRIDE.to_string(), Value::Double(1.0));

        let parsed = ClipSet::parse_set("default", &set).expect("explicit set");
        assert_eq!(parsed.asset_paths, vec!["explicit.usd".to_string()]);
    }

    fn clip_set(active: Vec<(f64, usize)>, times: Vec<gf::Vec2d>) -> ClipSet {
        ClipSet {
            name: "default".into(),
            prim_path: None,
            manifest_asset: None,
            asset_paths: Vec::new(),
            active,
            times,
            interpolate_missing: false,
        }
    }

    #[test]
    fn active_clip_ranges() {
        // active = [(0,0),(1,1),(2,2)] (spec 12.3.4.3 example).
        let cs = clip_set(vec![(0.0, 0), (1.0, 1), (2.0, 2)], vec![]);
        assert_eq!(cs.active_entry(-5.0).map(|(_, i)| i), Some(0)); // before first → first
        assert_eq!(cs.active_entry(0.0).map(|(_, i)| i), Some(0));
        assert_eq!(cs.active_entry(1.5).map(|(_, i)| i), Some(1));
        assert_eq!(cs.active_entry(2.0).map(|(_, i)| i), Some(2));
        assert_eq!(cs.active_entry(100.0).map(|(_, i)| i), Some(2)); // after last → last
    }

    #[test]
    fn active_clip_empty() {
        assert_eq!(clip_set(vec![], vec![]).active_entry(0.0), None);
    }

    #[test]
    fn map_times_linear() {
        // times = [(0,1),(1,2),(2,3)] (spec 12.3.4.4 example).
        let cs = clip_set(vec![], knots(&[(0.0, 1.0), (1.0, 2.0), (2.0, 3.0)]));
        assert_eq!(cs.map_stage_to_clip(0.0), 1.0);
        assert_eq!(cs.map_stage_to_clip(1.0), 2.0);
        assert_eq!(cs.map_stage_to_clip(1.5), 2.5); // interpolated
        assert_eq!(cs.map_stage_to_clip(-3.0), 1.0); // clamp low
        assert_eq!(cs.map_stage_to_clip(9.0), 3.0); // clamp high
    }

    #[test]
    fn map_times_identity() {
        // No times authored → stage time passes through.
        assert_eq!(clip_set(vec![], vec![]).map_stage_to_clip(7.5), 7.5);
    }

    #[test]
    fn stage_times_identity() {
        // Two clips, identity timing: each clip's in-clip samples are stage
        // times, clamped to that clip's active interval, plus the boundaries.
        let cs = clip_set(vec![(0.0, 0), (10.0, 1)], vec![]);
        // clip 0 authors {0,5,12} (12 is outside its [0,10) interval); clip 1 {10,15}.
        let times = cs.stage_sample_times(&[vec![0.0, 5.0, 12.0], vec![10.0, 15.0]]);
        assert_eq!(times, vec![0.0, 5.0, 10.0, 15.0]);
    }

    #[test]
    fn stage_times_empty_window_boundary() {
        // An active clip authoring no samples still reports the boundary where it
        // becomes active: clip 1's window opens at stage 10, a value-change point
        // (the active clip switches there), so 10 is reported alongside clip 0's
        // samples.
        let cs = clip_set(vec![(0.0, 0), (10.0, 1)], vec![]);
        let times = cs.stage_sample_times(&[vec![0.0, 5.0], vec![]]);
        assert_eq!(times, vec![0.0, 5.0, 10.0]);
    }

    #[test]
    fn stage_times_linear_timing() {
        // times maps stage→clip as clip = stage/2, so a clip time maps back to
        // stage 2*clip. Boundary 0 and timing knots {0,10} join the mapped
        // sample stage times {0,5,10}.
        let cs = clip_set(vec![(0.0, 0)], knots(&[(0.0, 0.0), (10.0, 5.0)]));
        let times = cs.stage_sample_times(&[vec![0.0, 2.5, 5.0]]);
        assert_eq!(times, vec![0.0, 5.0, 10.0]);
    }

    #[test]
    fn stage_times_before_first_active() {
        // The first clip is active from -∞ (matches active_entry), so a sample
        // mapping before its activation time is still reported — alongside the
        // activation time itself, which every clip contributes.
        let cs = clip_set(vec![(10.0, 0)], vec![]);
        let times = cs.stage_sample_times(&[vec![5.0, 15.0]]);
        assert_eq!(times, vec![5.0, 10.0, 15.0]);
    }

    #[test]
    fn stage_times_no_active() {
        // No active entries → no clip is scheduled → no sample times.
        assert!(
            clip_set(vec![], vec![])
                .stage_sample_times(&[vec![0.0, 1.0]])
                .is_empty()
        );
    }

    #[test]
    fn map_times_jump_discontinuity() {
        // times = [(0,0),(10,10),(10,25),(20,35)] (spec 12.3.4.8).
        // [0,10): first clip [0,10); [10,20]: second clip [25,35].
        let cs = clip_set(vec![], knots(&[(0.0, 0.0), (10.0, 10.0), (10.0, 25.0), (20.0, 35.0)]));
        assert_eq!(cs.map_stage_to_clip(5.0), 5.0);
        assert!((cs.map_stage_to_clip(9.999) - 9.999).abs() < 1e-6); // left of jump
        assert_eq!(cs.map_stage_to_clip(10.0), 25.0); // at jump → "at and after"
        assert_eq!(cs.map_stage_to_clip(15.0), 30.0); // second segment
        assert_eq!(cs.map_stage_to_clip(20.0), 35.0);
    }

    #[test]
    fn map_times_initial_jump() {
        // At a duplicated first stage time, the right-hand entry applies
        // exactly at the jump.
        let cs = clip_set(vec![], knots(&[(0.0, 0.0), (0.0, 25.0), (10.0, 35.0)]));
        assert_eq!(cs.map_stage_to_clip(-1.0), 0.0);
        assert_eq!(cs.map_stage_to_clip(0.0), 25.0);
        assert_eq!(cs.map_stage_to_clip(5.0), 30.0);
    }

    #[test]
    fn map_times_looping() {
        // times = [(0,0),(25,25),(25,0),(50,25)] — 25 frames looped twice.
        let cs = clip_set(vec![], knots(&[(0.0, 0.0), (25.0, 25.0), (25.0, 0.0), (50.0, 25.0)]));
        assert_eq!(cs.map_stage_to_clip(20.0), 20.0);
        assert_eq!(cs.map_stage_to_clip(45.0), 20.0); // one loop later → same clip time
    }

    /// Parses a clip set from a real USDA `clips` metadata opinion, mirroring
    /// the spec 12.3.4.1.2.4 example.
    #[test]
    fn parse_explicit_from_usda() {
        use crate::sdf::AbstractData;

        let parsed = crate::usda::parser::Parser::new(
            r#"#usda 1.0
def Xform "Geo" (
    clips = {
        dictionary default = {
            double2[] active = [(0, 0), (1, 1), (2, 2)]
            asset[] assetPaths = [@./quad_1.usda@, @./quad_2.usda@, @./quad_3.usda@]
            asset manifestAssetPath = @./manifest.usda@
            string primPath = "/Geo"
            double2[] times = [(0, 1), (1, 2), (2, 3)]
        }
    }
)
{
}
"#,
        )
        .parse()
        .expect("parse usda");
        let data = sdf::Data::from_specs(parsed);

        let clips = data
            .try_field(&Path::new("/Geo").unwrap(), "clips")
            .expect("try_field")
            .expect("clips authored")
            .into_owned();

        let sets = ClipSet::parse(&clips, None);
        assert_eq!(sets.len(), 1);
        let cs = &sets[0];
        assert_eq!(cs.name, "default");
        assert_eq!(cs.prim_path, Some(Path::new("/Geo").unwrap()));
        assert_eq!(cs.manifest_asset.as_deref(), Some("./manifest.usda"));
        assert_eq!(cs.asset_paths, vec!["./quad_1.usda", "./quad_2.usda", "./quad_3.usda"]);
        assert_eq!(cs.active, vec![(0.0, 0), (1.0, 1), (2.0, 2)]);
        assert_eq!(cs.times, knots(&[(0.0, 1.0), (1.0, 2.0), (2.0, 3.0)]));
    }
}