Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/).

### Fixed

- A copied import no longer reaches the file watcher as an external change,
so a background reclassification cannot race the import's own finalization.
Payload proof also ignores the brief staging sibling of an atomic
`metadata.json` replacement; any other unbound entry is still refused.
- A copied import finished before stable volume identities, such as a GGUF
reranker or audio model, can again be finished with "Verify and finish
import" after a reboot renumbers its drive. Its receipt recorded a raw
Expand Down
21 changes: 21 additions & 0 deletions rust/crates/pumas-core/src/metadata/atomic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,27 @@ impl DurablePublicationAdapter for PublicationSyncFault {

struct OsDurablePublicationAdapter;

/// Whether `name` is exactly a staging name the durable publisher creates
/// beside `target` (`<target>.<uuid>.<attempt>.tmp`). A concurrent atomic
/// replacement of `target` makes such a sibling briefly visible.
pub(crate) fn is_durable_staging_name(target: &str, name: &str) -> bool {
let Some(rest) = name
.strip_prefix(target)
.and_then(|rest| rest.strip_prefix('.'))
.and_then(|rest| rest.strip_suffix(".tmp"))
else {
return false;
};
let Some((uuid, attempt)) = rest.split_once('.') else {
return false;
};
uuid.len() == 36
&& Uuid::try_parse(uuid).is_ok()
&& !attempt.is_empty()
&& attempt.bytes().all(|byte| byte.is_ascii_digit())
&& attempt.parse::<u8>().is_ok()
}

impl DurablePublicationAdapter for OsDurablePublicationAdapter {
fn temp_name(&self, target: &OsStr, attempt: u8) -> OsString {
let mut name = target.to_os_string();
Expand Down
1 change: 1 addition & 0 deletions rust/crates/pumas-core/src/metadata/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
mod atomic;
mod manager;

pub(crate) use atomic::is_durable_staging_name;
pub use atomic::{atomic_read_json, atomic_write_json};
pub(crate) use atomic::{
AtomicJsonTarget, AtomicPublication, AtomicPublishFailure, AtomicPublishFailureKind,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,15 @@ impl DownloadRecoveryDestination {
}
}

/// Root control documents are not payload. Neither is the staging sibling a
/// concurrent atomic replacement of one of them briefly makes visible: it is
/// never bound, and its transient presence must not fail payload proof.
fn is_import_mutable_document_entry(name: &str) -> bool {
IMPORT_MUTABLE_DOCUMENTS.iter().any(|document| {
name == *document || crate::metadata::is_durable_staging_name(document, name)
})
}

fn observe_directory(
directory: &Dir,
relative: &Path,
Expand All @@ -417,7 +426,13 @@ fn observe_directory(
.to_str()
.ok_or_else(invalid_capability_path)?
.replace(std::path::MAIN_SEPARATOR, "/");
let metadata = directory.symlink_metadata(&name)?;
let root_document = relative.as_os_str().is_empty()
&& name.to_str().is_some_and(is_import_mutable_document_entry);
let metadata = match directory.symlink_metadata(&name) {
// A concurrent atomic replacement renamed its staging file away.
Err(error) if root_document && error.kind() == io::ErrorKind::NotFound => continue,
result => result?,
};
if metadata.is_symlink() {
return Err(invalid_capability_path().into());
}
Expand All @@ -434,11 +449,7 @@ fn observe_directory(
}),
);
} else if metadata.is_file() {
if relative.as_os_str().is_empty()
&& name
.to_str()
.is_some_and(|name| IMPORT_MUTABLE_DOCUMENTS.contains(&name))
{
if root_document {
continue;
}
let mut options = OpenOptions::new();
Expand Down Expand Up @@ -575,4 +586,45 @@ mod tests {
b"preserve"
);
}

#[test]
fn concurrent_document_staging_is_not_payload_but_other_entries_are() {
let temp = tempfile::tempdir().unwrap();
let root = DownloadDestinationRoot::open(temp.path()).unwrap();
let _grant = root.try_acquire_execution_grant().unwrap();
let stage = root.create_import_stage().unwrap();
stage
.create_import_file("weights")
.unwrap()
.write_all(b"weights")
.unwrap();
let proof = stage.capture_import_payload(&["weights".into()]).unwrap();
let directory = stage.display_path().to_path_buf();
// An atomic replacement of a root document stages beside it.
let staging = format!("metadata.json.{}.0.tmp", uuid::Uuid::new_v4());
assert!(crate::metadata::is_durable_staging_name(
"metadata.json",
&staging
));
std::fs::write(directory.join(&staging), b"{}").unwrap();
stage.verify_import_bindings(&proof).unwrap();
std::fs::remove_file(directory.join(&staging)).unwrap();
// Lookalikes, staging names of payload files, out-of-range attempts and
// staging-named directories are unbound entries that refuse the proof.
for name in [
"metadata.json.unbound.0.tmp".to_string(),
format!("weights.{}.0.tmp", uuid::Uuid::new_v4()),
format!("metadata.json.{}.256.tmp", uuid::Uuid::new_v4()),
] {
std::fs::write(directory.join(&name), b"x").unwrap();
assert!(stage.verify_import_bindings(&proof).is_err(), "{name}");
std::fs::remove_file(directory.join(&name)).unwrap();
}
let staged_directory = directory.join(&staging);
std::fs::create_dir(&staged_directory).unwrap();
assert!(stage.verify_import_bindings(&proof).is_err());
std::fs::remove_dir(&staged_directory).unwrap();
stage.verify_import_bindings(&proof).unwrap();
stage.remove_import_stage_all().unwrap();
}
}
5 changes: 5 additions & 0 deletions rust/crates/pumas-core/src/model_library/importer/staging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -484,6 +484,11 @@ impl ModelImporter {
if let Err(error) = self.import_boundary(ImportBoundary::DescendantsReleased, &stage) {
return settle_released(&publication, &stage, error, spec, security_tier);
}
// Publication indexes the model itself below. Like other owned moves,
// its destination must not reach the watcher as an external change,
// or reconciliation reclassifies the model concurrently with the
// importer's own finalization and its callers' first observations.
self.library.notify_owned_move_destination(&target_path);
let publication_outcome = match stage.publish_model_directory_noreplace(&target) {
Err(error) => return settle_released(&publication, &stage, error, spec, security_tier),
Ok(outcome) => outcome,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1072,8 +1072,8 @@ async fn copied_import_metadata_notifier_observes_write_paths_without_authorizin
let paths = notifications.lock().unwrap().clone();
assert_eq!(
paths.len(),
2,
"Pending and Ready metadata writes both notify"
3,
"Pending metadata, the owned publication destination and Ready metadata notify"
);
assert_eq!(paths[0].file_name().unwrap(), "metadata.json");
assert!(paths[0]
Expand All @@ -1087,7 +1087,10 @@ async fn copied_import_metadata_notifier_observes_write_paths_without_authorizin
!paths[0].exists(),
"notification is the former stage path, not retained filesystem authority"
);
// Publication is an owned move: its destination is announced before the
// rename so the watcher never mistakes it for an external change.
assert_eq!(paths[1], fixture.target().join("metadata.json"));
assert_eq!(paths[2], fixture.target().join("metadata.json"));
assert!(fixture.target().join("metadata.json").is_file());
fixture.tasks.shutdown_owned().await.unwrap();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -416,15 +416,17 @@ async fn copied_import_final_metadata_notifier_keeps_checksum_as_historical_evid
fixture
.library
.set_metadata_write_notifier(Some(Arc::new(move |path| {
if observed.fetch_add(1, Ordering::SeqCst) == 1 {
// Call 1 announces the publication destination before its rename;
// call 2 is the final metadata write in the published directory.
if observed.fetch_add(1, Ordering::SeqCst) == 2 {
let weights = path.parent().unwrap().join("model.onnx");
let bytes = std::fs::read(&weights).unwrap();
std::fs::write(weights, vec![b'x'; bytes.len()]).unwrap();
}
})));
let result = fixture.importer.import(&fixture.spec).await.unwrap();
assert!(result.success);
assert_eq!(calls.load(Ordering::SeqCst), 2);
assert_eq!(calls.load(Ordering::SeqCst), 3);
assert_eq!(receipt_at(&fixture.target())["state"], "confirmed");
let metadata = fixture
.library
Expand Down
Loading