diff --git a/distributed_cli/README.md b/distributed_cli/README.md index 3529039f..21e98366 100644 --- a/distributed_cli/README.md +++ b/distributed_cli/README.md @@ -282,7 +282,9 @@ from that selected surface. The runtime applies GraphQL singleton-list coercion, canonical scalar encoding, unknown-field rejection, and deterministic deep freezing before variables can identify a cache entry or reach the network. Manifest v7 and variable codec v2 carry the selected service's exact -`max_depth`, `max_bool_width`, and `max_in_list` contract. Static literal and +`max_depth`, `max_bool_width`, and `max_in_list` contract, and its `max_rows` +budget ([query cost](../docs/graphql-query-cost.md)): an operation whose +literal or default page sizes already exceed it fails to compile. Static literal and mixed-variable filters are rejected during generation when their known shape exceeds those limits; runtime variables carry per-use `filterBaseDepth` and `maxItems` constraints. Reused variables receive the most restrictive diff --git a/distributed_cli/src/client_compiler/graphql/mod.rs b/distributed_cli/src/client_compiler/graphql/mod.rs index 18e68b98..986db3b6 100644 --- a/distributed_cli/src/client_compiler/graphql/mod.rs +++ b/distributed_cli/src/client_compiler/graphql/mod.rs @@ -11,9 +11,9 @@ use serde::Serialize; use serde_json::{Map as JsonMap, Value as JsonValue}; use super::manifest::{ - hash_bytes, ClientAggregateSemantics, ClientArgument, ClientArgumentKind, - ClientComplexityWeights, ClientExecutionLimits, ClientField, ClientFilterField, - ClientFilterInput, ClientFilterSemantics, ClientManifest, ClientModel, ClientOrderSemantics, + hash_bytes, row_cost, ClientAggregateSemantics, ClientArgument, ClientArgumentKind, + ClientExecutionLimits, ClientField, ClientFilterField, ClientFilterInput, + ClientFilterSemantics, ClientManifest, ClientModel, ClientOrderSemantics, ClientPaginationSemantics, ClientRelationship, ClientRelationshipKind, ClientRelationshipMaintenance, ClientRoot, ClientRootKind, ClientRootOperation, ClientRowPolicy, FilterExpr, RelationshipKeyMapping, diff --git a/distributed_cli/src/client_compiler/graphql/validation.rs b/distributed_cli/src/client_compiler/graphql/validation.rs index 513cbc74..7fe39812 100644 --- a/distributed_cli/src/client_compiler/graphql/validation.rs +++ b/distributed_cli/src/client_compiler/graphql/validation.rs @@ -20,14 +20,13 @@ pub(super) fn validate_execution_limits( )); } - let weights = &execution.complexity; - let complexity = weights.root(kind, compiled_object_complexity(&root.selection, weights)); - if complexity > execution.max_complexity { + let rows = compiled_root_rows(root, kind); + if rows > execution.max_rows { return Err(source_error( - "client.operation.complexity_limit", + "client.operation.row_limit", format!( - "compiled operation complexity {complexity} exceeds the selected service max_complexity {}", - execution.max_complexity + "compiled operation may return {rows} rows, exceeding the selected service max_rows {}", + execution.max_rows ), document, position, @@ -53,31 +52,74 @@ pub(super) fn compiled_object_depth(selection: &CompiledObject, parent_depth: u6 .unwrap_or(parent_depth) } -/// The service's own cost formula ([`ClientComplexityWeights`]) over the -/// compiled selection, with the weights the selected service advertises. -pub(super) fn compiled_object_complexity( - selection: &CompiledObject, - weights: &ClientComplexityWeights, -) -> u64 { - weights.object(selection.members.iter().map(|member| match member { - CompiledMember::Scalar(_) => weights.scalar, - CompiledMember::Branch(branch) => { - let child = compiled_object_complexity(&branch.selection, weights); - match branch.semantic { - CompiledBranchSemantic::Relationship => weights.relationship( - branch - .relationship - .as_ref() - .expect("relationship branches retain their compiled descriptor") - .kind, - child, - ), - CompiledBranchSemantic::Aggregate => weights.aggregate(child), - CompiledBranchSemantic::AggregateFields => weights.scalar, - CompiledBranchSemantic::AggregateNodes => weights.aggregate_nodes(child), +/// The service's row cost ([`row_cost`]) of a compiled root: every list +/// counts its page size, so nested lists cost about the product of their +/// limits. +/// +/// A literal `limit` counts as given (capped by the field's `max_limit`); an +/// absent one, or a variable whose value is unknown until run time, counts as +/// the field's `default_limit`. The service checks the actual values again +/// for every request, so this build-time check refuses only what the defaults +/// already put over budget. +pub(super) fn compiled_root_rows(root: &CompiledRoot, kind: ClientRootKind) -> u64 { + let limit = page_limit(&root.arguments, root.coverage.as_ref()); + match kind { + ClientRootKind::List => row_cost::page(limit, compiled_object_rows(&root.selection, limit)), + ClientRootKind::ByPk => row_cost::one(compiled_object_rows(&root.selection, limit)), + ClientRootKind::Aggregate => compiled_object_rows(&root.selection, limit), + } +} + +/// Rows nested under one object. `nodes_limit` is the page size of an +/// aggregate's `nodes`, which take their arguments from the aggregate field. +fn compiled_object_rows(selection: &CompiledObject, nodes_limit: u64) -> u64 { + selection + .members + .iter() + .map(|member| match member { + CompiledMember::Scalar(_) => 0, + CompiledMember::Branch(branch) => { + let limit = page_limit(&branch.arguments, branch.coverage.as_ref()); + match branch.semantic { + CompiledBranchSemantic::Relationship => { + let nested = compiled_object_rows(&branch.selection, limit); + match branch.cardinality { + Cardinality::Many => row_cost::page(limit, nested), + Cardinality::One => row_cost::one(nested), + } + } + CompiledBranchSemantic::Aggregate => { + compiled_object_rows(&branch.selection, limit) + } + CompiledBranchSemantic::AggregateFields => 0, + CompiledBranchSemantic::AggregateNodes => row_cost::page( + nodes_limit, + compiled_object_rows(&branch.selection, nodes_limit), + ), + } } - } - })) + }) + .fold(0, u64::saturating_add) +} + +fn page_limit( + arguments: &BTreeMap, + coverage: Option<&CompiledCoverage>, +) -> u64 { + let Some(coverage) = coverage else { + return 1; + }; + let default = coverage.default_limit.unwrap_or(1); + let literal = coverage + .limit_argument + .as_ref() + .and_then(|name| arguments.get(name)) + .and_then(|argument| match argument { + CompiledArgument::Literal { value, .. } => value.as_u64(), + _ => None, + }); + let limit = literal.unwrap_or(default); + coverage.max_limit.map_or(limit, |max| limit.min(max)) } pub(super) fn filter_depth_from_selection(selection_depth: usize, root_offset: usize) -> u64 { @@ -1194,20 +1236,105 @@ pub(super) fn validate_order_entry_source( mod tests { use super::*; - /// The service charges one scalar for a selection with nothing costed in - /// it; a compiler that charged zero would accept an operation the service - /// then rejects at its `max_complexity`. - #[test] - fn an_empty_selection_costs_what_the_service_charges() { - let weights = ClientComplexityWeights { - scalar: 4, - ..ClientComplexityWeights::current() - }; - let empty = CompiledObject { + fn object(members: Vec) -> CompiledObject { + CompiledObject { typename: "todo".into(), storage: CompiledStorage::Embedded, - members: Vec::new(), + members, + } + } + + fn branch( + semantic: CompiledBranchSemantic, + cardinality: Cardinality, + limit: Option, + selection: CompiledObject, + ) -> CompiledMember { + let mut arguments = BTreeMap::new(); + if let Some(limit) = limit { + arguments.insert( + "limit".to_owned(), + CompiledArgument::Literal { + value: JsonValue::from(limit), + wire: limit.to_string(), + }, + ); + } + CompiledMember::Branch(Box::new(CompiledBranch { + semantic, + response_key: "items".into(), + field: "items".into(), + cardinality, + nullable: false, + arguments, + dependencies: Vec::new(), + coverage: Some(CompiledCoverage { + kind: "offset".into(), + offset_argument: None, + limit_argument: Some("limit".into()), + default_limit: Some(100), + max_limit: Some(1000), + }), + filter: None, + order: None, + pagination: None, + relationship: None, + selection, + })) + } + + /// The compiler's arithmetic is the service's: nested lists multiply, + /// one-to-one relationships add one row, aggregates count their nodes. + #[test] + fn row_cost_matches_the_service() { + let many = |limit, selection| { + branch( + CompiledBranchSemantic::Relationship, + Cardinality::Many, + limit, + selection, + ) }; - assert_eq!(compiled_object_complexity(&empty, &weights), 4); + // orders(limit: 1000) { items(limit: 1000) { id } } + let nested = object(vec![many(Some(1000), object(Vec::new()))]); + assert_eq!(compiled_object_rows(&nested, 1), 1000); + assert_eq!( + row_cost::page(1000, compiled_object_rows(&nested, 1)), + 1_001_000 + ); + // An absent limit is the default page. + assert_eq!( + compiled_object_rows(&object(vec![many(None, object(Vec::new()))]), 1), + 100 + ); + // A belongs-to costs one row plus what it carries. + let one = branch( + CompiledBranchSemantic::Relationship, + Cardinality::One, + None, + object(Vec::new()), + ); + assert_eq!(compiled_object_rows(&object(vec![one]), 1), 1); + // items_aggregate(limit: 7) { aggregate { count } nodes { id } } + let aggregate = branch( + CompiledBranchSemantic::Aggregate, + Cardinality::One, + Some(7), + object(vec![ + branch( + CompiledBranchSemantic::AggregateFields, + Cardinality::One, + None, + object(Vec::new()), + ), + branch( + CompiledBranchSemantic::AggregateNodes, + Cardinality::Many, + None, + object(Vec::new()), + ), + ]), + ); + assert_eq!(compiled_object_rows(&object(vec![aggregate]), 1), 7); } } diff --git a/distributed_cli/src/client_compiler/manifest/model_validation.rs b/distributed_cli/src/client_compiler/manifest/model_validation.rs index 3d2f9f4b..079295d9 100644 --- a/distributed_cli/src/client_compiler/manifest/model_validation.rs +++ b/distributed_cli/src/client_compiler/manifest/model_validation.rs @@ -197,6 +197,8 @@ pub(crate) fn validate_execution_limits( const JS_MAX_SAFE_INTEGER: u64 = 9_007_199_254_740_991; for (name, value) in [ ("max_depth", execution.max_depth), + ("max_fields", execution.max_fields), + ("max_rows", execution.max_rows), ("max_bool_width", execution.max_bool_width), ("max_in_list", execution.max_in_list), ] { @@ -207,31 +209,6 @@ pub(crate) fn validate_execution_limits( )); } } - if execution.complexity.version != 1 { - return Err(ClientCompileError::manifest( - "client.manifest.complexity_version", - format!( - "unsupported query complexity contract version {}; distributed requires version 1", - execution.complexity.version - ), - )); - } - let weights = [ - ("scalar", execution.complexity.scalar), - ("belongs_to", execution.complexity.belongs_to), - ("has_many", execution.complexity.has_many), - ("m2m", execution.complexity.m2m), - ("aggregate", execution.complexity.aggregate), - ("list_root", execution.complexity.list_root), - ("by_pk", execution.complexity.by_pk), - ("list_fanout", execution.complexity.list_fanout), - ]; - if let Some((name, _)) = weights.into_iter().find(|(_, value)| *value == 0) { - return Err(ClientCompileError::manifest( - "client.manifest.complexity_weight", - format!("query complexity weight `{name}` must be greater than zero"), - )); - } Ok(()) } diff --git a/distributed_cli/src/client_compiler/tests.rs b/distributed_cli/src/client_compiler/tests.rs index a094fd69..2feb03cb 100644 --- a/distributed_cli/src/client_compiler/tests.rs +++ b/distributed_cli/src/client_compiler/tests.rs @@ -301,20 +301,10 @@ pub(super) fn manifest() -> JsonValue { "protocol_fingerprint": "sha256:0dfa8a3f49e17d8d99c5c095c1ed14f528cae3e55fbc2f2b852975a50936ec5b", "execution": { "max_depth": 8, - "max_complexity": 500, + "max_fields": 500, + "max_rows": 200000, "max_bool_width": 256, - "max_in_list": 1000, - "complexity": { - "version": 1, - "scalar": 1, - "belongs_to": 2, - "has_many": 10, - "m2m": 12, - "aggregate": 8, - "list_root": 3, - "by_pk": 1, - "list_fanout": 5 - } + "max_in_list": 1000 }, "capabilities": { "live_queries": true, @@ -1509,7 +1499,7 @@ fn multiple_load_islands_may_share_one_future_boundary() { } #[test] -fn enforces_the_selected_services_exact_depth_and_complexity_limits() { +fn enforces_the_selected_services_exact_depth_and_row_limits() { let shallow_source = "query ExactDepth { todos { id } }"; let mut exact_depth_manifest = manifest(); exact_depth_manifest["execution"]["max_depth"] = json!(2); @@ -1548,23 +1538,42 @@ fn enforces_the_selected_services_exact_depth_and_complexity_limits() { )) .expect("the exact recursive service depth boundary must compile"); - let source = "query ExactCost { todos { id } }"; + // A literal limit counts as given; nested lists multiply. + let source = "query ExactRows { todos(limit: 40) { id } }"; let mut accepted_manifest = manifest(); - accepted_manifest["execution"]["max_complexity"] = json!(18); + accepted_manifest["execution"]["max_rows"] = json!(40); refresh_schema_fingerprint(&mut accepted_manifest); compile(input_with_manifest(accepted_manifest, source)) - .expect("the exact service complexity boundary must compile"); + .expect("the exact service row boundary must compile"); let mut rejected_manifest = manifest(); - rejected_manifest["execution"]["max_complexity"] = json!(17); + rejected_manifest["execution"]["max_rows"] = json!(39); refresh_schema_fingerprint(&mut rejected_manifest); let error = compile(input_with_manifest(rejected_manifest, source)) - .expect_err("complexity must fail at build time"); - assert_eq!(error.code, "client.operation.complexity_limit"); - assert!( - error.message.contains("operation complexity 18"), - "{error:?}" - ); + .expect_err("rows over budget must fail at build time"); + assert_eq!(error.code, "client.operation.row_limit"); + assert!(error.message.contains("may return 40 rows"), "{error:?}"); + + // An absent limit counts as the field's default (25); a literal above + // `max_limit` (100) counts as the cap. + let mut default_manifest = manifest(); + default_manifest["execution"]["max_rows"] = json!(24); + refresh_schema_fingerprint(&mut default_manifest); + let error = compile(input_with_manifest( + default_manifest, + "query DefaultRows { todos { id } }", + )) + .expect_err("the default page counts"); + assert!(error.message.contains("may return 25 rows"), "{error:?}"); + + let mut capped_manifest = manifest(); + capped_manifest["execution"]["max_rows"] = json!(100); + refresh_schema_fingerprint(&mut capped_manifest); + compile(input_with_manifest( + capped_manifest, + "query CappedRows { todos(limit: 5000) { id } }", + )) + .expect("a limit above max_limit costs max_limit"); } #[test] diff --git a/distributed_cli/tests/cli_client.rs b/distributed_cli/tests/cli_client.rs index 72b64f5a..b7baa053 100644 --- a/distributed_cli/tests/cli_client.rs +++ b/distributed_cli/tests/cli_client.rs @@ -16,24 +16,14 @@ const ROLE_MANIFEST: &str = r#"{ "kind": "role", "name": "user" }, - "schema_fingerprint": "sha256:758a97e4f7e1e538e8be86d24abd3d50a8da2d5813d29abd7a04bfa092d05189", + "schema_fingerprint": "sha256:eb28c89f691ba3b5500f63a610f427dfa6a2a2a46e8874330411a98199e21d15", "protocol_fingerprint": "sha256:0dfa8a3f49e17d8d99c5c095c1ed14f528cae3e55fbc2f2b852975a50936ec5b", "execution": { "max_depth": 8, - "max_complexity": 500, + "max_fields": 500, + "max_rows": 200000, "max_bool_width": 256, - "max_in_list": 1000, - "complexity": { - "version": 1, - "scalar": 1, - "belongs_to": 2, - "has_many": 10, - "m2m": 12, - "aggregate": 8, - "list_root": 3, - "by_pk": 1, - "list_fanout": 5 - } + "max_in_list": 1000 }, "capabilities": { "live_queries": false, @@ -391,8 +381,8 @@ fn literal_text_search_generates_a_typed_load_island() { .replace("\"_ilike\"", "\"_ilike\", \"_icontains\"") // Adding a filter changes the selected schema contract. .replace( - "sha256:758a97e4f7e1e538e8be86d24abd3d50a8da2d5813d29abd7a04bfa092d05189", - "sha256:9143345e62737d38ed28e997fd76f434b18ae6b9c794b2c06477d1879fcfc136", + "sha256:eb28c89f691ba3b5500f63a610f427dfa6a2a2a46e8874330411a98199e21d15", + "sha256:ef5eca766105f3447552a5662d8553ef6b4c9a0a9ae20b70257152208aca88ca", ), ) .unwrap(); diff --git a/distributed_cli/tests/cli_manifest.rs b/distributed_cli/tests/cli_manifest.rs index 35a82d88..f0caa331 100644 --- a/distributed_cli/tests/cli_manifest.rs +++ b/distributed_cli/tests/cli_manifest.rs @@ -72,9 +72,13 @@ fn client_manifest_uses_service_surface_export() { assert_eq!(manifest["service_id"], "orders"); assert_eq!(manifest["surface"]["kind"], "role"); assert_eq!(manifest["surface"]["name"], "user"); + // The fingerprint commits to the exported schema contract: it is the one + // a client recomputes from the manifest itself. + let decoded: distributed::graphql::DistributedClientManifest = + serde_json::from_value(manifest.clone()).unwrap(); assert_eq!( manifest["schema_fingerprint"], - "sha256:c919a2b667e09b9ba82b7631b84580086a7143333a736eaec4641160ebe5707e" + decoded.computed_schema_fingerprint().unwrap() ); assert_eq!( manifest["protocol_fingerprint"], diff --git a/distributed_cli/tests/fixtures/generated-commands.ts b/distributed_cli/tests/fixtures/generated-commands.ts index f389b339..5a27aaa4 100644 --- a/distributed_cli/tests/fixtures/generated-commands.ts +++ b/distributed_cli/tests/fixtures/generated-commands.ts @@ -68,7 +68,7 @@ export const Command_importTodos: ReplicaCommandArtifact ApplicationManifest { /// Pool-free client export consumed by `distributed client-manifest`. pub fn distributed_client_surface() -> DistributedClientSurfaceExport { let roles = [ROLE.to_string()]; - let selected = - surface_for_application_contract(&full_surface(), APPLICATION, &roles, &roles, &grants()) - .expect("mobpit application Surface should select"); + let selected = surface_for_application(&full_surface(), APPLICATION, &roles, &roles, &grants()) + .expect("mobpit application Surface should select"); DistributedClientSurfaceExport::from_selected(APPLICATION, selected) .expect("mobpit application Surface should export") } diff --git a/src/graphql/client_manifest/limits.rs b/src/graphql/client_manifest/limits.rs index 8888535b..3ba11c4e 100644 --- a/src/graphql/client_manifest/limits.rs +++ b/src/graphql/client_manifest/limits.rs @@ -1,225 +1,103 @@ use super::*; +/// The engine's query cost limits, exported so a client compiler refuses the +/// operations the engine would refuse. One unit per field; the model is +/// described in `docs/graphql-query-cost.md`. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct ClientExecutionLimits { + /// Nesting levels of fields, relationships and `where` filters. pub max_depth: u64, - pub max_complexity: u64, + /// Selected fields in one document, every field once at every level. + pub max_fields: u64, + /// Model rows one root field may produce ([`row_cost`]). + pub max_rows: u64, + /// Entries in one `_and` / `_or` list. pub max_bool_width: u64, + /// Entries in one `_in` / `_nin` list. pub max_in_list: u64, - pub complexity: ClientComplexityWeights, } impl Default for ClientExecutionLimits { fn default() -> Self { Self { max_depth: DEFAULT_MAX_DEPTH as u64, - max_complexity: DEFAULT_MAX_COMPLEXITY as u64, - max_bool_width: DEFAULT_MAX_BOOL_WIDTH, - max_in_list: DEFAULT_MAX_IN_LIST, - complexity: ClientComplexityWeights::current(), + max_fields: DEFAULT_MAX_FIELDS as u64, + max_rows: DEFAULT_MAX_ROWS, + max_bool_width: DEFAULT_MAX_BOOL_WIDTH as u64, + max_in_list: DEFAULT_MAX_IN_LIST as u64, } } } +/// How many model rows an operation can produce: the arithmetic the engine +/// checks against `max_rows` and a client compiler mirrors. +/// +/// A page of `limit` rows costs `limit × (1 + rows nested under one row)`; +/// one object (a by-pk root, a belongs-to relationship) costs +/// `1 + rows nested under it`; scalars and `aggregate { count }` cost nothing. +/// Sibling costs add. Arithmetic saturates, so an overflowing cost is refused +/// rather than wrapped. +pub mod row_cost { + /// A page of up to `limit` rows, each carrying `nested` rows. + pub fn page(limit: u64, nested: u64) -> u64 { + limit.saturating_mul(nested.saturating_add(1)) + } + + /// One row carrying `nested` rows. + pub fn one(nested: u64) -> u64 { + page(1, nested) + } +} + +#[cfg(feature = "graphql")] impl ClientExecutionLimits { - #[cfg(feature = "graphql")] pub(crate) fn from_runtime( max_depth: usize, - max_complexity: usize, + max_fields: usize, + max_rows: u64, max_bool_width: usize, max_in_list: usize, ) -> Result { + let wide = |name: &str, value: usize| { + u64::try_from(value).map_err(|_| { + ClientManifestError(format!("GraphQL {name} exceeds the client manifest range")) + }) + }; Ok(Self { - max_depth: u64::try_from(max_depth).map_err(|_| { - ClientManifestError("GraphQL max_depth exceeds the client manifest range".into()) - })?, - max_complexity: u64::try_from(max_complexity).map_err(|_| { - ClientManifestError( - "GraphQL max_complexity exceeds the client manifest range".into(), - ) - })?, - max_bool_width: u64::try_from(max_bool_width).map_err(|_| { - ClientManifestError( - "GraphQL max_bool_width exceeds the client manifest range".into(), - ) - })?, - max_in_list: u64::try_from(max_in_list).map_err(|_| { - ClientManifestError("GraphQL max_in_list exceeds the client manifest range".into()) - })?, - complexity: ClientComplexityWeights::current(), + max_depth: wide("max_depth", max_depth)?, + max_fields: wide("max_fields", max_fields)?, + max_rows, + max_bool_width: wide("max_bool_width", max_bool_width)?, + max_in_list: wide("max_in_list", max_in_list)?, }) } } -/// Weights and formula of nested query cost (contract version 1): what the -/// engine enforces against `max_complexity`, exported so a client compiler -/// rejects the same operations at build time. -/// -/// | Kind | Cost | -/// |---|---| -/// | scalar | `scalar` per leaf field | -/// | object | sum of its fields; an empty selection still costs `scalar` | -/// | belongs_to | `belongs_to` + child selection | -/// | has_many / m2m | `has_many`/`m2m` + `list_fanout` × child selection | -/// | aggregate | `aggregate` + child selection | -/// | list root | `list_root` + `list_fanout` × child selection | -/// | by_pk root | `by_pk` + child selection | -/// -/// `list_fanout` models nested row multiplication without using the full -/// `limit` (which defaults to 100 and would make any nest fail). It is a -/// conservative multiplier so deep `has_many` trees grow faster than flat -/// field counts. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct ClientComplexityWeights { - pub version: u32, - pub scalar: u64, - pub belongs_to: u64, - pub has_many: u64, - pub m2m: u64, - pub aggregate: u64, - pub list_root: u64, - pub by_pk: u64, - /// Multiplier for nested list relationship child selections. - pub list_fanout: u64, -} - -impl ClientComplexityWeights { - /// The weights this crate's engine enforces and its manifests export. - pub fn current() -> Self { - Self { - version: QUERY_COMPLEXITY_VERSION, - scalar: 1, - belongs_to: 2, - has_many: 10, - m2m: 12, - aggregate: 8, - list_root: 3, - by_pk: 1, - // Fan-out factor: deep has_many trees exceed - // DEFAULT_MAX_COMPLEXITY by about three nested levels while - // one-level nests remain usable. - list_fanout: 5, - } - } - - /// Cost of an object selection given the cost of each selected field. - /// A selection with no costed field still costs one scalar. - pub fn object(&self, fields: impl IntoIterator) -> u64 { - let mut fields = fields.into_iter().peekable(); - if fields.peek().is_none() { - return self.scalar; - } - fields.fold(0, u64::saturating_add) - } - - /// Cost of a relationship field whose selection costs `child`. - pub fn relationship(&self, kind: ClientRelationshipKind, child: u64) -> u64 { - match kind { - ClientRelationshipKind::BelongsTo => self.belongs_to.saturating_add(child), - ClientRelationshipKind::HasMany => self - .has_many - .saturating_add(self.list_fanout.saturating_mul(child)), - ClientRelationshipKind::ManyToMany => self - .m2m - .saturating_add(self.list_fanout.saturating_mul(child)), - } - } - - /// Cost of an aggregate (root or `_aggregate` field) whose - /// selection costs `child`. - pub fn aggregate(&self, child: u64) -> u64 { - self.aggregate.saturating_add(child) - } - - /// Cost of an aggregate's `nodes` field whose selection costs `child`. - pub fn aggregate_nodes(&self, child: u64) -> u64 { - self.list_fanout.saturating_mul(child).max(self.scalar) - } - - /// Cost of a root field whose selection costs `child`. - pub fn root(&self, kind: ClientRootKind, child: u64) -> u64 { - match kind { - ClientRootKind::List => self - .list_root - .saturating_add(self.list_fanout.saturating_mul(child)), - ClientRootKind::ByPk => self.by_pk.saturating_add(child), - ClientRootKind::Aggregate => self.aggregate(child), - } - } -} - #[cfg(test)] mod tests { - use super::*; - - fn weights() -> ClientComplexityWeights { - // Distinct primes: a formula that reads the wrong weight, or the - // built-in ones, gives another number. - ClientComplexityWeights { - version: QUERY_COMPLEXITY_VERSION, - scalar: 2, - belongs_to: 3, - has_many: 5, - m2m: 7, - aggregate: 11, - list_root: 13, - by_pk: 17, - list_fanout: 19, - } - } + use super::row_cost; + use crate::graphql::cost::{DEFAULT_LIMIT, DEFAULT_MAX_LIMIT, DEFAULT_MAX_ROWS}; #[test] - fn an_empty_selection_costs_one_scalar_wherever_it_nests() { - let w = weights(); - let empty = w.object([]); - assert_eq!(empty, 2); - assert_eq!(w.object([0]), 0, "a costed field is not an empty selection"); - assert_eq!(w.relationship(ClientRelationshipKind::BelongsTo, empty), 5); - assert_eq!(w.relationship(ClientRelationshipKind::HasMany, empty), 43); - assert_eq!(w.root(ClientRootKind::List, empty), 51); - assert_eq!(w.root(ClientRootKind::Aggregate, empty), 13); + fn a_chain_of_lists_costs_about_the_product_of_its_limits() { + // orders(limit: 1000) { items(limit: 1000) { id } } + assert_eq!(row_cost::page(1000, row_cost::page(1000, 0)), 1_001_000); + // todo(id) { owner { name } } + assert_eq!(row_cost::one(row_cost::one(0)), 2); + assert_eq!(row_cost::page(u64::MAX, 1), u64::MAX); } #[test] - fn every_cost_uses_the_given_weights() { - let w = weights(); - let child = w.object([w.scalar, w.scalar]); - assert_eq!(child, 4); - assert_eq!(w.relationship(ClientRelationshipKind::BelongsTo, child), 7); - assert_eq!(w.relationship(ClientRelationshipKind::HasMany, child), 81); - assert_eq!( - w.relationship(ClientRelationshipKind::ManyToMany, child), - 83 - ); - assert_eq!(w.aggregate(child), 15); - assert_eq!(w.aggregate_nodes(child), 76); - assert_eq!(w.aggregate_nodes(0), 2); - assert_eq!(w.root(ClientRootKind::List, child), 89); - assert_eq!(w.root(ClientRootKind::ByPk, child), 21); - assert_eq!(w.root(ClientRootKind::Aggregate, child), 15); - assert_eq!(w.root(ClientRootKind::List, u64::MAX), u64::MAX); - } - - #[test] - fn default_budget_admits_one_has_many_level_and_rejects_three() { - let w = ClientComplexityWeights::current(); - let has_many = |inner| { - w.relationship( - ClientRelationshipKind::HasMany, - w.object([w.scalar, w.scalar, inner]), - ) - }; - let leaf = w.relationship( - ClientRelationshipKind::HasMany, - w.object([w.scalar, w.scalar]), - ); - let flat = w.root(ClientRootKind::List, w.object([w.scalar; 3])); - let one_nest = w.root(ClientRootKind::List, w.object([w.scalar, leaf])); - let three_nest = w.root(ClientRootKind::List, w.object([w.scalar, has_many(leaf)])); - assert!(flat < one_nest && one_nest < three_nest); - assert!(one_nest < DEFAULT_MAX_COMPLEXITY as u64, "{one_nest}"); - assert!(three_nest > DEFAULT_MAX_COMPLEXITY as u64, "{three_nest}"); + fn default_budget_admits_one_level_of_nesting_and_refuses_two() { + let page = |limit, nested| row_cost::page(limit, nested); + let max_root_one_nest = page(DEFAULT_MAX_LIMIT, page(DEFAULT_LIMIT, 0)); + let siblings = page(DEFAULT_LIMIT, 19 * page(DEFAULT_LIMIT, 0)); + let two_levels = page(DEFAULT_LIMIT, page(DEFAULT_LIMIT, page(DEFAULT_LIMIT, 0))); + let max_nest = page(DEFAULT_MAX_LIMIT, page(DEFAULT_MAX_LIMIT, 0)); + assert!(max_root_one_nest <= DEFAULT_MAX_ROWS, "{max_root_one_nest}"); + assert!(siblings <= DEFAULT_MAX_ROWS, "{siblings}"); + assert!(two_levels > DEFAULT_MAX_ROWS, "{two_levels}"); + assert!(max_nest > DEFAULT_MAX_ROWS, "{max_nest}"); } } diff --git a/src/graphql/client_manifest/mod.rs b/src/graphql/client_manifest/mod.rs index 7a0f79ba..46463209 100644 --- a/src/graphql/client_manifest/mod.rs +++ b/src/graphql/client_manifest/mod.rs @@ -27,7 +27,10 @@ use std::sync::Arc; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; -use super::complexity_contract::{DEFAULT_MAX_COMPLEXITY, DEFAULT_MAX_DEPTH}; +use super::cost::{ + DEFAULT_MAX_BOOL_WIDTH, DEFAULT_MAX_DEPTH, DEFAULT_MAX_FIELDS, DEFAULT_MAX_IN_LIST, + DEFAULT_MAX_ROWS, +}; use super::filter::{FilterExpr, Operand}; use super::naming::{aggregate_fields_type_name, aggregate_type_name}; use super::surface::{ @@ -56,7 +59,7 @@ pub use commands::{command_operation, command_status_operation}; pub use error::ClientManifestError; pub use export::{prune_client_manifest, DistributedClientSurfaceExport}; pub use identity::ClientSurfaceIdentity; -pub use limits::{ClientComplexityWeights, ClientExecutionLimits}; +pub use limits::{row_cost, ClientExecutionLimits}; pub use projections::{ CLIENT_PROJECTION_BINDING_VERSION, CLIENT_PROJECTION_PROGRAM_VERSION, COMMAND_PROJECTION_EXTENSION_VERSION, @@ -93,7 +96,4 @@ const COMMAND_EXTENSION_SLOTS_VERSION: u32 = 2; const PROJECTOR_ENTRY_VERSION: u32 = 1; const PROTOCOL_OPERATIONS_VERSION: u32 = 1; const QUERY_CAPABILITIES_VERSION: u32 = 1; -const QUERY_COMPLEXITY_VERSION: u32 = 1; const KEY_ENCODING: &str = "canonical_json_tuple_v1"; -const DEFAULT_MAX_BOOL_WIDTH: u64 = 256; -const DEFAULT_MAX_IN_LIST: u64 = 1_000; diff --git a/src/graphql/client_manifest/tests.rs b/src/graphql/client_manifest/tests.rs index 47d870b7..dd08a2d3 100644 --- a/src/graphql/client_manifest/tests.rs +++ b/src/graphql/client_manifest/tests.rs @@ -771,10 +771,16 @@ fn role_manifest_is_deterministic_and_hides_denied_identity_and_commands() { assert_eq!(first, second); assert_eq!(first.manifest_version, 2); assert_eq!(first.schema_fingerprint, second.schema_fingerprint); - assert_eq!( - first.schema_fingerprint, - "sha256:d8bb6c9435afa563ff389501f005aaeec2dce269b751de0a40b191a74cc7a615" - ); + // Stable across builds: an export built afresh from the same inputs + // carries the same fingerprint. + let rebuilt = DistributedClientSurfaceExport::from_selected( + "todos-service", + surface_for_role(&full, "user", &grants()["user"]).unwrap(), + ) + .unwrap() + .manifest() + .unwrap(); + assert_eq!(first.schema_fingerprint, rebuilt.schema_fingerprint); assert_eq!( first.protocol_fingerprint, "sha256:0dfa8a3f49e17d8d99c5c095c1ed14f528cae3e55fbc2f2b852975a50936ec5b" diff --git a/src/graphql/compile/error.rs b/src/graphql/compile/error.rs new file mode 100644 index 00000000..e7cf70c1 --- /dev/null +++ b/src/graphql/compile/error.rs @@ -0,0 +1,89 @@ +//! Why a selection did not compile. +//! +//! The variant, not the message, decides what the client sees: each one maps +//! to a fixed `extensions.code` and a fixed short message +//! ([`CompileError::client_code`], [`CompileError::client_message`]). The +//! detail strings are for logs and tests; they never reach the client, so they +//! may name SQL, columns or limits. + +use std::fmt; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum CompileError { + /// Selection, relationship or filter nesting beyond `max_depth`. + TooDeep, + /// The statement could produce more rows than `max_rows` (see the cost + /// model in `docs/graphql-query-cost.md`). + TooManyRows { rows: u64, max_rows: u64 }, + /// An `_in`/`_nin` list longer than `max_in_list`, or an `_and`/`_or` + /// list wider than `max_bool_width`. + ListTooLong(String), + /// A response key (alias) that is not a GraphQL name. + InvalidResponseKey(String), + /// An unknown, ungranted or ambiguous `where` / `order_by` entry, or a + /// comparison the dialect does not support. + InvalidFilter(String), + /// A read the model's cell-by-key store cannot serve. + UnsupportedOnCellStore(String), + /// Any other request the compiler refuses (a malformed argument value, a + /// missing primary key, a claim the session lacks). + BadRequest(String), + /// The compiler reached something the per-privilege schema should never + /// have offered: a server fault, not the request's. + Internal(String), +} + +impl CompileError { + pub(crate) fn internal(detail: impl Into) -> Self { + Self::Internal(detail.into()) + } + + /// GraphQL `extensions.code`. + pub fn client_code(&self) -> &'static str { + match self { + Self::Internal(_) => "INTERNAL", + _ => "BAD_REQUEST", + } + } + + /// The client message: stable per variant and free of request detail. + pub fn client_message(&self) -> &'static str { + match self { + Self::TooDeep => "max depth exceeded", + Self::TooManyRows { .. } => "row budget exceeded", + Self::ListTooLong(_) => "list too long", + Self::InvalidResponseKey(_) => "invalid response key", + Self::InvalidFilter(_) => "invalid filter", + Self::UnsupportedOnCellStore(_) => "unsupported on cell store", + Self::BadRequest(_) => "bad request", + Self::Internal(_) => "internal error", + } + } +} + +impl fmt::Display for CompileError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::TooDeep => f.write_str("max depth exceeded"), + Self::TooManyRows { rows, max_rows } => { + write!(f, "query may return {rows} rows, max_rows is {max_rows}") + } + Self::ListTooLong(detail) + | Self::InvalidResponseKey(detail) + | Self::InvalidFilter(detail) + | Self::UnsupportedOnCellStore(detail) + | Self::BadRequest(detail) => f.write_str(detail), + Self::Internal(detail) => write!(f, "internal: {detail}"), + } + } +} + +impl std::error::Error for CompileError {} + +/// Helpers below the compiler (bind conversion, join keys, evidence plans) +/// report plain strings: a request they cannot express. +impl From for CompileError { + fn from(detail: String) -> Self { + Self::BadRequest(detail) + } +} diff --git a/src/graphql/compile/evidence.rs b/src/graphql/compile/evidence.rs index 2be168f5..4142c7ca 100644 --- a/src/graphql/compile/evidence.rs +++ b/src/graphql/compile/evidence.rs @@ -90,7 +90,7 @@ struct QueryEvidenceExtraction { impl QueryEvidencePlan { pub(super) fn new(root_response_key: String, root: QueryEvidenceNode) -> Result { - validate_response_key(&root_response_key)?; + validate_response_key(&root_response_key).map_err(|e| e.to_string())?; let mut size = QueryEvidencePlanSize::default(); root.validate(&mut size)?; Ok(Self { @@ -173,8 +173,8 @@ impl QueryEvidenceNode { let mut response_keys = std::collections::BTreeSet::new(); for field in &object.fields { - validate_response_key(&field.storage_key)?; - validate_response_key(&field.response_key)?; + validate_response_key(&field.storage_key).map_err(|e| e.to_string())?; + validate_response_key(&field.response_key).map_err(|e| e.to_string())?; if !response_keys.insert(field.response_key.as_str()) { return Err(format!( "query causal-evidence object repeats response key `{}`", @@ -646,13 +646,11 @@ mod query_evidence_tests { relationships: Vec::new(), kind: TableKind::ReadModel, }; - let mut binds = Vec::new(); let mut bytes_paths = Vec::new(); let (pairs, record) = record_identity_projection( SqlDialect::Sqlite, &schema, "t7", - &mut binds, &mut bytes_paths, "childrenAlias", ) @@ -671,15 +669,9 @@ mod query_evidence_tests { assert!(sql.contains(QUERY_EVIDENCE_HIDDEN_PREFIX), "{sql}"); assert!(!sql.contains("'visible'"), "{sql}"); - let (postgres_pairs, _) = record_identity_projection( - SqlDialect::Postgres, - &schema, - "t7", - &mut Vec::new(), - &mut Vec::new(), - "", - ) - .unwrap(); + let (postgres_pairs, _) = + record_identity_projection(SqlDialect::Postgres, &schema, "t7", &mut Vec::new(), "") + .unwrap(); assert_eq!(postgres_pairs[0].1, "t7.\"sequence_id\""); assert!( postgres_pairs[1].1.contains("replace(encode(") diff --git a/src/graphql/compile/filter.rs b/src/graphql/compile/filter.rs index 2c08a6c7..374b05ee 100644 --- a/src/graphql/compile/filter.rs +++ b/src/graphql/compile/filter.rs @@ -8,6 +8,7 @@ use super::super::engine::EngineInner; use super::binds::{operand_to_bind, value_to_bind, BindValue}; use super::dialect::{comparison_operand, placeholder, text_pattern, SqlDialect}; use super::scan::{relationship_link, ModelScan, ScanLink}; +use super::CompileError; impl ModelScan<'_> { /// `FROM "table" alias [JOIN …] WHERE [link AND] (row policy AND where)`. @@ -23,9 +24,9 @@ impl ModelScan<'_> { binds: &mut Vec, tables: &mut Vec, depth: usize, - ) -> Result { + ) -> Result { if depth > self.inner.max_depth { - return Err("max depth exceeded".into()); + return Err(CompileError::TooDeep); } let mut preds = Vec::new(); if let Some(policy) = self.grant.row_policy.filter() { @@ -41,7 +42,7 @@ impl ModelScan<'_> { )?); } if let Some(client_where) = client_where { - preds.push(compile_client_where( + preds.extend(compile_client_where( *self, client_where, alias, @@ -76,7 +77,7 @@ fn compile_filter_expr( binds: &mut Vec, tables: &mut Vec, depth: usize, -) -> Result { +) -> Result { match expr { FilterExpr::And(xs) => { if xs.is_empty() { @@ -116,7 +117,9 @@ fn compile_filter_expr( let col_ref = format!("{alias}.\"{column}\""); if matches!(op, CmpOp::Like | CmpOp::Ilike) { let BindValue::Text(pattern) = bind else { - return Err("a pattern comparison requires a string".into()); + return Err(CompileError::BadRequest( + "a pattern comparison requires a string".into(), + )); }; return compile_text_pattern( inner.dialect, @@ -174,11 +177,11 @@ fn compile_filter_expr( }); } if values.len() > inner.max_in_list { - return Err(format!( + return Err(CompileError::ListTooLong(format!( "_in list length {} exceeds max_in_list {}", values.len(), inner.max_in_list - )); + ))); } let col = schema .columns @@ -244,6 +247,8 @@ fn compile_filter_expr( } } +/// The predicate a client `where` adds, or `None` when it adds nothing (an +/// empty object, or only soft-skipped keys). fn compile_client_where( scan: ModelScan<'_>, value: &Value, @@ -251,28 +256,32 @@ fn compile_client_where( binds: &mut Vec, tables: &mut Vec, depth: usize, -) -> Result { - let (inner, session, schema) = (scan.inner, scan.session, scan.schema); +) -> Result, CompileError> { + let (inner, schema) = (scan.inner, scan.schema); if depth > inner.max_depth { - return Err("max depth exceeded".into()); + return Err(CompileError::TooDeep); } let Value::Object(map) = value else { - return Ok("TRUE".into()); + return Ok(None); + }; + let bool_list = |key: &str, items: &Vec| -> Result<(), CompileError> { + if items.len() > inner.max_bool_width { + return Err(CompileError::ListTooLong(format!( + "{key} list length {} exceeds max_bool_width {}", + items.len(), + inner.max_bool_width + ))); + } + Ok(()) }; let mut preds = Vec::new(); for (key, val) in map { match key.as_str() { "_and" => { if let Value::List(items) = val { - if items.len() > inner.max_bool_width { - return Err(format!( - "_and list length {} exceeds max_bool_width {}", - items.len(), - inner.max_bool_width - )); - } + bool_list("_and", items)?; for item in items { - preds.push(compile_client_where( + preds.extend(compile_client_where( scan, item, alias, @@ -285,23 +294,15 @@ fn compile_client_where( } "_or" => { if let Value::List(items) = val { - if items.len() > inner.max_bool_width { - return Err(format!( - "_or list length {} exceeds max_bool_width {}", - items.len(), - inner.max_bool_width - )); - } + bool_list("_or", items)?; let mut parts = Vec::new(); for item in items { - parts.push(compile_client_where( - scan, - item, - alias, - binds, - tables, - depth + 1, - )?); + // An empty disjunct matches every row, so the whole + // `_or` does. + match compile_client_where(scan, item, alias, binds, tables, depth + 1)? { + Some(part) => parts.push(part), + None => parts.push("TRUE".into()), + } } if !parts.is_empty() { preds.push(format!("({})", parts.join(" OR "))); @@ -309,16 +310,22 @@ fn compile_client_where( } } "_not" => { - preds.push(format!( - "NOT ({})", - compile_client_where(scan, val, alias, binds, tables, depth + 1,)? - )); + if let Some(inner_pred) = + compile_client_where(scan, val, alias, binds, tables, depth + 1)? + { + preds.push(format!("NOT ({inner_pred})")); + } else { + // `NOT (TRUE)`: an empty `_not` matches no row. + preds.push("FALSE".into()); + } } col_name => { if let Some(col) = schema.columns.iter().find(|c| c.column_name == *col_name) { if !scan.allows_column(col_name) { if inner.strict_where { - return Err(format!("ungranted where column `{col_name}`")); + return Err(CompileError::InvalidFilter(format!( + "ungranted where column `{col_name}`" + ))); } continue; } @@ -326,7 +333,6 @@ fn compile_client_where( for (op, rhs) in ops { preds.push(compile_client_op( inner, - session, col_name, &col.column_type, op, @@ -346,7 +352,9 @@ fn compile_client_where( // bypassed by a source-model predicate. let Some(target) = scan.target(rel) else { if inner.strict_where { - return Err(format!("ungranted where relationship `{col_name}`")); + return Err(CompileError::InvalidFilter(format!( + "ungranted where relationship `{col_name}`" + ))); } continue; }; @@ -373,34 +381,33 @@ fn compile_client_where( )? )); } else if inner.strict_where { - return Err(format!("unknown where field `{col_name}`")); + return Err(CompileError::InvalidFilter(format!( + "unknown where field `{col_name}`" + ))); } // soft-skip: ignore unknown keys when strict_where is false } } } - if preds.is_empty() { - Ok("TRUE".into()) - } else { - Ok(format!("({})", preds.join(" AND "))) - } + Ok((!preds.is_empty()).then(|| format!("({})", preds.join(" AND ")))) } fn compile_client_op( inner: &EngineInner, - _session: &Session, column: &str, column_type: &ColumnType, op: &str, rhs: &Value, alias: &str, binds: &mut Vec, -) -> Result { +) -> Result { let col_ref = format!("{alias}.\"{column}\""); match op { "_icontains" => { let Value::String(text) = rhs else { - return Err("_icontains requires a string".into()); + return Err(CompileError::BadRequest( + "_icontains requires a string".into(), + )); }; // Use an explicit escape character on both dialects. The operand // stays a bind parameter; user text never becomes SQL or a wildcard. @@ -416,7 +423,7 @@ fn compile_client_op( } "_like" | "_ilike" => { let Value::String(pattern) = rhs else { - return Err(format!("{op} requires a string")); + return Err(CompileError::BadRequest(format!("{op} requires a string"))); }; compile_text_pattern(inner.dialect, &col_ref, pattern, '\\', op == "_like", binds) } @@ -430,7 +437,7 @@ fn compile_client_op( } "_in" | "_nin" => { let Value::List(items) = rhs else { - return Err(format!("{op} requires a list")); + return Err(CompileError::BadRequest(format!("{op} requires a list"))); }; if items.is_empty() { return Ok(if op == "_in" { @@ -440,11 +447,11 @@ fn compile_client_op( }); } if items.len() > inner.max_in_list { - return Err(format!( + return Err(CompileError::ListTooLong(format!( "{op} list length {} exceeds max_in_list {}", items.len(), inner.max_in_list - )); + ))); } let mut phs = Vec::new(); for item in items { @@ -478,7 +485,11 @@ fn compile_client_op( require_postgres_json_op(inner.dialect, "_has_key")?; "?" } - _ => return Err(format!("unknown comparison op `{other}`")), + _ => { + return Err(CompileError::InvalidFilter(format!( + "unknown comparison op `{other}`" + ))) + } }; let ph = comparand(inner.dialect, value_to_bind(rhs, column_type)?, binds); let cast_ph = cast_placeholder(inner.dialect, column_type, &ph); @@ -495,14 +506,13 @@ fn compile_client_op( } /// Postgres jsonb operators are not emitted on SQLite (would confuse the driver -/// and risk opaque execute errors). Message must stay free of SQL fragments so -/// [`super::schema::sanitize_compile_error`] maps to a stable client code. -fn require_postgres_json_op(dialect: SqlDialect, op: &str) -> Result<(), String> { +/// and risk opaque execute errors). +fn require_postgres_json_op(dialect: SqlDialect, op: &str) -> Result<(), CompileError> { match dialect { SqlDialect::Postgres => Ok(()), - SqlDialect::Sqlite => Err(format!( - "unknown comparison op `{op}` is not supported on sqlite" - )), + SqlDialect::Sqlite => Err(CompileError::InvalidFilter(format!( + "comparison op `{op}` is not supported on sqlite" + ))), } } @@ -514,7 +524,7 @@ fn compile_text_pattern( escape: char, case_sensitive: bool, binds: &mut Vec, -) -> Result { +) -> Result { let ph = placeholder(dialect, binds.len() + 1); let (sql, bind) = text_pattern(dialect, col_ref, &ph, pattern, escape, case_sensitive)?; binds.push(BindValue::Text(bind)); diff --git a/src/graphql/compile/mod.rs b/src/graphql/compile/mod.rs index 4e0f4112..a91c13d4 100644 --- a/src/graphql/compile/mod.rs +++ b/src/graphql/compile/mod.rs @@ -18,6 +18,7 @@ mod binds; mod dialect; +mod error; mod evidence; mod filter; mod projection; @@ -25,15 +26,11 @@ mod relationship; mod scan; pub use binds::BindValue; -#[allow(unused_imports)] -pub use dialect::{DialectOps, SqlDialect}; -#[allow(unused_imports)] +pub use dialect::SqlDialect; +pub use error::CompileError; pub use projection::{ - compile_query, compile_root, selection_from_field, QueryPlan, RootKind, SelectionNode, SqlPlan, + compile_query, selection_from_field, QueryPlan, RootKind, SelectionNode, SqlPlan, }; -#[allow(unused_imports)] -pub(crate) use dialect::{join_predicate_direct, join_predicate_m2m_pairs}; -#[allow(unused_imports)] -pub(crate) use evidence::{ExtractedQueryEvidence, QueryRecordEvidence, QueryResponsePathSegment}; +pub(crate) use evidence::{ExtractedQueryEvidence, QueryResponsePathSegment}; pub(crate) use projection::cell_row_matches; diff --git a/src/graphql/compile/projection.rs b/src/graphql/compile/projection.rs index 15fd2590..b1e24df2 100644 --- a/src/graphql/compile/projection.rs +++ b/src/graphql/compile/projection.rs @@ -1,4 +1,5 @@ use std::collections::BTreeMap; +use std::sync::Arc; use async_graphql::Value; use serde_json::Value as JsonValue; @@ -18,10 +19,12 @@ use super::evidence::{ }; use super::relationship::{compile_relationship_aggregate_subquery, compile_relationship_subquery}; use super::scan::{value_as_u64, ModelScan, ScanLink}; +use super::CompileError; #[derive(Clone, Debug)] pub struct SqlPlan { - pub sql: String, + /// Shared with every execution, so running the plan copies no SQL. + pub sql: Arc, pub binds: Vec, /// JSON paths (dot-separated response keys) that need hex→base64 rewrite (SQLite Bytes). pub bytes_hex_paths: Vec, @@ -44,6 +47,26 @@ impl SqlPlan { ) -> Result { self.evidence.extract_and_strip(value) } + + /// What makes two executions comparable snapshots of one query: the same + /// statement over the same binds and tables. + pub(crate) fn snapshot_scope(&self) -> impl serde::Serialize + '_ { + #[derive(serde::Serialize)] + struct QueryPlanInstance<'a> { + domain: &'static str, + version: u32, + sql: &'a str, + binds: &'a [BindValue], + tables: &'a [String], + } + QueryPlanInstance { + domain: "distributed.graphql.query-plan-instance", + version: 1, + sql: &self.sql, + binds: &self.binds, + tables: &self.tables_touched, + } + } } #[derive(Clone, Debug)] @@ -59,7 +82,9 @@ type RecordEvidenceProjection = (Vec<(String, String)>, Option), CellByKey { model: String, pk: BTreeMap, @@ -76,16 +101,16 @@ pub fn compile_query( model_name: &str, kind: RootKind, selection: &SelectionNode, -) -> Result { +) -> Result { let store = inner .read_stores .get(model_name) .copied() .unwrap_or(crate::graphql::read_store::ReadStoreKind::SqlScan); match store { - crate::graphql::read_store::ReadStoreKind::SqlScan => Ok(QueryPlan::Sql(compile_root( - inner, session, role, model_name, kind, selection, - )?)), + crate::graphql::read_store::ReadStoreKind::SqlScan => Ok(QueryPlan::Sql(Arc::new( + compile_root(inner, session, role, model_name, kind, selection)?, + ))), crate::graphql::read_store::ReadStoreKind::CellByKey => { compile_cell_by_key(inner, session, role, model_name, kind, selection) } @@ -99,29 +124,28 @@ fn compile_cell_by_key( model_name: &str, kind: RootKind, selection: &SelectionNode, -) -> Result { +) -> Result { + let unsupported = |detail: &str| Err(CompileError::UnsupportedOnCellStore(detail.into())); let scan = ModelScan::open(inner, session, role, model_name)?; let schema = scan.schema; match kind { RootKind::List => { - return Err( - "cell-by-key store does not support list queries (would fan out to N cells); declare a SQL index read model" - .into(), + return unsupported( + "cell-by-key store does not support list queries (would fan out to N cells); declare a SQL index read model", ); } RootKind::Aggregate => { - return Err( - "cell-by-key store does not support aggregate queries; declare a SQL index read model" - .into(), + return unsupported( + "cell-by-key store does not support aggregate queries; declare a SQL index read model", ); } RootKind::ByPk => {} } if selection.args.contains_key("where") { - return Err("cell-by-key store does not support filter".into()); + return unsupported("cell-by-key store does not support filter"); } if selection.args.contains_key("order_by") { - return Err("cell-by-key store does not support sort".into()); + return unsupported("cell-by-key store does not support sort"); } for child in &selection.children { let is_join = schema.relationships.iter().any(|rel| { @@ -129,18 +153,17 @@ fn compile_cell_by_key( || child.field_name == format!("{}_aggregate", rel.field_name) }); if is_join { - return Err( - "cell-by-key store does not support SQL joins; declare a SQL index read model" - .into(), + return unsupported( + "cell-by-key store does not support SQL joins; declare a SQL index read model", ); } // The cell resolver returns stored fields by name: nothing else // stands between a selection and an ungranted column. if child.field_name != "__typename" && !scan.allows_column(&child.field_name) { - return Err(format!( - "internal: selection reached ungranted field `{}` on `{model_name}`", + return Err(CompileError::internal(format!( + "selection reached ungranted field `{}` on `{model_name}`", child.field_name - )); + ))); } } let row_filter = scan @@ -159,9 +182,9 @@ fn compile_cell_by_key( Value::String(s) => s.clone(), Value::Number(n) => n.to_string(), other => { - return Err(format!( + return Err(CompileError::UnsupportedOnCellStore(format!( "cell-by-key primary key `{column}` must be a scalar, got {other:?}" - )); + ))); } }; pk.insert(column.clone(), key); @@ -179,7 +202,7 @@ fn resolve_cell_row_filter( schema: &TableSchema, session: &Session, filter: &FilterExpr, -) -> Result { +) -> Result { Ok(match filter { FilterExpr::And(items) => FilterExpr::And( items @@ -215,9 +238,9 @@ fn resolve_cell_row_filter( ColumnType::Integer | ColumnType::UnsignedInteger | ColumnType::Float ) => {} _ => { - return Err(format!( + return Err(CompileError::UnsupportedOnCellStore(format!( "cell-by-key row policy operator `{op:?}` is unsupported for column `{column}`" - )); + ))); } } FilterExpr::Cmp { @@ -241,9 +264,9 @@ fn resolve_cell_row_filter( | ColumnType::UnsignedInteger | ColumnType::Float ) { - return Err(format!( + return Err(CompileError::UnsupportedOnCellStore(format!( "cell-by-key row policy IN is unsupported for column `{column}`" - )); + ))); } FilterExpr::In { column: column.clone(), @@ -262,9 +285,9 @@ fn resolve_cell_row_filter( } } FilterExpr::Rel { field, .. } => { - return Err(format!( + return Err(CompileError::UnsupportedOnCellStore(format!( "cell-by-key row policy cannot traverse relationship `{field}`" - )); + ))); } }) } @@ -284,21 +307,23 @@ fn resolve_cell_operand( operand: &Operand, session: &Session, column_type: &ColumnType, -) -> Result { +) -> Result { let literal = match operand_to_bind(operand, session, column_type)? { BindValue::Null => LitValue::Null, BindValue::Bool(value) => LitValue::Bool(value), BindValue::I64(value) => LitValue::I64(value), BindValue::F64(value) if value.is_finite() => LitValue::F64(value), BindValue::F64(value) => { - return Err(format!( + return Err(CompileError::UnsupportedOnCellStore(format!( "cell-by-key row-policy float `{value}` must be finite" - )); + ))); } BindValue::Text(value) => LitValue::String(value), BindValue::Json(value) => LitValue::Json(value), BindValue::Bytes(_) => { - return Err("cell-by-key row policies do not support byte operands".into()); + return Err(CompileError::UnsupportedOnCellStore( + "cell-by-key row policies do not support byte operands".into(), + )); } }; Ok(Operand::Lit(literal)) @@ -316,6 +341,9 @@ pub(crate) fn cell_row_matches(schema: &TableSchema, filter: &FilterExpr, row: & } /// Compile a root field selection into one SQL statement. +/// +/// Refuses a statement that could produce more than `max_rows` rows: see +/// [`Rows`] for how they are counted. pub fn compile_root( inner: &EngineInner, session: &Session, @@ -323,17 +351,7 @@ pub fn compile_root( model_name: &str, kind: RootKind, selection: &SelectionNode, -) -> Result { - // Relationship-aware complexity before SQL (covers query + subscription paths). - let cost = - super::super::complexity::estimate_root_complexity(inner, model_name, kind, selection)?; - if super::super::complexity::exceeds_budget(cost, inner.max_complexity) { - return Err(format!( - "query too complex (estimated {cost}, max {})", - inner.max_complexity - )); - } - +) -> Result { let scan = ModelScan::open(inner, session, role, model_name)?; let mut binds = Vec::new(); let mut bytes_paths = Vec::new(); @@ -341,9 +359,9 @@ pub fn compile_root( let alias = "t0"; let root = ScanLink::default(); - let (sql, evidence_root) = match kind { + let (sql, evidence_root, rows) = match kind { RootKind::List => { - let (page, evidence) = compile_page( + let (page, evidence, rows) = compile_page( scan, selection, &selection.args, @@ -358,12 +376,13 @@ pub fn compile_root( ( page, QueryEvidenceNode::List(Box::new(QueryEvidenceNode::Object(evidence))), + rows, ) } RootKind::ByPk => { // Binds are positional: the projection's (nested LIMIT/OFFSET) // come first in the statement text, then the key, then the WHERE. - let (projection, evidence) = compile_object_projection( + let (projection, evidence, nested) = compile_object_projection( scan, selection, alias, @@ -384,7 +403,7 @@ pub fn compile_root( .columns .iter() .find(|c| c.column_name == *pk) - .ok_or_else(|| format!("pk column `{pk}` missing"))?; + .ok_or_else(|| CompileError::internal(format!("pk column `{pk}` missing")))?; binds.push(value_to_bind(value, &column.column_type)?); let ph = placeholder(inner.dialect, binds.len()); key.push(format!("{alias}.\"{pk}\" = {ph}")); @@ -404,10 +423,11 @@ pub fn compile_root( ( format!("SELECT {projection} {rows} LIMIT 1"), QueryEvidenceNode::Object(evidence), + Rows::one(nested), ) } RootKind::Aggregate => { - let (object, evidence) = compile_aggregate( + let (object, evidence, rows) = compile_aggregate( scan, selection, alias, @@ -418,13 +438,20 @@ pub fn compile_root( "", 0, )?; - (format!("SELECT {object}"), evidence) + (format!("SELECT {object}"), evidence, rows) } }; - let evidence = QueryEvidencePlan::new(selection.response_key.clone(), evidence_root)?; + if rows.0 > inner.max_rows { + return Err(CompileError::TooManyRows { + rows: rows.0, + max_rows: inner.max_rows, + }); + } + let evidence = QueryEvidencePlan::new(selection.response_key.clone(), evidence_root) + .map_err(CompileError::Internal)?; Ok(SqlPlan { - sql, + sql: sql.into(), binds, bytes_hex_paths: bytes_paths, tables_touched: tables, @@ -432,6 +459,28 @@ pub fn compile_root( }) } +/// The most model rows one evaluation of a compiled expression can produce: +/// the query cost the engine bounds by `max_rows`, counted with +/// [`row_cost`](crate::graphql::row_cost) from each list's resolved limit. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) struct Rows(u64); + +impl Rows { + /// A page of up to `limit` rows, each carrying `nested`. + fn page(limit: u64, nested: Rows) -> Rows { + Rows(crate::graphql::row_cost::page(limit, nested.0)) + } + + /// One row carrying `nested`. + pub(super) fn one(nested: Rows) -> Rows { + Rows(crate::graphql::row_cost::one(nested.0)) + } + + fn add(self, other: Rows) -> Rows { + Rows(self.0.saturating_add(other.0)) + } +} + #[derive(Clone, Copy)] pub enum RootKind { List, @@ -439,11 +488,13 @@ pub enum RootKind { Aggregate, } -pub(super) fn validate_response_key(key: &str) -> Result<(), String> { +pub(super) fn validate_response_key(key: &str) -> Result<(), CompileError> { if is_valid_graphql_name(key) { Ok(()) } else { - Err(format!("invalid GraphQL response key `{key}`")) + Err(CompileError::InvalidResponseKey(format!( + "invalid GraphQL response key `{key}`" + ))) } } @@ -460,11 +511,11 @@ pub(super) fn compile_page( tables: &mut Vec, path_prefix: &str, depth: usize, -) -> Result<(String, QueryEvidenceObjectPlan), String> { +) -> Result<(String, QueryEvidenceObjectPlan, Rows), CompileError> { let dialect = scan.inner.dialect; let ops = dialect.ops(); let order_sql = scan.order_by(args.get("order_by"), alias)?; - let (projection, evidence) = compile_object_projection( + let (projection, evidence, nested) = compile_object_projection( scan, fields, alias, @@ -475,8 +526,9 @@ pub(super) fn compile_page( depth, )?; let rows = scan.visible_rows(alias, link, args.get("where"), binds, tables, depth)?; - binds.push(BindValue::I64(scan.limit(args.get("limit")) as i64)); - let limit = placeholder(dialect, binds.len()); + let limit = scan.limit(args.get("limit")); + binds.push(BindValue::I64(i64::try_from(limit).unwrap_or(i64::MAX))); + let limit_ph = placeholder(dialect, binds.len()); binds.push(BindValue::I64( args.get("offset").and_then(value_as_u64).unwrap_or(0) as i64, )); @@ -487,10 +539,11 @@ pub(super) fn compile_page( }; Ok(( format!( - "SELECT coalesce({}({row}), {}) FROM (\n SELECT {projection} AS r\n {rows}\n {order_sql}\n LIMIT {limit} OFFSET {offset}\n) page", + "SELECT coalesce({}({row}), {}) FROM (\n SELECT {projection} AS r\n {rows}\n {order_sql}\n LIMIT {limit_ph} OFFSET {offset}\n) page", ops.json_agg, ops.empty_array ), evidence, + Rows::page(limit, nested), )) } @@ -505,16 +558,17 @@ pub(super) fn compile_aggregate( tables: &mut Vec, path_prefix: &str, depth: usize, -) -> Result<(String, QueryEvidenceNode), String> { +) -> Result<(String, QueryEvidenceNode, Rows), CompileError> { if !scan.aggregations() { - return Err(format!( - "internal: aggregate reached `{}` without an aggregations grant", + return Err(CompileError::internal(format!( + "aggregate reached `{}` without an aggregations grant", scan.schema.model_name - )); + ))); } let dialect = scan.inner.dialect; let mut pairs = Vec::new(); let mut evidence_fields = Vec::new(); + let mut rows = Rows::default(); for member in &selection.children { match member.field_name.as_str() { "__typename" => {} @@ -540,9 +594,9 @@ pub(super) fn compile_aggregate( )); } _ => { - return Err( + return Err(CompileError::BadRequest( "aggregate fields selection contains an unsupported member".into(), - ); + )); } } } @@ -558,7 +612,7 @@ pub(super) fn compile_aggregate( } else { format!("{path_prefix}.{}", member.response_key) }; - let (page, evidence) = compile_page( + let (page, evidence, page_rows) = compile_page( scan, member, &selection.args, @@ -570,6 +624,7 @@ pub(super) fn compile_aggregate( &nodes_path, depth, )?; + rows = rows.add(page_rows); pairs.push(( member.response_key.clone(), dialect.ops().nested_json(format!("({page})")), @@ -583,7 +638,9 @@ pub(super) fn compile_aggregate( }); } _ => { - return Err("aggregate selection contains an unsupported member".into()); + return Err(CompileError::BadRequest( + "aggregate selection contains an unsupported member".into(), + )); } } } @@ -593,11 +650,13 @@ pub(super) fn compile_aggregate( record: None, fields: evidence_fields, }), + rows, )) } /// The JSON object for one row of `scan`: its selected columns and nested -/// relationships, plus the hidden identity the causal evidence needs. +/// relationships, plus the hidden identity the causal evidence needs. Also +/// returns the rows nested under that one row. pub(super) fn compile_object_projection( scan: ModelScan<'_>, selection: &SelectionNode, @@ -607,14 +666,15 @@ pub(super) fn compile_object_projection( tables: &mut Vec, path_prefix: &str, depth: usize, -) -> Result<(String, QueryEvidenceObjectPlan), String> { +) -> Result<(String, QueryEvidenceObjectPlan, Rows), CompileError> { let (inner, schema) = (scan.inner, scan.schema); if depth > inner.max_depth { - return Err("max depth exceeded".into()); + return Err(CompileError::TooDeep); } let (mut pairs, record) = - compile_record_evidence_projection(scan, alias, binds, bytes_paths, path_prefix)?; + compile_record_evidence_projection(scan, alias, bytes_paths, path_prefix)?; let mut evidence_fields = Vec::new(); + let mut nested = Rows::default(); let path = |response_key: &str| { if path_prefix.is_empty() { response_key.to_string() @@ -624,10 +684,9 @@ pub(super) fn compile_object_projection( }; let column_pair = |column: &crate::table::TableColumn, response_key: &str, - binds: &mut Vec, bytes_paths: &mut Vec| - -> Result<(String, String), String> { - let expr = column_json_expr(inner.dialect, alias, column, binds)?; + -> Result<(String, String), CompileError> { + let expr = column_json_expr(inner.dialect, alias, column); if matches!(column.column_type, ColumnType::Bytes) && matches!(inner.dialect, SqlDialect::Sqlite) { @@ -641,12 +700,7 @@ pub(super) fn compile_object_projection( if selection.children.is_empty() { for column in schema.columns.iter().filter(|c| !c.skipped) { if scan.allows_column(&column.column_name) { - pairs.push(column_pair( - column, - &column.column_name, - binds, - bytes_paths, - )?); + pairs.push(column_pair(column, &column.column_name, bytes_paths)?); } } } @@ -661,21 +715,16 @@ pub(super) fn compile_object_projection( { // The per-privilege schema never offers an ungranted column. if !scan.allows_column(&column.column_name) { - return Err(format!( - "internal: selection reached ungranted column `{}` on `{}`", + return Err(CompileError::internal(format!( + "selection reached ungranted column `{}` on `{}`", column.column_name, schema.model_name - )); + ))); } - pairs.push(column_pair( - column, - &child.response_key, - binds, - bytes_paths, - )?); + pairs.push(column_pair(column, &child.response_key, bytes_paths)?); continue; } let relationship = |name: &str| schema.relationships.iter().find(|r| r.field_name == name); - let (sub, evidence) = if let Some(rel) = relationship(&child.field_name) { + let (sub, evidence, rows) = if let Some(rel) = relationship(&child.field_name) { compile_relationship_subquery( scan, alias, @@ -704,12 +753,13 @@ pub(super) fn compile_object_projection( depth + 1, )? } else { - return Err(format!( - "internal: selection reached unknown field `{}` on `{}`", + return Err(CompileError::internal(format!( + "selection reached unknown field `{}` on `{}`", child.field_name, schema.model_name - )); + ))); }; validate_response_key(&child.response_key)?; + nested = nested.add(rows); pairs.push(( child.response_key.clone(), inner.dialect.ops().nested_json(sub), @@ -727,31 +777,33 @@ pub(super) fn compile_object_projection( record, fields: evidence_fields, }, + nested, )) } pub(super) fn compile_record_evidence_projection( scan: ModelScan<'_>, alias: &str, - binds: &mut Vec, bytes_paths: &mut Vec, path_prefix: &str, -) -> Result { +) -> Result { + // Evidence is read only by the causal protocol: without it, the hidden + // identity columns would be selected only to be stripped again. // Embedded client models deliberately have no stable normalized identity. // Do not manufacture per-record evidence that the client cannot address; // table/projector dependencies still flow through `tables_touched` and // produce conservative index evidence. - if !scan.has_client_normalized_identity() { + if scan.inner.protocol.is_none() || !scan.has_client_normalized_identity() { return Ok((Vec::new(), None)); } record_identity_projection( scan.inner.dialect, scan.schema, alias, - binds, bytes_paths, path_prefix, ) + .map_err(CompileError::Internal) } /// The hidden primary-key copy that names one row in causal evidence. @@ -759,7 +811,6 @@ pub(super) fn record_identity_projection( dialect: SqlDialect, schema: &TableSchema, alias: &str, - binds: &mut Vec, bytes_paths: &mut Vec, path_prefix: &str, ) -> Result { @@ -798,7 +849,7 @@ pub(super) fn record_identity_projection( "replace(encode({alias}.\"{}\", 'base64'), E'\\n', '')", column.column_name ), - _ => column_json_expr(dialect, alias, column, binds)?, + _ => column_json_expr(dialect, alias, column), }; if matches!(column.column_type, ColumnType::Bytes) && matches!(dialect, SqlDialect::Sqlite) { @@ -828,10 +879,9 @@ pub(super) fn column_json_expr( dialect: SqlDialect, alias: &str, col: &crate::table::TableColumn, - _binds: &mut Vec, -) -> Result { +) -> String { let q = format!("{alias}.\"{}\"", col.column_name); - Ok(match (&col.column_type, dialect) { + match (&col.column_type, dialect) { (ColumnType::Timestamp, SqlDialect::Postgres) => format!("{q}::text"), (ColumnType::Bytes, SqlDialect::Postgres) => format!("encode({q}, 'base64')"), (ColumnType::Bytes, SqlDialect::Sqlite) => format!("hex({q})"), @@ -839,7 +889,7 @@ pub(super) fn column_json_expr( // so the enclosing object embeds it as JSON, not as a string. (ColumnType::Json, SqlDialect::Sqlite) => format!("json({q})"), _ => q, - }) + } } pub(super) fn chunked_json_object(dialect: SqlDialect, pairs: &[(String, String)]) -> String { diff --git a/src/graphql/compile/relationship.rs b/src/graphql/compile/relationship.rs index 700fa0d4..098b67c3 100644 --- a/src/graphql/compile/relationship.rs +++ b/src/graphql/compile/relationship.rs @@ -3,9 +3,10 @@ use crate::table::{RelationshipDef, RelationshipKind}; use super::binds::BindValue; use super::evidence::QueryEvidenceNode; use super::projection::{ - compile_aggregate, compile_object_projection, compile_page, SelectionNode, + compile_aggregate, compile_object_projection, compile_page, Rows, SelectionNode, }; use super::scan::ModelScan; +use super::CompileError; /// `_aggregate { aggregate { count } nodes { … } }` under `source`'s row. pub(super) fn compile_relationship_aggregate_subquery( @@ -18,9 +19,11 @@ pub(super) fn compile_relationship_aggregate_subquery( tables: &mut Vec, path_prefix: &str, depth: usize, -) -> Result<(String, QueryEvidenceNode), String> { +) -> Result<(String, QueryEvidenceNode, Rows), CompileError> { if matches!(rel.kind, RelationshipKind::BelongsTo) { - return Err("belongs_to aggregate is not supported".into()); + return Err(CompileError::BadRequest( + "belongs_to aggregate is not supported".into(), + )); } let alias = format!("ta{depth}"); let (target, link) = @@ -50,11 +53,11 @@ pub(super) fn compile_relationship_subquery( tables: &mut Vec, path_prefix: &str, depth: usize, -) -> Result<(String, QueryEvidenceNode), String> { +) -> Result<(String, QueryEvidenceNode, Rows), CompileError> { let alias = format!("t{depth}"); let (target, link) = source.related(rel, source_alias, &alias, &format!("j{depth}"), tables)?; if matches!(rel.kind, RelationshipKind::BelongsTo) { - let (projection, evidence) = compile_object_projection( + let (projection, evidence, nested) = compile_object_projection( target, selection, &alias, @@ -75,9 +78,10 @@ pub(super) fn compile_relationship_subquery( return Ok(( format!("(SELECT {projection} {rows} LIMIT 1)"), QueryEvidenceNode::Object(evidence), + Rows::one(nested), )); } - let (page, evidence) = compile_page( + let (page, evidence, rows) = compile_page( target, selection, &selection.args, @@ -92,5 +96,6 @@ pub(super) fn compile_relationship_subquery( Ok(( format!("({page})"), QueryEvidenceNode::List(Box::new(QueryEvidenceNode::Object(evidence))), + rows, )) } diff --git a/src/graphql/compile/scan.rs b/src/graphql/compile/scan.rs index 4ec2d136..173e981d 100644 --- a/src/graphql/compile/scan.rs +++ b/src/graphql/compile/scan.rs @@ -16,6 +16,7 @@ use crate::table::{ use super::super::engine::EngineInner; use super::dialect::{join_predicate_direct, join_predicate_m2m_pairs, SqlDialect}; +use super::CompileError; /// Ties a scan to what encloses it: an optional `JOIN` (many-to-many through /// table) and the predicate selecting the enclosing row's related rows, or one @@ -43,7 +44,7 @@ impl<'a> ModelScan<'a> { session: &'a Session, role: &'a str, model_name: &str, - ) -> Result { + ) -> Result { let entry = inner .catalog .get(model_name) @@ -79,12 +80,12 @@ impl<'a> ModelScan<'a> { target_alias: &str, join_alias: &str, tables: &mut Vec, - ) -> Result<(ModelScan<'a>, ScanLink), String> { + ) -> Result<(ModelScan<'a>, ScanLink), CompileError> { let target = self.target(rel).ok_or_else(|| { - format!( - "internal: relationship `{}` reached ungranted model `{}`", + CompileError::internal(format!( + "relationship `{}` reached ungranted model `{}`", rel.field_name, rel.target_model - ) + )) })?; let link = relationship_link( self.inner, @@ -126,7 +127,7 @@ impl<'a> ModelScan<'a> { &self, order_arg: Option<&Value>, alias: &str, - ) -> Result { + ) -> Result { compile_order_by( self.schema, order_arg, @@ -149,35 +150,40 @@ pub(super) fn relationship_link( target_alias: &str, join_alias: &str, tables: &mut Vec, -) -> Result { +) -> Result { tables.push(target.table_name.clone()); match rel.kind { RelationshipKind::HasMany | RelationshipKind::BelongsTo => { - let pairs = - resolve_direct_join_keys(source, rel, target).map_err(|error| error.to_string())?; + let pairs = resolve_direct_join_keys(source, rel, target) + .map_err(|error| CompileError::internal(error.to_string()))?; Ok(ScanLink { join: String::new(), - on: join_predicate_direct(rel.kind.clone(), source_alias, target_alias, &pairs)?, + on: join_predicate_direct(rel.kind.clone(), source_alias, target_alias, &pairs) + .map_err(CompileError::Internal)?, }) } RelationshipKind::ManyToMany => { let through = rel .through .as_deref() - .ok_or_else(|| "m2m missing through".to_string())?; + .ok_or_else(|| CompileError::internal("m2m missing through"))?; let through_schema = inner .by_table .get(through) .and_then(|model| inner.catalog.get(model)) .map(|entry| &entry.schema) - .ok_or_else(|| format!("through table `{through}` not in catalog"))?; + .ok_or_else(|| { + CompileError::internal(format!("through table `{through}` not in catalog")) + })?; let keys = resolve_m2m_join_keys(source, rel, through_schema, target) - .map_err(|error| error.to_string())?; + .map_err(|error| CompileError::internal(error.to_string()))?; tables.push(through.to_string()); - let on_target = join_predicate_m2m_pairs(join_alias, target_alias, &keys.target)?; + let on_target = join_predicate_m2m_pairs(join_alias, target_alias, &keys.target) + .map_err(CompileError::Internal)?; Ok(ScanLink { join: format!(" JOIN \"{through}\" {join_alias} ON {on_target}"), - on: join_predicate_m2m_pairs(join_alias, source_alias, &keys.parent)?, + on: join_predicate_m2m_pairs(join_alias, source_alias, &keys.parent) + .map_err(CompileError::Internal)?, }) } } @@ -210,27 +216,31 @@ pub(super) fn compile_order_by( allows_column: impl Fn(&str) -> bool, strict: bool, dialect: SqlDialect, -) -> Result { +) -> Result { let mut parts = Vec::new(); if let Some(Value::List(items)) = order_arg { for item in items { if let Value::Object(map) = item { if map.len() > 1 { - return Err( + return Err(CompileError::InvalidFilter( "ambiguous order_by entry: use one field per list entry to declare priority" .into(), - ); + )); } for (col, dir) in map { if !schema.columns.iter().any(|c| c.column_name == *col) { if strict { - return Err(format!("unknown order_by column `{col}`")); + return Err(CompileError::InvalidFilter(format!( + "unknown order_by column `{col}`" + ))); } continue; } if !allows_column(col) { if strict { - return Err(format!("ungranted order_by column `{col}`")); + return Err(CompileError::InvalidFilter(format!( + "ungranted order_by column `{col}`" + ))); } continue; } @@ -325,7 +335,7 @@ mod strict_order_by_tests { let arg = order_list(vec![("nope", "asc")]); let err = compile_order_by(&schema, Some(&arg), "t0", perm, true, SqlDialect::Sqlite) .unwrap_err(); - assert!(err.contains("unknown order_by"), "{err}"); + assert!(err.to_string().contains("unknown order_by"), "{err}"); } #[test] @@ -335,7 +345,7 @@ mod strict_order_by_tests { let arg = order_list(vec![("secret", "asc")]); let err = compile_order_by(&schema, Some(&arg), "t0", perm, true, SqlDialect::Sqlite) .unwrap_err(); - assert!(err.contains("ungranted order_by"), "{err}"); + assert!(err.to_string().contains("ungranted order_by"), "{err}"); } #[test] @@ -382,8 +392,11 @@ mod strict_order_by_tests { let error = compile_order_by(&schema, Some(&arg), "t0", perm, false, SqlDialect::Sqlite) .unwrap_err(); - assert!(error.contains("ambiguous order_by"), "{error}"); - assert!(error.contains("one field per list entry"), "{error}"); + assert!( + matches!(&error, CompileError::InvalidFilter(detail) + if detail.contains("ambiguous order_by") && detail.contains("one field per list entry")), + "{error}" + ); } #[test] diff --git a/src/graphql/complexity.rs b/src/graphql/complexity.rs deleted file mode 100644 index 61e5457e..00000000 --- a/src/graphql/complexity.rs +++ /dev/null @@ -1,113 +0,0 @@ -//! Nested selection complexity estimation (ship-complexity-1). -//! -//! async-graphql's dynamic schema only supports flat `1 + children` complexity -//! (no per-field weights). We estimate a **relationship-aware** cost from the -//! selection tree before SQL compile so multi-level `has_many` fan-out is -//! bounded by `max_complexity`, not just `max_depth`. - -use crate::table::{RelationshipKind, TableSchema}; - -use super::client_manifest::{ClientComplexityWeights, ClientRelationshipKind, ClientRootKind}; -use super::compile::{RootKind, SelectionNode}; -pub(crate) use super::complexity_contract::{DEFAULT_MAX_COMPLEXITY, DEFAULT_MAX_DEPTH}; -use super::engine::EngineInner; - -/// Estimate complexity for a root field selection before SQL compile, with -/// the weights and formula the client manifest exports. -pub fn estimate_root_complexity( - inner: &EngineInner, - model_name: &str, - kind: RootKind, - selection: &SelectionNode, -) -> Result { - let entry = inner - .catalog - .get(model_name) - .ok_or_else(|| format!("unknown model `{model_name}`"))?; - let w = ClientComplexityWeights::current(); - let child = estimate_object_selection(inner, &entry.schema, selection, &w); - let kind = match kind { - RootKind::List => ClientRootKind::List, - RootKind::ByPk => ClientRootKind::ByPk, - RootKind::Aggregate => ClientRootKind::Aggregate, - }; - Ok(usize::try_from(w.root(kind, child)).unwrap_or(usize::MAX)) -} - -fn estimate_object_selection( - inner: &EngineInner, - schema: &TableSchema, - selection: &SelectionNode, - w: &ClientComplexityWeights, -) -> u64 { - w.object( - selection - .children - .iter() - .map(|child| estimate_field(inner, schema, child, w)), - ) -} - -fn estimate_field( - inner: &EngineInner, - schema: &TableSchema, - node: &SelectionNode, - w: &ClientComplexityWeights, -) -> u64 { - let name = node.field_name.as_str(); - - // Nested aggregate field: `_aggregate` - if let Some(rel_name) = name.strip_suffix("_aggregate") { - if let Some(rel) = schema - .relationships - .iter() - .find(|r| r.field_name == rel_name) - { - return match inner.catalog.get(&rel.target_model) { - Some(target) => { - w.aggregate(estimate_object_selection(inner, &target.schema, node, w)) - } - None => w.aggregate, - }; - } - } - - if let Some(rel) = schema.relationships.iter().find(|r| r.field_name == name) { - let Some(target) = inner.catalog.get(&rel.target_model) else { - return w.has_many; - }; - let kind = match rel.kind { - RelationshipKind::BelongsTo => ClientRelationshipKind::BelongsTo, - RelationshipKind::HasMany => ClientRelationshipKind::HasMany, - RelationshipKind::ManyToMany => ClientRelationshipKind::ManyToMany, - }; - return w.relationship( - kind, - estimate_object_selection(inner, &target.schema, node, w), - ); - } - - // `nodes` on an aggregate type is a list of the same model. - if name == "nodes" { - return w.aggregate_nodes(estimate_object_selection(inner, schema, node, w)); - } - - // `aggregate`, `count`, scalar or unknown field. - w.scalar -} - -/// True if estimated cost exceeds the engine budget. -pub fn exceeds_budget(cost: usize, max_complexity: usize) -> bool { - cost > max_complexity -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn exceeds_budget_helper() { - assert!(exceeds_budget(501, 500)); - assert!(!exceeds_budget(500, 500)); - } -} diff --git a/src/graphql/complexity_contract.rs b/src/graphql/complexity_contract.rs deleted file mode 100644 index fb0e0228..00000000 --- a/src/graphql/complexity_contract.rs +++ /dev/null @@ -1,9 +0,0 @@ -//! Feature-neutral query complexity contract shared by runtime execution and -//! portable client-manifest generation. The weights and the cost formula are -//! [`ClientComplexityWeights`](super::client_manifest::ClientComplexityWeights). - -/// Default engine budget (same as the historical builder default). -pub(crate) const DEFAULT_MAX_COMPLEXITY: usize = 500; - -/// Default maximum GraphQL document depth. -pub(crate) const DEFAULT_MAX_DEPTH: usize = 8; diff --git a/src/graphql/cost.rs b/src/graphql/cost.rs new file mode 100644 index 00000000..ce154002 --- /dev/null +++ b/src/graphql/cost.rs @@ -0,0 +1,45 @@ +//! The query cost model: what one GraphQL request may ask the database for. +//! +//! Every knob has one unit, and the engine enforces each in one place. The +//! client manifest exports the same numbers (`execution`) so a client compiler +//! rejects the same operations at build time. `docs/graphql-query-cost.md` +//! is the user-facing description. +//! +//! | Knob | Unit | Enforced by | +//! |---|---|---| +//! | `max_depth` | nesting levels: fields in the document; relationships and `where` (boolean and relationship nesting) in the compiler | async-graphql `limit_depth`, the compiler | +//! | `max_fields` | selected fields in one document, every field once at every level | async-graphql `limit_complexity` | +//! | `max_rows` | model rows one root field's statement can produce (below) | the compiler, per root field | +//! | `default_limit`, `max_limit`, role `limit` | a list's page size: the client's `limit`, else the default, capped by the role and the engine | the compiler, per list | +//! | `max_in_list`, `max_bool_width` | entries in one `_in`/`_nin` list; entries in one `_and`/`_or` list | the compiler | +//! | `statement_timeout` | wall clock per root field | the database and the executor | +//! +//! **Rows.** A page of `limit` rows costs `limit × (1 + rows nested under one +//! of its rows)`; one object (a by-pk root, a belongs-to relationship) costs +//! `1 + rows nested under it`; columns and `aggregate { count }` cost nothing. +//! Each list counts its *resolved* limit, so for one chain of nested lists the +//! cost is about the product of their limits: +//! `orders(limit: 1000) { items(limit: 1000) { id } }` costs 1,001,000 rows. +//! `offset` is not part of the cost: skipped rows are scanned, not returned, +//! and the statement timeout bounds the scan. + +/// Page size of a list whose request gives no `limit`. +#[cfg_attr(not(feature = "graphql"), allow(dead_code))] +pub(crate) const DEFAULT_LIMIT: u64 = 100; +/// Largest page size any list may resolve to. +#[cfg_attr(not(feature = "graphql"), allow(dead_code))] +pub(crate) const DEFAULT_MAX_LIMIT: u64 = 1_000; +/// Default nesting depth. +pub(crate) const DEFAULT_MAX_DEPTH: usize = 8; +/// Default selected fields per document. +pub(crate) const DEFAULT_MAX_FIELDS: usize = 500; +/// Default rows per root field. Admits a root list at the maximum page size +/// with one default-sized nested list (1000 × (1 + 100) = 101,000), or a +/// default-sized root list with up to 19 default-sized sibling lists; refuses +/// a second nested level at the default size (100 × (1 + 100 × 101) = +/// 1,010,100) and nested lists at the maximum size (1000 × 1001 = 1,001,000). +pub(crate) const DEFAULT_MAX_ROWS: u64 = 200_000; +/// Default entries in one `_in` / `_nin` list. +pub(crate) const DEFAULT_MAX_IN_LIST: usize = 1_000; +/// Default entries in one `_and` / `_or` list. +pub(crate) const DEFAULT_MAX_BOOL_WIDTH: usize = 256; diff --git a/src/graphql/delivery/mod.rs b/src/graphql/delivery/mod.rs index 56478823..f0bd6191 100644 --- a/src/graphql/delivery/mod.rs +++ b/src/graphql/delivery/mod.rs @@ -32,8 +32,36 @@ pub(crate) fn validator( .map_err(|_| "validator encoding failed".into()) } +/// Plan mode for one request: every root resolver records the plan it +/// compiled here and returns without executing it. Present in request data +/// only while [`GraphqlEngine::plan`](crate::graphql::GraphqlEngine) runs. #[derive(Clone, Default)] -pub(crate) struct PlanCapture( - pub(crate) std::sync::Arc>>, +pub(crate) struct PlanRecorder( + std::sync::Arc>>>>, ); -pub(crate) const CAPTURED: &str = "gateway query plan captured"; + +impl PlanRecorder { + /// Record `plan` (`None` when no SQL plan can stand for the field, as for + /// a cell-by-key read) and return the error the resolver returns instead + /// of a value. The error carries no meaning: eligibility is read from the + /// recorder, never from response errors. + pub(crate) fn record(&self, plan: crate::graphql::compile::QueryPlan) -> async_graphql::Error { + let plan = match plan { + crate::graphql::compile::QueryPlan::Sql(plan) => Some(plan), + crate::graphql::compile::QueryPlan::CellByKey { .. } => None, + }; + if let Ok(mut plans) = self.0.lock() { + plans.push(plan); + } + crate::graphql::schema::client_error("INTERNAL", "not executed") + } + + /// The plan, when exactly one root resolver ran and it compiled to SQL. + pub(crate) fn single(&self) -> Option> { + let mut plans = self.0.lock().ok()?; + match plans.len() { + 1 => plans.pop().flatten(), + _ => None, + } + } +} diff --git a/src/graphql/delivery/versions.rs b/src/graphql/delivery/versions.rs index 383b1c26..82e03a99 100644 --- a/src/graphql/delivery/versions.rs +++ b/src/graphql/delivery/versions.rs @@ -10,24 +10,32 @@ use std::{ }; const MAX_TABLES: usize = 128; -// The cached envelope includes projection evidence as well as model data. -// Version all persisted evidence dependencies, including no-op/empty commits. -const PROOF_TABLES: &[&str] = &[ - "projection_partitions", - "projection_generations", - "projection_source_capabilities", - "projection_input_identities", - "projection_input_cursors", - "projection_input_receipts", - "projection_table_ownership_fences", - "projection_causal_tables", - "projection_registered_models", - "projection_model_ownership", - "projection_records", - "projection_observations", - "projection_failures", - "projection_changes", -]; +// The cached envelope includes projection evidence as well as model data, so +// every persisted evidence dependency is versioned, no-op commits included. +use crate::projection_protocol::PROOF_TABLES; + +/// Why dependency versions could not be read. +#[derive(Debug)] +pub(crate) enum VersionError { + /// The store does not version every table the query reads, or a trigger + /// is missing or disabled: the query is not cacheable. + Uncovered(&'static str), + /// The database could not answer: try again later. + Storage(String), +} + +impl std::fmt::Display for VersionError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Uncovered(reason) => f.write_str(reason), + Self::Storage(detail) => write!(f, "dependency version read failed: {detail}"), + } + } +} + +fn storage(error: impl std::fmt::Display) -> VersionError { + VersionError::Storage(error.to_string()) +} /// Installed transactional dependency coverage for one origin database. Create /// after application migrations, before enabling gateway caching. Every covered @@ -198,11 +206,12 @@ impl GatewayVersionStore { Ok(store) } fn install_sql(&self, epoch: &str, postgres: bool) -> Vec { - let mut sql = - vec![ - include_str!("../../../migrations/postgres/0006_gateway_dependency_versions.sql") - .to_owned(), - ]; + let migration = if postgres { + include_str!("../../../migrations/postgres/0006_gateway_dependency_versions.sql") + } else { + include_str!("../../../migrations/sqlite/0006_gateway_dependency_versions.sql") + }; + let mut sql = vec![migration.to_owned()]; for table in self.tables.union(&self.proof_tables) { let ns = literal(&self.namespace); let table_literal = literal(table); @@ -252,29 +261,37 @@ impl GatewayVersionStore { &self, pool: &GraphqlPool, tables: &[String], - ) -> Result { + ) -> Result { + #[cfg(any(feature = "sqlite", feature = "postgres"))] + use crate::sqlx_repo::repo::SqlxRepoBackend; match pool { #[cfg(feature = "sqlite")] GraphqlPool::Sqlite(pool) => { - let mut tx = pool.begin().await.map_err(|e| e.to_string())?; + let mut tx = pool + .begin_with(sqlx::Sqlite::BEGIN_READ_SNAPSHOT) + .await + .map_err(storage)?; let result = self.sqlite(&mut tx, tables).await?; - tx.commit().await.map_err(|e| e.to_string())?; + tx.commit().await.map_err(storage)?; Ok(result) } #[cfg(feature = "postgres")] GraphqlPool::Postgres(pool) => { - let mut tx = pool.begin().await.map_err(|e| e.to_string())?; - sqlx::query("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY") - .execute(&mut *tx) + let mut tx = pool + .begin_with(sqlx::Postgres::BEGIN_READ_SNAPSHOT) .await - .map_err(|e| e.to_string())?; - super::super::execute::ensure_primary_backend(&mut tx, true).await?; + .map_err(storage)?; + super::super::execute::ensure_primary_backend(&mut tx, true) + .await + .map_err(VersionError::Storage)?; let result = self.postgres(&mut tx, tables).await?; - tx.commit().await.map_err(|e| e.to_string())?; + tx.commit().await.map_err(storage)?; Ok(result) } #[allow(unreachable_patterns)] - _ => Err("dependency versions require a SQL adapter".into()), + _ => Err(VersionError::Uncovered( + "dependency versions require a SQL adapter", + )), } } /// Activate a new explicit epoch after a rebuild or writer-coverage change. @@ -313,18 +330,18 @@ impl GatewayVersionStore { macro_rules! version_reader { ($method:ident, $connection:ty, $coverage:expr) => { impl GatewayVersionStore { - pub(crate) async fn $method(&self, connection: &mut $connection, tables: &[String]) -> Result { - if !self.covers(tables) { return Err("query dependency coverage is incomplete".into()); } + pub(crate) async fn $method(&self, connection: &mut $connection, tables: &[String]) -> Result { + if !self.covers(tables) { return Err(VersionError::Uncovered("query dependency coverage is incomplete")); } let selected: BTreeSet<_> = tables.iter().chain(self.proof_tables.iter()).collect(); let queries = selected.iter().map(|table| { let coverage_sql: String = ($coverage)(self, table); format!("SELECT table_name, epoch, version, ({coverage_sql}) AS covered FROM distributed_gateway_versions WHERE namespace={} AND table_name={}",literal(&self.namespace),literal(table)) }).collect::>().join(" UNION ALL "); - let rows: Vec<(String,String,i64,i64)> = sqlx::query_as(sqlx::AssertSqlSafe(queries)).fetch_all(&mut *connection).await.map_err(|e| e.to_string())?; - if rows.len() != selected.len() { return Err("dependency version coverage is unavailable".into()); } + let rows: Vec<(String,String,i64,i64)> = sqlx::query_as(sqlx::AssertSqlSafe(queries)).fetch_all(&mut *connection).await.map_err(storage)?; + if rows.len() != selected.len() { return Err(VersionError::Uncovered("dependency version coverage is unavailable")); } let mut result = BTreeMap::new(); for (table, epoch, version, covered) in rows { - if covered != 1 || version < 0 { return Err("dependency invalidation coverage is unavailable".into()); } + if covered != 1 || version < 0 { return Err(VersionError::Uncovered("dependency invalidation coverage is unavailable")); } result.insert(table, DependencyVersion { epoch, version: version.to_string() }); } Ok(result) diff --git a/src/graphql/engine/builder.rs b/src/graphql/engine/builder.rs index 4b47aa01..8d36d708 100644 --- a/src/graphql/engine/builder.rs +++ b/src/graphql/engine/builder.rs @@ -20,12 +20,13 @@ impl GraphqlEngineBuilder { permissions: BTreeMap::new(), roles: None, anonymous_role: "anonymous".into(), - default_limit: 100, - max_limit: 1000, - max_depth: crate::graphql::complexity::DEFAULT_MAX_DEPTH, - max_complexity: crate::graphql::complexity::DEFAULT_MAX_COMPLEXITY, - max_in_list: 1000, - max_bool_width: 256, + default_limit: cost::DEFAULT_LIMIT, + max_limit: cost::DEFAULT_MAX_LIMIT, + max_depth: cost::DEFAULT_MAX_DEPTH, + max_fields: cost::DEFAULT_MAX_FIELDS, + max_rows: cost::DEFAULT_MAX_ROWS, + max_in_list: cost::DEFAULT_MAX_IN_LIST, + max_bool_width: cost::DEFAULT_MAX_BOOL_WIDTH, // Fail-closed by default for unshipped GA: unknown/ungranted filter // and order keys must not silently no-op. strict_where: true, @@ -86,9 +87,7 @@ impl GraphqlEngineBuilder { Ok(target) => { if let Err(e) = self.insert_catalog(target.clone(), false) { // Shadow insert conflict only if different schema. - if !e.0.contains("identical") { - self.pending_errors.push(e.0); - } + self.pending_errors.push(e.0); } } Err(err) => { @@ -356,21 +355,9 @@ impl GraphqlEngineBuilder { self } - /// Register one exact named application surface for generated clients. - /// Both role sets are required: eligible principals may open the surface, - /// while schema roles determine its portable privilege intersection. - /// - /// The server still authorizes every request as its verified concrete role. - pub fn client_application_surface( - self, - application: impl Into, - eligible_roles: impl IntoIterator>, - schema_roles: impl IntoIterator>, - ) -> Self { - self.client_application_surface_with_schema_roles(application, eligible_roles, schema_roles) - } - - /// Register an application surface with distinct eligible and schema roles. + /// Register one exact named application surface for generated clients, + /// with distinct eligible and schema roles. The server still authorizes + /// every request as its verified concrete role. /// /// - `eligible_roles`: wire/protocol role list; multi-role principals may /// open the surface when any asserted role is in this set. @@ -378,7 +365,7 @@ impl GraphqlEngineBuilder { /// non-empty subset of `eligible_roles`). Use e.g. eligible /// `{admin,user}` + schema `{user}` so portable owner policies survive /// without collapsing model permission definitions. - pub fn client_application_surface_with_schema_roles( + pub fn client_application_surface( mut self, application: impl Into, eligible_roles: impl IntoIterator>, @@ -539,32 +526,49 @@ impl GraphqlEngineBuilder { self } + // Query cost knobs. Each has one unit; `docs/graphql-query-cost.md` + // describes the model. + + /// Page size of a list whose request gives no `limit` (default 100). pub fn default_limit(mut self, n: u64) -> Self { self.default_limit = n; self } + /// Largest page size any list resolves to (default 1000). A role's + /// `limit` may lower it further for that role's models. pub fn max_limit(mut self, n: u64) -> Self { self.max_limit = n; self } + /// Nesting levels: fields in the document, and relationships and `where` + /// filters in the compiled statement (default 8). pub fn max_depth(mut self, n: usize) -> Self { self.max_depth = n; self } - /// Maximum nested-selection complexity budget (default - /// [`crate::graphql::complexity::DEFAULT_MAX_COMPLEXITY`]). + /// Selected fields in one document, every field once at every level + /// (default 500). + pub fn max_fields(mut self, n: usize) -> Self { + self.max_fields = n; + self + } + /// Model rows one root field's statement may produce (default 200,000). /// - /// Cost uses relationship-aware weights (see `complexity` module), not only - /// flat GraphQL field counts, so multi-level `has_many` trees are bounded. - pub fn max_complexity(mut self, n: usize) -> Self { - self.max_complexity = n; + /// Every list counts its resolved limit: a page of `limit` rows costs + /// `limit × (1 + rows nested under one row)` and one object costs + /// `1 + rows nested under it`, so nested lists cost about the product of + /// their limits. A root field over budget fails with `BAD_REQUEST` + /// `row budget exceeded` before any SQL runs. + pub fn max_rows(mut self, n: u64) -> Self { + self.max_rows = n; self } + /// Entries in one `_in` / `_nin` list (default 1000). pub fn max_in_list(mut self, n: usize) -> Self { self.max_in_list = n; self } - /// Cap width of a single `_and` / `_or` list in client `where` (default 256). + /// Entries in one `_and` / `_or` list in client `where` (default 256). pub fn max_bool_width(mut self, n: usize) -> Self { self.max_bool_width = n; self @@ -806,6 +810,14 @@ impl GraphqlEngineBuilder { } }; + let client_execution = ClientExecutionLimits::from_runtime( + self.max_depth, + self.max_fields, + self.max_rows, + self.max_bool_width, + self.max_in_list, + ) + .map_err(|error| GraphqlBuildError(error.to_string()))?; let tables: Vec = self .catalog .values() @@ -869,7 +881,7 @@ impl GraphqlEngineBuilder { let schema = dyn_schema::build_role_schema( &role_surface, self.max_depth, - self.max_complexity, + self.max_fields, role == &anonymous && !self.introspection_for_anonymous, ) .map_err(GraphqlBuildError)?; @@ -877,8 +889,7 @@ impl GraphqlEngineBuilder { let graphiql_schema = dyn_schema::build_role_schema( &role_surface, self.max_depth.max(GRAPHIQL_INTROSPECTION_MAX_DEPTH_FLOOR), - self.max_complexity - .max(GRAPHIQL_INTROSPECTION_MAX_COMPLEXITY_FLOOR), + self.max_fields.max(GRAPHIQL_INTROSPECTION_MAX_FIELDS_FLOOR), role == &anonymous && !self.introspection_for_anonymous, ) .map_err(GraphqlBuildError)?; @@ -894,13 +905,7 @@ impl GraphqlEngineBuilder { let export = DistributedClientSurfaceExport::from_selected_with_execution( service_id, Arc::clone(&role_surface), - ClientExecutionLimits::from_runtime( - self.max_depth, - self.max_complexity, - self.max_bool_width, - self.max_in_list, - ) - .map_err(|error| GraphqlBuildError(error.to_string()))?, + client_execution.clone(), ) .map_err(|error| { GraphqlBuildError(format!( @@ -952,7 +957,7 @@ impl GraphqlEngineBuilder { } } let application_surface = Arc::new( - surface_for_application_contract( + surface_for_application( &full_surface, application, ®istration.eligible_roles, @@ -969,13 +974,7 @@ impl GraphqlEngineBuilder { let export = DistributedClientSurfaceExport::from_selected_with_execution( service_id, Arc::clone(&application_surface), - ClientExecutionLimits::from_runtime( - self.max_depth, - self.max_complexity, - self.max_bool_width, - self.max_in_list, - ) - .map_err(|error| GraphqlBuildError(error.to_string()))?, + client_execution.clone(), ) .map_err(|error| GraphqlBuildError(format!( "failed to derive GraphQL protocol surface for application `{application}`: {error}" @@ -1017,7 +1016,7 @@ impl GraphqlEngineBuilder { let app_schema = dyn_schema::build_role_schema( &application_surface, self.max_depth, - self.max_complexity, + self.max_fields, false, ) .map_err(GraphqlBuildError)?; @@ -1026,8 +1025,7 @@ impl GraphqlEngineBuilder { let graphiql_schema = dyn_schema::build_role_schema( &application_surface, self.max_depth.max(GRAPHIQL_INTROSPECTION_MAX_DEPTH_FLOOR), - self.max_complexity - .max(GRAPHIQL_INTROSPECTION_MAX_COMPLEXITY_FLOOR), + self.max_fields.max(GRAPHIQL_INTROSPECTION_MAX_FIELDS_FLOOR), false, ) .map_err(GraphqlBuildError)?; @@ -1097,16 +1095,15 @@ impl GraphqlEngineBuilder { gateway_versions: self.gateway_versions, catalog: self.catalog, by_table: self.by_table, - roles, anonymous_role: anonymous, default_limit: self.default_limit, max_limit: self.max_limit, max_depth: self.max_depth, - max_complexity: self.max_complexity, + max_rows: self.max_rows, max_in_list: self.max_in_list, max_bool_width: self.max_bool_width, + client_execution, strict_where: self.strict_where, - introspection_for_anonymous: self.introspection_for_anonymous, statement_timeout: self.statement_timeout, graphiql: self.graphiql, typed_commands: self.typed_commands, diff --git a/src/graphql/engine/core.rs b/src/graphql/engine/core.rs index 7d11b2e4..3499f70a 100644 --- a/src/graphql/engine/core.rs +++ b/src/graphql/engine/core.rs @@ -235,21 +235,20 @@ pub(crate) struct EngineInner { pub gateway_versions: Option, pub catalog: BTreeMap, pub by_table: BTreeMap, - pub roles: BTreeSet, pub anonymous_role: String, pub default_limit: u64, pub max_limit: u64, pub max_depth: usize, - #[allow(dead_code)] - pub max_complexity: usize, + /// Rows one root field may produce (`crate::graphql::cost`). + pub max_rows: u64, pub max_in_list: usize, /// Max length of a single `_and` / `_or` list in client `where` (breadth DoS). pub max_bool_width: usize, + /// The cost limits above as client manifests export them. + pub client_execution: ClientExecutionLimits, /// When true (default), unknown/ungranted client `where` and `order_by` /// keys fail the request instead of soft-skipping. pub strict_where: bool, - #[allow(dead_code)] - pub introspection_for_anonymous: bool, pub statement_timeout: Duration, pub graphiql: bool, pub(crate) typed_commands: TypedCommandInventory, @@ -336,7 +335,8 @@ pub struct GraphqlEngineBuilder { pub(crate) default_limit: u64, pub(crate) max_limit: u64, pub(crate) max_depth: usize, - pub(crate) max_complexity: usize, + pub(crate) max_fields: usize, + pub(crate) max_rows: u64, pub(crate) max_in_list: usize, pub(crate) max_bool_width: usize, pub(crate) strict_where: bool, diff --git a/src/graphql/engine/delivery.rs b/src/graphql/engine/delivery.rs index e70fcb24..04e80b6f 100644 --- a/src/graphql/engine/delivery.rs +++ b/src/graphql/engine/delivery.rs @@ -3,7 +3,9 @@ use crate::gateway::{ delivery::{OperationKey, OriginAdmission}, graphql::{operation_kind, OperationKind}, }; -use crate::graphql::delivery::{self, GatewayCapture, PlanCapture}; +use crate::graphql::compile::SqlPlan; +use crate::graphql::delivery::{self, GatewayCapture, PlanRecorder, VersionError}; +use async_graphql::Value; pub(crate) fn request_value(request: &Request) -> serde_json::Value { serde_json::json!({"query": request.query, "operationName":request.operation_name, "variables":request.variables, "extensions":request.extensions}) @@ -109,42 +111,20 @@ impl GraphqlEngine { } let operation = operation_fingerprint(&request.query); let policy = store.policy(&request.query, request.operation_name.as_deref()); - let captured = PlanCapture::default(); let request = request .data(session.clone()) .data(authority) - .data(Arc::clone(&self.inner)) - .data(captured.clone()); - let response = if live { - schema - .execute_stream(request) - .next() - .await - .unwrap_or_else(ineligible) - } else { - schema.execute(request).await - }; - // Schema validation and normal compiler authorization still run. Only - // the private capture sentinel may replace SQL; unknown/custom fields, - // cell reads and multi-root documents never acquire cache eligibility. - if response.errors.len() != 1 || response.errors[0].message != delivery::CAPTURED { + .data(Arc::clone(&self.inner)); + let Some(plan) = self.plan(schema, request, live).await else { return ineligible(); - } - let plan = match captured.0.lock() { - Ok(mut plans) if plans.len() == 1 => plans.pop().expect("captured plan"), - _ => return ineligible(), }; if !store.covers(&plan.tables_touched) { return ineligible(); } let versions = match store.current(&self.inner.pool, &plan.tables_touched).await { Ok(versions) => versions, - Err(error) - if error.starts_with("dependency ") || error.starts_with("query dependency ") => - { - return ineligible() - } - Err(_) => return unavailable(), + Err(VersionError::Uncovered(_)) => return ineligible(), + Err(VersionError::Storage(_)) => return unavailable(), }; let validator = match delivery::validator(&runtime.codec, &identity, &key, &versions) { Ok(validator) => validator, @@ -165,4 +145,84 @@ impl GraphqlEngine { .expect("serializable admission"), ) } + + /// Compile the request's single root field without executing it. + /// + /// `request` already carries its session, execution authority and engine. + /// Schema validation and the compiler's authorization run as for an + /// execution; resolvers record their plan instead of running SQL. `None` + /// when the operation is not exactly one root field compiling to one SQL + /// statement (several roots, a cell read, a custom field, an invalid or + /// unauthorized request). + pub(crate) async fn plan( + &self, + schema: &async_graphql::dynamic::Schema, + mut request: Request, + live: bool, + ) -> Option> { + if !has_single_root_field(&mut request) { + return None; + } + let recorder = PlanRecorder::default(); + let request = request.data(recorder.clone()); + if live { + // The stream's first item is the root resolver's outcome. + let _ = schema.execute_stream(request).next().await; + } else { + let _ = schema.execute(request).await; + } + recorder.single() + } +} + +/// The selected operation's root selection set is exactly one field, counting +/// through fragments. Anything unparsable, or nested past the request analysis +/// bounds, is not. +fn has_single_root_field(request: &mut Request) -> bool { + use async_graphql::parser::types::{ExecutableDocument, Selection, SelectionSet}; + + fn count( + set: &SelectionSet, + document: &ExecutableDocument, + depth: usize, + fields: &mut usize, + ) -> Option<()> { + if depth > REQUEST_ANALYSIS_MAX_DEPTH { + return None; + } + for item in &set.items { + match &item.node { + Selection::Field(_) => *fields += 1, + Selection::InlineFragment(fragment) => count( + &fragment.node.selection_set.node, + document, + depth + 1, + fields, + )?, + Selection::FragmentSpread(spread) => { + let fragment = document.fragments.get(&spread.node.fragment_name.node)?; + count( + &fragment.node.selection_set.node, + document, + depth + 1, + fields, + )? + } + } + if *fields > 1 { + return None; + } + } + Some(()) + } + + let operation_name = request.operation_name.clone(); + let Ok(document) = request.parsed_query() else { + return false; + }; + let Some(operation) = selected_operation(document, operation_name.as_deref()) else { + return false; + }; + let mut fields = 0; + count(&operation.selection_set.node, document, 0, &mut fields).is_some() && fields == 1 } diff --git a/src/graphql/engine/introspection.rs b/src/graphql/engine/introspection.rs index e83fff9a..c711925e 100644 --- a/src/graphql/engine/introspection.rs +++ b/src/graphql/engine/introspection.rs @@ -19,23 +19,10 @@ pub(crate) fn is_pure_introspection_request(request: &mut Request) -> bool { let Ok(document) = request.parsed_query() else { return false; }; - let mut operations = document.operations.iter(); - let operation = if let Some(requested) = operation_name.as_deref() { - operations - .find(|(name, _)| name.map(|name| name.as_str()) == Some(requested)) - .map(|(_, operation)| operation) - } else { - let first = operations.next().map(|(_, operation)| operation); - if operations.next().is_some() { - None - } else { - first - } - }; - let Some(operation) = operation else { + let Some(operation) = selected_operation(document, operation_name.as_deref()) else { return false; }; - if operation.node.ty != async_graphql::parser::types::OperationType::Query { + if operation.ty != async_graphql::parser::types::OperationType::Query { return false; } @@ -99,7 +86,7 @@ pub(crate) fn is_pure_introspection_request(request: &mut Request) -> bool { let mut remaining_selections = REQUEST_ANALYSIS_MAX_SELECTIONS; selection_is_introspection_only( - &operation.node.selection_set.node, + &operation.selection_set.node, document, &mut BTreeSet::new(), &mut HashMap::new(), diff --git a/src/graphql/engine/metrics.rs b/src/graphql/engine/metrics.rs index e70fe09e..b7737313 100644 --- a/src/graphql/engine/metrics.rs +++ b/src/graphql/engine/metrics.rs @@ -29,16 +29,6 @@ pub(crate) fn attach_protocol_response( } } -/// First asserted role, else anonymous — prefer [`ExecutionAuthority::privilege_role`]. -#[allow(dead_code)] -pub(crate) fn resolve_role(session: &Session, anonymous: &str) -> String { - session - .roles() - .first() - .map(|role| (*role).to_string()) - .unwrap_or_else(|| anonymous.to_string()) -} - /// Map GraphQL response errors to coarse metric `status` labels. /// /// Privacy: only stable class names (`ok`, `timeout`, `bad_request`, @@ -76,13 +66,7 @@ pub(crate) fn metrics_status_for_response(response: &Response) -> &'static str { "error" } -pub(crate) fn record_metrics( - session: &Session, - root_field: &str, - status: &str, - duration: Duration, -) { - let _ = session; +pub(crate) fn record_metrics(root_field: &str, status: &str, duration: Duration) { #[cfg(feature = "metrics")] crate::metrics::record_graphql_request(None, root_field, status, duration); #[cfg(not(feature = "metrics"))] diff --git a/src/graphql/engine/mod.rs b/src/graphql/engine/mod.rs index 5cc713c3..8125bcf0 100644 --- a/src/graphql/engine/mod.rs +++ b/src/graphql/engine/mod.rs @@ -6,7 +6,7 @@ use std::collections::{btree_map::Entry, BTreeMap, BTreeSet, HashMap}; use std::sync::Arc; use std::time::Duration; -use async_graphql::{Request, Response, ServerError, Value}; +use async_graphql::{Request, Response, ServerError}; use futures_util::stream::{self, BoxStream}; use futures_util::StreamExt; use serde::{Deserialize, Serialize}; @@ -24,8 +24,8 @@ use super::client_manifest::{ ClientTrustedPresetDescriptor, DistributedClientManifest, DistributedClientSurfaceExport, }; use super::commands::TypedCommandInventory; -use super::compile::{SqlDialect, SqlPlan}; -use super::execute; +use super::compile::SqlDialect; +use super::cost; use super::filter::FilterExpr; use super::identity::{IdentityConfig, IdentityResolver}; use super::naming::{ @@ -39,19 +39,42 @@ use super::protocol::{ }; use super::query_protocol::QueryProtocolRuntime; use super::schema as dyn_schema; -use super::sdl::{graphql_sdl_for_tables_with_options, graphql_sdl_from_surface, SdlOptions}; +use super::sdl::graphql_sdl_from_surface; use super::surface::{ - build_surface, surface_for_application_contract, surface_for_role, Surface, SurfaceDialect, + build_surface, surface_for_application, surface_for_role, Surface, SurfaceDialect, SurfaceOptions, SurfaceProjectionOwner, SurfaceProjector, SurfaceSelection, }; use crate::command::TypedServiceCommandBinding; use crate::command_dispatch::VerifiedPrincipal; const GRAPHIQL_INTROSPECTION_MAX_DEPTH_FLOOR: usize = 15; -const GRAPHIQL_INTROSPECTION_MAX_COMPLEXITY_FLOOR: usize = 10_000; +const GRAPHIQL_INTROSPECTION_MAX_FIELDS_FLOOR: usize = 10_000; const REQUEST_ANALYSIS_MAX_DEPTH: usize = 128; const REQUEST_ANALYSIS_MAX_SELECTIONS: usize = 4_096; +/// The operation a request runs: the named one, else the only one. +pub(crate) fn selected_operation<'d>( + document: &'d async_graphql::parser::types::ExecutableDocument, + name: Option<&str>, +) -> Option<&'d async_graphql::parser::types::OperationDefinition> { + let mut operations = document.operations.iter(); + let operation = match name { + Some(name) => { + operations + .find(|(candidate, _)| candidate.map(|candidate| candidate.as_str()) == Some(name))? + .1 + } + None => { + let operation = operations.next()?.1; + if operations.next().is_some() { + return None; + } + operation + } + }; + Some(&operation.node) +} + mod auth; mod builder; mod core; @@ -90,13 +113,7 @@ pub(crate) use protocol::{ protocol_trusted_presets, resolve_execution_authority, resolve_protocol_preset, select_protocol_surface, }; -pub(crate) use validation::{execute_plan, validate_generated_names}; - -/// Public helper for tests: compile + naming surface. -#[allow(dead_code)] -pub fn core_sdl_for_catalog(tables: &[TableSchema]) -> Result { - validation::core_sdl_for_catalog(tables) -} +pub(crate) use validation::validate_generated_names; #[cfg(feature = "gateway")] pub(crate) mod read_routing; diff --git a/src/graphql/engine/protocol.rs b/src/graphql/engine/protocol.rs index dae07e89..c8bc2de5 100644 --- a/src/graphql/engine/protocol.rs +++ b/src/graphql/engine/protocol.rs @@ -299,23 +299,10 @@ pub(crate) fn has_multiple_protocol_query_roots( let Ok(document) = request.parsed_query() else { return false; }; - let mut operations = document.operations.iter(); - let operation = if let Some(requested) = operation_name.as_deref() { - operations - .find(|(name, _)| name.map(|name| name.as_str()) == Some(requested)) - .map(|(_, operation)| operation) - } else { - let first = operations.next().map(|(_, operation)| operation); - if operations.next().is_some() { - None - } else { - first - } - }; - let Some(operation) = operation else { + let Some(operation) = selected_operation(document, operation_name.as_deref()) else { return false; }; - if operation.node.ty != async_graphql::parser::types::OperationType::Query { + if operation.ty != async_graphql::parser::types::OperationType::Query { return false; } @@ -396,7 +383,7 @@ pub(crate) fn has_multiple_protocol_query_roots( let mut response_keys = BTreeSet::new(); let mut remaining_selections = REQUEST_ANALYSIS_MAX_SELECTIONS; let analysis = collect_root_keys( - &operation.node.selection_set.node, + &operation.selection_set.node, document, &query_roots, &mut BTreeSet::new(), diff --git a/src/graphql/engine/public_api.rs b/src/graphql/engine/public_api.rs index a4727c75..a41cfd52 100644 --- a/src/graphql/engine/public_api.rs +++ b/src/graphql/engine/public_api.rs @@ -23,9 +23,6 @@ impl GraphqlEngine { } pub fn sdl_for_role(&self, role: &str) -> Option { - if !self.inner.roles.contains(role) && role != self.inner.anonymous_role { - // Still allow any role that has a built schema. - } self.inner.schemas.get(role).map(|s| s.sdl()) } @@ -93,12 +90,7 @@ impl GraphqlEngine { DistributedClientSurfaceExport::from_selected_with_execution( service_id, surface, - ClientExecutionLimits::from_runtime( - self.inner.max_depth, - self.inner.max_complexity, - self.inner.max_bool_width, - self.inner.max_in_list, - )?, + self.inner.client_execution.clone(), ) } @@ -160,12 +152,7 @@ impl GraphqlEngine { DistributedClientSurfaceExport::from_selected_with_execution( service_id, surface, - ClientExecutionLimits::from_runtime( - self.inner.max_depth, - self.inner.max_complexity, - self.inner.max_bool_width, - self.inner.max_in_list, - )?, + self.inner.client_execution.clone(), ) } diff --git a/src/graphql/engine/read_routing.rs b/src/graphql/engine/read_routing.rs index e339523c..2f80df67 100644 --- a/src/graphql/engine/read_routing.rs +++ b/src/graphql/engine/read_routing.rs @@ -3,6 +3,7 @@ use crate::gateway::{ delivery::*, graphql::{operation_kind, OperationKind}, }; +use crate::graphql::compile::SqlPlan; /// Explicit stale-tolerant allowlist. No timeout/stickiness is treated as replay /// proof. With any retained floor the initial router always uses primary. diff --git a/src/graphql/engine/request.rs b/src/graphql/engine/request.rs index 3705a4ab..7af6004f 100644 --- a/src/graphql/engine/request.rs +++ b/src/graphql/engine/request.rs @@ -27,6 +27,32 @@ impl ProtocolPreparationError { } } +/// A request ready to execute, from [`GraphqlEngine::prepare`]. +struct Prepared { + schema: async_graphql::dynamic::Schema, + request: Request, + after: AfterExecution, +} + +/// What each response needs once the schema has produced it. +struct AfterExecution { + accumulator: Option, + #[cfg(feature = "gateway")] + read: read_routing::ReadRequest, + root_field: String, +} + +impl AfterExecution { + /// Attach the protocol envelope (and, under `gateway`, enforce the read's + /// freshness floor) on one response. + fn finish(&self, response: Response) -> Response { + let response = attach_protocol_response(response, self.accumulator.as_ref()); + #[cfg(feature = "gateway")] + let response = read_routing::enforce_minimum(response, &self.read); + response + } +} + impl GraphqlEngine { /// Whether `request` is a mutation this engine must not run: the bound /// service's lifecycle gate is closed. @@ -50,87 +76,26 @@ impl GraphqlEngine { /// [`Self::execute`] for a caller that has already asked /// [`Self::refuses_mutation`] and answered a refusal its own way. - pub(crate) async fn execute_admitted( - &self, - session: &Session, - mut request: Request, - ) -> Response { + pub(crate) async fn execute_admitted(&self, session: &Session, request: Request) -> Response { #[cfg(feature = "gateway")] if delivery::action(&request).as_deref() == Some("validate") { return self.validate_delivery(session, request).await; } - let authority = match resolve_execution_authority(&self.inner, session, &request) { - Ok(authority) => authority, - Err(()) => { - return Response::from_errors(vec![ServerError::new( - "GraphQL execution requires a named application surface for multi-role principals, a membership-checked role surface, or an anonymous session", - None, - )]); - } - }; - let privilege = authority.privilege_role.clone(); - let introspection = self.inner.graphiql && is_pure_introspection_request(&mut request); - let schema = if introspection { - self.inner - .graphiql_schemas - .get(&privilege) - .or_else(|| self.inner.schemas.get(&privilege)) - } else { - self.inner.schemas.get(&privilege) - }; - let Some(schema) = schema else { - return Response::from_errors(vec![ServerError::new( - format!("privilege pack `{privilege}` is not configured for GraphQL"), - None, - )]); - }; - if has_multiple_protocol_query_roots(&self.inner, &privilege, &mut request) { - return protocol_multi_root_error_response(); - } - - let accumulator = match self.protocol_accumulator(&authority, session, &request) { - Ok(accumulator) => accumulator, - Err(error) => return error.into_response(), - }; - #[cfg(feature = "gateway")] - if let Some(accumulator) = &accumulator { - if self - .enable_delivery_capture(session, &request, accumulator) - .is_err() - { - return protocol_internal_error_response(); - } - } - if introspection { - // The relaxed schema is defense-in-depth restricted even if a - // future classifier or request extension behaves unexpectedly. - request = request.only_introspection(); - } - #[cfg(feature = "gateway")] - let read = match self.prepare_read(session, &request) { - Ok(read) => read, - Err(error) => return read_routing::delivery_error(error), + let Prepared { + schema, + request, + after, + } = match self.prepare(session, request, false) { + Ok(prepared) => prepared, + Err(response) => return response, }; - #[cfg(feature = "gateway")] - let request = request.data(read.clone()); - let mut request = request - .data(session.clone()) - .data(authority) - .data(Arc::clone(&self.inner)); - if let Some(accumulator) = &accumulator { - request = request.data(accumulator.clone()); - } let start = std::time::Instant::now(); - let response = - attach_protocol_response(schema.execute(request).await, accumulator.as_ref()); - #[cfg(feature = "gateway")] - let response = read_routing::enforce_minimum(response, &read); - let status = metrics_status_for_response(&response); - let root_field = match &response.data { - Value::Object(map) => map.keys().next().map(|s| s.as_str()).unwrap_or("_"), - _ => "_", - }; - record_metrics(session, root_field, status, start.elapsed()); + let response = after.finish(schema.execute(request).await); + record_metrics( + &after.root_field, + metrics_status_for_response(&response), + start.elapsed(), + ); response } @@ -143,18 +108,39 @@ impl GraphqlEngine { if self.refuses_mutation(&mut request) { return stream::once(async { lifecycle_mutation_rejected() }).boxed(); } - let authority = match resolve_execution_authority(&self.inner, session, &request) { - Ok(authority) => authority, - Err(()) => { - return stream::once(async { - Response::from_errors(vec![ServerError::new( - "GraphQL execution requires a named application surface for multi-role principals, a membership-checked role surface, or an anonymous session", - None, - )]) - }) - .boxed(); - } + let Prepared { + schema, + request, + after, + } = match self.prepare(session, request, true) { + Ok(prepared) => prepared, + Err(response) => return stream::once(async move { response }).boxed(), }; + schema + .execute_stream(request) + .map(move |response| after.finish(response)) + .boxed() + } + + /// Everything both entry points do before execution: authorize, pick the + /// schema, refuse multi-root causal reads, open the protocol accumulator + /// and read routing, and attach the request data resolvers read. + #[allow( + clippy::result_large_err, + reason = "the refusal is the response both callers return as-is" + )] + fn prepare( + &self, + session: &Session, + mut request: Request, + stream: bool, + ) -> Result { + let authority = resolve_execution_authority(&self.inner, session, &request).map_err(|()| { + Response::from_errors(vec![ServerError::new( + "GraphQL execution requires a named application surface for multi-role principals, a membership-checked role surface, or an anonymous session", + None, + )]) + })?; let privilege = authority.privilege_role.clone(); let introspection = self.inner.graphiql && is_pure_introspection_request(&mut request); let schema = if introspection { @@ -165,58 +151,59 @@ impl GraphqlEngine { } else { self.inner.schemas.get(&privilege) }; - let Some(schema) = schema.cloned() else { - return stream::once(async move { - Response::from_errors(vec![ServerError::new( - format!("privilege pack `{privilege}` is not configured for GraphQL"), - None, - )]) - }) - .boxed(); - }; + let schema = schema.cloned().ok_or_else(|| { + Response::from_errors(vec![ServerError::new( + format!("privilege pack `{privilege}` is not configured for GraphQL"), + None, + )]) + })?; if has_multiple_protocol_query_roots(&self.inner, &privilege, &mut request) { - return stream::once(async { protocol_multi_root_error_response() }).boxed(); + return Err(protocol_multi_root_error_response()); } - let accumulator = match self.protocol_accumulator(&authority, session, &request) { - Ok(accumulator) => accumulator, - Err(error) => { - return stream::once(async move { error.into_response() }).boxed(); - } - }; - if accumulator - .as_ref() - .is_some_and(|accumulator| accumulator.begin_stream().is_err()) - { - return stream::once(async { protocol_internal_error_response() }).boxed(); + let accumulator = self + .protocol_accumulator(&authority, session, &request) + .map_err(ProtocolPreparationError::into_response)?; + if let Some(accumulator) = &accumulator { + let opened = if stream { + accumulator.begin_stream().map_err(drop) + } else { + #[cfg(feature = "gateway")] + let opened = self.enable_delivery_capture(session, &request, accumulator); + #[cfg(not(feature = "gateway"))] + let opened = Ok(()); + opened + }; + opened.map_err(|()| protocol_internal_error_response())?; } if introspection { + // The relaxed schema is defense-in-depth restricted even if a + // future classifier or request extension behaves unexpectedly. request = request.only_introspection(); } #[cfg(feature = "gateway")] - let read = match self.prepare_read(session, &request) { - Ok(read) => read, - Err(error) => { - return stream::once(async move { read_routing::delivery_error(error) }).boxed() - } - }; + let read = self + .prepare_read(session, &request) + .map_err(read_routing::delivery_error)?; #[cfg(feature = "gateway")] - let request = request.data(read.clone()); + let mut request = request.data(read.clone()); + let root_field = metric_root_field(&mut request, self.inner.role_surfaces.get(&privilege)); let mut request = request .data(session.clone()) .data(authority) - .data(std::sync::Arc::clone(&self.inner)); + .data(Arc::clone(&self.inner)); if let Some(accumulator) = &accumulator { request = request.data(accumulator.clone()); } - schema - .execute_stream(request) - .map(move |response| { - let response = attach_protocol_response(response, accumulator.as_ref()); + Ok(Prepared { + schema, + request, + after: AfterExecution { + accumulator, #[cfg(feature = "gateway")] - let response = read_routing::enforce_minimum(response, &read); - response - }) - .boxed() + read, + root_field, + }, + }) } pub(super) fn protocol_accumulator( @@ -350,19 +337,51 @@ impl GraphqlEngine { fn selected_operation_type( request: &mut Request, ) -> Option { - let requested = request.operation_name.clone(); + let name = request.operation_name.clone(); let document = request.parsed_query().ok()?; - let mut operations = document.operations.iter(); - if let Some(requested) = requested.as_deref() { - return operations - .find(|(name, _)| name.map(|name| name.as_str()) == Some(requested)) - .map(|(_, operation)| operation.node.ty); - } - let operation = operations.next()?.1; - if operations.next().is_some() { - return None; - } - Some(operation.node.ty) + selected_operation(document, name.as_deref()).map(|operation| operation.ty) +} + +/// The `root_field` metric label: the schema name (not the client's alias) of +/// the selected operation's first root field, when the role's surface serves +/// it; `_` otherwise, so client-chosen text never becomes a label value. +pub(super) fn metric_root_field(request: &mut Request, surface: Option<&Arc>) -> String { + use async_graphql::parser::types::Selection; + + let name = request.operation_name.clone(); + let Some(surface) = surface else { + return "_".to_owned(); + }; + let Ok(document) = request.parsed_query() else { + return "_".to_owned(); + }; + let Some(field) = selected_operation(document, name.as_deref()).and_then(|operation| { + operation + .selection_set + .node + .items + .iter() + .find_map(|item| match &item.node { + Selection::Field(field) => Some(field.node.name.node.as_str()), + _ => None, + }) + }) else { + return "_".to_owned(); + }; + surface + .query_fields + .iter() + .chain(&surface.subscription_fields) + .map(|root| root.name.as_str()) + .chain( + surface + .commands + .iter() + .map(|command| command.field_name.as_str()), + ) + .find(|root| *root == field) + .map_or("_", |root| root) + .to_owned() } fn lifecycle_mutation_rejected() -> Response { diff --git a/src/graphql/engine/tests.rs b/src/graphql/engine/tests.rs index 1eda2006..6c56e32d 100644 --- a/src/graphql/engine/tests.rs +++ b/src/graphql/engine/tests.rs @@ -6,8 +6,6 @@ mod client_surface_parity_tests { use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; - use sha2::{Digest, Sha256}; - use super::*; use crate::command::CommandConsistency; use crate::command::TypedCommandContract; @@ -276,16 +274,65 @@ mod client_surface_parity_tests { .roles(&["user"]) .grant_all("user") .max_depth(6) - .max_complexity(37) + .max_fields(37) + .max_rows(4_321) + .max_in_list(9) + .max_bool_width(3) .build() .unwrap(); let manifest = engine.client_manifest_for_role("user").unwrap(); - assert_eq!(manifest.execution.max_depth, 6); - assert_eq!(manifest.execution.max_complexity, 37); - assert_eq!(manifest.execution.complexity.version, 1); - assert_eq!(manifest.execution.complexity.scalar, 1); - assert_eq!(manifest.execution.complexity.list_fanout, 5); + assert_eq!( + manifest.execution, + crate::graphql::ClientExecutionLimits { + max_depth: 6, + max_fields: 37, + max_rows: 4_321, + max_bool_width: 3, + max_in_list: 9, + } + ); + } + + /// The `root_field` metric label is the schema field, never the client's + /// alias, and anything the role's surface does not serve is `_`. + #[cfg(feature = "sqlite")] + #[tokio::test] + async fn metric_root_field_is_the_schema_field_not_the_alias() { + let pool = sqlx::sqlite::SqlitePoolOptions::new() + .connect_lazy("sqlite::memory:") + .unwrap(); + let project = ReadModelCatalog::new("orders-service").table_schema(orders()); + let engine = GraphqlEngine::from_schema_catalog(&project, pool) + .unwrap() + .identity(crate::graphql::IdentityConfig::dev_headers()) + .roles(&["user"]) + .grant_all("user") + .build() + .unwrap(); + let surface = engine.inner.role_surfaces.get("user"); + let root = engine.inner.role_surfaces["user"].query_fields[0] + .name + .clone(); + let label = |document: &str| { + super::request::metric_root_field(&mut Request::new(document), surface) + }; + + assert_eq!(label(&format!("{{ {root} {{ order_id }} }}")), root); + assert_eq!( + label(&format!("{{ anyClientText123: {root} {{ order_id }} }}")), + root + ); + assert_eq!(label("{ __typename }"), "_"); + assert_eq!(label("{ notAField }"), "_"); + assert_eq!(label("not graphql"), "_"); + assert_eq!( + super::request::metric_root_field( + &mut Request::new(format!("{{ {root} {{ order_id }} }}")), + None + ), + "_" + ); } #[cfg(feature = "sqlite")] @@ -318,7 +365,8 @@ mod client_surface_parity_tests { assert_eq!(generated, runtime); assert_eq!(runtime.execution.max_depth, 8); - assert_eq!(runtime.execution.max_complexity, 500); + assert_eq!(runtime.execution.max_fields, 500); + assert_eq!(runtime.execution.max_rows, 200_000); assert_eq!( with_graphiql.inner.schemas.get("user").unwrap().sdl(), with_graphiql @@ -404,7 +452,7 @@ mod client_surface_parity_tests { .await; assert_eq!( disabled.data, - Value::Null, + async_graphql::Value::Null, "GraphiQL must not override request-level introspection denial" ); let streamed = with_graphiql @@ -417,7 +465,7 @@ mod client_surface_parity_tests { assert_eq!(streamed.len(), 1); assert_eq!( streamed[0].data, - Value::Null, + async_graphql::Value::Null, "the streaming path must preserve request-level introspection denial" ); } @@ -527,10 +575,7 @@ mod client_surface_parity_tests { assert_eq!(first, second); assert_eq!(first["protocolVersion"], 1); assert_eq!(first["schemaHash"], manifest.schema_fingerprint); - assert_eq!( - first["operation"], - "sha256:7f56e67dd21ab3f30d1ff8b7bed08893f0a0db86449836189b361dd1e56ddb4b" - ); + assert_digest(first["operation"].as_str().unwrap()); let scope = first["cacheScope"].as_str().unwrap(); assert!(scope.starts_with("v1.cache-scope.")); assert!(!scope.contains("principal-a")); @@ -719,7 +764,7 @@ mod client_surface_parity_tests { .unwrap() .row_filter = Some(col("status").eq(claim("x-user-id"))); let engine = builder - .client_application_surface_with_schema_roles("console", ["admin", "user"], ["user"]) + .client_application_surface("console", ["admin", "user"], ["user"]) .protocol_token_key([7; 32]) .build() .unwrap(); @@ -1128,7 +1173,7 @@ mod client_surface_parity_tests { error["message"], "required session input is missing or invalid" ); - assert_eq!(response.data, Value::Null); + assert_eq!(response.data, async_graphql::Value::Null); assert!(!response.extensions.contains_key("distributed")); } } @@ -1420,10 +1465,7 @@ mod client_surface_parity_tests { for forbidden in ["_contains", "_contained_in", "_has_key"] { assert!(!metadata_ops.contains(forbidden)); } - assert_eq!( - manifest.schema_fingerprint, - "sha256:a183d191dcaedbd88466fcefb6ac7ff83e7733bd69bbd90180a97d157ba2deec" - ); + assert_digest(&manifest.schema_fingerprint); } #[cfg(feature = "sqlite")] @@ -1558,10 +1600,7 @@ mod client_surface_parity_tests { assert!(metadata_ops.contains(required)); } assert_eq!(manifest.service_id, "orders-service"); - assert_eq!( - manifest.schema_fingerprint, - "sha256:9c0150e725493dc1e5ddbb3fdfc8b651cad399f099908cbcac326e514389c48a" - ); + assert_digest(&manifest.schema_fingerprint); } fn customers() -> TableSchema { @@ -1809,23 +1848,20 @@ mod client_surface_parity_tests { inventory } - fn sha256(bytes: &[u8]) -> String { - format!("sha256:{:x}", Sha256::digest(bytes)) - } - - #[derive(Clone, Copy)] - struct ArtifactGoldens { - manifest: &'static str, - static_sdl: &'static str, - runtime_sdl: &'static str, + /// A content digest as the protocol writes them. Its value is pinned by + /// comparing independent builds, not by a golden constant. + fn assert_digest(digest: &str) { + let hex = digest.strip_prefix("sha256:").unwrap_or_default(); + assert!( + hex.len() == 64 + && hex + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)), + "not a sha256 digest: {digest}" + ); } - async fn assert_role_matrix( - engine: &GraphqlEngine, - dialect: SurfaceDialect, - role: &str, - expected: ArtifactGoldens, - ) { + async fn assert_role_matrix(engine: &GraphqlEngine, dialect: SurfaceDialect, role: &str) { let stored = engine.surface_for_role(role).unwrap(); let export = engine.client_surface_for_role(role).unwrap(); assert!(Arc::ptr_eq(&stored, export.surface())); @@ -1960,19 +1996,9 @@ mod client_surface_parity_tests { other => panic!("unexpected matrix role `{other}`"), } - let manifest_json = serde_json::to_vec(&manifest).unwrap(); - let actual_manifest = sha256(&manifest_json); - let actual_static_sdl = sha256(static_sdl.as_bytes()); - let actual_runtime_sdl = sha256(runtime_sdl.as_bytes()); - assert_eq!( - ( - actual_manifest.as_str(), - actual_static_sdl.as_str(), - actual_runtime_sdl.as_str() - ), - (expected.manifest, expected.static_sdl, expected.runtime_sdl), - "{dialect:?}/{role}" - ); + // The manifest equals one built independently from the same inputs + // (above), so its fingerprint is stable across builds. + assert_digest(&manifest.schema_fingerprint); } async fn assert_nested_command_validates(engine: &GraphqlEngine) { @@ -2002,34 +2028,6 @@ mod client_surface_parity_tests { ); } - #[cfg(feature = "sqlite")] - const SQLITE_RESTRICTED_GOLDENS: ArtifactGoldens = ArtifactGoldens { - manifest: "sha256:9d6a7a152ac4ec6cd935048df3e5e6e1d0108373ae9e862df227a3ca80dd6e17", - static_sdl: "sha256:03252ba251b1ddac611fe567d816f780f0876f9f6ce263be95a3480f88fc2283", - runtime_sdl: "sha256:3d099b8c0b27f0dcbdd677199f767fcc5993071e06b2c0a7d4aa02caf4e5f4ac", - }; - - #[cfg(feature = "sqlite")] - const SQLITE_ADMIN_GOLDENS: ArtifactGoldens = ArtifactGoldens { - manifest: "sha256:15828e5a01528e188c833fdac7b3cf7e37d815bb91f559884a2f78da9c8a2627", - static_sdl: "sha256:128b85bcd6485d14de62b0976e9f12e8b35ad9e7d96a5627d1edcfcabdb591b3", - runtime_sdl: "sha256:c0b6d600d353357ab4f393897fb6b7ee51f69546f7a4cc4b6786e42abe621f5c", - }; - - #[cfg(feature = "postgres")] - const POSTGRES_RESTRICTED_GOLDENS: ArtifactGoldens = ArtifactGoldens { - manifest: "sha256:9d6a7a152ac4ec6cd935048df3e5e6e1d0108373ae9e862df227a3ca80dd6e17", - static_sdl: "sha256:03252ba251b1ddac611fe567d816f780f0876f9f6ce263be95a3480f88fc2283", - runtime_sdl: "sha256:3d099b8c0b27f0dcbdd677199f767fcc5993071e06b2c0a7d4aa02caf4e5f4ac", - }; - - #[cfg(feature = "postgres")] - const POSTGRES_ADMIN_GOLDENS: ArtifactGoldens = ArtifactGoldens { - manifest: "sha256:cb6940a57989377e2f6ae1caf34ddb52b6bc73c8d6971e9f430ea3b6e9b834f6", - static_sdl: "sha256:afe92660c1700845ed5f3e0ddaacc4b481799c39f86b8eacecb46d1b8f99d421", - runtime_sdl: "sha256:de4885736fdf22a57ccc55160d63b6d1a7fdb33728dec399e8a81d54ce7e8c09", - }; - #[cfg(feature = "sqlite")] #[tokio::test] async fn sqlite_restricted_admin_full_artifact_matrix() { @@ -2037,20 +2035,8 @@ mod client_surface_parity_tests { .connect_lazy("sqlite::memory:") .unwrap(); let engine = matrix_engine(pool.into()); - assert_role_matrix( - &engine, - SurfaceDialect::Sqlite, - "restricted", - SQLITE_RESTRICTED_GOLDENS, - ) - .await; - assert_role_matrix( - &engine, - SurfaceDialect::Sqlite, - "admin", - SQLITE_ADMIN_GOLDENS, - ) - .await; + assert_role_matrix(&engine, SurfaceDialect::Sqlite, "restricted").await; + assert_role_matrix(&engine, SurfaceDialect::Sqlite, "admin").await; assert_nested_command_validates(&engine).await; } @@ -2061,20 +2047,8 @@ mod client_surface_parity_tests { .connect_lazy("postgres://postgres:postgres@localhost/distributed_test") .unwrap(); let engine = matrix_engine(pool.into()); - assert_role_matrix( - &engine, - SurfaceDialect::Postgres, - "restricted", - POSTGRES_RESTRICTED_GOLDENS, - ) - .await; - assert_role_matrix( - &engine, - SurfaceDialect::Postgres, - "admin", - POSTGRES_ADMIN_GOLDENS, - ) - .await; + assert_role_matrix(&engine, SurfaceDialect::Postgres, "restricted").await; + assert_role_matrix(&engine, SurfaceDialect::Postgres, "admin").await; assert_nested_command_validates(&engine).await; } @@ -2515,19 +2489,4 @@ mod client_surface_parity_tests { assert!(error.to_string().contains(expected), "{error}"); } } - - #[cfg(feature = "sqlite")] - #[tokio::test] - async fn sqlite_nocase_can_equate_unequal_code_unit_strings() { - let pool = sqlx::sqlite::SqlitePoolOptions::new() - .connect("sqlite::memory:") - .await - .unwrap(); - let equal: i64 = sqlx::query_scalar("SELECT 'A' = 'a' COLLATE NOCASE") - .fetch_one(&pool) - .await - .unwrap(); - assert_eq!(equal, 1); - assert_ne!("A", "a"); - } } diff --git a/src/graphql/engine/validation.rs b/src/graphql/engine/validation.rs index 32e98e56..2680b630 100644 --- a/src/graphql/engine/validation.rs +++ b/src/graphql/engine/validation.rs @@ -28,14 +28,3 @@ pub(crate) fn validate_generated_names( } Ok(()) } - -/// Execute a compiled plan against the engine pool (used by root resolvers). -pub(crate) async fn execute_plan(inner: &EngineInner, plan: &SqlPlan) -> Result { - execute::execute_sql(inner, plan).await -} - -/// Public helper for tests: compile + naming surface. -pub fn core_sdl_for_catalog(tables: &[TableSchema]) -> Result { - // Dialect-independent / SQLite-default SDL (no PG JSON ops). - graphql_sdl_for_tables_with_options(tables, &SdlOptions::sqlite()) -} diff --git a/src/graphql/execute.rs b/src/graphql/execute.rs index d2012c9f..dbadbab7 100644 --- a/src/graphql/execute.rs +++ b/src/graphql/execute.rs @@ -1,66 +1,301 @@ -//! Dialect executors: run a SqlPlan and decode the single JSON column. -#![allow(clippy::items_after_test_module)] +//! The one executor for compiled plans. +//! +//! [`execute_plan`] runs a [`SqlPlan`] on either SQL backend: one read +//! snapshot, the plan's single statement, then — only when the causal protocol +//! asks for it — the evidence reads inside the same snapshot. A plain read is +//! the protocol read with no evidence consumer. +//! +//! Round trips on PostgreSQL: the snapshot `BEGIN` and its `SET LOCAL +//! statement_timeout` go in one simple-query message; the authoritative-primary +//! check (`gateway`) rides in the plan's own statement; then `COMMIT`. So a +//! plain root field costs three round trips, where it used to cost five. use std::future::Future; +use std::sync::Arc; use std::time::Duration; use async_graphql::Value; +#[cfg(any(feature = "sqlite", feature = "postgres"))] use serde_json::Value as JsonValue; -use super::compile::{BindValue, ExtractedQueryEvidence, SqlDialect, SqlPlan}; +use super::compile::SqlPlan; +#[cfg(any(feature = "sqlite", feature = "postgres"))] +use super::compile::{BindValue, ExtractedQueryEvidence}; +#[cfg(all(feature = "gateway", any(feature = "sqlite", feature = "postgres")))] +use super::delivery::{GatewayVersionStore, VersionError, VersionVector}; use super::engine::{EngineInner, GraphqlPool}; +use super::protocol::{ + DistributedLiveMetadata, DistributedQuerySnapshot, ProtocolResponseAccumulator, + RequestedLiveResume, +}; +use super::surface::Surface; +use crate::projection_protocol::ProjectionProtocolError; -pub async fn execute_sql(inner: &EngineInner, plan: &SqlPlan) -> Result { - execute_sql_on_pool(inner, &inner.pool, true, plan).await +/// Why an execution failed, as far as the client may know. +#[derive(Debug)] +pub(crate) enum ExecuteError { + /// The statement ran past `statement_timeout`: the client may retry. + Timeout, + /// Anything else. The detail is for logs, never for the client. + Failed(String), } -pub(crate) async fn execute_sql_on_pool( +impl ExecuteError { + /// The GraphQL error the client sees. + pub(crate) fn client_error(&self) -> async_graphql::Error { + match self { + Self::Timeout => super::schema::client_error("TIMEOUT", "statement timeout"), + Self::Failed(_) => super::schema::client_error("INTERNAL", "internal error"), + } + } + + fn failed(detail: impl Into) -> Self { + Self::Failed(detail.into()) + } +} + +impl std::fmt::Display for ExecuteError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Timeout => f.write_str("statement timeout"), + Self::Failed(detail) => f.write_str(detail), + } + } +} + +#[cfg(any(feature = "sqlite", feature = "postgres"))] +impl From for ExecuteError { + fn from(error: sqlx::Error) -> Self { + if is_statement_timeout(&error) { + Self::Timeout + } else { + Self::Failed(error.to_string()) + } + } +} + +impl From for ExecuteError { + fn from(error: ProjectionProtocolError) -> Self { + #[cfg(any(feature = "sqlite", feature = "postgres"))] + if let ProjectionProtocolError::Repository(crate::RepositoryError::Storage { + source: Some(source), + .. + }) = &error + { + if source + .downcast_ref::() + .is_some_and(is_statement_timeout) + { + return Self::Timeout; + } + } + Self::Failed(error.to_string()) + } +} + +/// PostgreSQL cancelled the statement (SQLSTATE 57014, `query_canceled`): +/// the only cancellation the engine causes is its `statement_timeout`. +#[cfg(any(feature = "sqlite", feature = "postgres"))] +fn is_statement_timeout(error: &sqlx::Error) -> bool { + matches!(error, sqlx::Error::Database(db) if db.code().as_deref() == Some("57014")) +} + +/// The causal protocol's evidence consumer for one execution. +pub(crate) struct ProtocolRead { + pub(crate) role_surface: Arc, + pub(crate) accumulator: ProtocolResponseAccumulator, + /// `Some` for a live query: also read the resume metadata. + pub(crate) live_resume: Option, +} + +pub(crate) struct Executed { + pub(crate) value: Value, + /// Present exactly when a [`ProtocolRead`] was given. + pub(crate) protocol: Option, +} + +pub(crate) struct ProtocolEvidence { + pub(crate) snapshot: DistributedQuerySnapshot, + pub(crate) live: Option, +} + +/// Run `plan` on `pool`, within `statement_timeout`. +/// +/// `primary` asks PostgreSQL to prove the connection is not a standby +/// (`gateway` builds only). `protocol` adds the evidence reads; without it the +/// result carries no evidence. +pub(crate) async fn execute_plan( inner: &EngineInner, pool: &GraphqlPool, primary: bool, plan: &SqlPlan, -) -> Result { - let _ = primary; - match pool { - #[cfg(feature = "sqlite")] - GraphqlPool::Sqlite(pool) => execute_sqlite(pool, plan, inner.statement_timeout) - .await - .map(|executed| executed.value), - #[cfg(feature = "postgres")] - GraphqlPool::Postgres(pool) => { - execute_postgres(pool, plan, inner.statement_timeout, primary) - .await - .map(|executed| executed.value) + protocol: Option, +) -> Result { + let timeout = inner.statement_timeout; + let run = async move { + match pool { + #[cfg(feature = "sqlite")] + GraphqlPool::Sqlite(pool) => { + run_plan(inner, pool, timeout, primary, plan, protocol).await + } + #[cfg(feature = "postgres")] + GraphqlPool::Postgres(pool) => { + run_plan(inner, pool, timeout, primary, plan, protocol).await + } + #[allow(unreachable_patterns)] + _ => { + let _ = (inner, primary, plan, protocol); + Err(ExecuteError::failed( + "no database pool available for GraphQL execution", + )) + } } - #[allow(unreachable_patterns)] - _ => Err("no database pool available for GraphQL execution".into()), - } + }; + apply_statement_timeout(timeout, run).await } -pub(crate) struct ExecutedSql { - pub(crate) value: Value, - pub(crate) evidence: ExtractedQueryEvidence, +/// Wall-clock budget around one execution; the backstop for a backend with +/// no server-side statement timeout (SQLite). +pub(crate) async fn apply_statement_timeout( + timeout: Duration, + run: F, +) -> Result +where + F: Future>, +{ + tokio::time::timeout(timeout, run) + .await + .unwrap_or(Err(ExecuteError::Timeout)) } -/// Wall-clock budget around a single statement future. -/// -/// On elapse returns `Err("statement timeout")` — the stable string mapped to -/// client `TIMEOUT` by [`super::schema::client_error_for_execute_err`]. -pub(crate) async fn apply_statement_timeout(timeout: Duration, run: F) -> Result +/// What differs between the SQL backends when executing a plan. +#[cfg(any(feature = "sqlite", feature = "postgres"))] +pub(crate) trait GraphqlBackend: crate::sqlx_repo::repo::SqlxRepoBackend { + /// The one statement that opens a read snapshot whose statements are + /// bounded by `timeout`. + fn begin_read(timeout: Duration) -> String; + + /// Run the plan's statement and decode its JSON column (`null` for no + /// row). With `primary`, fail on a standby. + fn fetch<'c>( + connection: &'c mut Self::Connection, + plan: &'c SqlPlan, + primary: bool, + ) -> impl Future> + Send + 'c; + + /// The dependency versions a gateway validator binds, read in the same + /// snapshot as the result. + #[cfg(feature = "gateway")] + fn gateway_versions<'c>( + store: &'c GatewayVersionStore, + connection: &'c mut Self::Connection, + tables: &'c [String], + ) -> impl Future> + Send + 'c; +} + +#[cfg(any(feature = "sqlite", feature = "postgres"))] +async fn run_plan( + inner: &EngineInner, + pool: &sqlx::Pool, + timeout: Duration, + primary: bool, + plan: &SqlPlan, + protocol: Option, +) -> Result +where + DB: GraphqlBackend, + for<'c> &'c mut DB::Connection: sqlx::Executor<'c, Database = DB>, + DB::Arguments: sqlx::IntoArguments, + for<'q> i64: sqlx::Encode<'q, DB> + sqlx::Type + sqlx::Decode<'q, DB>, + for<'q> String: sqlx::Type + sqlx::Decode<'q, DB>, + for<'q> Vec: sqlx::Type + sqlx::Decode<'q, DB>, + for<'q> &'q str: sqlx::Encode<'q, DB> + sqlx::Type, + for<'q> &'q [u8]: sqlx::Encode<'q, DB> + sqlx::Type, + for<'r> &'r str: sqlx::ColumnIndex, +{ + if let Some(read) = &protocol { + // Matching compiler plans share one comparable snapshot scope, so a + // lagging refresh is never authoritative over a newer live frame + // merely because the transport operation differs. + read.accumulator + .bind_query_snapshot_scope(&plan.snapshot_scope()) + .map_err(|error| { + ExecuteError::failed(format!("query snapshot scope failed: {error}")) + })?; + } + let mut tx = pool + .begin_with(sqlx::AssertSqlSafe(DB::begin_read(timeout))) + .await?; + #[cfg(feature = "gateway")] + if protocol.is_some() { + if let Some(store) = &inner.gateway_versions { + store.record_result(); + } + } + let mut json = DB::fetch(&mut tx, plan, primary).await?; + let evidence = plan + .extract_evidence_and_strip(&mut json) + .map_err(ExecuteError::Failed)?; + let value = Value::from_json(json) + .map_err(|error| ExecuteError::failed(format!("graphql value: {error}")))?; + let protocol = match protocol { + None => None, + Some(read) => Some(read_evidence::(inner, &mut tx, plan, read, evidence).await?), + }; + tx.commit().await?; + Ok(Executed { value, protocol }) +} + +#[cfg(any(feature = "sqlite", feature = "postgres"))] +async fn read_evidence( + inner: &EngineInner, + connection: &mut DB::Connection, + plan: &SqlPlan, + read: ProtocolRead, + evidence: ExtractedQueryEvidence, +) -> Result where - F: Future>, + DB: GraphqlBackend, + for<'c> &'c mut DB::Connection: sqlx::Executor<'c, Database = DB>, + DB::Arguments: sqlx::IntoArguments, + for<'q> i64: sqlx::Encode<'q, DB> + sqlx::Type + sqlx::Decode<'q, DB>, + for<'q> String: sqlx::Type + sqlx::Decode<'q, DB>, + for<'q> Vec: sqlx::Type + sqlx::Decode<'q, DB>, + for<'q> &'q str: sqlx::Encode<'q, DB> + sqlx::Type, + for<'q> &'q [u8]: sqlx::Encode<'q, DB> + sqlx::Type, + for<'r> &'r str: sqlx::ColumnIndex, { - match tokio::time::timeout(timeout, run).await { - Ok(Ok(v)) => Ok(v), - Ok(Err(e)) => Err(e), - Err(_) => Err("statement timeout".into()), + let (snapshot, live) = super::query_protocol::finish_protocol_query::( + connection, + &inner.query_protocol, + &read.role_surface, + &read.accumulator, + plan, + evidence, + read.live_resume, + ) + .await?; + #[cfg(feature = "gateway")] + if read.accumulator.gateway_enabled() { + if let Some(store) = &inner.gateway_versions { + if store.covers(&plan.tables_touched) { + let versions = DB::gateway_versions(store, connection, &plan.tables_touched) + .await + .map_err(|error| ExecuteError::Failed(error.to_string()))?; + read.accumulator + .record_gateway_versions(&versions) + .map_err(|error| ExecuteError::Failed(error.to_string()))?; + } + } } + Ok(ProtocolEvidence { snapshot, live }) } /// Apply [`BindValue`]s to a sqlx query builder. /// /// Shared by SQLite and Postgres executors so bind-order and type mapping stay -/// in one place (dedup-3). Macro because sqlx `Query` is database-generic. +/// in one place. Macro because sqlx `Query` is database-generic. +#[cfg(any(feature = "sqlite", feature = "postgres"))] macro_rules! apply_binds { ($qb:expr, $binds:expr) => {{ let mut __qb = $qb; @@ -70,8 +305,8 @@ macro_rules! apply_binds { BindValue::Bool(b) => __qb.bind(*b), BindValue::I64(i) => __qb.bind(*i), BindValue::F64(f) => __qb.bind(*f), - BindValue::Text(s) => __qb.bind(s.clone()), - BindValue::Bytes(b) => __qb.bind(b.clone()), + BindValue::Text(s) => __qb.bind(s.as_str()), + BindValue::Bytes(b) => __qb.bind(b.as_slice()), // No sqlx `json` feature — bind as text; compiler adds casts. BindValue::Json(j) => __qb.bind(j.to_string()), }; @@ -81,191 +316,114 @@ macro_rules! apply_binds { } #[cfg(feature = "sqlite")] -async fn execute_sqlite( - pool: &sqlx::SqlitePool, - plan: &SqlPlan, - timeout: std::time::Duration, -) -> Result { - // SQL is compiler-produced from schema metadata + bound parameters only. - let text = apply_statement_timeout(timeout, fetch_sqlite_json(pool, plan)).await?; - decode_sqlite_value(text, plan) -} - -/// Execute a compiled SQLite plan on a caller-owned read snapshot. -#[cfg(feature = "sqlite")] -pub(crate) async fn execute_sqlite_in_connection( - connection: &mut sqlx::SqliteConnection, - plan: &SqlPlan, -) -> Result { - let text = fetch_sqlite_json(&mut *connection, plan).await?; - decode_sqlite_value(text, plan) -} - -#[cfg(feature = "sqlite")] -async fn fetch_sqlite_json<'e, E>(executor: E, plan: &SqlPlan) -> Result -where - E: sqlx::Executor<'e, Database = sqlx::Sqlite>, -{ - use sqlx::Row; - - let qb = apply_binds!( - sqlx::query(sqlx::AssertSqlSafe(plan.sql.clone())), - &plan.binds - ); - // by_pk and filtered lookups may return zero rows → GraphQL null. - let row = qb - .fetch_optional(executor) - .await - .map_err(|e| format!("sqlite execute: {e}"))?; - match row { - Some(row) => row - .try_get::, _>(0) - .map_err(|e| format!("sqlite json column: {e}")) - .map(|value| value.unwrap_or_else(|| "null".into())), - None => Ok("null".into()), +impl GraphqlBackend for sqlx::Sqlite { + fn begin_read(_timeout: Duration) -> String { + // SQLite has no statement timeout; `apply_statement_timeout` bounds + // the whole execution instead. + ::BEGIN_READ_SNAPSHOT.to_owned() } -} -#[cfg(feature = "sqlite")] -fn decode_sqlite_value(text: String, plan: &SqlPlan) -> Result { - let mut json: JsonValue = - serde_json::from_str(&text).map_err(|e| format!("json decode: {e}"))?; - rewrite_hex_bytes(&mut json, &plan.bytes_hex_paths); - finish_executed_value(json, plan) -} + async fn fetch( + connection: &mut sqlx::SqliteConnection, + plan: &SqlPlan, + _primary: bool, + ) -> Result { + use sqlx::Row; -#[cfg(test)] -mod statement_timeout_tests { - use super::apply_statement_timeout; - use std::time::Duration; - - #[tokio::test(start_paused = true)] - async fn elapses_to_statement_timeout_error() { - let run = async { - tokio::time::sleep(Duration::from_secs(10)).await; - Ok::("never".into()) + let query = apply_binds!( + sqlx::query(sqlx::AssertSqlSafe(Arc::clone(&plan.sql))), + &plan.binds + ); + // by_pk and filtered lookups may return zero rows → GraphQL null. + let text = match query.fetch_optional(&mut *connection).await? { + Some(row) => row.try_get::, _>(0)?, + None => None, }; - let handle = - tokio::spawn( - async move { apply_statement_timeout(Duration::from_millis(1), run).await }, - ); - tokio::time::advance(Duration::from_millis(5)).await; - let err = handle.await.expect("join").expect_err("budget must elapse"); - assert_eq!(err, "statement timeout"); - } - - #[tokio::test(start_paused = true)] - async fn completes_when_under_budget() { - let run = async { Ok::("ok".into()) }; - let handle = - tokio::spawn(async move { apply_statement_timeout(Duration::from_secs(5), run).await }); - // Allow the ready future to be polled under paused time. - tokio::time::advance(Duration::from_millis(1)).await; - let v: String = handle.await.expect("join").expect("under budget"); - assert_eq!(v, "ok"); + let mut json = match text { + Some(text) => serde_json::from_str(&text) + .map_err(|error| ExecuteError::failed(format!("json decode: {error}")))?, + None => JsonValue::Null, + }; + rewrite_hex_bytes(&mut json, &plan.bytes_hex_paths); + Ok(json) } - #[tokio::test(start_paused = true)] - async fn propagates_inner_error() { - let run = async { Err::("sqlite execute: boom".into()) }; - let handle = - tokio::spawn(async move { apply_statement_timeout(Duration::from_secs(5), run).await }); - tokio::time::advance(Duration::from_millis(1)).await; - let err = handle.await.expect("join").expect_err("inner err"); - assert!(err.contains("boom"), "{err}"); + #[cfg(feature = "gateway")] + fn gateway_versions<'c>( + store: &'c GatewayVersionStore, + connection: &'c mut sqlx::SqliteConnection, + tables: &'c [String], + ) -> impl Future> + Send + 'c { + store.sqlite(connection, tables) } } #[cfg(feature = "postgres")] -async fn execute_postgres( - pool: &sqlx::PgPool, - plan: &SqlPlan, - timeout: std::time::Duration, - primary: bool, -) -> Result { - let mut tx = pool - .begin() - .await - .map_err(|e| format!("postgres begin: {e}"))?; - let timeout_ms = timeout.as_millis() as i64; - sqlx::query(sqlx::AssertSqlSafe(format!( - "SET LOCAL statement_timeout = '{timeout_ms}ms'" - ))) - .execute(&mut *tx) - .await - .map_err(|e| format!("statement_timeout: {e}"))?; - - ensure_primary_backend(&mut tx, primary).await?; - let value = fetch_postgres_value(&mut *tx, plan).await?; - tx.commit() - .await - .map_err(|e| format!("postgres commit: {e}"))?; - - Ok(value) -} +impl GraphqlBackend for sqlx::Postgres { + fn begin_read(timeout: Duration) -> String { + let timeout_ms = i64::try_from(timeout.as_millis()).unwrap_or(i64::MAX); + // One simple-query message: both statements cost one round trip. + format!( + "{}; SET LOCAL statement_timeout = '{timeout_ms}ms'", + ::BEGIN_READ_SNAPSHOT + ) + } -/// Execute a compiled PostgreSQL plan on a caller-owned repeatable read -/// snapshot. The caller configures `SET LOCAL statement_timeout` once for the -/// complete physical-query/evidence transaction. -#[cfg(feature = "postgres")] -pub(crate) async fn execute_postgres_in_connection( - connection: &mut sqlx::PgConnection, - plan: &SqlPlan, -) -> Result { - fetch_postgres_value(&mut *connection, plan).await -} + async fn fetch( + connection: &mut sqlx::PgConnection, + plan: &SqlPlan, + primary: bool, + ) -> Result { + use sqlx::Row; -#[cfg(feature = "postgres")] -async fn fetch_postgres_value<'e, E>(executor: E, plan: &SqlPlan) -> Result -where - E: sqlx::Executor<'e, Database = sqlx::Postgres>, -{ - use sqlx::Row; - let qb = apply_binds!( - sqlx::query(sqlx::AssertSqlSafe(plan.sql.clone())), - &plan.binds - ); - let row = qb - .fetch_optional(executor) - .await - .map_err(|e| format!("postgres execute: {e}"))?; - - // Postgres returns `json`/`jsonb` which sqlx decodes as `Json` when the - // `json` feature is on; some plans also cast to text. Accept both. - let json: JsonValue = match row { - Some(r) => { - if let Ok(j) = r.try_get::, _>(0) { - j.0 - } else if let Ok(s) = r.try_get::(0) { - serde_json::from_str(&s).map_err(|e| format!("json decode: {e}"))? - } else if let Ok(Some(s)) = r.try_get::, _>(0) { - serde_json::from_str(&s).map_err(|e| format!("json decode: {e}"))? - } else if let Ok(None) = r.try_get::, _>(0) { - JsonValue::Null - } else { - return Err("postgres json column: unsupported type".into()); - } + // Only gateway builds route reads to replicas, so only they check + // that the "primary" connection is not a standby. The check rides + // in the plan's statement, on the same connection and snapshot. + let check_primary = cfg!(feature = "gateway") && primary; + let sql: Arc = if check_primary { + format!("SELECT pg_is_in_recovery(), ({})", plan.sql).into() + } else { + Arc::clone(&plan.sql) + }; + let column = usize::from(check_primary); + let query = apply_binds!(sqlx::query(sqlx::AssertSqlSafe(sql)), &plan.binds); + let Some(row) = query.fetch_optional(&mut *connection).await? else { + return Ok(JsonValue::Null); + }; + if check_primary && row.try_get::(0)? { + return Err(ExecuteError::failed("authoritative primary is unavailable")); } - None => JsonValue::Null, - }; - finish_executed_value(json, plan) -} + // Plans select `json`; accept text too, as a JSON document. + if let Ok(json) = row.try_get::>, _>(column) { + return Ok(json.map_or(JsonValue::Null, |json| json.0)); + } + match row.try_get::, _>(column)? { + Some(text) => serde_json::from_str(&text) + .map_err(|error| ExecuteError::failed(format!("json decode: {error}"))), + None => Ok(JsonValue::Null), + } + } -fn finish_executed_value(mut json: JsonValue, plan: &SqlPlan) -> Result { - let evidence = plan.extract_evidence_and_strip(&mut json)?; - let value = Value::from_json(json).map_err(|e| format!("graphql value: {e}"))?; - Ok(ExecutedSql { value, evidence }) + #[cfg(feature = "gateway")] + fn gateway_versions<'c>( + store: &'c GatewayVersionStore, + connection: &'c mut sqlx::PgConnection, + tables: &'c [String], + ) -> impl Future> + Send + 'c { + store.postgres(connection, tables) + } } /// Rewrite hex-encoded Bytes paths to base64 (SQLite executor path). -pub fn rewrite_hex_bytes(json: &mut JsonValue, paths: &[String]) { +pub fn rewrite_hex_bytes(json: &mut serde_json::Value, paths: &[String]) { for path in paths { let parts: Vec<&str> = path.split('.').collect(); rewrite_path(json, &parts); } } -fn rewrite_path(json: &mut JsonValue, parts: &[&str]) { +fn rewrite_path(json: &mut serde_json::Value, parts: &[&str]) { + use serde_json::Value as JsonValue; if parts.is_empty() { return; } @@ -303,18 +461,10 @@ fn hex_to_base64(hex: &str) -> Option { Some(base64::engine::general_purpose::STANDARD.encode(bytes)) } -#[allow(dead_code)] -pub fn dialect_name(d: SqlDialect) -> &'static str { - match d { - SqlDialect::Postgres => "postgres", - SqlDialect::Sqlite => "sqlite", - } -} - /// Check the actual transaction connection, not another pool checkout. This /// detects a physical standby misbound/switched into the primary slot; it does /// not claim a general timeline or WAL replay routing implementation. -#[cfg(feature = "postgres")] +#[cfg(all(feature = "postgres", feature = "gateway"))] pub(crate) async fn ensure_primary_backend( connection: &mut sqlx::PgConnection, primary: bool, @@ -331,3 +481,44 @@ pub(crate) async fn ensure_primary_backend( let _ = (connection, primary); Ok(()) } + +#[cfg(test)] +mod statement_timeout_tests { + use super::{apply_statement_timeout, ExecuteError}; + use std::time::Duration; + + #[tokio::test(start_paused = true)] + async fn elapses_to_statement_timeout_error() { + let run = async { + tokio::time::sleep(Duration::from_secs(10)).await; + Ok::("never".into()) + }; + let handle = + tokio::spawn( + async move { apply_statement_timeout(Duration::from_millis(1), run).await }, + ); + tokio::time::advance(Duration::from_millis(5)).await; + let err = handle.await.expect("join").expect_err("budget must elapse"); + assert!(matches!(err, ExecuteError::Timeout), "{err}"); + } + + #[tokio::test(start_paused = true)] + async fn completes_when_under_budget() { + let run = async { Ok::("ok".into()) }; + let handle = + tokio::spawn(async move { apply_statement_timeout(Duration::from_secs(5), run).await }); + tokio::time::advance(Duration::from_millis(1)).await; + let v: String = handle.await.expect("join").expect("under budget"); + assert_eq!(v, "ok"); + } + + #[tokio::test(start_paused = true)] + async fn propagates_inner_error() { + let run = async { Err::(ExecuteError::Failed("sqlite execute: boom".into())) }; + let handle = + tokio::spawn(async move { apply_statement_timeout(Duration::from_secs(5), run).await }); + tokio::time::advance(Duration::from_millis(1)).await; + let err = handle.await.expect("join").expect_err("inner err"); + assert!(matches!(&err, ExecuteError::Failed(detail) if detail.contains("boom"))); + } +} diff --git a/src/graphql/mod.rs b/src/graphql/mod.rs index 8be0dab6..7013fe0c 100644 --- a/src/graphql/mod.rs +++ b/src/graphql/mod.rs @@ -15,7 +15,7 @@ pub mod surface; // pool/server independent. `distributed` and the runtime engine must compile the same // surface without pulling in async-graphql or a database adapter. mod commands; -mod complexity_contract; +mod cost; mod filter; mod permissions; @@ -31,12 +31,11 @@ pub use sdl::{ graphql_sdl_from_surface, SdlOptions, }; pub use surface::{ - build_surface, surface_for_application, surface_for_application_contract, surface_for_role, - RootField, RootKind, Surface, SurfaceArgument, SurfaceArgumentKind, SurfaceCommand, - SurfaceCommandShape, SurfaceDialect, SurfaceDirectProjection, SurfaceModel, - SurfaceModeledProjection, SurfaceOptions, SurfaceProjectionOwner, SurfaceProjector, - SurfaceRelationshipAggregate, SurfaceRelationshipKeys, SurfaceRowPolicy, SurfaceTypeDef, - SurfaceTypeField, + build_surface, surface_for_application, surface_for_role, RootField, RootKind, Surface, + SurfaceArgument, SurfaceArgumentKind, SurfaceCommand, SurfaceCommandShape, SurfaceDialect, + SurfaceDirectProjection, SurfaceModel, SurfaceModeledProjection, SurfaceOptions, + SurfaceProjectionOwner, SurfaceProjector, SurfaceRelationshipAggregate, + SurfaceRelationshipKeys, SurfaceRowPolicy, SurfaceTypeDef, SurfaceTypeField, }; pub use filter::{ @@ -47,8 +46,6 @@ pub use permissions::{read, ModelPermissions, ReadPermission}; #[cfg(feature = "graphql")] mod compile; #[cfg(feature = "graphql")] -mod complexity; -#[cfg(feature = "graphql")] mod engine; #[cfg(feature = "graphql")] mod execute; diff --git a/src/graphql/projection_delta/lower.rs b/src/graphql/projection_delta/lower.rs index 76f8f132..b853bfc7 100644 --- a/src/graphql/projection_delta/lower.rs +++ b/src/graphql/projection_delta/lower.rs @@ -35,7 +35,7 @@ use super::{ /// context, or projection source from different authorization selections. pub(crate) struct ProjectionDeltaAuthority<'a, R> { surface: &'a crate::graphql::surface::Surface, - manifest: crate::graphql::client_manifest::DistributedClientManifest, + manifest: &'a crate::graphql::client_manifest::DistributedClientManifest, context: ProjectionDeltaContext, authorization: SelectedSurfaceAuthorization<'a, R, R>, } @@ -64,10 +64,10 @@ where request: &'a R, ) -> Result { let manifest = export - .manifest() + .manifest_ref() .map_err(|_| ProjectionDeltaError::ProjectionIdentityMismatch)?; let context = ProjectionDeltaContext::from_manifest( - &manifest, + manifest, request.authorization_generation(), request.cache_scope(), request.command_causation_id(), @@ -107,7 +107,7 @@ where .ok_or(ProjectionDeltaError::ProjectionIdentityMismatch)?; ProjectionDeltaSource::try_from_export( selected_projection, - &self.manifest, + self.manifest, self.context.wire_identity(), ) } diff --git a/src/graphql/projection_delta/runtime.rs b/src/graphql/projection_delta/runtime.rs index 03a5c4d4..50d48c45 100644 --- a/src/graphql/projection_delta/runtime.rs +++ b/src/graphql/projection_delta/runtime.rs @@ -533,11 +533,11 @@ impl ProtocolProjectionRequestSeed { .with_trusted_presets(self.trusted_presets.clone()); let manifest = self .export - .manifest() + .manifest_ref() .map_err(|_| ProjectionRuntimeAuthorityError::InvalidAuthority)?; metadata .delta - .validate_replay_scope(&manifest, &authority) + .validate_replay_scope(manifest, &authority) .map_err(ProjectionRuntimeAuthorityError::Delta) } @@ -585,7 +585,7 @@ impl ProtocolProjectionRequestSeed { .with_trusted_presets(self.trusted_presets.clone()); let manifest = self .export - .manifest() + .manifest_ref() .map_err(|_| ProjectionRuntimeAuthorityError::InvalidAuthority)?; let identity = &metadata.delta.identity; // Lifecycle authority may be exercised against an unchanged outer @@ -768,7 +768,7 @@ impl ProtocolProjectionRequestSeed { .with_trusted_presets(self.trusted_presets.clone()); let manifest = self .export - .manifest() + .manifest_ref() .map_err(|_| ProjectionRuntimeAuthorityError::InvalidAuthority)?; let identity = &metadata.delta.identity; if identity.manifest_version != manifest.manifest_version @@ -1542,7 +1542,7 @@ impl ProtocolProjectionDeltaRequestAuthority { return Err(ProjectionRuntimeAuthorityError::InvalidAuthority); } export - .manifest() + .manifest_ref() .map_err(|_| ProjectionRuntimeAuthorityError::InvalidAuthority)?; let surface = export.surface().clone(); SelectedSurfacePolicyVisibility::try_new(&surface) @@ -1630,9 +1630,8 @@ impl ProtocolProjectionDeltaRequestAuthority { ) -> Result { delta .validate_replay_scope( - &self - .export - .manifest() + self.export + .manifest_ref() .map_err(|_| ProjectionRuntimeAuthorityError::InvalidAuthority)?, self, ) @@ -1645,7 +1644,7 @@ impl ProtocolProjectionDeltaRequestAuthority { let mut obligations = Vec::with_capacity(observations.len()); let manifest = self .export - .manifest() + .manifest_ref() .map_err(|_| ProjectionRuntimeAuthorityError::InvalidAuthority)?; for observation in observations { let projection = delta @@ -1734,7 +1733,7 @@ impl ProtocolProjectionDeltaRequestAuthority { } let manifest = self .export - .manifest() + .manifest_ref() .map_err(|_| ProjectionRuntimeAuthorityError::InvalidAuthority)?; if surface != &ProjectionDeltaSurfaceIdentity::from(&manifest.surface) { return Err(ProjectionRuntimeAuthorityError::InvalidAuthority); diff --git a/src/graphql/protocol/accumulator.rs b/src/graphql/protocol/accumulator.rs index 6f35c590..9b343797 100644 --- a/src/graphql/protocol/accumulator.rs +++ b/src/graphql/protocol/accumulator.rs @@ -405,7 +405,7 @@ impl ProtocolResponseAccumulator { /// Stable exact-index scope. The current head is excluded so later /// positions within the same projector/partition/query window compare. - #[allow(dead_code)] + #[cfg(test)] pub(crate) fn issue_index_scope( &self, snapshot_scope: &OpaqueProtocolToken, @@ -458,7 +458,7 @@ impl ProtocolResponseAccumulator { })? } - #[allow(dead_code)] + #[cfg(test)] pub(crate) fn issue_live_resume( &self, projection: &str, @@ -502,7 +502,7 @@ impl ProtocolResponseAccumulator { /// Verify a client-returned cursor against one server-derived static /// projector scope. The public projection/position fields select the /// finite candidate; hidden topology/partition/epoch remain MAC-bound. - #[allow(dead_code)] + #[cfg(test)] pub(crate) fn verify_live_resume( &self, supplied: &DistributedLiveCursor, @@ -923,7 +923,7 @@ impl ProtocolResponseAccumulator { Ok(()) } - #[allow(dead_code)] + #[cfg(any(test, feature = "gateway"))] pub(crate) fn snapshot(&self) -> Result { self.inner .envelope diff --git a/src/graphql/query_protocol.rs b/src/graphql/query_protocol.rs index 06adef96..9ef85a54 100644 --- a/src/graphql/query_protocol.rs +++ b/src/graphql/query_protocol.rs @@ -8,15 +8,10 @@ use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; -use async_graphql::Value; #[cfg(any(feature = "sqlite", feature = "postgres"))] use sqlx::{Encode, Executor, IntoArguments, Type}; use super::compile::{ExtractedQueryEvidence, QueryResponsePathSegment, SqlPlan}; -use super::engine::EngineInner; -use super::engine::GraphqlPool; -#[cfg(any(feature = "sqlite", feature = "postgres"))] -use super::execute; use super::protocol::{ DistributedIndexRevision, DistributedLiveMetadata, DistributedLiveMode, DistributedQuerySnapshot, DistributedRecordRevision, ProtocolResponseAccumulator, @@ -33,7 +28,7 @@ use crate::projection_protocol::{ #[cfg(any(feature = "sqlite", feature = "postgres"))] use crate::sqlx_repo::projection_protocol::{ read_projection_changes_in_executor, read_projection_live_record_batch_in_executor, - read_projection_partition_snapshot_in_executor, with_projection_read_snapshot, + read_projection_partition_snapshot_in_executor, }; #[cfg(any(feature = "sqlite", feature = "postgres"))] use crate::sqlx_repo::repo::SqlxRepoBackend; @@ -239,11 +234,6 @@ impl QueryProtocolRuntime { } } - #[allow(dead_code)] - pub(crate) fn is_empty(&self) -> bool { - self.projectors.is_empty() - } - #[cfg(test)] pub(crate) fn topology_for_model( &self, @@ -539,12 +529,6 @@ fn validate_modeled_partition_binding( Ok(()) } -pub(crate) struct ProtocolQueryExecution { - pub(crate) value: Value, - pub(crate) snapshot: DistributedQuerySnapshot, - pub(crate) live: Option, -} - struct PreparedRecordProbe { request: ProjectionLiveRecordRequest, paths: Vec>, @@ -573,198 +557,18 @@ struct PreparedLiveMetadata { changes: Vec, } -/// Execute the physical query and all record/index evidence reads inside one -/// adapter snapshot. The returned GraphQL value has already had every hidden -/// compiler key removed. -#[cfg(any(feature = "sqlite", feature = "postgres"))] -pub(crate) async fn execute_query_with_protocol( - inner: &EngineInner, - pool: &GraphqlPool, - primary: bool, - role_surface: Arc, - accumulator: ProtocolResponseAccumulator, - plan: &SqlPlan, - live_resume: Option, -) -> Result { - #[derive(serde::Serialize)] - struct QueryPlanInstance<'a> { - domain: &'static str, - version: u32, - sql: &'a str, - binds: &'a [super::compile::BindValue], - tables: &'a [String], - } - - // Query and subscription documents retain distinct public operation - // hashes, but matching compiler plans share one comparable snapshot scope. - // This prevents a lagging refresh from being treated as authoritative over - // a newer live frame merely because the transport operation differs. - accumulator - .bind_query_snapshot_scope(&QueryPlanInstance { - domain: "distributed.graphql.query-plan-instance", - version: 1, - sql: &plan.sql, - binds: &plan.binds, - tables: &plan.tables_touched, - }) - .map_err(|error| format!("query snapshot scope failed: {error}"))?; - - // The snapshot helper accepts an HRTB closure whose returned future may - // borrow only its connection. Keep every other input owned by the closure - // so plan/runtime references cannot escape into that future. - let _ = primary; - let plan = plan.clone(); - let runtime = inner.query_protocol.clone(); - let statement_timeout = inner.statement_timeout; - #[cfg(feature = "gateway")] - let gateway_versions = inner.gateway_versions.clone(); - match pool { - #[cfg(feature = "sqlite")] - GraphqlPool::Sqlite(pool) => { - let run = with_projection_read_snapshot(pool, move |connection| { - let role_surface = Arc::clone(&role_surface); - let accumulator = accumulator.clone(); - let plan = plan.clone(); - let runtime = runtime.clone(); - let live_resume = live_resume.clone(); - #[cfg(feature = "gateway")] - let gateway_versions = gateway_versions.clone(); - Box::pin(async move { - #[cfg(feature = "gateway")] - if let Some(store) = &gateway_versions { - store.record_result(); - } - let executed = execute::execute_sqlite_in_connection(connection, &plan) - .await - .map_err(query_execution_error)?; - let result = finish_protocol_query::( - connection, - &runtime, - &role_surface, - &accumulator, - &plan, - executed, - live_resume, - ) - .await?; - #[cfg(feature = "gateway")] - if accumulator.gateway_enabled() { - if let Some(store) = &gateway_versions { - if store.covers(&plan.tables_touched) { - let versions = store - .sqlite(connection, &plan.tables_touched) - .await - .map_err(query_execution_error)?; - accumulator - .record_gateway_versions(&versions) - .map_err(query_execution_error)?; - } - } - } - Ok(result) - }) - }); - execute::apply_statement_timeout(statement_timeout, async { - run.await.map_err(|error| error.to_string()) - }) - .await - } - #[cfg(feature = "postgres")] - GraphqlPool::Postgres(pool) => { - let run = with_projection_read_snapshot(pool, move |connection| { - let role_surface = Arc::clone(&role_surface); - let accumulator = accumulator.clone(); - let plan = plan.clone(); - let runtime = runtime.clone(); - let live_resume = live_resume.clone(); - #[cfg(feature = "gateway")] - let gateway_versions = gateway_versions.clone(); - Box::pin(async move { - let timeout_ms = - i64::try_from(statement_timeout.as_millis()).unwrap_or(i64::MAX); - sqlx::query(sqlx::AssertSqlSafe(format!( - "SET LOCAL statement_timeout = '{timeout_ms}ms'" - ))) - .execute(&mut *connection) - .await - .map_err(|error| { - query_execution_error(format!("statement_timeout: {error}")) - })?; - execute::ensure_primary_backend(connection, primary) - .await - .map_err(query_execution_error)?; - #[cfg(feature = "gateway")] - if let Some(store) = &gateway_versions { - store.record_result(); - } - let executed = execute::execute_postgres_in_connection(connection, &plan) - .await - .map_err(query_execution_error)?; - let result = finish_protocol_query::( - connection, - &runtime, - &role_surface, - &accumulator, - &plan, - executed, - live_resume, - ) - .await?; - #[cfg(feature = "gateway")] - if accumulator.gateway_enabled() { - if let Some(store) = &gateway_versions { - if store.covers(&plan.tables_touched) { - let versions = store - .postgres(connection, &plan.tables_touched) - .await - .map_err(query_execution_error)?; - accumulator - .record_gateway_versions(&versions) - .map_err(query_execution_error)?; - } - } - } - Ok(result) - }) - }); - execute::apply_statement_timeout(statement_timeout, async { - run.await.map_err(|error| error.to_string()) - }) - .await - } - #[allow(unreachable_patterns)] - _ => Err("no database pool available for GraphQL execution".into()), - } -} - -#[cfg(not(any(feature = "sqlite", feature = "postgres")))] -pub(crate) async fn execute_query_with_protocol( - _inner: &EngineInner, - _pool: &GraphqlPool, - _primary: bool, - _role_surface: Arc, - _accumulator: ProtocolResponseAccumulator, - _plan: &SqlPlan, - _live_resume: Option, -) -> Result { - Err("no database pool available for GraphQL execution".into()) -} - +/// Read every record/index evidence row a query result needs, inside the +/// result's own snapshot (`connection`), and assemble the wire metadata. #[cfg(any(feature = "sqlite", feature = "postgres"))] -fn query_execution_error(error: String) -> ProjectionProtocolError { - ProjectionProtocolError::InvalidBatch(format!("GraphQL query snapshot failed: {error}")) -} - -#[cfg(any(feature = "sqlite", feature = "postgres"))] -async fn finish_protocol_query( +pub(crate) async fn finish_protocol_query( connection: &mut DB::Connection, runtime: &QueryProtocolRuntime, role_surface: &Surface, accumulator: &ProtocolResponseAccumulator, plan: &SqlPlan, - executed: execute::ExecutedSql, + evidence: ExtractedQueryEvidence, live_resume: Option, -) -> Result +) -> Result<(DistributedQuerySnapshot, Option), ProjectionProtocolError> where DB: SqlxRepoBackend, for<'c> &'c mut DB::Connection: Executor<'c, Database = DB>, @@ -776,7 +580,7 @@ where for<'q> &'q [u8]: Encode<'q, DB> + Type, for<'r> &'r str: sqlx::ColumnIndex, { - let prepared = prepare_query_evidence(runtime, role_surface, plan, executed.evidence)?; + let prepared = prepare_query_evidence(runtime, role_surface, plan, evidence)?; // Store evidence batches are deliberately capped at 128 to bound one SQL // statement. A query snapshot may carry up to 4,096 records, so read it in // bounded chunks inside this same database snapshot and preserve positional @@ -849,11 +653,7 @@ where snapshot.indexes.clear(); snapshot.observations.clear(); } - Ok(ProtocolQueryExecution { - value: executed.value, - snapshot, - live, - }) + Ok((snapshot, live)) } fn prepare_query_evidence( diff --git a/src/graphql/read_store.rs b/src/graphql/read_store.rs index d501cd45..b09da7b6 100644 --- a/src/graphql/read_store.rs +++ b/src/graphql/read_store.rs @@ -144,7 +144,9 @@ impl ReadStore { #[cfg(all(test, feature = "sqlite"))] mod tests { use super::*; - use crate::graphql::compile::{compile_query, QueryPlan, RootKind, SelectionNode}; + use crate::graphql::compile::{ + compile_query, CompileError, QueryPlan, RootKind, SelectionNode, + }; use crate::graphql::{claim, col, read, GraphqlEngine, ModelPermissions, ReadStore}; use crate::microsvc::Session; use crate::ReadModel; @@ -350,7 +352,10 @@ mod tests { &list_selection(), ) .unwrap_err(); - assert!(list.contains("fan out to N cells"), "{list}"); + assert!( + matches!(&list, CompileError::UnsupportedOnCellStore(detail) if detail.contains("fan out to N cells")), + "{list}" + ); let mut filtered = by_pk_selection("g1"); filtered.args.insert( @@ -366,7 +371,7 @@ mod tests { &filtered, ) .unwrap_err(); - assert!(filter.contains("filter"), "{filter}"); + assert!(filter.to_string().contains("filter"), "{filter}"); let join = compile_query( &engine.inner, @@ -377,7 +382,7 @@ mod tests { &by_pk_with_owner_join("g1"), ) .unwrap_err(); - assert!(join.contains("join"), "{join}"); + assert!(join.to_string().contains("join"), "{join}"); } #[tokio::test] diff --git a/src/graphql/schema.rs b/src/graphql/schema.rs index 626713ee..18645d98 100644 --- a/src/graphql/schema.rs +++ b/src/graphql/schema.rs @@ -9,8 +9,9 @@ use async_graphql::dynamic::{ }; use async_graphql::Value; -use super::compile::{self, QueryPlan, RootKind}; +use super::compile::{self, CompileError, QueryPlan, RootKind}; use super::engine::{EngineInner, ExecutionAuthority}; +use super::execute::{execute_plan, ProtocolRead}; use super::naming::{ bool_exp_name, causal_protocol_type_names, comparison_exp_name, order_by_name, COMMAND_STATUS_ROOT_FIELD, CUSTOM_SCALARS, DISTRIBUTED_COMMAND_STATE_TYPE, @@ -27,7 +28,7 @@ use crate::microsvc::Session; pub fn build_role_schema( role_surface: &Surface, max_depth: usize, - max_complexity: usize, + max_fields: usize, disable_introspection: bool, ) -> Result { let has_causal_commands = !role_surface.commands.is_empty(); @@ -279,43 +280,31 @@ pub fn build_role_schema( let authority = ctx.data_opt::().cloned(); let protocol = ctx.data_opt::().cloned(); #[cfg(feature = "gateway")] - let captured = ctx.data_opt::().cloned(); + let recorder = ctx.data_opt::().cloned(); let selection = compile::selection_from_field(ctx.field()); SubscriptionFieldFuture::new(async move { let inner = inner.ok_or_else(|| { async_graphql::Error::new("GraphqlEngine not in request data") })?; let role = execution_privilege(authority.as_ref())?; + let plan = compile::compile_query( + &inner, + &session, + &role, + &model, + compile::RootKind::List, + &selection, + ) + .map_err(|error| compile_client_error(&error))?; #[cfg(feature = "gateway")] - if let Some(captured) = captured { - let plan = compile::compile_query( - &inner, - &session, - &role, - &model, - compile::RootKind::List, - &selection, - ) - .map_err(async_graphql::Error::new)?; - if let compile::QueryPlan::Sql(plan) = plan { - captured - .0 - .lock() - .map_err(|_| { - async_graphql::Error::new("plan capture unavailable") - })? - .push(plan); - return Err(async_graphql::Error::new(super::delivery::CAPTURED)); - } - return Err(async_graphql::Error::new( - "query is ineligible for delivery reuse", - )); + if let Some(recorder) = recorder { + return Err::( + recorder.record(plan), + ); } - let stream = super::subscribe::live_query_stream( - inner, session, role, model, selection, protocol, - ) - .await - .map_err(async_graphql::Error::new)?; + let stream = + super::subscribe::live_query_stream(inner, role, plan, protocol) + .await?; Ok(stream) }) }, @@ -372,7 +361,9 @@ pub fn build_role_schema( let mut builder = builder .limit_depth(max_depth) - .limit_complexity(max_complexity); + // Every field costs 1 by default, so async-graphql's "complexity" is + // the document's field count. + .limit_complexity(max_fields); if disable_introspection { builder = builder.disable_introspection(); } @@ -755,14 +746,10 @@ async fn execute_cell_by_key( fn lookup_key(value: &Value, key: &str) -> Option { match value { - Value::Object(map) => { - for (k, v) in map { - if k.as_str() == key { - return (!matches!(v, Value::Null)).then(|| v.clone()); - } - } - None - } + Value::Object(map) => map + .get(key) + .filter(|value| !matches!(value, Value::Null)) + .cloned(), _ => None, } } @@ -787,18 +774,8 @@ async fn resolve_root( let plan = compile::compile_query(&inner, &session, &role, model, kind, &selection) .map_err(|e| compile_client_error(&e))?; #[cfg(feature = "gateway")] - if let Some(captured) = ctx.data_opt::() { - if let QueryPlan::Sql(plan) = plan { - let mut plans = captured - .0 - .lock() - .map_err(|_| client_error("INTERNAL", "plan capture unavailable"))?; - plans.push(plan); - return Err(async_graphql::Error::new(super::delivery::CAPTURED)); - } - return Err(async_graphql::Error::new( - "query is ineligible for delivery reuse", - )); + if let Some(recorder) = ctx.data_opt::() { + return Err(recorder.record(plan)); } let value = match plan { QueryPlan::CellByKey { @@ -814,30 +791,26 @@ async fn resolve_root( let (pool, primary) = ctx .data_opt::() .map_or((pool, primary), |read| read.pool(&inner, &plan)); - if let Some(protocol) = ctx.data_opt::().cloned() { - let role_surface = inner.role_surfaces.get(&role).cloned().ok_or_else(|| { - client_error("INTERNAL", "authorized GraphQL role surface is unavailable") - })?; - let executed = super::query_protocol::execute_query_with_protocol( - &inner, - pool, - primary, - role_surface, - protocol.clone(), - &plan, - None, - ) + let protocol = ctx.data_opt::(); + let read = match protocol { + None => None, + Some(accumulator) => Some(ProtocolRead { + role_surface: inner.role_surfaces.get(&role).cloned().ok_or_else(|| { + client_error("INTERNAL", "authorized GraphQL role surface is unavailable") + })?, + accumulator: accumulator.clone(), + live_resume: None, + }), + }; + let executed = execute_plan(&inner, pool, primary, &plan, read) .await - .map_err(|e| client_error_for_execute_err(&e))?; - protocol - .record_query_metadata(executed.snapshot, None) + .map_err(|error| error.client_error())?; + if let (Some(accumulator), Some(evidence)) = (protocol, executed.protocol) { + accumulator + .record_query_metadata(evidence.snapshot, None) .map_err(|_| client_error("INTERNAL", "query evidence encoding failed"))?; - executed.value - } else { - super::execute::execute_sql_on_pool(&inner, pool, primary, &plan) - .await - .map_err(|e| client_error_for_execute_err(&e))? } + executed.value } }; // `None` (not `Some(Null)`) so nullable by_pk roots do not try to resolve @@ -878,53 +851,10 @@ pub const ENGINE_ERROR_CODES: &[&str] = &[ "CONCURRENT_WRITE", // command mutations; nothing committed, retry ]; -/// Map executor error strings to stable client errors (`extensions.code`). -pub(crate) fn client_error_for_execute_err(e: &str) -> async_graphql::Error { - if e.contains("timeout") { - client_error("TIMEOUT", "statement timeout") - } else { - client_error("INTERNAL", "internal error") - } -} - -/// A compile failure as the client sees it: a schema/compiler disagreement -/// is the server's fault, anything else the request's. -fn compile_client_error(e: &str) -> async_graphql::Error { - if e.starts_with("internal:") { - client_error("INTERNAL", "internal error") - } else { - client_error("BAD_REQUEST", sanitize_compile_error(e)) - } -} - -fn sanitize_compile_error(e: &str) -> String { - // Stable short messages; never return raw SQL. - if e.contains("max depth") { - "max depth exceeded".into() - } else if e.contains("too complex") || e.contains("query too complex") { - "query too complex".into() - } else if e.contains("max_in_list") - || e.contains("_in list") - || e.contains("max_bool_width") - || e.contains("_and list") - || e.contains("_or list") - { - "list too long".into() - } else if e.contains("invalid GraphQL response key") { - "invalid response key".into() - } else if e.contains("unknown comparison") - || e.contains("unknown where field") - || e.contains("ungranted where") - || e.contains("unknown order_by") - || e.contains("ungranted order_by") - || e.contains("ambiguous order_by") - { - "invalid filter".into() - } else if e.contains("cell-by-key") { - "unsupported on cell store".into() - } else { - "bad request".into() - } +/// A compile failure as the client sees it: a fixed code and message per +/// [`CompileError`] variant, never the detail (which may name SQL or limits). +pub(crate) fn compile_client_error(error: &CompileError) -> async_graphql::Error { + client_error(error.client_code(), error.client_message()) } pub(crate) fn client_error(code: &str, message: impl Into) -> async_graphql::Error { @@ -951,7 +881,15 @@ pub(crate) fn client_error_with_status( #[cfg(test)] mod execute_err_mapping_tests { - use super::{client_error_for_execute_err, sanitize_compile_error, ENGINE_ERROR_CODES}; + use super::{compile_client_error, CompileError, ENGINE_ERROR_CODES}; + use crate::graphql::execute::ExecuteError; + + fn code(err: &async_graphql::Error) -> String { + match err.extensions.as_ref().and_then(|ext| ext.get("code")) { + Some(async_graphql::Value::String(code)) => code.clone(), + other => panic!("expected a string code, got {other:?}"), + } + } #[test] fn engine_error_codes_closed_set_v1() { @@ -976,84 +914,68 @@ mod execute_err_mapping_tests { #[test] fn statement_timeout_maps_to_timeout_code() { - let err = client_error_for_execute_err("statement timeout"); + let err = ExecuteError::Timeout.client_error(); assert_eq!(err.message, "statement timeout"); - let code = err - .extensions - .as_ref() - .and_then(|ext| ext.get("code")) - .map(|v| format!("{v:?}")); - assert!( - code.as_deref() - .map(|c| c.contains("TIMEOUT")) - .unwrap_or(false), - "expected TIMEOUT extension, got {code:?}" - ); + assert_eq!(code(&err), "TIMEOUT"); } #[test] - fn other_errors_map_to_internal() { - let err = client_error_for_execute_err("sqlite execute: boom"); + fn other_execute_errors_map_to_internal_without_detail() { + // The word "timeout" in a detail no longer decides the code. + let err = ExecuteError::Failed("pool timeout: secret dsn".into()).client_error(); assert_eq!(err.message, "internal error"); - let code = err - .extensions - .as_ref() - .and_then(|ext| ext.get("code")) - .map(|v| format!("{v:?}")); - assert!( - code.as_deref() - .map(|c| c.contains("INTERNAL")) - .unwrap_or(false), - "expected INTERNAL extension, got {code:?}" - ); + assert_eq!(code(&err), "INTERNAL"); } #[test] - fn sanitize_compile_error_table() { - assert_eq!( - sanitize_compile_error("max depth exceeded"), - "max depth exceeded" - ); - assert_eq!( - sanitize_compile_error("_and list length 999 exceeds max_bool_width 256"), - "list too long" - ); - assert_eq!( - sanitize_compile_error("_in list length 500 exceeds max_in_list 100"), - "list too long" - ); - assert_eq!( - sanitize_compile_error("invalid GraphQL response key `x y`"), - "invalid response key" - ); - assert_eq!( - sanitize_compile_error("unknown comparison op `_wat`"), - "invalid filter" - ); - assert_eq!( - sanitize_compile_error("unknown where field `nope`"), - "invalid filter" - ); - assert_eq!( - sanitize_compile_error("ungranted order_by column `secret`"), - "invalid filter" - ); - assert_eq!( - sanitize_compile_error( - "ambiguous order_by entry: use one field per list entry to declare priority" + fn compile_errors_map_by_variant_never_by_detail() { + let cases = [ + (CompileError::TooDeep, "BAD_REQUEST", "max depth exceeded"), + ( + CompileError::TooManyRows { + rows: 1_001_000, + max_rows: 20_000, + }, + "BAD_REQUEST", + "row budget exceeded", ), - "invalid filter" - ); - assert_eq!( - sanitize_compile_error("SELECT * FROM secret"), - "bad request" - ); - assert_eq!( - sanitize_compile_error( - "cell-by-key store does not support list queries (would fan out to N cells); declare a SQL index read model" + ( + CompileError::ListTooLong("_in list length 500 exceeds max_in_list 100".into()), + "BAD_REQUEST", + "list too long", ), - "unsupported on cell store" - ); + ( + CompileError::InvalidResponseKey("x y".into()), + "BAD_REQUEST", + "invalid response key", + ), + ( + CompileError::InvalidFilter("unknown where field `nope`".into()), + "BAD_REQUEST", + "invalid filter", + ), + ( + CompileError::UnsupportedOnCellStore("list on cell store".into()), + "BAD_REQUEST", + "unsupported on cell store", + ), + ( + // A detail that names a limit does not leak or reclassify. + CompileError::BadRequest("SELECT * FROM secret max depth".into()), + "BAD_REQUEST", + "bad request", + ), + ( + CompileError::internal("no join key for `secret`"), + "INTERNAL", + "internal error", + ), + ]; + for (error, expected_code, expected_message) in cases { + let err = compile_client_error(&error); + assert_eq!(code(&err), expected_code, "{error:?}"); + assert_eq!(err.message, expected_message, "{error:?}"); + } } } diff --git a/src/graphql/sdl.rs b/src/graphql/sdl.rs index 9231c70c..8930e3e8 100644 --- a/src/graphql/sdl.rs +++ b/src/graphql/sdl.rs @@ -6,7 +6,7 @@ use std::collections::{BTreeMap, BTreeSet}; -use crate::table::{TableKind, TableSchema}; +use crate::table::TableSchema; use super::naming::{ causal_protocol_type_names, comparison_exp_name, include_postgres_json_comparison_ops, @@ -623,17 +623,6 @@ fn surface_arguments_sdl(arguments: &[super::surface::SurfaceArgument]) -> Strin format!("({arguments})") } -/// Filter operational tables and render SDL for a read-model schema catalog. -pub fn graphql_sdl_from_schemas( - schemas: impl IntoIterator, -) -> Result { - let tables: Vec = schemas - .into_iter() - .filter(|t| matches!(t.kind, TableKind::ReadModel)) - .collect(); - graphql_sdl_for_tables(&tables) -} - #[cfg(test)] mod causal_command_sdl_tests { use super::*; diff --git a/src/graphql/subscribe.rs b/src/graphql/subscribe.rs index e800fbcf..7f8f266d 100644 --- a/src/graphql/subscribe.rs +++ b/src/graphql/subscribe.rs @@ -23,12 +23,13 @@ use async_graphql::Value; use futures_util::Stream; use tokio::sync::{broadcast, mpsc}; -use crate::microsvc::Session; use crate::read_model::ReadModelChange; -use super::compile::{self, RootKind, SelectionNode, SqlPlan}; -use super::engine::{execute_plan, EngineInner}; +use super::compile::{QueryPlan, SqlPlan}; +use super::engine::EngineInner; +use super::execute::{execute_plan, ProtocolRead}; use super::protocol::{ProtocolResponseAccumulator, RequestedLiveResume}; +use super::schema::client_error; /// Fan-out hub for read-model change notifications. #[derive(Clone, Debug)] @@ -103,26 +104,17 @@ impl Stream for LiveQueryStream { } } -/// Build a live-query stream for a subscription root field. +/// Build a live-query stream for a subscription root field's compiled plan. pub(crate) async fn live_query_stream( inner: Arc, - session: Session, role: String, - model: String, - selection: SelectionNode, + plan: QueryPlan, protocol: Option, -) -> Result { - let plan: SqlPlan = match compile::compile_query( - &inner, - &session, - &role, - &model, - RootKind::List, - &selection, - )? { - compile::QueryPlan::Sql(plan) => plan, - compile::QueryPlan::CellByKey { .. } => { - return Err("cell-by-key store does not support @live".into()); +) -> Result { + let plan: Arc = match plan { + QueryPlan::Sql(plan) => plan, + QueryPlan::CellByKey { .. } => { + return Err(client_error("BAD_REQUEST", "unsupported on cell store")); } }; let footprint = footprint_from_tables(&plan.tables_touched); @@ -133,7 +125,7 @@ pub(crate) async fn live_query_stream( .as_ref() .map(ProtocolResponseAccumulator::requested_live_resume) .transpose() - .map_err(|error| error.to_string())? + .map_err(|_| client_error("BAD_REQUEST", "invalid live resume"))? .unwrap_or(RequestedLiveResume::Absent); tokio::spawn(async move { @@ -144,13 +136,13 @@ pub(crate) async fn live_query_stream( }; let mut initial = match initial_result { Ok(executed) => executed, - Err(e) => { - let _ = tx.send(Err(async_graphql::Error::new(e))).await; + Err(error) => { + let _ = tx.send(Err(error)).await; return; } }; - if let Err(error) = initial.record_protocol_metadata(protocol.as_ref()) { - let _ = tx.send(Err(async_graphql::Error::new(error))).await; + if initial.record_protocol_metadata(protocol.as_ref()).is_err() { + let _ = tx.send(Err(evidence_failed())).await; return; } let mut last_hash = Some(initial.hash); @@ -207,8 +199,11 @@ pub(crate) async fn live_query_stream( if last_hash == Some(executed.hash) { continue; // hash gate: no push on no-change } - if let Err(error) = executed.record_protocol_metadata(protocol.as_ref()) { - let _ = tx.send(Err(async_graphql::Error::new(error))).await; + if executed + .record_protocol_metadata(protocol.as_ref()) + .is_err() + { + let _ = tx.send(Err(evidence_failed())).await; return; } last_hash = Some(executed.hash); @@ -216,8 +211,8 @@ pub(crate) async fn live_query_stream( return; } } - Err(e) => { - let _ = tx.send(Err(async_graphql::Error::new(e))).await; + Err(error) => { + let _ = tx.send(Err(error)).await; return; } } @@ -227,6 +222,10 @@ pub(crate) async fn live_query_stream( Ok(LiveQueryStream { rx }) } +fn evidence_failed() -> async_graphql::Error { + client_error("INTERNAL", "query evidence encoding failed") +} + struct ExecutedLiveQuery { value: Value, hash: u64, @@ -259,35 +258,31 @@ async fn execute_list( plan: &SqlPlan, protocol: Option<&ProtocolResponseAccumulator>, requested_live_resume: RequestedLiveResume, -) -> Result { - let Some(protocol) = protocol else { - let value = execute_plan(inner, plan).await?; +) -> Result { + let read = match protocol { + None => None, + Some(accumulator) => Some(ProtocolRead { + role_surface: inner.role_surfaces.get(role).cloned().ok_or_else(|| { + client_error("INTERNAL", "authorized GraphQL role surface is unavailable") + })?, + accumulator: accumulator.clone(), + live_resume: Some(requested_live_resume), + }), + }; + let executed = execute_plan(inner, &inner.pool, true, plan, read) + .await + .map_err(|error| error.client_error())?; + let Some(evidence) = executed.protocol else { return Ok(ExecutedLiveQuery { - hash: response_hash(&value), - value, + hash: response_hash(&executed.value), + value: executed.value, snapshot: None, live: None, next_live_resume: RequestedLiveResume::Absent, }); }; - - let role_surface = inner - .role_surfaces - .get(role) - .cloned() - .ok_or_else(|| "authorized GraphQL role surface is unavailable".to_string())?; - let executed = super::query_protocol::execute_query_with_protocol( - inner, - &inner.pool, - true, - role_surface, - protocol.clone(), - plan, - Some(requested_live_resume), - ) - .await?; - let hash = protocol_response_hash(&executed.value, &executed.snapshot, &executed.live); - let next_live_resume = executed + let hash = hash_json(&(&executed.value, &evidence.snapshot, &evidence.live)); + let next_live_resume = evidence .live .as_ref() .filter(|live| live.mode == super::protocol::DistributedLiveMode::Resumable) @@ -296,8 +291,8 @@ async fn execute_list( Ok(ExecutedLiveQuery { value: executed.value, hash, - snapshot: Some(executed.snapshot), - live: executed.live, + snapshot: Some(evidence.snapshot), + live: evidence.live, next_live_resume, }) } @@ -317,30 +312,30 @@ pub fn footprint_from_tables(tables: &[String]) -> BTreeSet { /// Hash a GraphQL JSON payload for hash-gated push (no push on no-change). pub fn response_hash(value: &Value) -> u64 { - use std::collections::hash_map::DefaultHasher; - use std::hash::{Hash, Hasher}; - let mut h = DefaultHasher::new(); - if let Ok(json) = serde_json::to_string(value) { - json.hash(&mut h); - } else { - format!("{value:?}").hash(&mut h); - } - h.finish() + hash_json(value) } -fn protocol_response_hash( - value: &Value, - snapshot: &super::protocol::DistributedQuerySnapshot, - live: &Option, -) -> u64 { - use std::collections::hash_map::DefaultHasher; - use std::hash::{Hash, Hasher}; - let mut hash = DefaultHasher::new(); - match serde_json::to_string(&(value, snapshot, live)) { - Ok(encoded) => encoded.hash(&mut hash), - Err(_) => format!("{value:?}:{snapshot:?}:{live:?}").hash(&mut hash), +/// Hash the JSON encoding of `value` as it is produced, without building the +/// string. +fn hash_json(value: &impl serde::Serialize) -> u64 { + use std::hash::Hasher; + + struct HashWriter(std::collections::hash_map::DefaultHasher); + impl std::io::Write for HashWriter { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.0.write(bytes); + Ok(bytes.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } } - hash.finish() + + let mut writer = HashWriter(Default::default()); + // Encoding a GraphQL value cannot fail; if it ever did, the partial + // encoding still hashes deterministically. + let _ = serde_json::to_writer(&mut writer, value); + writer.0.finish() } /// Forward an external change receiver into the engine hub. diff --git a/src/graphql/surface/application.rs b/src/graphql/surface/application.rs index e53527fd..00dc9902 100644 --- a/src/graphql/surface/application.rs +++ b/src/graphql/surface/application.rs @@ -480,33 +480,6 @@ pub(in crate::graphql::surface) fn validate_surface_filter( Ok(()) } -/// Build an explicit named application surface as the structural intersection -/// of its declared schema roles, with a separate eligible opener set. -/// -/// A missing role declaration is an error rather than an accidental empty or -/// admin surface. Commands must be granted to every schema role. Differing row -/// predicates are all enforced (their conjunction) and exported as -/// `ServerOnly`, so the client revalidates membership without learning another -/// role's policy. -/// -/// Prefer [`surface_for_application_contract`] when eligible principals are a -/// superset of the schema privilege set (portable multi-role principals). -pub fn surface_for_application( - surface: &Surface, - application: &str, - eligible_roles: &[String], - schema_roles: &[String], - grants_by_role: &BTreeMap>, -) -> Result { - surface_for_application_contract( - surface, - application, - eligible_roles, - schema_roles, - grants_by_role, - ) -} - /// Build an application surface with distinct **eligible** and **schema** roles. /// /// - `eligible_roles`: protocol identity — who may open this client contract @@ -517,7 +490,13 @@ pub fn surface_for_application( /// /// Example: eligible `{admin,user}` + schema `{user}` keeps owner-portable /// optimism while multi-role admin principals may open the surface. -pub fn surface_for_application_contract( +/// +/// A missing role declaration is an error rather than an accidental empty or +/// admin surface. Commands must be granted to every schema role. Differing row +/// predicates are all enforced (their conjunction) and exported as +/// `ServerOnly`, so the client revalidates membership without learning another +/// role's policy. +pub fn surface_for_application( surface: &Surface, application: &str, eligible_roles: &[String], diff --git a/src/graphql/surface/mod.rs b/src/graphql/surface/mod.rs index d25d83e6..8c3f2f9f 100644 --- a/src/graphql/surface/mod.rs +++ b/src/graphql/surface/mod.rs @@ -45,9 +45,7 @@ mod validation; #[cfg(test)] mod tests; -pub use application::{ - surface_for_application, surface_for_application_contract, surface_for_role, -}; +pub use application::{surface_for_application, surface_for_role}; pub use build::build_surface; pub use external::{ ExternalField, ExternalReadError, ExternalReadErrorKind, ExternalReadExecutor, diff --git a/src/projection_protocol/store/mod.rs b/src/projection_protocol/store/mod.rs index 9e50dafd..3f2f2a52 100644 --- a/src/projection_protocol/store/mod.rs +++ b/src/projection_protocol/store/mod.rs @@ -81,3 +81,82 @@ pub use query::*; pub use r#trait::ProjectionChangeRead; pub(crate) use r#trait::ProjectionProtocolStore; pub(crate) use replay::SameTransactionProjectionEvidence; + +/// Every table the projection store writes that a query's causal evidence +/// (snapshot, records, observations, cursors, failures) can read. A cache that +/// stores a response with its evidence must invalidate on writes to all of +/// them, including no-op commits. +/// +/// `projection_input_delivery_aliases` is deliberately absent: it maps +/// redelivered message ids onto inputs at ingestion and no query evidence +/// reads it. `proof_tables_cover_every_projection_table` keeps this list +/// in step with the migrations. +pub const PROOF_TABLES: &[&str] = &[ + "projection_partitions", + "projection_generations", + "projection_source_capabilities", + "projection_input_identities", + "projection_input_cursors", + "projection_input_receipts", + "projection_table_ownership_fences", + "projection_causal_tables", + "projection_registered_models", + "projection_model_ownership", + "projection_records", + "projection_observations", + "projection_failures", + "projection_changes", +]; + +/// Projection-store tables that are not query evidence, with the reason. +#[cfg(test)] +const NOT_PROOF_TABLES: &[(&str, &str)] = &[( + "projection_input_delivery_aliases", + "ingestion-side message id aliasing; no query evidence reads it", +)]; + +#[cfg(test)] +mod proof_table_tests { + use super::{NOT_PROOF_TABLES, PROOF_TABLES}; + use std::collections::BTreeSet; + + fn created_projection_tables(dialect: &str) -> BTreeSet { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("migrations") + .join(dialect); + let mut tables = BTreeSet::new(); + for entry in std::fs::read_dir(&dir).expect("migrations directory") { + let sql = std::fs::read_to_string(entry.expect("migration").path()).expect("migration"); + for statement in sql.split("CREATE TABLE").skip(1) { + let name = statement + .trim_start() + .trim_start_matches("IF NOT EXISTS") + .trim_start() + .split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) + .next() + .unwrap_or_default(); + if name.starts_with("projection_") { + tables.insert(name.to_owned()); + } + } + } + tables + } + + #[test] + fn proof_tables_cover_every_projection_table() { + let listed: BTreeSet = PROOF_TABLES + .iter() + .chain(NOT_PROOF_TABLES.iter().map(|(table, _)| table)) + .map(|table| (*table).to_owned()) + .collect(); + assert_eq!(listed.len(), PROOF_TABLES.len() + NOT_PROOF_TABLES.len()); + for dialect in ["postgres", "sqlite"] { + assert_eq!( + created_projection_tables(dialect), + listed, + "{dialect}: a projection_* table must be in PROOF_TABLES or NOT_PROOF_TABLES" + ); + } + } +} diff --git a/tests/application_composition.rs b/tests/application_composition.rs index 07c8ee86..4e4cbeba 100644 --- a/tests/application_composition.rs +++ b/tests/application_composition.rs @@ -8,8 +8,8 @@ use distributed::application::{ }; use distributed::command::{typed_command, CommandConsistency, Succeeded}; use distributed::graphql::{ - build_surface, col, prune_client_manifest, read, surface_for_application_contract, - surface_for_role, ClientCommandPureReduce, ClientProjectionArm, ClientProjectionEventRef, + build_surface, col, prune_client_manifest, read, surface_for_application, surface_for_role, + ClientCommandPureReduce, ClientProjectionArm, ClientProjectionEventRef, ClientProjectionFallback, ClientProjectionMutationKind, ClientProjectionOperation, ClientProjectionPartition, ClientProjectionProgram, ClientSurfaceIdentity, CommandProjectionArmRef, CommandProjectionExtension, CommandProjectionPreviewOccurrence, @@ -345,7 +345,7 @@ fn selected_surface() -> Surface { .rows(col("status").eq("open")), )]), )]); - surface_for_application_contract(&full, "web", &["user".into()], &["user".into()], &grants) + surface_for_application(&full, "web", &["user".into()], &["user".into()], &grants) .expect("role/application-selected Surface should compile") } @@ -356,7 +356,7 @@ fn explicit_module_commands_filter_allowed_and_forbidden_role_application_invent let role = surface_for_role(&catalog, "user", &user_grants).unwrap(); assert_eq!(command_names(&role), vec!["todo.allowed"]); - let application = surface_for_application_contract( + let application = surface_for_application( &catalog, "web", &["admin".into(), "user".into()], @@ -401,7 +401,7 @@ fn role_and_application_command_closure_rejects_missing_unauthorized_and_tampere let module = command_module(); let catalog = command_catalog(); let user_grants = grants_for("user"); - let selected = surface_for_application_contract( + let selected = surface_for_application( &catalog, "web", &["admin".into(), "user".into()], @@ -431,7 +431,7 @@ fn role_and_application_command_closure_rejects_missing_unauthorized_and_tampere .expect_err("tampered selected command must fail closed"); assert!(error.to_string().contains("not compatible")); - let admin = surface_for_application_contract( + let admin = surface_for_application( &catalog, "admin-web", &["admin".into()], @@ -877,8 +877,7 @@ fn contract_export_prunes_unselected_read_models() { ]), )]); let selected = - surface_for_application_contract(&full, "web", &["user".into()], &["user".into()], &grants) - .unwrap(); + surface_for_application(&full, "web", &["user".into()], &["user".into()], &grants).unwrap(); let export = DistributedClientSurfaceExport::from_contract("todo-app", selected).unwrap(); let todos_only = prune_client_manifest(export.manifest().unwrap(), ["TodoView"]).unwrap(); assert!(todos_only @@ -912,14 +911,9 @@ fn prune_drops_unselected_command_optimism_and_causal_slots() { ]), )]); let catalog = full.with_module(&command_module()).unwrap(); - let selected = surface_for_application_contract( - &catalog, - "web", - &["user".into()], - &["user".into()], - &grants, - ) - .unwrap(); + let selected = + surface_for_application(&catalog, "web", &["user".into()], &["user".into()], &grants) + .unwrap(); let export = DistributedClientSurfaceExport::from_contract("todo-app", selected).unwrap(); let mut manifest = export.manifest().unwrap(); attach_todo_and_chat_command_optimism(&mut manifest); diff --git a/tests/e2e-celld/crates/graphql-service/src/modules/graphql.rs b/tests/e2e-celld/crates/graphql-service/src/modules/graphql.rs index cac1c821..d714a81c 100644 --- a/tests/e2e-celld/crates/graphql-service/src/modules/graphql.rs +++ b/tests/e2e-celld/crates/graphql-service/src/modules/graphql.rs @@ -2,7 +2,7 @@ use std::sync::Arc; use distributed::application::CommandDefinition; use distributed::graphql::{ - build_surface, surface_for_application_contract, DistributedClientSurfaceExport, GraphqlEngine, + build_surface, surface_for_application, DistributedClientSurfaceExport, GraphqlEngine, GraphqlPoolSource, IdentityConfig, OidcConfig, Surface, SurfaceOptions, }; use distributed::microsvc::Service; @@ -54,11 +54,7 @@ pub(crate) fn build_graphql_engine_with_graphiql( let mut b = GraphqlEngine::builder(pool) .protocol_token_key(E2E_PROTOCOL_TOKEN_KEY) .roles(&["user", "admin", "anonymous"]) - .client_application_surface_with_schema_roles( - DISTRIBUTED_CLIENT_SURFACE, - ["admin", "user"], - ["user"], - ) + .client_application_surface(DISTRIBUTED_CLIENT_SURFACE, ["admin", "user"], ["user"]) .client_application_surface(DISTRIBUTED_ADMIN_CLIENT_SURFACE, ["admin"], ["admin"]) .client_application_surface( DISTRIBUTED_PUBLIC_CLIENT_SURFACE, @@ -102,9 +98,8 @@ fn pool_free_client_surface_contract( .map(|role| (*role).to_string()) .collect::>(); let grants = e2e_readmodels::application_grants(); - let selected = - surface_for_application_contract(&full, application, &eligible, &schema, &grants) - .expect("e2e-ui application Surface should select"); + let selected = surface_for_application(&full, application, &eligible, &schema, &grants) + .expect("e2e-ui application Surface should select"); DistributedClientSurfaceExport::from_selected("e2e-ui", selected) .expect("e2e-ui application Surface should export") } diff --git a/tests/e2e-ui/crates/service/src/modules/graphql.rs b/tests/e2e-ui/crates/service/src/modules/graphql.rs index a026f62b..ab646888 100644 --- a/tests/e2e-ui/crates/service/src/modules/graphql.rs +++ b/tests/e2e-ui/crates/service/src/modules/graphql.rs @@ -2,7 +2,7 @@ use std::sync::Arc; use distributed::application::CommandDefinition; use distributed::graphql::{ - build_surface, surface_for_application_contract, DistributedClientSurfaceExport, GraphqlEngine, + build_surface, surface_for_application, DistributedClientSurfaceExport, GraphqlEngine, GraphqlPoolSource, IdentityConfig, OidcConfig, Surface, SurfaceOptions, }; use distributed::microsvc::Service; @@ -82,11 +82,7 @@ fn build_engine( let mut b = GraphqlEngine::builder(pool) .protocol_token_key(E2E_PROTOCOL_TOKEN_KEY) .roles(&["user", "admin", "anonymous"]) - .client_application_surface_with_schema_roles( - DISTRIBUTED_CLIENT_SURFACE, - ["admin", "user"], - ["user"], - ) + .client_application_surface(DISTRIBUTED_CLIENT_SURFACE, ["admin", "user"], ["user"]) .client_application_surface(DISTRIBUTED_ADMIN_CLIENT_SURFACE, ["admin"], ["admin"]) .client_application_surface( DISTRIBUTED_PUBLIC_CLIENT_SURFACE, @@ -133,9 +129,8 @@ fn pool_free_client_surface_contract( .map(|role| (*role).to_string()) .collect::>(); let grants = e2e_readmodels::application_grants(); - let selected = - surface_for_application_contract(&full, application, &eligible, &schema, &grants) - .expect("e2e-ui application Surface should select"); + let selected = surface_for_application(&full, application, &eligible, &schema, &grants) + .expect("e2e-ui application Surface should select"); DistributedClientSurfaceExport::from_selected("e2e-ui", selected) .expect("e2e-ui application Surface should export") } diff --git a/tests/e2e-ui/ui/src/lib/walkthrough/demos.ts b/tests/e2e-ui/ui/src/lib/walkthrough/demos.ts index 881aa2ef..a727cb88 100644 --- a/tests/e2e-ui/ui/src/lib/walkthrough/demos.ts +++ b/tests/e2e-ui/ui/src/lib/walkthrough/demos.ts @@ -1113,7 +1113,7 @@ pub struct Todos { { file: 'modules/graphql.rs · build_engine surfaces', caption: 'One engine opens three surfaces: user, admin, and public. Each surface names its eligible roles and its privilege pack.', - code: `.client_application_surface_with_schema_roles( + code: `.client_application_surface( DISTRIBUTED_CLIENT_SURFACE, // "e2e-ui" ["admin", "user"], // eligible ["user"], // portable privilege pack @@ -1314,7 +1314,7 @@ mutation DeleteTodo { { file: 'modules/graphql.rs · dual surfaces', caption: 'The service crate opens the user, admin, and public surfaces.', - code: `.client_application_surface_with_schema_roles( + code: `.client_application_surface( "e2e-ui", ["admin", "user"], ["user"], diff --git a/tests/fixtures/generated-draining-command-v2.json b/tests/fixtures/generated-draining-command-v2.json index 4b361259..0b355396 100644 --- a/tests/fixtures/generated-draining-command-v2.json +++ b/tests/fixtures/generated-draining-command-v2.json @@ -39,7 +39,7 @@ "protocol": { "operation": "sha256:bb3a777dd32f7d40cccc173fafdbc7464f5dc50a3d17587909689a880fb0205a", "protocolHash": "sha256:0dfa8a3f49e17d8d99c5c095c1ed14f528cae3e55fbc2f2b852975a50936ec5b", - "schemaHash": "sha256:181ea04cb527069d736d5820317115458480c3f08020ec7185ca5af5952d3fef", + "schemaHash": "sha256:7184334ee5a83894d7a7d9786f468a3b3460917a282c016a0da4b9639c2f6000", "surface": { "kind": "role", "name": "admin" diff --git a/tests/graphql_harden/dos.rs b/tests/graphql_harden/dos.rs index d337fa94..31477e9f 100644 --- a/tests/graphql_harden/dos.rs +++ b/tests/graphql_harden/dos.rs @@ -223,7 +223,7 @@ pub async fn d7_concurrent_with_timeout_bound_terminates(db: Db) { /// Nested has_many fan-out exceeds relationship-aware complexity budget while /// staying under max_depth (proves weights, not only depth). -pub async fn d8_nested_has_many_exceeds_complexity_budget(db: Db) { +pub async fn d8_two_level_default_nest_exceeds_row_budget(db: Db) { use distributed::graphql::{read, GraphqlEngine}; use distributed::ReadModel; use distributed::{ReadModelCatalog, RelationalReadModel, RelationshipDef, RelationshipKind}; @@ -289,7 +289,7 @@ pub async fn d8_nested_has_many_exceeds_complexity_budget(db: Db) { .table_schema(child) .table_schema(grand); - // Default max_complexity (500) + max_depth high enough that depth is not the limit. + // Default max_rows (200,000) + max_depth high enough that depth is not the limit. let engine = GraphqlEngine::from_schema_catalog(&manifest, pool) .unwrap() .identity(IdentityConfig::dev_headers()) @@ -302,7 +302,7 @@ pub async fn d8_nested_has_many_exceeds_complexity_budget(db: Db) { .expect("build"); let s = session("user", "u"); - // 3-level has_many: relationship weights push estimated cost above 500. + // Three default pages nested: 100 × (1 + 100 × (1 + 100)) = 1,010,100 rows. let q = r#"{ parents { parent_id @@ -319,17 +319,17 @@ pub async fn d8_nested_has_many_exceeds_complexity_budget(db: Db) { let resp = engine.execute(&s, Request::new(q)).await; assert!( !resp.errors.is_empty(), - "3-level nested has_many must exceed complexity budget" + "3-level nested has_many must exceed the row budget" ); assert_no_sql_leak(&resp); let msgs = error_messages(&resp); assert!( - msgs.contains("complex") || msgs.contains("bad request"), - "expected complexity client error, got {msgs}" + msgs.contains("row budget exceeded"), + "expected row budget client error, got {msgs}" ); } -/// Shallow nest stays under default complexity budget. +/// One default nest stays under the default row budget (100 × 101 = 10,100). pub async fn d8_shallow_nested_has_many_within_budget(db: Db) { use distributed::graphql::{read, GraphqlEngine}; use distributed::ReadModel; @@ -393,8 +393,8 @@ pub async fn d8_shallow_nested_has_many_within_budget(db: Db) { ); } -/// Explicit low max_complexity rejects modest nests (budget knob works). -pub async fn d8_low_max_complexity_rejects_single_nest(db: Db) { +/// Explicit low max_rows rejects modest nests (budget knob works). +pub async fn d8_low_max_rows_rejects_single_nest(db: Db) { use distributed::graphql::{read, GraphqlEngine}; use distributed::ReadModel; use distributed::{ReadModelCatalog, RelationalReadModel, RelationshipDef, RelationshipKind}; @@ -438,7 +438,7 @@ pub async fn d8_low_max_complexity_rejects_single_nest(db: Db) { .unwrap() .identity(IdentityConfig::dev_headers()) .roles(&["user"]) - .max_complexity(20) + .max_rows(10_099) .max_depth(8) .permission::("user", read().all_columns()) .permission::("user", read().all_columns()) @@ -458,8 +458,90 @@ pub async fn d8_low_max_complexity_rejects_single_nest(db: Db) { ); assert_no_sql_leak(&resp); let msgs = error_messages(&resp); + assert!(msgs.contains("row budget exceeded"), "{msgs}"); +} + +/// Regression: the row budget counts each list's resolved `limit`. +/// +/// The old weighted complexity estimate ignored `limit` entirely, so this +/// request (a shape `d8_shallow_nested_has_many_within_budget` shows the +/// defaults admit) was accepted although it can return 1000 × (1 + 1000) = +/// 1,001,000 rows, five times the default `max_rows`. Lowering the limits +/// to a product within budget is accepted. +pub async fn d8_explicit_limits_multiply_into_the_row_budget(db: Db) { + use distributed::graphql::{read, GraphqlEngine}; + use distributed::ReadModel; + use distributed::{ReadModelCatalog, RelationalReadModel, RelationshipDef, RelationshipKind}; + use serde::{Deserialize, Serialize}; + + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ReadModel)] + #[table("parents")] + struct ParentView { + #[id("parent_id")] + parent_id: String, + name: String, + } + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ReadModel)] + #[table("children")] + struct ChildView { + #[id("child_id")] + child_id: String, + parent_id: String, + name: String, + } + + db.seed([parent("p1", "P")]).await; + db.seed([child("c1", "p1", "C")]).await; + let pool = db.pool(); + + let mut parent = ParentView::schema().clone(); + parent.relationships = vec![RelationshipDef { + references: None, + field_name: "children".into(), + kind: RelationshipKind::HasMany, + target_model: "ChildView".into(), + foreign_key: Some("parent_id".into()), + through: None, + target_foreign_key: None, + }]; + let manifest = ReadModelCatalog::new("cx4") + .table_schema(parent) + .table_schema(ChildView::schema().clone()); + let engine = GraphqlEngine::from_schema_catalog(&manifest, pool) + .unwrap() + .identity(IdentityConfig::dev_headers()) + .roles(&["user"]) + .permission::("user", read().all_columns()) + .permission::("user", read().all_columns()) + .build() + .expect("build"); + + let s = session("user", "u"); + let resp = engine + .execute( + &s, + Request::new( + "{ parents(limit: 1000) { parent_id children(limit: 1000) { child_id } } }", + ), + ) + .await; + assert_no_sql_leak(&resp); assert!( - msgs.contains("complex") || msgs.contains("bad request"), - "{msgs}" + error_messages(&resp).contains("row budget exceeded"), + "1,001,000 rows must exceed the default row budget: {:?}", + resp.errors ); + + // 1000 × (1 + 199) = 200,000: exactly the default budget. + let resp = engine + .execute( + &s, + Request::new( + "{ parents(limit: 1000) { parent_id children(limit: 199) { child_id } } }", + ), + ) + .await; + assert!(resp.errors.is_empty(), "{:?}", resp.errors); + let data = resp.data.into_json().unwrap(); + assert_eq!(data["parents"][0]["children"][0]["child_id"], "c1"); } diff --git a/tests/graphql_harden/main.rs b/tests/graphql_harden/main.rs index d585e9fe..b019ec9b 100644 --- a/tests/graphql_harden/main.rs +++ b/tests/graphql_harden/main.rs @@ -63,9 +63,10 @@ on_each_dialect! { d5_wide_and_list_rejected_by_max_bool_width, d7_concurrent_queries_complete, d7_concurrent_with_timeout_bound_terminates, - d8_nested_has_many_exceeds_complexity_budget, + d8_two_level_default_nest_exceeds_row_budget, d8_shallow_nested_has_many_within_budget, - d8_low_max_complexity_rejects_single_nest, + d8_low_max_rows_rejects_single_nest, + d8_explicit_limits_multiply_into_the_row_budget, } errors::{ compile_errors_do_not_leak_sql,