musefs-core 1.2.0

Orchestration for musefs: virtual tree, tag resolution, and scanning.
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
mod common;
use common::make_flac;
use common::{streaminfo_body, vorbis_comment_body};
use musefs_core::{CoreError, MountConfig, Musefs, VirtualTree, scan_directory};
use std::collections::BTreeMap;

fn config() -> MountConfig {
    MountConfig {
        template: "$artist/$title".to_string(),
        fallbacks: BTreeMap::new(),
        default_fallback: "Unknown".to_string(),
        mode: musefs_core::Mode::Synthesis,
        poll_interval: std::time::Duration::ZERO,
        case_insensitive: false,
        read_ahead_budget: 64 * 1024 * 1024,
        read_ahead_prefetch: false,
        skip_on_missing: false,
    }
}

fn scanned_db(dir: &std::path::Path) -> musefs_db::Db {
    let a = make_flac(
        &[
            (0, streaminfo_body()),
            (4, vorbis_comment_body("v", &["ARTIST=Alice", "TITLE=Song"])),
        ],
        &[0xAB; 64],
    );
    std::fs::write(dir.join("a.flac"), &a).unwrap();
    let db = musefs_db::Db::open_in_memory().unwrap();
    // Use an on-disk DB? in-memory is fine; scan writes absolute backing paths.
    scan_directory(&db, dir).unwrap();
    db
}

#[test]
fn lookup_getattr_readdir_and_read_through_the_facade() {
    let dir = tempfile::tempdir().unwrap();
    let db = scanned_db(dir.path());
    let fs = Musefs::open(db, config()).unwrap();

    // Tree: /Alice/Song.flac
    let artist = fs.lookup(VirtualTree::ROOT, "Alice").expect("artist dir");
    let dattr = fs.getattr(artist).unwrap();
    assert!(dattr.is_dir);

    let entries = fs.readdir(artist).unwrap();
    assert_eq!(entries.len(), 1);
    let (name, file_inode, is_dir) = entries.into_iter().next().unwrap();
    assert_eq!(name, "Song.flac");
    assert!(!is_dir);

    let fattr = fs.getattr(file_inode).unwrap();
    assert!(!fattr.is_dir);
    assert!(fattr.size > 0);

    // Reading the whole file yields a valid FLAC whose TITLE is the synthesized value.
    let bytes = fs.read(file_inode, None, 0, fattr.size).unwrap();
    assert_eq!(bytes.len() as u64, fattr.size);
    let tag = metaflac::Tag::read_from(&mut std::io::Cursor::new(&bytes)).unwrap();
    assert_eq!(
        tag.vorbis_comments()
            .unwrap()
            .get("TITLE")
            .map(std::vec::Vec::as_slice),
        Some(["Song".to_string()].as_slice())
    );
}

#[test]
fn parent_exposes_the_tree_hierarchy() {
    let dir = tempfile::tempdir().unwrap();
    let db = scanned_db(dir.path());
    let fs = Musefs::open(db, config()).unwrap();

    let artist = fs.lookup(VirtualTree::ROOT, "Alice").unwrap();
    assert_eq!(fs.parent(artist), Some(VirtualTree::ROOT));
    assert_eq!(fs.parent(VirtualTree::ROOT), Some(VirtualTree::ROOT));
    assert_eq!(fs.parent(424_242), None);
}

#[test]
fn refresh_rebuilds_tree_after_new_tracks() {
    let dir = tempfile::tempdir().unwrap();
    let db = scanned_db(dir.path());
    let fs = Musefs::open(db, config()).unwrap();
    assert!(fs.lookup(VirtualTree::ROOT, "Alice").is_some());
    assert!(fs.lookup(VirtualTree::ROOT, "Bob").is_none());

    // This test only asserts refresh_for_test() runs and the tree is rebuilt from
    // the DB; adding rows would require a handle to the DB, which Musefs now owns.
    // So we simply confirm it succeeds and the existing entry is still present.
    fs.refresh_for_test().unwrap();
    assert!(fs.lookup(VirtualTree::ROOT, "Alice").is_some());
}

#[test]
fn readdir_distinguishes_a_file_from_an_unknown_inode() {
    let dir = tempfile::tempdir().unwrap();
    let db = scanned_db(dir.path());
    let fs = Musefs::open(db, config()).unwrap();

    let artist = fs.lookup(VirtualTree::ROOT, "Alice").unwrap();
    let file = fs.readdir(artist).unwrap()[0].1;

    match fs.readdir(file) {
        Err(CoreError::NotADir(i)) => assert_eq!(i, file),
        other => panic!("expected NotADir, got {other:?}"),
    }
    match fs.readdir(987_654) {
        Err(CoreError::NoEntry(i)) => assert_eq!(i, 987_654),
        other => panic!("expected NoEntry, got {other:?}"),
    }
}

#[test]
fn reads_a_synthesized_mp3_through_the_facade() {
    use id3::TagLike;
    use std::io::Cursor;

    let dir = tempfile::tempdir().unwrap();

    // Backing MP3: ID3v2.4 tag (artist=Zoe, title=Old) + a fake audio frame.
    let mut tag = id3::Tag::new();
    tag.set_artist("Zoe");
    tag.set_title("Old");
    let mut bytes = Vec::new();
    tag.write_to(&mut bytes, id3::Version::Id3v24).unwrap();
    let audio = [0xFFu8, 0xFB, 7, 7, 7, 7];
    bytes.extend_from_slice(&audio);
    std::fs::write(dir.path().join("song.mp3"), &bytes).unwrap();

    let db = musefs_db::Db::open_in_memory().unwrap();
    scan_directory(&db, dir.path()).unwrap();
    let fs = Musefs::open(db, config()).unwrap();

    // Tree: /Zoe/Old.mp3
    let artist = fs.lookup(VirtualTree::ROOT, "Zoe").expect("artist dir");
    let entries = fs.readdir(artist).unwrap();
    let (name, file_inode, _) = entries.into_iter().next().unwrap();
    assert_eq!(name, "Old.mp3");

    let attr = fs.getattr(file_inode).unwrap();
    let whole = fs.read(file_inode, None, 0, attr.size).unwrap();
    assert_eq!(whole.len() as u64, attr.size);

    // The synthesized file is a valid ID3v2.4 stream carrying the DB tags, and the
    // original audio frames are spliced in unchanged at the tail.
    let parsed = id3::Tag::read_from2(Cursor::new(&whole)).unwrap();
    assert_eq!(parsed.artist(), Some("Zoe"));
    assert_eq!(parsed.title(), Some("Old"));
    assert_eq!(&whole[whole.len() - audio.len()..], &audio);
}

