diff --git a/CHANGELOG.md b/CHANGELOG.md index d05cdaee51..8d1d306f22 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -99,6 +99,28 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 canonical `{}`-placeholder template form so the registry↔doc sync test can compare them byte-for-byte; the concrete example now lives in each entry's prose instead. +- **Query executor errors now carry real `QRY-00N` codes** (#361, part of + #277) instead of the generic `INT-000` fallback: `QRY-001` invalid entity, + `QRY-002` attribute must be a keyword, `QRY-003` cannot transact a + pseudo-attribute, `QRY-004` invalid value, `QRY-005` transaction failed, + `QRY-006` retraction failed, `QRY-007` unknown predicate, `QRY-008` + functions lock poisoned, `QRY-009` rules lock poisoned — the full QRY + category (9 of 9 documented codes; see `docs/ERROR_REFERENCE.md`). Anything + that was matching on `MinigrafError::code() == "INT-000"` for one of these + conditions now sees the specific code instead. `QRY-001`/`004`/`005`/`006`'s + `ERROR_REFERENCE.md` "Error text" entries were also rewritten from a + concrete example (e.g. `` `Invalid entity: "not-a-uuid"` ``) to the + canonical `{}`-placeholder template form (`` `Invalid entity: {}` ``) they + share with `REGISTRY`, per the design spec's migration convention; the + worked example moved to each entry's "Example" section, unchanged. + `QRY-001`..`006` (the transact/retract validation codes) are wired into + `DatalogExecutor::execute_transact`/`execute_retract`, but that code path + is not reachable through `Minigraf::execute()` today — the public write + path routes `transact`/`retract` through `Minigraf::materialize_transaction`/ + `materialize_retraction` (`src/db.rs`) instead, which raise their own + uncoded (still `INT-000`) errors, two of which — "attribute must be a + keyword" and "cannot transact a pseudo-attribute" — are already earmarked + as `API-003`/`API-004` for the API+INT category PR (#277 step 6). - **The core binary size budget is raised from 1MB to ~1.2MB** (`binary-size.yml`'s `SIZE_LIMIT_BYTES`, and PHILOSOPHY.md §4's stated target), toward #277. The project was already at the 1MB wire before #277 started (measured diff --git a/docs/ERROR_REFERENCE.md b/docs/ERROR_REFERENCE.md index 888e58716a..fcb3c43f5f 100644 --- a/docs/ERROR_REFERENCE.md +++ b/docs/ERROR_REFERENCE.md @@ -1478,7 +1478,7 @@ predicate evaluation, or fact transacting. ### QRY-001 Invalid entity -**Error text**: `Invalid entity: "not-a-uuid"` +**Error text**: `Invalid entity: {}` **Cause**: An entity ID in a `transact` fact could not be resolved. Entity IDs must be UUIDs (as `#uuid "..."` tagged literals), existing entity symbols, or values that can be resolved to a UUID at execution time. @@ -1525,7 +1525,7 @@ predicate evaluation, or fact transacting. ### QRY-004 Invalid value -**Error text**: `Invalid value: [1, 2, 3]` +**Error text**: `Invalid value: {}` **Cause**: A value in a fact is of a type that Minigraf cannot store. Supported value types are: string, integer (i64), float (f64), boolean, UUID ref (`Value::Ref`), and keyword. @@ -1541,7 +1541,7 @@ predicate evaluation, or fact transacting. ### QRY-005 Transaction failed -**Error text**: `Transaction failed: write lock is poisoned` +**Error text**: `Transaction failed: {}` **Cause**: The batch of facts could not be committed. This is a wrapper error — the nested reason message identifies the root cause, which is typically a storage error, lock poisoning, or WAL write failure. @@ -1554,7 +1554,7 @@ predicate evaluation, or fact transacting. ### QRY-006 Retraction failed -**Error text**: `Retraction failed: fact not found` +**Error text**: `Retraction failed: {}` **Cause**: A retraction could not be applied. The nested reason message identifies the specific cause — the fact may not exist at the given transaction time, or a storage error occurred. @@ -1567,7 +1567,7 @@ predicate evaluation, or fact transacting. ### QRY-007 Unknown predicate -**Error text**: `unknown predicate: 'between?'` +**Error text**: `unknown predicate: '{}'` **Cause**: A `:where` clause invoked a predicate (expression function) that is not built-in and has not been registered via `db.register_predicate()`. diff --git a/src/error.rs b/src/error.rs index a791b8a781..cc558a73c9 100644 --- a/src/error.rs +++ b/src/error.rs @@ -35,6 +35,15 @@ pub enum ErrorCategory { /// downstream `match`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum ErrorCode { + Qry001, + Qry002, + Qry003, + Qry004, + Qry005, + Qry006, + Qry007, + Qry008, + Qry009, Int000, Wal001, Wal002, @@ -50,6 +59,60 @@ pub(crate) enum ErrorCode { /// "Error text" lines by the sync test in this module (added once real /// codes exist in a follow-up category PR — see the design spec). pub(crate) const REGISTRY: &[(ErrorCode, &str, &str, ErrorCategory)] = &[ + ( + ErrorCode::Qry001, + "QRY-001", + "Invalid entity: {}", + ErrorCategory::Query, + ), + ( + ErrorCode::Qry002, + "QRY-002", + "Attribute must be a keyword", + ErrorCategory::Query, + ), + ( + ErrorCode::Qry003, + "QRY-003", + "Cannot transact a pseudo-attribute", + ErrorCategory::Query, + ), + ( + ErrorCode::Qry004, + "QRY-004", + "Invalid value: {}", + ErrorCategory::Query, + ), + ( + ErrorCode::Qry005, + "QRY-005", + "Transaction failed: {}", + ErrorCategory::Query, + ), + ( + ErrorCode::Qry006, + "QRY-006", + "Retraction failed: {}", + ErrorCategory::Query, + ), + ( + ErrorCode::Qry007, + "QRY-007", + "unknown predicate: '{}'", + ErrorCategory::Query, + ), + ( + ErrorCode::Qry008, + "QRY-008", + "functions lock poisoned", + ErrorCategory::Query, + ), + ( + ErrorCode::Qry009, + "QRY-009", + "rules lock poisoned", + ErrorCategory::Query, + ), ( ErrorCode::Int000, "INT-000", @@ -336,6 +399,15 @@ mod tests { } match ErrorCode::Int000 { + ErrorCode::Qry001 => assert_has_registry_entry(ErrorCode::Qry001), + ErrorCode::Qry002 => assert_has_registry_entry(ErrorCode::Qry002), + ErrorCode::Qry003 => assert_has_registry_entry(ErrorCode::Qry003), + ErrorCode::Qry004 => assert_has_registry_entry(ErrorCode::Qry004), + ErrorCode::Qry005 => assert_has_registry_entry(ErrorCode::Qry005), + ErrorCode::Qry006 => assert_has_registry_entry(ErrorCode::Qry006), + ErrorCode::Qry007 => assert_has_registry_entry(ErrorCode::Qry007), + ErrorCode::Qry008 => assert_has_registry_entry(ErrorCode::Qry008), + ErrorCode::Qry009 => assert_has_registry_entry(ErrorCode::Qry009), ErrorCode::Int000 => assert_has_registry_entry(ErrorCode::Int000), ErrorCode::Wal001 => assert_has_registry_entry(ErrorCode::Wal001), ErrorCode::Wal002 => assert_has_registry_entry(ErrorCode::Wal002), diff --git a/src/query/datalog/evaluator.rs b/src/query/datalog/evaluator.rs index 08835ecad2..8e42a96ee0 100644 --- a/src/query/datalog/evaluator.rs +++ b/src/query/datalog/evaluator.rs @@ -27,6 +27,7 @@ use super::functions::FunctionRegistry; use super::matcher::{Bindings, PatternMatcher, edn_to_entity_id, edn_to_value}; use super::rules::RuleRegistry; use super::types::{AttributeSpec, EdnValue, Pattern, Rule, WhereClause}; +use crate::error::{ErrorCode, err_coded}; use crate::graph::FactStorage; use crate::graph::types::{Fact, Value}; use crate::storage::index::encode_value; @@ -206,7 +207,7 @@ impl RecursiveEvaluator { let registry = self .rules .read() - .map_err(|_| anyhow!("rule registry lock poisoned"))?; + .map_err(|_| err_coded!(ErrorCode::Qry009))?; // For each predicate, evaluate all its rules for predicate in predicates { @@ -286,7 +287,7 @@ impl RecursiveEvaluator { let fn_guard = self .functions .read() - .map_err(|_| anyhow!("function registry lock poisoned"))?; + .map_err(|_| err_coded!(ErrorCode::Qry008))?; let bindings = apply_expr_clauses_in_evaluator(bindings, &expr_clauses, &fn_guard); for binding in bindings { @@ -609,7 +610,7 @@ impl StratifiedEvaluator { let registry = self .rules .read() - .map_err(|_| anyhow!("rule registry lock poisoned"))?; + .map_err(|_| err_coded!(ErrorCode::Qry009))?; // Build dependency graph and stratify let graph = DependencyGraph::from_rules(®istry); @@ -652,7 +653,7 @@ impl StratifiedEvaluator { let registry = self .rules .read() - .map_err(|_| anyhow!("rule registry lock poisoned"))?; + .map_err(|_| err_coded!(ErrorCode::Qry009))?; let stratum_preds: Vec = all_preds .iter() .filter(|p| *strata.get(*p).unwrap_or(&0) == stratum) @@ -819,7 +820,7 @@ impl StratifiedEvaluator { let fn_guard = self .functions .read() - .map_err(|_| anyhow!("function registry lock poisoned"))?; + .map_err(|_| err_coded!(ErrorCode::Qry008))?; let mut candidates: Vec = vec![Bindings::new()]; for (clause, hint) in planned { match clause { @@ -862,7 +863,7 @@ impl StratifiedEvaluator { let registry_guard = self .rules .read() - .map_err(|_| anyhow!("rule registry lock poisoned"))?; + .map_err(|_| err_coded!(ErrorCode::Qry009))?; // Rule bodies in the semi-naive evaluator don't have access to a // FunctionRegistry (UDF registration happens at the db layer). Use the // built-in-only registry so or-branches can still use built-in predicates. @@ -952,7 +953,7 @@ impl StratifiedEvaluator { let fn_guard = self .functions .read() - .map_err(|_| anyhow!("function registry lock poisoned"))?; + .map_err(|_| err_coded!(ErrorCode::Qry008))?; not_bindings = apply_expr_clauses_in_evaluator( not_bindings, ¬_body_expr_clauses, @@ -968,7 +969,7 @@ impl StratifiedEvaluator { let fn_guard = self .functions .read() - .map_err(|_| anyhow!("function registry lock poisoned"))?; + .map_err(|_| err_coded!(ErrorCode::Qry008))?; if evaluate_not_join( join_vars, nj_clauses, @@ -1061,6 +1062,20 @@ mod tests { // ── Additional targeted branch coverage ─────────────────────────────────── + /// `FactStorage` (the `Ok` type of `evaluate_recursive_rules`/`evaluate`) + /// deliberately does not implement `Debug`, so `Result::unwrap_err()` — which + /// requires `T: Debug` to format a panic message on the non-error branch — + /// cannot be used directly. Extract the code via a plain match instead. + fn expect_err_code(result: Result) -> String { + match result { + Ok(_) => panic!("expected an error"), + Err(e) => { + let err: crate::error::MinigrafError = e.into(); + err.code().to_string() + } + } + } + #[test] fn test_max_iterations_exceeded_returns_error() { // Line 113: iteration > self.max_iterations → returns Err @@ -1086,7 +1101,135 @@ mod tests { DEFAULT_MAX_RESULTS, ); let result = evaluator.evaluate_recursive_rules(&["reachable".to_string()]); - assert!(result.is_err(), "should fail when max iterations exceeded"); + let code = expect_err_code(result); + // No QRY-0xx code is documented in ERROR_REFERENCE.md for the + // recursion/depth-limit family ("Max iterations exceeded", "Max + // derived facts exceeded", "Max query results exceeded") — the 9 + // documented QRY codes cover transact/retract validation, unknown + // predicates, and function/rule registry lock poisoning only. This + // is a live, public-API-reachable error path (a query over a + // non-terminating recursive rule with a low `max_derived_facts`/ + // `max_results`, or — as constructed directly here — a pathological + // `max_iterations`), currently falling through to the generic + // INT-000 catch-all by design (see src/error.rs's `MinigrafError::from` + // fallback). Locking in today's code here so this is a deliberate, + // documented gap rather than a silent one; assigning it a real code + // is candidate follow-up work for the API+INT category PR (#277 + // step 6), which audits every leftover uncoded call site crate-wide. + assert_eq!(code, "INT-000"); + } + + #[test] + fn test_max_derived_facts_exceeded_returns_int000() { + // Same rationale as test_max_iterations_exceeded_returns_error above: + // "Max derived facts per iteration exceeded" has no documented QRY + // code, so it currently — and, for this PR, deliberately — surfaces + // as INT-000. + let storage = create_test_storage(); + let rules = Arc::new(RwLock::new(RuleRegistry::new())); + register_test_rule(&rules, r#"(rule [(reachable ?x ?y) [?x :connected ?y]])"#); + register_test_rule( + &rules, + r#"(rule [(reachable ?x ?y) [?x :connected ?z] (reachable ?z ?y)])"#, + ); + let functions = Arc::new(RwLock::new(FunctionRegistry::with_builtins())); + // max_derived_facts=0 means the very first iteration's derived facts + // (there are 2 base :connected facts) exceed the limit. + let evaluator = + RecursiveEvaluator::new(storage, rules, functions, 1000, 0, DEFAULT_MAX_RESULTS); + let result = evaluator.evaluate_recursive_rules(&["reachable".to_string()]); + let code = expect_err_code(result); + assert_eq!(code, "INT-000"); + } + + #[test] + fn evaluate_iteration_rule_registry_lock_poisoned_error() { + let storage = create_test_storage(); + let rules = Arc::new(RwLock::new(RuleRegistry::new())); + register_test_rule(&rules, r#"(rule [(reachable ?x ?y) [?x :connected ?y]])"#); + let functions = Arc::new(RwLock::new(FunctionRegistry::with_builtins())); + { + let rules = rules.clone(); + let _ = std::thread::spawn(move || { + let _guard = rules.write().unwrap(); + panic!( + "deliberate poison for evaluate_iteration_rule_registry_lock_poisoned_error" + ); + }) + .join(); + } + let evaluator = RecursiveEvaluator::new( + storage, + rules, + functions, + DEFAULT_MAX_ITERATIONS, + DEFAULT_MAX_DERIVED_FACTS, + DEFAULT_MAX_RESULTS, + ); + let result = evaluator.evaluate_recursive_rules(&["reachable".to_string()]); + let code = expect_err_code(result); + assert_eq!(code, "QRY-009"); + } + + #[test] + fn evaluate_rule_function_registry_lock_poisoned_error() { + // Exercises evaluate_rule's function registry read (used to apply + // Expr clauses in a rule body). + let storage = create_test_storage(); + let rules = Arc::new(RwLock::new(RuleRegistry::new())); + register_test_rule( + &rules, + r#"(rule [(over_ten ?x ?y) [?x :connected ?y] [(> 1 0)]])"#, + ); + let functions = Arc::new(RwLock::new(FunctionRegistry::with_builtins())); + { + let functions = functions.clone(); + let _ = std::thread::spawn(move || { + let _guard = functions.write().unwrap(); + panic!("deliberate poison for evaluate_rule_function_registry_lock_poisoned_error"); + }) + .join(); + } + let evaluator = RecursiveEvaluator::new( + storage, + rules, + functions, + DEFAULT_MAX_ITERATIONS, + DEFAULT_MAX_DERIVED_FACTS, + DEFAULT_MAX_RESULTS, + ); + let result = evaluator.evaluate_recursive_rules(&["over_ten".to_string()]); + let code = expect_err_code(result); + assert_eq!(code, "QRY-008"); + } + + #[test] + fn stratified_evaluate_rule_registry_lock_poisoned_error() { + let storage = create_test_storage(); + let rules = Arc::new(RwLock::new(RuleRegistry::new())); + register_test_rule(&rules, r#"(rule [(reachable ?x ?y) [?x :connected ?y]])"#); + let functions = Arc::new(RwLock::new(FunctionRegistry::with_builtins())); + { + let rules = rules.clone(); + let _ = std::thread::spawn(move || { + let _guard = rules.write().unwrap(); + panic!( + "deliberate poison for stratified_evaluate_rule_registry_lock_poisoned_error" + ); + }) + .join(); + } + let evaluator = StratifiedEvaluator::new( + storage, + rules, + functions, + DEFAULT_MAX_ITERATIONS, + DEFAULT_MAX_DERIVED_FACTS, + DEFAULT_MAX_RESULTS, + ); + let result = evaluator.evaluate(&["reachable".to_string()]); + let code = expect_err_code(result); + assert_eq!(code, "QRY-009"); } #[test] diff --git a/src/query/datalog/executor.rs b/src/query/datalog/executor.rs index 0bd7561051..7b4d6e7539 100644 --- a/src/query/datalog/executor.rs +++ b/src/query/datalog/executor.rs @@ -7,6 +7,7 @@ use super::types::{ AsOf, AttributeSpec, BinOp, DatalogCommand, DatalogQuery, EdnValue, Expr, FindSpec, Order, Pattern, Rule, Transaction, UnaryOp, ValidAt, WhereClause, WindowFunc, }; +use crate::error::{ErrorCode, bail_coded, err_coded}; use crate::graph::FactStorage; use crate::graph::types::{Fact, TransactOptions, TxId, Value, tx_id_now}; use anyhow::{Result, anyhow}; @@ -241,18 +242,18 @@ impl DatalogExecutor { let mut fact_tuples = Vec::new(); for pattern in tx.facts { let entity_id = - edn_to_entity_id(&pattern.entity).map_err(|e| anyhow!("Invalid entity: {}", e))?; + edn_to_entity_id(&pattern.entity).map_err(|e| err_coded!(ErrorCode::Qry001, e))?; let attribute = match &pattern.attribute { AttributeSpec::Real(EdnValue::Keyword(k)) => k.clone(), - AttributeSpec::Real(_) => return Err(anyhow!("Attribute must be a keyword")), + AttributeSpec::Real(_) => bail_coded!(ErrorCode::Qry002), AttributeSpec::Pseudo(_) => { - return Err(anyhow!("Cannot transact a pseudo-attribute")); + bail_coded!(ErrorCode::Qry003); } }; let value = - edn_to_value(&pattern.value).map_err(|e| anyhow!("Invalid value: {}", e))?; + edn_to_value(&pattern.value).map_err(|e| err_coded!(ErrorCode::Qry004, e))?; let per_fact_opts = if pattern.valid_from.is_some() || pattern.valid_to.is_some() { Some(TransactOptions::new(pattern.valid_from, pattern.valid_to)) @@ -266,7 +267,7 @@ impl DatalogExecutor { let (tx_id, _tx_count) = self .storage .transact_batch(fact_tuples, tx_opts) - .map_err(|e| anyhow!("Transaction failed: {}", e))?; + .map_err(|e| err_coded!(ErrorCode::Qry005, e))?; Ok(QueryResult::Transacted(tx_id)) } @@ -277,18 +278,18 @@ impl DatalogExecutor { for pattern in tx.facts { let entity_id = - edn_to_entity_id(&pattern.entity).map_err(|e| anyhow!("Invalid entity: {}", e))?; + edn_to_entity_id(&pattern.entity).map_err(|e| err_coded!(ErrorCode::Qry001, e))?; let attribute = match &pattern.attribute { AttributeSpec::Real(EdnValue::Keyword(k)) => k.clone(), - AttributeSpec::Real(_) => return Err(anyhow!("Attribute must be a keyword")), + AttributeSpec::Real(_) => bail_coded!(ErrorCode::Qry002), AttributeSpec::Pseudo(_) => { - return Err(anyhow!("Cannot transact a pseudo-attribute")); + bail_coded!(ErrorCode::Qry003); } }; let value = - edn_to_value(&pattern.value).map_err(|e| anyhow!("Invalid value: {}", e))?; + edn_to_value(&pattern.value).map_err(|e| err_coded!(ErrorCode::Qry004, e))?; fact_tuples.push((entity_id, attribute, value)); } @@ -296,7 +297,7 @@ impl DatalogExecutor { let (tx_id, _tx_count) = self .storage .retract(fact_tuples) - .map_err(|e| anyhow!("Retraction failed: {}", e))?; + .map_err(|e| err_coded!(ErrorCode::Qry006, e))?; Ok(QueryResult::Retracted(tx_id)) } @@ -502,7 +503,7 @@ impl DatalogExecutor { let registry = self .functions .read() - .map_err(|_| anyhow!("functions lock poisoned"))?; + .map_err(|_| err_coded!(ErrorCode::Qry008))?; // Pre-validate UDF predicate names: surface unknown predicates as errors before // processing any rows (matches the behaviour of the former apply_expr_clauses post-pass). @@ -513,7 +514,7 @@ impl DatalogExecutor { } = clause && registry.get_predicate(name).is_none() { - anyhow::bail!("unknown predicate: '{}'", name); + bail_coded!(ErrorCode::Qry007, name); } } @@ -593,7 +594,7 @@ impl DatalogExecutor { let rules_guard = self .rules .read() - .map_err(|_| anyhow!("rules lock poisoned"))?; + .map_err(|_| err_coded!(ErrorCode::Qry009))?; let mut bindings = apply_or_clauses( &query.where_clauses, bindings, @@ -695,7 +696,7 @@ impl DatalogExecutor { let reg = self .rules .read() - .map_err(|_| anyhow!("rule registry lock poisoned"))?; + .map_err(|_| err_coded!(ErrorCode::Qry009))?; crate::query::datalog::magic_sets::rewrite(&query, ®) }; let (eval_rules, seed_facts) = match rewritten { @@ -733,7 +734,7 @@ impl DatalogExecutor { let registry = self .functions .read() - .map_err(|_| anyhow!("functions lock poisoned"))?; + .map_err(|_| err_coded!(ErrorCode::Qry008))?; // Pre-validate UDF predicate names. for clause in &query.where_clauses { @@ -743,7 +744,7 @@ impl DatalogExecutor { } = clause && registry.get_predicate(name).is_none() { - anyhow::bail!("unknown predicate: '{}'", name); + bail_coded!(ErrorCode::Qry007, name); } } @@ -851,7 +852,7 @@ impl DatalogExecutor { let rules_guard = self .rules .read() - .map_err(|_| anyhow!("rules lock poisoned"))?; + .map_err(|_| err_coded!(ErrorCode::Qry009))?; let mut bindings = apply_or_clauses( &query.where_clauses, bindings, @@ -908,7 +909,7 @@ impl DatalogExecutor { // Register the rule self.rules .write() - .map_err(|_| anyhow!("rules lock poisoned"))? + .map_err(|_| err_coded!(ErrorCode::Qry009))? .register_rule(predicate, rule)?; Ok(QueryResult::Ok) @@ -2376,7 +2377,7 @@ pub(crate) fn apply_expr_clauses( } = clause && registry.get_predicate(name).is_none() { - anyhow::bail!("unknown predicate: '{}'", name); + bail_coded!(ErrorCode::Qry007, name); } } @@ -4495,6 +4496,18 @@ mod expr_eval_tests { } // ── Stream 3: branches unreachable via the parser ───────────────────────── + // + // `execute_transact`/`execute_retract` (below) carry the QRY-001..006 + // codes, but `Minigraf::execute()`'s write path (src/db.rs `execute_inner`) + // routes `transact`/`retract` commands through `Minigraf::materialize_transaction`/ + // `materialize_retraction` instead, for WAL-first-ordering reasons — it + // never calls these methods. That makes these branches unreachable from + // `db.execute()` today (confirmed empirically, not just by inspection), so + // they are exercised here via direct `DatalogExecutor` construction, same + // as the rest of this "unreachable via the parser" stream. `db.rs`'s own + // near-duplicate messages are already earmarked as API-003/API-004 in + // ERROR_REFERENCE.md for the API+INT category PR (#277 step 6); QRY-001/ + // 004/005/006 currently have no `db.rs`-side equivalent at all. #[test] fn execute_transact_non_keyword_attribute_error() { @@ -4511,7 +4524,8 @@ mod expr_eval_tests { valid_to: None, }); let r = executor.execute(cmd); - assert!(r.is_err(), "non-keyword attribute in transact must fail"); + let err: crate::error::MinigrafError = r.unwrap_err().into(); + assert_eq!(err.code(), "QRY-002"); } #[test] @@ -4528,12 +4542,13 @@ mod expr_eval_tests { valid_to: None, }); let r = executor.execute(cmd); - assert!(r.is_err(), "non-keyword attribute in retract must fail"); + let err: crate::error::MinigrafError = r.unwrap_err().into(); + assert_eq!(err.code(), "QRY-002"); } #[test] fn execute_transact_pseudo_attr_error() { - // Exercises executor.rs line 103: Pseudo(_) arm in execute_transact + // Exercises the Pseudo(_) arm in execute_transact use crate::query::datalog::types::{PseudoAttr, Transaction}; let storage = FactStorage::new(); let executor = DatalogExecutor::new(storage); @@ -4547,12 +4562,13 @@ mod expr_eval_tests { valid_to: None, }); let r = executor.execute(cmd); - assert!(r.is_err(), "transacting a pseudo-attribute must fail"); + let err: crate::error::MinigrafError = r.unwrap_err().into(); + assert_eq!(err.code(), "QRY-003"); } #[test] fn execute_retract_pseudo_attr_error() { - // Exercises executor.rs line 139: Pseudo(_) arm in execute_retract + // Exercises the Pseudo(_) arm in execute_retract use crate::query::datalog::types::{PseudoAttr, Transaction}; let storage = FactStorage::new(); let executor = DatalogExecutor::new(storage); @@ -4566,7 +4582,175 @@ mod expr_eval_tests { valid_to: None, }); let r = executor.execute(cmd); - assert!(r.is_err(), "retracting a pseudo-attribute must fail"); + let err: crate::error::MinigrafError = r.unwrap_err().into(); + assert_eq!(err.code(), "QRY-003"); + } + + #[test] + fn execute_transact_invalid_entity_error() { + // Entity is neither a Keyword nor a Uuid — edn_to_entity_id fails. + let storage = FactStorage::new(); + let executor = DatalogExecutor::new(storage); + let cmd = DatalogCommand::Transact(Transaction { + facts: vec![Pattern::new( + EdnValue::String("not-a-uuid".to_string()), + EdnValue::Keyword(":name".to_string()), + EdnValue::String("Alice".to_string()), + )], + valid_from: None, + valid_to: None, + }); + let r = executor.execute(cmd); + let err: crate::error::MinigrafError = r.unwrap_err().into(); + assert_eq!(err.code(), "QRY-001"); + } + + #[test] + fn execute_retract_invalid_entity_error() { + let storage = FactStorage::new(); + let executor = DatalogExecutor::new(storage); + let cmd = DatalogCommand::Retract(Transaction { + facts: vec![Pattern::new( + EdnValue::Integer(42), + EdnValue::Keyword(":name".to_string()), + EdnValue::String("Alice".to_string()), + )], + valid_from: None, + valid_to: None, + }); + let r = executor.execute(cmd); + let err: crate::error::MinigrafError = r.unwrap_err().into(); + assert_eq!(err.code(), "QRY-001"); + } + + #[test] + fn execute_transact_invalid_value_error() { + // An unbound `?variable` symbol cannot be converted to a stored Value. + let storage = FactStorage::new(); + let executor = DatalogExecutor::new(storage); + let cmd = DatalogCommand::Transact(Transaction { + facts: vec![Pattern::new( + EdnValue::Keyword(":e".to_string()), + EdnValue::Keyword(":name".to_string()), + EdnValue::Symbol("?unbound".to_string()), + )], + valid_from: None, + valid_to: None, + }); + let r = executor.execute(cmd); + let err: crate::error::MinigrafError = r.unwrap_err().into(); + assert_eq!(err.code(), "QRY-004"); + } + + #[test] + fn execute_retract_invalid_value_error() { + let storage = FactStorage::new(); + let executor = DatalogExecutor::new(storage); + let cmd = DatalogCommand::Retract(Transaction { + facts: vec![Pattern::new( + EdnValue::Keyword(":e".to_string()), + EdnValue::Keyword(":name".to_string()), + EdnValue::Symbol("?unbound".to_string()), + )], + valid_from: None, + valid_to: None, + }); + let r = executor.execute(cmd); + let err: crate::error::MinigrafError = r.unwrap_err().into(); + assert_eq!(err.code(), "QRY-004"); + } + + // NOTE: QRY-005 (Transaction failed) and QRY-006 (Retraction failed) wrap + // `FactStorage::transact_batch`/`retract`'s only failure mode — its + // private `data: RwLock` (src/graph/storage.rs) being poisoned. + // That field isn't reachable from this module (or from any of the other + // four files in this issue's scope) without a test-only hook inside + // `src/graph/storage.rs`, which is outside this PR's scope (issue #361 + // covers only executor.rs/evaluator.rs/optimizer.rs/matcher.rs/ + // magic_sets.rs). The call sites are migrated and their templates are + // verified against ERROR_REFERENCE.md by `error::tests:: + // registry_is_a_subset_of_error_reference_doc`; a genuine end-to-end + // trigger is left to whichever PR next touches src/graph/storage.rs. + + /// Poisons `lock` with a real panic in another thread while the write + /// guard is held, then joins (discarding the panic payload). Unlike + /// `FactStorage`'s internal `data` lock, `rules`/`functions` are + /// constructor parameters of `DatalogExecutor`, so they can be poisoned + /// from outside — no test hook needed in another file. + fn poison_rwlock(lock: &Arc>) + where + T: Send + Sync + 'static, + { + let lock = lock.clone(); + let _ = std::thread::spawn(move || { + let _guard = lock.write().unwrap(); + panic!("deliberate poison for a QRY-008/QRY-009 regression test"); + }) + .join(); + } + + #[test] + fn execute_query_functions_lock_poisoned_error() { + let storage = FactStorage::new(); + let rules = Arc::new(RwLock::new(RuleRegistry::new())); + let functions = Arc::new(RwLock::new(FunctionRegistry::with_builtins())); + poison_rwlock(&functions); + + let executor = DatalogExecutor::new_with_rules_and_functions(storage, rules, functions); + let cmd = parse_datalog_command(r#"(query [:find ?e :where [?e :name ?n]])"#).unwrap(); + let r = executor.execute(cmd); + let err: crate::error::MinigrafError = r.unwrap_err().into(); + assert_eq!(err.code(), "QRY-008"); + } + + #[test] + fn execute_rule_rules_lock_poisoned_error() { + let storage = FactStorage::new(); + let rules = Arc::new(RwLock::new(RuleRegistry::new())); + let functions = Arc::new(RwLock::new(FunctionRegistry::with_builtins())); + poison_rwlock(&rules); + + let executor = DatalogExecutor::new_with_rules_and_functions(storage, rules, functions); + let cmd = parse_datalog_command(r#"(rule [(p ?x) [?x :a true]])"#).unwrap(); + let r = executor.execute(cmd); + let err: crate::error::MinigrafError = r.unwrap_err().into(); + assert_eq!(err.code(), "QRY-009"); + } + + #[test] + fn execute_query_with_rules_rules_lock_poisoned_error() { + // Covers the magic-sets rewrite's rules.read() in execute_query_with_rules + // (distinct call site from execute_rule's rules.write()). + let storage = FactStorage::new(); + let rules = Arc::new(RwLock::new(RuleRegistry::new())); + let functions = Arc::new(RwLock::new(FunctionRegistry::with_builtins())); + { + // Register a rule normally first so the query recognises it as + // rule-backed (uses_rules()) and takes the rules path. + let mut reg = rules.write().unwrap(); + reg.register_rule( + "p".to_string(), + Rule { + head: vec![ + EdnValue::Symbol("p".to_string()), + EdnValue::Symbol("?x".to_string()), + ], + body: vec![WhereClause::Pattern(Pattern::new( + EdnValue::Symbol("?x".to_string()), + EdnValue::Keyword(":a".to_string()), + EdnValue::Boolean(true), + ))], + }, + ) + .unwrap(); + } + poison_rwlock(&rules); + + let executor = DatalogExecutor::new_with_rules_and_functions(storage, rules, functions); + let cmd = parse_datalog_command(r#"(query [:find ?x :where (p ?x)])"#).unwrap(); + let r = executor.execute(cmd); + let err: crate::error::MinigrafError = r.unwrap_err().into(); + assert_eq!(err.code(), "QRY-009"); } #[test] diff --git a/tests/error_codes_qry_test.rs b/tests/error_codes_qry_test.rs new file mode 100644 index 0000000000..94d8888827 --- /dev/null +++ b/tests/error_codes_qry_test.rs @@ -0,0 +1,109 @@ +//! Regression tests for issue #361 (part of #277): QRY-0xx error codes. +//! +//! Drives the full public `Minigraf::execute()` API and asserts the specific +//! `QRY-00N` code documented in `docs/ERROR_REFERENCE.md` comes back through +//! `MinigrafError::code()`. +//! +//! Coverage note: only QRY-007 (unknown predicate) and QRY-008/QRY-009 +//! (function/rule registry lock poisoned) are reachable through +//! `Minigraf::execute()` for a *query* — that path constructs a +//! `DatalogExecutor` directly (see `src/db.rs` `execute_inner`'s read-only +//! branch). QRY-001..006 (transact/retract validation, wired in +//! `DatalogExecutor::execute_transact`/`execute_retract`) are NOT reachable +//! through `Minigraf::execute()` today: `execute_inner`'s write path routes +//! `transact`/`retract` commands through `Minigraf::materialize_transaction`/ +//! `materialize_retraction` (src/db.rs) instead, for WAL-first-ordering +//! reasons, and never calls those `DatalogExecutor` methods. `db.rs`'s +//! near-duplicate messages there are already earmarked as API-003/API-004 in +//! ERROR_REFERENCE.md for the API+INT category PR (#277 step 6); QRY-001/ +//! 004/005/006 currently have no `db.rs`-side equivalent at all. QRY-001..006 +//! are still migrated and covered by unit tests in +//! `src/query/datalog/executor.rs` (constructing `DatalogExecutor` directly, +//! the same convention already used there for other parser-unreachable +//! branches) — see that file's "Stream 3: branches unreachable via the +//! parser" test group. +//! +//! This file also locks in current (INT-000) behavior for two error families +//! that live in this issue's in-scope files but have no documented QRY code: +//! the recursive-rule iteration/derived-fact/result limit family in +//! `src/query/datalog/evaluator.rs` (the "limit/depth-exceeded" and +//! "recursion-error" paths), and the runtime aggregate type-mismatch family, +//! which is raised in `src/query/datalog/functions.rs` — not one of this +//! issue's five in-scope files, so it's out of scope for migration here. + +use minigraf::Minigraf; + +// ─── QRY-007: unknown predicate ─────────────────────────────────────────── + +#[test] +fn query_unknown_predicate_returns_qry_007() { + let db = Minigraf::in_memory().unwrap(); + db.execute(r#"(transact [[:a :x "hello"]])"#).unwrap(); + let result = db.execute(r#"(query [:find ?e :where [?e :x ?v] [(nosuchpred361? ?v)]])"#); + let err = result.expect_err("unknown predicate must fail"); + assert_eq!(err.code(), "QRY-007"); +} + +#[test] +fn query_with_rules_unknown_predicate_returns_qry_007() { + // Same check, but through the rules-aware execute_query_with_rules path + // (a distinct call site from the plain execute_query path above). + let db = Minigraf::in_memory().unwrap(); + db.execute(r#"(transact [[:a :x "hello"]])"#).unwrap(); + db.execute(r#"(rule [(p ?e) [?e :x ?v]])"#).unwrap(); + let result = + db.execute(r#"(query [:find ?e :where (p ?e) [?e :x ?v] [(nosuchpred361b? ?v)]])"#); + let err = result.expect_err("unknown predicate must fail"); + assert_eq!(err.code(), "QRY-007"); +} + +// ─── Limit/recursion-error family: no documented QRY code (INT-000) ─────── + +/// A recursive rule with an artificially tiny per-query `max_derived_facts` +/// hits `RecursiveEvaluator::evaluate_recursive_rules`'s "Max derived facts +/// per iteration exceeded" branch (src/query/datalog/evaluator.rs). No +/// QRY-0xx code is documented for this in ERROR_REFERENCE.md — see the +/// module doc comment above for why. This test locks in that it currently +/// (and, for the scope of this PR, deliberately) surfaces as INT-000 rather +/// than silently succeeding or panicking. +#[test] +fn recursive_rule_derived_facts_limit_returns_int000() { + let db = Minigraf::in_memory().unwrap(); + db.execute(r#"(transact [[:a :connected :b] [:b :connected :c] [:c :connected :d]])"#) + .unwrap(); + db.execute(r#"(rule [(reachable ?x ?y) [?x :connected ?y]])"#) + .unwrap(); + db.execute(r#"(rule [(reachable ?x ?y) [?x :connected ?z] (reachable ?z ?y)])"#) + .unwrap(); + let result = + db.execute(r#"(query [:find ?x ?y :where (reachable ?x ?y) :max-derived-facts 1])"#); + match result { + Ok(_) => { + // If per-query :max-derived-facts syntax isn't recognised (or + // the limit isn't tight enough to trip on this tiny dataset), + // this test isn't exercising the intended branch — investigate + // rather than treat as a pass. + panic!("expected the derived-facts limit to be exceeded"); + } + Err(err) => assert_eq!(err.code(), "INT-000"), + } +} + +// ─── Runtime type-mismatch family: out of this issue's file scope ───────── + +/// `sum` over a non-numeric attribute fails at query execution time. The +/// error originates in `apply_builtin_aggregate` +/// (src/query/datalog/functions.rs), which is NOT one of this issue's five +/// in-scope files (executor.rs, evaluator.rs, optimizer.rs, matcher.rs, +/// magic_sets.rs) — so it is intentionally left uncoded by this PR and +/// currently surfaces as INT-000. Locked in here as a known, documented gap +/// rather than left to silently regress. +#[test] +fn aggregate_type_mismatch_returns_int000() { + let db = Minigraf::in_memory().unwrap(); + db.execute(r#"(transact [[:a :score "high"] [:b :score "low"]])"#) + .unwrap(); + let result = db.execute(r#"(query [:find (sum ?s) :where [?e :score ?s]])"#); + let err = result.expect_err("sum of strings must fail at runtime"); + assert_eq!(err.code(), "INT-000"); +}