8000 feat: Phase 7.6 — temporal metadata bindings + range queries (v0.15.0) by adityamukho · Pull Request #28 · project-minigraf/minigraf · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <ts>` → `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
Expand Down
4 changes: 2 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
34 changes: 20 additions & 14 deletions ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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**
Expand All @@ -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)
Expand Down
23 changes: 17 additions & 6 deletions TEST_COVERAGE.md
Original file line number Diff line number Diff line change
@@ -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)
Expand All @@ -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
Expand Down
96 changes: 91 additions & 5 deletions src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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"
);
}
}
18 changes: 12 additions & 6 deletions src/query/datalog/evaluator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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.
Expand Down
Loading
Loading
0