#[test]
fn reads_a_synthesized_m4a_through_the_facade() {
    let dir = tempfile::tempdir().unwrap();

    // Backing M4A: moov-first with ilst (title="Orig M4A", artist="Orig Artist")
    // and an mdat carrying verbatim audio.
    let audio = b"AUDIODATA";
    std::fs::write(dir.path().join("song.m4a"), common::minimal_m4a(audio)).unwrap();

    let db = musefs_db::Db::open_in_memory().unwrap();
    scan_directory(&db, dir.path()).unwrap();
    let fs = Musefs::open(db, config()).unwrap();

    // Tree: /Orig Artist/Orig M4A.m4a
    let artist = fs
        .lookup(VirtualTree::ROOT, "Orig Artist")
        .expect("artist dir");
    let entries = fs.readdir(artist).unwrap();
    let (name, file_inode, _) = entries.into_iter().next().unwrap();
    assert_eq!(name, "Orig M4A.m4a");

    let attr = fs.getattr(file_inode).unwrap();
    let whole = fs.read(file_inode, None, 0, attr.size).unwrap();
    assert_eq!(whole.len() as u64, attr.size);

    // The original audio frames are spliced in verbatim at the tail of the
    // synthesized stream.
    assert!(
        whole.windows(audio.len()).any(|w| w == audio),
        "synthesized m4a should contain the verbatim audio payload"
    );
    assert_eq!(&whole[whole.len() - audio.len()..], audio);
}

#[test]
fn serves_flac_with_embedded_art_through_the_facade() {
    let dir = tempfile::tempdir().unwrap();
    let img = vec![0xC3u8; 120];

    // Build a FLAC with a PICTURE block (type 3 = front cover).
    fn picture_body(mime: &str, data: &[u8]) -> Vec<u8> {
        let mut b = Vec::new();
        b.extend_from_slice(&3u32.to_be_bytes()); // front cover
        b.extend_from_slice(&u32::try_from(mime.len()).unwrap().to_be_bytes());
        b.extend_from_slice(mime.as_bytes());
        b.extend_from_slice(&0u32.to_be_bytes()); // description length
        b.extend_from_slice(&0u32.to_be_bytes()); // width
        b.extend_from_slice(&0u32.to_be_bytes()); // height
        b.extend_from_slice(&0u32.to_be_bytes()); // color depth
        b.extend_from_slice(&0u32.to_be_bytes()); // colors used
        b.extend_from_slice(&u32::try_from(data.len()).unwrap().to_be_bytes());
        b.extend_from_slice(data);
        b
    }
    let mut flac = Vec::new();
    flac.extend_from_slice(b"fLaC");
    flac.extend_from_slice(&common::flac_block(0, &common::streaminfo_body(), false));
    flac.extend_from_slice(&common::flac_block(
        4,
        &common::vorbis_comment_body("v", &["ARTIST=Art", "TITLE=Cover"]),
        false,
    ));
    flac.extend_from_slice(&common::flac_block(
        6,
        &picture_body("image/png", &img),
        true,
    ));
    flac.extend_from_slice(&[0x5Au8; 40]);
    std::fs::write(dir.path().join("c.flac"), &flac).unwrap();

    let db = musefs_db::Db::open_in_memory().unwrap();
    scan_directory(&db, dir.path()).unwrap();
    let fs = Musefs::open(db, config()).unwrap();

    let artist = fs.lookup(VirtualTree::ROOT, "Art").unwrap();
    let (_name, file_inode, _) = fs.readdir(artist).unwrap().into_iter().next().unwrap();
    let attr = fs.getattr(file_inode).unwrap();
    let whole = fs.read(file_inode, None, 0, attr.size).unwrap();
    assert_eq!(whole.len() as u64, attr.size);

    // The synthesized FLAC carries the embedded picture with the original bytes.
    let tag = metaflac::Tag::read_from(&mut std::io::Cursor::new(&whole)).unwrap();
    let pic = tag.pictures().next().expect("a picture");
    assert_eq!(pic.data, img);
    assert_eq!(pic.mime_type, "image/png");
}

#[test]
fn serves_mp3_with_embedded_art_through_the_facade() {
    use id3::TagLike;

    let dir = tempfile::tempdir().unwrap();
    let img = vec![0xD4u8; 90];

    let mut tag = id3::Tag::new();
    tag.set_artist("Pix");
    tag.set_title("Song");
    tag.add_frame(id3::frame::Picture {
        mime_type: "image/jpeg".to_string(),
        picture_type: id3::frame::PictureType::CoverFront,
        description: String::new(),
        data: img.clone(),
    });
    let mut bytes = Vec::new();
    tag.write_to(&mut bytes, id3::Version::Id3v24).unwrap();
    bytes.extend_from_slice(&[0xFF, 0xFB, 1, 2, 3, 4]);
    std::fs::write(dir.path().join("s.mp3"), &bytes).unwrap();

    let db = musefs_db::Db::open_in_memory().unwrap();
    scan_directory(&db, dir.path()).unwrap();
    let fs = Musefs::open(db, config()).unwrap();

    let artist = fs.lookup(VirtualTree::ROOT, "Pix").unwrap();
    let (_name, file_inode, _) = fs.readdir(artist).unwrap().into_iter().next().unwrap();
    let attr = fs.getattr(file_inode).unwrap();
    let whole = fs.read(file_inode, None, 0, attr.size).unwrap();
    assert_eq!(whole.len() as u64, attr.size);

    // The synthesized MP3 carries the embedded APIC picture with the original bytes.
    let parsed = id3::Tag::read_from2(std::io::Cursor::new(&whole)).unwrap();
    let pic = parsed.pictures().next().expect("a picture");
    assert_eq!(pic.data, img);
    assert_eq!(pic.mime_type, "image/jpeg");
}

