Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion distributed_cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions distributed_cli/src/client_compiler/graphql/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
211 changes: 169 additions & 42 deletions distributed_cli/src/client_compiler/graphql/validation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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<String, CompiledArgument>,
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 {
Expand Down Expand Up @@ -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<CompiledMember>) -> CompiledObject {
CompiledObject {
typename: "todo".into(),
storage: CompiledStorage::Embedded,
members: Vec::new(),
members,
}
}

fn branch(
semantic: CompiledBranchSemantic,
cardinality: Cardinality,
limit: Option<u64>,
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);
}
}
27 changes: 2 additions & 25 deletions distributed_cli/src/client_compiler/manifest/model_validation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
] {
Expand All @@ -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(())
}

Expand Down
57 changes: 33 additions & 24 deletions distributed_cli/src/client_compiler/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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]
Expand Down
Loading
Loading