Skip to content

Challenge 4: Verify BTreeMap node memory safety with Kani and VeriFast - #684

Open
v3risec wants to merge 9 commits into
model-checking:mainfrom
v3risec:challenge-4-btree
Open

v3risec wants to merge 9 commits into
model-checking:mainfrom
v3risec:challenge-4-btree

Conversation

@v3risec

@v3risec v3risec commented Sep 10, 2026 •

Copy link
Copy Markdown

Summary

This PR verifies the memory safety of alloc::collections::btree::node using complementary Kani and VeriFast proofs.

Challenge 4 names 26 functions in its first success-criteria list and eight additional functions that require unbounded verification. This PR covers all 34 explicitly listed targets:

  • Kani verifies the 26 listed functions and additional supporting operations against the production implementations, using the repository's default verification settings.
  • VeriFast establishes unbounded proofs for the eight recursive and balancing targets, using the production node layout, generic key and value types, and an inductive model of the ancestor chain.

The verification also covers supporting production paths required by these proofs, including node initialization, parent-link repair, suffix movement, destruction, and root replacement.

The library changes add verification contracts and cfg(kani) harnesses only. Normal runtime behavior is unchanged.

Challenge 4 coverage

1. The 26 functions in the first success-criteria list

Category Functions
LeafNode (1) LeafNode::new
NodeRef (14) as_internal_mut, len, ascend, first_edge, last_edge, first_kv, last_kv, into_leaf, keys, as_leaf_mut, into_leaf_mut, as_leaf_dying, pop_internal_level, push
Handle (11) left_edge, right_edge, left_kv, right_kv, descend, into_kv, key_mut, into_val_mut, into_kv_mut, into_kv_valmut, kv_mut

All 26 have dedicated Kani harness coverage.

2. The eight unbounded targets

Production function Verification
NodeRef::new_internal VeriFast
Handle::insert_recursing VeriFast
BalancingContext::do_merge VeriFast
BalancingContext::merge_tracking_child_edge VeriFast
BalancingContext::steal_left VeriFast
BalancingContext::steal_right VeriFast
BalancingContext::bulk_steal_left VeriFast
BalancingContext::bulk_steal_right VeriFast

The first list is not an exhaustive inventory of every relevant function in the module. The proof additionally covers supporting operations such as LeafNode::init, InternalNode::new, handle constructors, sibling navigation, leaf removal, into_key_val, deallocate_and_ascend, consider_for_balancing, choose_parent_kv, marker transitions, parent-link repair, Handle::move_suffix, and NodeRef::drop_kvs.

Approach

1. Kani: production methods and local contracts

The Kani verification module contains 48 proof harnesses.

  • Every function in the 26-function Challenge 4 list has dedicated harness coverage.
  • Symbolic node occupancies, edge indices, and operation parameters cover their complete legal domains, subject to production preconditions.
  • Nodes are constructed using real production allocation and initialization paths rather than fabricated arbitrary pointers.
  • Eight proof_for_contract harnesses cover all six Kani contracts.
  • Additional harnesses check the production RangeInclusive iterator step used by the relinking proof and the NonZero height conversion used by NodeRef::new_internal.
  • Assertions and kani::cover properties check initialization, pointer relationships, metadata, returned handles, and parent backlinks.

Kani uses the pinned repository version and default verification settings. The B-tree harness group contains zero explicit kani::assume calls, stubs, or #[kani::unwind] annotations.

The fixed node capacity bounds the storage of an individual node. It does not impose a bound on the tree height or ancestor chain in the VeriFast proofs.

2. VeriFast: unbounded insertion and balancing

The VeriFast proofs are generic over K and V and use the production CAPACITY and node layout.

Insertion and root propagation

The insertion proof models the ancestor chain as an inductive list. Its loop invariant carries:

  • The pending split.
  • The remaining unvisited ancestors.
  • The completed propagation levels.
  • The dormant handle to the inserted slot.
  • The ownership and backlink relationships needed to continue propagation.

