Repository navigation
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
Draft
alejoamiras wants to merge 31 commits into
alejoamiras wants to merge 31 commits into
Conversation
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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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/reorgsfrom 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, withlock_timeout10 s). A child links to its parent when itslast_archive.rootis the parent'sarchive.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 aboveproposedTip.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. Withfinalized, it also joins when that link is undecided and the canonical block below, if any, is its parent.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.l2_reorgrecord 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.orphaned). The txs of blocks that become canonical leave the pending and dropped lists.orphan_hasOrphanedParentis kept current for the off-chain blocks a change touches.SKIPPED_BLOCK_TX_CONFLICT.src/events/received/on-block/index.ts: the block handler ignores blocks withoutordered("not from the ordered stream") and passesordered.proposedTip; the catch-up handler passesfinalized. Post-commit hooks run only for canonical blocks.l2block/store.ts:store(dbTx, block, orphanTimestamp)stores a block in the change's transaction;writeTxEffectwrites one effect, or moves it from an off-chain block.l2contract/store.ts:storeBlockContractswrites a canonical block's contract rows in its transaction, each in a savepoint.on-block/contracts.tsparses them first (parseBlockContracts).l2Tx/remove-pending-and-dropped.tsruns in the change's transaction, with heartbeats.l2block/missing-ranges.ts:recordRepairHeightsopensreorg_repairrows for the heights a change asks for;fulfilRepairHeightcloses one in the change that makes its block canonical.l2block/get-block.ts:getReorgsserves/l2/reorgsfrom 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).on-block/reorg-handler.ts,l2block/delete.ts,l2block/orphan.tsandhandleDuplicateBlockError. No code path deletes a block any more.0038_block_link_indexes.sql: indexes onarchive.rootandlast_archive.root; a nullablel2_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_hashandcause_kind,observed_at,revived_at) andl2_reorg_block(reorg id, height, hash), with an index on the hash.cause_hashis the hash of the incoming block whose change wrote the record, andcause_kindisorderedorcatchup. A record's lowest block and count are not stored:getReorgsderives them froml2_reorg_block.0040_one_canonical_block_per_height.sql: the unique partial indexl2block_one_canonical_per_height_idxon"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):finalizedcatch-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 withfinalizedcatch-up blocks;finalizedone that joins with its link from above undecided requests the height below it; a stale post-commit hook keeps a repair open;l2block_one_canonical_per_height_idx, the block handler rethrows the error, and nothing of the block is kept. With0040emptied, the same test fails;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 markedit.failshere 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.tsandopen-gap-scheduler.test.ts: a repair row is requested while its block is present, until a block message there fulfils it;recordRepairHeightswrites each height once.rollup-version-scoping.integration.test.ts: a reorg demotes only its own rollup version's blocks.tests/unit/block-tx-conflict.test.tsandtests/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 lintis clean.yarn testpasses 451 tests, with 1 skipped, andyarn test:integrationpasses 174, besides the expected failure above.Migration and rollout
0038,0039and0040only add indexes, a nullable column and two tables. Nothing is backfilled.0038and0040build their indexes withoutCONCURRENTLY, since the migrations run in one transaction. Writes toarchive,last_archiveandl2Blockwait 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(*) > 1must return no row first.DROP INDEX IF EXISTS "l2block_one_canonical_per_height_idx";): the previous code never ran against it./l2/reorgsstarts 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.ordered. Release the listener first, then this API right after.l2_reorg_blockrow, but its page is gone.🤖 Generated with Claude Code