#[test]
fn poll_refresh_picks_up_external_db_edits() {
    use musefs_db::{Format, NewTrack, Tag};

    let dir = tempfile::tempdir().unwrap();
    let db_path = dir.path().join("m.db");

    // Seed one track (Alice) and open a mount over the on-disk DB.
    {
        let db = musefs_db::Db::open(&db_path).unwrap();
        let id = db
            .upsert_track(&NewTrack {
                backing_path: "/x/a.flac".to_string(),
                format: Format::Flac,
                audio_offset: 0,
                audio_length: 0,
                backing_size: 0,
                backing_mtime_ns: 0,
                backing_ctime_ns: 0,
            })
            .unwrap();
        db.replace_tags(
            id,
            &[Tag::new("artist", "Alice", 0), Tag::new("title", "A", 0)],
        )
        .unwrap();
    }
    let db = musefs_db::Db::open(&db_path).unwrap();
    let fs = Musefs::open(db, config()).unwrap();
    assert!(fs.lookup(VirtualTree::ROOT, "Alice").is_some());
    assert!(fs.lookup(VirtualTree::ROOT, "Bob").is_none());

    // A separate connection adds a track (as beets/picard would).
    {
        let db2 = musefs_db::Db::open(&db_path).unwrap();
        let id = db2
            .upsert_track(&NewTrack {
                backing_path: "/x/b.flac".to_string(),
                format: Format::Flac,
                audio_offset: 0,
                audio_length: 0,
                backing_size: 0,
                backing_mtime_ns: 0,
                backing_ctime_ns: 0,
            })
            .unwrap();
        db2.replace_tags(
            id,
            &[Tag::new("artist", "Bob", 0), Tag::new("title", "B", 0)],
        )
        .unwrap();
    }

    // Polling notices the external commit and rebuilds the tree.
    assert!(fs.poll_refresh().unwrap());
    assert!(fs.lookup(VirtualTree::ROOT, "Bob").is_some());
    // The rebuild is additive — the pre-existing entry is still present.
    assert!(fs.lookup(VirtualTree::ROOT, "Alice").is_some());
    // A second poll with no further change is a no-op.
    assert!(!fs.poll_refresh().unwrap());
}

#[test]
fn open_handle_read_and_release_roundtrip() {
    let dir = tempfile::tempdir().unwrap();
    let db = scanned_db(dir.path());
    let fs = Musefs::open(db, config()).unwrap();

    let artist = fs.lookup(VirtualTree::ROOT, "Alice").unwrap();
    let (_, file_inode, _) = fs.readdir(artist).unwrap().into_iter().next().unwrap();
    let size = fs.getattr(file_inode).unwrap().size;

    let fh = fs.open_handle(file_inode).unwrap();
    let via_handle = fs.read(file_inode, Some(fh), 0, size).unwrap();
    let via_fallback = fs.read(file_inode, None, 0, size).unwrap();
    assert_eq!(via_handle, via_fallback);
    assert_eq!(via_handle.len() as u64, size);

    fs.release_handle(fh);
    let after = fs.read(file_inode, Some(fh), 0, size).unwrap(); // unknown fh → fallback
    assert_eq!(after, via_fallback);
}

#[test]
fn stale_fh_after_release_and_reopen_falls_back() {
    let dir = tempfile::tempdir().unwrap();
    let db = scanned_db(dir.path());
    let fs = Musefs::open(db, config()).unwrap();

    let artist = fs.lookup(VirtualTree::ROOT, "Alice").unwrap();
    let (_, file_inode, _) = fs.readdir(artist).unwrap().into_iter().next().unwrap();
    let size = fs.getattr(file_inode).unwrap().size;
    let canonical = fs.read(file_inode, None, 0, size).unwrap(); // inode fallback bytes

    let fh_a = fs.open_handle(file_inode).unwrap();
    fs.release_handle(fh_a);
    let fh_b = fs.open_handle(file_inode).unwrap();

    // Generation-encoded keys: the reissued handle must not collide with the stale one.
    assert_ne!(fh_a, fh_b);
    // A read on the stale fh_a misses the slab (None) and falls back to inode
    // resolution — correct bytes, never fh_b's handle, never a panic.
    let via_stale = fs.read(file_inode, Some(fh_a), 0, size).unwrap();
    assert_eq!(via_stale, canonical);
    // The live handle still serves correctly.
    let via_live = fs.read(file_inode, Some(fh_b), 0, size).unwrap();
    assert_eq!(via_live, canonical);

    fs.release_handle(fh_b);
}

#[test]
fn poll_refresh_keeps_unchanged_entries_and_prunes_vanished() {
    use musefs_db::{Format, NewTrack, Tag};
    let dir = tempfile::tempdir().unwrap();
    let backing = dir.path().join("a.flac");
    let bytes = make_flac(
        &[
            (0, streaminfo_body()),
            (4, vorbis_comment_body("v", &["ARTIST=Alice", "TITLE=Song"])),
        ],
        &[0xAB; 64],
    );
    std::fs::write(&backing, &bytes).unwrap();
    let db_path = dir.path().join("m.db");
    {
        let db = musefs_db::Db::open(&db_path).unwrap();
        scan_directory(&db, dir.path()).unwrap();
    }
    let fs = Musefs::open(musefs_db::Db::open(&db_path).unwrap(), config()).unwrap();
    let artist = fs.lookup(VirtualTree::ROOT, "Alice").unwrap();
    let (_, inode, _) = fs.readdir(artist).unwrap().into_iter().next().unwrap();
    let size_before = fs.getattr(inode).unwrap().size;

    // Unrelated external commit bumps data_version without changing Alice's track.
    {
        let db2 = musefs_db::Db::open(&db_path).unwrap();
        let id = db2
            .upsert_track(&NewTrack {
                backing_path: "/x/ghost.mp3".to_string(),
                format: Format::Mp3,
                audio_offset: 0,
                audio_length: 0,
                backing_size: 0,
                backing_mtime_ns: 0,
                backing_ctime_ns: 0,
            })
            .unwrap();
        db2.replace_tags(
            id,
            &[Tag::new("artist", "Ghost", 0), Tag::new("title", "G", 0)],
        )
        .unwrap();
    }
    assert!(fs.poll_refresh().unwrap());

    let size_after = fs.getattr(inode).unwrap().size;
    assert_eq!(size_before, size_after);
    assert!(fs.lookup(VirtualTree::ROOT, "Ghost").is_some());
}

