Skip to content

fix: keep dropped txs, tips, contract rows and cached reads on the canonical chain - #114

Draft
alejoamiras wants to merge 34 commits into
follow-chain-by-hash-api-canonicalfrom
follow-chain-by-hash-api-state
Draft

alejoamiras wants to merge 34 commits into
follow-chain-by-hash-api-canonicalfrom
follow-chain-by-hash-api-state

Conversation

@alejoamiras

@alejoamiras alejoamiras commented Nov 27, 2026 •

Copy link
Copy Markdown
Collaborator

Part 5 of 6 of the stack that makes the explorer follow the L2 chain by block hash. Closes #92. Closes #99. Closes #100.

With part 4 the API decides the canonical chain from ordered blocks. This part makes the state around the chain follow it: a tx counts as mined only while a canonical block holds it (#99), a tip mismatch stays open until its cause is gone (#100), contract rows move to the block that registers them on the chain, and cached reads end when the chain changes. It also carries #93's fix for #92: block statuses hold up to the checkpointed tip while the proposed block is on its way (statusTipHeights), and storing that block validates the tips again. #93 can close once this merges.

What changed

Explorer API:

  • Dropped and pending txs (on-dropped-txs.ts, on-pending-txs.ts): each tx is written in its own transaction under the chain lock, after a heartbeat. withChainLock moves to controllers/chain-lock.ts. A tx counts as mined only while a canonical block holds it (txEffectExists), checked in the same transaction. Write errors now propagate, so the message is redelivered. A pending tx that fails to parse is logged and skipped.
  • Start-up: removeMinedDroppedTxs replaces removeDroppedThatHaveTxEffects. In one statement under the chain lock, it deletes the dropped rows of txs a canonical block holds.
  • Tips (controllers/l2/tips.ts):
    • upsertTips validates and writes the tips under the chain lock;
    • every chain change that demotes or promotes a block revalidates the stored tips in its transaction, healthy or degraded (revalidateTips);
    • a tier at block 0 counts as valid;
    • an open mismatch resolves only when the canonical block at its height has the expected hash, a reorg record lists that hash, or it was last seen more than 24 h ago. Mismatches record their rollup version;
    • block statuses follow statusTipHeights: while only the proposed boundary block is missing, heights up to the checkpointed tip keep their status.
  • Repairs (l2block/missing-ranges.ts): gap discovery stops at the latest canonical height. buildTipBoundaryRepairRequest builds from unresolved mismatch rows instead of the tips' degradedReason: due windows only, least recently seen first, the mismatch height before its neighbors, each window within the request's block budget.
  • Contracts (l2contract/store.ts): a class, deployment or update registered again moves to the incoming block when its current block is off the chain, or when its own block is delivered again. Another canonical block keeps it. The verified artifact and deployment arguments stay.
  • Public calls (l2Public-call/store.ts): storePublicCallRequests skips duplicate rows, so a pending tx whose two public calls share their calldata is stored.
  • Tx effects (l2TxEffect/get-tx-effect.ts): reads by height come from canonical blocks only, and height 0 is a valid bound.
  • Cached reads: svcs/cache/chain-revision.ts keeps a chain revision in Redis, a random UUID with a 7-day TTL. Every applied block bumps it after its commit, and start-up bumps it, in archive mode too. Block, tx-effect and contract-instance reads (getOnChain) and every getLatest read include it in their cache keys (db-wrapper.ts).

Explorer UI:

  • Pending and dropped tx lookups answer null on a 404, so a refetch clears what they found before.
  • A block or tips frame refreshes the reorg lists and every open block, tx and contract instance query (CHAIN_QUERIES in hooks/websocket/message-callbacks.ts).
  • The block page lists the block's own txs. An orphaned block's page shows no index or fee, and notes where a tx mined again is listed.
  • The tx page shows only its selected status, and links the effect's block by hash. A tx whose effect only an orphaned block keeps shows as not mined, and a tx no lookup found shows no status.
  • The contract instance page shows whether its deployment is orphaned.

Also: a contract row whose savepoint fails with a transient database error (SQLSTATE classes 08, 40, 53, 57 and 58, or lock timeout 55P03, also as a query error's cause) rolls the block back for redelivery; a row that fails on its own data is still logged and skipped. An open tx page refetches its effect every 10 s while the effect is orphaned, and every 60 s once it is canonical or while no lookup has found the tx; until its effect is found, a pending tx's page polls every 5 s, as before. The block page's two queries refetch every 60 s. No websocket frame announces a catch-up block, so both pages poll. WALK_BOUND in canonical.ts now comes from CHAIN_WALK_BOUND in @chicmoz-pkg/message-registry, which also caps the listener's prune depth.

How it was tested

API:

  • tests/integration/pending-and-dropped.integration.test.ts (new, 4 tests): a dropped tx's write and the block that includes it serialize on the chain lock, so the tx ends mined; a tx counts as mined only while a canonical block holds it; a pending tx whose two public calls share their calldata is stored; the start-up sweep keeps a dropped tx and removes the dropped row of a mined one.
  • tests/unit/mempool-heartbeats.test.ts (new, 2 tests): the pending and dropped handlers heartbeat between txs, and each tx's lock waits for its heartbeat.
  • tests/integration/l2-tips-block-race.integration.test.ts (new, 5 tests): statuses up to the checkpointed tip hold while the proposed block is on its way; the tips count as valid once their block is stored; another hash at the proposed height keeps them degraded; a demotion degrades healthy tips, and the reorg record resolves the mismatch; tips are validated on the chain they are written against.
  • tests/integration/young-chain-tips.integration.test.ts (new, 1 test): the tips stay healthy while the proven and finalized tiers are at block 0.
  • tests/integration/late-replacing-block.integration.test.ts: a replaced height is requested while the tips validate at other heights, until the block they named arrives (the case marked it.fails in part 4); a mismatch nothing fixed resolves a day after it was last seen.
  • open-gap.integration.test.ts and open-gap-scheduler.test.ts: tip repairs go out least recently seen first, again once their window's backoff has passed, past more backed-off windows than the scheduler's candidates, and with the mismatch height first.
  • block-reorg.integration.test.ts: a contract class, instance and update registered again move to the replacing chain, keeping what was verified for them, but never away from a canonical block.
  • tests/unit/block-contract-row-errors.test.ts (new, 4 tests): a lock timeout, also as a query error's cause, or an I/O error in a contract row's savepoint aborts the block, so the bus redelivers it; a row that fails on its own data is skipped, and the next is stored.
  • tests/integration/chain-cache.integration.test.ts (new, 1 test, real Postgres and Redis): from a warm cache, the API serves the block that replaced the tip and the tx and instance it took, and none of the replaced block's own txs.
  • tests/integration/start-up.integration.test.ts and tests/unit/start-up.test.ts (new, 1 test each): after a crash cut off a bump, a start serves the replacing block; start-up bumps the revision after the dropped-tx sweep and before it consumes.
  • block-ingest.integration.test.ts: no tx effects at height 0. l2-tips-native-status.test.ts, consumer-replay.corpus.test.ts (and its snapshot) and recorded-blocks.integration.test.ts follow the lock, the revision and the new cache keys.

UI:

  • src/api/by-hash-lookups.test.ts (new, 4 tests): a lookup answers null once the tx has no row, and still fails on other errors.
  • src/pages/block-detail/index.test.tsx, src/pages/tx-detail/index.test.tsx and src/pages/contract-instance/index.test.tsx (new, 2, 5 and 1 tests): the page changes above.
  • src/hooks/api/tx-effect.test.tsx (new, 2 tests): an orphaned effect refetches every 10 s and a canonical or missing one every minute; the block page's queries refetch every minute.
  • tests/characterization/ws-frame.test.ts: block and tips frames mark the chain queries stale.

yarn lint is clean. yarn test passes 472 tests, with 1 skipped, and yarn test:integration passes 194.

Migration and rollout

  • No migration.
  • Release with part 4, after the listener (part 3). Roll both back together, before the listener.
  • The start-up sweep now removes the dropped rows only of txs a canonical block holds: a subset of what the previous sweep removed.
  • After the upgrade, chain reads use new cache keys, so the first reads miss the cache. The old entries expire with their TTL. A rolled-back API reads its old keys again, which this version never writes.

🤖 Generated with Claude Code

alejoamiras and others added 30 commits November 27, 2026 19:53
The dropped- and pending-tx handlers decided whether a tx was mined, then
wrote, outside any transaction: a block attach could commit in between,
and a mined tx ended listed as dropped. Any stored tx effect counted as
mined, so a tx only a dead block holds was never stored as dropped, and
a pending event for a mined tx stored it as pending again.

Each tx now gets one transaction under the network's chain lock, which
moves to its own module: only a canonical owner counts as mined
(txEffectExists), and the writes go through the same transaction. The
dropped handler no longer swallows errors; the pending handler skips a
payload that does not parse and lets every other error through, so a
lock timeout redelivers the message. In one transaction a conflict
aborts every write, so two public calls with one calldata, which share
their key, now keep one row instead of failing.

The start-up sweep becomes one statement under the lock, and removes
only the dropped rows of txs a canonical block holds: a genuinely
dropped tx survives a restart.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A contract class, deployment or update that a replacing block registers
again hit its key (class id and version, or address) and was skipped as
a duplicate, so it stayed on the dead block: the explorer showed the
contract as orphaned while the chain held it.

On a key conflict the row now moves to the incoming block when the block
holding it is off the chain, and its own block writes it again. Only the
block moves: a class keeps its verified artifact and source, and an
instance its verified arguments and deployer metadata. An update moves
with the new block's values. A row another canonical block holds, as
with a second rollup version, stays there and is logged.

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

Tips and blocks arrive on separate topics, and the stored tips were
validated only when a tips event came. A block stored after the tips
that named it left every block's status unknown until the next event,
and a change that demoted a block the tips named left them stored as
healthy. upsertTips validated and then wrote without the chain lock, so
tips validated before a demotion could be written after it as healthy.

Every change that moves a canonical status now validates the stored
tips again in its own transaction, healthy or degraded, and writes only
a changed result, so a mismatch's occurrences still count tips events.
upsertTips validates and writes under the chain lock. While the only
problem is a missing proposed boundary block, usually one on its way,
heights up to the checkpointed tip keep their status in block reads,
the by-status blocks and the UI table filter.

Clean tips resolved every open mismatch, so the repair forgot a height
that was never fixed. A mismatch now resolves only when the canonical
block at its height has the hash the tips named, a reorg record lists
that hash, or it was last seen a day ago. Mismatches record their rollup
version, and the tip-boundary repair asks for the window around the
most recently seen open one whose window is not backing off, instead of
parsing the degraded reason. Gap discovery stops at the latest canonical
height: the ordered stream is still sending the heights above it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
After a prune at the tip's height, the API kept serving the old block, its
tx effects and its contract instances from Redis for up to a minute, and
the explorer UI did not refetch a block or tx page it had open.

Reads whose answer depends on which blocks are canonical now end their
cache key with a chain revision: blocks by height and hash, tx effects by
hash and by height, contract instances by address and by block, and every
latest-height read. The block consumers replace the revision after each
block they apply, and the service once at start-up, which covers a crash
between a commit and its bump. The revision is a random value: the cache
client has no atomic increment, and the keys only need a value never used
before.

In the UI, a block or tips frame now also marks the reorg lists and the
block and tx detail queries stale.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The case was written for the height rules, which kept the stored block at
a replaced height on the chain until its replacement arrived. The next
ordered block links to the replacement, which is missing, so the stored
block there leaves the chain and its height is asked for; the tip-boundary
repair still covers that height after the next tips validate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The tx effects at a height, and the effect at a height and index, were
selected by height, index and rollup version alone. A block taken off the
chain keeps the effects no canonical block took, so both reads still
served the replaced block's own txs, on a cold cache too. They now join
only blocks on the chain, as the UI tables already do. The latest tx
effects still list those effects, flagged `isOrphaned`.

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

A chain change validated the stored tips again, but returned before
resolving anything when the result was unchanged. Tips that already
validated at other heights left the mismatch at a height open after the
block they named arrived there, and its height stayed in the repair
request until the next tips event. An unchanged result now resolves the
open mismatches whose cause is gone, and still records none, so a
mismatch's occurrence count keeps counting tips events.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The tx page counted any effect as mined. The API still answers a tx's
effect by hash after its block leaves the chain, flagged `isOrphaned`, so
the page showed the tx as mined and linked it by height to the block that
replaced it. Mined now needs an effect on the chain; an orphaned one shows
as the tx's history and links its block by hash.

A tx with no dropped row now reads as a successful `null`. The lookup used
to reject on the 404, and a rejected refetch keeps its old data, so a tx
included again kept showing the drop it had before.

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

The listener fetches a range request from its lowest height until
`maxBlocks` runs out. A repair window wider than that budget started more
than `maxBlocks` below its mismatch, so every retry fetched the same
heights below it and never the mismatch itself. The window's radius is
now at most half the budget, which keeps the mismatch inside what the
listener fetches.

A mismatch at height 0 is passed over: the listener fetches nothing below
height 1, so its window could never repair it and only took the turn of
a mismatch that could be.

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

Both handlers write each tx in its own transaction under the chain lock,
and each may wait for the lock. They never called the heartbeat, so a
long frame could outlast the consumer's session, and the group would
deliver the same frame again from its start. Each handler now calls the
heartbeat before every tx.

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

A block or tips frame refreshed the latest views and the block and tx
details, but not the paginated block list or the contract instance
queries: the instance detail, a class's instances and the paged instance
list. None of them refetches on a timer, so an open page kept the block list,
or the deploying block and orphan flag, it loaded before the prune.
Both frames now refresh them by prefix.

The instance page also shows whether the instance's deployment is
orphaned, as the instance lists do.

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

Start-up bumps the chain revision to retire cached reads that a crash
between a block's commit and its bump left behind, and those the start-up
writes change. Archive mode returned before that bump, though it serves
the same cached reads, so it kept answering with the block a stored
replacement had taken off the chain until those entries expired. The
bump now runs before the archive-mode return.

The new integration test warms a block read, stores a replacing block
whose bump a crash cuts off, starts the service, and expects the served
block to be the replacement.

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

Drops three comments that restate the write below them. The contract
store's doc now gives only its savepoint and heartbeat failure semantics.
The chain lock's doc states the order it relies on, the chain lock before
any other lock, and its timeout, without promising callers a redelivery.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A tier at block 0 names the genesis block, which the chain never stores.
Validation looked it up like any other tier, found nothing and recorded a
missing boundary. On a young chain, whose proven and finalized tiers are
still at 0, the tips therefore stayed degraded and every block's status
read unknown until those tiers moved. A tier at block 0 is now valid by
definition: it records no mismatch and does not degrade the tips.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The tx effects of a height took the latest-list branch when neither bound
was truthy, and height 0 is falsy: `/l2/blocks/0/tx-effects` answered
with the latest tx effects, orphaned ones included, instead of the none
stored at height 0. The bounds are now checked for presence, there and in
the height condition.

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

The heartbeat stub recorded its call and resolved at once, so a handler
that called the heartbeat without awaiting it kept the same order. The
stub now stays pending: no chain lock starts until it passes, the next
tx's lock waits for the next heartbeat, and a failed heartbeat stops the
frame before that lock.

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

A tip repair sent its window as one range, sized to the API's own block
budget. The listener sends each range from its lowest height, within
width and block limits of its own, so a listener with lower limits than
the API's stopped below the mismatch on every retry. With a window
clamped to 99 heights either side and a listener limit of 50, it sent
the 50 heights from 99 below the mismatch, and never the mismatch.

The request now names the mismatch height alone first, then the heights
below and above it. The window row and its backoff are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The tip repair read the 50 most recently seen open mismatch rows, then
dropped height 0 and every window still backing off. Rows the tick would
pass over took the slots first: past 50 newer backed-off windows, an
older mismatch whose window was due was never sent.

One query now picks the most recently seen mismatch at height 1 or more
whose window is not backing off, so its limit counts only rows the tick
would send.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The block page listed the rows of the tx table read for its height,
which serves the canonical block there. On an orphaned block's page that
is the block that replaced it, so the page listed the replacement's txs
under the orphaned block.

The rows now come from the block's own body, in its order. The height
read only adds the fee of a tx it lists too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The tx page could contradict its own status. A mined tx with a dropped
row it once had showed "dropped at"; a dropped tx with a pending row
still stored showed the pending panel and hid its drop. The pending
lookup failed on a 404, so a refetch kept the pending row it had found
before. And a mined effect linked its block by height, which names
whichever block is canonical there when the link is followed.

The pending lookup now answers null on a 404, as the dropped lookup
does. The pending and dropped panels, and the "dropped at" line, show
only under their own status. Every effect links its block by hash.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The tip repair picked the most recently seen due mismatch. While the
block consumer lags, a newer mismatch can appear on every tick, and each
one kept an older due window waiting for as long as the lag lasted.

The due windows now go oldest first; the backoff filter is unchanged.
Blocks arrive in order, so the oldest mismatches resolve first, and one
that never resolves still reaches the front.

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

No test sent a tip repair a second time. A picker that passed over every
window with a row, due or not, would send each repair once and never
again while its mismatch stayed open, and every test still passed.

The new case requests a window, sees it skipped while its one request
backs it off, and sees it sent again two cadences later.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A tx's effect is one row per tx hash, and it moves to the block that
mines the tx again. An orphaned block's body therefore keeps only the
txs no later block mined, so the page numbered them by position, not by
their index in the block. A fee matched by hash could only come from the
later block, when the page's two reads straddled the move.

On an orphaned block's page every row now shows no index and no fee,
and one line says that a tx a later block also mined is listed under
that block.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With no effect, no pending row and no drop, the tx page's status fell
back to "pending", so it showed a Pending pill above "tx not found". A
pending lookup that answers null on a 404 reaches that case more often.

The page now shows no status pill until a lookup finds the tx.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…count as they are

The tip repair's doc comment said a window is re-sent whole; the request
names the mismatch height first, then the rest of its window. The tips
revalidation's comment said a mismatch's occurrence count counts tips
events only; a chain change whose result changed records its mismatch
too.

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

storeBlockContracts skipped every failed contract row, so a lock timeout
committed the block and left the row on its old block. A retryable SQLSTATE
now rolls the block back for the bus to redeliver; a data error still skips the row.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The tx effect query stopped polling once it had data, so an open tx page kept
showing orphaned or dropped after a catch-up block, which sends no websocket
frame, moved the effect back onto the chain. It now refetches every 10 s while orphaned.

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

The listener's prune-depth cap and the API's walk bound are one limit;
defining it once keeps the two from drifting.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A block changes with the chain, so the cache comment no longer claims it
never does.

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

drizzle-orm 0.44 and later wrap pg's error and keep it as `cause`; the
lock-timeout case now checks that shape as well as the error pg throws.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
alejoamiras and others added 4 commits November 27, 2026 19:53
…tem error

A SQLSTATE class 58 error (external to PostgreSQL, such as I/O) in a row's
upsert was logged and skipped, so its block committed without the row. It
now aborts the block, which the bus redelivers.

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

No websocket frame announces a catch-up block, which can move a canonical
tx's effect or fill a block's txs, so an open page kept showing the old
block. A canonical effect and the block page's queries now refetch every minute.

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

A tx that neither the pending, the indexed nor the dropped lookup knows
showed "tx not found" and polled only while it was pending. A catch-up
block that indexes it sends no websocket frame, so an open page stayed on
"not found" until a reload. A lookup that has found nothing now refetches
every minute, as a found canonical effect does; a pending tx still polls
every 5 s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The test imported the module inside its body, so loading its module
graph counted against the 5 s test timeout, which a loaded machine
exceeded. A static import loads it during collection, under the same
hoisted mocks.

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 state fix: keep dropped txs, tips, contract rows and cached reads on the canonical chain 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