openusd 0.8.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
//! Composition-invalidation tests: the surgical cache invalidation that
//! `pcp::Changes` drives from a layer's `sdf::ChangeList` — an authoring call
//! drops only the affected prim indices, with a "blow the world" fallback for
//! layer-stack edits. The change-record derivation itself
//! (`sdf::ChangeList::from_overlay`) is unit-tested in `src/sdf/change.rs`.

use std::cell::RefCell;
use std::collections::HashMap;
use std::fs;
use std::path::Path as FsPath;
use std::rc::Rc;

use openusd::Result;
use openusd::{gf, pcp, sdf, tf, usd};

#[test]
fn change_list_entry_dedups() {
    let mut cl = sdf::ChangeList::new();
    let p = sdf::Path::abs_root();
    cl.entry_mut(&p).flags |= sdf::ChangeFlags::ADD_NON_INERT_PRIM;
    cl.entry_mut(&p).note("specifier", sdf::FieldChange::Value);
    assert_eq!(cl.entries().len(), 1);
    assert!(cl.entries()[0].1.flags.contains(sdf::ChangeFlags::ADD_NON_INERT_PRIM));
    assert!(cl.entries()[0].1.changed("specifier"));
}

#[test]
fn change_list_empty_until_entry() {
    let mut cl = sdf::ChangeList::new();
    assert!(cl.is_empty());
    cl.entry_mut(&sdf::Path::abs_root());
    assert!(!cl.is_empty());
}

fn open_in_memory() -> usd::Stage {
    usd::Stage::builder().in_memory("anon.usda").expect("in-memory stage")
}

fn exists(stage: &usd::Stage, path: &str) -> bool {
    stage.prim(path).unwrap().is_valid().unwrap()
}

fn child_names(stage: &usd::Stage, path: &str) -> Vec<String> {
    stage
        .prim(path)
        .unwrap()
        .child_names()
        .unwrap()
        .into_iter()
        .map(String::from)
        .collect()
}

/// The composed-change path channels a [`usd::CommittedChange`] reports,
/// accumulated across every notice an edit publishes.
#[derive(Default, Debug)]
struct Notices {
    resynced: Vec<sdf::Path>,
    changed_info_only: Vec<sdf::Path>,
    asset_paths_resynced: Vec<sdf::Path>,
}

/// Installs a sink recording all three channels, so a test can pin what an
/// `expressionVariables` edit publishes as well as what it invalidates.
fn capture_notices(stage: &usd::Stage) -> Rc<RefCell<Notices>> {
    let notices = Rc::new(RefCell::new(Notices::default()));
    let sink = notices.clone();
    stage.add_sink(move |_stage: &usd::Stage, change: &usd::CommittedChange<'_>| {
        let mut n = sink.borrow_mut();
        n.resynced.extend(change.resynced.iter().cloned());
        n.changed_info_only.extend(change.changed_info_only.iter().cloned());
        n.asset_paths_resynced
            .extend(change.asset_paths_resynced.iter().cloned());
    });
    notices
}

/// Parses each of `paths`, for comparing a captured channel against literals.
fn paths(paths: &[&str]) -> Vec<sdf::Path> {
    paths.iter().map(|p| sdf::path(p).expect("valid path")).collect()
}

/// The identifier of the loaded layer whose file name is `leaf`.
fn identifier_by_leaf(stage: &usd::Stage, leaf: &str) -> String {
    stage
        .layer_identifiers()
        .into_iter()
        .find(|id| FsPath::new(id).ends_with(leaf))
        .expect("layer is loaded")
}

/// Warm two sibling prim indices, author at one — the other must stay indexed.
#[test]
fn author_keeps_sibling_indexed() {
    let stage = open_in_memory();
    stage.define_prim("/Foo").unwrap().set_type_name("Xform").unwrap();
    stage.define_prim("/Bar").unwrap().set_type_name("Xform").unwrap();

    let _ = stage.prim("/Foo").unwrap().type_name().unwrap();
    let _ = stage.prim("/Bar").unwrap().type_name().unwrap();
    assert!(stage.is_indexed(&sdf::path("/Foo").unwrap()));
    assert!(stage.is_indexed(&sdf::path("/Bar").unwrap()));

    stage.override_prim("/Foo").unwrap().set_kind("component").unwrap();

    assert!(
        stage.is_indexed(&sdf::path("/Bar").unwrap()),
        "/Bar's index must not be dropped when authoring at /Foo",
    );
}

/// A significant change at an ancestor invalidates a self-root-only descendant.
///
/// `/Foo/Bar`'s sole node is the skipped self-Root, so it registers only in the
/// layer-agnostic `by_path` map and never appears in the per-layer subtree
/// lookup. The literal-path subtree drop in `fanout_significant` still reaches
/// it, because it is a namespace descendant of the changed `/Foo`.
#[test]
fn significant_at_ancestor_drops_descendant() {
    let stage = open_in_memory();
    stage.define_prim("/Foo").unwrap().set_type_name("Xform").unwrap();
    stage.define_prim("/Foo/Bar").unwrap().set_type_name("Xform").unwrap();

    let _ = stage.prim("/Foo").unwrap().type_name().unwrap();
    let _ = stage.prim("/Foo/Bar").unwrap().type_name().unwrap();
    assert!(stage.is_indexed(&sdf::path("/Foo").unwrap()));
    assert!(stage.is_indexed(&sdf::path("/Foo/Bar").unwrap()));

    stage.override_prim("/Foo").unwrap().set_instanceable(true).unwrap();

    assert!(
        !stage.is_indexed(&sdf::path("/Foo/Bar").unwrap()),
        "a significant change at /Foo must invalidate its self-root-only descendant /Foo/Bar",
    );
}

