From 253ae127097437cd4f94d32e739cdb9c26a56f87 Mon Sep 17 00:00:00 2001 From: Shane McGuirt <10144278+srmcguirt@users.noreply.github.com> Date: Sat, 1 Aug 2026 11:11:09 -0400 Subject: [PATCH 1/2] =?UTF-8?q?fix(dataplan):=20tweak-aware=20step=20finge?= =?UTF-8?q?rprints=20=E2=80=94=20close=20the=20dedup=20unsoundness?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PgSelectStep's config hash covered schema/table/selected_cols/fk_col and deliberately excluded tweaks ("tweaks are runtime, not plan-time"). But tweaks are registered at plan time and carry WHERE/ORDER/LIMIT, and the optimizer's deduplicate() merges steps on (type_id, deps, config_hash) — so two steps over the same table with DIFFERENT filter arguments shared a fingerprint, and the optimizer would collapse them and serve one field's rows to the other field. Latent today (nothing constructs a plan yet); live data-bleed the moment the plan path gains a caller. The fix makes tweak identity part of the fingerprint, two ways: apply_keyed(key, tweak) the caller declares the argument values the tweak was built from; the key hashes into the fingerprint in registration order. Same table + same declared args => steps still dedupe (the whole point of the optimizer); different args => never collide. apply(tweak) unkeyed: the closure is opaque, its effect on the SQL is unknowable, so the step's own id is folded in, making the fingerprint unique. An unkeyed step never deduplicates — safe by default rather than fast by assumption. Four regression tests pin the property: same-args dedupe, different-args never collide, unkeyed poisons dedup, untweaked baseline still dedupes. Co-Authored-By: Claude Fable 5 --- crates/magna-dataplan/src/steps/pg_select.rs | 116 ++++++++++++++++++- 1 file changed, 114 insertions(+), 2 deletions(-) diff --git a/crates/magna-dataplan/src/steps/pg_select.rs b/crates/magna-dataplan/src/steps/pg_select.rs index 9b05b96..d0eca7e 100644 --- a/crates/magna-dataplan/src/steps/pg_select.rs +++ b/crates/magna-dataplan/src/steps/pg_select.rs @@ -69,6 +69,20 @@ pub struct PgSelectStep { /// These are closures that transform the SqlBuilder just before build(). tweaks: Vec, + /// Hashes of the keys supplied via [`apply_keyed`](Self::apply_keyed), in + /// registration order. These participate in the fingerprint so that two + /// steps whose tweaks were built from the same argument values dedupe, + /// while steps tweaked with different arguments never collide. + tweak_keys: Vec, + + /// True once any *unkeyed* tweak has been registered via + /// [`apply`](Self::apply). An unkeyed tweak's semantics are invisible to + /// the fingerprint (it is an opaque closure), so the only sound treatment + /// is to make this step's fingerprint unique — it must never dedupe with + /// anything, or one field's WHERE/ORDER/LIMIT would silently serve + /// another field's rows. + has_unkeyed_tweak: bool, + deps: Vec, } @@ -91,6 +105,8 @@ impl PgSelectStep { fk_col: None, parent_pk_col: "id".to_string(), tweaks: Vec::new(), + tweak_keys: Vec::new(), + has_unkeyed_tweak: false, deps: Vec::new(), } } @@ -117,8 +133,37 @@ impl PgSelectStep { /// argument values only knowable at runtime. /// /// Tweaks are applied in registration order. + /// + /// An unkeyed tweak makes this step's fingerprint **unique**: the closure + /// is opaque, so the optimizer cannot know whether two tweaked steps ask + /// the same question, and deduplicating them on the base config alone + /// would serve one field's filtered rows to a different field. Prefer + /// [`apply_keyed`](Self::apply_keyed) whenever the tweak is a pure + /// function of hashable argument values — that keeps deduplication. pub fn apply(&mut self, tweak: impl Fn(SqlBuilder) -> SqlBuilder + Send + Sync + 'static) { self.tweaks.push(Box::new(tweak)); + self.has_unkeyed_tweak = true; + } + + /// Register a runtime tweak together with the argument values it was + /// built from. The key is hashed into the step's fingerprint, so two + /// steps over the same table whose tweaks encode the **same** arguments + /// deduplicate into one query, while tweaks encoding **different** + /// arguments never collide. + /// + /// The caller owns the contract that `key` fully determines the tweak's + /// effect on the SQL: same key ⇒ same WHERE/ORDER/LIMIT. Registration + /// order still matters and is part of the fingerprint (keys are hashed + /// in sequence). + pub fn apply_keyed( + &mut self, + key: K, + tweak: impl Fn(SqlBuilder) -> SqlBuilder + Send + Sync + 'static, + ) { + let mut h = DefaultHasher::new(); + key.hash(&mut h); + self.tweak_keys.push(h.finish()); + self.tweaks.push(Box::new(tweak)); } /// Add an explicit dependency. @@ -128,14 +173,27 @@ impl PgSelectStep { } } - /// Plan-time fingerprint hash: schema + table + selected_cols + fk_col. - /// Does NOT include tweaks — tweaks are runtime, not plan-time. + /// Plan-time fingerprint hash: schema + table + selected_cols + fk_col, + /// plus the tweak discipline: + /// + /// * **Keyed tweaks** contribute their key hashes in registration order — + /// same table + same tweak arguments ⇒ same hash ⇒ the optimizer merges + /// the two steps into one query; different arguments ⇒ different hash. + /// * **Any unkeyed tweak** folds this step's own `id` in, making the + /// fingerprint unique to this step. An opaque closure's effect on the + /// SQL is unknowable here, and the failure mode of guessing wrong is + /// the optimizer serving one field's filtered rows to another field — + /// so an unkeyed step simply never deduplicates. fn compute_config_hash(&self) -> u64 { let mut h = DefaultHasher::new(); self.schema.hash(&mut h); self.table.hash(&mut h); self.selected_cols.hash(&mut h); self.fk_col.hash(&mut h); + self.tweak_keys.hash(&mut h); + if self.has_unkeyed_tweak { + self.id.hash(&mut h); + } h.finish() } @@ -411,6 +469,60 @@ mod tests { assert_eq!(params[0].as_i64(), Some(10)); } + // ── Tweak fingerprint discipline ───────────────────────────────────── + // These four tests are the regression suite for the dedup-unsoundness + // class: the optimizer merges steps with equal fingerprints, so a + // fingerprint that ignores tweak arguments would let a step filtered + // `WHERE book = 'John'` absorb a step filtered `WHERE book = 'Gen'` and + // serve John's rows to Genesis's field. + + #[tokio::test] + async fn same_keyed_tweak_args_dedupe() { + let pool = mock_pool(); + let mut a = PgSelectStep::new(1, pool.clone(), "public", "users", vec!["id".into()]); + let mut b = PgSelectStep::new(2, pool, "public", "users", vec!["id".into()]); + a.apply_keyed(("book", "John"), |b| b.limit(10)); + b.apply_keyed(("book", "John"), |b| b.limit(10)); + // Same table, same declared arguments → same config hash → the + // optimizer may (and should) collapse these into one query. + assert_eq!(a.compute_config_hash(), b.compute_config_hash()); + } + + #[tokio::test] + async fn different_keyed_tweak_args_never_collide() { + let pool = mock_pool(); + let mut a = PgSelectStep::new(1, pool.clone(), "public", "users", vec!["id".into()]); + let mut b = PgSelectStep::new(2, pool, "public", "users", vec!["id".into()]); + a.apply_keyed(("book", "John"), |b| b.limit(10)); + b.apply_keyed(("book", "Gen"), |b| b.limit(10)); + assert_ne!( + a.compute_config_hash(), + b.compute_config_hash(), + "steps tweaked with different arguments must never share a fingerprint", + ); + } + + #[tokio::test] + async fn unkeyed_tweak_poisons_dedup() { + let pool = mock_pool(); + let mut a = PgSelectStep::new(1, pool.clone(), "public", "users", vec!["id".into()]); + let mut b = PgSelectStep::new(2, pool, "public", "users", vec!["id".into()]); + // Identical closures — but the fingerprint cannot see inside them, + // so each step must be unique rather than assumed equivalent. + a.apply(|b| b.limit(10)); + b.apply(|b| b.limit(10)); + assert_ne!(a.compute_config_hash(), b.compute_config_hash()); + } + + #[tokio::test] + async fn untweaked_steps_still_dedupe() { + let pool = mock_pool(); + let a = PgSelectStep::new(1, pool.clone(), "public", "users", vec!["id".into()]); + let b = PgSelectStep::new(2, pool, "public", "users", vec!["id".into()]); + // The baseline behavior the optimizer relies on is preserved. + assert_eq!(a.compute_config_hash(), b.compute_config_hash()); + } + #[test] fn pg_value_eq_works() { assert!(pg_value_eq(&PgValue::Int(1), &PgValue::Int(1))); From 399d94bb215d2ae0c77088acac16541d2be46da8 Mon Sep 17 00:00:00 2001 From: Shane McGuirt <10144278+srmcguirt@users.noreply.github.com> Date: Sat, 1 Aug 2026 11:21:02 -0400 Subject: [PATCH 2/2] =?UTF-8?q?feat(build):=20wire=20the=20planner=20into?= =?UTF-8?q?=20the=20request=20lifecycle=20=E2=80=94=20plan=5Ffield=20+=20P?= =?UTF-8?q?lanExtension?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The engine (magna-core), the batched steps (magna-dataplan), and the register→execute→read bridge (PlanContext) were all complete and tested — and nothing called them. The auto-generated resolvers bypass the planner via QueryExecutor, and there was no async-graphql Extension anywhere that would turn an incoming operation into a plan. This commit is that missing piece, in the Grafast shape: plan the whole operation, run one DAG, resolve fields from its results. WHAT'S NEW plan_extension.rs PlanRegistry plan fns keyed by (type, field), populated at schema-build time; empty registry ⇒ extension not attached ⇒ unplanned schemas pay nothing. PlanScope what a plan fn works against: allocates step ids, registers steps into the operation's ONE shared plan (which is what makes cross-field dedup structural). PlanResults request-scoped handle; resolvers read their output by response key (alias if present, else field name). PlanExtension per-request lifecycle: prepare_request inserts the results handle → parse_query captures the operation → execute() walks root query selections, resolves field arguments against variables, calls plan fns, executes the plan, publishes outputs — then resolution runs. ExtensionContext::plan_field(type, field, fn) The embedder registration surface, available in every phase. The field itself is still registered via query_field with a resolver that reads PlanResults — planning supplies the data, not the schema entry. OptimizedPlan.remap + PlanContext follows it Dedup removed the duplicate step and rewrote graph edges, but DISCARDED the removed→canonical remap — so get_result(deduped_id) returned None, breaking result lookup for exactly the fields dedup helped. The remap now survives into PlanContext and get_result forwards through it. SCOPE (first pass, documented in the module) Root query fields only; fragment-reached fields are not planned and must error loudly rather than silently fall back. Mutations/subscriptions unplanned. Nested selection planning (steps depending on parent output) is the next stage, not this one. PROOF (tests/plan_wiring.rs — no database) · a field served entirely through the plan path · { a: answer(n:7) b: answer(n:7) } → ONE step execution, BOTH fields resolve (the remap fix, live) · { a: answer(n:1) b: answer(n:2) } → two executions — different args never share (the data-bleed guard from the fingerprint commit) · variables resolve into plan arguments · unplanned operations execute zero steps Workspace: 405 passed, 0 failed. Co-Authored-By: Claude Fable 5 --- crates/magna-build/src/extension.rs | 62 +++- crates/magna-build/src/lib.rs | 19 ++ crates/magna-build/src/plan_extension.rs | 365 +++++++++++++++++++++++ crates/magna-build/src/plan_resolver.rs | 21 +- crates/magna-build/tests/plan_wiring.rs | 230 ++++++++++++++ crates/magna-core/src/optimizer.rs | 21 +- 6 files changed, 710 insertions(+), 8 deletions(-) create mode 100644 crates/magna-build/src/plan_extension.rs create mode 100644 crates/magna-build/tests/plan_wiring.rs diff --git a/crates/magna-build/src/extension.rs b/crates/magna-build/src/extension.rs index b0a9939..2bf8e0b 100644 --- a/crates/magna-build/src/extension.rs +++ b/crates/magna-build/src/extension.rs @@ -30,6 +30,9 @@ use async_graphql::dynamic::{Field, Object, SchemaBuilder, Type}; +use crate::plan_extension::{FieldArgs, PlanRegistry, PlanScope}; +use magna_types::{FwGraphError, StepId}; + /// Context passed to a [`SchemaExtension`] hook so it can register types and /// add fields. Internals are private — all mutation is via methods. /// @@ -53,6 +56,9 @@ pub struct ExtensionContext<'a> { query: Option<&'a mut Object>, /// In-progress Mutation root. `Some` only during `extend_mutation`. mutation: Option<&'a mut Object>, + /// Plan-fn registry for plan-based execution. Available in every phase — + /// planning is orthogonal to which root the field hangs from. + plan_registry: &'a mut PlanRegistry, } impl<'a> ExtensionContext<'a> { @@ -115,6 +121,30 @@ impl<'a> ExtensionContext<'a> { replace_with(*q, |obj| obj.field(field)); } + /// Register a plan function for `type_name.field_name` — the field's data + /// needs, as steps in the operation's shared plan. Available in every + /// phase. + /// + /// When at least one plan fn is registered, `build_schema` attaches the + /// plan extension to the schema: per request, the operation's planned + /// root fields register their steps into ONE plan, the optimizer + /// deduplicates steps with equal fingerprints across fields, the plan + /// executes before resolution begins, and each field's resolver reads + /// its output from [`crate::PlanResults`] by response key. + /// + /// The field itself must still be registered (via + /// [`query_field`](Self::query_field)) with a resolver that reads + /// `ctx.data::>()` — planning supplies the data, not + /// the schema entry. + pub fn plan_field( + &mut self, + type_name: impl Into, + field_name: impl Into, + f: impl Fn(&PlanScope<'_>, &FieldArgs) -> Result + Send + Sync + 'static, + ) { + self.plan_registry.plan_field(type_name, field_name, f); + } + /// Add a field to the Mutation root. Only valid inside `extend_mutation`. /// Panics if called from `register_types` or `extend_query`. /// @@ -230,6 +260,7 @@ pub(crate) fn run_extension_phase( builder: SchemaBuilder, query: &mut Object, mutation: Option<&mut Object>, + plan_registry: &mut PlanRegistry, extensions: &[Box], phase: Phase, ) -> SchemaBuilder { @@ -254,6 +285,7 @@ pub(crate) fn run_extension_phase( builder: current_builder.take(), query: ctx_query, mutation: ctx_mutation, + plan_registry: &mut *plan_registry, }; match phase { @@ -292,12 +324,16 @@ mod tests { } } - fn fresh_ctx<'a>(query: &'a mut Object) -> ExtensionContext<'a> { + fn fresh_ctx<'a>( + query: &'a mut Object, + plan_registry: &'a mut PlanRegistry, + ) -> ExtensionContext<'a> { let builder = async_graphql::dynamic::Schema::build("Query", None, None); ExtensionContext { builder: Some(builder), query: Some(query), mutation: None, + plan_registry, } } @@ -312,14 +348,17 @@ mod tests { let mut query = Object::new("Query"); // RegisterTypes phase: query/mutation are None. let builder = async_graphql::dynamic::Schema::build("Query", None, None); + let mut plan_reg = PlanRegistry::default(); let mut ctx = ExtensionContext { builder: Some(builder), query: None, mutation: None, + plan_registry: &mut plan_reg, }; ext.register_types(&mut ctx); // ExtendQuery phase: query is Some. - let mut ctx2 = fresh_ctx(&mut query); + let mut plan_reg2 = PlanRegistry::default(); + let mut ctx2 = fresh_ctx(&mut query, &mut plan_reg2); ext.extend_query(&mut ctx2); ext.extend_mutation(&mut ctx2); } @@ -334,10 +373,12 @@ mod tests { } } let builder = async_graphql::dynamic::Schema::build("Query", None, None); + let mut plan_reg = PlanRegistry::default(); let mut ctx = ExtensionContext { builder: Some(builder), query: None, mutation: None, + plan_registry: &mut plan_reg, }; TypeAdder.register_types(&mut ctx); assert!(ctx.builder.is_some(), "builder should be restored"); @@ -359,7 +400,8 @@ mod tests { } } let mut query = Object::new("Query"); - let mut ctx = fresh_ctx(&mut query); + let mut plan_reg = PlanRegistry::default(); + let mut ctx = fresh_ctx(&mut query, &mut plan_reg); MultiFielder.extend_query(&mut ctx); // The placeholder type name must never leak into the result. assert_eq!(query.type_name(), "Query"); @@ -369,10 +411,12 @@ mod tests { #[should_panic(expected = "outside extend_query phase")] fn test_query_field_panics_outside_extend_query() { let builder = async_graphql::dynamic::Schema::build("Query", None, None); + let mut plan_reg = PlanRegistry::default(); let mut ctx = ExtensionContext { builder: Some(builder), query: None, mutation: None, + plan_registry: &mut plan_reg, }; ctx.query_field(Field::new( "x", @@ -385,10 +429,12 @@ mod tests { #[should_panic(expected = "outside extend_mutation phase")] fn test_mutation_field_panics_outside_extend_mutation() { let builder = async_graphql::dynamic::Schema::build("Query", None, None); + let mut plan_reg = PlanRegistry::default(); let mut ctx = ExtensionContext { builder: Some(builder), query: None, mutation: None, + plan_registry: &mut plan_reg, }; ctx.mutation_field(Field::new( "x", @@ -442,7 +488,15 @@ mod tests { }, )); let exts: Vec> = vec![Box::new(DataInjector)]; - let builder = run_extension_phase(builder, &mut query, None, &exts, Phase::RegisterTypes); + let mut plan_reg = PlanRegistry::default(); + let builder = run_extension_phase( + builder, + &mut query, + None, + &mut plan_reg, + &exts, + Phase::RegisterTypes, + ); let schema = builder.register(query).finish().expect("schema must finish"); let res = schema.execute("{ marker }").await; diff --git a/crates/magna-build/src/lib.rs b/crates/magna-build/src/lib.rs index 8bb9117..d2398c8 100644 --- a/crates/magna-build/src/lib.rs +++ b/crates/magna-build/src/lib.rs @@ -3,6 +3,7 @@ pub(crate) mod executor; pub mod gather; pub mod ir; pub mod naming; +pub mod plan_extension; pub mod plan_resolver; pub mod register; pub mod resolve; @@ -17,6 +18,9 @@ pub use ir::{ BehaviorSet, GatherOutput, ResolvedColumn, ResolvedEnum, ResolvedRelation, ResolvedResource, ResourceKind, }; +pub use plan_extension::{ + FieldArgs, PlanExtensionFactory, PlanFn, PlanRegistry, PlanResults, PlanScope, +}; pub use plan_resolver::PlanContext; pub use union_step::{PgUnionStep, TaggedRow}; pub use extension::{ExtensionContext, SchemaExtension}; @@ -218,12 +222,17 @@ pub fn build_schema( // 11. Register condition types for all resources builder = register_condition_types(builder, &output.resources); + // Plan-fn registry — populated by extensions via `plan_field` during any + // phase; if non-empty after all phases, the plan extension is attached. + let mut plan_registry = plan_extension::PlanRegistry::default(); + // 11b. Let extensions register custom types BEFORE query/mutation field construction // so extensions can reference auto-generated types in their field signatures. builder = extension::run_extension_phase( builder, &mut query, None, + &mut plan_registry, extensions, extension::Phase::RegisterTypes, ); @@ -244,6 +253,7 @@ pub fn build_schema( builder, &mut query, None, + &mut plan_registry, extensions, extension::Phase::ExtendQuery, ); @@ -281,6 +291,7 @@ pub fn build_schema( builder, &mut query, Some(&mut mutation), + &mut plan_registry, extensions, extension::Phase::ExtendMutation, ); @@ -307,6 +318,14 @@ pub fn build_schema( // 17. Apply limits and finish builder = builder.limit_complexity(200).limit_depth(10); + // Attach plan-based execution only when an extension registered at least + // one plan fn — unplanned schemas pay zero per-request overhead. + if !plan_registry.is_empty() { + builder = builder.extension(plan_extension::PlanExtensionFactory::new(Arc::new( + plan_registry, + ))); + } + builder .finish() .map_err(|e| BuildError::SchemaFinish(e.to_string())) diff --git a/crates/magna-build/src/plan_extension.rs b/crates/magna-build/src/plan_extension.rs new file mode 100644 index 0000000..08b63ce --- /dev/null +++ b/crates/magna-build/src/plan_extension.rs @@ -0,0 +1,365 @@ +//! Plan-based execution wiring — the bridge between magna-core's two-phase +//! planner and async-graphql's request lifecycle. +//! +//! Everything below this module already existed and was tested: the planner +//! DAG (`magna-core`), fingerprint deduplication (`optimize`), batched +//! Postgres steps (`magna-dataplan::PgSelectStep`), and the register→execute→ +//! read bridge (`PlanContext`). What was missing was the piece that turns an +//! **incoming GraphQL operation** into a plan and hands the executed results +//! to field resolvers. This module is that piece. +//! +//! # Lifecycle +//! +//! 1. At schema-build time an embedder registers plan fns via +//! [`crate::ExtensionContext::plan_field`], keyed by `(type, field)`. +//! If at least one is registered, `build_schema` attaches +//! [`PlanExtensionFactory`] to the schema. +//! 2. Per request, [`PlanExtension::prepare_request`] inserts a shared +//! [`PlanResults`] handle into the request data. +//! 3. [`PlanExtension::parse_query`] captures the parsed operation and its +//! variables. +//! 4. [`PlanExtension::execute`] walks the operation's **root selections**, +//! calls every registered plan fn (with variable-resolved field +//! arguments), executes the resulting plan — one DAG for the whole +//! operation, so steps shared between root fields deduplicate and batch — +//! and publishes the outputs into the [`PlanResults`] handle. +//! 5. Field resolvers read their output via +//! [`PlanResults::field_output`], keyed by the field's **response key** +//! (alias if present, else name). +//! +//! # Scope (first pass) +//! +//! * Root `query` fields only. Fields reached through fragment spreads or +//! inline fragments at the root are **not** planned — a planned field +//! inside a fragment will find no output and should error loudly, not +//! silently fall back. Mutations and subscriptions are unplanned. +//! * The plan executes **before** field resolution begins (no lazy +//! per-field planning). This is the Grafast shape: plan the whole +//! operation, then run it. + +use std::collections::HashMap; +use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::{Arc, Mutex, OnceLock}; + +use async_graphql::extensions::{ + Extension, ExtensionContext as RequestContext, ExtensionFactory, NextExecute, NextParseQuery, + NextPrepareRequest, +}; +use async_graphql::parser::types::{ExecutableDocument, OperationType, Selection}; +use async_graphql::{Request, Response, ServerError, ServerResult, Variables}; +use magna_core::{ExecutableStep, ExecutionContext, StepOutput}; +use magna_types::{FwGraphError, JwtClaims, StepId}; + +use crate::plan_resolver::PlanContext; + +/// Batch size handed to the planner. Bounds how many parent ids a single +/// batched child query carries; not a hard result limit. +const PLAN_BATCH_SIZE: usize = 64; + +/// A planned field's arguments: name → JSON value, with GraphQL variables +/// already substituted. Plan fns never see raw AST. +pub type FieldArgs = serde_json::Map; + +/// The registration surface a [`PlanFn`] works against: allocates step ids +/// and registers steps into the operation's single shared plan. +pub struct PlanScope<'a> { + ctx: &'a PlanContext, + next_id: &'a AtomicU32, +} + +impl PlanScope<'_> { + /// Allocate a fresh step id, unique within this operation's plan. + pub fn next_step_id(&self) -> StepId { + self.next_id.fetch_add(1, Ordering::Relaxed) + } + + /// Register a step. Steps registered by different fields land in the + /// same plan, which is what lets the optimizer deduplicate shared work + /// across fields. + pub fn register(&self, step: Arc) -> Result { + self.ctx.register_step(step) + } +} + +/// A field's plan function: registers the steps that produce the field's +/// data and returns the id of the step whose output the resolver should +/// read. Runs once per request, before any resolver. +pub type PlanFn = + Arc, &FieldArgs) -> Result + Send + Sync>; + +/// Plan fns keyed by `(type_name, field_name)`. Populated at schema-build +/// time via [`crate::ExtensionContext::plan_field`]; immutable afterwards. +#[derive(Default)] +pub struct PlanRegistry { + fields: HashMap<(String, String), PlanFn>, +} + +impl PlanRegistry { + /// Register a plan fn for `type_name.field_name`. Last registration wins, + /// matching the "later extensions may override earlier ones" convention. + pub fn plan_field( + &mut self, + type_name: impl Into, + field_name: impl Into, + f: impl Fn(&PlanScope<'_>, &FieldArgs) -> Result + Send + Sync + 'static, + ) { + self.fields + .insert((type_name.into(), field_name.into()), Arc::new(f)); + } + + /// True when no plan fns are registered — `build_schema` skips attaching + /// the extension entirely, so unplanned schemas pay nothing. + pub fn is_empty(&self) -> bool { + self.fields.is_empty() + } + + fn get(&self, type_name: &str, field_name: &str) -> Option<&PlanFn> { + // Keyed lookup without allocating a (String, String) per call. + self.fields + .iter() + .find(|((t, f), _)| t == type_name && f == field_name) + .map(|(_, v)| v) + } +} + +/// The executed plan's outputs, readable by field resolvers. +/// +/// Inserted into the request data as `Arc` by +/// [`PlanExtension::prepare_request`]; published once by +/// [`PlanExtension::execute`] after the plan runs. A resolver for a planned +/// field calls [`field_output`](Self::field_output) with its response key. +#[derive(Default)] +pub struct PlanResults { + inner: OnceLock, +} + +struct Planned { + ctx: PlanContext, + /// Response key (alias if present, else field name) → the field's output step. + field_steps: HashMap, +} + +impl PlanResults { + /// The executed output for the field with this response key, or `None` + /// when the field was not planned (not registered, not a root field, or + /// reached through a fragment). Resolvers should treat `None` for a field + /// that *expects* planning as an error, never as empty data. + pub fn field_output(&self, response_key: &str) -> Option> { + let planned = self.inner.get()?; + let step_id = planned.field_steps.get(response_key)?; + planned.ctx.get_result(*step_id) + } + + /// True once the operation's plan has executed and results are readable. + pub fn is_planned(&self) -> bool { + self.inner.get().is_some() + } +} + +/// Attaches plan-based execution to a schema. Constructed by `build_schema` +/// when the [`PlanRegistry`] is non-empty. +pub struct PlanExtensionFactory { + registry: Arc, +} + +impl PlanExtensionFactory { + pub fn new(registry: Arc) -> Self { + Self { registry } + } +} + +impl ExtensionFactory for PlanExtensionFactory { + fn create(&self) -> Arc { + // One PlanExtension per request: the captured document and the + // results handle are request-scoped state. + Arc::new(PlanExtension { + registry: Arc::clone(&self.registry), + captured: Mutex::new(None), + results: Arc::new(PlanResults::default()), + }) + } +} + +/// Per-request extension instance. See the module docs for the lifecycle. +pub struct PlanExtension { + registry: Arc, + /// Captured by `parse_query`, consumed by `execute`. + captured: Mutex>, + results: Arc, +} + +impl PlanExtension { + /// Build and execute the plan for the captured operation. Returns + /// resolver-visible errors; an operation with no planned fields is a + /// successful no-op. + async fn plan( + &self, + ctx: &RequestContext<'_>, + operation_name: Option<&str>, + ) -> Result<(), Vec> { + let Some((doc, variables)) = self.captured.lock().expect("captured lock").take() else { + return Ok(()); + }; + + // Select the operation the same way the executor will. Ambiguity + // (multiple operations, no name) is not planning's error to report — + // skip, and let downstream produce the canonical error. + let operation = match operation_name { + Some(name) => doc.operations.iter().find(|(n, _)| { + n.map(|n| n.as_str() == name).unwrap_or(false) + }), + None => { + let mut iter = doc.operations.iter(); + let first = iter.next(); + if iter.next().is_some() { None } else { first } + } + }; + let Some((_, op)) = operation else { + return Ok(()); + }; + if op.node.ty != OperationType::Query { + return Ok(()); + } + + // Gather the planned root fields: (response key, plan fn, resolved args). + let mut planned_fields: Vec<(String, PlanFn, FieldArgs)> = Vec::new(); + for sel in &op.node.selection_set.node.items { + let Selection::Field(field) = &sel.node else { + // Fragment spread / inline fragment at the root: not planned + // in the first pass (module docs). The field's resolver will + // find no output and must error loudly. + continue; + }; + let name = field.node.name.node.as_str(); + let Some(plan_fn) = self.registry.get("Query", name) else { + continue; + }; + + let mut args = FieldArgs::new(); + for (arg_name, arg_value) in &field.node.arguments { + let const_value = arg_value + .node + .clone() + .into_const_with(|var_name| { + variables.get(&var_name).cloned().ok_or_else(|| { + ServerError::new( + format!("unknown variable ${var_name}"), + Some(arg_value.pos), + ) + }) + }) + .map_err(|e| vec![e])?; + let json = const_value.into_json().map_err(|e| { + vec![ServerError::new( + format!("argument {arg_name} is not JSON-representable: {e}"), + Some(arg_value.pos), + )] + })?; + args.insert(arg_name.node.to_string(), json); + } + + let response_key = field + .node + .alias + .as_ref() + .map(|a| a.node.to_string()) + .unwrap_or_else(|| name.to_string()); + planned_fields.push((response_key, Arc::clone(plan_fn), args)); + } + + if planned_fields.is_empty() { + return Ok(()); + } + + // One ExecutionContext and ONE plan for the whole operation — this is + // what makes cross-field dedup structural rather than per-field. + let jwt_claims = ctx.data_opt::().cloned().map(Arc::new); + let variables_json = serde_json::Value::Object( + variables + .iter() + .map(|(name, value)| { + ( + name.to_string(), + value.clone().into_json().unwrap_or(serde_json::Value::Null), + ) + }) + .collect(), + ); + let exec_ctx = Arc::new(ExecutionContext { + request_id: uuid::Uuid::new_v4(), + jwt_claims, + variables: Arc::new(variables_json), + }); + + let plan_ctx = PlanContext::new(exec_ctx, PLAN_BATCH_SIZE); + let next_id = AtomicU32::new(1); + let scope = PlanScope { + ctx: &plan_ctx, + next_id: &next_id, + }; + + let mut field_steps = HashMap::new(); + for (response_key, plan_fn, args) in planned_fields { + let step_id = plan_fn(&scope, &args).map_err(|e| { + vec![ServerError::new( + format!("planning failed for field '{response_key}': {e}"), + None, + )] + })?; + field_steps.insert(response_key, step_id); + } + + plan_ctx + .execute() + .await + .map_err(|e| vec![ServerError::new(format!("plan execution failed: {e}"), None)])?; + + // OnceLock: publish exactly once. A second publish would mean two + // execute() hooks ran for one request instance — a bug upstream. + let _ = self.results.inner.set(Planned { + ctx: plan_ctx, + field_steps, + }); + Ok(()) + } +} + +#[async_trait::async_trait] +impl Extension for PlanExtension { + async fn prepare_request( + &self, + ctx: &RequestContext<'_>, + request: Request, + next: NextPrepareRequest<'_>, + ) -> ServerResult { + // Make the (not-yet-populated) results handle visible to resolvers. + let request = request.data(Arc::clone(&self.results)); + next.run(ctx, request).await + } + + async fn parse_query( + &self, + ctx: &RequestContext<'_>, + query: &str, + variables: &Variables, + next: NextParseQuery<'_>, + ) -> ServerResult { + let doc = next.run(ctx, query, variables).await?; + if !self.registry.is_empty() { + *self.captured.lock().expect("captured lock") = Some((doc.clone(), variables.clone())); + } + Ok(doc) + } + + async fn execute( + &self, + ctx: &RequestContext<'_>, + operation_name: Option<&str>, + next: NextExecute<'_>, + ) -> Response { + if let Err(errors) = self.plan(ctx, operation_name).await { + return Response::from_errors(errors); + } + next.run(ctx, operation_name).await + } +} diff --git a/crates/magna-build/src/plan_resolver.rs b/crates/magna-build/src/plan_resolver.rs index 66d1c3c..037dd46 100644 --- a/crates/magna-build/src/plan_resolver.rs +++ b/crates/magna-build/src/plan_resolver.rs @@ -19,6 +19,10 @@ use magna_types::{FwGraphError, StepId}; pub struct PlanContext { planner: Mutex>, results: OnceLock>>, + /// The optimizer's dedup remap (removed id → canonical id), retained so + /// a caller that registered a step which was then deduplicated away can + /// still read its result — via the canonical step that absorbed it. + remap: OnceLock>, exec_ctx: Arc, #[allow(dead_code)] batch_size: usize, @@ -30,6 +34,7 @@ impl PlanContext { Self { planner: Mutex::new(Some(Planner::new(batch_size))), results: OnceLock::new(), + remap: OnceLock::new(), exec_ctx, batch_size, } @@ -74,6 +79,11 @@ impl PlanContext { let optimized = optimize(plan); let outputs = Executor::execute(&optimized, Arc::clone(&self.exec_ctx)).await?; + // Retain the dedup remap BEFORE storing results: a registered step + // that was deduplicated away no longer appears in `outputs`, and + // `get_result` must forward its id to the canonical step. + let _ = self.remap.set(optimized.remap); + // Store results — OnceLock guarantees this only happens once. self.results.set(outputs).map_err(|_| { FwGraphError::ExecutionError("results already set (internal error)".to_string()) @@ -84,9 +94,18 @@ impl PlanContext { /// Retrieve the output for a specific step after `execute()` completes. /// + /// The id may be one the caller registered that was then deduplicated + /// away by the optimizer — it is forwarded to the canonical step that + /// absorbed it (equal fingerprints ⇒ identical output, by contract). + /// /// Returns `None` if `execute()` has not been called yet, or if the step ID is unknown. pub fn get_result(&self, step_id: StepId) -> Option> { - self.results.get()?.get(&step_id).cloned() + let canonical = self + .remap + .get() + .and_then(|m| m.get(&step_id).copied()) + .unwrap_or(step_id); + self.results.get()?.get(&canonical).cloned() } /// Returns `true` if `execute()` has been called and completed successfully. diff --git a/crates/magna-build/tests/plan_wiring.rs b/crates/magna-build/tests/plan_wiring.rs new file mode 100644 index 0000000..e797897 --- /dev/null +++ b/crates/magna-build/tests/plan_wiring.rs @@ -0,0 +1,230 @@ +//! End-to-end proof of the plan-based execution wiring — no database. +//! +//! This is the test the planner never had: a GraphQL request served THROUGH +//! the plan path. It exercises the full lifecycle: +//! +//! plan_field registration (ExtensionContext) → build_schema attaches the +//! plan extension → prepare_request inserts PlanResults → parse_query +//! captures the operation → execute() plans root fields, runs the DAG, +//! publishes outputs → field resolvers read results by response key. +//! +//! It also pins the two properties that make planning worth having: +//! +//! * **Cross-field dedup**: two root fields whose steps carry equal +//! fingerprints execute ONE step, and both fields still resolve — via +//! the optimizer's remap, which `PlanContext::get_result` follows. +//! * **Argument isolation**: fields planned with different arguments carry +//! different fingerprints and never share an execution. + +use std::collections::HashMap; +use std::hash::{Hash, Hasher}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; + +use async_graphql::dynamic::{Field, FieldFuture, TypeRef}; +use async_trait::async_trait; +use magna_build::{ + build_schema, ExtensionContext, GatherOutput, PlanResults, SchemaExtension, +}; +use magna_core::{ + ExecutableStep, ExecutionContext, StepFingerprint, StepInputs, StepOutput, +}; +use magna_types::{FwGraphError, StepId}; + +fn lazy_pool() -> sqlx::PgPool { + sqlx::PgPool::connect_lazy("postgresql://nobody:nobody@127.0.0.1:1/nodb") + .expect("connect_lazy accepts a bogus URL") +} + +fn empty_gather() -> GatherOutput { + GatherOutput { + resources: vec![], + relations: vec![], + behaviors: HashMap::new(), + enums: vec![], + smart_tags: HashMap::new(), + plugin_metadata: serde_json::Map::new(), + } +} + +/// A DB-free step: returns `base + offset` as its single value and counts +/// its executions. `base` participates in the fingerprint (it stands in for +/// "the arguments this step was built from"); `offset` deliberately does +/// not (it stands in for closure state the fingerprint cannot see — which +/// is exactly why equal fingerprints MUST imply identical outputs, and why +/// these tests only give equal bases equal offsets). +struct ConstStep { + id: StepId, + base: i64, + executions: Arc, +} + +#[async_trait] +impl ExecutableStep for ConstStep { + fn id(&self) -> StepId { + self.id + } + + fn dependencies(&self) -> &[StepId] { + &[] + } + + fn fingerprint(&self) -> StepFingerprint { + let mut h = std::collections::hash_map::DefaultHasher::new(); + self.base.hash(&mut h); + StepFingerprint::new(std::any::TypeId::of::(), vec![], h.finish()) + } + + async fn execute( + &self, + _ctx: &ExecutionContext, + _inputs: StepInputs, + ) -> Result { + self.executions.fetch_add(1, Ordering::SeqCst); + Ok(StepOutput::from_values(vec![Arc::new(self.base)])) + } +} + +/// The embedder side, written exactly the way fw-resolvers would write it: +/// each planned field gets (a) a schema entry whose resolver reads +/// `PlanResults` by its response key, and (b) a plan fn registering its step. +struct PlannedFieldsExtension { + executions: Arc, +} + +/// A resolver that reads the field's planned output. This is the ONLY data +/// path — there is no fallback fetch. A planned field with no output is a +/// hard error, never silently empty. +fn planned_resolver(field_name: &'static str) -> impl Fn(async_graphql::dynamic::ResolverContext) -> FieldFuture + Send + Sync + 'static +{ + move |ctx| { + FieldFuture::new(async move { + let results = ctx.data::>()?; + let key = ctx + .field() + .alias() + .unwrap_or(field_name) + .to_string(); + let output = results.field_output(&key).ok_or_else(|| { + async_graphql::Error::new(format!("field '{key}' was not planned")) + })?; + let value = output.values[0] + .downcast_ref::() + .copied() + .ok_or_else(|| async_graphql::Error::new("planned output type mismatch"))?; + Ok(Some(async_graphql::Value::from(value))) + }) + } +} + +impl SchemaExtension for PlannedFieldsExtension { + fn name(&self) -> &str { + "planned-fields" + } + + fn extend_query(&self, ctx: &mut ExtensionContext<'_>) { + // `answer(n: Int!)` — planned from its argument value. + ctx.query_field( + Field::new("answer", TypeRef::named_nn(TypeRef::INT), planned_resolver("answer")) + .argument(async_graphql::dynamic::InputValue::new( + "n", + TypeRef::named_nn(TypeRef::INT), + )), + ); + + let executions = Arc::clone(&self.executions); + ctx.plan_field("Query", "answer", move |scope, args| { + let n = args.get("n").and_then(|v| v.as_i64()).unwrap_or(0); + scope.register(Arc::new(ConstStep { + id: scope.next_step_id(), + base: n, + executions: Arc::clone(&executions), + })) + }); + } +} + +async fn planned_schema(executions: Arc) -> async_graphql::dynamic::Schema { + let gather = empty_gather(); + build_schema( + &gather, + &gather.behaviors, + lazy_pool(), + &[Box::new(PlannedFieldsExtension { executions })], + ) + .expect("schema build") +} + +#[tokio::test] +async fn a_field_is_served_entirely_through_the_plan_path() { + let executions = Arc::new(AtomicUsize::new(0)); + let schema = planned_schema(Arc::clone(&executions)).await; + + let resp = schema.execute("{ answer(n: 42) }").await; + assert!(resp.errors.is_empty(), "unexpected errors: {:?}", resp.errors); + assert_eq!(resp.data.to_string(), r#"{answer: 42}"#); + assert_eq!(executions.load(Ordering::SeqCst), 1, "exactly one step execution"); +} + +#[tokio::test] +async fn equal_arguments_across_fields_execute_once_and_both_fields_resolve() { + // THE dedup proof, end to end: two aliased root fields, same argument, + // so their steps carry equal fingerprints. The optimizer collapses them + // to one execution — and the field whose step was deduplicated away + // still resolves, because get_result follows the optimizer's remap. + let executions = Arc::new(AtomicUsize::new(0)); + let schema = planned_schema(Arc::clone(&executions)).await; + + let resp = schema + .execute("{ a: answer(n: 7) b: answer(n: 7) }") + .await; + assert!(resp.errors.is_empty(), "unexpected errors: {:?}", resp.errors); + assert_eq!(resp.data.to_string(), r#"{a: 7, b: 7}"#); + assert_eq!( + executions.load(Ordering::SeqCst), + 1, + "equal fingerprints must collapse to ONE execution shared by both fields", + ); +} + +#[tokio::test] +async fn different_arguments_never_share_an_execution() { + // The other half of the §fingerprint contract: different arguments ⇒ + // different fingerprints ⇒ no sharing. If this ever fails, one field is + // being served another field's rows — the data-bleed class. + let executions = Arc::new(AtomicUsize::new(0)); + let schema = planned_schema(Arc::clone(&executions)).await; + + let resp = schema + .execute("{ a: answer(n: 1) b: answer(n: 2) }") + .await; + assert!(resp.errors.is_empty(), "unexpected errors: {:?}", resp.errors); + assert_eq!(resp.data.to_string(), r#"{a: 1, b: 2}"#); + assert_eq!(executions.load(Ordering::SeqCst), 2, "two distinct executions"); +} + +#[tokio::test] +async fn variables_resolve_into_plan_arguments() { + // Arguments arriving via GraphQL variables (the common client shape) + // must reach the plan fn resolved, not as AST variable references. + let executions = Arc::new(AtomicUsize::new(0)); + let schema = planned_schema(Arc::clone(&executions)).await; + + let req = async_graphql::Request::new("query Q($n: Int!) { answer(n: $n) }") + .variables(async_graphql::Variables::from_json(serde_json::json!({ "n": 9 }))); + let resp = schema.execute(req).await; + assert!(resp.errors.is_empty(), "unexpected errors: {:?}", resp.errors); + assert_eq!(resp.data.to_string(), r#"{answer: 9}"#); +} + +#[tokio::test] +async fn unplanned_operations_pay_nothing() { + // A query that touches no planned field must not fail and must not + // execute any step. + let executions = Arc::new(AtomicUsize::new(0)); + let schema = planned_schema(Arc::clone(&executions)).await; + + let resp = schema.execute("{ __typename }").await; + assert!(resp.errors.is_empty()); + assert_eq!(executions.load(Ordering::SeqCst), 0, "no steps executed"); +} diff --git a/crates/magna-core/src/optimizer.rs b/crates/magna-core/src/optimizer.rs index 5c5a85a..e09fd5f 100644 --- a/crates/magna-core/src/optimizer.rs +++ b/crates/magna-core/src/optimizer.rs @@ -19,6 +19,16 @@ pub struct OptimizedPlan { /// Step IDs in topological execution order. Steps earlier in this /// list have no unresolved dependencies when it is their turn. pub execution_order: Vec, + + /// Deduplication remap: removed step id → the canonical step that + /// absorbed it. A caller holding the id of a step it registered must + /// follow this map when reading results — the registered step may no + /// longer exist in the plan, but its output is the canonical step's + /// output by construction (equal fingerprints ⇒ identical results). + /// Values are always canonical (never themselves remapped): dedup + /// processes in topological order and a fingerprint's first occurrence + /// stays canonical for the whole pass. + pub remap: HashMap, } /// Run all optimization passes on an ExecutionPlan. @@ -33,7 +43,7 @@ pub fn optimize(mut plan: ExecutionPlan) -> OptimizedPlan { let order = topological_sort(&plan); // Deduplicate steps with matching fingerprints - deduplicate(&mut plan, &order); + let remap = deduplicate(&mut plan, &order); // Re-sort after dedup since the graph may have changed let mut execution_order = topological_sort(&plan); @@ -44,6 +54,7 @@ pub fn optimize(mut plan: ExecutionPlan) -> OptimizedPlan { OptimizedPlan { plan, execution_order, + remap, } } @@ -58,11 +69,13 @@ pub fn topological_sort(plan: &ExecutionPlan) -> Vec { sorted.iter().map(|&idx| plan.graph[idx]).collect() } -/// Deduplicate steps with identical fingerprints. +/// Deduplicate steps with identical fingerprints. Returns the remap of +/// removed step id → canonical step id, so result lookups for a deduped +/// step can be forwarded to the step that absorbed it. /// /// Processes steps in topological order so that dependency IDs are /// already remapped by the time we compute a step's fingerprint. -fn deduplicate(plan: &mut ExecutionPlan, topo_order: &[StepId]) { +fn deduplicate(plan: &mut ExecutionPlan, topo_order: &[StepId]) -> HashMap { let mut seen: HashMap = HashMap::new(); let mut remap: HashMap = HashMap::new(); let mut to_remove: Vec = Vec::new(); @@ -107,6 +120,8 @@ fn deduplicate(plan: &mut ExecutionPlan, topo_order: &[StepId]) { if !remap.is_empty() { rebuild_edges_after_remap(plan, &remap); } + + remap } /// After deduplication, rebuild the graph edges so that steps which