data_bucket 0.7.13

DataBucket is container for WorkTable's data
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
//! Read-only, content-addressed attachment for immutable DataBucket artifacts.
//!
//! The rest of this crate defines the page and archive format. This module owns
//! the runtime policy around it: mmap attachment, complete-object identity,
//! shared leases, and explicit unload. A writer must publish a complete file
//! atomically and never mutate it after publication.

use alloc::collections::BTreeMap;
use alloc::format;
use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::future::Future;
use core::ops::Deref;
use core::time::Duration;

use eko::file::File;
use eko::mmap::Mmap;
use eko::path::{Path, PathBuf};
use eko::thread::Mutex;
use rkyv::Archive;
use sha2::{Digest as _, Sha256};

use crate::error::report::{self, report_msg};
use crate::{GeneralHeader, Link, DATA_VERSION, GENERAL_HEADER_SIZE, INNER_PAGE_SIZE, PAGE_SIZE};

#[cfg(unix)]
extern "C" {
    fn mlock(addr: *const core::ffi::c_void, len: usize) -> core::ffi::c_int;
    fn munlock(addr: *const core::ffi::c_void, len: usize) -> core::ffi::c_int;
}

#[cfg(not(unix))]
unsafe fn mlock(_addr: *const core::ffi::c_void, _len: usize) -> core::ffi::c_int {
    -1
}

#[cfg(not(unix))]
unsafe fn munlock(_addr: *const core::ffi::c_void, _len: usize) -> core::ffi::c_int {
    0
}

/// Path arguments accepted by [`AttachedBucket`] and [`BucketLoader`].
pub trait AsLoaderPath {
    fn to_eko_path_buf(&self) -> report::Result<PathBuf>;
}

impl AsLoaderPath for str {
    fn to_eko_path_buf(&self) -> report::Result<PathBuf> {
        Ok(PathBuf::from(self))
    }
}

impl AsLoaderPath for String {
    fn to_eko_path_buf(&self) -> report::Result<PathBuf> {
        Ok(PathBuf::from(self.as_str()))
    }
}

impl AsLoaderPath for Path {
    fn to_eko_path_buf(&self) -> report::Result<PathBuf> {
        Ok(self.to_path_buf())
    }
}

impl AsLoaderPath for PathBuf {
    fn to_eko_path_buf(&self) -> report::Result<PathBuf> {
        Ok(self.clone())
    }
}

impl<T: AsLoaderPath + ?Sized> AsLoaderPath for &T {
    fn to_eko_path_buf(&self) -> report::Result<PathBuf> {
        (*self).to_eko_path_buf()
    }
}

#[cfg(test)]
impl AsLoaderPath for std::path::Path {
    fn to_eko_path_buf(&self) -> report::Result<PathBuf> {
        self.to_str()
            .map(PathBuf::from)
            .ok_or_else(|| report_msg!("non-UTF-8 DataBucket path"))
    }
}

#[cfg(test)]
impl AsLoaderPath for std::path::PathBuf {
    fn to_eko_path_buf(&self) -> report::Result<PathBuf> {
        self.as_path().to_eko_path_buf()
    }
}

/// Content identity of one complete, immutable DataBucket file.
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct BucketId(String);

impl BucketId {
    pub fn parse(value: impl Into<String>) -> report::Result<Self> {
        let value = value.into();
        if value.len() != 64
            || !value
                .bytes()
                .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
        {
            return Err(report_msg!(
                "DataBucket identity must be a lowercase hexadecimal SHA-256"
            ));
        }
        Ok(Self(value))
    }