It covers insertion into a leaf, propagation through ancestors with available capacity, splitting a full internal parent, and installing a new root through all three production callbacks.

In particular, the proof checks the path:

full leaf
  -> leaf split
  -> ascend through parent backlink
  -> full internal parent
  -> internal parent split
  -> continue propagation
  -> production root callback
  -> awaken inserted handle

No fixed bound on tree height or ancestor-chain length is used to establish this result.

Balancing

The balancing proofs cover both leaf and internal children. They use symbolic child heights, occupancies, donation counts, and tracked edge indices.

  • do_merge transfers the separator and initialized entries, moves internal edges, repairs parent backlinks, and deallocates the right child using its actual layout.
  • merge_tracking_child_edge checks the tracked edge and its resulting location after merging.
  • steal_left and steal_right use the verified bulk-steal operations with a donation count of one.
  • bulk_steal_left and bulk_steal_right verify entry and edge transfers, shifts, and the affected parent-link repairs.

Relinking and destruction

Additional loop proofs cover half-open and inclusive child relinking, suffix movement, and destruction of initialized key-value slots.

The destruction proof preserves the unwind behavior of generic key and value destructors. It checks the value guard after a panicking key destructor, the remaining initialized suffix, and the cleanup path when another destructor unwinds during an existing unwind.

3. Production correspondence

Following the accepted LinkedList and RawVec VeriFast solutions, the runner separates source identity, verification, and production correspondence.

It:

  1. Checks the original/ snapshots of node.rs, borrow.rs, and mem.rs against the repository's library/ sources.
  2. Checks fingerprints of the additional production dependencies.
  3. Runs the annotated VeriFast proofs.
  4. Compares the production and verified Rust MIR.

There are four MIR comparisons:

Comparison Scope
Backlinks Parent-link access and repair
Operations Production constructors, insertion, split, merge, steal, and suffix movement
Loops Root installation, relinking regions, and tracked-handle operations
Whole functions Insertion propagation, do_merge, destruction guards, accessors, navigation, and local operations

The whole-function comparison follows both normal and unwind cleanup paths without inlining calls. It retains the owned allocator and FnOnce call scopes.

In particular, both MIR comparisons involving do_merge are assembled from the annotated proof. The runner checks the complete production scope, including unwind behavior, rather than relying on a disconnected hand-written merge transcription.

The wrong-layout mutation changes the deallocation layout in the annotated merge proof. VeriFast and both production comparisons reject this mutation.

4. Undefined-behavior obligations

The proofs address all four UB categories specified by Challenge 4.

UB category Main proof obligation
Dangling or misaligned access Accesses use live typed storage with the required alignment and bounds. Deallocation consumes the allocation with its matching layout.
Uninitialized read Reads require initialized MaybeUninit payloads. Shared views derive initialization from the occupied prefix.
Mutation of immutable bytes Shared permissions are fractional; stores and exclusive borrows require the necessary ownership of the affected slots.
Invalid value Type interpretations and typed ownership are preserved when constructing, accessing, and moving values.

VeriFast toolchain extensions and upstream plan

1. Why local VeriFast patches are currently required

The B-tree proof uses VeriFast 26.10. The current Rust frontend and refinement checker do not yet support several MIR shapes and Rust memory-model operations required by the production B-tree implementation.

To make these proofs possible without weakening their memory-safety obligations, this PR currently builds the pinned VeriFast version with 14 local tool patches.

The patches are applied by verifast-proofs/alloc/collections/btree/node.rs/verifast-patches/build.sh. Their exact scope, rationale, rollback evidence, regression tests, and upstream status are documented in:

verifast-patches/README.md

The patches are grouped below by their purpose.

2. Patch inventory and correctness rationale

