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 diff --git a/src/db.rs b/src/db.rs index e6bc3a9f29..3357aa3c4a 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, 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) @@ -1114,4 +1116,88 @@ 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_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 + 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/evaluator.rs b/src/query/datalog/evaluator.rs index f68919c1dd..5e815e3298 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..2a160ab4d0 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}; @@ -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 { @@ -77,8 +97,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 +133,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 = @@ -180,9 +206,30 @@ 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. @@ -238,7 +285,12 @@ 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; } } @@ -283,6 +335,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)?; @@ -343,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(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) @@ -448,7 +519,10 @@ 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 { @@ -541,7 +615,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 @@ -557,7 +636,10 @@ 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()] @@ -843,6 +925,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() @@ -855,7 +944,8 @@ 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 { @@ -906,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()) { + if not_body_matches( + not_body, + binding, + storage.clone(), + branch_valid_at_value.clone(), + ) { return false; } } @@ -3014,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(); @@ -3297,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 012114164b..4aa776d3ea 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, 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, } } @@ -70,18 +83,49 @@ 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; + } + // 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(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; + } + } } Some(bindings) @@ -96,6 +140,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, @@ -242,6 +289,52 @@ 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(); @@ -256,9 +349,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; @@ -266,7 +365,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); } @@ -278,9 +377,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, @@ -362,6 +467,15 @@ pub fn edn_to_entity_id(edn: &EdnValue) -> Result { mod tests { use super::*; + #[test] + fn test_from_slice_with_valid_at_field() { + 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)); + } + #[test] fn test_match_simple_pattern() { let storage = FactStorage::new(); @@ -748,4 +862,217 @@ 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::storage::net_asserted_facts; + use crate::graph::types::{Fact, Value}; + 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))); + } + + #[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 + // 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" + ); + } } 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..905056a5f3 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; @@ -568,7 +575,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 +920,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] + && 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 + )); + } + + // 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())); + } + + Pattern::from_edn(vec) +} + /// Parse a single branch of an (or ...) or (or-join ...) clause. /// /// A branch is either: @@ -1092,7 +1142,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) => { @@ -1108,12 +1158,21 @@ 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() - && !name.starts_with("?_") - { - vars.push(name.to_string()); - } + if let Some(name) = p.entity.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("?_") + { + vars.push(name.to_string()); } vars } @@ -1353,7 +1412,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() { @@ -1473,7 +1532,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"), @@ -2316,6 +2375,47 @@ 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)] diff --git a/src/query/datalog/types.rs b/src/query/datalog/types.rs index 7fc9491913..66037ed49c 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,29 @@ 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, + } + } + + /// 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, @@ -233,7 +304,7 @@ impl Pattern { ) -> Self { Pattern { entity, - attribute, + attribute: AttributeSpec::Real(attribute), value, valid_from, valid_to, @@ -251,7 +322,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 +651,10 @@ mod tests { ); assert!(pattern.entity.is_variable()); - assert!(pattern.attribute.is_keyword()); + assert!(matches!( + pattern.attribute, + AttributeSpec::Real(EdnValue::Keyword(_)) + )); } #[test] @@ -595,7 +669,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())); } @@ -1076,4 +1150,101 @@ 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_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( + EdnValue::Symbol("?e".to_string()), + PseudoAttr::ValidFrom, + EdnValue::Symbol("?vf".to_string()), + ); + assert!(matches!( + p.attribute, + 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"); + } } diff --git a/tests/temporal_metadata_test.rs b/tests/temporal_metadata_test.rs new file mode 100644 index 0000000000..d2124ec54a --- /dev/null +++ b/tests/temporal_metadata_test.rs @@ -0,0 +1,549 @@ +//! 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(); + // 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#" + (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" + ); +} + +// ─── 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" + ); +}