/// Attribute value writes never invalidate the owning prim's graph.
#[test]
fn attribute_value_keeps_owner_indexed() {
    let stage = open_in_memory();
    let attr = stage
        .define_prim("/A")
        .unwrap()
        .set_type_name("Xform")
        .unwrap()
        .create_attribute("x", "double")
        .unwrap()
        .set(sdf::Value::Double(1.0))
        .unwrap();

    let _ = stage.prim("/A").unwrap().type_name().unwrap();
    assert!(stage.is_indexed(&sdf::path("/A").unwrap()));

    let attr = attr.set(sdf::Value::Double(2.0)).unwrap();
    assert!(
        stage.is_indexed(&sdf::path("/A").unwrap()),
        "attribute value writes must not invalidate the prim graph",
    );
    assert_eq!(attr.get().unwrap(), Some(sdf::Value::Double(2.0)));
}

/// `instanceable` is a significant-promoter — authoring it drops the index.
#[test]
fn set_instanceable_invalidates_owner() {
    let stage = open_in_memory();
    stage.define_prim("/Inst").unwrap().set_type_name("Xform").unwrap();
    stage.define_prim("/Other").unwrap().set_type_name("Xform").unwrap();
    let _ = stage.prim("/Inst").unwrap().type_name().unwrap();
    let _ = stage.prim("/Other").unwrap().type_name().unwrap();
    assert!(stage.is_indexed(&sdf::path("/Inst").unwrap()));

    stage.override_prim("/Inst").unwrap().set_instanceable(true).unwrap();

    assert!(
        !stage.is_indexed(&sdf::path("/Inst").unwrap()),
        "instanceable is a significant-tier field; owner must be invalidated",
    );
    assert!(
        stage.is_indexed(&sdf::path("/Other").unwrap()),
        "unrelated prim must remain indexed",
    );
}

/// `kind` is a spec-only metadata change on an existing prim — the cached
/// index survives, and the new opinion is still visible (live read).
#[test]
fn kind_change_no_op_for_cache() {
    let stage = open_in_memory();
    let prim = stage.define_prim("/A").unwrap().set_type_name("Xform").unwrap();
    let _ = stage.prim("/A").unwrap().type_name().unwrap();
    assert!(stage.is_indexed(&sdf::path("/A").unwrap()));

    prim.set_kind("group").unwrap();

    assert!(
        stage.is_indexed(&sdf::path("/A").unwrap()),
        "spec-only field changes must not invalidate the prim graph",
    );
    assert_eq!(stage.prim("/A").unwrap().kind().unwrap().as_deref(), Some("group"));
}

/// A `defaultPrim` edit evicts only the prims whose composition resolved a
/// reference or payload through the field. Prims that never consulted it — here,
/// every prim on the stage — keep their cached indices.
#[test]
fn default_prim_keeps_unrelated() {
    let stage = open_in_memory();
    stage.define_prim("/World").unwrap().set_type_name("Xform").unwrap();
    stage.define_prim("/Other").unwrap().set_type_name("Xform").unwrap();

    let _ = stage.prim("/World").unwrap().type_name().unwrap();
    let _ = stage.prim("/Other").unwrap().type_name().unwrap();
    let pre = stage.indexed_count();
    assert!(pre >= 2);

    stage.set_default_prim("World").unwrap();

    assert_eq!(
        stage.indexed_count(),
        pre,
        "no prim resolves an arc through the default, so none is evicted",
    );
    assert_eq!(stage.default_prim().as_deref(), Some("World"));
}

/// `override_prim` on a cached miss invalidates so the over becomes visible.
#[test]
fn override_after_cached_miss() {
    let stage = open_in_memory();
    assert!(!exists(&stage, "/A"));
    assert!(stage.is_indexed(&sdf::path("/A").unwrap()));

    stage.override_prim("/A").unwrap();

    assert!(exists(&stage, "/A"), "inert add must invalidate cached empty index");
}

/// Auto-created ancestor `over`s are recorded so a cached miss on the ancestor
/// path gets invalidated alongside the new leaf.
#[test]
fn define_invalidates_ancestors() {
    let stage = open_in_memory();
    assert!(!exists(&stage, "/A"));
    assert!(!exists(&stage, "/A/B"));

    stage.define_prim("/A/B/C").unwrap().set_type_name("Xform").unwrap();

    assert!(exists(&stage, "/A"), "auto-created /A must be visible");
    assert!(exists(&stage, "/A/B"), "auto-created /A/B must be visible");
    assert!(child_names(&stage, "/A").contains(&"B".to_string()));
    assert!(child_names(&stage, "/A/B").contains(&"C".to_string()));
}

/// `create_attribute` auto-creates the owning prim; the ancestor add must
/// invalidate the cached miss.
#[test]
fn create_attribute_invalidates_owner() {
    let stage = open_in_memory();
    assert!(!exists(&stage, "/Mesh"));

    stage.create_attribute("/Mesh.x", "double").unwrap();

    assert!(
        exists(&stage, "/Mesh"),
        "auto-created owning prim /Mesh must be visible after create_attribute",
    );
}

/// A redundant `define_prim` on an existing prim is a no-op for the cache.
#[test]
fn idempotent_define_preserves_cache() {
    let stage = open_in_memory();
    stage.define_prim("/Foo").unwrap().set_type_name("Xform").unwrap();
    stage.define_prim("/Foo/Child").unwrap();
    let _ = stage.prim("/Foo").unwrap().type_name().unwrap();
    let _ = stage.prim("/Foo/Child").unwrap().type_name().unwrap();
    assert!(stage.is_indexed(&sdf::path("/Foo").unwrap()));
    assert!(stage.is_indexed(&sdf::path("/Foo/Child").unwrap()));

    stage.define_prim("/Foo").unwrap();

    assert!(stage.is_indexed(&sdf::path("/Foo").unwrap()));
    assert!(stage.is_indexed(&sdf::path("/Foo/Child").unwrap()));
}

