8000 fix(prepared): keep a literal :as-of / :valid-at when binding slots (#603) by adityamukho · Pull Request #604 · 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
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Fixed

- **A prepared query keeps a literal `:as-of`, `:valid-at` or `:any-valid-time`** (#603). Binding a prepared query's slots dropped any `:as-of` or `:valid-at` that was not itself a slot, so `PreparedQuery::execute` and `PreparedQuery::query` ran at the current transaction time and valid now: `(query [:find ?v :as-of 1 :where [:a :n ?v]])` prepared returned the current rows, not those at transaction 1, and a prepared per-fact pseudo-attribute query with `:any-valid-time` failed with `INT-026`. Slot forms (`:as-of $tx`, `:valid-at $t`) were not affected. Present since 2026-04-04; fixed on v2.x too.
- **The wasm32 builds are tested again, and the browser layer no longer panics or drops pages.** The repo split (#231) moved the browser and WASI CI jobs to minigraf-wasm, which only builds the package, so core's own wasm tests stopped running and the wasm32 test build broke unnoticed. A new `wasm.yml` workflow runs the `wasm-bindgen` tests in headless Firefox and Chrome, runs the unit and integration tests on `wasm32-wasip1` under Wasmtime, and lints both targets with `clippy -D warnings`. Fixes found on the way: `BrowserDb` skipped any dirty page it could not read when flushing to IndexedDB and still reported success, and now returns the error (also fixed in v2.0.4, #470). The IndexedDB upgrade callback, the IndexedDB backend handle and the page-buffer lock no longer `unwrap()` (on wasm32 a panic aborts the whole instance). IndexedDB keys that are not whole page numbers are rejected instead of truncated. The nine `BrowserBufferBackend` tests used `#[test]`, which the wasm test runner never runs, and now run. File-only modules (`wal`, `storage::verify`, `storage::dir_sync`) are no longer compiled for wasm32, so the wasm32 builds have no warnings.
- **`BrowserDb` stores upgraded pages and keeps only live pages** (#411, #440). `BrowserDb.open()` now writes the pages an open produced to IndexedDB, so a v7 store is upgraded to v8 once instead of in memory on every open. Pages on the free list no longer keep their bytes in memory or their keys in IndexedDB: open drops them (after a v7 upgrade, the whole old v7 region), and each `transact`, `retract`, `checkpoint()` and `importGraph()` drops the pages its commit freed, in the same IndexedDB transaction as the commit's pages and meta page. Memory and IndexedDB size now follow the live data rather than the write history, and opening no longer reads dead pages back. `importGraph()` also deletes the keys of the replaced database's pages, which a reopen used to load next to the imported ones. `exportGraph()` writes free pages as zeros and is as long as the file's meta page says; the blob opens natively as before.
- Two values of the same attribute written in one transaction are both returned by every query path. Previously only one came back, and entity-bound and attribute-bound queries could return different ones (#371, #287).
Expand Down
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ Auto-migrates v7 → v8 on open (spec §9, with a backup meta page). v1–v6 are

## Test Coverage

**1532 tests** (1522 passing, 10 ignored; unit + integration + doc).
**1534 tests** (1524 passing, 10 ignored; unit + integration + doc).
See `docs/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 README.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ let r2 = pq.execute(&[("tx", BindValue::TxCount(2)), ("entity", BindValue::Entit

```bash
cargo run # interactive Datalog REPL
cargo test # run 1532 tests
cargo test # run 1534 tests
cargo run < demos/demo_recursive.txt # recursive rules demo
```

Expand Down
3 changes: 2 additions & 1 deletion docs/TEST_COVERAGE.md

Large diffs are not rendered by default.

27 changes: 23 additions & 4 deletions src/query/datalog/prepared.rs
Original file line number Diff line number Diff line change
Expand Up @@ -308,12 +308,13 @@ fn substitute(
) -> Result<DatalogQuery> {
let mut query = template.clone();

if let Some(AsOf::Slot(name)) = query.as_of.take() {
query.as_of = Some(resolve_as_of_slot(&name, bindings)?);
// Only a slot is replaced; a literal `:as-of` / `:valid-at` is kept (#603).
if let Some(AsOf::Slot(name)) = &query.as_of {
query.as_of = Some(resolve_as_of_slot(name, bindings)?);
}

if let Some(ValidAt::Slot(name)) = query.valid_at.take() {
query.valid_at = Some(resolve_valid_at_slot(&name, bindings)?);
if let Some(ValidAt::Slot(name)) = &query.valid_at {
query.valid_at = Some(resolve_valid_at_slot(name, bindings)?);
}

for clause in &mut query.where_clauses {
Expand Down Expand Up @@ -724,6 +725,24 @@ mod tests {
));
}

#[test]
fn test_substitute_keeps_literal_as_of_and_valid_at() {
// #603: only a slot is replaced.
let mut q = make_query_entity_slot();
q.as_of = Some(AsOf::Counter(3));
q.valid_at = Some(ValidAt::AnyValidTime);
let bv = BindValue::Entity(uuid::Uuid::nil());
let bindings: HashMap<&str, &BindValue> = [("entity", &bv)].into();
let filled = substitute(&q, &bindings).unwrap();
assert!(matches!(filled.as_of, Some(AsOf::Counter(3))));
assert!(matches!(filled.valid_at, Some(ValidAt::AnyValidTime)));
q.as_of = Some(AsOf::Timestamp(5));
q.valid_at = Some(ValidAt::Timestamp(7));
let filled = substitute(&q, &bindings).unwrap();
assert!(matches!(filled.as_of, Some(AsOf::Timestamp(5))));
assert!(matches!(filled.valid_at, Some(ValidAt::Timestamp(7))));
}

#[test]
fn test_substitute_valid_at_any() {
let q = make_query_valid_at_slot();
Expand Down
67 changes: 67 additions & 0 deletions tests/prepared_statements_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -439,3 +439,70 @@ fn write_transaction_execute_rejects_bind_slots() {
assert_eq!(err.code(), "API-010");
tx.rollback();
}

// ─── Literal time travel in a prepared query (#603) ──────────────────────────

/// Rows of `q` through `execute`, a prepared `execute` and a prepared cursor,
/// none with bind values; all three must agree.
fn three_ways(db: &Minigraf, q: &str) -> usize {
let direct = match db.execute(q).unwrap() {
QueryResult::QueryResults { results, .. } => results.len(),
_ => panic!("expected QueryResults"),
};
let prepared = db.prepare(q).unwrap();
let executed = match prepared.execute(&[]).unwrap() {
QueryResult::QueryResults { results, .. } => results.len(),
_ => panic!("expected QueryResults"),
};
let mut cursor = prepared.query(&[]).unwrap();
let mut pulled = 0;
while let Some(batch) = cursor.next_batch(100).unwrap() {
pulled += batch.rows().len();
}
assert_eq!(executed, direct, "prepared execute agrees with execute");
assert_eq!(pulled, direct, "prepared cursor agrees with execute");
direct
}

#[test]
fn prepared_literal_as_of_and_valid_at_are_kept() {
let db = Minigraf::in_memory().unwrap();
db.execute(r#"(transact {:valid-from "2020-01-01" :valid-to "2021-01-01"} [[:a :n 1]])"#)
.unwrap();
db.execute("(transact [[:a :n 2]])").unwrap();
assert_eq!(
three_ways(
&db,
"(query [:find ?v :as-of 1 :valid-at :any-valid-time :where [:a :n ?v]])"
),
1
);
assert_eq!(
three_ways(
&db,
r#"(query [:find ?v :as-of "2000-01-01T00:00:00Z" :any-valid-time :where [:a :n ?v]])"#
),
0
);
assert_eq!(
three_ways(
&db,
r#"(query [:find ?v :valid-at "2020-06-01T00:00:00Z" :where [:a :n ?v]])"#
),
1
);
assert_eq!(
three_ways(&db, "(query [:find ?v :any-valid-time :where [:a :n ?v]])"),
2
);
assert_eq!(three_ways(&db 5ACE , "(query [:find ?v :where [:a :n ?v]])"), 1);
// A per-fact pseudo-attribute needs :any-valid-time; a prepared query
// keeps it (INT-026 before the fix).
assert_eq!(
three_ways(
&db,
"(query [:find ?v ?t :any-valid-time :where [:a :n ?v] [:a :db/tx-count ?t]])"
),
2
);
}
Loading
0