diff --git a/pkgs/id/crates/id-core/src/graph/cursor.rs b/pkgs/id/crates/id-core/src/graph/cursor.rs new file mode 100644 index 0000000000..175aec59ec --- /dev/null +++ b/pkgs/id/crates/id-core/src/graph/cursor.rs @@ -0,0 +1,89 @@ +//! Snapshot query cursors (slice A-GRAPH-9126-01, #10221; design part A +//! §5.1, statements S5.8, S5.10, S5.11). +//! +//! A cursor is opaque to callers. Inside, it is the canonical CBOR array +//! `[1, frontier: bstr(32), query: bstr(32), after: uint]`: the snapshot +//! frontier the first page was read at, a digest of the query it +//! continues, and how many rows of the stable total order were already +//! returned. A cursor is honoured only at the same frontier +//! ([`CursorError::Expired`] otherwise) and for the same query +//! ([`CursorError::Mismatch`] otherwise, including any bytes that are +//! not a cursor). Because the order is total and the snapshot is fixed, +//! consecutive pages concatenate without omission or duplication. + +use crate::canonical_cbor::{Value, decode_canonical, encode_canonical}; + +/// Cursor format version. +pub const CURSOR_VERSION: u64 = 1; + +/// Identity of a fixed snapshot of assertions. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct Frontier(pub [u8; 32]); + +/// An opaque continuation token for the next page of one query. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct Cursor(Vec); + +/// Why a cursor was refused. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CursorError { + /// The cursor belongs to another snapshot frontier. + Expired, + /// The cursor belongs to another query, or is not a cursor. + Mismatch, +} + +impl Cursor { + /// A cursor resuming `query` at `frontier` after `after` rows. + #[must_use] + pub fn new(frontier: Frontier, query: [u8; 32], after: u64) -> Self { + let value = Value::Array(vec![ + Value::UInt(CURSOR_VERSION), + Value::Bytes(frontier.0.to_vec()), + Value::Bytes(query.to_vec()), + Value::UInt(after), + ]); + Self(encode_canonical(&value).unwrap_or_default()) + } + + /// Wraps cursor bytes received from a caller. + #[must_use] + pub const fn from_bytes(bytes: Vec) -> Self { + Self(bytes) + } + + /// The opaque bytes to hand to a caller. + #[must_use] + pub fn as_bytes(&self) -> &[u8] { + &self.0 + } + + /// The row offset this cursor resumes after, if it continues `query` + /// at `frontier`. + /// + /// # Errors + /// + /// [`CursorError`] when the cursor is malformed, for another query, + /// or for another frontier. + pub fn resume(&self, frontier: Frontier, query: [u8; 32]) -> Result { + let Ok(Value::Array(items)) = decode_canonical(&self.0) else { + return Err(CursorError::Mismatch); + }; + let [ + Value::UInt(CURSOR_VERSION), + Value::Bytes(at), + Value::Bytes(for_query), + Value::UInt(after), + ] = items.as_slice() + else { + return Err(CursorError::Mismatch); + }; + if for_query.as_slice() != query.as_slice() { + return Err(CursorError::Mismatch); + } + if at.as_slice() != frontier.0.as_slice() { + return Err(CursorError::Expired); + } + Ok(*after) + } +} diff --git a/pkgs/id/crates/id-core/src/graph/query.rs b/pkgs/id/crates/id-core/src/graph/query.rs new file mode 100644 index 0000000000..c9c928fbf8 --- /dev/null +++ b/pkgs/id/crates/id-core/src/graph/query.rs @@ -0,0 +1,519 @@ +//! Bounded read-only triple-pattern queries (slice A-GRAPH-9126-01, +//! #10221; design part A §5.1, statements S5.8, S5.10, S5.11). +//! +//! A [`Query`] is a non-empty conjunction of [`TriplePattern`]s over a +//! fixed [`Snapshot`] of assertions. Each pattern position is a wildcard, +//! an exact [`Term`] or a [`Variable`]; a variable bound in one place +//! must bind the same term everywhere it occurs. There are no updates, +//! property paths, federation, entailment or caller-chosen sort. +//! +//! Rows come out in one stable total order: for each pattern in turn, +//! `(graph, subject, predicate, object, assertion id)`, with terms +//! compared by their canonical bytes. Every row carries the assertions it +//! matched and their `source_record` provenance. +//! +//! Every query runs under a read policy and an operator [`Profile`]: +//! +//! - a pattern that names a graph the policy does not allow fails with +//! [`QueryError::UnauthorizedGraph`]; assertions in other unreadable +//! graphs are never visited, so they cannot change a result or a cost; +//! - every page is limited, and a request cannot raise the profile's row +//! ceiling; +//! - evaluation counts index steps, and running past the profile's step +//! budget fails with [`QueryError::BudgetExceeded`] instead of +//! returning rows that look complete. +//! +//! A page that is not the last carries a [`Cursor`] bound to the +//! snapshot frontier and the query (see [`super::cursor`]). +//! +//! Module wiring into `graph/mod.rs` belongs to slice 9110-09; until +//! then the integration test includes this file by path. + +use std::collections::BTreeMap; +use std::fmt; + +use super::cursor::{Cursor, CursorError, Frontier}; +use super::term::{Term, Triple}; +use crate::canonical_cbor::{Value, encode_canonical}; +use crate::signed_envelope::{EnvelopeId, LogicalGraphId}; + +/// Most patterns one query may join. +pub const MAX_PATTERNS: usize = 8; +/// Longest variable name, in bytes. +pub const MAX_VARIABLE_BYTES: usize = 64; + +const FRONTIER_DOMAIN: &[u8] = b"id/graph-frontier/v1\0"; +const QUERY_DOMAIN: &[u8] = b"id/graph-query/v1\0"; + +/// Operator-validated finite ceilings. Requests cannot raise them. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Profile { + /// Rows per page when a query names no limit. + pub page_default: u32, + /// Largest limit a query may ask for. + pub row_ceiling: u32, + /// Most index steps one page evaluation may take. + pub max_steps: u64, +} + +impl Profile { + /// The design's initial deployment profile. + pub const INITIAL: Self = Self { + page_default: 100, + row_ceiling: 1_000, + max_steps: 1_000_000, + }; +} + +/// Decides which logical graphs the caller may read. +pub trait GraphReadPolicy { + /// Whether the caller may read `graph`. + fn may_read(&self, graph: &LogicalGraphId) -> bool; +} + +/// A query variable name: 1 to 64 ASCII letters, digits or `_`. +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct Variable(String); + +impl Variable { + /// A variable from its name. + /// + /// # Errors + /// + /// [`QueryError::InvalidPattern`] for an empty, overlong or + /// non-identifier name. + pub fn new(name: &str) -> Result { + if name.is_empty() + || name.len() > MAX_VARIABLE_BYTES + || !name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') + { + return Err(QueryError::InvalidPattern("bad variable name")); + } + Ok(Self(name.to_owned())) + } + + /// The name. + #[must_use] + pub fn name(&self) -> &str { + &self.0 + } +} + +/// One position of a triple pattern. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum TermPattern { + /// Matches exactly this term. + Exact(Term), + /// Binds, or must equal, this variable. + Var(Variable), +} + +/// A pattern over one assertion. `None` positions match anything. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct TriplePattern { + /// Restricts the match to one logical graph. + pub graph: Option, + /// Subject position. + pub subject: Option, + /// Predicate position. + pub predicate: Option, + /// Object position. + pub object: Option, +} + +/// A conjunctive query and its page request. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Query { + /// The patterns, joined on shared variables. + pub patterns: Vec, + /// The variables each row reports, in this order. + pub projection: Vec, + /// Rows per page; `None` takes the profile's default. + pub limit: Option, + /// Where the previous page stopped. + pub cursor: Option, +} + +/// One verified assertion in a snapshot. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct StoredAssertion { + /// The signed record the triple came from. + pub record: EnvelopeId, + /// Its position in that record. + pub index: u32, + /// Its logical graph. + pub graph: LogicalGraphId, + /// The triple. + pub triple: Triple, + /// The evidence the record names, if any. + pub source_record: Option, +} + +/// An assertion's place in the stable order: graph, the three terms' +/// canonical bytes, then the assertion id (record, index). +type AssertionKey = ([u8; 32], [Vec; 3], (u8, [u8; 32], u32)); + +fn assertion_key(assertion: &StoredAssertion) -> AssertionKey { + let id = assertion.record.content_id(); + let term = |t: &Term| t.to_bytes().unwrap_or_default(); + ( + *assertion.graph.as_bytes(), + [ + term(&assertion.triple.subject), + term(&assertion.triple.predicate), + term(&assertion.triple.object), + ], + (id.profile().tag(), *id.digest(), assertion.index), + ) +} + +/// A fixed set of verified assertions, read at one frontier. +#[derive(Debug, Clone)] +pub struct Snapshot { + frontier: Frontier, + assertions: Vec<(AssertionKey, StoredAssertion)>, +} + +impl Snapshot { + /// A snapshot of `assertions`. Entries with the same assertion id + /// (record and index) are kept once. The frontier is the BLAKE3 hash + /// of the sorted assertion ids, so it is the same whatever order the + /// assertions arrive in. + #[must_use] + pub fn new(assertions: Vec) -> Self { + let mut keyed: Vec<(AssertionKey, StoredAssertion)> = assertions + .into_iter() + .map(|a| (assertion_key(&a), a)) + .collect(); + keyed.sort_by_key(|a| a.0.2); + keyed.dedup_by(|a, b| a.0.2 == b.0.2); + let mut hasher = blake3::Hasher::new(); + hasher.update(FRONTIER_DOMAIN); + for ((_, _, (tag, digest, index)), _) in &keyed { + hasher.update(&[*tag]); + hasher.update(digest); + hasher.update(&index.to_be_bytes()); + } + keyed.sort_by(|a, b| a.0.cmp(&b.0)); + Self { + frontier: Frontier(*hasher.finalize().as_bytes()), + assertions: keyed, + } + } + + /// The snapshot's frontier. + #[must_use] + pub const fn frontier(&self) -> Frontier { + self.frontier + } + + /// How many assertions it holds. + #[must_use] + pub const fn len(&self) -> usize { + self.assertions.len() + } + + /// Whether it holds none. + #[must_use] + pub const fn is_empty(&self) -> bool { + self.assertions.is_empty() + } +} + +/// One matched assertion, with its provenance. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Matched { + /// The record the triple was signed in. + pub record: EnvelopeId, + /// Its position in that record. + pub index: u32, + /// The evidence that record names, if any. + pub source_record: Option, +} + +/// One result row. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Row { + /// The projected variables' terms, in projection order. + pub values: Vec, + /// The assertion each pattern matched, in pattern order. + pub matched: Vec, +} + +/// What a page cost. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Cost { + /// Index steps taken. + pub scanned: u64, + /// Rows returned. + pub returned: u32, +} + +/// One page of results. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct QueryPage { + /// The rows, in the stable order. + pub rows: Vec, + /// Present when more rows follow. + pub next_cursor: Option, + /// The frontier the page was read at. + pub snapshot: Frontier, + /// True only on the last page of a fully evaluated result. + pub complete: bool, + /// What the page cost. + pub cost: Cost, +} + +/// Why a query was refused. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum QueryError { + /// The query is not well formed. + InvalidPattern(&'static str), + /// A pattern names a graph the caller may not read. + UnauthorizedGraph, + /// The cursor was issued at another snapshot frontier. + CursorExpired, + /// The cursor is for another query, or not a cursor. + CursorMismatch, + /// Evaluation ran past the profile's step budget. + BudgetExceeded { + /// Steps taken before stopping. + scanned: u64, + }, +} + +impl QueryError { + /// A stable failure class name. + #[must_use] + pub const fn class(&self) -> &'static str { + match self { + Self::InvalidPattern(_) => "invalid_pattern", + Self::UnauthorizedGraph => "unauthorized_graph", + Self::CursorExpired => "cursor_expired", + Self::CursorMismatch => "cursor_mismatch", + Self::BudgetExceeded { .. } => "budget_exceeded", + } + } +} + +impl fmt::Display for QueryError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidPattern(why) => write!(f, "invalid query: {why}"), + Self::UnauthorizedGraph => write!(f, "query names a graph the caller may not read"), + Self::CursorExpired => write!(f, "cursor is for another snapshot"), + Self::CursorMismatch => write!(f, "cursor is for another query"), + Self::BudgetExceeded { scanned } => { + write!(f, "query stopped after {scanned} steps, over budget") + } + } + } +} + +impl std::error::Error for QueryError {} + +impl From for QueryError { + fn from(error: CursorError) -> Self { + match error { + CursorError::Expired => Self::CursorExpired, + CursorError::Mismatch => Self::CursorMismatch, + } + } +} + +fn pattern_value(position: Option<&TermPattern>) -> Value { + match position { + None => Value::Null, + Some(TermPattern::Exact(term)) => { + Value::Array(vec![Value::UInt(0), term.to_value().unwrap_or(Value::Null)]) + } + Some(TermPattern::Var(var)) => { + Value::Array(vec![Value::UInt(1), Value::Text(var.0.clone())]) + } + } +} + +impl Query { + /// A digest of what the query asks (patterns and projection, not the + /// page size or cursor), which a cursor is bound to. + #[must_use] + pub fn digest(&self) -> [u8; 32] { + let patterns = self + .patterns + .iter() + .map(|p| { + Value::Array(vec![ + p.graph + .map_or(Value::Null, |g| Value::Bytes(g.as_bytes().to_vec())), + pattern_value(p.subject.as_ref()), + pattern_value(p.predicate.as_ref()), + pattern_value(p.object.as_ref()), + ]) + }) + .collect(); + let projection = self + .projection + .iter() + .map(|v| Value::Text(v.0.clone())) + .collect(); + let bytes = encode_canonical(&Value::Array(vec![ + Value::Array(patterns), + Value::Array(projection), + ])) + .unwrap_or_default(); + let mut hasher = blake3::Hasher::new(); + hasher.update(QUERY_DOMAIN); + hasher.update(&bytes); + *hasher.finalize().as_bytes() + } + + fn mentions(&self, var: &Variable) -> bool { + self.patterns.iter().any(|p| { + [&p.subject, &p.predicate, &p.object] + .into_iter() + .any(|pos| matches!(pos, Some(TermPattern::Var(v)) if v == var)) + }) + } +} + +type Bindings = BTreeMap; + +fn bind(position: Option<&TermPattern>, term: &Term, bindings: &mut Bindings) -> bool { + match position { + None => true, + Some(TermPattern::Exact(want)) => want == term, + Some(TermPattern::Var(var)) => { + if let Some(bound) = bindings.get(var) { + return bound == term; + } + bindings.insert(var.clone(), term.clone()); + true + } + } +} + +fn matches(pattern: &TriplePattern, assertion: &StoredAssertion, bindings: &mut Bindings) -> bool { + pattern.graph.is_none_or(|g| g == assertion.graph) + && bind( + pattern.subject.as_ref(), + &assertion.triple.subject, + bindings, + ) + && bind( + pattern.predicate.as_ref(), + &assertion.triple.predicate, + bindings, + ) + && bind(pattern.object.as_ref(), &assertion.triple.object, bindings) +} + +/// Runs one page of `query` over `snapshot`. +/// +/// # Errors +/// +/// [`QueryError`] for a malformed query, an unreadable named graph, a +/// cursor for another query or snapshot, or a blown step budget. +pub fn run( + query: &Query, + snapshot: &Snapshot, + policy: &dyn GraphReadPolicy, + profile: &Profile, +) -> Result { + if query.patterns.is_empty() { + return Err(QueryError::InvalidPattern("a query needs a pattern")); + } + if query.patterns.len() > MAX_PATTERNS { + return Err(QueryError::InvalidPattern("too many patterns")); + } + if !query.projection.iter().all(|var| query.mentions(var)) { + return Err(QueryError::InvalidPattern( + "projected variable is not in any pattern", + )); + } + let limit = query.limit.unwrap_or(profile.page_default); + if limit == 0 || limit > profile.row_ceiling { + return Err(QueryError::InvalidPattern( + "limit must be 1 to the profile's row ceiling", + )); + } + if query + .patterns + .iter() + .filter_map(|p| p.graph.as_ref()) + .any(|g| !policy.may_read(g)) + { + return Err(QueryError::UnauthorizedGraph); + } + let digest = query.digest(); + let offset = match &query.cursor { + Some(cursor) => cursor.resume(snapshot.frontier, digest)?, + None => 0, + }; + + let visible: Vec<&(AssertionKey, StoredAssertion)> = snapshot + .assertions + .iter() + .filter(|(_, a)| policy.may_read(&a.graph)) + .collect(); + let mut scanned = 0_u64; + let mut partial: Vec<(Vec, Bindings)> = vec![(Vec::new(), Bindings::new())]; + for pattern in &query.patterns { + let mut next = Vec::new(); + for (chosen, bindings) in &partial { + for (at, (_, assertion)) in visible.iter().enumerate() { + scanned += 1; + if scanned > profile.max_steps { + return Err(QueryError::BudgetExceeded { scanned }); + } + let mut extended = bindings.clone(); + if matches(pattern, assertion, &mut extended) { + let mut path = chosen.clone(); + path.push(at); + next.push((path, extended)); + } + } + } + partial = next; + } + // `visible` is in assertion-key order and each pass extends the + // partial rows in order, so `partial` is already in the stable row + // order: lexicographic over the matched assertions' keys. + + let total = partial.len() as u64; + let start = offset.min(total); + let end = start.saturating_add(u64::from(limit)).min(total); + let rows: Vec = partial + .iter() + .skip(usize::try_from(start).unwrap_or(usize::MAX)) + .take(usize::try_from(end - start).unwrap_or(0)) + .map(|(path, bindings)| Row { + values: query + .projection + .iter() + .map(|var| bindings[var].clone()) + .collect(), + matched: path + .iter() + .map(|at| { + let a = &visible[*at].1; + Matched { + record: a.record, + index: a.index, + source_record: a.source_record, + } + }) + .collect(), + }) + .collect(); + let next_cursor = (end < total).then(|| Cursor::new(snapshot.frontier, digest, end)); + Ok(QueryPage { + complete: next_cursor.is_none(), + cost: Cost { + scanned, + returned: u32::try_from(rows.len()).unwrap_or(u32::MAX), + }, + rows, + next_cursor, + snapshot: snapshot.frontier, + }) +} diff --git a/pkgs/id/crates/id-core/tests/graph_query_reference.rs b/pkgs/id/crates/id-core/tests/graph_query_reference.rs new file mode 100644 index 0000000000..fcb367c42e --- /dev/null +++ b/pkgs/id/crates/id-core/tests/graph_query_reference.rs @@ -0,0 +1,649 @@ +//! Bounded triple-pattern queries and cursors (slice A-GRAPH-9126-01, +//! issue #10221; design part A §5.1, statements S5.8, S5.10, S5.11). +//! +//! Oracle: **reference**. An independent pure matcher in this file +//! enumerates every tuple of readable assertions, checks the patterns +//! with its own variable bindings, orders rows by keys built from its own +//! encoding of the terms, and counts the steps the query should take. +//! The paged query must agree with it at a fixed frontier: cursor pages +//! concatenate to exactly the reference rows with no omission or +//! duplication, only the last page reports complete, and unauthorized or +//! over-budget queries fail instead of reporting complete. +//! +//! `graph/mod.rs` does not export these modules yet (slice 9110-09 wires +//! them), so this test includes them, and the modules they build on, by +//! path. + +#![allow( + clippy::unwrap_used, + clippy::expect_used, + clippy::panic, + clippy::cast_possible_truncation, + clippy::many_single_char_names, + clippy::type_complexity, + clippy::unnecessary_wraps, + clippy::missing_const_for_fn +)] + +#[path = "../src/canonical_cbor.rs"] +#[allow(dead_code)] +mod canonical_cbor; + +#[path = "../src/id_shape.rs"] +#[allow(dead_code)] +mod id_shape; + +#[path = "../src/signed_envelope.rs"] +#[allow(dead_code)] +mod signed_envelope; + +#[path = "../src/hash_profile.rs"] +#[allow(dead_code)] +mod hash_profile; + +#[path = "../src/graph/term.rs"] +#[allow(dead_code)] +mod term; + +#[path = "../src/graph/cursor.rs"] +mod cursor; + +#[path = "../src/graph/query.rs"] +mod query; + +use std::collections::BTreeSet; + +use cursor::Cursor; +use id_shape::{ContentId, HashProfile}; +use proptest::prelude::*; +use query::{ + GraphReadPolicy, Profile, Query, QueryError, QueryPage, Snapshot, StoredAssertion, TermPattern, + TriplePattern, Variable, run, +}; +use signed_envelope::{EnvelopeId, LogicalGraphId}; +use term::{Term, Triple}; + +// --------------------------------------------------------------------- +// Fixture helpers. + +fn graph(n: u8) -> LogicalGraphId { + LogicalGraphId::new([n; 32]) +} + +fn record(n: u8) -> EnvelopeId { + EnvelopeId::from_content_id(ContentId::new(HashProfile::RawBlake3_256, [n; 32])) +} + +fn t(tag: u8, byte: u8) -> Term { + Term::typed(u64::from(tag), vec![byte]) +} + +fn var(name: &str) -> Variable { + Variable::new(name).unwrap() +} + +fn v(name: &str) -> Option { + Some(TermPattern::Var(var(name))) +} + +fn exact(term: Term) -> Option { + Some(TermPattern::Exact(term)) +} + +/// Compact assertion: (graph, record, index, s, p, o, source). +type Spec = (u8, u8, u32, (u8, u8), (u8, u8), (u8, u8), Option); + +fn stored(spec: Spec) -> StoredAssertion { + let (g, r, index, s, p, o, source) = spec; + StoredAssertion { + record: record(r), + index, + graph: graph(g), + triple: Triple::new(t(s.0, s.1), t(p.0, p.1), t(o.0, o.1)), + source_record: source.map(record), + } +} + +struct Readable(BTreeSet); + +impl GraphReadPolicy for Readable { + fn may_read(&self, g: &LogicalGraphId) -> bool { + self.0.contains(&g.as_bytes()[0]) + } +} + +fn all_graphs() -> Readable { + Readable((0..=255).collect()) +} + +fn query(patterns: Vec, projection: &[&str], limit: u32) -> Query { + Query { + patterns, + projection: projection.iter().map(|n| var(n)).collect(), + limit: Some(limit), + cursor: None, + } +} + +/// Follows cursors to the end and returns every page. +fn all_pages( + mut q: Query, + snapshot: &Snapshot, + policy: &dyn GraphReadPolicy, + profile: &Profile, +) -> Result, QueryError> { + let mut pages = Vec::new(); + loop { + let page = run(&q, snapshot, policy, profile)?; + let next = page.next_cursor.clone(); + pages.push(page); + match next { + Some(cursor) => q.cursor = Some(cursor), + None => return Ok(pages), + } + } +} + +// --------------------------------------------------------------------- +// Independent reference matcher. + +/// Own canonical encoding of a one-byte typed term, `[0, tag, h'byte']`, +/// valid for tags below 24. +fn ref_term_bytes(term: &Term) -> Vec { + let Term::Typed { type_tag, bytes } = term else { + panic!("reference handles typed terms only") + }; + assert!(*type_tag < 24 && bytes.len() < 24); + let mut out = vec![0x83, 0x00, *type_tag as u8, 0x40 | bytes.len() as u8]; + out.extend_from_slice(bytes); + out +} + +type RefKey = (Vec, Vec, Vec, Vec, Vec, u32); + +fn ref_key(a: &StoredAssertion) -> RefKey { + ( + a.graph.as_bytes().to_vec(), + ref_term_bytes(&a.triple.subject), + ref_term_bytes(&a.triple.predicate), + ref_term_bytes(&a.triple.object), + a.record.content_id().digest().to_vec(), + a.index, + ) +} + +fn ref_bind(pos: Option<&TermPattern>, term: &Term, env: &mut Vec<(String, Term)>) -> bool { + match pos { + None => true, + Some(TermPattern::Exact(want)) => want == term, + Some(TermPattern::Var(name)) => { + if let Some((_, bound)) = env.iter().find(|(n, _)| n == name.name()) { + return bound == term; + } + env.push((name.name().to_owned(), term.clone())); + true + } + } +} + +/// Every consistent tuple for the first `upto` patterns, unordered. +fn ref_tuples( + patterns: &[TriplePattern], + upto: usize, + readable: &[StoredAssertion], +) -> Vec<(Vec, Vec<(String, Term)>)> { + let mut out = Vec::new(); + let n = readable.len(); + let total = n.pow(upto as u32); + for mut code in 0..total { + let mut chosen = Vec::with_capacity(upto); + for _ in 0..upto { + chosen.push(code % n); + code /= n; + } + let mut env = Vec::new(); + let ok = patterns[..upto].iter().zip(&chosen).all(|(p, at)| { + let a = &readable[*at]; + p.graph.is_none_or(|g| g == a.graph) + && ref_bind(p.subject.as_ref(), &a.triple.subject, &mut env) + && ref_bind(p.predicate.as_ref(), &a.triple.predicate, &mut env) + && ref_bind(p.object.as_ref(), &a.triple.object, &mut env) + }); + if ok { + out.push((chosen, env)); + } + } + out +} + +struct Expected { + rows: Vec<(Vec, Vec<(EnvelopeId, u32, Option)>)>, + steps: u64, +} + +fn reference(q: &Query, assertions: &[StoredAssertion], policy: &Readable) -> Expected { + let mut readable: Vec = assertions + .iter() + .filter(|a| policy.may_read(&a.graph)) + .cloned() + .collect(); + readable.sort_by_key(ref_key); + let n = readable.len() as u64; + let steps = (0..q.patterns.len()) + .map(|i| ref_tuples(&q.patterns, i, &readable).len() as u64 * n) + .sum(); + let mut tuples = ref_tuples(&q.patterns, q.patterns.len(), &readable); + tuples.sort_by(|a, b| { + let ka: Vec = a.0.iter().map(|i| ref_key(&readable[*i])).collect(); + let kb: Vec = b.0.iter().map(|i| ref_key(&readable[*i])).collect(); + ka.cmp(&kb) + }); + let rows = tuples + .into_iter() + .map(|(chosen, env)| { + let values = q + .projection + .iter() + .map(|p| env.iter().find(|(n, _)| n == p.name()).unwrap().1.clone()) + .collect(); + let matched = chosen + .iter() + .map(|i| { + let a = &readable[*i]; + (a.record, a.index, a.source_record) + }) + .collect(); + (values, matched) + }) + .collect(); + Expected { rows, steps } +} + +fn flatten(pages: &[QueryPage]) -> Vec<(Vec, Vec<(EnvelopeId, u32, Option)>)> { + pages + .iter() + .flat_map(|p| &p.rows) + .map(|r| { + ( + r.values.clone(), + r.matched + .iter() + .map(|m| (m.record, m.index, m.source_record)) + .collect(), + ) + }) + .collect() +} + +// --------------------------------------------------------------------- +// Fixtures. + +fn social() -> Vec { + // graph 1: alice(1) knows(9) bob(2), bob knows carol(3), alice likes(8) carol. + // graph 2 (private): carol knows alice. + [ + (1, 10, 0, (1, 1), (1, 9), (1, 2), None), + (1, 10, 1, (1, 2), (1, 9), (1, 3), None), + (1, 11, 0, (1, 1), (1, 8), (1, 3), Some(10)), + (2, 12, 0, (1, 3), (1, 9), (1, 1), None), + ] + .into_iter() + .map(stored) + .collect() +} + +#[test] +fn two_hop_join_returns_bindings_and_provenance_in_stable_order() { + let snapshot = Snapshot::new(social()); + let q = query( + vec![ + TriplePattern { + subject: v("a"), + predicate: exact(t(1, 9)), + object: v("b"), + ..TriplePattern::default() + }, + TriplePattern { + subject: v("b"), + predicate: exact(t(1, 9)), + object: v("c"), + ..TriplePattern::default() + }, + ], + &["a", "c"], + 10, + ); + let page = run(&q, &snapshot, &all_graphs(), &Profile::INITIAL).unwrap(); + // alice→bob→carol, bob→carol→alice (across graphs), carol→alice→bob. + let got: Vec> = page.rows.iter().map(|r| r.values.clone()).collect(); + assert_eq!( + got, + vec![ + vec![t(1, 1), t(1, 3)], + vec![t(1, 2), t(1, 1)], + vec![t(1, 3), t(1, 2)], + ] + ); + assert!(page.complete); + assert!(page.next_cursor.is_none()); + assert_eq!(page.cost.returned, 3); + assert_eq!(page.cost.scanned, 4 + 3 * 4); + assert_eq!(page.snapshot, snapshot.frontier()); + + // Provenance: the "likes" row cites its source record. + let likes = query( + vec![TriplePattern { + predicate: exact(t(1, 8)), + ..TriplePattern::default() + }], + &[], + 10, + ); + let page = run(&likes, &snapshot, &all_graphs(), &Profile::INITIAL).unwrap(); + assert_eq!(page.rows.len(), 1); + assert_eq!(page.rows[0].matched[0].record, record(11)); + assert_eq!(page.rows[0].matched[0].source_record, Some(record(10))); +} + +#[test] +fn unreadable_graphs_are_refused_by_name_and_invisible_otherwise() { + let snapshot = Snapshot::new(social()); + let public = Readable(BTreeSet::from([1])); + let named = query( + vec![TriplePattern { + graph: Some(graph(2)), + ..TriplePattern::default() + }], + &[], + 10, + ); + assert_eq!( + run(&named, &snapshot, &public, &Profile::INITIAL), + Err(QueryError::UnauthorizedGraph) + ); + let any = query( + vec![TriplePattern { + subject: v("s"), + ..TriplePattern::default() + }], + &["s"], + 10, + ); + let page = run(&any, &snapshot, &public, &Profile::INITIAL).unwrap(); + assert_eq!(page.rows.len(), 3); + // The hidden assertion does not show up in the cost either. + assert_eq!(page.cost.scanned, 3); +} + +#[test] +fn budget_and_limits_are_enforced_without_claiming_completeness() { + let snapshot = Snapshot::new(social()); + let q = query( + vec![TriplePattern::default(), TriplePattern::default()], + &[], + 10, + ); + let tight = Profile { + max_steps: 19, + ..Profile::INITIAL + }; + assert_eq!( + run(&q, &snapshot, &all_graphs(), &tight), + Err(QueryError::BudgetExceeded { scanned: 20 }) + ); + let exact_fit = Profile { + max_steps: 20, + ..Profile::INITIAL + }; + assert!(run(&q, &snapshot, &all_graphs(), &exact_fit).is_ok()); + + let mut over = q.clone(); + over.limit = Some(Profile::INITIAL.row_ceiling + 1); + assert_eq!( + run(&over, &snapshot, &all_graphs(), &Profile::INITIAL) + .unwrap_err() + .class(), + "invalid_pattern" + ); + let mut zero = q.clone(); + zero.limit = Some(0); + assert!(run(&zero, &snapshot, &all_graphs(), &Profile::INITIAL).is_err()); + let mut default = q; + default.limit = None; + let small = Profile { + page_default: 5, + ..Profile::INITIAL + }; + let page = run(&default, &snapshot, &all_graphs(), &small).unwrap(); + assert_eq!(page.rows.len(), 5); + assert!(!page.complete); +} + +#[test] +fn malformed_queries_reject() { + let snapshot = Snapshot::new(social()); + let empty = query(vec![], &[], 10); + assert_eq!( + run(&empty, &snapshot, &all_graphs(), &Profile::INITIAL) + .unwrap_err() + .class(), + "invalid_pattern" + ); + let unbound = query(vec![TriplePattern::default()], &["x"], 10); + assert!(run(&unbound, &snapshot, &all_graphs(), &Profile::INITIAL).is_err()); + let too_many = query(vec![TriplePattern::default(); 9], &[], 10); + assert!(run(&too_many, &snapshot, &all_graphs(), &Profile::INITIAL).is_err()); + for good in ["a_b", "_", "X9", &"x".repeat(64)] { + assert!(Variable::new(good).is_ok(), "{good:?}"); + } + for bad in ["", "has space", "dash-ed", &"x".repeat(65)] { + assert!(Variable::new(bad).is_err(), "{bad:?}"); + } +} + +#[test] +fn cursors_are_bound_to_their_query_and_frontier() { + let snapshot = Snapshot::new(social()); + let q = query(vec![TriplePattern::default()], &[], 1); + let first = run(&q, &snapshot, &all_graphs(), &Profile::INITIAL).unwrap(); + let cursor = first.next_cursor.unwrap(); + assert!(!first.complete); + + let mut other = query( + vec![TriplePattern { + subject: v("s"), + ..TriplePattern::default() + }], + &[], + 1, + ); + other.cursor = Some(cursor.clone()); + assert_eq!( + run(&other, &snapshot, &all_graphs(), &Profile::INITIAL), + Err(QueryError::CursorMismatch) + ); + + let mut grown = social(); + grown.push(stored((1, 13, 0, (1, 4), (1, 9), (1, 1), None))); + let newer = Snapshot::new(grown); + let mut resumed = q.clone(); + resumed.cursor = Some(cursor.clone()); + assert_eq!( + run(&resumed, &newer, &all_graphs(), &Profile::INITIAL), + Err(QueryError::CursorExpired) + ); + + let mut forged = q.clone(); + forged.cursor = Some(Cursor::from_bytes(vec![0x01, 0x02])); + assert_eq!( + run(&forged, &snapshot, &all_graphs(), &Profile::INITIAL), + Err(QueryError::CursorMismatch) + ); + // Editing a real cursor's bytes does not move it to another query. + let mut edited = cursor.as_bytes().to_vec(); + let last = edited.len() - 1; + edited[last] ^= 0xff; + forged.cursor = Some(Cursor::from_bytes(edited)); + assert_eq!( + run(&forged, &snapshot, &all_graphs(), &Profile::INITIAL), + Err(QueryError::CursorMismatch) + ); + + // The graph a pattern names is part of the query a cursor is for. + let in_graph = |g: u8| { + query( + vec![TriplePattern { + graph: Some(graph(g)), + ..TriplePattern::default() + }], + &[], + 1, + ) + }; + let g1_cursor = run(&in_graph(1), &snapshot, &all_graphs(), &Profile::INITIAL) + .unwrap() + .next_cursor + .unwrap(); + let mut g2 = in_graph(2); + g2.cursor = Some(g1_cursor); + assert_eq!( + run(&g2, &snapshot, &all_graphs(), &Profile::INITIAL), + Err(QueryError::CursorMismatch) + ); + + // A different page size may continue the same query. + let mut wider = q; + wider.limit = Some(10); + wider.cursor = Some(cursor); + let rest = run(&wider, &snapshot, &all_graphs(), &Profile::INITIAL).unwrap(); + assert_eq!(rest.rows.len(), 3); + assert!(rest.complete); +} + +#[test] +fn frontier_ignores_arrival_order_and_duplicates() { + let mut shuffled = social(); + shuffled.reverse(); + shuffled.push(social()[0].clone()); + let a = Snapshot::new(social()); + let b = Snapshot::new(shuffled); + assert_eq!(a.frontier(), b.frontier()); + assert_eq!(b.len(), 4); + assert!(!b.is_empty() && Snapshot::new(Vec::new()).is_empty()); + assert_ne!( + a.frontier(), + Snapshot::new(social()[..3].to_vec()).frontier() + ); + // The frontier covers each assertion's index, not only its record. + let mut moved = social(); + moved[0].index = 7; + assert_ne!(a.frontier(), Snapshot::new(moved).frontier()); +} + +// --------------------------------------------------------------------- +// Property test against the reference matcher. + +fn term_strategy() -> impl Strategy { + (0_u8..2, 0_u8..2) +} + +fn assertion_strategy() -> impl Strategy { + ( + 1_u8..3, + 0_u8..4, + 0_u32..3, + term_strategy(), + term_strategy(), + term_strategy(), + prop::option::of(0_u8..4), + ) +} + +fn position_strategy() -> impl Strategy> { + prop_oneof![ + 2 => Just(None), + 1 => term_strategy().prop_map(|(a, b)| exact(t(a, b))), + 3 => prop::sample::select(vec!["x", "y", "z"]).prop_map(v), + ] +} + +fn pattern_strategy() -> impl Strategy { + ( + prop::option::weighted(0.2, 1_u8..4), + position_strategy(), + position_strategy(), + position_strategy(), + ) + .prop_map(|(g, subject, predicate, object)| TriplePattern { + graph: g.map(graph), + subject, + predicate, + object, + }) +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(512))] + + #[test] + fn paged_query_matches_the_reference( + specs in prop::collection::vec(assertion_strategy(), 3..12), + patterns in prop::collection::vec(pattern_strategy(), 1..4), + projection in prop::sample::subsequence(vec!["x", "y", "z"], 0..=3), + readable in prop::collection::btree_set(1_u8..4, 1..=3), + limit in 1_u32..5, + max_steps in prop_oneof![1 => 0_u64..60, 3 => Just(u64::MAX)], + ) { + // Assertion ids are unique in a real store. + let mut ids = BTreeSet::new(); + let assertions: Vec = specs + .into_iter() + .filter(|s| ids.insert((s.1, s.2))) + .map(stored) + .collect(); + let snapshot = Snapshot::new(assertions.clone()); + let policy = Readable(readable); + let profile = Profile { page_default: 3, row_ceiling: 4, max_steps }; + let mut q = query(patterns, &projection, limit); + q.projection.retain(|p| { + q.patterns.iter().any(|pat| { + [&pat.subject, &pat.predicate, &pat.object] + .into_iter() + .any(|pos| matches!(pos, Some(TermPattern::Var(x)) if x == p)) + }) + }); + + let named_hidden = q + .patterns + .iter() + .filter_map(|p| p.graph.as_ref()) + .any(|g| !policy.may_read(g)); + let got = all_pages(q.clone(), &snapshot, &policy, &profile); + if named_hidden { + prop_assert_eq!(got.unwrap_err(), QueryError::UnauthorizedGraph); + return Ok(()); + } + let want = reference(&q, &assertions, &policy); + if want.steps > max_steps { + prop_assert_eq!( + got.unwrap_err(), + QueryError::BudgetExceeded { scanned: max_steps + 1 } + ); + return Ok(()); + } + let pages = got.unwrap(); + prop_assert_eq!(flatten(&pages), want.rows); + for (i, page) in pages.iter().enumerate() { + let last = i + 1 == pages.len(); + prop_assert_eq!(page.complete, last); + prop_assert_eq!(page.next_cursor.is_none(), last); + prop_assert!(page.rows.len() <= limit as usize); + prop_assert_eq!(page.cost.returned as usize, page.rows.len()); + prop_assert_eq!(page.cost.scanned, want.steps); + prop_assert_eq!(page.snapshot, snapshot.frontier()); + if !last { + prop_assert_eq!(page.rows.len(), limit as usize); + } + } + } +}