#[test]
fn poll_refresh_debounces_within_interval() {
    use musefs_db::{Format, NewTrack, Tag};
    let dir = tempfile::tempdir().unwrap();
    let db_path = dir.path().join("m.db");
    {
        let db = musefs_db::Db::open(&db_path).unwrap();
        let id = db
            .upsert_track(&NewTrack {
                backing_path: "/x/a.flac".to_string(),
                format: Format::Flac,
                audio_offset: 0,
                audio_length: 0,
                backing_size: 0,
                backing_mtime_ns: 0,
                backing_ctime_ns: 0,
            })
            .unwrap();
        db.replace_tags(
            id,
            &[Tag::new("artist", "Alice", 0), Tag::new("title", "A", 0)],
        )
        .unwrap();
    }
    let cfg = MountConfig {
        poll_interval: std::time::Duration::from_hours(1),
        ..config()
    };
    let fs = Musefs::open(musefs_db::Db::open(&db_path).unwrap(), cfg).unwrap();
    {
        let db2 = musefs_db::Db::open(&db_path).unwrap();
        let id = db2
            .upsert_track(&NewTrack {
                backing_path: "/x/b.flac".to_string(),
                format: Format::Flac,
                audio_offset: 0,
                audio_length: 0,
                backing_size: 0,
                backing_mtime_ns: 0,
                backing_ctime_ns: 0,
            })
            .unwrap();
        db2.replace_tags(
            id,
            &[Tag::new("artist", "Bob", 0), Tag::new("title", "B", 0)],
        )
        .unwrap();
    }
    assert!(!fs.poll_refresh().unwrap()); // debounced (within 1h of open)
    assert!(fs.lookup(VirtualTree::ROOT, "Bob").is_none());
}

#[test]
fn unchanged_refresh_poll_consumes_debounce_window() {
    use musefs_db::{Format, NewTrack, Tag};
    let dir = tempfile::tempdir().unwrap();
    let db_path = dir.path().join("m.db");
    {
        let db = musefs_db::Db::open(&db_path).unwrap();
        let id = db
            .upsert_track(&NewTrack {
                backing_path: "/x/a.flac".to_string(),
                format: Format::Flac,
                audio_offset: 0,
                audio_length: 0,
                backing_size: 0,
                backing_mtime_ns: 0,
                backing_ctime_ns: 0,
            })
            .unwrap();
        db.replace_tags(
            id,
            &[Tag::new("artist", "Alice", 0), Tag::new("title", "A", 0)],
        )
        .unwrap();
    }
    // A generous interval keeps the DB-mutation gap below reliably within the
    // debounce window; the window is crossed via the test hook, not a sleep, so
    // the assertions don't race wall-clock jitter on a loaded CI runner.
    let cfg = MountConfig {
        poll_interval: std::time::Duration::from_secs(30),
        ..config()
    };
    let fs = Musefs::open(musefs_db::Db::open(&db_path).unwrap(), cfg).unwrap();
    fs.expire_poll_debounce_for_test();
    assert!(!fs.poll_refresh().unwrap());
    {
        let db2 = musefs_db::Db::open(&db_path).unwrap();
        let id = db2
            .upsert_track(&NewTrack {
                backing_path: "/x/b.flac".to_string(),
                format: Format::Flac,
                audio_offset: 0,
                audio_length: 0,
                backing_size: 0,
                backing_mtime_ns: 0,
                backing_ctime_ns: 0,
            })
            .unwrap();
        db2.replace_tags(
            id,
            &[Tag::new("artist", "Bob", 0), Tag::new("title", "B", 0)],
        )
        .unwrap();
    }
    assert!(
        !fs.poll_refresh().unwrap(),
        "unchanged poll should have reset the debounce window"
    );
    fs.expire_poll_debounce_for_test();
    assert!(fs.poll_refresh().unwrap());
}

#[test]
fn failed_refresh_retries_after_backoff_not_every_call() {
    use musefs_db::{Format, NewTrack, Tag};
    let dir = tempfile::tempdir().unwrap();
    let db_path = dir.path().join("m.db");
    {
        let db = musefs_db::Db::open(&db_path).unwrap();
        let id = db
            .upsert_track(&NewTrack {
                backing_path: "/x/a.flac".to_string(),
                format: Format::Flac,
                audio_offset: 0,
                audio_length: 0,
                backing_size: 0,
                backing_mtime_ns: 0,
                backing_ctime_ns: 0,
            })
            .unwrap();
        db.replace_tags(
            id,
            &[Tag::new("artist", "Alice", 0), Tag::new("title", "A", 0)],
        )
        .unwrap();
    }
    let cfg = MountConfig {
        poll_interval: std::time::Duration::from_millis(20),
        ..config()
    };
    let fs = Musefs::open(musefs_db::Db::open(&db_path).unwrap(), cfg).unwrap();
    std::thread::sleep(std::time::Duration::from_millis(25));
    {
        let db2 = musefs_db::Db::open(&db_path).unwrap();
        let id = db2
            .upsert_track(&NewTrack {
                backing_path: "/x/b.flac".to_string(),
                format: Format::Flac,
                audio_offset: 0,
                audio_length: 0,
                backing_size: 0,
                backing_mtime_ns: 0,
                backing_ctime_ns: 0,
            })
            .unwrap();
        db2.replace_tags(
            id,
            &[Tag::new("artist", "Bob", 0), Tag::new("title", "B", 0)],
        )
        .unwrap();
    }
    fs.force_rebuild_errors_for_test(true);
    assert!(fs.poll_refresh().is_err());
    assert!(
        !fs.poll_refresh().unwrap(),
        "immediate retry should be suppressed by refresh failure backoff"
    );
    std::thread::sleep(std::time::Duration::from_millis(110));
    assert!(fs.poll_refresh().is_err());
}