    pub fn of_bytes(bytes: &[u8]) -> Self {
        Self(format!("{:x}", Sha256::digest(bytes)))
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

#[derive(Clone, Copy, Debug)]
pub struct AttachedPage<'a> {
    pub header: GeneralHeader,
    pub data: &'a [u8],
}

/// One validated, read-only memory mapping.
pub struct AttachedBucket {
    path: PathBuf,
    id: BucketId,
    map: Mmap,
    headers: Vec<GeneralHeader>,
    memory_locked: bool,
    private_file_checked: bool,
}

/// Security policy for an immutable direct-memory attachment.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct AttachPolicy {
    /// Refuse group/world permissions. The mapped bytes may contain source,
    /// prompts, weights, or provenance and are sensitive by default.
    pub require_private_file: bool,
    /// Pin the mapping so the OS cannot page its contents to swap. This is
    /// fail-closed because silently continuing would violate the caller's
    /// confidentiality policy.
    pub lock_memory: bool,
}

impl Default for AttachPolicy {
    fn default() -> Self {
        Self {
            require_private_file: true,
            lock_memory: false,
        }
    }
}

impl AttachPolicy {
    pub const fn sensitive() -> Self {
        Self {
            require_private_file: true,
            lock_memory: true,
        }
    }
}

impl core::fmt::Debug for AttachedBucket {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        formatter
            .debug_struct("AttachedBucket")
            .field("path", &self.path)
            .field("id", &self.id)
            .field("bytes", &self.map.len())
            .field("pages", &self.headers.len())
            .finish()
    }
}

impl AttachedBucket {
    /// Attach only if the complete file matches `expected_id` and every page
    /// header/range validates. Payload bytes are exposed directly from mmap.
    pub fn attach(path: impl AsLoaderPath, expected_id: BucketId) -> report::Result<Self> {
        Self::attach_with_policy(path, expected_id, AttachPolicy::default())
    }

    pub fn attach_with_policy(
        path: impl AsLoaderPath,
        expected_id: BucketId,
        policy: AttachPolicy,
    ) -> report::Result<Self> {
        Self::attach_inner(path, Some(expected_id), policy)
    }

    /// Attach a complete immutable generation and derive its identity from the
    /// bytes actually mapped. This is the normal `load cluster.db` path; an
    /// expected identity is an optional pin, not a required sidecar.
    pub fn attach_observed(path: impl AsLoaderPath, policy: AttachPolicy) -> report::Result<Self> {
        Self::attach_inner(path, None, policy)
    }

