Sub topic 13
Checking Invariants in Tests
A balanced tree can return correct answers and still be broken. Lookups succeed while the tree quietly drifts into a shape that costs O(n) per operation. This chapter shows how to write validators that check the structural rules directly, and how to drive them with randomized tests.
This chapter assumes you have read the earlier chapters on AVL and red-black trees. You should know the AVL balance rule and the red-black color rules, and be comfortable reading Python. The code uses insert, delete, rebalance, update and min_nodes from the AVL chapters, and check_rb from the red-black chapters.
Why ordinary tests are not enough
Suppose you test a tree by inserting keys and then searching for them. A plain, unbalanced BST passes every such test. A rotation that forgets to update a cached height passes too, until some later insertion misjudges the balance factor and builds a tall tree.
The cause is that search results depend only on the ordering invariant. Balance and color rules affect performance and are invisible in return values. To test them you must inspect the structure.
An invariant check is a function that walks the whole tree and raises an error if any rule is broken. It has three uses:
- Test oracle. Call it after every operation in a test.
- Debugging aid. It reports the first node where the structure goes wrong, which is close to the bug.
- Specification. The validator is the executable version of the rules. If you cannot write it, you do not yet know the rules.
What to check
Each tree type has rules that no operation may violate, whether it ends in a rotation, a recolor or a plain pointer change.
| Tree | Invariant | How the validator checks it |
|---|---|---|
| Any BST | Every key in a left subtree is smaller than the node, and every key in a right subtree is larger | Pass an open interval `(lo, hi)` down the recursion |
| AVL | Subtree heights differ by at most 1 | Recompute heights bottom-up and compare |
| AVL (cached) | Stored `height` equals the true height | Compare the stored value to the recomputed one |
| Red-black | Black root, no red-red parent and child, equal black count on every path | Return the black-height from each subtree and compare |
| Either | Height is O(log n) | Compare the measured height to the proven bound |
Validating an AVL tree
The validator must not trust the tree's own bookkeeping. It recomputes each height from the children and then compares that value with the cached height. If it read n.height alone, a stale cached value would hide the very bug you want to find.
class Node:
def __init__(self, key, left=None, right=None, height=1):
self.key = key
self.left = left
self.right = right
self.height = height
def height(n):
return n.height if n else 0
def update(n):
n.height = 1 + max(height(n.left), height(n.right))
def check_avl(root):
"""Raise ValueError if ordering, balance or cached heights are wrong.
Return the true height of the tree."""
def walk(n, lo, hi):
if n is None:
return 0
if (lo is not None and n.key <= lo) or (hi is not None and n.key >= hi):
raise ValueError("BST order violated at %r" % n.key)
lh = walk(n.left, lo, n.key)
rh = walk(n.right, n.key, hi)
if abs(lh - rh) > 1:
raise ValueError("imbalance at %r: %d vs %d" % (n.key, lh, rh))
h = 1 + max(lh, rh)
if n.height != h:
raise ValueError("stale height at %r: stored %d, true %d" % (n.key, n.height, h))
return h
return walk(root, None, None)
</parameter>
</invoke>Three details matter here.
First, the validator passes bounds down the tree instead of comparing each node only with its children. A tree where 3 has a right child 6 and sits in the left subtree of 5 passes every parent-child comparison. It still breaks the ordering rule, because 6 is larger than 5.
Second, the comparisons are strict, so duplicate keys are rejected. That matches the insert from the AVL chapter, which ignores duplicates. If your tree allows duplicates, change the bounds to match and say so in a comment.
Third, the checks run bottom-up. The error you see names the deepest broken node, which is usually the node where the bug acted.
Test the validator first
A validator that never fails proves nothing. Before you rely on it, feed it small trees you built by hand with one deliberate flaw each, and confirm it complains about the right one.
def expect_error(tree, fragment):
try:
check_avl(tree)
except ValueError as e:
assert fragment in str(e), str(e)
else:
raise AssertionError("validator accepted a broken tree")
# Order broken two levels away: 6 is in the left subtree of 5.
expect_error(Node(5, Node(3, None, Node(6), 2), None, 3), "order")
# Correct heights, but a right-leaning chain 1 -> 2 -> 3.
expect_error(Node(1, None, Node(2, None, Node(3), 2), 3), "imbalance")
# Balanced and ordered, but the root's cached height was not updated.
expect_error(Node(2, Node(1), None, 1), "stale height")
check_avl(None) # an empty tree is valid
check_avl(Node(7)) # so is a single node
print("validator self-tests passed")This is a small form of mutation testing: you break the structure on purpose and check that the test notices. Do the same for check_rb from the red-black chapters. Build a tree with a red root, one with a red node under a red node, and one where one path has an extra black node.
Randomized testing against a model
Hand-built cases find bugs you thought of. Rebalancing bugs tend to appear in sequences you did not think of, such as a deletion that triggers a double rotation two levels above the leaf. A randomized test applies many random operations and runs the validator after each.
The test also needs a second check. The validator confirms the shape is legal, but it cannot tell you that a key went missing. Keep a Python set as a model of what the tree should contain, and compare the tree's in-order keys with the sorted model.
Because the instructions require a specific diagram format, here is the diagram of that loop:
The harness takes the operations and the validator as arguments, so the same code tests the AVL tree and the red-black tree. It uses a seeded random generator, so a failure can be replayed exactly.
import random
def keys_inorder(n, out):
if n is not None:
keys_inorder(n.left, out)
out.append(n.key)
keys_inorder(n.right, out)
return out
def fuzz(insert, delete, check, steps=500, key_range=60, seed=0):
rng = random.Random(seed)
root = None
model = set()
for step in range(steps):
k = rng.randrange(key_range)
if rng.random() < 0.6:
op = "insert"
root = insert(root, k)
model.add(k)
else:
op = "delete"
root = delete(root, k)
model.discard(k)
try:
check(root)
except ValueError as e:
raise AssertionError(
"seed=%d step=%d op=%s key=%d: %s" % (seed, step, op, k, e)
) from None
assert keys_inorder(root, []) == sorted(model), (
"contents differ at seed=%d step=%d" % (seed, step)
)
return rootTo test the real implementation, call fuzz(insert, delete, check_avl) with the functions from the AVL chapters. To prove the harness can catch a failure, run it on a plain BST that never rebalances:
def bst_insert(n, key):
if n is None:
return Node(key)
if key < n.key:
n.left = bst_insert(n.left, key)
elif key > n.key:
n.right = bst_insert(n.right, key)
update(n)
return n
def bst_delete(n, key):
if n is None:
return None
if key < n.key:
n.left = bst_delete(n.left, key)
elif key > n.key:
n.right = bst_delete(n.right, key)
else:
if n.left is None:
return n.right
if n.right is None:
return n.left
s = n.right
while s.left:
s = s.left
n.key = s.key
n.right = bst_delete(n.right, s.key)
update(n)
return n
try:
fuzz(bst_insert, bst_delete, check_avl)
except AssertionError as e:
print("caught:", e)This prints a line starting caught: seed=0 step=, followed by the step, operation, key and the imbalance message. The tree is a correct BST with correct heights, and the validator still rejects it, because it is not balanced. That is the failure ordinary search tests cannot see.
Checking the height bound
The shape rules should imply a logarithmic height. You can test the consequence directly. This catches a different class of mistake, where the validator is too weak, for example because it forgot a rule.
For an AVL tree, the sparsest tree of height h has min_nodes(h) nodes, so a valid tree with n nodes and height h must satisfy n >= min_nodes(h). For a red-black tree, height is at most 2 * log2(n + 1).
import math
def count(n):
return 0 if n is None else 1 + count(n.left) + count(n.right)
def depth(n):
return 0 if n is None else 1 + max(depth(n.left), depth(n.right))
def check_rb_height(root):
n, h = count(root), depth(root)
assert h <= 2 * math.log2(n + 1), "height %d too large for %d nodes" % (h, n)
# The three-node tree from the red-black validator example:
class RBNode:
def __init__(self, key, color, left=None, right=None):
self.key, self.color, self.left, self.right = key, color, left, right
check_rb_height(RBNode(2, "B", RBNode(1, "R"), RBNode(3, "R"))) # 2 <= 4
print("height bound holds")In the fuzz harness, wrap the two checks in one function, such as lambda r: (check_rb(r), check_rb_height(r)), and pass that as check.
Practical limits and edge cases
- Cost. Each validation is O(n), so a test with n operations costs O(n²). That is fine for a few hundred operations. For large runs, validate every k-th step and keep the model comparison on a schedule too.
- Recursion depth. The recursive validators hit Python's recursion limit on a degenerate tree of about a thousand nodes. That is acceptable here, because a failing balanced-tree test is already a failure. If you want a readable message instead of a
RecursionError, keep key ranges small. - Key range. A small key range such as 60 makes deletions of present keys, deletions of absent keys and repeated inserts common. A huge range makes almost every delete a no-op.
- Operation mix. Include phases that insert in sorted order, insert in reverse order and delete everything. Sorted runs are where rotations fire constantly. Deleting down to an empty tree checks the
Noneroot. - Reproducibility. Always print the seed. A failure you cannot replay is much harder to fix.
- Intermediate states. Validators are meant to run between operations. During an insertion, the tree is legitimately broken for a moment, so never call the validator from inside
insert. - Property-based tools. A library such as Hypothesis can generate and shrink operation sequences for you. The idea is the same: random operations, an invariant check after each, and a model for the contents.
Exercise
A colleague's validator checks that each node's left child key is smaller and its right child key is larger, and that heights differ by at most 1. Describe a tree that it accepts but that is not a valid AVL tree, and say what change fixes the validator.
Show answer
Take root 5 with left child 3, and give 3 a right child 6. Every parent-child comparison passes (3 < 5, 6 > 3), and the heights are balanced, but 6 is in the left subtree of 5 and is larger than 5, so the ordering invariant is broken. Fix it by passing an open interval (lo, hi) down the recursion, so each node is compared with the bounds set by all its ancestors: the left child gets (lo, n.key) and the right child gets (n.key, hi).
Exercise
Your randomized test of a red-black tree passes 10,000 steps, but you have not run any test that deletes keys that are absent from the tree. Why might this leave a bug hidden, and how do you adjust the harness?
Show answer
Deleting an absent key exercises the search path without removing a node, so code that wrongly rebalances, recolors or changes the root on a no-op delete is never reached. Use a small key range relative to the number of steps, as in the harness above, so that many deletes target absent keys and many inserts hit duplicates. Compare the tree with the model after each step to confirm nothing changed.