#[test]
fn poll_refresh_single_flights_concurrent_callers() {
    use musefs_db::{Format, NewTrack, Tag};
    use std::sync::Arc;
    let dir = tempfile::tempdir().unwrap();
    let db_path = dir.path().join("m.db");
    {
        let db = musefs_db::Db::open(&db_path).unwrap();
        let id = db
            .upsert_track(&NewTrack {
                backing_path: "/x/a.flac".into(),
                format: Format::Flac,
                audio_offset: 0,
                audio_length: 0,
                backing_size: 0,
                backing_mtime_ns: 0,
                backing_ctime_ns: 0,
            })
            .unwrap();
        db.replace_tags(
            id,
            &[Tag::new("artist", "Alice", 0), Tag::new("title", "A", 0)],
        )
        .unwrap();
    }
    let cfg = MountConfig {
        poll_interval: std::time::Duration::ZERO,
        ..config()
    };
    let fs = Arc::new(Musefs::open(musefs_db::Db::open(&db_path).unwrap(), cfg).unwrap());
    {
        let db2 = musefs_db::Db::open(&db_path).unwrap();
        let id = db2
            .upsert_track(&NewTrack {
                backing_path: "/x/b.flac".into(),
                format: Format::Flac,
                audio_offset: 0,
                audio_length: 0,
                backing_size: 0,
                backing_mtime_ns: 0,
                backing_ctime_ns: 0,
            })
            .unwrap();
        db2.replace_tags(
            id,
            &[Tag::new("artist", "Bob", 0), Tag::new("title", "B", 0)],
        )
        .unwrap();
    }
    let trues: usize = std::thread::scope(|s| {
        let handles: Vec<_> = (0..8)
            .map(|_| {
                let fs = Arc::clone(&fs);
                s.spawn(move || usize::from(fs.poll_refresh().unwrap()))
            })
            .collect();
        handles.into_iter().map(|h| h.join().unwrap()).sum()
    });
    assert_eq!(trues, 1, "single-flight: exactly one caller rebuilds");
    assert!(fs.lookup(VirtualTree::ROOT, "Bob").is_some());
}

#[test]
fn inode_is_stable_across_refresh() {
    use musefs_db::{Format, NewTrack, Tag};
    let dir = tempfile::tempdir().unwrap();
    let db_path = dir.path().join("m.db");
    {
        let db = musefs_db::Db::open(&db_path).unwrap();
        let id = db
            .upsert_track(&NewTrack {
                backing_path: "/x/a.flac".into(),
                format: Format::Flac,
                audio_offset: 0,
                audio_length: 0,
                backing_size: 0,
                backing_mtime_ns: 0,
                backing_ctime_ns: 0,
            })
            .unwrap();
        db.replace_tags(
            id,
            &[Tag::new("artist", "Alice", 0), Tag::new("title", "A", 0)],
        )
        .unwrap();
    }
    let cfg = MountConfig {
        poll_interval: std::time::Duration::ZERO,
        ..config()
    };
    let fs = Musefs::open(musefs_db::Db::open(&db_path).unwrap(), cfg).unwrap();
    let alice = fs.lookup(VirtualTree::ROOT, "Alice").unwrap();
    let (_, song_before, _) = fs.readdir(alice).unwrap().into_iter().next().unwrap();
    {
        let db2 = musefs_db::Db::open(&db_path).unwrap();
        let id = db2
            .upsert_track(&NewTrack {
                backing_path: "/x/b.flac".into(),
                format: Format::Flac,
                audio_offset: 0,
                audio_length: 0,
                backing_size: 0,
                backing_mtime_ns: 0,
                backing_ctime_ns: 0,
            })
            .unwrap();
        db2.replace_tags(
            id,
            &[Tag::new("artist", "Bob", 0), Tag::new("title", "B", 0)],
        )
        .unwrap();
    }
    assert!(fs.poll_refresh().unwrap());
    let alice_after = fs.lookup(VirtualTree::ROOT, "Alice").unwrap();
    let (_, song_after, _) = fs.readdir(alice_after).unwrap().into_iter().next().unwrap();
    assert_eq!(alice, alice_after);
    assert_eq!(song_before, song_after);
}

#[test]
fn poll_refresh_notify_reports_changed_track_inode() {
    use musefs_db::Tag;
    let dir = tempfile::tempdir().unwrap();
    // Two backing files -> two tracks: Alice/Song and Bob/Tune.
    for (name, artist, title) in [("a.flac", "Alice", "Song"), ("b.flac", "Bob", "Tune")] {
        let bytes = make_flac(
            &[
                (0, streaminfo_body()),
                (
                    4,
                    vorbis_comment_body(
                        "v",
                        &[&format!("ARTIST={artist}"), &format!("TITLE={title}")],
                    ),
                ),
            ],
            &[0xAB; 64],
        );
        std::fs::write(dir.path().join(name), &bytes).unwrap();
    }
    let db_path = dir.path().join("m.db");
    {
        let db = musefs_db::Db::open(&db_path).unwrap();
        scan_directory(&db, dir.path()).unwrap();
    }
    let fs = Musefs::open(musefs_db::Db::open(&db_path).unwrap(), config()).unwrap();

    let alice = fs.lookup(VirtualTree::ROOT, "Alice").unwrap();
    let alice_song = fs.lookup(alice, "Song.flac").unwrap();

    // Find Alice's track id (scan assigns ids by discovery order).
    let alice_id = musefs_db::Db::open(&db_path)
        .unwrap()
        .list_tracks()
        .unwrap()
        .into_iter()
        .find(|t| t.backing_path.ends_with("a.flac"))
        .unwrap()
        .id;

    // External edit: retag Alice WITHOUT moving her (same artist/title, extra
    // album tag) so her path/inode is stable but content_version bumps.
    {
        let db2 = musefs_db::Db::open(&db_path).unwrap();
        db2.replace_tags(
            alice_id,
            &[
                Tag::new("artist", "Alice", 0),
                Tag::new("title", "Song", 0),
                Tag::new("album", "New", 0),
            ],
        )
        .unwrap();
    }

    let mut changed = Vec::new();
    assert!(fs.poll_refresh_notify(|ino| changed.push(ino)).unwrap());
    assert_eq!(changed, vec![alice_song], "only Alice's inode changed");
    // Inode stayed stable across the refresh.
    assert_eq!(
        fs.lookup(fs.lookup(VirtualTree::ROOT, "Alice").unwrap(), "Song.flac")
            .unwrap(),
        alice_song
    );
}