Group Patches What they change and why they are needed Why the changes are justified
MIR refinement and soundness 0001 Raw pointer refinement; 0010 Address scanning after merge_fractions; 0011 Rust field provenance; 0012 Rust MIR Drop unwind Preserve raw-pointer kind and place information during refinement; continue address-taken analysis after fraction merging; remove an incompatible Rust field-provenance inverse axiom; translate and compare compiler-generated normal and unwind cleanup paths for Drop, calls, and assertions. These are necessary for checking production pointer operations, moved values, and destructor cleanup. The pointer comparison retains source dereferences and pointer projections. The fraction patch does not change fraction rules. Removing the provenance axiom eliminates an inconsistent assumption rather than adding one. The Drop patch compares cleanup actions instead of ignoring them. Targeted regressions cover raw borrows, distinct field-projection addresses, generic drops, drop flags, and cleanup ordering.
Box and pointer lowering 0002 Rust Box dereference unwind; 0009 Borrowed Box projection Correctly extract the normal result of Box pointer projection and handle the borrowed-Box MIR pattern involving an adjacent, retag-free Box copy and pointer projection. These are required to retain the owned Box storage and recover its pointer permissions in the B-tree allocation proofs. The lowering preserves the Box allocation and ownership semantics. The borrowed-Box fold applies only when the temporary's projection is its sole read, while the refinement checker retains the original dereference and Box pointer projection. Removing the changes blocks the corresponding ownership proof or regression.
Fixed-array and slice support 0003 Fixed-array MIR index; 0004 Preserve initialized array values; 0005 Shared array-to-slice projection; 0006 Mutable array-to-slice projection; 0008 Array prefix indexing; 0013 Shared initialized slice; 0014 Raw slice access Support evaluated array indices and element types, initialized-array permissions, shared and mutable array unsizing, checked RangeTo indexing, initialized slice views, and raw slot projections. These operations are required for key/value storage, edge-array movement, and ValMut access. The original evaluated index and element type are retained, and the MIR bounds assertion remains. Array-to-slice projections preserve the base address, tag, and lifetime. Mutable projections transfer only the selected in-bounds permission and restore it through the borrow end token. Prefix indexing checks the static bound. Regression cases reject oversized ranges, uninitialized prefixes, and conflicting exclusive borrows.
Scoped mutable borrowing 0007 Scoped mutable reference creation Adds an explicit track_ref_creation directive to invoke the existing fresh-mutable-reference rule for selected production places. This is required to model the scoped mutable projections used by the B-tree proof. The directive consumes the original points-to ownership and records the reference origin and end token. It does not create an additional independent permission. A standalone raw-borrow regression and the B-tree proof fail when the rule is removed.

3. Relationship with upstream VeriFast

These 14 patches are currently local changes; they have not all been merged into upstream VeriFast.

Some changes overlap with existing upstream work:

The remaining changes are organized into seven focused upstream submissions in the patch README:

  1. Rust Box pointer projection.
  2. Fixed-array MIR projections.
  3. Array-to-slice projections.
  4. Scoped mutable reference creation.
  5. Address scanning after merge_fractions.
  6. Rust field provenance.
  7. Rust MIR Drop unwind handling.

I plan to submit these changes incrementally to upstream VeriFast, coordinating with existing PRs to avoid duplicating ongoing work. The Rust field-provenance and Drop fixes are prioritized because they address important refinement and soundness concerns independently of the B-tree proof.

4. Trusted boundary and regression evidence

These patches extend or correct VeriFast's Rust frontend, checker, and library support. They are therefore part of the trusted toolchain for this proof.

This PR does not claim that the modified verifier itself has been formally verified. Instead, the changes are accompanied by:

  • A pinned VeriFast version and reproducible build.
  • A patch-by-patch explanation of the affected translation or refinement rule.
  • Rollback checks showing which proof or regression fails when a patch is removed.
  • Targeted positive and negative regression cases.
  • Strict production/verified MIR comparisons.
  • B-tree-specific mutation tests that ensure incorrect memory operations and cleanup behavior are rejected.

In particular, the patches do not replace the B-tree ownership proofs with additional unchecked permissions. They make the verifier preserve the pointer, initialization, borrow, lifetime, and unwind semantics required to express those proofs.

