Writing

Testing Fork Choice in an Executable Spec: My Work on leanSpec

Reading time: 8 minutes

Between March and April 2026 I contributed seven merged pull requests to leanEthereum/leanSpec, the Python specification for Lean Ethereum. Most of them were fork choice tests. One was a refactor of the QUIC transport, and one added unit coverage for the validator registry and service.

None of this is glamorous work. Still, it taught me more about consensus than most code I have written, because a test in an executable spec has to be right in a way that a test in an application does not. This post covers what I built, why each piece matters, and what I took away from it.

What leanSpec is

The README describes leanSpec as “the Lean Ethereum protocol specifications and cryptographic subspecifications.” Two properties make it different from a prose spec:

  • It runs. The fork choice store, state transition, networking and validator logic are real Python. You can step a Store forward in time and inspect it.
  • It produces test vectors. Tests are written as pytest “fillers”. Running uv run fill --fork=... --clean executes them against the spec and writes fixtures that other client implementations consume.

That second property is the one that matters for client diversity. In my earlier essay on client diversity incentives versus coordination I called this “spec-driven convergence”: independent teams can write clients in different languages and still agree, because they are all checked against the same vectors. A missing vector is a place where two clients can quietly disagree. A wrong vector is worse, because it teaches every client the same mistake.

Fixing tests before adding them

My first two PRs were small corrections, and they set the tone for the rest.

#480 fixed test_equal_weight_forks_use_lexicographic_tiebreaker, and #481 fixed test_head_with_deep_fork_split. Both tests built two competing forks that reused the same slots: fork A at slots 2 and 3, and fork B also at slots 2 and 3.

That is not a valid chain in leanSpec. Proposer selection is round-robin:

def is_proposer_for(self, slot: Slot, num_validators: Uint64) -> bool:
    return int(slot) % int(num_validators) == int(self)

One slot maps to exactly one proposer, so two honest blocks at the same slot cannot exist. As I wrote in the #480 description, multiple blocks per slot “would be rejected before state transition.” The fix moved fork B to slots 4 and 5 and rebalanced the attestations so both forks still end with equal weight when the last block lands:

# Fork B: second block, carrying attestation for fork_b_4 (weight = 1)
# Both forks now have equal weight, so the tiebreaker selects the head
BlockStep(
    block=BlockSpec(slot=Slot(5), parent_label="fork_b_4", label="fork_b_5", ...),
    checks=StoreChecks(lexicographic_head_among=["fork_a_3", "fork_b_5"]),
),

The lesson I took: a test can pass and still describe an impossible world. If a client team ports that vector, they either have to accept an invalid chain or mark the vector as broken. Neither is good for convergence.

Why the tiebreaker has to be boring

The tiebreaker test exists because LMD-GHOST needs a deterministic answer when two children carry the same weight. In leanSpec the rule is one line inside _compute_lmd_ghost_head:

# Choose best child: most attestations, then lexicographically highest hash
head = max(children, key=lambda x: (weights[x], x))

The tuple key does the work. Weight first, then the block root as a byte string. Every client sees the same roots, so every client picks the same head.

The alternatives look harmless and are not. “First block received” depends on network arrival order, which differs per node. “Lowest slot” can still tie. Any rule that depends on local state lets two honest nodes pick different heads from identical inputs, and they then attest to different blocks. A test that pins the lexicographic rule is a cheap way to make sure no implementation drifts toward one of those local rules.

The five-interval slot

The bigger piece of work was #607, which closed three issues (#555, #556, #557) about tick behaviour. In leanSpec a slot is divided into five intervals, and the store does something different at each one. This is how tick_interval reads:

current_interval = store.time % INTERVALS_PER_SLOT

if current_interval == Interval(0) and has_proposal:
    store = store.accept_new_attestations()
elif current_interval == Interval(2) and is_aggregator:
    store, new_aggregates = store.aggregate()