/// A redundant `override_prim` on an existing spec is a no-op for the cache.
#[test]
fn idempotent_override_preserves_cache() {
    let stage = open_in_memory();
    stage.define_prim("/Foo").unwrap();
    let _ = stage.prim("/Foo").unwrap().type_name().unwrap();
    assert!(stage.is_indexed(&sdf::path("/Foo").unwrap()));

    stage.override_prim("/Foo").unwrap();

    assert!(stage.is_indexed(&sdf::path("/Foo").unwrap()));
}

/// `add_applied_schema` writes `apiSchemas`, which is resolved off the cached
/// prim index — the owner's index must drop.
#[test]
fn add_applied_schema_invalidates_owner() {
    let stage = open_in_memory();
    let prim = stage.define_prim("/A").unwrap().set_type_name("Xform").unwrap();
    assert_eq!(
        stage.prim(prim.path()).unwrap().api_schemas().unwrap(),
        Vec::<tf::Token>::new()
    );
    assert!(stage.is_indexed(&sdf::path("/A").unwrap()));

    prim.add_applied_schema("MaterialBindingAPI").unwrap();

    assert!(
        !stage.is_indexed(&sdf::path("/A").unwrap()),
        "apiSchemas authoring must invalidate the owner's cached prim index",
    );
    assert_eq!(
        stage.prim("/A").unwrap().api_schemas().unwrap(),
        vec![tf::Token::from("MaterialBindingAPI")],
    );
}

/// Re-setting `defaultPrim` to the current value must not blow the cache.
#[test]
fn idempotent_default_prim_preserves_cache() {
    let stage = open_in_memory();
    stage.define_prim("/World").unwrap();
    stage.set_default_prim("World").unwrap();
    let _ = stage.prim("/World").unwrap().type_name().unwrap();
    let pre = stage.indexed_count();
    assert!(pre > 0);

    stage.set_default_prim("World").unwrap();

    assert_eq!(
        stage.indexed_count(),
        pre,
        "redundant set_default_prim must not clear cached indices"
    );
}

/// Writes a stage whose `/Empty` references `@t.usda@` with no prim path (so the
/// arc resolves through the target's `defaultPrim`), `/Explicit` names the same
/// target prim outright, and `/Source` is an unrelated local prim that merely
/// shares the default prim's path. `t.usda`'s `defaultPrim` is `default_prim`.
fn open_default_prim_fixture(dir: &tempfile::TempDir, default_prim: Option<&str>) -> Result<usd::Stage> {
    let header = match default_prim {
        Some(name) => format!("#usda 1.0\n(\n    defaultPrim = \"{name}\"\n)\n"),
        None => "#usda 1.0\n".to_string(),
    };
    fs::write(
        dir.path().join("t.usda"),
        format!("{header}def \"Source\" {{ custom double y = 1 }}\ndef \"Second\" {{ custom double y = 2 }}\n"),
    )?;
    let root = dir.path().join("root.usda");
    fs::write(
        &root,
        r#"#usda 1.0
def "Empty" (
    references = @./t.usda@
)
{
}
def "Explicit" (
    references = @./t.usda@</Source>
)
{
}
def "Source" {
    custom double local = 3
}
"#,
    )?;
    let stage = usd::Stage::open(root.to_str().unwrap())?;
    // Warm every index, including the bystander cached at `/Source`.
    stage.attribute("/Empty.y")?.get::<f64>()?;
    assert_eq!(stage.attribute("/Explicit.y")?.get::<f64>()?, Some(1.0));
    assert_eq!(stage.attribute("/Source.local")?.get::<f64>()?, Some(3.0));
    Ok(stage)
}

/// Authors `name` as the referenced `t.usda`'s `defaultPrim`, the edit every
/// test over [`open_default_prim_fixture`] performs.
fn set_target_default_prim(stage: &usd::Stage, name: &str) -> Result<()> {
    let target = identifier_by_leaf(stage, "t.usda");
    stage
        .layer_mut(&target)
        .expect("target layer is live")
        .edit(|e| e.set_default_prim(name))?;
    Ok(())
}

/// Repointing a referenced layer's `defaultPrim` reports the C++ set: the
/// dependents of the prim path it used to name. That reaches the prim that
/// resolved through the field and the one that named the same path explicitly —
/// which C++ resyncs too — but not a stage prim that merely happens to be cached
/// at that path and never reads the edited layer.
#[test]
fn default_prim_resync_notice() -> Result<()> {
    let dir = tempfile::tempdir()?;
    let stage = open_default_prim_fixture(&dir, Some("Source"))?;
    let notices = capture_notices(&stage);

    set_target_default_prim(&stage, "Second")?;

    assert!(!stage.is_indexed(&sdf::path("/Empty")?), "the consumer is evicted");
    assert!(
        stage.is_indexed(&sdf::path("/Explicit")?),
        "an explicit target composes the same, so it is reported but not evicted"
    );
    assert_eq!(stage.attribute("/Empty.y")?.get::<f64>()?, Some(2.0));
    let notices = notices.borrow();
    assert_eq!(notices.resynced, paths(&["/Empty", "/Explicit"]));
    assert_eq!(
        notices.changed_info_only,
        paths(&["/"]),
        "the layer's own metadata changed, and no resync covers its pseudo-root"
    );
    Ok(())
}