#[test]
fn poll_refresh_notify_reports_changed_inode_on_full_rebuild_fallback() {
    use musefs_db::Tag;
    let dir = tempfile::tempdir().unwrap();
    // Two backing files -> two tracks: Alice/Song and Bob/Tune.
    for (name, artist, title) in [("a.flac", "Alice", "Song"), ("b.flac", "Bob", "Tune")] {
        let bytes = make_flac(
            &[
                (0, streaminfo_body()),
                (
                    4,
                    vorbis_comment_body(
                        "v",
                        &[&format!("ARTIST={artist}"), &format!("TITLE={title}")],
                    ),
                ),
            ],
            &[0xAB; 64],
        );
        std::fs::write(dir.path().join(name), &bytes).unwrap();
    }
    let db_path = dir.path().join("m.db");
    {
        let db = musefs_db::Db::open(&db_path).unwrap();
        scan_directory(&db, dir.path()).unwrap();
    }
    let fs = Musefs::open(musefs_db::Db::open(&db_path).unwrap(), config()).unwrap();

    let alice = fs.lookup(VirtualTree::ROOT, "Alice").unwrap();
    let alice_song = fs.lookup(alice, "Song.flac").unwrap();

    let alice_id = musefs_db::Db::open(&db_path)
        .unwrap()
        .list_tracks()
        .unwrap()
        .into_iter()
        .find(|t| t.backing_path.ends_with("a.flac"))
        .unwrap()
        .id;

    // Path-stable retag: content_version bumps, inode/path stay put.
    {
        let db2 = musefs_db::Db::open(&db_path).unwrap();
        db2.replace_tags(
            alice_id,
            &[
                Tag::new("artist", "Alice", 0),
                Tag::new("title", "Song", 0),
                Tag::new("album", "New", 0),
            ],
        )
        .unwrap();
    }

    // Force the changelog-gap full-rebuild path so the notifier is
    // `notify_changed` (the full-rebuild routine) rather than the incremental
    // `notify_changed_delta` the sibling test exercises — covering the
    // full-rebuild change-detection (content_version-rose + path-stable). The
    // rebuild reuses the same inode for a path-stable track.
    {
        let writer = musefs_db::Db::open(&db_path).unwrap();
        let max_seq = writer.changelog_since(0).unwrap().max_seq;
        writer.delete_changelog_through_for_test(max_seq).unwrap();
    }
    let mut changed = Vec::new();
    assert!(fs.poll_refresh_notify(|ino| changed.push(ino)).unwrap());
    assert_eq!(
        changed,
        vec![alice_song],
        "full-rebuild path must invalidate exactly the changed track's stable inode"
    );
}

#[test]
fn poll_refresh_notify_reports_old_inode_for_path_changing_retag() {
    use musefs_db::Tag;
    let dir = tempfile::tempdir().unwrap();
    let bytes = make_flac(
        &[
            (0, streaminfo_body()),
            (4, vorbis_comment_body("v", &["ARTIST=Alice", "TITLE=Song"])),
        ],
        &[0xAB; 64],
    );
    std::fs::write(dir.path().join("a.flac"), &bytes).unwrap();
    let db_path = dir.path().join("m.db");
    {
        let db = musefs_db::Db::open(&db_path).unwrap();
        scan_directory(&db, dir.path()).unwrap();
    }
    let fs = Musefs::open(musefs_db::Db::open(&db_path).unwrap(), config()).unwrap();
    let alice = fs.lookup(VirtualTree::ROOT, "Alice").unwrap();
    let old_inode = fs.lookup(alice, "Song.flac").unwrap();
    let track_id = musefs_db::Db::open(&db_path)
        .unwrap()
        .list_tracks()
        .unwrap()
        .into_iter()
        .next()
        .unwrap()
        .id;

    {
        let db2 = musefs_db::Db::open(&db_path).unwrap();
        db2.replace_tags(
            track_id,
            &[
                Tag::new("artist", "Alice", 0),
                Tag::new("title", "Moved", 0),
            ],
        )
        .unwrap();
    }

    let mut changed = Vec::new();
    assert!(fs.poll_refresh_notify(|ino| changed.push(ino)).unwrap());
    let alice_after = fs.lookup(VirtualTree::ROOT, "Alice").unwrap();
    let new_inode = fs.lookup(alice_after, "Moved.flac").unwrap();
    assert!(
        changed.contains(&old_inode),
        "old inode should be invalidated"
    );
    // The track MOVED to a brand-new path (Moved.flac), which gets a freshly
    // allocated inode (the persistent allocator never recycles retired inodes).
    // The kernel has never cached it, so there is nothing stale to drop — only the
    // OLD inode (whose cache may be live) must be invalidated. See SP2 notify_changed.
    assert!(
        !changed.contains(&new_inode),
        "new (freshly allocated) inode has no cache and must not be reported"
    );
    assert_ne!(old_inode, new_inode);
}

#[test]
fn poll_refresh_notify_invalidates_old_inode_for_removed_track() {
    let dir = tempfile::tempdir().unwrap();
    let bytes = make_flac(
        &[
            (0, streaminfo_body()),
            (4, vorbis_comment_body("v", &["ARTIST=Alice", "TITLE=Song"])),
        ],
        &[0xAB; 64],
    );
    std::fs::write(dir.path().join("a.flac"), &bytes).unwrap();
    let db_path = dir.path().join("m.db");
    {
        let db = musefs_db::Db::open(&db_path).unwrap();
        scan_directory(&db, dir.path()).unwrap();
    }
    let fs = Musefs::open(musefs_db::Db::open(&db_path).unwrap(), config()).unwrap();
    let alice = fs.lookup(VirtualTree::ROOT, "Alice").unwrap();
    let old_inode = fs.lookup(alice, "Song.flac").unwrap();
    let track_id = musefs_db::Db::open(&db_path)
        .unwrap()
        .list_tracks()
        .unwrap()
        .into_iter()
        .next()
        .unwrap()
        .id;

    {
        let db2 = musefs_db::Db::open(&db_path).unwrap();
        db2.delete_track(track_id).unwrap();
    }

    let mut changed = Vec::new();
    assert!(fs.poll_refresh_notify(|ino| changed.push(ino)).unwrap());
    assert!(
        changed.contains(&old_inode),
        "old inode should be invalidated after track removal"
    );
}

#[test]
fn reads_m4b_alias() {
    let dir = tempfile::tempdir().unwrap();
    let audio = b"AUDIODATA";
    let bytes = common::minimal_m4a(audio);
    std::fs::write(dir.path().join("book.m4b"), &bytes).unwrap();
    let db = musefs_db::Db::open_in_memory().unwrap();
    scan_directory(&db, dir.path()).unwrap();
    let track = db.list_tracks().unwrap().into_iter().next().unwrap();
    assert_eq!(track.format, musefs_db::Format::M4a);
    let fs = Musefs::open(db, config()).unwrap();
    let artist = fs.lookup(VirtualTree::ROOT, "Orig Artist").unwrap();
    let entries = fs.readdir(artist).unwrap();
    let (name, file_inode, _) = entries.into_iter().next().unwrap();
    assert_eq!(name, "Orig M4A.m4a");
    let attr = fs.getattr(file_inode).unwrap();
    assert!(!attr.is_dir);
    assert!(attr.size > 0);
}