    fn attach_inner(
        path: impl AsLoaderPath,
        expected_id: Option<BucketId>,
        policy: AttachPolicy,
    ) -> report::Result<Self> {
        let path = path.to_eko_path_buf()?;
        let file = open_readonly_nofollow(&path)
            .map_err(|error| report_msg!("opening DataBucket {}: {error}", path.display()))?;
        let metadata = file
            .metadata()
            .map_err(|error| report_msg!("reading DataBucket metadata: {error}"))?;
        if !metadata.is_file() {
            return Err(report_msg!("DataBucket object is not a regular file"));
        }
        if policy.require_private_file && (metadata.mode() & 0o077 != 0) {
            return Err(report_msg!(
                "sensitive DataBucket {} must not grant group/world permissions",
                path.display()
            ));
        }
        if metadata.len() < GENERAL_HEADER_SIZE as u64 {
            return Err(report_msg!(
                "DataBucket object is shorter than one page header"
            ));
        }

        // SAFETY: this mapping is read-only (`MAP_PRIVATE`). The publication
        // contract forbids truncation after the complete-object digest is published.
        let map = unsafe { Mmap::map(file) }
            .map_err(|error| report_msg!("mapping DataBucket {}: {error}", path.display()))?;

        struct MlockRollback {
            ptr: *const core::ffi::c_void,
            len: usize,
            active: bool,
        }
        impl Drop for MlockRollback {
            fn drop(&mut self) {
                if self.active && self.len > 0 {
                    unsafe {
                        let _ = munlock(self.ptr, self.len);
                    }
                }
            }
        }

        let mut mlock_guard = MlockRollback {
            ptr: map.as_ptr().cast(),
            len: map.len(),
            active: false,
        };
        if policy.lock_memory && !map.is_empty() {
            // Lock before touching/hashing mapped bytes so sensitive pages cannot
            // be faulted in and evicted to swap prior to mlock.
            let status = unsafe { mlock(map.as_ptr().cast(), map.len()) };
            if status != 0 {
                return Err(report_msg!(
                    "locking sensitive DataBucket {} in memory: {}",
                    path.display(),
                    eko::Errno::current()
                ));
            }
            mlock_guard.active = true;
        }

        let observed_id = BucketId::of_bytes(&map);
        if let Some(expected_id) = expected_id.as_ref() {
            if observed_id != *expected_id {
                return Err(report_msg!(
                    "DataBucket identity mismatch: expected {}, observed {}",
                    expected_id.as_str(),
                    observed_id.as_str()
                ));
            }
        }

        let page_count = map.len().div_ceil(PAGE_SIZE);
        let mut headers = Vec::with_capacity(page_count);
        for index in 0..page_count {
            let start = index
                .checked_mul(PAGE_SIZE)
                .ok_or_else(|| report_msg!("DataBucket page offset overflow"))?;
            let header_end = start
                .checked_add(GENERAL_HEADER_SIZE)
                .ok_or_else(|| report_msg!("DataBucket header offset overflow"))?;
            if header_end > map.len() {
                return Err(report_msg!(
                    "DataBucket page {index} has a truncated header"
                ));
            }
            let archived = crate::access_archived::<<GeneralHeader as Archive>::Archived>(
                &map[start..header_end],
            )
            .map_err(|error| {
                report_msg!("DataBucket page {index} header failed validation: {error}")
            })?;
            let header: GeneralHeader = rkyv::deserialize::<_, rkyv::rancor::Error>(archived)
                .map_err(|error| {
                    report_msg!("DataBucket page {index} header failed decode: {error}")
                })?;
            if header.data_version != DATA_VERSION {
                return Err(report_msg!(
                    "DataBucket page {index} version {} differs from supported {DATA_VERSION}",
                    header.data_version
                ));
            }
            if usize::from(header.page_id) != index {
                return Err(report_msg!(
                    "DataBucket physical page {index} declares page id {}",
                    header.page_id
                ));
            }
            let length = payload_length(header)?;
            let data_end = header_end
                .checked_add(length)
                .ok_or_else(|| report_msg!("DataBucket page {index} length overflow"))?;
            let page_end = start
                .checked_add(PAGE_SIZE)
                .ok_or_else(|| report_msg!("DataBucket page {index} end overflow"))?;
            if data_end > map.len() || data_end > page_end {
                return Err(report_msg!(
                    "DataBucket page {index} payload exceeds its page or file"
                ));
            }
            headers.push(header);
        }

        mlock_guard.active = false;

        Ok(Self {
            path,
            id: observed_id,
            map,
            headers,
            memory_locked: policy.lock_memory,
            private_file_checked: policy.require_private_file,
        })
    }

    pub fn id(&self) -> &BucketId {
        &self.id
    }

    pub fn path(&self) -> &Path {
        self.path.as_path()
    }

    pub fn len(&self) -> usize {
        self.map.len()
    }

    pub fn is_empty(&self) -> bool {
        self.map.is_empty()
    }

    pub fn page_count(&self) -> usize {
        self.headers.len()
    }

    pub fn memory_locked(&self) -> bool {
        self.memory_locked
    }

    pub fn page(&self, index: usize) -> report::Result<AttachedPage<'_>> {
        let header = *self
            .headers
            .get(index)
            .ok_or_else(|| report_msg!("DataBucket page {index} is absent"))?;
        let start = index
            .checked_mul(PAGE_SIZE)
            .and_then(|base| base.checked_add(GENERAL_HEADER_SIZE))
            .ok_or_else(|| report_msg!("DataBucket page {index} offset overflow"))?;
        let end = start
            .checked_add(payload_length(header)?)
            .ok_or_else(|| report_msg!("DataBucket page {index} payload end overflow"))?;
        let data = self
            .map
            .get(start..end)
            .ok_or_else(|| report_msg!("DataBucket page {index} slice out of bounds"))?;
        Ok(AttachedPage { header, data })
    }

    pub fn get(&self, link: Link) -> report::Result<&[u8]> {
        let page_index = usize::from(link.page_id);
        let page = self.page(page_index)?;
        let start = link.offset as usize;
        let end = start
            .checked_add(link.length as usize)
            .ok_or_else(|| report_msg!("DataBucket Link range overflow"))?;
        if end > page.data.len() {
            return Err(report_msg!(
                "DataBucket Link [{start}..{end}] exceeds page {page_index} payload {}",
                page.data.len()
            ));
        }
        Ok(&page.data[start..end])
    }
}