elif current_interval == Interval(3):
    store = store.update_safe_target()
elif current_interval == Interval(4):
    store = store.accept_new_attestations()
flowchart LR
    I0["Interval 0: proposal; accept attestations only if has_proposal"]
    I1["Interval 1: votes propagate; no store action"]
    I2["Interval 2: aggregators build proofs"]
    I3["Interval 3: update safe target"]
    I4["Interval 4: new pool moves to known pool"]
    I0 --> I1 --> I2 --> I3 --> I4 --> I0

Fork choice bugs often hide here. An attestation that moves from “new” to “known” one interval too early changes the head one interval too early. Over a network, that is the difference between validators agreeing and validators splitting.

The existing TickStep only accepted a Unix timestamp, which the fixture converted to an interval count. That works for coarse tests but makes exact interval semantics awkward to express. I extended the step type so a test can target the store’s interval clock directly, and can say whether interval 0 sees a proposal:

class TickStep(BaseForkChoiceStep):
    time: int | None = None
    interval: int | None = None
    has_proposal: bool = False

    @model_validator(mode="after")
    def validate_target(self) -> "TickStep":
        """Require exactly one time target representation."""
        if (self.time is None) == (self.interval is None):
            raise ValueError("TickStep requires exactly one of time or interval")
        return self

The validator was a deliberate choice. Allowing both fields would invite tests where the timestamp and interval disagree, and the fixture would silently pick one. Making it an error keeps the vector format unambiguous for whoever consumes it.

The three new tests in test_tick_system.py cover:

  • A full slot, interval by interval. An attestation gossiped after interval 2 lands in “new”, interval 3 recomputes the safe target from it, and interval 4 migrates it to “known”.
  • Empty slots. Time advances across several slots with no blocks, and the head does not move.
  • Interval 0 depends on the proposer. At slot 3 interval 0, validator 0 is not the proposer, so the attestation stays in “new”. At slot 4 interval 0 with has_proposal=True, it moves to “known” immediately instead of waiting for interval 4.

The last one is the subtle case. A client that always accepts attestations at interval 0, or never does, will pass most other tests and still diverge here.

I also added safe_target_slot and safe_target_root_label to StoreChecks, so later tests could assert on the safe target by label instead of by raw root.

The safe target and the 2/3 line

The safe target is the deepest block with supermajority support. Validators use it to choose what to attest to. In update_safe_target it is the same LMD-GHOST walk as the head, but with a threshold:

