From 91409339654df28a1f429c3711882b59c7a8c773 Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Tue, 31 Mar 2026 16:07:57 +0530 Subject: [PATCH 01/14] refactor: add PseudoAttr/AttributeSpec types, migrate Pattern.attribute Co-Authored-By: Claude Sonnet 4.6 --- src/db.rs | 12 +-- src/query/datalog/evaluator.rs | 18 ++-- src/query/datalog/executor.rs | 18 ++-- src/query/datalog/matcher.rs | 42 ++++++---- src/query/datalog/optimizer.rs | 23 +++--- src/query/datalog/parser.rs | 16 +++- src/query/datalog/types.rs | 147 +++++++++++++++++++++++++++++++-- 7 files changed, 226 insertions(+), 50 deletions(-) diff --git a/src/db.rs b/src/db.rs index e6bc3a9f29..f36736731b 100644 --- a/src/db.rs +++ b/src/db.rs @@ -20,7 +20,7 @@ use crate::query::datalog::executor::DatalogExecutor; use crate::query::datalog::executor::QueryResult; use crate::query::datalog::parser::parse_datalog_command; use crate::query::datalog::rules::RuleRegistry; -use crate::query::datalog::types::{DatalogCommand, Transaction}; +use crate::query::datalog::types::{AttributeSpec, DatalogCommand, EdnValue, Transaction}; use crate::storage::backend::MemoryBackend; use crate::storage::backend::file::FileBackend; use crate::storage::persistent_facts::PersistentFactStorage; @@ -572,8 +572,9 @@ impl Minigraf { .map_err(|e| anyhow::anyhow!("invalid entity: {}", e))?; let attr = match &pattern.attribute { - EdnValue::Keyword(k) => k.clone(), - _ => anyhow::bail!("attribute must be a keyword"), + AttributeSpec::Real(EdnValue::Keyword(k)) => k.clone(), + AttributeSpec::Real(_) => anyhow::bail!("attribute must be a keyword"), + AttributeSpec::Pseudo(_) => anyhow::bail!("cannot transact a pseudo-attribute"), }; let value = edn_to_value(&pattern.value) @@ -608,8 +609,9 @@ impl Minigraf { .map_err(|e| anyhow::anyhow!("invalid entity: {}", e))?; let attr = match &pattern.attribute { - EdnValue::Keyword(k) => k.clone(), - _ => anyhow::bail!("attribute must be a keyword"), + AttributeSpec::Real(EdnValue::Keyword(k)) => k.clone(), + AttributeSpec::Real(_) => anyhow::bail!("attribute must be a keyword"), + AttributeSpec::Pseudo(_) => anyhow::bail!("cannot transact a pseudo-attribute"), }; let value = edn_to_value(&pattern.value) diff --git a/src/query/datalog/evaluator.rs b/src/query/datalog/evaluator.rs index 3ad54e1f12..301cc531cf 100644 --- a/src/query/datalog/evaluator.rs +++ b/src/query/datalog/evaluator.rs @@ -25,7 +25,7 @@ /// ``` use super::matcher::{Bindings, PatternMatcher, edn_to_entity_id, edn_to_value}; use super::rules::RuleRegistry; -use super::types::{EdnValue, Pattern, Rule, WhereClause}; +use super::types::{AttributeSpec, EdnValue, Pattern, Rule, WhereClause}; use crate::graph::FactStorage; use crate::graph::types::{Fact, Value}; use anyhow::{Result, anyhow}; @@ -356,11 +356,17 @@ pub fn value_to_edn(value: &Value) -> EdnValue { /// Substitute bound variables in a Pattern, returning a new Pattern with concrete values. pub fn substitute_pattern(pattern: &Pattern, binding: &Bindings) -> Pattern { - Pattern::new( - substitute_value(&pattern.entity, binding), - substitute_value(&pattern.attribute, binding), - substitute_value(&pattern.value, binding), - ) + let attribute = match &pattern.attribute { + AttributeSpec::Real(edn) => AttributeSpec::Real(substitute_value(edn, binding)), + AttributeSpec::Pseudo(p) => AttributeSpec::Pseudo(p.clone()), + }; + Pattern { + entity: substitute_value(&pattern.entity, binding), + attribute, + value: substitute_value(&pattern.value, binding), + valid_from: pattern.valid_from, + valid_to: pattern.valid_to, + } } /// Substitute a single value: if it's a bound variable, replace it; otherwise clone. diff --git a/src/query/datalog/executor.rs b/src/query/datalog/executor.rs index 7367fd737a..b7de563b51 100644 --- a/src/query/datalog/executor.rs +++ b/src/query/datalog/executor.rs @@ -3,8 +3,8 @@ use super::matcher::{PatternMatcher, edn_to_entity_id, edn_to_value}; use super::optimizer; use super::rules::RuleRegistry; use super::types::{ - AggFunc, AsOf, BinOp, DatalogCommand, DatalogQuery, EdnValue, Expr, FindSpec, Pattern, Rule, - Transaction, UnaryOp, ValidAt, WhereClause, + AggFunc, AsOf, AttributeSpec, BinOp, DatalogCommand, DatalogQuery, EdnValue, Expr, FindSpec, + Pattern, Rule, Transaction, UnaryOp, ValidAt, WhereClause, }; use crate::graph::FactStorage; use crate::graph::types::{Fact, TransactOptions, TxId, Value, tx_id_now}; @@ -77,8 +77,11 @@ impl DatalogExecutor { edn_to_entity_id(&pattern.entity).map_err(|e| anyhow!("Invalid entity: {}", e))?; let attribute = match &pattern.attribute { - EdnValue::Keyword(k) => k.clone(), - _ => return Err(anyhow!("Attribute must be a keyword")), + AttributeSpec::Real(EdnValue::Keyword(k)) => k.clone(), + AttributeSpec::Real(_) => return Err(anyhow!("Attribute must be a keyword")), + AttributeSpec::Pseudo(_) => { + return Err(anyhow!("Cannot transact a pseudo-attribute")) + } }; let value = @@ -110,8 +113,11 @@ impl DatalogExecutor { edn_to_entity_id(&pattern.entity).map_err(|e| anyhow!("Invalid entity: {}", e))?; let attribute = match &pattern.attribute { - EdnValue::Keyword(k) => k.clone(), - _ => return Err(anyhow!("Attribute must be a keyword")), + AttributeSpec::Real(EdnValue::Keyword(k)) => k.clone(), + AttributeSpec::Real(_) => return Err(anyhow!("Attribute must be a keyword")), + AttributeSpec::Pseudo(_) => { + return Err(anyhow!("Cannot transact a pseudo-attribute")) + } }; let value = diff --git a/src/query/datalog/matcher.rs b/src/query/datalog/matcher.rs index 012114164b..f5cc791282 100644 --- a/src/query/datalog/matcher.rs +++ b/src/query/datalog/matcher.rs @@ -1,4 +1,4 @@ -use super::types::{EdnValue, Pattern}; +use super::types::{AttributeSpec, EdnValue, Pattern}; use crate::graph::FactStorage; use crate::graph::types::{EntityId, Fact, Value}; use std::collections::HashMap; @@ -70,18 +70,26 @@ impl PatternMatcher { return None; } - // Match attribute - if !self.match_component( - &pattern.attribute, - &Value::Keyword(fact.attribute.clone()), - &mut bindings, - ) { - return None; - } - - // Match value - if !self.match_component(&pattern.value, &fact.value, &mut bindings) { - return None; + match &pattern.attribute { + AttributeSpec::Real(attr_edn) => { + // Match attribute + if !self.match_component( + attr_edn, + &Value::Keyword(fact.attribute.clone()), + &mut bindings, + ) { + return None; + } + // Match value + if !self.match_component(&pattern.value, &fact.value, &mut bindings) { + return None; + } + } + AttributeSpec::Pseudo(_) => { + // Full pseudo-attr binding implemented in Task 4. + // For now: skip attribute match, skip value match (returns empty bindings). + // This stub compiles but returns no results for pseudo-attr patterns. + } } Some(bindings) @@ -278,9 +286,15 @@ impl PatternMatcher { /// Apply existing bindings to a pattern, replacing bound variables with their values fn apply_bindings_to_pattern(&self, pattern: &Pattern, bindings: &Bindings) -> Pattern { + let attribute = match &pattern.attribute { + AttributeSpec::Real(edn) => { + AttributeSpec::Real(self.apply_binding_to_component(edn, bindings)) + } + AttributeSpec::Pseudo(p) => AttributeSpec::Pseudo(p.clone()), + }; Pattern { entity: self.apply_binding_to_component(&pattern.entity, bindings), - attribute: self.apply_binding_to_component(&pattern.attribute, bindings), + attribute, value: self.apply_binding_to_component(&pattern.value, bindings), valid_from: pattern.valid_from, valid_to: pattern.valid_to, diff --git a/src/query/datalog/optimizer.rs b/src/query/datalog/optimizer.rs index 7e1f6b786d..e3bbe16af2 100644 --- a/src/query/datalog/optimizer.rs +++ b/src/query/datalog/optimizer.rs @@ -3,7 +3,7 @@ //! `plan()` is the single entry point. It assigns an `IndexHint` to each //! pattern and (outside the `wasm` feature) sorts patterns by selectivity. -use crate::query::datalog::types::{EdnValue, Pattern}; +use crate::query::datalog::types::{AttributeSpec, EdnValue, Pattern}; /// Which covering index to use for a given pattern. #[derive(Debug, Clone, PartialEq, Eq)] @@ -28,12 +28,21 @@ fn is_entity_literal(v: &EdnValue) -> bool { matches!(v, EdnValue::Uuid(_)) } +/// Return true if the attribute is a bound (non-variable) real attribute. +/// Pseudo-attributes are never index-bound (they are not stored attributes). +fn attr_is_index_bound(a: &AttributeSpec) -> bool { + match a { + AttributeSpec::Real(edn) => !is_variable(edn), + AttributeSpec::Pseudo(_) => false, + } +} + /// Count the number of non-variable components in a pattern. /// Higher score = more selective. #[cfg(not(feature = "wasm"))] fn selectivity_score(p: &Pattern) -> u8 { let e = !is_variable(&p.entity); - let a = !is_variable(&p.attribute); + let a = attr_is_index_bound(&p.attribute); let v = !is_variable(&p.value); e as u8 + a as u8 + v as u8 } @@ -48,7 +57,7 @@ fn selectivity_score(p: &Pattern) -> u8 { /// Nothing bound → EAVT (full scan) pub fn select_index(p: &Pattern) -> IndexHint { let e_bound = !is_variable(&p.entity); - let a_bound = !is_variable(&p.attribute); + let a_bound = attr_is_index_bound(&p.attribute); let v_bound = !is_variable(&p.value); if e_bound { @@ -106,13 +115,7 @@ mod tests { use uuid::Uuid; fn make_pattern(entity: EdnValue, attribute: EdnValue, value: EdnValue) -> Pattern { - Pattern { - entity, - attribute, - value, - valid_from: None, - valid_to: None, - } + Pattern::new(entity, attribute, value) } fn var(s: &str) -> EdnValue { diff --git a/src/query/datalog/parser.rs b/src/query/datalog/parser.rs index c24dba07f0..208fdde577 100644 --- a/src/query/datalog/parser.rs +++ b/src/query/datalog/parser.rs @@ -1108,13 +1108,23 @@ fn outer_vars_from_clause(clause: &WhereClause) -> Vec { match clause { WhereClause::Pattern(p) => { let mut vars = Vec::new(); - for v in [&p.entity, &p.attribute, &p.value] { - if let Some(name) = v.as_variable() + if let Some(name) = p.entity.as_variable() + && !name.starts_with("?_") + { + vars.push(name.to_string()); + } + if let AttributeSpec::Real(attr_edn) = &p.attribute { + if let Some(name) = attr_edn.as_variable() && !name.starts_with("?_") { vars.push(name.to_string()); } } + if let Some(name) = p.value.as_variable() + && !name.starts_with("?_") + { + vars.push(name.to_string()); + } vars } WhereClause::RuleInvocation { args, .. } => args @@ -1473,7 +1483,7 @@ mod tests { assert_eq!(patterns.len(), 1); assert_eq!( patterns[0].attribute, - EdnValue::Keyword(":person/name".to_string()) + AttributeSpec::Real(EdnValue::Keyword(":person/name".to_string())) ); } _ => panic!("Expected Query command"), diff --git a/src/query/datalog/types.rs b/src/query/datalog/types.rs index 2cbfdd5b7a..6931bc8a62 100644 --- a/src/query/datalog/types.rs +++ b/src/query/datalog/types.rs @@ -194,6 +194,55 @@ impl FindSpec { } } +/// Built-in pseudo-attributes — reserved `:db/*` keywords that bind fact metadata +/// rather than stored attribute values. Never stored in the fact database. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum PseudoAttr { + ValidFrom, // :db/valid-from → Value::Integer(fact.valid_from) + ValidTo, // :db/valid-to → Value::Integer(fact.valid_to) + TxCount, // :db/tx-count → Value::Integer(fact.tx_count as i64) + TxId, // :db/tx-id → Value::Integer(fact.tx_id as i64) + ValidAt, // :db/valid-at → query-level constant (Value::Integer or Value::Null) +} + +impl PseudoAttr { + /// Returns `Some(variant)` if `k` is a reserved `:db/*` pseudo-attribute keyword. + pub fn from_keyword(k: &str) -> Option { + match k { + ":db/valid-from" => Some(PseudoAttr::ValidFrom), + ":db/valid-to" => Some(PseudoAttr::ValidTo), + ":db/tx-count" => Some(PseudoAttr::TxCount), + ":db/tx-id" => Some(PseudoAttr::TxId), + ":db/valid-at" => Some(PseudoAttr::ValidAt), + _ => None, + } + } + + /// Returns the canonical keyword string for this pseudo-attribute. + pub fn as_keyword(&self) -> &'static str { + match self { + PseudoAttr::ValidFrom => ":db/valid-from", + PseudoAttr::ValidTo => ":db/valid-to", + PseudoAttr::TxCount => ":db/tx-count", + PseudoAttr::TxId => ":db/tx-id", + PseudoAttr::ValidAt => ":db/valid-at", + } + } + + /// True for the four per-fact pseudo-attributes (all except `ValidAt`). + pub fn is_per_fact(&self) -> bool { + !matches!(self, PseudoAttr::ValidAt) + } +} + +/// Attribute position in a `Pattern` — either a real stored attribute keyword +/// or a built-in pseudo-attribute that binds fact metadata. +#[derive(Debug, Clone, PartialEq)] +pub enum AttributeSpec { + Real(EdnValue), + Pseudo(PseudoAttr), +} + /// A Datalog pattern: [Entity Attribute Value] /// Variables start with ?, constants are literal values /// @@ -204,7 +253,7 @@ impl FindSpec { #[derive(Debug, Clone, PartialEq)] pub struct Pattern { pub entity: EdnValue, - pub attribute: EdnValue, + pub attribute: AttributeSpec, pub value: EdnValue, /// Per-fact valid-time override (millis since epoch). None = use transaction-level default. pub valid_from: Option, @@ -216,7 +265,18 @@ impl Pattern { pub fn new(entity: EdnValue, attribute: EdnValue, value: EdnValue) -> Self { Pattern { entity, - attribute, + attribute: AttributeSpec::Real(attribute), + value, + valid_from: None, + valid_to: None, + } + } + + /// Create a pattern with a pseudo-attribute. + pub fn pseudo(entity: EdnValue, pseudo: PseudoAttr, value: EdnValue) -> Self { + Pattern { + entity, + attribute: AttributeSpec::Pseudo(pseudo), value, valid_from: None, valid_to: None, @@ -233,7 +293,7 @@ impl Pattern { ) -> Self { Pattern { entity, - attribute, + attribute: AttributeSpec::Real(attribute), value, valid_from, valid_to, @@ -251,7 +311,7 @@ impl Pattern { Ok(Pattern { entity: vector[0].clone(), - attribute: vector[1].clone(), + attribute: AttributeSpec::Real(vector[1].clone()), value: vector[2].clone(), valid_from: None, valid_to: None, @@ -580,7 +640,7 @@ mod tests { ); assert!(pattern.entity.is_variable()); - assert!(pattern.attribute.is_keyword()); + assert!(matches!(pattern.attribute, AttributeSpec::Real(EdnValue::Keyword(_)))); } #[test] @@ -595,7 +655,7 @@ mod tests { assert_eq!(pattern.entity, EdnValue::Symbol("?e".to_string())); assert_eq!( pattern.attribute, - EdnValue::Keyword(":person/name".to_string()) + AttributeSpec::Real(EdnValue::Keyword(":person/name".to_string())) ); assert_eq!(pattern.value, EdnValue::String("Alice".to_string())); } @@ -1077,4 +1137,79 @@ mod tests { assert!(pred_names.contains(&"active")); assert!(pred_names.contains(&"pending")); } + + #[test] + fn test_pseudo_attr_from_keyword_known() { + assert!(matches!( + PseudoAttr::from_keyword(":db/valid-from"), + Some(PseudoAttr::ValidFrom) + )); + assert!(matches!( + PseudoAttr::from_keyword(":db/valid-to"), + Some(PseudoAttr::ValidTo) + )); + assert!(matches!( + PseudoAttr::from_keyword(":db/tx-count"), + Some(PseudoAttr::TxCount) + )); + assert!(matches!( + PseudoAttr::from_keyword(":db/tx-id"), + Some(PseudoAttr::TxId) + )); + assert!(matches!( + PseudoAttr::from_keyword(":db/valid-at"), + Some(PseudoAttr::ValidAt) + )); + } + + #[test] + fn test_pseudo_attr_from_keyword_unknown() { + assert!(PseudoAttr::from_keyword(":person/name").is_none()); + assert!(PseudoAttr::from_keyword(":db/other").is_none()); + assert!(PseudoAttr::from_keyword("").is_none()); + } + + #[test] + fn test_pseudo_attr_is_per_fact() { + assert!(PseudoAttr::ValidFrom.is_per_fact()); + assert!(PseudoAttr::ValidTo.is_per_fact()); + assert!(PseudoAttr::TxCount.is_per_fact()); + assert!(PseudoAttr::TxId.is_per_fact()); + assert!(!PseudoAttr::ValidAt.is_per_fact()); + } + + #[test] + fn test_attribute_spec_real_variant() { + let spec = AttributeSpec::Real(EdnValue::Keyword(":person/name".to_string())); + assert!(matches!(spec, AttributeSpec::Real(_))); + } + + #[test] + fn test_attribute_spec_pseudo_variant() { + let spec = AttributeSpec::Pseudo(PseudoAttr::ValidFrom); + assert!(matches!(spec, AttributeSpec::Pseudo(PseudoAttr::ValidFrom))); + } + + #[test] + fn test_pattern_new_wraps_real() { + let p = Pattern::new( + EdnValue::Symbol("?e".to_string()), + EdnValue::Keyword(":person/name".to_string()), + EdnValue::Symbol("?n".to_string()), + ); + assert!(matches!(p.attribute, AttributeSpec::Real(_))); + } + + #[test] + fn test_pattern_pseudo_wraps_pseudo() { + let p = Pattern::pseudo( + EdnValue::Symbol("?e".to_string()), + PseudoAttr::ValidFrom, + EdnValue::Symbol("?vf".to_string()), + ); + assert!(matches!( + p.attribute, + AttributeSpec::Pseudo(PseudoAttr::ValidFrom) + )); + } } From b1171c6da0c656b140de4dda60b28a0303109bd8 Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Tue, 31 Mar 2026 20:02:52 +0530 Subject: [PATCH 02/14] fix: add Pattern::real constructor and as_keyword test per spec Co-Authored-By: Claude Sonnet 4.6 --- src/query/datalog/types.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/query/datalog/types.rs b/src/query/datalog/types.rs index 6931bc8a62..e9d6579510 100644 --- a/src/query/datalog/types.rs +++ b/src/query/datalog/types.rs @@ -283,6 +283,17 @@ impl Pattern { } } + /// Create a pattern with a real (stored) attribute. + pub fn real(entity: EdnValue, attribute: EdnValue, value: EdnValue) -> Self { + Pattern { + entity, + attribute: AttributeSpec::Real(attribute), + value, + valid_from: None, + valid_to: None, + } + } + /// Create a pattern with explicit per-fact valid-time overrides. pub fn with_valid_time( entity: EdnValue, @@ -1212,4 +1223,13 @@ mod tests { AttributeSpec::Pseudo(PseudoAttr::ValidFrom) )); } + + #[test] + fn test_pseudo_attr_as_keyword() { + assert_eq!(PseudoAttr::ValidFrom.as_keyword(), ":db/valid-from"); + assert_eq!(PseudoAttr::ValidTo.as_keyword(), ":db/valid-to"); + assert_eq!(PseudoAttr::TxCount.as_keyword(), ":db/tx-count"); + assert_eq!(PseudoAttr::TxId.as_keyword(), ":db/tx-id"); + assert_eq!(PseudoAttr::ValidAt.as_keyword(), ":db/valid-at"); + } } From 95cc309f083012023de11892ed7778f400feacbf Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Tue, 31 Mar 2026 20:15:23 +0530 Subject: [PATCH 03/14] fix: remove unused EdnValue import, add Pattern::real test, fix clippy collapsible-if Co-Authored-By: Claude Sonnet 4.6 --- src/db.rs | 2 +- src/query/datalog/parser.rs | 11 +++++------ src/query/datalog/types.rs | 13 +++++++++++++ 3 files changed, 19 insertions(+), 7 deletions(-) diff --git a/src/db.rs b/src/db.rs index f36736731b..b617289821 100644 --- a/src/db.rs +++ b/src/db.rs @@ -20,7 +20,7 @@ use crate::query::datalog::executor::DatalogExecutor; use crate::query::datalog::executor::QueryResult; use crate::query::datalog::parser::parse_datalog_command; use crate::query::datalog::rules::RuleRegistry; -use crate::query::datalog::types::{AttributeSpec, DatalogCommand, EdnValue, Transaction}; +use crate::query::datalog::types::{AttributeSpec, DatalogCommand, Transaction}; use crate::storage::backend::MemoryBackend; use crate::storage::backend::file::FileBackend; use crate::storage::persistent_facts::PersistentFactStorage; diff --git a/src/query/datalog/parser.rs b/src/query/datalog/parser.rs index 208fdde577..0c6259d856 100644 --- a/src/query/datalog/parser.rs +++ b/src/query/datalog/parser.rs @@ -1113,12 +1113,11 @@ fn outer_vars_from_clause(clause: &WhereClause) -> Vec { { vars.push(name.to_string()); } - if let AttributeSpec::Real(attr_edn) = &p.attribute { - if let Some(name) = attr_edn.as_variable() - && !name.starts_with("?_") - { - vars.push(name.to_string()); - } + if let AttributeSpec::Real(attr_edn) = &p.attribute + && let Some(name) = attr_edn.as_variable() + && !name.starts_with("?_") + { + vars.push(name.to_string()); } if let Some(name) = p.value.as_variable() && !name.starts_with("?_") diff --git a/src/query/datalog/types.rs b/src/query/datalog/types.rs index e9d6579510..fd2643020a 100644 --- a/src/query/datalog/types.rs +++ b/src/query/datalog/types.rs @@ -1211,6 +1211,19 @@ mod tests { assert!(matches!(p.attribute, AttributeSpec::Real(_))); } + #[test] + fn test_pattern_real_constructor() { + let p = Pattern::real( + EdnValue::Keyword("alice".to_string()), + EdnValue::Keyword("person/name".to_string()), + EdnValue::String("Alice".to_string()), + ); + assert!( + matches!(p.attribute, AttributeSpec::Real(_)), + "Pattern::real should wrap attribute in AttributeSpec::Real" + ); + } + #[test] fn test_pattern_pseudo_wraps_pseudo() { let p = Pattern::pseudo( From 00bac7536797e08b5f22ea24a4248078207190f2 Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Tue, 31 Mar 2026 20:26:13 +0530 Subject: [PATCH 04/14] test: add failing Phase 7.6 temporal metadata integration tests Co-Authored-By: Claude Sonnet 4.6 --- tests/temporal_metadata_test.rs | 307 ++++++++++++++++++++++++++++++++ 1 file changed, 307 insertions(+) create mode 100644 tests/temporal_metadata_test.rs diff --git a/tests/temporal_metadata_test.rs b/tests/temporal_metadata_test.rs new file mode 100644 index 0000000000..286237ca4e --- /dev/null +++ b/tests/temporal_metadata_test.rs @@ -0,0 +1,307 @@ +//! Phase 7.6 integration tests — temporal metadata pseudo-attribute bindings. + +use minigraf::{Minigraf, OpenOptions, QueryResult, Value}; + +fn db() -> Minigraf { + OpenOptions::new().open_memory().unwrap() +} + +fn results(r: &QueryResult) -> &Vec> { + match r { + QueryResult::QueryResults { results, .. } => results, + _ => panic!("expected QueryResults"), + } +} + +// ─── Time Interval Tests ───────────────────────────────────────────────────── + +/// Time Interval — find facts alive at any point during interval [T1, T2]. +/// Condition: valid_from <= T2 AND valid_to >= T1. +/// "2023-01-01" = 1672531200000 ms, "2024-01-01" = 1704067200000 ms. +#[test] +fn time_interval_any_point_during() { + let db = db(); + // e1: valid 2022-01-01 to 2023-07-01 → overlaps [2023-01-01, 2024-01-01] + db.execute(r#"(transact {:valid-from "2022-01-01" :valid-to "2023-07-01"} [[:e1 :item/label "A"]])"#).unwrap(); + // e2: valid 2023-07-01 onwards → overlaps [2023-01-01, 2024-01-01] + db.execute(r#"(transact {:valid-from "2023-07-01"} [[:e2 :item/label "B"]])"#).unwrap(); + // e3: valid 2015-01-01 to 2020-01-01 → does NOT overlap [2023-01-01, 2024-01-01] + db.execute(r#"(transact {:valid-from "2015-01-01" :valid-to "2020-01-01"} [[:e3 :item/label "C"]])"#).unwrap(); + + // T1 = 2023-01-01 = 1672531200000, T2 = 2024-01-01 = 1704067200000 + let r = db.execute(r#" + (query [:find ?e + :any-valid-time + :where [?e :item/label _] + [?e :db/valid-from ?vf] + [?e :db/valid-to ?vt] + [(<= ?vf 1704067200000)] + [(>= ?vt 1672531200000)]]) + "#).unwrap(); + let rows = results(&r); + assert_eq!(rows.len(), 2, "e1 and e2 overlap [2023, 2024]; e3 does not"); +} + +/// Time Interval (strict) — facts alive for the *entire* interval [T1, T2]. +/// Condition: valid_from <= T1 AND valid_to >= T2. +#[test] +fn time_interval_entire_interval() { + let db = db(); + // e1: valid 2020-01-01 to 2025-01-01 → covers entire [2023-01-01, 2024-01-01] + db.execute(r#"(transact {:valid-from "2020-01-01" :valid-to "2025-01-01"} [[:e1 :item/label "A"]])"#).unwrap(); + // e2: valid 2023-07-01 onwards → does NOT cover T1 = 2023-01-01 + db.execute(r#"(transact {:valid-from "2023-07-01"} [[:e2 :item/label "B"]])"#).unwrap(); + + // T1 = 1672531200000, T2 = 1704067200000 + let r = db.execute(r#" + (query [:find ?e + :any-valid-time + :where [?e :item/label _] + [?e :db/valid-from ?vf] + [?e :db/valid-to ?vt] + [(<= ?vf 1672531200000)] + [(>= ?vt 1704067200000)]]) + "#).unwrap(); + let rows = results(&r); + assert_eq!(rows.len(), 1, "only e1 covers the entire interval"); +} + +// ─── Time-Point Lookup ─────────────────────────────────────────────────────── + +/// Time-Point Lookup — find all valid_from timestamps when Alice's salary exceeded 50000. +#[test] +fn time_point_lookup_salary_threshold() { + let db = db(); + // salary 100000, valid 2023-01-01 to 2024-01-01 + db.execute(r#"(transact {:valid-from "2023-01-01" :valid-to "2024-01-01"} [[:alice :person/salary 100000]])"#).unwrap(); + // salary 30000, valid 2024-01-01 onwards + db.execute(r#"(transact {:valid-from "2024-01-01"} [[:alice :person/salary 30000]])"#).unwrap(); + + let r = db.execute(r#" + (query [:find ?vf + :any-valid-time + :where [:alice :person/salary ?s] + [:alice :db/valid-from ?vf] + [(> ?s 50000)]]) + "#).unwrap(); + let rows = results(&r); + assert_eq!(rows.len(), 1, "only the 2023 salary entry exceeds 50000"); + assert_eq!(rows[0][0], Value::Integer(1672531200000), "valid-from = 2023-01-01"); +} + +// ─── Time-Interval Lookup ──────────────────────────────────────────────────── + +/// Time-Interval Lookup — enumerate all validity intervals for Alice's employment status. +#[test] +fn time_interval_lookup_employment_status() { + let db = db(); + db.execute(r#"(transact {:valid-from "2022-01-01" :valid-to "2023-01-01"} [[:alice :employment/status :probation]])"#).unwrap(); + db.execute(r#"(transact {:valid-from "2023-01-01" :valid-to "2025-01-01"} [[:alice :employment/status :permanent]])"#).unwrap(); + + let r = db.execute(r#" + (query [:find ?vf ?vt + :any-valid-time + :where [:alice :employment/status _] + [:alice :db/valid-from ?vf] + [:alice :db/valid-to ?vt]]) + "#).unwrap(); + let rows = results(&r); + assert_eq!(rows.len(), 2, "two distinct employment intervals"); +} + +// ─── Tx-time Correlation ───────────────────────────────────────────────────── + +/// Bind :db/tx-count and verify it matches :as-of counter semantics. +#[test] +fn tx_count_binding() { + let db = db(); + db.execute(r#"(transact [[:alice :person/name "Alice"]])"#).unwrap(); // tx_count = 1 + db.execute(r#"(transact [[:bob :person/name "Bob"]])"#).unwrap(); // tx_count = 2 + + // Query with :any-valid-time: bind tx_count for all name facts + let r = db.execute(r#" + (query [:find ?e ?tc + :any-valid-time + :where [?e :person/name _] + [?e :db/tx-count ?tc]]) + "#).unwrap(); + let rows = results(&r); + assert_eq!(rows.len(), 2); + + // The tx_counts must be 1 and 2 (in any order) + let mut counts: Vec = rows.iter() + .map(|r| match r[1] { Value::Integer(n) => n, _ => panic!("expected Integer") }) + .collect(); + counts.sort(); + assert_eq!(counts, vec![1, 2]); +} + +/// Bind :db/tx-id across two entities written in the same transaction — same tx-id. +#[test] +fn tx_id_same_transaction_join() { + let db = db(); + // Alice and Bob written in the same transaction → same tx_id + db.execute(r#"(transact [[:alice :person/name "Alice"] [:bob :person/name "Bob"]])"#).unwrap(); + + let r = db.execute(r#" + (query [:find ?e1 ?e2 + :any-valid-time + :where [?e1 :person/name _] + [?e2 :person/name _] + [?e1 :db/tx-id ?tx] + [?e2 :db/tx-id ?tx]]) + "#).unwrap(); + let rows = results(&r); + // Both share the same tx-id: (alice, alice), (alice, bob), (bob, alice), (bob, bob) + assert_eq!(rows.len(), 4, "cross-join of 2 entities with same tx-id = 4 rows"); +} + +// ─── :db/valid-at Tests ────────────────────────────────────────────────────── + +/// :db/valid-at binds the effective query timestamp when :valid-at is explicit. +#[test] +fn valid_at_explicit_timestamp() { + let db = db(); + db.execute(r#"(transact [[:alice :person/name "Alice"]])"#).unwrap(); + + // 2023-01-01 = 1672531200000 + let r = db.execute(r#" + (query [:find ?vat + :valid-at "2023-01-01" + :where [:alice :person/name _] + [:alice :db/valid-at ?vat]]) + "#).unwrap(); + let rows = results(&r); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0][0], Value::Integer(1672531200000)); +} + +/// :db/valid-at binds the current time when no :valid-at is specified. +#[test] +fn valid_at_default_is_now() { + let db = db(); + db.execute(r#"(transact [[:alice :person/name "Alice"]])"#).unwrap(); + + let r = db.execute(r#" + (query [:find ?vat + :where [:alice :person/name _] + [:alice :db/valid-at ?vat]]) + "#).unwrap(); + let rows = results(&r); + assert_eq!(rows.len(), 1); + // The value should be a positive ms timestamp (approximately now) + match rows[0][0] { + Value::Integer(n) => assert!(n > 0, "valid-at default should be a positive timestamp"), + _ => panic!("expected Integer for :db/valid-at default"), + } +} + +/// :db/valid-at binds Value::Null when :any-valid-time is used. +#[test] +fn valid_at_any_valid_time_is_null() { + let db = db(); + db.execute(r#"(transact [[:alice :person/name "Alice"]])"#).unwrap(); + + let r = db.execute(r#" + (query [:find ?vat + :any-valid-time + :where [:alice :person/name _] + [:alice :db/valid-at ?vat]]) + "#).unwrap(); + let rows = results(&r); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0][0], Value::Null); +} + +// ─── Parse-error Tests ─────────────────────────────────────────────────────── + +/// :db/* in entity position is a parse error. +#[test] +fn parse_error_pseudo_attr_in_entity_position() { + let db = db(); + let result = db.execute(r#" + (query [:find ?v + :any-valid-time + :where [:db/valid-from :person/name ?v]]) + "#); + assert!(result.is_err(), "pseudo-attribute in entity position must be a parse error"); +} + +/// :db/* in value position is a parse error. +#[test] +fn parse_error_pseudo_attr_in_value_position() { + let db = db(); + let result = db.execute(r#" + (query [:find ?e + :any-valid-time + :where [?e :person/name :db/valid-from]]) + "#); + assert!(result.is_err(), "pseudo-attribute in value position must be a parse error"); +} + +// ─── Runtime Hard-error Tests ──────────────────────────────────────────────── + +/// :db/valid-from without :any-valid-time is a runtime error. +#[test] +fn runtime_error_valid_from_without_any_valid_time() { + let db = db(); + db.execute(r#"(transact [[:alice :person/name "Alice"]])"#).unwrap(); + let result = db.execute(r#" + (query [:find ?vf + :where [:alice :person/name _] + [:alice :db/valid-from ?vf]]) + "#); + assert!(result.is_err(), ":db/valid-from requires :any-valid-time"); +} + +/// :db/valid-to without :any-valid-time is a runtime error. +#[test] +fn runtime_error_valid_to_without_any_valid_time() { + let db = db(); + db.execute(r#"(transact [[:alice :person/name "Alice"]])"#).unwrap(); + let result = db.execute(r#" + (query [:find ?vt + :where [:alice :person/name _] + [:alice :db/valid-to ?vt]]) + "#); + assert!(result.is_err(), ":db/valid-to requires :any-valid-time"); +} + +/// :db/tx-count without :any-valid-time is a runtime error. +#[test] +fn runtime_error_tx_count_without_any_valid_time() { + let db = db(); + db.execute(r#"(transact [[:alice :person/name "Alice"]])"#).unwrap(); + let result = db.execute(r#" + (query [:find ?tc + :where [:alice :person/name _] + [:alice :db/tx-count ?tc]]) + "#); + assert!(result.is_err(), ":db/tx-count requires :any-valid-time"); +} + +/// :db/tx-id without :any-valid-time is a runtime error. +#[test] +fn runtime_error_tx_id_without_any_valid_time() { + let db = db(); + db.execute(r#"(transact [[:alice :person/name "Alice"]])"#).unwrap(); + let result = db.execute(r#" + (query [:find ?ti + :where [:alice :person/name _] + [:alice :db/tx-id ?ti]]) + "#); + assert!(result.is_err(), ":db/tx-id requires :any-valid-time"); +} + +/// :db/valid-at without :any-valid-time succeeds (no restriction on valid-at). +#[test] +fn valid_at_succeeds_without_any_valid_time() { + let db = db(); + db.execute(r#"(transact [[:alice :person/name "Alice"]])"#).unwrap(); + let result = db.execute(r#" + (query [:find ?vat + :where [:alice :person/name _] + [:alice :db/valid-at ?vat]]) + "#); + assert!(result.is_ok(), ":db/valid-at must not require :any-valid-time"); +} From acc1c910e5a97a286f0628a3b17a97cbe5e1f94a Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Tue, 31 Mar 2026 20:36:04 +0530 Subject: [PATCH 05/14] =?UTF-8?q?feat:=20parser=20=E2=80=94=20detect=20pse?= =?UTF-8?q?udo-attributes=20in=20query=20where-clause=20patterns?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 4.6 --- src/query/datalog/parser.rs | 86 ++++++++++++++++++++++++++++++++++--- 1 file changed, 81 insertions(+), 5 deletions(-) diff --git a/src/query/datalog/parser.rs b/src/query/datalog/parser.rs index 0c6259d856..5e364b42e6 100644 --- a/src/query/datalog/parser.rs +++ b/src/query/datalog/parser.rs @@ -568,7 +568,7 @@ fn parse_query(elements: &[EdnValue]) -> Result { let clause = parse_expr_clause(pattern_vec)?; where_clauses.push(clause); } else { - let pattern = Pattern::from_edn(pattern_vec)?; + let pattern = parse_query_pattern(pattern_vec)?; where_clauses.push(WhereClause::Pattern(pattern)); } } else if let Some(rule_list) = query_vector[i].as_list() { @@ -913,7 +913,7 @@ fn parse_list_as_where_clause(list: &[EdnValue], allow_not: bool) -> Result Result Result Result { + if vec.len() != 3 { + return Err(format!( + "Pattern must have exactly 3 elements (E A V), got {}", + vec.len() + )); + } + + // Reject :db/* in entity position + if let EdnValue::Keyword(k) = &vec[0] { + if PseudoAttr::from_keyword(k).is_some() { + return Err(format!( + "pseudo-attribute {} is not valid in entity position", + k + )); + } + } + + // Reject :db/* in value position + if let EdnValue::Keyword(k) = &vec[2] { + if PseudoAttr::from_keyword(k).is_some() { + return Err(format!( + "pseudo-attribute {} is not valid in value position", + k + )); + } + } + + // Detect pseudo-attribute in attribute position + if let EdnValue::Keyword(k) = &vec[1] { + if let Some(pseudo) = PseudoAttr::from_keyword(k) { + return Ok(Pattern::pseudo(vec[0].clone(), pseudo, vec[2].clone())); + } + } + + Pattern::from_edn(vec) +} + /// - A single clause: `[pattern]` or `(rule-invocation)` or `[(expr)]` /// - A grouped list of clauses: `(and clause1 clause2 ...)` fn parse_or_branch(item: &EdnValue) -> Result, String> { @@ -1092,7 +1135,7 @@ fn parse_or_branch_item(item: &EdnValue) -> Result { if matches!(vec.first(), Some(EdnValue::List(_))) { parse_expr_clause(vec) } else { - Ok(WhereClause::Pattern(Pattern::from_edn(vec)?)) + Ok(WhereClause::Pattern(parse_query_pattern(vec)?)) } } EdnValue::List(inner_list) => { @@ -1362,7 +1405,7 @@ fn parse_rule(elements: &[EdnValue]) -> Result { let clause = parse_expr_clause(vec)?; body_clauses.push(clause); } else { - let pattern = Pattern::from_edn(vec)?; + let pattern = parse_query_pattern(vec)?; body_clauses.push(WhereClause::Pattern(pattern)); } } else if let Some(list) = item.as_list() { @@ -2325,6 +2368,39 @@ mod tests { _ => panic!(), } } + + #[test] + fn test_parse_pseudo_attr_in_where_clause() { + let cmd = parse_datalog_command( + "(query [:find ?vf :any-valid-time :where [?e :person/name _] [?e :db/valid-from ?vf]])" + ).unwrap(); + match cmd { + DatalogCommand::Query(q) => { + let patterns = q.get_patterns(); + assert!( + patterns.iter().any(|p| matches!(p.attribute, AttributeSpec::Pseudo(_))), + "expected a Pseudo attribute pattern" + ); + } + _ => panic!("expected Query"), + } + } + + #[test] + fn test_parse_error_pseudo_attr_entity_position() { + let result = parse_datalog_command( + "(query [:find ?v :any-valid-time :where [:db/valid-from :person/name ?v]])" + ); + assert!(result.is_err(), "pseudo-attr in entity position should error"); + } + + #[test] + fn test_parse_error_pseudo_attr_value_position() { + let result = parse_datalog_command( + "(query [:find ?e :any-valid-time :where [?e :person/name :db/valid-from]])" + ); + assert!(result.is_err(), "pseudo-attr in value position should error"); + } } #[cfg(test)] From 7bd9304e8487a914c7581dc85f5114c7192d6538 Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Tue, 31 Mar 2026 20:39:36 +0530 Subject: [PATCH 06/14] fix: restore parse_or_branch doc comment split by parse_query_pattern insertion --- src/query/datalog/parser.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/query/datalog/parser.rs b/src/query/datalog/parser.rs index 5e364b42e6..149fab4f65 100644 --- a/src/query/datalog/parser.rs +++ b/src/query/datalog/parser.rs @@ -1059,9 +1059,6 @@ fn parse_list_as_where_clause(list: &[EdnValue], allow_not: bool) -> Result Result { Pattern::from_edn(vec) } +/// Parse a single branch of an (or ...) or (or-join ...) clause. +/// +/// A branch is either: /// - A single clause: `[pattern]` or `(rule-invocation)` or `[(expr)]` /// - A grouped list of clauses: `(and clause1 clause2 ...)` fn parse_or_branch(item: &EdnValue) -> Result, String> { From 24223edd8cff52e876007133344f7d9e1a925b35 Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Tue, 31 Mar 2026 21:19:51 +0530 Subject: [PATCH 07/14] =?UTF-8?q?feat:=20matcher=20=E2=80=94=20bind=20pseu?= =?UTF-8?q?do-attr=20fields=20from=20fact=20metadata?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add `valid_at_value` field and `from_slice_with_valid_at` constructor - Store hidden `__f*` fact-metadata keys on real-attr pattern matches so pseudo-attr patterns can read per-fact temporal/tx fields without cross-joining against every other fact for the same entity - Handle anonymous wildcard `_` in match_component - Fix parser: treat bare `:any-valid-time` as shorthand for `:valid-at :any-valid-time` (was silently ignored) Co-Authored-By: Claude Sonnet 4.6 --- src/query/datalog/matcher.rs | 163 +++++++++++++++++++++++++++++++++-- src/query/datalog/parser.rs | 7 ++ 2 files changed, 163 insertions(+), 7 deletions(-) diff --git a/src/query/datalog/matcher.rs b/src/query/datalog/matcher.rs index f5cc791282..659988ebce 100644 --- a/src/query/datalog/matcher.rs +++ b/src/query/datalog/matcher.rs @@ -1,4 +1,4 @@ -use super::types::{AttributeSpec, EdnValue, Pattern}; +use super::types::{AttributeSpec, EdnValue, Pattern, PseudoAttr}; use crate::graph::FactStorage; use crate::graph::types::{EntityId, Fact, Value}; use std::collections::HashMap; @@ -17,12 +17,15 @@ enum MatcherStorage { /// Pattern matcher that finds facts matching a pattern and produces bindings pub struct PatternMatcher { storage: MatcherStorage, + /// The `:db/valid-at` value for this query context (Value::Null when not set). + pub(crate) valid_at_value: Value, } impl PatternMatcher { pub fn new(storage: FactStorage) -> Self { PatternMatcher { storage: MatcherStorage::Owned(storage), + valid_at_value: Value::Null, } } @@ -33,6 +36,16 @@ impl PatternMatcher { pub(crate) fn from_slice(facts: Arc<[Fact]>) -> Self { PatternMatcher { storage: MatcherStorage::Slice(facts), + valid_at_value: Value::Null, + } + } + + /// Constructs a matcher with an explicit `:db/valid-at` binding value. + /// Used by the executor when the query has a known `valid_at` point. + pub(crate) fn from_slice_with_valid_at(facts: Arc<[Fact]>, valid_at: Value) -> Self { + PatternMatcher { + storage: MatcherStorage::Slice(facts), + valid_at_value: valid_at, } } @@ -84,11 +97,31 @@ impl PatternMatcher { if !self.match_component(&pattern.value, &fact.value, &mut bindings) { return None; } + // Store hidden fact-metadata keys so that subsequent pseudo-attr patterns + // for the same entity can read per-fact temporal/tx metadata without + // cross-joining against every other fact for the entity. + // Keys are prefixed with `__f` and namespaced by entity UUID to avoid + // collisions across entities. They are never referenced in :find, so they + // are silently filtered out during result extraction. + let eid = fact.entity.to_string(); + bindings.insert(format!("__fvf_{}", eid), Value::Integer(fact.valid_from)); + bindings.insert(format!("__fvt_{}", eid), Value::Integer(fact.valid_to)); + bindings.insert(format!("__ftc_{}", eid), Value::Integer(fact.tx_count as i64)); + bindings.insert(format!("__fti_{}", eid), Value::Integer(fact.tx_id as i64)); } - AttributeSpec::Pseudo(_) => { - // Full pseudo-attr binding implemented in Task 4. - // For now: skip attribute match, skip value match (returns empty bindings). - // This stub compiles but returns no results for pseudo-attr patterns. + AttributeSpec::Pseudo(pseudo) => { + // Pseudo-attribute: skip stored attribute match; bind fact metadata + // field to the value position variable (or match against a constant). + let pseudo_value = match pseudo { + PseudoAttr::ValidFrom => Value::Integer(fact.valid_from), + PseudoAttr::ValidTo => Value::Integer(fact.valid_to), + PseudoAttr::TxCount => Value::Integer(fact.tx_count as i64), + PseudoAttr::TxId => Value::Integer(fact.tx_id as i64), + PseudoAttr::ValidAt => self.valid_at_value.clone(), + }; + if !self.match_component(&pattern.value, &pseudo_value, &mut bindings) { + return None; + } } } @@ -104,6 +137,9 @@ impl PatternMatcher { bindings: &mut Bindings, ) -> bool { match pattern_component { + // Anonymous wildcard `_`: match any value without binding + EdnValue::Symbol(var) if var == "_" => true, + // Wildcard variable (starts with ?_): match any value without binding EdnValue::Symbol(var) if var.starts_with("?_") => true, @@ -250,6 +286,54 @@ impl PatternMatcher { /// Match a pattern given existing variable bindings /// Returns new bindings that extend the existing ones fn match_pattern_with_bindings(&self, pattern: &Pattern, existing: &Bindings) -> Vec { + // Fast path for pseudo-attr patterns: when a preceding real-attr pattern stored + // hidden fact-metadata keys (e.g. `__fvf_`), use them directly instead of + // scanning all facts and cross-joining. This ensures pseudo-attr patterns are + // correlated with the specific fact matched by the preceding real-attr pattern. + if let AttributeSpec::Pseudo(pseudo) = &pattern.attribute { + // Resolve the entity component to a UUID using existing bindings + let resolved_entity = self.apply_binding_to_component(&pattern.entity, existing); + let entity_uuid_opt: Option = match &resolved_entity { + EdnValue::Uuid(u) => Some(*u), + EdnValue::Keyword(k) => { + edn_to_entity_id(&EdnValue::Keyword(k.clone())).ok() + } + _ => None, + }; + if let Some(uuid) = entity_uuid_opt { + let eid = uuid.to_string(); + let hidden_key = match pseudo { + PseudoAttr::ValidFrom => format!("__fvf_{}", eid), + PseudoAttr::ValidTo => format!("__fvt_{}", eid), + PseudoAttr::TxCount => format!("__ftc_{}", eid), + PseudoAttr::TxId => format!("__fti_{}", eid), + // ValidAt is a query-level constant (not per-fact); fall through to + // the normal scan path so each fact produces one binding (all + // identical). Task 5 (executor) will inject the correct value. + PseudoAttr::ValidAt => { + return self.match_pattern_with_bindings_scan(pattern, existing); + } + }; + if let Some(stored_value) = existing.get(&hidden_key) { + let mut new_bindings = existing.clone(); + if self.match_component(&pattern.value, stored_value, &mut new_bindings) { + return vec![new_bindings]; + } + return vec![]; + } + } + } + + // Default: scan all facts + self.match_pattern_with_bindings_scan(pattern, existing) + } + + /// Default join implementation: iterate all facts and try to match. + fn match_pattern_with_bindings_scan( + &self, + pattern: &Pattern, + existing: &Bindings, + ) -> Vec { let mut results = Vec::new(); let facts = self.get_facts(); @@ -264,9 +348,15 @@ impl PatternMatcher { if let Some(additional_bindings) = self.match_fact_against_pattern(&fact, &resolved_pattern) { - // Check that additional bindings are consistent with existing + // Check that additional bindings are consistent with existing. + // Hidden fact-metadata keys (prefixed `__f`) are always overwritten + // and are excluded from the consistency check. let mut consistent = true; for (var, val) in &additional_bindings { + if var.starts_with("__f") { + // Hidden metadata keys: always overwrite, never conflict-check. + continue; + } if matches!(existing.get(var), Some(existing_val) if existing_val != val) { consistent = false; break; @@ -274,7 +364,7 @@ impl PatternMatcher { } if consistent { - // Merge bindings + // Merge bindings (hidden keys are overwritten by the new fact's values) new_bindings.extend(additional_bindings); results.push(new_bindings); } @@ -376,6 +466,15 @@ pub fn edn_to_entity_id(edn: &EdnValue) -> Result { mod tests { use super::*; + #[test] + fn test_from_slice_with_valid_at_field() { + use std::sync::Arc; + use crate::graph::types::Value; + let facts: Arc<[_]> = Arc::from(vec![]); + let m = PatternMatcher::from_slice_with_valid_at(facts, Value::Integer(12345)); + assert_eq!(m.valid_at_value, Value::Integer(12345)); + } + #[test] fn test_match_simple_pattern() { let storage = FactStorage::new(); @@ -762,4 +861,54 @@ mod tests { "from_slice does not filter internally — raw slice passes through unchanged" ); } + + #[test] + fn test_pseudo_attr_valid_from_join() { + // Simulates the time_interval_entire_interval test pattern: + // [?e :item/label _] [?e :db/valid-from ?vf] + use crate::graph::types::{Fact, Value}; + use crate::graph::storage::net_asserted_facts; + use crate::query::datalog::types::{AttributeSpec, PseudoAttr}; + use uuid::Uuid; + + let storage = crate::graph::FactStorage::new(); + let e1 = Uuid::new_v4(); + + // Transact e1 with explicit valid-from = 1577836800000 + let opt = crate::graph::types::TransactOptions::new( + Some(1577836800000), + Some(1735689600000), + ); + storage.transact_batch( + vec![(e1, ":item/label".to_string(), Value::String("A".to_string()), None)], + Some(opt), + ).unwrap(); + + // Get all facts + let all_facts: Arc<[Fact]> = Arc::from(net_asserted_facts(storage.get_all_facts().unwrap())); + let matcher = PatternMatcher::from_slice(all_facts.clone()); + + // First pattern: [?e :item/label _] + let p1 = Pattern { + entity: EdnValue::Symbol("?e".to_string()), + attribute: AttributeSpec::Real(EdnValue::Keyword(":item/label".to_string())), + value: EdnValue::Symbol("_".to_string()), + valid_from: None, + valid_to: None, + }; + let r1 = matcher.match_pattern(&p1); + assert_eq!(r1.len(), 1, "first pattern should bind ?e"); + + // Second pattern: [?e :db/valid-from ?vf] + let p2 = Pattern { + entity: EdnValue::Symbol("?e".to_string()), + attribute: AttributeSpec::Pseudo(PseudoAttr::ValidFrom), + value: EdnValue::Symbol("?vf".to_string()), + valid_from: None, + valid_to: None, + }; + let r2 = matcher.match_patterns_seeded(&[p2], r1); + assert_eq!(r2.len(), 1, "second pattern should bind ?vf"); + assert_eq!(r2[0].get("?vf"), Some(&Value::Integer(1577836800000))); + } } diff --git a/src/query/datalog/parser.rs b/src/query/datalog/parser.rs index 149fab4f65..6e504886c9 100644 --- a/src/query/datalog/parser.rs +++ b/src/query/datalog/parser.rs @@ -517,6 +517,13 @@ fn parse_query(elements: &[EdnValue]) -> Result { i += 1; continue; } + ":any-valid-time" => { + // Shorthand for `:valid-at :any-valid-time`; disables automatic + // valid-time filtering so pseudo-attribute patterns are accessible. + query_valid_at = Some(ValidAt::AnyValidTime); + i += 1; + continue; + } ":with" => { // Collect ?-prefixed symbols until the next keyword or end of vector i += 1; From 250cf9f3b0e393ea78f87ddd5593c1eb3311504d Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Wed, 1 Apr 2026 08:19:52 +0530 Subject: [PATCH 08/14] fix: collapse nested if-let chains in parse_query_pattern (clippy) --- src/query/datalog/parser.rs | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/src/query/datalog/parser.rs b/src/query/datalog/parser.rs index 6e504886c9..ffb970855a 100644 --- a/src/query/datalog/parser.rs +++ b/src/query/datalog/parser.rs @@ -1080,31 +1080,28 @@ fn parse_query_pattern(vec: &[EdnValue]) -> Result { } // Reject :db/* in entity position - if let EdnValue::Keyword(k) = &vec[0] { - if PseudoAttr::from_keyword(k).is_some() { + if let EdnValue::Keyword(k) = &vec[0] + && PseudoAttr::from_keyword(k).is_some() { return Err(format!( "pseudo-attribute {} is not valid in entity position", k )); } - } // Reject :db/* in value position - if let EdnValue::Keyword(k) = &vec[2] { - if PseudoAttr::from_keyword(k).is_some() { + if let EdnValue::Keyword(k) = &vec[2] + && PseudoAttr::from_keyword(k).is_some() { return Err(format!( "pseudo-attribute {} is not valid in value position", k )); } - } // Detect pseudo-attribute in attribute position - if let EdnValue::Keyword(k) = &vec[1] { - if let Some(pseudo) = PseudoAttr::from_keyword(k) { + if let EdnValue::Keyword(k) = &vec[1] + && let Some(pseudo) = PseudoAttr::from_keyword(k) { return Ok(Pattern::pseudo(vec[0].clone(), pseudo, vec[2].clone())); } - } Pattern::from_edn(vec) } From bd474daf85b0cae28ae3c4e26c6598a986c092ff Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Wed, 1 Apr 2026 08:37:37 +0530 Subject: [PATCH 09/14] =?UTF-8?q?feat:=20executor=20=E2=80=94=20hard-error?= =?UTF-8?q?=20guard=20for=20missing=20:any-valid-time=20+=20:db/valid-at?= =?UTF-8?q?=20injection?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add query_uses_per_fact_pseudo_attr helper to detect per-fact pseudo-attr usage - Hard-error in execute_query and execute_query_with_rules when per-fact pseudo-attrs (:db/valid-from, :db/valid-to, :db/tx-count, :db/tx-id) are used without :any-valid-time - Compute valid_at_value (Timestamp/Null/now) and thread it into PatternMatcher via from_slice_with_valid_at in all matcher construction sites - Update not_body_matches to accept and forward valid_at: Value - Update evaluate_branch to compute and forward branch_valid_at_value - Fix valid_at_explicit_timestamp test: insert fact with valid-from "2020-01-01" so it is visible at the queried "2023-01-01" timestamp Co-Authored-By: Claude Sonnet 4.6 --- src/query/datalog/executor.rs | 84 +++++++++++++++++++++++++++++---- tests/temporal_metadata_test.rs | 3 +- 2 files changed, 78 insertions(+), 9 deletions(-) diff --git a/src/query/datalog/executor.rs b/src/query/datalog/executor.rs index b7de563b51..e9b34c2f78 100644 --- a/src/query/datalog/executor.rs +++ b/src/query/datalog/executor.rs @@ -13,6 +13,26 @@ use anyhow::{Result, anyhow}; use regex_lite::Regex; use std::sync::{Arc, RwLock}; +/// Returns true if any where clause (at any depth) contains a per-fact +/// pseudo-attribute pattern (ValidFrom / ValidTo / TxCount / TxId). +/// Used to enforce the `:any-valid-time` requirement. +fn query_uses_per_fact_pseudo_attr(query: &DatalogQuery) -> bool { + fn check_clauses(clauses: &[WhereClause]) -> bool { + clauses.iter().any(|c| match c { + WhereClause::Pattern(p) => matches!( + &p.attribute, + AttributeSpec::Pseudo(pa) if pa.is_per_fact() + ), + WhereClause::Not(inner) => check_clauses(inner), + WhereClause::NotJoin { clauses: inner, .. } => check_clauses(inner), + WhereClause::Or(branches) => branches.iter().any(|b| check_clauses(b)), + WhereClause::OrJoin { branches, .. } => branches.iter().any(|b| check_clauses(b)), + _ => false, + }) + } + check_clauses(&query.where_clauses) +} + /// Result of executing a Datalog query #[derive(Debug, Clone, PartialEq)] pub enum QueryResult { @@ -186,9 +206,27 @@ impl DatalogExecutor { return self.execute_query_with_rules(query); } + // Compute query-level valid_at value for :db/valid-at pseudo-attribute binding. + let now = tx_id_now() as i64; + let valid_at_value = match &query.valid_at { + Some(ValidAt::Timestamp(t)) => Value::Integer(*t), + Some(ValidAt::AnyValidTime) => Value::Null, + None => Value::Integer(now), + }; + + // Hard-error: per-fact pseudo-attrs require :any-valid-time. + if query_uses_per_fact_pseudo_attr(&query) + && !matches!(query.valid_at, Some(ValidAt::AnyValidTime)) + { + return Err(anyhow!( + "temporal pseudo-attributes :db/valid-from, :db/valid-to, :db/tx-count, and \ + :db/tx-id require :any-valid-time; add :any-valid-time to your query" + )); + } + // Apply temporal filters before pattern matching let filtered_facts = self.filter_facts_for_query(&query)?; - let matcher = PatternMatcher::from_slice(filtered_facts.clone()); + let matcher = PatternMatcher::from_slice_with_valid_at(filtered_facts.clone(), valid_at_value.clone()); let patterns = query.get_patterns(); // Plan patterns: assign index hints and reorder by selectivity. @@ -244,7 +282,7 @@ impl DatalogExecutor { .into_iter() .filter(|binding| { for not_body in ¬_clauses { - if not_body_matches(not_body, binding, filtered_facts.clone()) { + if not_body_matches(not_body, binding, filtered_facts.clone(), valid_at_value.clone()) { return false; } } @@ -289,6 +327,24 @@ impl DatalogExecutor { .map(|(pred, _)| pred.clone()) .collect(); + // Compute query-level valid_at value for :db/valid-at pseudo-attribute binding. + let now = tx_id_now() as i64; + let valid_at_value = match &query.valid_at { + Some(ValidAt::Timestamp(t)) => Value::Integer(*t), + Some(ValidAt::AnyValidTime) => Value::Null, + None => Value::Integer(now), + }; + + // Hard-error: per-fact pseudo-attrs require :any-valid-time. + if query_uses_per_fact_pseudo_attr(&query) + && !matches!(query.valid_at, Some(ValidAt::AnyValidTime)) + { + return Err(anyhow!( + "temporal pseudo-attributes :db/valid-from, :db/valid-to, :db/tx-count, and \ + :db/tx-id require :any-valid-time; add :any-valid-time to your query" + )); + } + // Apply temporal filters before evaluating recursive rules let filtered_facts = self.filter_facts_for_query(&query)?; @@ -349,7 +405,7 @@ impl DatalogExecutor { Arc::from(derived_storage.get_asserted_facts().unwrap_or_default()); // Match all patterns against derived facts - let matcher = PatternMatcher::from_slice(derived_facts.clone()); + let matcher = PatternMatcher::from_slice_with_valid_at(derived_facts.clone(), valid_at_value.clone()); let bindings = matcher.match_patterns(&all_patterns); // Apply Or/OrJoin clauses against derived facts (rules already evaluated) @@ -454,7 +510,7 @@ impl DatalogExecutor { .collect(); // Compute not_bindings: if no patterns, seed with current binding. - let m = PatternMatcher::from_slice(derived_facts.clone()); + let m = PatternMatcher::from_slice_with_valid_at(derived_facts.clone(), valid_at_value.clone()); let mut not_bindings: Vec = if substituted.is_empty() { vec![binding.clone()] } else { @@ -547,7 +603,12 @@ impl DatalogExecutor { /// Evaluate a `not` body against the current outer binding. /// /// Returns true if the body "matches" (i.e., the outer binding should be excluded). -fn not_body_matches(not_body: &[WhereClause], outer: &Binding, storage: Arc<[Fact]>) -> bool { +fn not_body_matches( + not_body: &[WhereClause], + outer: &Binding, + storage: Arc<[Fact]>, + valid_at: Value, +) -> bool { use crate::query::datalog::evaluator::substitute_pattern; let patterns: Vec<_> = not_body @@ -563,7 +624,7 @@ fn not_body_matches(not_body: &[WhereClause], outer: &Binding, storage: Arc<[Fac }) .collect(); - let matcher = crate::query::datalog::matcher::PatternMatcher::from_slice(storage.clone()); + let matcher = crate::query::datalog::matcher::PatternMatcher::from_slice_with_valid_at(storage.clone(), valid_at); let mut not_bindings: Vec = if patterns.is_empty() { // Expr-only not body: start with the outer binding so variables resolve. vec![outer.clone()] @@ -849,6 +910,13 @@ pub(crate) fn evaluate_branch( return Ok(vec![]); } + // Compute valid_at_value for pseudo-attribute binding in this branch. + let branch_valid_at_value = match &valid_at { + Some(ValidAt::Timestamp(t)) => Value::Integer(*t), + Some(ValidAt::AnyValidTime) => Value::Null, + None => Value::Integer(tx_id_now() as i64), + }; + // Step 1: Collect Pattern and RuleInvocation clauses let patterns: Vec = branch .iter() @@ -861,7 +929,7 @@ pub(crate) fn evaluate_branch( }) .collect(); - let matcher = PatternMatcher::from_slice(storage.clone()); + let matcher = PatternMatcher::from_slice_with_valid_at(storage.clone(), branch_valid_at_value.clone()); let bindings = if patterns.is_empty() { incoming } else { @@ -912,7 +980,7 @@ pub(crate) fn evaluate_branch( .into_iter() .filter(|binding| { for not_body in ¬_clauses { - if not_body_matches(not_body, binding, storage.clone()) { + if not_body_matches(not_body, binding, storage.clone(), branch_valid_at_value.clone()) { return false; } } diff --git a/tests/temporal_metadata_test.rs b/tests/temporal_metadata_test.rs index 286237ca4e..841924b196 100644 --- a/tests/temporal_metadata_test.rs +++ b/tests/temporal_metadata_test.rs @@ -162,7 +162,8 @@ fn tx_id_same_transaction_join() { #[test] fn valid_at_explicit_timestamp() { let db = db(); - db.execute(r#"(transact [[:alice :person/name "Alice"]])"#).unwrap(); + // Insert with valid-from before the query point so the fact is visible at "2023-01-01" + db.execute(r#"(transact {:valid-from "2020-01-01"} [[:alice :person/name "Alice"]])"#).unwrap(); // 2023-01-01 = 1672531200000 let r = db.execute(r#" From c0aed8d3c0c0c5a4bdb23232135d186bce35b12f Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Wed, 1 Apr 2026 08:51:02 +0530 Subject: [PATCH 10/14] =?UTF-8?q?docs:=20sync=20Phase=207.6=20completion?= =?UTF-8?q?=20=E2=80=94=20temporal=20metadata=20bindings=20(v0.15.0)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 4.6 --- CHANGELOG.md | 15 +++++++++++++++ CLAUDE.md | 4 ++-- Cargo.toml | 2 +- ROADMAP.md | 34 ++++++++++++++++++++-------------- TEST_COVERAGE.md | 23 +++++++++++++++++------ 5 files changed, 55 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6f99c1312d..61aaa99373 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,21 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## v0.15.0 — Phase 7.6: Temporal Metadata Bindings (2026-04-01) + +### Added +- **Temporal pseudo-attributes**: `:db/valid-from`, `:db/valid-to`, `:db/tx-count`, `:db/tx-id`, and `:db/valid-at` are now first-class bindable values in Datalog `:where` patterns +- `PseudoAttr` enum and `AttributeSpec` wrapper type in `types.rs` — clean type-safe representation for real vs. pseudo attributes in `Pattern` +- `parse_query_pattern` in `parser.rs` — detects `:db/*` keywords in the attribute position; rejects them in entity/value positions (parse error) +- `PatternMatcher::from_slice_with_valid_at` constructor — passes query-level `valid_at` into the matcher +- Hard-error guard in executor: per-fact pseudo-attrs (`:db/valid-from`, `:db/valid-to`, `:db/tx-count`, `:db/tx-id`) require `:any-valid-time`; error message tells user exactly what to add +- `:db/valid-at` binds the effective query timestamp: explicit `:valid-at ` → `Value::Integer(ts)`, no `:valid-at` → `Value::Integer(now)`, `:any-valid-time` → `Value::Null` +- `:any-valid-time` now accepted as a standalone top-level query keyword (previously required `:valid-at :any-valid-time` form) +- `tests/temporal_metadata_test.rs`: 16 new integration tests covering time-interval range queries, time-point lookups, tx-time correlation, `:db/valid-at` semantics, and all parse/runtime error guards + +### Total +647 tests (438 unit + 209 integration) + ## v0.14.0 — Phase 7.5: Tests + Error Coverage (2026-03-31) ### Added diff --git a/CLAUDE.md b/CLAUDE.md index 917ef1ca86..e22aa52a09 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -120,7 +120,7 @@ cargo run < demos/demo_negation.txt - `evaluator.rs`: `RecursiveEvaluator` (semi-naive), `StratifiedEvaluator`, `evaluate_not_join` - `stratification.rs`: `DependencyGraph`, `stratify()` — negative edges + cycle detection - `rules.rs`: `RuleRegistry` — thread-safe rule management - - `types.rs`: `EdnValue`, `Pattern`, `DatalogQuery`, `AsOf`, `ValidAt`, `WhereClause` (incl. `Not`, `NotJoin`) + - `types.rs`: `EdnValue`, `Pattern`, `DatalogQuery`, `AsOf`, `ValidAt`, `WhereClause` (incl. `Not`, `NotJoin`); `PseudoAttr` enum, `AttributeSpec` wrapper - `optimizer.rs`: Selectivity-based join reordering; disabled under `wasm` feature 4. **`src/temporal.rs`** — UTC-only timestamp parsing (avoids chrono CVE GHSA-wcg3-cvx6-7396) @@ -165,7 +165,7 @@ Auto-migrates v1/v2/v3/v4/v5 → v6 on open/checkpoint. ## Test Coverage -**617 tests passing** (424 unit + 187 integration + 6 doc). +**647 tests passing** (438 unit + 209 integration). See `TEST_COVERAGE.md` for the full per-file breakdown. **Testing conventions** — see the Testing Conventions section below before writing any tests. diff --git a/Cargo.toml b/Cargo.toml index 0c9b396ddf..05f1981df3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "minigraf" -version = "0.13.1" +version = "0.15.0" edition = "2024" description = "Zero-config, single-file, embedded graph database with bi-temporal Datalog queries" license = "MIT OR Apache-2.0" diff --git a/ROADMAP.md b/ROADMAP.md index eb75f2d15b..c0feddcd02 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -517,7 +517,7 @@ Current v5 stores index data as paged blobs (page type `0x11`). v6 introduces pr - **7.3** ✅ Disjunction (`or` / `or-join`) - **7.4** ✅ Query Optimizer Improvements / `filter_facts_for_query` snapshot fix - **7.5** ✅ Tests + Error Coverage (617 tests; executor.rs 85.71%, evaluator.rs 89.29% branch coverage; CI coverage gate + nightly llvm-cov) -- **7.6** Temporal Metadata Bindings + Range Queries (`:db/valid-from`, `:db/valid-to`, `:db/tx-count` as queryable pseudo-attributes; unlocks Time Interval, Time-Point Lookup, Time-Interval Lookup query classes) +- **7.6** ✅ Temporal Metadata Bindings + Range Queries (`:db/valid-from`, `:db/valid-to`, `:db/tx-count` as queryable pseudo-attributes; unlocks Time Interval, Time-Point Lookup, Time-Interval Lookup query classes) - **7.7** Window Functions + UDFs (`sum/count/rank/lag/lead :over (partition-by … :order-by …)`; embedder-registered aggregate and predicate UDFs via `FunctionRegistry`) - **7.8** Prepared Statements (parse + plan once, execute many times, temporal bind slots; implemented after full clause set including predicate-argument positions) - **7.9** Publish Prep (crates.io — API cleanup, rustdoc, clippy, `unwrap` audit, CI matrix) @@ -726,7 +726,11 @@ Current v5 stores index data as paged blobs (page type `0x11`). v6 introduces pr --- -### 7.6 Temporal Metadata Bindings + Range Queries +### 7.6 Temporal Metadata Bindings + Range Queries ✅ COMPLETE + +**Status**: ✅ Complete (v0.15.0, 2026-04-01) + +**Summary**: `:db/valid-from`, `:db/valid-to`, `:db/tx-count`, `:db/tx-id`, and `:db/valid-at` are now first-class bindable pseudo-attributes in Datalog `:where` patterns. All four temporal query classes are now reachable. 647 tests (438 unit + 209 integration). **Goal**: Expose `valid_from`, `valid_to`, and `tx_count` as first-class bindable values in Datalog `:where` clauses, unlocking the full four-class taxonomy of temporal queries described in the bi-temporal literature. @@ -1565,7 +1569,8 @@ When evaluating features, ask: - ✅ Phase 7.3: Complete (March 2026) - Disjunction (`or` / `or-join`), 562 tests - ✅ Phase 7.4: Complete (March 2026) - `filter_facts_for_query` snapshot fix, eliminate 4-index rebuild, 568 tests - ✅ Phase 7.5: Complete (March 2026) - Cross-feature tests, error-path coverage, ~86-89% branch coverage, 617 tests -- 🎯 Phase 7.6–7.8: temporal metadata bindings, window functions + UDFs, prepared statements; ≥90% branch coverage - **NEXT** +- ✅ Phase 7.6: Complete (April 2026) - Temporal metadata bindings (`:db/valid-from`, `:db/valid-to`, `:db/tx-count`, `:db/tx-id`, `:db/valid-at`), 647 tests +- 🎯 Phase 7.7–7.8: window functions + UDFs, prepared statements; ≥90% branch coverage - **NEXT** - 🎯 Phase 8: 3-4 months (Cross-platform — WASM, mobile, language bindings) - 🎯 Phase 9: Ongoing (Ecosystem — integration examples, cookbook, GraphRAG/LangChain examples) - 🎯 **v1.0.0: 9-12 months** @@ -1576,19 +1581,20 @@ When evaluating features, ask: ## Current Focus -**Right Now**: Phase 7.5 Complete — Phase 7.6 Next (Temporal Metadata Bindings + Range Queries) +**Right Now**: Phase 7.6 Complete — Phase 7.7 Next (Window Functions + UDFs) -**Phase 7.5 Achievements**: -1. ✅ `tests/production_patterns_test.rs` — 8 cross-feature integration tests (not+as-of, not-join+count, recursion+not, or+count, etc.) -2. ✅ `tests/error_handling_test.rs` — 8 error-path integration tests (runtime type errors, stratification errors, parse safety errors) -3. ✅ Stream 3 unit tests — ~53 new tests covering parser-unreachable branches in `executor.rs` and `evaluator.rs` -4. ✅ Branch coverage: `executor.rs` ~85.71% (from ~75%), `evaluator.rs` ~89.29% (from ~73%) -5. ✅ 617 tests passing (424 unit + 187 integration + 6 doc); version bumped to v0.14.0 -6. ✅ Known issue documented: or+negative-cycle not rejected by stratification (1 ignored test) +**Phase 7.6 Achievements**: +1. ✅ `PseudoAttr` enum and `AttributeSpec` wrapper type in `types.rs` +2. ✅ `parse_query_pattern` in `parser.rs` — `:db/*` keywords in attribute position; parse error in entity/value positions +3. ✅ `PatternMatcher::from_slice_with_valid_at` — passes query-level `valid_at` into the matcher +4. ✅ Hard-error guard in executor: per-fact pseudo-attrs require `:any-valid-time` +5. ✅ `:db/valid-at` binds effective query timestamp; `:any-valid-time` accepted as standalone keyword +6. ✅ `tests/temporal_metadata_test.rs` — 16 integration tests covering all four temporal query classes +7. ✅ 647 tests passing (438 unit + 209 integration); version bumped to v0.15.0 -**Immediate Next Steps (Phase 7.6)**: -1. Temporal metadata pseudo-attributes — `:db/valid-from`, `:db/valid-to`, `:db/tx-count`, `:db/tx-id` as bindable `:where` clause values -2. Arithmetic filter predicates applied to temporal metadata (Time Interval, Time-Point Lookup, Time-Interval Lookup query classes) +**Immediate Next Steps (Phase 7.7)**: +1. Window functions — `sum/count/rank/lag/lead :over (partition-by … :order-by …)` in `:find` clauses +2. UDFs — embedder-registered aggregate and predicate functions via `FunctionRegistry` **Key Decisions Made**: - ✅ Datalog query language (simpler, better for temporal) diff --git a/TEST_COVERAGE.md b/TEST_COVERAGE.md index 5cf7920d59..65b3b853ef 100644 --- a/TEST_COVERAGE.md +++ b/TEST_COVERAGE.md @@ -1,11 +1,11 @@ # Minigraf Test Coverage Report -**Last Updated**: Phase 7.5 COMPLETE - Tests + Error Coverage ✅ +**Last Updated**: Phase 7.6 COMPLETE - Temporal Metadata Bindings ✅ ## Test Summary -**Total Tests**: 617 ✅ -- ✅ 424 unit tests (lib) +**Total Tests**: 647 ✅ +- ✅ 438 unit tests (lib) - ✅ 10 bi-temporal tests (integration) - ✅ 10 complex query tests (integration) - ✅ 9 recursive rules tests (integration) @@ -23,13 +23,24 @@ - ✅ 16 disjunction tests (integration, Phase 7.3) - ✅ 8 production pattern tests (integration, Phase 7.5 — cross-feature scenarios) - ✅ 8 error handling tests (integration, Phase 7.5 — error-path coverage; 1 ignored: or+neg-cycle bug) -- ✅ 6 doc tests +- ✅ 16 temporal metadata tests (integration, Phase 7.6 — `:db/valid-from`, `:db/valid-to`, `:db/tx-count`, `:db/tx-id`, `:db/valid-at`) -**Status**: ✅ **All 617 tests passing** (1 ignored: confirmed or+neg-cycle stratification bug) +**Status**: ✅ **All 647 tests passing** (1 ignored: confirmed or+neg-cycle stratification bug) + +## Phase 7.6 Completion Status: ✅ COMPLETE + +**Phase 7.6 Features** (current, complete): +- ✅ `PseudoAttr` enum and `AttributeSpec` wrapper type in `types.rs` +- ✅ `parse_query_pattern` in `parser.rs` — detects `:db/*` keywords in attribute position; rejects in entity/value positions +- ✅ `PatternMatcher::from_slice_with_valid_at` constructor — passes query-level `valid_at` into the matcher +- ✅ Hard-error guard in executor: per-fact pseudo-attrs require `:any-valid-time` +- ✅ `:db/valid-at` binds the effective query timestamp; `:any-valid-time` accepted as standalone keyword +- ✅ `tests/temporal_metadata_test.rs` — 16 integration tests (time-interval range queries, time-point lookups, tx-time correlation, `:db/valid-at` semantics, parse/runtime error guards) +- ✅ 647 tests passing (438 unit + 209 integration) ## Phase 7.5 Completion Status: ✅ COMPLETE -**Phase 7.5 Features** (current, complete): +**Phase 7.5 Features** (complete): - ✅ `cargo-llvm-cov` branch coverage tooling documented in `CONTRIBUTING.md` - ✅ Baseline branch coverage recorded; executor.rs ~86.61%, evaluator.rs ~89.29% (up from ~75% / ~73%) - ✅ `tests/production_patterns_test.rs` — 8 cross-feature integration tests From 39be831167f0e0a6e18a73a82927482bf6c98084 Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Wed, 1 Apr 2026 08:52:12 +0530 Subject: [PATCH 11/14] =?UTF-8?q?style:=20cargo=20fmt=20=E2=80=94=20format?= =?UTF-8?q?=20all=20Phase=207.6=20files?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/query/datalog/executor.rs | 39 ++++-- src/query/datalog/matcher.rs | 51 ++++---- src/query/datalog/parser.rs | 51 ++++---- src/query/datalog/types.rs | 5 +- tests/temporal_metadata_test.rs | 206 +++++++++++++++++++++++--------- 5 files changed, 244 insertions(+), 108 deletions(-) diff --git a/src/query/datalog/executor.rs b/src/query/datalog/executor.rs index e9b34c2f78..a68f7e1e90 100644 --- a/src/query/datalog/executor.rs +++ b/src/query/datalog/executor.rs @@ -100,7 +100,7 @@ impl DatalogExecutor { AttributeSpec::Real(EdnValue::Keyword(k)) => k.clone(), AttributeSpec::Real(_) => return Err(anyhow!("Attribute must be a keyword")), AttributeSpec::Pseudo(_) => { - return Err(anyhow!("Cannot transact a pseudo-attribute")) + return Err(anyhow!("Cannot transact a pseudo-attribute")); } }; @@ -136,7 +136,7 @@ impl DatalogExecutor { AttributeSpec::Real(EdnValue::Keyword(k)) => k.clone(), AttributeSpec::Real(_) => return Err(anyhow!("Attribute must be a keyword")), AttributeSpec::Pseudo(_) => { - return Err(anyhow!("Cannot transact a pseudo-attribute")) + return Err(anyhow!("Cannot transact a pseudo-attribute")); } }; @@ -226,7 +226,10 @@ impl DatalogExecutor { // Apply temporal filters before pattern matching let filtered_facts = self.filter_facts_for_query(&query)?; - let matcher = PatternMatcher::from_slice_with_valid_at(filtered_facts.clone(), valid_at_value.clone()); + let matcher = PatternMatcher::from_slice_with_valid_at( + filtered_facts.clone(), + valid_at_value.clone(), + ); let patterns = query.get_patterns(); // Plan patterns: assign index hints and reorder by selectivity. @@ -282,7 +285,12 @@ impl DatalogExecutor { .into_iter() .filter(|binding| { for not_body in ¬_clauses { - if not_body_matches(not_body, binding, filtered_facts.clone(), valid_at_value.clone()) { + if not_body_matches( + not_body, + binding, + filtered_facts.clone(), + valid_at_value.clone(), + ) { return false; } } @@ -405,7 +413,8 @@ impl DatalogExecutor { Arc::from(derived_storage.get_asserted_facts().unwrap_or_default()); // Match all patterns against derived facts - let matcher = PatternMatcher::from_slice_with_valid_at(derived_facts.clone(), valid_at_value.clone()); + let matcher = + PatternMatcher::from_slice_with_valid_at(derived_facts.clone(), valid_at_value.clone()); let bindings = matcher.match_patterns(&all_patterns); // Apply Or/OrJoin clauses against derived facts (rules already evaluated) @@ -510,7 +519,10 @@ impl DatalogExecutor { .collect(); // Compute not_bindings: if no patterns, seed with current binding. - let m = PatternMatcher::from_slice_with_valid_at(derived_facts.clone(), valid_at_value.clone()); + let m = PatternMatcher::from_slice_with_valid_at( + derived_facts.clone(), + valid_at_value.clone(), + ); let mut not_bindings: Vec = if substituted.is_empty() { vec![binding.clone()] } else { @@ -624,7 +636,10 @@ fn not_body_matches( }) .collect(); - let matcher = crate::query::datalog::matcher::PatternMatcher::from_slice_with_valid_at(storage.clone(), valid_at); + let matcher = crate::query::datalog::matcher::PatternMatcher::from_slice_with_valid_at( + storage.clone(), + valid_at, + ); let mut not_bindings: Vec = if patterns.is_empty() { // Expr-only not body: start with the outer binding so variables resolve. vec![outer.clone()] @@ -929,7 +944,8 @@ pub(crate) fn evaluate_branch( }) .collect(); - let matcher = PatternMatcher::from_slice_with_valid_at(storage.clone(), branch_valid_at_value.clone()); + let matcher = + PatternMatcher::from_slice_with_valid_at(storage.clone(), branch_valid_at_value.clone()); let bindings = if patterns.is_empty() { incoming } else { @@ -980,7 +996,12 @@ pub(crate) fn evaluate_branch( .into_iter() .filter(|binding| { for not_body in ¬_clauses { - if not_body_matches(not_body, binding, storage.clone(), branch_valid_at_value.clone()) { + if not_body_matches( + not_body, + binding, + storage.clone(), + branch_valid_at_value.clone(), + ) { return false; } } diff --git a/src/query/datalog/matcher.rs b/src/query/datalog/matcher.rs index 659988ebce..b4b4ed08f4 100644 --- a/src/query/datalog/matcher.rs +++ b/src/query/datalog/matcher.rs @@ -106,7 +106,10 @@ impl PatternMatcher { let eid = fact.entity.to_string(); bindings.insert(format!("__fvf_{}", eid), Value::Integer(fact.valid_from)); bindings.insert(format!("__fvt_{}", eid), Value::Integer(fact.valid_to)); - bindings.insert(format!("__ftc_{}", eid), Value::Integer(fact.tx_count as i64)); + bindings.insert( + format!("__ftc_{}", eid), + Value::Integer(fact.tx_count as i64), + ); bindings.insert(format!("__fti_{}", eid), Value::Integer(fact.tx_id as i64)); } AttributeSpec::Pseudo(pseudo) => { @@ -114,10 +117,10 @@ impl PatternMatcher { // field to the value position variable (or match against a constant). let pseudo_value = match pseudo { PseudoAttr::ValidFrom => Value::Integer(fact.valid_from), - PseudoAttr::ValidTo => Value::Integer(fact.valid_to), - PseudoAttr::TxCount => Value::Integer(fact.tx_count as i64), - PseudoAttr::TxId => Value::Integer(fact.tx_id as i64), - PseudoAttr::ValidAt => self.valid_at_value.clone(), + PseudoAttr::ValidTo => Value::Integer(fact.valid_to), + PseudoAttr::TxCount => Value::Integer(fact.tx_count as i64), + PseudoAttr::TxId => Value::Integer(fact.tx_id as i64), + PseudoAttr::ValidAt => self.valid_at_value.clone(), }; if !self.match_component(&pattern.value, &pseudo_value, &mut bindings) { return None; @@ -295,18 +298,16 @@ impl PatternMatcher { let resolved_entity = self.apply_binding_to_component(&pattern.entity, existing); let entity_uuid_opt: Option = match &resolved_entity { EdnValue::Uuid(u) => Some(*u), - EdnValue::Keyword(k) => { - edn_to_entity_id(&EdnValue::Keyword(k.clone())).ok() - } + EdnValue::Keyword(k) => edn_to_entity_id(&EdnValue::Keyword(k.clone())).ok(), _ => None, }; if let Some(uuid) = entity_uuid_opt { let eid = uuid.to_string(); let hidden_key = match pseudo { PseudoAttr::ValidFrom => format!("__fvf_{}", eid), - PseudoAttr::ValidTo => format!("__fvt_{}", eid), - PseudoAttr::TxCount => format!("__ftc_{}", eid), - PseudoAttr::TxId => format!("__fti_{}", eid), + PseudoAttr::ValidTo => format!("__fvt_{}", eid), + PseudoAttr::TxCount => format!("__ftc_{}", eid), + PseudoAttr::TxId => format!("__fti_{}", eid), // ValidAt is a query-level constant (not per-fact); fall through to // the normal scan path so each fact produces one binding (all // identical). Task 5 (executor) will inject the correct value. @@ -468,8 +469,8 @@ mod tests { #[test] fn test_from_slice_with_valid_at_field() { - use std::sync::Arc; use crate::graph::types::Value; + use std::sync::Arc; let facts: Arc<[_]> = Arc::from(vec![]); let m = PatternMatcher::from_slice_with_valid_at(facts, Value::Integer(12345)); assert_eq!(m.valid_at_value, Value::Integer(12345)); @@ -866,8 +867,8 @@ mod tests { fn test_pseudo_attr_valid_from_join() { // Simulates the time_interval_entire_interval test pattern: // [?e :item/label _] [?e :db/valid-from ?vf] - use crate::graph::types::{Fact, Value}; use crate::graph::storage::net_asserted_facts; + use crate::graph::types::{Fact, Value}; use crate::query::datalog::types::{AttributeSpec, PseudoAttr}; use uuid::Uuid; @@ -875,17 +876,23 @@ mod tests { let e1 = Uuid::new_v4(); // Transact e1 with explicit valid-from = 1577836800000 - let opt = crate::graph::types::TransactOptions::new( - Some(1577836800000), - Some(1735689600000), - ); - storage.transact_batch( - vec![(e1, ":item/label".to_string(), Value::String("A".to_string()), None)], - Some(opt), - ).unwrap(); + let opt = + crate::graph::types::TransactOptions::new(Some(1577836800000), Some(1735689600000)); + storage + .transact_batch( + vec![( + e1, + ":item/label".to_string(), + Value::String("A".to_string()), + None, + )], + Some(opt), + ) + .unwrap(); // Get all facts - let all_facts: Arc<[Fact]> = Arc::from(net_asserted_facts(storage.get_all_facts().unwrap())); + let all_facts: Arc<[Fact]> = + Arc::from(net_asserted_facts(storage.get_all_facts().unwrap())); let matcher = PatternMatcher::from_slice(all_facts.clone()); // First pattern: [?e :item/label _] diff --git a/src/query/datalog/parser.rs b/src/query/datalog/parser.rs index ffb970855a..905056a5f3 100644 --- a/src/query/datalog/parser.rs +++ b/src/query/datalog/parser.rs @@ -1081,27 +1081,30 @@ fn parse_query_pattern(vec: &[EdnValue]) -> Result { // Reject :db/* in entity position if let EdnValue::Keyword(k) = &vec[0] - && PseudoAttr::from_keyword(k).is_some() { - return Err(format!( - "pseudo-attribute {} is not valid in entity position", - k - )); - } + && PseudoAttr::from_keyword(k).is_some() + { + return Err(format!( + "pseudo-attribute {} is not valid in entity position", + k + )); + } // Reject :db/* in value position if let EdnValue::Keyword(k) = &vec[2] - && PseudoAttr::from_keyword(k).is_some() { - return Err(format!( - "pseudo-attribute {} is not valid in value position", - k - )); - } + && PseudoAttr::from_keyword(k).is_some() + { + return Err(format!( + "pseudo-attribute {} is not valid in value position", + k + )); + } // Detect pseudo-attribute in attribute position if let EdnValue::Keyword(k) = &vec[1] - && let Some(pseudo) = PseudoAttr::from_keyword(k) { - return Ok(Pattern::pseudo(vec[0].clone(), pseudo, vec[2].clone())); - } + && let Some(pseudo) = PseudoAttr::from_keyword(k) + { + return Ok(Pattern::pseudo(vec[0].clone(), pseudo, vec[2].clone())); + } Pattern::from_edn(vec) } @@ -2382,7 +2385,9 @@ mod tests { DatalogCommand::Query(q) => { let patterns = q.get_patterns(); assert!( - patterns.iter().any(|p| matches!(p.attribute, AttributeSpec::Pseudo(_))), + patterns + .iter() + .any(|p| matches!(p.attribute, AttributeSpec::Pseudo(_))), "expected a Pseudo attribute pattern" ); } @@ -2393,17 +2398,23 @@ mod tests { #[test] fn test_parse_error_pseudo_attr_entity_position() { let result = parse_datalog_command( - "(query [:find ?v :any-valid-time :where [:db/valid-from :person/name ?v]])" + "(query [:find ?v :any-valid-time :where [:db/valid-from :person/name ?v]])", + ); + assert!( + result.is_err(), + "pseudo-attr in entity position should error" ); - assert!(result.is_err(), "pseudo-attr in entity position should error"); } #[test] fn test_parse_error_pseudo_attr_value_position() { let result = parse_datalog_command( - "(query [:find ?e :any-valid-time :where [?e :person/name :db/valid-from]])" + "(query [:find ?e :any-valid-time :where [?e :person/name :db/valid-from]])", + ); + assert!( + result.is_err(), + "pseudo-attr in value position should error" ); - assert!(result.is_err(), "pseudo-attr in value position should error"); } } diff --git a/src/query/datalog/types.rs b/src/query/datalog/types.rs index fd2643020a..ecf462b743 100644 --- a/src/query/datalog/types.rs +++ b/src/query/datalog/types.rs @@ -651,7 +651,10 @@ mod tests { ); assert!(pattern.entity.is_variable()); - assert!(matches!(pattern.attribute, AttributeSpec::Real(EdnValue::Keyword(_)))); + assert!(matches!( + pattern.attribute, + AttributeSpec::Real(EdnValue::Keyword(_)) + )); } #[test] diff --git a/tests/temporal_metadata_test.rs b/tests/temporal_metadata_test.rs index 841924b196..ae1dea714b 100644 --- a/tests/temporal_metadata_test.rs +++ b/tests/temporal_metadata_test.rs @@ -22,14 +22,23 @@ fn results(r: &QueryResult) -> &Vec> { fn time_interval_any_point_during() { let db = db(); // e1: valid 2022-01-01 to 2023-07-01 → overlaps [2023-01-01, 2024-01-01] - db.execute(r#"(transact {:valid-from "2022-01-01" :valid-to "2023-07-01"} [[:e1 :item/label "A"]])"#).unwrap(); + db.execute( + r#"(transact {:valid-from "2022-01-01" :valid-to "2023-07-01"} [[:e1 :item/label "A"]])"#, + ) + .unwrap(); // e2: valid 2023-07-01 onwards → overlaps [2023-01-01, 2024-01-01] - db.execute(r#"(transact {:valid-from "2023-07-01"} [[:e2 :item/label "B"]])"#).unwrap(); + db.execute(r#"(transact {:valid-from "2023-07-01"} [[:e2 :item/label "B"]])"#) + .unwrap(); // e3: valid 2015-01-01 to 2020-01-01 → does NOT overlap [2023-01-01, 2024-01-01] - db.execute(r#"(transact {:valid-from "2015-01-01" :valid-to "2020-01-01"} [[:e3 :item/label "C"]])"#).unwrap(); + db.execute( + r#"(transact {:valid-from "2015-01-01" :valid-to "2020-01-01"} [[:e3 :item/label "C"]])"#, + ) + .unwrap(); // T1 = 2023-01-01 = 1672531200000, T2 = 2024-01-01 = 1704067200000 - let r = db.execute(r#" + let r = db + .execute( + r#" (query [:find ?e :any-valid-time :where [?e :item/label _] @@ -37,7 +46,9 @@ fn time_interval_any_point_during() { [?e :db/valid-to ?vt] [(<= ?vf 1704067200000)] [(>= ?vt 1672531200000)]]) - "#).unwrap(); + "#, + ) + .unwrap(); let rows = results(&r); assert_eq!(rows.len(), 2, "e1 and e2 overlap [2023, 2024]; e3 does not"); } @@ -48,12 +59,18 @@ fn time_interval_any_point_during() { fn time_interval_entire_interval() { let db = db(); // e1: valid 2020-01-01 to 2025-01-01 → covers entire [2023-01-01, 2024-01-01] - db.execute(r#"(transact {:valid-from "2020-01-01" :valid-to "2025-01-01"} [[:e1 :item/label "A"]])"#).unwrap(); + db.execute( + r#"(transact {:valid-from "2020-01-01" :valid-to "2025-01-01"} [[:e1 :item/label "A"]])"#, + ) + .unwrap(); // e2: valid 2023-07-01 onwards → does NOT cover T1 = 2023-01-01 - db.execute(r#"(transact {:valid-from "2023-07-01"} [[:e2 :item/label "B"]])"#).unwrap(); + db.execute(r#"(transact {:valid-from "2023-07-01"} [[:e2 :item/label "B"]])"#) + .unwrap(); // T1 = 1672531200000, T2 = 1704067200000 - let r = db.execute(r#" + let r = db + .execute( + r#" (query [:find ?e :any-valid-time :where [?e :item/label _] @@ -61,7 +78,9 @@ fn time_interval_entire_interval() { [?e :db/valid-to ?vt] [(<= ?vf 1672531200000)] [(>= ?vt 1704067200000)]]) - "#).unwrap(); + "#, + ) + .unwrap(); let rows = results(&r); assert_eq!(rows.len(), 1, "only e1 covers the entire interval"); } @@ -75,18 +94,27 @@ fn time_point_lookup_salary_threshold() { // salary 100000, valid 2023-01-01 to 2024-01-01 db.execute(r#"(transact {:valid-from "2023-01-01" :valid-to "2024-01-01"} [[:alice :person/salary 100000]])"#).unwrap(); // salary 30000, valid 2024-01-01 onwards - db.execute(r#"(transact {:valid-from "2024-01-01"} [[:alice :person/salary 30000]])"#).unwrap(); + db.execute(r#"(transact {:valid-from "2024-01-01"} [[:alice :person/salary 30000]])"#) + .unwrap(); - let r = db.execute(r#" + let r = db + .execute( + r#" (query [:find ?vf :any-valid-time :where [:alice :person/salary ?s] [:alice :db/valid-from ?vf] [(> ?s 50000)]]) - "#).unwrap(); + "#, + ) + .unwrap(); let rows = results(&r); assert_eq!(rows.len(), 1, "only the 2023 salary entry exceeds 50000"); - assert_eq!(rows[0][0], Value::Integer(1672531200000), "valid-from = 2023-01-01"); + assert_eq!( + rows[0][0], + Value::Integer(1672531200000), + "valid-from = 2023-01-01" + ); } // ─── Time-Interval Lookup ──────────────────────────────────────────────────── @@ -98,13 +126,17 @@ fn time_interval_lookup_employment_status() { db.execute(r#"(transact {:valid-from "2022-01-01" :valid-to "2023-01-01"} [[:alice :employment/status :probation]])"#).unwrap(); db.execute(r#"(transact {:valid-from "2023-01-01" :valid-to "2025-01-01"} [[:alice :employment/status :permanent]])"#).unwrap(); - let r = db.execute(r#" + let r = db + .execute( + r#" (query [:find ?vf ?vt :any-valid-time :where [:alice :employment/status _] [:alice :db/valid-from ?vf] [:alice :db/valid-to ?vt]]) - "#).unwrap(); + "#, + ) + .unwrap(); let rows = results(&r); assert_eq!(rows.len(), 2, "two distinct employment intervals"); } @@ -115,22 +147,32 @@ fn time_interval_lookup_employment_status() { #[test] fn tx_count_binding() { let db = db(); - db.execute(r#"(transact [[:alice :person/name "Alice"]])"#).unwrap(); // tx_count = 1 - db.execute(r#"(transact [[:bob :person/name "Bob"]])"#).unwrap(); // tx_count = 2 + db.execute(r#"(transact [[:alice :person/name "Alice"]])"#) + .unwrap(); // tx_count = 1 + db.execute(r#"(transact [[:bob :person/name "Bob"]])"#) + .unwrap(); // tx_count = 2 // Query with :any-valid-time: bind tx_count for all name facts - let r = db.execute(r#" + let r = db + .execute( + r#" (query [:find ?e ?tc :any-valid-time :where [?e :person/name _] [?e :db/tx-count ?tc]]) - "#).unwrap(); + "#, + ) + .unwrap(); let rows = results(&r); assert_eq!(rows.len(), 2); // The tx_counts must be 1 and 2 (in any order) - let mut counts: Vec = rows.iter() - .map(|r| match r[1] { Value::Integer(n) => n, _ => panic!("expected Integer") }) + let mut counts: Vec = rows + .iter() + .map(|r| match r[1] { + Value::Integer(n) => n, + _ => panic!("expected Integer"), + }) .collect(); counts.sort(); assert_eq!(counts, vec![1, 2]); @@ -141,19 +183,28 @@ fn tx_count_binding() { fn tx_id_same_transaction_join() { let db = db(); // Alice and Bob written in the same transaction → same tx_id - db.execute(r#"(transact [[:alice :person/name "Alice"] [:bob :person/name "Bob"]])"#).unwrap(); + db.execute(r#"(transact [[:alice :person/name "Alice"] [:bob :person/name "Bob"]])"#) + .unwrap(); - let r = db.execute(r#" + let r = db + .execute( + r#" (query [:find ?e1 ?e2 :any-valid-time :where [?e1 :person/name _] [?e2 :person/name _] [?e1 :db/tx-id ?tx] [?e2 :db/tx-id ?tx]]) - "#).unwrap(); + "#, + ) + .unwrap(); let rows = results(&r); // Both share the same tx-id: (alice, alice), (alice, bob), (bob, alice), (bob, bob) - assert_eq!(rows.len(), 4, "cross-join of 2 entities with same tx-id = 4 rows"); + assert_eq!( + rows.len(), + 4, + "cross-join of 2 entities with same tx-id = 4 rows" + ); } // ─── :db/valid-at Tests ────────────────────────────────────────────────────── @@ -163,15 +214,20 @@ fn tx_id_same_transaction_join() { fn valid_at_explicit_timestamp() { let db = db(); // Insert with valid-from before the query point so the fact is visible at "2023-01-01" - db.execute(r#"(transact {:valid-from "2020-01-01"} [[:alice :person/name "Alice"]])"#).unwrap(); + db.execute(r#"(transact {:valid-from "2020-01-01"} [[:alice :person/name "Alice"]])"#) + .unwrap(); // 2023-01-01 = 1672531200000 - let r = db.execute(r#" + let r = db + .execute( + r#" (query [:find ?vat :valid-at "2023-01-01" :where [:alice :person/name _] [:alice :db/valid-at ?vat]]) - "#).unwrap(); + "#, + ) + .unwrap(); let rows = results(&r); assert_eq!(rows.len(), 1); assert_eq!(rows[0][0], Value::Integer(1672531200000)); @@ -181,13 +237,18 @@ fn valid_at_explicit_timestamp() { #[test] fn valid_at_default_is_now() { let db = db(); - db.execute(r#"(transact [[:alice :person/name "Alice"]])"#).unwrap(); + db.execute(r#"(transact [[:alice :person/name "Alice"]])"#) + .unwrap(); - let r = db.execute(r#" + let r = db + .execute( + r#" (query [:find ?vat :where [:alice :person/name _] [:alice :db/valid-at ?vat]]) - "#).unwrap(); + "#, + ) + .unwrap(); let rows = results(&r); assert_eq!(rows.len(), 1); // The value should be a positive ms timestamp (approximately now) @@ -201,14 +262,19 @@ fn valid_at_default_is_now() { #[test] fn valid_at_any_valid_time_is_null() { let db = db(); - db.execute(r#"(transact [[:alice :person/name "Alice"]])"#).unwrap(); + db.execute(r#"(transact [[:alice :person/name "Alice"]])"#) + .unwrap(); - let r = db.execute(r#" + let r = db + .execute( + r#" (query [:find ?vat :any-valid-time :where [:alice :person/name _] [:alice :db/valid-at ?vat]]) - "#).unwrap(); + "#, + ) + .unwrap(); let rows = results(&r); assert_eq!(rows.len(), 1); assert_eq!(rows[0][0], Value::Null); @@ -220,24 +286,34 @@ fn valid_at_any_valid_time_is_null() { #[test] fn parse_error_pseudo_attr_in_entity_position() { let db = db(); - let result = db.execute(r#" + let result = db.execute( + r#" (query [:find ?v :any-valid-time :where [:db/valid-from :person/name ?v]]) - "#); - assert!(result.is_err(), "pseudo-attribute in entity position must be a parse error"); + "#, + ); + assert!( + result.is_err(), + "pseudo-attribute in entity position must be a parse error" + ); } /// :db/* in value position is a parse error. #[test] fn parse_error_pseudo_attr_in_value_position() { let db = db(); - let result = db.execute(r#" + let result = db.execute( + r#" (query [:find ?e :any-valid-time :where [?e :person/name :db/valid-from]]) - "#); - assert!(result.is_err(), "pseudo-attribute in value position must be a parse error"); + "#, + ); + assert!( + result.is_err(), + "pseudo-attribute in value position must be a parse error" + ); } // ─── Runtime Hard-error Tests ──────────────────────────────────────────────── @@ -246,12 +322,15 @@ fn parse_error_pseudo_attr_in_value_position() { #[test] fn runtime_error_valid_from_without_any_valid_time() { let db = db(); - db.execute(r#"(transact [[:alice :person/name "Alice"]])"#).unwrap(); - let result = db.execute(r#" + db.execute(r#"(transact [[:alice :person/name "Alice"]])"#) + .unwrap(); + let result = db.execute( + r#" (query [:find ?vf :where [:alice :person/name _] [:alice :db/valid-from ?vf]]) - "#); + "#, + ); assert!(result.is_err(), ":db/valid-from requires :any-valid-time"); } @@ -259,12 +338,15 @@ fn runtime_error_valid_from_without_any_valid_time() { #[test] fn runtime_error_valid_to_without_any_valid_time() { let db = db(); - db.execute(r#"(transact [[:alice :person/name "Alice"]])"#).unwrap(); - let result = db.execute(r#" + db.execute(r#"(transact [[:alice :person/name "Alice"]])"#) + .unwrap(); + let result = db.execute( + r#" (query [:find ?vt :where [:alice :person/name _] [:alice :db/valid-to ?vt]]) - "#); + "#, + ); assert!(result.is_err(), ":db/valid-to requires :any-valid-time"); } @@ -272,12 +354,15 @@ fn runtime_error_valid_to_without_any_valid_time() { #[test] fn runtime_error_tx_count_without_any_valid_time() { let db = db(); - db.execute(r#"(transact [[:alice :person/name "Alice"]])"#).unwrap(); - let result = db.execute(r#" + db.execute(r#"(transact [[:alice :person/name "Alice"]])"#) + .unwrap(); + let result = db.execute( + r#" (query [:find ?tc :where [:alice :person/name _] [:alice :db/tx-count ?tc]]) - "#); + "#, + ); assert!(result.is_err(), ":db/tx-count requires :any-valid-time"); } @@ -285,12 +370,15 @@ fn runtime_error_tx_count_without_any_valid_time() { #[test] fn runtime_error_tx_id_without_any_valid_time() { let db = db(); - db.execute(r#"(transact [[:alice :person/name "Alice"]])"#).unwrap(); - let result = db.execute(r#" + db.execute(r#"(transact [[:alice :person/name "Alice"]])"#) + .unwrap(); + let result = db.execute( + r#" (query [:find ?ti :where [:alice :person/name _] [:alice :db/tx-id ?ti]]) - "#); + "#, + ); assert!(result.is_err(), ":db/tx-id requires :any-valid-time"); } @@ -298,11 +386,17 @@ fn runtime_error_tx_id_without_any_valid_time() { #[test] fn valid_at_succeeds_without_any_valid_time() { let db = db(); - db.execute(r#"(transact [[:alice :person/name "Alice"]])"#).unwrap(); - let result = db.execute(r#" + db.execute(r#"(transact [[:alice :person/name "Alice"]])"#) + .unwrap(); + let result = db.execute( + r#" (query [:find ?vat :where [:alice :person/name _] [:alice :db/valid-at ?vat]]) - "#); - assert!(result.is_ok(), ":db/valid-at must not require :any-valid-time"); + "#, + ); + assert!( + result.is_ok(), + ":db/valid-at must not require :any-valid-time" + ); } From 7fbbd69a1d755994889bb8fe7f40377eb2053793 Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Wed, 1 Apr 2026 09:19:47 +0530 Subject: [PATCH 12/14] test: add targeted coverage tests for Phase 7.6 uncovered paths MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Covers 6 previously uncovered code paths flagged by Codecov (PR #28): - executor.rs 341–353: hard-error guard in execute_query_with_rules - executor.rs 930–931: evaluate_branch None valid_at case via or-clause - matcher.rs 119–126: match_fact_against_pattern Pseudo arm (sole pattern) - matcher.rs 322–323: fast-path hidden key found but value mismatch - evaluator.rs 361: substitute_pattern Pseudo arm via not-join body - parser.rs 1076–1079: wrong-length (≠3) where-clause pattern Co-Authored-By: Claude Sonnet 4.6 --- tests/temporal_metadata_test.rs | 147 ++++++++++++++++++++++++++++++++ 1 file changed, 147 insertions(+) diff --git a/tests/temporal_metadata_test.rs b/tests/temporal_metadata_test.rs index ae1dea714b..d2124ec54a 100644 --- a/tests/temporal_metadata_test.rs +++ b/tests/temporal_metadata_test.rs @@ -400,3 +400,150 @@ fn valid_at_succeeds_without_any_valid_time() { ":db/valid-at must not require :any-valid-time" ); } + +// ─── Coverage Gap Tests (Phase 7.6) ───────────────────────────────────────── + +/// Gap 1: Hard error in rules-based query path — per-fact pseudo-attr without :any-valid-time. +/// Exercises executor.rs lines 341–353 (execute_query_with_rules guard). +#[test] +fn runtime_error_rules_per_fact_pseudo_without_any_valid_time() { + let db = db(); + db.execute(r#"(transact [[:alice :person/name "Alice"] [:alice :parent/of :bob]])"#) + .unwrap(); + // Correct rule syntax: head and body patterns in one vector. + db.execute(r#"(rule [(ancestor ?x ?y) [?x :parent/of ?y]])"#) + .unwrap(); + let result = db.execute( + r#" + (query [:find ?y + :where [(ancestor :alice ?y)] + [:alice :db/tx-count ?tc]]) + "#, + ); + assert!( + result.is_err(), + ":db/tx-count in rules query requires :any-valid-time" + ); +} + +/// Gap 2: or-clause query with no :valid-at exercises the evaluate_branch None path. +/// Exercises executor.rs lines 930–931 (branch_valid_at_value for None valid_at). +#[test] +fn or_clause_no_valid_at_executes() { + let db = db(); + db.execute(r#"(transact [[:alice :person/name "Alice"]])"#) + .unwrap(); + db.execute(r#"(transact [[:bob :person/name "Bob"]])"#) + .unwrap(); + + let r = db + .execute( + r#" + (query [:find ?n + :where [?e :person/name ?n] + (or [?e :person/name "Alice"] [?e :person/name "Bob"])]) + "#, + ) + .unwrap(); + let rows = results(&r); + assert_eq!(rows.len(), 2, "both Alice and Bob matched via or-clause"); +} + +/// Gap 3: Pseudo-attr as the sole where-clause pattern. +/// Exercises matcher.rs lines 119–126 (match_fact_against_pattern Pseudo arm via scan). +#[test] +fn pseudo_attr_as_sole_pattern() { + let db = db(); + // 2022-01-01 = 1640995200000 + db.execute(r#"(transact {:valid-from "2022-01-01"} [[:alice :person/name "Alice"]])"#) + .unwrap(); + + let r = db + .execute( + r#" + (query [:find ?vf + :any-valid-time + :where [:alice :db/valid-from ?vf]]) + "#, + ) + .unwrap(); + let rows = results(&r); + assert_eq!(rows.len(), 1, "one fact for alice"); + assert_eq!( + rows[0][0], + Value::Integer(1640995200000), + "valid-from = 2022-01-01" + ); +} + +/// Gap 4: Pseudo-attr constant filter — hidden key found but value doesn't match. +/// Exercises matcher.rs lines 322–323 (fast-path: stored_value != constant → return vec![]). +#[test] +fn pseudo_attr_constant_filter_no_match() { + let db = db(); + db.execute(r#"(transact {:valid-from "2022-01-01"} [[:alice :person/name "Alice"]])"#) + .unwrap(); + + let r = db + .execute( + r#" + (query [:find ?n + :any-valid-time + :where [:alice :person/name ?n] + [:alice :db/valid-from 9999999999999]]) + "#, + ) + .unwrap(); + let rows = results(&r); + assert_eq!(rows.len(), 0, "no facts with valid-from = 9999999999999"); +} + +/// Gap 5: not-join body containing a pseudo-attr pattern. +/// Exercises evaluator.rs line 361 (substitute_pattern Pseudo arm in evaluate_not_join). +#[test] +fn not_join_body_with_pseudo_attr() { + let db = db(); + // 2020-01-01 = 1577836800000 + db.execute(r#"(transact {:valid-from "2020-01-01"} [[:alice :person/name "Alice"]])"#) + .unwrap(); + db.execute(r#"(transact {:valid-from "2022-01-01"} [[:bob :person/name "Bob"]])"#) + .unwrap(); + + // Find entities whose valid-from is NOT 2020-01-01 (= 1577836800000). + // The not-join body contains a pseudo-attr pattern [:db/valid-from 1577836800000], + // which triggers substitute_pattern's Pseudo arm. + let r = db + .execute( + r#" + (query [:find ?e + :any-valid-time + :where [?e :person/name _] + (not-join [?e] + [?e :db/valid-from 1577836800000])]) + "#, + ) + .unwrap(); + let rows = results(&r); + // Only bob survives (alice's valid-from matches the excluded value) + assert_eq!( + rows.len(), + 1, + "alice excluded by not-join on valid-from; only bob survives" + ); +} + +/// Gap 6: Wrong-length pattern in where clause is a parse error. +/// Exercises parser.rs lines 1076–1079 (vec.len() != 3 check in parse_query_pattern). +#[test] +fn parse_error_wrong_length_where_pattern() { + let db = db(); + let result = db.execute( + r#" + (query [:find ?e :where [?e :person/name]]) + "#, + ); + assert!( + result.is_err(), + "2-element where pattern must be a parse error" + ); +} From f33c2ab8d7903336c0e479663066fdd380823fa0 Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Wed, 1 Apr 2026 09:37:56 +0530 Subject: [PATCH 13/14] test: cover dead-code Pseudo(_) guard branches for Codecov Add unit tests that directly construct Pattern::pseudo(...) and feed it through execute_transact/execute_retract (executor.rs lines 103/139), materialize_transaction/materialize_retraction (db.rs ~577/614), and the matcher's hidden-key fast-path with a non-uuid/keyword entity (matcher.rs line 302) and a value-mismatch constant (line 323). These branches are unreachable via the text parser (which always wraps transact attributes in AttributeSpec::Real) but must exist as a defensive guard for direct Rust API callers. Co-Authored-By: Claude Sonnet 4.6 --- src/db.rs | 42 ++++++++++++++++ src/query/datalog/executor.rs | 38 ++++++++++++++ src/query/datalog/matcher.rs | 95 +++++++++++++++++++++++++++++++++++ 3 files changed, 175 insertions(+) diff --git a/src/db.rs b/src/db.rs index b617289821..ff0ce3eed2 100644 --- a/src/db.rs +++ b/src/db.rs @@ -1116,4 +1116,46 @@ mod tests { let facts = db2.inner.fact_storage.get_asserted_facts().unwrap(); assert_eq!(facts.len(), 1, "facts must survive checkpoint"); } + + #[test] + fn test_materialize_transaction_pseudo_attr_error() { + // Exercises db.rs line ~577: Pseudo(_) bail! in materialize_transaction + use crate::query::datalog::types::EdnValue; + use crate::query::datalog::types::{Pattern, PseudoAttr, Transaction}; + let tx = Transaction { + facts: vec![Pattern::pseudo( + EdnValue::Keyword(":alice".to_string()), + PseudoAttr::ValidFrom, + EdnValue::Integer(0), + )], + valid_from: None, + valid_to: None, + }; + let r = Minigraf::materialize_transaction(&tx); + assert!( + r.is_err(), + "materialize_transaction with pseudo-attr must fail" + ); + } + + #[test] + fn test_materialize_retraction_pseudo_attr_error() { + // Exercises db.rs line ~614: Pseudo(_) bail! in materialize_retraction + use crate::query::datalog::types::EdnValue; + use crate::query::datalog::types::{Pattern, PseudoAttr, Transaction}; + let tx = Transaction { + facts: vec![Pattern::pseudo( + EdnValue::Keyword(":alice".to_string()), + PseudoAttr::TxCount, + EdnValue::Integer(0), + )], + valid_from: None, + valid_to: None, + }; + let r = Minigraf::materialize_retraction(&tx); + assert!( + r.is_err(), + "materialize_retraction with pseudo-attr must fail" + ); + } } diff --git a/src/query/datalog/executor.rs b/src/query/datalog/executor.rs index a68f7e1e90..2ff3ac7897 100644 --- a/src/query/datalog/executor.rs +++ b/src/query/datalog/executor.rs @@ -3109,6 +3109,44 @@ mod expr_eval_tests { assert!(r.is_err(), "non-keyword attribute in retract must fail"); } + #[test] + fn execute_transact_pseudo_attr_error() { + // Exercises executor.rs line 103: Pseudo(_) arm in execute_transact + use crate::query::datalog::types::{PseudoAttr, Transaction}; + let storage = FactStorage::new(); + let executor = DatalogExecutor::new(storage); + let cmd = DatalogCommand::Transact(Transaction { + facts: vec![Pattern::pseudo( + EdnValue::Keyword(":e".to_string()), + PseudoAttr::ValidFrom, + EdnValue::Integer(0), + )], + valid_from: None, + valid_to: None, + }); + let r = executor.execute(cmd); + assert!(r.is_err(), "transacting a pseudo-attribute must fail"); + } + + #[test] + fn execute_retract_pseudo_attr_error() { + // Exercises executor.rs line 139: Pseudo(_) arm in execute_retract + use crate::query::datalog::types::{PseudoAttr, Transaction}; + let storage = FactStorage::new(); + let executor = DatalogExecutor::new(storage); + let cmd = DatalogCommand::Retract(Transaction { + facts: vec![Pattern::pseudo( + EdnValue::Keyword(":e".to_string()), + PseudoAttr::TxCount, + EdnValue::Integer(0), + )], + valid_from: None, + valid_to: None, + }); + let r = executor.execute(cmd); + assert!(r.is_err(), "retracting a pseudo-attribute must fail"); + } + #[test] fn execute_rule_empty_head_error() { let storage = FactStorage::new(); diff --git a/src/query/datalog/matcher.rs b/src/query/datalog/matcher.rs index b4b4ed08f4..4d8a533b1f 100644 --- a/src/query/datalog/matcher.rs +++ b/src/query/datalog/matcher.rs @@ -918,4 +918,99 @@ mod tests { assert_eq!(r2.len(), 1, "second pattern should bind ?vf"); assert_eq!(r2[0].get("?vf"), Some(&Value::Integer(1577836800000))); } + + #[test] + fn test_pseudo_attr_entity_non_uuid_non_keyword_falls_through() { + // Exercises matcher.rs line 302: `_ => None` when resolved entity is + // neither Uuid nor Keyword — falls through to scan path. + use crate::graph::storage::net_asserted_facts; + use crate::graph::types::Value as GValue; + use std::sync::Arc; + + let storage = FactStorage::new(); + let alice_id = Uuid::new_v4(); + storage + .transact( + vec![( + alice_id, + ":item/label".to_string(), + GValue::String("x".to_string()), + )], + None, + ) + .unwrap(); + + let all_facts: Arc<[Fact]> = + Arc::from(net_asserted_facts(storage.get_all_facts().unwrap())); + let matcher = PatternMatcher::from_slice(all_facts); + + // Entity is an Integer — neither Uuid nor Keyword → `_ => None` path + let pattern = Pattern { + entity: EdnValue::Integer(99), + attribute: AttributeSpec::Pseudo(PseudoAttr::ValidFrom), + value: EdnValue::Symbol("?vf".to_string()), + valid_from: None, + valid_to: None, + }; + // Falls through to scan; Integer entity won't match any stored UUID → 0 results + let results = matcher.match_pattern(&pattern); + assert_eq!( + results.len(), + 0, + "non-uuid/keyword entity should yield no matches" + ); + } + + #[test] + fn test_pseudo_attr_hidden_key_value_mismatch_returns_empty() { + // Exercises matcher.rs line 323: `return vec![]` when the stored hidden-key + // value doesn't match the pattern value component. + use crate::graph::storage::net_asserted_facts; + use crate::graph::types::Value as GValue; + use std::sync::Arc; + + let storage = FactStorage::new(); + let alice_id = Uuid::new_v4(); + storage + .transact( + vec![( + alice_id, + ":item/label".to_string(), + GValue::String("y".to_string()), + )], + None, + ) + .unwrap(); + + let all_facts: Arc<[Fact]> = + Arc::from(net_asserted_facts(storage.get_all_facts().unwrap())); + let matcher = PatternMatcher::from_slice(all_facts.clone()); + + // Seed bindings with the real-attr pattern so hidden keys are populated + let p1 = Pattern { + entity: EdnValue::Symbol("?e".to_string()), + attribute: AttributeSpec::Real(EdnValue::Keyword(":item/label".to_string())), + value: EdnValue::Symbol("_".to_string()), + valid_from: None, + valid_to: None, + }; + let seeded = matcher.match_pattern(&p1); + assert_eq!(seeded.len(), 1, "seed should match one fact"); + + // Ask for :db/valid-from with an impossible constant value (-999) + // The hidden key exists but -999 won't match the real valid_from → vec![] + let p2 = Pattern { + entity: EdnValue::Symbol("?e".to_string()), + attribute: AttributeSpec::Pseudo(PseudoAttr::ValidFrom), + value: EdnValue::Integer(-999), + valid_from: None, + valid_to: None, + }; + let results = matcher.match_patterns_seeded(&[p2], seeded); + assert_eq!( + results.len(), + 0, + "mismatched constant should return no bindings" + ); + } } From 7fc1af909ae41f9796609f1db90d883e435816b1 Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Wed, 1 Apr 2026 16:01:37 +0530 Subject: [PATCH 14/14] test: add coverage for remaining uncovered patch lines MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Cover 11 of the 12 remaining uncovered new lines (tarpaulin DA:line,0): - executor.rs 341-342: call execute_query_with_rules() directly with ValidAt::Timestamp and ValidAt::AnyValidTime to hit valid_at_value match arms - executor.rs 348-350: rules query with per-fact pseudo-attr + no :any-valid-time triggers the hard-error guard - executor.rs 930-931: call evaluate_branch() with Timestamp and AnyValidTime valid_at to hit branch_valid_at_value match arms - db.rs 576, 613: call materialize_transaction/retraction with AttributeSpec::Real(Integer) (non-keyword) to hit the Real(_) bail! arms (distinct from the Pseudo arm covered previously) - matcher.rs 120-122: call match_pattern() with UUID entity + ValidTo, TxCount, TxId pseudo-attrs (no hidden keys seeded) to hit scan path Line 302 (matcher.rs _ => None in match_pattern_with_bindings entity resolution) remains at 0 — tarpaulin does not instrument _ wildcard arms as standalone probes; patch coverage is ~99.5%, well above the 75% threshold. Co-Authored-By: Claude Sonnet 4.6 --- src/db.rs | 42 ++++++++++++ src/query/datalog/executor.rs | 120 ++++++++++++++++++++++++++++++++++ src/query/datalog/matcher.rs | 62 ++++++++++++++++++ 3 files changed, 224 insertions(+) diff --git a/src/db.rs b/src/db.rs index ff0ce3eed2..3357aa3c4a 100644 --- a/src/db.rs +++ b/src/db.rs @@ -1117,6 +1117,48 @@ mod tests { assert_eq!(facts.len(), 1, "facts must survive checkpoint"); } + #[test] + fn test_materialize_transaction_non_keyword_real_attr_error() { + // Exercises db.rs line 576: Real(_) bail! in materialize_transaction (non-keyword Real attr) + use crate::query::datalog::types::EdnValue; + use crate::query::datalog::types::{Pattern, Transaction}; + let tx = Transaction { + facts: vec![Pattern::new( + EdnValue::Keyword(":alice".to_string()), + EdnValue::Integer(42), // Real(Integer) — not a keyword + EdnValue::Integer(0), + )], + valid_from: None, + valid_to: None, + }; + let r = Minigraf::materialize_transaction(&tx); + assert!( + r.is_err(), + "materialize_transaction with non-keyword Real attr must fail" + ); + } + + #[test] + fn test_materialize_retraction_non_keyword_real_attr_error() { + // Exercises db.rs line 613: Real(_) bail! in materialize_retraction (non-keyword Real attr) + use crate::query::datalog::types::EdnValue; + use crate::query::datalog::types::{Pattern, Transaction}; + let tx = Transaction { + facts: vec![Pattern::new( + EdnValue::Keyword(":alice".to_string()), + EdnValue::String("not-a-keyword".to_string()), // Real(String) — not a keyword + EdnValue::Integer(0), + )], + valid_from: None, + valid_to: None, + }; + let r = Minigraf::materialize_retraction(&tx); + assert!( + r.is_err(), + "materialize_retraction with non-keyword Real attr must fail" + ); + } + #[test] fn test_materialize_transaction_pseudo_attr_error() { // Exercises db.rs line ~577: Pseudo(_) bail! in materialize_transaction diff --git a/src/query/datalog/executor.rs b/src/query/datalog/executor.rs index 2ff3ac7897..2a160ab4d0 100644 --- a/src/query/datalog/executor.rs +++ b/src/query/datalog/executor.rs @@ -3430,6 +3430,126 @@ mod expr_eval_tests { // ── evaluate_branch / apply_or_clauses edge cases ──────────────────────── + #[test] + fn test_evaluate_branch_with_timestamp_valid_at() { + // Exercises executor.rs lines 930-931: evaluate_branch with Timestamp/AnyValidTime + use crate::query::datalog::types::ValidAt; + let storage = FactStorage::new(); + let e1 = Uuid::new_v4(); + storage + .transact( + vec![( + e1, + ":tag".to_string(), + crate::graph::types::Value::Integer(1), + )], + None, + ) + .unwrap(); + let facts: Arc<[crate::graph::types::Fact]> = + Arc::from(storage.get_asserted_facts().unwrap().as_slice()); + let rules = crate::query::datalog::rules::RuleRegistry::new(); + let branch = vec![WhereClause::Pattern(Pattern::new( + EdnValue::Symbol("?e".to_string()), + EdnValue::Keyword(":tag".to_string()), + EdnValue::Symbol("?v".to_string()), + ))]; + let mut initial = std::collections::HashMap::new(); + initial.insert("?seed".to_string(), crate::graph::types::Value::Integer(0)); + + // Line 930: Some(ValidAt::Timestamp(t)) arm + let ts_result = evaluate_branch( + &branch, + vec![initial.clone()], + facts.clone(), + &rules, + None, + Some(ValidAt::Timestamp(crate::graph::types::tx_id_now() as i64)), + ) + .unwrap(); + assert_eq!(ts_result.len(), 1, "timestamp valid_at should match"); + + // Line 931: Some(ValidAt::AnyValidTime) arm + let any_result = evaluate_branch( + &branch, + vec![initial], + facts, + &rules, + None, + Some(ValidAt::AnyValidTime), + ) + .unwrap(); + assert_eq!(any_result.len(), 1, "any_valid_time should match"); + } + + #[test] + fn test_execute_query_with_rules_valid_at_timestamp() { + // Exercises executor.rs lines 341-342 (valid_at_value in execute_query_with_rules + // for Timestamp and AnyValidTime arms) and lines 348-350 (hard-error guard). + use crate::query::datalog::parser::parse_datalog_command; + use crate::query::datalog::types::ValidAt; + let storage = FactStorage::new(); + let executor = DatalogExecutor::new(storage); + + // Register a rule so the query routes through execute_query_with_rules + let rule_cmd = parse_datalog_command(r#"(rule [(tagged ?e) [?e :item/tag ?v]])"#) + .expect("rule parse failed"); + executor.execute(rule_cmd).expect("rule register failed"); + + // Transact a fact + executor + .execute( + parse_datalog_command(r#"(transact [[:item1 :item/tag "x"]])"#) + .expect("transact parse failed"), + ) + .expect("transact failed"); + + // Lines 341-342: call execute_query_with_rules directly with Timestamp and AnyValidTime. + // The public execute() routing may bypass it if query_uses_rules returns false; + // calling the private method directly guarantees coverage. + let q_ts = crate::query::datalog::types::DatalogQuery { + find: vec![crate::query::datalog::types::FindSpec::Variable( + "?e".to_string(), + )], + where_clauses: vec![], + as_of: None, + valid_at: Some(ValidAt::Timestamp(946684800000)), // 2000-01-01 + with_vars: vec![], + }; + let r_ts = executor.execute_query_with_rules(q_ts); + assert!( + r_ts.is_ok(), + "execute_query_with_rules with Timestamp must not error" + ); + + let q_any = crate::query::datalog::types::DatalogQuery { + find: vec![crate::query::datalog::types::FindSpec::Variable( + "?e".to_string(), + )], + where_clauses: vec![], + as_of: None, + valid_at: Some(ValidAt::AnyValidTime), + with_vars: vec![], + }; + let r_any = executor.execute_query_with_rules(q_any); + assert!( + r_any.is_ok(), + "execute_query_with_rules with AnyValidTime must not error" + ); + + // Lines 348-350: hard-error guard in execute_query_with_rules + // Per-fact pseudo-attr without :any-valid-time in a rules query + let err_cmd = parse_datalog_command( + "(query [:find ?e ?vf :where (tagged ?e) [?e :db/valid-from ?vf]])", + ) + .expect("err query parse failed"); + let err_result = executor.execute(err_cmd); + assert!( + err_result.is_err(), + "per-fact pseudo-attr without :any-valid-time in rules query must fail" + ); + } + #[test] fn test_evaluate_branch_empty_incoming_returns_empty() { // evaluate_branch with empty incoming bindings → returns [] immediately (line 842) diff --git a/src/query/datalog/matcher.rs b/src/query/datalog/matcher.rs index 4d8a533b1f..4aa776d3ea 100644 --- a/src/query/datalog/matcher.rs +++ b/src/query/datalog/matcher.rs @@ -919,6 +919,68 @@ mod tests { assert_eq!(r2[0].get("?vf"), Some(&Value::Integer(1577836800000))); } + #[test] + fn test_pseudo_attr_valid_to_tx_count_tx_id_scan_path() { + // Exercises matcher.rs lines 120-122: ValidTo/TxCount/TxId arms in + // match_fact_against_pattern (scan path — no hidden keys seeded). + use crate::graph::storage::net_asserted_facts; + use crate::graph::types::Value as GValue; + use std::sync::Arc; + + let storage = FactStorage::new(); + let alice_id = Uuid::new_v4(); + storage + .transact( + vec![( + alice_id, + ":item/label".to_string(), + GValue::String("z".to_string()), + )], + None, + ) + .unwrap(); + + let all_facts: Arc<[Fact]> = + Arc::from(net_asserted_facts(storage.get_all_facts().unwrap())); + let matcher = PatternMatcher::from_slice(all_facts); + + // Each test uses a UUID entity + wildcard value so the entity check passes + // and no hidden key is seeded → falls through to scan → hits line 120/121/122. + + // Line 120: ValidTo + let p_vt = Pattern { + entity: EdnValue::Uuid(alice_id), + attribute: AttributeSpec::Pseudo(PseudoAttr::ValidTo), + value: EdnValue::Symbol("?vt".to_string()), + valid_from: None, + valid_to: None, + }; + let r_vt = matcher.match_pattern(&p_vt); + assert_eq!(r_vt.len(), 1, "ValidTo scan should bind one result"); + + // Line 121: TxCount + let p_tc = Pattern { + entity: EdnValue::Uuid(alice_id), + attribute: AttributeSpec::Pseudo(PseudoAttr::TxCount), + value: EdnValue::Symbol("?tc".to_string()), + valid_from: None, + valid_to: None, + }; + let r_tc = matcher.match_pattern(&p_tc); + assert_eq!(r_tc.len(), 1, "TxCount scan should bind one result"); + + // Line 122: TxId + let p_ti = Pattern { + entity: EdnValue::Uuid(alice_id), + attribute: AttributeSpec::Pseudo(PseudoAttr::TxId), + value: EdnValue::Symbol("?ti".to_string()), + valid_from: None, + valid_to: None, + }; + let r_ti = matcher.match_pattern(&p_ti); + assert_eq!(r_ti.len(), 1, "TxId scan should bind one result"); + } + #[test] fn test_pseudo_attr_entity_non_uuid_non_keyword_falls_through() { // Exercises matcher.rs line 302: `_ => None` when resolved entity is