impl Drop for AttachedBucket {
    fn drop(&mut self) {
        if self.memory_locked && !self.map.is_empty() {
            // SAFETY: this is the same live range successfully passed to
            // `mlock`; the mapping is dropped only after this method returns.
            unsafe {
                let _ = munlock(self.map.as_ptr().cast(), self.map.len());
            }
        }
    }
}

fn open_readonly_nofollow(path: &Path) -> eko::file::Result<File> {
    let c = path.as_c();
    let fd = unsafe {
        eko::libc_lite::open2(
            c.as_ptr().cast(),
            eko::libc_lite::O_RDONLY | eko::libc_lite::O_CLOEXEC | eko::libc_lite::O_NOFOLLOW,
        )
    };
    if fd < 0 {
        return Err(eko::file::Error::from_errno(eko::Errno::current(), "open"));
    }
    Ok(unsafe { File::from_raw_fd(fd) })
}

/// A shared lease. Removing the registry entry does not invalidate readers;
/// the mapping disappears after the last lease is dropped.
#[derive(Clone, Debug)]
pub struct BucketLease(Arc<AttachedBucket>);

impl Deref for BucketLease {
    type Target = AttachedBucket;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct UnloadReport {
    pub id: BucketId,
    pub removed: bool,
    pub outstanding_leases: usize,
}

/// Process-local registry for explicit load/get/unload operations.
#[derive(Debug, Default)]
pub struct BucketLoader {
    loaded: Mutex<BTreeMap<BucketId, Arc<AttachedBucket>>>,
}

impl BucketLoader {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn load(&self, path: impl AsLoaderPath, id: BucketId) -> report::Result<BucketLease> {
        self.load_with_policy(path, id, AttachPolicy::default())
    }

    pub fn load_observed(
        &self,
        path: impl AsLoaderPath,
        policy: AttachPolicy,
    ) -> report::Result<BucketLease> {
        let attached = Arc::new(AttachedBucket::attach_observed(path, policy)?);
        let id = attached.id().clone();
        let mut loaded = self.loaded.lock();
        let attached = loaded.entry(id).or_insert(attached).clone();
        Self::check_policy(&attached, policy)?;
        Ok(BucketLease(attached))
    }

    pub fn load_with_policy(
        &self,
        path: impl AsLoaderPath,
        id: BucketId,
        policy: AttachPolicy,
    ) -> report::Result<BucketLease> {
        if let Some(existing) = self.get(&id)? {
            Self::check_policy(&existing.0, policy)?;
            return Ok(existing);
        }

        // Digest and page validation happen outside the registry lock.
        let candidate = Arc::new(AttachedBucket::attach_with_policy(
            path,
            id.clone(),
            policy,
        )?);
        let mut loaded = self.loaded.lock();
        let attached = loaded.entry(id).or_insert(candidate).clone();
        Self::check_policy(&attached, policy)?;
        Ok(BucketLease(attached))
    }

    fn check_policy(attached: &AttachedBucket, policy: AttachPolicy) -> report::Result<()> {
        if (policy.lock_memory && !attached.memory_locked)
            || (policy.require_private_file && !attached.private_file_checked)
        {
            return Err(report_msg!(
                "existing attachment does not satisfy the requested policy"
            ));
        }
        Ok(())
    }

    pub fn get(&self, id: &BucketId) -> report::Result<Option<BucketLease>> {
        let loaded = self.loaded.lock();
        Ok(loaded.get(id).cloned().map(BucketLease))
    }

