From 2427c56259930c68dce4e95d72276277a2ca803e Mon Sep 17 00:00:00 2001 From: eitsupi Date: Thu, 10 Sep 2026 13:39:30 +0000 Subject: [PATCH 1/4] feat(rd-rds): add installed code database inspection --- CHANGELOG.md | 3 + crates/rd-rds/README.md | 14 + crates/rd-rds/src/inspect.rs | 2 +- crates/rd-rds/src/package.rs | 11 + crates/rd-rds/src/package/installed_code.rs | 811 ++++++++++++++++++ .../tests/fixtures/data/lazyload/README.md | 4 +- .../data/lazyload/installed/empty.rdb | 0 .../data/lazyload/installed/empty.rdx | Bin 0 -> 169 bytes .../generate_installed_lazyload_fixture.R | 9 + crates/rd-rds/tests/installed_code.rs | 284 ++++++ 10 files changed, 1136 insertions(+), 2 deletions(-) create mode 100644 crates/rd-rds/src/package/installed_code.rs create mode 100644 crates/rd-rds/tests/fixtures/data/lazyload/installed/empty.rdb create mode 100644 crates/rd-rds/tests/fixtures/data/lazyload/installed/empty.rdx create mode 100644 crates/rd-rds/tests/installed_code.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 22718c3..d25efd6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,9 @@ ### Added +- [rd-rds] Add the package-level `package::InstalledCodeDb` API for explicit + installed-package `R/.rdx`/`.rdb` access, index-order stored bindings, + bounded closure-prefix inspection, and best-effort database provenance. - [rd-rds] Add the owned `package::NamespaceMetadata` view for static `Meta/nsInfo.rds` declarations, including field-local diagnostics, import aliases and exclusions, source/export name pairs, S3 diff --git a/crates/rd-rds/README.md b/crates/rd-rds/README.md index dfd888e..b515b32 100644 --- a/crates/rd-rds/README.md +++ b/crates/rd-rds/README.md @@ -29,6 +29,20 @@ API returns both the exact addressed bytes and the decompressed payload, with independent 256 MiB default bounds. Raw records are already XDR bytes and do not carry a length prefix; zlib records carry a four-byte declared length. +With the same feature, [`package::InstalledCodeDb`] provides the package-level +API for that pair. The caller supplies the installed package directory; the +reader selects `R/.rdx` and `.rdb` and does not discover libraries or +scan runtime exports. [`InstalledCodeDb::stored_bindings`] is the complete +`variables` map in index order, including duplicate names. Consequently this +view's completeness domain is `CodeDatabaseVariables`, not exports or runtime +bindings. [`InstalledCodeDb::inspect_stored_binding`] returns structured +unknown/ambiguous errors instead of choosing among duplicate names, reads only +a unique direct record, and returns bounded closure prefix metadata. Closure +bodies are reported as `BodyValidation::NotValidated`. +The provenance includes both selected paths, compression, and an opaque +`CodeDbGeneration` derived from best-effort file metadata. It is an identity +hint rather than a content hash or a transaction guarantee. + The `lazyload` feature includes the `gzip` feature because installed package `.rdx` indexes use the standalone gzip envelope in the normal package profile. Callers that enable `lazyload` therefore also get gzip `.rds` diff --git a/crates/rd-rds/src/inspect.rs b/crates/rd-rds/src/inspect.rs index fb1f982..3271e79 100644 --- a/crates/rd-rds/src/inspect.rs +++ b/crates/rd-rds/src/inspect.rs @@ -5,7 +5,7 @@ //! closure body tag, which makes it suitable for answering metadata queries //! about large or partially damaged objects. -#![allow(dead_code)] +#![cfg_attr(not(feature = "lazyload"), allow(dead_code))] use std::fmt; diff --git a/crates/rd-rds/src/package.rs b/crates/rd-rds/src/package.rs index 08082ef..a2f0e1b 100644 --- a/crates/rd-rds/src/package.rs +++ b/crates/rd-rds/src/package.rs @@ -30,6 +30,17 @@ use crate::{RObject, RStr, RValue}; mod namespace; +#[cfg(feature = "lazyload")] +mod installed_code; + +#[cfg(feature = "lazyload")] +pub use installed_code::{ + BodyValidation, CodeDbGeneration, CodeDbProvenance, DefaultPresence, FailureCause, + FailurePhase, Formal, FormalsInspection, FormalsNotApplicable, FormalsUnavailable, + FunctionFormals, InspectionExtent, InstalledCodeDb, InstalledCodeError, InstalledCodeOptions, + PrefixFailure, StoredBinding, StoredKind, StoredObjectInspection, +}; + pub use namespace::{ ImportedName, MetadataField, NamespaceExport, NamespaceImport, NamespaceMetadata, S3MethodName, S3Registration, diff --git a/crates/rd-rds/src/package/installed_code.rs b/crates/rd-rds/src/package/installed_code.rs new file mode 100644 index 0000000..787a4bc --- /dev/null +++ b/crates/rd-rds/src/package/installed_code.rs @@ -0,0 +1,811 @@ +//! Owned access to an installed package's `R/.rdx` and `R/.rdb`. +//! +//! This is a package-level view over [`crate::lazyload`]. The caller supplies +//! the installed package directory; this module does not search library paths +//! or inspect runtime exports. The completeness domain of [`InstalledCodeDb`] +//! is therefore the `variables` map in the code database index. + +use std::{ + fs, io, + path::{Path, PathBuf}, + time::UNIX_EPOCH, +}; + +use crate::{Limits, SexpKind, inspect}; + +use super::super::lazyload::{self, Compression, LazyLoadDb, Options as LazyLoadOptions}; + +/// Limits applied while opening and inspecting an installed code database. +#[derive(Debug, Clone, Copy)] +pub struct InstalledCodeOptions { + lazyload: LazyLoadOptions, + limits: Limits, + max_formals: usize, + max_bytes_visited: usize, +} + +impl Default for InstalledCodeOptions { + fn default() -> Self { + Self { + lazyload: LazyLoadOptions::default(), + limits: Limits::default(), + max_formals: 1_000_000, + max_bytes_visited: 256 * 1024 * 1024, + } + } +} + +impl InstalledCodeOptions { + /// Sets the maximum number of bytes read from the `.rdx` file. + #[must_use] + pub fn max_index_bytes(mut self, value: usize) -> Self { + self.lazyload = self.lazyload.max_index_bytes(value); + self + } + + /// Sets the maximum stored size of one `.rdb` record. + #[must_use] + pub fn max_stored_record_bytes(mut self, value: usize) -> Self { + self.lazyload = self.lazyload.max_stored_record_bytes(value); + self + } + + /// Sets the maximum decompressed size of one `.rdb` record. + #[must_use] + pub fn max_decompressed_record_bytes(mut self, value: usize) -> Self { + self.lazyload = self.lazyload.max_decompressed_record_bytes(value); + self + } + + /// Sets the limits shared by strict decoding and prefix inspection. + #[must_use] + pub fn limits(mut self, value: Limits) -> Self { + self.limits = value; + self + } + + /// Sets the maximum number of formals collected from one closure. + #[must_use] + pub fn max_formals(mut self, value: usize) -> Self { + self.max_formals = value; + self + } + + /// Sets the maximum number of record bytes visited by prefix inspection. + #[must_use] + pub fn max_bytes_visited(mut self, value: usize) -> Self { + self.max_bytes_visited = value; + self + } +} + +/// Errors opening or inspecting an installed code database. +#[derive(Debug, thiserror::Error)] +#[non_exhaustive] +pub enum InstalledCodeError { + /// The package has no `R/.rdx` code database. + #[error("installed package has no code database at {path}")] + NoCodeDatabase { path: PathBuf }, + /// The supplied path does not identify an installed package directory. + #[error("cannot determine package name from directory {path}")] + InvalidPackageDirectory { path: PathBuf }, + /// Opening the index or data file failed. + #[error("failed to open code database file at {path}: {source}")] + Open { + path: PathBuf, + #[source] + source: lazyload::Error, + }, + /// Reading or parsing the `.rdx` code database index failed. + #[error("failed to read code database index at {path}: {source}")] + Index { + path: PathBuf, + #[source] + source: lazyload::Error, + }, + /// The index changed while it was opened. + #[error("code database index changed while it was being read: {path}: {source}")] + IndexChanged { + path: PathBuf, + #[source] + source: lazyload::Error, + }, + /// A previously opened handle observed replacement of its data file. + #[error("code database changed while it was being read: {path}: {source}")] + DatabaseChanged { + path: PathBuf, + #[source] + source: lazyload::Error, + }, + /// The requested binding name does not occur in the index. + #[error("unknown stored binding {name:?}")] + UnknownStoredBinding { name: String }, + /// The requested binding name occurs more than once in the index. + #[error("stored binding {name:?} occurs {count} times")] + AmbiguousStoredBinding { name: String, count: usize }, + /// Reading a selected record failed; other index entries remain usable. + #[error("failed to read stored binding {name:?}: {source}")] + Record { + name: String, + #[source] + source: lazyload::Error, + }, + /// Inspection failed before the serialized root could be observed. + #[error("failed to inspect stored binding {name:?}: {failure}")] + Inspection { + name: String, + #[source] + failure: PrefixFailure, + }, +} + +/// An opaque best-effort identity for one opened code database generation. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct CodeDbGeneration { + index: FileIdentity, + data: FileIdentity, +} + +/// Provenance for an opened installed code database. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CodeDbProvenance { + package_dir: PathBuf, + package_name: String, + index_path: PathBuf, + data_path: PathBuf, + compression: Compression, + generation: CodeDbGeneration, +} + +impl CodeDbProvenance { + /// Returns the caller-supplied installed package directory. + #[must_use] + pub fn package_dir(&self) -> &Path { + &self.package_dir + } + + /// Returns the basename used to select the `R/.rdx` and `.rdb` files. + #[must_use] + pub fn package_name(&self) -> &str { + &self.package_name + } + + /// Returns the selected `.rdx` path. + #[must_use] + pub fn index_path(&self) -> &Path { + &self.index_path + } + + /// Returns the selected `.rdb` path. + #[must_use] + pub fn data_path(&self) -> &Path { + &self.data_path + } + + /// Returns the compression declared by the index. + #[must_use] + pub fn compression(&self) -> Compression { + self.compression + } + + /// Returns the opaque identity captured when the database was opened. + #[must_use] + pub fn generation(&self) -> CodeDbGeneration { + self.generation + } +} + +/// Public name for the observed serialized S-expression kind. +pub type StoredKind = SexpKind; + +/// One entry from the `.rdx` `variables` map, retained in index order. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct StoredBinding { + name: String, +} + +impl StoredBinding { + /// Returns the stored binding name. + #[must_use] + pub fn name(&self) -> &str { + &self.name + } +} + +/// The extent reached by a bounded record inspection. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub enum InspectionExtent { + RootTagOnly, + ThroughFormals { + body_offset: usize, + record_len: usize, + body_kind: StoredKind, + body_validation: BodyValidation, + }, +} + +impl InspectionExtent { + /// Returns the body tag offset when the closure prefix reached it. + #[must_use] + pub fn body_offset(&self) -> Option { + match self { + Self::ThroughFormals { body_offset, .. } => Some(*body_offset), + Self::RootTagOnly => None, + } + } + + /// Returns the observed body kind when the closure prefix reached it. + #[must_use] + pub fn body_kind(&self) -> Option { + match self { + Self::ThroughFormals { body_kind, .. } => Some(*body_kind), + Self::RootTagOnly => None, + } + } + + /// Returns the body validation status when the body tag was observed. + #[must_use] + pub fn body_validation(&self) -> Option { + match self { + Self::ThroughFormals { + body_validation, .. + } => Some(*body_validation), + Self::RootTagOnly => None, + } + } + + /// Returns the complete record length when available. + #[must_use] + pub fn record_len(&self) -> Option { + match self { + Self::ThroughFormals { record_len, .. } => Some(*record_len), + Self::RootTagOnly => None, + } + } +} + +/// Presence of a closure formal's default expression. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] +pub enum DefaultPresence { + Absent, + Present, +} + +/// One owned formal name and default-presence observation. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Formal { + name: String, + default: DefaultPresence, +} + +impl Formal { + /// Returns the formal name in serialized order. + #[must_use] + pub fn name(&self) -> &str { + &self.name + } + + /// Returns whether a default expression was serialized. + #[must_use] + pub fn default(&self) -> DefaultPresence { + self.default + } +} + +/// Owned closure formals in serialized order. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct FunctionFormals { + values: Vec, +} + +impl FunctionFormals { + /// Returns the owned formal slice. + #[must_use] + pub fn as_slice(&self) -> &[Formal] { + &self.values + } + + /// Returns the number of serialized formals. + #[must_use] + pub fn len(&self) -> usize { + self.values.len() + } + + /// Returns whether no formals were serialized. + #[must_use] + pub fn is_empty(&self) -> bool { + self.values.is_empty() + } + + /// Returns one formal by serialized position. + #[must_use] + pub fn get(&self, index: usize) -> Option<&Formal> { + self.values.get(index) + } + + /// Iterates over formals in serialized order. + pub fn iter(&self) -> impl Iterator { + self.values.iter() + } +} + +impl AsRef<[Formal]> for FunctionFormals { + fn as_ref(&self) -> &[Formal] { + self.as_slice() + } +} + +impl std::ops::Index for FunctionFormals { + type Output = Formal; + + fn index(&self, index: usize) -> &Self::Output { + &self.values[index] + } +} + +/// Closure-formal availability after bounded prefix inspection. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub enum FormalsInspection { + Available(FunctionFormals), + NotApplicable(FormalsNotApplicable), + Unavailable(FormalsUnavailable), +} + +/// Why a stored object has no closure formals. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] +pub enum FormalsNotApplicable { + BuiltIn, + Special, + NonClosure, +} + +/// Why closure formals are unavailable. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub enum FormalsUnavailable { + PromiseNotEvaluated, + PersistentReferenceUnresolved, + Prefix(PrefixFailure), +} + +/// A failure observed after (or while) reading a serialized prefix. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[error("{phase:?} failure at byte {offset}: {cause:?}")] +pub struct PrefixFailure { + phase: FailurePhase, + offset: usize, + cause: FailureCause, +} + +impl PrefixFailure { + /// Returns the logical phase in which inspection failed. + #[must_use] + pub fn phase(&self) -> FailurePhase { + self.phase + } + + /// Returns the serialized byte offset associated with the failure. + #[must_use] + pub fn offset(&self) -> usize { + self.offset + } + + /// Returns the failure cause. + #[must_use] + pub fn cause(&self) -> &FailureCause { + &self.cause + } +} + +/// Logical inspection phase. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] +pub enum FailurePhase { + Root, + Attributes, + Environment, + Formals, + Default(usize), + BodyTag, +} + +/// Cause of an inspection prefix failure. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub enum FailureCause { + Unsupported { type_code: u8, kind: StoredKind }, + Malformed, + ResourceLimit, +} + +/// Body bytes are intentionally not validated by prefix inspection. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] +pub enum BodyValidation { + NotValidated, +} + +/// Owned metadata observed from one selected stored record. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct StoredObjectInspection { + kind: StoredKind, + extent: InspectionExtent, + formals: FormalsInspection, +} + +impl StoredObjectInspection { + /// Returns the serialized root kind. + #[must_use] + pub fn kind(&self) -> StoredKind { + self.kind + } + + /// Returns how far inspection read the selected record. + #[must_use] + pub fn extent(&self) -> &InspectionExtent { + &self.extent + } + + /// Returns the closure formal observation. + #[must_use] + pub fn formals(&self) -> &FormalsInspection { + &self.formals + } +} + +/// An owned, package-level reader over the installed code database. +#[derive(Debug)] +pub struct InstalledCodeDb { + package_dir: PathBuf, + data_path: PathBuf, + lazyload: LazyLoadDb, + bindings: Vec, + provenance: CodeDbProvenance, + options: InstalledCodeOptions, +} + +impl InstalledCodeDb { + /// Opens `R/.rdx` and `R/.rdb` below `package_dir`. + pub fn open(package_dir: impl AsRef) -> Result { + Self::open_with_options(package_dir, InstalledCodeOptions::default()) + } + + /// Opens an installed code database with explicit bounds. + pub fn open_with_options( + package_dir: impl AsRef, + options: InstalledCodeOptions, + ) -> Result { + let package_dir = package_dir.as_ref().to_path_buf(); + let package = package_dir + .file_name() + .and_then(|name| name.to_str()) + .ok_or_else(|| InstalledCodeError::InvalidPackageDirectory { + path: package_dir.clone(), + })?; + let code_dir = package_dir.join("R"); + let index_path = code_dir.join(format!("{package}.rdx")); + let data_path = code_dir.join(format!("{package}.rdb")); + match fs::metadata(&index_path) { + Ok(_) => {} + Err(source) if source.kind() == io::ErrorKind::NotFound => { + return Err(InstalledCodeError::NoCodeDatabase { path: index_path }); + } + Err(source) => { + return Err(InstalledCodeError::Open { + path: index_path.clone(), + source: lazyload::Error::Io { + path: index_path, + source, + }, + }); + } + } + let index_before = file_identity(&index_path)?; + let data_before = file_identity(&data_path)?; + let lazyload = LazyLoadDb::open_with_options(&index_path, &data_path, options.lazyload) + .map_err(|error| map_open_error(error, &index_path))?; + let generation = CodeDbGeneration { + index: file_identity(&index_path)?, + data: file_identity(&data_path)?, + }; + if generation.index != index_before { + return Err(InstalledCodeError::IndexChanged { + path: index_path, + source: lazyload::Error::IndexChanged, + }); + } + if generation.data != data_before { + return Err(InstalledCodeError::DatabaseChanged { + path: data_path, + source: lazyload::Error::DataFileChanged, + }); + } + let compression = lazyload.compression(); + let bindings = lazyload + .variables() + .iter() + .map(|binding| StoredBinding { + name: binding.name().to_owned(), + }) + .collect(); + let provenance = CodeDbProvenance { + package_dir: package_dir.clone(), + package_name: package.to_owned(), + index_path: index_path.clone(), + data_path: data_path.clone(), + compression, + generation, + }; + Ok(Self { + package_dir, + data_path, + lazyload, + bindings, + provenance, + options, + }) + } + + /// Returns the caller-supplied installed package directory. + #[must_use] + pub fn package_dir(&self) -> &Path { + &self.package_dir + } + + /// Returns the selected `.rdx` path. + #[must_use] + pub fn index_path(&self) -> &Path { + &self.provenance.index_path + } + + /// Returns the selected `.rdb` path. + #[must_use] + pub fn data_path(&self) -> &Path { + &self.provenance.data_path + } + + /// Returns provenance captured at open time. + #[must_use] + pub fn provenance(&self) -> &CodeDbProvenance { + &self.provenance + } + + /// Returns the index-declared record compression. + #[must_use] + pub fn compression(&self) -> Compression { + self.lazyload.compression() + } + + /// Returns every `.rdx` variable in index order, including duplicate names. + #[must_use] + pub fn stored_bindings(&self) -> &[StoredBinding] { + &self.bindings + } + + /// Inspects one uniquely named stored binding without materializing it. + /// + /// Unknown and duplicate names are returned as structured errors. A + /// duplicate is never silently resolved with the low-level last-wins + /// policy. + pub fn inspect_stored_binding( + &self, + name: &str, + ) -> Result { + let mut matches = self + .bindings + .iter() + .filter(|binding| binding.name() == name); + let Some(_) = matches.next() else { + return Err(InstalledCodeError::UnknownStoredBinding { + name: name.to_owned(), + }); + }; + let count = 1 + matches.count(); + if count != 1 { + return Err(InstalledCodeError::AmbiguousStoredBinding { + name: name.to_owned(), + count, + }); + } + let record = self + .lazyload + .read(name) + .map_err(|error| map_record_error(error, name, &self.data_path))?; + let prefix = inspect::inspect_stored_object( + record.decompressed_bytes(), + inspect::InspectionOptions::default() + .limits(self.options.limits) + .max_formals(self.options.max_formals) + .max_bytes_visited(self.options.max_bytes_visited), + ) + .map_err(|failure| InstalledCodeError::Inspection { + name: name.to_owned(), + failure: map_prefix_failure(failure), + })?; + Ok(map_inspection(prefix)) + } +} + +fn map_inspection(value: inspect::PrefixInspection) -> StoredObjectInspection { + let formals = match value.formals { + inspect::FormalsInspection::Available(values) => { + FormalsInspection::Available(FunctionFormals { + values: values + .into_iter() + .map(|formal| Formal { + name: formal.name, + default: match formal.default { + inspect::DefaultPresence::Absent => DefaultPresence::Absent, + inspect::DefaultPresence::Present => DefaultPresence::Present, + }, + }) + .collect(), + }) + } + inspect::FormalsInspection::NotApplicable => match value.kind { + SexpKind::Promise => { + FormalsInspection::Unavailable(FormalsUnavailable::PromiseNotEvaluated) + } + SexpKind::Persist => { + FormalsInspection::Unavailable(FormalsUnavailable::PersistentReferenceUnresolved) + } + SexpKind::BuiltIn => FormalsInspection::NotApplicable(FormalsNotApplicable::BuiltIn), + SexpKind::Special => FormalsInspection::NotApplicable(FormalsNotApplicable::Special), + _ => FormalsInspection::NotApplicable(FormalsNotApplicable::NonClosure), + }, + inspect::FormalsInspection::Unavailable(failure) => { + FormalsInspection::Unavailable(FormalsUnavailable::Prefix(map_prefix_failure(failure))) + } + }; + StoredObjectInspection { + kind: value.kind, + extent: match value.extent { + inspect::InspectionExtent::RootTagOnly => InspectionExtent::RootTagOnly, + inspect::InspectionExtent::ThroughFormals { + body_offset, + record_len, + body_kind, + } => InspectionExtent::ThroughFormals { + body_offset, + record_len, + body_kind, + body_validation: BodyValidation::NotValidated, + }, + }, + formals, + } +} + +fn map_prefix_failure(value: inspect::PrefixFailure) -> PrefixFailure { + PrefixFailure { + phase: match value.phase { + inspect::FailurePhase::Root => FailurePhase::Root, + inspect::FailurePhase::Attributes => FailurePhase::Attributes, + inspect::FailurePhase::Environment => FailurePhase::Environment, + inspect::FailurePhase::Formals => FailurePhase::Formals, + inspect::FailurePhase::Default(index) => FailurePhase::Default(index), + inspect::FailurePhase::BodyTag => FailurePhase::BodyTag, + }, + offset: value.offset, + cause: match value.reason { + inspect::FailureReason::Unsupported { type_code, kind } => { + FailureCause::Unsupported { type_code, kind } + } + inspect::FailureReason::Malformed => FailureCause::Malformed, + inspect::FailureReason::ResourceLimit => FailureCause::ResourceLimit, + }, + } +} + +fn map_open_error(error: lazyload::Error, index_path: &Path) -> InstalledCodeError { + match error { + lazyload::Error::Io { path, source } => InstalledCodeError::Open { + path: path.clone(), + source: lazyload::Error::Io { path, source }, + }, + lazyload::Error::IndexChanged => InstalledCodeError::IndexChanged { + path: index_path.to_path_buf(), + source: lazyload::Error::IndexChanged, + }, + source => InstalledCodeError::Index { + path: index_path.to_path_buf(), + source, + }, + } +} + +fn map_record_error(error: lazyload::Error, name: &str, data_path: &Path) -> InstalledCodeError { + match error { + lazyload::Error::DataFileChanged => InstalledCodeError::DatabaseChanged { + path: data_path.to_path_buf(), + source: lazyload::Error::DataFileChanged, + }, + other => InstalledCodeError::Record { + name: name.to_owned(), + source: other, + }, + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +struct FileIdentity { + len: u64, + modified_nanos: Option, + #[cfg(unix)] + dev: u64, + #[cfg(unix)] + ino: u64, +} + +fn file_identity(path: &Path) -> Result { + let metadata = fs::metadata(path).map_err(|source| InstalledCodeError::Open { + path: path.to_path_buf(), + source: lazyload::Error::Io { + path: path.to_path_buf(), + source, + }, + })?; + let modified_nanos = metadata.modified().ok().and_then(|time| { + time.duration_since(UNIX_EPOCH) + .ok() + .map(|duration| duration.as_nanos()) + }); + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + Ok(FileIdentity { + len: metadata.len(), + modified_nanos, + dev: metadata.dev(), + ino: metadata.ino(), + }) + } + #[cfg(not(unix))] + { + Ok(FileIdentity { + len: metadata.len(), + modified_nanos, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn map_kind(kind: SexpKind) -> StoredObjectInspection { + map_inspection(inspect::PrefixInspection { + kind, + extent: inspect::InspectionExtent::RootTagOnly, + formals: inspect::FormalsInspection::NotApplicable, + }) + } + + #[test] + fn maps_non_closure_formal_reasons_without_inventing_failures() { + assert!(matches!( + map_kind(SexpKind::BuiltIn).formals(), + FormalsInspection::NotApplicable(FormalsNotApplicable::BuiltIn) + )); + assert!(matches!( + map_kind(SexpKind::Special).formals(), + FormalsInspection::NotApplicable(FormalsNotApplicable::Special) + )); + assert!(matches!( + map_kind(SexpKind::Integer).formals(), + FormalsInspection::NotApplicable(FormalsNotApplicable::NonClosure) + )); + assert!(matches!( + map_kind(SexpKind::Promise).formals(), + FormalsInspection::Unavailable(FormalsUnavailable::PromiseNotEvaluated) + )); + assert!(matches!( + map_kind(SexpKind::Persist).formals(), + FormalsInspection::Unavailable(FormalsUnavailable::PersistentReferenceUnresolved) + )); + } +} diff --git a/crates/rd-rds/tests/fixtures/data/lazyload/README.md b/crates/rd-rds/tests/fixtures/data/lazyload/README.md index d45ffcf..0e914fc 100644 --- a/crates/rd-rds/tests/fixtures/data/lazyload/README.md +++ b/crates/rd-rds/tests/fixtures/data/lazyload/README.md @@ -13,4 +13,6 @@ Rscript crates/rd-rds/tests/fixtures/generate_installed_lazyload_fixture.R \ The generated pair uses the normal installed-package profile: a gzip-enveloped `.rdx` index and a zlib `.rdb` record database. The smoke test opens the -committed pair directly and reads and parses a known binding. +committed pair directly and reads and parses a known binding. The generator +also writes `empty.rdx` and `empty.rdb`, a valid empty variables map used to +distinguish an empty database from a missing index. diff --git a/crates/rd-rds/tests/fixtures/data/lazyload/installed/empty.rdb b/crates/rd-rds/tests/fixtures/data/lazyload/installed/empty.rdb new file mode 100644 index 0000000..e69de29 diff --git a/crates/rd-rds/tests/fixtures/data/lazyload/installed/empty.rdx b/crates/rd-rds/tests/fixtures/data/lazyload/installed/empty.rdx new file mode 100644 index 0000000000000000000000000000000000000000..6ceeb200ca2c6cdef339c2cafa8fbf6ed91c2fcd GIT binary patch literal 169 zcmb2|=3oE==I#ec2?+^l35m%m32CfGk`d0%cS>|6BxbZ66yo7gn8kQ1oiQm+puMp% zP_ikp#vsG(QS%LMftqDn9TMCgeS#T6>L)hsIdbPpl7cfsj)ltvUDNevPMs2HO>a45 z?DlXbL*)O48QeJr63se^fA~$OORk!=S!bh$v7sh=hN4TuY7JA}ts18Kl8Te&%#RM3 V5*0IN7L$<(gZRS88?uZH3; PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("tests/fixtures/data/lazyload") + .join(name) +} + +fn installed_fixture() -> PathBuf { + static NEXT_FIXTURE: AtomicUsize = AtomicUsize::new(0); + let package_dir = std::env::temp_dir() + .join(format!( + "rd-rds-installed-code-{}-{}", + std::process::id(), + NEXT_FIXTURE.fetch_add(1, Ordering::Relaxed) + )) + .join("lazyfixture"); + let _ = fs::remove_dir_all(&package_dir); + fs::create_dir_all(package_dir.join("R")).unwrap(); + fs::copy( + fixture("installed/lazyfixture.rdx"), + package_dir.join("R/lazyfixture.rdx"), + ) + .unwrap(); + fs::copy( + fixture("installed/lazyfixture.rdb"), + package_dir.join("R/lazyfixture.rdb"), + ) + .unwrap(); + package_dir +} + +#[test] +fn opens_explicit_installed_shape_and_inspects_unique_bindings() { + let package_dir = installed_fixture(); + let db = InstalledCodeDb::open(&package_dir).unwrap(); + assert_eq!(db.package_dir(), package_dir); + assert_eq!(db.index_path(), package_dir.join("R/lazyfixture.rdx")); + assert_eq!(db.data_path(), package_dir.join("R/lazyfixture.rdb")); + assert_eq!(db.provenance().package_name(), "lazyfixture"); + assert_eq!(db.compression(), rd_rds::lazyload::Compression::Zlib); + assert!(!db.stored_bindings().is_empty()); + assert!( + db.stored_bindings() + .iter() + .any(|binding| binding.name() == "lazy_fixture_value") + ); + assert_eq!( + db.stored_bindings() + .iter() + .map(|binding| binding.name()) + .collect::>(), + [ + ".__NAMESPACE__.", + ".__S3MethodsTable__.", + ".packageName", + "lazy_fixture", + "lazy_fixture_value", + ] + ); + + let closure = db.inspect_stored_binding("lazy_fixture").unwrap(); + assert_eq!(closure.kind(), StoredKind::Closure); + let FormalsInspection::Available(formals) = closure.formals() else { + panic!("expected closure formals"); + }; + assert_eq!(formals.len(), 1); + assert_eq!(formals[0].name(), "value"); + assert!(matches!( + formals[0].default(), + rd_rds::package::DefaultPresence::Present + )); + assert!(matches!( + closure.extent(), + rd_rds::package::InspectionExtent::ThroughFormals { .. } + )); + assert_eq!( + closure.extent().body_validation(), + Some(rd_rds::package::BodyValidation::NotValidated) + ); + + let inspection = db.inspect_stored_binding("lazy_fixture_value").unwrap(); + assert_eq!(inspection.kind(), StoredKind::Integer); + assert!(matches!( + inspection.formals(), + FormalsInspection::NotApplicable(FormalsNotApplicable::NonClosure) + )); + assert!(inspection.extent().body_validation().is_none()); + + assert!(matches!( + db.inspect_stored_binding("missing"), + Err(rd_rds::package::InstalledCodeError::UnknownStoredBinding { name }) if name == "missing" + )); + let _ = fs::remove_dir_all(package_dir); +} + +#[test] +fn missing_index_is_distinct_from_missing_data_file() { + let package_dir = std::env::temp_dir() + .join(format!( + "rd-rds-installed-code-missing-{}", + std::process::id() + )) + .join("missing"); + let _ = fs::remove_dir_all(&package_dir); + fs::create_dir_all(package_dir.join("R")).unwrap(); + assert!(matches!( + InstalledCodeDb::open(&package_dir), + Err(rd_rds::package::InstalledCodeError::NoCodeDatabase { .. }) + )); + fs::copy( + fixture("installed/lazyfixture.rdx"), + package_dir.join("R/missing.rdx"), + ) + .unwrap(); + assert!(matches!( + InstalledCodeDb::open(&package_dir), + Err(rd_rds::package::InstalledCodeError::Open { .. }) + )); + let _ = fs::remove_dir_all(package_dir); +} + +#[test] +fn duplicate_names_are_reported_without_selecting_last_wins() { + let package_dir = std::env::temp_dir() + .join(format!( + "rd-rds-installed-code-duplicate-{}", + std::process::id() + )) + .join("zlib"); + let _ = fs::remove_dir_all(&package_dir); + fs::create_dir_all(package_dir.join("R")).unwrap(); + fs::copy(fixture("zlib.rdx"), package_dir.join("R/zlib.rdx")).unwrap(); + fs::copy(fixture("zlib.rdb"), package_dir.join("R/zlib.rdb")).unwrap(); + let db = InstalledCodeDb::open(&package_dir).unwrap(); + assert_eq!( + db.stored_bindings() + .iter() + .map(|binding| binding.name()) + .collect::>(), + ["duplicate", "other", "duplicate"] + ); + assert!(matches!( + db.inspect_stored_binding("duplicate"), + Err(rd_rds::package::InstalledCodeError::AmbiguousStoredBinding { count: 2, .. }) + )); + let _ = fs::remove_dir_all(package_dir); +} + +#[test] +fn replacement_is_reported_and_new_open_gets_a_new_generation() { + let package_dir = installed_fixture(); + let db = InstalledCodeDb::open(&package_dir).unwrap(); + let old_generation = db.provenance().generation(); + let data_path = package_dir.join("R/lazyfixture.rdb"); + let replacement = package_dir.join("R/replacement.rdb"); + fs::copy(fixture("installed/lazyfixture.rdb"), &replacement).unwrap(); + fs::remove_file(&data_path).unwrap(); + fs::rename(replacement, &data_path).unwrap(); + assert!(matches!( + db.inspect_stored_binding("lazy_fixture_value"), + Err(rd_rds::package::InstalledCodeError::DatabaseChanged { .. }) + )); + + let replacement_db = InstalledCodeDb::open(&package_dir).unwrap(); + assert_ne!(old_generation, replacement_db.provenance().generation()); + let _ = fs::remove_dir_all(package_dir); +} + +#[test] +fn inspection_and_container_limits_remain_structured() { + let package_dir = installed_fixture(); + let index_limited = InstalledCodeDb::open_with_options( + &package_dir, + InstalledCodeOptions::default().max_index_bytes(1), + ) + .unwrap_err(); + assert!(matches!( + index_limited, + rd_rds::package::InstalledCodeError::Index { + source: rd_rds::lazyload::Error::IndexSizeLimitExceeded { limit: 1 }, + .. + } + )); + + let limited = InstalledCodeDb::open_with_options( + &package_dir, + InstalledCodeOptions::default().max_formals(0), + ) + .unwrap(); + let inspection = limited.inspect_stored_binding("lazy_fixture").unwrap(); + assert!(matches!( + inspection.formals(), + FormalsInspection::Unavailable(FormalsUnavailable::Prefix(_)) + )); + + let byte_limited = InstalledCodeDb::open_with_options( + &package_dir, + InstalledCodeOptions::default().max_bytes_visited(2), + ) + .unwrap(); + assert!(matches!( + byte_limited.inspect_stored_binding("lazy_fixture"), + Err(rd_rds::package::InstalledCodeError::Inspection { .. }) + )); + + let record_limited = InstalledCodeDb::open_with_options( + &package_dir, + InstalledCodeOptions::default().max_decompressed_record_bytes(1), + ) + .unwrap(); + assert!(matches!( + record_limited.inspect_stored_binding("lazy_fixture_value"), + Err(rd_rds::package::InstalledCodeError::Record { .. }) + )); + let _ = fs::remove_dir_all(package_dir); +} + +#[test] +fn empty_variables_database_is_not_missing() { + let package_dir = std::env::temp_dir() + .join(format!( + "rd-rds-installed-code-empty-{}", + std::process::id() + )) + .join("empty"); + let _ = fs::remove_dir_all(&package_dir); + fs::create_dir_all(package_dir.join("R")).unwrap(); + fs::copy( + fixture("installed/empty.rdx"), + package_dir.join("R/empty.rdx"), + ) + .unwrap(); + fs::copy( + fixture("installed/empty.rdb"), + package_dir.join("R/empty.rdb"), + ) + .unwrap(); + let db = InstalledCodeDb::open(&package_dir).unwrap(); + assert!(db.stored_bindings().is_empty()); + assert!(matches!( + db.inspect_stored_binding("anything"), + Err(rd_rds::package::InstalledCodeError::UnknownStoredBinding { .. }) + )); + let _ = fs::remove_dir_all(package_dir); +} + +#[test] +fn one_bad_record_does_not_hide_other_records_or_the_index() { + let package_dir = installed_fixture(); + let data_path = package_dir.join("R/lazyfixture.rdb"); + let low_level = + rd_rds::lazyload::LazyLoadDb::open(package_dir.join("R/lazyfixture.rdx"), &data_path) + .unwrap(); + let bad_location = low_level + .variable("lazy_fixture_value") + .unwrap() + .location() + .unwrap(); + let mut data = fs::read(&data_path).unwrap(); + data[bad_location.offset() as usize] ^= 0xff; + fs::write(&data_path, data).unwrap(); + let db = InstalledCodeDb::open(&package_dir).unwrap(); + + assert!(matches!( + db.inspect_stored_binding("lazy_fixture_value"), + Err(rd_rds::package::InstalledCodeError::Record { .. }) + )); + assert_eq!(db.stored_bindings().len(), 5); + let closure = db.inspect_stored_binding("lazy_fixture").unwrap(); + assert_eq!(closure.kind(), StoredKind::Closure); + let _ = fs::remove_dir_all(package_dir); +} From ff5bc84833fe3935b39c9381f17f5a9a1b69ae50 Mon Sep 17 00:00:00 2001 From: eitsupi Date: Thu, 10 Sep 2026 13:45:15 +0000 Subject: [PATCH 2/4] docs(rd-rds): clarify installed code inspection bounds --- crates/rd-rds/README.md | 6 ++++++ crates/rd-rds/src/package/installed_code.rs | 13 +++++++++++-- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/crates/rd-rds/README.md b/crates/rd-rds/README.md index b515b32..4178e1f 100644 --- a/crates/rd-rds/README.md +++ b/crates/rd-rds/README.md @@ -39,6 +39,12 @@ bindings. [`InstalledCodeDb::inspect_stored_binding`] returns structured unknown/ambiguous errors instead of choosing among duplicate names, reads only a unique direct record, and returns bounded closure prefix metadata. Closure bodies are reported as `BodyValidation::NotValidated`. +The selected record is fully loaded, decompressed, and checked by the +`LazyLoadDb` container layer first; stored/decompressed size limits, framing, +compression, and trailing-stream corruption therefore fail before prefix +inspection. `InstalledCodeOptions::max_bytes_visited` applies only to the +semantic prefix walker, which stops before reading or validating a closure's +decompressed body payload. The provenance includes both selected paths, compression, and an opaque `CodeDbGeneration` derived from best-effort file metadata. It is an identity hint rather than a content hash or a transaction guarantee. diff --git a/crates/rd-rds/src/package/installed_code.rs b/crates/rd-rds/src/package/installed_code.rs index 787a4bc..28691a7 100644 --- a/crates/rd-rds/src/package/installed_code.rs +++ b/crates/rd-rds/src/package/installed_code.rs @@ -71,7 +71,13 @@ impl InstalledCodeOptions { self } - /// Sets the maximum number of record bytes visited by prefix inspection. + /// Sets the semantic prefix-walker byte limit. + /// + /// The selected record is first fully read and passed through + /// [`LazyLoadDb`]'s stored-size, decompressed-size, decompression, and + /// container/framing checks. This limit then bounds the prefix walker; + /// semantic payload bytes after the observed closure body tag are not + /// read or validated by inspection. #[must_use] pub fn max_bytes_visited(mut self, value: usize) -> Self { self.max_bytes_visited = value; @@ -590,7 +596,10 @@ impl InstalledCodeDb { /// /// Unknown and duplicate names are returned as structured errors. A /// duplicate is never silently resolved with the low-level last-wins - /// policy. + /// policy. Record loading and container validation happen before semantic + /// prefix inspection, so compressed-stream, framing, and trailing-byte + /// corruption is reported as an inspection error. For closures, the + /// semantic body payload itself is intentionally not read or validated. pub fn inspect_stored_binding( &self, name: &str, From 901bec3539346a642c92502354cd35218dc8b81b Mon Sep 17 00:00:00 2001 From: eitsupi Date: Thu, 10 Sep 2026 13:55:37 +0000 Subject: [PATCH 3/4] fix(rd-rds): detect Windows database replacement --- crates/rd-rds/README.md | 4 +++- crates/rd-rds/src/lazyload.rs | 15 +++++++++++++++ crates/rd-rds/src/package/installed_code.rs | 15 +++++++++++++++ 3 files changed, 33 insertions(+), 1 deletion(-) diff --git a/crates/rd-rds/README.md b/crates/rd-rds/README.md index 4178e1f..5624caf 100644 --- a/crates/rd-rds/README.md +++ b/crates/rd-rds/README.md @@ -58,7 +58,9 @@ record decoder to an already isolated `(offset, length)` byte slice. Record reads take a metadata snapshot when the database opens and compare it before and after each read. On Unix this includes device and inode, and on -other platforms it uses file length and modification time when available. +Windows it includes the creation/write times exposed by stable standard-library +metadata APIs; on other platforms it uses file length and modification time +when available. This is best-effort detection of replacement or concurrent modification and cannot provide a transaction guarantee against races after the final check. diff --git a/crates/rd-rds/src/lazyload.rs b/crates/rd-rds/src/lazyload.rs index 79ba252..dbcf73c 100644 --- a/crates/rd-rds/src/lazyload.rs +++ b/crates/rd-rds/src/lazyload.rs @@ -818,6 +818,10 @@ struct FileSnapshot { dev: u64, #[cfg(unix)] ino: u64, + #[cfg(windows)] + creation_time: u64, + #[cfg(windows)] + last_write_time: u64, } fn snapshot(path: &Path) -> Result { @@ -841,6 +845,17 @@ fn snapshot_metadata(metadata: &Metadata) -> FileSnapshot { } #[cfg(not(unix))] { + #[cfg(windows)] + { + use std::os::windows::fs::MetadataExt; + return FileSnapshot { + len: metadata.len(), + modified: metadata.modified().ok(), + creation_time: metadata.creation_time(), + last_write_time: metadata.last_write_time(), + }; + } + #[cfg(not(windows))] FileSnapshot { len: metadata.len(), modified: metadata.modified().ok(), diff --git a/crates/rd-rds/src/package/installed_code.rs b/crates/rd-rds/src/package/installed_code.rs index 28691a7..11fc58c 100644 --- a/crates/rd-rds/src/package/installed_code.rs +++ b/crates/rd-rds/src/package/installed_code.rs @@ -748,6 +748,10 @@ struct FileIdentity { dev: u64, #[cfg(unix)] ino: u64, + #[cfg(windows)] + creation_time: u64, + #[cfg(windows)] + last_write_time: u64, } fn file_identity(path: &Path) -> Result { @@ -775,6 +779,17 @@ fn file_identity(path: &Path) -> Result { } #[cfg(not(unix))] { + #[cfg(windows)] + { + use std::os::windows::fs::MetadataExt; + return Ok(FileIdentity { + len: metadata.len(), + modified_nanos, + creation_time: metadata.creation_time(), + last_write_time: metadata.last_write_time(), + }); + } + #[cfg(not(windows))] Ok(FileIdentity { len: metadata.len(), modified_nanos, From 90fa3710ed82f7d1fbebda82af5df3b20891b961 Mon Sep 17 00:00:00 2001 From: eitsupi Date: Thu, 10 Sep 2026 14:01:43 +0000 Subject: [PATCH 4/4] fix(rd-rds): align replacement checks with metadata identity --- crates/rd-rds/README.md | 7 ++--- crates/rd-rds/src/lazyload.rs | 23 +++------------- crates/rd-rds/src/package/installed_code.rs | 25 +++--------------- crates/rd-rds/tests/installed_code.rs | 29 ++++++++++++++++++++- 4 files changed, 39 insertions(+), 45 deletions(-) diff --git a/crates/rd-rds/README.md b/crates/rd-rds/README.md index 5624caf..272a0a3 100644 --- a/crates/rd-rds/README.md +++ b/crates/rd-rds/README.md @@ -58,11 +58,12 @@ record decoder to an already isolated `(offset, length)` byte slice. Record reads take a metadata snapshot when the database opens and compare it before and after each read. On Unix this includes device and inode, and on -Windows it includes the creation/write times exposed by stable standard-library -metadata APIs; on other platforms it uses file length and modification time -when available. +other platforms it uses file length and modification time when available. This is best-effort detection of replacement or concurrent modification and cannot provide a transaction guarantee against races after the final check. +Neither the generation nor replacement detection is a content hash or a +portable guarantee: a replacement that preserves all observed metadata may +not be distinguishable on every platform. The [`rd-helpdb`](../rd-helpdb/README.md) crate uses the file layer for standalone help-database RDS files, and [`rd-ast`](../rd-ast/README.md) can diff --git a/crates/rd-rds/src/lazyload.rs b/crates/rd-rds/src/lazyload.rs index dbcf73c..dec6af1 100644 --- a/crates/rd-rds/src/lazyload.rs +++ b/crates/rd-rds/src/lazyload.rs @@ -818,10 +818,6 @@ struct FileSnapshot { dev: u64, #[cfg(unix)] ino: u64, - #[cfg(windows)] - creation_time: u64, - #[cfg(windows)] - last_write_time: u64, } fn snapshot(path: &Path) -> Result { @@ -844,22 +840,9 @@ fn snapshot_metadata(metadata: &Metadata) -> FileSnapshot { } } #[cfg(not(unix))] - { - #[cfg(windows)] - { - use std::os::windows::fs::MetadataExt; - return FileSnapshot { - len: metadata.len(), - modified: metadata.modified().ok(), - creation_time: metadata.creation_time(), - last_write_time: metadata.last_write_time(), - }; - } - #[cfg(not(windows))] - FileSnapshot { - len: metadata.len(), - modified: metadata.modified().ok(), - } + FileSnapshot { + len: metadata.len(), + modified: metadata.modified().ok(), } } diff --git a/crates/rd-rds/src/package/installed_code.rs b/crates/rd-rds/src/package/installed_code.rs index 11fc58c..c8dce42 100644 --- a/crates/rd-rds/src/package/installed_code.rs +++ b/crates/rd-rds/src/package/installed_code.rs @@ -748,10 +748,6 @@ struct FileIdentity { dev: u64, #[cfg(unix)] ino: u64, - #[cfg(windows)] - creation_time: u64, - #[cfg(windows)] - last_write_time: u64, } fn file_identity(path: &Path) -> Result { @@ -778,23 +774,10 @@ fn file_identity(path: &Path) -> Result { }) } #[cfg(not(unix))] - { - #[cfg(windows)] - { - use std::os::windows::fs::MetadataExt; - return Ok(FileIdentity { - len: metadata.len(), - modified_nanos, - creation_time: metadata.creation_time(), - last_write_time: metadata.last_write_time(), - }); - } - #[cfg(not(windows))] - Ok(FileIdentity { - len: metadata.len(), - modified_nanos, - }) - } + Ok(FileIdentity { + len: metadata.len(), + modified_nanos, + }) } #[cfg(test)] diff --git a/crates/rd-rds/tests/installed_code.rs b/crates/rd-rds/tests/installed_code.rs index f16067e..591588c 100644 --- a/crates/rd-rds/tests/installed_code.rs +++ b/crates/rd-rds/tests/installed_code.rs @@ -159,7 +159,34 @@ fn duplicate_names_are_reported_without_selecting_last_wins() { } #[test] -fn replacement_is_reported_and_new_open_gets_a_new_generation() { +fn replacement_with_changed_metadata_is_reported_and_new_open_gets_a_new_generation() { + let package_dir = installed_fixture(); + let db = InstalledCodeDb::open(&package_dir).unwrap(); + let old_generation = db.provenance().generation(); + let data_path = package_dir.join("R/lazyfixture.rdb"); + let replacement = package_dir.join("R/replacement.rdb"); + fs::copy(fixture("installed/lazyfixture.rdb"), &replacement).unwrap(); + let mut replacement_file = fs::OpenOptions::new() + .append(true) + .open(&replacement) + .unwrap(); + std::io::Write::write_all(&mut replacement_file, &[0]).unwrap(); + drop(replacement_file); + fs::remove_file(&data_path).unwrap(); + fs::rename(replacement, &data_path).unwrap(); + assert!(matches!( + db.inspect_stored_binding("lazy_fixture_value"), + Err(rd_rds::package::InstalledCodeError::DatabaseChanged { .. }) + )); + + let replacement_db = InstalledCodeDb::open(&package_dir).unwrap(); + assert_ne!(old_generation, replacement_db.provenance().generation()); + let _ = fs::remove_dir_all(package_dir); +} + +#[cfg(unix)] +#[test] +fn unix_same_size_replacement_is_reported_by_device_and_inode() { let package_dir = installed_fixture(); let db = InstalledCodeDb::open(&package_dir).unwrap(); let old_generation = db.provenance().generation();