/// Authoring a `defaultPrim` where there was none reports the prims that
/// recorded consulting the field. C++ reaches them by fanning out from the
/// pseudo-root site on the layer, which also sweeps in every other dependent of
/// it; the record names exactly the consumers, so `/Explicit` stays out.
#[test]
fn absent_default_notice() -> Result<()> {
    let dir = tempfile::tempdir()?;
    let stage = open_default_prim_fixture(&dir, None)?;
    let notices = capture_notices(&stage);
    assert_eq!(
        stage.attribute("/Empty.y")?.get::<f64>()?,
        None,
        "nothing to resolve yet"
    );

    set_target_default_prim(&stage, "Source")?;

    assert_eq!(
        stage.attribute("/Empty.y")?.get::<f64>()?,
        Some(1.0),
        "the arc that had no default recomposes"
    );
    let notices = notices.borrow();
    assert_eq!(notices.resynced, paths(&["/Empty"]));
    assert_eq!(
        notices.changed_info_only,
        paths(&["/"]),
        "no resync covers the pseudo-root, so the metadata change is still reported"
    );
    Ok(())
}

/// The same edit on the stage's own root layer — what `Stage::set_default_prim`
/// always writes — reports only the internal reference that consults it, not
/// every prim reading the root layer.
#[test]
fn root_layer_default_notice() -> Result<()> {
    let dir = tempfile::tempdir()?;
    let root = dir.path().join("root.usda");
    fs::write(
        &root,
        r#"#usda 1.0
def "Source" {
    custom double y = 1
}
def "Empty" (
    references = <>
)
{
}
def "Other" {
    custom double o = 3
}
"#,
    )?;
    let stage = usd::Stage::open(root.to_str().unwrap())?;
    assert_eq!(
        stage.attribute("/Empty.y")?.get::<f64>()?,
        None,
        "no default to resolve"
    );
    assert_eq!(stage.attribute("/Other.o")?.get::<f64>()?, Some(3.0));
    let notices = capture_notices(&stage);

    stage.set_default_prim("Source")?;

    assert_eq!(
        notices.borrow().resynced,
        paths(&["/Empty"]),
        "only the internal reference consults the field, though every prim reads this layer"
    );
    assert_eq!(
        stage.attribute("/Empty.y")?.get::<f64>()?,
        Some(1.0),
        "and it recomposes against the new default"
    );
    Ok(())
}

/// Re-spelling the same prim leaves the composed default where it was, so
/// nothing resyncs and nothing is evicted — but the authored token did change,
/// so the pseudo-root is still reported as changed info.
#[test]
fn respelling_info_only_notice() -> Result<()> {
    let dir = tempfile::tempdir()?;
    let stage = open_default_prim_fixture(&dir, Some("Source"))?;
    let pre = stage.indexed_count();
    let notices = capture_notices(&stage);

    set_target_default_prim(&stage, "/Source")?;

    // Read through the stage before borrowing the sink's slot: a composed read
    // drains any pending edit, which fires the sink.
    assert_eq!(stage.indexed_count(), pre, "nothing is evicted");
    let notices = notices.borrow();
    assert!(notices.resynced.is_empty(), "nothing resyncs: {:?}", notices.resynced);
    assert_eq!(notices.changed_info_only, paths(&["/"]));
    Ok(())
}

/// Writes a stage whose `/User` selects a variant through `${SEL}` while
/// `/Other` reads no variable, and opens it — the fixture behind the
/// fine-grained `expressionVariables` invalidation tests.
fn open_variant_fixture(dir: &tempfile::TempDir) -> Result<usd::Stage> {
    let root = dir.path().join("root.usda");
    fs::write(
        &root,
        r#"#usda 1.0
(
    expressionVariables = { string SEL = "x" }
)
def "User" (
    variantSets = "v"
    variants = { string v = "`${SEL}`" }
)
{
    variantSet "v" = {
        "x" { custom double vx = 1 }
        "y" { custom double vy = 2 }
    }
}
def "Other" {
    custom double o = 3
}
"#,
    )?;
    let stage = usd::Stage::open(root.to_str().unwrap())?;
    assert_eq!(stage.attribute("/User.vx")?.get::<f64>()?, Some(1.0), "SEL=x at open");
    assert_eq!(stage.attribute("/Other.o")?.get::<f64>()?, Some(3.0));
    assert!(stage.is_indexed(&sdf::path("/User")?));
    assert!(stage.is_indexed(&sdf::path("/Other")?));
    Ok(stage)
}

/// Editing `expressionVariables` to add a name no prim reads keeps every
/// cached index warm — the fine-grained diff finds no dependents (C++
/// `_DidChangeLayerStackExpressionVariables` step 4, empty intersection).
#[test]
fn unused_var_keeps_index() -> Result<()> {
    let dir = tempfile::tempdir()?;
    let stage = open_variant_fixture(&dir)?;
    let notices = capture_notices(&stage);

    stage.set_expression_variables(HashMap::from([
        ("SEL".to_string(), sdf::Value::String("x".to_string())),
        ("FREE".to_string(), sdf::Value::String("z".to_string())),
    ]))?;

    {
        let notices = notices.borrow();
        assert!(
            notices.resynced.is_empty(),
            "no prim reads FREE, got {:?}",
            notices.resynced
        );
        assert_eq!(
            notices.asset_paths_resynced,
            paths(&["/"]),
            "the root stack's composed variables moved, so any asset value may re-resolve"
        );
        assert_eq!(notices.changed_info_only, paths(&["/"]));
    }
    assert!(
        stage.is_indexed(&sdf::path("/User")?),
        "/User reads SEL, whose value is unchanged — its index survives"
    );
    assert!(
        stage.is_indexed(&sdf::path("/Other")?),
        "/Other reads no variable — its index survives"
    );
    Ok(())
}

