diff --git a/crates/magna-build/tests/plan_wiring.rs b/crates/magna-build/tests/plan_wiring.rs index e797897..210ab24 100644 --- a/crates/magna-build/tests/plan_wiring.rs +++ b/crates/magna-build/tests/plan_wiring.rs @@ -217,6 +217,130 @@ async fn variables_resolve_into_plan_arguments() { assert_eq!(resp.data.to_string(), r#"{answer: 9}"#); } +/// A step that depends on another step, and echoes its dependency's value. +/// This is the document-assembly shape: leaves fetch, an assembler composes. +struct EchoDepStep { + id: StepId, + deps: Vec, + tag: i64, +} + +#[async_trait] +impl ExecutableStep for EchoDepStep { + fn id(&self) -> StepId { + self.id + } + + fn dependencies(&self) -> &[StepId] { + &self.deps + } + + fn is_unary(&self) -> bool { + true + } + + fn fingerprint(&self) -> StepFingerprint { + let mut h = std::collections::hash_map::DefaultHasher::new(); + self.tag.hash(&mut h); + StepFingerprint::new( + std::any::TypeId::of::(), + self.deps.clone(), + h.finish(), + ) + } + + async fn execute( + &self, + _ctx: &ExecutionContext, + inputs: StepInputs, + ) -> Result { + // Positional downcast — exactly what a document assembler does, and + // what silently breaks if a dependency's output goes missing. + let dep = inputs + .dep_outputs + .first() + .ok_or_else(|| FwGraphError::ExecutionError("assembler got no inputs".into()))?; + let base = dep.values[0] + .downcast_ref::() + .copied() + .ok_or_else(|| FwGraphError::ExecutionError("dependency had wrong type".into()))?; + Ok(StepOutput::from_values(vec![Arc::new(base + self.tag)])) + } +} + +/// Two roots, each registering a leaf (same key ⇒ deduped) plus its own +/// assembler that depends on that leaf. +struct AssemblerExtension { + executions: Arc, +} + +impl SchemaExtension for AssemblerExtension { + fn name(&self) -> &str { + "assemblers" + } + + fn extend_query(&self, ctx: &mut ExtensionContext<'_>) { + for (field, tag) in [("left", 100i64), ("right", 200i64)] { + ctx.query_field(Field::new( + field, + TypeRef::named_nn(TypeRef::INT), + planned_resolver(field), + )); + + let executions = Arc::clone(&self.executions); + ctx.plan_field("Query", field, move |scope, _args| { + // Identical leaf in both roots ⇒ the SECOND one is + // deduplicated away, and its assembler's dependency id + // becomes stale. + let leaf = scope.register(Arc::new(ConstStep { + id: scope.next_step_id(), + base: 5, + executions: Arc::clone(&executions), + }))?; + scope.register(Arc::new(EchoDepStep { + id: scope.next_step_id(), + deps: vec![leaf], + tag, + })) + }); + } + } +} + +/// Regression: an assembly step whose dependency was deduplicated away must +/// still receive that dependency's output. +/// +/// Dedup removes the duplicate leaf and rebuilds graph edges, but a surviving +/// step still NAMES the id it was constructed with. The executor therefore +/// has to resolve dependency ids through the remap before looking them up — +/// and must treat a genuinely missing output as an error rather than +/// dropping it, because `StepInputs` is positional and a silent drop shifts +/// every later input into the wrong slot. +#[tokio::test] +async fn an_assembler_whose_dependency_was_deduped_still_gets_its_input() { + let executions = Arc::new(AtomicUsize::new(0)); + let gather = empty_gather(); + let schema = build_schema( + &gather, + &gather.behaviors, + lazy_pool(), + &[Box::new(AssemblerExtension { + executions: Arc::clone(&executions), + })], + ) + .expect("schema build"); + + let resp = schema.execute("{ left right }").await; + assert!(resp.errors.is_empty(), "unexpected errors: {:?}", resp.errors); + // Both assemblers saw the shared leaf's value (5), and added their tags. + assert_eq!(resp.data.to_string(), r#"{left: 105, right: 205}"#); + assert_eq!( + executions.load(Ordering::SeqCst), + 1, + "the shared leaf must execute once", + ); +} + #[tokio::test] async fn unplanned_operations_pay_nothing() { // A query that touches no planned field must not fail and must not diff --git a/crates/magna-core/src/executor.rs b/crates/magna-core/src/executor.rs index be316f8..da00035 100644 --- a/crates/magna-core/src/executor.rs +++ b/crates/magna-core/src/executor.rs @@ -41,23 +41,48 @@ impl Executor { continue; }; - // Gather inputs from dependency outputs - let dep_ids = step.dependencies(); + // Gather inputs from dependency outputs. + // + // A step OWNS its dependency ids, and deduplication does not + // rewrite them — it removes the duplicate step and rebuilds + // the graph's edges, leaving surviving steps still naming the + // id they were built with. So every dependency id must be + // resolved through the dedup remap before it is looked up, + // or a step whose dependency was deduplicated away finds + // nothing. + let dep_ids: Vec = step + .dependencies() + .iter() + .map(|id| plan.remap.get(id).copied().unwrap_or(*id)) + .collect(); // Check if any dependency has propagating flags that // should skip this step's execution. - let should_skip = check_propagating_flags(dep_ids, &outputs, batch_size); + let should_skip = check_propagating_flags(&dep_ids, &outputs, batch_size); if let Some(skip_output) = should_skip { outputs.insert(step_id, Arc::new(skip_output)); continue; } - // Build inputs for this step - let dep_outputs: Vec> = dep_ids - .iter() - .filter_map(|id| outputs.get(id).cloned()) - .collect(); + // Build inputs for this step. + // + // `StepInputs` is POSITIONAL — `dep_outputs[i]` must + // correspond to `dependencies()[i]`, and steps downcast by + // position. Dropping a missing dependency would silently + // shift every later input down one slot and hand a step the + // wrong value at the wrong type, so a missing output is a + // hard error naming the step and the dependency. + let mut dep_outputs: Vec> = Vec::with_capacity(dep_ids.len()); + for id in &dep_ids { + let output = outputs.get(id).cloned().ok_or_else(|| { + FwGraphError::ExecutionError(format!( + "step {step_id} depends on step {id}, which produced no output \ + (dependency missing from the plan or executed out of order)" + )) + })?; + dep_outputs.push(output); + } let inputs = StepInputs::new(dep_outputs); let step = Arc::clone(step); diff --git a/crates/magna-core/src/optimizer.rs b/crates/magna-core/src/optimizer.rs index e09fd5f..d4f10f3 100644 --- a/crates/magna-core/src/optimizer.rs +++ b/crates/magna-core/src/optimizer.rs @@ -8,7 +8,7 @@ use crate::fingerprint::StepFingerprint; use crate::planner::ExecutionPlan; use magna_types::StepId; -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; /// Result of the optimization pass: an ordered list of step IDs /// to execute, plus the (possibly reduced) plan. @@ -152,38 +152,50 @@ fn rebuild_edges_after_remap(plan: &mut ExecutionPlan, remap: &HashMap) { - // Partition into unary and non-unary, preserving relative order - let mut unary_ids: Vec = Vec::new(); - let mut non_unary_ids: Vec = Vec::new(); + // Hoist unary steps toward the front so their single value is available + // as early as possible — but NEVER past a step they depend on. + // + // The naive version of this pass partitioned into unary/non-unary and + // concatenated. That is only sound under the assumption a unary step + // never depends on a non-unary one, which the old comment asserted and + // nothing enforced. It is also false in practice: a document assembler + // is unary (one document) and legitimately depends on a batched, and + // therefore non-unary, read. Concatenating placed the assembler BEFORE + // its input, and the executor then found no output for a dependency + // that had not run yet. + // + // So a step is hoisted only once every dependency it names is already + // placed. Walking the incoming topological order and deferring anything + // not yet satisfied keeps the result a valid topological order by + // construction, while still pulling independent unary steps forward. + let mut hoisted: Vec = Vec::with_capacity(order.len()); + let mut deferred: Vec = Vec::with_capacity(order.len()); + let mut placed: HashSet = HashSet::new(); for &id in order.iter() { - if let Some(step) = plan.steps.get(&id) { - if step.is_unary() { - unary_ids.push(id); - } else { - non_unary_ids.push(id); - } - } - } - - // Rebuild: unary first (they have no batch deps), then non-unary. - // Both sub-lists are already in valid topological order since we - // preserved relative ordering within each partition. - // - // This is safe because unary steps' dependencies are either: - // - Other unary steps (which are also hoisted) - // - No dependencies (root steps) - // A unary step should never depend on a non-unary step (that would - // make it batch-dependent). We verify this at placement time. - let mut result = Vec::with_capacity(order.len()); + let Some(step) = plan.steps.get(&id) else { + // Not in the plan (removed by dedup) — drop it from the order. + continue; + }; - // Insert unary steps, respecting their internal dependency order - result.extend(unary_ids.iter().copied()); + let deps_satisfied = plan + .dependencies_of(id) + .iter() + .all(|dep| placed.contains(dep)); - // Insert non-unary steps after all unary steps - result.extend(non_unary_ids.iter().copied()); + if step.is_unary() && deps_satisfied { + placed.insert(id); + hoisted.push(id); + } else { + deferred.push(id); + } + } - *order = result; + // `deferred` keeps its relative order, which was topologically valid on + // the way in; `hoisted` only ever contains steps whose dependencies were + // already placed. Concatenating preserves both. + hoisted.extend(deferred.iter().copied()); + *order = hoisted; } #[cfg(test)] @@ -308,3 +320,77 @@ mod tests { assert_eq!(optimized.plan.step_count(), 2); } } + +#[cfg(test)] +mod dedup_dep_tests { + use super::*; + use crate::planner::Planner; + use crate::step::{ExecutableStep, ExecutionContext, StepInputs, StepOutput}; + use magna_types::FwGraphError; + use std::sync::Arc; + + struct Leaf { id: StepId, key: u64 } + #[async_trait::async_trait] + impl ExecutableStep for Leaf { + fn id(&self) -> StepId { self.id } + fn dependencies(&self) -> &[StepId] { &[] } + fn is_unary(&self) -> bool { true } + fn fingerprint(&self) -> StepFingerprint { + StepFingerprint::new(std::any::TypeId::of::(), vec![], self.key) + } + async fn execute(&self, _c: &ExecutionContext, _i: StepInputs) -> Result { + Ok(StepOutput::from_values(vec![Arc::new(self.key)])) + } + } + struct Asm { id: StepId, deps: Vec, tag: u64 } + #[async_trait::async_trait] + impl ExecutableStep for Asm { + fn id(&self) -> StepId { self.id } + fn dependencies(&self) -> &[StepId] { &self.deps } + fn is_unary(&self) -> bool { true } + fn fingerprint(&self) -> StepFingerprint { + StepFingerprint::new(std::any::TypeId::of::(), self.deps.clone(), self.tag) + } + async fn execute(&self, _c: &ExecutionContext, _i: StepInputs) -> Result { + Ok(StepOutput::from_values(vec![Arc::new(self.tag)])) + } + } + + #[test] + fn remap_points_removed_to_surviving() { + let mut p = Planner::new(4); + p.register(Arc::new(Leaf { id: 1, key: 5 })); + p.register(Arc::new(Asm { id: 2, deps: vec![1], tag: 100 })); + p.register(Arc::new(Leaf { id: 3, key: 5 })); + p.register(Arc::new(Asm { id: 4, deps: vec![3], tag: 200 })); + let opt = optimize(p.build().unwrap()); + + eprintln!("remap = {:?}", opt.remap); + eprintln!("surviving = {:?}", { + let mut v: Vec<_> = opt.plan.step_ids(); v.sort(); v + }); + eprintln!("order = {:?}", opt.execution_order); + + // Every remap TARGET must survive; every remap SOURCE must be gone. + for (removed, canonical) in &opt.remap { + assert!(opt.plan.get_step(*canonical).is_some(), + "remap {removed}->{canonical} but {canonical} was removed"); + assert!(opt.plan.get_step(*removed).is_none(), + "remap {removed}->{canonical} but {removed} still present"); + } + // Every surviving step's deps must resolve to a surviving step. + for id in opt.plan.step_ids() { + let step = opt.plan.get_step(id).unwrap(); + for d in step.dependencies() { + let c = opt.remap.get(d).copied().unwrap_or(*d); + assert!(opt.plan.get_step(c).is_some(), + "step {id} dep {d} -> {c} which does not survive"); + // …and it must be ordered BEFORE this step. + let pos_dep = opt.execution_order.iter().position(|x| *x == c); + let pos_self = opt.execution_order.iter().position(|x| *x == id); + assert!(pos_dep < pos_self, + "step {id} (pos {pos_self:?}) runs before its dep {c} (pos {pos_dep:?})"); + } + } + } +}