#[test]
fn refresh_picks_up_externally_added_track() {
    use musefs_db::{Format, NewTrack, Tag};
    let dir = tempfile::tempdir().unwrap();
    let db_path = dir.path().join("m.db");
    {
        let db = musefs_db::Db::open(&db_path).unwrap();
        let id = db
            .upsert_track(&NewTrack {
                backing_path: "/x/a.flac".into(),
                format: Format::Flac,
                audio_offset: 0,
                audio_length: 0,
                backing_size: 0,
                backing_mtime_ns: 0,
                backing_ctime_ns: 0,
            })
            .unwrap();
        db.replace_tags(
            id,
            &[Tag::new("artist", "Alice", 0), Tag::new("title", "A", 0)],
        )
        .unwrap();
    }
    let fs = Musefs::open(musefs_db::Db::open(&db_path).unwrap(), config()).unwrap();
    assert!(fs.lookup(VirtualTree::ROOT, "Bob").is_none());
    {
        let db2 = musefs_db::Db::open(&db_path).unwrap();
        let id = db2
            .upsert_track(&NewTrack {
                backing_path: "/x/b.flac".into(),
                format: Format::Flac,
                audio_offset: 0,
                audio_length: 0,
                backing_size: 0,
                backing_mtime_ns: 0,
                backing_ctime_ns: 0,
            })
            .unwrap();
        db2.replace_tags(
            id,
            &[Tag::new("artist", "Bob", 0), Tag::new("title", "B", 0)],
        )
        .unwrap();
    }
    fs.refresh_for_test().unwrap();
    assert!(
        fs.lookup(VirtualTree::ROOT, "Bob").is_some(),
        "refresh must rebuild the tree"
    );
}

#[test]
fn open_handle_returns_distinct_ids_and_rejects_dirs() {
    let dir = tempfile::tempdir().unwrap();
    let db = scanned_db(dir.path());
    let fs = Musefs::open(db, config()).unwrap();
    let artist = fs.lookup(VirtualTree::ROOT, "Alice").unwrap();
    let (_, file_inode, _) = fs.readdir(artist).unwrap().into_iter().next().unwrap();

    let fh1 = fs.open_handle(file_inode).unwrap();
    let fh2 = fs.open_handle(file_inode).unwrap();
    assert_ne!(fh1, fh2, "each open must yield a fresh handle id");

    assert!(matches!(fs.open_handle(artist), Err(CoreError::IsDir(_))));
}

/// Scaffold shared by the in-place backing-change tests: scan one FLAC, open a
/// handle, warm the per-handle fast path, apply `mutate` to the backing file, then
/// assert the next read through the held handle reports `BackingChanged` (drift
/// detected on the held fd, not served silently).
fn assert_backing_change_detected_through_handle(mutate: impl FnOnce(&std::path::Path)) {
    let dir = tempfile::tempdir().unwrap();
    let db = scanned_db(dir.path());
    let fs = Musefs::open(db, config()).unwrap();
    let artist = fs.lookup(VirtualTree::ROOT, "Alice").unwrap();
    let (_, file_inode, _) = fs.readdir(artist).unwrap().into_iter().next().unwrap();
    let size = fs.getattr(file_inode).unwrap().size;

    let fh = fs.open_handle(file_inode).unwrap();
    let warm = fs.read(file_inode, Some(fh), 0, size).unwrap();
    assert_eq!(warm.len() as u64, size);

    mutate(&dir.path().join("a.flac"));

    let err = fs.read(file_inode, Some(fh), 0, size).unwrap_err();
    assert!(matches!(err, CoreError::BackingChanged(_)), "got {err:?}");
}

#[test]
fn read_through_handle_errors_after_backing_grows_in_place() {
    use std::io::Write;
    // In-place grow (same inode), no DB change.
    assert_backing_change_detected_through_handle(|path| {
        let mut f = std::fs::OpenOptions::new().append(true).open(path).unwrap();
        f.write_all(&[0u8; 64]).unwrap();
    });
}

#[test]
fn read_through_handle_errors_after_backing_truncated_in_place() {
    // Truncate in place (same inode): std::fs::write create+truncates the path.
    assert_backing_change_detected_through_handle(|path| {
        std::fs::write(path, [0xCDu8; 8]).unwrap();
    });
}

#[test]
fn read_through_handle_errors_after_same_length_rewrite_with_new_mtime() {
    assert_backing_change_detected_through_handle(|path| {
        // Same-length in-place rewrite (same inode), then a distinct mtime second.
        // mtime_secs is whole-second; the rewrite lands in the scan's second, so
        // set a deterministic, distinct timestamp (year ~2001 — well clear of the
        // scan second regardless of wall clock).
        let original_len = std::fs::read(path).unwrap().len();
        std::fs::write(path, vec![0xEEu8; original_len]).unwrap();
        let distinct = std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_000_000_000);
        let f = std::fs::OpenOptions::new().write(true).open(path).unwrap();
        f.set_times(std::fs::FileTimes::new().set_modified(distinct))
            .unwrap();
    });
}

#[test]
fn read_through_handle_keeps_succeeding_when_backing_unchanged() {
    let dir = tempfile::tempdir().unwrap();
    let db = scanned_db(dir.path());
    let fs = Musefs::open(db, config()).unwrap();
    let artist = fs.lookup(VirtualTree::ROOT, "Alice").unwrap();
    let (_, file_inode, _) = fs.readdir(artist).unwrap().into_iter().next().unwrap();
    let size = fs.getattr(file_inode).unwrap().size;

    let fh = fs.open_handle(file_inode).unwrap();
    let first = fs.read(file_inode, Some(fh), 0, size).unwrap();
    let second = fs.read(file_inode, Some(fh), 0, size).unwrap();
    assert_eq!(first, second);
    assert_eq!(first.len() as u64, size);
}

#[test]
fn release_handle_forces_fallback_on_next_read() {
    use std::io::Write;
    let dir = tempfile::tempdir().unwrap();
    let db = scanned_db(dir.path());
    let fs = Musefs::open(db, config()).unwrap();
    let artist = fs.lookup(VirtualTree::ROOT, "Alice").unwrap();
    let (_, file_inode, _) = fs.readdir(artist).unwrap().into_iter().next().unwrap();
    let size = fs.getattr(file_inode).unwrap().size;

    let fh = fs.open_handle(file_inode).unwrap();
    fs.release_handle(fh);
    {
        let mut f = std::fs::OpenOptions::new()
            .append(true)
            .open(dir.path().join("a.flac"))
            .unwrap();
        f.write_all(&[0u8; 64]).unwrap();
    }
    assert!(matches!(
        fs.read(file_inode, Some(fh), 0, size),
        Err(CoreError::BackingChanged(_))
    ));
}

