Skip to main content

aft_base/
live_db_files.rs

1//! Which file on disk each open SQLite connection is actually attached to.
2//!
3//! SQLite keeps one WAL-index (the `-shm` file) per database file inside a
4//! process, and the first connection to win the exclusive dead-man-switch lock
5//! on a `-shm` shrinks that file (to three bytes on Darwin, zero on other Unix
6//! platforms) before mapping it. POSIX
7//! advisory locks never conflict between two descriptors held by the *same*
8//! process, so that lock protects nothing once one process holds two
9//! connections attached to two *different* database files at the *same* path:
10//! the newer connection truncates a `-shm` the older connection has already
11//! memory-mapped, and the older connection dies with SIGBUS the next time it
12//! reads through the mapping.
13//!
14//! Nothing in that crash names its cause. The fault surfaces deep inside
15//! SQLite, in whichever later query happens to touch the mapping, long after
16//! the delete-and-recreate that set it up. So this registry records the
17//! identity of the file behind every tracked connection and reports the moment
18//! two identities diverge at one path, naming the database and both
19//! connections. It also reports a database file that is deleted, renamed, or
20//! replaced while this process still has a connection open on it, which is the
21//! operation that creates the divergence in the first place.
22//!
23//! Callgraph file-set mutations also use this registry for enforcement: opening
24//! and registering a handle is serialized with checking for live users and
25//! removing or renaming its files.
26
27use std::collections::{BTreeMap, HashMap, HashSet};
28use std::ffi::OsStr;
29use std::path::{Path, PathBuf};
30use std::sync::{Mutex, OnceLock, RwLock};
31
32/// Most recent hazards retained for inspection. Bounded because a process that
33/// keeps replacing databases under open connections would otherwise grow this
34/// without limit.
35const RETAINED_HAZARDS: usize = 64;
36
37/// Identity of the file a connection is attached to, as SQLite keys it: the
38/// device and inode, not the path.
39#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
40pub struct FileIdentity {
41    device: u64,
42    inode: u64,
43}
44
45impl std::fmt::Display for FileIdentity {
46    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47        write!(formatter, "dev={}/ino={}", self.device, self.inode)
48    }
49}
50
51/// Read the identity of the file currently at `path`.
52///
53/// Unix uses device/inode; Windows uses volume serial number/file index from
54/// a metadata-only handle. Returns `None` when no identity is available.
55pub fn identity_of(path: &Path) -> Option<FileIdentity> {
56    #[cfg(any(test, feature = "test-support"))]
57    stat_probe::record(path);
58    native_identity(crate::file_identity::metadata(path).ok()?.1)
59}
60
61fn native_identity(identity: crate::file_identity::FileIdentity) -> Option<FileIdentity> {
62    match identity {
63        crate::file_identity::FileIdentity::Known { volume, index } => Some(FileIdentity {
64            device: volume,
65            inode: index,
66        }),
67        crate::file_identity::FileIdentity::Unavailable => None,
68    }
69}
70
71#[rustfmt::skip]
72test_support_visibility! {
73
74fn metadata_identity(metadata: &std::fs::Metadata) -> Option<FileIdentity> {
75    #[cfg(unix)]
76    {
77        use std::os::unix::fs::MetadataExt;
78        Some(FileIdentity {
79            device: metadata.dev(),
80            inode: metadata.ino(),
81        })
82    }
83    #[cfg(not(unix))]
84    {
85        let _ = metadata;
86        None
87    }
88}
89}
90
91#[rustfmt::skip]
92test_support_visibility! {
93// Cached sidecar identities outlive unlinks while a database remains open.
94// Include birth time where available to distinguish recycled inodes from live
95// SQLite aliases. Unlike ctime, birth time survives renames.
96#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
97struct LiveFileIdentity {
98    #[cfg(any(test, feature = "test-support"))]
99    pub file: FileIdentity,
100    #[cfg(not(any(test, feature = "test-support")))]
101    file: FileIdentity,
102    #[cfg(any(test, feature = "test-support"))]
103    pub created: Option<std::time::SystemTime>,
104    #[cfg(not(any(test, feature = "test-support")))]
105    created: Option<std::time::SystemTime>,
106}
107}
108
109impl LiveFileIdentity {
110    fn from_metadata(metadata: &std::fs::Metadata) -> Option<Self> {
111        Some(Self {
112            file: metadata_identity(metadata)?,
113            // Filesystems without birth times retain inode-only protection.
114            created: metadata.created().ok(),
115        })
116    }
117
118    fn of(path: &Path) -> Option<Self> {
119        #[cfg(any(test, feature = "test-support"))]
120        stat_probe::record_followed(path);
121        let (metadata, identity) = crate::file_identity::metadata(path).ok()?;
122        Some(Self {
123            file: native_identity(identity)?,
124            created: metadata.created().ok(),
125        })
126    }
127}
128
129pub(crate) fn candidate_metadata(path: &Path) -> std::io::Result<std::fs::Metadata> {
130    #[cfg(any(test, feature = "test-support"))]
131    stat_probe::record(path);
132    std::fs::symlink_metadata(path)
133}
134
135#[derive(Clone, Copy, Debug, PartialEq, Eq)]
136pub enum HazardKind {
137    /// Two live connections in this process are attached to two different files
138    /// at one path. This is the precondition for the WAL-index truncation
139    /// described at the top of this module.
140    Replaced,
141    /// A database file was deleted, renamed, or replaced while this process
142    /// still had a connection open on it.
143    MutatedWhileOpen,
144}
145
146impl HazardKind {
147    const fn summary(self) -> &'static str {
148        match self {
149            Self::Replaced => "two open connections are attached to different files at one path",
150            Self::MutatedWhileOpen => "database file changed while connections were open on it",
151        }
152    }
153}
154
155#[derive(Clone, Debug, PartialEq, Eq)]
156pub struct DatabaseHazard {
157    pub kind: HazardKind,
158    pub path: PathBuf,
159    pub detail: String,
160}
161
162impl DatabaseHazard {
163    pub fn message(&self) -> String {
164        format!(
165            "sqlite database hazard ({}): {} — {}",
166            self.kind.summary(),
167            self.path.display(),
168            self.detail
169        )
170    }
171}
172
173#[derive(Clone, Debug)]
174struct Opener {
175    store: &'static str,
176    thread: String,
177    identity: Option<FileIdentity>,
178}
179
180impl Opener {
181    fn describe(&self) -> String {
182        match self.identity {
183            Some(identity) => format!("{} on {} attached to {identity}", self.store, self.thread),
184            None => format!(
185                "{} on {} (file identity unavailable)",
186                self.store, self.thread
187            ),
188        }
189    }
190}
191
192#[rustfmt::skip]
193test_support_visibility! {
194#[derive(Debug, Default)]
195struct OpenDatabase {
196    openers: Vec<Opener>,
197    identities: HashSet<LiveFileIdentity>,
198}
199}
200
201#[rustfmt::skip]
202test_support_visibility! {
203
204fn open_databases() -> &'static Mutex<BTreeMap<PathBuf, OpenDatabase>> {
205    static DATABASES: OnceLock<Mutex<BTreeMap<PathBuf, OpenDatabase>>> = OnceLock::new();
206    DATABASES.get_or_init(|| Mutex::new(BTreeMap::new()))
207}
208}
209
210#[derive(Default)]
211struct LiveFiles {
212    names: HashMap<PathBuf, usize>,
213    identities: HashMap<LiveFileIdentity, usize>,
214}
215
216fn live_files() -> &'static RwLock<LiveFiles> {
217    static FILES: OnceLock<RwLock<LiveFiles>> = OnceLock::new();
218    FILES.get_or_init(RwLock::default)
219}
220
221#[rustfmt::skip]
222test_support_visibility! {
223
224fn database_files(key: &Path) -> [PathBuf; 4] {
225    let sidecar = |suffix| {
226        let mut path = key.as_os_str().to_os_string();
227        path.push(suffix);
228        PathBuf::from(path)
229    };
230    [
231        key.to_path_buf(),
232        sidecar("-wal"),
233        sidecar("-shm"),
234        sidecar("-journal"),
235    ]
236}
237}
238
239#[rustfmt::skip]
240test_support_visibility! {
241
242fn retain_identities(
243    database: &mut OpenDatabase,
244    identities: impl IntoIterator<Item = LiveFileIdentity>,
245) {
246    let mut files = live_files().write().unwrap_or_else(|p| p.into_inner());
247    for identity in identities {
248        if database.identities.insert(identity) {
249            *files.identities.entry(identity).or_default() += 1;
250        }
251    }
252}
253}
254
255fn reported() -> &'static Mutex<Vec<DatabaseHazard>> {
256    static REPORTED: OnceLock<Mutex<Vec<DatabaseHazard>>> = OnceLock::new();
257    REPORTED.get_or_init(|| Mutex::new(Vec::new()))
258}
259
260/// Resolve a path to the key this registry files it under.
261///
262/// Symlinks are followed so two spellings of one database agree, matching how
263/// SQLite itself keys a database by the inode it ends up at. A path that names
264/// nothing yet still resolves through its parent directory, so the key a
265/// removal computes matches the key its connections registered under.
266fn registry_key(path: &Path) -> PathBuf {
267    if let Ok(resolved) = std::fs::canonicalize(path) {
268        return resolved;
269    }
270    match (path.parent(), path.file_name()) {
271        (Some(parent), Some(name)) if !parent.as_os_str().is_empty() => {
272            std::fs::canonicalize(parent).map_or_else(|_| path.to_path_buf(), |dir| dir.join(name))
273        }
274        _ => path.to_path_buf(),
275    }
276}
277
278fn thread_label() -> String {
279    let current = std::thread::current();
280    match current.name() {
281        Some(name) => format!("thread {name}"),
282        None => format!("thread {:?}", current.id()),
283    }
284}
285
286fn crash_diagnostics_armed() -> bool {
287    static ARMED: OnceLock<bool> = OnceLock::new();
288    *ARMED.get_or_init(|| {
289        std::env::var_os("AFT_CAPTURE_CRASH_DIAGNOSTICS").as_deref() == Some(OsStr::new("1"))
290    })
291}
292
293fn report(hazard: DatabaseHazard) {
294    let message = hazard.message();
295    crate::slog_warn!("{message}");
296    if crash_diagnostics_armed() {
297        // The test run that arms fatal-signal diagnostics collects stderr, and a
298        // hazard reported here is the earlier event a later SIGBUS is downstream
299        // of, so the two land in one log next to each other.
300        write_stderr_line(&format!("\nAFT sqlite database hazard: {message}\n"));
301    }
302    let mut reported = reported()
303        .lock()
304        .unwrap_or_else(std::sync::PoisonError::into_inner);
305    if reported.len() >= RETAINED_HAZARDS {
306        reported.remove(0);
307    }
308    reported.push(hazard);
309}
310
311/// Write straight to the standard error descriptor.
312///
313/// Rust's test harness captures `eprintln!` and discards it for a test that
314/// passes, and throws it away entirely when the process dies by signal. A
315/// hazard is most valuable in exactly those two cases: a run that did not crash
316/// but set the crash up, and the run that crashed. Writing to the descriptor
317/// bypasses the capture, which is what the fatal-signal handler already does.
318#[cfg(unix)]
319fn write_stderr_line(line: &str) {
320    let bytes = line.as_bytes();
321    unsafe {
322        libc::write(
323            libc::STDERR_FILENO,
324            bytes.as_ptr().cast::<std::ffi::c_void>(),
325            bytes.len(),
326        );
327    }
328}
329
330#[cfg(not(unix))]
331fn write_stderr_line(line: &str) {
332    eprint!("{line}");
333}
334
335/// Serialize SQLite opens with AFT file-set mutations. The staging database
336/// keeps this gate while checking whether its file exists and calling the open
337/// helper; reentrancy permits that nested call. Connection lifetimes do not hold
338/// this gate; the registry protects live users.
339fn filesystem_gate() -> &'static parking_lot::ReentrantMutex<()> {
340    static GATE: parking_lot::ReentrantMutex<()> = parking_lot::ReentrantMutex::new(());
341    &GATE
342}
343
344pub fn filesystem_guard() -> parking_lot::ReentrantMutexGuard<'static, ()> {
345    filesystem_gate().lock()
346}
347
348/// Record that a tracked connection has opened `path`, and return the key the
349/// matching [`note_close`] must use.
350///
351/// The key is returned rather than recomputed at close time because the
352/// database file may be gone by then, and a path that no longer resolves would
353/// otherwise file the close under a different key than the open.
354pub fn note_open(path: &Path, store: &'static str) -> PathBuf {
355    let key = registry_key(path);
356    let paths = database_files(&key);
357    let identities = paths.each_ref().map(|path| LiveFileIdentity::of(path));
358    let opener = Opener {
359        store,
360        thread: thread_label(),
361        identity: identities[0].map(|identity| identity.file),
362    };
363    let hazard = {
364        let mut databases = open_databases()
365            .lock()
366            .unwrap_or_else(std::sync::PoisonError::into_inner);
367        let entry = databases.entry(key.clone()).or_default();
368        if entry.openers.is_empty() {
369            let mut files = live_files().write().unwrap_or_else(|p| p.into_inner());
370            for path in paths {
371                *files.names.entry(path).or_default() += 1;
372            }
373        }
374        let hazard = replacement_hazard(&key, entry, &opener);
375        retain_identities(entry, identities.into_iter().flatten());
376        entry.openers.push(opener);
377        hazard
378    };
379    if let Some(hazard) = hazard {
380        report(hazard);
381    }
382    key
383}
384
385/// Record that a tracked connection opened under `key` has closed.
386pub fn note_close(key: &Path, store: &'static str) {
387    let mut databases = open_databases()
388        .lock()
389        .unwrap_or_else(std::sync::PoisonError::into_inner);
390    let Some(entry) = databases.get_mut(key) else {
391        return;
392    };
393    if let Some(index) = entry
394        .openers
395        .iter()
396        .rposition(|opener| opener.store == store)
397    {
398        entry.openers.remove(index);
399    }
400    if entry.openers.is_empty() {
401        let mut files = live_files().write().unwrap_or_else(|p| p.into_inner());
402        for path in database_files(key) {
403            if let Some(count) = files.names.get_mut(&path) {
404                *count -= 1;
405                if *count == 0 {
406                    files.names.remove(&path);
407                }
408            }
409        }
410        for identity in &entry.identities {
411            if let Some(count) = files.identities.get_mut(identity) {
412                *count -= 1;
413                if *count == 0 {
414                    files.identities.remove(identity);
415                }
416            }
417        }
418        databases.remove(key);
419    }
420}
421
422fn replacement_hazard(key: &Path, entry: &OpenDatabase, opener: &Opener) -> Option<DatabaseHazard> {
423    let identity = opener.identity?;
424    let previous = entry
425        .openers
426        .iter()
427        .find(|held| held.identity.is_some_and(|held| held != identity))?;
428    Some(DatabaseHazard {
429        kind: HazardKind::Replaced,
430        path: key.to_path_buf(),
431        detail: format!(
432            "the already-open {} met a new {}; SQLite shares one WAL-index per path, \
433             so the newer connection truncates the WAL-index the older one has mapped",
434            previous.describe(),
435            opener.describe()
436        ),
437    })
438}
439
440/// Number of registered connections at `path` or at another name for its inode.
441/// Hold [`filesystem_guard`] across this query and any file-set mutation so an
442/// opener cannot appear between checking the registry and changing the files.
443pub fn registered_connections_for_key(key: &Path) -> usize {
444    open_databases()
445        .lock()
446        .unwrap_or_else(std::sync::PoisonError::into_inner)
447        .get(key)
448        .map_or(0, |entry| entry.openers.len())
449}
450
451pub fn open_connections(path: &Path) -> usize {
452    let key = registry_key(path);
453    let identity = identity_of(&key);
454    open_databases()
455        .lock()
456        .unwrap_or_else(std::sync::PoisonError::into_inner)
457        .iter()
458        .map(|(registered_path, entry)| {
459            entry
460                .openers
461                .iter()
462                .filter(|opener| {
463                    registered_path == &key || identity.is_some() && opener.identity == identity
464                })
465                .count()
466        })
467        .sum()
468}
469
470#[rustfmt::skip]
471test_support_visibility! {
472
473/// Cheap name check for project walkers whose roots are already canonical.
474pub(crate) fn is_registered_file_path(path: &Path) -> bool {
475    live_files()
476        .read()
477        .unwrap_or_else(|p| p.into_inner())
478        .names
479        .contains_key(path)
480}
481}
482
483/// Source readers must also reject aliases to live databases and their
484/// sidecars. `stat` inspects the inode without opening a descriptor, so it does
485/// not release SQLite's process-wide file locks.
486pub fn is_live_sqlite_file(path: &Path) -> bool {
487    if is_registered_file_path(path) {
488        return true;
489    }
490    #[cfg(any(test, feature = "test-support"))]
491    stat_probe::record(path);
492    let Ok((metadata, identity, links)) = crate::file_identity::metadata_with_link_count(path)
493    else {
494        return false;
495    };
496    let Some(file) = native_identity(identity) else {
497        return false;
498    };
499    is_live_identity(
500        LiveFileIdentity {
501            file,
502            created: metadata.created().ok(),
503        },
504        links,
505    )
506}
507
508fn is_live_identity(identity: LiveFileIdentity, links: u64) -> bool {
509    let known = || {
510        live_files()
511            .read()
512            .unwrap_or_else(|p| p.into_inner())
513            .identities
514            .contains_key(&identity)
515    };
516    if known() {
517        return true;
518    }
519    if links < 2 {
520        return false;
521    }
522    refresh_sidecar_identities();
523    known()
524}
525
526pub fn is_live_sqlite_file_with_metadata(
527    path: &Path,
528    metadata: Option<&std::fs::Metadata>,
529) -> bool {
530    #[cfg(windows)]
531    {
532        // On Windows, std::fs::Metadata omits the file index; crate::file_identity
533        // reads it from a handle opened without data access.
534        let _ = metadata;
535        return is_live_sqlite_file(path);
536    }
537    #[cfg(not(windows))]
538    {
539        // A symlink's own inode and link count say nothing about SQLite's target.
540        // Resolve only this uncommon case; ordinary source reads need one stat.
541        if metadata.is_some_and(|metadata| metadata.file_type().is_symlink()) {
542            let key = registry_key(path);
543            if is_registered_file_path(&key) {
544                return true;
545            }
546            let target = std::fs::metadata(path).ok();
547            return is_live_sqlite_file_with_metadata(&key, target.as_ref());
548        }
549        let Some(metadata) = metadata else {
550            return false;
551        };
552        let Some(identity) = LiveFileIdentity::from_metadata(metadata) else {
553            return false;
554        };
555        #[cfg(unix)]
556        let links = {
557            use std::os::unix::fs::MetadataExt;
558            metadata.nlink()
559        };
560        #[cfg(not(unix))]
561        let links = 1;
562        is_live_identity(identity, links)
563    }
564}
565
566fn refresh_sidecar_identities() {
567    let paths = open_databases()
568        .lock()
569        .unwrap_or_else(|p| p.into_inner())
570        .keys()
571        .cloned()
572        .collect::<Vec<_>>();
573    // Never stat while holding the connection registry or the reader cache lock.
574    let refreshed = paths
575        .into_iter()
576        .map(|key| {
577            let identities = database_files(&key)[1..]
578                .iter()
579                .filter_map(|path| LiveFileIdentity::of(path))
580                .collect::<Vec<_>>();
581            (key, identities)
582        })
583        .collect::<Vec<_>>();
584    let mut databases = open_databases().lock().unwrap_or_else(|p| p.into_inner());
585    for (key, identities) in refreshed {
586        if let Some(database) = databases.get_mut(&key) {
587            retain_identities(database, identities);
588        }
589    }
590}
591
592/// Whether an already-open file is a live SQLite database or sidecar, judged
593/// by the handle's own identity (`metadata` must come from the open handle):
594/// its device and inode, plus its birth time where the filesystem records
595/// one, exactly as the registry keys live files. Unlike the path checks above
596/// there is no link-count shortcut: by the time a file is open, the names
597/// that made it look innocent may already be gone. Birth time keeps a
598/// recycled inode of an unlinked sidecar from refusing an unrelated file.
599///
600/// On Windows, std::fs::Metadata omits the file index. Use is_live_sqlite_file
601/// there to obtain the identity through a metadata-only handle.
602pub fn is_live_sqlite_handle(metadata: &std::fs::Metadata) -> bool {
603    let Some(identity) = LiveFileIdentity::from_metadata(metadata) else {
604        return false;
605    };
606    let known = || {
607        live_files()
608            .read()
609            .unwrap_or_else(|p| p.into_inner())
610            .identities
611            .contains_key(&identity)
612    };
613    if known() {
614        return true;
615    }
616    // Sidecars created after their database opened are learned only here.
617    #[cfg(unix)]
618    refresh_sidecar_identities();
619    known()
620}
621
622/// Report `action` if it is about to delete, rename, or replace the database
623/// file at `path` while this process still has a connection open on it.
624///
625/// `action` names the caller in the report, so it should read as a description
626/// of the operation, for example `"callgraph generation sweep"`.
627pub fn guard_replacement(path: &Path, action: &str) {
628    let key = registry_key(path);
629    let detail = {
630        let databases = open_databases()
631            .lock()
632            .unwrap_or_else(std::sync::PoisonError::into_inner);
633        let Some(entry) = databases.get(&key) else {
634            return;
635        };
636        if entry.openers.is_empty() {
637            return;
638        }
639        let openers = entry
640            .openers
641            .iter()
642            .map(Opener::describe)
643            .collect::<Vec<_>>()
644            .join("; ");
645        format!("{action} ran while these connections were still open: [{openers}]")
646    };
647    report(DatabaseHazard {
648        kind: HazardKind::MutatedWhileOpen,
649        path: key,
650        detail,
651    });
652}
653
654/// Hazards reported for `path` so far, newest last.
655pub fn hazards_for_path(path: &Path) -> Vec<DatabaseHazard> {
656    let key = registry_key(path);
657    reported()
658        .lock()
659        .unwrap_or_else(std::sync::PoisonError::into_inner)
660        .iter()
661        .filter(|hazard| hazard.path == key)
662        .cloned()
663        .collect()
664}
665
666/// Every hazard retained so far, newest last.
667pub fn reported_hazards() -> Vec<DatabaseHazard> {
668    reported()
669        .lock()
670        .unwrap_or_else(std::sync::PoisonError::into_inner)
671        .clone()
672}
673
674#[cfg(any(test, feature = "test-support"))]
675pub mod stat_probe {
676    use super::*;
677    use std::cell::RefCell;
678
679    thread_local! {
680        static COUNTS: RefCell<Option<BTreeMap<PathBuf, usize>>> = const { RefCell::new(None) };
681        static CANDIDATES_ONLY: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
682    }
683
684    pub fn record_followed(path: &Path) {
685        if !CANDIDATES_ONLY.with(|only| only.get()) {
686            record(path);
687        }
688    }
689
690    pub fn record(path: &Path) {
691        COUNTS.with(|counts| {
692            if let Some(counts) = counts.borrow_mut().as_mut() {
693                *counts.entry(path.to_path_buf()).or_default() += 1;
694            }
695        });
696    }
697
698    pub fn count(f: impl FnOnce()) -> BTreeMap<PathBuf, usize> {
699        struct Reset;
700        impl Drop for Reset {
701            fn drop(&mut self) {
702                COUNTS.with(|counts| *counts.borrow_mut() = None);
703            }
704        }
705        let _reset = Reset;
706        COUNTS.with(|counts| *counts.borrow_mut() = Some(BTreeMap::new()));
707        f();
708        COUNTS.with(|counts| counts.borrow_mut().take().unwrap())
709    }
710}
711
712#[cfg(test)]
713mod tests {
714    #[cfg(unix)]
715    use super::*;
716
717    // Only the POSIX-only tests below open raw connections.
718    #[cfg(unix)]
719    use rusqlite::Connection;
720
721    #[cfg(unix)]
722    fn shm_path(path: &Path) -> PathBuf {
723        PathBuf::from(format!("{}-shm", path.display()))
724    }
725
726    /// The mechanism, stated as an executable fact about SQLite rather than as
727    /// prose: replace the database file at a path while a connection still has
728    /// that path's WAL-index mapped, and the next connection truncates the
729    /// WAL-index under the first one.
730    ///
731    /// SQLite maps a WAL-index in 32 KiB regions and re-extends the file to
732    /// cover region 0 immediately after truncating it, so the visible damage is
733    /// the file shrinking back to one region while the first connection still
734    /// holds pointers into region 1. Reading through those pointers is a read
735    /// past the end of a file-backed mapping, which the kernel answers with a
736    /// page-aligned SIGBUS. That is why the fixture first grows the WAL past
737    /// the 4062 frames region 0 can index: with only region 0 mapped, the
738    /// re-extension hides the truncation behind a page of zeroes instead.
739    ///
740    /// The first connection is deliberately never used or dropped after the
741    /// truncation: touching it is the fault. Leaking one handle for the rest of
742    /// the test binary is the price of observing the state safely.
743    // Windows refuses to unlink or rename a database while a connection holds
744    // it open, so the replaced-under-a-live-connection precondition cannot form
745    // there; the hazard this registry reports is a POSIX one.
746    #[cfg(unix)]
747    #[test]
748    fn replacing_the_database_file_truncates_the_wal_index_under_a_live_mapping() {
749        /// SQLite maps the WAL-index one 32 KiB region at a time.
750        const WAL_INDEX_REGION_BYTES: u64 = 32 * 1024;
751
752        let dir = tempfile::tempdir().expect("tempdir");
753        let path = dir.path().join("replaced.sqlite");
754
755        let first = Connection::open(&path).expect("open first connection");
756        // A small page size keeps the WAL small in bytes while still producing
757        // the thousands of frames needed to reach the second WAL-index region.
758        first
759            .pragma_update(None, "page_size", 512)
760            .expect("small pages");
761        first
762            .pragma_update(None, "journal_mode", "WAL")
763            .expect("first connection WAL");
764        first
765            .pragma_update(None, "synchronous", "OFF")
766            .expect("unsynced fixture writes");
767        first
768            .pragma_update(None, "wal_autocheckpoint", 0)
769            .expect("no autocheckpoint");
770        first
771            .execute_batch("CREATE TABLE t(id INTEGER PRIMARY KEY, payload BLOB);")
772            .expect("seed");
773
774        // One transaction per row, so every commit appends WAL frames and the
775        // log grows past what a single WAL-index region can address.
776        let mut mapped_bytes = 0;
777        for id in 0..20_000_i64 {
778            first
779                .execute(
780                    "INSERT INTO t(id, payload) VALUES (?1, zeroblob(400))",
781                    [id],
782                )
783                .expect("append a WAL frame");
784            if id % 256 == 0 {
785                mapped_bytes = std::fs::metadata(shm_path(&path))
786                    .expect("WAL-index exists")
787                    .len();
788                if mapped_bytes > WAL_INDEX_REGION_BYTES {
789                    break;
790                }
791            }
792        }
793        assert!(
794            mapped_bytes > WAL_INDEX_REGION_BYTES,
795            "fixture never mapped a second WAL-index region (got {mapped_bytes} bytes); \
796             without one the truncation is hidden by SQLite re-extending region 0"
797        );
798        let first_identity = identity_of(&path).expect("first database identity");
799
800        // Replace the database file at the same path, leaving the WAL-index
801        // exactly where it is. This is the shape being hunted: a new database
802        // file inode under an unchanged `-shm` inode.
803        std::fs::remove_file(&path).expect("remove the database file");
804        let second = Connection::open(&path).expect("open second connection");
805        second
806            .pragma_update(None, "journal_mode", "WAL")
807            .expect("second connection WAL");
808        second
809            .execute_batch("CREATE TABLE t(id INTEGER PRIMARY KEY);")
810            .expect("write through the replacement");
811        let second_identity = identity_of(&path).expect("second database identity");
812        assert_ne!(
813            first_identity, second_identity,
814            "fixture did not actually replace the database file"
815        );
816
817        let after_bytes = std::fs::metadata(shm_path(&path))
818            .expect("WAL-index still exists")
819            .len();
820        assert!(
821            after_bytes < mapped_bytes,
822            "the second connection did not truncate the WAL-index the first one has mapped \
823             (before={mapped_bytes} bytes, after={after_bytes} bytes)"
824        );
825
826        drop(second);
827        // Dropping `first` would make SQLite read the truncated mapping during
828        // its close-time checkpoint, so the handle is deliberately leaked.
829        std::mem::forget(first);
830    }
831}