8000 test(storage): Kani proofs of the key and value encoders (#627) by adityamukho · Pull Request #690 · 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
97 changes: 97 additions & 0 deletions .github/workflows/kani.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
name: Kani proofs

# Two branches, 12 hours apart: main at 06:00 UTC, v3 at 18:00 UTC.
# Scheduled runs always use this file from the default branch, so the branch
# under test is chosen from the cron string that fired (as in
# grammar-verifier.yml). Keep the cron strings here and in KANI_REF/run-name
# identical.
run-name: >-
Kani proofs (${{ github.event_name == 'pull_request' && github.head_ref
|| github.event_name == 'workflow_dispatch' && inputs.ref
|| (github.event.schedule == '0 18 * * *' && 'v3' || 'main') }})

# #627: proves the byte encoders that order index keys (src/storage/keys/
# verification.rs, src/storage/index/verification.rs). The whole set takes
# about 30 seconds of proof time and ~1 GB of memory. Kani upgrades are
# deliberate PRs that re-run the set.

on:
pull_request:
paths:
- "src/storage/keys.rs"
- "src/storage/keys/**"
- "src/storage/index.rs"
- "src/storage/index/**"
- "src/graph/types.rs"
- "Cargo.toml"
- ".github/workflows/kani.yml"
schedule:
- cron: "0 6 * * *" # main
- cron: "0 18 * * *" # v3
workflow_dispatch:
inputs:
ref:
description: Branch to prove
required: true
default: main

permissions:
contents: read
issues: write

env:
KANI_REF: ${{ github.event_name == 'workflow_dispatch' && inputs.ref || (github.event.schedule == '0 18 * * *' && 'v3' || 'main') }}

jobs:
kani:
name: Kani proofs
runs-on: ubuntu-latest
timeout-minutes: 30

steps:
- uses: actions/checkout@v4
if: ${{ github.event_name == 'pull_request' }}

- uses: actions/checkout@v4
if: ${{ github.event_name != 'pull_request' }}
with:
ref: ${{ env.KANI_REF }}

- name: Run Kani
uses: model-checking/kani-github-action@v1.1
with:
kani-version: 0.68.0
args: --lib -j --output-format terse -Z unstable-options --harness-timeout 10m

- name: Record Kani failure
if: ${{ failure() && github.event_name == 'schedule' }}
shell: bash
env:
GH_TOKEN: ${{ github.token }}
ISSUE_TITLE: "Nightly Kani failure (${{ env.KANI_REF }})"
run: |
report_file="kani-failure.md"
{
echo "The Kani proofs failed on ${{ env.KANI_REF }}."
echo
echo "- Run: $GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID"
echo "- Commit: $(git rev-parse HEAD)"
echo "- Reproduce: \`cargo kani --lib -j --output-format terse -Z unstable-options --harness-timeout 10m\` (Kani 0.68.0)"
echo
echo "The failing harness and its counterexample are in the run log."
} > "$report_file"

existing_issue="$(gh issue list \
--repo "$GITHUB_REPOSITORY" \
--state open \
--search "$ISSUE_TITLE in:title" \
--json number,title \
--limit 100 \
--jq ".[] | select(.title == \"$ISSUE_TITLE\") | .number" \
| head -n 1)"

if [ -n "$existing_issue" ]; then
gh issue comment "$existing_issue" --repo "$GITHUB_REPOSITORY" --body-file "$report_file"
else
gh issue create --repo "$GITHUB_REPOSITORY" --title "$ISSUE_TITLE" --body-file "$report_file"
fi
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `tests/snapshot_atomicity_test.rs` races a writer against a reader: a query must see each transaction whole, whether written with `execute` or a `WriteTransaction` (#554), and must read one state for all its patterns (#555), in memory and on file. It also runs the v2.x checkpoint race from #558, which never failed on v3: copy-on-write checkpoints do not overwrite pages a published reader uses.
- **The `datalog_eval` fuzz guard counts partial bindings** (#597). The guard skipped inputs whose patterns join to more than 50,000 rows, counting only the rows after the last pattern. A `not-join` body still runs on the executor pattern by pattern in text order, so a 120-pattern body built hundreds of thousands of partial bindings before its last pattern matched nothing, and ran past the 60-second timeout. The guard now counts the bindings after every pattern. On the `v3` corpus (4,783 inputs) coverage drops by 7 of 9,719 edges. The input is added as a seed, as is the `btree_page` input of the cursor fix above.

- **Kani proofs of the key and value encoders (#627).** `src/storage/keys/verification.rs` and `src/storage/index/verification.rs` hold 12 Kani harnesses, compiled only under `cfg(kani)`. They prove for every input that the v8 key encoders (`put_int`, `put_uint`, `put_tx_desc`, `put_valid_to`, `float_bits`) and `encode_value` keep the order the indexes rely on, that every NaN encodes to one value, and that `float_bits` round-trips. `.github/workflows/kani.yml` runs them on pull requests that touch the encoders and nightly on `main` and `v3`. Decoders, strings, packed pages and the WAL are not covered: the model checker does not finish on them, and the fuzz and property tests remain their defence. Test-only; `Cargo.toml` declares the `kani` cfg so normal builds do not warn.
- **Parser vs grammar verifier (#643).** `src/query/datalog/parser/verifier.rs` checks, for every generated input, that the parser rejects what `tests/grammar/grammar.pest` rejects, and accepts what it accepts unless the error code is semantic (a listed code with a witness pest accepts). It runs every string of 1 to 3 characters over 102 characters (ASCII, `\t \n \r`, four non-ASCII stand-ins) through `parse_edn`, and every bracket-balanced sequence of up to `MINIGRAF_GRAMMAR_BOUND` (default 3) of 32 tokens in 15 command templates through `parse_datalog_command`, also with no separators up to 3 tokens. Deterministic; about 20 s by default and 3.5 min at bound 4 on a 16-thread machine. The drift it found is listed in `KNOWN_DRIFT` by cause (comments and non-ASCII letters #650, since documented: see below; empty sections, ignored keywords, rule and call heads, a lone `:` or `-`, unterminated strings #651, since fixed; a fact of more than four elements losing elements, #649, since fixed); each fix removes its entry. `grammar.pest` now says what the parser means: a fact is exactly `[e a v]` plus an optional valid-time map and a retracted fact exactly `[e a v]`; `not`, `not-join`, `or`, `or-join` (and `and` inside an `or`) are never rule names; literal keywords end at a word boundary (`:find?x` is one keyword).
- **The grammar documents comments and non-ASCII identifiers** (#650). The parser has always accepted both; `tests/grammar/grammar.pest` and `docs/GRAMMAR.md` now say so. A `;` starts a comment that runs to the end of the line and is skipped like whitespace. Symbols, variables, keywords and bind slots take Unicode letters and numerals (`:person/名前`, `?ñ`), as Rust's `char::is_alphabetic` and `char::is_numeric` define them; a symbol starts with a letter or `_`, and `-` followed by a numeral starts a number, not a symbol. Nothing the parser accepts or rejects changes.

Expand Down
8 changes: 6 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,10 @@ cargo test --test complex_queries_test -- --nocapture
cargo test --test recursive_rules_test -- --nocapture
cargo test --test concurrency_test

# Kani proofs of the encoders (#627); ~1 GB. Never add decoder/string harnesses
# without a bench-machine run first: they went past 27 GB without finishing
cargo kani --lib -j --output-format terse -Z unstable-options --harness-timeout 10m

# Run examples
cargo run --example embedded
cargo run --example file_storage
Expand Down Expand Up @@ -112,8 +116,8 @@ cargo run < demos/demo_negation.txt
- `backend/memory.rs`: In-memory backend for testing
- `backend/fault_inject.rs`: `FaultInjectingBackend` — injects I/O errors for durability tests (test builds only)
- `fault.rs`: thread-local fault plan (test builds only, #390) — EIO, torn/short writes, sticky ENOSPC, failed fsync with or without lost writes, at the k-th write or sync of `FileBackend`, the WAL and `sync_parent_dir`; driven by `src/fault_matrix.rs`
- `index.rs`: pending (uncheckpointed) EAVT/AEVT keys over UUIDs and strings, `encode_value`
- `keys.rs`: byte-comparable v8 keys (FDB integers, value tags, `tx↓`, FOREVER), DICT keys, `MAX_VALUE_BYTES`, `MAX_IDENT_BYTES`
- `index.rs`: pending (uncheckpointed) EAVT/AEVT keys over UUIDs and strings, `encode_value`; `index/verification.rs`: Kani proofs of `encode_value` (`#[cfg(kani)]`, #627)
- `keys.rs`: byte-comparable v8 keys (FDB integers, value tags, `tx↓`, FOREVER), DICT keys, `MAX_VALUE_BYTES`, `MAX_IDENT_BYTES`; `keys/verification.rs`: Kani proofs that the key encoders preserve order (`#[cfg(kani)]`, #627; `kani.yml` runs them on encoder PRs and nightly)
- `node.rs`: prefix-compressed leaf and shortest-separator internal node codecs
- `btree.rs`: On-disk B+tree over byte keys (`build_btree`, `cow_update` (copy-on-write inserts and deletes; an emptied leaf or node leaves its parent, an emptied tree is root 0; #550) and `cow_insert`, `LeafCursor` with `seek`, `prefix_scan`, `get`, `MutexStorageBackend`)
- `dict.rs`: `DictReader` (id ↔ UUID/ident, tx timestamps, long values) and `Encoder` (checkpoint-time id assignment and key building)
Expand Down
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,10 @@ lto = "thin"
[lints]
workspace = true

[workspace.lints.rust]
# Kani proof harnesses (#627): `cargo kani` sets cfg(kani).
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(kani)'] }

[workspace.lints.clippy]
# Panic prevention — use Result/? or debug_assert! instead
unwrap_used = "deny"
Expand Down
5 changes: 5 additions & 0 deletions docs/TEST_COVERAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ This covers the unreleased file-format-v8 work (#287, #371): the index-key value
- **Large transactions** (`src/storage/persistent_facts/large_tx.rs`, 7 tests; `src/fault_matrix.rs`, 4 tests; `src/storage/page.rs`, 2 tests; `src/storage/cache.rs`, `src/storage/btree.rs` and `statement.rs`, 4 tests; #550): a `transact`/`retract` of more than one chunk, run by `Minigraf::execute` on a file database at chunk sizes 1 to 4, stores the same records as the one-chunk path (repeats across chunks stored once, several values and windows of one attribute, shared long values, refs, keywords, transaction-level windows, retractions, pending WAL entries committed with it), returns its `tx_id`, answers `:as-of`, passes `verify`, deletes the WAL and survives reopen; another window of a triple an earlier chunk wrote (`API-011`) and a value too long for a checkpoint in a later chunk (`WAL-003`) give the one-chunk path's code and message, take no `tx_count`, write no meta and leave the WAL, and the next checkpoint writes a meta before deleting it, as the first checkpoint after an open with a WAL does; a crash before the meta write on a new file reopens through the WAL guard, and is `STG-033` without it; cursors and fact logs opened before and between chunks keep their snapshot through later checkpoints. The fault matrix injects every write and sync fault at every call of a large transaction on a file with one and with two valid meta slots, with and without a WAL beforehand. Allocator tracking and release, cache eviction, and cursor peeking have unit tests. With `test-oracle`, `tests/crash_kill_test.rs` adds a variant whose child makes most transactions large and rolls back a large statement after writing pages, and `tests/model_based_test.rs` runs at a chunk size of 2; `tests/large_transaction_acceptance_test.rs` (ignored, `test-oracle` only, nightly in `.github/workflows/smoke.yml`) holds at most 16,384 materialised facts for a 1M-fact `transact` and prints peak RSS.
- **Grammar page** (`tests/grammar_doc.rs`, 10 tests; #643): `docs/GRAMMAR.md` matches the EBNF rendered from `tests/grammar/grammar.pest`; each rendering rule (sequence, choice and grouping, names and builtins, `SOI`/`EOI` dropped, lookaheads as comments, bounded repetition, quoting, token marks, section titles, line breaking, the whitespace note and the comment note it joins) on a small grammar.
- **Plan independence** (`tests/plan_independence_test.rs`, 15 tests, `test-oracle` feature only; #596): a matrix of queries (joins in both text orders, cross products, keyword and ref, floats, long strings, filter and binding expressions, recursive rules and rules with `not`, `or`/`or-join` including the #250 short-circuit shapes, placed and deferred `not`/`not-join`, aggregates, `:as-of`, `:valid-at`, `:any-valid-time`), in memory and on file after a checkpoint and a reopen, through `execute` and a cursor, gives the same bag of rows with clause reordering on and off (`minigraf::__reorder`) and with the engine's negation bodies and `or` branches chosen, forced hashed and forced correlated (`minigraf::__subplans`, #546; the matrix gains #546's negation and disjunction shapes); #596's example and the unification cases (an expression whose output is its input, two expressions on one variable, integer vs float, `-0.0` vs `0.0`); and `or` / `or-join` branches whose expressions read or bind from a variable only the outer row binds, nested and in rule bodies (#620); and expressions, chains of them and a `not` after them, reading a variable only an `or` binds, in queries, with rules and in rule bodies (#625; `tests/disjunction_test.rs` repeats them without `test-oracle`). Under `test-oracle` the model-based and property tests also rerun every generated query with reordering off (the property test also with negation bodies and `or` branches forced hashed; it generates `or` / `or-join` over bound variables, #546). Unit tests cover `branch_outer_reads` (#620), the planner deferring an expression only an `or` can bind for, after the expressions placed before it and ahead of the deferred `not`s (#625), `apply_expr` (equal, different, integer vs float, NaN, `-0.0`/`0.0` with and without replacing, keyword vs ref both ways, a failing expression), `Binders::expression`, the switch (source order kept, per thread, restored on drop), and the engine planner's `Bind` modes and build side with the switch off; the engine's join matrix gains six unification shapes.
- **Kani proofs of the encoders** (#627; not `#[test]`s, run by `cargo kani` and `.github/workflows/kani.yml`): 12 harnesses prove, for every input, that the byte encoders ordering index keys keep their order. `src/storage/keys/verification.rs` (7): `put_int`, `put_uint` and `put_valid_to` (including `VALID_TIME_FOREVER`) preserve order, `put_tx_desc` reverses it, `float_bits` preserves IEEE total order on non-NaN floats (`-0.0` before `0.0`), maps every NaN to one value after a 8 ll other 84A4 s, and round-trips through `float_from_bits`. `src/storage/index/verification.rs` (5): `encode_value` writes `Null` as `[0x00]` and each of `Boolean`, `Integer`, `Float` and `Ref` with its own type byte and in its own order, and every NaN to the same bytes. Each harness fails when its encoder is broken on purpose. Decoders, strings, packed pages and the WAL are left out: CBMC does not finish on them (decoder error paths build an `anyhow::Error`; a 3-byte string order proof is a 105M-clause formula), so the fuzz and property tests cover them (spec `docs/superpowers/specs/2026-10-22-kani-storage-encoding-design.md` §5).
- **Public diagnostics**: structured parser, query, storage, WAL, API, and internal error codes; the error-code registry is checked against [`ERROR_REFERENCE.md`](ERROR_REFERENCE.md).
- **Compatibility and quality**: golden-file corpus of released file formats, cross-platform format compatibility, property-based tests, long-haul smoke coverage, a weekly soak at 10M facts with a 5-hour churn (#392), XTDB/Datomic semantic compatibility, grammar conformance, and rustdoc examples.

Expand All @@ -59,6 +60,10 @@ cargo test --quiet
# Include the scheduled/ignored tests when the host supports them
cargo test -- --include-ignored

# Kani proofs of the encoders (#627): ~40 s and ~1 GB with -j; Kani pins its own nightly
cargo install --locked kani-verifier && cargo kani setup
cargo kani --lib -j --output-format terse -Z unstable-options --harness-timeout 10m

# Generate a local branch-coverage report (requires cargo-llvm-cov and a nightly toolchain)
cargo +nightly llvm-cov --branch --html

Expand Down
Loading
Loading
0