#[test]
fn getattr_reresolves_size_after_content_version_bump() {
    use common::{make_flac, streaminfo_body, vorbis_comment_body};
    use musefs_db::Tag;
    let dir = tempfile::tempdir().unwrap();
    let backing = dir.path().join("a.flac");
    let bytes = make_flac(
        &[
            (0, streaminfo_body()),
            (4, vorbis_comment_body("v", &["ARTIST=Alice", "TITLE=Song"])),
        ],
        &[0xAB; 64],
    );
    std::fs::write(&backing, &bytes).unwrap();
    let db_path = dir.path().join("m.db");
    {
        let db = musefs_db::Db::open(&db_path).unwrap();
        scan_directory(&db, dir.path()).unwrap();
    }
    let fs = Musefs::open(musefs_db::Db::open(&db_path).unwrap(), config()).unwrap();
    let alice = fs.lookup(VirtualTree::ROOT, "Alice").unwrap();
    let inode = fs.lookup(alice, "Song.flac").unwrap();
    let size_before = fs.getattr(inode).unwrap().size;

    let track_id = musefs_db::Db::open(&db_path)
        .unwrap()
        .list_tracks()
        .unwrap()[0]
        .id;
    {
        let db2 = musefs_db::Db::open(&db_path).unwrap();
        db2.replace_tags(
            track_id,
            &[
                Tag::new("artist", "Alice", 0),
                Tag::new("title", "Song", 0),
                Tag::new("album", &"X".repeat(500), 0),
            ],
        )
        .unwrap();
    }
    let size_after = fs.getattr(inode).unwrap().size;
    assert!(
        size_after > size_before,
        "size must reflect the larger retagged header"
    );
}

/// Regression for #203: `refresh_for_test` and `poll_refresh` share the
/// `refreshing` single-flight gate, so two rebuilds can never overlap and
/// publish a stale tree. We churn `data_version` from a writer thread while a
/// forced-refresh thread and a poll thread race; if a stale rebuild published an
/// outdated tree last, tracks committed after it would be missing. This is a
/// stress test — it is reliably green with the gate, and probabilistic at
/// catching an un-gated regression — so we run enough iterations to make a race
/// likely.
#[test]
fn forced_refresh_and_poll_refresh_never_publish_stale_tree() {
    use musefs_db::{Format, NewTrack, Tag};
    use std::sync::atomic::{AtomicBool, Ordering};

    fn insert(db: &musefs_db::Db, n: usize) {
        let id = db
            .upsert_track(&NewTrack {
                backing_path: format!("/x/track{n}.flac"),
                format: Format::Flac,
                audio_offset: 0,
                audio_length: 0,
                backing_size: 0,
                backing_mtime_ns: 0,
                backing_ctime_ns: 0,
            })
            .unwrap();
        db.replace_tags(
            id,
            &[
                Tag::new("artist", &format!("A{n}"), 0),
                Tag::new("title", &format!("T{n}"), 0),
            ],
        )
        .unwrap();
    }

    const N: usize = 80;
    let dir = tempfile::tempdir().unwrap();
    let db_path = dir.path().join("m.db");
    {
        let db = musefs_db::Db::open(&db_path).unwrap();
        insert(&db, 0);
    }

    let fs = Musefs::open(musefs_db::Db::open(&db_path).unwrap(), config()).unwrap();
    let done = AtomicBool::new(false);

    std::thread::scope(|s| {
        // Writer: commit tracks one at a time, churning `data_version`.
        s.spawn(|| {
            let db = musefs_db::Db::open(&db_path).unwrap();
            for n in 1..=N {
                insert(&db, n);
            }
            done.store(true, Ordering::Release);
        });
        // Forced full rebuilds, racing the writer and the poller.
        s.spawn(|| {
            while !done.load(Ordering::Acquire) {
                fs.refresh_for_test().unwrap();
            }
        });
        // Production refresh path (incremental, with full-rebuild fallback).
        s.spawn(|| {
            while !done.load(Ordering::Acquire) {
                let _ = fs.poll_refresh().unwrap();
            }
        });
    });

    // Settle on the final committed state, then assert nothing was lost.
    fs.refresh_for_test().unwrap();
    for n in 0..=N {
        assert!(
            fs.lookup(VirtualTree::ROOT, &format!("A{n}")).is_some(),
            "track A{n} missing — a stale rebuild published an outdated tree"
        );
    }
}

// Template-agnostic: walk readdir from the root to the first non-dir entry.
fn first_file_inode(fs: &Musefs) -> u64 {
    fn walk(fs: &Musefs, inode: u64) -> Option<u64> {
        for (name, child, is_dir) in fs.readdir(inode).unwrap() {
            if name == "." || name == ".." {
                continue;
            }
            if is_dir {
                if let Some(f) = walk(fs, child) {
                    return Some(f);
                }
            } else {
                return Some(child);
            }
        }
        None
    }
    walk(fs, VirtualTree::ROOT).expect("a file inode under root")
}

// getattr's warm size-cache hit must re-stat with the full stamp (#276/#279):
// a same-size sub-second rewrite after the first getattr must surface
// BackingChanged, not stale attrs.
#[test]
fn getattr_size_cache_rejects_subsecond_rewrite() {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("a.flac");
    common::write_flac(&src, &["TITLE=T", "ARTIST=A"], &[0xAB; 4096]);
    let db = musefs_db::Db::open_in_memory().unwrap();
    scan_directory(&db, dir.path()).unwrap();
    let fs = Musefs::open(db, config()).unwrap();

    let inode = first_file_inode(&fs);
    fs.getattr(inode).unwrap(); // warm the size cache

    let mut v = std::fs::read(&src).unwrap();
    *v.last_mut().unwrap() ^= 0xFF; // same size, new mtime/ctime
    std::fs::write(&src, v).unwrap();

    let err = fs.getattr(inode).unwrap_err();
    assert!(matches!(err, CoreError::BackingChanged(_)), "got {err:?}");
}