A Rust BTreeSet holds keys whose Ord reads a Cell, and one key is changed in place; why do lookups start missing, and is it undefined behaviour?
answer
- position fixed at insert
- searches follow a stale layout
- what the docs call it
- a Clippy lint for keys
- remove, change, reinsert
basics
~20 sThe tree placed the key by its old ordering and never re-sorts, so searches for either value take the wrong path and miss. std calls this a logic error: results are unspecified (wrong answers, panics, leaks, non-termination) but never undefined behaviour.
solid answer
~50 s`BTreeSet` and `BTreeMap` place each key by `Ord` at insert time and assume that position stays valid. If a key's ordering changes while it is stored, later searches compare against a stale layout. The docs say that is normally only possible through `Cell`, `RefCell`, global state, I/O or unsafe code. In the demo, after priority 3 becomes 99, `contains` misses both 3 and 99, `len` still says 20, and iteration shows 99 sitting between 2 and 4. The docs call this a logic error: its behaviour is unspecified but confined to that collection, and it is never undefined behaviour. It can show up as panics, wrong results, aborts, leaks or non-termination. Since Rust 1.96, `BTreeMap::append` may even panic on an incorrect `Ord`. Clippy's `mutable_key_type` lint flags keys with interior mutability. The fix is immutable keys: remove the key, change it, and insert it again.
code
rust · 41 linesuse std::cell::Cell;
use std::cmp::Ordering;
use std::collections::BTreeSet;
// A key whose ordering reads a Cell: it can change while the key is in the set.
#[derive(Debug)]
struct Ticket {
priority: Cell<u32>,
}
impl Ord for Ticket {
fn cmp(&self, other: &Self) -> Ordering {
self.priority.get().cmp(&other.priority.get())
}
}
impl PartialOrd for Ticket {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for Ticket {
fn eq(&self, other: &Self) -> bool {
self.cmp(other) == Ordering::Equal
}
}
impl Eq for Ticket {}
fn t(p: u32) -> Ticket {
Ticket { priority: Cell::new(p) }
}
fn main() {
let set: BTreeSet<Ticket> = (1..=20).map(t).collect();
// Mutate one key in place through a shared reference.
set.iter().find(|k| k.priority.get() == 3).unwrap().priority.set(99);
println!("contains 99? {}", set.contains(&t(99)));
println!("contains 3? {}", set.contains(&t(3)));
println!("len = {}", set.len());
let order: Vec<u32> = set.iter().map(|k| k.priority.get()).collect();
println!("iteration: {order:?}");
}go deeper
Recall that a key in a BTreeMap or BTreeSet must not change its ordering while stored; to change it, remove and reinsert.
Explain that the tree places keys at insert and never re-sorts, so a changed key strands its entry and searches miss.
Name the contract, a logic error with unspecified results but no undefined behaviour, find the culprit key type, and enable clippy::mutable_key_type.
Set a codebase rule that key types are immutable value types, enforced by lint and review, since the failure is silent and release-dependent.
## How the tree relies on `Ord` A `BTreeSet<T>` or `BTreeMap<K, V>` decides **where** each key lives by comparing it with `Ord::cmp` when it is inserted. Every later operation, including `contains`, `get`, `remove`, `range` and the next insert, walks down the tree by comparing again and **assumes each stored key is still where its ordering puts it**. The tree never re-sorts. If a stored key's ordering changes, the layout is stale and the searches are wrong. ## What a mutated key does Interior mutability is how a key's ordering can change after insertion. Take twenty `Ticket`s in a `BTreeSet`, each ordered by a `Cell<u32>` priority, and set the ticket with priority 3 to 99 through a shared reference. Built with rustc 1.99.1, the program reports: 1. `contains(&t(99))` is **false**. The search for 99 heads to the right-hand end of the tree, but the changed key still sits between 2 and 4. 2. `contains(&t(3))` is **false**. No key compares equal to 3 any more. 3. `len()` is still **20**. Nothing was lost; it is just unreachable by search. 4. Iteration yields `1, 2, 99, 4, 5, …`: the stored order, now out of sorted order. The same result comes from a key whose `Ord` impl is **inconsistent**: one that is not transitive, depends on global state or I/O, or calls `NaN` equal to everything. Writing a correct `Ord` is covered with the comparison traits. This question is about what the collection does when the order breaks. ## A logic error, not undefined behaviour The std docs for both types spell out the contract: - It is a **logic error** for a key's ordering relative to other keys to change while it is in the map. That is "normally only possible through `Cell`, `RefCell`, global state, I/O, or unsafe code." - The resulting behaviour is **not specified**, but it is **encapsulated to the collection** that observed the error and does **not** result in undefined behaviour. - It "could include panics, incorrect results, aborts, memory leaks, and non-termination." Why std can promise no UB: `Ord` is a safe trait that any code can implement badly. The `core::cmp` docs say users of the trait must keep such logic errors from causing undefined behaviour, and that **unsafe code must not rely on** these methods being correct. The B-tree's internal unsafe code is written to that rule. So a lying `Ord` corrupts answers, never memory. ## The release note to know The behaviour stays unspecified, and std may change it between releases. **Rust 1.96** lists a compatibility note: `BTreeMap::append` was optimised and **may now panic** for types with incorrect `Ord` impls. Code that "worked" with a broken ordering can start failing after a toolchain bump. That is a reason to fix the key type rather than tolerate it. ## Prevention - **Keep keys immutable.** Put changing state in the **value**: a `Cell` inside `V` is harmless, because values are never compared. - **Change a key by removing and reinserting it**: `set.take(&key)` or `remove`, modify it, then `insert`. Do it before the change, because once the order is corrupted, `remove` may not find the key. - **Turn on Clippy.** `clippy::mutable_key_type` (warn-level, in the `suspicious` group) checks for mutable map and set key types, which covers `BTreeMap` and `BTreeSet` keys with interior mutability. It fires on a `BTreeSet<Ticket>` like the one above. - **Test the ordering** of custom key types with property tests that check it is consistent. ## Diagnosing it in production | Symptom | Likely cause | |---|---| | `get` or `contains` misses a key that iteration shows | key mutated in place, or an inconsistent `Ord` | | `len()` larger than the number of findable keys | entries stranded at stale positions | | a panic inside `append` after upgrading to 1.96 or later | an incorrect `Ord` impl | | a loop that never ends during a lookup | an `Ord` that is not a total order | A senior answer names the contract (logic error, no UB), shows how to find the culprit (keys with interior mutability, comparisons that read global state), and fixes the type. It does not add retries around lookups.
- Is a Cell inside a Rust BTreeMap value, rather than its key, also a problem?No. The map compares only keys, so a value's contents never affect where an entry lives. Interior mutability in `V`, or plain mutation through `get_mut`, `values_mut` or `range_mut`, is safe and expected. The rule applies only to whatever the key's `Ord` reads.
- Why must Rust's BTreeMap stay memory-safe even when a key's Ord lies?`Ord` is a safe trait, so any safe code can implement it inconsistently. The `core::cmp` docs say users of the trait must not let such logic errors cause undefined behaviour, and that unsafe code must not rely on these methods being correct. The B-tree's unsafe internals follow that rule, so a broken ordering can corrupt results but never memory.
- How do you correctly change the priority of a ticket stored in a Rust BTreeSet?Take it out first: `set.take(&key)` returns the owned element, or call `remove(&key)` and rebuild the value. Change the priority, then `insert` it again. Do this before mutating anything, because once the stored order is corrupted, `take` or `remove` may fail to find the key.
- Mutating a key through a Cell is undefined behaviour, like a data race.
- BTreeSet re-sorts a key automatically when its value changes.
- A broken Ord can only give wrong answers, never a panic.
- Interior mutability anywhere in a map entry corrupts the tree, values included.
- The compiler rejects a BTreeMap key type that contains a Cell.
Assumes Rust 1.99; the logic-error contract is long-standing, and the 1.96 release notes add that BTreeMap::append may now panic for types with incorrect Ord impls.