/// Changing a variable's value drops exactly the prims whose builds recorded
/// reading it: `/User`'s variant selection recomposes to the new branch while
/// `/Other` stays indexed.
#[test]
fn used_var_drops_user() -> Result<()> {
    let dir = tempfile::tempdir()?;
    let stage = open_variant_fixture(&dir)?;
    let notices = capture_notices(&stage);

    stage.set_expression_variables(HashMap::from([(
        "SEL".to_string(),
        sdf::Value::String("y".to_string()),
    )]))?;

    {
        let notices = notices.borrow();
        assert_eq!(notices.resynced, paths(&["/User"]), "only the reader recomposes");
        assert_eq!(notices.asset_paths_resynced, paths(&["/"]));
        assert_eq!(notices.changed_info_only, paths(&["/"]));
    }
    assert!(
        !stage.is_indexed(&sdf::path("/User")?),
        "/User recorded reading SEL, so its index drops"
    );
    assert!(
        stage.is_indexed(&sdf::path("/Other")?),
        "/Other reads no variable — its index survives"
    );
    assert_eq!(
        stage.attribute("/User.vy")?.get::<f64>()?,
        Some(2.0),
        "/User recomposes with the new selection"
    );
    assert_eq!(stage.attribute("/User.vx")?.get::<f64>()?, None);
    Ok(())
}

/// A changed name that feeds a stack's own `${VAR}` sublayer entry is
/// significant for every prim using the stack — the membership swaps — so even
/// a prim reading no variable drops (C++ step 3, the sublayer-dependency hit).
#[test]
fn sublayer_dep_drops_stack() -> Result<()> {
    let dir = tempfile::tempdir()?;
    let root = dir.path().join("root.usda");
    fs::write(
        &root,
        r#"#usda 1.0
(
    expressionVariables = { string W = "a" }
    subLayers = [@`"${W}.usda"`@]
)
def "Other" {
    custom double o = 3
}
"#,
    )?;
    fs::write(
        dir.path().join("a.usda"),
        r#"#usda 1.0
def "A" {
    custom double x = 1
}
"#,
    )?;
    fs::write(
        dir.path().join("b.usda"),
        r#"#usda 1.0
def "B" {
    custom double y = 2
}
"#,
    )?;

    let stage = usd::Stage::open(root.to_str().unwrap())?;
    assert_eq!(stage.attribute("/A.x")?.get::<f64>()?, Some(1.0), "W=a at open");
    assert_eq!(stage.attribute("/Other.o")?.get::<f64>()?, Some(3.0));
    let notices = capture_notices(&stage);

    stage.set_expression_variables(HashMap::from([("W".to_string(), sdf::Value::String("b".to_string()))]))?;

    assert!(
        !stage.is_indexed(&sdf::path("/Other")?),
        "W selects a root-stack sublayer, so the change is stack-significant"
    );
    {
        let notices = notices.borrow();
        assert_eq!(notices.resynced, paths(&["/"]), "the whole root stack recomposes");
        assert!(
            notices.asset_paths_resynced.is_empty(),
            "the stage-wide resync already covers every asset value, got {:?}",
            notices.asset_paths_resynced
        );
        assert!(
            notices.changed_info_only.is_empty(),
            "the pseudo-root info change is subsumed by the pseudo-root resync"
        );
    }
    assert_eq!(
        stage.attribute("/B.y")?.get::<f64>()?,
        Some(2.0),
        "the newly selected b.usda loads and composes"
    );
    assert_eq!(
        stage.attribute("/A.x")?.get::<f64>()?,
        None,
        "a.usda's selection dropped"
    );
    Ok(())
}

/// Authoring a reference target's first `expressionVariables` flips the target
/// stack's variable source (root → itself), which resyncs every prim using the
/// stack even though no prim recorded reading a variable (C++ step 2). Its
/// composed set moved too — from empty to the authored pair — so the asset-path
/// channel names the same prims, and the resync subsumes them.
#[test]
fn source_change_resyncs() -> Result<()> {
    let dir = tempfile::tempdir()?;
    let root = dir.path().join("root.usda");
    fs::write(
        &root,
        r#"#usda 1.0
def "P" (
    references = @t.usda@
) {}
def "Other" {
    custom double o = 3
}
"#,
    )?;
    fs::write(
        dir.path().join("t.usda"),
        r#"#usda 1.0
(
    defaultPrim = "P"
)
def "P" {
    custom double x = 1
}
"#,
    )?;

    let stage = usd::Stage::open(root.to_str().unwrap())?;
    assert_eq!(stage.attribute("/P.x")?.get::<f64>()?, Some(1.0));
    assert_eq!(stage.attribute("/Other.o")?.get::<f64>()?, Some(3.0));

    let notices = capture_notices(&stage);
    let target_id = identifier_by_leaf(&stage, "t.usda");
    stage.layer_mut(&target_id).expect("target layer is live").edit(|e| {
        e.set_expression_variables(HashMap::from([("V".to_string(), sdf::Value::String("x".to_string()))]))
    })?;

    assert!(
        !stage.is_indexed(&sdf::path("/P")?),
        "the target stack's variable source flipped, so its user resyncs"
    );
    {
        let notices = notices.borrow();
        assert_eq!(notices.resynced, paths(&["/P"]));
        assert!(
            notices.asset_paths_resynced.is_empty(),
            "the /P resync already covers its asset values, got {:?}",
            notices.asset_paths_resynced
        );
        // The edited layer is not local, so this is `Provenance::DirectLayerEdit`
        // and the entry is `t.usda`'s own pseudo-root. Pruning compares it only
        // against the resyncs in its own namespace, and the stage-namespace `/P`
        // is not one of them, so it survives untouched.
        assert_eq!(notices.changed_info_only, paths(&["/"]));
    }
    assert!(
        stage.is_indexed(&sdf::path("/Other")?),
        "/Other does not use the target stack — its index survives"
    );
    assert_eq!(stage.attribute("/P.x")?.get::<f64>()?, Some(1.0), "/P recomposes");
    Ok(())
}

