diff --git a/Cargo.lock b/Cargo.lock index ed5486be6a..ab0417b79b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -93,8 +93,8 @@ dependencies = [ "accesskit_consumer", "hashbrown 0.17.1", "static_assertions", - "windows 0.62.2", - "windows-core 0.62.2", + "windows", + "windows-core", ] [[package]] @@ -1021,7 +1021,7 @@ dependencies = [ "num-traits", "serde", "wasm-bindgen", - "windows-link 0.2.1", + "windows-link", ] [[package]] @@ -2372,8 +2372,8 @@ dependencies = [ "read-fonts", "roxmltree 0.21.1", "smallvec", - "windows 0.62.2", - "windows-core 0.62.2", + "windows", + "windows-core", "yeslogic-fontconfig-sys", ] @@ -2572,7 +2572,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" dependencies = [ "rustix 1.1.5", - "windows-link 0.2.1", + "windows-link", ] [[package]] @@ -2774,7 +2774,7 @@ dependencies = [ "log", "presser", "thiserror 2.0.21", - "windows 0.62.2", + "windows", ] [[package]] @@ -2998,7 +2998,7 @@ dependencies = [ "js-sys", "log", "wasm-bindgen", - "windows-core 0.62.2", + "windows-core", ] [[package]] @@ -3402,7 +3402,7 @@ dependencies = [ "simd_cesu8", "thiserror 2.0.21", "walkdir", - "windows-link 0.2.1", + "windows-link", ] [[package]] @@ -3752,7 +3752,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" dependencies = [ "cfg-if", - "windows-link 0.2.1", + "windows-link", ] [[package]] @@ -4841,7 +4841,7 @@ dependencies = [ "libc", "redox_syscall 0.5.18", "smallvec", - "windows-link 0.2.1", + "windows-link", ] [[package]] @@ -5082,6 +5082,7 @@ dependencies = [ "photocraft-format", "photocraft-geom", "photocraft-io", + "photocraft-psd", "photocraft-raster", "photocraft-raw", "rmcp", @@ -5380,6 +5381,7 @@ dependencies = [ "rayon", "serde", "sysinfo", + "winsafe", ] [[package]] @@ -7381,16 +7383,16 @@ dependencies = [ [[package]] name = "sysinfo" -version = "0.37.2" +version = "0.40.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16607d5caffd1c07ce073528f9ed972d88db15dd44023fa57142963be3feb11f" +checksum = "0e8a3edbe0394ce115f3917a00349dd242be09eb5a091ed509eaf67b55cfb8a8" dependencies = [ "libc", "memchr", "ntapi", "objc2-core-foundation", "objc2-io-kit", - "windows 0.61.3", + "windows", ] [[package]] @@ -8664,9 +8666,9 @@ dependencies = [ "web-sys", "wgpu-naga-bridge", "wgpu-types", - "windows 0.62.2", - "windows-core 0.62.2", - "windows-result 0.4.1", + "windows", + "windows-core", + "windows-result", ] [[package]] @@ -8732,38 +8734,16 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" -[[package]] -name = "windows" -version = "0.61.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893" -dependencies = [ - "windows-collections 0.2.0", - "windows-core 0.61.2", - "windows-future 0.2.1", - "windows-link 0.1.3", - "windows-numerics 0.2.0", -] - [[package]] name = "windows" version = "0.62.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" dependencies = [ - "windows-collections 0.3.2", - "windows-core 0.62.2", - "windows-future 0.3.2", - "windows-numerics 0.3.1", -] - -[[package]] -name = "windows-collections" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3beeceb5e5cfd9eb1d76b381630e82c4241ccd0d27f1a39ed41b2760b255c5e8" -dependencies = [ - "windows-core 0.61.2", + "windows-collections", + "windows-core", + "windows-future", + "windows-numerics", ] [[package]] @@ -8772,20 +8752,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" dependencies = [ - "windows-core 0.62.2", -] - -[[package]] -name = "windows-core" -version = "0.61.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3" -dependencies = [ - "windows-implement", - "windows-interface", - "windows-link 0.1.3", - "windows-result 0.3.4", - "windows-strings 0.4.2", + "windows-core", ] [[package]] @@ -8796,20 +8763,9 @@ checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" dependencies = [ "windows-implement", "windows-interface", - "windows-link 0.2.1", - "windows-result 0.4.1", - "windows-strings 0.5.1", -] - -[[package]] -name = "windows-future" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e" -dependencies = [ - "windows-core 0.61.2", - "windows-link 0.1.3", - "windows-threading 0.1.0", + "windows-link", + "windows-result", + "windows-strings", ] [[package]] @@ -8818,9 +8774,9 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" dependencies = [ - "windows-core 0.62.2", - "windows-link 0.2.1", - "windows-threading 0.2.1", + "windows-core", + "windows-link", + "windows-threading", ] [[package]] @@ -8845,36 +8801,20 @@ dependencies = [ "syn 2.0.119", ] -[[package]] -name = "windows-link" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a" - [[package]] name = "windows-link" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" -[[package]] -name = "windows-numerics" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9150af68066c4c5c07ddc0ce30421554771e528bde427614c61038bc2c92c2b1" -dependencies = [ - "windows-core 0.61.2", - "windows-link 0.1.3", -] - [[package]] name = "windows-numerics" version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" dependencies = [ - "windows-core 0.62.2", - "windows-link 0.2.1", + "windows-core", + "windows-link", ] [[package]] @@ -8883,18 +8823,9 @@ version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" dependencies = [ - "windows-link 0.2.1", - "windows-result 0.4.1", - "windows-strings 0.5.1", -] - -[[package]] -name = "windows-result" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56f42bd332cc6c8eac5af113fc0c1fd6a8fd2aa08a0119358686e5160d0586c6" -dependencies = [ - "windows-link 0.1.3", + "windows-link", + "windows-result", + "windows-strings", ] [[package]] @@ -8903,16 +8834,7 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" dependencies = [ - "windows-link 0.2.1", -] - -[[package]] -name = "windows-strings" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56e6c93f3a0c3b36176cb1327a4958a0353d5d166c2a35cb268ace15e91d3b57" -dependencies = [ - "windows-link 0.1.3", + "windows-link", ] [[package]] @@ -8921,7 +8843,7 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" dependencies = [ - "windows-link 0.2.1", + "windows-link", ] [[package]] @@ -8948,7 +8870,7 @@ version = "0.61.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" dependencies = [ - "windows-link 0.2.1", + "windows-link", ] [[package]] @@ -8967,22 +8889,13 @@ dependencies = [ "windows_x86_64_msvc", ] -[[package]] -name = "windows-threading" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b66463ad2e0ea3bbf808b7f1d371311c80e115c0b71d60efc142cafbcfb057a6" -dependencies = [ - "windows-link 0.1.3", -] - [[package]] name = "windows-threading" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" dependencies = [ - "windows-link 0.2.1", + "windows-link", ] [[package]] @@ -9108,8 +9021,8 @@ dependencies = [ "strum", "tar", "thiserror 2.0.21", - "windows 0.62.2", - "windows-core 0.62.2", + "windows", + "windows-core", "windows-implement", "xml", ] @@ -9282,7 +9195,7 @@ dependencies = [ "thiserror 2.0.21", "url", "widestring", - "windows 0.62.2", + "windows", "xcb", "zbus", ] diff --git a/apps/photocraft-cli/src/args.rs b/apps/photocraft-cli/src/args.rs index 8c7b708b7d..33175a15be 100644 --- a/apps/photocraft-cli/src/args.rs +++ b/apps/photocraft-cli/src/args.rs @@ -95,6 +95,9 @@ pub(crate) struct ConvertArgs { /// Allow an that is the file, replacing the original #[arg(long)] pub(crate) in_place: bool, + /// Explicitly approve high-memory PSD/PSB imports within the hard memory budget + #[arg(long)] + pub(crate) approve_high_memory: bool, #[command(flatten)] pub(crate) export: ExportArgs, } @@ -106,6 +109,9 @@ pub(crate) struct InfoArgs { /// One line of JSON instead of pretty-printed #[arg(long)] pub(crate) compact: bool, + /// Explicitly approve high-memory PSD/PSB imports within the hard memory budget + #[arg(long)] + pub(crate) approve_high_memory: bool, } /// Open a file (or start a new document), run engine commands in order, save the result @@ -134,6 +140,9 @@ pub(crate) struct RunArgs { /// Allow an --out that is the , replacing the original #[arg(long)] pub(crate) in_place: bool, + /// Explicitly approve high-memory PSD/PSB imports within the hard memory budget + #[arg(long)] + pub(crate) approve_high_memory: bool, #[command(flatten)] pub(crate) export: ExportArgs, /// `--cmd` and `--params` values in command-line order, set by [`parse`]. @@ -173,6 +182,9 @@ pub(crate) struct BatchArgs { /// originals; --in-place allows it #[arg(long)] pub(crate) in_place: bool, + /// Explicitly approve high-memory PSD/PSB imports within the hard memory budget + #[arg(long)] + pub(crate) approve_high_memory: bool, #[command(flatten)] pub(crate) export: ExportArgs, } diff --git a/apps/photocraft-cli/src/batch.rs b/apps/photocraft-cli/src/batch.rs index 02bb1bb702..a9f85fddb1 100644 --- a/apps/photocraft-cli/src/batch.rs +++ b/apps/photocraft-cli/src/batch.rs @@ -81,7 +81,7 @@ pub(crate) fn batch(a: &BatchArgs, out: &mut dyn Write, err: &mut dyn Write) -> // Steps that play another action find it in the set; the session's playback stack // stops an action that calls itself. h.session.actions.list = set.clone(); - h.open(input)?; + h.open_with_approval(input, a.approve_high_memory)?; for (id, p) in &actions { if photocraft_engine::actions_cmds::shell_view_command(id) || photocraft_engine::actions_cmds::shell_save_command(id) diff --git a/apps/photocraft-cli/src/document.rs b/apps/photocraft-cli/src/document.rs index 95d4c28288..4c6678bfb1 100644 --- a/apps/photocraft-cli/src/document.rs +++ b/apps/photocraft-cli/src/document.rs @@ -30,7 +30,8 @@ pub(crate) fn convert(a: &ConvertArgs, _out: &mut dyn Write, err: &mut dyn Write let (input, output) = (&a.input, &a.output); let opts = ExportOptions::from(&a.export); refuse_overwriting_input(a.in_place, input, output)?; - let mut o = files::open(input)?; + let import_opts = photocraft_io::ImportOptions { psd_high_memory_approved: a.approve_high_memory, ..Default::default() }; + let mut o = files::open_with_options(input, &import_opts)?; // Preferences › Raw Defaults › Resolution at its default, as `run` and `info` open a raw. photocraft_engine::file_cmds::raw_defaults(&photocraft_engine::Session::new(), &o.warnings, &mut o.document); warn_all(err, &o.warnings); @@ -43,7 +44,7 @@ pub(crate) fn convert(a: &ConvertArgs, _out: &mut dyn Write, err: &mut dyn Write pub(crate) fn info(a: &InfoArgs, out: &mut dyn Write) -> Result { let file = &a.file; let mut h = Headless::trusted_local(); - let opened = h.open(file)?; + let opened = h.open_with_approval(file, a.approve_high_memory)?; let mut doc = h.inspect(None)?; let mut warnings = opened["warnings"].as_array().cloned().unwrap_or_default(); if let Some(st) = h.session.active() { @@ -86,7 +87,7 @@ pub(crate) fn run_cmds(a: &RunArgs, out: &mut dyn Write, err: &mut dyn Write) -> if let Some(out) = &a.out { refuse_overwriting_input(a.in_place, file, out)?; } - let o = h.open(file)?; + let o = h.open_with_approval(file, a.approve_high_memory)?; let ws: Vec = serde_json::from_value(o["warnings"].clone()).unwrap_or_default(); warn_all(err, &ws); reported_fonts.extend(ws); diff --git a/crates/automation/Cargo.toml b/crates/automation/Cargo.toml index e72b38f760..320a1f50f4 100644 --- a/crates/automation/Cargo.toml +++ b/crates/automation/Cargo.toml @@ -32,6 +32,10 @@ clap = { workspace = true } photocraft-geom = { workspace = true } # Synthetic camera raws (#7789). photocraft-raw = { workspace = true, features = ["testgen"] } +# Tiny generated PSDs and the scoped estimate charge for the high-memory approval tests +# (no multi-gigabyte fixture or global override). +photocraft-io = { workspace = true, features = ["testgen"] } +photocraft-psd = { workspace = true, features = ["testgen"] } rmcp = { version = "3.5", default-features = false, features = ["client", "server", "macros", "transport-io"] } tokio = { version = "1", features = ["rt-multi-thread", "macros", "io-std", "sync", "net", "io-util", "time"] } diff --git a/crates/automation/src/files.rs b/crates/automation/src/files.rs index fddd15ca96..0ecc057c59 100644 --- a/crates/automation/src/files.rs +++ b/crates/automation/src/files.rs @@ -18,17 +18,27 @@ pub struct Opened { /// Decode a document that was read through a filesystem capability. pub fn open_bytes(name: &str, bytes: &[u8]) -> Result { + open_bytes_with_options(name, bytes, &photocraft_io::ImportOptions::default()) +} + +/// Decode a document that was read through a filesystem capability with custom import options. +pub fn open_bytes_with_options(name: &str, bytes: &[u8], opts: &photocraft_io::ImportOptions) -> Result { if Path::new(name).extension().is_some_and(|extension| extension.eq_ignore_ascii_case(photocraft_format::EXTENSION)) { let document = photocraft_format::load_from_bytes(bytes)?; return Ok(Opened { warnings: photocraft_io::open_warnings(&document), document, source_read_only: false }); } - let r = photocraft_io::import(name, bytes)?; + let r = photocraft_io::import_with_options(name, bytes, opts)?; Ok(Opened { document: r.document, warnings: r.warnings, source_read_only: r.source_read_only }) } /// Open a document from disk. Directory bundles and `.pcraft` ZIPs load /// natively; everything else goes through `photocraft-io` (PSD, PNG, …). pub fn open(path: &Path) -> Result { + open_with_options(path, &photocraft_io::ImportOptions::default()) +} + +/// Open a document from disk with custom import options. +pub fn open_with_options(path: &Path, opts: &photocraft_io::ImportOptions) -> Result { if path.is_dir() { let document = photocraft_format::load_path(path)?; return Ok(Opened { warnings: photocraft_io::open_warnings(&document), document, source_read_only: false }); @@ -38,17 +48,16 @@ pub fn open(path: &Path) -> Result { // convert or info of a 2 GB file does not hold the file in memory next to the document. #[cfg(any(unix, windows))] { - let r = - photocraft_io::import_file(&name, path, &photocraft_io::ImportOptions::default(), &photocraft_raster::Interrupt::NONE).map_err(|e| match e { - photocraft_io::IoError::Read(msg) => AutomationError::Io(msg), - e => e.into(), - })?; + let r = photocraft_io::import_file(&name, path, opts, &photocraft_raster::Interrupt::NONE).map_err(|e| match e { + photocraft_io::IoError::Read(msg) => AutomationError::Io(msg), + e => e.into(), + })?; Ok(Opened { document: r.document, warnings: r.warnings, source_read_only: r.source_read_only }) } #[cfg(not(any(unix, windows)))] { let bytes = photocraft_format::read_file(path).map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))?; - open_bytes(&name, &bytes) + open_bytes_with_options(&name, &bytes, opts) } } diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs index 8b08daa6aa..e623e69f2c 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -90,14 +90,25 @@ impl Headless { /// Open a file and make it the active document. pub fn open(&mut self, path: &Path) -> Result { + self.open_with_approval(path, false) + } + + /// Open a file with optional high-memory approval and make it the active document. + pub fn open_with_approval(&mut self, path: &Path, approve_high_memory: bool) -> Result { + let opts = photocraft_io::ImportOptions { psd_high_memory_approved: approve_high_memory, ..Default::default() }; + self.open_with_options(path, &opts) + } + + /// Open a file with custom import options and make it the active document. + pub fn open_with_options(&mut self, path: &Path, opts: &photocraft_io::ImportOptions) -> Result { let requested = path.to_str().ok_or_else(|| AutomationError::BadRequest("automation paths must be valid UTF-8".into()))?; let mut o = match &self.filesystem { Filesystem::Denied => return Err(AutomationError::BadRequest("automation filesystem access is not granted: read authority is absent".into())), - Filesystem::TrustedLocal => files::open(path)?, + Filesystem::TrustedLocal => files::open_with_options(path, opts)?, Filesystem::Workspace(workspace) => { let bytes = workspace.read(requested)?; let name = path.file_name().and_then(|name| name.to_str()).unwrap_or(requested); - files::open_bytes(name, &bytes)? + files::open_bytes_with_options(name, &bytes, opts)? } }; // Preferences › Raw Defaults › Resolution, as the app's File › Open applies it. @@ -129,7 +140,8 @@ impl Headless { /// Place a file into a document as a Smart Object layer: the capability-scoped counterpart /// of `file.placeEmbedded`, which reads an ambient path and is therefore refused in /// automation (#2810). `path` resolves beneath the read root the way `open` resolves one, - /// and `params` carries the command's own options (`scale`, `fit`, `center`). + /// and `params` carries the command's own options (`scale`, `fit`, `center`, + /// `approveHighMemory`). pub fn place(&mut self, index: Option, path: &str, params: &Value) -> Result { self.on_doc(index, |this| { let mut opts = params.as_object().cloned().unwrap_or_default(); diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs index 7ccf168055..c7576e08c4 100644 --- a/crates/automation/src/rpc.rs +++ b/crates/automation/src/rpc.rs @@ -61,6 +61,36 @@ pub const METHODS: &[&str] = &[ "methods", ]; +/// Adds the structured memory fields (`required`, soft and hard limits and measured capacity) +/// from a typed admission error to a JSON error object, so clients can offer approval. +fn attach_memory_error_details(obj: &mut Value, err: &AutomationError) { + match err { + AutomationError::Import(photocraft_io::IoError::PsdApprovalRequired { required, soft_limit, hard_limit, available_ram }) + | AutomationError::Engine(photocraft_engine::EngineError::PsdApprovalRequired { required, soft_limit, hard_limit, available_ram, .. }) => { + if let Some(m) = obj.as_object_mut() { + m.insert("required".into(), json!(required)); + m.insert("soft".into(), json!(soft_limit)); + m.insert("softLimit".into(), json!(soft_limit)); + m.insert("hard".into(), json!(hard_limit)); + m.insert("hardLimit".into(), json!(hard_limit)); + if let Some(avail) = available_ram { + m.insert("available".into(), json!(avail)); + m.insert("availableRam".into(), json!(avail)); + } + } + } + AutomationError::Import(photocraft_io::IoError::PsdImportBudget { required, limit }) + | AutomationError::Engine(photocraft_engine::EngineError::PsdHardBudget { required, limit, .. }) => { + if let Some(m) = obj.as_object_mut() { + m.insert("required".into(), json!(required)); + m.insert("hard".into(), json!(limit)); + m.insert("hardLimit".into(), json!(limit)); + } + } + _ => {} + } +} + fn bad(msg: impl Into) -> AutomationError { AutomationError::BadRequest(msg.into()) } @@ -107,10 +137,18 @@ impl Headless { "session.list" => Ok(self.session_list()), "doc.open" => { let path = str_of(&p, "path").ok_or_else(|| bad("doc.open needs `path`"))?; - self.open(&PathBuf::from(path)) + let approve = match p.get("approveHighMemory") { + None | Some(Value::Null) => false, + Some(Value::Bool(b)) => *b, + Some(_) => return Err(bad("`approveHighMemory` must be a boolean")), + }; + self.open_with_approval(&PathBuf::from(path), approve) } "doc.place" => { let path = str_of(&p, "path").ok_or_else(|| bad("doc.place needs `path`"))?; + if p.get("approveHighMemory").is_some_and(|v| !v.is_boolean()) { + return Err(bad("`approveHighMemory` must be a boolean")); + } let mut opts = p.as_object().cloned().unwrap_or_default(); opts.remove("path"); opts.remove("index"); @@ -230,7 +268,11 @@ impl Headless { let was_error = r.is_err(); let result = match r { Ok(v) => json!({"ok": true, "result": v}), - Err(e) => json!({"ok": false, "error": e.to_string()}), + Err(e) => { + let mut obj = json!({"ok": false, "error": e.to_string()}); + attach_memory_error_details(&mut obj, &e); + obj + } }; if let Err(error) = reply_budget.charge(&result) { failed += 1; @@ -268,7 +310,11 @@ pub fn respond(h: &Mutex, line: &str) -> Value { .unwrap_or_else(|_| Err(AutomationError::Other(format!("internal error: `{method}` panicked")))); match r { Ok(v) => json!({"id": id, "ok": true, "result": v}), - Err(e) => json!({"id": id, "ok": false, "error": e.to_string()}), + Err(e) => { + let mut obj = json!({"id": id, "ok": false, "error": e.to_string()}); + attach_memory_error_details(&mut obj, &e); + obj + } } } diff --git a/crates/automation/src/rpc/tests.rs b/crates/automation/src/rpc/tests.rs index 131df72413..0a20075267 100644 --- a/crates/automation/src/rpc/tests.rs +++ b/crates/automation/src/rpc/tests.rs @@ -1028,3 +1028,88 @@ fn invalid_document_index_is_rejected_not_the_active_document() { assert_eq!(reply["ok"], true, "{reply}"); assert_eq!(count(&h), 1); } + +#[test] +fn approve_high_memory_rejects_invalid_types_and_formats_structured_error() { + let h = session(); + // Non-boolean approveHighMemory is rejected strictly + let reply = respond(&h, r#"{"method":"doc.open","params":{"path":"test.psd","approveHighMemory":"yes"}}"#); + assert_eq!(reply["ok"], false); + assert!(reply["error"].as_str().unwrap().contains("must be a boolean")); + + let reply_place = respond(&h, r#"{"method":"doc.place","params":{"path":"test.psd","approveHighMemory":123}}"#); + assert_eq!(reply_place["ok"], false); + assert!(reply_place["error"].as_str().unwrap().contains("must be a boolean")); + + // Verify attach_memory_error_details adds machine-readable fields + let mut err_obj = json!({"id": 1, "ok": false, "error": "test"}); + let auto_err = crate::AutomationError::Import(photocraft_io::IoError::PsdApprovalRequired { + required: 5000, + soft_limit: 2000, + hard_limit: 8000, + available_ram: Some(10000), + }); + super::attach_memory_error_details(&mut err_obj, &auto_err); + assert_eq!(err_obj["required"], 5000); + assert_eq!(err_obj["soft"], 2000); + assert_eq!(err_obj["softLimit"], 2000); + assert_eq!(err_obj["hard"], 8000); + assert_eq!(err_obj["hardLimit"], 8000); + assert_eq!(err_obj["available"], 10000); + assert_eq!(err_obj["availableRam"], 10000); + + // An engine-command hard refusal (Open As / Place go through `EngineError`) keeps its typed + // fields, and only the fields an approval request has: no soft limit and no capacity, since + // no approval can raise the ceiling. + let mut hard_obj = json!({"id": 2, "ok": false, "error": "test"}); + let hard = crate::AutomationError::Engine(photocraft_engine::EngineError::PsdHardBudget { name: "big.psd".into(), required: 9000, limit: 8000 }); + super::attach_memory_error_details(&mut hard_obj, &hard); + assert_eq!(hard_obj["required"], 9000); + assert_eq!(hard_obj["hard"], 8000); + assert_eq!(hard_obj["hardLimit"], 8000); + for absent in ["soft", "softLimit", "available", "availableRam"] { + assert!(hard_obj.get(absent).is_none(), "a hard refusal has no {absent}: {hard_obj}"); + } +} + +/// #10897: `doc.place` forwards the strict one-shot high-memory approval on both routes: the +/// read-root route (the bytes are imported in-process) and trusted local (the ambient +/// `file.placeEmbedded` command reads the path). A tiny PSD plus the scoped estimate charge +/// reaches the real approval window without allocating anything close to a gigabyte. +#[test] +fn doc_place_forwards_high_memory_approval() { + if cfg!(target_pointer_width = "32") { + return; // the 3 GiB charge would exceed a 32-bit process cap + } + let gb = 1u64 << 30; + let root = std::env::temp_dir().join(format!("pc-doc-place-approval-{}", std::process::id())); + std::fs::create_dir_all(&root).unwrap(); + let psd = photocraft_psd::testgen::small(photocraft_psd::Version::Psd, photocraft_psd::Compression::Zip).to_bytes().unwrap(); + std::fs::write(root.join("high.psd"), &psd).unwrap(); + // Known 5 GiB RAM: S = 2.5 GiB, H = 3.75 GiB. A 3 GiB estimate charge lands in (S, H]. + let snap = photocraft_io::memory::MemorySnapshot { available_ram: Some(5 * gb), swap_free: None, commit_headroom: None }; + let trial = |h: &mut Headless, path: &str| { + photocraft_io::psd_budget::with_test_estimate_charge(3 * gb, || { + photocraft_io::memory::with_mock_memory(snap, || { + let refused = h.handle("doc.place", json!({"path": path})).unwrap_err(); + assert!( + matches!(refused, crate::AutomationError::Engine(photocraft_engine::EngineError::PsdApprovalRequired { .. })), + "an unapproved high-memory place must ask for approval: {refused}" + ); + let placed = h.handle("doc.place", json!({"path": path, "approveHighMemory": true})).unwrap(); + assert!(placed["layer"].as_u64().is_some(), "the approval lets the same place proceed: {placed}"); + }); + }); + }; + let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap()); + h.handle("doc.new", json!({"width": 40, "height": 30})).unwrap(); + trial(&mut h, "high.psd"); + // Release directory capabilities before cleanup on Windows. + drop(h); + let mut t = Headless::trusted_local(); + t.handle("doc.new", json!({"width": 40, "height": 30})).unwrap(); + let absolute = root.join("high.psd").to_string_lossy().into_owned(); + trial(&mut t, &absolute); + drop(t); + std::fs::remove_dir_all(root).unwrap(); +} diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index 0b7c3fa753..b3bf9f3f11 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -50,6 +50,9 @@ pub struct DocIndex { pub struct OpenParams { /// Path beneath the configured automation read root: relative (forward slashes) or absolute. pub path: String, + /// Explicitly approve high-memory PSD/PSB imports that fit within the hard memory budget. + #[serde(default)] + pub approve_high_memory: bool, } #[derive(Debug, Default, Deserialize, JsonSchema)] @@ -69,6 +72,9 @@ pub struct PlaceParams { /// Centre of the placed layer, in document pixels. #[serde(default)] pub center: Option<[f64; 2]>, + /// Explicitly approve high-memory PSD/PSB imports that fit within the hard memory budget. + #[serde(default)] + pub approve_high_memory: bool, } #[derive(Debug, Default, Deserialize, JsonSchema)] @@ -484,13 +490,64 @@ fn png_result(png: &[u8], note: String) -> CallToolResult { bounded_tool_result(CallToolResult::success(vec![Content::image(b64, "image/png"), Content::text(note)])) } +/// Adds the typed byte counts of a memory refusal to an error object: an approval request keeps +/// its soft limit, hard limit and (when known) capacity; a hard refusal keeps only its required +/// and hard amounts, because no approval can raise that ceiling. +fn attach_memory_error_details(obj: &mut Value, err: &AutomationError) { + let Some(obj) = obj.as_object_mut() else { return }; + match err { + AutomationError::Import(photocraft_io::IoError::PsdApprovalRequired { required, soft_limit, hard_limit, available_ram }) + | AutomationError::Engine(photocraft_engine::EngineError::PsdApprovalRequired { required, soft_limit, hard_limit, available_ram, .. }) => { + obj.insert("required".into(), json!(required)); + obj.insert("soft".into(), json!(soft_limit)); + obj.insert("softLimit".into(), json!(soft_limit)); + obj.insert("hard".into(), json!(hard_limit)); + obj.insert("hardLimit".into(), json!(hard_limit)); + if let Some(avail) = available_ram { + obj.insert("available".into(), json!(avail)); + obj.insert("availableRam".into(), json!(avail)); + } + } + AutomationError::Import(photocraft_io::IoError::PsdImportBudget { required, limit }) + | AutomationError::Engine(photocraft_engine::EngineError::PsdHardBudget { required, limit, .. }) => { + obj.insert("required".into(), json!(required)); + obj.insert("hard".into(), json!(limit)); + obj.insert("hardLimit".into(), json!(limit)); + } + _ => {} + } +} + fn to_result(r: Result) -> Result { Ok(match r { Ok(v) => ok_json(&v), - Err(e) => fail(e), + Err(e) => { + let mut obj = json!({"error": e.to_string()}); + attach_memory_error_details(&mut obj, &e); + let text = serde_json::to_string(&obj).unwrap_or_else(|_| e.to_string()); + CallToolResult::error(vec![Content::text(text)]) + } }) } +/// A `doc_place` call's command options, including the explicit high-memory approval. +fn place_options(p: &PlaceParams) -> Value { + let mut opts = serde_json::Map::new(); + if let Some(v) = p.scale { + opts.insert("scale".into(), json!(v)); + } + if let Some(v) = p.fit { + opts.insert("fit".into(), json!(v)); + } + if let Some(v) = p.center { + opts.insert("center".into(), json!(v)); + } + if p.approve_high_memory { + opts.insert("approveHighMemory".into(), json!(true)); + } + Value::Object(opts) +} + fn bridge_only(name: &str) -> Result { Ok(fail(format!( "`{name}` drives the live GUI and needs bridge mode: start the app with \ @@ -635,30 +692,25 @@ impl PhotocraftMcp { #[tool(description = "Open an image or document file and make it active. Returns index, size and import warnings.")] async fn doc_open(&self, Parameters(p): Parameters) -> Result { let path = PathBuf::from(&p.path); - if let Some(r) = self.headless_op(move |h| h.open(&path)).await { + let approve = p.approve_high_memory; + if let Some(r) = self.headless_op(move |h| h.open_with_approval(&path, approve)).await { return to_result(r); } let Some(b) = self.bridge_client() else { return Ok(no_backend()); }; - to_result(b.call("app.open", json!({"path": p.path})).await) + let mut params = json!({"path": p.path}); + if approve { + params["approveHighMemory"] = json!(true); + } + to_result(b.call("app.open", params).await) } #[tool( - description = "Place a file into the document as a Smart Object layer (Place Embedded), reading `path` beneath the read root. `scale` (percent), `fit` and `center` are the command's own." + description = "Place a file into the document as a Smart Object layer (Place Embedded), reading `path` beneath the read root. `scale` (percent), `fit`, `center` and `approve_high_memory` (one-shot PSD/PSB consent, default false) are the command's own." )] async fn doc_place(&self, Parameters(p): Parameters) -> Result { - let mut opts = serde_json::Map::new(); - if let Some(v) = p.scale { - opts.insert("scale".into(), json!(v)); - } - if let Some(v) = p.fit { - opts.insert("fit".into(), json!(v)); - } - if let Some(v) = p.center { - opts.insert("center".into(), json!(v)); - } - let opts = Value::Object(opts); + let opts = place_options(&p); // Bridge mode runs the app on this machine, which reads the path itself like any command. let mut bridge_params = opts.clone(); if let Some(o) = bridge_params.as_object_mut() { @@ -943,7 +995,11 @@ impl PhotocraftMcp { let was_error = response.is_err(); let result = match response { Ok(value) => json!({"ok": true, "result": value}), - Err(error) => json!({"ok": false, "error": error.to_string()}), + Err(error) => { + let mut obj = json!({"ok": false, "error": error.to_string()}); + attach_memory_error_details(&mut obj, &error); + obj + } }; if let Err(error) = reply_budget.charge(&result) { failed += 1; @@ -1265,6 +1321,66 @@ mod tests { assert_eq!(docs, 0, "the step after the budget ran out did not run"); } + #[tokio::test(flavor = "multi_thread")] + async fn mcp_doc_open_schema_and_structured_error() { + let schema = &PhotocraftMcp::tool_router().map["doc_open"].attr.input_schema; + assert_eq!(schema["properties"]["approve_high_memory"]["type"], "boolean"); + let omitted: OpenParams = serde_json::from_value(json!({"path": "file.psd"})).unwrap(); + assert!(!omitted.approve_high_memory); + let approved: OpenParams = serde_json::from_value(json!({"path": "file.psd", "approve_high_memory": true})).unwrap(); + assert!(approved.approve_high_memory); + for invalid in [Value::Null, json!("true"), json!(1)] { + assert!(serde_json::from_value::(json!({"path": "file.psd", "approve_high_memory": invalid})).is_err()); + } + + let err = AutomationError::Import(photocraft_io::IoError::PsdApprovalRequired { + required: 6000, + soft_limit: 3000, + hard_limit: 9000, + available_ram: Some(12000), + }); + let res = to_result(Err(err)).unwrap(); + assert_eq!(res.is_error, Some(true)); + let text = &res.content.first().and_then(|c| c.as_text()).unwrap().text; + let v: Value = serde_json::from_str(text).unwrap(); + assert_eq!(v["required"], 6000); + assert_eq!(v["soft"], 3000); + assert_eq!(v["hard"], 9000); + assert_eq!(v["available"], 12000); + } + + /// #10897: the MCP `doc_place` tool takes the same strict, defaulted approval as `doc_open` + /// and forwards it as the command's `approveHighMemory` option. A hard refusal keeps its + /// typed `required`/`hardLimit` fields and claims nothing about a soft limit or capacity. + #[tokio::test(flavor = "multi_thread")] + async fn mcp_doc_place_schema_approval_and_structured_hard_error() { + let schema = &PhotocraftMcp::tool_router().map["doc_place"].attr.input_schema; + assert_eq!(schema["properties"]["approve_high_memory"]["type"], "boolean"); + let omitted: PlaceParams = serde_json::from_value(json!({"path": "file.psd"})).unwrap(); + assert!(!omitted.approve_high_memory); + assert!(place_options(&omitted).get("approveHighMemory").is_none(), "false is not forwarded"); + let approved: PlaceParams = serde_json::from_value(json!({"path": "file.psd", "approve_high_memory": true})).unwrap(); + assert!(approved.approve_high_memory); + assert_eq!(place_options(&approved)["approveHighMemory"], true); + let explicit_false: PlaceParams = serde_json::from_value(json!({"path": "file.psd", "approve_high_memory": false})).unwrap(); + assert!(!explicit_false.approve_high_memory); + for invalid in [Value::Null, json!("true"), json!(1)] { + assert!(serde_json::from_value::(json!({"path": "file.psd", "approve_high_memory": invalid})).is_err(), "{invalid}"); + } + + let err = AutomationError::Engine(photocraft_engine::EngineError::PsdHardBudget { name: "huge.psd".into(), required: 9_000, limit: 8_000 }); + let res = to_result(Err(err)).unwrap(); + assert_eq!(res.is_error, Some(true)); + let text = &res.content.first().and_then(|c| c.as_text()).unwrap().text; + let v: Value = serde_json::from_str(text).unwrap(); + assert_eq!(v["required"], 9_000); + assert_eq!(v["hard"], 8_000); + assert_eq!(v["hardLimit"], 8_000); + for absent in ["soft", "softLimit", "available", "availableRam"] { + assert!(v.get(absent).is_none(), "a hard refusal has no {absent}: {v}"); + } + } + /// The MCP server applies finished jobs before every tool call too (#503). #[tokio::test(flavor = "multi_thread")] async fn mcp_tools_see_a_finished_background_job() { diff --git a/crates/codecs/src/codecs/tiff/decode.rs b/crates/codecs/src/codecs/tiff/decode.rs index 9747b7c2f0..e2359e6828 100644 --- a/crates/codecs/src/codecs/tiff/decode.rs +++ b/crates/codecs/src/codecs/tiff/decode.rs @@ -165,6 +165,18 @@ impl<'a> TiffBands<'a> { self.p.lay.out_row().checked_mul(rows).ok_or_else(|| CodecError::LimitExceeded("band size".into())) } + /// A conservative bound on the decoder's own scratch memory in a whole-image decode of this + /// page (as `decode_page` does it): one strip or tile per worker that decodes a band at + /// once. Zero when strips are decoded in place. Add the decoded image itself and any + /// extra-sample planes. + pub fn decode_scratch_bytes(&self) -> u64 { + #[cfg(not(target_arch = "wasm32"))] + let workers = rayon::current_num_threads() as u64; + #[cfg(target_arch = "wasm32")] + let workers = 1; + scratch_bound(self.p.lay.direct(), self.p.scratch_bytes as u64, self.p.band_rows, self.p.h, workers) + } + /// Decodes the image a group of bands at a time, in order, handing each group to `sink` /// with the position of its top-left pixel in the image [`TiffBands::dimensions`] gives. A /// group is about 64 MiB (at least one strip or row of tiles per worker, at most `max_alloc`; @@ -219,6 +231,16 @@ impl<'a> TiffBands<'a> { } } +/// [`TiffBands::decode_scratch_bytes`]'s bound: none when chunks are decoded in place, +/// otherwise one chunk per worker that decodes a band, and never more chunks than the image has. +fn scratch_bound(direct: bool, chunk_bytes: u64, band_rows: usize, h: u32, workers: u64) -> u64 { + if direct { + return 0; + } + let bands = u64::from(h).div_ceil(band_rows.max(1) as u64).max(1); + chunk_bytes.saturating_mul(workers.min(bands)) +} + /// The Orientation (1–8) of page `page` (`None`: the default page); 1 when absent, malformed /// or out of range. Classic TIFF and BigTIFF. pub(crate) fn orientation(bytes: &[u8], page: Option) -> u16 { @@ -559,6 +581,9 @@ pub(super) struct Prepared { extras_over_limit: usize, /// Extra samples left out because they did not fit the allocation budget beside the image. extras_dropped: u32, + /// Bytes one strip or tile decodes to, before clipping to the image: a worker's scratch + /// buffer. A strip is the full width; a tile keeps its declared size even at an edge. + scratch_bytes: usize, } impl Prepared { @@ -803,6 +828,9 @@ fn prepare(f: &File<'_>, dir: &Ifd, limits: &Limits, whole: bool) -> Result, dir: &Ifd, limits: &Limits, whole: bool) -> Result std::result::Result<(), String> { if cfg!(target_arch = "wasm32") { Err("not available on the web (no file system)".into()) } else { Ok(()) } } +fn always(_: &Session) -> std::result::Result<(), String> { + Ok(()) +} + pub(crate) fn native_doc(s: &Session) -> std::result::Result<(), String> { native(s)?; has_doc(s) @@ -119,6 +123,10 @@ pub(crate) fn str_param<'a>(p: &'a Value, key: &str, cmd: &str) -> Result<&'a st p.get(key).and_then(Value::as_str).filter(|v| !v.is_empty()).ok_or_else(|| EngineError::BadParams { cmd: cmd.into(), msg: format!("missing \"{key}\"") }) } +pub(crate) fn u64_param(p: &Value, key: &str, cmd: &str) -> Result { + p.get(key).and_then(Value::as_u64).ok_or_else(|| EngineError::BadParams { cmd: cmd.into(), msg: format!("missing or invalid \"{key}\"") }) +} + pub(crate) fn f64_param(p: &Value, key: &str) -> Option { p.get(key).and_then(Value::as_f64).filter(|v| v.is_finite()) } @@ -255,16 +263,30 @@ pub fn specs() -> Vec { "Open As…", &["File"], Some("Cmd+Alt+Shift+O"), - r##"{"path":str,"as":"psd|png|jpg|tiff|…"? (decode as this format)}"##, + r##"{"path":str,"as":"psd|png|jpg|tiff|…"? (decode as this format),"approveHighMemory":bool=false (explicitly approve high memory usage)}"##, native, open_as ), + // One-shot permission for one file, not something to replay later: never journaled or + // recorded in an action, since replaying it in another session/on another file would + // grant memory use nobody approved (#10897). It also releases the queued source on both + // answers, so it must not be replayed as a step that expects a missing preflight. + CommandSpec { + id: "file.approveMemory", + label: "Approve High Memory PSD Import", + menu: &[], + shortcut: None, + params: r##"{"id":u64,"approve":bool=true,"background":bool=true}"##, + enabled: always, + run: approve_memory, + journal: false, + }, spec!( "file.placeEmbedded", "Place Embedded…", &["File"], None, - r##"{"path":str,"scale":%? (default: fit when larger than the canvas),"fit":bool? (default: Preferences > General > Resize Image During Place),"smartObject":bool? (default: Preferences > General > Always Create Smart Objects When Placing),"center":[x,y]?}"##, + r##"{"path":str,"scale":%? (default: fit when larger than the canvas),"fit":bool? (default: Preferences > General > Resize Image During Place),"smartObject":bool? (default: Preferences > General > Always Create Smart Objects When Placing),"center":[x,y]?,"approveHighMemory":bool=false (explicitly approve high memory usage)}"##, native_doc, |s, p| place(s, p, false) ), @@ -273,7 +295,7 @@ pub fn specs() -> Vec { "Place Linked…", &["File"], None, - r##"{"path":str,"scale":%?,"fit":bool? (default: Preferences > General > Resize Image During Place),"center":[x,y]?}"##, + r##"{"path":str,"scale":%?,"fit":bool? (default: Preferences > General > Resize Image During Place),"center":[x,y]?,"approveHighMemory":bool=false (explicitly approve high memory usage)}"##, native_doc, |s, p| place(s, p, true) ), diff --git a/crates/engine/src/cmd/file_cmds/open.rs b/crates/engine/src/cmd/file_cmds/open.rs index efc44e880f..1397702318 100644 --- a/crates/engine/src/cmd/file_cmds/open.rs +++ b/crates/engine/src/cmd/file_cmds/open.rs @@ -5,7 +5,13 @@ use super::{ }; pub(crate) fn import(name: &str, bytes: &[u8]) -> Result { - import_result(name, bytes).map(|r| r.document) + import_with_options(name, bytes, &photocraft_io::ImportOptions::default()) +} + +/// [`import`] with the caller's import settings. Footage passes its PSD/layered-TIFF memory limit, +/// so a frame import cannot bypass the admission the rest of the open path applies. +pub(crate) fn import_with_options(name: &str, bytes: &[u8], opts: &photocraft_io::ImportOptions) -> Result { + import_result_with(name, bytes, opts).map(|r| r.document) } /// [`import`] for a file that becomes a document of its own (Revert, Load Files into Stack; @@ -23,8 +29,15 @@ pub(super) fn import_at_raw_ppi(raw_ppi: f64, name: &str, bytes: &[u8]) -> Resul } fn import_result(name: &str, bytes: &[u8]) -> Result { + import_result_with(name, bytes, &photocraft_io::ImportOptions::default()) +} + +/// The one import path every caller shares: allocation checkpoint, native `.pcraft` and format +/// dispatch through `photocraft_io::import_with_options`, typed memory refusals, and the +/// preview-only refusal wherever the import came from. +fn import_result_with(name: &str, bytes: &[u8], opts: &photocraft_io::ImportOptions) -> Result { crate::allocation::checkpoint("importing document")?; - let r = photocraft_io::import(name, bytes).map_err(|e| EngineError::Other(format!("{name}: {e}")))?; + let r = photocraft_io::import_with_options(name, bytes, opts).map_err(|e| crate::error::io_open_error(name, e))?; // Auxiliary imports return only a document and cannot surface the preview's fidelity warning. // Open has its own warning-preserving path; never silently place or process a thumbnail. if r.preview_only { @@ -109,12 +122,30 @@ fn raw_resolution(ppi: f64, warnings: &[String], doc: &mut Document) { } pub fn open_bytes_as(s: &mut Session, name: &str, bytes: &[u8], as_ext: Option<&str>, path: Option) -> Result { + open_bytes_as_with_options(s, name, bytes, as_ext, path, false) +} + +/// [`open_bytes_as`] with the caller's high-memory approval for these bytes. +/// +/// A one-shot approved estimate is deliberately not forwarded: these bytes may be a fresh copy +/// whose estimate was never approved, so approval applies only through the boolean flag. +pub fn open_bytes_as_with_options( + s: &mut Session, + name: &str, + bytes: &[u8], + as_ext: Option<&str>, + path: Option, + approve_high_memory: bool, +) -> Result { crate::allocation::checkpoint("importing document")?; let decode_name = match as_ext { Some(ext) => format!("{}.{}", stem(name), ext.trim_start_matches('.')), None => name.to_string(), }; - let r = photocraft_io::import(&decode_name, bytes).map_err(|e| EngineError::Other(format!("{decode_name}: {e}")))?; + let mut opts = crate::jobs::import_options(s.prefs()); + opts.psd_high_memory_approved = approve_high_memory; + opts.psd_approved_estimate = None; + let r = photocraft_io::import_with_options(&decode_name, bytes, &opts).map_err(|e| crate::error::io_open_error(&decode_name, e))?; let mut doc = r.document; tag_exr_colorspace(s, &decode_name, &mut doc); raw_defaults(s, &r.warnings, &mut doc); @@ -139,9 +170,69 @@ pub fn open_bytes_as(s: &mut Session, name: &str, bytes: &[u8], as_ext: Option<& pub(super) fn open_as(s: &mut Session, p: &Value) -> Result { let path = str_param(p, "path", "file.openAs")?.to_string(); - let bytes = read_file(&path)?; let as_ext = p.get("as").or_else(|| p.get("format")).and_then(Value::as_str); - open_bytes_as(s, &path, &bytes, as_ext, Some(path.clone())) + let approve_high_memory = match p.get("approveHighMemory") { + None | Some(Value::Null) => false, + Some(Value::Bool(b)) => *b, + Some(_) => { + return Err(EngineError::BadParams { cmd: "file.openAs".into(), msg: "expected boolean for \"approveHighMemory\"".into() }); + } + }; + let bytes = read_file(&path)?; + open_bytes_as_with_options(s, &path, &bytes, as_ext, Some(path.clone()), approve_high_memory) +} + +/// Answers a pending high-memory preflight: `approve` false cancels it; true rechecks the hard +/// limit and starts the approved open. The preflight is removed either way, so a refusal or a +/// later failure releases the source it held. +pub(super) fn approve_memory(s: &mut Session, p: &Value) -> Result { + let id = crate::file_cmds::u64_param(p, "id", "file.approveMemory")?; + let approve = match p.get("approve") { + None | Some(Value::Null) => true, + Some(Value::Bool(b)) => *b, + Some(_) => { + return Err(EngineError::BadParams { cmd: "file.approveMemory".into(), msg: "expected boolean for \"approve\"".into() }); + } + }; + let _background = match p.get("background") { + None | Some(Value::Null) => true, + Some(Value::Bool(b)) => *b, + Some(_) => { + return Err(EngineError::BadParams { cmd: "file.approveMemory".into(), msg: "expected boolean for \"background\"".into() }); + } + }; + if !approve { + s.cancel_pending_preflight(id) + .ok_or_else(|| EngineError::BadParams { cmd: "file.approveMemory".into(), msg: format!("no pending high-memory preflight for id {id}") })?; + return Ok(json!({"id": id, "approved": false, "cancelled": true})); + } + // Taking the preflight releases the source bytes it held: approval, refusal and a later + // failure all end the wait. The one-shot authorization is bound to this source and estimate; + // the import re-checks both against the handle it actually decodes. + let preflight = s + .take_pending_preflight(id) + .ok_or_else(|| EngineError::BadParams { cmd: "file.approveMemory".into(), msg: format!("no pending high-memory preflight for id {id}") })?; + // The resolved policy is the platform's: desktop uses its measured adaptive budget, the web + // its 1 GiB automatic / 2 GiB hard product cap. Explicit consent is available on both; the + // hard ceiling is never raised by an approval. While the scratch disk is spilling, tile + // pixels may use its room too; this fast refusal grants the whole room (the pending prompt + // does not keep the tile share), and the import re-checks the exact split before decoding. + let budget = photocraft_io::memory::resolve_budget_with_scratch(photocraft_io::memory::MemorySnapshot::current(), None, u64::MAX); + if preflight.required > budget.hard_limit { + return Err(EngineError::PsdHardBudget { name: preflight.name, required: preflight.required, limit: budget.hard_limit }); + } + let started = s.start_open_approved_with_background( + &preflight.name, + preflight.source, + preflight.confirm_damage, + Some(preflight.required), + Some(preflight.fingerprint), + _background, + )?; + match started { + crate::jobs::Started::Done(v) => Ok(json!({"id": id, "approved": true, "result": v})), + crate::jobs::Started::Job(job_id) => Ok(json!({"id": id, "approved": true, "job": job_id.0})), + } } // ---------- place ---------- @@ -159,8 +250,17 @@ pub fn place_bytes(s: &mut Session, name: &str, bytes: Vec, linked: Option false, + Some(Value::Bool(b)) => *b, + Some(_) => { + return Err(EngineError::BadParams { cmd: "file.placeEmbedded".into(), msg: "expected boolean for \"approveHighMemory\"".into() }); + } + }; + let mut opts = crate::jobs::import_options(s.prefs()); + opts.psd_high_memory_approved = approve; + opts.psd_approved_estimate = None; + let imported = photocraft_io::import_with_options(name, &bytes, &opts).map_err(|e| crate::error::io_open_error(name, e))?; if imported.preview_only { return Err(EngineError::Other(format!( "{name}: only this Affinity file's embedded preview could be read; open it with File › Open to see the warning, or export PSD or PNG from Affinity before using it here" @@ -214,6 +314,9 @@ pub fn place_bytes(s: &mut Session, name: &str, bytes: Vec, linked: Option Result { let cmd = if linked { "file.placeLinked" } else { "file.placeEmbedded" }; + if p.get("approveHighMemory").is_some_and(|v| !v.is_null() && !v.is_boolean()) { + return Err(EngineError::BadParams { cmd: cmd.into(), msg: "expected boolean for approveHighMemory".into() }); + } let path = str_param(p, "path", cmd)?.to_string(); let bytes = read_file(&path)?; // The link is stored absolute: a relative one would later be taken from the document's diff --git a/crates/engine/src/cmd/file_cmds/tests.rs b/crates/engine/src/cmd/file_cmds/tests.rs index ff3949918b..0f353d76d7 100644 --- a/crates/engine/src/cmd/file_cmds/tests.rs +++ b/crates/engine/src/cmd/file_cmds/tests.rs @@ -2042,3 +2042,323 @@ fn sanitize_keeps_windows_device_names_off_the_disk() { assert_eq!(sanitize(name), name); } } + +#[test] +fn approve_memory_validates_parameters_and_unknown_ids() { + let mut s = session(4, 4, 8); + assert!(matches!(s.execute("file.approveMemory", json!({})), Err(EngineError::BadParams { .. }))); + assert!(matches!(s.execute("file.approveMemory", json!({"id": "not_a_number"})), Err(EngineError::BadParams { .. }))); + assert!(matches!(s.execute("file.approveMemory", json!({"id": 12345})), Err(EngineError::BadParams { .. }))); + assert!( + matches!(s.execute("file.approveMemory", json!({"id": 12345, "approve": false})), Err(EngineError::BadParams { .. })), + "unknown id on cancel must fail" + ); + assert!( + matches!(s.execute("file.approveMemory", json!({"id": 12345, "approve": "true"})), Err(EngineError::BadParams { .. })), + "wrong approve type string must BadParams" + ); + assert!( + matches!(s.execute("file.approveMemory", json!({"id": 12345, "approve": 1})), Err(EngineError::BadParams { .. })), + "wrong approve type int must BadParams" + ); + assert!( + matches!(s.execute("file.openAs", json!({"path": "a.psd", "approveHighMemory": "true"})), Err(EngineError::BadParams { .. })), + "wrong approveHighMemory on openAs must BadParams" + ); + assert!( + matches!(s.execute("file.placeEmbedded", json!({"path": "a.psd", "approveHighMemory": 1})), Err(EngineError::BadParams { .. })), + "wrong approveHighMemory on placeEmbedded must BadParams" + ); + assert!( + matches!(s.execute("file.approveMemory", json!({"id": 12345, "background": "true"})), Err(EngineError::BadParams { .. })), + "wrong background type string must BadParams" + ); + assert!( + matches!(s.execute("file.approveMemory", json!({"id": 12345, "background": 1})), Err(EngineError::BadParams { .. })), + "wrong background type int must BadParams" + ); +} + +#[test] +fn approve_memory_cancels_and_removes_pending_preflight() { + let mut s = Session::new(); + let id = s + .store_pending_preflight(crate::jobs::PendingPsdPreflight { + id: 0, + name: "test.psd".into(), + source: crate::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![1, 2, 3])), + fingerprint: crate::jobs::SourceFingerprint::of(&crate::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![1, 2, 3]))).unwrap(), + required: 1000, + soft_limit: 500, + hard_limit: 2000, + available_ram: Some(4000), + confirm_damage: true, + }) + .unwrap(); + let res = s.execute("file.approveMemory", json!({"id": id, "approve": false})).unwrap(); + assert_eq!(res["approved"], false); + assert_eq!(res["cancelled"], true); + assert!(s.take_pending_preflight(id).is_none(), "preflight removed on cancel"); +} + +#[test] +fn approve_memory_refuses_when_source_changes_before_confirmation() { + let dir = tmp("fingerprint_test"); + let path = join(&dir, "change.psd"); + std::fs::write(&path, b"initial content").unwrap(); + + let mut s = Session::new(); + let src = crate::jobs::OpenSource::Path(path.clone()); + let fp = crate::jobs::SourceFingerprint::of(&src).unwrap(); + let id = s + .store_pending_preflight(crate::jobs::PendingPsdPreflight { + id: 0, + name: "change.psd".into(), + source: src, + fingerprint: fp, + required: 1000, + soft_limit: 500, + hard_limit: 2000, + available_ram: Some(4000), + confirm_damage: true, + }) + .unwrap(); + + // Modify file on disk + std::fs::write(&path, b"changed content longer").unwrap(); + + let res = s.execute("file.approveMemory", json!({"id": id, "approve": true, "background": false})); + assert!(matches!(res, Err(EngineError::SourceChanged { .. })), "changed file must fail identity verification: {res:?}"); +} + +#[test] +fn approve_memory_refuses_when_available_ram_decreases() { + let gb = 1u64 << 30; + let mut s = Session::new(); + let src = crate::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0; 16])); + let fp = crate::jobs::SourceFingerprint::of(&src).unwrap(); + let id = s + .store_pending_preflight(crate::jobs::PendingPsdPreflight { + id: 0, + name: "ram_drop.psd".into(), + source: src, + fingerprint: fp, + required: 8 * gb, + soft_limit: 6 * gb, + hard_limit: 9 * gb, + available_ram: Some(12 * gb), + confirm_damage: true, + }) + .unwrap(); + + // Memory drops: only 6 GiB available -> H = 4.5 GiB < 8 GiB + let snap_low = photocraft_io::memory::MemorySnapshot { available_ram: Some(6 * gb), swap_free: None, commit_headroom: None }; + photocraft_io::memory::with_mock_memory(snap_low, || { + let res = s.execute("file.approveMemory", json!({"id": id, "approve": true})); + assert!(res.is_err(), "decreased memory must refuse"); + }); +} + +#[test] +fn pending_preflights_cap_fails_closed() { + let mut s = Session::new(); + let src = crate::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0; 4])); + let fp = crate::jobs::SourceFingerprint::of(&src).unwrap(); + for i in 0..crate::Session::MAX_PENDING_PREFLIGHTS { + assert!( + s.store_pending_preflight(crate::jobs::PendingPsdPreflight { + id: 0, + name: format!("file_{i}.psd"), + source: src.clone(), + fingerprint: fp.clone(), + required: 1000, + soft_limit: 500, + hard_limit: 2000, + available_ram: Some(4000), + confirm_damage: true, + }) + .is_ok() + ); + } + assert!( + s.store_pending_preflight(crate::jobs::PendingPsdPreflight { + id: 0, + name: "overflow.psd".into(), + source: src, + fingerprint: fp, + required: 1000, + soft_limit: 500, + hard_limit: 2000, + available_ram: Some(4000), + confirm_damage: true, + }) + .is_err() + ); +} + +/// A queued high-memory preflight for `source`, with fields a test can read. +fn memory_preflight(name: &str, source: crate::jobs::OpenSource) -> crate::jobs::PendingPsdPreflight { + let fingerprint = crate::jobs::SourceFingerprint::of(&source).unwrap(); + crate::jobs::PendingPsdPreflight { + id: 0, + name: name.into(), + source, + fingerprint, + required: 1000, + soft_limit: 500, + hard_limit: 2000, + available_ram: Some(4000), + confirm_damage: true, + } +} + +#[test] +fn pending_preflights_bound_retained_bytes_and_charge_a_shared_buffer_once() { + let mut s = Session::new(); + let cap = 100; + let a_src = crate::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0u8; 40])); + let b_src = crate::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0u8; 40])); + let a_id = s.store_pending_preflight_with_limit(memory_preflight("a.psd", a_src.clone()), cap).unwrap(); + let b_id = s.store_pending_preflight_with_limit(memory_preflight("b.psd", b_src), cap).unwrap(); + assert_eq!(s.pending_preflight_bytes().unwrap(), 80); + // A second reference to the same allocation is already held: queued for free. + let a_again = s.store_pending_preflight_with_limit(memory_preflight("a-again.psd", a_src), cap).unwrap(); + assert_eq!(s.pending_preflight_bytes().unwrap(), 80, "one shared buffer is charged once, not three times"); + // A different buffer would carry the total over the cap: refused, and nothing is charged. + let c_src = crate::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0u8; 30])); + let err = s.store_pending_preflight_with_limit(memory_preflight("c.psd", c_src.clone()), cap).expect_err("a further 30 bytes must not fit beside 80"); + assert!(err.to_string().contains("waiting for a memory approval"), "{err}"); + assert_eq!(s.pending_preflight_bytes().unwrap(), 80, "a refused preflight adds no charge"); + // Cancelling one released its buffer; the refused one now fits; clearing releases the rest. + assert!(s.cancel_pending_preflight(a_again).is_some()); + assert_eq!(s.pending_preflight_bytes().unwrap(), 80, "the other live reference still holds the buffer"); + assert!(s.cancel_pending_preflight(a_id).is_some()); + assert_eq!(s.pending_preflight_bytes().unwrap(), 40); + let c_id = s.store_pending_preflight_with_limit(memory_preflight("c.psd", c_src), cap).unwrap(); + assert_eq!(s.pending_preflight_bytes().unwrap(), 70); + s.clear_pending_preflights(); + assert_eq!(s.pending_preflight_bytes().unwrap(), 0, "clear releases every held buffer"); + assert!(s.cancel_pending_preflight(b_id).is_none()); + assert!(s.cancel_pending_preflight(c_id).is_none()); +} + +#[test] +fn pending_preflights_charge_the_retained_allocation_not_the_visible_length() { + let mut s = Session::new(); + let cap = 100; + // Room for 128 bytes but one byte of contents: what stays resident is the allocation, so a + // cap that fits the contents must still refuse it. + let mut grown = Vec::with_capacity(128); + grown.push(7u8); + let held = grown.capacity() as u64; + assert!(held >= 128, "the buffer really has the larger allocation: {held}"); + let big = std::sync::Arc::new(grown); + let err = s + .store_pending_preflight_with_limit(memory_preflight("big.psd", crate::jobs::OpenSource::Bytes(std::sync::Arc::clone(&big))), cap) + .expect_err("the held capacity, not the one byte of contents, must be charged"); + assert!(err.to_string().contains("waiting for a memory approval"), "{err}"); + assert_eq!(s.pending_preflight_bytes().unwrap(), 0, "a refused preflight adds no charge"); + + // A cap that admits the whole allocation accepts it, and shared clones count once. + let id = s.store_pending_preflight_with_limit(memory_preflight("big.psd", crate::jobs::OpenSource::Bytes(std::sync::Arc::clone(&big))), held).unwrap(); + let shared = + s.store_pending_preflight_with_limit(memory_preflight("shared.psd", crate::jobs::OpenSource::Bytes(std::sync::Arc::clone(&big))), held).unwrap(); + assert_eq!(s.pending_preflight_bytes().unwrap(), held, "one shared allocation is charged once, whatever its length"); + assert!(s.cancel_pending_preflight(shared).is_some()); + assert_eq!(s.pending_preflight_bytes().unwrap(), held, "the other shared reference still holds the allocation"); + assert!(s.cancel_pending_preflight(id).is_some()); + assert_eq!(s.pending_preflight_bytes().unwrap(), 0, "cancelling the last reference releases the allocation"); + s.clear_pending_preflights(); + + // A buffer whose length was shrunk to zero still holds its allocation: the held capacity is + // measured, so it is charged even though `len()` says nothing is there. + let mut emptied = Vec::with_capacity(128); + emptied.push(1u8); + emptied.clear(); + assert!(emptied.is_empty(), "the length is zero while the allocation stays"); + let emptied = std::sync::Arc::new(emptied); + let emptied_held = emptied.capacity() as u64; + assert!(emptied_held >= 128, "clearing does not release the allocation: {emptied_held}"); + let emptied_id = s + .store_pending_preflight_with_limit(memory_preflight("emptied.psd", crate::jobs::OpenSource::Bytes(emptied)), emptied_held) + .expect("the allocation fits the cap that admits it"); + assert_eq!(s.pending_preflight_bytes().unwrap(), emptied_held, "an empty length is not zero bytes held"); + s.clear_pending_preflights(); + assert_eq!(s.pending_preflight_bytes().unwrap(), 0, "clear releases every held allocation"); + assert!(s.cancel_pending_preflight(emptied_id).is_none()); +} + +#[test] +fn approve_memory_is_neither_journaled_nor_recorded_in_an_action() { + let mut s = Session::new(); + let id = s.store_pending_preflight(memory_preflight("cancel.psd", crate::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0u8; 4])))).unwrap(); + s.execute("actions.record", json!({"name": "Memory approvals"})).unwrap(); + let r = s.execute("file.approveMemory", json!({"id": id, "approve": false})).unwrap(); + assert_eq!((r["approved"].clone(), r["cancelled"].clone()), (json!(false), json!(true))); + s.execute("actions.stop", json!({})).unwrap(); + assert!(s.journal.iter().all(|(command, _)| command != "file.approveMemory"), "one-shot approval must not become a journal entry: {:?}", s.journal); + let action = s.actions.list.first().expect("the recorded action"); + assert!(action.steps.iter().all(|(command, _)| command != "file.approveMemory"), "one-shot approval must not replay from an action: {:?}", action.steps); +} + +#[test] +fn approve_memory_releases_the_preflight_when_the_hard_limit_refuses_it() { + let gb = 1u64 << 30; + let mut s = Session::new(); + let preflight = crate::jobs::PendingPsdPreflight { + required: 8 * gb, + soft_limit: 6 * gb, + hard_limit: 9 * gb, + available_ram: Some(12 * gb), + ..memory_preflight("ram_drop.psd", crate::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0u8; 16]))) + }; + let id = s.store_pending_preflight(preflight).unwrap(); + let snap_low = photocraft_io::memory::MemorySnapshot { available_ram: Some(4 * gb), swap_free: None, commit_headroom: None }; + let expected_limit = photocraft_io::memory::resolve_budget(snap_low, None).hard_limit; + photocraft_io::memory::with_mock_memory(snap_low, || { + let err = s.execute("file.approveMemory", json!({"id": id, "approve": true, "background": false})).unwrap_err(); + match &err { + EngineError::PsdHardBudget { name, required, limit } => { + assert_eq!(name, "ram_drop.psd"); + assert_eq!((*required, *limit), (8 * gb, expected_limit)); + } + other => panic!("the hard refusal must keep its fields, got {other}"), + } + }); + assert!(s.take_pending_preflight(id).is_none(), "a hard refusal releases the held source"); + assert_eq!(s.pending_preflight_bytes().unwrap(), 0); +} + +#[test] +fn open_as_and_place_keep_the_typed_hard_budget_fields() { + let gb = 1u64 << 30; + let dir = tmp("hard_budget"); + let path = join(&dir, "big.psd"); + let mut src = Session::new(); + src.execute("file.new", json!({"width": 4, "height": 4, "depth": 8})).unwrap(); + std::fs::write(&path, photocraft_io::export(&src.active().unwrap().doc, "x.psd", &Default::default()).unwrap().bytes).unwrap(); + // An estimate over the resolved hard ceiling is refused, and no approval raises the ceiling. + // The estimate charge is a test seam so the fixture stays tiny. + let snap = photocraft_io::memory::MemorySnapshot { available_ram: Some(4 * gb), swap_free: None, commit_headroom: None }; + let hard = photocraft_io::memory::resolve_budget(snap, None).hard_limit; + assert!(hard < u64::MAX); + photocraft_io::memory::with_mock_memory(snap, || { + photocraft_io::psd_budget::with_test_estimate_charge(hard + 1, || { + let mut s = Session::new(); + let err = s.execute("file.openAs", json!({"path": path.clone(), "approveHighMemory": true})).unwrap_err(); + match &err { + EngineError::PsdHardBudget { name, required, limit } => { + assert_eq!(name, &path); + assert!(*required > hard && *limit == hard); + } + other => panic!("openAs must keep name/required/limit, got {other}"), + } + let mut s = session(8, 8, 8); + let err = s.execute("file.placeEmbedded", json!({"path": path.clone(), "approveHighMemory": true})).unwrap_err(); + match &err { + EngineError::PsdHardBudget { required, limit, .. } => assert!(*required > hard && *limit == hard), + other => panic!("place must keep required/limit, got {other}"), + } + }); + }); +} diff --git a/crates/engine/src/cmd/video_cmds.rs b/crates/engine/src/cmd/video_cmds.rs index edc6c7e59d..d5540c1f79 100644 --- a/crates/engine/src/cmd/video_cmds.rs +++ b/crates/engine/src/cmd/video_cmds.rs @@ -263,10 +263,90 @@ type ImportFrames = fn( /// Frame storage one footage import may keep (whole tiles, all frames together). const MAX_FOOTAGE_BYTES: u64 = 2 << 30; +/// The footage frame limit this import applies: the production cap, or a test scope's lowered +/// cap so a regression can reach the refusal without keeping gibibytes of frames. +fn footage_byte_limit() -> u64 { + #[cfg(test)] + if let Some(limit) = limits::max_footage_bytes() { + return limit; + } + MAX_FOOTAGE_BYTES +} + +/// Import options for footage files. A test scope may lower the PSD/layered-TIFF memory limit, +/// which the user's preferences do not expose, to reach an admission refusal on a small file. +fn footage_import_options(s: &Session) -> photocraft_io::ImportOptions { + #[cfg(test)] + if let Some(limit) = limits::psd_max_pixel_bytes() { + return photocraft_io::ImportOptions { psd_max_pixel_bytes: limit, ..crate::jobs::import_options(s.prefs()) }; + } + crate::jobs::import_options(s.prefs()) +} + +/// Per-thread test overrides for the footage import limits. A scope restores the previous values +/// on drop, and the thread-local keeps parallel tests from lowering each other's limits. +#[cfg(test)] +mod limits { + use std::cell::Cell; + + #[derive(Clone, Copy, Default)] + struct Overrides { + psd_max_pixel_bytes: Option, + max_footage_bytes: Option, + } + + thread_local! { + static CURRENT: Cell = const { Cell::new(Overrides { psd_max_pixel_bytes: None, max_footage_bytes: None }) }; + } + + /// Restores the previous overrides when dropped. + pub(crate) struct Scoped(Overrides); + + impl Scoped { + /// Lowers the PSD/layered-TIFF memory admission limit for the current thread. + pub(crate) fn psd_max_pixel_bytes(limit: u64) -> Self { + Self::set(Overrides { psd_max_pixel_bytes: Some(limit), ..Default::default() }) + } + + /// Lowers the retained footage-frame limit for the current thread. + pub(crate) fn max_footage_bytes(limit: u64) -> Self { + Self::set(Overrides { max_footage_bytes: Some(limit), ..Default::default() }) + } + + fn set(next: Overrides) -> Self { + Self(CURRENT.with(|current| current.replace(next))) + } + } + + impl Drop for Scoped { + fn drop(&mut self) { + CURRENT.with(|current| current.set(self.0)); + } + } + + pub(super) fn psd_max_pixel_bytes() -> Option { + CURRENT.with(|current| current.get().psd_max_pixel_bytes) + } + + pub(super) fn max_footage_bytes() -> Option { + CURRENT.with(|current| current.get().max_footage_bytes) + } +} + +/// The engine error for a failed page of a multi-page TIFF. A memory refusal keeps its typed form, +/// so the UI, control channel and agents still get the required and limit fields they need to +/// offer approval or explain the hard limit; any other failure keeps the page's text. +fn tiff_page_error(display: &std::path::Path, name: &str, page: usize, error: photocraft_io::IoError) -> EngineError { + match error { + photocraft_io::IoError::PsdApprovalRequired { .. } | photocraft_io::IoError::PsdImportBudget { .. } => crate::error::io_open_error(name, error), + error => EngineError::Other(format!("`{}` page {}: {error}", display.display(), page + 1)), + } +} + /// Load frames from `path`: a single image (1 frame, or every frame of an animated GIF or WebP), or a /// directory of images (sorted = an image sequence). Each becomes a full raster frame in the /// document's format. -fn load_frames(path: &str, fmt: photocraft_color::PixelFormat) -> Result { +fn load_frames(path: &str, fmt: photocraft_color::PixelFormat, opts: &photocraft_io::ImportOptions) -> Result { let p = std::path::Path::new(path); let is_img = |f: &std::path::Path| { matches!( @@ -292,6 +372,7 @@ fn load_frames(path: &str, fmt: photocraft_color::PixelFormat) -> Result, surface: Surface| -> std::result::Result<(), String> { // A frame of fully transparent pixels stores no tiles, so the count needs its own limit. if frames.len() >= crate::timeline_cmds::MAX_DURATION { @@ -299,8 +380,8 @@ fn load_frames(path: &str, fmt: photocraft_color::PixelFormat) -> Result MAX_FOOTAGE_BYTES { - return Err(format!("the footage needs more than {} MiB of frames", MAX_FOOTAGE_BYTES >> 20)); + if kept_bytes > max_footage_bytes { + return Err(format!("the footage needs more than {} MiB of frames", max_footage_bytes >> 20)); } frames.push(surface); Ok(()) @@ -345,15 +426,20 @@ fn load_frames(path: &str, fmt: photocraft_color::PixelFormat) -> Result Result { .ok_or_else(|| EngineError::BadParams { cmd: "layer.videoLayers.newVideoLayerFromFile".into(), msg: "need `path`".into() })? .to_string(); let fmt = s.active().ok_or(EngineError::NoDocument)?.doc.pixel_format(); - let Footage { frames, fps: footage_fps } = load_frames(&path, fmt)?; + let Footage { frames, fps: footage_fps } = load_frames(&path, fmt, &footage_import_options(s))?; // An explicit `fps` wins, then the rate the footage implies, then 30. let fps = crate::timeline_cmds::fps_param("layer.videoLayers.newVideoLayerFromFile", p)?.or(footage_fps).unwrap_or(30.0); let n = frames.len(); @@ -410,7 +496,7 @@ fn replace_footage(s: &mut Session, p: &Value) -> Result { .ok_or_else(|| EngineError::BadParams { cmd: "layer.videoLayers.replaceFootage".into(), msg: "need `path`".into() })? .to_string(); let fmt = s.active().ok_or(EngineError::NoDocument)?.doc.pixel_format(); - let frames = load_frames(&path, fmt)?.frames; + let frames = load_frames(&path, fmt, &footage_import_options(s))?.frames; edit_video(s, "Replace Footage", move |v, _| { v.original_frames = Some(frames.clone()); v.frames = frames; @@ -446,7 +532,7 @@ fn reload_frame(s: &mut Session, _p: &Value) -> Result { }; // The footage path is stored in the document. let file = crate::doc_path::resolve(&path).map_err(|why| crate::doc_path::refusal("the footage", &path, why))?; - let frames = load_frames(&file.to_string_lossy(), fmt)?.frames; + let frames = load_frames(&file.to_string_lossy(), fmt, &footage_import_options(s))?.frames; edit_video(s, "Reload Frame", move |v, _| { v.original_frames = Some(frames.clone()); v.frames = frames; @@ -471,7 +557,7 @@ fn frames_to_layers(s: &mut Session, p: &Value) -> Result { .ok_or_else(|| EngineError::BadParams { cmd: "file.import.videoFramesToLayers".into(), msg: "need `path`".into() })? .to_string(); let fmt = s.active().ok_or(EngineError::NoDocument)?.doc.pixel_format(); - let frames = load_frames(&path, fmt)?.frames; + let frames = load_frames(&path, fmt, &footage_import_options(s))?.frames; let n = frames.len(); s.edit("Video Frames to Layers", |doc, active| { let mut above = *active; diff --git a/crates/engine/src/cmd/video_cmds/tests.rs b/crates/engine/src/cmd/video_cmds/tests.rs index d08135f60e..f2acb0bd0f 100644 --- a/crates/engine/src/cmd/video_cmds/tests.rs +++ b/crates/engine/src/cmd/video_cmds/tests.rs @@ -99,6 +99,46 @@ fn write_tiff(path: &str, pages: &[(u32, u32, u8, u32)]) { std::fs::write(path, f).unwrap(); } +/// A real layered TIFF from the exporter: two 8×6 raster layers and Photoshop layer data in tag +/// 37724, in one full-resolution page. +fn layered_tiff_bytes() -> Vec { + let mut doc = Document::new("layered", photocraft_geom::Size::new(8, 6), photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8); + let fmt = doc.pixel_format(); + for name in ["bottom", "top"] { + let mut surface = Surface::new(fmt); + surface.write_interleaved(photocraft_geom::Rect::new(0, 0, 8, 6), &vec![96u8; 8 * 6 * fmt.bytes_per_pixel()]); + doc.layers.push(Layer::new(name, LayerContent::Raster(surface))); + } + let bytes = + photocraft_io::export(&doc, "layered.tif", &photocraft_io::ExportOptions { tiff_layers: true, ..Default::default() }).expect("a layered TIFF").bytes; + assert_eq!(bytes.get(0..2), Some(&b"II"[..]), "the TIFF exporter writes little-endian files here"); + assert_eq!(u16::from_le_bytes([bytes[2], bytes[3]]), 42, "a classic TIFF"); + bytes +} + +/// [`layered_tiff_bytes`] extended to two pages by appending a copy of its first directory as the +/// next one. The copied directory keeps the original tag and pixel offsets, so both pages carry +/// genuine layer data without hand-written Photoshop blocks; the file stays small, and the second +/// page is never decoded. +fn write_layered_multipage_tiff(path: &str) { + let bytes = layered_tiff_bytes(); + let u16_at = |o: usize| u16::from_le_bytes([bytes[o], bytes[o + 1]]); + let first_ifd = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]) as usize; + let count = u16_at(first_ifd) as usize; + let dir_len = 2 + count * 12 + 4; + let mut f = bytes.clone(); + if f.len() % 2 == 1 { + f.push(0); + } + let second_ifd = f.len(); + f.extend_from_slice(&bytes[first_ifd..first_ifd + dir_len]); + let second_next = second_ifd + 2 + count * 12; + f[second_next..second_next + 4].copy_from_slice(&0u32.to_le_bytes()); + let first_next = first_ifd + 2 + count * 12; + f[first_next..first_next + 4].copy_from_slice(&u32::try_from(second_ifd).expect("a small TIFF").to_le_bytes()); + std::fs::write(path, f).expect("write the two-page TIFF"); +} + /// #6379: Video Frames to Layers takes every page of a multi-page TIFF, one layer each, in /// order, as it takes a GIF's frames; a thumbnail is not a page. A single-page TIFF is one frame. #[test] @@ -145,6 +185,121 @@ fn video_frames_to_layers_refuses_a_tiff_with_an_incomplete_page_list() { assert_eq!(s.active().unwrap().doc.layers.len(), before, "nothing imported"); } +/// #10897 review: a page refused by the PSD memory admission must reach the caller typed, so the +/// UI, control channel and agents can offer approval or explain the hard limit; a multi-page TIFF +/// is not a way to get a text-only refusal. Every other page failure keeps its file and page text. +#[test] +fn tiff_page_errors_keep_memory_refusals_typed_and_other_context() { + let display = std::path::Path::new("/tmp/footage/pages.tif"); + let name = "/tmp/footage/pages.tif"; + + let refusal = photocraft_io::IoError::PsdApprovalRequired { required: 9_000, soft_limit: 8_000, hard_limit: 16_000, available_ram: Some(4_000) }; + match tiff_page_error(display, name, 1, refusal) { + EngineError::PsdApprovalRequired { name: named, required, soft_limit, hard_limit, available_ram } => { + assert_eq!(named, name); + assert_eq!((required, soft_limit, hard_limit, available_ram), (9_000, 8_000, 16_000, Some(4_000))); + } + other => panic!("page 2 approval refusal lost its fields: {other:?}"), + } + + let hard = photocraft_io::IoError::PsdImportBudget { required: 9_000, limit: 8_000 }; + match tiff_page_error(display, name, 2, hard) { + EngineError::PsdHardBudget { name: named, required, limit } => { + assert_eq!(named, name); + assert_eq!((required, limit), (9_000, 8_000)); + } + other => panic!("page 3 hard refusal lost its fields: {other:?}"), + } + + let broken = photocraft_io::IoError::Unsupported("corrupt page".into()); + let err = tiff_page_error(display, name, 0, broken); + assert!(matches!(err, EngineError::Other(_)), "{err:?}"); + let msg = err.to_string(); + assert!(msg.contains("pages.tif") && msg.contains("page 1") && msg.contains("corrupt page"), "{msg}"); +} + +/// #10897 review: a multi-page TIFF page with Photoshop layer data is admitted like a PSD. A tiny +/// explicit caller limit must reach the caller as the typed `PsdHardBudget`, with the file name, +/// required bytes and limit intact, and the document must be left untouched. A helper-only test +/// would still pass if the page loop turned that refusal into text. +#[test] +fn video_frames_to_layers_keeps_a_layered_tiff_page_refusal_typed() { + let dir = tmpdir("tiff-typed"); + let path = format!("{dir}/layered.tif"); + write_layered_multipage_tiff(&path); + let mut s = session(); + let before_layers = s.active().unwrap().doc.layers.len(); + let before_active = s.active().unwrap().active_layer; + let _limit = super::limits::Scoped::psd_max_pixel_bytes(1); + let err = s.execute("file.import.videoFramesToLayers", json!({"path": path})).unwrap_err(); + match err { + EngineError::PsdHardBudget { name, required, limit } => { + assert_eq!(name, path); + assert_eq!(limit, 1); + assert!(required > limit, "the page estimate must be past the caller's limit: {required} > {limit}"); + } + other => panic!("the layered page's refusal lost its typed fields: {other:?}"), + } + assert_eq!(s.active().unwrap().doc.layers.len(), before_layers, "no partial frame layers"); + assert_eq!(s.active().unwrap().active_layer, before_active, "the active layer is unchanged"); +} + +/// #10897 review: every page of a multi-page TIFF goes through the footage `keep` budget, as a +/// GIF's frames do. Before, the pages were pushed straight into `frames`, so many large pages could +/// keep more than the cap without an error. A thread-local test scope lowers the cap, so the +/// regression needs a few tiles of memory rather than gibibytes. +#[test] +fn video_frames_to_layers_enforces_the_footage_limit_on_every_tiff_page() { + let dir = tmpdir("tiff-budget"); + let path = format!("{dir}/pages.tif"); + let mut s = session(); + let fmt = s.active().unwrap().doc.pixel_format(); + let tile = u64::from(photocraft_geom::TILE_SIZE.unsigned_abs()).pow(2) * fmt.bytes_per_pixel() as u64; + let budget = 1u64 << 20; + assert!(tile < budget, "one page must fit in the lowered budget"); + // One more page than fits in the budget: only the accumulation can refuse it. + let pages = usize::try_from(budget / tile + 1).expect("a small page count"); + write_tiff(&path, &vec![(16, 16, 40, 0); pages]); + let before = s.active().unwrap().doc.layers.len(); + let _limit = super::limits::Scoped::max_footage_bytes(budget); + let err = s.execute("file.import.videoFramesToLayers", json!({"path": path})).unwrap_err().to_string(); + assert!(err.contains("pages.tif") && err.contains("more than 1 MiB"), "{err}"); + assert_eq!(s.active().unwrap().doc.layers.len(), before, "nothing imported"); +} + +/// #10897 review: a single-page layered TIFF does not take the multi-page branch, so it falls +/// through to the ordinary single-file import. That import must carry the footage import settings, +/// including the PSD/layered-TIFF memory limit the caller lowered; before, it called the default +/// import and ignored the limit, so this refusal was never typed (and a caller limit could be +/// bypassed). The same file imports as one frame when the limit is not lowered. +#[test] +fn video_frames_to_layers_uses_the_footage_limit_for_a_single_page_layered_tiff() { + let dir = tmpdir("tiff-single-typed"); + let path = format!("{dir}/layered.tif"); + std::fs::write(&path, layered_tiff_bytes()).expect("write the layered TIFF"); + let mut s = session(); + let before_layers = s.active().unwrap().doc.layers.len(); + let before_active = s.active().unwrap().active_layer; + { + let _limit = super::limits::Scoped::psd_max_pixel_bytes(1); + let err = s.execute("file.import.videoFramesToLayers", json!({"path": path})).unwrap_err(); + match err { + EngineError::PsdHardBudget { name, required, limit } => { + assert_eq!(name, path); + assert_eq!(limit, 1); + assert!(required > limit, "the page estimate must be past the caller's limit: {required} > {limit}"); + } + other => panic!("the single-page layered TIFF's refusal lost its typed fields: {other:?}"), + } + } + assert_eq!(s.active().unwrap().doc.layers.len(), before_layers, "no partial frame layers"); + assert_eq!(s.active().unwrap().active_layer, before_active, "the active layer is unchanged"); + // The same page imports normally under the budget the footage command always applied. + let r = s.execute("file.import.videoFramesToLayers", json!({"path": path})).unwrap(); + assert_eq!(r["layers"], 1, "one page is one frame"); + assert_eq!(s.active().unwrap().doc.layers.len(), before_layers + 1); +} + #[test] fn new_video_layer_from_image_sequence() { let dir = tmpdir("seq"); @@ -382,8 +537,13 @@ fn tga_sequence_frames_keep_their_transparency() { let dir = tmpdir("tga"); write_tga(&format!("{dir}/f01.tga")); write_tga(&format!("{dir}/f02.tga")); - let frames = - load_frames(&dir, photocraft_color::PixelFormat::new(photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8, true)).unwrap().frames; + let frames = load_frames( + &dir, + photocraft_color::PixelFormat::new(photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8, true), + &photocraft_io::ImportOptions::default(), + ) + .unwrap() + .frames; assert_eq!(frames.len(), 2); for f in &frames { assert_eq!(f.pixel(2, 6), vec![1.0, 0.0, 0.0, 1.0]); diff --git a/crates/engine/src/error.rs b/crates/engine/src/error.rs index 323d3f5203..0abdb6302a 100644 --- a/crates/engine/src/error.rs +++ b/crates/engine/src/error.rs @@ -1,7 +1,7 @@ use super::LayerId; use crate::command_hints; -#[derive(Debug, thiserror::Error)] +#[derive(Clone, Debug, PartialEq, thiserror::Error)] pub enum EngineError { /// Displays with the nearest registered ids, if any ([`command_hints`], #3674). #[error("unknown command `{id}`{hint}", id = .0, hint = command_hints::unknown_command_hint(.0))] @@ -18,6 +18,17 @@ pub enum EngineError { /// ids are not positions (#5058). #[error("no such layer {}; {known}", id.0)] UnknownLayer { id: LayerId, known: String }, + /// Opening a PSD/PSB file requires explicit high-memory confirmation. + #[error("opening “{name}” requires explicit memory approval: {required} bytes required (soft limit {soft_limit}, hard limit {hard_limit})")] + PsdApprovalRequired { name: String, required: u64, soft_limit: u64, hard_limit: u64, available_ram: Option }, + /// The file's estimated memory cannot be admitted within the hard ceiling, which no approval + /// can raise. The requirement may equal the ceiling when the estimate saturated. + #[error("cannot open “{name}”: its estimated memory requirement of {required} bytes cannot be admitted within the {limit} byte hard limit on this machine")] + PsdHardBudget { name: String, required: u64, limit: u64 }, + /// The file behind an opened handle is not the one whose memory estimate was approved. + /// The document is discarded and is not opened. + #[error("“{name}” changed since it was checked; open it again to approve the new file")] + SourceChanged { name: String }, #[error("{0}")] Other(String), /// A background job was cancelled (see [`jobs`]); nothing changed. @@ -27,6 +38,33 @@ pub enum EngineError { pub type Result = std::result::Result; +impl EngineError { + /// Whether an approval-required error also carries the unknown-capacity warning: capacity was + /// unknown when the estimate was made and the estimate is above the warning threshold. A + /// fresh measurement or a known capacity never sets it, and no number is invented for a + /// capacity that could not be measured. + pub fn uncertain_capacity_warning(&self) -> bool { + match self { + Self::PsdApprovalRequired { required, available_ram, .. } => photocraft_io::memory::uncertain_capacity_warning(*required, *available_ram), + _ => false, + } + } +} + +/// Maps an io open/import failure to the engine's typed errors, preserving the memory fields the +/// UI, control channel and agents need to answer or explain it. +pub(crate) fn io_open_error(name: &str, error: photocraft_io::IoError) -> EngineError { + use photocraft_io::IoError; + match error { + IoError::PsdApprovalRequired { required, soft_limit, hard_limit, available_ram } => { + EngineError::PsdApprovalRequired { name: name.to_string(), required, soft_limit, hard_limit, available_ram } + } + IoError::PsdImportBudget { required, limit } => EngineError::PsdHardBudget { name: name.to_string(), required, limit }, + IoError::SourceChanged => EngineError::SourceChanged { name: name.to_string() }, + error => EngineError::Other(format!("{name}: {error}")), + } +} + impl From for EngineError { fn from(error: photocraft_raster::AllocationError) -> Self { Self::Other(format!("not enough memory for this operation ({error}); the document was not changed")) diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rs index 7c64b74fa5..ae1b880a64 100644 --- a/crates/engine/src/jobs.rs +++ b/crates/engine/src/jobs.rs @@ -170,6 +170,11 @@ pub struct JobEvent { pub label: String, pub document: Option, pub outcome: JobOutcome, + /// The typed failure behind a failed `outcome`: a hard-budget refusal keeps its + /// name/required/limit, an approval request keeps its limits, a changed source keeps its + /// kind. `None` for done, cancelled and panics without a typed error. Not serialized; + /// `JobInfo::error` remains the display string on the wire. + pub error: Option, } /// A job's state for the UI, the control channel and MCP (`jobs.list`). @@ -192,6 +197,10 @@ pub struct JobInfo { pub result: Option, #[serde(skip_serializing_if = "Option::is_none")] pub error: Option, + /// The typed failure behind `error`, for callers in this process (not serialized: the wire + /// form is the message, as before). + #[serde(skip)] + pub error_kind: Option, } type Payload = Box; @@ -273,6 +282,7 @@ impl Running { elapsed_ms: now_ms() - self.started_ms, result: None, error: None, + error_kind: None, } } } @@ -340,16 +350,29 @@ fn independent_of_document(id: &str) -> bool { PREFIXES.iter().any(|p| id.starts_with(p)) || IDS.contains(&id) } +/// Imports the file at `path`, taking its identity from the very handle it decodes. +/// +/// `expected` is the identity approved for this file, if any. It is checked against the opened +/// handle before decoding and again when the memory preflight pauses for approval, so the +/// document opened is the approved file even if the path is replaced meanwhile. `opened` receives +/// the handle's identity as soon as it is known, including when the import stops for approval. #[cfg(not(target_arch = "wasm32"))] fn import_path( name: &str, path: &str, opts: &photocraft_io::ImportOptions, + expected: Option<&SourceFingerprint>, ctl: &photocraft_raster::Interrupt, + opened: &mut Option, ) -> std::result::Result<(photocraft_io::ImportResult, bool), photocraft_io::IoError> { + let expected = match expected { + None => None, + Some(SourceFingerprint::Path { identity, .. }) => Some(identity), + Some(SourceFingerprint::Bytes { .. }) => return Err(photocraft_io::IoError::SourceChanged), + }; // Bounded reads, and a clear error for a file larger than memory (#375); a PSD/PSB is - // parsed from the open file instead of being read whole. - photocraft_io::import_file_for_open_with(name, std::path::Path::new(path), opts, ctl) + // streamed from the open file instead of being read whole. + photocraft_io::import_file_for_open_verified(name, std::path::Path::new(path), expected, opts, ctl, opened) } #[cfg(target_arch = "wasm32")] @@ -357,7 +380,9 @@ fn import_path( _: &str, path: &str, _: &photocraft_io::ImportOptions, + _: Option<&SourceFingerprint>, _: &photocraft_raster::Interrupt, + _: &mut Option, ) -> std::result::Result<(photocraft_io::ImportResult, bool), photocraft_io::IoError> { Err(photocraft_io::IoError::Read(format!("cannot open paths on the web: {path}"))) } @@ -540,6 +565,76 @@ pub fn import_options(prefs: &crate::prefs::Preferences) -> photocraft_io::Impor } } +/// Fingerprint verifying that a source has not changed between preflight and approval. +/// +/// A path's fingerprint is the [`photocraft_io::FileIdentity`] of an opened handle, never a path +/// stat made before a separate open: the importer takes it from the very handle it decodes +/// (`photocraft_io::import_file_for_open_verified`), so a path replaced or rewritten between +/// the estimate and the approval is refused with [`EngineError::SourceChanged`]. The Unix +/// identity includes the inode change time and nanoseconds, so restoring a modification time +/// cannot hide a same-size rewrite. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum SourceFingerprint { + Bytes { len: usize, identity: usize }, + Path { path: String, identity: photocraft_io::FileIdentity }, +} + +impl SourceFingerprint { + /// Fingerprint of `source`. + /// + /// An in-memory source's identity is its shared buffer. A path is inspected here for + /// discovery only; the decode path re-reads its identity from the handle it opens. Fails + /// closed when the identity data cannot be read. + pub fn of(source: &OpenSource) -> Result { + match source { + OpenSource::Bytes(b) => Ok(SourceFingerprint::Bytes { len: b.len(), identity: Arc::as_ptr(b) as usize }), + OpenSource::Path(p) => { + Ok(Self::path(p.clone(), photocraft_io::FileIdentity::of_path(std::path::Path::new(p)).map_err(|e| EngineError::Other(format!("{p}: {e}")))?)) + } + } + } + + /// Fingerprint of the file identity read from an opened handle for `path`. + pub fn path(path: String, identity: photocraft_io::FileIdentity) -> Self { + SourceFingerprint::Path { path, identity } + } + + /// The handle identity a path fingerprint compares against, if this is one. + pub fn file_identity(&self) -> Option<&photocraft_io::FileIdentity> { + match self { + SourceFingerprint::Path { identity, .. } => Some(identity), + SourceFingerprint::Bytes { .. } => None, + } + } + + /// Whether both fingerprints capture the same source identity (and, for a path, the same path). + pub fn matches(&self, other: &Self) -> bool { + self == other + } + + /// Re-reads `source`'s fingerprint and compares it with this one; an unreadable source does not match. + pub fn matches_source(&self, source: &OpenSource) -> bool { + match Self::of(source) { + Ok(cur) => self.matches(&cur), + Err(_) => false, + } + } +} + +/// A pending high-memory PSD preflight request waiting for user confirmation before pixel decoding. +#[derive(Clone, Debug)] +pub struct PendingPsdPreflight { + pub id: u64, + pub name: String, + pub source: OpenSource, + pub fingerprint: SourceFingerprint, + pub required: u64, + pub soft_limit: u64, + pub hard_limit: u64, + pub available_ram: Option, + pub confirm_damage: bool, +} + impl Session { /// Run the heavy part of inline (not background) job commands under `ctx`, so another thread /// can cancel them: a live preview whose parameters changed stops its stale computation @@ -555,6 +650,137 @@ impl Session { self.dispatch(id, params, true) } + pub const MAX_PENDING_PREFLIGHTS: usize = 32; + + /// Most bytes of file data pending approvals may keep alive together. + /// + /// This is a retention bound for the *sources* of files waiting for an answer, not a pixel + /// budget and not an admission limit: only an [`OpenSource::Bytes`] source holds data (a path + /// streams from its file once opened), the allocation's capacity is charged rather than its + /// contents, and one shared buffer counts once however many preflights refer to it. 1 GiB is + /// chosen conservatively: it is below the 2 GiB web hard + /// product cap, so even a web session that queues several large dropped files cannot spend + /// the whole hard budget on data it has not decoded, and a native session keeps a comparable + /// amount out of the adaptive allowance. A file that would exceed the cap cannot become + /// pending: it is refused with an error instead of being decoded, and the caller can answer + /// or cancel queued prompts and try again, rather than holding an unbounded amount of memory + /// for unanswered prompts. The record count + /// ([`Self::MAX_PENDING_PREFLIGHTS`]) stays as a separate bound, so many small files are + /// bounded too. + pub const MAX_PENDING_PREFLIGHT_BYTES: u64 = 1 << 30; + + /// Queues an approval prompt, assigning its id, and enforces both the pending-count and + /// retained-byte limits. + pub fn store_pending_preflight(&mut self, preflight: PendingPsdPreflight) -> Result { + self.store_pending_preflight_with_limit(preflight, Self::MAX_PENDING_PREFLIGHT_BYTES) + } + + /// [`Self::store_pending_preflight`] with an explicit retention cap (tests use a tiny one so + /// the boundary is exercised without holding a gigabyte). + pub(crate) fn store_pending_preflight_with_limit(&mut self, mut preflight: PendingPsdPreflight, byte_limit: u64) -> Result { + if self.pending_preflights.len() >= Self::MAX_PENDING_PREFLIGHTS { + return Err(EngineError::Other("too many pending high-memory preflights waiting for confirmation".into())); + } + let held = self.pending_preflight_bytes_with(&preflight.source)?; + if held > byte_limit { + return Err(EngineError::Other(format!( + "too much memory is already held by files waiting for a memory approval ({held} bytes, limit {byte_limit}); answer or cancel one of them and try again" + ))); + } + loop { + self.next_pending_preflight = self.next_pending_preflight.checked_add(1).unwrap_or(1); + if self.next_pending_preflight != 0 && !self.pending_preflights.iter().any(|p| p.id == self.next_pending_preflight) { + break; + } + } + preflight.id = self.next_pending_preflight; + self.pending_preflights.push(preflight); + Ok(self.next_pending_preflight) + } + + /// Bytes held alive by the queued preflights, counting an `Arc>` shared by several of + /// them once. Computed from the queue, so approving, cancelling, refusing or clearing always + /// releases the charge; a rejected preflight never adds one. + pub fn pending_preflight_bytes(&self) -> Result { + Self::retained_source_bytes(self.pending_preflights.iter().map(|p| &p.source)) + } + + /// [`Self::pending_preflight_bytes`] as if `incoming` were queued too, so accepting it can be + /// checked before the list is changed. + fn pending_preflight_bytes_with(&self, incoming: &OpenSource) -> Result { + let mut sources: Vec<&OpenSource> = self.pending_preflights.iter().map(|p| &p.source).collect(); + sources.push(incoming); + Self::retained_source_bytes(sources) + } + + /// Total retained capacity of distinct in-memory sources, counting a shared buffer once. + /// + /// Capacity, not length, is charged because a truncated `Vec` keeps its allocation; overflow + /// is an error rather than a wrapped total. + fn retained_source_bytes<'a>(sources: impl IntoIterator) -> Result { + let mut seen: Vec = Vec::new(); + let mut total: u64 = 0; + for source in sources { + let OpenSource::Bytes(bytes) = source else { continue }; + let identity = Arc::as_ptr(bytes) as usize; + // Distinct live allocations cannot share an address, so identity dedupes clones of + // one buffer without under-counting two different files with equal contents. + if seen.contains(&identity) { + continue; + } + seen.push(identity); + // The allocation is what stays resident, not its contents: a `Vec` that once held a + // large file keeps that capacity after being truncated, so charging `len()` would + // under-count the memory a pending prompt holds. Overflow is an error, never a wrap. + let held = u64::try_from(bytes.capacity()).unwrap_or(u64::MAX); + total = total.checked_add(held).ok_or_else(|| EngineError::Other("held file size overflow while counting pending memory approvals".into()))?; + } + Ok(total) + } + + /// Removes and returns the pending preflight with `id`, releasing the source it held. + pub fn take_pending_preflight(&mut self, id: u64) -> Option { + let i = self.pending_preflights.iter().position(|p| p.id == id)?; + Some(self.pending_preflights.remove(i)) + } + + /// Cancels the pending preflight with `id` by removing it; `None` means no such prompt. + pub fn cancel_pending_preflight(&mut self, id: u64) -> Option { + self.take_pending_preflight(id) + } + + /// Drops every pending preflight, releasing all retained source buffers. + pub fn clear_pending_preflights(&mut self) { + self.pending_preflights.clear(); + } + + /// Starts an open with high-memory approval already granted, on a background worker. + /// `expected_fingerprint`, when given, must still match the decoded source. + pub fn start_open_approved( + &mut self, + name: &str, + source: OpenSource, + confirm_damage: bool, + approved_estimate: Option, + expected_fingerprint: Option, + ) -> Result { + self.start_open_approved_with_background(name, source, confirm_damage, approved_estimate, expected_fingerprint, true) + } + + /// [`Self::start_open_approved`] with an explicit choice between a background worker and + /// inline work. + pub fn start_open_approved_with_background( + &mut self, + name: &str, + source: OpenSource, + confirm_damage: bool, + approved_estimate: Option, + expected_fingerprint: Option, + background: bool, + ) -> Result { + self.start_open_inner(name, source, confirm_damage, true, approved_estimate, expected_fingerprint, background) + } + /// Open a file in the background: read (for a path) and decode on a worker, with progress /// (per layer for PSD/PSB) and cancellation, then add the document like /// [`Session::open_document`] (Color Settings policies apply). `name` names the document. @@ -565,76 +791,175 @@ impl Session { /// result is `{held, name, warnings, color}` (`color` the question): take it with /// [`Session::take_held_open`] once answered. pub fn start_open(&mut self, name: &str, source: OpenSource) -> Result { - self.start_open_inner(name, source, false) + self.start_open_inner(name, source, false, false, None, None, true) } /// Interactive opening: hold a damaged PSD until the user answers a damage /// confirmation, without changing import or subsequent save behaviour. /// Headless callers keep using [`Self::start_open`]. pub fn start_open_for_user(&mut self, name: &str, source: OpenSource) -> Result { - self.start_open_inner(name, source, true) + self.start_open_for_user_with_background(name, source, true) + } + + /// Interactive open with an explicit background/inline choice: damaged PSD content and + /// high-memory preflights wait for the user instead of opening non-interactively. + pub fn start_open_for_user_with_background(&mut self, name: &str, source: OpenSource, background: bool) -> Result { + self.start_open_inner(name, source, true, false, None, None, background) } /// Decodes a file in a job and optionally holds damaged PSD content for /// interactive confirmation while leaving headless opens non-interactive. - fn start_open_inner(&mut self, name: &str, source: OpenSource, confirm_damage: bool) -> Result { + // Keep the worker and apply closures together with their execution options. + #[allow(clippy::too_many_arguments)] + fn start_open_inner( + &mut self, + name: &str, + source: OpenSource, + confirm_damage: bool, + approve_high_memory: bool, + approved_estimate: Option, + expected_fingerprint: Option, + background: bool, + ) -> Result { let label = format!("Opening {name}"); let name_w = name.to_string(); let name_a = name.to_string(); - let opts = import_options(self.prefs()); - self.start_job( + let mut opts = import_options(self.prefs()); + opts.psd_high_memory_approved = approve_high_memory; + opts.psd_approved_estimate = approved_estimate; + let test_memory_scope = photocraft_io::memory::TestMemoryScope::capture(); + enum WorkResult { + Decoded(Box<(photocraft_io::ImportResult, bool)>), + PreflightNeeded { required: u64, soft_limit: u64, hard_limit: u64, available_ram: Option, source: OpenSource, fingerprint: SourceFingerprint }, + } + self.start_job_with_spawn( OPEN_JOB, json!({"name": name}), &label, false, + background, move |ctx| { + let _test_memory = test_memory_scope.enter(); ctx.progress(0.0, "Reading"); - let imported = match source { + + // An in-memory source's identity is its shared buffer, known before decoding. A + // path's identity can only come from the handle the verified import opens, so + // that import compares it against `expected_fingerprint` itself, before reading + // any pixel and again after its memory preflight. + let initial_fingerprint = match &source { + OpenSource::Bytes(_) => Some(SourceFingerprint::of(&source)?), + OpenSource::Path(_) => None, + }; + if let Some(expected) = &expected_fingerprint + && let Some(current) = &initial_fingerprint + && !expected.matches(current) + { + return Err(EngineError::SourceChanged { name: name_w.clone() }); + } + + let outcome = match source { OpenSource::Bytes(bytes) => { ctx.check()?; ctx.progress(0.02, "Decoding"); - ctx.stage(0.02, 0.95, "Decoding", |ctl| photocraft_io::import_for_open_with(&name_w, &bytes, &opts, ctl)) + let res = ctx.stage(0.02, 0.95, "Decoding", |ctl| photocraft_io::import_for_open_with(&name_w, &bytes, &opts, ctl)); + match res { + Ok(imported) => WorkResult::Decoded(Box::new(imported)), + Err(photocraft_io::IoError::PsdApprovalRequired { required, soft_limit, hard_limit, available_ram }) if confirm_damage => { + // The buffer cannot change while it is decoded, so the identity + // captured before reading is still exact. + let fingerprint = initial_fingerprint.clone().ok_or_else(|| EngineError::Other("missing source identity".into()))?; + WorkResult::PreflightNeeded { required, soft_limit, hard_limit, available_ram, source: OpenSource::Bytes(bytes), fingerprint } + } + Err(photocraft_io::IoError::PsdApprovalRequired { required, soft_limit, hard_limit, available_ram }) => { + return Err(EngineError::PsdApprovalRequired { name: name_w.clone(), required, soft_limit, hard_limit, available_ram }); + } + Err(photocraft_io::IoError::Cancelled) => return Err(EngineError::Cancelled), + Err(e) => return Err(crate::error::io_open_error(&name_w, e)), + } + } + OpenSource::Path(p) => { + let mut opened = None; + let res = ctx.stage(0.0, 0.95, "Decoding", |ctl| import_path(&name_w, &p, &opts, expected_fingerprint.as_ref(), ctl, &mut opened)); + match res { + Ok(imported) => WorkResult::Decoded(Box::new(imported)), + Err(photocraft_io::IoError::PsdApprovalRequired { required, soft_limit, hard_limit, available_ram }) if confirm_damage => { + // This identity is the one read from the handle that was + // estimated, and the verified import refused a handle that is + // not the approved file or changed while preflighting. + let identity = opened.ok_or_else(|| EngineError::Other(format!("{p}: the file's identity could not be read")))?; + let fingerprint = SourceFingerprint::path(p.clone(), identity); + WorkResult::PreflightNeeded { required, soft_limit, hard_limit, available_ram, source: OpenSource::Path(p), fingerprint } + } + Err(photocraft_io::IoError::PsdApprovalRequired { required, soft_limit, hard_limit, available_ram }) => { + return Err(EngineError::PsdApprovalRequired { name: name_w.clone(), required, soft_limit, hard_limit, available_ram }); + } + Err(photocraft_io::IoError::Cancelled) => return Err(EngineError::Cancelled), + Err(e) => return Err(crate::error::io_open_error(&name_w, e)), + } + } + }; + + match &outcome { + WorkResult::PreflightNeeded { .. } => Ok(outcome), + WorkResult::Decoded(imported) => { + ctx.progress(0.95, "Preparing layers"); + warm_layer_bounds(&imported.0.document, || ctx.check())?; + if crate::type_extra_cmds::has_type_layers(&imported.0.document) { + ctx.progress(0.97, "Loading fonts"); + let _ = photocraft_text::shared(); + ctx.check()?; + } + Ok(outcome) } - // A PSD/PSB is decoded straight from the file, which is never read whole. - OpenSource::Path(p) => ctx.stage(0.0, 0.95, "Decoding", |ctl| import_path(&name_w, &p, &opts, ctl)), } - .map_err(|e| match e { - photocraft_io::IoError::Cancelled => EngineError::Cancelled, - e => EngineError::Other(e.to_string()), - })?; - ctx.progress(0.95, "Preparing layers"); - warm_layer_bounds(&imported.0.document, || ctx.check())?; - // Type layers need the shared text engine, whose first use waits for the - // installed-font scan started at launch (minutes on some machines). Wait here, - // so the shell's missing-font check after the open finds it ready instead of - // freezing the window (#7332). - if crate::type_extra_cmds::has_type_layers(&imported.0.document) { - ctx.progress(0.97, "Loading fonts"); - let _ = photocraft_text::shared(); - ctx.check()?; - } - Ok(imported) }, - move |s, (mut r, damaged): (photocraft_io::ImportResult, bool)| { - // File Handling's ACEScg option, before the colour prompt looks at the profile. - crate::file_cmds::tag_exr_colorspace(s, &name_a, &mut r.document); - crate::file_cmds::raw_defaults(s, &r.warnings, &mut r.document); - // Ask When Opening: held back until the prompt is answered (`take_held_open`). A - // developed raw has no embedded profile to ask about. - let raw = r.warnings.iter().any(|w| w.contains(photocraft_io::raw::DEVELOPED_NOTE)); - let damaged = confirm_damage && damaged; - let question = s.color.open_question(&r.document).filter(|_| !raw); - if damaged || question.is_some() { - let held = s.hold_open(r.document, r.source_read_only); - return Ok(json!({"held": held, "name": name_a, "warnings": r.warnings, "color": question, "damaged": damaged})); + move |s, outcome| match outcome { + WorkResult::PreflightNeeded { required, soft_limit, hard_limit, available_ram, source, fingerprint } => { + // The warning follows the capacity measured for this estimate: an unknown + // capacity carries no fabricated number, and above the threshold it also + // says the process or tab may run out of memory. The UI shows both. + let capacity_unknown = available_ram.is_none(); + let uncertain_capacity = photocraft_io::memory::uncertain_capacity_warning(required, available_ram); + let id = s.store_pending_preflight(PendingPsdPreflight { + id: 0, + name: name_a.clone(), + source, + fingerprint, + required, + soft_limit, + hard_limit, + available_ram, + confirm_damage, + })?; + Ok(json!({ + "pendingPreflight": id, + "name": name_a, + "estimated": required, + "softLimit": soft_limit, + "hardLimit": hard_limit, + "availableRam": available_ram, + "capacityUnknown": capacity_unknown, + "uncertainCapacityWarning": uncertain_capacity, + })) } - let (index, color) = s.open_document(r.document, None); - // Persisted IDs can collide: report the identity the session actually admitted. - let id = s.documents().get(index).ok_or(EngineError::NoDocument)?.doc.id; - if let Some(st) = s.active_mut() { - st.source_read_only = r.source_read_only; + WorkResult::Decoded(imported) => { + let (mut r, damaged) = *imported; + crate::file_cmds::tag_exr_colorspace(s, &name_a, &mut r.document); + crate::file_cmds::raw_defaults(s, &r.warnings, &mut r.document); + let raw = r.warnings.iter().any(|w| w.contains(photocraft_io::raw::DEVELOPED_NOTE)); + let damaged = confirm_damage && damaged; + let question = s.color.open_question(&r.document).filter(|_| !raw); + if damaged || question.is_some() { + let held = s.hold_open(r.document, r.source_read_only); + return Ok(json!({"held": held, "name": name_a, "warnings": r.warnings, "color": question, "damaged": damaged})); + } + let (index, color) = s.open_document(r.document, None); + let id = s.documents().get(index).ok_or(EngineError::NoDocument)?.doc.id; + if let Some(st) = s.active_mut() { + st.source_read_only = r.source_read_only; + } + Ok(json!({"document": index, "docId": id.0, "name": name_a, "warnings": r.warnings, "color": color})) } - Ok(json!({"document": index, "docId": id.0, "name": name_a, "warnings": r.warnings, "color": color})) }, ) } @@ -653,9 +978,27 @@ impl Session { work: impl FnOnce(&JobCtx) -> Result + Send + 'static, apply: impl FnOnce(&mut Session, T) -> Result + Send + 'static, ) -> Result { - self.jobs.spawn = true; + self.start_job_with_spawn(command, params, label, lock_document, true, work, apply) + } + + // Keep the worker and apply closures together with their execution options. + /// [`Self::start_job`] with an explicit `spawn` flag: when false (or on wasm) the work runs + /// inline and its result is returned directly; otherwise it becomes a background job. + #[allow(clippy::too_many_arguments)] + pub fn start_job_with_spawn( + &mut self, + command: &str, + params: Value, + label: &str, + lock_document: bool, + spawn: bool, + work: impl FnOnce(&JobCtx) -> Result + Send + 'static, + apply: impl FnOnce(&mut Session, T) -> Result + Send + 'static, + ) -> Result { + let prev_spawn = self.jobs.spawn; + self.jobs.spawn = spawn && !cfg!(target_arch = "wasm32"); let r = run(self, label, lock_document, work, apply); - self.jobs.spawn = false; + self.jobs.spawn = prev_spawn; let pending = self.jobs.pending.take(); match (r, pending) { (Err(e), Some(job)) => { @@ -720,7 +1063,9 @@ impl Session { match self.jobs.recent.iter().rev().find(|j| j.id == id) { Some(j) if j.state == "done" => Ok(j.result.clone().unwrap_or(Value::Null)), Some(j) if j.state == "cancelled" => Err(EngineError::Cancelled), - Some(j) => Err(EngineError::Other(j.error.clone().unwrap_or_else(|| "the job failed".into()))), + // A typed failure keeps its fields for a caller that answers or explains it; the + // display string stays available through `jobs.list`. + Some(j) => Err(j.error_kind.clone().unwrap_or_else(|| EngineError::Other(j.error.clone().unwrap_or_else(|| "the job failed".into())))), None => Err(EngineError::Other(format!("no job {}", id.0))), } } @@ -1028,17 +1373,19 @@ impl Session { /// Apply (or report the failure of) a job whose worker has delivered `r`. fn finish_job(&mut self, mut job: Running, r: Result) { let apply = job.apply.take(); - let outcome = match r { - Err(EngineError::Cancelled) => JobOutcome::Cancelled, - Err(e) => JobOutcome::Failed(e.to_string()), - Ok(_) if job.ctx.cancelled() => JobOutcome::Cancelled, + // Keep the typed error beside its display text, so `wait_job` and `JobEvent` can still + // report a hard budget's required/limit or an approval request's limits. + let (outcome, error) = match r { + Err(EngineError::Cancelled) => (JobOutcome::Cancelled, None), + Err(e) => (JobOutcome::Failed(e.to_string()), Some(e)), + Ok(_) if job.ctx.cancelled() => (JobOutcome::Cancelled, None), Ok(payload) => match self.apply_job(&job, apply, payload) { - Ok(v) => JobOutcome::Done(v), - Err(EngineError::Cancelled) => JobOutcome::Cancelled, - Err(e) => JobOutcome::Failed(e.to_string()), + Ok(v) => (JobOutcome::Done(v), None), + Err(EngineError::Cancelled) => (JobOutcome::Cancelled, None), + Err(e) => (JobOutcome::Failed(e.to_string()), Some(e)), }, }; - self.end_job(&job, outcome); + self.end_job_with_error(&job, outcome, error); } fn apply_job(&mut self, job: &Running, apply: Option, payload: Payload) -> Result { @@ -1124,6 +1471,12 @@ impl Session { } fn end_job(&mut self, job: &Running, outcome: JobOutcome) { + self.end_job_with_error(job, outcome, None); + } + + /// Records a finished job's terminal state (done, failed or cancelled) and optional typed + /// error in the recent-job list, invalidating any live preview. + fn end_job_with_error(&mut self, job: &Running, outcome: JobOutcome, error_kind: Option) { // Every terminal path invalidates a preview, including worker errors, cancellation // and discarded results whose document was closed or changed. self.live_commit = None; @@ -1136,6 +1489,7 @@ impl Session { info.state = state; info.result = result; info.error = error; + info.error_kind = error_kind.clone(); if state == "done" { info.progress = 1.0; } @@ -1144,7 +1498,7 @@ impl Session { let extra = self.jobs.recent.len() - RECENT; self.jobs.recent.drain(..extra); } - self.jobs.events.push(JobEvent { id: job.id, command: job.command.clone(), label: job.label.clone(), document: job.doc, outcome }); + self.jobs.events.push(JobEvent { id: job.id, command: job.command.clone(), label: job.label.clone(), document: job.doc, outcome, error: error_kind }); } } diff --git a/crates/engine/src/jobs/tests.rs b/crates/engine/src/jobs/tests.rs index 271162e3c6..38cca3b206 100644 --- a/crates/engine/src/jobs/tests.rs +++ b/crates/engine/src/jobs/tests.rs @@ -814,3 +814,207 @@ fn every_job_terminal_path_drops_a_live_commit_stroke() { assert!(s.live_commit.is_none(), "terminal path {outcome} retained the preview"); } } + +#[cfg(unix)] +fn tmp_dir(name: &str) -> std::path::PathBuf { + let d = std::env::temp_dir().join(format!("photocraft-engine-jobs-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +/// A tiny real PSD fixture, so an admission test never allocates anything near a threshold. +fn tiny_psd() -> Vec { + super::psd_open_fixture::make_psd(false) +} + +#[cfg(target_pointer_width = "64")] +#[test] +fn approved_open_forwards_the_flag_and_the_bound_estimate() { + let gb = 1u64 << 30; + let bytes = Arc::new(tiny_psd()); + // Known 8 GiB: S = 4 GiB, H = 6 GiB. The test charge puts the estimate just over S. + let snapshot = photocraft_io::memory::MemorySnapshot { available_ram: Some(8 * gb), swap_free: None, commit_headroom: None }; + photocraft_io::memory::with_mock_memory(snapshot, || { + photocraft_io::psd_budget::with_test_estimate_charge(4 * gb + 1, || { + let mut s = Session::new(); + let started = s.start_open_for_user_with_background("tiny.psd", OpenSource::Bytes(Arc::clone(&bytes)), false).unwrap(); + let v = match started { + Started::Done(v) => v, + Started::Job(id) => s.wait_job(id).unwrap(), + }; + let id = v["pendingPreflight"].as_u64().unwrap_or_else(|| panic!("expected a memory preflight: {v}")); + assert!(v["estimated"].as_u64().unwrap() > 4 * gb, "the seam's charge is part of the estimate: {v}"); + assert!(s.documents().is_empty()); + // Approving forwards the one-shot flag and estimate through the real import path. + let r = s.execute("file.approveMemory", json!({"id": id, "approve": true, "background": false})).unwrap(); + assert_eq!(r["approved"], json!(true), "{r}"); + assert!(r["result"].get("document").is_some(), "the approved import opened the document: {r}"); + assert_eq!(s.documents().len(), 1); + assert_eq!(s.pending_preflight_bytes().unwrap(), 0, "approval releases the held source bytes"); + }); + }); +} + +#[cfg(target_pointer_width = "64")] +#[test] +fn approval_is_bound_to_the_approved_estimate() { + let gb = 1u64 << 30; + let bytes = Arc::new(tiny_psd()); + let snapshot = photocraft_io::memory::MemorySnapshot { available_ram: Some(8 * gb), swap_free: None, commit_headroom: None }; + photocraft_io::memory::with_mock_memory(snapshot, || { + photocraft_io::psd_budget::with_test_estimate_charge(4 * gb + 1, || { + let mut s = Session::new(); + let source = OpenSource::Bytes(Arc::clone(&bytes)); + let fingerprint = SourceFingerprint::of(&source).unwrap(); + // Consent given for a much smaller estimate does not cover this file. + let err = s + .start_open_approved_with_background("tiny.psd", source, false, Some(1 << 20), Some(fingerprint), false) + .expect_err("a larger estimate needs fresh consent"); + assert!(matches!(&err, EngineError::PsdApprovalRequired { .. }), "got {err:?}"); + assert!(s.documents().is_empty()); + }); + }); +} + +#[cfg(target_pointer_width = "64")] +#[test] +fn unknown_capacity_metadata_never_invents_available_ram() { + let gb = 1u64 << 30; + let bytes = Arc::new(tiny_psd()); + let snapshot = photocraft_io::memory::MemorySnapshot { available_ram: None, swap_free: None, commit_headroom: None }; + photocraft_io::memory::with_mock_memory(snapshot, || { + // Above both the 2 GiB unknown-capacity allowance and the 8 GiB warning threshold. + photocraft_io::psd_budget::with_test_estimate_charge(8 * gb + 1, || { + let mut s = Session::new(); + let started = s.start_open_for_user_with_background("unknown.psd", OpenSource::Bytes(Arc::clone(&bytes)), false).unwrap(); + let v = match started { + Started::Done(v) => v, + Started::Job(id) => s.wait_job(id).unwrap(), + }; + assert!(v["availableRam"].is_null(), "no number is invented for an unmeasured capacity: {v}"); + assert_eq!(v["capacityUnknown"], json!(true), "{v}"); + assert_eq!(v["uncertainCapacityWarning"], json!(true), "{v}"); + let id = v["pendingPreflight"].as_u64().unwrap(); + assert!(s.take_pending_preflight(id).is_some()); + }); + }); +} + +#[test] +fn an_open_reports_a_typed_hard_budget_refusal() { + let gb = 1u64 << 30; + let bytes = Arc::new(tiny_psd()); + // A measured 4 GiB gives a finite hard limit; a charge over it is refused. + let snapshot = photocraft_io::memory::MemorySnapshot { available_ram: Some(4 * gb), swap_free: None, commit_headroom: None }; + let hard = photocraft_io::memory::resolve_budget(snapshot, None).hard_limit; + assert!(hard < u64::MAX, "the test needs a finite hard limit"); + photocraft_io::memory::with_mock_memory(snapshot, || { + photocraft_io::psd_budget::with_test_estimate_charge(hard + 1, || { + let mut s = Session::new(); + let err = s.start_open_for_user_with_background("over.psd", OpenSource::Bytes(Arc::clone(&bytes)), false).unwrap_err(); + match &err { + EngineError::PsdHardBudget { required, limit, .. } => assert!(*required > hard && *limit == hard), + other => panic!("the job must keep the hard-budget fields, got {other:?}"), + } + assert!(s.documents().is_empty()); + }); + }); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_failed_job_keeps_its_typed_error_for_wait_and_events() { + let mut s = Session::new(); + let started = s + .start_job( + "test.hardBudget", + json!({}), + "Test hard budget", + false, + |_ctx| -> Result<()> { Err(EngineError::PsdHardBudget { name: "too-big.psd".into(), required: 9000, limit: 4000 }) }, + |_, _| Ok(Value::Null), + ) + .unwrap(); + let id = job(started); + let err = s.wait_job(id).expect_err("the job fails"); + assert!( + matches!(&err, EngineError::PsdHardBudget { name, required, limit } if name == "too-big.psd" && *required == 9000 && *limit == 4000), + "wait_job must not flatten the typed refusal: {err:?}" + ); + let event = s.poll_jobs().into_iter().find(|e| e.id == id).expect("the job event"); + assert!( + matches!(&event.error, Some(EngineError::PsdHardBudget { required, limit, .. }) if *required == 9000 && *limit == 4000), + "the event carries the typed refusal: {event:?}" + ); +} + +#[cfg(unix)] +#[test] +fn a_replaced_path_is_refused_with_the_source_identity_reason() { + let dir = tmp_dir("replaced"); + let path = dir.join("source.psd"); + let bytes = tiny_psd(); + std::fs::write(&path, &bytes).unwrap(); + let source = OpenSource::Path(path.to_string_lossy().into_owned()); + let fingerprint = SourceFingerprint::of(&source).unwrap(); + // A different inode with identical content and length: only the identity differs. + let replacement = dir.join("replacement.psd"); + std::fs::write(&replacement, &bytes).unwrap(); + std::fs::rename(&replacement, &path).unwrap(); + let mut s = Session::new(); + let err = s + .start_open_approved_with_background("source.psd", source.clone(), false, Some(1024), Some(fingerprint.clone()), false) + .expect_err("the handle is not the approved file"); + assert!(matches!(&err, EngineError::SourceChanged { .. }), "the inline refusal must name the identity, not a parser failure: {err:?}"); + assert!(s.documents().is_empty()); + // The same check on the worker path: the job fails with the identity reason, not a decode error. + let started = s.start_open_approved_with_background("source.psd", source, false, Some(1024), Some(fingerprint), true).unwrap(); + let Started::Job(id) = started else { panic!("expected a background job") }; + let err = s.wait_job(id).expect_err("the worker's handle is not the approved file"); + assert!(matches!(&err, EngineError::SourceChanged { .. }), "the background refusal must name the identity: {err:?}"); + assert!(s.documents().is_empty()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[cfg(unix)] +#[test] +fn a_same_size_rewrite_with_a_restored_mtime_is_refused_with_the_identity_reason() { + let dir = tmp_dir("rewrite"); + let path = dir.join("source.psd"); + let bytes = tiny_psd(); + std::fs::write(&path, &bytes).unwrap(); + let source = OpenSource::Path(path.to_string_lossy().into_owned()); + let fingerprint = SourceFingerprint::of(&source).unwrap(); + let modified = std::fs::metadata(&path).unwrap().modified().unwrap(); + std::thread::sleep(Duration::from_millis(10)); + // Same inode, same length, same bytes, restored modification time: only ctime differs. + std::fs::write(&path, &bytes).unwrap(); + std::fs::OpenOptions::new().write(true).open(&path).unwrap().set_times(std::fs::FileTimes::new().set_modified(modified)).unwrap(); + let mut s = Session::new(); + let err = s + .start_open_approved_with_background("source.psd", source, false, Some(1024), Some(fingerprint), false) + .expect_err("the rewrite is not the file whose estimate was approved"); + assert!(matches!(&err, EngineError::SourceChanged { .. }), "a restored mtime must not hide the rewrite: {err:?}"); + assert!(s.documents().is_empty()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[cfg(unix)] +#[test] +fn unix_fingerprint_detects_a_same_size_rewrite_with_a_restored_mtime() { + let dir = tmp_dir("ctime"); + let path = dir.join("source.psd"); + std::fs::write(&path, b"AAAAAAAAAA").unwrap(); + let before = SourceFingerprint::of(&OpenSource::Path(path.to_string_lossy().into_owned())).unwrap(); + let modified = std::fs::metadata(&path).unwrap().modified().unwrap(); + std::thread::sleep(Duration::from_millis(10)); + std::fs::write(&path, b"BBBBBBBBBB").unwrap(); + std::fs::OpenOptions::new().write(true).open(&path).unwrap().set_times(std::fs::FileTimes::new().set_modified(modified)).unwrap(); + let after = SourceFingerprint::of(&OpenSource::Path(path.to_string_lossy().into_owned())).unwrap(); + let (b, a) = (before.file_identity().unwrap(), after.file_identity().unwrap()); + assert_eq!((b.len, b.modified, b.ino), (a.len, a.modified, a.ino), "same length, modification time and inode"); + assert_ne!((b.ctime_secs, b.ctime_nanos), (a.ctime_secs, a.ctime_nanos), "the Unix identity carries ctime, so a restored mtime cannot hide a rewrite"); + assert_ne!(before, after, "a same-size rewrite with a restored mtime is a different source"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 1b370ace46..65d3eb04ff 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -283,6 +283,8 @@ pub struct Session { /// document, source read-only)`. The shell takes them with [`Session::take_held_open`]. held_opens: Vec<(u64, Document, bool)>, next_held_open: u64, + pub(crate) pending_preflights: Vec, + next_pending_preflight: u64, /// Shared native memory supervision, owned and stopped by the last session using it. scratch_runtime: Option, /// [`photocraft_raster::spill::epoch`] when History's byte limits were last applied: a diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index e58875b959..1c6a7324d6 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -14,6 +14,8 @@ workspace = true corpus = [] # HEIC/HEIF decode (forwarded to photocraft-codecs; see its `heif` feature). heif = ["photocraft-codecs/heif"] +# Test support for synthetic memory injection, estimate charges and verification across crates. +testgen = [] [dependencies] photocraft-geom = { workspace = true } diff --git a/crates/io/src/flat.rs b/crates/io/src/flat.rs index 9863bdf9b0..c7a4101c36 100644 --- a/crates/io/src/flat.rs +++ b/crates/io/src/flat.rs @@ -13,18 +13,62 @@ use crate::{ExportOptions, ExportResult, ImportResult, IoError, TgaBits, XmpEmbe /// Bytes per band when converting or exporting a band of rows at a time. const BAND_BYTES: usize = 32 << 20; +#[cfg(test)] +thread_local! { + /// Called on this thread just before a layered TIFF's composite is decoded. A test proves + /// that admission refused a file without ever reaching that decode. + static TEST_BEFORE_COMPOSITE_DECODE: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; +} + +/// Runs `f` with `hook` called on this thread just before a layered TIFF's composite is decoded. +#[cfg(test)] +pub(crate) fn with_before_composite_decode(hook: std::rc::Rc, f: impl FnOnce() -> R) -> R { + struct Reset(Option>); + impl Drop for Reset { + fn drop(&mut self) { + TEST_BEFORE_COMPOSITE_DECODE.with(|h| *h.borrow_mut() = self.0.take()); + } + } + let prev = TEST_BEFORE_COMPOSITE_DECODE.with(|h| h.borrow_mut().replace(hook)); + let _reset = Reset(prev); + f() +} + +/// Runs the test hook installed by [`with_before_composite_decode`], if any. +#[cfg(test)] +fn before_composite_decode() { + if let Some(hook) = TEST_BEFORE_COMPOSITE_DECODE.with(|h| h.borrow().clone()) { + hook(); + } +} + +/// No-op outside tests: production decodes have no pre-composite hook. +#[cfg(not(test))] +fn before_composite_decode() {} + /// Decodes a flat image into a single-layer document; a TIFF with Photoshop layer data opens /// layered (see [`crate::tiff_layers`]). pub fn import_flat(name: &str, bytes: &[u8]) -> Result { - import_flat_with_limit(name, bytes, crate::DEFAULT_PSD_IMPORT_PIXEL_BYTES) + import_flat_with_options(name, bytes, &crate::ImportOptions::default(), &photocraft_raster::Interrupt::NONE) } -/// [`import_flat`] with the caller's PSD pixel allowance, which a layered TIFF is held to. -pub(crate) fn import_flat_with_limit(name: &str, bytes: &[u8], pixel_limit: u64) -> Result { +/// [`import_flat`] with the user's import settings and the job's cancellation. +/// +/// A layered TIFF's composite, layer and retained-image estimate is admitted through +/// [`crate::memory::evaluate_psd_admission`] with these settings; a zero +/// `psd_max_pixel_bytes` therefore means the adaptive budget, and +/// `psd_high_memory_approved`/`psd_approved_estimate` apply to it like to a PSD. The other flat +/// decoders keep their own limits. +pub(crate) fn import_flat_with_options( + name: &str, + bytes: &[u8], + opts: &crate::ImportOptions, + ctl: &photocraft_raster::Interrupt, +) -> Result { // Detected once; every step below branches on it. let format = codecs::detect(bytes); if format == Some(Format::Tiff) { - return import_tiff_page_with_limit(name, bytes, None, pixel_limit); + return import_tiff_page_with_options(name, bytes, None, opts, ctl); } let img = codecs::decode_as(format.ok_or(codecs::CodecError::UnknownFormat)?, bytes)?; // A palette BMP, PNG or GIF opens in Indexed Color mode with its colour table, as in @@ -234,47 +278,145 @@ pub fn tga_alpha_channel_to_transparency(doc: &mut Document) { /// rows at a time straight into the layer's tiles, so it opens up to 300,000 px a side without /// a second full-size copy (#8169), when the machine has the memory for it (see /// [`crate::memory`]). +/// +/// A layered page is admitted by the adaptive budget like a PSD, with +/// [`crate::ImportOptions`]' defaults: it can be refused with [`IoError::PsdApprovalRequired`] +/// or [`IoError::PsdImportBudget`]. Callers that can ask the user or carry cancellation use +/// [`import_tiff_page_with_options`]. pub fn import_tiff_page(name: &str, bytes: &[u8], page: Option) -> Result { - import_tiff_page_with_limit(name, bytes, page, crate::DEFAULT_PSD_IMPORT_PIXEL_BYTES) + import_tiff_page_with_options(name, bytes, page, &crate::ImportOptions::default(), &photocraft_raster::Interrupt::NONE) } -fn import_tiff_page_with_limit(name: &str, bytes: &[u8], page: Option, pixel_limit: u64) -> Result { +/// [`import_tiff_page`] with the user's import settings and the job's cancellation. +/// +/// A layered page takes the same caller limit and high-memory approval as a PSD +/// (`ImportOptions::psd_*`): its composite, PSD layer model and retained decoded image are +/// estimated from the page's tags and admitted *before* the composite is decoded. A cancelled +/// job stops waiting for the PSD decode gate and between bands. +pub fn import_tiff_page_with_options( + name: &str, + bytes: &[u8], + page: Option, + opts: &crate::ImportOptions, + ctl: &photocraft_raster::Interrupt, +) -> Result { + ctl.check().map_err(|_| IoError::Cancelled)?; let bands = codecs::TiffBands::open(bytes, page, &codecs::Limits::banded())?; - // A page with layers or extra samples (alpha and spot channels) is decoded whole: the layers - // and channels are built from the full image. Only one copy of the layer data is kept through - // that decode. - if bands.meta.photoshop_layers.as_deref().is_some_and(|l| !l.is_empty()) || bands.extra_samples() > 0 { - drop(bands); - return import_tiff_whole(name, bytes, page, pixel_limit); + // Photoshop layer data is decoded whole, so the layers can be built from the complete + // composite; the tags are read (not decoded) first, to admit the import before that decode. + if bands.meta.photoshop_layers.as_deref().is_some_and(|l| !l.is_empty()) { + return import_tiff_layered(name, bytes, page, bands, opts, ctl); } - tiff_to_document(name, bands.upright(), crate::memory::available, BAND_BYTES) + // Extra samples (alpha and spot channels) are only available from a whole-image decode. + if bands.extra_samples() > 0 { + drop(bands); + return import_tiff_with_extras(name, bytes, page, ctl); + } + tiff_to_document(name, bands.upright(), crate::memory::available, BAND_BYTES, ctl) } -/// A layered TIFF, or a flat one with extra samples, decoded whole: the layers are built from the -/// composite, the channels from the extra samples. -fn import_tiff_whole(name: &str, bytes: &[u8], page: Option, pixel_limit: u64) -> Result { +/// A layered TIFF page: its layer tag and resources are read into a plan, the plan's estimate is +/// admitted, and only then is the composite decoded. +/// +/// The admission guard is held across the composite decode and the PSD conversion that follows, +/// so nested decodes spend the same attempt's allowance and nothing here is charged twice. +fn import_tiff_layered( + name: &str, + bytes: &[u8], + page: Option, + bands: codecs::TiffBands<'_>, + opts: &crate::ImportOptions, + ctl: &photocraft_raster::Interrupt, +) -> Result { + let plan = crate::tiff_layers::preflight(&bands)?; + // A file this machine cannot open is refused here, before any composite pixel is decoded, + // and an eligible one rechecks a fresh measurement after the gate. + let _admission = tiff_admission(plan.required, plan.tiles, opts, ctl)?; + drop(bands); + before_composite_decode(); // The orientation is applied after the layer check: rotating the composite but not the // layers would misalign them, so a layered TIFF keeps its stored orientation. let keep = codecs::DecodeOptions { keep_orientation: true, ..Default::default() }; + let (mut img, orientation) = match page { + None => (codecs::decode_with(bytes, &keep)?, codecs::tiff_orientation(bytes)), + Some(p) => (codecs::decode_tiff_page(bytes, p, &keep)?, codecs::tiff_page_orientation(bytes, p)), + }; + // The plan already holds both tags, parsed: a layered page drops the decoder's copies + // instead of keeping two of each through the conversion. A flattened fallback still needs + // the resources for its channels. + if plan.is_layered() { + img.meta.photoshop_layers = None; + img.meta.photoshop_resources = None; + } + ctl.check().map_err(|_| IoError::Cancelled)?; + let mut r = crate::tiff_layers::import_layered(name, &img, plan, ctl)?; + if orientation != 1 { + r.warnings.push("the TIFF's orientation tag was ignored so the layers stay aligned with the image".to_string()); + } + Ok(r) +} + +/// Admits a layered TIFF import for `required` bytes, `spillable` of them tile pixels (see +/// [`crate::memory::evaluate_psd_admission`]), and holds decode admission for it. +/// +/// A nested import of a different file spends the enclosing attempt's remaining allowance: it +/// never resolves a fresh budget, resets the parent or charges the parent's image again. A +/// top-level import is refused before waiting for the gate and rechecked with a fresh +/// measurement once admitted, so a memory drop during the wait is seen before pixels are +/// decoded. Cancellation is checked before an allowance is consumed, so a cancelled nested +/// import never spends its parent's budget. +fn tiff_admission( + required: u64, + spillable: u64, + opts: &crate::ImportOptions, + ctl: &photocraft_raster::Interrupt, +) -> Result { + let caller_limit = opts.psd_max_pixel_bytes; + let admit = |snapshot: crate::memory::MemorySnapshot| { + crate::memory::evaluate_psd_admission(required, spillable, caller_limit, opts.psd_high_memory_approved, opts.psd_approved_estimate, snapshot) + }; + if crate::psd_gate::is_holding_admission() { + // A nested, independent TIFF: the same-file continuation never gets here, because + // `import_tiff_layered` admits once and `import_layered` does not admit again. It spends + // the enclosing attempt's remaining allowance, and the caller's explicit bounds still + // apply before that charge (a refused nested import leaves the parent untouched). + ctl.check().map_err(|_| IoError::Cancelled)?; + crate::memory::nested_import_local_bound(required, caller_limit, opts.psd_approved_estimate)?; + let guard = crate::psd_gate::acquire_decode_admission(ctl)?; + crate::psd_gate::consume_attempt_allowance(required)?; + return Ok(guard); + } + admit(crate::memory::MemorySnapshot::current())?; + let guard = crate::psd_gate::acquire_decode_admission(ctl)?; + let outcome = admit(crate::memory::MemorySnapshot::current())?; + crate::psd_gate::set_active_attempt_budget(outcome.authorized_total.saturating_sub(required)); + Ok(guard) +} + +/// A flat TIFF page with extra samples, decoded whole: the composite becomes the layer, the +/// extra samples its channels. +fn import_tiff_with_extras(name: &str, bytes: &[u8], page: Option, ctl: &photocraft_raster::Interrupt) -> Result { + ctl.check().map_err(|_| IoError::Cancelled)?; + let keep = codecs::DecodeOptions { keep_orientation: true, ..Default::default() }; let (img, orientation) = match page { None => (codecs::decode_with(bytes, &keep)?, codecs::tiff_orientation(bytes)), Some(p) => (codecs::decode_tiff_page(bytes, p, &keep)?, codecs::tiff_page_orientation(bytes, p)), }; - if let Some(layers) = img.meta.photoshop_layers.as_deref().filter(|l| !l.is_empty()) { - let mut r = crate::tiff_layers::import_layered(name, &img, layers, pixel_limit)?; - if orientation != 1 { - r.warnings.push("the TIFF's orientation tag was ignored so the layers stay aligned with the image".to_string()); - } - return Ok(r); - } + ctl.check().map_err(|_| IoError::Cancelled)?; image_to_document(name, &img.oriented(orientation)?) } /// A flat TIFF page as a single-layer document, decoded a group of rows at a time into the /// layer's tiles: only one group exists beside the document. `available`: the memory this /// process can still use (see [`crate::memory::available`]); `budget`: the source bytes per core -/// converted at a time ([`BAND_BYTES`]). -fn tiff_to_document(name: &str, mut bands: codecs::TiffBands<'_>, available: impl FnOnce() -> Option, budget: usize) -> Result { +/// converted at a time ([`BAND_BYTES`]); `ctl`: the job's cancellation, checked per group. +fn tiff_to_document( + name: &str, + mut bands: codecs::TiffBands<'_>, + available: impl FnOnce() -> Option, + budget: usize, + ctl: &photocraft_raster::Interrupt, +) -> Result { let (w, h) = bands.dimensions(); let (layout, sample) = (bands.layout(), bands.sample_type()); let f = document_format(layout, sample); @@ -284,11 +426,13 @@ fn tiff_to_document(name: &str, mut bands: codecs::TiffBands<'_>, available: imp // The layer's tiles, plus a group as decoded, turned upright, converted and read into a // worker's scratch buffer. Linux overcommits, so the tiles below are allocated even when // they can't be backed, and writing them would have the process killed: refuse first. - let tiles = |n: u32| u64::from(n).div_ceil(TILE_SIZE as u64).saturating_mul(TILE_SIZE as u64); - let layer = tiles(w).saturating_mul(tiles(h)).saturating_mul(bpp); let group = bands.group_bytes()? as u64; let group_px = group / (layout.channels() as u64 * sample.bytes() as u64).max(1); - let needed = layer.saturating_add(group.saturating_mul(3)).saturating_add(group_px.saturating_mul(bpp)); + let surface = surface_bytes(w, h, fmt); + let needed = surface.saturating_add(group.saturating_mul(3)).saturating_add(group_px.saturating_mul(bpp)); + // The layer is streamed into tiles a group at a time, so while the scratch disk is + // spilling the tiles it has room for need no RAM; the groups always do. + let needed = needed.saturating_sub(crate::memory::scratch_credit(surface)); crate::memory::check_fits(w, h, needed, available())?; } let mut s = Surface::new(fmt); @@ -297,6 +441,7 @@ fn tiff_to_document(name: &str, mut bands: codecs::TiffBands<'_>, available: imp IoError::Unsupported(format!("not enough memory to open this {w} × {h} px image: it needs about {gb:.1} GB ({e})")) }; bands.decode(|x, y, group: &Image| -> Result<(), IoError> { + ctl.check().map_err(|_| IoError::Cancelled)?; let (gw, gh) = group.dimensions(); let (x, y) = (x as i32, y as i32); let rect = |rows: &std::ops::Range| Rect::new(x, y + rows.start as i32, x.saturating_add(gw as i32), y + rows.end as i32); @@ -326,6 +471,40 @@ fn tiff_to_document(name: &str, mut bands: codecs::TiffBands<'_>, available: imp Ok(single_layer_document(name, (w, h), f, layout.has_alpha(), s, bands.icc.take(), meta, warnings)) } +/// Bytes a `w` × `h` px document surface of `fmt` allocates: whole tiles, including the padding +/// of a partly covered edge tile, as [`Surface`] holds them. +fn surface_bytes(w: u32, h: u32, fmt: PixelFormat) -> u64 { + let tiles = |n: u32| u64::from(n).div_ceil(TILE_SIZE as u64).saturating_mul(TILE_SIZE as u64); + tiles(w).saturating_mul(tiles(h)).saturating_mul(fmt.bytes_per_pixel() as u64) +} + +/// Bytes a flat page that is decoded whole needs: the decoded image and its extra-sample planes, +/// the band buffers [`image_surface`] converts through when the document format differs from the +/// page's, the layer's tiles and, per extra sample, its channel's tiles and its copied plane. +/// +/// A TIFF whose Photoshop layer tag cannot be read still opens its composite flattened; this +/// bounds that whole-image decode and its conversion before anything is allocated. +/// +/// Every term saturates instead of wrapping: an estimate that overflows `u64` is the +/// `u64::MAX` sentinel, which admission always refuses (see +/// [`crate::memory::MemoryBudget::decide`]) rather than admitting a wrapped-around value. +pub(crate) fn flattened_import_bytes(w: u32, h: u32, layout: ChannelLayout, sample: CSample, extras: usize, scratch: u64) -> u64 { + let f = document_format(layout, sample); + let fmt = PixelFormat::new(f.mode, f.depth, true); + let pixels = u64::from(w).saturating_mul(u64::from(h)); + let in_bps = sample.bytes() as u64; + let out_bps = f.sample.bytes() as u64; + let e = extras as u64; + let decoded = pixels.saturating_mul((layout.channels() as u64).saturating_add(e.saturating_mul(2))).saturating_mul(in_bps); + // A band of rows is copied, normalized to 32-bit floats and converted; a few bands' worth + // are live at once and the scratch pool reuses the rest within its own budget. + let convert = if layout == f.layout && sample == f.sample { 0 } else { (BAND_BYTES as u64).saturating_mul(16) }; + let layer = surface_bytes(w, h, fmt); + let channel = surface_bytes(w, h, PixelFormat::new(ColorMode::Grayscale, f.depth, false)); + let channels = e.saturating_mul(channel.saturating_add(pixels.saturating_mul(out_bps))); + layer.saturating_add(decoded).saturating_add(convert).saturating_add(channels).saturating_add(scratch) +} + /// Whether a `w` × `h` flat TIFF is checked against free memory before it opens: only the sizes /// the whole-image decode refused, which only the banded decode opens. Every image that opened /// before opens as it did, also on a small machine or in a container whose page cache fills. @@ -1395,7 +1574,7 @@ mod tiff_banded_tests { let img = Image::from_raw(64, 64, ChannelLayout::Rgb, CSample::U8, vec![77; 64 * 64 * 3]).unwrap(); let bytes = codecs::encode(&img, Format::Tiff, &codecs::EncodeOptions::default()).unwrap(); let bands = codecs::TiffBands::open(&bytes, None, &codecs::Limits::banded()).unwrap(); - let r = tiff_to_document("small.tif", bands.upright(), || Some(0), BAND_BYTES).unwrap(); + let r = tiff_to_document("small.tif", bands.upright(), || Some(0), BAND_BYTES, &photocraft_raster::Interrupt::NONE).unwrap(); assert_eq!((r.document.size.width, r.document.size.height), (64, 64)); } @@ -1411,7 +1590,7 @@ mod tiff_banded_tests { let bytes = codecs::encode(&img, Format::Tiff, &codecs::EncodeOptions::default()).unwrap(); let bands = codecs::TiffBands::open(&bytes, None, &codecs::Limits::banded()).unwrap(); let row = w as usize * layout.channels() * sample.bytes(); - let r = tiff_to_document("rounds.tif", bands, || None, 3 * row).unwrap(); + let r = tiff_to_document("rounds.tif", bands, || None, 3 * row, &photocraft_raster::Interrupt::NONE).unwrap(); let f = document_format(layout, sample); let want = codecs::decode(&bytes).unwrap().convert(f.layout, f.sample); let LayerContent::Raster(s) = &r.document.layers[0].content else { panic!("not a raster layer") }; @@ -1657,4 +1836,71 @@ mod streamed_png_tests { assert!(streams_png(&doc(8000, 6000, SampleType::U16))); assert!(streams_png(&doc(117_504, 22_464, SampleType::U8))); } + + /// A cancelled nested TIFF import never spends its parent's remaining allowance: the + /// cancellation check comes before the charge, and the reentrant guard is taken first. + #[test] + fn a_cancelled_nested_tiff_admission_leaves_the_parent_allowance_untouched() { + let _parent = crate::psd_gate::acquire_decode_admission(&Interrupt::NONE).expect("parent admission"); + crate::psd_gate::set_active_attempt_budget(1000); + let yes = || true; + let cancelled = Interrupt::cancel_only(&yes); + match tiff_admission(100, 0, &crate::ImportOptions::default(), &cancelled) { + Err(IoError::Cancelled) => {} + other => panic!("expected a cancelled nested admission, got {:?}", other.map(|_| ())), + } + assert_eq!(crate::psd_gate::active_attempt_remaining(), Some(1000), "a cancelled nested import must not consume the parent's budget"); + } + + /// A nested TIFF import still enforces the caller's explicit bounds, before the parent's + /// allowance is charged; one within those bounds is charged exactly once. + #[test] + fn nested_tiff_admission_enforces_the_callers_local_bounds_before_charging_the_parent() { + let ctl = Interrupt::NONE; + let _parent = crate::psd_gate::acquire_decode_admission(&ctl).expect("parent admission"); + let ample = 1000u64; + crate::psd_gate::set_active_attempt_budget(ample); + + let lowered = crate::ImportOptions { psd_max_pixel_bytes: 99, ..Default::default() }; + match tiff_admission(100, 0, &lowered, &ctl) { + Err(IoError::PsdImportBudget { required, limit }) => assert_eq!((required, limit), (100, 99)), + other => panic!("expected the caller's limit to refuse, got {:?}", other.map(|_| ())), + } + assert_eq!(crate::psd_gate::active_attempt_remaining(), Some(ample), "a refused nested import leaves the parent's allowance untouched"); + + let stale = crate::ImportOptions { psd_high_memory_approved: true, psd_approved_estimate: Some(99), ..Default::default() }; + match tiff_admission(100, 0, &stale, &ctl) { + Err(IoError::PsdImportBudget { required, limit }) => assert_eq!((required, limit), (100, 99)), + other => panic!("expected the approved estimate bound to refuse, got {:?}", other.map(|_| ())), + } + assert_eq!(crate::psd_gate::active_attempt_remaining(), Some(ample), "a refused nested import leaves the parent's allowance untouched"); + + let allowed = crate::ImportOptions { psd_max_pixel_bytes: 100, psd_high_memory_approved: true, psd_approved_estimate: Some(100), ..Default::default() }; + let guard = tiff_admission(100, 0, &allowed, &ctl).expect("within the caller's bounds"); + assert_eq!(crate::psd_gate::active_attempt_remaining(), Some(ample - 100), "the nested import is charged once"); + drop(guard); + assert_eq!(crate::psd_gate::active_attempt_remaining(), Some(ample - 100), "releasing the nested guard neither refunds nor resets the parent"); + } + + /// A layered TIFF estimate that overflowed `u64` saturates at `u64::MAX`. Unknown native + /// memory has `u64::MAX` as its hard limit, so approval used to admit the sentinel; it is + /// refused before the gate and before any composite is decoded. + #[test] + fn a_saturated_tiff_estimate_is_refused_before_any_decode() { + if cfg!(target_pointer_width = "32") { + return; + } + crate::memory::with_mock_memory(crate::memory::MemorySnapshot::UNKNOWN, || { + for opts in [ + crate::ImportOptions::default(), + crate::ImportOptions { psd_high_memory_approved: true, ..Default::default() }, + crate::ImportOptions { psd_high_memory_approved: true, psd_approved_estimate: Some(u64::MAX), ..Default::default() }, + ] { + match tiff_admission(u64::MAX, 0, &opts, &Interrupt::NONE) { + Err(IoError::PsdImportBudget { required, limit }) => assert_eq!((required, limit), (u64::MAX, u64::MAX)), + other => panic!("expected a hard refusal for {opts:?}, got {:?}", other.map(|_| ())), + } + } + }); + } } diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 2d4371d4c1..f7d2881e4d 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -66,10 +66,11 @@ pub mod pdf; mod pdn; pub use pcraft_cache::PcraftExportCache; pub mod pixels; -mod psd_budget; +pub mod psd_budget; mod psd_export; +mod psd_gate; mod psd_import; -pub use psd_budget::DEFAULT_PSD_IMPORT_PIXEL_BYTES; +pub use psd_budget::{DEFAULT_PSD_IMPORT_PIXEL_BYTES, PsdMemoryEstimate, estimate as estimate_psd_memory}; pub mod psd_thumbnail; pub mod raw; pub mod slices_map; @@ -90,8 +91,8 @@ use photocraft_psd::{PsdError, PsdFile}; pub use adjust_map::ADJUSTMENT_KEYS; pub use flat::{ - DEFAULT_LOSSY_WEBP_QUALITY, apply_file_encoding, document_to_image, file_encoding, import_gif_frames, import_tiff_page, import_webp_frames, - tga_alpha_channel_to_transparency, tga_default_bits, + DEFAULT_LOSSY_WEBP_QUALITY, apply_file_encoding, document_to_image, file_encoding, import_gif_frames, import_tiff_page, import_tiff_page_with_options, + import_webp_frames, tga_alpha_channel_to_transparency, tga_default_bits, }; pub use psd_export::{PsdExportOptions, document_to_psd, document_to_psd_with}; pub use psd_import::{psd_to_document, psd_to_document_with}; @@ -117,6 +118,16 @@ pub enum IoError { /// The conservative PSD pixel-storage and workspace estimate exceeded its allowance. #[error("PSD import needs an estimated {required} bytes of pixel memory; limit is {limit} bytes")] PsdImportBudget { required: u64, limit: u64 }, + /// PSD pixel-storage estimate exceeds the automatic soft limit, but is within the hard limit. + /// Explicit approval is required to proceed. + #[error( + "PSD import needs an estimated {required} bytes of pixel memory (soft limit {soft_limit} bytes, hard limit {hard_limit} bytes); explicit approval required" + )] + PsdApprovalRequired { required: u64, soft_limit: u64, hard_limit: u64, available_ram: Option }, + /// The file behind the opened handle is not the one whose memory estimate was approved: it + /// was replaced, rewritten or resized since it was checked. Nothing was decoded. + #[error("the file changed since it was checked; approve it again to open the new file")] + SourceChanged, /// A pixel buffer could not be allocated while reading a file: the file may be fine, but /// this machine has no memory for it. #[error("not enough memory: {0}")] @@ -161,6 +172,72 @@ pub struct ImportResult { pub preview_only: bool, } +/// Identity of the file behind an opened handle, read from that handle. +/// +/// A one-shot high-memory approval is bound to a file, not to a path: the importer opens the +/// path once, takes this identity from the handle and refuses to decode unless it is the file the +/// estimate was approved for (`import_file_for_open_verified`). The Unix form includes the +/// device, inode, modification time and change time with nanoseconds, so a same-size rewrite +/// cannot hide behind a restored modification timestamp. The identity fails closed when any of +/// these cannot be read (see [`Self::of_handle`]). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct FileIdentity { + /// File length in bytes. + pub len: u64, + /// Last modification time. + pub modified: std::time::SystemTime, + /// Device holding the file (Unix). + #[cfg(unix)] + pub dev: u64, + /// Inode of the file (Unix). + #[cfg(unix)] + pub ino: u64, + /// Inode change time, seconds since the Unix epoch (Unix). + #[cfg(unix)] + pub ctime_secs: i64, + /// Nanosecond part of [`Self::ctime_secs`] (Unix). + #[cfg(unix)] + pub ctime_nanos: i64, +} + +impl FileIdentity { + /// Identity of an open file handle. + /// + /// Reads the handle's own metadata, never the path, so replacing the path cannot change what + /// this describes. A metadata field that cannot be read is an error: callers must fail closed + /// rather than decode under an approval they cannot verify. + pub fn of_handle(file: &std::fs::File) -> std::io::Result { + Self::of_metadata(&file.metadata()?) + } + + /// Identity of the file currently at `path`. + /// + /// For discovery only (a fingerprint kept while an estimate is made). The decode path must + /// open the file and compare the identity of that handle, since the path can change between + /// this call and the open. + pub fn of_path(path: &std::path::Path) -> std::io::Result { + Self::of_metadata(&std::fs::metadata(path)?) + } + + /// Builds an identity from metadata already read from an open handle or path. + /// + /// Unix adds the device, inode and inode-change time so a same-size rewrite with a restored + /// modification time is still detected; other platforms compare length and modification time. + fn of_metadata(metadata: &std::fs::Metadata) -> std::io::Result { + let len = metadata.len(); + let modified = metadata.modified()?; + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + Ok(Self { len, modified, dev: metadata.dev(), ino: metadata.ino(), ctime_secs: metadata.ctime(), ctime_nanos: metadata.ctime_nsec() }) + } + #[cfg(not(unix))] + { + Ok(Self { len, modified }) + } + } +} + /// The import note for a file whose horizontal and vertical resolutions (`x`, `y`, in pixels per /// inch) differ: a document has one resolution, so it keeps the horizontal one and saves it on /// both axes (#1018). Differences under 0.01 ppi are below what the warning can show. @@ -418,9 +495,16 @@ pub struct ImportOptions { pub max_group_depth: usize, /// The demosaic method camera raws are developed with. pub demosaic: raw::Demosaic, - /// PSD layer/mask/merged pixel allowance, including conversion workspace. May lower the - /// default cap; does not cover metadata or smart-filter caches. + /// PSD layer/mask/merged pixel allowance, including conversion workspace, and the + /// equivalent allowance for a layered TIFF's composite and retained decoded image. May + /// lower the default cap; 0 uses the adaptive budget. Does not cover metadata or + /// smart-filter caches. pub psd_max_pixel_bytes: u64, + /// Explicit one-shot authorization for imports that exceed the soft budget but fit within the hard budget. + pub psd_high_memory_approved: bool, + /// Optional estimate limit for high-memory approval. When set, approval only applies if + /// the fresh preflight estimate does not exceed this amount. + pub psd_approved_estimate: Option, } impl Default for ImportOptions { @@ -428,7 +512,9 @@ impl Default for ImportOptions { ImportOptions { max_group_depth: photocraft_doc::MAX_GROUP_DEPTH, demosaic: raw::Demosaic::default(), - psd_max_pixel_bytes: DEFAULT_PSD_IMPORT_PIXEL_BYTES, + psd_max_pixel_bytes: 0, + psd_high_memory_approved: false, + psd_approved_estimate: None, } } } @@ -476,29 +562,83 @@ fn import_psd( name: &str, ctl: &photocraft_raster::Interrupt, damaged: &mut bool, - pixel_limit: u64, + opts: &ImportOptions, parse: impl FnOnce( &dyn Fn(&PsdFile) -> photocraft_psd::Result, &dyn Fn(&PsdFile) -> bool, ) -> photocraft_psd::Result<(PsdFile, Option>>)>, ) -> Result { - // A merged image the import reads is decoded with the parse: a ZIP one is inflated once. - // A failed read of the file (one parsed from its source) is a read error, as reading the - // whole file first would report it. let preflight_error = std::cell::RefCell::new(None); + let admission_guard: std::cell::RefCell> = std::cell::RefCell::new(None); + let parsed = parse( &|file| { // Only an import that keeps the layer tree is bound by the group nesting cap. let depth = if psd_import::can_recover_layers(file) { psd_import::check_group_depth(file) } else { Ok(()) }; - let checked = depth.and_then(|()| psd_budget::check(file, pixel_limit)); - if let Err(error) = checked { - *preflight_error.borrow_mut() = Some(error); - return Err(PsdError::LimitExceeded("PSD import preflight refused the file")); + let preflight_check: Result = (|| { + depth?; + let est = psd_budget::estimate(file)?; + + if psd_gate::is_holding_admission() { + // Nested import: it spends the enclosing attempt's remaining allowance and + // never resets or re-charges the parent. Cancellation is checked before the + // charge, and admission is reentrant here, so a cancelled or refused nested + // import leaves the parent's allowance untouched. The caller's explicit + // bounds (a lower allowance and a one-shot estimate) still apply before the + // parent is charged. + ctl.check().map_err(|_| IoError::Cancelled)?; + memory::nested_import_local_bound(est.total_bytes, opts.psd_max_pixel_bytes, opts.psd_approved_estimate)?; + let guard = psd_gate::acquire_decode_admission(ctl)?; + psd_gate::consume_attempt_allowance(est.total_bytes)?; + *admission_guard.borrow_mut() = Some(guard); + return Ok(psd_import::merged_needed(file)); + } + + // 1. Initial admission check BEFORE waiting on or acquiring the gate. + // Invalid or unapproved files fail fast without blocking other decodes or acquiring gate. + memory::evaluate_psd_admission( + est.total_bytes, + est.tile_bytes, + opts.psd_max_pixel_bytes, + opts.psd_high_memory_approved, + opts.psd_approved_estimate, + memory::MemorySnapshot::current(), + )?; + + // 2. Cancellation-aware gate acquisition BEFORE any merged or layer pixel decoding/inflation. + let guard = psd_gate::acquire_decode_admission(ctl)?; + + // 3. Re-evaluate adaptive budget immediately after gate acquisition. + // If available memory dropped while waiting for gate, this returns Err, + // guard is dropped (releasing gate immediately), and error is returned before prompting. + let outcome = memory::evaluate_psd_admission( + est.total_bytes, + est.tile_bytes, + opts.psd_max_pixel_bytes, + opts.psd_high_memory_approved, + opts.psd_approved_estimate, + memory::MemorySnapshot::current(), + )?; + + // Initialize enclosing attempt allowance for any nested decodes. + psd_gate::set_active_attempt_budget(outcome.authorized_total.saturating_sub(est.total_bytes)); + + // Retain guard across parse and conversion + *admission_guard.borrow_mut() = Some(guard); + Ok(psd_import::merged_needed(file)) + })(); + + match preflight_check { + Ok(want_merged) => Ok(want_merged), + Err(error) => { + *preflight_error.borrow_mut() = Some(error); + Err(PsdError::LimitExceeded("PSD import preflight refused the file")) + } } - Ok(psd_import::merged_needed(file)) }, &psd_import::can_recover_layers, ); + if let Some(error) = preflight_error.into_inner() { return Err(error); } @@ -509,6 +649,7 @@ fn import_psd( })?; ctl.check().map_err(|_| IoError::Cancelled)?; ctl.progress(0.05); + // Read before the conversion, which moves the global blocks into the document. let txt2 = file.global_blocks.iter().find(|b| &b.key == b"Txt2").and_then(|b| photocraft_text::psd::parse_txt2(&b.data)); let (mut document, warnings, psd_damaged, fatal_error) = psd_import::psd_to_document_owned(file, ctl, merged).ok_or(IoError::Cancelled)?; @@ -535,54 +676,126 @@ pub fn import_file_for_open_with( path: &std::path::Path, opts: &ImportOptions, ctl: &photocraft_raster::Interrupt, +) -> Result<(ImportResult, bool), IoError> { + let mut identity = None; + import_file_for_open_verified(name, path, None, opts, ctl, &mut identity) +} + +/// [`import_file_for_open_with`] bound to the identity of the file handle it decodes. +/// +/// The path is opened exactly once. `identity_out` is set from that handle before any pixel is +/// read; a PSD/PSB is then streamed from the same handle (not read whole), anything else is read +/// from it within `photocraft_format::MAX_OPEN_BYTES`. When `expected` is given, the import +/// refuses with [`IoError::SourceChanged`] unless the opened file is that one. When the parse +/// stops for a high-memory approval, the identity is read again from a duplicate of the same +/// handle: a file rewritten in place while its estimate was checked is refused, so the approval +/// always refers to the bytes that will be decoded. +/// +/// A missing or unreadable metadata field fails the open instead of decoding under an identity +/// that cannot be verified. +#[cfg(any(unix, windows))] +pub fn import_file_for_open_verified( + name: &str, + path: &std::path::Path, + expected: Option<&FileIdentity>, + opts: &ImportOptions, + ctl: &photocraft_raster::Interrupt, + identity_out: &mut Option, ) -> Result<(ImportResult, bool), IoError> { let read_failed = |e: std::io::Error| IoError::Read(format!("{}: {e}", path.display())); ctl.check().map_err(|_| IoError::Cancelled)?; let source = photocraft_psd::FileSource::open(path).map_err(read_failed)?; + let metadata = source.file().metadata().map_err(read_failed)?; + if !metadata.is_file() { + return Err(IoError::Read(format!("{}: not a regular file", path.display()))); + } + let identity = FileIdentity::of_metadata(&metadata).map_err(read_failed)?; + *identity_out = Some(identity.clone()); + if expected.is_some_and(|expected| expected != &identity) { + return Err(IoError::SourceChanged); + } + // A duplicate of the same open file (not a fresh path lookup): the approval pause re-reads + // the identity from it after parsing, and never from a path that may point elsewhere now. + let watch = source.file().try_clone().map_err(read_failed)?; let mut magic = [0u8; 4]; let psd = !has_extension(name, photocraft_format::EXTENSION) && photocraft_psd::ReadAt::read_at(&source, 0, &mut magic).is_ok() && is_psd(&magic); - if !psd { - drop(source); + let result = if psd { + import_source_with_options(name, photocraft_psd::Source::new(source), ctl, opts) + } else { + // Read from the handle that was just identified, not by opening the path again. + let mut file = source.file(); + // Windows seek_read advances this handle during the format probe. + // Rewind the same verified handle before reading a non-PSD file. + std::io::Seek::rewind(&mut file).map_err(read_failed)?; // A flat scanline EXR is decoded block by block straight into tiles; other EXR // layouts, and EXR headers the band decoder refuses, are read whole below. + let mut streamed = None; if !has_extension(name, photocraft_format::EXTENSION) && photocraft_codecs::detect(&magic) == Some(photocraft_codecs::Format::OpenExr) { let before = photocraft_raster::spill::read_error_generation(); - let mut file = std::fs::File::open(path).map_err(read_failed)?; - let original = file.metadata().map_err(read_failed)?; if let Some(mut result) = exr_native::import(&mut file, ctl)? { - let current = std::fs::metadata(path).map_err(read_failed)?; - if current.len() != original.len() || current.modified().ok() != original.modified().ok() { + // A rewrite in place while the blocks were read must not become the document. + if FileIdentity::of_handle(&watch).map_err(read_failed)? != identity { return Err(IoError::Read(format!("{}: the file changed while it was being opened; open it again", path.display()))); } photocraft_raster::spill::check_since(before).map_err(IoError::Read)?; ctl.check().map_err(|_| IoError::Cancelled)?; result.document.name = name.to_string(); - return Ok((result, false)); + streamed = Some(result); + } else { + std::io::Seek::rewind(&mut file).map_err(read_failed)?; } } - let bytes = photocraft_format::read_file(path).map_err(read_failed)?; - return import_for_open_with(name, &bytes, opts, ctl); + match streamed { + Some(result) => Ok((result, false)), + None => { + let bytes = photocraft_format::read::read_all(&mut file, photocraft_psd::ReadAt::len(&source)).map_err(read_failed)?; + import_for_open_with(name, &bytes, opts, ctl) + } + } + }; + // An approval pause must describe a file that still has the identity it was estimated with; + // an approved resume must have decoded that file, not a rewrite that raced the decode. + if expected.is_some() || matches!(&result, Err(IoError::PsdApprovalRequired { .. })) { + let after = FileIdentity::of_handle(&watch).map_err(read_failed)?; + if after != identity { + return Err(IoError::SourceChanged); + } + *identity_out = Some(after); } - import_source_with_limit(name, photocraft_psd::Source::new(source), ctl, opts.psd_max_pixel_bytes.min(DEFAULT_PSD_IMPORT_PIXEL_BYTES)) + result } /// [`import_file_for_open_with`] for a PSD/PSB in any [`photocraft_psd::ReadAt`] source. pub fn import_source_for_open_with(name: &str, source: photocraft_psd::Source, ctl: &photocraft_raster::Interrupt) -> Result<(ImportResult, bool), IoError> { - import_source_with_limit(name, source, ctl, DEFAULT_PSD_IMPORT_PIXEL_BYTES) + import_source_with_options(name, source, ctl, &ImportOptions::default()) } -fn import_source_with_limit( +/// [`import_source_for_open_with`] with custom import options. +pub fn import_source_with_options( + name: &str, + source: photocraft_psd::Source, + ctl: &photocraft_raster::Interrupt, + opts: &ImportOptions, +) -> Result<(ImportResult, bool), IoError> { + ctl.check().map_err(|_| IoError::Cancelled)?; + let mut damaged = false; + let r = import_psd(name, ctl, &mut damaged, opts, |want, recover| PsdFile::from_source_and_merged_preflight(source, want, recover))?; + ctl.check().map_err(|_| IoError::Cancelled)?; + ctl.progress(1.0); + Ok((r, damaged)) +} + +/// [`import_source_with_options`] with an explicit PSD pixel limit, for tests that exercise +/// admission without the default allowance. +#[cfg(test)] +pub(crate) fn import_source_with_limit( name: &str, source: photocraft_psd::Source, ctl: &photocraft_raster::Interrupt, pixel_limit: u64, ) -> Result<(ImportResult, bool), IoError> { - ctl.check().map_err(|_| IoError::Cancelled)?; - let mut damaged = false; - let r = import_psd(name, ctl, &mut damaged, pixel_limit, |want, recover| PsdFile::from_source_and_merged_preflight(source, want, recover))?; - ctl.check().map_err(|_| IoError::Cancelled)?; - ctl.progress(1.0); - Ok((r, damaged)) + let opts = ImportOptions { psd_max_pixel_bytes: pixel_limit, ..Default::default() }; + import_source_with_options(name, source, ctl, &opts) } /// [`import_file_for_open_with`] without the damage flag. @@ -602,9 +815,7 @@ fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, o // Magic first: an Affinity file renamed .psd is still Affinity (#5258 corpus // preview_never_saves_back_to_its_native_or_renamed_source). if is_psd(bytes) { - return import_psd(name, ctl, damaged, opts.psd_max_pixel_bytes.min(DEFAULT_PSD_IMPORT_PIXEL_BYTES), |want, recover| { - PsdFile::from_bytes_and_merged_preflight(bytes, want, recover) - }); + return import_psd(name, ctl, damaged, opts, |want, recover| PsdFile::from_bytes_and_merged_preflight(bytes, want, recover)); } if affinity::is_affinity(bytes) || affinity::has_extension(name) { return affinity::import(name, bytes); @@ -637,11 +848,9 @@ fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, o // A `.psd`/`.psb`/`.psdt` with no raster signature keeps the PSD error instead of // `codec: unrecognized image format` (#5258). Magic already returned above. if is_psd_input(name, bytes) { - return import_psd(name, ctl, damaged, opts.psd_max_pixel_bytes.min(DEFAULT_PSD_IMPORT_PIXEL_BYTES), |want, recover| { - PsdFile::from_bytes_and_merged_preflight(bytes, want, recover) - }); + return import_psd(name, ctl, damaged, opts, |want, recover| PsdFile::from_bytes_and_merged_preflight(bytes, want, recover)); } - flat::import_flat_with_limit(name, bytes, opts.psd_max_pixel_bytes.min(DEFAULT_PSD_IMPORT_PIXEL_BYTES)) + flat::import_flat_with_options(name, bytes, opts, ctl) } /// Extension names can be wrong (for example, an image downloaded as WebP and renamed `.svg`). @@ -998,6 +1207,53 @@ mod tests { assert!(!result.source_read_only); } + /// A nested PSD import still enforces the caller's explicit bounds before it spends the + /// parent's allowance, and one within those bounds is charged exactly once. + #[cfg(not(any(target_arch = "wasm32", target_pointer_width = "32")))] + #[test] + fn nested_psd_import_enforces_the_callers_local_bounds_before_charging_the_parent() { + let gb = 1u64 << 30; + let bytes = testgen::small(Version::Psd, Compression::Raw).to_bytes().unwrap(); + let ctl = photocraft_raster::Interrupt::NONE; + let ample = 16 * gb; + let _parent = super::psd_gate::acquire_decode_admission(&ctl).expect("parent admission"); + + // The tiny fixture plus a thread-local charge lands in the approval band; nothing near a + // gigabyte is allocated. + super::psd_budget::with_test_estimate_charge(5 * gb, || { + // What the real nested import is charged, learned from one admitted run. + super::psd_gate::set_active_attempt_budget(ample); + super::import_with_options_and_interrupt("nested.psd", &bytes, &ImportOptions::default(), &ctl).expect("an admitted nested import"); + let required = ample - super::psd_gate::active_attempt_remaining().expect("the parent attempt keeps an allowance"); + assert!(required > 5 * gb, "the test charge is part of the estimate: {required}"); + + let cases = [ + (ImportOptions { psd_max_pixel_bytes: required - 1, ..Default::default() }, "the caller's lower allowance"), + ( + ImportOptions { psd_high_memory_approved: true, psd_approved_estimate: Some(required - 1), ..Default::default() }, + "the one-shot approved estimate", + ), + ]; + for (opts, what) in cases { + super::psd_gate::set_active_attempt_budget(ample); + match super::import_with_options_and_interrupt("nested.psd", &bytes, &opts, &ctl) { + Err(super::IoError::PsdImportBudget { required: r, limit }) => { + assert_eq!((r, limit), (required, required - 1), "{what} must refuse with its exact fields") + } + other => panic!("expected {what} to refuse, got {:?}", other.map(|_| ())), + } + assert_eq!(super::psd_gate::active_attempt_remaining(), Some(ample), "{what} must not spend the parent's allowance"); + } + + super::psd_gate::set_active_attempt_budget(ample); + let bounded = + ImportOptions { psd_max_pixel_bytes: required, psd_high_memory_approved: true, psd_approved_estimate: Some(required), ..Default::default() }; + let opened = super::import_with_options_and_interrupt("nested.psd", &bytes, &bounded, &ctl).expect("within the caller's bounds"); + assert!(opened.document.size.area() > 0, "the bounded nested import really opened a document"); + assert_eq!(super::psd_gate::active_attempt_remaining(), Some(ample - required), "the nested import is charged once"); + }); + } + #[test] fn svg_extension_does_not_override_another_format_signature() { let webp_header = b"RIFF\x04\0\0\0WEBP"; @@ -1023,6 +1279,68 @@ mod tests { assert!(!super::is_psd(b"\0\xffKA")); } + #[cfg(any(unix, windows))] + #[test] + fn verified_path_import_reads_a_flat_file_from_its_start() { + let dir = std::env::temp_dir().join(format!("photocraft-verified-png-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("verified.png"); + let image = photocraft_codecs::Image::from_u8(2, 3, photocraft_codecs::ChannelLayout::Rgb, vec![64; 18]).unwrap(); + let bytes = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + std::fs::write(&path, bytes).unwrap(); + let mut identity = None; + let (opened, damaged) = + super::import_file_for_open_verified("verified.png", &path, None, &ImportOptions::default(), &photocraft_raster::Interrupt::NONE, &mut identity) + .unwrap(); + assert_eq!((opened.document.size.width, opened.document.size.height), (2, 3)); + assert!(!damaged); + assert_eq!(identity, Some(super::FileIdentity::of_path(&path).unwrap())); + std::fs::remove_dir_all(dir).unwrap(); + } + + /// The identity a verified open returns is the opened handle's, and a different inode with + /// identical content is refused with the dedicated reason before any pixel is decoded. + #[cfg(unix)] + #[test] + fn verified_import_binds_the_decoded_handle_identity() { + let dir = std::env::temp_dir().join(format!("photocraft-io-verified-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("source.psd"); + let bytes = testgen::small(Version::Psd, Compression::Raw).to_bytes().unwrap(); + std::fs::write(&path, &bytes).unwrap(); + let expected = super::FileIdentity::of_path(&path).unwrap(); + let mut opened = None; + let (result, _) = super::import_file_for_open_verified( + "source.psd", + &path, + Some(&expected), + &ImportOptions::default(), + &photocraft_raster::Interrupt::NONE, + &mut opened, + ) + .unwrap(); + assert!(!result.document.layers.is_empty()); + assert_eq!(opened.as_ref(), Some(&expected), "the identity comes from the decoded handle"); + // Replacement with identical bytes but a different inode: not the approved file. + let replacement = dir.join("replacement.psd"); + std::fs::write(&replacement, &bytes).unwrap(); + std::fs::rename(&replacement, &path).unwrap(); + let mut opened = None; + let err = super::import_file_for_open_verified( + "source.psd", + &path, + Some(&expected), + &ImportOptions::default(), + &photocraft_raster::Interrupt::NONE, + &mut opened, + ) + .expect_err("the path now names another file"); + assert!(matches!(&err, super::IoError::SourceChanged), "got {err:?}"); + assert!(opened.is_some(), "the refused handle's identity is still reported"); + let _ = std::fs::remove_dir_all(&dir); + } + /// A common mislabeled download: PNG/JPEG bytes named `.psd` open from the signature, /// as on main and in Photoshop. #[test] diff --git a/crates/io/src/memory.rs b/crates/io/src/memory.rs index 94d34aa902..c9b8c54378 100644 --- a/crates/io/src/memory.rs +++ b/crates/io/src/memory.rs @@ -8,20 +8,461 @@ use crate::IoError; /// Memory left free beside what an import needs: for the app, its display and the system. pub const RESERVE: u64 = 512 << 20; +/// Automatic allowance for native platforms when available memory is unknown. +/// +/// Estimates above it need explicit per-invocation approval, up to the platform's aggregate +/// admission limit (see [`native_platform_cap`]). This is a conservative automatic admission +/// threshold, not a hard ceiling and not a per-buffer allocation bound. +pub const NATIVE_FALLBACK_BUDGET: u64 = 2 << 30; + +/// Automatic allowance for WebAssembly execution. +/// +/// Estimates above it need explicit per-invocation approval, up to +/// [`WASM_MAX_PEAK_BUDGET`]. This is a conservative product threshold, not an assertion that +/// the browser can allocate that much. +pub const WASM_BUDGET: u64 = 1 << 30; + +/// Upper ceiling on the automatic soft import budget when available memory is known. +pub const MAX_SOFT_BUDGET: u64 = 8 << 30; + +/// Estimate above which an import made with unknown available memory carries an extra warning. +/// +/// It is a warning threshold, not a hard ceiling: explicit approval remains possible up to the +/// platform's actual allocation limits, but the process may run out of memory. +pub const UNKNOWN_MEMORY_WARNING_THRESHOLD: u64 = 8 << 30; + +/// Reserve subtracted from commit headroom when known. +pub const COMMIT_RESERVE: u64 = 512 << 20; + +/// Bytes Rust's layout rules allow for one contiguous allocation on this target +/// (`isize::MAX`), not a bound on an import's aggregate peak. +/// +/// A layer plane, a decode buffer or a tile is one contiguous allocation, so each must fit this +/// limit at the point it is allocated. An import's peak is the *sum* of many such buffers and +/// may legitimately exceed this; decode paths enforce their own per-buffer limits +/// (`photocraft-psd::MAX_DECODED_BYTES`, `photocraft-codecs`' `Limits::max_alloc`) there. +pub const MAX_SINGLE_ALLOCATION: u64 = isize::MAX as u64; + +/// Architectural maximum linear memory of wasm32: 65,536 pages of 64 KiB (4 GiB). +/// +/// This is the whole address space of one wasm32 instance, shared with the resident document, +/// history, decoder buffers, the allocator, the stack and the runtime. It is an address-space +/// bound, not a promise that 4 GiB can be allocated; browsers may cap linear memory lower. +pub const WASM_LINEAR_MEMORY_LIMIT: u64 = 4u64 << 30; + +/// Largest single Rust allocation on wasm32 (`isize::MAX`): 2 GiB - 1. +/// +/// A per-buffer bound only. Aggregate admission on web uses [`WASM_MAX_PEAK_BUDGET`]; the layout +/// limit itself rejects a larger single buffer, and decoders may apply a tighter cap. +pub const WASM_MAX_SINGLE_ALLOCATION: u64 = (1u64 << 31) - 1; + +/// Conservative product cap for the aggregate peak of one web import: 2 GiB. +/// +/// Chosen by this project, not dictated by the architecture: it sits below both the 4 GiB +/// wasm32 linear-memory limit (leaving room for the runtime, stack, allocator metadata and the +/// resident document) and is reachable only through explicit approval above [`WASM_BUDGET`]. +/// Browsers commonly allow less, and allocation may still fail. Do not read it as a guarantee. +pub const WASM_MAX_PEAK_BUDGET: u64 = 2 << 30; + +/// Conservative product cap for the aggregate peak of a 32-bit native process: 2 GiB. +/// +/// A 32-bit process has a 4 GiB address space, but the kernel/reserved range, runtime, stack, +/// allocator metadata, document and history share it. This is a product choice well below the +/// architectural limit, not an architectural bound. +pub const NATIVE_32BIT_PEAK_CAP: u64 = 2 << 30; + +/// A snapshot of system memory availability, distinguishing physical RAM from swap and commit headroom. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub struct MemorySnapshot { + /// Currently available physical RAM (A) in bytes, bounded by applicable container or process limits. + /// Free swap is explicitly excluded. A value of `Some(0)` represents zero capacity, not unknown memory. + pub available_ram: Option, + /// Available swap headroom in bytes, if known. + pub swap_free: Option, + /// System or process commit headroom (C) in bytes, if measurable. + pub commit_headroom: Option, +} + +#[cfg(any(test, feature = "testgen"))] +thread_local! { + static MOCK_SNAPSHOT: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; + /// A per-attempt provider consulted on every query, unlike the fixed [`MOCK_SNAPSHOT`]. + /// Tests use it to change the measured capacity between admission checks from another + /// thread; it is thread-local, so it never affects unrelated parallel tests. + static MOCK_PROVIDER: std::cell::RefCell MemorySnapshot>>> = const { std::cell::RefCell::new(None) }; + /// Mocked [`scratch_capacity`]: `Some(None)` = spilling off, `Some(Some(n))` = `n` bytes. + static MOCK_SCRATCH: std::cell::Cell>> = const { std::cell::Cell::new(None) }; +} + +/// Tile bytes the scratch disk can take beyond RAM: `None` while spilling is off, paused or +/// unavailable (web), or its room is unknown. See [`photocraft_raster::spill::scratch_capacity`]. +/// +/// Test builds: a mocked memory snapshot without a mocked scratch disk measures no scratch, so a +/// test that mocks RAM keeps the RAM-only policy whatever another test did to the process-wide +/// scratch disk. +pub fn scratch_capacity() -> Option { + #[cfg(any(test, feature = "testgen"))] + { + if let Some(mock) = MOCK_SCRATCH.with(std::cell::Cell::get) { + return mock; + } + if MOCK_SNAPSHOT.with(|m| m.borrow().is_some()) || MOCK_PROVIDER.with(|p| p.borrow().is_some()) { + return None; + } + } + if cfg!(target_arch = "wasm32") { + return None; + } + photocraft_raster::spill::scratch_capacity() +} + +/// How much of `spillable` tile bytes the scratch disk covers on `platform` right now. The web +/// has no scratch disk, so it never gets credit. +fn scratch_credit_for(platform: Platform, spillable: u64) -> u64 { + if platform == Platform::Web || spillable == 0 { + return 0; + } + scratch_capacity().map_or(0, |room| spillable.min(room)) +} + +/// [`scratch_credit_for`] on this build's platform. +pub(crate) fn scratch_credit(spillable: u64) -> u64 { + scratch_credit_for(active_platform(), spillable) +} + +impl MemorySnapshot { + /// Unknown memory measurement. + pub const UNKNOWN: Self = Self { available_ram: None, swap_free: None, commit_headroom: None }; + + /// The current measurement from the shared detector, [`photocraft_raster::memory::system`], + /// which also sizes the tile residency budget. + pub fn current() -> Self { + #[cfg(any(test, feature = "testgen"))] + { + if let Some(provider) = MOCK_PROVIDER.with(|p| p.borrow().clone()) { + return provider(); + } + if let Some(mock) = MOCK_SNAPSHOT.with(|m| *m.borrow()) { + return mock; + } + } + + photocraft_raster::memory::system::current().into() + } +} + +impl From for MemorySnapshot { + /// The shared detector's measurement; an unreadable constraint is already the fail-closed + /// `Some(0)` available RAM, which admission refuses. + fn from(m: photocraft_raster::memory::system::SystemMemory) -> Self { + Self { available_ram: m.available_ram, swap_free: m.swap_free, commit_headroom: m.commit_headroom } + } +} + +/// Resolved memory budgets derived from a [`MemorySnapshot`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct MemoryBudget { + /// Automatic admission ceiling (S): imports requiring <= S open without confirmation. + pub soft_limit: u64, + /// Hard refusal ceiling (H): imports requiring > H are refused and cannot be overridden. + pub hard_limit: u64, + /// Currently available physical RAM from the snapshot, if known. + pub available_ram: Option, + /// Set when available memory is unknown: estimates above this threshold still need explicit + /// approval but also carry the uncertain-capacity warning. `None` when capacity is known. + pub warning_threshold: Option, +} + +/// Admission decision for a given required memory estimate. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BudgetDecision { + /// Estimated memory <= soft limit: open automatically. + Automatic, + /// Soft limit < estimated memory <= hard limit: requires explicit user/caller confirmation. + RequiresApproval, + /// Estimated memory > hard limit, or the saturated `u64::MAX` overflow sentinel: refused. + Refused, +} + +impl MemoryBudget { + /// Determines the admission decision for an estimated requirement in bytes. + /// + /// `u64::MAX` is the sentinel a format estimate produces when a size overflowed `u64` + /// (`photocraft-io`'s TIFF estimates saturate there rather than wrap). It is not a real + /// requirement, so it is always refused, even when the hard limit is itself `u64::MAX` (the + /// native unknown-memory cap) and even with explicit approval or a matching one-shot + /// estimate. The refusal keeps the estimate and limit as they are; no value is invented. + pub fn decide(&self, required: u64) -> BudgetDecision { + if required == u64::MAX { + return BudgetDecision::Refused; + } + if required <= self.soft_limit { + BudgetDecision::Automatic + } else if required <= self.hard_limit { + BudgetDecision::RequiresApproval + } else { + BudgetDecision::Refused + } + } + + /// Whether an approvable estimate also needs the uncertain-capacity warning. + /// + /// This is only meaningful together with [`BudgetDecision::RequiresApproval`]; it says the + /// budget came from the unknown-memory fallback and the estimate is above + /// [`UNKNOWN_MEMORY_WARNING_THRESHOLD`]. + pub fn requires_uncertainty_warning(&self, required: u64) -> bool { + self.warning_threshold.is_some_and(|threshold| required > threshold) + } +} + +/// Whether an approval-required estimate carries the unknown-capacity warning, given the +/// capacity measured when the estimate was made. +/// +/// A known capacity never carries it (a measured number is reported instead of a guess); when +/// capacity is unknown, an estimate above [`UNKNOWN_MEMORY_WARNING_THRESHOLD`] is still +/// approvable but says the process or tab may run out of memory. Kept separate from +/// [`MemoryBudget`] so a pending approval can carry the flag across a later, fresh measurement. +pub fn uncertain_capacity_warning(required: u64, available_ram: Option) -> bool { + available_ram.is_none() && required > UNKNOWN_MEMORY_WARNING_THRESHOLD +} + +/// Which platform policy to resolve. Tests use this to exercise the web policy on any host. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Platform { + Native, + Web, +} + +/// The platform policy selected for this build: Web on wasm32, Native everywhere else. +fn active_platform() -> Platform { + if cfg!(target_arch = "wasm32") { Platform::Web } else { Platform::Native } +} + +/// Aggregate address-space bound for native admission (not a per-buffer allocation bound). +/// +/// A 64-bit process has no practical aggregate address-space limit measurable through safe +/// standard APIs, so this is `u64::MAX`; per-buffer and format limits are enforced where buffers +/// are actually allocated. A 32-bit process uses [`NATIVE_32BIT_PEAK_CAP`]. +pub fn native_platform_cap() -> u64 { + if cfg!(target_pointer_width = "32") { NATIVE_32BIT_PEAK_CAP } else { u64::MAX } +} + +/// Resolves the adaptive hard and soft import budgets from a snapshot and an optional caller limit. +/// +/// The limits are for an import's aggregate peak estimate, not for one allocation: a peak may sum +/// many buffers, each of which is separately bounded where the decoder allocates it. +/// +/// Policy: +/// - Known RAM: H = min(floor(3*A/4), A - 1 GiB, C - reserve if known, [`native_platform_cap`]); +/// S = min(A/2, 8 GiB, H). +/// - Unknown native RAM: S = min(2 GiB, H) where H is [`native_platform_cap`], reduced by known +/// commit headroom; approval above S is possible up to H. 8 GiB is a warning threshold, not H. +/// - Web (wasm32): S = 1 GiB; H = min([`WASM_MAX_PEAK_BUDGET`], caller limit). +/// - <= S: automatic; S < E <= H: explicit approval; > H: refuse, no unlimited override. +/// - The saturated `u64::MAX` overflow sentinel is always refused, even when H is `u64::MAX` +/// (see [`MemoryBudget::decide`]). +/// - Known zero available RAM stays zero (it never becomes unknown/free). +/// - swap is never part of the adaptive budget. +/// - Explicit caller limits may lower admission, never bypass the hard boundary. +pub fn resolve_budget(snapshot: MemorySnapshot, caller_limit: Option) -> MemoryBudget { + resolve_budget_for(active_platform(), snapshot, caller_limit) +} + +/// [`resolve_budget`] for an import whose estimate includes `spillable` bytes of tile pixels. +/// +/// While the scratch disk is spilling (on and not paused), tiles beyond the residency budget are +/// written to it, so those pixels are not bounded by physical RAM: the part of `spillable` the +/// disk has room for ([`scratch_capacity`], after the Scratch Size Limit and the free-space +/// reserve) is added to both S and H before the caller's explicit limit applies. Equivalently, +/// the non-spillable working memory (decode buffers, conversion copies, merged planes) is +/// admitted against the RAM policy alone, and the whole estimate against RAM plus scratch room. +/// With spilling off or paused, and always on the web, this is exactly [`resolve_budget`]. +pub fn resolve_budget_with_scratch(snapshot: MemorySnapshot, caller_limit: Option, spillable: u64) -> MemoryBudget { + let platform = active_platform(); + resolve_budget_credited(platform, snapshot, caller_limit, scratch_credit_for(platform, spillable)) +} + +/// [`resolve_budget`] for an explicit platform, so tests can exercise the web policy on a native host. +fn resolve_budget_for(platform: Platform, snapshot: MemorySnapshot, caller_limit: Option) -> MemoryBudget { + resolve_budget_credited(platform, snapshot, caller_limit, 0) +} + +/// The policy with `credit` bytes of scratch room added to S and H before the caller's limit. +fn resolve_budget_credited(platform: Platform, snapshot: MemorySnapshot, caller_limit: Option, credit: u64) -> MemoryBudget { + if platform == Platform::Web { + let mut hard = WASM_MAX_PEAK_BUDGET; + if let Some(caller) = caller_limit.filter(|&c| c > 0) { + hard = hard.min(caller); + } + return MemoryBudget { soft_limit: WASM_BUDGET.min(hard), hard_limit: hard, available_ram: None, warning_threshold: None }; + } + + let platform_cap = native_platform_cap(); + let (mut hard, mut soft, warning_threshold) = match snapshot.available_ram { + Some(a) => { + let h_pct = ((a as u128 * 3) / 4) as u64; + let h_reserve = a.saturating_sub(1 << 30); + let mut h = h_pct.min(h_reserve); + + if let Some(c) = snapshot.commit_headroom { + let c_room = c.saturating_sub(COMMIT_RESERVE); + h = h.min(c_room); + } + + h = h.min(platform_cap); + + let s_pct = a / 2; + let s = s_pct.min(MAX_SOFT_BUDGET).min(h); + (h, s, None) + } + None => { + let mut h = platform_cap; + if let Some(c) = snapshot.commit_headroom { + let c_room = c.saturating_sub(COMMIT_RESERVE); + h = h.min(c_room); + } + let s = NATIVE_FALLBACK_BUDGET.min(h); + (h, s, Some(UNKNOWN_MEMORY_WARNING_THRESHOLD)) + } + }; + // Tile pixels the scratch disk takes need no RAM (see [`resolve_budget_with_scratch`]). + hard = hard.saturating_add(credit); + soft = soft.saturating_add(credit); + + if let Some(caller) = caller_limit.filter(|&c| c > 0) { + hard = hard.min(caller); + soft = soft.min(hard); + } + + MemoryBudget { soft_limit: soft, hard_limit: hard, available_ram: snapshot.available_ram, warning_threshold } +} + +/// Result of evaluating an import admission request. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct AdmissionOutcome { + pub budget: MemoryBudget, + /// Total authorized memory allowance for the entire attempt (top-level + nested decodes): + /// `min(S if automatic else H if approved, caller cap if any, approved_estimate if present)`. + pub authorized_total: u64, +} + +/// Central evaluation of PSD admission against adaptive budgets and options. +/// +/// Refuses before decoding if: +/// - `required` is the saturated `u64::MAX` overflow sentinel (see [`MemoryBudget::decide`]); +/// - `required > hard_limit` (regardless of approvals: hard ceiling cannot be overridden); +/// - `required > soft_limit` and high memory is not approved; +/// - high memory is approved, but `approved_estimate` is specified and `required > approved_estimate` +/// (preventing unbounded approval for altered/enlarged files). +/// +/// `spillable` is the part of `required` that is tile pixels; while the scratch disk is spilling +/// the limits include the room it has for them (see [`resolve_budget_with_scratch`]). Errors +/// still report the whole `required` (the figure approval binds to) and the effective limits. +pub(crate) fn evaluate_psd_admission( + required: u64, + spillable: u64, + caller_limit: u64, + high_memory_approved: bool, + approved_estimate: Option, + snapshot: MemorySnapshot, +) -> Result { + evaluate_psd_admission_for(active_platform(), required, spillable, caller_limit, high_memory_approved, approved_estimate, snapshot) +} + +/// [`evaluate_psd_admission`] for an explicit platform, so tests can exercise the web policy on a native host. +fn evaluate_psd_admission_for( + platform: Platform, + required: u64, + spillable: u64, + caller_limit: u64, + high_memory_approved: bool, + approved_estimate: Option, + snapshot: MemorySnapshot, +) -> Result { + let limit_opt = (caller_limit > 0).then_some(caller_limit); + let budget = resolve_budget_credited(platform, snapshot, limit_opt, scratch_credit_for(platform, spillable.min(required))); + + let authorized_total = match budget.decide(required) { + BudgetDecision::Automatic => { + let mut cap = budget.soft_limit; + if let Some(caller) = limit_opt { + cap = cap.min(caller); + } + if let Some(appr) = approved_estimate { + cap = cap.min(appr); + } + cap + } + BudgetDecision::RequiresApproval => { + if !high_memory_approved { + return Err(IoError::PsdApprovalRequired { + required, + soft_limit: budget.soft_limit, + hard_limit: budget.hard_limit, + available_ram: budget.available_ram, + }); + } + let mut cap = budget.hard_limit; + if let Some(caller) = limit_opt { + cap = cap.min(caller); + } + if let Some(appr) = approved_estimate { + cap = cap.min(appr); + } + cap + } + BudgetDecision::Refused => return Err(IoError::PsdImportBudget { required, limit: budget.hard_limit }), + }; + + if required > authorized_total { + return Err(IoError::PsdApprovalRequired { + required, + soft_limit: budget.soft_limit, + hard_limit: budget.hard_limit, + available_ram: budget.available_ram, + }); + } + Ok(AdmissionOutcome { budget, authorized_total }) +} + +/// Applies a caller's explicit local bounds to a nested decode. +/// +/// A nested import spends the enclosing attempt's remaining allowance: it never resolves an +/// independent adaptive budget and never resets the parent's. The caller's explicit bounds still +/// apply, because they limit this attempt rather than describe a second budget: +/// `caller_limit > 0` is the lower caller allowance, and `approved_estimate` (when present) is the +/// estimate one-shot consent was given for. Both are checked before the parent is charged, so a +/// refusal leaves its remaining allowance untouched, and the tighter bound is the one reported. +/// +/// A nested attempt cannot ask for fresh consent, so exceeding either bound is a hard refusal +/// ([`IoError::PsdImportBudget`], the form the outer caller limit already uses) rather than a new +/// approval request. +/// +/// The saturated `u64::MAX` overflow sentinel is not covered here (there is no meaningful limit to +/// report when no local bound is set); [`crate::psd_gate::consume_attempt_allowance`] refuses it +/// before the parent is charged. +pub(crate) fn nested_import_local_bound(required: u64, caller_limit: u64, approved_estimate: Option) -> Result<(), IoError> { + let caller = (caller_limit > 0).then_some(caller_limit); + let limit = match (caller, approved_estimate) { + (Some(caller), Some(approved)) => Some(caller.min(approved)), + (caller, approved) => caller.or(approved), + }; + match limit { + Some(limit) if required > limit => Err(IoError::PsdImportBudget { required, limit }), + _ => Ok(()), + } +} + /// Bytes this process can still use without running out, or `None` where that isn't known. On -/// Linux: the free RAM the kernel can hand out (`MemAvailable`, capped by the process's cgroup -/// v2 `memory.max` and those above it) plus free swap (capped by the cgroup's `memory.swap.max` and those above it). -/// Elsewhere `None`: Windows refuses an allocation past its commit limit, which the importers -/// already report as an error, and macOS pages to disk as it needs. +/// Linux: the free RAM the kernel can hand out (`MemAvailable`, capped by the process's memory +/// cgroup — v2 `memory.max` or v1 `memory.limit_in_bytes`/`memsw` — and those above it) plus free +/// swap (capped by the cgroup's swap limits). Elsewhere `None`: Windows refuses an allocation past +/// its commit limit, which the importers already report as an error, and macOS pages to disk as it +/// needs. macOS's physical-memory provider feeds the adaptive budget, not this legacy +/// RAM-plus-swap helper; flat and layered TIFF conversion keep their existing behaviour. Measured +/// by [`photocraft_raster::memory::system::available_with_swap`]. pub fn available() -> Option { - #[cfg(target_os = "linux")] - { - linux::available() - } - #[cfg(not(target_os = "linux"))] - { - None - } + photocraft_raster::memory::system::available_with_swap() } /// Refuses to open a `w` × `h` px image whose layer and decode buffers take `needed` bytes when @@ -39,51 +480,167 @@ pub(crate) fn check_fits(w: u32, h: u32, needed: u64, available: Option) -> ))) } -#[cfg(target_os = "linux")] -mod linux { - use std::path::{Path, PathBuf}; +/// Sets a thread-local mock memory snapshot for testing policy and import admission. +#[cfg(any(test, feature = "testgen"))] +pub fn set_mock_memory(snapshot: Option) { + MOCK_SNAPSHOT.with(|m| *m.borrow_mut() = snapshot); +} - pub(super) fn available() -> Option { - let info = std::fs::read_to_string("/proc/meminfo").ok()?; - let ram = meminfo(&info, "MemAvailable:")?; - let swap = meminfo(&info, "SwapFree:").unwrap_or(0); - let Some(dir) = cgroup_dir() else { return Some(ram.saturating_add(swap)) }; - let (ram_room, swap_room) = cgroup_room(&dir); - Some(ram.min(ram_room.unwrap_or(u64::MAX)).saturating_add(swap.min(swap_room.unwrap_or(u64::MAX)))) +/// Runs a closure with a temporarily injected mock memory snapshot on the current thread. +/// +/// Restores the previous snapshot upon return or panic, supporting nested invocations. +#[cfg(any(test, feature = "testgen"))] +pub fn with_mock_memory(snapshot: MemorySnapshot, f: impl FnOnce() -> R) -> R { + let prev = MOCK_SNAPSHOT.with(|m| { + let old = *m.borrow(); + *m.borrow_mut() = Some(snapshot); + old + }); + + struct Reset { + prev: Option, + } + impl Drop for Reset { + fn drop(&mut self) { + MOCK_SNAPSHOT.with(|m| *m.borrow_mut() = self.prev); + } } - /// A `/proc/meminfo` field in bytes. - pub(super) fn meminfo(info: &str, field: &str) -> Option { - let kb: u64 = info.lines().find_map(|l| l.strip_prefix(field))?.trim().trim_end_matches("kB").trim().parse().ok()?; - kb.checked_mul(1024) + let _reset = Reset { prev }; + f() +} + +/// Runs a closure with a per-attempt memory provider on the current thread. +/// +/// Unlike [`with_mock_memory`], the provider is consulted for every +/// [`MemorySnapshot::current`], so a test can change the measured capacity while an import is +/// waiting on the decode gate and observe the post-gate recheck. The provider is thread-local +/// and restored on return or panic, so it never overrides another test's measurement. +#[cfg(any(test, feature = "testgen"))] +pub fn with_mock_memory_provider(provider: std::rc::Rc MemorySnapshot>, f: impl FnOnce() -> R) -> R { + let prev = MOCK_PROVIDER.with(|p| p.borrow_mut().replace(provider)); + + struct Reset { + prev: Option MemorySnapshot>>, + } + impl Drop for Reset { + fn drop(&mut self) { + MOCK_PROVIDER.with(|p| *p.borrow_mut() = self.prev.take()); + } } - /// The process's cgroup v2 directory. - fn cgroup_dir() -> Option { - let groups = std::fs::read_to_string("/proc/self/cgroup").ok()?; - let path = groups.lines().find_map(|l| l.strip_prefix("0::"))?; - Some(Path::new("/sys/fs/cgroup").join(path.trim().trim_start_matches('/'))) + let _reset = Reset { prev }; + f() +} + +/// Runs a closure with a mocked scratch disk on the current thread: `Some(n)` = spilling with +/// `n` bytes of room, `None` = spilling off or paused. Restored on return or panic, and captured +/// by [`TestMemoryScope`]. +#[cfg(any(test, feature = "testgen"))] +pub fn with_mock_scratch(capacity: Option, f: impl FnOnce() -> R) -> R { + struct Reset(Option>); + impl Drop for Reset { + fn drop(&mut self) { + MOCK_SCRATCH.with(|m| m.set(self.0)); + } + } + let _reset = Reset(MOCK_SCRATCH.with(|m| m.replace(Some(capacity)))); + f() +} + +/// Explicit test-support capture/scope object to propagate the thread-local fixed mock snapshot +/// and the scoped PSD estimate charge across worker threads without modifying global process +/// state. +/// +/// It captures `set_mock_memory`/`with_mock_memory`'s fixed snapshot and +/// [`crate::psd_budget::with_test_estimate_charge`]'s extra charge, so an engine worker that +/// enters the scope makes the same admission estimates as the test thread. The per-attempt +/// provider set by `with_mock_memory_provider` is not captured: that provider is a non-`Send` +/// closure re-consulted on every [`MemorySnapshot::current`], and propagating it to a worker +/// needs an explicitly shared, `Send + Sync` scope designed for that purpose (follow-up work). +/// A worker an import starts therefore sees the fixed snapshot, not a live provider. +/// +/// Capturing is explicit: nothing here changes a thread that never enters the scope, and no +/// global state is written. +/// +/// In production, this is an inert zero-overhead type. +#[derive(Clone, Copy, Debug, Default)] +pub struct TestMemoryScope { + #[cfg(any(test, feature = "testgen"))] + mock: Option, + /// The estimate charge captured with the scope (zero when the test set none). + #[cfg(any(test, feature = "testgen"))] + estimate_charge: u64, + /// The tile-pixel share of that charge. + #[cfg(any(test, feature = "testgen"))] + tile_charge: u64, + /// The mocked scratch disk ([`with_mock_scratch`]), if any. + #[cfg(any(test, feature = "testgen"))] + scratch: Option>, +} + +/// RAII guard that restores the previous thread-local mock memory and estimate charge upon drop. +pub struct TestMemoryGuard { + #[cfg(any(test, feature = "testgen"))] + prev: Option, + #[cfg(any(test, feature = "testgen"))] + prev_charge: (u64, u64), + #[cfg(any(test, feature = "testgen"))] + prev_scratch: Option>, +} + +#[cfg(any(test, feature = "testgen"))] +impl Drop for TestMemoryGuard { + fn drop(&mut self) { + MOCK_SNAPSHOT.with(|m| *m.borrow_mut() = self.prev); + crate::psd_budget::enter_test_estimate_charge(self.prev_charge.0, self.prev_charge.1); + MOCK_SCRATCH.with(|m| m.set(self.prev_scratch)); + } +} + +impl TestMemoryScope { + /// Captures the current thread's fixed mock memory snapshot and estimate charge, if any (see + /// [`TestMemoryScope`] for what is not captured). + /// + /// Never captures actual system RAM as a permanent snapshot so that + /// production memory rechecks remain fresh. + pub fn capture() -> Self { + #[cfg(any(test, feature = "testgen"))] + { + let mock = MOCK_SNAPSHOT.with(|m| *m.borrow()); + let (estimate_charge, tile_charge) = crate::psd_budget::test_estimate_charge(); + Self { mock, estimate_charge, tile_charge, scratch: MOCK_SCRATCH.with(std::cell::Cell::get) } + } + #[cfg(not(any(test, feature = "testgen")))] + { + Self {} + } } - /// Memory and swap left under the limits of `dir` and every cgroup above it (`None`: no - /// limit). Both limits apply hierarchically. `memory.current` includes page cache, which the - /// kernel reclaims before a cgroup hits `memory.max`, so its inactive part counts as free. - pub(super) fn cgroup_room(dir: &Path) -> (Option, Option) { - let read = |d: &Path, f: &str| std::fs::read_to_string(d.join(f)).ok(); - let room = |d: &Path, max: &str, current: &str, reclaimable: u64| -> Option { - let max = read(d, max)?.trim().parse::().ok()?; - let current = read(d, current).and_then(|c| c.trim().parse::().ok()).unwrap_or(0); - Some(max.saturating_sub(current.saturating_sub(reclaimable))) - }; - let inactive_file = |d: &Path| read(d, "memory.stat").and_then(|s| stat(&s, "inactive_file")).unwrap_or(0); - let swap = dir.ancestors().take(64).filter_map(|d| room(d, "memory.swap.max", "memory.swap.current", 0)).min(); - let ram = dir.ancestors().take(64).filter_map(|d| room(d, "memory.max", "memory.current", inactive_file(d))).min(); - (ram, swap) + /// Enters this captured mock memory scope, returning a RAII guard that + /// restores the thread's previous mock state and estimate charge on drop. + pub fn enter(self) -> TestMemoryGuard { + #[cfg(any(test, feature = "testgen"))] + { + let prev = MOCK_SNAPSHOT.with(|m| { + let old = *m.borrow(); + *m.borrow_mut() = self.mock; + old + }); + let prev_charge = crate::psd_budget::enter_test_estimate_charge(self.estimate_charge, self.tile_charge); + let prev_scratch = MOCK_SCRATCH.with(|m| m.replace(self.scratch)); + TestMemoryGuard { prev, prev_charge, prev_scratch } + } + #[cfg(not(any(test, feature = "testgen")))] + { + TestMemoryGuard {} + } } - /// A `memory.stat` field (` ` per line). - fn stat(stat: &str, field: &str) -> Option { - stat.lines().find_map(|l| l.strip_prefix(field)?.strip_prefix(' '))?.trim().parse().ok() + /// Executes a closure within this captured mock memory scope. + pub fn run(self, f: impl FnOnce() -> R) -> R { + let _guard = self.enter(); + f() } } @@ -103,47 +660,425 @@ mod tests { assert!(check_fits(10, 10, u64::MAX, Some(u64::MAX)).is_err()); } - #[cfg(target_os = "linux")] #[test] - fn linux_memory_is_read_from_meminfo_and_the_cgroup() { - let info = "MemTotal: 24314352 kB\nMemAvailable: 12626632 kB\nSwapFree: 1024 kB\n"; - assert_eq!(linux::meminfo(info, "MemAvailable:"), Some(12_626_632 * 1024)); - assert_eq!(linux::meminfo(info, "SwapFree:"), Some(1024 * 1024)); - assert_eq!(linux::meminfo(info, "Missing:"), None); - assert_eq!(linux::meminfo("MemAvailable: lots kB", "MemAvailable:"), None); + fn pure_policy_adheres_to_approved_thresholds() { + if cfg!(target_arch = "wasm32") { + return; // the web policy has its own tests + } + if native_platform_cap() < 24 << 30 { + // This table uses 6-24 GiB limits, above a 32-bit aggregate cap. + return; + } + let gb = 1u64 << 30; - let root = std::env::temp_dir().join(format!("photocraft-cgroup-{}", std::process::id())); - let leaf = root.join("app.slice/app.scope"); - std::fs::create_dir_all(&leaf).unwrap(); - let write = |d: &Path, f: &str, v: &str| std::fs::write(d.join(f), v).unwrap(); - write(&root, "memory.max", "8589934592\n"); - write(&root, "memory.current", "2147483648\n"); - write(&leaf, "memory.max", "max\n"); - write(&leaf, "memory.current", "1073741824\n"); - write(&leaf, "memory.swap.max", "1073741824\n"); - write(&leaf, "memory.swap.current", "0\n"); - assert_eq!(linux::cgroup_room(&leaf), (Some(6 << 30), Some(1 << 30)), "the parent's limit applies"); - write(&root, "memory.swap.max", "1073741824\n"); - write(&root, "memory.swap.current", "805306368\n"); - write(&leaf, "memory.swap.max", "max\n"); - assert_eq!(linux::cgroup_room(&leaf).1, Some(256 << 20), "the parent's remaining swap applies to an unlimited leaf"); - write(&root, "memory.swap.max", "0\n"); - assert_eq!(linux::cgroup_room(&leaf).1, Some(0), "a parent can forbid swap"); - write(&root, "memory.swap.max", "1073741824\n"); - write(&leaf, "memory.swap.max", "134217728\n"); - assert_eq!(linux::cgroup_room(&leaf).1, Some(128 << 20), "the tighter leaf swap limit wins"); - write(&leaf, "memory.max", "1610612736\n"); - assert_eq!(linux::cgroup_room(&leaf).0, Some(512 << 20), "the tighter limit wins"); - write(&leaf, "memory.max", "2147483648\n"); - write(&leaf, "memory.current", "2147483648\n"); - write(&leaf, "memory.stat", "anon 268435456\nfile 1879048192\ninactive_file_x 1\ninactive_file 1610612736\n"); - assert_eq!(linux::cgroup_room(&leaf).0, Some(1610612736), "inactive page cache is reclaimed before the limit"); - write(&leaf, "memory.stat", "anon 268435456\n"); - assert_eq!(linux::cgroup_room(&leaf).0, Some(0), "no inactive_file: memory.current is all in use"); - std::fs::remove_dir_all(&root).unwrap(); - assert!(available().is_some()); + // 12 GiB RAM: H = min(9 GiB, 11 GiB) = 9 GiB; S = min(6 GiB, 8 GiB, 9 GiB) = 6 GiB. + let snap12 = MemorySnapshot { available_ram: Some(12 * gb), swap_free: None, commit_headroom: None }; + let b12 = resolve_budget(snap12, None); + assert_eq!(b12.soft_limit, 6 * gb); + assert_eq!(b12.hard_limit, 9 * gb); + assert_eq!(b12.warning_threshold, None); + + // 5.80 GiB estimate (5.8 * 1 GiB = 6227702579) + let est_5_8 = (5.80 * (gb as f64)).round() as u64; + assert_eq!(b12.decide(est_5_8), BudgetDecision::Automatic); + assert_eq!(b12.decide(6 * gb), BudgetDecision::Automatic); + assert_eq!(b12.decide(6 * gb + 1), BudgetDecision::RequiresApproval); + assert_eq!(b12.decide(9 * gb), BudgetDecision::RequiresApproval); + assert_eq!(b12.decide(9 * gb + 1), BudgetDecision::Refused); + + // 8 GiB RAM: H = min(6 GiB, 7 GiB) = 6 GiB; S = min(4 GiB, 8 GiB, 6 GiB) = 4 GiB. + let snap8 = MemorySnapshot { available_ram: Some(8 * gb), swap_free: None, commit_headroom: None }; + let b8 = resolve_budget(snap8, None); + assert_eq!(b8.soft_limit, 4 * gb); + assert_eq!(b8.hard_limit, 6 * gb); + assert_eq!(b8.decide(est_5_8), BudgetDecision::RequiresApproval); + + // 6 GiB RAM: H = min(4.5 GiB, 5 GiB) = 4.5 GiB; S = 3 GiB. + let snap6 = MemorySnapshot { available_ram: Some(6 * gb), swap_free: None, commit_headroom: None }; + let b6 = resolve_budget(snap6, None); + assert_eq!(b6.soft_limit, 3 * gb); + assert_eq!(b6.hard_limit, (4.5 * (gb as f64)) as u64); + assert_eq!(b6.decide(est_5_8), BudgetDecision::Refused); + + // 32 GiB RAM: H = min(24 GiB, 31 GiB) = 24 GiB; S = min(16 GiB, 8 GiB, 24 GiB) = 8 GiB cap. + let snap32 = MemorySnapshot { available_ram: Some(32 * gb), swap_free: None, commit_headroom: None }; + let b32 = resolve_budget(snap32, None); + assert_eq!(b32.soft_limit, 8 * gb); + assert_eq!(b32.hard_limit, 24 * gb); + assert_eq!(b32.warning_threshold, None); + assert!(!b32.requires_uncertainty_warning(10 * gb), "known memory has no unknown-capacity warning"); + + // Commit headroom constraint: C = 5 GiB -> C - 512 MiB = 4.5 GiB. + let snap_commit = MemorySnapshot { available_ram: Some(12 * gb), swap_free: None, commit_headroom: Some(5 * gb) }; + let b_commit = resolve_budget(snap_commit, None); + assert_eq!(b_commit.hard_limit, 5 * gb - COMMIT_RESERVE); + assert_eq!(b_commit.soft_limit, 5 * gb - COMMIT_RESERVE); + + // Caller limits: lowers admission, cannot raise past H. + let b_caller = resolve_budget(snap12, Some(5 * gb)); + assert_eq!(b_caller.hard_limit, 5 * gb); + assert_eq!(b_caller.soft_limit, 5 * gb); + + let b_caller_high = resolve_budget(snap8, Some(20 * gb)); + assert_eq!(b_caller_high.hard_limit, 6 * gb); + assert_eq!(b_caller_high.soft_limit, 4 * gb); } - #[cfg(target_os = "linux")] - use std::path::Path; + #[test] + fn zero_available_ram_is_not_unknown() { + if cfg!(target_arch = "wasm32") { + return; + } + let snap_zero = MemorySnapshot { available_ram: Some(0), swap_free: None, commit_headroom: None }; + let b_zero = resolve_budget(snap_zero, None); + assert_eq!(b_zero.soft_limit, 0); + assert_eq!(b_zero.hard_limit, 0); + assert_eq!(b_zero.warning_threshold, None); + assert_eq!(b_zero.decide(1), BudgetDecision::Refused); + + let snap_unknown = MemorySnapshot::UNKNOWN; + let b_unknown = resolve_budget(snap_unknown, None); + assert_eq!(b_unknown.soft_limit, NATIVE_FALLBACK_BUDGET.min(native_platform_cap())); + assert_eq!(b_unknown.hard_limit, native_platform_cap()); + assert_eq!(b_unknown.available_ram, None); + assert_eq!(b_unknown.warning_threshold, Some(UNKNOWN_MEMORY_WARNING_THRESHOLD)); + assert_eq!(b_unknown.decide(1), BudgetDecision::Automatic); + let expected = if b_unknown.hard_limit > b_unknown.soft_limit { BudgetDecision::RequiresApproval } else { BudgetDecision::Automatic }; + assert_eq!(b_unknown.decide(b_unknown.hard_limit.min(u64::MAX - 1)), expected); + assert_eq!(b_unknown.decide(u64::MAX), BudgetDecision::Refused, "the saturated overflow sentinel is never approved"); + if b_unknown.hard_limit < u64::MAX { + assert_eq!(b_unknown.decide(b_unknown.hard_limit + 1), BudgetDecision::Refused); + } + } + + /// A format estimate that overflows `u64` saturates at `u64::MAX`. Unknown native memory has + /// `u64::MAX` as its hard limit, so without a sentinel rule explicit approval would admit it. + #[test] + fn a_saturated_estimate_is_refused_even_at_the_unknown_native_hard_limit() { + if cfg!(target_pointer_width = "32") { + // A 32-bit aggregate cap already refuses it; the case this test guards is the + // 64-bit unknown-memory cap, where the limit itself is the sentinel. + return; + } + let budget = resolve_budget_for(Platform::Native, MemorySnapshot::UNKNOWN, None); + assert_eq!(budget.hard_limit, u64::MAX, "the case that would otherwise admit the sentinel"); + assert_eq!(budget.decide(u64::MAX), BudgetDecision::Refused, "the decision agrees with evaluation"); + assert_eq!(budget.decide(u64::MAX - 1), BudgetDecision::RequiresApproval); + + for (approved, estimate) in [(false, None), (true, None), (true, Some(u64::MAX))] { + match evaluate_psd_admission_for(Platform::Native, u64::MAX, 0, 0, approved, estimate, MemorySnapshot::UNKNOWN) { + Err(IoError::PsdImportBudget { required, limit }) => { + assert_eq!((required, limit), (u64::MAX, u64::MAX), "the typed refusal keeps the estimate and limit unchanged") + } + other => panic!("approved={approved}, estimate={estimate:?}: expected a hard refusal, got {other:?}"), + } + } + + // A caller limit equal to the sentinel, or an approved estimate of it, is no exception. + assert!(matches!( + evaluate_psd_admission_for(Platform::Native, u64::MAX, 0, u64::MAX, true, Some(u64::MAX), MemorySnapshot::UNKNOWN), + Err(IoError::PsdImportBudget { required: u64::MAX, limit: u64::MAX }) + )); + } + + #[test] + fn unknown_memory_is_conservative_but_not_capped_at_eight_gib() { + if cfg!(target_pointer_width = "32") { + return; + } + let gb = 1u64 << 30; + let b = resolve_budget_for(Platform::Native, MemorySnapshot::UNKNOWN, None); + assert_eq!(b.soft_limit, NATIVE_FALLBACK_BUDGET); + assert_eq!(b.hard_limit, native_platform_cap()); + + assert_eq!(b.decide(NATIVE_FALLBACK_BUDGET), BudgetDecision::Automatic); + assert_eq!(b.decide(NATIVE_FALLBACK_BUDGET + 1), BudgetDecision::RequiresApproval); + assert_eq!(b.decide(UNKNOWN_MEMORY_WARNING_THRESHOLD), BudgetDecision::RequiresApproval); + assert!(!b.requires_uncertainty_warning(UNKNOWN_MEMORY_WARNING_THRESHOLD)); + assert!(b.requires_uncertainty_warning(UNKNOWN_MEMORY_WARNING_THRESHOLD + 1)); + assert_eq!(b.decide(UNKNOWN_MEMORY_WARNING_THRESHOLD + 1), BudgetDecision::RequiresApproval, "8 GiB is a warning threshold, not a hard ceiling"); + assert_eq!(b.decide(64 * gb), BudgetDecision::RequiresApproval); + assert!(b.requires_uncertainty_warning(64 * gb)); + } + + #[test] + fn unknown_memory_with_known_commit_headroom_stays_conservative() { + if cfg!(target_arch = "wasm32") { + return; + } + let gb = 1u64 << 30; + + let snap_zero = MemorySnapshot { available_ram: None, swap_free: None, commit_headroom: Some(0) }; + let b_zero = resolve_budget(snap_zero, None); + assert_eq!(b_zero.hard_limit, 0); + assert_eq!(b_zero.soft_limit, 0); + assert_eq!(b_zero.decide(1), BudgetDecision::Refused); + + let snap_tight = MemorySnapshot { available_ram: None, swap_free: None, commit_headroom: Some(gb) }; + let b_tight = resolve_budget(snap_tight, None); + assert_eq!(b_tight.hard_limit, gb - COMMIT_RESERVE); + assert_eq!(b_tight.soft_limit, gb - COMMIT_RESERVE); + + let snap_room = MemorySnapshot { available_ram: None, swap_free: None, commit_headroom: Some(4 * gb) }; + let b_room = resolve_budget(snap_room, None); + assert_eq!(b_room.hard_limit, 4 * gb - COMMIT_RESERVE); + assert_eq!(b_room.soft_limit, NATIVE_FALLBACK_BUDGET); + } + + #[test] + fn unknown_memory_admits_approved_imports_above_eight_gib() { + if cfg!(target_pointer_width = "32") { + return; // the 32-bit platform cap is below 8 GiB + } + let gb = 1u64 << 30; + let snap = MemorySnapshot::UNKNOWN; + let required = 9 * gb; + + let err = evaluate_psd_admission_for(Platform::Native, required, 0, 0, false, None, snap).unwrap_err(); + assert!(matches!(err, IoError::PsdApprovalRequired { available_ram: None, .. })); + + let out = evaluate_psd_admission_for(Platform::Native, required, 0, 0, true, Some(required), snap).unwrap(); + assert_eq!(out.authorized_total, required); + assert!(out.budget.requires_uncertainty_warning(required), "the consent warning must carry through admission"); + + let err = evaluate_psd_admission_for(Platform::Native, required, 0, 0, true, Some(required - 1), snap).unwrap_err(); + assert!(matches!(err, IoError::PsdApprovalRequired { .. }), "a larger estimate needs fresh consent"); + } + + #[test] + fn web_policy_allows_approval_above_one_gib_within_its_own_cap() { + let b = resolve_budget_for(Platform::Web, MemorySnapshot::UNKNOWN, None); + assert_eq!(b.soft_limit, WASM_BUDGET); + assert_eq!(b.hard_limit, WASM_MAX_PEAK_BUDGET); + assert!(b.hard_limit < WASM_LINEAR_MEMORY_LIMIT, "the aggregate cap stays below the wasm32 address space"); + const { assert!(WASM_MAX_SINGLE_ALLOCATION < WASM_LINEAR_MEMORY_LIMIT, "a single Rust allocation cannot use all 4 GiB") }; + assert_eq!(b.available_ram, None); + assert_eq!(b.warning_threshold, None); + + assert_eq!(b.decide(WASM_BUDGET), BudgetDecision::Automatic); + assert_eq!(b.decide(WASM_BUDGET + 1), BudgetDecision::RequiresApproval); + assert_eq!(b.decide(WASM_MAX_PEAK_BUDGET), BudgetDecision::RequiresApproval); + assert_eq!(b.decide(WASM_MAX_PEAK_BUDGET + 1), BudgetDecision::Refused); + const { assert!(WASM_MAX_SINGLE_ALLOCATION < WASM_MAX_PEAK_BUDGET, "the aggregate cap must not be the single-allocation layout bound") }; + let out = evaluate_psd_admission_for(Platform::Web, WASM_MAX_PEAK_BUDGET, 0, 0, true, Some(WASM_MAX_PEAK_BUDGET), MemorySnapshot::UNKNOWN).unwrap(); + assert_eq!(out.authorized_total, WASM_MAX_PEAK_BUDGET, "approval may authorize an aggregate above one buffer's layout limit"); + + let capped = resolve_budget_for(Platform::Web, MemorySnapshot::UNKNOWN, Some(512 << 20)); + assert_eq!(capped.hard_limit, 512 << 20); + assert_eq!(capped.soft_limit, 512 << 20); + + let no_raise = resolve_budget_for(Platform::Web, MemorySnapshot::UNKNOWN, Some(64 << 30)); + assert_eq!(no_raise.hard_limit, WASM_MAX_PEAK_BUDGET); + } + + #[test] + fn web_admission_requires_approval_above_its_automatic_allowance() { + let snap = MemorySnapshot::UNKNOWN; + let approval = 3 * (WASM_BUDGET / 2); + + let out = evaluate_psd_admission_for(Platform::Web, WASM_BUDGET, 0, 0, false, None, snap).unwrap(); + assert_eq!(out.authorized_total, WASM_BUDGET); + + let err = evaluate_psd_admission_for(Platform::Web, WASM_BUDGET + 1, 0, 0, false, None, snap).unwrap_err(); + assert!(matches!( + err, + IoError::PsdApprovalRequired { required, soft_limit, hard_limit, available_ram } + if required == WASM_BUDGET + 1 && soft_limit == WASM_BUDGET && hard_limit == WASM_MAX_PEAK_BUDGET && available_ram.is_none() + )); + + let out = evaluate_psd_admission_for(Platform::Web, approval, 0, 0, true, Some(approval), snap).unwrap(); + assert_eq!(out.authorized_total, approval); + + let err = evaluate_psd_admission_for(Platform::Web, approval, 0, 0, true, Some(approval - 1), snap).unwrap_err(); + assert!(matches!(err, IoError::PsdApprovalRequired { .. })); + + let err = evaluate_psd_admission_for(Platform::Web, WASM_MAX_PEAK_BUDGET + 1, 0, 0, true, None, snap).unwrap_err(); + assert!(matches!(err, IoError::PsdImportBudget { .. })); + } + + #[test] + fn caller_caps_lower_unknown_memory_admission() { + let b = resolve_budget_for(Platform::Native, MemorySnapshot::UNKNOWN, Some(1 << 30)); + assert_eq!(b.hard_limit, 1 << 30); + assert_eq!(b.soft_limit, 1 << 30); + assert_eq!(b.warning_threshold, Some(UNKNOWN_MEMORY_WARNING_THRESHOLD)); + + let no_raise = resolve_budget_for(Platform::Native, MemorySnapshot::UNKNOWN, Some(64 << 30)); + assert_eq!(no_raise.hard_limit, native_platform_cap().min(64 << 30)); + assert_eq!(no_raise.soft_limit, NATIVE_FALLBACK_BUDGET.min(native_platform_cap())); + } + + #[test] + fn arithmetic_overflow_safety() { + if cfg!(target_arch = "wasm32") { + return; + } + let snap_huge = MemorySnapshot { available_ram: Some(u64::MAX), swap_free: Some(u64::MAX), commit_headroom: Some(u64::MAX) }; + let b = resolve_budget(snap_huge, None); + let expected_hard = (((u64::MAX as u128) * 3) / 4) as u64; + let expected_hard = expected_hard.min(native_platform_cap()); + assert_eq!(b.hard_limit, expected_hard); + assert_eq!(b.soft_limit, MAX_SOFT_BUDGET.min(expected_hard)); + } + + #[test] + fn nested_mock_memory_restores_previous() { + let snap1 = MemorySnapshot { available_ram: Some(100), swap_free: None, commit_headroom: None }; + let snap2 = MemorySnapshot { available_ram: Some(200), swap_free: None, commit_headroom: None }; + with_mock_memory(MemorySnapshot::UNKNOWN, || { + assert_eq!(MemorySnapshot::current(), MemorySnapshot::UNKNOWN); + with_mock_memory(snap1, || { + assert_eq!(MemorySnapshot::current().available_ram, Some(100)); + with_mock_memory(snap2, || { + assert_eq!(MemorySnapshot::current().available_ram, Some(200)); + }); + assert_eq!(MemorySnapshot::current().available_ram, Some(100)); + }); + assert_eq!(MemorySnapshot::current(), MemorySnapshot::UNKNOWN); + }); + } + + #[test] + fn central_admission_evaluation_enforces_bounds() { + if cfg!(any(target_arch = "wasm32", target_pointer_width = "32")) { + return; + } + let gb = 1u64 << 30; + let snap = MemorySnapshot { available_ram: Some(12 * gb), swap_free: None, commit_headroom: None }; + // S = 6 GiB, H = 9 GiB + + // Below S: automatic, authorized_total = S (6 GiB) + let out = evaluate_psd_admission(5 * gb, 0, 0, false, None, snap).unwrap(); + assert_eq!(out.authorized_total, 6 * gb); + + // In [S, H]: requires approval + let err = evaluate_psd_admission(7 * gb, 0, 0, false, None, snap).unwrap_err(); + assert!(matches!(err, IoError::PsdApprovalRequired { required, .. } if required == 7 * gb)); + + // In [S, H] with approval and no approved_estimate bound: admitted, authorized_total = H (9 GiB) + let out = evaluate_psd_admission(7 * gb, 0, 0, true, None, snap).unwrap(); + assert_eq!(out.authorized_total, 9 * gb); + + // In [S, H] with approval but required exceeds approved_estimate: requires fresh approval + let err = evaluate_psd_admission(7 * gb, 0, 0, true, Some(6 * gb), snap).unwrap_err(); + assert!(matches!(err, IoError::PsdApprovalRequired { .. })); + + // In [S, H] with approval and required within approved_estimate: admitted, authorized_total = approved_estimate (7 GiB) + let out = evaluate_psd_admission(7 * gb, 0, 0, true, Some(7 * gb), snap).unwrap(); + assert_eq!(out.authorized_total, 7 * gb); + + // Exceeding H: refused even if high_memory_approved is true + let err = evaluate_psd_admission(10 * gb, 0, 0, true, Some(10 * gb), snap).unwrap_err(); + assert!(matches!(err, IoError::PsdImportBudget { .. })); + } + + /// While the scratch disk spills, tile pixels are admitted against RAM plus its room, and + /// everything else against RAM alone. + #[test] + fn spilling_scratch_admits_tile_pixels_beyond_ram() { + if cfg!(any(target_arch = "wasm32", target_pointer_width = "32")) { + return; + } + let gb = 1u64 << 30; + let snap = MemorySnapshot { available_ram: Some(12 * gb), swap_free: None, commit_headroom: None }; + // RAM-only: S = 6 GiB, H = 9 GiB. + with_mock_scratch(Some(40 * gb), || { + // 20 GiB of which 18 GiB tiles: 2 GiB non-spillable fits S, so it is automatic. + let out = evaluate_psd_admission(20 * gb, 18 * gb, 0, false, None, snap).unwrap(); + assert_eq!(out.authorized_total, 6 * gb + 18 * gb); + // 8 GiB non-spillable sits in [S, H]: approval is still required, and is bound to + // the whole estimate. + let err = evaluate_psd_admission(26 * gb, 18 * gb, 0, false, None, snap).unwrap_err(); + assert!(matches!(err, IoError::PsdApprovalRequired { required, soft_limit, hard_limit, .. } + if required == 26 * gb && soft_limit == 24 * gb && hard_limit == 27 * gb)); + assert!(evaluate_psd_admission(26 * gb, 18 * gb, 0, true, Some(26 * gb), snap).is_ok()); + assert!(evaluate_psd_admission(26 * gb, 18 * gb, 0, true, Some(26 * gb - 1), snap).is_err()); + // 10 GiB non-spillable is over H: refused even when approved. + let err = evaluate_psd_admission(28 * gb, 18 * gb, 0, true, Some(28 * gb), snap).unwrap_err(); + assert!(matches!(err, IoError::PsdImportBudget { required, limit } if required == 28 * gb && limit == 27 * gb)); + // A spillable share claimed beyond the total is clamped to the total. + assert!(evaluate_psd_admission(5 * gb, u64::MAX, 0, false, None, snap).is_ok()); + // The caller's explicit limit still bounds the whole import. + let err = evaluate_psd_admission(20 * gb, 18 * gb, 10 * gb, false, None, snap).unwrap_err(); + assert!(matches!(err, IoError::PsdImportBudget { limit, .. } if limit == 10 * gb)); + }); + // Less room than tiles: only the room is credited. + with_mock_scratch(Some(4 * gb), || { + let err = evaluate_psd_admission(20 * gb, 18 * gb, 0, true, Some(20 * gb), snap).unwrap_err(); + assert!(matches!(err, IoError::PsdImportBudget { limit, .. } if limit == 13 * gb)); + assert_eq!(resolve_budget_with_scratch(snap, None, 18 * gb).soft_limit, 10 * gb); + }); + } + + /// Spilling off or paused, or the web: the RAM-only policy, unchanged. + #[test] + fn without_spilling_scratch_the_ram_policy_is_unchanged() { + if cfg!(any(target_arch = "wasm32", target_pointer_width = "32")) { + return; + } + let gb = 1u64 << 30; + let snap = MemorySnapshot { available_ram: Some(12 * gb), swap_free: None, commit_headroom: None }; + for scratch in [None, Some(0)] { + with_mock_scratch(scratch, || { + assert_eq!(resolve_budget_with_scratch(snap, None, 18 * gb), resolve_budget(snap, None)); + let err = evaluate_psd_admission(20 * gb, 18 * gb, 0, true, Some(20 * gb), snap).unwrap_err(); + assert!(matches!(err, IoError::PsdImportBudget { limit, .. } if limit == 9 * gb)); + let err = evaluate_psd_admission(7 * gb, 7 * gb, 0, false, None, snap).unwrap_err(); + assert!(matches!(err, IoError::PsdApprovalRequired { soft_limit, hard_limit, .. } if soft_limit == 6 * gb && hard_limit == 9 * gb)); + }); + } + // A mocked RAM snapshot without a mocked scratch disk never measures the real one. + with_mock_memory(snap, || assert_eq!(scratch_capacity(), None)); + with_mock_scratch(Some(40 * gb), || { + assert_eq!(scratch_credit_for(Platform::Web, 18 * gb), 0); + let err = evaluate_psd_admission_for(Platform::Web, WASM_BUDGET + 1, WASM_BUDGET, 0, false, None, snap).unwrap_err(); + assert!(matches!(err, IoError::PsdApprovalRequired { soft_limit, .. } if soft_limit == WASM_BUDGET)); + let err = evaluate_psd_admission_for(Platform::Web, WASM_MAX_PEAK_BUDGET + 1, WASM_MAX_PEAK_BUDGET, 0, true, None, snap).unwrap_err(); + assert!(matches!(err, IoError::PsdImportBudget { .. })); + }); + } + + /// A [`TestMemoryScope`] carries the mocked scratch disk to a worker thread. + #[test] + fn test_memory_scope_captures_the_mocked_scratch_disk() { + let scope = with_mock_scratch(Some(123), TestMemoryScope::capture); + std::thread::spawn(move || { + assert_eq!(MOCK_SCRATCH.with(std::cell::Cell::get), None); + let _g = scope.enter(); + assert_eq!(scratch_capacity(), Some(123)); + }) + .join() + .unwrap(); + } + + #[test] + fn known_snapshot_uses_known_memory_policy_on_every_target() { + let gb = 1u64 << 30; + let snap = MemorySnapshot { available_ram: Some(16 * gb), swap_free: None, commit_headroom: None }; + let b = resolve_budget_for(Platform::Native, snap, None); + let expected_hard = (12 * gb).min(native_platform_cap()); + assert_eq!(b.hard_limit, expected_hard); + assert_eq!(b.soft_limit, (8 * gb).min(expected_hard)); + assert_eq!(b.available_ram, Some(16 * gb)); + assert_eq!(b.warning_threshold, None); + } + + #[test] + fn aggregate_cap_is_not_a_single_allocation_bound() { + let cap = native_platform_cap(); + if cfg!(target_pointer_width = "32") { + assert_eq!(cap, NATIVE_32BIT_PEAK_CAP, "32-bit native uses the documented product cap"); + } else { + assert_eq!(cap, u64::MAX, "64-bit native has no measurable aggregate address-space cap"); + assert!(MAX_SINGLE_ALLOCATION < cap, "a per-buffer limit must not become the aggregate limit"); + } + } + + #[test] + fn swap_is_never_part_of_the_adaptive_budget() { + let gb = 1u64 << 30; + let with_swap = MemorySnapshot { available_ram: Some(4 * gb), swap_free: Some(64 * gb), commit_headroom: None }; + let without_swap = MemorySnapshot { available_ram: Some(4 * gb), swap_free: None, commit_headroom: None }; + assert_eq!(resolve_budget_for(Platform::Native, with_swap, None), resolve_budget_for(Platform::Native, without_swap, None)); + } } diff --git a/crates/io/src/psd_budget.rs b/crates/io/src/psd_budget.rs index b3c00ed4ef..a80230322d 100644 --- a/crates/io/src/psd_budget.rs +++ b/crates/io/src/psd_budget.rs @@ -16,10 +16,102 @@ use crate::IoError; /// workspace and tile padding. Other format/parser limits still apply. Callers may lower it. pub const DEFAULT_PSD_IMPORT_PIXEL_BYTES: u64 = if cfg!(target_arch = "wasm32") { 1 << 30 } else { 2 << 30 }; +/// Structured memory estimate for a PSD/PSB import. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct PsdMemoryEstimate { + /// Bytes required for all possible retained layer, mask, and merged surfaces. + pub retained_bytes: u64, + /// Largest scratch/conversion workspace required during decoding. + pub workspace_bytes: u64, + /// Total peak requirement (retained + workspace). + pub total_bytes: u64, + /// The part of `retained_bytes` that is tile pixels (layer, mask, channel, fallback and + /// pattern surfaces). Tiles can be spilled to the scratch disk while it is on, so admission + /// does not bound them by physical RAM; the merged planes, pattern decodes and the workspace + /// are ordinary memory. + pub tile_bytes: u64, +} + #[derive(Default)] struct ImportBudget { retained: u64, workspace: u64, + tiles: u64, +} + +#[cfg(any(test, feature = "testgen"))] +thread_local! { + /// Extra bytes added to every estimate on this thread by [`with_test_estimate_charge`]. + static TEST_ESTIMATE_CHARGE: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Extra tile-pixel bytes added by [`with_test_tile_charge`]. + static TEST_TILE_CHARGE: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Adds `bytes` to every PSD memory estimate made on this thread while `f` runs. +/// +/// A test seam: an admission-threshold test can use a tiny fixture, so nothing near a gigabyte +/// is ever allocated, while still exercising the real import path with its approval flags and +/// gate ordering. Scoped to the thread and restored on return or panic. +/// +/// The charge lives on the calling thread. A real import that runs on another thread (or a +/// worker the engine starts for it) does not see it unless the caller propagates an explicitly +/// captured scope: [`crate::memory::TestMemoryScope`] captures this charge together with the +/// fixed mock snapshot, so an engine worker that enters that scope makes the same estimates as +/// the test thread. This is the seam engine and UI dev-dependency tests use through the +/// `testgen` feature; it is never process-global. +#[cfg(any(test, feature = "testgen"))] +pub fn with_test_estimate_charge(bytes: u64, f: impl FnOnce() -> R) -> R { + struct Reset(u64); + impl Drop for Reset { + fn drop(&mut self) { + TEST_ESTIMATE_CHARGE.with(|c| c.set(self.0)); + } + } + let prev = TEST_ESTIMATE_CHARGE.with(|c| c.replace(bytes)); + let _reset = Reset(prev); + f() +} + +/// [`with_test_estimate_charge`] for tile pixels: `bytes` are added to every estimate made on +/// this thread while `f` runs, as spillable tile bytes ([`PsdMemoryEstimate::tile_bytes`]), so a +/// scratch-aware admission test needs no huge fixture. Captured by +/// [`crate::memory::TestMemoryScope`] like the plain charge. +#[cfg(any(test, feature = "testgen"))] +pub fn with_test_tile_charge(bytes: u64, f: impl FnOnce() -> R) -> R { + struct Reset(u64); + impl Drop for Reset { + fn drop(&mut self) { + TEST_TILE_CHARGE.with(|c| c.set(self.0)); + } + } + let prev = TEST_TILE_CHARGE.with(|c| c.replace(bytes)); + let _reset = Reset(prev); + f() +} + +/// The calling thread's current (plain, tile) estimate charges, for an explicit scope to capture. +#[cfg(any(test, feature = "testgen"))] +pub(crate) fn test_estimate_charge() -> (u64, u64) { + (TEST_ESTIMATE_CHARGE.with(|c| c.get()), TEST_TILE_CHARGE.with(|c| c.get())) +} + +/// Enters captured estimate charges (an explicit [`crate::memory::TestMemoryScope`] worker) and +/// returns the charges they replaced, to restore after the scope ends. +#[cfg(any(test, feature = "testgen"))] +pub(crate) fn enter_test_estimate_charge(bytes: u64, tiles: u64) -> (u64, u64) { + (TEST_ESTIMATE_CHARGE.with(|c| c.replace(bytes)), TEST_TILE_CHARGE.with(|c| c.replace(tiles))) +} + +/// The test seam's extra (plain, tile) charges; zero in every other build. +fn test_estimate_charge_value() -> (u64, u64) { + #[cfg(any(test, feature = "testgen"))] + { + test_estimate_charge() + } + #[cfg(not(any(test, feature = "testgen")))] + { + (0, 0) + } } fn overflow() -> IoError { @@ -49,14 +141,6 @@ impl ImportBudget { self.retained.checked_add(self.workspace).ok_or_else(overflow) } - fn check(&self, limit: u64) -> Result<(), IoError> { - let required = self.required()?; - if required > limit { - return Err(IoError::PsdImportBudget { required, limit }); - } - Ok(()) - } - fn surface(&mut self, rect: Rect, channels: u64, sample: u64) -> Result<(), IoError> { if rect.is_empty() { return Ok(()); @@ -66,15 +150,24 @@ impl ImportBudget { // origin occupies four tiles. Widen first, including the exclusive right/bottom edge. let nx = (i64::from(rect.right) - 1).div_euclid(tile) - i64::from(rect.left).div_euclid(tile) + 1; let ny = (i64::from(rect.bottom) - 1).div_euclid(tile) - i64::from(rect.top).div_euclid(tile) + 1; - self.retain(mul(mul(mul(nx as u64, ny as u64)?, (TILE_SIZE as u64).pow(2))?, mul(channels, sample)?)?) + let bytes = mul(mul(mul(nx as u64, ny as u64)?, (TILE_SIZE as u64).pow(2))?, mul(channels, sample)?)?; + self.tile(bytes) + } + + /// Retained tile pixels: spillable to the scratch disk. + fn tile(&mut self, bytes: u64) -> Result<(), IoError> { + self.retain(bytes)?; + self.tiles = self.tiles.checked_add(bytes).ok_or_else(overflow)?; + Ok(()) } } +/// Computes the conservative preflight pixel memory and workspace estimate for `file`. +/// /// No decoding here: even a compact ZIP stream must be refused before inflation. The sum /// deliberately counts full decoded planes for every compression method, plus their row -/// buffers, interleave output and float conversion workspace. This is an upper estimate, -/// rather than a promise that an allocator or OS can satisfy an accepted import. -pub(crate) fn check(file: &PsdFile, limit: u64) -> Result<(), IoError> { +/// buffers, interleave output and float conversion workspace. +pub fn estimate(file: &PsdFile) -> Result { let mut budget = ImportBudget::default(); let h = &file.header; h.validate()?; @@ -145,7 +238,20 @@ pub(crate) fn check(file: &PsdFile, limit: u64) -> Result<(), IoError> { budget.scratch(converted.checked_add(p.decoded_bytes).ok_or_else(overflow)?); } } - budget.check(limit) + let (charge, tile_charge) = test_estimate_charge_value(); + budget.retain(charge)?; + budget.tile(tile_charge)?; + let total_bytes = budget.required()?; + Ok(PsdMemoryEstimate { retained_bytes: budget.retained, workspace_bytes: budget.workspace, total_bytes, tile_bytes: budget.tiles }) +} + +/// Checks that `file`'s estimate does not exceed `limit`. +pub fn check(file: &PsdFile, limit: u64) -> Result { + let est = estimate(file)?; + if est.total_bytes > limit { + return Err(IoError::PsdImportBudget { required: est.total_bytes, limit }); + } + Ok(est) } #[cfg(test)] diff --git a/crates/io/src/psd_budget/tests.rs b/crates/io/src/psd_budget/tests.rs index 3c1a195486..9e24676716 100644 --- a/crates/io/src/psd_budget/tests.rs +++ b/crates/io/src/psd_budget/tests.rs @@ -8,8 +8,7 @@ fn retained_storage_is_summed_but_workspace_is_reused() { budget.retain(20).unwrap(); budget.scratch(30); budget.scratch(10); - assert!(budget.check(90).is_ok()); - assert!(matches!(budget.check(89), Err(IoError::PsdImportBudget { required: 90, limit: 89 }))); + assert_eq!(budget.required().unwrap(), 90); budget.retain(u64::MAX).unwrap_err(); budget.workspace = u64::MAX; assert!(budget.required().is_err()); @@ -55,9 +54,16 @@ fn large_off_canvas_layer_is_rejected_without_decoding_its_tiny_data() { // section. No enormous decoded plane is ever constructed by this test. let mut bytes = file.to_bytes().unwrap(); bytes.truncate(bytes.len() - file.image_data.data.len() - 2); - assert!(matches!(crate::import("huge.psd", &bytes), Err(IoError::PsdImportBudget { .. }))); - let source = photocraft_psd::Source::new(bytes); - assert!(matches!(crate::import_source_for_open_with("huge.psd", source, &photocraft_raster::Interrupt::NONE), Err(IoError::PsdImportBudget { .. }))); + crate::memory::with_mock_memory(crate::memory::MemorySnapshot::UNKNOWN, || { + // Unknown memory keeps a conservative automatic allowance, so this file is refused + // pending approval (or by the hard platform limit on 32-bit) before any pixel decode. + assert!(matches!(crate::import("huge.psd", &bytes), Err(IoError::PsdApprovalRequired { .. } | IoError::PsdImportBudget { .. }))); + let source = photocraft_psd::Source::new(bytes); + assert!(matches!( + crate::import_source_for_open_with("huge.psd", source, &photocraft_raster::Interrupt::NONE), + Err(IoError::PsdApprovalRequired { .. } | IoError::PsdImportBudget { .. }) + )); + }); } #[test] @@ -119,9 +125,12 @@ fn accepted_off_canvas_pixels_and_depths_are_preserved() { fn legacy_conversion_reports_a_rejected_import_instead_of_decoding_it() { let mut file = testgen::small(Version::Psd, Compression::Zip); file.layers_mut()[0].rect = Rect::from_xywh(0, 0, 20000, 20000); - let (doc, warnings) = crate::psd_to_document(&file); - assert!(doc.layers.is_empty()); - assert!(warnings.iter().any(|warning| warning.contains("pixel memory"))); + // Use fallback snapshot to ensure test does not depend on host available RAM + crate::memory::with_mock_memory(crate::memory::MemorySnapshot::UNKNOWN, || { + let (doc, warnings) = crate::psd_to_document(&file); + assert!(doc.layers.is_empty()); + assert!(warnings.iter().any(|warning| warning.contains("pixel memory"))); + }); } fn pattern_block(mode: u32, depth: u16, width: u32, height: u32) -> photocraft_psd::TaggedBlock { @@ -192,3 +201,380 @@ fn an_unknown_color_mode_pays_for_the_layers_it_imports_as_rgb() { let refused = crate::import_source_with_limit("mode5.psd", source, &photocraft_raster::Interrupt::NONE, required - 1); assert!(matches!(refused, Err(IoError::PsdImportBudget { .. })), "{:?}", refused.map(|(r, _)| r.warnings)); } + +#[test] +fn adaptive_budget_requires_explicit_approval_in_confirmation_range() { + let file = testgen::small(Version::Psd, Compression::Zip); + let bytes = file.to_bytes().unwrap(); + let est = estimate(&file); + + // Set mock RAM such that est is strictly between S and H. + // E.g., if A = est * 2 + 1 GiB: + // H = min(75% A, A - 1 GiB) = min(1.5 est + 768 MiB, 2 est) = 1.5 est + 768 MiB > est. + // S = min(50% A, 8 GiB, H) = min(est + 512 MiB, 8 GiB, H). + // Let us set A precisely so S < est <= H: + // If we want S < est, 50% A < est => A < 2 est. + // If A = (est * 16) / 10 (i.e. 1.6 est): + // S = 0.8 est < est. + // H = min(1.2 est, 1.6 est - 1 GiB). + // To ensure saturating A - 1 GiB is not 0, let A = 10 * (1 << 30) (10 GiB): + // S = 5 GiB, H = 7.5 GiB. + // Target estimate est in (5 GiB, 7.5 GiB]. + // With mock memory, we can scale mock RAM: + let gb = 1u64 << 30; + // Set RAM such that soft = est - 1, hard = est + 1000: + // With 12 GiB RAM: S = 6 GiB, H = 9 GiB. + let snap = crate::memory::MemorySnapshot { available_ram: Some(12 * gb), swap_free: None, commit_headroom: None }; + crate::memory::with_mock_memory(snap, || { + // Without caller limit, small file is << 6 GiB -> automatically admitted + assert!(crate::import_with_options("small.psd", &bytes, &crate::ImportOptions::default()).is_ok()); + + // Now set caller limit to est + 1: + // Then hard = est + 1, soft = est + 1. + let opts = crate::ImportOptions { psd_max_pixel_bytes: est + 1, ..Default::default() }; + assert!(crate::import_with_options("small.psd", &bytes, &opts).is_ok()); + + // Now set caller limit to est - 1: + // Then hard = est - 1 -> refused + let opts = crate::ImportOptions { psd_max_pixel_bytes: est - 1, ..Default::default() }; + assert!(matches!(crate::import_with_options("small.psd", &bytes, &opts), Err(IoError::PsdImportBudget { .. }))); + }); +} + +#[test] +fn explicit_approval_allows_confirmation_range_but_never_bypasses_hard_boundary() { + if cfg!(any(target_arch = "wasm32", target_pointer_width = "32")) { + return; // the 6 GiB hard limit is above the 32-bit aggregate cap + } + let gb = 1u64 << 30; + + // Scale RAM so that est falls between S and H: + // S = 50% A, H = 75% A. + // We want S < est <= H. + // So 0.50 A < est <= 0.75 A => (4/3) est <= A < 2 est. + // If A = 1.6 * est, then S = 0.8 est, H_pct = 1.2 est. + // To satisfy saturating A - 1 GiB: we test pure policy decision: + let snap = crate::memory::MemorySnapshot { available_ram: Some(8 * gb), swap_free: None, commit_headroom: None }; + let budget = crate::memory::resolve_budget(snap, None); + assert_eq!(budget.soft_limit, 4 * gb); + assert_eq!(budget.hard_limit, 6 * gb); + + // In confirmation range: + let mid = 5 * gb; + assert_eq!(budget.decide(mid), crate::memory::BudgetDecision::RequiresApproval); + + // Over hard limit: + let over = 7 * gb; + assert_eq!(budget.decide(over), crate::memory::BudgetDecision::Refused); +} + +#[test] +fn zero_available_ram_refuses_admission() { + if cfg!(target_arch = "wasm32") { + return; // the web policy ignores a host snapshot; it has its own tests + } + let file = testgen::small(Version::Psd, Compression::Zip); + let bytes = file.to_bytes().unwrap(); + + let snap = crate::memory::MemorySnapshot { available_ram: Some(0), swap_free: None, commit_headroom: None }; + crate::memory::with_mock_memory(snap, || { + let opts = crate::ImportOptions::default(); + let res = crate::import_with_options("small.psd", &bytes, &opts); + assert!(matches!(res, Err(IoError::PsdImportBudget { .. }))); + }); +} + +#[test] +fn preflight_rejection_and_approval_files_release_gate() { + if cfg!(any(target_arch = "wasm32", target_pointer_width = "32")) { + return; + } + let mut file = testgen::small(Version::Psd, Compression::Zip); + file.header.width = 1; + file.header.height = 1; + file.layers_mut()[0].rect = Rect::from_xywh(0, 0, 30_000, 30_000); + let bytes = file.to_bytes().unwrap(); + + let gb = 1u64 << 30; + // Set RAM such that this large layer exceeds hard limit + let snap = crate::memory::MemorySnapshot { available_ram: Some(4 * gb), swap_free: None, commit_headroom: None }; + crate::memory::with_mock_memory(snap, || { + assert!(!crate::psd_gate::is_holding_admission()); + let res = crate::import_with_options("huge.psd", &bytes, &crate::ImportOptions::default()); + assert!(matches!(res, Err(IoError::PsdImportBudget { .. }))); + // Gate must not be held after rejection + assert!(!crate::psd_gate::is_holding_admission()); + }); + + // Set RAM such that file falls in confirmation range + let est = estimate(&file); + let snap_mid = crate::memory::MemorySnapshot { available_ram: Some(est * 2), swap_free: None, commit_headroom: None }; + crate::memory::with_mock_memory(snap_mid, || { + assert!(!crate::psd_gate::is_holding_admission()); + let res = crate::import_with_options("mid.psd", &bytes, &crate::ImportOptions::default()); + assert!(matches!(res, Err(IoError::PsdApprovalRequired { .. }))); + // Gate must not be held when requiring approval + assert!(!crate::psd_gate::is_holding_admission()); + }); +} + +#[test] +fn retry_estimate_cap_rejects_altered_or_enlarged_file() { + if cfg!(any(target_arch = "wasm32", target_pointer_width = "32")) { + return; + } + let gb = 1u64 << 30; + let snap = crate::memory::MemorySnapshot { available_ram: Some(12 * gb), swap_free: None, commit_headroom: None }; + // S = 6 GiB, H = 9 GiB + + // 1. Within approved_estimate: passes + let res = crate::memory::evaluate_psd_admission(7 * gb, 0, 0, true, Some(7 * gb), snap); + assert!(res.is_ok()); + + // 2. Fresh requirement exceeds approved_estimate: requires fresh approval + let res = crate::memory::evaluate_psd_admission(8 * gb, 0, 0, true, Some(7 * gb), snap); + assert!(matches!(res, Err(IoError::PsdApprovalRequired { required, .. }) if required == 8 * gb)); + + // 3. Exceeds hard limit: refused completely regardless of approval + let res = crate::memory::evaluate_psd_admission(10 * gb, 0, 0, true, Some(10 * gb), snap); + assert!(matches!(res, Err(IoError::PsdImportBudget { required, limit }) if required == 10 * gb && limit == 9 * gb)); +} + +#[test] +fn caller_zero_and_lower_caps_cannot_bypass_hard_boundary() { + if cfg!(any(target_arch = "wasm32", target_pointer_width = "32")) { + return; + } + let gb = 1u64 << 30; + let snap = crate::memory::MemorySnapshot { available_ram: Some(8 * gb), swap_free: None, commit_headroom: None }; + // S = 4 GiB, H = 6 GiB + + // 0 uses adaptive budget + let b_zero = crate::memory::resolve_budget(snap, Some(0)); + assert_eq!(b_zero.hard_limit, 6 * gb); + assert_eq!(b_zero.soft_limit, 4 * gb); + + // Lower cap lowers both hard and soft + let b_lower = crate::memory::resolve_budget(snap, Some(3 * gb)); + assert_eq!(b_lower.hard_limit, 3 * gb); + assert_eq!(b_lower.soft_limit, 3 * gb); + + // Higher cap cannot raise above hard limit + let b_higher = crate::memory::resolve_budget(snap, Some(20 * gb)); + assert_eq!(b_higher.hard_limit, 6 * gb); + assert_eq!(b_higher.soft_limit, 4 * gb); +} + +#[test] +fn test_memory_scope_propagates_to_worker_thread() { + let gb = 1u64 << 30; + let mock = crate::memory::MemorySnapshot { available_ram: Some(4 * gb), swap_free: None, commit_headroom: None }; + crate::memory::with_mock_memory(mock, || { + let scope = crate::memory::TestMemoryScope::capture(); + let handle = std::thread::spawn(move || { + scope.run(|| { + assert_eq!(crate::memory::MemorySnapshot::current().available_ram, Some(4 * gb)); + }); + }); + handle.join().unwrap(); + }); +} + +#[test] +fn test_memory_scope_propagates_the_estimate_charge_to_a_worker() { + let gb = 1u64 << 30; + let file = std::sync::Arc::new(testgen::small(Version::Psd, Compression::Zip)); + let bare = estimate(&file); + with_test_estimate_charge(2 * gb, || { + assert_eq!(estimate(&file), bare + 2 * gb, "the charge is part of the estimate on this thread"); + let scope = crate::memory::TestMemoryScope::capture(); + let worker_file = std::sync::Arc::clone(&file); + std::thread::spawn(move || { + scope.run(|| assert_eq!(estimate(&worker_file), bare + 2 * gb, "a captured scope carries the charge to its worker")); + }) + .join() + .unwrap(); + }); + assert_eq!(estimate(&file), bare, "the charge is restored on this thread"); + let detached = std::sync::Arc::clone(&file); + assert_eq!(std::thread::spawn(move || estimate(&detached)).join().unwrap(), bare, "a worker outside the scope never sees it"); +} + +#[test] +fn nested_imports_consume_from_shared_allowance_and_do_not_reset_parent() { + let gb = 1u64 << 30; + let ctl = photocraft_raster::Interrupt::NONE; + let _guard = crate::psd_gate::acquire_decode_admission(&ctl).unwrap(); + // Simulate top-level attempt authorized total of 5 GB with 2 GB remaining allowance + crate::psd_gate::set_active_attempt_budget(2 * gb); + + // First nested consume fits within 2 GB + assert!(crate::psd_gate::consume_attempt_allowance(gb).is_ok()); + + // Second nested consume exceeds remaining 1 GB + let err = crate::psd_gate::consume_attempt_allowance(2 * gb).unwrap_err(); + assert!(matches!(err, IoError::PsdImportBudget { required, limit } if required == 2 * gb && limit == gb)); + + // Allowance is still 1 GB (failed attempt does not reset or corrupt parent) + assert!(crate::psd_gate::consume_attempt_allowance(gb).is_ok()); + assert!(crate::psd_gate::consume_attempt_allowance(1).is_err()); +} + +#[test] +fn nested_tiff_layer_import_consumes_composite_and_estimate_without_resetting_parent() { + let gb = 1u64 << 30; + let ctl = photocraft_raster::Interrupt::NONE; + let _guard = crate::psd_gate::acquire_decode_admission(&ctl).unwrap(); + crate::psd_gate::set_active_attempt_budget(3 * gb); + + assert!(crate::psd_gate::is_holding_admission()); + assert!(crate::psd_gate::consume_attempt_allowance(gb).is_ok()); + assert!(crate::psd_gate::consume_attempt_allowance(2 * gb).is_ok()); + assert!(crate::psd_gate::consume_attempt_allowance(1).is_err()); +} + +/// A real import carries the approval flag and its estimate bound into admission: the fixture is +/// tiny, and a thread-local test charge puts it in the confirmation band without allocating +/// gigabytes. +#[test] +fn real_import_propagates_high_memory_approval_and_its_estimate_bound() { + if cfg!(any(target_arch = "wasm32", target_pointer_width = "32")) { + return; + } + let gb = 1u64 << 30; + let file = testgen::small(Version::Psd, Compression::Zip); + let bytes = file.to_bytes().unwrap(); + let snapshot = crate::memory::MemorySnapshot { available_ram: Some(12 * gb), swap_free: None, commit_headroom: None }; + crate::memory::with_mock_memory(snapshot, || { + let automatic_layers = + crate::import_with_options("approval.psd", &bytes, &crate::ImportOptions::default()).expect("small file is automatic").document.layers.len(); + with_test_estimate_charge(7 * gb, || { + let required = match crate::import_with_options("approval.psd", &bytes, &crate::ImportOptions::default()) { + Err(IoError::PsdApprovalRequired { required, soft_limit, hard_limit, available_ram }) => { + assert_eq!((soft_limit, hard_limit), (6 * gb, 9 * gb)); + assert_eq!(available_ram, Some(12 * gb)); + required + } + other => panic!("expected an approval request, got {other:?}"), + }; + assert!((7 * gb..=9 * gb).contains(&required), "the charge lands in the approval band: {required}"); + + let approved = crate::ImportOptions { psd_high_memory_approved: true, ..Default::default() }; + assert_eq!( + crate::import_with_options("approval.psd", &bytes, &approved).expect("approved").document.layers.len(), + automatic_layers, + "an approved import decodes the same document as an automatic one" + ); + let bounded = crate::ImportOptions { psd_high_memory_approved: true, psd_approved_estimate: Some(required), ..Default::default() }; + assert!(crate::import_with_options("approval.psd", &bytes, &bounded).is_ok()); + let stale = crate::ImportOptions { psd_high_memory_approved: true, psd_approved_estimate: Some(required - 1), ..Default::default() }; + assert!(matches!(crate::import_with_options("approval.psd", &bytes, &stale), Err(IoError::PsdApprovalRequired { .. }))); + let lowered = crate::ImportOptions { psd_high_memory_approved: true, psd_max_pixel_bytes: required - 1, ..Default::default() }; + assert!(matches!( + crate::import_with_options("approval.psd", &bytes, &lowered), + Err(IoError::PsdImportBudget { required: r, limit: l }) if r == required && l == required - 1 + )); + }); + }); +} + +/// Available memory can drop while an import waits for the decode gate. The post-gate recheck +/// must then refuse before anything is decoded. A per-attempt provider, shared with this test +/// only, changes the measurement while the worker is blocked; nothing near a gigabyte is +/// allocated, and the real document is never opened. +#[test] +fn memory_drop_while_waiting_for_the_gate_refuses_before_decoding() { + use std::sync::Arc; + use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; + use std::time::{Duration, Instant}; + + if cfg!(any(target_arch = "wasm32", target_pointer_width = "32")) { + return; + } + let gb = 1u64 << 30; + let file = testgen::small(Version::Psd, Compression::Zip); + let bytes = file.to_bytes().unwrap(); + + // Hold the gate so the worker stops after its first admission check. + let _guard = crate::psd_gate::acquire_decode_admission(&photocraft_raster::Interrupt::NONE).expect("active decode"); + + let available = Arc::new(AtomicU64::new(32 * gb)); + let prechecked = Arc::new(AtomicBool::new(false)); + let (tx, rx) = std::sync::mpsc::channel(); + let handle = { + let available = Arc::clone(&available); + let prechecked = Arc::clone(&prechecked); + std::thread::spawn(move || { + let provider = std::rc::Rc::new(move || { + prechecked.store(true, Ordering::SeqCst); + crate::memory::MemorySnapshot { available_ram: Some(available.load(Ordering::SeqCst)), swap_free: None, commit_headroom: None } + }); + let result = + crate::memory::with_mock_memory_provider(provider, || crate::import_with_options("drop.psd", &bytes, &crate::ImportOptions::default())); + tx.send(result.map(|r| r.document.layers.len())).ok(); + }) + }; + + // The provider's first call is the pre-gate admission check. + let deadline = Instant::now() + Duration::from_secs(10); + while !prechecked.load(Ordering::SeqCst) { + assert!(Instant::now() < deadline, "the import never reached its admission check"); + std::thread::yield_now(); + } + // The precheck admitted it; now the machine has nothing left. Release the gate afterwards. + available.store(0, Ordering::SeqCst); + drop(_guard); + + let result = rx.recv_timeout(Duration::from_secs(10)).expect("the post-gate recheck must refuse instead of decoding"); + match result { + Err(IoError::PsdImportBudget { required, limit: 0 }) => assert!(required > 0), + other => panic!("expected the post-gate recheck to refuse with a zero budget, got {other:?}"), + } + handle.join().expect("worker thread"); +} + +/// A real import counts its tile pixels as spillable: with a spilling scratch disk they are +/// admitted against RAM plus its room, while non-spillable working memory still needs RAM, and +/// with spilling off the RAM-only policy applies unchanged. Nothing near a gigabyte is allocated. +#[test] +fn real_import_admits_tile_pixels_against_scratch_room_only_while_spilling() { + if cfg!(any(target_arch = "wasm32", target_pointer_width = "32")) { + return; + } + let gb = 1u64 << 30; + let file = testgen::small(Version::Psd, Compression::Zip); + let bytes = file.to_bytes().unwrap(); + let est = estimate(&file); + let snapshot = crate::memory::MemorySnapshot { available_ram: Some(12 * gb), swap_free: None, commit_headroom: None }; + let import = |opts: &crate::ImportOptions| crate::import_with_options("scratch.psd", &bytes, opts); + crate::memory::with_mock_memory(snapshot, || { + assert!(super::estimate(&file).unwrap().tile_bytes > 0, "layer surfaces are tile pixels"); + with_test_tile_charge(18 * gb, || { + let charged = super::estimate(&file).unwrap(); + assert_eq!(charged.total_bytes, est + 18 * gb); + // Spilling off (or paused): 18 GiB of tiles is over H = 9 GiB. + crate::memory::with_mock_scratch(None, || { + assert!(matches!(import(&Default::default()), Err(IoError::PsdImportBudget { limit, .. }) if limit == 9 * gb)); + }); + // Spilling with room for every tile: automatic, no approval. + crate::memory::with_mock_scratch(Some(40 * gb), || { + assert!(import(&Default::default()).is_ok()); + }); + // Room for only part of the tiles: the rest must fit RAM. + crate::memory::with_mock_scratch(Some(4 * gb), || { + assert!(matches!(import(&Default::default()), Err(IoError::PsdImportBudget { .. }))); + }); + }); + // Non-spillable memory gets no scratch credit: 7 GiB still asks for approval. + with_test_estimate_charge(7 * gb, || { + crate::memory::with_mock_scratch(Some(40 * gb), || match import(&Default::default()) { + Err(IoError::PsdApprovalRequired { required, soft_limit, .. }) => { + let tiles = super::estimate(&file).unwrap().tile_bytes; + assert_eq!(soft_limit, 6 * gb + tiles); + assert!(required > soft_limit); + } + other => panic!("expected an approval request, got {other:?}"), + }); + }); + }); +} diff --git a/crates/io/src/psd_gate.rs b/crates/io/src/psd_gate.rs new file mode 100644 index 0000000000..d661166018 --- /dev/null +++ b/crates/io/src/psd_gate.rs @@ -0,0 +1,265 @@ +//! Process-wide serialization gate for PSD/PSB pixel decoding. +//! +//! Prevents concurrent PSD imports from spending the same headroom at the same time, +//! using cancellation-aware waiting outside the UI thread. Reentrant/nested decodes on +//! the same thread are admitted without deadlocking and share the enclosing attempt's +//! budget. Approval prompts never hold this lock. +//! +//! Nested callers check cancellation and take the reentrant guard before calling +//! `consume_attempt_allowance`, so a cancelled or refused nested import never spends its +//! parent's remaining allowance; a failed charge deducts nothing. + +use std::cell::Cell; +use std::marker::PhantomData; +use std::sync::{Condvar, Mutex, OnceLock}; +use std::thread::ThreadId; +#[cfg(any(test, not(target_arch = "wasm32")))] +use std::time::Duration; + +use crate::IoError; + +struct GateState { + active: bool, + owner: Option, +} + +static GATE: OnceLock<(Mutex, Condvar)> = OnceLock::new(); + +/// Returns the process-wide decode gate, creating its mutex and condition variable on first use. +fn get_gate() -> &'static (Mutex, Condvar) { + GATE.get_or_init(|| (Mutex::new(GateState { active: false, owner: None }), Condvar::new())) +} + +thread_local! { + static NESTED_DEPTH: Cell = const { Cell::new(0) }; + static ATTEMPT_ALLOWANCE: Cell> = const { Cell::new(None) }; +} + +/// RAII guard releasing decode admission when dropped. +/// Non-Send and non-Sync to prevent cross-thread leakage or premature release. +pub(crate) struct AdmissionGuard { + _marker: PhantomData<*const ()>, +} + +impl Drop for AdmissionGuard { + fn drop(&mut self) { + let depth = NESTED_DEPTH.with(|d| { + let val = d.get().saturating_sub(1); + d.set(val); + val + }); + if depth == 0 { + ATTEMPT_ALLOWANCE.with(|a| a.set(None)); + let (mutex, cvar) = get_gate(); + let mut state = mutex.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + state.active = false; + state.owner = None; + cvar.notify_one(); + } + } +} + +/// Returns whether the current thread currently holds decode admission. +pub(crate) fn is_holding_admission() -> bool { + NESTED_DEPTH.with(|d| d.get() > 0) +} + +/// Sets the remaining memory allowance for the active import attempt on the current thread. +pub(crate) fn set_active_attempt_budget(allowance: u64) { + ATTEMPT_ALLOWANCE.with(|a| a.set(Some(allowance))); +} + +/// Consumes `bytes` from the enclosing attempt's remaining allowance, or returns +/// [`IoError::PsdImportBudget`] if the required amount exceeds what remains. +/// +/// `u64::MAX` is a format estimate's saturated overflow sentinel, not a requirement: it is +/// refused even when the remaining allowance is also `u64::MAX` (the native unknown-memory +/// attempt cap), and a refusal never spends the parent's allowance. +pub(crate) fn consume_attempt_allowance(bytes: u64) -> Result<(), IoError> { + ATTEMPT_ALLOWANCE.with(|a| match a.get() { + Some(remaining) => { + if bytes == u64::MAX || bytes > remaining { + return Err(IoError::PsdImportBudget { required: bytes, limit: remaining }); + } + a.set(Some(remaining - bytes)); + Ok(()) + } + None => { + // Unknown allowance during reentrant gate must fail closed. + Err(IoError::PsdImportBudget { required: bytes, limit: 0 }) + } + }) +} + +/// The enclosing attempt's remaining allowance, for tests that assert a nested import was +/// charged instead of resetting the parent attempt's budget. +#[cfg(test)] +pub(crate) fn active_attempt_remaining() -> Option { + ATTEMPT_ALLOWANCE.with(|a| a.get()) +} + +/// Acquires process-wide admission to decode PSD pixels, or awaits completion of an active decode. +/// +/// If the current thread already holds admission (a nested/reentrant decode), it is admitted +/// immediately without reacquiring the mutex or waiting on the condvar. Otherwise, it polls +/// `ctl.check()` every 50 ms while waiting so cancellation halts the wait immediately. +pub(crate) fn acquire_decode_admission(ctl: &photocraft_raster::Interrupt) -> Result { + let current_thread = std::thread::current().id(); + let (mutex, _cvar) = get_gate(); + let mut state = mutex.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + + if state.active && state.owner == Some(current_thread) { + ctl.check().map_err(|_| IoError::Cancelled)?; + NESTED_DEPTH.with(|d| d.set(d.get().saturating_add(1))); + return Ok(AdmissionGuard { _marker: PhantomData }); + } + + #[cfg(target_arch = "wasm32")] + if state.active { + // Stateless wasm is single-threaded: contention cannot be resolved by waiting on Condvar. + return Err(IoError::Unsupported("concurrent PSD decoding is not supported on wasm".into())); + } + + #[cfg(not(target_arch = "wasm32"))] + while state.active { + ctl.check().map_err(|_| IoError::Cancelled)?; + let (next_state, _) = _cvar.wait_timeout(state, Duration::from_millis(50)).unwrap_or_else(std::sync::PoisonError::into_inner); + state = next_state; + } + + ctl.check().map_err(|_| IoError::Cancelled)?; + state.active = true; + state.owner = Some(current_thread); + NESTED_DEPTH.with(|d| d.set(1)); + + Ok(AdmissionGuard { _marker: PhantomData }) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Arc; + use std::sync::atomic::{AtomicBool, Ordering}; + + #[test] + fn reentrant_admission_does_not_deadlock() { + let ctl = photocraft_raster::Interrupt::NONE; + let guard1 = acquire_decode_admission(&ctl).unwrap(); + assert!(is_holding_admission()); + + // Nested admission on the same thread + let guard2 = acquire_decode_admission(&ctl).unwrap(); + assert!(is_holding_admission()); + + drop(guard2); + assert!(is_holding_admission()); + drop(guard1); + assert!(!is_holding_admission()); + + // Can acquire again after release + let _guard3 = acquire_decode_admission(&ctl).unwrap(); + assert!(is_holding_admission()); + } + + #[test] + fn unknown_allowance_during_reentrant_gate_fails_closed() { + let ctl = photocraft_raster::Interrupt::NONE; + let _guard = acquire_decode_admission(&ctl).unwrap(); + // Allowance is None (unknown) + let res = consume_attempt_allowance(100); + assert!(matches!(res, Err(IoError::PsdImportBudget { limit: 0, .. }))); + } + + #[test] + fn nested_allowance_consumption_deducts_and_caps() { + let ctl = photocraft_raster::Interrupt::NONE; + let _guard = acquire_decode_admission(&ctl).unwrap(); + set_active_attempt_budget(5000); + + assert!(consume_attempt_allowance(2000).is_ok()); + assert_eq!(ATTEMPT_ALLOWANCE.with(|a| a.get()), Some(3000)); + + assert!(consume_attempt_allowance(3001).is_err()); + assert!(consume_attempt_allowance(1000).is_ok()); + assert_eq!(ATTEMPT_ALLOWANCE.with(|a| a.get()), Some(2000)); + } + + /// A saturated estimate is not a charge, even when the parent's allowance is the same + /// saturated value: it is refused and spends nothing. + #[test] + fn a_saturated_nested_charge_is_refused_and_spends_nothing() { + let ctl = photocraft_raster::Interrupt::NONE; + let _guard = acquire_decode_admission(&ctl).unwrap(); + set_active_attempt_budget(u64::MAX); + + let err = consume_attempt_allowance(u64::MAX).expect_err("the overflow sentinel is never a charge"); + assert!(matches!(err, IoError::PsdImportBudget { required, limit } if required == u64::MAX && limit == u64::MAX)); + assert_eq!(active_attempt_remaining(), Some(u64::MAX), "a refused sentinel charge leaves the parent's allowance untouched"); + + // One byte below the sentinel is an ordinary, enormous charge. + assert!(consume_attempt_allowance(u64::MAX - 1).is_ok()); + assert_eq!(active_attempt_remaining(), Some(1)); + } + + #[test] + fn gate_serializes_concurrent_threads() { + let ctl = photocraft_raster::Interrupt::NONE; + let guard = acquire_decode_admission(&ctl).unwrap(); + + let thread_started = Arc::new(AtomicBool::new(false)); + let thread_acquired = Arc::new(AtomicBool::new(false)); + + let t_started = Arc::clone(&thread_started); + let t_acquired = Arc::clone(&thread_acquired); + let handle = std::thread::spawn(move || { + let ctl = photocraft_raster::Interrupt::NONE; + t_started.store(true, Ordering::SeqCst); + let g = acquire_decode_admission(&ctl).unwrap(); + t_acquired.store(true, Ordering::SeqCst); + drop(g); + }); + + while !thread_started.load(Ordering::SeqCst) { + std::thread::yield_now(); + } + // Give background thread time to reach condvar wait + std::thread::sleep(Duration::from_millis(60)); + assert!(!thread_acquired.load(Ordering::SeqCst), "second thread must block while guard held"); + + drop(guard); + handle.join().unwrap(); + assert!(thread_acquired.load(Ordering::SeqCst), "second thread must acquire after release"); + } + + #[test] + fn blocked_wait_aborts_on_cancellation() { + let ctl = photocraft_raster::Interrupt::NONE; + let guard = acquire_decode_admission(&ctl).unwrap(); + + let cancelled = Arc::new(AtomicBool::new(false)); + let c_flag = Arc::clone(&cancelled); + + let flag_for_thread = Arc::clone(&cancelled); + let handle = std::thread::spawn(move || { + let cancelled = || flag_for_thread.load(Ordering::SeqCst); + let progress = |_: f32| {}; + let interrupt = photocraft_raster::Interrupt::new(&cancelled, &progress); + acquire_decode_admission(&interrupt).map(drop) + }); + + // Let thread block on condvar + std::thread::sleep(Duration::from_millis(60)); + // Cancel waiting thread + c_flag.store(true, Ordering::SeqCst); + + let res = handle.join().unwrap(); + assert!(matches!(res, Err(IoError::Cancelled)), "waiting thread must abort with Cancelled"); + + // First thread releases guard + drop(guard); + + // Subsequent acquire succeeds cleanly + let next_guard = acquire_decode_admission(&ctl); + assert!(next_guard.is_ok(), "gate must remain functional after cancelled wait"); + } +} diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rs index a70577fb6f..12aabf6e8d 100644 --- a/crates/io/src/psd_import.rs +++ b/crates/io/src/psd_import.rs @@ -1228,6 +1228,30 @@ pub(crate) fn psd_to_document_decoded_integrity( psd_to_document_global(file, ctl, decoded, global, false).map(|(doc, warnings, damaged, _)| (doc, warnings, damaged)) } +/// Admission for a legacy conversion. +/// +/// A nested conversion spends the enclosing attempt's remaining allowance and never resets it. +/// A standalone conversion refuses an ineligible file before waiting for the decode gate and +/// rechecks the fresh measurement once admitted, so a refused file never waits behind an active +/// decode and a memory drop during the wait is seen before any pixel is decoded. +fn legacy_admission(est: &crate::psd_budget::PsdMemoryEstimate, ctl: &photocraft_raster::Interrupt) -> Result { + if crate::psd_gate::is_holding_admission() { + // Cancellation is checked before the charge and admission is reentrant here, so a + // cancelled or refused nested conversion never spends its parent's allowance. + ctl.check().map_err(|_| crate::IoError::Cancelled)?; + let guard = crate::psd_gate::acquire_decode_admission(ctl)?; + crate::psd_gate::consume_attempt_allowance(est.total_bytes)?; + return Ok(guard); + } + let snapshot = || crate::memory::MemorySnapshot::current(); + // Legacy standalone is unconfirmed: it cannot silently auto allow an estimate above S. + crate::memory::evaluate_psd_admission(est.total_bytes, est.tile_bytes, 0, false, None, snapshot())?; + let guard = crate::psd_gate::acquire_decode_admission(ctl)?; + let outcome = crate::memory::evaluate_psd_admission(est.total_bytes, est.tile_bytes, 0, false, None, snapshot())?; + crate::psd_gate::set_active_attempt_budget(outcome.authorized_total.saturating_sub(est.total_bytes)); + Ok(guard) +} + fn psd_to_document_global( file: &PsdFile, ctl: &photocraft_raster::Interrupt, @@ -1238,11 +1262,26 @@ fn psd_to_document_global( // Legacy conversion APIs return warnings rather than Result. Reject before metadata or // pixels are decoded, and retain the fatal error for the ordinary import path. An import // that checked the file against its own limit first (`preflighted`) does not estimate twice. - if !preflighted && let Err(error) = crate::psd_budget::check(file, crate::DEFAULT_PSD_IMPORT_PIXEL_BYTES) { - let message = error.to_string(); - let doc = Document::new("Untitled", Size::new(1, 1), ColorMode::Rgb, SampleType::U8); - return Some((doc, vec![message], true, Some(error))); - } + let _guard = if !preflighted || !crate::psd_gate::is_holding_admission() { + let est = match crate::psd_budget::estimate(file) { + Ok(e) => e, + Err(error) => { + let message = error.to_string(); + let doc = Document::new("Untitled", Size::new(1, 1), ColorMode::Rgb, SampleType::U8); + return Some((doc, vec![message], true, Some(error))); + } + }; + match legacy_admission(&est, ctl) { + Ok(guard) => Some(guard), + Err(error) => { + let message = error.to_string(); + let doc = Document::new("Untitled", Size::new(1, 1), ColorMode::Rgb, SampleType::U8); + return Some((doc, vec![message], true, Some(error))); + } + } + } else { + None + }; let (mode, layered, multichannel, depth) = import_format(file); let h = &file.header; let mut warnings = Vec::new(); diff --git a/crates/io/src/psd_import/tests.rs b/crates/io/src/psd_import/tests.rs index 3fc4e3222e..a2b42161e4 100644 --- a/crates/io/src/psd_import/tests.rs +++ b/crates/io/src/psd_import/tests.rs @@ -600,3 +600,30 @@ fn only_allocation_failures_are_fatal_to_a_layer_channel() { other => panic!("{other:?}"), } } + +/// A standalone legacy conversion that is over budget is refused *before* it waits for the +/// decode gate, so an ineligible file never blocks behind an active decode. The legacy API keeps +/// its warning (the ordinary import path still receives the fatal error). +#[test] +fn legacy_conversion_refuses_before_waiting_for_the_decode_gate() { + let mut file = testgen::small(Version::Psd, Compression::Zip); + // 30,000² tiles are several GiB: far past the hard budget of the 4 GiB machine below. + file.layers_mut()[0].rect = photocraft_psd::Rect::from_xywh(0, 0, 30_000, 30_000); + let snapshot = crate::memory::MemorySnapshot { available_ram: Some(4 << 30), swap_free: None, commit_headroom: None }; + let ctl = photocraft_raster::Interrupt::NONE; + let _guard = crate::psd_gate::acquire_decode_admission(&ctl).expect("active decode"); + + let (tx, rx) = std::sync::mpsc::channel(); + let handle = std::thread::spawn(move || { + let (doc, warnings) = crate::memory::with_mock_memory(snapshot, || crate::psd_to_document(&file)); + tx.send((doc.layers.len(), warnings)).ok(); + }); + + // The refusal arrives while this thread still holds the gate: the legacy call never waited. + let (layers, warnings) = rx.recv_timeout(std::time::Duration::from_secs(10)).expect("a refused legacy conversion must not wait for the decode gate"); + assert_eq!(layers, 0, "a refused conversion returns an empty document"); + assert!(warnings.iter().any(|w| w.contains("pixel memory")), "{warnings:?}"); + + drop(_guard); + handle.join().expect("worker thread"); +} diff --git a/crates/io/src/tiff_layers.rs b/crates/io/src/tiff_layers.rs index f001b6a265..e382ff108c 100644 --- a/crates/io/src/tiff_layers.rs +++ b/crates/io/src/tiff_layers.rs @@ -48,19 +48,64 @@ fn set_resource(resources: &mut Vec, id: u16, data: Option Result { - let mut warnings = Vec::new(); - let (isd, w) = match ImageSourceData::from_bytes(layers) { +/// Everything a layered TIFF page's Photoshop tags say, read before any pixel is decoded. +/// +/// It is built from a [`codecs::TiffBands`] page's dimensions, layout, sample type, +/// extra-sample count, metadata and decoder scratch bound, never from its pixels, so the whole +/// import is admitted through the adaptive budget before the composite is decoded. +pub(crate) struct LayeredPlan { + /// The PSD model the layer tag rebuilds, or `None` when the tag could not be read and the + /// page opens flattened. + model: Option>, + /// Why the page opens flattened, when the layer tag did not parse. + flatten_warning: Option, + /// Warnings the layer tag and the image resources produced. + warnings: Vec, + /// Bytes this import needs beside what it already holds, for admission; see + /// [`layered_import_bytes`]. + pub(crate) required: u64, + /// The part of `required` that is tile pixels, spillable to the scratch disk + /// ([`crate::psd_budget::PsdMemoryEstimate::tile_bytes`]); 0 for a flattened fallback, whose + /// admission charge is decode and conversion memory. + pub(crate) tiles: u64, +} + +struct LayeredModel { + /// The PSD model with an empty merged image: the TIFF's pixels replace it after decoding. + file: photocraft_psd::PsdFile, +} + +impl LayeredPlan { + /// Whether the page's layer tag parsed into a PSD model, as opposed to opening flattened. + /// + /// A flattened fallback still reads the page's image resources for channel names and spot + /// flags, so the decoder's copies stay available; a layered page's tags are already in the + /// plan and the decoder's copies can be dropped. + pub(crate) fn is_layered(&self) -> bool { + self.model.is_some() + } +} + +/// Reads a layered TIFF page's layer tag and image resources into a [`LayeredPlan`] without +/// decoding any pixels, and checks the group nesting depth and the PSD memory estimate. +pub(crate) fn preflight(bands: &codecs::TiffBands<'_>) -> Result { + let (w, h) = bands.dimensions(); + let (layout, sample) = (bands.layout(), bands.sample_type()); + let extras = bands.extra_samples(); + let scratch = bands.decode_scratch_bytes(); + let layers = bands.meta.photoshop_layers.as_deref().unwrap_or_default(); + let (isd, isd_warnings) = match ImageSourceData::from_bytes(layers) { Ok(v) => v, Err(e) => { - let mut r = image_to_document(name, img)?; - r.warnings.push(format!("the PSD layer data could not be read ({e}); opened flattened")); - return Ok(r); + // Malformed layer data opens flat, but the composite it opens still has to be + // bounded: its whole-image decode and the conversion are admitted too. + let warning = format!("the PSD layer data could not be read ({e}); opened flattened"); + let required = crate::flat::flattened_import_bytes(w, h, layout, sample, extras, scratch); + return Ok(LayeredPlan { model: None, flatten_warning: Some(warning), warnings: Vec::new(), required, tiles: 0 }); } }; - warnings.extend(w.into_iter().map(|w| format!("layer data: {w}"))); - let (mut resources, w) = match img.meta.photoshop_resources.as_deref().filter(|r| !r.is_empty()).map(resources_from_bytes) { + let mut warnings: Vec = isd_warnings.into_iter().map(|w| format!("layer data: {w}")).collect(); + let (mut resources, resource_warnings) = match bands.meta.photoshop_resources.as_deref().filter(|r| !r.is_empty()).map(resources_from_bytes) { Some(Ok(v)) => v, Some(Err(e)) => { warnings.push(format!("the PSD image resources could not be read: {e}")); @@ -68,44 +113,38 @@ pub(crate) fn import_layered(name: &str, img: &Image, layers: &[u8], pixel_limit } None => (Vec::new(), Vec::new()), }; - warnings.extend(w.into_iter().map(|w| format!("image resources: {w}"))); - // The profile, resolution, XMP and EXIF are the TIFF's own tags; they win over any copy - // in the resources. - set_resource(&mut resources, ids::ICC_PROFILE, img.icc.clone()); - if let Some((x, y)) = img.meta.dpi.filter(|d| d.0 > 0.0) { + warnings.extend(resource_warnings.into_iter().map(|w| format!("image resources: {w}"))); + // The profile, resolution, XMP and EXIF are the TIFF's own tags; they win over any copy in + // the resources. They are set here, from the page's metadata, because the model is complete + // before the composite exists. + set_resource(&mut resources, ids::ICC_PROFILE, bands.icc.clone()); + if let Some((x, y)) = bands.meta.dpi.filter(|d| d.0 > 0.0) { // Both axes, so the PSD import notes a vertical resolution the document can't keep. let ri = ResolutionInfo { v_res_fixed: ResolutionInfo::from_dpi(f64::from(y)).v_res_fixed, ..ResolutionInfo::from_dpi(f64::from(x)) }; set_resource(&mut resources, ids::RESOLUTION_INFO, Some(ri.to_bytes())); } - if let Some(xmp) = &img.meta.xmp { + if let Some(xmp) = &bands.meta.xmp { set_resource(&mut resources, ids::XMP, Some(xmp.as_bytes().to_vec())); } - if let Some(exif) = &img.meta.exif { + if let Some(exif) = &bands.meta.exif { set_resource(&mut resources, ids::EXIF, Some(exif.clone())); } // The TIFF's pixels become the PSD's merged image: planar, big-endian, CMYK inverted. - let (mode, color_channels) = match img.layout() { - ChannelLayout::Gray | ChannelLayout::GrayA => (PsdMode::Grayscale, 1), - ChannelLayout::Rgb | ChannelLayout::Rgba => (PsdMode::Rgb, 3), - ChannelLayout::Cmyk | ChannelLayout::CmykA => (PsdMode::Cmyk, 4), - ChannelLayout::Lab | ChannelLayout::LabA => (PsdMode::Lab, 3), + let mode = match layout { + ChannelLayout::Gray | ChannelLayout::GrayA => PsdMode::Grayscale, + ChannelLayout::Rgb | ChannelLayout::Rgba => PsdMode::Rgb, + ChannelLayout::Cmyk | ChannelLayout::CmykA => PsdMode::Cmyk, + ChannelLayout::Lab | ChannelLayout::LabA => PsdMode::Lab, }; - let depth = match img.sample_type() { + let depth = match sample { CSample::U8 => 8, CSample::U16 => 16, CSample::F16 | CSample::F32 => 32, }; - let (w, h) = img.dimensions(); - // A half-float image is stored as 32-bit float; it is converted after the budget check, as - // the conversion allocates several times the decoded image. - let bps = if img.sample_type() == CSample::F16 { CSample::F32.bytes() } else { img.sample_type().bytes() }; - let plane_len = (w as usize).saturating_mul(h as usize).saturating_mul(bps); - // The budget is checked on the model before the planar copy of the whole image is allocated, - // so an over-budget file is refused without it. The extra samples that fit the image count - // towards the channels the check sees. - let extras = img.meta.extra_samples.iter().take(codecs::MAX_EXTRA_SAMPLES).filter(|e| e.data.len() == plane_len).count(); - let channels = u16::try_from(img.layout().channels().saturating_add(extras)).map_err(|_| IoError::Unsupported("too many channels".into()))?; + // The extra samples that fit the image count towards the channels the estimate sees; the + // codec already capped them at [`codecs::MAX_EXTRA_SAMPLES`]. + let channels = u16::try_from(layout.channels().saturating_add(extras)).map_err(|_| IoError::Unsupported("too many channels".into()))?; let header = Header::new(isd.version, w, h, channels, depth, mode); let mut file = isd.into_psd(header, resources, ImageData::new(Compression::Raw, Vec::new())); // Empty `Patt` and the default filter mask are written so Photoshop's block list matches @@ -118,13 +157,73 @@ pub(crate) fn import_layered(name: &str, img: &Image, layers: &[u8], pixel_limit }); // The same nesting limit as opening a PSD (#2940). crate::psd_import::check_group_depth(&file)?; - // The planar composite is copied whether or not the budget counts a merged image, so it is - // held against the allowance as well. - let composite = u64::try_from(plane_len.saturating_mul(usize::from(channels))).unwrap_or(u64::MAX); - if composite > pixel_limit { - return Err(photocraft_psd::PsdError::LimitExceeded("the TIFF composite exceeds the import allowance").into()); - } - crate::psd_budget::check(&file, pixel_limit - composite)?; + // Layer/mask/merged pixel planes and their conversion workspace, from the tag alone. + let est = crate::psd_budget::estimate(&file)?; + // The decoder makes its own copy of the two Photoshop tags while decoding. The plan's + // copies are already made and are bounded by the file, not by the image size. + let tags = layers.len().saturating_add(bands.meta.photoshop_resources.as_ref().map_or(0, |r| r.len())); + let required = layered_import_bytes(est.total_bytes, w, h, layout.channels(), sample, extras, scratch, tags); + Ok(LayeredPlan { model: Some(Box::new(LayeredModel { file })), flatten_warning: None, warnings, required, tiles: est.tile_bytes }) +} + +/// Bytes a layered TIFF import needs beyond [`crate::psd_budget::estimate`]'s layer, mask, +/// merged and workspace charge: +/// +/// - the decoded composite and its extra-sample planes: the decoder holds the interleaved extra +/// buffer and one split plane per sample at once; +/// - for a 16-bit float page, the normalized and 32-bit copies the conversion makes while the +/// 16-bit image and its planes are still alive; +/// - the planar big-endian merged-image copy, with one extra plane copied while it grows; +/// - the decoder's own scratch buffers (see [`codecs::TiffBands::decode_scratch_bytes`]); +/// - the decoder's copy of the Photoshop tags. +/// +/// Every term saturates instead of wrapping: an estimate too large for `u64` is the `u64::MAX` +/// sentinel, which admission always refuses (see [`crate::memory::MemoryBudget::decide`]), so it +/// can never become an admitted, wrapped-around value. +#[allow(clippy::too_many_arguments)] +pub(crate) fn layered_import_bytes(est: u64, w: u32, h: u32, channels: usize, sample: CSample, extras: usize, scratch: u64, tags: usize) -> u64 { + let pixels = u64::from(w).saturating_mul(u64::from(h)); + let ch = channels as u64; + let e = extras as u64; + let in_bps = sample.bytes() as u64; + let out_bps = if sample == CSample::F16 { CSample::F32.bytes() as u64 } else { in_bps }; + let decoded = pixels.saturating_mul(ch.saturating_add(e.saturating_mul(2))).saturating_mul(in_bps); + // A normalized 32-bit buffer and the 32-bit result exist beside the 16-bit source. + let float_convert = if sample == CSample::F16 { pixels.saturating_mul(ch.saturating_add(e)).saturating_mul(8) } else { 0 }; + let planar = pixels.saturating_mul(ch.saturating_add(e)).saturating_mul(out_bps); + let plane = if e > 0 { pixels.saturating_mul(out_bps) } else { 0 }; + est.saturating_add(decoded).saturating_add(float_convert).saturating_add(planar).saturating_add(plane).saturating_add(scratch).saturating_add(tags as u64) +} + +/// Opens a layered TIFF page from its decoded `img`, using the model and estimate [`preflight`] +/// read from the same page's tags. +/// +/// The caller has admitted `plan.required` through the adaptive budget and holds decode +/// admission before any pixel is decoded, so nothing here resolves a second budget or charges +/// the enclosing attempt again: a top-level TIFF is charged once, and a nested independent one +/// spends only what its parent still has. `ctl` stops the PSD conversion between layers. +pub(crate) fn import_layered(name: &str, img: &Image, plan: LayeredPlan, ctl: &photocraft_raster::Interrupt) -> Result { + let LayeredPlan { model, flatten_warning, mut warnings, required: _, tiles: _ } = plan; + let Some(model) = model else { + let mut r = image_to_document(name, img)?; + if let Some(warning) = flatten_warning { + r.warnings.push(warning); + } + return Ok(r); + }; + let LayeredModel { mut file } = *model; + let mode = match img.layout() { + ChannelLayout::Gray | ChannelLayout::GrayA => PsdMode::Grayscale, + ChannelLayout::Rgb | ChannelLayout::Rgba => PsdMode::Rgb, + ChannelLayout::Cmyk | ChannelLayout::CmykA => PsdMode::Cmyk, + ChannelLayout::Lab | ChannelLayout::LabA => PsdMode::Lab, + }; + let color_channels = img.layout().color_channels(); + // A half-float image is stored as 32-bit float; it is converted here, after admission, as + // the conversion allocates several times the decoded image (charged by the estimate). + let bps = if img.sample_type() == CSample::F16 { CSample::F32.bytes() } else { img.sample_type().bytes() }; + let (w, h) = img.dimensions(); + let plane_len = (w as usize).saturating_mul(h as usize).saturating_mul(bps); let img = if img.sample_type() == CSample::F16 { warnings.push("16-bit float samples are stored as 32-bit float".to_string()); std::borrow::Cow::Owned(img.convert(img.layout(), CSample::F32)) @@ -149,11 +248,11 @@ pub(crate) fn import_layered(name: &str, img: &Image, layers: &[u8], pixel_limit // Spot planes are read in Photoshop's polarity (0 = solid ink), as from a PSD. The importer's // rule for PSDs from earlier PhotoCraft versions never applies: those versions stored no // extra samples in a TIFF, and a TIFF with them carries 1053. - let (mut doc, w, _, fatal_error) = psd_to_document_owned(file, &photocraft_raster::Interrupt::NONE, None).ok_or(IoError::Cancelled)?; + let (mut doc, psd_warnings, _, fatal_error) = psd_to_document_owned(file, ctl, None).ok_or(IoError::Cancelled)?; if let Some(error) = fatal_error { return Err(error); } - warnings.extend(w); + warnings.extend(psd_warnings); doc.name = name.to_string(); if doc.icc_profile.is_none() { doc.icc_profile = img.icc.clone().map(Arc::new); @@ -996,7 +1095,7 @@ mod tests { use photocraft_doc::{Color, Document, Fill, FillCache, Layer, LayerContent}; use photocraft_raster::Surface; - use crate::{ExportOptions, export}; + use crate::{ExportOptions, ImportOptions, IoError, export}; /// Hidden solid fills on a 2048² canvas: counted as canvas-sized planes (16 MiB each at 8 /// bits), 140 of them pass 2 GB, while their real pixels (the cached rendering, pruned to @@ -1015,6 +1114,30 @@ mod tests { doc } + /// A small two-layer RGB document exported as a TIFF with Photoshop layer data: the real + /// file the admission tests below import. No fixture is decoded at a size near a threshold. + fn layered_tiff(w: u32, h: u32) -> Vec { + let mut doc = Document::new("charge.tif", photocraft_geom::Size::new(w, h), photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8); + let fmt = doc.pixel_format(); + let bytes = (w as usize * h as usize * fmt.bytes_per_pixel()).max(1); + for name in ["bottom", "top"] { + let mut s = Surface::new(fmt); + s.write_interleaved(photocraft_geom::Rect::new(0, 0, w as i32, h as i32), &vec![96u8; bytes]); + doc.layers.push(Layer::new(name, LayerContent::Raster(s))); + } + export(&doc, "charge.tif", &ExportOptions { tiff_layers: true, ..Default::default() }).expect("export layered TIFF").bytes + } + + /// The bytes of the layered TIFF's decoded composite: the size of both the planar copy the + /// importer builds and the interleaved image it keeps beside it. + fn composite_bytes(bytes: &[u8]) -> u64 { + let img = photocraft_codecs::decode_with(bytes, &photocraft_codecs::DecodeOptions { keep_orientation: true, ..Default::default() }) + .expect("decode the composite"); + let (w, h) = img.dimensions(); + let sample = u64::try_from(img.sample_type().bytes()).unwrap_or(1); + u64::from(w).saturating_mul(u64::from(h)).saturating_mul(sample).saturating_mul(img.layout().channels() as u64) + } + #[test] fn layered_tiff_ignores_the_uncompressed_size_estimate() { let doc = many_cheap_fills(); @@ -1039,4 +1162,337 @@ mod tests { let (_, layers) = photocraft_codecs::tiff_photoshop_tags(&r.bytes); assert!(layers.unwrap().starts_with(photocraft_psd::tiff::SIGNATURE_PSB)); } + + /// The adaptive budget, not only the caller's pixel limit, decides a layered TIFF: a known + /// zero reading refuses the import before the planar composite is allocated, while a normal + /// machine opens the same file. Before this route the fixed 2 GiB default admitted it. + #[test] + fn layered_tiff_import_honours_a_known_zero_adaptive_budget() { + let bytes = layered_tiff(8, 6); + let zero = crate::memory::MemorySnapshot { available_ram: Some(0), swap_free: None, commit_headroom: None }; + crate::memory::with_mock_memory(zero, || match crate::import_with_options("zero.tif", &bytes, &ImportOptions::default()) { + Err(IoError::PsdImportBudget { limit: 0, .. }) => {} + other => panic!("expected an import-budget refusal, got {other:?}"), + }); + + let plenty = crate::memory::MemorySnapshot { available_ram: Some(16 << 30), swap_free: None, commit_headroom: None }; + crate::memory::with_mock_memory(plenty, || { + let opened = crate::import_with_options("plenty.tif", &bytes, &ImportOptions::default()).expect("a normal machine opens it"); + assert_eq!(opened.document.layers.len(), 2); + }); + } + + /// Approval and its estimate bound reach the TIFF route: the same options that a PSD takes + /// decide the layered TIFF's composite, layer and retained-image charge. The fixture is tiny; + /// the threshold charge is a thread-local test seam, so nothing near a gigabyte is allocated. + #[test] + fn layered_tiff_import_uses_the_adaptive_budget_approval_options() { + if cfg!(any(target_arch = "wasm32", target_pointer_width = "32")) { + return; + } + let gb = 1u64 << 30; + let bytes = layered_tiff(8, 6); + // 12 GiB: S = 6 GiB, H = 9 GiB. + let snapshot = crate::memory::MemorySnapshot { available_ram: Some(12 * gb), swap_free: None, commit_headroom: None }; + crate::memory::with_mock_memory(snapshot, || { + let plain = crate::import_with_options("l.tif", &bytes, &ImportOptions::default()).expect("automatic").document.layers.len(); + crate::psd_budget::with_test_estimate_charge(7 * gb, || { + let required = match crate::import_with_options("l.tif", &bytes, &ImportOptions::default()) { + Err(IoError::PsdApprovalRequired { required, soft_limit, hard_limit, available_ram }) => { + assert_eq!((soft_limit, hard_limit), (6 * gb, 9 * gb)); + assert_eq!(available_ram, Some(12 * gb)); + required + } + other => panic!("expected an approval request, got {other:?}"), + }; + assert!((7 * gb..=9 * gb).contains(&required), "the charge lands in the approval band: {required}"); + + // Approval opens the same file. + let approved = ImportOptions { psd_high_memory_approved: true, ..Default::default() }; + assert_eq!(crate::import_with_options("l.tif", &bytes, &approved).expect("approved").document.layers.len(), plain); + // A matching one-shot estimate bound is enough; a smaller one needs fresh consent. + let bounded = ImportOptions { psd_high_memory_approved: true, psd_approved_estimate: Some(required), ..Default::default() }; + assert!(crate::import_with_options("l.tif", &bytes, &bounded).is_ok()); + let stale = ImportOptions { psd_high_memory_approved: true, psd_approved_estimate: Some(required - 1), ..Default::default() }; + assert!(matches!(crate::import_with_options("l.tif", &bytes, &stale), Err(IoError::PsdApprovalRequired { .. }))); + // Approval never bypasses a lower caller limit. + let lowered = ImportOptions { psd_high_memory_approved: true, psd_max_pixel_bytes: required - 1, ..Default::default() }; + assert!(matches!( + crate::import_with_options("l.tif", &bytes, &lowered), + Err(IoError::PsdImportBudget { required: r, limit: l }) if r == required && l == required - 1 + )); + }); + }); + } + + /// A real nested layered TIFF spends the enclosing attempt's remaining allowance: the charge + /// covers the planar composite and the decoded image kept beside it, and a refused nested + /// import neither waits for a fresh gate nor resets the parent's budget. + #[test] + fn real_nested_layered_tiff_import_is_charged_without_resetting_the_parent() { + let bytes = layered_tiff(8, 6); + let composite = composite_bytes(&bytes); + assert!(composite > 0); + let ctl = photocraft_raster::Interrupt::NONE; + + let _guard = crate::psd_gate::acquire_decode_admission(&ctl).expect("parent admission"); + let start = 1u64 << 40; + crate::psd_gate::set_active_attempt_budget(start); + crate::import_with_options_and_interrupt("charge.tif", &bytes, &ImportOptions::default(), &ctl).expect("nested import"); + let remaining = crate::psd_gate::active_attempt_remaining().expect("the parent attempt keeps an allowance"); + let charged = start - remaining; + assert!( + charged >= composite.saturating_mul(2), + "both the planar composite ({composite}) and the decoded image kept beside it are charged; charged {charged}" + ); + assert!(crate::psd_gate::is_holding_admission(), "the nested import must not release the parent's admission"); + + // One byte short: the real import is refused, the reason is the charge, and the parent's + // remaining allowance is untouched. + crate::psd_gate::set_active_attempt_budget(charged - 1); + match crate::import_with_options_and_interrupt("charge.tif", &bytes, &ImportOptions::default(), &ctl) { + Err(IoError::PsdImportBudget { required, limit }) => assert_eq!((required, limit), (charged, charged - 1)), + other => panic!("expected an import-budget refusal, got {other:?}"), + } + assert_eq!(crate::psd_gate::active_attempt_remaining(), Some(charged - 1), "a failed nested import leaves the allowance as it was"); + + // Exactly enough succeeds and leaves nothing, so the charge is not reset per attempt. + crate::psd_gate::set_active_attempt_budget(charged); + crate::import_with_options_and_interrupt("charge.tif", &bytes, &ImportOptions::default(), &ctl).expect("exact allowance"); + assert_eq!(crate::psd_gate::active_attempt_remaining(), Some(0)); + } + + /// A cancelled job stops waiting for the PSD decode gate: the interrupt reaches the layered + /// TIFF's gate wait, so it does not block behind another decode until that one finishes. + #[test] + fn cancelled_layered_tiff_import_stops_waiting_for_the_gate() { + use std::sync::Arc; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::time::{Duration, Instant}; + + let bytes = layered_tiff(8, 6); + let snapshot = crate::memory::MemorySnapshot { available_ram: Some(32 << 30), swap_free: None, commit_headroom: None }; + let _guard = crate::psd_gate::acquire_decode_admission(&photocraft_raster::Interrupt::NONE).expect("active decode"); + + let cancel = Arc::new(AtomicBool::new(false)); + let prechecked = Arc::new(AtomicBool::new(false)); + let (tx, rx) = std::sync::mpsc::channel(); + + let handle = { + let cancel = Arc::clone(&cancel); + let prechecked = Arc::clone(&prechecked); + std::thread::spawn(move || { + let provider = std::rc::Rc::new(move || { + prechecked.store(true, Ordering::SeqCst); + snapshot + }); + let cancelled = move || cancel.load(Ordering::SeqCst); + let progress = |_: f32| {}; + let ctl = photocraft_raster::Interrupt::new(&cancelled, &progress); + let result = crate::memory::with_mock_memory_provider(provider, || { + crate::import_with_options_and_interrupt("cancel.tif", &bytes, &ImportOptions::default(), &ctl) + }); + tx.send(result.map(|r| r.document.layers.len())).ok(); + }) + }; + + // The provider's first call is the precheck, which happens before the gate wait. + let deadline = Instant::now() + Duration::from_secs(10); + while !prechecked.load(Ordering::SeqCst) { + assert!(Instant::now() < deadline, "the import never reached its admission precheck"); + std::thread::yield_now(); + } + cancel.store(true, Ordering::SeqCst); + + // This thread still holds the gate, so the only way to answer is to abort the wait. + let result = rx.recv_timeout(Duration::from_secs(10)).expect("a cancelled import must stop waiting for the gate"); + match result { + Err(IoError::Cancelled) => {} + other => panic!("expected the cancelled import to fail, got {other:?}"), + } + + drop(_guard); + handle.join().expect("worker thread"); + } + + /// The estimate covers what the layered import holds besides the PSD layer model: the + /// decoded composite, the planar merged copy, the decoder's extra-sample planes and scratch, + /// the tags it copies, and a half-float conversion's extra buffers. + #[test] + fn layered_estimate_counts_decode_conversion_extras_and_scratch() { + use photocraft_codecs::SampleType as S; + // 100 × 50 px, RGB, 8-bit, no extras: the decoded image plus the planar copy. + let pixels = 100u64 * 50; + assert_eq!(super::layered_import_bytes(0, 100, 50, 3, S::U8, 0, 0, 0), 2 * pixels * 3); + // Two extra samples add their interleaved buffer, their split planes and one big-endian + // plane copied into the merged image. + assert_eq!(super::layered_import_bytes(0, 100, 50, 3, S::U8, 2, 0, 0), pixels * 13); + // A half-float page is converted: the 16-bit image and planes stay alive beside the + // normalized 32-bit buffer and the 32-bit result. + assert_eq!(super::layered_import_bytes(0, 100, 50, 3, S::F16, 0, 0, 0), pixels * (3 * 2 + 3 * 8 + 3 * 4)); + let base = super::layered_import_bytes(0, 100, 50, 3, S::U8, 0, 0, 0); + assert_eq!(super::layered_import_bytes(0, 100, 50, 3, S::U8, 0, 1234, 99), base + 1234 + 99); + assert_eq!(super::layered_import_bytes(u64::MAX, 100, 50, 3, S::U8, 0, 0, 0), u64::MAX, "an estimate never wraps into an admitted one"); + } + + /// A TIFF whose layer tag cannot be read still opens flattened, and its whole-image decode + /// and conversion are admitted like a layered page: a refused file never reaches the decode, + /// and the flatten warning is unchanged. + #[test] + fn malformed_layer_tag_bounds_the_composite_before_it_is_decoded() { + use std::cell::Cell; + use std::rc::Rc; + + use photocraft_codecs::{ChannelLayout, EncodeOptions, Format, Image, SampleType}; + + if cfg!(any(target_arch = "wasm32", target_pointer_width = "32")) { + return; + } + let mut img = Image::from_raw(4, 3, ChannelLayout::Rgb, SampleType::U8, vec![40; 4 * 3 * 3]).unwrap(); + img.meta.photoshop_layers = Some(b"not Photoshop image source data".to_vec()); + let bytes = photocraft_codecs::encode(&img, Format::Tiff, &EncodeOptions::default()).unwrap(); + + let decoded = Rc::new(Cell::new(0u32)); + let hook = |decoded: &Rc>| -> Rc { + let decoded = Rc::clone(decoded); + Rc::new(move || decoded.set(decoded.get() + 1)) + }; + + let zero = crate::memory::MemorySnapshot { available_ram: Some(0), swap_free: None, commit_headroom: None }; + crate::memory::with_mock_memory(zero, || { + crate::flat::with_before_composite_decode(hook(&decoded), || { + match crate::import_with_options("bogus.tif", &bytes, &ImportOptions::default()) { + Err(IoError::PsdImportBudget { limit: 0, required }) => assert!(required > 0), + other => panic!("expected an import-budget refusal, got {other:?}"), + } + assert_eq!(decoded.get(), 0, "a refused file must not decode its composite"); + }); + }); + + let plenty = crate::memory::MemorySnapshot { available_ram: Some(16 << 30), swap_free: None, commit_headroom: None }; + crate::memory::with_mock_memory(plenty, || { + crate::flat::with_before_composite_decode(hook(&decoded), || { + let opened = crate::import_with_options("bogus.tif", &bytes, &ImportOptions::default()).expect("a normal machine opens the composite"); + assert_eq!(opened.document.layers.len(), 1); + assert!(opened.warnings.iter().any(|w| w.contains("opened flattened")), "{:?}", opened.warnings); + assert_eq!(decoded.get(), 1, "the admitted import decodes the composite exactly once"); + }); + }); + } + + /// Admission happens before a layered TIFF's composite is decoded: a known-zero budget and + /// an approval-needed estimate both refuse the file without reaching the decode, and an + /// approved import does reach it. The fixture is the real tiny layered TIFF; the estimate + /// threshold is the scoped test seam, so nothing near a gigabyte is allocated. + #[test] + fn layered_tiff_is_refused_before_its_composite_is_decoded() { + use std::cell::Cell; + use std::rc::Rc; + + if cfg!(any(target_arch = "wasm32", target_pointer_width = "32")) { + return; + } + let gb = 1u64 << 30; + let bytes = layered_tiff(8, 6); + let decoded = Rc::new(Cell::new(0u32)); + let hook = |decoded: &Rc>| -> Rc { + let decoded = Rc::clone(decoded); + Rc::new(move || decoded.set(decoded.get() + 1)) + }; + + let zero = crate::memory::MemorySnapshot { available_ram: Some(0), swap_free: None, commit_headroom: None }; + crate::memory::with_mock_memory(zero, || { + crate::flat::with_before_composite_decode(hook(&decoded), || { + match crate::import_with_options("zero.tif", &bytes, &ImportOptions::default()) { + Err(IoError::PsdImportBudget { limit: 0, required }) => assert!(required > 0), + other => panic!("expected an import-budget refusal, got {other:?}"), + } + assert_eq!(decoded.get(), 0, "a refused file must not decode its composite"); + }); + }); + + // 12 GiB: S = 6 GiB, H = 9 GiB. The seam puts the estimate in the approval band. + let snapshot = crate::memory::MemorySnapshot { available_ram: Some(12 * gb), swap_free: None, commit_headroom: None }; + crate::memory::with_mock_memory(snapshot, || { + crate::flat::with_before_composite_decode(hook(&decoded), || { + crate::psd_budget::with_test_estimate_charge(7 * gb, || { + match crate::import_with_options("approval.tif", &bytes, &ImportOptions::default()) { + Err(IoError::PsdApprovalRequired { required, soft_limit, hard_limit, .. }) => { + assert_eq!((soft_limit, hard_limit), (6 * gb, 9 * gb)); + assert!(required > 6 * gb, "the charge reaches the approval band: {required}"); + } + other => panic!("expected an approval request, got {other:?}"), + } + assert_eq!(decoded.get(), 0, "approval is needed before the composite is decoded, not after it"); + + let approved = ImportOptions { psd_high_memory_approved: true, ..Default::default() }; + let opened = crate::import_with_options("approval.tif", &bytes, &approved).expect("approved"); + assert_eq!(opened.document.layers.len(), 2); + assert_eq!(decoded.get(), 1, "the approved import decodes the composite exactly once"); + }); + }); + }); + } + + /// Available memory can drop while a layered TIFF waits for the decode gate: the post-gate + /// recheck must refuse it before the composite is decoded. A per-attempt provider shared with + /// this test only changes the measurement; nothing near a gigabyte is allocated. + #[test] + fn layered_tiff_memory_drop_while_waiting_for_the_gate_refuses_before_decoding() { + use std::rc::Rc; + use std::sync::Arc; + use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; + use std::time::{Duration, Instant}; + + if cfg!(any(target_arch = "wasm32", target_pointer_width = "32")) { + return; + } + let gb = 1u64 << 30; + let bytes = layered_tiff(8, 6); + + // Hold the gate so the import stops between its pre-gate check and the post-gate one. + let _guard = crate::psd_gate::acquire_decode_admission(&photocraft_raster::Interrupt::NONE).expect("active decode"); + let available = Arc::new(AtomicU64::new(32 * gb)); + let prechecked = Arc::new(AtomicBool::new(false)); + let decoded = Arc::new(AtomicBool::new(false)); + let (tx, rx) = std::sync::mpsc::channel(); + + let handle = { + let available = Arc::clone(&available); + let prechecked = Arc::clone(&prechecked); + let decoded = Arc::clone(&decoded); + std::thread::spawn(move || { + let provider = Rc::new(move || { + // Read before signalling, so the pre-gate check that the main thread waits + // for has already measured the larger figure. + let ram = available.load(Ordering::SeqCst); + prechecked.store(true, Ordering::SeqCst); + crate::memory::MemorySnapshot { available_ram: Some(ram), swap_free: None, commit_headroom: None } + }); + let hook: Rc = Rc::new(move || decoded.store(true, Ordering::SeqCst)); + let result = crate::memory::with_mock_memory_provider(provider, || { + crate::flat::with_before_composite_decode(hook, || crate::import_with_options("drop.tif", &bytes, &ImportOptions::default())) + }); + tx.send(result.map(|r| r.document.layers.len())).ok(); + }) + }; + + // The provider's first call is the pre-gate admission check. + let deadline = Instant::now() + Duration::from_secs(10); + while !prechecked.load(Ordering::SeqCst) { + assert!(Instant::now() < deadline, "the import never reached its admission precheck"); + std::thread::yield_now(); + } + // The precheck admitted it; now the machine has nothing left. Release the gate afterwards. + available.store(0, Ordering::SeqCst); + drop(_guard); + + let result = rx.recv_timeout(Duration::from_secs(10)).expect("the post-gate recheck must refuse instead of decoding"); + match result { + Err(IoError::PsdImportBudget { limit: 0, required }) => assert!(required > 0), + other => panic!("expected the post-gate recheck to refuse with a zero budget, got {other:?}"), + } + assert!(!decoded.load(Ordering::SeqCst), "the composite must not be decoded after the post-gate refusal"); + handle.join().expect("worker thread"); + } } diff --git a/crates/raster/Cargo.toml b/crates/raster/Cargo.toml index e7f5af6420..058e275b60 100644 --- a/crates/raster/Cargo.toml +++ b/crates/raster/Cargo.toml @@ -18,7 +18,12 @@ lz4_flex = { version = "0.11", default-features = false, features = ["std", "saf # sysinfo reads the physical RAM size for the memory limit and the scratch volume's free space. [target.'cfg(not(target_arch = "wasm32"))'.dependencies] rayon = { workspace = true } -sysinfo = { version = "0.37", default-features = false, features = ["system", "disk"] } +sysinfo = { version = "=0.40.1", default-features = false, features = ["system", "disk"] } + +# Available physical memory and commit headroom (memory/system.rs) through winsafe's safe +# `GlobalMemoryStatusEx` wrapper. +[target.'cfg(windows)'.dependencies] +winsafe = { version = "=0.0.29", default-features = false, features = ["kernel"] } [dev-dependencies] proptest = { workspace = true } diff --git a/crates/raster/src/memory.rs b/crates/raster/src/memory.rs index 5ad3df50d0..b996bd3152 100644 --- a/crates/raster/src/memory.rs +++ b/crates/raster/src/memory.rs @@ -6,6 +6,8 @@ use std::sync::OnceLock; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Mutex, PoisonError}; +pub mod system; + const MIB: u64 = 1 << 20; #[derive(Clone, Copy, Debug, Default, serde::Serialize)] @@ -76,14 +78,23 @@ pub fn configuration_generation() -> u64 { #[cfg(not(target_arch = "wasm32"))] pub fn measure() -> Snapshot { use sysinfo::{Pid, ProcessRefreshKind, ProcessesToUpdate, System}; - static SYSTEM: OnceLock> = OnceLock::new(); - let mut s = SYSTEM.get_or_init(|| Mutex::new(System::new())).lock().unwrap_or_else(PoisonError::into_inner); + static SYSTEM: OnceLock>> = OnceLock::new(); + let mut guard = SYSTEM.get_or_init(|| Mutex::new(System::new().ok())).lock().unwrap_or_else(PoisonError::into_inner); + // No provider: an unknown total keeps the configured ceiling (see [`budgets`]). + let Some(s) = guard.as_mut() else { return Snapshot::default() }; s.refresh_memory(); let pid = Pid::from_u32(std::process::id()); s.refresh_processes_specifics(ProcessesToUpdate::Some(&[pid]), true, ProcessRefreshKind::nothing().with_memory()); + // The shared detector bounds host memory by the process's cgroup and, on macOS, counts only + // reclaimable pages. A constraint it could not read keeps the host figure here: the tile + // budget only decides what to spill, and a fail-closed zero would stall every operation. + let available = match system::current() { + system::SystemMemory { available_ram: Some(ram), constraint_unreadable: false, .. } => ram, + _ => s.available_memory(), + }; Snapshot { total_bytes: s.total_memory(), - available_bytes: s.available_memory(), + available_bytes: available, process_resident_bytes: s.process(pid).map_or(0, |p| p.memory()), process_virtual_bytes: s.process(pid).map_or(0, |p| p.virtual_memory()), } diff --git a/crates/raster/src/memory/system.rs b/crates/raster/src/memory/system.rs new file mode 100644 index 0000000000..ac2e4b772b --- /dev/null +++ b/crates/raster/src/memory/system.rs @@ -0,0 +1,1175 @@ +//! Platform measurements of the memory this process can use, shared by the tile residency +//! budget ([`super::measure`]) and the import admission budget (`photocraft_io::memory`), so +//! there is one detector of available RAM. +//! +//! - Linux: `/proc/meminfo` `MemAvailable`, capped by the process's memory cgroup (v2 +//! `memory.max`/`memory.high` and v1 `memory.limit_in_bytes`/`memsw`, with every visible +//! ancestor); a cgroup that exists but cannot be read fails closed. +//! - Windows: `GlobalMemoryStatusEx` available physical memory and commit headroom. +//! - macOS: the reclaimable pool from the VM counters (free, file-backed, purgeable). +//! - Elsewhere (including the web): unknown. +//! +//! Swap is reported separately and never counted as available RAM. + +/// Memory this process can use now, distinguishing physical RAM from swap and commit headroom. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub struct SystemMemory { + /// Available physical RAM in bytes, bounded by applicable container or process limits. Free + /// swap is excluded. `Some(0)` is zero capacity, not unknown memory. + pub available_ram: Option, + /// Available swap headroom in bytes, if known. + pub swap_free: Option, + /// System or process commit headroom in bytes, if measurable. + pub commit_headroom: Option, + /// A memory constraint exists but could not be read, so `available_ram` is the fail-closed + /// `Some(0)` rather than a measurement. Admission refuses on it; the tile residency budget + /// falls back to the host figure instead, because a zero budget would stall every operation. + pub constraint_unreadable: bool, +} + +impl SystemMemory { + /// Unknown memory measurement. + pub const UNKNOWN: Self = Self { available_ram: None, swap_free: None, commit_headroom: None, constraint_unreadable: false }; +} + +/// Measures [`SystemMemory`] from the platform provider. +pub fn current() -> SystemMemory { + #[cfg(target_os = "linux")] + { + linux::snapshot() + } + #[cfg(windows)] + { + windows_mem::snapshot() + } + #[cfg(target_os = "macos")] + { + macos_mem::snapshot() + } + #[cfg(not(any(target_os = "linux", windows, target_os = "macos")))] + { + fallback_mem::snapshot() + } +} + +/// Bytes this process can still use without running out, counting free swap, or `None` where +/// that isn't known. On Linux: [`current`]'s available RAM plus free swap (both capped by the +/// memory cgroup). Elsewhere `None`: Windows refuses an allocation past its commit limit, which +/// the importers already report as an error, and macOS pages to disk as it needs. +pub fn available_with_swap() -> Option { + #[cfg(target_os = "linux")] + { + linux::available() + } + #[cfg(not(target_os = "linux"))] + { + None + } +} + +#[cfg(target_os = "linux")] +pub(super) mod linux { + use super::SystemMemory; + use std::path::{Path, PathBuf}; + + /// cgroup v1 reports `PAGE_COUNTER_MAX * page_size` for "no limit", which is always close to + /// `i64::MAX`. Any limit at or above 4 EiB is treated as unlimited. + const V1_UNLIMITED: u64 = 1 << 62; + + /// Bound on ancestor walks; cgroup hierarchies are far shallower than this. + const MAX_CGROUP_DEPTH: usize = 128; + + #[derive(Clone, Debug, PartialEq, Eq)] + enum Limit { + Missing, + Unlimited, + Value(u64), + Invalid, + } + + /// What the process's memory cgroup says, independent of host `/proc/meminfo`. + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub(super) enum CgroupLimits { + /// No memory controller in this process's hierarchy: host memory applies. + NotConstrained, + /// Headroom under the memory controller; `None` means that dimension is unlimited. + Limited { ram: Option, swap: Option }, + /// A memory controller exists but its mount, path or limit could not be read. Callers + /// must fail closed instead of falling back to unrestricted host memory. + Unreadable, + } + + #[derive(Clone, Debug, PartialEq, Eq)] + struct CgroupDir { + leaf: PathBuf, + /// The visible root of the walk (the mount point). + root: PathBuf, + /// Whether `root` is the hierarchy's own root rather than a subtree exposed by a mount. + /// Only the hierarchy root is exempt from exposing its controller interface files. + hierarchy_root: bool, + } + + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + struct Membership<'a> { + /// Unified (v2) hierarchy path (`0::`). + v2: Option<&'a str>, + /// v1 hierarchy path for the `memory` controller. + v1_memory: Option<&'a str>, + } + + /// Result of reading `/proc/self/cgroup`. + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + enum MembershipParse<'a> { + Parsed(Membership<'a>), + /// A non-empty line could not be understood, so the absence of a memory controller cannot + /// be established. + Malformed, + } + + #[derive(Clone, Debug, PartialEq, Eq)] + struct Mount { + root: String, + mount_point: String, + fstype: String, + options: String, + super_options: String, + } + + /// Measures available RAM and free swap from `/proc/meminfo`, capped by the process's memory + /// cgroup. Unreadable cgroup constraints fail closed as zero available memory rather than + /// falling back to unrestricted host memory. + pub(super) fn snapshot() -> SystemMemory { + snapshot_at(Path::new("/proc"), Path::new("/sys/fs/cgroup")) + } + + /// Provider body with explicit roots, so tests exercise the real filesystem parsing without + /// global mocks. + pub(super) fn snapshot_at(proc_root: &Path, sys_root: &Path) -> SystemMemory { + let info = std::fs::read_to_string(proc_root.join("meminfo")).ok(); + let host_ram = info.as_deref().and_then(|i| meminfo(i, "MemAvailable:")); + let host_swap = info.as_deref().and_then(|i| meminfo(i, "SwapFree:")); + + let (cgroup_ram, cgroup_swap) = match cgroup_limits(proc_root, sys_root) { + CgroupLimits::NotConstrained => (None, None), + CgroupLimits::Limited { ram, swap } => (ram, swap), + CgroupLimits::Unreadable => return SystemMemory { available_ram: Some(0), swap_free: Some(0), commit_headroom: None, constraint_unreadable: true }, + }; + + let available_ram = match (host_ram, cgroup_ram) { + (Some(host), Some(cgroup)) => Some(host.min(cgroup)), + (Some(host), None) => Some(host), + (None, Some(cgroup)) => Some(cgroup), + (None, None) => None, + }; + let swap_free = match (host_swap, cgroup_swap) { + (Some(host), Some(cgroup)) => Some(host.min(cgroup)), + (Some(host), None) => Some(host), + (None, Some(cgroup)) => Some(cgroup), + (None, None) => None, + }; + SystemMemory { available_ram, swap_free, commit_headroom: None, constraint_unreadable: false } + } + + pub(super) fn available() -> Option { + available_at(Path::new("/proc"), Path::new("/sys/fs/cgroup")) + } + + /// Legacy RAM-plus-swap helper with explicit roots. Its meaning is deliberately unchanged: + /// the adaptive budget excludes swap, but flat and layered TIFF conversion still count it + /// (now bounded by the cgroup figures derived above, including v1 `memsw`). + pub(super) fn available_at(proc_root: &Path, sys_root: &Path) -> Option { + let snap = snapshot_at(proc_root, sys_root); + snap.available_ram.map(|ram| ram.saturating_add(snap.swap_free.unwrap_or(0))) + } + + /// A `/proc/meminfo` field in bytes. + pub(super) fn meminfo(info: &str, field: &str) -> Option { + let kb: u64 = info.lines().find_map(|l| l.strip_prefix(field))?.trim().trim_end_matches("kB").trim().parse().ok()?; + kb.checked_mul(1024) + } + + /// Resolves the memory cgroup from `/proc/self/cgroup` plus `/proc/self/mountinfo`. + /// + /// v1 is preferred when the `memory` controller appears there; otherwise the unified v2 + /// hierarchy is used. A memory controller that cannot be resolved or read, or membership that + /// cannot be parsed, is [`CgroupLimits::Unreadable`], never host memory. Ancestors above a + /// cgroup namespace's root are not visible to an unprivileged reader (the kernel still + /// enforces them), so only visible ancestors can be accounted for. The widest visible view of + /// the hierarchy is used, not merely the deepest matching mount point. + pub(super) fn cgroup_limits(proc_root: &Path, sys_root: &Path) -> CgroupLimits { + let Ok(groups) = std::fs::read_to_string(proc_root.join("self/cgroup")) else { + // Without membership we cannot prove that no memory cgroup applies. + return CgroupLimits::Unreadable; + }; + let membership = match parse_membership(&groups) { + MembershipParse::Parsed(membership) => membership, + MembershipParse::Malformed => return CgroupLimits::Unreadable, + }; + let mountinfo = std::fs::read_to_string(proc_root.join("self/mountinfo")).ok(); + + if let Some(path) = membership.v1_memory { + let Some(dir) = resolve_dir(sys_root, mountinfo.as_deref(), path, "cgroup", Some("memory")) else { + return CgroupLimits::Unreadable; + }; + return v1_limits(&dir); + } + if let Some(path) = membership.v2 { + let Some(dir) = resolve_dir(sys_root, mountinfo.as_deref(), path, "cgroup2", None) else { + return CgroupLimits::Unreadable; + }; + return v2_limits(&dir); + } + CgroupLimits::NotConstrained + } + + /// Parses `/proc/self/cgroup`. + /// + /// Kernel format is `::`; the + /// unified hierarchy uses `0::`. A line that does not have that shape makes the whole + /// file untrustworthy: returning "no memory controller" from a partial parse would silently + /// fall back to unrestricted host memory, so an empty or malformed file is reported as + /// malformed instead. + fn parse_membership(text: &str) -> MembershipParse<'_> { + let mut membership = Membership { v2: None, v1_memory: None }; + let mut saw_line = false; + for line in text.lines() { + let line = line.trim_end_matches('\r'); + if line.is_empty() { + continue; + } + saw_line = true; + let mut fields = line.splitn(3, ':'); + let (Some(hierarchy), Some(controllers), Some(path)) = (fields.next(), fields.next(), fields.next()) else { + return MembershipParse::Malformed; + }; + let Ok(hierarchy) = hierarchy.parse::() else { return MembershipParse::Malformed }; + if !path.starts_with('/') { + return MembershipParse::Malformed; + } + if hierarchy == 0 { + if !controllers.is_empty() { + return MembershipParse::Malformed; + } + membership.v2.get_or_insert(path); + } else if controllers.is_empty() { + return MembershipParse::Malformed; + } else if controllers.split(',').any(|c| c.trim() == "memory") { + membership.v1_memory.get_or_insert(path); + } + } + if !saw_line { + return MembershipParse::Malformed; + } + MembershipParse::Parsed(membership) + } + + /// Parses `/proc/self/mountinfo` into the mount fields used to locate a cgroup hierarchy. + /// + /// Malformed lines are skipped; callers fail closed when no matching mount is found. + fn parse_mountinfo(text: &str) -> Vec { + let mut mounts = Vec::new(); + for line in text.lines() { + let fields: Vec<&str> = line.split_whitespace().collect(); + let Some(separator) = fields.iter().position(|f| *f == "-") else { continue }; + let (Some(root), Some(point), Some(fstype), Some(super_options)) = + (fields.get(3).copied(), fields.get(4).copied(), fields.get(separator + 1).copied(), fields.get(separator + 3).copied()) + else { + continue; + }; + let options = fields.get(5).copied().unwrap_or(""); + mounts.push(Mount { + root: unescape(root), + mount_point: unescape(point), + fstype: fstype.to_string(), + options: options.to_string(), + super_options: super_options.to_string(), + }); + } + mounts + } + + /// Finds the mount for `fstype`/`controller` and joins the process's cgroup path to it. + /// + /// Reads `/proc/self/mountinfo` (dedicated controller mounts, bind mounts and non-root mount + /// roots). If that file cannot be read, the conventional `/sys/fs/cgroup[/]` + /// layout is the only guess available. When mountinfo *is* readable, a missing matching mount + /// fails closed instead of guessing another mount's hierarchy: a wrong directory must never + /// become unrestricted host memory. + /// + /// A bind mount of a subtree has a deeper `root` and hides the cgroup ancestors above that + /// subtree, so the *widest* matching view is preferred: the mount whose cgroup root is + /// highest in the hierarchy (fewest path components), not the longest mount point. A deep + /// bind mount must not be allowed to hide a limit on an ancestor that is visible through the + /// hierarchy's real mount. + fn resolve_dir(sys_root: &Path, mountinfo: Option<&str>, membership: &str, fstype: &str, controller: Option<&str>) -> Option { + let membership = unescape(membership.trim()); + let Some(info) = mountinfo else { + let root = match controller { + Some(c) => sys_root.join(c), + None => sys_root.to_path_buf(), + }; + let leaf = join_membership(&root, &membership)?; + // The conventional layout mounts each hierarchy at its own root. + return leaf.is_dir().then_some(CgroupDir { leaf, root, hierarchy_root: true }); + }; + + let mut best: Option<(usize, usize, CgroupDir)> = None; + for mount in parse_mountinfo(info) { + if mount.fstype != fstype { + continue; + } + if controller.is_some_and(|c| !has_option(&mount.options, c) && !has_option(&mount.super_options, c)) { + continue; + } + let Some(relative) = strip_mount_root(&mount.root, &membership) else { continue }; + let root = normalize_root(&mount.mount_point); + let Some(leaf) = join_membership(&root, relative) else { continue }; + if !leaf.is_dir() { + continue; + } + let key = (cgroup_path_depth(&mount.root), mount.mount_point.len()); + if best.as_ref().is_none_or(|(depth, point, _)| key < (*depth, *point)) { + let hierarchy_root = mount.root.trim_end_matches('/').is_empty(); + best = Some((key.0, key.1, CgroupDir { leaf, root, hierarchy_root })); + } + } + best.map(|(_, _, dir)| dir) + } + + /// Trims trailing slashes so `Path` equality holds while walking ancestors, keeping `/`. + fn normalize_root(point: &str) -> PathBuf { + let trimmed = point.trim_end_matches('/'); + PathBuf::from(if trimmed.is_empty() { "/" } else { trimmed }) + } + + /// Joins a cgroup path below a visible hierarchy root, normalizing `.` components and + /// rejecting parent traversal so a malformed path cannot escape the mount. + fn join_membership(root: &Path, path: &str) -> Option { + let mut leaf = root.to_path_buf(); + for component in Path::new(path.trim_start_matches('/')).components() { + match component { + std::path::Component::Normal(part) => leaf.push(part), + std::path::Component::CurDir => {} + std::path::Component::ParentDir | std::path::Component::RootDir | std::path::Component::Prefix(_) => return None, + } + } + Some(leaf) + } + + /// Number of path components in a mount's cgroup root; `/` or an empty root is zero. + fn cgroup_path_depth(root: &str) -> usize { + Path::new(root).components().filter(|c| matches!(c, std::path::Component::Normal(_))).count() + } + + /// Whether a v2 mount's `cgroup.controllers` exposes the memory controller. + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + enum V2Controller { + /// `cgroup.controllers` lists `memory`. + Available, + /// `cgroup.controllers` is readable and omits `memory`, so no cgroup memory limit exists. + Absent, + /// `cgroup.controllers` could not be read, so absence cannot be established. + Unknown, + } + + /// Whether the cgroup v2 hierarchy at `root` exposes the memory controller. An unreadable + /// `cgroup.controllers` is `Unknown`, so its absence cannot be proven. + fn v2_controller(root: &Path) -> V2Controller { + match std::fs::read_to_string(root.join("cgroup.controllers")) { + Ok(text) => { + if text.split_whitespace().any(|controller| controller == "memory") { + V2Controller::Available + } else { + V2Controller::Absent + } + } + Err(_) => V2Controller::Unknown, + } + } + + /// Whether a cgroup's `cgroup.subtree_control` enables memory for its children. + /// + /// Interface files are created by the parent, so this decides whether a child *must* expose + /// `memory.max`: a readable control file without memory means the child legitimately has no + /// limit, while an unreadable one means that cannot be established. + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + enum Delegation { + Enabled, + Disabled, + Unknown, + } + + /// Whether `parent` enables the memory controller for its children in + /// `cgroup.subtree_control`. An unreadable file is `Unknown`, not "disabled". + fn v2_delegation(parent: &Path) -> Delegation { + match std::fs::read_to_string(parent.join("cgroup.subtree_control")) { + Ok(text) => { + if text.split_whitespace().any(|controller| controller.trim_start_matches('+') == "memory") { + Delegation::Enabled + } else { + Delegation::Disabled + } + } + Err(_) => Delegation::Unknown, + } + } + + /// cgroup v2: `memory.max`/`memory.current`, reclaiming `inactive_file`, plus + /// `memory.swap.max`/`memory.swap.current`. Every visible ancestor limit applies. + /// + /// A missing `memory.max` is not always an error: the hierarchy root is exempt from resource + /// control, and a child has the file only when its parent delegates the controller. A missing + /// file where the parent *does* delegate memory, or where delegation cannot be read, means the + /// visible view is incomplete and is reported as unreadable instead of unrestricted. + fn v2_limits(dir: &CgroupDir) -> CgroupLimits { + if !dir.leaf.starts_with(&dir.root) || !dir.leaf.is_dir() { + return CgroupLimits::Unreadable; + } + let controller = v2_controller(&dir.root); + + let mut nodes = Vec::new(); + let mut node = Some(dir.leaf.as_path()); + while let Some(path) = node { + nodes.push(path); + if path == dir.root.as_path() { + break; + } + if nodes.len() > MAX_CGROUP_DEPTH { + return CgroupLimits::Unreadable; + } + node = path.parent(); + } + if nodes.last().is_none_or(|path| *path != dir.root.as_path()) { + return CgroupLimits::Unreadable; + } + nodes.reverse(); + + let mut ram: Option = None; + let mut swap: Option = None; + let mut enabled = false; + for (index, path) in nodes.iter().enumerate() { + let expected = if index == 0 { + if dir.hierarchy_root { + // The hierarchy root is exempt from resource control and may have no + // `memory.max` at all. + None + } else if controller == V2Controller::Absent { + Some(Delegation::Disabled) + } else { + // A mounted subtree root must expose the controller when it is enabled for + // that cgroup; without the parent's control file its absence is unprovable. + Some(Delegation::Unknown) + } + } else { + Some(v2_delegation(nodes[index - 1])) + }; + match read_limit(&path.join("memory.max")) { + Limit::Value(max) => { + enabled = true; + let Some(current) = read_u64(&path.join("memory.current")) else { return CgroupLimits::Unreadable }; + let inactive = read_stat(&path.join("memory.stat"), "inactive_file"); + let room = max.saturating_sub(current.saturating_sub(inactive)); + ram = Some(ram.map_or(room, |r| r.min(room))); + } + Limit::Unlimited => enabled = true, + Limit::Invalid => return CgroupLimits::Unreadable, + Limit::Missing => match expected { + None | Some(Delegation::Disabled) => {} + Some(Delegation::Enabled | Delegation::Unknown) => return CgroupLimits::Unreadable, + }, + } + match read_limit(&path.join("memory.swap.max")) { + Limit::Value(max) => { + enabled = true; + let Some(current) = read_u64(&path.join("memory.swap.current")) else { return CgroupLimits::Unreadable }; + let room = max.saturating_sub(current); + swap = Some(swap.map_or(room, |r| r.min(room))); + } + Limit::Unlimited => enabled = true, + Limit::Invalid => return CgroupLimits::Unreadable, + // Kernels before swap accounting expose `memory.max` without `memory.swap.*`; + // absence there means no swap limit at this cgroup, not an unreadable constraint. + Limit::Missing => {} + } + } + + if enabled { + return CgroupLimits::Limited { ram, swap }; + } + match controller { + // The controller is genuinely absent, or available but not enabled anywhere on the + // visible path (the root may normally have no interface files): no cgroup limit. + V2Controller::Absent | V2Controller::Available => CgroupLimits::NotConstrained, + // No readable limit file and no metadata proving the controller absent. + V2Controller::Unknown => CgroupLimits::Unreadable, + } + } + + /// cgroup v1: `memory.limit_in_bytes`/`memory.usage_in_bytes` (inactive cache reclaimable) + /// and the separate `memory.memsw` memory-plus-swap bound. + /// + /// A memsw limit also caps RAM because memory usage counts toward it, but its remaining room + /// is not swap that can be added on top of a different ancestor's RAM headroom. Each + /// ancestor's swap allowance is `memsw limit - memory limit - swap already used`, and those + /// allowances are combined separately. Subtracting one global combined headroom from one + /// global RAM headroom would invent swap room from different ancestors. + fn v1_limits(dir: &CgroupDir) -> CgroupLimits { + if !dir.leaf.starts_with(&dir.root) || !dir.leaf.is_dir() { + return CgroupLimits::Unreadable; + } + let mut ram: Option = None; + let mut swap: Option = None; + let mut enabled = false; + let mut node = Some(dir.leaf.as_path()); + let mut depth = 0; + while let Some(path) = node { + if depth >= MAX_CGROUP_DEPTH { + return CgroupLimits::Unreadable; + } + + // `None` means unlimited at this ancestor; the raw usage feeds the swap bound. + let mut memory_usage = None; + let memory_limit = match read_limit(&path.join("memory.limit_in_bytes")) { + Limit::Missing | Limit::Invalid => return CgroupLimits::Unreadable, + Limit::Unlimited => { + enabled = true; + None + } + Limit::Value(bytes) if bytes >= V1_UNLIMITED => { + enabled = true; + None + } + Limit::Value(bytes) => { + enabled = true; + let Some(usage) = read_u64(&path.join("memory.usage_in_bytes")) else { return CgroupLimits::Unreadable }; + memory_usage = Some(usage); + let inactive = std::fs::read_to_string(path.join("memory.stat")) + .ok() + .and_then(|s| stat(&s, "total_inactive_file").or_else(|| stat(&s, "inactive_file"))) + .unwrap_or(0); + let room = bytes.saturating_sub(usage.saturating_sub(inactive)); + ram = Some(ram.map_or(room, |r| r.min(room))); + Some(bytes) + } + }; + + match read_limit(&path.join("memory.memsw.limit_in_bytes")) { + Limit::Missing | Limit::Unlimited => {} + Limit::Invalid => return CgroupLimits::Unreadable, + Limit::Value(bytes) if bytes >= V1_UNLIMITED => {} + Limit::Value(bytes) => { + let Some(memsw_usage) = read_u64(&path.join("memory.memsw.usage_in_bytes")) else { + return CgroupLimits::Unreadable; + }; + // Memory plus swap is bounded by memsw, so its remaining room also bounds RAM. + let combined_room = bytes.saturating_sub(memsw_usage); + ram = Some(ram.map_or(combined_room, |r| r.min(combined_room))); + if let Some(memory_limit) = memory_limit { + // Swap can only use the part of memsw above the memory limit after the + // swap already in use; filling RAM to its own limit does not consume it. + let used_swap = memsw_usage.saturating_sub(memory_usage.unwrap_or(0)); + let room = bytes.saturating_sub(memory_limit).saturating_sub(used_swap); + swap = Some(swap.map_or(room, |s| s.min(room))); + } else { + // With no RAM limit the remaining memsw room can all be consumed by RAM, + // so no swap room is guaranteed on top of the RAM allowance. + swap = Some(0); + } + } + } + + if path == dir.root.as_path() { + break; + } + node = path.parent(); + depth += 1; + } + if !enabled { + // The v1 hierarchy claims a memory controller but never exposed a limit file. + return CgroupLimits::Unreadable; + } + CgroupLimits::Limited { ram, swap } + } + + /// Reads a cgroup limit file: `max` is unlimited, a number is a byte limit, and a missing file + /// is distinguished from one that cannot be read or parsed. + fn read_limit(path: &Path) -> Limit { + match std::fs::read_to_string(path) { + Ok(text) => match text.trim() { + "max" => Limit::Unlimited, + value => match value.parse::() { + Ok(bytes) => Limit::Value(bytes), + Err(_) => Limit::Invalid, + }, + }, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Limit::Missing, + Err(_) => Limit::Invalid, + } + } + + /// Reads a whitespace-terminated unsigned value from a cgroup interface file. + fn read_u64(path: &Path) -> Option { + std::fs::read_to_string(path).ok()?.trim().parse().ok() + } + + /// Reads `field` from a cgroup `*.stat` file, treating a missing file or field as zero. + fn read_stat(path: &Path, field: &str) -> u64 { + std::fs::read_to_string(path).ok().and_then(|s| stat(&s, field)).unwrap_or(0) + } + + /// Finds `field` in `key value` stat lines and parses its value. + fn stat(s: &str, field: &str) -> Option { + s.lines().find_map(|l| { + let mut parts = l.split_whitespace(); + let key = parts.next()?; + if key == field { parts.next()?.parse().ok() } else { None } + }) + } + + /// Whether a comma-separated mount option list contains `controller`. + fn has_option(options: &str, controller: &str) -> bool { + options.split(',').any(|option| option.trim() == controller) + } + + /// Strips a mount's root prefix from a cgroup path, returning the path relative to the mount. + fn strip_mount_root<'a>(root: &str, path: &'a str) -> Option<&'a str> { + let root = root.trim_end_matches('/'); + if root.is_empty() { + return Some(path); + } + let rest = path.strip_prefix(root)?; + if rest.is_empty() { + return Some(""); + } + rest.strip_prefix('/') + } + + /// Decodes mountinfo/mount-path octal escapes (`\040` space, `\011` tab, `\134` backslash). + fn unescape(value: &str) -> String { + let bytes = value.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut index = 0; + while let Some(&byte) = bytes.get(index) { + if byte == b'\\' + && let Some(digits) = bytes.get(index + 1..index + 4) + { + let code = digits.iter().try_fold(0u32, |acc, digit| { + let value = digit.checked_sub(b'0')?; + (value < 8).then_some(acc * 8 + u32::from(value)) + }); + if let Some(byte) = code.and_then(|code| u8::try_from(code).ok()) { + out.push(byte); + index += 4; + continue; + } + } + out.push(byte); + index += 1; + } + String::from_utf8_lossy(&out).into_owned() + } + + /// Exposed for the Linux provider tests; the policy itself never calls this. + #[cfg(test)] + pub(super) fn membership_for_test(text: &str) -> Option<(Option, Option)> { + match parse_membership(text) { + MembershipParse::Parsed(membership) => Some((membership.v2.map(str::to_string), membership.v1_memory.map(str::to_string))), + MembershipParse::Malformed => None, + } + } +} + +#[cfg(windows)] +mod windows_mem { + use super::SystemMemory; + + /// Measures available physical and commit memory through `GlobalMemoryStatusEx`. A failed + /// query reports unknown memory rather than inventing a measurement. + pub(super) fn snapshot() -> SystemMemory { + match winsafe::GlobalMemoryStatusEx() { + Ok(msx) => SystemMemory { + available_ram: Some(msx.ullAvailPhys), + swap_free: None, + commit_headroom: Some(msx.ullAvailPageFile), + constraint_unreadable: false, + }, + Err(_) => SystemMemory::UNKNOWN, + } + } +} + +/// Conservative reclaimable physical RAM from macOS VM counters, or `None` when the query failed. +/// +/// `total` is installed physical memory (`sysctl` `HW_MEMSIZE`). The other three are the same +/// `host_statistics64` `vm_statistics64` fields that `sysinfo` derives: +/// +/// - `free` = `free_memory` = `free_count - speculative_count` pages; +/// - `available` = `available_memory` = `active + inactive + free_count` pages; +/// - `used` = `used_memory` = `internal_page_count - purgeable_count + wire_count + +/// compressor_page_count` pages. +/// +/// XNU documents `AVAILABLE_NON_COMPRESSED_MEMORY = active + inactive + free + speculative` as +/// "everything that is not either wired, compressed, or stolen" +/// (). +/// That includes anonymous working sets, which can only be released by compressing or swapping +/// them, so on its own it is too optimistic for a budget that excludes swap. +/// +/// `internal_page_count` counts anonymous pages and `external_page_count` counts file-backed +/// pages (), +/// so `total - used` is the pool that can be handed out without evicting a working set: +/// `free + file-backed + purgeable`. That is close to the fully-reclaimable pool jetsam monitors +/// (`file-backed + free + purgeable`, same document). The smaller of the two derivations is +/// taken so a counter disagreement stays conservative, and the result is never below `free`: +/// pages that are already free are allocatable by definition, so a derived value below them +/// means the counters disagree and cannot be used to claim less. +/// +/// Only a demonstrably failed query is unknown. A live host always has a non-zero installed size +/// and non-zero used memory (wired kernel pages alone), so either reading zero proves the +/// provider query failed. A genuine "no reclaimable pages" reading stays a known zero rather +/// than becoming the 2 GiB unknown-memory allowance. +#[cfg(any(target_os = "macos", test))] +fn macos_available_ram(total: u64, free: u64, available: u64, used: u64) -> Option { + if total == 0 || used == 0 { + return None; + } + let free = free.min(total); + let reclaimable = total.saturating_sub(used).min(available).max(free); + Some(reclaimable.min(total)) +} + +#[cfg(target_os = "macos")] +mod macos_mem { + use super::SystemMemory; + use sysinfo::{MemoryRefreshKind, RefreshKind, System}; + + /// Available physical memory through `sysinfo`'s safe API. + /// + /// On macOS that is `host_statistics64`'s `vm_statistics64` (see + /// [`super::macos_available_ram`]). The estimate counts free pages, file-backed pages and + /// purgeable pages, not anonymous working sets, wired memory, compressed memory or swap. A + /// failed query reports unknown; a successful zero reading stays zero. + pub(super) fn snapshot() -> SystemMemory { + let system = match System::new_with_specifics(RefreshKind::nothing().with_memory(MemoryRefreshKind::nothing().with_ram())) { + Ok(system) => system, + Err(_) => return SystemMemory::UNKNOWN, + }; + match super::macos_available_ram(system.total_memory(), system.free_memory(), system.available_memory(), system.used_memory()) { + Some(ram) => SystemMemory { available_ram: Some(ram), swap_free: None, commit_headroom: None, constraint_unreadable: false }, + None => SystemMemory::UNKNOWN, + } + } +} + +#[cfg(not(any(target_os = "linux", windows, target_os = "macos")))] +mod fallback_mem { + use super::SystemMemory; + + /// Fallback provider for platforms without a validated memory-availability provider. + /// + /// Available memory is reported as unknown (`None`), which applies the conservative native + /// fallback budget (2 GiB, approval above it) without inventing a measurement. + pub(super) fn snapshot() -> SystemMemory { + SystemMemory::UNKNOWN + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn macos_available_ram_counts_reclaimable_pages_not_free_only() { + let gb = 1u64 << 30; + // A failed provider query: no installed size, or no used memory on a live host. + assert_eq!(macos_available_ram(0, 0, 0, 0), None, "an empty query is not a measurement"); + assert_eq!(macos_available_ram(0, 1 << 20, 4 * gb, 4 * gb), None, "no installed size: the sysctl query failed"); + assert_eq!(macos_available_ram(16 * gb, 1 << 20, 8 * gb, 0), None, "no used memory on a live host: the VM query failed"); + + // A genuine zero-capacity reading stays zero, not unknown. + assert_eq!(macos_available_ram(16 * gb, 0, 0, 16 * gb), Some(0), "everything is wired or compressed"); + + // Low free memory beside a large file-backed cache: free alone would report ~0 and the + // hard budget would collapse, while 12 GiB is reclaimable without touching a working set. + assert_eq!(macos_available_ram(16 * gb, 100 << 20, 12 * gb, 4 * gb), Some(12 * gb)); + + // A loaded machine: most memory is anonymous working set, which is not reclaimable, so + // `available` (which counts it) does not raise the estimate above total - used. + assert_eq!(macos_available_ram(16 * gb, 200 << 20, 8 * gb, 14 * gb), Some(2 * gb)); + + // Counters that disagree: free pages are allocatable by definition, so never claim less. + assert_eq!(macos_available_ram(16 * gb, 3 * gb, gb, 15 * gb), Some(3 * gb)); + + // Never above installed memory. + assert_eq!(macos_available_ram(gb, 2 * gb, 4 * gb, 1), Some(gb)); + } + + #[cfg(target_os = "macos")] + #[test] + fn macos_provider_excludes_swap_and_commit_headroom() { + let snap = current(); + assert_eq!(snap.swap_free, None, "the adaptive budget must not count swap"); + assert_eq!(snap.commit_headroom, None); + // The numeric floor and zero-versus-unknown semantics are covered deterministically by + // `macos_available_ram_counts_reclaimable_pages_not_free_only`; asserting a live `> 0` + // here would be vacuous because a genuine zero is a valid reading. + } + + #[cfg(target_os = "linux")] + use std::path::{Path, PathBuf}; + + #[cfg(target_os = "linux")] + fn fixture(name: &str) -> (PathBuf, PathBuf) { + let root = std::env::temp_dir().join(format!("photocraft-cgroup-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(root.join("proc/self")).unwrap(); + std::fs::create_dir_all(root.join("sys/fs/cgroup")).unwrap(); + (root.join("proc"), root.join("sys/fs/cgroup")) + } + + #[cfg(target_os = "linux")] + fn write(path: &Path, text: &str) { + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).unwrap(); + } + std::fs::write(path, text).unwrap(); + } + + #[cfg(target_os = "linux")] + #[test] + fn linux_memory_is_read_from_meminfo() { + let info = "MemTotal: 24314352 kB\nMemAvailable: 12626632 kB\nSwapFree: 1024 kB\n"; + assert_eq!(linux::meminfo(info, "MemAvailable:"), Some(12_626_632 * 1024)); + assert_eq!(linux::meminfo(info, "SwapFree:"), Some(1024 * 1024)); + assert_eq!(linux::meminfo(info, "Missing:"), None); + assert_eq!(linux::meminfo("MemAvailable: lots kB", "MemAvailable:"), None); + } + + #[cfg(target_os = "linux")] + #[test] + fn linux_cgroup_membership_distinguishes_v1_and_v2() { + assert_eq!(linux::membership_for_test("0::/user.slice/session.scope\n"), Some((Some("/user.slice/session.scope".into()), None))); + assert_eq!(linux::membership_for_test("4:memory:/docker/abc\n"), Some((None, Some("/docker/abc".into())))); + assert_eq!(linux::membership_for_test("4:cpu,cpuacct:/user.slice\n5:memory:/a/b\n"), Some((None, Some("/a/b".into())))); + assert_eq!(linux::membership_for_test("12:pids:/\n"), Some((None, None)), "no memory controller is demonstrably absent"); + assert_eq!(linux::membership_for_test("garbage\n"), None); + assert_eq!(linux::membership_for_test(""), None, "an empty file cannot prove absence"); + assert_eq!(linux::membership_for_test("0:memory:/app\n"), None, "the unified hierarchy cannot name controllers"); + assert_eq!(linux::membership_for_test("4::/app\n"), None, "a v1 line must name a controller"); + assert_eq!(linux::membership_for_test("4:memory:relative\n"), None, "cgroup paths are absolute"); + } + + #[cfg(target_os = "linux")] + #[test] + fn linux_mountinfo_octal_escapes_are_decoded() { + let (proc, sys) = fixture("escaped"); + write(&proc.join("self/cgroup"), "0::/app\n"); + let mount = sys.join("cg root"); + let escaped = mount.display().to_string().replace(' ', "\\040"); + write(&proc.join("self/mountinfo"), &format!("30 20 0:26 / {} rw,relatime - cgroup2 cgroup2 rw\n", escaped)); + write(&mount.join("app/memory.max"), "1073741824\n"); + write(&mount.join("app/memory.current"), "0\n"); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::Limited { ram: Some(1 << 30), swap: None }); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + } + + #[cfg(target_os = "linux")] + #[test] + fn linux_v2_cgroup_applies_mount_path_and_ancestor_limits() { + let (proc, sys) = fixture("v2"); + write(&proc.join("self/cgroup"), "0::/app.scope\n"); + write(&proc.join("self/mountinfo"), &format!("30 20 0:26 / {} rw,nosuid,nodev,noexec,relatime - cgroup2 cgroup2 rw,nsdelegate\n", sys.display())); + let leaf = sys.join("app.scope"); + write(&sys.join("memory.max"), "8589934592\n"); + write(&sys.join("memory.current"), "2147483648\n"); + write(&sys.join("memory.stat"), "inactive_file 1073741824\n"); + write(&leaf.join("memory.max"), "max\n"); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::Limited { ram: Some(7 << 30), swap: None }, "the parent's limit applies"); + + write(&leaf.join("memory.max"), "4294967296\n"); + write(&leaf.join("memory.current"), "1073741824\n"); + write(&leaf.join("memory.stat"), "inactive_file 0\n"); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::Limited { ram: Some(3 << 30), swap: None }, "the tighter leaf limit wins"); + + write(&leaf.join("memory.swap.max"), "1073741824\n"); + write(&leaf.join("memory.swap.current"), "268435456\n"); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::Limited { ram: Some(3 << 30), swap: Some(768 << 20) }); + + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + } + + #[cfg(target_os = "linux")] + #[test] + fn linux_v2_distinguishes_disabled_controller_from_missing_expected_limit() { + // The hierarchy root may legitimately have no `memory.max`; a child has one exactly when + // its parent delegates the controller. + let (proc, sys) = fixture("v2-metadata"); + write(&proc.join("self/cgroup"), "0::/app\n"); + write(&proc.join("self/mountinfo"), &format!("30 20 0:26 / {} rw - cgroup2 cgroup2 rw\n", sys.display())); + write(&sys.join("cgroup.controllers"), "cpu io memory\n"); + write(&sys.join("cgroup.subtree_control"), "+cpu +memory\n"); + write(&sys.join("app/memory.max"), "1073741824\n"); + write(&sys.join("app/memory.current"), "0\n"); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::Limited { ram: Some(1 << 30), swap: None }, "a missing root file is normal"); + + write(&sys.join("cgroup.controllers"), "cpu io\n"); + write(&sys.join("cgroup.subtree_control"), "+cpu\n"); + std::fs::remove_file(sys.join("app/memory.max")).unwrap(); + assert_eq!( + linux::cgroup_limits(&proc, &sys), + linux::CgroupLimits::NotConstrained, + "readable controllers without memory prove the controller is absent" + ); + + write(&sys.join("cgroup.controllers"), "cpu io memory\n"); + write(&sys.join("cgroup.subtree_control"), "+memory\n"); + assert_eq!( + linux::cgroup_limits(&proc, &sys), + linux::CgroupLimits::Unreadable, + "memory is delegated to the child, so the missing child file means the view is incomplete" + ); + + std::fs::remove_file(sys.join("cgroup.controllers")).unwrap(); + std::fs::remove_file(sys.join("cgroup.subtree_control")).unwrap(); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::Unreadable, "without metadata the absence of a constraint cannot be established"); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + + // Available but not delegated anywhere on the path: no cgroup limit applies. + let (proc, sys) = fixture("v2-not-enabled"); + write(&proc.join("self/cgroup"), "0::/app\n"); + write(&proc.join("self/mountinfo"), &format!("30 20 0:26 / {} rw - cgroup2 cgroup2 rw\n", sys.display())); + write(&sys.join("cgroup.controllers"), "cpu io memory\n"); + write(&sys.join("cgroup.subtree_control"), "+cpu\n"); + write(&sys.join("app/cgroup.controllers"), "\n"); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::NotConstrained); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + } + + #[cfg(target_os = "linux")] + #[test] + fn linux_prefers_the_widest_hierarchy_view_over_a_deep_bind_mount() { + let (proc, sys) = fixture("bind-widest"); + write(&proc.join("self/cgroup"), "0::/user.slice/app.scope\n"); + let narrow = sys.join("bind"); + write( + &proc.join("self/mountinfo"), + &format!("30 20 0:26 / {} rw - cgroup2 cgroup2 rw\n31 30 0:26 /user.slice/app.scope {} rw - cgroup2 cgroup2 rw\n", sys.display(), narrow.display()), + ); + write(&sys.join("user.slice/memory.max"), "2147483648\n"); + write(&sys.join("user.slice/memory.current"), "0\n"); + write(&sys.join("user.slice/cgroup.subtree_control"), "+memory\n"); + write(&sys.join("user.slice/app.scope/memory.max"), "max\n"); + write(&narrow.join("memory.max"), "max\n"); + assert_eq!( + linux::cgroup_limits(&proc, &sys), + linux::CgroupLimits::Limited { ram: Some(2 << 30), swap: None }, + "the hierarchy's own mount exposes user.slice's limit; the deep bind mount would hide it" + ); + + write(&proc.join("self/mountinfo"), &format!("31 30 0:26 /user.slice/app.scope {} rw - cgroup2 cgroup2 rw\n", narrow.display())); + assert_eq!( + linux::cgroup_limits(&proc, &sys), + linux::CgroupLimits::Limited { ram: None, swap: None }, + "the bind mount alone cannot see the ancestor limit, which is why the widest view is preferred" + ); + + std::fs::remove_file(narrow.join("memory.max")).unwrap(); + assert_eq!( + linux::cgroup_limits(&proc, &sys), + linux::CgroupLimits::Unreadable, + "a mounted subtree root cannot silently lose the controller file it should expose" + ); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + } + + #[cfg(target_os = "linux")] + #[test] + fn linux_v1_cgroup_honours_controller_mounts_and_ancestors() { + let (proc, sys) = fixture("v1"); + write(&proc.join("self/cgroup"), "4:memory:/docker/abc\n"); + let mount = sys.join("memory"); + write(&proc.join("self/mountinfo"), &format!("31 24 0:26 / {} rw,nosuid,nodev,noexec,relatime shared:12 - cgroup cgroup rw,memory\n", mount.display())); + let leaf = mount.join("docker/abc"); + write(&mount.join("docker/memory.limit_in_bytes"), "9223372036854771712\n"); + write(&mount.join("memory.limit_in_bytes"), "8589934592\n"); + write(&mount.join("memory.usage_in_bytes"), "2147483648\n"); + write(&mount.join("memory.stat"), "total_inactive_file 1073741824\n"); + write(&leaf.join("memory.limit_in_bytes"), "9223372036854771712\n"); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::Limited { ram: Some(7 << 30), swap: None }, "the v1 sentinel is unlimited"); + + write(&leaf.join("memory.limit_in_bytes"), "3221225472\n"); + write(&leaf.join("memory.usage_in_bytes"), "1073741824\n"); + write(&leaf.join("memory.stat"), "total_inactive_file 0\n"); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::Limited { ram: Some(2 << 30), swap: None }, "the tighter leaf limit wins"); + + write(&mount.join("memory.memsw.limit_in_bytes"), "9663676416\n"); + write(&mount.join("memory.memsw.usage_in_bytes"), "2147483648\n"); + assert_eq!( + linux::cgroup_limits(&proc, &sys), + linux::CgroupLimits::Limited { ram: Some(2 << 30), swap: Some(1 << 30) }, + "swap room is memsw limit - memory limit - swap used at the same ancestor, not combined headroom minus RAM headroom" + ); + + write(&mount.join("memory.memsw.usage_in_bytes"), "3221225472\n"); + assert_eq!( + linux::cgroup_limits(&proc, &sys), + linux::CgroupLimits::Limited { ram: Some(2 << 30), swap: Some(0) }, + "a gigabyte already swapped uses the ancestor's whole swap allowance" + ); + + write(&mount.join("memory.memsw.limit_in_bytes"), "10737418240\n"); + assert_eq!( + linux::cgroup_limits(&proc, &sys), + linux::CgroupLimits::Limited { ram: Some(2 << 30), swap: Some(1 << 30) }, + "only the memsw allowance above the memory limit counts as added swap room" + ); + + write(&mount.join("memory.limit_in_bytes"), "9223372036854771712\n"); + write(&leaf.join("memory.limit_in_bytes"), "9223372036854771712\n"); + write(&mount.join("memory.memsw.limit_in_bytes"), "2147483648\n"); + write(&mount.join("memory.memsw.usage_in_bytes"), "0\n"); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::Limited { ram: Some(2 << 30), swap: Some(0) }, "memsw alone still caps RAM"); + + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + } + + #[cfg(target_os = "linux")] + #[test] + fn linux_v1_swap_bounds_combine_per_ancestor() { + let (proc, sys) = fixture("v1-swap-ancestors"); + write(&proc.join("self/cgroup"), "4:memory:/a/b\n"); + let mount = sys.join("memory"); + write(&proc.join("self/mountinfo"), &format!("31 24 0:26 / {} rw - cgroup cgroup rw,memory\n", mount.display())); + write(&mount.join("memory.limit_in_bytes"), "8589934592\n"); + write(&mount.join("memory.usage_in_bytes"), "2147483648\n"); + write(&mount.join("memory.memsw.limit_in_bytes"), "9663676416\n"); + write(&mount.join("memory.memsw.usage_in_bytes"), "2147483648\n"); + write(&mount.join("a/memory.limit_in_bytes"), "10737418240\n"); + write(&mount.join("a/memory.usage_in_bytes"), "1073741824\n"); + write(&mount.join("a/memory.memsw.limit_in_bytes"), "21474836480\n"); + write(&mount.join("a/memory.memsw.usage_in_bytes"), "2147483648\n"); + write(&mount.join("a/b/memory.limit_in_bytes"), "3221225472\n"); + write(&mount.join("a/b/memory.usage_in_bytes"), "1073741824\n"); + + assert_eq!( + linux::cgroup_limits(&proc, &sys), + linux::CgroupLimits::Limited { ram: Some(2 << 30), swap: Some(1 << 30) }, + "root swap allowance is 9 - 8 - 0 = 1 GiB; /a contributes 9 GiB and the leaf adds no swap limit" + ); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + } + + #[cfg(target_os = "linux")] + #[test] + fn linux_v1_mount_root_prefix_is_stripped() { + let (proc, sys) = fixture("v1-root"); + write(&proc.join("self/cgroup"), "4:memory:/docker/abc/child\n"); + let mount = sys.join("memory"); + write(&proc.join("self/mountinfo"), &format!("31 24 0:26 /docker/abc {} rw,relatime - cgroup cgroup rw,memory\n", mount.display())); + write(&mount.join("memory.limit_in_bytes"), "1073741824\n"); + write(&mount.join("memory.usage_in_bytes"), "0\n"); + write(&mount.join("memory.stat"), "total_inactive_file 0\n"); + write(&mount.join("child/memory.limit_in_bytes"), "1073741824\n"); + write(&mount.join("child/memory.usage_in_bytes"), "0\n"); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::Limited { ram: Some(1 << 30), swap: None }); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + } + + #[cfg(target_os = "linux")] + #[test] + fn linux_cgroup_falls_back_to_conventional_layouts() { + let (proc, sys) = fixture("fallback-v2"); + write(&proc.join("self/cgroup"), "0::/app.scope\n"); + write(&sys.join("app.scope/memory.max"), "1073741824\n"); + write(&sys.join("app.scope/memory.current"), "0\n"); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::Limited { ram: Some(1 << 30), swap: None }); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + + let (proc, sys) = fixture("fallback-v1"); + write(&proc.join("self/cgroup"), "4:memory:/app\n"); + write(&sys.join("memory/memory.limit_in_bytes"), "1073741824\n"); + write(&sys.join("memory/memory.usage_in_bytes"), "0\n"); + write(&sys.join("memory/memory.stat"), "total_inactive_file 0\n"); + write(&sys.join("memory/app/memory.limit_in_bytes"), "1073741824\n"); + write(&sys.join("memory/app/memory.usage_in_bytes"), "0\n"); + write(&sys.join("memory/app/memory.stat"), "total_inactive_file 0\n"); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::Limited { ram: Some(1 << 30), swap: None }); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + } + + #[cfg(target_os = "linux")] + #[test] + fn linux_unreadable_constraints_fail_closed() { + let (proc, sys) = fixture("unreadable-missing-dir"); + write(&proc.join("self/cgroup"), "0::/missing\n"); + write(&proc.join("meminfo"), "MemAvailable: 12582912 kB\nSwapFree: 2097152 kB\n"); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::Unreadable); + let snap = linux::snapshot_at(&proc, &sys); + assert_eq!(snap.available_ram, Some(0), "host memory must not be assumed"); + assert_eq!(snap.swap_free, Some(0)); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + + let (proc, sys) = fixture("unreadable-v1-limit"); + write(&proc.join("self/cgroup"), "4:memory:/app\n"); + let mount = sys.join("memory"); + write(&proc.join("self/mountinfo"), &format!("31 24 0:26 / {} rw,relatime - cgroup cgroup rw,memory\n", mount.display())); + std::fs::create_dir_all(mount.join("app")).unwrap(); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::Unreadable); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + + let (proc, sys) = fixture("unreadable-v2-limit"); + write(&proc.join("self/cgroup"), "0::/app\n"); + write(&sys.join("app/memory.max"), "lots\n"); + write(&sys.join("app/memory.current"), "0\n"); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::Unreadable); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + + let (proc, sys) = fixture("no-memory-controller"); + write(&proc.join("self/cgroup"), "4:cpu,cpuacct:/user.slice\n"); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::NotConstrained); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + + let (proc, sys) = fixture("malformed-membership"); + write(&proc.join("self/cgroup"), "0:memory:/app\n"); + write(&proc.join("meminfo"), "MemAvailable: 12582912 kB\nSwapFree: 2097152 kB\n"); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::Unreadable, "a malformed membership line cannot prove the controller absent"); + assert_eq!(linux::snapshot_at(&proc, &sys).available_ram, Some(0), "host memory must not be assumed"); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + + let (proc, sys) = fixture("empty-membership"); + write(&proc.join("self/cgroup"), ""); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::Unreadable, "an empty membership file cannot prove absence"); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + + let (proc, sys) = fixture("mountinfo-without-cgroup"); + write(&proc.join("self/cgroup"), "0::/app\n"); + write(&proc.join("self/mountinfo"), "30 20 8:1 / / rw - ext4 /dev/root rw\n"); + write(&sys.join("app/memory.max"), "1073741824\n"); + write(&sys.join("app/memory.current"), "0\n"); + assert_eq!( + linux::cgroup_limits(&proc, &sys), + linux::CgroupLimits::Unreadable, + "a readable mountinfo without a cgroup mount must not be guessed away by the conventional path" + ); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + } + + #[cfg(target_os = "linux")] + #[test] + fn linux_snapshot_combines_host_meminfo_and_cgroup_room() { + let (proc, sys) = fixture("snapshot"); + write(&proc.join("self/cgroup"), "0::/app.scope\n"); + write(&proc.join("meminfo"), "MemTotal: 16777216 kB\nMemAvailable: 12582912 kB\nSwapFree: 2097152 kB\n"); + write(&proc.join("self/mountinfo"), &format!("30 20 0:26 / {} rw,relatime - cgroup2 cgroup2 rw\n", sys.display())); + write(&sys.join("app.scope/memory.max"), "4294967296\n"); + write(&sys.join("app.scope/memory.current"), "0\n"); + write(&sys.join("app.scope/memory.swap.max"), "536870912\n"); + write(&sys.join("app.scope/memory.swap.current"), "0\n"); + + let snap = linux::snapshot_at(&proc, &sys); + assert_eq!(snap.available_ram, Some(4 << 30), "the cgroup limit is smaller than host MemAvailable"); + assert_eq!(snap.swap_free, Some(512 << 20)); + assert_eq!(snap.commit_headroom, None); + assert_eq!(linux::available_at(&proc, &sys), Some((4 << 30) + (512 << 20)), "legacy helper keeps RAM + swap"); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + } +} diff --git a/crates/raster/src/scratch_file.rs b/crates/raster/src/scratch_file.rs index bcb46c3d0f..188c0cbcd1 100644 --- a/crates/raster/src/scratch_file.rs +++ b/crates/raster/src/scratch_file.rs @@ -247,7 +247,7 @@ fn reap_abandoned(dir: &Path, own: &File) { use std::os::unix::fs::MetadataExt; use sysinfo::{Pid, ProcessRefreshKind, ProcessesToUpdate, System}; let Ok(metadata) = own.metadata() else { return }; - let mut system = System::new(); + let Ok(mut system) = System::new() else { return }; system.refresh_processes_specifics(ProcessesToUpdate::All, true, ProcessRefreshKind::nothing()); // Fail closed when process enumeration isn't available. Live files are never removed. if system.process(Pid::from_u32(std::process::id())).is_none() { diff --git a/crates/raster/src/spill.rs b/crates/raster/src/spill.rs index 26e06785b7..ac37c85686 100644 --- a/crates/raster/src/spill.rs +++ b/crates/raster/src/spill.rs @@ -508,13 +508,8 @@ fn no_room(dir: &Path, cap: Option) -> String { #[cfg(not(target_arch = "wasm32"))] fn free_space(dir: &Path) -> Option<(u64, u64)> { let dir = std::fs::canonicalize(dir).ok()?; - let disks = sysinfo::Disks::new_with_refreshed_list_specifics(sysinfo::DiskRefreshKind::nothing().with_storage()); - disks - .list() - .iter() - .filter(|d| dir.starts_with(d.mount_point())) - .max_by_key(|d| d.mount_point().as_os_str().len()) - .map(|d| (d.available_space(), d.total_space())) + let disks = sysinfo::Disks::new_with_refreshed_list_specifics(sysinfo::DiskRefreshKind::nothing().with_storage()).ok()?; + disks.iter().filter(|d| dir.starts_with(d.mount_point())).max_by_key(|d| d.mount_point().as_os_str().len()).map(|d| (d.available_space(), d.total_space())) } #[cfg(target_arch = "wasm32")] @@ -695,6 +690,29 @@ pub fn last_error() -> Option { M.config().last_error.clone() } +/// Uncompressed tile bytes the scratch disk can still take before it reaches its size limit +/// ([`set_size_cap`]) or the volume's free-space reserve, so an import can admit tile pixels +/// beyond physical RAM. `None` while spilling is off or paused, and when neither the free space +/// nor a size limit is known (nothing to promise). Tiles are written compressed; this counts +/// them uncompressed, less 1/64 for the allocator's block rounding, so it never over-promises. +pub fn scratch_capacity() -> Option { + if !enabled() || paused() { + return None; + } + let (dir, used, cap) = { + let c = M.config(); + (c.dir.clone()?, c.file.as_ref().map_or(0, |f| f.used()), c.size_cap) + }; + let room = free_space(&dir).map(|(available, total)| available.saturating_sub(RESERVE_MIN.max(total / 20))); + let room = match (room, cap) { + (Some(room), Some(cap)) => room.min(cap.saturating_sub(used)), + (Some(room), None) => room, + (None, Some(cap)) => cap.saturating_sub(used), + (None, None) => return None, + }; + Some(room - room / 64) +} + /// Whether spilling is on (tiles beyond the budget go to disk). pub fn enabled() -> bool { M.budget.load(Ordering::Relaxed) > 0 diff --git a/crates/raster/tests/scratch_capacity.rs b/crates/raster/tests/scratch_capacity.rs new file mode 100644 index 0000000000..33698e7d15 --- /dev/null +++ b/crates/raster/tests/scratch_capacity.rs @@ -0,0 +1,40 @@ +//! [`spill::scratch_capacity`]: the room imports may count on for tile pixels beyond RAM. +//! +//! One test function: the spill manager is process-wide, so its steps must not interleave. + +use photocraft_raster::spill; + +#[test] +fn scratch_capacity_follows_spilling_the_size_limit_and_pauses() { + let root = std::env::temp_dir().join(format!("photocraft-scratch-capacity-{}", std::process::id())); + let dir = root.join("scratch"); + + // Spilling off: nothing to promise. + spill::configure(None, 0).unwrap(); + assert_eq!(spill::scratch_capacity(), None); + + spill::configure(Some(&dir), 1 << 20).unwrap(); + assert!(spill::enabled() && !spill::paused()); + // The free-space reserve applies; an unknown volume without a size limit promises nothing. + if let Some(room) = spill::scratch_capacity() { + assert!(room < u64::MAX / 2, "the reserve and margin are applied: {room}"); + } + + // The Scratch Size Limit bounds it, less the 1/64 margin, whatever the volume has free. + let cap = 64u64 << 20; + spill::set_size_cap(Some(cap)); + let room = spill::scratch_capacity().expect("a size limit is known room"); + assert!(room <= cap - cap / 64, "{room}"); + + // Paused (an unusable directory): no credit while tiles cannot leave memory. + let blocked = root.join("not-a-dir"); + std::fs::write(&blocked, b"x").unwrap(); + assert!(spill::configure(Some(&blocked), 1 << 20).is_err()); + assert!(spill::paused()); + assert_eq!(spill::scratch_capacity(), None); + + spill::set_size_cap(None); + spill::configure(None, 0).unwrap(); + assert_eq!(spill::scratch_capacity(), None); + let _ = std::fs::remove_dir_all(&root); +} diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 326e6bf7a7..9fccf05de1 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -57,6 +57,7 @@ sys-locale = "=0.3.2" winsafe = { version = "=0.0.29", default-features = false, features = ["kernel", "dxgi", "advapi"] } [dev-dependencies] +photocraft-io = { workspace = true, features = ["testgen"] } # egui's own default fonts in tests: the oracle for egui_fonts.rs, and contexts made with # `Context::default()` (no install_fonts) can lay out text. egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts"] } diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 1aac580d35..982dd5f6b3 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -194,6 +194,8 @@ impl PhotocraftApp { jpeg_options: None, dds_options: None, held_opens: Default::default(), + held_memory_prompts: Default::default(), + prompt_order: Default::default(), held_preset_import: None, allow_close: false, stylus: Default::default(), diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 27d61ddead..b62f9cc2eb 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -58,6 +58,19 @@ impl PhotocraftApp { /// [`Self::open_bytes`] for a file read from `path` (File › Save writes back there; it goes /// to Open Recent), when known. pub(crate) fn open_bytes_from(&mut self, name: &str, bytes: &[u8], path: Option<&str>) -> Result, String> { + self.open_bytes_placed(name, bytes, path, None, None) + } + + /// [`Self::open_bytes_from`] for a file dropped on a tab slot (`slot`) or opened as one of a + /// set (`order`): both survive the inline decode, a memory prompt and the final placement. + pub(crate) fn open_bytes_placed( + &mut self, + name: &str, + bytes: &[u8], + path: Option<&str>, + slot: Option, + order: Option, + ) -> Result, String> { if let Some(r) = preset_files_ui::open(self, name, bytes) { return r.map(|()| Vec::new()); } @@ -65,15 +78,28 @@ impl PhotocraftApp { // Decoded on a worker: a tab with progress appears now, the document when it's ready // (warnings are shown then). if self.background_jobs { - jobs_ui::start_open(self, name, path.map(str::to_string), jobs_ui::bytes(bytes))?; + jobs_ui::start_open(self, name, path.map(str::to_string), jobs_ui::bytes(bytes), slot, order)?; return Ok(Vec::new()); } let import = self.services.import.as_ref().ok_or("no importer configured")?; let opts = photocraft_engine::jobs::import_options(self.session.prefs()); - let (mut doc, warnings, damaged) = if photocraft_io::is_psd(bytes) { + // A PSD and a magic-detected TIFF both go through the typed IO path: only it carries + // `PsdApprovalRequired` (and, for a PSD, the structured damaged flag), so a layered + // TIFF's high-memory decision can raise its prompt instead of becoming a terminal + // string. Every other format keeps the shell's import service. + let typed_open = photocraft_io::is_psd(bytes) || photocraft_codecs::detect(bytes) == Some(photocraft_codecs::Format::Tiff); + let (mut doc, warnings, damaged) = if typed_open { // Read PSD damage as structured information in the same decode, not by - // retrying an error or matching the text of a compatibility warning. - let (r, damaged) = photocraft_io::import_for_open(name, bytes, &opts).map_err(|e| e.to_string())?; + // retrying an error or matching the text of a compatibility warning. A TIFF never + // sets it: its layered import has no damaged-content confirmation. + let (r, damaged) = match photocraft_io::import_for_open(name, bytes, &opts) { + Ok(result) => result, + Err(photocraft_io::IoError::PsdApprovalRequired { .. }) => { + jobs_ui::start_open(self, name, path.map(str::to_string), jobs_ui::bytes(bytes), slot, order)?; + return Ok(Vec::new()); + } + Err(error) => return Err(error.to_string()), + }; (r.document, r.warnings, damaged) } else { let (doc, warnings) = import(name, bytes, &opts)?; @@ -99,7 +125,8 @@ impl PhotocraftApp { path: path.map(str::to_string), warnings: warnings.clone(), bytes: (wants_raw && path.is_none()).then(|| std::sync::Arc::new(bytes.to_vec())), - slot: None, + slot, + order, question, policy_applied: false, }, @@ -112,13 +139,18 @@ impl PhotocraftApp { /// Returns the import warnings (also shown to the user). Brush and gradient /// files go to the preset libraries, as for interactive opens. pub fn open_automation_bytes(&mut self, name: &str, bytes: &[u8]) -> Result, String> { + self.open_automation_bytes_with_approval(name, bytes, false) + } + + /// [`Self::open_automation_bytes`] with the caller's high-memory approval for the imported bytes. + pub fn open_automation_bytes_with_approval(&mut self, name: &str, bytes: &[u8], approved: bool) -> Result, String> { let events_enabled = self.session.prefs().script_events.enabled; if events_enabled { self.session.edit_prefs(|prefs| prefs.script_events.enabled = false); } let result = match preset_files_ui::open(self, name, bytes) { Some(r) => r.map(|()| Vec::new()), - None => self.import_automation_document(name, bytes), + None => self.import_automation_document(name, bytes, approved), }; if events_enabled { self.session.edit_prefs(|prefs| prefs.script_events.enabled = true); @@ -128,9 +160,10 @@ impl PhotocraftApp { /// The document half of [`open_automation_bytes`](Self::open_automation_bytes): no script /// events and no Color Settings policy (which may read user-configured profile paths). - fn import_automation_document(&mut self, name: &str, bytes: &[u8]) -> Result, String> { + fn import_automation_document(&mut self, name: &str, bytes: &[u8], approved: bool) -> Result, String> { let import = self.services.import.as_ref().ok_or("no importer configured")?; - let opts = photocraft_engine::jobs::import_options(self.session.prefs()); + let mut opts = photocraft_engine::jobs::import_options(self.session.prefs()); + opts.psd_high_memory_approved = approved; let (mut doc, warnings) = import(name, bytes, &opts)?; photocraft_engine::file_cmds::raw_defaults(&self.session, &warnings, &mut doc); // The caller records the path it read from. diff --git a/crates/ui-egui/src/control/dispatch.rs b/crates/ui-egui/src/control/dispatch.rs index 3c7b22dda0..7d9c6dd5cd 100644 --- a/crates/ui-egui/src/control/dispatch.rs +++ b/crates/ui-egui/src/control/dispatch.rs @@ -1369,7 +1369,11 @@ fn app_methods(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlReques let p = &req.params; Some(match req.method.as_str() { "app.open" => match str_param(p, "path") { - Some(path) => app_open(app, path), + Some(path) => match p.get("approveHighMemory") { + None | Some(Value::Null) => app_open(app, path, false), + Some(Value::Bool(approved)) => app_open(app, path, *approved), + Some(_) => err("expected boolean for `approveHighMemory`"), + }, None => err("missing `path`"), }, "app.save" => match crate::FormatChoices::from_params(p, "app.save") { @@ -1388,7 +1392,9 @@ fn app_methods(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlReques }) } -fn app_open(app: &mut PhotocraftApp, path: &str) -> Outcome { +/// The `app.open` control method: opens a path through the configured automation read +/// capability, with optional high-memory approval. +fn app_open(app: &mut PhotocraftApp, path: &str, approved: bool) -> Outcome { if let Some(outcome) = open_pcraft_directory(app, path) { return outcome; } @@ -1398,7 +1404,7 @@ fn app_open(app: &mut PhotocraftApp, path: &str) -> Outcome { }; wrap(opened.and_then(|(name, bytes)| { let name = app.open_name(&name); - let warnings = app.open_automation_bytes(&name, &bytes)?; + let warnings = app.open_automation_bytes_with_approval(&name, &bytes, approved)?; // Brushes/gradients go to the preset libraries: no document, no Open Recent entry. if !crate::preset_files_ui::is_preset_file(&name) { app.opened_from(path); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 88a6e96dbe..0e527bf908 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -280,6 +280,7 @@ pub(crate) fn close_box(ui: &mut egui::Ui, rect: egui::Rect) -> bool { fn command_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, d: &Dialog, fields: &mut Fields, id: egui::Id, interactive: bool) -> Option { let mut outcome: Option = None; match d.kind { + _ if crate::open_prompt::owns_memory(fields) => crate::open_prompt::memory_body(ui, fields), _ if crate::open_prompt::owns_damage(fields) => crate::open_prompt::damage_body(ui, fields), _ if crate::guide_layout_ui::owns(fields) => outcome = crate::guide_layout_ui::body(app, ui, fields, interactive), _ if crate::brush_preset_dialog::owns(fields) => outcome = crate::brush_preset_dialog::body(app, ui, fields, interactive), @@ -520,6 +521,8 @@ fn button_row( fn ok_label(d: &Dialog) -> &'static str { if d.kind == DialogKind::NewDocument { tl!("Create") + } else if crate::open_prompt::owns_memory(&d.fields) { + tl!("Open anyway") } else if crate::open_prompt::owns_damage(&d.fields) { tl!("Continue") } else if crate::delete_layer_prompt::owns(&d.fields) { @@ -989,6 +992,7 @@ fn confirm_preflight(app: &mut PhotocraftApp, id: u64) -> Result<(), String> { /// and small editors are here, the rest in `confirm_command_more`. fn confirm_command(app: &mut PhotocraftApp, d: Dialog) -> Result { match d.kind { + _ if crate::open_prompt::owns_memory(&d.fields) => crate::open_prompt::answer_memory(app, true), _ if crate::open_prompt::owns_damage(&d.fields) => crate::open_prompt::answer_damage(app, true), _ if crate::guide_layout_ui::owns(&d.fields) => crate::guide_layout_ui::confirm(app, &d.fields), _ if crate::brush_preset_dialog::owns(&d.fields) => crate::brush_preset_dialog::confirm(app, &d.fields), @@ -1061,7 +1065,9 @@ pub fn cancel(app: &mut PhotocraftApp, id: u64) -> Result { app.ui.dialogs.retain(|child| child.fields.get("__dialog").and_then(Value::as_u64) != Some(id)); } // Cancel on a profile prompt opens neither its file nor the ones still to come. - if crate::open_prompt::owns_damage(&closed.fields) { + if crate::open_prompt::owns_memory(&closed.fields) { + crate::open_prompt::answer_memory(app, false)?; + } else if crate::open_prompt::owns_damage(&closed.fields) { crate::open_prompt::answer_damage(app, false)?; } else if crate::open_prompt::owns(&closed.fields) { crate::open_prompt::answer(app, None)?; diff --git a/crates/ui-egui/src/dialogs/open_prompt.rs b/crates/ui-egui/src/dialogs/open_prompt.rs index ef04f0b576..2da15f9fb4 100644 --- a/crates/ui-egui/src/dialogs/open_prompt.rs +++ b/crates/ui-egui/src/dialogs/open_prompt.rs @@ -33,6 +33,10 @@ pub struct Held { pub bytes: Option>>, /// The tab position a reopened file keeps. pub slot: Option, + /// The file's place in a set opened together, when it is one of several + /// ([`crate::jobs_ui::OpenOrder`]): kept while this file waits, so its tab still lands in the + /// set's order. + pub order: Option, /// The profile question ([`photocraft_engine::color_cmds::ColorState::open_question`]), or /// `None` to open without asking. pub question: Option, @@ -41,35 +45,95 @@ pub struct Held { pub policy_applied: bool, } +/// Dialog field for the high-memory confirmation prompt. +pub const MEMORY_FIELD: &str = "__psdMemoryOpen"; + +/// Item kind in the arrival-ordered open prompt queue. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum PromptKind { + Memory, + Open, +} + +/// An un-decoded PSD file whose preflight estimate requires user approval. +#[derive(Clone)] +pub struct MemoryPrompt { + pub id: u64, + pub name: String, + pub path: Option, + pub slot: Option, + pub order: Option, + pub estimated: u64, + /// The capacity measured when the estimate was made; `None` when it could not be measured. + pub available: Option, + /// The engine could not measure available memory for this estimate. No number is shown. + pub capacity_unknown: bool, + /// The estimate is above the unknown-capacity warning threshold (8 GiB), so the prompt also + /// says the process or tab may run out of memory. Approval stays possible. + pub uncertain_capacity_warning: bool, +} + /// Whether a file that just finished reading has to wait: one earlier in the queue does. pub fn waiting(app: &PhotocraftApp) -> bool { - !app.held_opens.is_empty() + !app.held_opens.is_empty() || !app.held_memory_prompts.is_empty() } /// Opens `held` now, or queues it behind the file whose prompt is up. pub fn arrive(app: &mut PhotocraftApp, held: Held) { app.held_opens.push_back(held); + app.prompt_order.push_back(PromptKind::Open); advance(app); } +/// Whether any open prompt (damage, profile or high-memory) is currently on screen. +pub fn has_open_dialog(app: &PhotocraftApp) -> bool { + app.ui.dialogs.iter().any(|d| owns(&d.fields) || owns_damage(&d.fields) || owns_memory(&d.fields)) +} + /// Opens queued files in order until one needs its prompt, which is shown if it isn't yet. -fn advance(app: &mut PhotocraftApp) { - while let Some(front) = app.held_opens.front() { - if front.damage_pending { - if !app.ui.dialogs.iter().any(|d| owns_damage(&d.fields)) { - show_damage(app); +pub fn advance(app: &mut PhotocraftApp) { + // Reconcile legacy callers that populated held queues directly. + if app.prompt_order.is_empty() { + app.prompt_order.extend(std::iter::repeat_n(PromptKind::Open, app.held_opens.len())); + app.prompt_order.extend(std::iter::repeat_n(PromptKind::Memory, app.held_memory_prompts.len())); + } + if has_open_dialog(app) { + return; + } + loop { + match app.prompt_order.front() { + None => return, + Some(PromptKind::Memory) => { + if let Some(front) = app.held_memory_prompts.front().cloned() { + show_memory(app, &front); + return; + } else { + app.prompt_order.pop_front(); + } } - return; - } - if front.question.is_some() { - if !app.ui.dialogs.iter().any(|d| d.fields.contains_key(FIELD)) { - show(app); + Some(PromptKind::Open) => { + let Some(front) = app.held_opens.front() else { + app.prompt_order.pop_front(); + continue; + }; + if front.damage_pending { + show_damage(app); + return; + } + if front.question.is_some() { + show(app); + return; + } + let Some(held) = app.held_opens.pop_front() else { + app.prompt_order.pop_front(); + continue; + }; + app.prompt_order.pop_front(); + let _ = open(app, held, None); + if has_open_dialog(app) { + return; + } } - return; - } - if let Some(held) = app.held_opens.pop_front() { - // A failure is shown to the user (`open_failed`); the next file still opens. - let _ = open(app, held, None); } } } @@ -129,19 +193,31 @@ pub fn answer(app: &mut PhotocraftApp, action: Option<&str>) -> Result>() { app.session.cancel_job(job); } + app.jobs.opens.clear(); + app.jobs.batches.clear(); + app.ui.dialogs.retain(|d| !owns(&d.fields) && !owns_damage(&d.fields) && !owns_memory(&d.fields)); app.ui.status = crate::i18n::fmt(tl!("Cancelled opening {name}"), &[("name", &name)]); app.ui.status_error = false; return Ok(json!({"cancelled": dropped})); }; let Some(held) = app.held_opens.pop_front() else { return Err("no file is waiting to open".into()) }; + if let Some(pos) = app.prompt_order.iter().position(|p| *p == PromptKind::Open) { + app.prompt_order.remove(pos); + } let r = open(app, held, Some(action)); advance(app); + crate::jobs_ui::end_batch(app); r } @@ -164,14 +240,19 @@ pub fn answer_remembering(app: &mut PhotocraftApp, action: &str) -> Result Result) -> Result) -> Result app .run("document.move", json!({"document": index, "to": slot})) @@ -267,3 +353,134 @@ fn open(app: &mut PhotocraftApp, held: Held, action: Option<&str>) -> Result, + slot: Option, + order: Option, + estimated: u64, + available: Option, + capacity_unknown: bool, + uncertain_capacity_warning: bool, +) { + app.held_memory_prompts.push_back(MemoryPrompt { id, name, path, slot, order, estimated, available, capacity_unknown, uncertain_capacity_warning }); + app.prompt_order.push_back(PromptKind::Memory); + advance_memory(app); +} + +/// Whether a dialog's fields mark it as the high-memory confirmation. +pub fn owns_memory(fields: &serde_json::Map) -> bool { + fields.contains_key(MEMORY_FIELD) +} + +/// Draws the high-memory prompt's message body from its dialog fields. +pub(crate) fn memory_body(ui: &mut egui::Ui, fields: &serde_json::Map) { + ui.label(fields.get("message").and_then(Value::as_str).unwrap_or_default()); +} + +/// Advances the shared open-prompt queue; memory prompts take their turn with damage and profile +/// prompts in arrival order. +pub fn advance_memory(app: &mut PhotocraftApp) { + advance(app); +} + +/// Builds and opens the confirmation dialog for a queued high-memory preflight. +fn show_memory(app: &mut PhotocraftApp, prompt: &MemoryPrompt) { + let est_gb = prompt.estimated as f64 / (1u64 << 30) as f64; + // An unmeasured capacity is never printed as a number, even if a stale measurement is + // attached: the engine's `capacityUnknown` wins. + let available = prompt.available.filter(|_| !prompt.capacity_unknown); + let mut message = match available { + Some(a) => crate::i18n::fmt( + tl!("Opening “{name}” requires an estimated {est} GiB of memory ({avail} GiB available)."), + &[("name", &prompt.name), ("est", &format!("{est_gb:.1}")), ("avail", &format!("{:.1}", a as f64 / (1u64 << 30) as f64))], + ), + None => crate::i18n::fmt( + tl!("Opening “{name}” requires an estimated {est} GiB of memory. The available memory could not be measured."), + &[("name", &prompt.name), ("est", &format!("{est_gb:.1}"))], + ), + }; + message.push_str("\n\n"); + message.push_str(tl!("Opening this document uses more memory and may slow down your computer or other running applications.")); + if prompt.uncertain_capacity_warning { + message.push_str("\n\n"); + message.push_str(tl!( + "The estimate is above 8 GiB and the available memory is unknown, so this process or browser tab may run out of memory. You can still try to open it." + )); + } + + let fields = [ + (MEMORY_FIELD.into(), json!(true)), + ("__label".into(), json!(tl!("High Memory Photoshop Document"))), + ("name".into(), json!(prompt.name)), + ("id".into(), json!(prompt.id)), + ("message".into(), json!(message)), + ("estimated".into(), json!(prompt.estimated)), + ("available".into(), json!(available)), + ("capacityUnknown".into(), json!(prompt.capacity_unknown)), + ("uncertainCapacityWarning".into(), json!(prompt.uncertain_capacity_warning)), + ] + .into_iter() + .collect(); + + app.ui.open_dialog(crate::state::DialogKind::Command, fields); +} + +/// Answers the front high-memory prompt: accepts and starts the approved open, or declines and +/// advances the queue. The engine command revalidates the source identity and the hard limit. +pub(crate) fn answer_memory(app: &mut PhotocraftApp, accept: bool) -> Result { + let Some(front) = app.held_memory_prompts.pop_front() else { + advance(app); + return Err("no high-memory PSD is waiting for confirmation".into()); + }; + if let Some(pos) = app.prompt_order.iter().position(|p| *p == PromptKind::Memory) { + app.prompt_order.remove(pos); + } + let id = front.id; + let name = front.name.clone(); + let path = front.path.clone(); + let slot = front.slot; + let order = front.order; + + let res = app.run("file.approveMemory", json!({"id": id, "approve": accept, "background": app.background_jobs})).map_err(|e| format!("{}: {e}", name)); + + match res { + Ok(r) => { + if accept { + if let Some(job) = r.get("job").and_then(Value::as_u64) { + app.jobs.opens.push(crate::jobs_ui::OpenTab { job: photocraft_engine::jobs::JobId(job), name: name.clone(), path, slot, order }); + app.jobs.focus = Some(photocraft_engine::jobs::JobId(job)); + app.ui.chrome.home = None; + app.ui.status = crate::i18n::fmt(tl!("Opening {name}…"), &[("name", &name)]); + app.ui.status_error = false; + } else if let Some(result) = r.get("result") { + let tab = crate::jobs_ui::OpenTab { job: photocraft_engine::jobs::JobId(0), name: name.clone(), path: path.clone(), slot, order }; + if let Err(e) = crate::jobs_ui::finish_open_tab(app, &tab, result) { + app.ui.status = e; + app.ui.status_error = true; + } + } + } else { + app.ui.status = crate::i18n::fmt(tl!("Cancelled opening {name}"), &[("name", &name)]); + app.ui.status_error = false; + crate::jobs_ui::end_batch(app); + } + advance(app); + crate::jobs_ui::end_batch(app); + Ok(r) + } + Err(err) => { + app.ui.status = err.clone(); + app.ui.status_error = true; + crate::jobs_ui::end_batch(app); + advance(app); + crate::jobs_ui::end_batch(app); + Err(err) + } + } +} diff --git a/crates/ui-egui/src/file_open.rs b/crates/ui-egui/src/file_open.rs index 65c1fb5758..814fc4e114 100644 --- a/crates/ui-egui/src/file_open.rs +++ b/crates/ui-egui/src/file_open.rs @@ -93,16 +93,27 @@ impl PhotocraftApp { /// `path` for File › Save unless it is a derivative preview, and `path` goes to the top of Open Recent. Returns the import /// warnings (also shown to the user). pub fn open_file(&mut self, path: &str, bytes: &[u8]) -> Result, String> { + self.open_file_placed(path, bytes, None, None) + } + + /// [`Self::open_file`] for a file dropped on a tab slot or opened as one of a set. + pub(crate) fn open_file_placed( + &mut self, + path: &str, + bytes: &[u8], + slot: Option, + order: Option, + ) -> Result, String> { // Brushes/gradients go to the preset libraries (no document, no Open Recent entry). if let Some(r) = crate::preset_files_ui::open(self, path, bytes) { return r.map(|()| Vec::new()); } if self.background_jobs { // The path and Open Recent are recorded when the background open finishes. - crate::jobs_ui::start_open(self, &display_name(path), Some(path.to_string()), crate::jobs_ui::bytes(bytes))?; + crate::jobs_ui::start_open(self, &display_name(path), Some(path.to_string()), crate::jobs_ui::bytes(bytes), slot, order)?; return Ok(Vec::new()); } - self.open_bytes_from(&display_name(path), bytes, Some(path)) + self.open_bytes_placed(&display_name(path), bytes, Some(path), slot, order) } /// Record that the active document was just opened from `path`: File › Save writes back to it @@ -131,6 +142,13 @@ impl PhotocraftApp { /// Read and open the file at `path` (see [`open_file`](Self::open_file)). #[cfg(not(target_arch = "wasm32"))] pub fn open_path(&mut self, path: &str) -> Result, String> { + self.open_path_placed(path, None, None) + } + + /// [`Self::open_path`] for a file dropped on a tab slot or opened as one of a set: the slot + /// and order survive an inline memory/profile prompt and the document's final placement. + #[cfg(not(target_arch = "wasm32"))] + fn open_path_placed(&mut self, path: &str, slot: Option, order: Option) -> Result, String> { if self.show_if_open(path) { return Ok(Vec::new()); } @@ -138,11 +156,18 @@ impl PhotocraftApp { // would block the window). Preset files (brushes, gradients) go the usual way. let ext = std::path::Path::new(path).extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default(); if self.background_jobs && !crate::preset_files_ui::PRESET_EXTS.contains(&ext.as_str()) { - crate::jobs_ui::start_open(self, &display_name(path), Some(path.to_string()), photocraft_engine::jobs::OpenSource::Path(path.to_string()))?; + crate::jobs_ui::start_open( + self, + &display_name(path), + Some(path.to_string()), + photocraft_engine::jobs::OpenSource::Path(path.to_string()), + slot, + order, + )?; return Ok(Vec::new()); } let bytes = photocraft_format::read_file(std::path::Path::new(path)).map_err(|e| format!("{path}: {e}"))?; - self.open_file(path, &bytes) + self.open_file_placed(path, &bytes, slot, order) } #[cfg(target_arch = "wasm32")] @@ -150,6 +175,12 @@ impl PhotocraftApp { Err(format!("cannot open paths on the web: {path}")) } + /// The web has no filesystem paths: a drop read by the shell arrives as bytes. + #[cfg(target_arch = "wasm32")] + fn open_path_placed(&mut self, path: &str, _slot: Option, _order: Option) -> Result, String> { + Err(format!("cannot open paths on the web: {path}")) + } + /// Open several files, reporting each failure to the user instead of stopping. Relative paths /// are resolved against the working directory so the remembered path stays valid. The files /// open in name order ([`natural_cmp`]: `File_2` before `File_10`), and their tabs keep that @@ -168,21 +199,14 @@ impl PhotocraftApp { continue; } let order = crate::jobs_ui::OpenOrder { batch, seq }; - let pending = self.jobs.opens.len(); - match self.open_path(abs) { - Ok(_) => { - opened += 1; - // A background open's tab takes its place when it finishes; a document opened - // at once is in place now. - match self.jobs.opens.get_mut(pending) { - Some(tab) => tab.order = Some(order), - None => crate::jobs_ui::opened_in_order(&mut self.jobs, order), - } - } + // The order travels with the open: a background tab, an inline document, or a memory + // prompt that is answered later all place the file at its place in the set. + match self.open_path_placed(abs, None, Some(order)) { + Ok(_) => opened += 1, Err(e) => self.open_failed(&display_name(abs), &e), } } - crate::jobs_ui::end_batch(&mut self.jobs); + crate::jobs_ui::end_batch(self); opened } @@ -198,6 +222,13 @@ impl PhotocraftApp { } else if let Some(o) = self.jobs.opens.iter().find(|o| o.path.as_deref().is_some_and(|p| !is_template(p) && same(p))) { // A template still loading opens as another Untitled, as it does once loaded. self.jobs.focus = Some(o.job); + } else if self.held_memory_prompts.iter().any(|m| m.path.as_deref().is_some_and(|p| !is_template(p) && same(p))) { + // The file's high-memory prompt is already waiting: show it, don't queue a second + // prompt and a second open for the same file. A template still opens again as + // another Untitled, like one that is still loading. + crate::open_prompt::advance_memory(self); + self.ui.chrome.home = None; + return true; } else { return false; } @@ -282,22 +313,23 @@ impl PhotocraftApp { DropTarget::Elsewhere } - /// Open one dropped file; with `slot`, its tab goes there (when it finishes opening, for - /// background opens). True when it took the slot. + /// Open one dropped file; with `slot`, its tab goes there (at once, or when a held prompt is + /// answered). True when it took the slot. fn open_dropped_file(&mut self, f: &egui::DroppedFileHandle, name: &str, slot: Option) -> Result { - // Opens append: a background open's tab, or a document. let (docs, opens) = (self.session.documents().len(), self.jobs.opens.len()); + let held = self.held_opens.len() + self.held_memory_prompts.len(); + // The slot travels with the open through the inline document, a background tab and a + // memory/profile prompt, so no separate move here can land on another document. if f.path().is_absolute() { - self.open_path(&path_text(f.path(), false)?)?; + self.open_path_placed(&path_text(f.path(), false)?, slot, None)?; } else { - self.open_bytes(name, &crate::read_dropped(&**f)?)?; + self.open_bytes_placed(name, &crate::read_dropped(&**f)?, None, slot, None)?; } - let Some(slot) = slot else { return Ok(false) }; - if let Some(tab) = self.jobs.opens.get_mut(opens) { - tab.slot = Some(slot); - return Ok(true); + if slot.is_none() { + return Ok(false); } - Ok(self.run("document.move", serde_json::json!({"document": docs, "to": slot})).is_ok()) + let took = self.jobs.opens.len() > opens || self.session.documents().len() > docs || self.held_opens.len() + self.held_memory_prompts.len() > held; + Ok(took) } /// Place the next file dropped on the canvas and start Free Transform on it, once no other diff --git a/crates/ui-egui/src/file_open/tests.rs b/crates/ui-egui/src/file_open/tests.rs index c0323da9a1..bd74eceb9e 100644 --- a/crates/ui-egui/src/file_open/tests.rs +++ b/crates/ui-egui/src/file_open/tests.rs @@ -885,7 +885,7 @@ fn a_set_of_background_opens_keeps_its_order_however_they_finish() { let index = app.session.add_document(Document::new("f1.psd", Size::new(4, 4), ColorMode::Rgb, SampleType::U8), None); assert_eq!(index, 1); jobs_ui::opened_in_order(&mut app.jobs, OpenOrder { batch, seq: 1 }); - jobs_ui::end_batch(&mut app.jobs); + jobs_ui::end_batch(&mut app); assert_eq!(app.jobs.batches.len(), 1, "kept while members are opening"); // The rest finish out of order: last, first, third. for seq in [3usize, 0, 2] { diff --git a/crates/ui-egui/src/jobs_ui.rs b/crates/ui-egui/src/jobs_ui.rs index 00fce3da53..760a7b6b48 100644 --- a/crates/ui-egui/src/jobs_ui.rs +++ b/crates/ui-egui/src/jobs_ui.rs @@ -197,14 +197,24 @@ pub fn run(app: &mut PhotocraftApp, id: &str, params: Value) -> Result, source: OpenSource) -> Result<(), String> { +/// replaces it when decoded. `path` is remembered for File › Save and Open Recent. `slot` (a file +/// dropped on the tabs) and `order` (its place in a set opened together) survive an inline +/// completion, a memory prompt and the open itself, so the tab lands where it belongs either way. +pub fn start_open( + app: &mut PhotocraftApp, + name: &str, + path: Option, + source: OpenSource, + slot: Option, + order: Option, +) -> Result<(), String> { let name = &app.open_name(name); - match app.session.start_open_for_user(name, source).map_err(|e| e.to_string())? { - // Inline (wasm): finish now, like a background open that ended at once. - Started::Done(v) => finish_open(app, name, path.as_deref(), &v, None), + match app.session.start_open_for_user_with_background(name, source, app.background_jobs).map_err(|e| e.to_string())? { + // Inline (wasm, or background jobs off): finish now, like a background open that ended at + // once. A preflight keeps the slot and set order in its memory prompt. + Started::Done(v) => finish_open(app, name, path.as_deref(), &v, slot, order), Started::Job(job) => { - app.jobs.opens.push(OpenTab { job, name: name.to_string(), path, slot: None, order: None }); + app.jobs.opens.push(OpenTab { job, name: name.to_string(), path, slot, order }); app.jobs.focus = Some(job); app.ui.chrome.home = None; app.ui.status = crate::i18n::fmt(tl!("Opening {name}…"), &[("name", name)]); @@ -226,16 +236,20 @@ pub(crate) fn begin_batch(app: &mut PhotocraftApp) -> u64 { /// A member of a set opened at once (not in the background): its document is in place at the /// end, so later members go after it. +#[cfg(test)] pub(crate) fn opened_in_order(jobs: &mut JobsUi, order: OpenOrder) { if let Some(batch) = jobs.batches.iter_mut().find(|b| b.id == order.batch) { batch.opened.push(order.seq); } } -/// Every member of the set has been started: forget it unless some are still opening. -pub(crate) fn end_batch(jobs: &mut JobsUi) { - let opens = &jobs.opens; - jobs.batches.retain(|b| opens.iter().any(|o| o.order.is_some_and(|x| x.batch == b.id))); +/// Every member of the set has been started: forget it unless some are still opening, waiting on +/// their prompt (memory, profile or damage), or waiting for a prompt to clear. +pub(crate) fn end_batch(app: &mut PhotocraftApp) { + let waiting: Vec = + app.held_memory_prompts.iter().filter_map(|m| m.order.map(|o| o.batch)).chain(app.held_opens.iter().filter_map(|h| h.order.map(|o| o.batch))).collect(); + let JobsUi { opens, batches, .. } = &mut app.jobs; + batches.retain(|b| opens.iter().any(|o| o.order.is_some_and(|x| x.batch == b.id)) || waiting.contains(&b.id)); } /// The tab position for a member of a set that just opened: after the members before it that @@ -247,12 +261,19 @@ fn batch_slot(jobs: &mut JobsUi, order: OpenOrder) -> Option { Some(slot) } +/// Where a finished open puts its tab: an explicit slot (a file dropped on the tabs) wins; +/// otherwise its place in a set opened together, if that set is still tracked. +pub(crate) fn tab_slot(app: &mut PhotocraftApp, slot: Option, order: Option) -> Option { + let in_set = order.and_then(|o| batch_slot(&mut app.jobs, o)); + slot.or(in_set) +} + /// A background open's result (`{document, warnings, color}`) for `tab`, already taken out of -/// [`JobsUi::opens`]: the document goes to the tab's slot, or to its place in its set. +/// [`JobsUi::opens`]: the document goes to the tab's slot, or to its place in its set. A memory +/// preflight keeps both in its prompt. pub(crate) fn finish_open_tab(app: &mut PhotocraftApp, tab: &OpenTab, v: &Value) -> Result<(), String> { - let slot = tab.slot.or_else(|| tab.order.and_then(|o| batch_slot(&mut app.jobs, o))); - let r = finish_open(app, &tab.name, tab.path.as_deref(), v, slot); - end_batch(&mut app.jobs); + let r = finish_open(app, &tab.name, tab.path.as_deref(), v, tab.slot, tab.order); + end_batch(app); r } @@ -447,6 +468,8 @@ pub fn cancel(app: &mut PhotocraftApp, id: JobId) -> bool { cancelled } +/// Handles one finished job: optional completion beep, waiting control replies, and the +/// command-specific open, save, transform and recovery paths. fn on_event(app: &mut PhotocraftApp, ctx: &egui::Context, e: JobEvent) { // Preferences ▸ General ▸ Beep When Done (off by default): a finished operation beeps, like // Photoshop's cue. Cancelling is the user's own action and stays silent. @@ -507,7 +530,7 @@ fn on_event(app: &mut PhotocraftApp, ctx: &egui::Context, e: JobEvent) { app.ui.status_error = false; } } - end_batch(&mut app.jobs); + end_batch(app); return; } match e.outcome { @@ -546,8 +569,29 @@ fn on_event(app: &mut PhotocraftApp, ctx: &egui::Context, e: JobEvent) { } /// What [`crate::PhotocraftApp::open_bytes`] does after decoding, for a background open's result -/// (`{document, docId, warnings, color}` or `{held, …}`). -fn finish_open(app: &mut PhotocraftApp, name: &str, path: Option<&str>, v: &Value, slot: Option) -> Result<(), String> { +/// (`{document, docId, warnings, color}` or `{held, …}`). `slot` and `order` are the tab position +/// and set place the file keeps: through a memory prompt, a profile/damage prompt and the final +/// document, so an inline completion lands where a background tab would. +fn finish_open(app: &mut PhotocraftApp, name: &str, path: Option<&str>, v: &Value, slot: Option, order: Option) -> Result<(), String> { + if let Some(preflight_id) = v.get("pendingPreflight").and_then(Value::as_u64) { + let estimated = v.get("estimated").and_then(Value::as_u64).unwrap_or(0); + let available = v.get("availableRam").and_then(Value::as_u64); + let capacity_unknown = v.get("capacityUnknown").and_then(Value::as_bool).unwrap_or(available.is_none()); + let uncertain_capacity_warning = v.get("uncertainCapacityWarning").and_then(Value::as_bool).unwrap_or(false); + crate::open_prompt::arrive_memory( + app, + preflight_id, + name.to_string(), + path.map(str::to_string), + slot, + order, + estimated, + available, + capacity_unknown, + uncertain_capacity_warning, + ); + return Ok(()); + } let warnings: Vec = v.get("warnings").and_then(Value::as_array).map(|a| a.iter().filter_map(|w| w.as_str().map(str::to_string)).collect()).unwrap_or_default(); let held = |doc, read_only, question, policy_applied| crate::open_prompt::Held { @@ -559,6 +603,7 @@ fn finish_open(app: &mut PhotocraftApp, name: &str, path: Option<&str>, v: &Valu warnings: warnings.clone(), bytes: None, slot, + order, question, policy_applied, }; @@ -581,7 +626,7 @@ fn finish_open(app: &mut PhotocraftApp, name: &str, path: Option<&str>, v: &Valu crate::open_prompt::arrive(app, held(doc, read_only, None, true)); return Ok(()); } - if let Some(slot) = slot { + if let Some(slot) = tab_slot(app, slot, order) { let _ = app.run("document.move", json!({"document": index, "to": slot})); } after_open(app, document, name, path, &warnings, None) diff --git a/crates/ui-egui/src/jobs_ui/tests.rs b/crates/ui-egui/src/jobs_ui/tests.rs index 4377074ed5..ffb6207fd4 100644 --- a/crates/ui-egui/src/jobs_ui/tests.rs +++ b/crates/ui-egui/src/jobs_ui/tests.rs @@ -940,7 +940,7 @@ fn background_open_warns_about_missing_fonts() { // What the open job leaves behind: the decoded document in the session, then its result. let (index, _) = app.session.open_document(doc, None); let id = app.session.documents()[index].doc.id; - super::finish_open(&mut app, "poster.psd", None, &json!({"document": index, "docId": id.0, "warnings": []}), None).unwrap(); + super::finish_open(&mut app, "poster.psd", None, &json!({"document": index, "docId": id.0, "warnings": []}), None, None).unwrap(); let want = vec!["font 'NoSuchFamily4559' is not installed; text may render using a fallback face".to_string()]; assert!(app.ui.notices.last().is_some_and(|n| n.title.contains("poster.psd") && n.lines == want), "{:?}", app.ui.notices); } @@ -1022,7 +1022,7 @@ fn open_identity_survives_tab_reordering() { let old_index = result["document"].as_u64().unwrap() as usize; app.session.move_document(old_index, 0).unwrap(); assert_eq!(app.session.documents()[old_index].doc.id, control.doc.id); - super::finish_open(&mut app, "imported.png", Some("imported.png"), &result, None).unwrap(); + super::finish_open(&mut app, "imported.png", Some("imported.png"), &result, None, None).unwrap(); control.assert_untouched(&app); assert_eq!(app.session.active().unwrap().doc.id, imported); assert_eq!(app.session.active().unwrap().path.as_deref(), Some("imported.png")); @@ -1037,7 +1037,7 @@ fn open_identity_survives_an_earlier_tab_closing() { let (result, imported) = identified_result(&app, result); app.session.close(1).unwrap(); app.session.set_active(0); - super::finish_open(&mut app, "imported.png", Some("imported.png"), &result, Some(0)).unwrap(); + super::finish_open(&mut app, "imported.png", Some("imported.png"), &result, Some(0), None).unwrap(); control.assert_untouched(&app); assert_eq!(app.session.active().unwrap().doc.id, imported); assert_eq!(app.session.documents()[0].doc.id, imported, "the requested destination slot applies to the correct document"); @@ -1059,13 +1059,13 @@ fn open_identity_rejects_closed_missing_and_invalid_identities() { } Some(value) => result["docId"] = value, } - assert!(super::finish_open(&mut app, "closed.png", Some("closed.png"), &result, Some(0)).is_err(), "invalid identity was accepted: {result}"); + assert!(super::finish_open(&mut app, "closed.png", Some("closed.png"), &result, Some(0), None).is_err(), "invalid identity was accepted: {result}"); control.assert_untouched(&app); assert_eq!(app.session.active().unwrap().doc.id, control.doc.id); assert_eq!(app.session.documents().len(), 1); result["docId"] = json!(imported.0); assert!( - super::finish_open(&mut app, "closed.png", Some("closed.png"), &result, None).is_err(), + super::finish_open(&mut app, "closed.png", Some("closed.png"), &result, None, None).is_err(), "a closed identity must not fall back to the old tab index" ); control.assert_untouched(&app); @@ -1086,9 +1086,9 @@ fn open_identity_keeps_same_poll_results_in_the_profile_queue() { let (second, second_id) = identified_result(&app, second); // All engine applies have finished. Handling the first ordinary result removes its tab, // shifting the second result before its UI callback runs. - super::finish_open(&mut app, "profile.png", Some("profile.png"), &prompt, None).unwrap(); - super::finish_open(&mut app, "first.png", Some("first.png"), &first, None).unwrap(); - super::finish_open(&mut app, "second.png", Some("second.png"), &second, None).unwrap(); + super::finish_open(&mut app, "profile.png", Some("profile.png"), &prompt, None, None).unwrap(); + super::finish_open(&mut app, "first.png", Some("first.png"), &first, None, None).unwrap(); + super::finish_open(&mut app, "second.png", Some("second.png"), &second, None, None).unwrap(); assert_eq!(app.held_opens.iter().map(|held| held.name.as_str()).collect::>(), ["profile.png", "first.png", "second.png"]); assert_eq!(app.held_opens.iter().skip(1).map(|held| held.doc.id).collect::>(), [first_id, second_id]); assert_eq!(app.session.documents().len(), 1, "both completed imports wait behind the profile prompt"); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 87f7ddf100..8c82874876 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -691,6 +691,9 @@ pub struct PhotocraftApp { /// Files read but not opened yet: the first waits on its profile prompt, the rest behind it /// (see `open_prompt`). pub(crate) held_opens: std::collections::VecDeque, + /// PSD files whose memory preflight requires user approval before pixel decoding (see `open_prompt`). + pub(crate) held_memory_prompts: std::collections::VecDeque, + pub(crate) prompt_order: std::collections::VecDeque, /// A brush or gradient file waiting on the group-name prompt (see `preset_group_prompt`). pub(crate) held_preset_import: Option, /// Set once the user has agreed to quit, so the resulting close request goes through. diff --git a/crates/ui-egui/src/psd_open_tests.rs b/crates/ui-egui/src/psd_open_tests.rs index 1c40f898bd..719c760f35 100644 --- a/crates/ui-egui/src/psd_open_tests.rs +++ b/crates/ui-egui/src/psd_open_tests.rs @@ -197,3 +197,759 @@ fn background_damage_only_open_does_not_create_a_spurious_profile_question() { assert_eq!(app.session.documents().len(), 1); assert!(app.ui.dialogs.is_empty(), "color:null is not a profile question"); } + +#[test] +fn memory_confirmation_dialog_and_cancel_lifecycle() { + let mut app = app(); + let gb = 1u64 << 30; + + let preflight_id = app + .session + .store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { + id: 0, + name: "high_mem.psd".into(), + source: photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0; 16])), + fingerprint: photocraft_engine::jobs::SourceFingerprint::of(&photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0; 16]))).unwrap(), + required: 7 * gb, + soft_limit: 4 * gb, + hard_limit: 8 * gb, + available_ram: Some(10 * gb), + confirm_damage: true, + }) + .unwrap(); + + crate::open_prompt::arrive_memory(&mut app, preflight_id, "high_mem.psd".into(), None, None, None, 7 * gb, Some(10 * gb), false, false); + assert_eq!(app.ui.dialogs.len(), 1); + assert!(crate::open_prompt::owns_memory(&app.ui.dialogs[0].fields)); + let dlg_id = app.ui.dialogs[0].id; + + assert_eq!(call(&mut app, "ui.dialog.cancel", json!({"dialog": dlg_id}))["ok"], true); + assert!(app.ui.dialogs.is_empty()); + assert!(app.session.take_pending_preflight(preflight_id).is_none(), "pending preflight dropped on cancel"); + assert!(app.held_memory_prompts.is_empty()); + assert!(app.prompt_order.is_empty()); +} + +/// #10897: the inline path (the browser shell and any desktop open with background jobs off) +/// routes the memory prompt's answer through `file.approveMemory`, and the retry only opens the +/// file when it carries the one-shot approval. A tiny fixture under a scoped estimate charge +/// reaches the real approval window, so dropping the approval flag or the bound estimate in the +/// retry leaves the prompt (and no document) instead of passing silently. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn memory_confirmation_resume_inline_success() { + if cfg!(target_pointer_width = "32") { + return; // the 3 GiB charge would exceed a 32-bit process cap + } + let gb = 1u64 << 30; + let mut app = app(); + app.background_jobs = false; + let psd = recovery_psd::make_psd(false); + // Known 5 GiB: S = 2.5 GiB, H = 3.75 GiB. The 3 GiB charge lands in (S, H] on this thread. + let snap = photocraft_io::memory::MemorySnapshot { available_ram: Some(5 * gb), swap_free: None, commit_headroom: None }; + photocraft_io::psd_budget::with_test_estimate_charge(3 * gb, || { + photocraft_io::memory::with_mock_memory(snap, || { + // The real inline import raises the preflight: no fabricated prompt or preflight. + app.open_bytes_from("inline_resume.psd", &psd, Some("/test/inline_resume.psd")).unwrap(); + assert!(app.session.documents().is_empty(), "the file waits for approval"); + assert_eq!(app.held_memory_prompts.len(), 1); + assert_eq!(app.ui.dialogs.len(), 1); + let fields = &app.ui.dialogs[0].fields; + assert!(crate::open_prompt::owns_memory(fields)); + assert!(fields["estimated"].as_u64().unwrap() > 3 * gb, "the charged estimate is shown: {fields:?}"); + assert_eq!(fields["available"], json!(5 * gb)); + assert_eq!(fields["capacityUnknown"], json!(false)); + assert_eq!(fields["uncertainCapacityWarning"], json!(false)); + let dlg_id = app.ui.dialogs[0].id; + + let res = call(&mut app, "ui.dialog.confirm", json!({"dialog": dlg_id})); + assert_eq!(res["ok"], true, "{res}"); + assert!(app.ui.dialogs.is_empty(), "dialog dismissed after inline resume"); + assert_eq!(app.session.documents().len(), 1, "document opened via inline resume"); + assert_eq!(app.session.documents()[0].doc.name, "inline_resume.psd"); + assert_eq!(app.session.documents()[0].path.as_deref(), Some("/test/inline_resume.psd")); + assert!(app.held_memory_prompts.is_empty()); + assert!(app.held_opens.is_empty()); + assert!(app.prompt_order.is_empty()); + assert!(app.jobs.opens.is_empty()); + assert_eq!(app.session.pending_preflight_bytes().unwrap(), 0, "the approval consumed and released the preflight"); + }); + }); +} + +/// #10897: a background open carries the same scoped estimate into its worker through the +/// explicitly captured test scope (never a global mock), so the real job raises the approval +/// prompt; the retry then opens the file only with the one-shot approval. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn memory_confirmation_resume_background_success() { + if cfg!(target_pointer_width = "32") { + return; // the 3 GiB charge would exceed a 32-bit process cap + } + let gb = 1u64 << 30; + let mut app = app(); + app.background_jobs = true; + let psd = recovery_psd::make_psd(false); + let snap = photocraft_io::memory::MemorySnapshot { available_ram: Some(5 * gb), swap_free: None, commit_headroom: None }; + photocraft_io::psd_budget::with_test_estimate_charge(3 * gb, || { + photocraft_io::memory::with_mock_memory(snap, || { + app.open_bytes_from("bg_resume.psd", &psd, Some("/test/bg_resume.psd")).unwrap(); + assert_eq!(app.jobs.opens.len(), 1, "a background open tab appears at once"); + let jobs: Vec<_> = app.session.jobs().iter().map(|j| j.id).collect(); + for id in jobs { + app.session.wait_job(id).unwrap(); + } + crate::jobs_ui::tick(&mut app, &egui::Context::default()); + assert!(app.session.documents().is_empty(), "the file waits for approval"); + assert_eq!(app.held_memory_prompts.len(), 1); + assert_eq!(app.ui.dialogs.len(), 1); + let fields = &app.ui.dialogs[0].fields; + assert!(crate::open_prompt::owns_memory(fields)); + assert!(fields["estimated"].as_u64().unwrap() > 3 * gb, "the worker made the charged estimate: {fields:?}"); + assert_eq!(fields["available"], json!(5 * gb)); + assert_eq!(fields["capacityUnknown"], json!(false)); + let dlg_id = app.ui.dialogs[0].id; + + let res = call(&mut app, "ui.dialog.confirm", json!({"dialog": dlg_id})); + assert_eq!(res["ok"], true, "{res}"); + assert_eq!(app.jobs.opens.len(), 1, "background retry job registered in jobs.opens"); + + let jobs: Vec<_> = app.session.jobs().iter().map(|j| j.id).collect(); + for id in jobs { + app.session.wait_job(id).unwrap(); + } + crate::jobs_ui::tick(&mut app, &egui::Context::default()); + assert_eq!(app.session.documents().len(), 1, "document opened via background resume"); + assert_eq!(app.session.documents()[0].doc.name, "bg_resume.psd"); + assert_eq!(app.session.documents()[0].path.as_deref(), Some("/test/bg_resume.psd")); + assert!(app.ui.dialogs.is_empty()); + assert!(app.held_memory_prompts.is_empty()); + assert!(app.held_opens.is_empty()); + assert!(app.prompt_order.is_empty()); + assert!(app.jobs.opens.is_empty()); + assert_eq!(app.session.pending_preflight_bytes().unwrap(), 0); + }); + }); +} + +#[test] +fn memory_confirmation_refuses_when_source_changed_inline() { + let mut app = app(); + app.background_jobs = false; + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("changed.psd"); + std::fs::write(&path, b"initial file contents").unwrap(); + + let src = photocraft_engine::jobs::OpenSource::Path(path.to_string_lossy().to_string()); + let fp = photocraft_engine::jobs::SourceFingerprint::of(&src).unwrap(); + + let preflight_id = app + .session + .store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { + id: 0, + name: "changed.psd".into(), + source: src, + fingerprint: fp, + required: 1000, + soft_limit: 500, + hard_limit: 50_000, + available_ram: Some(100_000), + confirm_damage: true, + }) + .unwrap(); + + crate::open_prompt::arrive_memory( + &mut app, + preflight_id, + "changed.psd".into(), + Some(path.to_string_lossy().to_string()), + None, + None, + 1000, + Some(100_000), + false, + false, + ); + assert_eq!(app.ui.dialogs.len(), 1); + let dlg_id = app.ui.dialogs[0].id; + + // Mutate file before confirming: + std::fs::write(&path, b"modified file contents longer").unwrap(); + + let res = call(&mut app, "ui.dialog.confirm", json!({"dialog": dlg_id})); + assert_eq!(res["ok"], false, "confirming changed file inline must fail"); + let error = res["error"].as_str().unwrap_or_default(); + assert!(error.contains("changed since it was checked"), "the refusal names the changed identity, not a parser failure: {res}"); + assert!(app.session.documents().is_empty()); + assert!(app.held_memory_prompts.is_empty()); +} + +#[test] +fn memory_confirmation_refuses_when_source_changed_async() { + let mut app = app(); + app.background_jobs = true; + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("changed_async.psd"); + std::fs::write(&path, b"initial file contents").unwrap(); + + let src = photocraft_engine::jobs::OpenSource::Path(path.to_string_lossy().to_string()); + let fp = photocraft_engine::jobs::SourceFingerprint::of(&src).unwrap(); + + let preflight_id = app + .session + .store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { + id: 0, + name: "changed_async.psd".into(), + source: src, + fingerprint: fp, + required: 1000, + soft_limit: 500, + hard_limit: 50_000, + available_ram: Some(100_000), + confirm_damage: true, + }) + .unwrap(); + + crate::open_prompt::arrive_memory( + &mut app, + preflight_id, + "changed_async.psd".into(), + Some(path.to_string_lossy().to_string()), + None, + None, + 1000, + Some(100_000), + false, + false, + ); + assert_eq!(app.ui.dialogs.len(), 1); + let dlg_id = app.ui.dialogs[0].id; + + // Mutate file before confirming: + std::fs::write(&path, b"modified file contents longer").unwrap(); + + let res = call(&mut app, "ui.dialog.confirm", json!({"dialog": dlg_id})); + assert_eq!(res["ok"], true, "confirmation kicks off background job"); + assert_eq!(app.jobs.opens.len(), 1); + + // Run the job to completion and observe async failure: + let jobs: Vec<_> = app.session.jobs().iter().map(|j| j.id).collect(); + for id in jobs { + let _ = app.session.wait_job(id); + } + crate::jobs_ui::tick(&mut app, &egui::Context::default()); + + assert!(app.session.documents().is_empty(), "no document opened on changed file failure"); + assert!(app.jobs.opens.is_empty(), "opens cleared on job failure"); + assert!(app.ui.status_error, "error recorded in UI status"); + assert!(app.ui.status.contains("changed since it was checked"), "the background refusal names the changed identity: {}", app.ui.status); +} + +#[test] +fn memory_decline_advances_queue_and_cleans_batch() { + let mut app = app(); + let batch_id = crate::jobs_ui::begin_batch(&mut app); + let order = crate::jobs_ui::OpenOrder { batch: batch_id, seq: 0 }; + + let preflight_id = app + .session + .store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { + id: 0, + name: "declined.psd".into(), + source: photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0; 16])), + fingerprint: photocraft_engine::jobs::SourceFingerprint::of(&photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0; 16]))).unwrap(), + required: 1000, + soft_limit: 500, + hard_limit: 2000, + available_ram: Some(4000), + confirm_damage: true, + }) + .unwrap(); + + crate::open_prompt::arrive_memory(&mut app, preflight_id, "declined.psd".into(), None, None, Some(order), 1000, Some(4000), false, false); + assert_eq!(app.ui.dialogs.len(), 1); + let dlg_id = app.ui.dialogs[0].id; + + let res = call(&mut app, "ui.dialog.cancel", json!({"dialog": dlg_id})); + assert_eq!(res["ok"], true); + assert!(app.ui.dialogs.is_empty()); + assert!(app.session.take_pending_preflight(preflight_id).is_none()); + assert!(app.jobs.batches.is_empty(), "batch cleaned up on decline"); + assert!(app.prompt_order.is_empty()); +} + +#[test] +fn batch_single_file_cancel_preserves_other_held_memory_orders() { + let mut app = app(); + let batch_id = crate::jobs_ui::begin_batch(&mut app); + let order0 = crate::jobs_ui::OpenOrder { batch: batch_id, seq: 0 }; + let order1 = crate::jobs_ui::OpenOrder { batch: batch_id, seq: 1 }; + + let p0 = app + .session + .store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { + id: 0, + name: "first.psd".into(), + source: photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0; 4])), + fingerprint: photocraft_engine::jobs::SourceFingerprint::of(&photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0; 4]))).unwrap(), + required: 1000, + soft_limit: 500, + hard_limit: 2000, + available_ram: Some(4000), + confirm_damage: true, + }) + .unwrap(); + + let p1 = app + .session + .store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { + id: 0, + name: "second.psd".into(), + source: photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0; 4])), + fingerprint: photocraft_engine::jobs::SourceFingerprint::of(&photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0; 4]))).unwrap(), + required: 1000, + soft_limit: 500, + hard_limit: 2000, + available_ram: Some(4000), + confirm_damage: true, + }) + .unwrap(); + + crate::open_prompt::arrive_memory(&mut app, p0, "first.psd".into(), None, None, Some(order0), 1000, Some(4000), false, false); + crate::open_prompt::arrive_memory(&mut app, p1, "second.psd".into(), None, None, Some(order1), 1000, Some(4000), false, false); + + // Cancel first file: + let dlg0 = app.ui.dialogs[0].id; + assert_eq!(call(&mut app, "ui.dialog.cancel", json!({"dialog": dlg0}))["ok"], true); + + // Batch must be preserved because second file is still waiting: + assert_eq!(app.jobs.batches.len(), 1, "batch preserved while second file is waiting"); + assert_eq!(app.held_memory_prompts.len(), 1); + + // Now cancel second file: + let dlg1 = app.ui.dialogs[0].id; + assert_eq!(call(&mut app, "ui.dialog.cancel", json!({"dialog": dlg1}))["ok"], true); + assert!(app.jobs.batches.is_empty(), "batch cleaned after all members cancelled"); + assert!(app.prompt_order.is_empty()); +} + +#[test] +fn profile_cancel_cancels_whole_queue_including_memory_prompts() { + let mut app = app(); + let gb = 1u64 << 30; + + let preflight_id = app + .session + .store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { + id: 0, + name: "high_mem.psd".into(), + source: photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0; 16])), + fingerprint: photocraft_engine::jobs::SourceFingerprint::of(&photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0; 16]))).unwrap(), + required: 7 * gb, + soft_limit: 4 * gb, + hard_limit: 8 * gb, + available_ram: Some(10 * gb), + confirm_damage: true, + }) + .unwrap(); + + crate::open_prompt::arrive_memory(&mut app, preflight_id, "high_mem.psd".into(), None, None, None, 7 * gb, Some(10 * gb), false, false); + + crate::open_prompt::arrive( + &mut app, + crate::open_prompt::Held { + doc: photocraft_doc::Document::new("test", photocraft_geom::Size::new(4, 4), photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::U8), + read_only: false, + damage_pending: false, + name: "profile.psd".into(), + path: None, + warnings: vec![], + bytes: None, + slot: None, + order: None, + question: Some(json!({"missing": false, "working": "sRGB", "embedded": "Adobe RGB"})), + policy_applied: false, + }, + ); + + let r = crate::open_prompt::answer(&mut app, None).unwrap(); + assert_eq!(r["cancelled"], 2, "both held open and memory prompt dropped"); + assert!(app.held_opens.is_empty()); + assert!(app.held_memory_prompts.is_empty()); + assert!(app.prompt_order.is_empty()); + assert!(app.session.take_pending_preflight(preflight_id).is_none(), "pending preflight cancelled"); +} + +#[test] +fn mixed_prompts_follow_arrival_order_fifo() { + let mut app = app(); + let gb = 1u64 << 30; + + // 1. Arrive damage prompt first + crate::open_prompt::arrive( + &mut app, + crate::open_prompt::Held { + doc: photocraft_doc::Document::new("test", photocraft_geom::Size::new(4, 4), photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::U8), + read_only: false, + damage_pending: true, + name: "first_damage.psd".into(), + path: None, + warnings: vec!["damaged data".into()], + bytes: None, + slot: None, + order: None, + question: None, + policy_applied: false, + }, + ); + + // 2. Arrive memory prompt second + let preflight_id = app + .session + .store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { + id: 0, + name: "second_mem.psd".into(), + source: photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0; 16])), + fingerprint: photocraft_engine::jobs::SourceFingerprint::of(&photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0; 16]))).unwrap(), + required: 7 * gb, + soft_limit: 4 * gb, + hard_limit: 8 * gb, + available_ram: Some(10 * gb), + confirm_damage: true, + }) + .unwrap(); + crate::open_prompt::arrive_memory(&mut app, preflight_id, "second_mem.psd".into(), None, None, None, 7 * gb, Some(10 * gb), false, false); + + // First prompt shown must be damage (since it arrived first)! + assert_eq!(app.ui.dialogs.len(), 1); + assert!(crate::open_prompt::owns_damage(&app.ui.dialogs[0].fields)); + + // Cancel damage prompt: + let dlg_id = app.ui.dialogs[0].id; + assert_eq!(call(&mut app, "ui.dialog.cancel", json!({"dialog": dlg_id}))["ok"], true); + + // Now memory prompt must be shown! + assert_eq!(app.ui.dialogs.len(), 1); + assert!(crate::open_prompt::owns_memory(&app.ui.dialogs[0].fields)); + let dlg_mem = app.ui.dialogs[0].id; + assert_eq!(call(&mut app, "ui.dialog.cancel", json!({"dialog": dlg_mem}))["ok"], true); + assert!(app.ui.dialogs.is_empty()); +} + +/// A stored preflight for the prompt tests, with a tiny in-memory source so nothing large is +/// ever held. +fn store_preflight(app: &mut PhotocraftApp, name: &str, required: u64, available: Option) -> u64 { + let bytes = std::sync::Arc::new(vec![0u8; 16]); + let source = photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::clone(&bytes)); + let fingerprint = photocraft_engine::jobs::SourceFingerprint::of(&source).unwrap(); + app.session + .store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { + id: 0, + name: name.into(), + source, + fingerprint, + required, + soft_limit: required / 2, + hard_limit: required.saturating_mul(2), + available_ram: available, + confirm_damage: true, + }) + .unwrap() +} + +/// #10897: the browser and desktop share one consent route. The web shell runs every open inline +/// (`background_jobs == false`), answers the same `MemoryPrompt`, and dispatches the same +/// `file.approveMemory` command: it is not menu-only, journaled or gated off wasm. The web's own +/// allowance and 2 GiB product cap stay in `photocraft-io`'s policy, so approval never raises +/// them. This checks the routing half on the host; the web policy half is covered by +/// `photocraft_io::memory`'s web-policy tests. +#[test] +fn memory_approval_routes_through_the_file_approve_memory_command() { + let app = app(); + assert!(!app.background_jobs, "the browser shell is always inline"); + assert!(app.session.is_enabled("file.approveMemory"), "the one-shot approval command is available on every target"); + let spec = photocraft_engine::commands::find("file.approveMemory").expect("registered"); + assert!(spec.menu.is_empty(), "it is not a menu item"); + assert!(!spec.journal, "a one-shot permission is never journaled or replayed"); +} + +/// #10897: on the web the same prompt offers consent, and `file.approveMemory` may authorize an +/// estimate above the 1 GiB automatic allowance only within the 2 GiB product cap: a 1.5 GiB +/// estimate is approved and opens, a 3 GiB estimate is refused before decoding. The fixed mock +/// snapshot is ignored on wasm (the web policy does not read one), so the charge alone sets the +/// window. This target is compile-checked, not executed, by the current CI (`cargo xtask wasm` +/// checks the crates without test targets); the same web policy is exercised on native by +/// `photocraft_io::memory`'s web-policy tests. +#[cfg(target_arch = "wasm32")] +#[test] +fn web_memory_prompt_offers_consent_within_the_two_gib_product_cap() { + let gb = 1u64 << 30; + let psd = recovery_psd::make_psd(false); + let mut approved = app(); + photocraft_io::psd_budget::with_test_estimate_charge(3 * gb / 2, || { + approved.open_bytes_from("web.psd", &psd, Some("web.psd")).unwrap(); + assert_eq!(approved.held_memory_prompts.len(), 1, "1.5 GiB is above the web's 1 GiB automatic allowance"); + let fields = &approved.ui.dialogs[0].fields; + assert_eq!(fields["available"], json!(null)); + assert_eq!(fields["capacityUnknown"], json!(true), "the browser cannot measure the tab's capacity"); + let dlg = approved.ui.dialogs[0].id; + assert_eq!(call(&mut approved, "ui.dialog.confirm", json!({"dialog": dlg}))["ok"], true); + assert_eq!(approved.session.documents().len(), 1, "consent opens an estimate within the product cap"); + }); + let mut refused = app(); + photocraft_io::psd_budget::with_test_estimate_charge(3 * gb, || { + assert!(refused.open_bytes_from("too-big.psd", &psd, Some("too-big.psd")).is_err(), "consent cannot raise the 2 GiB product cap"); + assert!(refused.ui.dialogs.is_empty()); + assert!(refused.session.documents().is_empty()); + }); +} + +/// #10897: the prompt shows an unmeasured capacity honestly (no invented number) and adds the +/// above-8-GiB warning, both from the engine's typed flags, so the browser and desktop consent +/// text matches what was actually measured. +#[test] +fn memory_prompt_states_unknown_capacity_and_the_eight_gib_warning() { + let gb = 1u64 << 30; + let mut app = app(); + let id = store_preflight(&mut app, "unknown.psd", 9 * gb, None); + let tab = crate::jobs_ui::OpenTab { + job: photocraft_engine::jobs::JobId(1), + name: "unknown.psd".into(), + path: Some("/pics/unknown.psd".into()), + slot: None, + order: None, + }; + crate::jobs_ui::finish_open_tab( + &mut app, + &tab, + &json!({"pendingPreflight": id, "estimated": 9 * gb, "availableRam": null, "capacityUnknown": true, "uncertainCapacityWarning": true}), + ) + .unwrap(); + assert_eq!(app.ui.dialogs.len(), 1); + let fields = &app.ui.dialogs[0].fields; + assert!(crate::open_prompt::owns_memory(fields)); + assert_eq!(fields["available"], json!(null), "no number is invented for an unmeasured capacity"); + assert_eq!(fields["capacityUnknown"], json!(true)); + assert_eq!(fields["uncertainCapacityWarning"], json!(true)); + let message = fields["message"].as_str().unwrap(); + assert!(message.contains("could not be measured"), "{message}"); + assert!(message.contains("8 GiB") && message.contains("may run out of memory"), "{message}"); + assert!(!message.contains("available)"), "the unknown-capacity message claims no available figure: {message}"); + let dialog = app.ui.dialogs[0].id; + assert_eq!(call(&mut app, "ui.dialog.cancel", json!({"dialog": dialog}))["ok"], true); + + // A measured capacity shows the number and drops the uncertainty warning. + let id = store_preflight(&mut app, "known.psd", 3 * gb, Some(5 * gb)); + let tab = crate::jobs_ui::OpenTab { job: photocraft_engine::jobs::JobId(2), name: "known.psd".into(), path: None, slot: None, order: None }; + crate::jobs_ui::finish_open_tab( + &mut app, + &tab, + &json!({"pendingPreflight": id, "estimated": 3 * gb, "availableRam": 5 * gb, "capacityUnknown": false, "uncertainCapacityWarning": false}), + ) + .unwrap(); + let fields = &app.ui.dialogs[0].fields; + assert_eq!(fields["available"], json!(5 * gb)); + assert_eq!(fields["capacityUnknown"], json!(false)); + let message = fields["message"].as_str().unwrap(); + assert!(message.contains("5.0 GiB available"), "{message}"); + assert!(!message.contains("could not be measured") && !message.contains("may run out of memory"), "{message}"); + let dialog = app.ui.dialogs[0].id; + assert_eq!(call(&mut app, "ui.dialog.cancel", json!({"dialog": dialog}))["ok"], true); + assert!(app.ui.dialogs.is_empty()); +} + +/// #10897: reopening an ordinary file whose high-memory prompt is already waiting shows that +/// prompt instead of queueing a second one and a second open; a template still opens again as +/// another Untitled, like one that is still loading. +#[test] +fn reopening_a_file_whose_memory_prompt_waits_does_not_queue_a_duplicate() { + let gb = 1u64 << 30; + let mut app = app(); + let id = store_preflight(&mut app, "slow.psd", 3 * gb, Some(5 * gb)); + crate::open_prompt::arrive_memory(&mut app, id, "slow.psd".into(), Some("/pics/slow.psd".into()), None, None, 3 * gb, Some(5 * gb), false, false); + assert_eq!(app.held_memory_prompts.len(), 1); + assert_eq!(app.ui.dialogs.len(), 1); + assert!(app.show_if_open("/pics/slow.psd"), "the waiting prompt is shown"); + assert_eq!(app.held_memory_prompts.len(), 1, "no second prompt for the same file"); + assert_eq!(app.ui.dialogs.len(), 1); + + // The template exception: a repeat open still creates another Untitled. + let id = store_preflight(&mut app, "card.psdt", 3 * gb, Some(5 * gb)); + crate::open_prompt::arrive_memory(&mut app, id, "card.psdt".into(), Some("/pics/card.psdt".into()), None, None, 3 * gb, Some(5 * gb), false, false); + assert_eq!(app.held_memory_prompts.len(), 2); + assert!(!app.show_if_open("/pics/card.psdt"), "a template reopens instead of reusing the waiting prompt"); + assert_eq!(app.held_memory_prompts.len(), 2); +} + +/// A tiny PNG so a set can hold one PSD that needs approval and one flat file that opens at once. +#[cfg(not(target_arch = "wasm32"))] +fn png_file() -> Vec { + let img = photocraft_codecs::Image::from_u8(2, 2, photocraft_codecs::ChannelLayout::Rgb, vec![10; 2 * 2 * 3]).unwrap(); + photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap() +} + +/// #10897: a set opened inline keeps the charged PSD's place in the set through its memory +/// prompt: the prompt carries the batch order and the answered file lands before the later member. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn inline_set_keeps_the_memory_prompted_file_in_batch_order() { + if cfg!(target_pointer_width = "32") { + return; // the 3 GiB charge would exceed a 32-bit process cap + } + let gb = 1u64 << 30; + let dir = tempfile::tempdir().unwrap(); + let psd = dir.path().join("a_high.psd"); + let png = dir.path().join("b_flat.png"); + std::fs::write(&psd, recovery_psd::make_psd(false)).unwrap(); + std::fs::write(&png, png_file()).unwrap(); + let paths = vec![psd.to_string_lossy().into_owned(), png.to_string_lossy().into_owned()]; + let mut app = app(); + let snap = photocraft_io::memory::MemorySnapshot { available_ram: Some(5 * gb), swap_free: None, commit_headroom: None }; + photocraft_io::psd_budget::with_test_estimate_charge(3 * gb, || { + photocraft_io::memory::with_mock_memory(snap, || { + assert_eq!(app.open_paths(&paths), 2); + assert_eq!(app.held_memory_prompts.len(), 1, "the charged PSD waits for approval"); + assert_eq!(app.held_memory_prompts.front().unwrap().order.map(|o| o.seq), Some(0), "the set order travels with the prompt"); + // The flat file waits behind the prompt, keeping its own place in the set. + assert_eq!(app.held_opens.len(), 1); + assert_eq!(app.held_opens.front().unwrap().order.map(|o| o.seq), Some(1)); + let dlg = app.ui.dialogs[0].id; + assert_eq!(call(&mut app, "ui.dialog.confirm", json!({"dialog": dlg}))["ok"], true); + let names: Vec<_> = app.session.documents().iter().map(|d| d.doc.name.clone()).collect(); + assert_eq!(names, ["a_high.psd", "b_flat.png"]); + assert!(app.held_memory_prompts.is_empty() && app.held_opens.is_empty()); + assert!(app.jobs.batches.is_empty(), "the set is forgotten once every member opened"); + assert!(app.prompt_order.is_empty()); + }); + }); +} + +/// A real tiny layered TIFF: a small two-layer RGB document exported with Photoshop layer data. +/// The fixture is the actual file the UI opens, not a fabricated preflight. +#[cfg(not(target_arch = "wasm32"))] +fn exported_layered_tiff(w: u32, h: u32) -> Vec { + use photocraft_doc::{Document, Layer, LayerContent}; + use photocraft_raster::Surface; + + let mut doc = Document::new("layers.tif", photocraft_geom::Size::new(w, h), photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8); + let fmt = doc.pixel_format(); + let bytes = (w as usize * h as usize * fmt.bytes_per_pixel()).max(1); + for name in ["bottom", "top"] { + let mut s = Surface::new(fmt); + s.write_interleaved(photocraft_geom::Rect::new(0, 0, w as i32, h as i32), &vec![96u8; bytes]); + doc.layers.push(Layer::new(name, LayerContent::Raster(s))); + } + photocraft_io::export(&doc, "layers.tif", &photocraft_io::ExportOptions { tiff_layers: true, ..Default::default() }).expect("export a layered TIFF").bytes +} + +/// #10897: a layered TIFF opened inline reaches the same high-memory prompt a PSD does. Only the +/// typed IO path carries `PsdApprovalRequired`; the shell's plain import service turns it into a +/// terminal string, so without that routing this open fails instead of prompting. The real +/// two-layer fixture plus the scoped estimate charge land in the confirmation band under a fixed +/// 5 GiB, and the prompt arrives before any composite pixel is decoded. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn inline_layered_tiff_prompts_before_decoding_and_opens_or_declines() { + if cfg!(target_pointer_width = "32") { + return; // the 3 GiB charge would exceed a 32-bit process cap + } + let gb = 1u64 << 30; + let bytes = exported_layered_tiff(8, 6); + let path = "/pics/layered.tif"; + let mut app = app(); + assert!(!app.background_jobs, "the inline path the web shell uses"); + let snap = photocraft_io::memory::MemorySnapshot { available_ram: Some(5 * gb), swap_free: None, commit_headroom: None }; + photocraft_io::psd_budget::with_test_estimate_charge(3 * gb, || { + photocraft_io::memory::with_mock_memory(snap, || { + let order = crate::jobs_ui::OpenOrder { batch: crate::jobs_ui::begin_batch(&mut app), seq: 0 }; + app.open_bytes_placed("layered.tif", &bytes, Some(path), None, Some(order)).unwrap(); + // The prompt comes first: nothing is decoded, no tab is opened, and the engine holds + // the source for the approval. The set order travels with the prompt. + assert!(app.session.documents().is_empty(), "the layered TIFF waits for approval instead of opening"); + assert!(app.jobs.opens.is_empty(), "inline: no background tab"); + assert_eq!(app.held_memory_prompts.len(), 1); + assert_eq!(app.held_memory_prompts.front().unwrap().order, Some(order)); + assert_eq!(app.ui.dialogs.len(), 1); + let fields = &app.ui.dialogs[0].fields; + assert!(crate::open_prompt::owns_memory(fields)); + assert!(fields["estimated"].as_u64().unwrap() > 3 * gb, "the charged estimate is shown: {fields:?}"); + assert_eq!(fields["available"], json!(5 * gb)); + assert!(app.session.pending_preflight_bytes().unwrap() > 0, "the engine preflight holds the source"); + + // Accepting runs the typed TIFF import with the one-shot approval: both layers, in + // their order, keep the document's path, and the preflight is released. + let dlg = app.ui.dialogs[0].id; + let res = call(&mut app, "ui.dialog.confirm", json!({"dialog": dlg})); + assert_eq!(res["ok"], true, "{res}"); + assert_eq!(app.session.documents().len(), 1, "the approved TIFF opens"); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.name, "layered.tif"); + assert_eq!(st.path.as_deref(), Some(path), "the approved open keeps its path"); + let names: Vec<_> = st.doc.layers.iter().map(|l| l.name.clone()).collect(); + assert_eq!(names, ["bottom", "top"], "both layers open in their order"); + assert!(app.ui.dialogs.is_empty(), "a TIFF has no damage prompt"); + assert!(app.held_memory_prompts.is_empty()); + assert!(app.jobs.batches.is_empty(), "the set is forgotten once its prompted file opened"); + assert_eq!(app.session.pending_preflight_bytes().unwrap(), 0, "accepting clears the engine preflight"); + + // Declining opens nothing and releases the engine preflight too. + app.open_bytes_from("declined.tif", &bytes, Some("/pics/declined.tif")).unwrap(); + assert_eq!(app.held_memory_prompts.len(), 1); + assert!(app.session.pending_preflight_bytes().unwrap() > 0); + let dlg = app.ui.dialogs[0].id; + assert_eq!(call(&mut app, "ui.dialog.cancel", json!({"dialog": dlg}))["ok"], true); + assert!(app.held_memory_prompts.is_empty() && app.ui.dialogs.is_empty()); + assert_eq!(app.session.documents().len(), 1, "declining opens nothing"); + assert_eq!(app.session.pending_preflight_bytes().unwrap(), 0, "declining clears the engine preflight"); + }); + }); +} + +/// A TIFF whose Photoshop layer tag cannot be read still opens flattened through the typed path, +/// with its warning: routing TIFF magic to typed IO must not turn a malformed tag into a refusal. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn inline_tiff_with_a_malformed_layer_tag_opens_flattened() { + use photocraft_codecs::{ChannelLayout, EncodeOptions, Format, Image, SampleType}; + + let mut img = Image::from_raw(4, 3, ChannelLayout::Rgb, SampleType::U8, vec![40; 4 * 3 * 3]).unwrap(); + img.meta.photoshop_layers = Some(b"not Photoshop image source data".to_vec()); + let bytes = photocraft_codecs::encode(&img, Format::Tiff, &EncodeOptions::default()).unwrap(); + let mut app = app(); + let snap = photocraft_io::memory::MemorySnapshot { available_ram: Some(16 << 30), swap_free: None, commit_headroom: None }; + photocraft_io::memory::with_mock_memory(snap, || { + let warnings = app.open_bytes("bogus.tif", &bytes).unwrap(); + assert_eq!(app.session.documents().len(), 1, "the composite still opens"); + assert_eq!(app.session.active().unwrap().doc.layers.len(), 1, "a malformed tag opens one flat layer"); + assert!(warnings.iter().any(|w| w.contains("opened flattened")), "{warnings:?}"); + assert!(app.ui.dialogs.is_empty()); + }); +} + +/// #10897: a file dropped on a tab slot keeps that slot through an inline memory prompt, even +/// though the open completes later (before, it appended to the end of the tab strip). +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn inline_drop_slot_survives_the_memory_prompt() { + if cfg!(target_pointer_width = "32") { + return; // the 3 GiB charge would exceed a 32-bit process cap + } + let gb = 1u64 << 30; + let mut app = app(); + for name in ["first.psd", "second.psd"] { + app.open_bytes(name, &recovery_psd::make_psd(false)).unwrap(); + } + assert_eq!(app.session.documents().len(), 2); + let snap = photocraft_io::memory::MemorySnapshot { available_ram: Some(5 * gb), swap_free: None, commit_headroom: None }; + photocraft_io::psd_budget::with_test_estimate_charge(3 * gb, || { + photocraft_io::memory::with_mock_memory(snap, || { + app.open_bytes_placed("dropped.psd", &recovery_psd::make_psd(false), None, Some(0), None).unwrap(); + assert_eq!(app.held_memory_prompts.len(), 1); + assert_eq!(app.held_memory_prompts.front().unwrap().slot, Some(0), "the drop slot travels with the prompt"); + let dlg = app.ui.dialogs[0].id; + assert_eq!(call(&mut app, "ui.dialog.confirm", json!({"dialog": dlg}))["ok"], true); + let names: Vec<_> = app.session.documents().iter().map(|d| d.doc.name.clone()).collect(); + assert_eq!(names, ["dropped.psd", "first.psd", "second.psd"], "the approved drop keeps its tab slot"); + }); + }); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 609363ca9d..e74938dc2f 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -443,8 +443,8 @@ stdio, and a value that is not a port is a usage error naming the variable. Impl | `jobs.list` / `jobs.cancel` | `{}` / `{job?}`: background jobs; cancel one or all. Every request (and MCP tool call) first applies the jobs that finished, so `doc.save`, `doc.inspect`, `doc.render` and `session.list` include a finished job's result without polling `jobs.list` first | | `engine.commands` | `{filter?}`: registry with params docs and enablement (`enabled`, `disabledReason`, `needsDocument`); `result` is a bare array of command objects ([Command list replies](#command-list-replies)) | | `session.list` | open documents and the active index | -| `doc.open` / `doc.new` | `{path}` / `file.new` params | -| `doc.place` | `{path, scale? (percent), fit? (true), center? ([x, y]), index?}`: places a file as a Smart Object layer above the active one and returns `{layer, scale, bounds}`. `path` resolves beneath the read root, so this is the capability-scoped `file.placeEmbedded` — that command itself still refuses an ambient path | +| `doc.open` / `doc.new` | `{path, approveHighMemory? (false)}` / `file.new` params (`approveHighMemory` is the same one-shot PSD/PSB consent as the `file.openAs` command; see [development.md](development.md) for the structured refusal fields) | +| `doc.place` | `{path, scale? (percent), fit? (true), center? ([x, y]), approveHighMemory? (false), index?}`: places a file as a Smart Object layer above the active one and returns `{layer, scale, bounds}`. `path` resolves beneath the read root, so this is the capability-scoped `file.placeEmbedded` — that command itself still refuses an ambient path. `approveHighMemory` is refused unless it is a boolean | | `doc.replaceSmartObject` | `{path, layer? (id or name; default the active layer), index?}` → the command's `{layer, instances}`: replaces a Smart Object's contents (one history step, transform and filters kept). `path` resolves beneath the read root, so this is the capability-scoped `layer.smartObjects.replaceContents`, which itself still refuses an ambient path (#8061) | | `doc.exportLayers` | `{dir, format? (png), prefix?, visibleOnly? (true), quality?, index?}` → `{files, skipped}` (plus `count` for workspace exports): one file per exported top-level layer, named like `file.export.layersToFiles` names them. `count` is present only for workspace exports and counts written files only. `skipped` is always an array (empty when nothing is omitted), in top-to-bottom order, of `{layer, name, reason}`: the session layer id, original unsanitized name, and `"hidden by visibleOnly"` or `"adjustment layer has no pixels of its own"`. Visibility takes precedence for hidden adjustments; `visibleOnly:false` exports hidden non-adjustment layers. Groups export merged; their children are not separate exports or skips. Existing filenames/numbering are unchanged. `dir` resolves beneath the write root, so the ambient command stays refused. The bytes come from the command's own core, so both paths write the same files; the write capability refuses to overwrite an existing file. Encode/write failures are errors, not skips | | `doc.exportDataSets` | `{dir, format? (png), dataSets? (all), naming? ("{name}\|{index}\|{document}"), index?}` → `{files, count}`: the capability-scoped `file.export.dataSetsAsFiles`. The batch is planned first and colliding names are refused before any file is written, as in the command | diff --git a/docs/development.md b/docs/development.md index 49093fa23a..25578943fc 100644 --- a/docs/development.md +++ b/docs/development.md @@ -678,12 +678,122 @@ before merged-image validation or decoding. The conservative estimate sums retai storage (including padding and negative offsets) and the largest decode/conversion workspace. It does not credit uniform-tile sharing or pruning, so some files that could fit after decoding are refused. Valid off-canvas pixels are preserved; oversized layers are rejected rather than -clipped. Defaults are 2 GiB on native targets and 1 GiB on wasm. Applications can lower the -allowance with `ImportOptions::psd_max_pixel_bytes`; values above the default are capped. -The source-only convenience API uses the default; `import_file_for_open_with` honours options. +clipped. -An over-budget ordinary or interactive import returns `IoError::PsdImportBudget` with the -estimated and allowed byte counts; damaged-file recovery never bypasses that error. The legacy +Native desktop platforms use an adaptive memory policy evaluated against currently available +physical RAM (excluding swap) and, where measurable, system commit headroom: +- **Hard budget (H)** for known RAM: $\min(75\% \text{ RAM}, \text{RAM} - 1 \text{ GiB}, \text{commit headroom} - 512 \text{ MiB}, \text{aggregate address-space cap})$. +- **Soft budget (S)**: $\min(50\% \text{ RAM}, 8 \text{ GiB}, H)$. +- Files requiring $\le S$ are admitted automatically. +- Files requiring $S < E \le H$ prompt for explicit one-shot user confirmation ("Open anyway") in the UI. Headless callers default to no interactive dialog and require explicit per-invocation opt-in: + - Engine commands: `file.openAs` and `file.placeEmbedded` take `approveHighMemory: bool` (default `false`); `file.approveMemory` takes `{"id": u64, "approve": bool = true}`. + - Headless RPC / control protocol: `doc.open` and `doc.place` take `approveHighMemory: bool`. + - MCP: `doc_open` and `doc_place` take `approve_high_memory: bool` (default `false`; a wrong type is refused, not coerced). + - CLI: `convert`, `info`, `run`, and `batch` take `--approve-high-memory`. + - Explicit approval authorizes imports within $(S, H]$ but never bypasses the hard memory budget $H$. +- Files requiring $> H$ are refused and cannot be overridden. +- When available RAM is unknown (an unsupported platform or a failed provider), native + automatic admission is 2 GiB, not 8 GiB: + $S = \min(2 \text{ GiB}, H)$, where $H$ is the aggregate address-space cap + (`native_platform_cap`), reduced by known commit headroom. Estimates above $S$ need the same + explicit, per-invocation approval as known-memory estimates above $S$, and approval is possible + up to $H$. Estimates above 8 GiB remain approvable; `MemoryBudget::warning_threshold` and + `MemoryBudget::requires_uncertainty_warning` let callers show the uncertain-capacity warning. + 8 GiB is a warning threshold, not a hard ceiling, because the process may still run out of + memory. +- These budgets apply to an import's **aggregate peak estimate**, not to one allocation: a peak + may sum many layer, mask, merged and workspace buffers. Each individual buffer must still fit + the target's layout limit (`isize::MAX`) and the decoder's own per-buffer allowance + (`photocraft-psd`'s `MAX_DECODED_BYTES`, `photocraft-codecs`' `Limits::max_alloc`), which is + enforced by fallible allocation or an explicit cap where that buffer is created. A 64-bit + native process has no measurable aggregate address-space cap, so admission relies on explicit + approval plus those per-buffer checks; 32-bit native uses a 2 GiB project cap + (`NATIVE_32BIT_PEAK_CAP`), a product choice below its 4 GiB address space. +- WebAssembly (wasm32): automatic admission is 1 GiB; estimates above it use the same explicit + approval. The architectural linear-memory limit is 4 GiB (65,536 × 64 KiB pages), shared with + the runtime, stack, allocator, resident document and history, and one Rust allocation cannot + exceed `isize::MAX` (2 GiB − 1). Admission uses a **project cap of 2 GiB** + (`WASM_MAX_PEAK_BUDGET`) for the aggregate peak, chosen below the address space to leave room + for the rest; it is not an architectural maximum, browsers often allow less, and allocation can + still fail. +- macOS reads a conservative reclaimable-memory measurement through `sysinfo`'s safe API: + $\min(\text{total} - \text{used}, \text{available})$, never below `free`. `total` is + `HW_MEMSIZE`; `used` is `internal_page_count - purgeable_count + wire_count + + compressor_page_count`; `available` is sysinfo's `available_memory` (`active + inactive + + free_count`, where XNU counts speculative pages inside `free_count`); `free` is its + `free_memory` (`free_count - speculative`). XNU documents *available memory* (active + + inactive + free + speculative) as everything not wired, compressed or stolen, which counts + anonymous working sets, while $\text{total} - \text{used}$ is the pool that can be handed out + without evicting one: free + file-backed + purgeable pages, close to the fully-reclaimable + pool jetsam monitors. Taking the smaller of the two keeps a counter disagreement + conservative, and `free` is a measured floor because those pages are allocatable by + definition. Swap is excluded. A genuine zero reading stays zero; unknown memory is reported + only when the provider query demonstrably failed (zero installed size or zero used memory, + which a live host cannot report). Linux reads `MemAvailable` from `/proc/meminfo` and + constrains it by the memory cgroup: v2 from the unified hierarchy's + `memory.max`/`memory.current`/`memory.swap.max`, using `cgroup.controllers` and + `cgroup.subtree_control` to distinguish a genuinely disabled controller (and the interface-file + exemption of the hierarchy root) from a view that is missing files it should expose; v1 from the + `memory` controller mount found in `/proc/self/mountinfo` (including dedicated mounts, bind + mounts and non-root process paths), applying every visible ancestor limit. When several mounts + match, the widest view (the shortest cgroup mount root) is used so a deep bind mount cannot hide + a constrained ancestor. Inactive page cache counts as reclaimable (`inactive_file` on v2, + `total_inactive_file` on v1). A v1 `memsw` limit also caps RAM; per ancestor its swap allowance + is `memsw limit - memory limit - swap already used`, and those allowances are combined + separately from RAM headroom. A memory cgroup whose mount, path, membership, limit or usage + cannot be read, or whose membership file is malformed or empty, fails closed (available memory + is treated as zero) rather than falling back to unrestricted host RAM. +- Applications can lower the admission threshold with `ImportOptions::psd_max_pixel_bytes`; explicit caller limits may lower admission, never bypass the hard boundary. +- Concurrent PSD decodes are serialized using a process-wide, cancellation-aware admission gate, with nested decodes sharing the enclosing allowance. +- A pending high-memory approval is bound to one source and one estimate. The engine keeps at + most 32 pending preflights and, separately, at most 1 GiB of source bytes + (`Session::MAX_PENDING_PREFLIGHT_BYTES`): only an in-memory source holds data (a path streams + from its file once opened), and an `Arc` shared by several preflights is counted once. The + retention cap is not a pixel budget or an admission limit; it keeps an unanswered prompt from + pinning unbounded memory, and is deliberately below the 2 GiB web hard cap. The charge is + computed from the queue, so answering, cancelling, refusing or clearing releases it. +- The approval verifies the file it decodes, not the path it was told about: the importer opens + the path once, reads `photocraft_io::FileIdentity` from that handle (Unix: device, inode, + length, mtime and ctime with nanoseconds), refuses with `SourceChanged` when it is not the + approved file, and re-reads the identity from the same handle when the memory preflight pauses + for approval. Windows has no stable file-index API in `std`, so its identity is the length and + modification time (a different file with both preserved is not distinguished there). The + `file.approveMemory` permission is one-shot and is not journaled or recorded in an action. A + refusal above the hard ceiling is the typed `PsdHardBudget` error (name, required, limit), not + a string, and it releases the queued source. +- A layered TIFF (Photoshop layer data in tags 37724/34377) is admitted by the same policy + before its composite is decoded. The page's tags are read into the PSD model first, without + pixels; then that model's layer/workspace estimate, the decoded composite and its + extra-sample planes, the planar big-endian merged copy, a 16-bit-float conversion's extra + copies, the decoder's scratch buffers (one strip or tile per worker, see + `codecs::TiffBands::decode_scratch_bytes`) and the decoder's copy of the tags are charged + together, with the caller limit and approval flags from `ImportOptions`. A zero caller limit + means the adaptive budget, as for a PSD. A TIFF whose layer tag cannot be read still opens + flattened with the same warning as before, and that whole-image decode and conversion are + bounded the same way. A layered TIFF opened inside another import spends the enclosing + attempt's remaining allowance instead of resolving a fresh budget, and its admission guard is + held across the composite decode and the PSD conversion, so a top-level import is charged + once and a same-file continuation is never charged again. +- Before waiting for the decode gate, an import checks admission; it checks again with a fresh + measurement once admitted, and only then decodes. This holds for the ordinary PSD and layered + TIFF paths and for the standalone legacy `psd_to_document` conversion, so an ineligible file + never waits behind an active decode. A nested import checks cancellation before consuming its + parent's remaining allowance and takes the reentrant admission guard first, so a cancelled or + refused nested import never spends the parent's budget. Hiding a large estimate behind a + destroyed composite or a malformed layer tag does not bypass the obvious bound: the + codecs' per-buffer limit (`Limits::max_alloc`) and the flat band check still apply to a page + opened without Photoshop layers. + +Headless RPC and MCP report approval-required memory errors with byte counts (`required`, +`softLimit`, `hardLimit`, and `availableRam` when known). A hard-budget refusal reports only +`required` and `hardLimit`: no approval can raise that ceiling, so there is no soft limit or +capacity to act on. This holds for `doc.open` and `doc.place` and for the MCP `doc_open` and +`doc_place` tools, including a refusal from `file.openAs`/`file.placeEmbedded` reached through a +command. GUI automation imports currently cross a service boundary that returns string errors. + +An import exceeding the hard budget returns `IoError::PsdImportBudget` with the estimated +and allowed byte counts; imports requiring confirmation return `IoError::PsdApprovalRequired` +when unapproved. Damaged-file recovery never bypasses these memory guards. The legacy `psd_to_document` conversion APIs cannot return an error, so they return an empty document and an explicit warning on preflight refusal. Layer and mask pixel allocation failures also fail ordinary imports instead of opening partial content. @@ -705,6 +815,12 @@ contents, generated vector caches, and text preparation are outside it and retai existing limits. Joining these paths to a shared budget and streaming ZIP inflation are follow-up work. An accepted estimate does not guarantee allocation success on a memory-constrained host. +The legacy `memory::available()` helper used by flat TIFF conversion keeps its established +meaning: on Linux it reports `MemAvailable + SwapFree`, now bounded by cgroup v2 swap limits or +v1 `memsw`, and it is `None` on Windows and macOS. The adaptive budget is the only consumer of +the macOS physical-memory provider. Banded flat TIFF pages keep that helper; a layered TIFF's +whole-image work is admitted by the adaptive policy above. + ## Test corpora Real files are our best oracles, but they are large binaries, so they never go into this diff --git a/docs/scratch-disks.md b/docs/scratch-disks.md index bcc3103bce..acc784d242 100644 --- a/docs/scratch-disks.md +++ b/docs/scratch-disks.md @@ -59,3 +59,12 @@ read from outside the edited document (for example a clipboard copy) is not dete Scratch storage alone does not make every format, filter or renderer streamable. See [EXR streaming](streaming-io.md) for the block-by-block EXR import. Viewport rendering is a separate change built on these guards and memory reservations. + +Available RAM is measured in one place, `photocraft_raster::memory::system` (cgroup v1/v2 +limits on Linux, reclaimable pages on macOS, the commit limit on Windows; swap never counts as +RAM, and an unreadable container limit fails closed). The residency budget and the PSD/PSB and +layered-TIFF import admission (`photocraft_io::memory`) both read it. While spilling is on and +not paused, import admission counts the tile pixels of a file against RAM plus the scratch room +(`spill::scratch_capacity`: the free space above the reserve, within the Scratch Size Limit); +decode buffers, conversion copies and merged planes still need RAM. With spilling off or +paused, and on the web, the RAM-only limits apply unchanged.