5. Separate library specification changes

In addition to the 14 tool patches, the runner applies library-specs.patch to the pinned VeriFast library specifications.

This is separate from the VeriFast frontend and checker patches. It supplies the proof-facing models needed for:

  • Tuple ownership.
  • AllocatorClone and allocator identity.
  • RangeInclusive iterator construction and advancement.
  • NonZero conversions.
  • MaybeUninit initialization and borrow permissions.
  • Array and slice projections.
  • ptr::copy and drop_in_place behavior, including unwind specifications.
  • Relevant Option and conversion operations.

These specifications encode the preconditions, memory permissions, initialization state, and documented library guarantees used by the B-tree proofs. Their role and assumptions are documented separately in the B-tree proof README.

Verification results

Kani 0.68.0 / CBMC 6.11.0

  • 48 harnesses successfully verified.
  • All 79 cover properties reached.
  • Zero explicit assumptions, stubs, or unwind annotations in the B-tree harness group.
  • Serial audit: 6 min 7 s, with a peak sampled RSS of 2.08 GiB.

VeriFast 26.10

  • Four B-tree proof programs passed.
  • Four production MIR comparisons passed.
  • All 32 mutation cases were rejected, producing 47 expected rejection outcomes across the verifier and refinement checks.
  • All 48 upstream Rust refinement-checker cases and 11 patch-registered Rust verifier cases produced their expected outcomes.
  • The audit rebuilt the pinned verifier and reproduced the proofs, comparisons, and mutation results.
  • Audit runtime: 3 min 42 s, with a peak sampled RSS of 1.15 GiB.

The repository's VeriFast CI entry builds the pinned verifier and runs both the positive B-tree proofs and the B-tree-specific negative mutation suite.

Reproducing the checks

Run Kani:

./scripts/run-kani.sh --path . --kani-args --harness-timeout 1800 --jobs 1 \
    --harness collections::btree::node::verify::

Run the repository VeriFast entry, including the B-tree mutation suite:

bash verifast-proofs/check-verifast-proofs.sh

The VeriFast patch rationale, rollback evidence, and upstream follow-up plan are documented in verifast-patches/README.md.

Resolves #77

By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 and MIT licenses.

@v3risec
v3risec requested a review from a team as a code owner September 10, 2026 05:51
@feliperodri feliperodri added the Challenge Used to tag a challenge label Sep 12, 2026

@feliperodri feliperodri left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @v3risec. Reviewed against Challenge 4. This is much stronger than the other Ch4 attempts — 26/26 listed base fns each with a dedicated harness, all 8 recursion/balancing fns present, symbolic occupancy (len = kani::any_where(|l| *l <= CAPACITY) with symbolic keys/values built through the real push path), and #[kani::unwind(13)] fully unwinds the ≤12-edge relink loops — so for the CAPACITY-bounded loops a full-occupancy symbolic harness is genuinely complete. Clean soundness: no cfg body swaps, no trivial invariants, the one contract (LeafNode::init) has a matching proof_for_contract, no assume-the-conclusion.

