8000 test(storage): Kani proofs of encode_value (#627) — backport by adityamukho · Pull Request #691 · 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 8000 _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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

- **Prepared queries use the database's rule limits** (#679), back 8000 ported from v3.0.0. `PreparedQuery::execute` ran a rule query with the default `max_derived_facts` and `max_results` of 1,000,000 whatever `OpenOptions` set, so a lower limit set to stop a runaway recursive rule did not apply to prepared queries, and a higher one set for a large derivation failed with `INT-020` where `execute` of the same query succeeded. It now uses the database's limits, as `execute` does. `:max-derived-facts` and `:max-results` written in the query text were always applied. Present since v0.19.0.

### Tests

- **Kani proofs of the value encoding (#627), backported from v3.0.0.** `src/storage/index/verification.rs` holds 5 Kani harnesses, compiled only under `cfg(kani)`. They prove for every input that `encode_value`, the value part of the v7 index keys, gives each of `Null`, `Boolean`, `Integer`, `Float` and `Ref` its own type byte and keeps each one's order, and that every NaN encodes to the same bytes. `.github/workflows/kani.yml` runs them on pull requests that touch the encoder and nightly on `main` and `v3`. Strings, keywords, decoders, fact pages and the WAL are not covered: the model checker does not finish on them. Test-only; `Cargo.toml` declares the `kani` cfg so normal builds do not warn.

## v2.0.9 — 2026-10-21

Patch release on the v2.x line under the [support policy](PHILOSOPHY.md#support-policy): two data-integrity fixes, for a pseudo-attribute in a rule body that read the wrong valid time and tx metadata (#661) and for a fact of more than four elements whose extra elements were silently dropped (#649), plus error codes in `BrowserDb` rejections (#673). File format is unchanged (v7). No API changes; a fact of more than four elements, which used to be stored truncated, now fails with `PRS-108`. Upgrading is recommended for every v2.x user who reads `:db/valid-from`, `:db/valid-to`, `:db/tx-count` or `:db/tx-id` in rules.
Expand Down
6 changes: 5 additions & 1 deletion 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 value encoding (#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 All @@ -108,7 +112,7 @@ cargo run < demos/demo_negation.txt
- `backend/file.rs`: Single `.graph` file backend (4KB pages, cross-platform)
- `backend/memory.rs`: In-memory backend for testing
- `backend/fault_inject.rs`: `FaultInjectingBackend` — injects I/O errors for durability tests (test builds only)
- `index.rs`: EAVT / AEVT / AVET / VAET key types, `FactRef`, `encode_value`
- `index.rs`: EAVT / AEVT / AVET / VAET key types, `FactRef`, `encode_value`; `index/verification.rs`: Kani proofs of `encode_value` (`#[cfg(kani)]`, #627; `kani.yml` runs them on encoder PRs and nightly)
- `btree_v6.rs`: On-disk B+tree (`build_btree`, `rebuild_btree_incremental`, `OnDiskIndexReader`, `MutexStorageBackend`)
- `btree.rs`: Legacy v5 B+tree (migration only)
- `cache.rs`: LRU page cache (`PageCache`, default 256 pages)
Expand Down
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,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 @@ -35,6 +35,7 @@ The v2.0.9 suite covers the public database API, the Datalog engine, storage and
- **Core database behavior**: in-memory and file-backed operation, transactions, checkpoints, retractions, bi-temporal queries, recursive rules, prepared statements, aggregation, expressions, disjunction, window functions, UDFs, and magic-sets evaluation.
- **Storage correctness**: packed pages, B+tree indexes and range scans, cache behavior, file-header validation, migration, WAL replay, checksums, corruption handling, and fault injection.
- **Reliability and concurrency**: concurrent reads and writes, rollback behavior, same-process handle exclusion, cross-process locking, PID namespaces, NFS and container lock behavior, and SIGKILL recovery, and queries seeing each concurrent transaction whole and reading one state for all their patterns, also during a checkpoint (`tests/snapshot_atomicity_test.rs`, #554, #555, #558).
- **Kani proofs of the value encoding** (#627; not `#[test]`s, run by `cargo kani` and `.github/workflows/kani.yml`): 5 harnesses in `src/storage/index/verification.rs` prove, for every input, that `encode_value` (the `value_bytes` of the v7 indexes) writes `Null` as `[0x00]` and each of `Boolean`, `Integer`, `Float` and `Ref` with its own type byte and in its own order (non-NaN floats by IEEE total order, so `-0.0` before `0.0`), and every NaN to the same bytes. Each harness fails when its encoder is broken on purpose. Where NaN sorts is not asserted (#688). Strings, keywords, decoders, fact pages and the WAL are left out: the model checker does not finish on them, so the fuzz and property tests cover them. v3.0.0 adds proofs of its key encoders.
- **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 @@ -56,6 +57,10 @@ cargo test --quiet
# Include the scheduled/ignored tests when the host supports them
cargo test -- --include-ignored

# Kani proofs of the value encoding (#627): ~10 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
3 changes: 3 additions & 0 deletions src/storage/index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,9 @@ impl Indexes {
}
}

#[cfg(kani)]
mod verification;

#[cfg(test)]
mod tests {
use super::*;
Expand Down
67 changes: 67 additions & 0 deletions 67 src/storage/index/verification.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
//! Kani proof harnesses for the canonical value encoding (#627).
//!
//! Each harness proves one variant's encoding for every value of that variant:
//! the type byte, and that byte order matches the variant's order. An order
//! that is exact on equality is also injective, and distinct type bytes order
//! and separate the variants. Strings and keywords are left out: CBMC does not
//! finish on variable-length encodings at a useful bound, so the fuzz and
//! property tests cover them.

use super::*;
use uuid::Uuid;

#[kani::proof]
fn encode_value_null_and_boolean() {
let a: bool = kani::any();
let b: bool = kani::any();
let ea = encode_value(&Value::Boolean(a));
let eb = encode_value(&Value::Boolean(b));
assert_eq!(ea.first(), Some(&0x01));
assert_eq!(a.cmp(&b), ea.cmp(&eb));
assert_eq!(encode_value(&Value::Null), vec![0x00]);
}

#[kani::proof]
fn encode_value_integer_preserves_order() {
let a: i64 = kani::any();
let b: i64 = kani::any();
let ea = encode_value(&Value::Integer(a));
let eb = encode_value(&Value::Integer(b));
assert_eq!(ea.first(), Some(&0x02));
assert_eq!(a.cmp(&b), ea.cmp(&eb));
}

/// Non-NaN floats keep IEEE total order, so `-0.0` sorts before `0.0` and the
/// two encode differently.
#[kani::proof]
fn encode_value_float_preserves_order() {
let a: f64 = kani::any();
let b: f64 = kani::any();
kani::assume(!a.is_nan() && !b.is_nan());
let ea = encode_value(&Value::Float(a));
let eb = encode_value(&Value::Float(b));
assert_eq!(ea.first(), Some(&0x03));
assert_eq!(a.total_cmp(&b), ea.cmp(&eb));
}

/// Every NaN encodes to the same bytes.
#[kani::proof]
fn encode_value_nan_is_canonical() {
let a: f64 = kani::any();
let b: f64 = kani::any();
kani::assume(a.is_nan() && b.is_nan());
assert_eq!(
encode_value(&Value::Float(a)),
encode_value(&Value::Float(b))
);
}

#[kani::proof]
fn encode_value_ref_preserves_order() {
let a = Uuid::from_bytes(kani::any());
let b = Uuid::from_bytes(kani::any());
let ea = encode_value(&Value::Ref(a));
let eb = encode_value(&Value::Ref(b));
assert_eq!(ea.first(), Some(&0x06));
assert_eq!(a.cmp(&b), ea.cmp(&eb));
}
Loading
0