/// A root variable read inside a referenced stack: the root edit's delta
/// cascades to the seeded target stack (C++ step 5), and the prim recorded its
/// read through the ancestral sub-build merge, so exactly that prim resyncs
/// and recomposes against the newly selected asset.
#[test]
fn chain_propagation() -> Result<()> {
    let dir = tempfile::tempdir()?;
    let root = dir.path().join("root.usda");
    fs::write(
        &root,
        r#"#usda 1.0
(
    expressionVariables = { string V = "x" }
)
def "P" (
    references = @a.usda@</Outer/Inner>
) {}
def "Other" {
    custom double o = 3
}
"#,
    )?;
    fs::write(
        dir.path().join("a.usda"),
        r#"#usda 1.0
def "Outer" (
    references = @`"${V}.usda"`@
)
{
    def "Inner" {}
}
"#,
    )?;
    fs::write(
        dir.path().join("x.usda"),
        r#"#usda 1.0
(
    defaultPrim = "O"
)
def "O" {
    def "Inner" {
        custom double vx = 1
    }
}
"#,
    )?;
    fs::write(
        dir.path().join("y.usda"),
        r#"#usda 1.0
(
    defaultPrim = "O"
)
def "O" {
    def "Inner" {
        custom double vy = 2
    }
}
"#,
    )?;

    let stage = usd::Stage::open(root.to_str().unwrap())?;
    assert_eq!(
        stage.attribute("/P.vx")?.get::<f64>()?,
        Some(1.0),
        "V=x reaches the referenced stack's `${{V}}` reference"
    );
    assert_eq!(stage.attribute("/Other.o")?.get::<f64>()?, Some(3.0));
    let notices = capture_notices(&stage);

    stage.set_expression_variables(HashMap::from([("V".to_string(), sdf::Value::String("y".to_string()))]))?;

    assert!(
        !stage.is_indexed(&sdf::path("/P")?),
        "the delta cascades to the seeded target stack and finds /P's recorded read"
    );
    {
        let notices = notices.borrow();
        assert_eq!(notices.resynced, paths(&["/P"]), "only the recorded reader recomposes");
        assert_eq!(
            notices.asset_paths_resynced,
            paths(&["/"]),
            "the root stack moved too, so its pseudo-root subsumes the cascaded stack's users"
        );
        assert_eq!(notices.changed_info_only, paths(&["/"]));
    }
    assert!(
        stage.is_indexed(&sdf::path("/Other")?),
        "/Other reads no variable — its index survives"
    );
    assert_eq!(
        stage.attribute("/P.vy")?.get::<f64>()?,
        Some(2.0),
        "/P recomposes against the newly selected y.usda"
    );
    assert_eq!(stage.attribute("/P.vx")?.get::<f64>()?, None);
    Ok(())
}

/// A failed `${VAR}` evaluation records the undefined name as a dependency, so
/// later defining the variable resyncs the prim and the repaired arc composes
/// — without the definition, the failure would pin forever.
#[test]
fn failure_records_dep() -> Result<()> {
    let dir = tempfile::tempdir()?;
    let root = dir.path().join("root.usda");
    fs::write(
        &root,
        r#"#usda 1.0
def "P" (
    references = @`${TGT}`@
)
{
    custom double local = 5
}
"#,
    )?;
    fs::write(
        dir.path().join("t.usda"),
        r#"#usda 1.0
(
    defaultPrim = "P"
)
def "P" {
    custom double x = 1
}
"#,
    )?;

    let stage = usd::Stage::open(root.to_str().unwrap())?;
    assert_eq!(
        stage.attribute("/P.local")?.get::<f64>()?,
        Some(5.0),
        "the prim composes past the failed arc expression"
    );
    assert!(
        stage
            .composition_errors()
            .iter()
            .any(|e| matches!(e, pcp::CompositionDiagnostic::InvalidExpression { .. })),
        "the undefined reference expression is diagnosed"
    );
    assert!(stage.is_indexed(&sdf::path("/P")?));

    stage.set_expression_variables(HashMap::from([(
        "TGT".to_string(),
        sdf::Value::String("t.usda".to_string()),
    )]))?;

    assert_eq!(
        stage.attribute("/P.x")?.get::<f64>()?,
        Some(1.0),
        "defining TGT resyncs /P and the repaired reference composes"
    );
    assert!(
        stage.composition_errors().is_empty(),
        "the healed expression stops reporting, got {:?}",
        stage.composition_errors()
    );
    Ok(())
}

/// A reference fixture still composes correctly through the dependency-aware
/// cache after the change-recording rework.
#[test]
fn reference_fixture_composes() {
    let manifest = std::env::var("CARGO_MANIFEST_DIR").unwrap();
    let path = format!("{manifest}/fixtures/sublayer_override.usda");
    let stage = usd::Stage::open(&path).expect("open sublayer fixture");

    let children = child_names(&stage, "/World");
    assert!(children.contains(&"Cube".to_string()));
    assert!(children.contains(&"Sphere".to_string()));
    assert!(stage.is_indexed(&sdf::path("/World").unwrap()));
}

