Skip to content

fix(explorer-api): decide the canonical chain from the listener's ordered blocks, not by height - #113

Draft
alejoamiras wants to merge 31 commits into
follow-chain-by-hash-listener-streamfrom
follow-chain-by-hash-api-canonical
Draft

alejoamiras wants to merge 31 commits into
follow-chain-by-hash-listener-streamfrom
follow-chain-by-hash-api-canonical

Conversation

@alejoamiras

@alejoamiras alejoamiras commented Nov 27, 2026 •

Copy link
Copy Markdown
Collaborator

Part 4 of 6 of the stack that makes the explorer follow the L2 chain by block hash. Closes #98. Closes #102. Part of #99 and #100.

The API decided which block is canonical by height. After a prune it orphaned live blocks (#98), deleted blocks to resolve tx conflicts, and derived /l2/reorgs from orphan marks on block rows (#102). It now takes the chain from the listener's ordered blocks (part 3), links blocks by archive root, never deletes a block, and writes one reorg record for each chain change that demotes blocks.

What changed

  • src/svcs/database/controllers/l2block/canonical.ts (new) makes every change to which blocks are canonical. Each change runs in one transaction under a per-network advisory lock (withChainLock, with lock_timeout 10 s). A child links to its parent when its last_archive.root is the parent's archive.root, one height apart, on the same rollup version.
    • applyOrderedBlock(incoming, proposedTip, heartbeat): an ordered block is canonical at its height. It replaces the block there, with that block's linked descendants, and every other canonical holder of its txs, with theirs. It brings back its stored ancestors, asks for the heights below it that this leaves empty, and demotes every canonical block above proposedTip.
    • applyCatchupBlock(incoming, finalized, heartbeat): a catch-up block only fills an empty height below the canonical head. It joins when the canonical chain above descends from it. With finalized, it also joins when that link is undecided and the canonical block below, if any, is its parent.
    • Walks stop at WALK_BOUND (10,000) steps, and a walk down asks for the height where it stopped. More than 10,000 canonical blocks above a tip throws, changing nothing.
    • Every change that demotes blocks writes an l2_reorg record listing them, with the hash of the incoming block whose change it was and whether that block came ordered or as a catch-up block. A record is marked revived once every block it lists is canonical again.
    • Each change demotes a height's canonical block before it promotes another there. A unique index now holds one canonical block per height and rollup version, so a change that would break this fails: its error propagates and the bus redelivers the message.
    • The txs of demoted blocks are listed as dropped (orphaned). The txs of blocks that become canonical leave the pending and dropped lists.
    • orphan_hasOrphanedParent is kept current for the off-chain blocks a change touches.
    • A block that would become canonical while another canonical block holds one of its txs is not applied, and is logged as SKIPPED_BLOCK_TX_CONFLICT.
    • It heartbeats every 500 walk steps, before each write of at most 1,000 rows, and before each tx effect and contract row it writes.
  • src/events/received/on-block/index.ts: the block handler ignores blocks without ordered ("not from the ordered stream") and passes ordered.proposedTip; the catch-up handler passes finalized. Post-commit hooks run only for canonical blocks.
  • l2block/store.ts: store(dbTx, block, orphanTimestamp) stores a block in the change's transaction; writeTxEffect writes one effect, or moves it from an off-chain block.
  • l2contract/store.ts: storeBlockContracts writes a canonical block's contract rows in its transaction, each in a savepoint. on-block/contracts.ts parses them first (parseBlockContracts).
  • l2Tx/remove-pending-and-dropped.ts runs in the change's transaction, with heartbeats.
  • l2block/missing-ranges.ts: recordRepairHeights opens reorg_repair rows for the heights a change asks for; fulfilRepairHeight closes one in the change that makes its block canonical.
  • l2block/get-block.ts: getReorgs serves /l2/reorgs from the records: each active record, with the blocks it lists that are still off the chain. A block that several records list shows only under the newest. The response keeps its shape, but its meaning changes: an entry's count and lowest block shrink as its blocks return to the chain, and an entry disappears once all of them have. The schema's descriptions say so (packages/types/src/aztec/reorg.ts).
  • Removed: on-block/reorg-handler.ts, l2block/delete.ts, l2block/orphan.ts and handleDuplicateBlockError. No code path deletes a block any more.
  • Migrations:
    • 0038_block_link_indexes.sql: indexes on archive.root and last_archive.root; a nullable l2_tip_boundary_mismatch.rollup_version; a partial index on unresolved mismatches (l2_network_id, height).
    • 0039_l2_reorg.sql: l2_reorg (network, rollup version, cause_hash and cause_kind, observed_at, revived_at) and l2_reorg_block (reorg id, height, hash), with an index on the hash. cause_hash is the hash of the incoming block whose change wrote the record, and cause_kind is ordered or catchup. A record's lowest block and count are not stored: getReorgs derives them from l2_reorg_block.
    • 0040_one_canonical_block_per_height.sql: the unique partial index l2block_one_canonical_per_height_idx on "l2Block"(version, height) WHERE orphan_timestamp IS NULL, also declared in the Drizzle schema.

How it was tested

  • tests/integration/chain-head.integration.test.ts (new, 32 tests, real Postgres):
    • the ordered rule: the replaced block, its linked descendants and every block above the tip leave in one record, which names the ordered block that wrote it; an already-canonical block changes nothing; a replay and a flip end on the listener's chain with one active record; the live chain above a gap is never demoted for a block below it;
    • the catch-up rule: a finalized catch-up block at a held height stays off the chain until its ordered copy arrives; one at an empty height joins only when the chain above descends from it; one above the head stays off; a block below a joined catch-up block that is not its parent is demoted, in a record that names the catch-up block, and its parent requested; history fills from block 1 with finalized catch-up blocks;
    • the next ordered block puts back a block that a stale catch-up undid, listing one reorg;
    • repairs: catch-up blocks that join below an ordered block far above the head request each parent in turn, down to the old chain; a finalized one that joins with its link from above undecided requests the height below it; a stale post-commit hook keeps a repair open;
    • records: a partly revived record lists only its blocks still off the chain, and a block that died twice is listed once; a live block the old code orphaned comes back when it arrives ordered, without demoting the chain above it;
    • stale canonical holders of a block's txs are demoted above and below it, and the heights this empties are requested;
    • a parent lookup that finds two blocks counts as a missing parent; a block event not from the ordered stream is ignored;
    • the unique index: with a canonical row at a height that no chain read sees, an ordered block there fails on l2block_one_canonical_per_height_idx, the block handler rethrows the error, and nothing of the block is kept. With 0040 emptied, the same test fails;
    • the block and catch-up consumers serialize on the chain lock; heartbeats while settling and before each tx effect; a failed heartbeat rolls back the block with its effects and contract rows;
    • bounds: a walk stops at the bound, and a walk down requests the height below it; more blocks above a tip than the bound throws and changes nothing; a lock wait over 10 s rethrows.
  • tests/integration/late-replacing-block.integration.test.ts (new, 3 tests): the replacing chain's stored blocks stay canonical when its block at the replaced height arrives after them, and a block's txs stop being listed as dropped once it is canonical again. One case, still requests a replaced height after the next tips validate at other heights, is marked it.fails here and passes with part 5.
  • tests/integration/block-reorg.integration.test.ts (rewritten; it asserted that the replaced block is deleted): a replacing block takes a tx it includes again, and the replaced block stays stored; a two-block reorg is recorded once, and the redelivery of its second block resolves; a block whose tx its canonical parent holds is skipped.
  • tests/unit/chain-write-heartbeats.test.ts (new): the per-row write loops heartbeat, and a failed heartbeat aborts the block.
  • open-gap.integration.test.ts and open-gap-scheduler.test.ts: a repair row is requested while its block is present, until a block message there fulfils it; recordRepairHeights writes each height once.
  • rollup-version-scoping.integration.test.ts: a reorg demotes only its own rollup version's blocks.
  • Removed with their code: tests/unit/block-tx-conflict.test.ts and tests/unit/duplicate-block-error.test.ts. The test block builder gives each block its own archive and a parent link (tests/integration/support/blocks.ts, support/chain.ts).
  • yarn lint is clean. yarn test passes 451 tests, with 1 skipped, and yarn test:integration passes 174, besides the expected failure above.

Migration and rollout

  • 0038, 0039 and 0040 only add indexes, a nullable column and two tables. Nothing is backfilled.
  • 0038 and 0040 build their indexes without CONCURRENTLY, since the migrations run in one transaction. Writes to archive, last_archive and l2Block wait until the migration commits; reads do not.
  • 0040's unique index builds at release. It fails, and the API does not start, if a rollup version has two canonical blocks at one height: SELECT version, height FROM "l2Block" WHERE orphan_timestamp IS NULL GROUP BY version, height HAVING count(*) > 1 must return no row first.
  • A rollback to the previous API version drops the index first (DROP INDEX IF EXISTS "l2block_one_canonical_per_height_idx";): the previous code never ran against it.
  • /l2/reorgs starts empty after the upgrade: it lists only the chain changes this version applies. Rows the previous version wrote keep their orphan marks until a chain change reaches them. So does a stale block it left canonical, since a catch-up block fills only an empty height.
  • This API needs the ordered stream from part 3, since it ignores blocks without ordered. Release the listener first, then this API right after.
  • Release and revert parts 4 and 5 together. Part 4 alone leaves re-registered contracts on their dead blocks, dropped-tx writes outside the chain lock, and the start-up dropped-tx sweep on its old rule.
  • Roll the API back before the listener. Once the index is dropped, the previous API runs on the new schema and ignores the new tables and column. After a rollback it can delete a dead block whose tx a canonical block includes again: the block's hash stays in its l2_reorg_block row, but its page is gone.

🤖 Generated with Claude Code

alejoamiras and others added 30 commits November 27, 2026 19:40
Link lookups match a block's last archive root to its parent's archive
root; both columns get an index, as only the foreign keys had one.
l2_tip_boundary_mismatch gains a nullable rollup_version and an index
for unresolved rows.

l2_reorg holds one row per demotion of canonical blocks, with the
lowest demoted block, the count removed, the time it was applied and
the time every listed block was canonical again; l2_reorg_block lists
the demoted blocks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… link

Every built block shared one archive and one last archive, so no two
built blocks linked. As in 6fd18994, each now gets an archive of its own
(or a given one), and `parent` makes its last archive the parent's
archive. `buildChain` builds linked runs, and `orderedEvent` and
`catchupEvent` build the two block messages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A block from the ordered stream carries its pass's tip and is canonical
at its height. It demotes the block it replaces with that block's linked
descendants, and any canonical holder of its txs above it with theirs;
it brings back its stored ancestors, demoting their competitors and
clearing the height of a missing parent; and it demotes every canonical
block above the tip. Catch-up blocks only fill empty heights: when the
canonical chain above descends from them, or, when final, on the
canonical parent below. They never demote. Block events without
`ordered` are ignored.

Each change runs in one transaction under a per-network advisory lock
with a 10 s lock timeout, and the block's rows, tx effects and contracts
are written inside it. Walks stop after 10,000 steps and heartbeat every
500; more than 10,000 canonical blocks above a tip throws. A tx effect
held by an off-chain block moves to the canonical one, and off-chain
blocks are kept, not deleted. Each demotion writes one `l2_reorg`
record, marked revived once all its blocks are canonical again, and
`/l2/reorgs` is computed from the records. A block made canonical
without its own message gets a `reorg_repair` gap row, requested until
its message attaches its txs.

The height-based reorg handler, orphaning and block deletion are gone,
with their unit tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The cases of 6fd18994, on the new rules: the stream's blocks go in as
ordered blocks and the late copy as a catch-up block. A replacing chain
stays canonical when its block at the replaced height arrives after its
children, and a block's txs stop being listed as dropped once it is
canonical again. The third case, a replaced height still requested
after the next tips validate elsewhere, is still marked as failing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…quests

One case per rule of ordered and catch-up blocks, each on its own
rollup version: replacement and the tip, replays and flips, gaps, final
catch-up blocks, walks that bring blocks back, records and their
revival, tx holders above a gap, ambiguous parents, unordered events
and concurrent consumers. The bound cases run on bare chains inserted
in bulk: a 10,000-step walk keeps its partition in a consumer group
whose session is shorter than the walk, and rolls back when a heartbeat
fails; more canonical blocks above a tip than the bound throw; a lock
wait over 10 s rethrows. The gap scheduler requests a repair row while
its block is present, until a block message fulfils it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Prettier's own output for the canonical chain module, its reorg schema,
its test files and the contract store. No other change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The writes a change makes in statements of up to a thousand rows
(demotions, reorg records, dropped txs, orphan flags, repair requests) ran
without a heartbeat, so a change that demoted thousands of blocks could
outlast the consumer's session after its walk ended. Each such statement
now heartbeats first; KafkaJS sends at most one heartbeat per interval, so
the extra calls cost nothing.

Open-gap rows are now upserted in one statement per call instead of one per
row, so a change's repair requests take one statement per thousand heights.
The scheduler's unit fake takes multi-row inserts and counts statements.

The rebalance test reads its counters only once the broker holds the
offset commit, so a member lost before the commit is counted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
An ordered block that includes a tx again, held by a stale canonical block
below it, was skipped when its missing parent stopped the ancestor walk
before that block: the tx conflict rolled the change back and the message
was acknowledged. Every other canonical block of the version up to the tip
that holds one of its txs now leaves the chain with its linked run, also
when the block is already canonical, and every height below the block that
this leaves without a canonical block is requested.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…the chain

With no canonical block above it, a final catch-up block whose parent was
the head joined the chain, so catch-up could extend the chain past the last
ordered pass. A catch-up block now joins only below a canonical block.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ed from above

A catch-up block that the canonical chain above descends from joined
without looking below it: it could sit on a canonical block that is not its
parent, and a backward repair stopped after one attach. It now carries that
chain's authority below its height, as an ordered block does: other
canonical holders of its txs there leave with their linked runs, its stored
ancestors come back, the block below that is not its parent leaves, and its
parent and every height left empty are requested. Such a join can now
demote blocks and record a reorg.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…off the chain

The parent flag was refreshed only around the blocks a change moved, so a
block stored off the chain under an off-chain parent kept `false`. The
block a change stores and leaves off the chain is now refreshed with them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…canonical

The post-commit height hook closed a repair whenever any block stood at its
height, so a delayed hook could close a repair that a later change opened
for another block. A repair now closes inside the change whose block
message made the block at its height canonical, and the hook leaves repairs
alone. Repair rows carry no rollup version, so a block of another version
at that height still closes one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…test

The test also passed without the lock whenever the two transactions ran
one after the other. It now holds the chain lock, waits until both
consumers queue on it with neither finished, then releases it and checks
that the height ends with one canonical block.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The dropped- and pending-tx handlers write without the chain lock, and
lock_timeout bounds every lock wait in the transaction, not only the
lock's own. Drops two summaries that restated their code, and the
late-replacing test's note on its expected failure, keeping the fixture's
height constraint.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…h-up

A catch-up block that links to a stale canonical block above a gap can
undo an ordered block: it brings the replaced block back and demotes the
ordered one. The next ordered block puts it back. The test pins both
steps, and that /l2/reorgs then lists only the record rooted at the
replaced block.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…sting it

A walk that brought back WALK_BOUND blocks asked for the height below the
last one but left that height's canonical block in place, so the parent
the request brought back could never join there. The bound now clears
the height first, as a missing parent does.

The test's bulk chain can now be inserted off the chain and returns its
top block as a parent for a built block.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…a repair

Repair rows carry no rollup version, so a canonical block of an older
version at a repaired height closed a newer version's repair, and the
txs a walked block had moved stayed dropped. A block now closes a repair
only while no newer version is stored. The check reads max(version),
one entry of l2block_version_idx: a NOT EXISTS on newer versions is
planned as a seq scan past every older version's row, inside the chain
lock.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ale holders below

A block a walk made canonical gets its txs back from its own message,
the catch-up its repaired height asks for. A canonical block of another
chain below it could still hold one of those txs: attaching them threw
TxConflict, the change rolled back, and the repair was asked for again
without end. A canonical block with a canonical child linked to it now
has the chain above's authority below its height, as a catch-up joined
from above has: its catch-up demotes the holders of its txs below it,
with their linked runs, and asks for the heights that leaves empty.
Without such a child it is handled as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The test hands each catch-up block to the handler itself, so its name
says what each joining block opens, not that repairs are walked back
one per attach.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Inside the chain lock, removePendingAndDroppedTx runs one UPDATE per
pending tx and storeBlockContracts one savepoint per contract row, with
no heartbeat between them. Both now heartbeat before each row. In
storeBlockContracts the heartbeat sits outside the row's error handling,
so a failed heartbeat aborts the change instead of being logged as a
failed row.

The settlement heartbeat test counted the beats of demoting the bound,
which come before settlement, so it passed with settlement's heartbeats
removed. Its own test now settles a block that walks and demotes
nothing, where every beat comes from settlement; the bound test keeps
only the bound.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The doc said a catch-up block never replaces a canonical block. One the
chain above descends from demotes, below its height, the other holders
of its txs and the blocks its stored ancestors come back in place of;
only the canonical block at its own height is never replaced.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…e version

This reverts commit 25686c42 ("fix(explorer-api): keep an older rollup
version's block from closing a repair").

Rollup versions are not ordered numbers: the registry maps an index to
an arbitrary version. After an upgrade to a numerically lower version,
the max(version) check kept the current version's repairs open for good,
and an older version's block could still close them. A repair closes
again in the change that makes any block at its height canonical. Its
test goes with it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A final catch-up block whose link from above is undecided joins when
the canonical block below, if any, is its parent. With no canonical
block below, it joined over an empty height and asked for nothing, so
the gap waited for the cadence scan. It now records a repair for that
height, above height 1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Attaching a block's tx effects ran with no heartbeat: two statements
an effect plus one per public data write, for every effect of the
block, inside the chain lock. The change now heartbeats before each
effect it writes; the protocol caps public data writes at 64 a tx, so
that bounds the statements between two heartbeats.

A second test fails a heartbeat after a block's effect and class row
are written, and finds the block, the effect and the class row gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The applyCatchupBlock doc had grown a clause at a time. It now says
which heights a catch-up block fills, the authority it carries below its
height when linked to the chain above, that an already-canonical block
with a linked canonical child has the same, and when a final block also
joins.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…catch-up block's finalized

The block handler validates `ordered.proposedTip` and passes it to
`applyOrderedBlock` as its ceiling; the catch-up handler passes
`finalized`. The test event builders and the chain tests use the new
field names.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…le root

`l2_reorg` drops `root_height`, `root_hash` and `removed_count`: nothing
read them, and `getReorgs` derives the lowest block and the count from
`l2_reorg_block`. It gains what cannot be derived later: `cause_hash`,
the hash of the incoming block whose change wrote the record, and
`cause_kind`, whether that block came on the ordered stream or as a
catch-up block. Both are NOT NULL; `cause_kind` is typed as
`"ordered" | "catchup"`.

Every record is written by `apply`, for one incoming ordered or
catch-up block, so each has a cause. The schema's TSDoc now says catch-up
blocks write records too. Migration 0039 has not shipped and changes in
place.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… index

Migration 0040 adds `l2block_one_canonical_per_height_idx`, a unique
partial index on `"l2Block"(version, height) WHERE orphan_timestamp IS
NULL`, also declared in the Drizzle schema. Until now only the chain
code held the rule.

Every write that makes a block canonical is `promote` in canonical.ts,
and each caller first demotes the canonical blocks at that height in the
same transaction; `store` inserts blocks off the chain. A violation is a
unique violation from `promote`'s UPDATE: it propagates out of the chain
transaction and the handler, so the message is redelivered. No catch on
that path reads a 23505 as a duplicate.

A new chain test hides a canonical row from the chain reads and delivers
an ordered block at its height: the database refuses it, the handler
rethrows the refusal, and nothing of the block is kept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
`/l2/reorgs` now serves records whose blocks can return to the chain:
an entry's count and lowest block cover only its blocks still orphaned,
and an entry disappears once all of them are canonical again. The
schema's descriptions say so, and the OpenAPI spec carries them. The
response shape is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…T EXISTS

With IF NOT EXISTS, an index of the same name and another definition
would let migration 0040 pass without enforcing one canonical block per
rollup version and height. Without it, such an index fails the migration.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
In zod 4, `.extend()` returns a schema without the base schema's
description, so the OpenAPI document described a reorg record's two
fields but no longer the record itself. The response schema now carries
the record's metadata over, and `/l2/reorgs` documents all three again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@alejoamiras
alejoamiras added this pull request to stack #116 November 27, 2026 20:45
@alejoamiras alejoamiras changed the title follow chain by hash api canonical fix(explorer-api): decide the canonical chain from the listener's ordered blocks, not by height Nov 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant