From 822e72d8567d034a3c7aa88e4acf98a2abc94fc9 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sat, 31 Oct 2026 18:53:45 -0700 Subject: [PATCH] Guard named Batch playback against recursion and budget bypass --- crates/engine/src/cmd/actions_cmds.rs | 5 +- crates/engine/src/cmd/file_cmds/batch_run.rs | 32 ++-- crates/engine/src/cmd/file_cmds/tests.rs | 169 +++++++++++++++++++ 3 files changed, 195 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/actions_cmds.rs b/crates/engine/src/cmd/actions_cmds.rs index 8e8d532d5b..9963ea8b6b 100644 --- a/crates/engine/src/cmd/actions_cmds.rs +++ b/crates/engine/src/cmd/actions_cmds.rs @@ -493,9 +493,12 @@ pub fn restore_recording(s: &mut Session, idx: usize, action: &str, from: usize) s.journal.push(("actions.play".into(), params)); } -/// Nested playback returns a structured failure even though the command itself succeeded. +/// Nested playback and Batch return structured failures even though the command succeeded. /// Promote it to the caller's failed step so no later parent steps run after a child fails. pub fn nested_failure(id: &str, value: &Value) -> Option { + if id == "file.automate.batch" { + return value.get("errors")?.as_array()?.first()?.get("error")?.as_str().map(str::to_string); + } (id == "actions.play" || id == "actions.conditional").then(|| value.get("failed")).flatten().map(|failure| { format!( "action `{}` step {} failed: {}", diff --git a/crates/engine/src/cmd/file_cmds/batch_run.rs b/crates/engine/src/cmd/file_cmds/batch_run.rs index 45822ab441..02e20bba87 100644 --- a/crates/engine/src/cmd/file_cmds/batch_run.rs +++ b/crates/engine/src/cmd/file_cmds/batch_run.rs @@ -247,9 +247,12 @@ pub(crate) fn batch_keeps_step(id: &str) -> bool { /// Run explicit steps or a saved action on each input using the requested output settings. pub(super) fn batch(s: &mut Session, p: &Value) -> Result { let cmd = "file.automate.batch"; - let mut steps = match p.get("steps").or_else(|| p.get("action").filter(|v| v.is_array())) { - Some(steps) => parse_steps(steps)?, - None => crate::automate_cmds::named_action_steps(s, p, cmd)?, + let (mut steps, action) = match p.get("steps").or_else(|| p.get("action").filter(|v| v.is_array())) { + Some(steps) => (parse_steps(steps)?, None), + None => { + let (action, _) = crate::actions_cmds::playback_plan(s, &json!({"action": p.get("action")}))?; + (action.enabled_steps().map(|(_, step)| step.clone()).collect(), Some(action.name)) + } }; // Each result goes to the destination folder, which overrides the action's recorded Save / // Save As steps: they only mark the result. @@ -276,23 +279,32 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { }; // A batch inside a played action charges its inputs × steps (at least one each: an input is read, // decoded and saved even with no steps) to the playback tree it is in and - // hands the count on, so a batch of batches can't multiply past the limit. A top-level batch - // is not limited by it. + // hands the count on, so a batch of batches can't multiply past the limit. A named action + // starts a playback tree too; top-level explicit steps retain their existing behavior. let mut playback_steps = 0; - if s.actions.playing > 0 { - playback_steps = s.actions.playback_steps.saturating_add((steps.len().max(1) as u64).saturating_mul(inputs.len() as u64)); + if s.actions.playing > 0 || action.is_some() { + let spent = if s.actions.playing > 0 { s.actions.playback_steps } else { 0 }; + playback_steps = spent.saturating_add((steps.len().max(1) as u64).saturating_mul(inputs.len() as u64)); if playback_steps > crate::actions_cmds::MAX_PLAYBACK_STEPS { - return Err(EngineError::BadParams { cmd: cmd.into(), msg: "this batch would exceed the playback step limit of the action that runs it".into() }); + return Err(EngineError::BadParams { cmd: cmd.into(), msg: "this batch would exceed the action playback step limit".into() }); + } + if s.actions.playing > 0 { + s.actions.playback_steps = playback_steps; } - s.actions.playback_steps = playback_steps; } - let actions = crate::actions_cmds::ActionState { + let mut actions = crate::actions_cmds::ActionState { list, playing: s.actions.playing, playback_stack: s.actions.playback_stack.clone(), playback_steps, ..Default::default() }; + // Keep the selected identity in scratch sessions, so nested Batch and Play calls use + // the same cycle/depth guards without changing how the caller records this Batch command. + if let Some(name) = action { + actions.playing = actions.playing.saturating_add(1); + actions.playback_stack.push(name); + } let names = batch_naming::plan(&inputs, &output, &format, p)?; let save = SaveOpts::from_params(s, p, cmd)?; let authorize = s.authorize; diff --git a/crates/engine/src/cmd/file_cmds/tests.rs b/crates/engine/src/cmd/file_cmds/tests.rs index d93c15fd82..e496d90dbf 100644 --- a/crates/engine/src/cmd/file_cmds/tests.rs +++ b/crates/engine/src/cmd/file_cmds/tests.rs @@ -1257,6 +1257,175 @@ fn load_files_into_stack_and_image_processor_and_batch() { assert!(s.execute("file.automate.batch", json!({"steps": [["no.such.command", {}]], "input": input, "output": out})).is_err()); } +#[test] +fn named_batch_cycles_stop_before_the_test_ceiling() { + use std::sync::atomic::{AtomicUsize, Ordering}; + static CALLS: AtomicUsize = AtomicUsize::new(0); + fn bounded(id: &str, _: &Value) -> Result<()> { + if id == "file.automate.batch" && CALLS.fetch_add(1, Ordering::SeqCst) >= 4 { + return Err(EngineError::Other("test recursion ceiling".into())); + } + Ok(()) + } + // Play checks authorization both before dispatch and at command execution. + for (route, calls) in [("self", 2), ("mutual", 3), ("play-child", 3), ("play-parent", 2)] { + let dir = tmp(&format!("named-batch-recursion-{route}")); + let input = png(&dir, "red.png", 8, 8, "#ff0000"); + let output = join(&dir, "out"); + let params = json!({"action": "A", "input": [input], "output": output, "format": "png"}); + let mut child = params.clone(); + child["action"] = json!(if route == "self" || route == "play-parent" { "A" } else { "B" }); + let first = if route == "play-child" { ("actions.play".into(), json!({"action": "B"})) } else { ("file.automate.batch".into(), child) }; + let mut s = Session::new(); + s.actions.list = vec![ + crate::actions_cmds::Action::new("A", vec![first]), + crate::actions_cmds::Action::new("B", vec![("file.automate.batch".into(), params.clone())]), + ]; + s.authorize = Some(bounded); + CALLS.store(0, Ordering::SeqCst); + let result = if route == "play-parent" { s.execute("actions.play", json!({"action": "A"})) } else { s.execute("file.automate.batch", params) }.unwrap(); + assert_eq!(CALLS.load(Ordering::SeqCst), calls, "{route}: the test ceiling must not be needed: {result}"); + let error = if route == "play-parent" { &result["failed"]["error"] } else { &result["errors"][0]["error"] }; + assert!(error.as_str().unwrap().contains("recursive action call"), "{route}: {result}"); + if route != "play-parent" { + assert_eq!(result["files"], json!([]), "{route}: {result}"); + } + assert!(!std::path::Path::new(&output).exists()); + assert_eq!(s.actions.playing, 0); + assert!(s.actions.playback_stack.is_empty()); + } +} + +#[test] +fn named_batch_limits_nesting_and_keeps_the_callers_state() { + use crate::actions_cmds::Action; + let dir = tmp("named-batch-state"); + let input = png(&dir, "red.png", 8, 8, "#ff0000"); + let output = join(&dir, "out"); + let params = json!({"action": "Invert", "input": [input], "output": output, "format": "png"}); + let mut s = Session::new(); + s.actions.list.push(Action::new("Invert", vec![("image.adjustments.invert".into(), json!({}))])); + s.actions.playing = 16; + s.actions.playback_stack = (0..16).map(|i| format!("Parent{i}")).collect(); + let before = s.actions.clone(); + let error = s.execute("file.automate.batch", params.clone()).unwrap_err(); + assert!(error.to_string().contains("nesting exceeds 16"), "{error}"); + assert_eq!(s.actions, before); + assert!(!std::path::Path::new(&output).exists()); + + s.actions.playing = 0; + s.actions.playback_stack.clear(); + s.execute("actions.record", json!({"name": "Recorder"})).unwrap(); + let recording = s.actions.recording; + let mut missing_output = params.clone(); + missing_output.as_object_mut().unwrap().remove("output"); + assert!(s.execute("file.automate.batch", missing_output).is_err()); + assert_eq!(s.actions.recording, recording); + assert!(s.actions.playback_stack.is_empty()); + let result = s.execute("file.automate.batch", params.clone()).unwrap(); + assert_eq!(result["errors"], json!([]), "{result}"); + assert_eq!(s.actions.recording, recording); + assert_eq!(s.actions.playing, 0); + assert!(s.actions.playback_stack.is_empty()); + s.execute("actions.stop", json!({})).unwrap(); + assert_eq!(s.actions.list[1].steps, vec![("file.automate.batch".into(), params)]); +} + +#[test] +fn named_batch_charges_the_existing_budget_across_inputs_and_children() { + use crate::actions_cmds::{Action, MAX_PLAYBACK_STEPS}; + let dir = tmp("named-batch-budget"); + let input = png(&dir, "red.png", 8, 8, "#ff0000"); + let output = join(&dir, "out"); + let mut s = Session::new(); + s.actions.list.push(Action::new("Large", vec![("image.adjustments.invert".into(), json!({})); 100])); + let result = s.execute("file.automate.batch", json!({"action": "Large", "input": vec![input.clone(); 1001], "output": output})).unwrap_err(); + assert!(result.to_string().contains("step limit"), "{result}"); + assert!(!std::path::Path::new(&output).exists()); + assert_eq!(s.actions.playing, 0); + assert!(s.actions.playback_stack.is_empty()); + + // A finished playback leaves its count behind; a new named Batch starts fresh. + s.actions.list = vec![Action::new("Empty", Vec::new())]; + s.actions.playback_steps = MAX_PLAYBACK_STEPS; + let result = s.execute("file.automate.batch", json!({"action": "Empty", "input": [input], "output": join(&dir, "fresh")})).unwrap(); + assert_eq!(result["errors"], json!([]), "{result}"); + assert_eq!(result["files"].as_array().unwrap().len(), 1); + + s.actions.list = vec![ + Action::new("Outer", vec![("actions.play".into(), json!({"action": "Leaf"}))]), + Action::new("Leaf", vec![("select.deselect".into(), json!({})); 2]), + ]; + s.actions.playing = 1; + s.actions.playback_stack = vec!["Parent".into()]; + s.actions.playback_steps = MAX_PLAYBACK_STEPS - 4; + let result = s.execute("file.automate.batch", json!({"action": "Outer", "input": [input, input], "output": output, "naming": "{serial}"})).unwrap(); + assert_eq!(result["files"].as_array().unwrap().len(), 1, "{result}"); + assert!(result["errors"][0]["error"].as_str().unwrap().contains("step limit"), "{result}"); + assert_eq!(s.actions.playback_steps, MAX_PLAYBACK_STEPS); + assert_eq!(s.actions.playing, 1); + assert_eq!(s.actions.playback_stack, ["Parent"]); +} + +#[test] +fn named_batch_allows_nested_work_and_preserves_authorization() { + use crate::actions_cmds::Action; + fn deny_invert(id: &str, _: &Value) -> Result<()> { + if id == "image.adjustments.invert" { Err(EngineError::Other("invert denied".into())) } else { Ok(()) } + } + let dir = tmp("named-batch-nesting"); + let input = png(&dir, "red.png", 8, 8, "#ff0000"); + for denied in [false, true] { + let output = join(&dir, &format!("out-{denied}")); + let inner = join(&dir, &format!("inner-{denied}")); + let child = json!({"action": "Leaf", "input": [input], "output": inner, "format": "png"}); + let mut s = Session::new(); + s.actions.list = + vec![Action::new("Outer", vec![("file.automate.batch".into(), child)]), Action::new("Leaf", vec![("image.adjustments.invert".into(), json!({}))])]; + if denied { + s.authorize = Some(deny_invert); + } + let before = s.actions.clone(); + let result = s.execute("file.automate.batch", json!({"action": "Outer", "input": [input], "output": output, "format": "png"})).unwrap(); + if denied { + assert_eq!(result["files"], json!([]), "{result}"); + assert!(result["errors"][0]["error"].as_str().unwrap().contains("invert denied"), "{result}"); + assert!(!std::path::Path::new(&output).exists()); + assert!(!std::path::Path::new(&inner).exists()); + } else { + assert_eq!(result["errors"], json!([]), "{result}"); + let saved = photocraft_io::import("red.png", &std::fs::read(join(&inner, "red.png")).unwrap()).unwrap().document; + assert_eq!(photocraft_compose::render(&saved, Rect::new(1, 1, 2, 2)).px[0], [0.0, 1.0, 1.0, 1.0]); + } + assert_eq!(s.actions, before); + } +} + +#[test] +fn nested_batch_errors_stop_actions_and_scripts_without_changing_top_level_results() { + use crate::actions_cmds::Action; + let dir = tmp("nested-batch-failure"); + let input = png(&dir, "red.png", 8, 8, "#ff0000"); + let output = join(&dir, "out"); + let batch = json!({"input": [input], "output": output, "steps": [["file.close", {}]]}); + let mut s = Session::new(); + let result = s.execute("file.automate.batch", batch.clone()).unwrap(); + assert_eq!(result["files"], json!([])); + assert_eq!(result["errors"].as_array().unwrap().len(), 1); + let steps = vec![("file.automate.batch".into(), batch), ("file.new".into(), json!({"width": 2, "height": 2}))]; + s.actions.list.push(Action::new("Caller", steps.clone())); + let result = s.execute("actions.play", json!({"action": "Caller"})).unwrap(); + assert_eq!(result["ran"], 0, "{result}"); + assert!(result["failed"]["error"].as_str().unwrap().contains("no active document"), "{result}"); + let result = s.execute("file.scripts.browse", json!({"steps": steps})).unwrap(); + assert_eq!(result["ok"], false, "{result}"); + assert_eq!(result["results"].as_array().unwrap().len(), 1); + assert!(s.documents().is_empty(), "neither caller reaches file.new"); + assert!(!std::path::Path::new(&output).exists()); + assert_eq!(crate::actions_cmds::nested_failure("file.automate.batch", &json!({"files": ["ok.png"], "errors": []})), None); + assert_eq!(crate::actions_cmds::nested_failure("file.automate.batch", &json!({"errors": "invalid"})), None); +} + #[test] fn color_lookup_table_bakes_the_adjustment_stack() { let mut s = session(8, 8, 8);