/// The automatic layer-stack sweep, end to end through the public API:
/// composing enough reference targets ripens the mint-count trigger, so the
/// next edit seam (a mute) sweeps — removing the muted target's stack, which
/// nothing references once its user's index dropped — and the unmute demand
/// path recomposes it transparently, values intact.
#[test]
fn threshold_sweep_recomposes() -> Result<()> {
    let dir = tempfile::tempdir()?;
    let count = 40;
    let mut root_text = String::from("#usda 1.0\n");
    for i in 0..count {
        root_text.push_str(&format!("def \"P{i}\" (\n    references = @t{i}.usda@</P>\n) {{}}\n"));
        fs::write(
            dir.path().join(format!("t{i}.usda")),
            format!("#usda 1.0\ndef \"P\" {{\n    custom double x = {i}\n}}\n"),
        )?;
    }
    let root = dir.path().join("root.usda");
    fs::write(&root, root_text)?;

    let stage = usd::Stage::open(root.to_str().unwrap())?;
    for i in 0..count {
        assert_eq!(stage.attribute(format!("/P{i}.x"))?.get::<f64>()?, Some(i as f64));
    }

    // The mute drops /P0's index and runs the ripe sweep; every other target
    // stack stays referenced by its cached index and survives.
    let t0 = identifier_by_leaf(&stage, "t0.usda");
    stage.mute_layer(t0.clone());
    assert_eq!(
        stage.attribute("/P0.x")?.get::<f64>()?,
        None,
        "the muted target is gone"
    );
    assert!(
        stage.is_indexed(&sdf::path("/P39")?),
        "unrelated indices survive the sweep"
    );

    stage.unmute_layer(&t0);
    for i in 0..count {
        assert_eq!(
            stage.attribute(format!("/P{i}.x"))?.get::<f64>()?,
            Some(i as f64),
            "every target composes after the sweep-and-recompose round trip"
        );
    }
    assert!(
        stage.composition_errors().is_empty(),
        "no diagnostics accrete across the sweep, got {:?}",
        stage.composition_errors()
    );
    Ok(())
}

/// A clip set's `clips` dictionary, selecting `active_index` from two clips.
fn clip_metadata(active_index: f64) -> sdf::Value {
    let set = HashMap::from([
        (
            "assetPaths".to_string(),
            sdf::Value::AssetPathVec(vec!["./clipA.usda".into(), "./clipB.usda".into()]),
        ),
        (
            "manifestAssetPath".to_string(),
            sdf::Value::AssetPath("./manifest.usda".into()),
        ),
        ("primPath".to_string(), sdf::Value::String("/Model".to_string())),
        (
            "active".to_string(),
            sdf::Value::Vec2dVec(vec![gf::vec2d(0.0, active_index)]),
        ),
    ]);
    sdf::Value::Dictionary(HashMap::from([("default".to_string(), sdf::Value::Dictionary(set))]))
}

/// A stage whose `/Model` carries a two-clip set selecting the first, with the
/// subtree composed so there is something for a later edit to evict.
fn open_clip_fixture(dir: &tempfile::TempDir) -> Result<usd::Stage> {
    for (name, sample) in [("clipA.usda", 1.0), ("clipB.usda", 2.0)] {
        fs::write(
            dir.path().join(name),
            format!("#usda 1.0\ndef \"Model\"\n{{\n    float size.timeSamples = {{\n        0: {sample}\n    }}\n}}\n"),
        )?;
    }
    fs::write(
        dir.path().join("manifest.usda"),
        "#usda 1.0\ndef \"Model\"\n{\n    float size\n}\n",
    )?;
    let root = dir.path().join("root.usda");
    fs::write(
        &root,
        "#usda 1.0\ndef \"Model\"\n{\n    float size\n    def \"Child\"\n    {\n    }\n}\n",
    )?;

    let stage = usd::Stage::open(root.to_str().unwrap())?;
    stage
        .prim("/Model")?
        .set_metadata(sdf::FieldKey::Clips.as_str(), clip_metadata(0.0))?;
    assert!(exists(&stage, "/Model/Child"));
    assert_eq!(clip_value(&stage), Some(1.0));
    Ok(stage)
}

/// `/Model.size` at time 0. Read through `sdf::Value` because a usda
/// `timeSamples` entry carries the type its literal spells, not the one the
/// attribute declares.
fn clip_value(stage: &usd::Stage) -> Option<f64> {
    stage
        .attribute("/Model.size")
        .unwrap()
        .get_at::<sdf::Value>(usd::TimeCode::new(0.0))
        .expect("value_at")
        .map(|value| value.cast::<f64>().expect("numeric"))
}

/// Editing what a clip set holds invalidates nothing: the sets are composed
/// live on each clip query, and only whether the metadata exists is cached.
#[test]
fn clip_edit_is_inert() -> Result<()> {
    let dir = tempfile::tempdir()?;
    let stage = open_clip_fixture(&dir)?;
    let pre = stage.indexed_count();
    let notices = capture_notices(&stage);

    // Re-point the schedule at the other clip: the metadata is still there, so
    // only what it holds changed.
    stage
        .prim("/Model")?
        .set_metadata(sdf::FieldKey::Clips.as_str(), clip_metadata(1.0))?;

    // Read through the stage before borrowing the sink's slot: a composed read
    // drains any pending edit, which fires the sink.
    assert_eq!(clip_value(&stage), Some(2.0), "the new schedule takes effect");
    assert_eq!(stage.indexed_count(), pre, "nothing is evicted");
    let notices = notices.borrow();
    assert!(notices.resynced.is_empty(), "nothing resyncs: {:?}", notices.resynced);
    Ok(())
}

/// Removing the metadata, by contrast, is a presence change and must resync the
/// subtree that inherited the cached answer.
#[test]
fn clip_removal_resyncs_subtree() -> Result<()> {
    let dir = tempfile::tempdir()?;
    let stage = open_clip_fixture(&dir)?;
    let notices = capture_notices(&stage);

    stage.prim("/Model")?.clear_metadata(sdf::FieldKey::Clips.as_str())?;

    assert_eq!(clip_value(&stage), None, "the clips no longer source the value");
    let notices = notices.borrow();
    assert_eq!(notices.resynced, paths(&["/Model"]));
    Ok(())
}