    pub fn unload(&self, id: &BucketId) -> report::Result<UnloadReport> {
        let mut loaded = self.loaded.lock();
        let Some(attachment) = loaded.remove(id) else {
            return Ok(UnloadReport {
                id: id.clone(),
                removed: false,
                outstanding_leases: 0,
            });
        };
        let outstanding_leases = Arc::strong_count(&attachment).saturating_sub(1);
        Ok(UnloadReport {
            id: id.clone(),
            removed: true,
            outstanding_leases,
        })
    }

    /// Quiesce the owner of every index over this bucket before detaching it.
    pub async fn unload_gracefully<F, Fut>(
        &self,
        id: &BucketId,
        timeout: Duration,
        quiesce: F,
    ) -> report::Result<UnloadReport>
    where
        F: FnOnce() -> Fut,
        Fut: Future<Output = report::Result<()>>,
    {
        let Some(target_lease) = self.get(id)? else {
            return Ok(UnloadReport {
                id: id.clone(),
                removed: false,
                outstanding_leases: 0,
            });
        };
        let target_arc = target_lease.0;
        nagoya::timeout(timeout, quiesce())
            .await
            .map_err(|_| report_msg!("timed out while quiescing indexes for {}", id.as_str()))??;
        let mut loaded = self.loaded.lock();
        match loaded.get(id) {
            Some(current) if Arc::ptr_eq(current, &target_arc) => {
                let removed = loaded.remove(id).expect("checked Some above");
                drop(target_arc);
                let outstanding_leases = Arc::strong_count(&removed).saturating_sub(1);
                Ok(UnloadReport {
                    id: id.clone(),
                    removed: true,
                    outstanding_leases,
                })
            }
            _ => Ok(UnloadReport {
                id: id.clone(),
                removed: false,
                outstanding_leases: 0,
            }),
        }
    }

    pub fn loaded_ids(&self) -> report::Result<Vec<BucketId>> {
        let loaded = self.loaded.lock();
        Ok(loaded.keys().cloned().collect())
    }
}

fn payload_length(header: GeneralHeader) -> report::Result<usize> {
    let length = if header.data_length == 0 {
        INNER_PAGE_SIZE
    } else {
        header.data_length as usize
    };
    if length > INNER_PAGE_SIZE {
        return Err(report_msg!(
            "DataBucket page {} declares {} payload bytes, exceeding {}",
            header.page_id,
            length,
            INNER_PAGE_SIZE
        ));
    }
    Ok(length)
}

#[cfg(test)]
mod tests {
    use std::io::Write;

    use crate::{GeneralHeader, PageType, Persistable, SpaceId};

    use super::*;

    fn fixture(payload: &[u8]) -> (tempfile::NamedTempFile, BucketId) {
        let mut header = GeneralHeader::new(0.into(), PageType::Data, SpaceId::from(7));
        header.data_length = payload.len() as u32;
        let mut bytes = vec![0u8; PAGE_SIZE];
        bytes[..GENERAL_HEADER_SIZE].copy_from_slice(header.as_bytes().as_ref());
        bytes[GENERAL_HEADER_SIZE..GENERAL_HEADER_SIZE + payload.len()].copy_from_slice(payload);
        let mut file = tempfile::NamedTempFile::new().unwrap();
        file.write_all(&bytes).unwrap();
        file.as_file().sync_all().unwrap();
        (file, BucketId::of_bytes(&bytes))
    }

    #[test]
    fn attachment_exposes_page_and_link_from_the_mapping() {
        let (file, id) = fixture(b"typed-node-data");
        let bucket = AttachedBucket::attach(file.path(), id).unwrap();
        assert_eq!(bucket.page_count(), 1);
        assert_eq!(bucket.page(0).unwrap().data, b"typed-node-data");
        assert_eq!(
            bucket
                .get(Link {
                    page_id: 0.into(),
                    offset: 6,
                    length: 4,
                })
                .unwrap(),
            b"node"
        );
    }