Requesting changes on two real coverage gaps versus the criteria:

  1. insert_recursing recursion is never exercised. harness_insert_recursing inserts into an empty leaf root with spare capacity, so self.insert returns (None, handle) and returns before the loop (node.rs:1068) — your own comment says "completed without splitting." The recursive/splitting path (the whole point of listing it as an unbounded fn) is dead. Please drive a full node that forces a split and ascends.
  2. Balancing fns cover the leaf arm only. do_merge, merge_tracking_child_edge, steal_left/right, bulk_steal_left/right build new_leaf children, so the internal-node edge-array-copy + parent-relink arm is never taken. (#666's full-occupancy internal do_merge harness is worth borrowing for this.)

This is the prioritized Ch4 solution — close those two gaps (recursion + internal-node balancing arms) and it's approvable. Nice work on the symbolic-occupancy fixtures.

@ivmat

ivmat commented Sep 14, 2026

Copy link
Copy Markdown

@v3risec #666 is closed but as feliperodri mentioned, please see if you could reuse do_merge harness from the PR

@v3risec

v3risec commented Sep 15, 2026

Copy link
Copy Markdown
Author

@feliperodri Thanks for the detailed review and suggestions. I’m currently working on the requested changes, in particular exercising the recursive/splitting path in insert_recursing and adding coverage for the internal-node balancing paths.

@ivmat Thanks for the guidance! I’ll take a closer look at the do_merge harness from #666 and reuse/adapt the relevant parts. Thanks again!

Use unit K/V structural fixtures and narrower symbolic inputs for internal balancing paths while preserving edge movement, identity, and backlink checks.
@v3risec

v3risec commented Sep 21, 2026

Copy link
Copy Markdown
Author

I pushed the follow-up changes for the two coverage gaps from the review.

The main changes are:

  • insert_recursing now exercises the actual split/ascend/propagation path, including a split propagating through a full internal parent.

  • do_merge, merge_tracking_child_edge, steal_left/right, and bulk_steal_left/right now have dedicated internal-node structural harnesses, so the internal edge-array movement and parent-link repair branches are no longer dead.

  • The larger internal harnesses were reworked to keep the structural state symbolic while reducing verification cost enough to make them practical for CI.

1. insert_recursing: the recursive/splitting path is now exercised

The previous harness could return before entering the propagation loop. The updated harnesses distinguish several cases:

  • insertion into a non-full leaf;

  • splitting a full leaf root;

  • splitting a full leaf and ascending into an internal parent that has room;

  • splitting a full leaf, ascending into a full internal parent, splitting that parent, and propagating the split to the root callback.

The last case is harness_insert_recursing_parent_split_unit.

Its fixture builds a full height-one parent whose rightmost leaf is also full. The fixture is constructed through the production new_leaf, new_internal, and push paths, so the child uses the real parent backlink installed by the implementation.

The insertion therefore follows this path:

full leaf
  -> leaf split
  -> ascend through the real parent backlink
  -> full parent cannot absorb the promoted KV
  -> internal parent split
  -> another propagation iteration
  -> root callback

The callback asserts that the resulting split has height 1. The original leaf split has height 0, so reaching the callback with a height-one split demonstrates that the internal parent also split and that insert_recursing propagated beyond the original leaf split.

This directly addresses the previously dead recursive/splitting path.

2. Internal balancing paths are now exercised

I added internal-node harnesses for:

  • do_merge

  • merge_tracking_child_edge

  • steal_left

  • steal_right

  • bulk_steal_left

  • bulk_steal_right

These fixtures use a height-two tree: the balancing parent has height 2 and its two children have height 1. Therefore the production code takes the Internal/Internal branch instead of the leaf-only branch.

The internal fixtures are still constructed through the real allocation/linking operations:

new_leaf
  -> new_internal
  -> push

They do not fabricate child pointers, parent, or parent_idx fields directly.

The internal harnesses also check more than branch reachability. Before the operation they snapshot real child-node pointers; after the operation they verify that:

  • the same child pointer appears at the expected new edge index;

  • shifted or surviving edges preserve child identity;

  • ascend() returns the expected new edge index;

  • the backlink points to the expected new parent node.

So the internal edge-array move/shift and parent-link repair are checked by observable structural postconditions.

3. The occupancy/count/index domains remain symbolic

The internal balancing harnesses are not single hand-picked occupancy examples.

For the balancing operations, node occupancy is symbolic over the complete legal bounded domain for the operation:

  • merge harnesses cover all left_len / right_len combinations satisfying
    left_len + 1 + right_len <= CAPACITY;

  • steal_left covers every non-empty legal left source occupancy and every right destination occupancy with room for one element;

  • steal_right covers the symmetric legal domain;

  • the bulk-steal harnesses use symbolic source occupancy, destination occupancy, and symbolic positive count, constrained only by the production preconditions.

Tracked indices are also symbolic where the API has tracking semantics.

For example, merge_tracking_child_edge_internal symbolically selects both:

  • whether the tracked edge starts in the left or right child; and

  • the legal edge index inside that child.

Likewise, the bulk-steal harnesses use arbitrary symbolic witnesses for both important edge classes: a moved edge and a shifted/surviving edge.

The internal harnesses encode these small bounded quantities as u8 and convert them to usize. Since CAPACITY == 11, this does not reduce the legal occupancy/index/count domain; it only reduces the bit-width presented to the solver.

4. do_merge_internal also covers the parent-level trailing-edge repair

For the internal do_merge coverage, I used the approach from #666 as a reference point, following @ivmat 's suggestion. I adapted that approach to the current harness structure and CI constraints.

The updated fixture also includes a third internal child:

edge0: left
kv0
edge1: right
kv1
edge2: spare

Merging kv0 produces:

edge0: merged
kv0: old kv1
edge1: spare

This is important because it makes the parent-level repair

parent_node.correct_childrens_parent_links(parent_idx + 1..old_parent_len)

non-empty.

The harness records the old spare child at edge 2 and checks after the merge that:

  • the same child pointer moved to edge 1;

  • its parent_idx changed to 1;

  • its parent pointer still points to the shrunk parent.

Separately, it records a grandchild from the right internal child and checks that the internal-child edge copy moved that grandchild to the merged left child and repaired its backlink.

So do_merge_internal now exercises both relink sites:

  1. the parent trailing-edge shift/relink after removing the right child edge; and

  2. the internal-child edge-array copy/relink.

5. Why the supplemental internal harnesses use K = V = ()

I initially experimented locally with non-ZST instantiations such as u8 and i32. Those versions also verified in my local runs, but the larger internal harnesses became impractical for CI in my environment: representative runs exceeded 30 GB of memory and took more than 500 seconds. I therefore use unit K/V for the additional internal structural harnesses. This is a proof decomposition, not a claim that K/V are irrelevant to every part of these functions.

The specific properties added to close this review gap are:

  • recursive control flow;

  • leaf-vs-internal branch selection;

  • internal edge-array movement;

  • translated edge indices;

  • child-node identity;

  • parent / parent_idx backlink repair.

Those properties are not removed by using unit K/V.

In particular:

  • the leaf/internal branch is selected from node height/type, not from the size of K or V;

  • an internal node's edge array still contains real child-node pointers when K = V = ();

  • move_to_slice, slice_shl, and slice_shr on the edge arrays still operate on those child pointers;

  • correct_childrens_parent_links still descends through those edges and writes real parent and parent_idx metadata;

  • the harnesses explicitly compare child-pointer identity before/after the operation and then call ascend() to validate the repaired backlink.

Therefore the ZST payload does not make the internal edge-array-copy or relinking behavior vacuous. If an edge is moved to the wrong slot, not moved, or its backlink is repaired incorrectly, the identity/index/parent assertions fail.

Non-ZST payload coverage is also not removed from the overall suite. The corresponding leaf balancing harnesses continue to use u8/u8. The K/V move/replace logic in these balancing functions is in the common portion of the operation, while the additional unit harnesses specifically exercise the previously missing internal edge/relink branch.

So the intended decomposition is roughly:

u8/u8 leaf harnesses:
    K/V data movement + common balancing behavior

()/() internal harnesses:
    internal edge-array movement
    edge-index translation
    child identity
    parent/backlink repair

6. Unwind bounds

The internal harnesses do not all use the same unwind value because their reachable production loops have different maximum lengths.

CAPACITY == 11, so an internal node can have at most 11 KVs and 12 child edges.

The bounds used are:

  • harness_insert_recursing_parent_split_unit: #[kani::unwind(6)]

    The large fixture construction is source-unrolled, so its 10/11 setup pushes do not consume loop unwinding. For this fixed rightmost full-parent split, the largest production relink loop repairs at most 5 child backlinks after the parent split. The insert_recursing propagation loop itself only needs the leaf-split and parent-split propagation iterations. An unwind of 6 is therefore sufficient for the loops reachable in this fixed structural scenario.

  • harness_do_merge_internal: #[kani::unwind(12)]

    A successful merge satisfies:

    left_len + 1 + right_len <= 11
    

    The internal merge repairs right_len + 1 moved child edges, which is at most 11 iterations. The additional parent trailing-edge repair in this fixture is only one iteration. Thus 12 fully unwinds the maximum 11-iteration loop.

  • harness_merge_tracking_child_edge_internal: #[kani::unwind(12)]

    It reaches the same underlying internal do_merge operation, so the same maximum of 11 child-edge relink iterations applies.

  • harness_steal_left_internal: #[kani::unwind(13)]

    steal_left delegates to bulk_steal_left(1). The destination right child may become full: 11 KVs means 12 child edges. The production code repairs all 0..new_right_len + 1 backlinks, so the loop can execute 12 times. This requires an unwind bound of 13.

  • harness_steal_right_internal: #[kani::unwind(12)]

    At least one element is removed from the right source, so afterward it can contain at most 10 KVs / 11 child edges. The moved-edge relink on the left is only one edge. The maximum loop length is therefore 11.

  • harness_bulk_steal_left_internal: #[kani::unwind(13)]

    With symbolic positive count, the destination right child can again become full and contain 12 child edges. Its backlink-repair range can therefore execute 12 iterations.

  • harness_bulk_steal_right_internal: #[kani::unwind(12)]

    Because count > 0, the right source has at most 10 KVs / 11 child edges after the steal. The left moved-edge repair range has length count <= 11. Both production relink loops therefore have a maximum of 11 iterations.

So the differing unwind values follow the reachable loop bounds for each production path rather than using one uniform conservative number.

7. Limitations

There are still some deliberate limits to these proofs:

  • The unit internal harnesses are structural proofs. They do not independently verify non-ZST byte/layout/drop behavior for K/V in those exact internal-node instances.

  • harness_insert_recursing_parent_split_unit uses one deliberately fixed recursive shape: a full height-one parent, a full rightmost leaf, and a rightmost insertion. It proves that recursive parent splitting/propagation is reachable and safe for that structural path. It's not a proof over arbitrary tree heights or arbitrary insertion positions.

  • The balancing internal fixtures use a fixed tree height of two and balance around parent KV 0. Child occupancy, bulk counts, and tracked child-edge indices are symbolic over their legal domains, but parent height and parent-KV position are not symbolic.

Within those stated bounds, the two gaps from the review are now directly exercised:

  1. insert_recursing enters and propagates through the recursive/splitting path;

  2. the balancing operations enter their internal-node edge-array movement and parent-relink branches, with pointer identity, translated indices, and backlinks checked after the operations.

@v3risec
v3risec requested a review from feliperodri September 21, 2026 14:57

@feliperodri feliperodri left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Challenge 4 requires: "Verification must be unbounded for functions that use recursion or contain loops" That requirement is final. A Kani solution will only be accepted if it is unbounded in the input size for every required function. This PR still verifies at least part of the challenge with bounded harnesses (kani::unwind bounds and/or fixed-size inputs), so I'm requesting changes until every required function is verified without a bound on the input size.

@v3risec v3risec changed the title Challenge 4: Verify memory safety of BTreeMap node module with Kani Challenge 4: Verify BTreeMap node memory safety with Kani and VeriFast Nov 24, 2026
@v3risec

v3risec commented Nov 24, 2026

Copy link
Copy Markdown
Author

@feliperodri The updated proof addresses the unbounded-verification requirement and the production-coverage gaps identified in the earlier reviews.

1. Unbounded verification

Challenge 4 names 26 functions in its first success-criteria list and eight additional unbounded targets. This PR covers all 26 listed functions with Kani and all eight unbounded targets with VeriFast.

The 48 Kani harnesses also include contract and supporting-operation checks; they are not a count of distinct production functions.

VeriFast establishes the eight unbounded results over the production node layout, with generic K and V and an inductive ancestor-chain model. insert_recursing propagates splits over an arbitrary ancestor list and checks all three production root callbacks. The balancing proofs cover both leaf and internal children, including edge-array movement, tracked indices, and parent-link repair. Additional loop invariants cover relinking, suffix movement, and destruction.

No fixed bound on tree height or ancestor-chain length is used to establish these results.

2. VeriFast toolchain patches

The production B-tree proof requires several Rust MIR and ownership features that are not fully supported by the current upstream VeriFast 26.10 frontend and refinement checker.

I therefore currently build the pinned VeriFast version with 14 local patches. These patches add missing translation support, correct refinement behavior, and preserve Rust pointer, borrow, and unwind semantics required by the proof.

They are grouped by purpose:

Group Patches Purpose and correctness evidence
MIR refinement and soundness 0001, 0010, 0011, 0012 Preserve raw-pointer places, continue address-taken analysis, remove an inconsistent field-provenance axiom, and compare compiler cleanup paths. Regression tests cover raw borrows, distinct field-projection addresses, and destructor unwind ordering.
Box and pointer lowering 0002, 0009 Support normal Box pointer projection and borrowed-Box MIR patterns while retaining the original allocation and ownership semantics. The borrowed-Box regression fails when the required lowering is removed.
Fixed-array and slice support 0003–0006, 0008, 0013, 0014 Preserve evaluated indices, initialization state, pointer metadata, lifetimes, and exact slice permissions. Bounds checks remain in place; negative regressions reject oversized ranges, uninitialized prefixes, and conflicting exclusive borrows.
Scoped mutable borrowing 0007 Adds an explicit reference-tracking directive. It transfers the original permission into a scoped borrow and records its origin and end token rather than creating additional ownership. A raw-borrow regression checks this behavior.

The patch README documents each individual patch, its necessity, the affected upstream code, and the corresponding rollback or regression evidence:

verifast-patches/README.md

These patches are part of the trusted toolchain, and I do not claim that the modified verifier itself has been formally verified. The correctness argument is based on preserving the relevant Rust MIR and ownership semantics, strengthening the refinement checks where necessary, removing inconsistent assumptions, and providing targeted regression and negative tests.

3. Upstream plan

The patches are not intended to remain as a permanent local fork.

Some changes overlap with existing upstream work, including #1062, #994, #1001, #1015, and #1023.

The remaining changes are organized into seven focused upstream submissions covering Box projection, fixed-array MIR support, array-to-slice projections, scoped mutable borrowing, address scanning, Rust field provenance, and Rust MIR Drop unwind handling.

I plan to submit these changes incrementally to upstream VeriFast, coordinating with existing PRs and prioritizing the provenance and Drop fixes.

The separate library-specs.patch records the proof-facing models for allocator contracts, MaybeUninit, array and slice projections, ptr::copy, and unwind behavior. It is documented separately from the 14 frontend and checker patches.

4. Verification results

A fresh serial audit produced:

  • Kani 0.68.0 / CBMC 6.11.0: all 48 harnesses verified and all 79 cover properties were reached. The harness group contains no explicit assume calls, stubs, or unwind annotations.
  • VeriFast 26.10: all four B-tree proof programs and four production MIR comparisons passed.
  • All 32 B-tree mutation cases were rejected, producing 47 expected rejection outcomes across the verifier and refinement checks.
  • All 48 upstream refinement-checker cases and 11 patch-registered verifier cases produced their expected outcomes.

The audit rebuilt the pinned VeriFast tool from source and reproduced the proofs, comparisons, and mutation results.

The B-tree positive proofs and mutation suite are integrated into the repository's existing VeriFast CI entry.

@v3risec
v3risec requested a review from feliperodri November 24, 2026 16:12
@feliperodri feliperodri self-assigned this Nov 24, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Challenge Used to tag a challenge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Challenge 4: Memory safety of BTreeMap's btree::node module

3 participants