/// A value edit is reported at every composed path that reads it, not only the
/// one it was authored on: a prim referencing the edited site composes the same
/// property, and a consumer watching it must be told (C++
/// `_AddAffectedStagePaths` translates an info change through the dependency
/// map before reporting it).
#[test]
fn info_change_names_referrer() {
    let stage = open_in_memory();
    stage.define_prim("/Source").unwrap();
    stage.create_attribute("/Source.x", "double").unwrap();
    stage
        .override_prim("/Ref")
        .unwrap()
        .set_metadata(
            sdf::FieldKey::References.as_str(),
            sdf::Value::ReferenceListOp(sdf::ReferenceListOp::prepended([sdf::Reference {
                prim_path: sdf::path("/Source").unwrap(),
                ..Default::default()
            }])),
        )
        .unwrap();
    // Compose the referrer so the dependency map records what it reads.
    assert_eq!(stage.attribute("/Ref.x").unwrap().get::<f64>().unwrap(), None);

    let notices = capture_notices(&stage);
    stage
        .attribute("/Source.x")
        .unwrap()
        .set(sdf::Value::Double(4.0))
        .unwrap();

    let notices = notices.borrow();
    assert!(
        notices.changed_info_only.contains(&sdf::path("/Ref.x").unwrap()),
        "the referrer's composed property must be reported, got {:?}",
        notices.changed_info_only
    );
    assert!(
        notices.changed_info_only.contains(&sdf::path("/Source.x").unwrap()),
        "so must the authored path itself, got {:?}",
        notices.changed_info_only
    );
}

/// A relocate renames a referenced prim in the referrer's namespace, so a
/// resync under the relocation source must be reported at the *relocated*
/// composed path — the one a consumer watches — and not at the pre-relocation
/// path an identity translation would produce.
#[test]
fn relocated_resync_notice() -> Result<()> {
    let dir = relocated_reference()?;
    let stage = usd::Stage::open(dir.path().join("root.usda").to_str().unwrap())?;
    // Compose the relocated prim so its index is cached and its dependency on
    // the source site registered; nothing is registered for a prim never built.
    assert!(stage.prim("/Ref/Moved")?.is_valid()?);

    let notices = capture_notices(&stage);
    // `active` is a significant field, so this goes through the significant
    // tier rather than being reported as an info change. The edit targets the
    // referenced layer, where the prim is actually authored.
    let source = identifier_by_leaf(&stage, "source.usda");
    stage.layer_mut(&source).expect("loaded").edit(|edit| {
        edit.prim_mut(&sdf::path("/Source/Inner")?)
            .expect("the source layer parsed")
            .expect("the prim is authored there")
            .set_active(false);
        Ok(())
    })?;

    // The edit is queued; composing again publishes it to the sink.
    let _ = stage.prim("/Ref/Moved")?.is_valid()?;
    let notices = notices.borrow();
    assert!(
        notices.resynced.contains(&sdf::path("/Ref/Moved")?),
        "the relocated composed path must be resynced, got {:?}",
        notices.resynced
    );
    assert!(
        !notices.resynced.contains(&sdf::path("/Ref/Inner")?),
        "the pre-relocation path is not a composed path, got {:?}",
        notices.resynced
    );
    Ok(())
}

/// The info-only channel translates the whole path, property suffix included,
/// so a value edit under a relocation source is reported at the relocated
/// property (C++ `_AddAffectedStagePaths`).
#[test]
fn relocated_info_notice() -> Result<()> {
    let dir = relocated_reference()?;
    let stage = usd::Stage::open(dir.path().join("root.usda").to_str().unwrap())?;
    // Warm the consumer: the dependency exists only for a cached index.
    assert_eq!(stage.attribute("/Ref/Moved.x")?.get::<f64>()?, Some(1.0));

    let notices = capture_notices(&stage);
    let source = identifier_by_leaf(&stage, "source.usda");
    stage.layer_mut(&source).expect("loaded").edit(|edit| {
        edit.attribute_mut(&sdf::path("/Source/Inner.x")?)
            .expect("the source layer parsed")
            .expect("the attribute is authored there")
            .set_default(sdf::Value::Double(2.0))?;
        Ok(())
    })?;

    // The edit is queued; reading through it publishes the notice.
    assert_eq!(stage.attribute("/Ref/Moved.x")?.get::<f64>()?, Some(2.0));
    let notices = notices.borrow();
    assert!(
        notices.changed_info_only.contains(&sdf::path("/Ref/Moved.x")?),
        "the relocated composed property must be named, got {:?}",
        notices.changed_info_only
    );
    assert!(
        !notices.changed_info_only.contains(&sdf::path("/Ref/Inner.x")?),
        "the identity-derived path must not appear, got {:?}",
        notices.changed_info_only
    );
    Ok(())
}

/// A reference whose target relocates `/Source/Inner` to `/Source/Moved`, so
/// the referrer composes it at `/Ref/Moved` — a rename *below* the arc's own
/// site, which is what an identity translation cannot reconstruct.
fn relocated_reference() -> Result<tempfile::TempDir> {
    let dir = tempfile::tempdir()?;
    fs::write(
        dir.path().join("source.usda"),
        r#"#usda 1.0

def "Source"
{
    def "Inner"
    {
        double x = 1
    }
}
"#,
    )?;
    // The relocate is authored in the referrer's own layer stack, where the
    // source carries no opinion of its own — an opinion at a relocation source
    // is invalid in the stack that relocates it.
    fs::write(
        dir.path().join("root.usda"),
        r#"#usda 1.0
(
    relocates = {
        </Ref/Inner>: </Ref/Moved>
    }
)

def "Ref" (
    references = @./source.usda@</Source>
)
{
}
"#,
    )?;
    Ok(dir)
}