min_target_score = -(-num_validators * 2 // 3)  # ceiling of 2N/3

safe_target = self._compute_lmd_ghost_head(
    start_root=self.latest_justified.root,
    attestations=attestations,
    min_score=min_target_score,
)

Inside the walk, any child below min_score is dropped from the tree before the descent starts. If no child of the justified root clears the bar, the safe target stays at the justified root.

#623 (closing #558) added six fillers in test_safe_target.py, each aimed at one property:

Test Property
advances with supermajority weight 4 of 6 votes moves the safe target
does not advance below supermajority 3 of 6 keeps it at genesis
advances incrementally along the chain latest vote per validator wins
follows heavier fork on split the 2-of-6 fork is pruned, the 4-of-6 fork is followed
is conservative relative to LMD-GHOST head head and safe target can differ
uses merged pools at interval 3 “new” and “known” are both counted

Two of these are worth explaining.

The conservative test uses 9 validators, with 6 voting for block_2 and 3 voting for its child block_3. LMD-GHOST has no threshold, so the head goes to block_3. The safe target walk prunes block_3 because 3 is below 6, so it stops at block_2. That gap is the point of having a safe target at all, and a client that reuses its head computation without the threshold would get it wrong.

The merged pools test exists because of a design detail in the spec. At interval 3, migration has not run yet, so some attestations sit in “known” (for example, the proposer’s own attestation bundled in the block) and some in “new” (fresh gossip). The spec merges both. The docstring notes that this is more conservative than the Ream implementation, which uses only the “new” pool. A vector where neither pool alone reaches the threshold, but the merged view does, turns that design decision into something a client can be checked against.

#639 (closing #559) then reworked the below-threshold test into a parametrized one, with 2 of 6 attesters as the far-below case and 3 of 6 as the tight boundary, one vote short:

@pytest.mark.parametrize(
    "num_attesters",
    [
        pytest.param(2, id="two_of_six"),    # far below the threshold of 4
        pytest.param(3, id="three_of_six"),  # one vote short: the off-by-one edge
    ],
)

The boundary case is the one I care about. A <= where there should be a < in the prune condition passes a far-below test and fails this one. The PR also used GossipAggregatedAttestationStep rather than individual attestations, because update_safe_target reads the aggregated payload pools, and routing through interval 2 aggregation would have mixed in a concern the test was not about.

Validator registry and service coverage

#502 (closing #493) was ordinary unit testing on modules that had none. The PR description lists validator/registry.py and validator/service.py at 0% coverage before and reports at least 90% and 100% after.

The part I thought hardest about was _sign_with_key, which advances one-time-signature keys before signing. As I noted in the PR, it is “the most security-sensitive path: a bug here could exhaust OTS keys or reuse them.” The tests cover no advance, one advance, several advances, persistence of the advanced key back into the registry, and isolation between the attestation key and the proposal key.

One practical note from that PR: ValidatorService is a @dataclass(slots=True), which prevents patching methods on an instance. All mocks had to patch the class instead. Small thing, but it cost me time before I understood it.

The QUIC refactor

#553 (closing #552) is the only change I made to non-test spec code, and it deliberately changed no behaviour.

connection.py defined QuicStream and its error types, and also needed QuicStreamAdapter. stream_adapter.py needed QuicStream. That is a cycle, and it had been worked around with a deferred import at the bottom of connection.py:

# circular import between connection.py and stream_adapter.py, then move this
# import back to the top of the file. See .../issues/552
from .stream_adapter import QuicStreamAdapter  # noqa: E402

I moved QuicStream, QuicStreamResetError and QuicTransportError into a new quic/stream.py. Both modules now import from it, the deferred import is gone, and connection.py keeps re-exports so existing imports still resolve:

# connection.py
from .stream import QuicStream, QuicTransportError
from .stream_adapter import QuicStreamAdapter

# stream_adapter.py
from .stream import QuicStream

Why bother in a spec? Because people read spec code to learn how the protocol works. A # noqa: E402 at the end of a file signals that the module structure is fighting the domain. Once streams live in their own module, the layering is obvious: streams at the bottom, the adapter above them, connections on top. The trade-off was a larger diff for zero functional change, and I accepted that by keeping the move mechanical and the re-exports in place.

What I learned

  • A spec test is a claim about the protocol. In an app, a wrong test wastes time. In a spec, it propagates to every client that consumes the vector.
  • Time is part of the state. Most of the interesting fork choice behaviour depends on which interval you are in, not just which blocks and votes exist. Tests need to express time at interval precision.
  • Determinism is a feature. The lexicographic tiebreak and the strict 2/3 boundary exist so that honest nodes with the same inputs reach the same answer. Tests should target exactly those edges.
  • Small, scoped PRs get merged. The maintainers asked for one PR per test case on #470, and I split later work the same way. It made review easy and kept each change readable.
  • Refactors in a spec are about readability. The QUIC change mattered because the code is also documentation.

Takeaways

  • Fork choice needs precise tests for timing, thresholds and tiebreaks, because those are where independent clients diverge.
  • Test vectors from an executable spec are what turn client diversity from a risk into a strength.
  • Fix invalid tests before adding new ones. An impossible scenario is a silent bug in the vector set.
  • Keep spec refactors behaviour-neutral and backward compatible, and say so in the PR.