    #[test]
    fn identity_and_page_corruption_fail_closed() {
        let (mut file, id) = fixture(b"evidence");
        let wrong = BucketId::of_bytes(b"other");
        assert!(AttachedBucket::attach(file.path(), wrong).is_err());

        file.as_file_mut().write_all(&[0xff]).unwrap();
        file.as_file_mut().sync_all().unwrap();
        assert!(AttachedBucket::attach(file.path(), id).is_err());
    }

    #[cfg(unix)]
    #[test]
    fn sensitive_attach_rejects_public_permissions_and_symlinks() {
        use std::os::unix::fs::{symlink, PermissionsExt as _};

        let (file, id) = fixture(b"secret");
        std::fs::set_permissions(file.path(), std::fs::Permissions::from_mode(0o644)).unwrap();
        assert!(AttachedBucket::attach(file.path(), id.clone()).is_err());

        std::fs::set_permissions(file.path(), std::fs::Permissions::from_mode(0o600)).unwrap();
        let link_dir = tempfile::tempdir().unwrap();
        let link = link_dir.path().join("bucket.db");
        symlink(file.path(), &link).unwrap();
        assert!(AttachedBucket::attach(link, id).is_err());
    }

    #[test]
    fn unload_removes_discovery_but_preserves_outstanding_leases() {
        let (file, id) = fixture(b"resident");
        let loader = BucketLoader::new();
        let lease = loader.load(file.path(), id.clone()).unwrap();
        let second = loader.get(&id).unwrap().unwrap();
        assert_eq!(loader.loaded_ids().unwrap(), vec![id.clone()]);

        let report = loader.unload(&id).unwrap();
        assert!(report.removed);
        assert_eq!(report.outstanding_leases, 2);
        assert!(loader.get(&id).unwrap().is_none());
        assert_eq!(lease.page(0).unwrap().data, b"resident");
        assert_eq!(second.page(0).unwrap().data, b"resident");
    }

    #[test]
    fn repeated_load_reuses_the_same_attachment_identity() {
        let (file, id) = fixture(b"shared");
        let loader = BucketLoader::new();
        let first = loader.load(file.path(), id.clone()).unwrap();
        let second = loader.load(file.path(), id).unwrap();
        assert!(Arc::ptr_eq(&first.0, &second.0));
    }

    #[test]
    fn graceful_unload_waits_for_the_index_owner() {
        nagoya::block_on(async {
            let (file, id) = fixture(b"durable");
            let loader = BucketLoader::new();
            let lease = loader.load(file.path(), id.clone()).unwrap();
            let flushed = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
            let observed = flushed.clone();

            let report = loader
                .unload_gracefully(&id, Duration::from_secs(1), || async move {
                    observed.store(true, std::sync::atomic::Ordering::SeqCst);
                    Ok(())
                })
                .await
                .unwrap();

            assert!(flushed.load(std::sync::atomic::Ordering::SeqCst));
            assert!(report.removed);
            assert!(loader.get(&id).unwrap().is_none());
            assert_eq!(lease.page(0).unwrap().data, b"durable");
        });
    }

    #[test]
    fn failed_or_timed_out_quiescence_keeps_the_bucket_loaded() {
        nagoya::block_on(async {
            let (file, id) = fixture(b"no-wal");
            let loader = BucketLoader::new();
            loader.load(file.path(), id.clone()).unwrap();

            let failed = loader
                .unload_gracefully(&id, Duration::from_secs(1), || async {
                    Err(report_msg!("flush failed"))
                })
                .await;
            assert!(failed.is_err());
            assert!(loader.get(&id).unwrap().is_some());

            let timed_out = loader
                .unload_gracefully(&id, Duration::from_millis(1), || async {
                    nagoya::sleep(Duration::from_secs(1)).await;
                    Ok(())
                })
                .await;
            assert!(timed_out.is_err());
            assert!(loader.get(&id).unwrap().is_some());
        });
    }
}