From b289f0e1ed97da3bcac7741f6ce04ca3410175eb Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 01:25:13 +0000 Subject: [PATCH 01/34] fix(explorer-api): write dropped and pending txs under the chain lock 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 --- .../src/events/received/on-dropped-txs.ts | 31 +-- .../src/events/received/on-pending-txs.ts | 27 ++- services/explorer-api/src/start.ts | 4 +- .../svcs/database/controllers/chain-lock.ts | 23 ++ .../database/controllers/dropped-tx/remove.ts | 46 ++-- .../database/controllers/dropped-tx/store.ts | 7 +- .../controllers/l2PendingL2ToL1Msg/delete.ts | 3 +- .../controllers/l2PendingL2ToL1Msg/store.ts | 5 +- .../controllers/l2Public-call/delete.ts | 3 +- .../controllers/l2Public-call/store.ts | 14 +- .../svcs/database/controllers/l2Tx/delete.ts | 3 +- .../svcs/database/controllers/l2Tx/store.ts | 7 +- .../controllers/l2TxEffect/get-tx-effect.ts | 13 +- .../database/controllers/l2block/canonical.ts | 18 +- .../consumer-replay.corpus.test.ts.snap | 9 + .../consumer-replay.corpus.test.ts | 9 + .../chain-head.integration.test.ts | 38 +--- .../pending-and-dropped.integration.test.ts | 196 ++++++++++++++++++ .../tests/integration/support/chain-lock.ts | 52 +++++ 19 files changed, 391 insertions(+), 117 deletions(-) create mode 100644 services/explorer-api/src/svcs/database/controllers/chain-lock.ts create mode 100644 services/explorer-api/tests/integration/pending-and-dropped.integration.test.ts create mode 100644 services/explorer-api/tests/integration/support/chain-lock.ts diff --git a/services/explorer-api/src/events/received/on-dropped-txs.ts b/services/explorer-api/src/events/received/on-dropped-txs.ts index ccd365cd7..b9a7b2095 100644 --- a/services/explorer-api/src/events/received/on-dropped-txs.ts +++ b/services/explorer-api/src/events/received/on-dropped-txs.ts @@ -7,6 +7,7 @@ import { import { SERVICE_NAME } from "../../constants.js"; import { L2_NETWORK_ID } from "../../environment.js"; import { logger } from "../../logger.js"; +import { withChainLock } from "../../svcs/database/controllers/chain-lock.js"; import { storeDroppedTx } from "../../svcs/database/controllers/dropped-tx/store.js"; import { deleteTx } from "../../svcs/database/controllers/l2Tx/index.js"; import { txEffectExists } from "../../svcs/database/controllers/l2TxEffect/get-tx-effect.js"; @@ -17,26 +18,16 @@ const onDroppedTxs = async ({ txs }: DroppedTxsEvent) => { logger.info(`๐Ÿ—‘๏ธ Received ${txs.length} dropped txs to handle`); for (const droppedTx of txs) { - const isAlreadyStored = await txEffectExists(droppedTx.txHash); - if (isAlreadyStored) { - logger.info(`๐Ÿ—‘๏ธ Dropped tx ${droppedTx.txHash} already exists, skipping`); - continue; - } - try { - // Store as dropped transaction - await storeDroppedTx(droppedTx); - - // Delete public call data - await deletePublicCall(droppedTx.txHash); - - // Delete L2-to-L1 messages - await deleteL2ToL1Msgs(droppedTx.txHash); - - // Delete from pending transactions - await deleteTx(droppedTx.txHash); - } catch (error) { - logger.error(`Error processing dropped tx ${droppedTx.txHash}:`, error); - } + await withChainLock(async (dbTx) => { + if (await txEffectExists(droppedTx.txHash, dbTx)) { + logger.info(`๐Ÿ—‘๏ธ Dropped tx ${droppedTx.txHash} is mined, skipping`); + return; + } + await storeDroppedTx(droppedTx, dbTx); + await deletePublicCall(droppedTx.txHash, dbTx); + await deleteL2ToL1Msgs(droppedTx.txHash, dbTx); + await deleteTx(droppedTx.txHash, dbTx); + }); } }; diff --git a/services/explorer-api/src/events/received/on-pending-txs.ts b/services/explorer-api/src/events/received/on-pending-txs.ts index 7e854b831..a60738b38 100644 --- a/services/explorer-api/src/events/received/on-pending-txs.ts +++ b/services/explorer-api/src/events/received/on-pending-txs.ts @@ -8,30 +8,39 @@ import { chicmozL2PendingTxSchema } from "@chicmoz-pkg/types"; import { SERVICE_NAME } from "../../constants.js"; import { L2_NETWORK_ID } from "../../environment.js"; import { logger } from "../../logger.js"; +import { withChainLock } from "../../svcs/database/controllers/chain-lock.js"; import { storeOrUpdateL2Tx } from "../../svcs/database/controllers/l2Tx/index.js"; import { removeDroppedTxByHash } from "../../svcs/database/controllers/dropped-tx/index.js"; -import { handleDuplicateError } from "./utils.js"; +import { txEffectExists } from "../../svcs/database/controllers/l2TxEffect/get-tx-effect.js"; const onPendingTxs = async ({ txs }: PendingTxsEvent) => { logger.info(`๐Ÿ• Received ${txs.length} pending txs to store`); for (const tx of txs) { - try { - const res = chicmozL2PendingTxSchema.parse(tx); - + const parsed = chicmozL2PendingTxSchema.safeParse(tx); + if (!parsed.success) { + logger.error( + `Failed to parse pending tx ${tx.txHash}: ${parsed.error.message}`, + ); + continue; + } + const res = parsed.data; + await withChainLock(async (dbTx) => { + if (await txEffectExists(res.txHash, dbTx)) { + logger.info(`๐Ÿ• Pending tx ${res.txHash} is mined, skipping`); + return; + } // Handle resubmissions: remove from dropped table if exists - const removedCount = await removeDroppedTxByHash(res.txHash); + const removedCount = await removeDroppedTxByHash(res.txHash, dbTx); if (removedCount > 0) { logger.info( `๐Ÿ”„ Resubmitted tx ${res.txHash}: removed from dropped table`, ); } // Store/update in pending table (handles both new and resubmitted transactions) - await storeOrUpdateL2Tx(res); + await storeOrUpdateL2Tx(res, dbTx); logger.debug(`โœ… Stored/updated pending tx: ${res.txHash}`); - } catch (e) { - handleDuplicateError(e as Error, `tx ${tx.txHash}`); - } + }); } }; diff --git a/services/explorer-api/src/start.ts b/services/explorer-api/src/start.ts index d8cae475f..1c604fdec 100644 --- a/services/explorer-api/src/start.ts +++ b/services/explorer-api/src/start.ts @@ -7,7 +7,7 @@ import { } from "./environment.js"; import { subscribeHandlers } from "./events/received/index.js"; import { logger } from "./logger.js"; -import { removeDroppedThatHaveTxEffects } from "./svcs/database/controllers/dropped-tx/remove.js"; +import { removeMinedDroppedTxs } from "./svcs/database/controllers/dropped-tx/remove.js"; import { updateContractInstanceAztecScanNotes } from "./svcs/database/controllers/l2/aztec-scan-notes.js"; import { initializeRollupVersionCache } from "./svcs/database/controllers/l2/chain-info/rollup-version-cache.js"; import { deleteAllTxs } from "./svcs/database/controllers/l2Tx/delete-all-txs.js"; @@ -23,7 +23,7 @@ import { export const start = async () => { await deleteAllTxs(); // TODO: perhaps a more specific deleteAllTxs should be created, also some logs could be good. - await removeDroppedThatHaveTxEffects(); + await removeMinedDroppedTxs(); await initializeRollupVersionCache(); await initializeProtocolContracts(); const aztecScanNotes = AZTEC_SCAN_NOTES[L2_NETWORK_ID]; diff --git a/services/explorer-api/src/svcs/database/controllers/chain-lock.ts b/services/explorer-api/src/svcs/database/controllers/chain-lock.ts new file mode 100644 index 000000000..d5fa6f025 --- /dev/null +++ b/services/explorer-api/src/svcs/database/controllers/chain-lock.ts @@ -0,0 +1,23 @@ +import { getDb as db } from "@chicmoz-pkg/postgres-helper"; +import { sql } from "drizzle-orm"; +import { L2_NETWORK_ID } from "../../../environment.js"; +import { type DbTx } from "./utils.js"; + +const LOCK_NAMESPACE = 1_815_307_112; + +/** + * Runs `fn` in one transaction that first takes the network's chain lock. + * Every chain change takes it, and so does every write that depends on + * whether a canonical block holds a tx: the dropped- and pending-tx handlers + * and the start-up sweep. `lock_timeout` bounds every lock wait in the + * transaction, this one included: a wait over 10 s throws, so the message is + * redelivered. + */ +export const withChainLock = (fn: (dbTx: DbTx) => Promise): Promise => + db().transaction(async (dbTx) => { + await dbTx.execute(sql`SET LOCAL lock_timeout = '10s'`); + await dbTx.execute( + sql`SELECT pg_advisory_xact_lock(${LOCK_NAMESPACE}::int4, hashtext(${L2_NETWORK_ID}))`, + ); + return fn(dbTx); + }); diff --git a/services/explorer-api/src/svcs/database/controllers/dropped-tx/remove.ts b/services/explorer-api/src/svcs/database/controllers/dropped-tx/remove.ts index ac95cffae..73890ff19 100644 --- a/services/explorer-api/src/svcs/database/controllers/dropped-tx/remove.ts +++ b/services/explorer-api/src/svcs/database/controllers/dropped-tx/remove.ts @@ -1,10 +1,10 @@ import { getDb as db } from "@chicmoz-pkg/postgres-helper"; import { HexString } from "@chicmoz-pkg/types"; -import { eq } from "drizzle-orm"; +import { and, eq, exists, isNull, sql } from "drizzle-orm"; import { logger } from "../../../../logger.js"; import { droppedTx } from "../../../database/schema/dropped-tx/index.js"; -import { txEffect } from "../../schema/index.js"; -import { getDroppedTxs } from "./get-tx.js"; +import { body, l2Block, txEffect } from "../../schema/index.js"; +import { withChainLock } from "../chain-lock.js"; /** * Removes a dropped transaction by its hash @@ -14,8 +14,9 @@ import { getDroppedTxs } from "./get-tx.js"; */ export const removeDroppedTxByHash = async ( txHash: HexString, + executor: ReturnType = db(), ): Promise => { - const deletedEntries = await db() + const deletedEntries = await executor .delete(droppedTx) .where(eq(droppedTx.txHash, txHash)) .returning(); @@ -27,20 +28,25 @@ export const removeDroppedTxByHash = async ( return deletedEntries.length; }; -export const removeDroppedThatHaveTxEffects = async (): Promise => { - const allDroppedTxs = await getDroppedTxs(); - let count = 0; - for (const tx of allDroppedTxs) { - const txEffectRes = await db() - .select() - .from(txEffect) - .where(eq(txEffect.txHash, tx.txHash)) - .limit(1); - if (txEffectRes.length > 0) { - await removeDroppedTxByHash(tx.txHash); - count++; - } - } - logger.info(`๐Ÿ—‘๏ธ๐Ÿ—‘๏ธ๐Ÿ”ฅ๐Ÿ”ฅ removed ${count} dropped txs that already had a txEffect`); - return count; +/** Removes the dropped rows of txs a canonical block holds: those are mined. */ +export const removeMinedDroppedTxs = async (): Promise => { + const { rowCount } = await withChainLock((dbTx) => + dbTx.delete(droppedTx).where( + exists( + dbTx + .select({ one: sql`1` }) + .from(txEffect) + .innerJoin(body, eq(txEffect.bodyId, body.id)) + .innerJoin(l2Block, eq(body.blockHash, l2Block.hash)) + .where( + and( + eq(txEffect.txHash, droppedTx.txHash), + isNull(l2Block.orphan_timestamp), + ), + ), + ), + ), + ); + logger.info(`๐Ÿ—‘๏ธ๐Ÿ—‘๏ธ๐Ÿ”ฅ๐Ÿ”ฅ removed ${rowCount ?? 0} dropped txs that are mined`); + return rowCount ?? 0; }; diff --git a/services/explorer-api/src/svcs/database/controllers/dropped-tx/store.ts b/services/explorer-api/src/svcs/database/controllers/dropped-tx/store.ts index afa9636a5..5f1180c47 100644 --- a/services/explorer-api/src/svcs/database/controllers/dropped-tx/store.ts +++ b/services/explorer-api/src/svcs/database/controllers/dropped-tx/store.ts @@ -3,8 +3,11 @@ import { ChicmozL2DroppedTx } from "@chicmoz-pkg/types"; import { logger } from "../../../../logger.js"; import { droppedTx } from "../../schema/dropped-tx/index.js"; -export const storeDroppedTx = async (tx: ChicmozL2DroppedTx): Promise => { - const res = await db() +export const storeDroppedTx = async ( + tx: ChicmozL2DroppedTx, + executor: ReturnType = db(), +): Promise => { + const res = await executor .insert(droppedTx) .values(tx) .onConflictDoNothing() diff --git a/services/explorer-api/src/svcs/database/controllers/l2PendingL2ToL1Msg/delete.ts b/services/explorer-api/src/svcs/database/controllers/l2PendingL2ToL1Msg/delete.ts index 4dd250c4c..959e108f1 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2PendingL2ToL1Msg/delete.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2PendingL2ToL1Msg/delete.ts @@ -5,6 +5,7 @@ import { l2TxL2ToL1Msg } from "../../schema/index.js"; export const deleteL2ToL1Msgs = async ( txHash: ChicmozL2PendingTx["txHash"], + executor: ReturnType = db(), ): Promise => { - await db().delete(l2TxL2ToL1Msg).where(eq(l2TxL2ToL1Msg.txHash, txHash)); + await executor.delete(l2TxL2ToL1Msg).where(eq(l2TxL2ToL1Msg.txHash, txHash)); }; diff --git a/services/explorer-api/src/svcs/database/controllers/l2PendingL2ToL1Msg/store.ts b/services/explorer-api/src/svcs/database/controllers/l2PendingL2ToL1Msg/store.ts index c564733e9..ced104b45 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2PendingL2ToL1Msg/store.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2PendingL2ToL1Msg/store.ts @@ -7,13 +7,14 @@ import { deleteL2ToL1Msgs } from "./delete.js"; export const storeL2ToL1Msgs = async ( txHash: HexString, msgs: ChicmozL2PendingL2ToL1Msg[], + executor: ReturnType = db(), ): Promise => { if (msgs.length === 0) { return; } // Delete-then-insert for idempotency (same pattern as public call requests) - await deleteL2ToL1Msgs(txHash); + await deleteL2ToL1Msgs(txHash, executor); const values = msgs.map((msg) => ({ txHash, @@ -23,7 +24,7 @@ export const storeL2ToL1Msgs = async ( content: msg.content, })); - await db().insert(l2TxL2ToL1Msg).values(values); + await executor.insert(l2TxL2ToL1Msg).values(values); logger.info(`๐Ÿ“จ Stored ${msgs.length} L2-to-L1 messages for tx: ${txHash}`); }; diff --git a/services/explorer-api/src/svcs/database/controllers/l2Public-call/delete.ts b/services/explorer-api/src/svcs/database/controllers/l2Public-call/delete.ts index d19cc799b..be92b4d0d 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2Public-call/delete.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2Public-call/delete.ts @@ -5,9 +5,10 @@ import { l2TxPublicCallRequest } from "../../schema/index.js"; export const deletePublicCall = async ( txHash: ChicmozL2PendingTx["txHash"], + executor: ReturnType = db(), ): Promise => { // Delete existing public call requests for this txHash - await db() + await executor .delete(l2TxPublicCallRequest) .where(eq(l2TxPublicCallRequest.txHash, txHash)); }; diff --git a/services/explorer-api/src/svcs/database/controllers/l2Public-call/store.ts b/services/explorer-api/src/svcs/database/controllers/l2Public-call/store.ts index 0cde13760..22ba0421a 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2Public-call/store.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2Public-call/store.ts @@ -20,8 +20,9 @@ import { deletePublicCall } from "./delete.js"; const resolveArtifactNames = async ( contractAddress: string, functionSelector: string | undefined, + executor: ReturnType, ): Promise<{ contractName: string | null; functionName: string | null }> => { - const rows = await db() + const rows = await executor .select({ artifactContractName: l2ContractClassRegistered.artifactContractName, selectorMap: l2ContractClassRegistered.selectorMap, @@ -62,18 +63,20 @@ const resolveArtifactNames = async ( export const storePublicCallRequests = async ( txHash: HexString, publicCallRequests: PublicCallRequest[], + executor: ReturnType = db(), ): Promise => { if (publicCallRequests.length === 0) { return; } - await deletePublicCall(txHash); + await deletePublicCall(txHash, executor); const values = await Promise.all( publicCallRequests.map(async (request) => { const { contractName, functionName } = await resolveArtifactNames( request.contractAddress, request.functionSelector, + executor, ); return { txHash, @@ -89,7 +92,12 @@ export const storePublicCallRequests = async ( }), ); - await db().insert(l2TxPublicCallRequest).values(values); + // Two calls with one calldata share the key, and a conflict would abort the + // caller's transaction with it. + await executor + .insert(l2TxPublicCallRequest) + .values(values) + .onConflictDoNothing(); logger.info( `๐Ÿ“‹ Stored ${publicCallRequests.length} public call requests for tx: ${txHash}`, diff --git a/services/explorer-api/src/svcs/database/controllers/l2Tx/delete.ts b/services/explorer-api/src/svcs/database/controllers/l2Tx/delete.ts index b2920ceb7..059ae09a5 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2Tx/delete.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2Tx/delete.ts @@ -5,6 +5,7 @@ import { l2Tx } from "../../schema/index.js"; export const deleteTx = async ( hash: ChicmozL2PendingTx["txHash"], + executor: ReturnType = db(), ): Promise => { - await db().delete(l2Tx).where(eq(l2Tx.txHash, hash)).execute(); + await executor.delete(l2Tx).where(eq(l2Tx.txHash, hash)).execute(); }; diff --git a/services/explorer-api/src/svcs/database/controllers/l2Tx/store.ts b/services/explorer-api/src/svcs/database/controllers/l2Tx/store.ts index 36b70236e..33b8737f0 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2Tx/store.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2Tx/store.ts @@ -18,8 +18,9 @@ export const storeL2Tx = async (tx: ChicmozL2PendingTx): Promise => { export const storeOrUpdateL2Tx = async ( tx: ChicmozL2PendingTx, + executor: ReturnType = db(), ): Promise => { - const res = await db() + const res = await executor .insert(l2Tx) .values(tx) .onConflictDoUpdate({ @@ -56,11 +57,11 @@ export const storeOrUpdateL2Tx = async ( // Store public call requests if they exist if (tx.publicCallRequests && tx.publicCallRequests.length > 0) { - await storePublicCallRequests(tx.txHash, tx.publicCallRequests); + await storePublicCallRequests(tx.txHash, tx.publicCallRequests, executor); } // Store L2-to-L1 messages if they exist if (tx.l2ToL1Msgs && tx.l2ToL1Msgs.length > 0) { - await storeL2ToL1Msgs(tx.txHash, tx.l2ToL1Msgs); + await storeL2ToL1Msgs(tx.txHash, tx.l2ToL1Msgs, executor); } }; diff --git a/services/explorer-api/src/svcs/database/controllers/l2TxEffect/get-tx-effect.ts b/services/explorer-api/src/svcs/database/controllers/l2TxEffect/get-tx-effect.ts index 88b94dcce..4874b8b8b 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2TxEffect/get-tx-effect.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2TxEffect/get-tx-effect.ts @@ -14,6 +14,7 @@ import { getTableColumns, gte, isNotNull, + isNull, lt, sql, } from "drizzle-orm"; @@ -304,13 +305,19 @@ export const getTxEffectDynamicWhere = async ( return chicmozL2TxEffectDeluxeSchema.parse(toParse); }; -export const txEffectExists = async (hash: HexString): Promise => { - const res = await db() +/** Whether a canonical block holds the tx: an effect a dead block keeps is not mined. */ +export const txEffectExists = async ( + hash: HexString, + executor: ReturnType = db(), +): Promise => { + const res = await executor .select({ txHash: txEffect.txHash, }) .from(txEffect) - .where(eq(txEffect.txHash, hash)) + .innerJoin(body, eq(txEffect.bodyId, body.id)) + .innerJoin(l2Block, eq(body.blockHash, l2Block.hash)) + .where(and(eq(txEffect.txHash, hash), isNull(l2Block.orphan_timestamp))) .limit(1) .execute(); diff --git a/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts b/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts index 90ba720bf..0c9a53e0c 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts @@ -1,5 +1,4 @@ import { type Heartbeat } from "@chicmoz-pkg/message-bus"; -import { getDb as db } from "@chicmoz-pkg/postgres-helper"; import { type ChicmozL2Block, type HexString } from "@chicmoz-pkg/types"; import { and, asc, eq, gt, inArray, isNotNull, isNull, sql } from "drizzle-orm"; import { alias } from "drizzle-orm/pg-core"; @@ -19,6 +18,7 @@ import { lastArchive, txEffect, } from "../../schema/l2block/index.js"; +import { withChainLock } from "../chain-lock.js"; import { storeBlockContracts, type BlockContracts, @@ -51,24 +51,8 @@ import { store, writeTxEffect } from "./store.js"; /** Walks stop after this many steps; more canonical blocks than this above a tip is corrupted state. */ export const WALK_BOUND = 10_000; const HEARTBEAT_EVERY = 500; -const LOCK_NAMESPACE = 1_815_307_112; const ROWS_PER_STATEMENT = 1_000; -/** - * Runs `fn` in one transaction that first takes the network's chain lock, - * which every chain change takes; the dropped- and pending-tx handlers write - * without it. `lock_timeout` bounds every lock wait in the transaction, this - * one included: a wait over 10 s throws, so the message is redelivered. - */ -export const withChainLock = (fn: (dbTx: DbTx) => Promise): Promise => - db().transaction(async (dbTx) => { - await dbTx.execute(sql`SET LOCAL lock_timeout = '10s'`); - await dbTx.execute( - sql`SELECT pg_advisory_xact_lock(${LOCK_NAMESPACE}::int4, hashtext(${L2_NETWORK_ID}))`, - ); - return fn(dbTx); - }); - export type IncomingBlock = { block: ChicmozL2Block; contracts: BlockContracts; diff --git a/services/explorer-api/tests/characterization/__snapshots__/consumer-replay.corpus.test.ts.snap b/services/explorer-api/tests/characterization/__snapshots__/consumer-replay.corpus.test.ts.snap index cacc015df..6e5a2adaf 100644 --- a/services/explorer-api/tests/characterization/__snapshots__/consumer-replay.corpus.test.ts.snap +++ b/services/explorer-api/tests/characterization/__snapshots__/consumer-replay.corpus.test.ts.snap @@ -555,6 +555,14 @@ exports[`committed frames replayed into the explorer-api consumers > recorded lo { "args": [ "0x12bac4f40aa7b6d3b7f9a960ec18d12646d9e0ff390352033e2f69b80b47b38a", + "chain-locked transaction", + ], + "seam": "txEffectExists", + }, + { + "args": [ + "0x12bac4f40aa7b6d3b7f9a960ec18d12646d9e0ff390352033e2f69b80b47b38a", + "chain-locked transaction", ], "seam": "removeDroppedTxByHash", }, @@ -581,6 +589,7 @@ exports[`committed frames replayed into the explorer-api consumers > recorded lo "teardownGasLimitL2": 0, "txHash": "0x12bac4f40aa7b6d3b7f9a960ec18d12646d9e0ff390352033e2f69b80b47b38a", }, + "chain-locked transaction", ], "seam": "storeOrUpdateL2Tx", }, diff --git a/services/explorer-api/tests/characterization/consumer-replay.corpus.test.ts b/services/explorer-api/tests/characterization/consumer-replay.corpus.test.ts index 5a8b2e5e8..7307317ce 100644 --- a/services/explorer-api/tests/characterization/consumer-replay.corpus.test.ts +++ b/services/explorer-api/tests/characterization/consumer-replay.corpus.test.ts @@ -87,6 +87,15 @@ vi.mock("../../src/svcs/database/controllers/l2Tx/index.js", () => ({ vi.mock("../../src/svcs/database/controllers/dropped-tx/index.js", () => ({ removeDroppedTxByHash: seam.record("removeDroppedTxByHash", 0), })); +vi.mock( + "../../src/svcs/database/controllers/l2TxEffect/get-tx-effect.js", + () => ({ txEffectExists: seam.record("txEffectExists", false) }), +); +// Its transaction shows in the snapshot as the writes' last argument. +vi.mock("../../src/svcs/database/controllers/chain-lock.js", () => ({ + withChainLock: (fn: (dbTx: unknown) => Promise) => + fn("chain-locked transaction"), +})); // Only the compile-result consumer uses it; its real module reads the Redis // environment on import. vi.mock( diff --git a/services/explorer-api/tests/integration/chain-head.integration.test.ts b/services/explorer-api/tests/integration/chain-head.integration.test.ts index 912905fc9..6cf7a5e2e 100644 --- a/services/explorer-api/tests/integration/chain-head.integration.test.ts +++ b/services/explorer-api/tests/integration/chain-head.integration.test.ts @@ -17,6 +17,7 @@ import { orderedEvent, } from "./support/blocks.js"; import { heads, loadChainReads } from "./support/chain.js"; +import { loadChainLockProbes } from "./support/chain-lock.js"; import { type ExplorerApiForTest, startExplorerApiForTest, @@ -54,7 +55,7 @@ describe("the canonical chain on a real database", () => { event: NewBlockEvent, ) => Promise<{ deliveries: number; rebalances: number; beats: number }>; let holdChainLock: () => Promise<() => Promise>; - let lockWaiters: () => Promise; + let untilLockWaiters: (count: number, what: string) => Promise; let fulfilByHeight: (height: bigint) => Promise; let walkBound: number; @@ -63,7 +64,7 @@ describe("the canonical chain on a real database", () => { const { blockHandler, catchupHandler } = await import( "../../src/events/received/on-block/index.js" ); - const { WALK_BOUND, withChainLock } = await import( + const { WALK_BOUND } = await import( "../../src/svcs/database/controllers/l2block/canonical.js" ); const { markOpenGapsFulfilledByHeight } = await import( @@ -268,30 +269,7 @@ describe("the canonical chain on a real database", () => { await admin.disconnect(); } }; - holdChainLock = async () => { - let release: () => void = () => undefined; - let held: Promise = Promise.resolve(); - await new Promise((locked) => { - held = withChainLock(() => { - locked(); - return new Promise((resolve) => { - release = resolve; - }); - }); - }); - return async () => { - release(); - await held; - }; - }; - // Lock requests waiting in this file's database, where the chain lock is - // the only advisory lock taken. - lockWaiters = async () => { - const { rows } = await db.execute<{ waiting: number }>( - sql`SELECT count(*)::int AS waiting FROM pg_locks WHERE locktype = 'advisory' AND NOT granted AND database = (SELECT oid FROM pg_database WHERE datname = current_database())`, - ); - return rows[0]?.waiting ?? 0; - }; + ({ holdChainLock, untilLockWaiters } = await loadChainLockProbes()); fulfilByHeight = markOpenGapsFulfilledByHeight; }); @@ -928,13 +906,7 @@ describe("the canonical chain on a real database", () => { catchup(fromCatchup).then(() => finished.push("catch-up")), ]); try { - const deadline = Date.now() + 5_000; - while ((await lockWaiters()) < 2) { - if (Date.now() > deadline) { - throw new Error("the consumers never waited on the chain lock"); - } - await new Promise((resolve) => setTimeout(resolve, 50)); - } + await untilLockWaiters(2, "the consumers"); expect(finished).toEqual([]); } finally { await release(); diff --git a/services/explorer-api/tests/integration/pending-and-dropped.integration.test.ts b/services/explorer-api/tests/integration/pending-and-dropped.integration.test.ts new file mode 100644 index 000000000..d3e87047a --- /dev/null +++ b/services/explorer-api/tests/integration/pending-and-dropped.integration.test.ts @@ -0,0 +1,196 @@ +import { + type DroppedTxsEvent, + type PendingTxsEvent, +} from "@chicmoz-pkg/message-registry"; +import { + type ChicmozL2DroppedTx, + type HexString, + type PublicCallRequest, +} from "@chicmoz-pkg/types"; +import { deliver, frameBytes, loadFixture } from "@chicmoz/test-harness"; +import { BSON } from "bson"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { + type BuiltBlock, + buildBlock, + freshTxHash, + orderedEvent, +} from "./support/blocks.js"; +import { loadChainReads } from "./support/chain.js"; +import { loadChainLockProbes } from "./support/chain-lock.js"; +import { + type ExplorerApiForTest, + startExplorerApiForTest, +} from "./support/explorer-api.js"; + +let lastVersion = 1_000; +const freshVersion = () => ++lastVersion; + +const droppedRow = (txHash: HexString): ChicmozL2DroppedTx => ({ + txHash, + createdAsPendingAt: Date.now(), + droppedAt: Date.now(), + dropReason: "dropped", +}); + +// Whether a tx counts as mined decides every write here, so each one runs on +// the chain lock that canonical changes take. +describe("pending and dropped txs on a real database", () => { + let api: ExplorerApiForTest; + let reads: Awaited>; + let probes: Awaited>; + let ordered: (b: BuiltBlock) => Promise; + let dropped: (txHash: HexString) => Promise; + let pending: ( + txHash: HexString, + publicCallRequests?: PublicCallRequest[], + ) => Promise; + let takeOffChain: (b: BuiltBlock) => Promise; + let isPending: (txHash: HexString) => Promise; + let storeDropped: (txHash: HexString) => Promise; + let sweep: () => Promise; + + beforeAll(async () => { + api = await startExplorerApiForTest(); + const { blockHandler } = await import( + "../../src/events/received/on-block/index.js" + ); + const { droppedTxHandler } = await import( + "../../src/events/received/on-dropped-txs.js" + ); + const { pendingTxHandler } = await import( + "../../src/events/received/on-pending-txs.js" + ); + const { removeMinedDroppedTxs } = await import( + "../../src/svcs/database/controllers/dropped-tx/remove.js" + ); + const { storeDroppedTx } = await import( + "../../src/svcs/database/controllers/dropped-tx/store.js" + ); + const { l2Block } = await import( + "../../src/svcs/database/schema/l2block/index.js" + ); + const { l2Tx } = await import( + "../../src/svcs/database/schema/l2tx/index.js" + ); + const { getDb } = await import("@chicmoz-pkg/postgres-helper"); + const { eq } = await import("drizzle-orm"); + const db = getDb(); + reads = await loadChainReads(); + probes = await loadChainLockProbes(); + + const { + txs: [recorded], + } = ( + BSON.deserialize( + frameBytes( + loadFixture("local-network", "frame", "pending-txs-event-1"), + ), + ) as { data: PendingTxsEvent } + ).data; + if (!recorded) { + throw new Error("the recorded pending-txs frame holds no tx"); + } + ordered = (b) => deliver(blockHandler, orderedEvent(b)); + dropped = (txHash) => + deliver(droppedTxHandler, { + txs: [droppedRow(txHash)], + } satisfies DroppedTxsEvent); + pending = (txHash, publicCallRequests) => + deliver(pendingTxHandler, { + txs: [{ ...recorded, txHash, publicCallRequests }], + } satisfies PendingTxsEvent); + takeOffChain = async (b) => { + await db + .update(l2Block) + .set({ orphan_timestamp: Date.now(), orphan_hasOrphanedParent: false }) + .where(eq(l2Block.hash, b.hash)); + }; + isPending = async (txHash) => + ( + await db + .select({ txHash: l2Tx.txHash }) + .from(l2Tx) + .where(eq(l2Tx.txHash, txHash)) + ).length > 0; + storeDropped = (txHash) => storeDroppedTx(droppedRow(txHash)); + sweep = removeMinedDroppedTxs; + }); + + afterAll(async () => { + await api?.close(); + }); + + it("serializes a dropped tx's write with the block that includes it on the chain lock, so the tx ends mined", async () => { + const tx = freshTxHash(); + const block = await buildBlock(1_000n, [tx], { version: freshVersion() }); + const deliveries: Promise[] = []; + + const release = await probes.holdChainLock(); + try { + deliveries.push(ordered(block)); + await probes.untilLockWaiters(1, "the block"); + deliveries.push(dropped(tx)); + await probes.untilLockWaiters(2, "the dropped-tx handler"); + } finally { + await release(); + await Promise.all(deliveries); + } + + expect(await reads.ownerOf(tx)).toBe(block.hash); + expect(await reads.isDropped(tx)).toBe(false); + }); + + it("counts a tx as mined only while a canonical block holds it: a dropped tx an off-chain block holds is stored, a pending tx a canonical block holds is not", async () => { + const version = freshVersion(); + const [mined, kept] = [freshTxHash(), freshTxHash()]; + const live = await buildBlock(2_000n, [mined], { version }); + const dead = await buildBlock(2_001n, [kept], { version, parent: live }); + await ordered(live); + await ordered(dead); + await takeOffChain(dead); + + await dropped(kept); + await pending(mined); + + expect(await reads.isDropped(kept)).toBe(true); + expect(await isPending(mined)).toBe(false); + }); + + it("stores a pending tx whose two public calls share their calldata", async () => { + const tx = freshTxHash(); + const call: PublicCallRequest = { + msgSender: `0x${"00".repeat(31)}0a`, + contractAddress: `0x${"00".repeat(31)}0b`, + isStaticCall: false, + calldataHash: `0x${"00".repeat(31)}0c`, + callType: "revertible", + functionSelector: "0x0000000d", + }; + + await pending(tx, [call, call]); + + expect(await isPending(tx)).toBe(true); + }); + + it("keeps a genuinely dropped tx through the start-up sweep, and removes the dropped row of a mined one", async () => { + const version = freshVersion(); + const [mined, kept, lost] = [freshTxHash(), freshTxHash(), freshTxHash()]; + const live = await buildBlock(3_000n, [mined], { version }); + const dead = await buildBlock(3_001n, [kept], { version, parent: live }); + await ordered(live); + await ordered(dead); + await takeOffChain(dead); + for (const tx of [mined, kept, lost]) { + await storeDropped(tx); + } + + await sweep(); + + expect([ + await reads.isDropped(mined), + await reads.isDropped(kept), + await reads.isDropped(lost), + ]).toEqual([false, true, true]); + }); +}); diff --git a/services/explorer-api/tests/integration/support/chain-lock.ts b/services/explorer-api/tests/integration/support/chain-lock.ts new file mode 100644 index 000000000..a922271a3 --- /dev/null +++ b/services/explorer-api/tests/integration/support/chain-lock.ts @@ -0,0 +1,52 @@ +/** + * Probes of the network's chain lock on a test file's database. Call after + * startExplorerApiForTest, like any explorer-api import. + */ +export const loadChainLockProbes = async () => { + const { getDb } = await import("@chicmoz-pkg/postgres-helper"); + const { sql } = await import("drizzle-orm"); + const { withChainLock } = await import( + "../../../src/svcs/database/controllers/chain-lock.js" + ); + const db = getDb(); + + /** Takes the chain lock and holds it until the returned release is awaited. */ + const holdChainLock = async () => { + let release: () => void = () => undefined; + let held: Promise = Promise.resolve(); + await new Promise((locked) => { + held = withChainLock(() => { + locked(); + return new Promise((resolve) => { + release = resolve; + }); + }); + }); + return async () => { + release(); + await held; + }; + }; + + // Lock requests waiting in this file's database, where the chain lock is + // the only advisory lock taken. + const lockWaiters = async () => { + const { rows } = await db.execute<{ waiting: number }>( + sql`SELECT count(*)::int AS waiting FROM pg_locks WHERE locktype = 'advisory' AND NOT granted AND database = (SELECT oid FROM pg_database WHERE datname = current_database())`, + ); + return rows[0]?.waiting ?? 0; + }; + + /** Resolves once `count` requests wait on the lock; throws after 5 s. */ + const untilLockWaiters = async (count: number, what: string) => { + const deadline = Date.now() + 5_000; + while ((await lockWaiters()) < count) { + if (Date.now() > deadline) { + throw new Error(`${what} never waited on the chain lock`); + } + await new Promise((resolve) => setTimeout(resolve, 50)); + } + }; + + return { holdChainLock, untilLockWaiters }; +}; From 5291e01fca168ed9f02da1079c90a304ce54feeb Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 01:56:33 +0000 Subject: [PATCH 02/34] fix(explorer-api): move a re-registered contract to its canonical block 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 --- .../database/controllers/l2contract/store.ts | 138 +++++++++++++++--- .../block-reorg.integration.test.ts | 97 ++++++++++++ .../chain-head.integration.test.ts | 2 +- .../tests/integration/support/blocks.ts | 59 +++++--- .../tests/integration/support/chain.ts | 30 +++- 5 files changed, 277 insertions(+), 49 deletions(-) diff --git a/services/explorer-api/src/svcs/database/controllers/l2contract/store.ts b/services/explorer-api/src/svcs/database/controllers/l2contract/store.ts index 348f452c4..6eae1a5ca 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2contract/store.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2contract/store.ts @@ -8,8 +8,20 @@ import { type ChicmozL2ContractInstanceVerifiedDeploymentArgumnetsSchema, type ChicmozL2PrivateFunctionBroadcastedEvent, type ChicmozL2UtilityFunctionBroadcastedEvent, + type HexString, } from "@chicmoz-pkg/types"; -import { and, eq, inArray, isNull, or } from "drizzle-orm"; +import { + and, + eq, + exists, + inArray, + isNotNull, + isNull, + or, + sql, + type SQL, +} from "drizzle-orm"; +import { type PgColumn } from "drizzle-orm/pg-core"; import { l2ContractClassRegistered, l2ContractInstanceDeployed, @@ -19,6 +31,7 @@ import { l2UtilityFunction, } from "../../../database/schema/l2contract/index.js"; import { l2TxPublicCallRequest } from "../../../database/schema/l2public-call/index.js"; +import { l2Block } from "../../schema/index.js"; import { buildSelectorMap, selectorMapValueToFunctionName, @@ -26,21 +39,82 @@ import { import { logger } from "../../../../logger.js"; import { type DbTx } from "../utils.js"; +/** + * A contract row's rule on a key conflict: it moves to `incoming` from a + * block off the chain, and its own block writes it again; another canonical + * block keeps it. + */ +const movesTo = ( + executor: ReturnType, + owner: PgColumn, + incoming: HexString, +): SQL => + sql`${eq(owner, incoming)} OR ${exists( + executor + .select({ one: sql`1` }) + .from(l2Block) + .where(and(eq(l2Block.hash, owner), isNotNull(l2Block.orphan_timestamp))), + )}`; + +/** + * Stores a deployment, or moves it as `movesTo` allows. Only its block + * changes: the arguments verified for the address, and its deployer metadata, + * stay. False when another canonical block keeps it. + */ export const storeContractInstanceDeployed = async ( instance: ChicmozL2ContractInstanceDeployedEvent, executor: ReturnType = db(), -): Promise => { +): Promise => { const { publicKeys, ...rest } = instance; - await executor + const stored = await executor .insert(l2ContractInstanceDeployed) - .values({ ...publicKeys, ...rest }); + .values({ ...publicKeys, ...rest }) + .onConflictDoUpdate({ + target: l2ContractInstanceDeployed.address, + set: { blockHash: rest.blockHash }, + setWhere: movesTo( + executor, + l2ContractInstanceDeployed.blockHash, + rest.blockHash, + ), + }) + .returning({ address: l2ContractInstanceDeployed.address }); + return stored.length > 0; }; +/** + * Stores an update, or moves it with its new block's values as `movesTo` + * allows. False when another canonical block keeps it. + */ export const storeContractInstanceUpdated = async ( instance: ChicmozL2ContractInstanceUpdatedEvent, executor: ReturnType = db(), -): Promise => { - await executor.insert(l2ContractInstanceUpdate).values({ ...instance }); +): Promise => { + const { + blockHash, + prevContractClassId, + newContractClassId, + timestampOfChange, + } = instance; + const stored = await executor + .insert(l2ContractInstanceUpdate) + .values({ ...instance }) + .onConflictDoUpdate({ + target: l2ContractInstanceUpdate.address, + set: { + blockHash, + prevContractClassId, + newContractClassId, + timestampOfChange, + }, + setWhere: movesTo( + executor, + l2ContractInstanceUpdate.blockHash, + blockHash, + ), + }) + .returning({ address: l2ContractInstanceUpdate.address }); + return stored.length > 0; }; export const storeContractInstanceVerifiedDeploymentArguments = async ( @@ -60,13 +134,32 @@ export const storeContractInstanceVerifiedDeploymentArguments = async ( }); }; +/** + * Stores a class, or moves it as `movesTo` allows. Only its block changes: + * the artifact and source verified for the class stay. False when another + * canonical block keeps it. + */ export const storeContractClass = async ( contractClass: ChicmozL2ContractClassRegisteredEvent, executor: ReturnType = db(), -): Promise => { - await executor.insert(l2ContractClassRegistered).values({ - ...contractClass, - }); +): Promise => { + const stored = await executor + .insert(l2ContractClassRegistered) + .values({ ...contractClass }) + .onConflictDoUpdate({ + target: [ + l2ContractClassRegistered.contractClassId, + l2ContractClassRegistered.version, + ], + set: { blockHash: contractClass.blockHash }, + setWhere: movesTo( + executor, + l2ContractClassRegistered.blockHash, + contractClass.blockHash, + ), + }) + .returning({ contractClassId: l2ContractClassRegistered.contractClassId }); + return stored.length > 0; }; export type BlockContracts = { @@ -76,10 +169,11 @@ export type BlockContracts = { }; /** - * Stores a block's contract rows inside its transaction, each in a savepoint: - * a row that fails (a duplicate, or an instance whose class was never - * stored) is logged and skipped without aborting the block; a failed - * heartbeat, taken before each row, aborts it. + * Stores a canonical block's contract rows inside its transaction, each in a + * savepoint: a row another canonical block keeps is logged, and one that + * fails (an instance whose class was never stored) is logged and skipped + * without aborting the block; a failed heartbeat, taken before each row, + * aborts it. */ export const storeBlockContracts = async ( dbTx: DbTx, @@ -89,20 +183,20 @@ export const storeBlockContracts = async ( const each = async ( rows: T[], label: (row: T) => string, - write: (row: T, executor: DbTx) => Promise, + write: (row: T, executor: DbTx) => Promise, ) => { for (const row of rows) { await heartbeat(); try { - await dbTx.transaction((savepoint) => write(row, savepoint)); - } catch (e) { - if ((e as { code?: string }).code === "23505") { - logger.warn(`DB Duplicate: ${label(row)}`); - } else { - logger.error( - `Failed to store ${label(row)}: ${(e as Error).stack ?? String(e)}`, + if (!(await dbTx.transaction((savepoint) => write(row, savepoint)))) { + logger.warn( + `${label(row)} stays with the canonical block that holds it`, ); } + } catch (e) { + logger.error( + `Failed to store ${label(row)}: ${(e as Error).stack ?? String(e)}`, + ); } } }; diff --git a/services/explorer-api/tests/integration/block-reorg.integration.test.ts b/services/explorer-api/tests/integration/block-reorg.integration.test.ts index 5e5bd9bc4..2a374455b 100644 --- a/services/explorer-api/tests/integration/block-reorg.integration.test.ts +++ b/services/explorer-api/tests/integration/block-reorg.integration.test.ts @@ -1,3 +1,4 @@ +import { type HexString } from "@chicmoz-pkg/types"; import { deliver } from "@chicmoz/test-harness"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { @@ -7,6 +8,12 @@ import { orderedEvent, } from "./support/blocks.js"; import { loadChainReads } from "./support/chain.js"; +import { + rawArtifact, + readClassRow, + readDeploymentArguments, + seedStoredArtifact, +} from "./support/contracts.js"; import { type ExplorerApiForTest, startExplorerApiForTest, @@ -97,4 +104,94 @@ describe("block conflicts on a real database", () => { await store(new301); await settled(); }); + + it("moves the contract class and instance a replacing chain registers again to it, keeping what was verified for them, but never from a canonical block", async () => { + const { controllers } = await import("../../src/svcs/database/index.js"); + const chainAt400 = async ( + [classTx, deployTx]: HexString[], + version?: number, + ) => { + const publishing = await buildBlock(400n, [classTx], { + version, + effect: "publishesClass", + }); + const deploying = await buildBlock(401n, [deployTx], { + version, + parent: publishing, + effect: "deploysInstance", + }); + return { publishing, deploying }; + }; + const txs = [freshTxHash(), freshTxHash()]; + const replaced = await chainAt400(txs); + await store(replaced.publishing); + await store(replaced.deploying); + const [contractClassId] = await reads.classesOf(replaced.publishing.hash); + const [address] = await reads.instancesOf(replaced.deploying.hash); + expect([contractClassId, address]).not.toContain(undefined); + await seedStoredArtifact( + { contractClassId, version: 1 }, + rawArtifact("escrow_contract-Escrow"), + ); + const salt = freshTxHash(); + await controllers.l2Contract.storeContractInstanceVerifiedDeploymentArguments( + { + address, + salt, + deployer: `0x${"00".repeat(32)}`, + publicKeysString: "0x00", + constructorArgs: [], + }, + ); + + const replacing = await chainAt400(txs); + await store(replacing.publishing); + await store(replacing.deploying); + const owned = async () => [ + await reads.classesOf(replacing.publishing.hash), + await reads.instancesOf(replacing.deploying.hash), + ]; + expect(await owned()).toEqual([[contractClassId], [address]]); + expect(await readClassRow({ contractClassId, version: 1 })).toMatchObject({ + artifactContractName: "Escrow", + }); + expect(await readDeploymentArguments(address)).toMatchObject({ salt }); + + const other = await chainAt400([freshTxHash(), freshTxHash()], 2); + await store(other.publishing); + await store(other.deploying); + expect(await reads.stateOf(other.deploying.hash)).toBe("canonical"); + expect(await owned()).toEqual([[contractClassId], [address]]); + }); + + it("moves a contract update emitted again from a block off the chain with the new block's values, but never from another canonical block", async () => { + const { controllers } = await import("../../src/svcs/database/index.js"); + const address = `0x${"0a".repeat(32)}` as const; + const updateIn = (block: BuiltBlock, timestampOfChange: number) => + controllers.l2Contract.storeContractInstanceUpdated({ + address, + prevContractClassId: `0x${"01".repeat(32)}`, + newContractClassId: `0x${"02".repeat(32)}`, + timestampOfChange, + blockHash: block.hash, + }); + const replaced = await buildBlock(500n, [freshTxHash()]); + const replacing = await buildBlock(500n, [freshTxHash()]); + const child = await buildBlock(501n, [freshTxHash()], { + parent: replacing, + }); + await store(replaced); + await updateIn(replaced, 1_000); + await store(replacing); + + expect(await updateIn(replacing, 2_000)).toBe(true); + // Its own block, delivered again, writes it again. + expect(await updateIn(replacing, 2_000)).toBe(true); + await store(child); + expect(await updateIn(child, 3_000)).toBe(false); + expect(await reads.updateOf(address)).toEqual({ + blockHash: replacing.hash, + timestampOfChange: 2_000, + }); + }); }); diff --git a/services/explorer-api/tests/integration/chain-head.integration.test.ts b/services/explorer-api/tests/integration/chain-head.integration.test.ts index 6cf7a5e2e..718d4495a 100644 --- a/services/explorer-api/tests/integration/chain-head.integration.test.ts +++ b/services/explorer-api/tests/integration/chain-head.integration.test.ts @@ -957,7 +957,7 @@ describe("the canonical chain on a real database", () => { const tx = freshTxHash(); const block = await buildBlock(28_000n, [tx], { version: freshVersion(), - publishesClass: true, + effect: "publishesClass", }); let beats = 0; // The beats before its effect and before its class row pass; the next, diff --git a/services/explorer-api/tests/integration/support/blocks.ts b/services/explorer-api/tests/integration/support/blocks.ts index 121ea0236..0ae58aee7 100644 --- a/services/explorer-api/tests/integration/support/blocks.ts +++ b/services/explorer-api/tests/integration/support/blocks.ts @@ -41,25 +41,38 @@ const recorded = ( return L2Block.fromBuffer(Buffer.from(fixture.data.hex, "hex")); }; -// A recorded effect with public logs and no contract-class logs, so storing a -// clone adds no contract rows that would collide across blocks. -let plain: L2Block | undefined; -// A recorded effect that publishes a contract class. Its clones share the -// class row, so only the first one stored in a database adds it. -let publishing: L2Block | undefined; -const baseBlock = (publishesClass: boolean): L2Block => - publishesClass - ? (publishing ??= recorded( - "a contract class log", - (e) => e.counts.contractClassLogs > 0, - )) - : (plain ??= recorded( - "public logs and no contract logs", - (e) => - e.counts.publicLogs > 0 && - e.counts.contractClassLogs === 0 && - e.contractInstanceAddresses.length === 0, - )); +type Effect = "plain" | "publishesClass" | "deploysInstance"; + +// Recorded effects to clone. A plain one has public logs and no contract +// logs, so its clones add no contract rows. The others publish the recorded +// contract class and deploy the recorded instance of it: their clones share +// one row each. +const EFFECTS: Record< + Effect, + [string, (expected: FixtureData["l2-block"]["expected"]) => boolean] +> = { + plain: [ + "public logs and no contract logs", + (e) => + e.counts.publicLogs > 0 && + e.counts.contractClassLogs === 0 && + e.contractInstanceAddresses.length === 0, + ], + publishesClass: [ + "a contract class log", + (e) => e.counts.contractClassLogs > 0, + ], + deploysInstance: [ + "a contract instance deployment", + (e) => e.contractInstanceAddresses.length > 0, + ], +}; +const bases = new Map(); +const baseBlock = (effect: Effect): L2Block => { + const base = bases.get(effect) ?? recorded(...EFFECTS[effect]); + bases.set(effect, base); + return base; +}; /** * The coinbase is salted to tell headers at one height apart. The handler @@ -67,7 +80,7 @@ const baseBlock = (publishesClass: boolean): L2Block => * `version` replaces the recorded rollup version. Each block gets an archive * of its own, unless `archive` names one; `parent` makes the block's last * archive the parent's archive, the link a chain's consecutive blocks have. - * `publishesClass` clones an effect that publishes a contract class. + * `effect` names the recorded effect the txs clone. */ export const buildBlock = async ( height: bigint, @@ -76,15 +89,15 @@ export const buildBlock = async ( version, parent, archive: sharedArchive, - publishesClass, + effect: cloned = "plain", }: { version?: number; parent?: Pick; archive?: AppendOnlyTreeSnapshot; - publishesClass?: true; + effect?: Effect; } = {}, ): Promise => { - const base = baseBlock(publishesClass === true); + const base = baseBlock(cloned); const [effect] = base.body.txEffects; if (!effect) { throw new Error("base block has no tx effect"); diff --git a/services/explorer-api/tests/integration/support/chain.ts b/services/explorer-api/tests/integration/support/chain.ts index b60dd9995..2eecc53c2 100644 --- a/services/explorer-api/tests/integration/support/chain.ts +++ b/services/explorer-api/tests/integration/support/chain.ts @@ -39,9 +39,11 @@ export const loadChainReads = async () => { const { l2OpenGapTable } = await import( "../../../src/svcs/database/schema/l2/open-gap.js" ); - const { l2ContractClassRegistered } = await import( - "../../../src/svcs/database/schema/l2contract/index.js" - ); + const { + l2ContractClassRegistered, + l2ContractInstanceDeployed, + l2ContractInstanceUpdate, + } = await import("../../../src/svcs/database/schema/l2contract/index.js"); const { getReorgs } = await import( "../../../src/svcs/database/controllers/l2block/get-block.js" ); @@ -92,6 +94,26 @@ export const loadChainReads = async () => { .where(eq(l2ContractClassRegistered.blockHash, blockHash)) ).map(({ id }) => id); + /** The addresses of the contract instances deployed with a block. */ + const instancesOf = async (blockHash: HexString) => + ( + await db + .select({ address: l2ContractInstanceDeployed.address }) + .from(l2ContractInstanceDeployed) + .where(eq(l2ContractInstanceDeployed.blockHash, blockHash)) + ).map(({ address }) => address); + + const updateOf = async (address: string) => { + const [row] = await db + .select({ + blockHash: l2ContractInstanceUpdate.blockHash, + timestampOfChange: l2ContractInstanceUpdate.timestampOfChange, + }) + .from(l2ContractInstanceUpdate) + .where(eq(l2ContractInstanceUpdate.address, address)); + return row; + }; + const isDropped = async (txHash: HexString) => ( await db @@ -169,6 +191,8 @@ export const loadChainReads = async () => { stateOf, ownerOf, classesOf, + instancesOf, + updateOf, isDropped, recordsOf, listed, From ce5bc1ab3616336bb18f817315f87f43522f4abd Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 02:15:08 +0000 Subject: [PATCH 03/34] fix(explorer-api): validate the tips on the chain they are stored against 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 --- .../svcs/database/controllers/chain-lock.ts | 4 +- .../src/svcs/database/controllers/l2/tips.ts | 263 ++++++++++++++---- .../database/controllers/l2block/canonical.ts | 4 + .../database/controllers/l2block/get-block.ts | 14 +- .../controllers/l2block/missing-ranges.ts | 83 +++--- .../svcs/database/controllers/ui/tables.ts | 13 +- .../l2-tips-block-race.integration.test.ts | 193 +++++++++++++ .../late-replacing-block.integration.test.ts | 47 ++++ .../tests/unit/l2-tips-native-status.test.ts | 13 +- .../tests/unit/open-gap-scheduler.test.ts | 39 +-- 10 files changed, 545 insertions(+), 128 deletions(-) create mode 100644 services/explorer-api/tests/integration/l2-tips-block-race.integration.test.ts diff --git a/services/explorer-api/src/svcs/database/controllers/chain-lock.ts b/services/explorer-api/src/svcs/database/controllers/chain-lock.ts index d5fa6f025..be0c7433c 100644 --- a/services/explorer-api/src/svcs/database/controllers/chain-lock.ts +++ b/services/explorer-api/src/svcs/database/controllers/chain-lock.ts @@ -8,8 +8,8 @@ const LOCK_NAMESPACE = 1_815_307_112; /** * Runs `fn` in one transaction that first takes the network's chain lock. * Every chain change takes it, and so does every write that depends on - * whether a canonical block holds a tx: the dropped- and pending-tx handlers - * and the start-up sweep. `lock_timeout` bounds every lock wait in the + * which blocks are canonical: the dropped- and pending-tx handlers, the + * start-up sweep and the tips. `lock_timeout` bounds every lock wait in the * transaction, this one included: a wait over 10 s throws, so the message is * redelivered. */ diff --git a/services/explorer-api/src/svcs/database/controllers/l2/tips.ts b/services/explorer-api/src/svcs/database/controllers/l2/tips.ts index 0cdb00926..dcdcea9b9 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2/tips.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2/tips.ts @@ -8,15 +8,18 @@ import { L2NetworkId, chicmozL2TipsSchema, } from "@chicmoz-pkg/types"; -import { and, desc, eq, isNull, sql } from "drizzle-orm"; +import { and, desc, eq, exists, isNull, lt, or, sql } from "drizzle-orm"; import { L2_NETWORK_ID } from "../../../../environment.js"; import { logger } from "../../../../logger.js"; +import { l2ReorgBlockTable } from "../../schema/l2/reorg.js"; import { l2TipBoundaryMismatchTable, l2TipsTable, StoredL2Tips, } from "../../schema/l2/tips.js"; import { l2Block } from "../../schema/l2block/index.js"; +import { withChainLock } from "../chain-lock.js"; +import { type DbTx } from "../utils.js"; import { getCurrentRollupVersionNumber } from "./chain-info/rollup-version-cache.js"; type TipBucket = "finalized" | "proven" | "checkpointed" | "proposed"; @@ -103,10 +106,16 @@ const flattenTips = ( updatedAt: new Date(), }); -const getBoundaryBlock = async (height: number, rollupVersion: number | null) => { +type Executor = ReturnType; + +const getBoundaryBlock = async ( + executor: Executor, + height: number, + rollupVersion: number | null, +) => { const versionFilter = rollupVersion !== null ? eq(l2Block.version, rollupVersion) : undefined; - const rows = await db() + const rows = await executor .select({ hash: l2Block.hash }) .from(l2Block) .where( @@ -120,20 +129,28 @@ const getBoundaryBlock = async (height: number, rollupVersion: number | null) => return rows[0]?.hash; }; +const missingBoundaryReason = (bucket: TipBucket, height: number) => + `${bucket} boundary block ${height} is missing`; + const validateBoundary = async ( + executor: Executor, bucket: TipBucket, tips: ChicmozL2Tips, rollupVersion: number | null, ): Promise => { const tip = bucket === "proposed" ? tips.proposed : tips[bucket].block; - const boundaryHash = await getBoundaryBlock(tip.number, rollupVersion); + const boundaryHash = await getBoundaryBlock( + executor, + tip.number, + rollupVersion, + ); if (!boundaryHash) { return { bucket, height: tip.number, expectedHash: tip.hash, observedDbHash: null, - reason: `${bucket} boundary block ${tip.number} is missing`, + reason: missingBoundaryReason(bucket, tip.number), }; } if (boundaryHash !== tip.hash) { @@ -148,6 +165,30 @@ const validateBoundary = async ( return null; }; +const findBoundaryMismatch = async ( + executor: Executor, + tips: ChicmozL2Tips, + rollupVersion: number | null, +): Promise => { + for (const bucket of [ + "finalized", + "proven", + "checkpointed", + "proposed", + ] as const) { + const mismatch = await validateBoundary( + executor, + bucket, + tips, + rollupVersion, + ); + if (mismatch) { + return mismatch; + } + } + return null; +}; + const mismatchId = ({ bucket, height, @@ -156,7 +197,11 @@ const mismatchId = ({ }: BoundaryValidationResult) => `${L2_NETWORK_ID}:${bucket}:${height}:${expectedHash}:${observedDbHash ?? "missing"}`; -const recordBoundaryMismatch = async (mismatch: BoundaryValidationResult) => { +const recordBoundaryMismatch = async ( + executor: Executor, + mismatch: BoundaryValidationResult, + rollupVersion: number | null, +) => { const values = { id: mismatchId(mismatch), l2NetworkId: L2_NETWORK_ID, @@ -167,9 +212,10 @@ const recordBoundaryMismatch = async (mismatch: BoundaryValidationResult) => { reason: mismatch.reason, lastSeenAt: new Date(), resolvedAt: null, + rollupVersion, }; - await db() + await executor .insert(l2TipBoundaryMismatchTable) .values(values) .onConflictDoUpdate({ @@ -179,55 +225,150 @@ const recordBoundaryMismatch = async (mismatch: BoundaryValidationResult) => { lastSeenAt: values.lastSeenAt, occurrenceCount: sql`${l2TipBoundaryMismatchTable.occurrenceCount} + 1`, resolvedAt: null, + rollupVersion, }, }); }; -const resolveBoundaryMismatches = async () => { - const database = db(); - if (typeof database.update !== "function") { - return; - } - await database - .update(l2TipBoundaryMismatchTable) +const MISMATCH_EXPIRY_MS = 24 * 60 * 60 * 1000; + +/** + * Resolves the open mismatches whose cause is gone: the canonical block at + * the height has the hash the tips named, a reorg record lists that hash, or + * the mismatch was last seen a day ago. Tips that validate at other heights + * resolve nothing. + */ +const resolveBoundaryMismatches = async (executor: Executor) => { + const mismatch = l2TipBoundaryMismatchTable; + await executor + .update(mismatch) .set({ resolvedAt: new Date() }) .where( and( - eq(l2TipBoundaryMismatchTable.l2NetworkId, L2_NETWORK_ID), - isNull(l2TipBoundaryMismatchTable.resolvedAt), + eq(mismatch.l2NetworkId, L2_NETWORK_ID), + isNull(mismatch.resolvedAt), + or( + lt(mismatch.lastSeenAt, new Date(Date.now() - MISMATCH_EXPIRY_MS)), + exists( + executor + .select({ one: sql`1` }) + .from(l2Block) + .where( + and( + eq(l2Block.hash, mismatch.expectedHash), + eq(l2Block.height, mismatch.height), + isNull(l2Block.orphan_timestamp), + ), + ), + ), + exists( + executor + .select({ one: sql`1` }) + .from(l2ReorgBlockTable) + .where(eq(l2ReorgBlockTable.hash, mismatch.expectedHash)), + ), + ), ), ); }; +const recordValidation = async ( + executor: Executor, + mismatch: BoundaryValidationResult | null, + rollupVersion: number | null, +) => { + if (mismatch) { + await recordBoundaryMismatch(executor, mismatch, rollupVersion); + } + await resolveBoundaryMismatches(executor); +}; + +/** + * Validates and stores tips under the network's chain lock: tips validated + * before a chain change and written after it would describe a chain that no + * longer exists. + */ export const upsertTips = async (event: L2TipsEvent) => { const tips = chicmozL2TipsSchema.parse(event.tips); const rollupVersion = await getCurrentRollupVersionNumber(); - let degradedReason: string | null = null; - let degradedMismatch: BoundaryValidationResult | null = null; - for (const bucket of ["finalized", "proven", "checkpointed", "proposed"] as const) { - const mismatch = await validateBoundary(bucket, tips, rollupVersion); + await withChainLock(async (dbTx) => { + const mismatch = await findBoundaryMismatch(dbTx, tips, rollupVersion); if (mismatch) { - degradedReason = mismatch.reason; - degradedMismatch = mismatch; - logger.warn(`L2 tips degraded: ${degradedReason}`); - break; + logger.warn(`L2 tips degraded: ${mismatch.reason}`); } - } - - const values = flattenTips({ ...event, tips }, degradedReason); - await db() - .insert(l2TipsTable) - .values(values) - .onConflictDoUpdate({ + const values = flattenTips({ ...event, tips }, mismatch?.reason ?? null); + await dbTx.insert(l2TipsTable).values(values).onConflictDoUpdate({ target: l2TipsTable.l2NetworkId, set: values, }); + await recordValidation(dbTx, mismatch, rollupVersion); + }); +}; - if (degradedMismatch) { - await recordBoundaryMismatch(degradedMismatch); +/** + * Validates the stored tips again inside a chain change, healthy or + * degraded: the change may have stored a block they name, or demoted one. + * An unchanged result writes nothing, so a mismatch's occurrence count + * counts tips events. + */ +export const revalidateTips = async (dbTx: DbTx) => { + const [row] = await dbTx + .select() + .from(l2TipsTable) + .where(eq(l2TipsTable.l2NetworkId, L2_NETWORK_ID)) + .limit(1); + if (!row) { + return; + } + const rollupVersion = await getCurrentRollupVersionNumber(); + const mismatch = await findBoundaryMismatch( + dbTx, + toStoredTips(row), + rollupVersion, + ); + const degradedReason = mismatch?.reason ?? null; + if (degradedReason === row.degradedReason) { + return; + } + await dbTx + .update(l2TipsTable) + .set({ degradedReason, updatedAt: new Date() }) + .where(eq(l2TipsTable.l2NetworkId, L2_NETWORK_ID)); + if (mismatch) { + logger.warn(`L2 tips degraded: ${mismatch.reason}`); } else { - await resolveBoundaryMismatches(); + logger.info(`L2 tips valid again (was: ${row.degradedReason})`); } + await recordValidation(dbTx, mismatch, rollupVersion); +}; + +/** + * The heights of the open mismatches, most recently seen first: those of + * `rollupVersion`, and those recorded before mismatches carried a version. + */ +export const getUnresolvedBoundaryHeights = async ( + rollupVersion: number | null, + limit: number, +): Promise => { + const mismatch = l2TipBoundaryMismatchTable; + const rows = await db() + .select({ height: mismatch.height }) + .from(mismatch) + .where( + and( + eq(mismatch.l2NetworkId, L2_NETWORK_ID), + isNull(mismatch.resolvedAt), + rollupVersion === null + ? undefined + : or( + isNull(mismatch.rollupVersion), + eq(mismatch.rollupVersion, rollupVersion), + ), + ), + ) + .orderBy(desc(mismatch.lastSeenAt)) + .limit(limit); + return [...new Set(rows.map(({ height }) => height))]; }; export const getRecentBoundaryMismatches = async ( @@ -252,35 +393,59 @@ export const getTips = async ( return rows[0] ? toStoredTips(rows[0]) : null; }; -export const deriveNativeStatus = ( - block: Pick, +type StatusTipHeights = Record; + +/** + * The tip heights block statuses derive from, or null while the stored tips + * cannot be trusted. A missing proposed boundary block is usually one still on + * its way, so heights up to the validated checkpointed tip keep their status + * and only those above it are unknown. + */ +export const statusTipHeights = ( storedTips: StoredL2Tips | null, -): ChicmozL2NativeBlockStatus => { +): StatusTipHeights | null => { if (!storedTips) { - return "unknown"; + return null; } - if (storedTips.degradedReason) { - return "unknown"; + const heights = { + finalized: storedTips.finalized.block.number, + proven: storedTips.proven.block.number, + checkpointed: storedTips.checkpointed.block.number, + proposed: storedTips.proposed.number, + }; + if (!storedTips.degradedReason) { + return heights; } - if (block.orphan) { + if ( + storedTips.degradedReason === + missingBoundaryReason("proposed", storedTips.proposed.number) + ) { + return { ...heights, proposed: heights.checkpointed }; + } + return null; +}; + +export const deriveNativeStatus = ( + block: Pick, + storedTips: StoredL2Tips | null, +): ChicmozL2NativeBlockStatus => { + const tips = statusTipHeights(storedTips); + if (!tips || block.orphan) { return "unknown"; } const height = Number(block.height); - if (!Number.isSafeInteger(height) || height > storedTips.proposed.number) { + if (!Number.isSafeInteger(height) || height > tips.proposed) { return "unknown"; } - if (height <= storedTips.finalized.block.number) { + if (height <= tips.finalized) { return "finalized"; } - if (height <= storedTips.proven.block.number) { + if (height <= tips.proven) { return "proven"; } - if (height <= storedTips.checkpointed.block.number) { + if (height <= tips.checkpointed) { return "checkpointed"; } - if (height <= storedTips.proposed.number) { - return "proposed"; - } - return "unknown"; + return "proposed"; }; diff --git a/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts b/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts index 0c9a53e0c..29d4e8d1c 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts @@ -19,6 +19,7 @@ import { txEffect, } from "../../schema/l2block/index.js"; import { withChainLock } from "../chain-lock.js"; +import { revalidateTips } from "../l2/tips.js"; import { storeBlockContracts, type BlockContracts, @@ -733,6 +734,9 @@ const settle = async ( [...new Set([...change.walked.values(), ...change.repairs])], (part) => recordRepairHeights(change.dbTx, part), ); + if (change.demoted.size > 0 || change.promoted.size > 0) { + await revalidateTips(change.dbTx); + } if (canonical) { await fulfilRepairHeight(change.dbTx, block.height); } diff --git a/services/explorer-api/src/svcs/database/controllers/l2block/get-block.ts b/services/explorer-api/src/svcs/database/controllers/l2block/get-block.ts index e9409c19d..37d0ec6d7 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2block/get-block.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2block/get-block.ts @@ -17,7 +17,7 @@ import { import { DB_MAX_BLOCKS, L2_NETWORK_ID } from "../../../../environment.js"; import { l2ReorgBlockTable, l2ReorgTable } from "../../schema/l2/reorg.js"; import { getCurrentRollupVersionNumber } from "../l2/chain-info/rollup-version-cache.js"; -import { deriveNativeStatus, getTips } from "../l2/tips.js"; +import { deriveNativeStatus, getTips, statusTipHeights } from "../l2/tips.js"; import { getLatestBlockRollupVersion } from "./get-latest.js"; import { archive, @@ -127,17 +127,17 @@ export const getBlock = async ( export const getBlocksByNativeStatus = async ( options: BlockQueryOptions = {}, ): Promise => { - const tips = await getTips(); - if (!tips || tips.degradedReason) { + const tips = statusTipHeights(await getTips()); + if (!tips) { const latest = await getBlock(-1n, options); return latest ? [latest] : []; } const heights = [ - tips.finalized.block.number, - tips.proven.block.number, - tips.checkpointed.block.number, - tips.proposed.number, + tips.finalized, + tips.proven, + tips.checkpointed, + tips.proposed, ]; const blocks: ChicmozL2BlockLight[] = []; const seen = new Set(); diff --git a/services/explorer-api/src/svcs/database/controllers/l2block/missing-ranges.ts b/services/explorer-api/src/svcs/database/controllers/l2block/missing-ranges.ts index 392a31019..f5582f421 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2block/missing-ranges.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2block/missing-ranges.ts @@ -29,7 +29,7 @@ import { logger } from "../../../../logger.js"; import { l2OpenGapTable } from "../../schema/l2/open-gap.js"; import { l2Block } from "../../schema/l2block/index.js"; import { getCurrentRollupVersionNumber } from "../l2/chain-info/rollup-version-cache.js"; -import { getTips } from "../l2/tips.js"; +import { getUnresolvedBoundaryHeights } from "../l2/tips.js"; import { getLatestBlockRollupVersion, getLatestHeight } from "./get-latest.js"; type GapRange = { from: number; to: number; statusHint: "proposed" }; @@ -517,11 +517,11 @@ const findPresentHeights = async (ranges: Array<{ from: number; to: number }>) = return new Set(rows.map((row) => Number(row.height))); }; +// Heights above the latest canonical block are still on their way in the +// ordered stream: asking for them would race it. const getReconciliationUpperBound = async () => { - const tips = await getTips(); const latestHeight = await getLatestHeight(); - const upperBound = tips?.proposed.number ?? (latestHeight ? Number(latestHeight) : 0); - return { tips, upperBound }; + return latestHeight === null ? 0 : Number(latestHeight); }; export const buildMissingBlockRangeRequest = async ({ @@ -533,7 +533,7 @@ export const buildMissingBlockRangeRequest = async ({ scanWindow?: number; maxBlocks?: number; }): Promise => { - const { upperBound } = await getReconciliationUpperBound(); + const upperBound = await getReconciliationUpperBound(); if (!Number.isSafeInteger(upperBound) || upperBound < 1) { logger.info(`Skipping ${reason} L2 block reconciliation: no upper bound`); return null; @@ -581,40 +581,55 @@ export const buildMissingBlockRangeRequest = async ({ }; }; -const parseTipBoundaryHeight = (degradedReason: string | undefined) => { - if (!degradedReason) { - return null; - } - const match = /boundary block (\d+) (?:is missing|hash mismatch)/u.exec(degradedReason); - if (!match?.[1]) { - return null; - } - const height = Number(match[1]); - return Number.isSafeInteger(height) && height > 0 ? height : null; -}; - +/** + * Asks for the window around an open tip-boundary mismatch: the most recently + * seen one whose window is not backing off. A window is re-sent whole while + * its mismatch stays open (its heights may be present but wrong), with the + * same backoff as other gaps, whatever the window row's status: blocks + * landing in the window fulfil it without resolving a mismatch. + */ export const buildTipBoundaryRepairRequest = async (): Promise => { - const tips = await getTips(); - const height = parseTipBoundaryHeight(tips?.degradedReason); - if (!height) { + const repairWindow = L2_BLOCK_RECONCILIATION_TIP_REPAIR_WINDOW; + const windows = ( + await getUnresolvedBoundaryHeights( + await getCurrentRollupVersionNumber(), + CANDIDATE_GAP_LIMIT, + ) + ).map((height) => { + const from = Math.max(1, height - repairWindow); + const to = height + repairWindow; + return { + height, + from, + to, + id: gapId({ from, to, reason: TIP_BOUNDARY_REASON }), + }; + }); + if (windows.length === 0) { return null; } - const repairWindow = L2_BLOCK_RECONCILIATION_TIP_REPAIR_WINDOW; - const from = Math.max(1, height - repairWindow); - const to = height + repairWindow; - const id = gapId({ from, to, reason: TIP_BOUNDARY_REASON }); - // The window is re-sent whole while the tips stay degraded (its heights - // may be present but wrong), with the same backoff as other gaps, - // whatever the row's status: blocks landing in the window fulfil it - // without fixing a mismatch. - const [existing] = await db() - .select({ due: sql`${gapDueSql(Date.now())}` }) - .from(l2OpenGapTable) - .where(eq(l2OpenGapTable.id, id)); - if (existing && !existing.due) { + const backingOff = new Set( + ( + await db() + .select({ id: l2OpenGapTable.id }) + .from(l2OpenGapTable) + .where( + and( + inArray( + l2OpenGapTable.id, + windows.map(({ id }) => id), + ), + not(gapDueSql(Date.now())), + ), + ) + ).map(({ id }) => id), + ); + const window = windows.find(({ id }) => !backingOff.has(id)); + if (!window) { return null; } + const { height, from, to, id } = window; const range = { from, to, statusHint: "proposed" as const }; // Reopening must not reset the backoff here: the row is "fulfilled" as // soon as its heights are present, mismatch or not. @@ -624,7 +639,7 @@ export const buildTipBoundaryRepairRequest = resetOnReopen: false, }); logger.warn( - `Requesting L2 tip-boundary repair around block ${height}: ${from}-${to}; reason=${tips?.degradedReason}`, + `Requesting L2 tip-boundary repair around block ${height}: ${from}-${to}`, ); return { request: { diff --git a/services/explorer-api/src/svcs/database/controllers/ui/tables.ts b/services/explorer-api/src/svcs/database/controllers/ui/tables.ts index 023b5b911..dda084729 100644 --- a/services/explorer-api/src/svcs/database/controllers/ui/tables.ts +++ b/services/explorer-api/src/svcs/database/controllers/ui/tables.ts @@ -29,7 +29,7 @@ import { uiTxEffectTableSchema, } from "@chicmoz-pkg/types"; import { getCurrentRollupVersionNumber } from "../l2/chain-info/rollup-version-cache.js"; -import { deriveNativeStatus, getTips } from "../l2/tips.js"; +import { deriveNativeStatus, getTips, statusTipHeights } from "../l2/tips.js"; type GetBlocksByRange = { from: bigint | undefined; @@ -41,14 +41,15 @@ const statusFilterWhere = ( status: Exclude, l2Tips: Awaited>, ) => { - if (!l2Tips || l2Tips.degradedReason) { + const tips = statusTipHeights(l2Tips); + if (!tips) { return status === "unknown" ? isNull(l2Block.orphan_timestamp) : sql`false`; } - const finalizedHeight = BigInt(l2Tips.finalized.block.number); - const provenHeight = BigInt(l2Tips.proven.block.number); - const checkpointedHeight = BigInt(l2Tips.checkpointed.block.number); - const proposedHeight = BigInt(l2Tips.proposed.number); + const finalizedHeight = BigInt(tips.finalized); + const provenHeight = BigInt(tips.proven); + const checkpointedHeight = BigInt(tips.checkpointed); + const proposedHeight = BigInt(tips.proposed); switch (status) { case "proposed": diff --git a/services/explorer-api/tests/integration/l2-tips-block-race.integration.test.ts b/services/explorer-api/tests/integration/l2-tips-block-race.integration.test.ts new file mode 100644 index 000000000..cbae7aae5 --- /dev/null +++ b/services/explorer-api/tests/integration/l2-tips-block-race.integration.test.ts @@ -0,0 +1,193 @@ +import { type L2TipsEvent } from "@chicmoz-pkg/message-registry"; +import { type HexString } from "@chicmoz-pkg/types"; +import { deliver } from "@chicmoz/test-harness"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { + type BuiltBlock, + buildBlock, + buildChain, + freshTxHash, + orderedEvent, +} from "./support/blocks.js"; +import { loadChainLockProbes } from "./support/chain-lock.js"; +import { + type ExplorerApiForTest, + startExplorerApiForTest, +} from "./support/explorer-api.js"; + +const word = (n: number): HexString => `0x${n.toString(16).padStart(64, "0")}`; + +// Tips and blocks arrive on separate topics, so tips can name a proposed +// block before it is stored, or one a later change demotes. Finalized 1, +// proven 2, checkpointed 3. +describe("native block statuses when the tips and the chain disagree", () => { + let api: ExplorerApiForTest; + let chain: BuiltBlock[]; + let deliverBlock: (block: BuiltBlock) => Promise; + let deliverTips: (proposed: BuiltBlock) => Promise; + let statusesOf: (heights: number[]) => Promise; + let degradedReason: () => Promise; + let openMismatches: (height: number) => Promise; + let unknownInUiTable: () => Promise; + let holdChainLock: () => Promise<() => Promise>; + let untilLockWaiters: (count: number, what: string) => Promise; + let takeOffChain: (block: BuiltBlock) => Promise; + + beforeAll(async () => { + api = await startExplorerApiForTest(); + const { blockHandler } = await import( + "../../src/events/received/on-block/index.js" + ); + const { l2TipsHandler } = await import( + "../../src/events/received/on-l2-tips.js" + ); + const { getBlock } = await import( + "../../src/svcs/database/controllers/l2block/get-block.js" + ); + const { getBlocksForUiTable } = await import( + "../../src/svcs/database/controllers/ui/tables.js" + ); + const tips = await import("../../src/svcs/database/controllers/l2/tips.js"); + const { l2Block } = await import( + "../../src/svcs/database/schema/l2block/index.js" + ); + const { eq } = await import("drizzle-orm"); + + chain = await buildChain(1n, 5); + deliverBlock = (block) => deliver(blockHandler, orderedEvent(block)); + const at = (block: BuiltBlock, checkpoint: number) => ({ + block: { number: Number(block.height), hash: block.hash }, + checkpoint: { number: checkpoint, hash: word(0x500 + checkpoint) }, + }); + deliverTips = (proposed) => + deliver(l2TipsHandler, { + tips: { + proposed: { number: Number(proposed.height), hash: proposed.hash }, + checkpointed: at(chain[2], 3), + proven: at(chain[1], 2), + finalized: at(chain[0], 1), + }, + observedAt: Date.now(), + source: { rpcNodeName: "node", aztecNodeVersion: "test" }, + } satisfies L2TipsEvent); + statusesOf = (heights) => + Promise.all( + heights.map( + async (height) => + (await getBlock(BigInt(height)))?.nativeStatus ?? "absent", + ), + ); + degradedReason = async () => (await tips.getTips())?.degradedReason; + openMismatches = async (height) => + (await tips.getRecentBoundaryMismatches()) + .filter( + (mismatch) => !mismatch.resolvedAt && mismatch.height === height, + ) + .map(({ bucket, observedDbHash, occurrenceCount }) => ({ + bucket, + observedDbHash, + occurrenceCount, + })); + unknownInUiTable = async () => + ( + await getBlocksForUiTable({ + from: undefined, + to: undefined, + status: "unknown", + }) + ).map((block) => Number(block.height)); + ({ holdChainLock, untilLockWaiters } = await loadChainLockProbes()); + takeOffChain = async (block) => { + await (await import("@chicmoz-pkg/postgres-helper")) + .getDb() + .update(l2Block) + .set({ orphan_timestamp: Date.now(), orphan_hasOrphanedParent: false }) + .where(eq(l2Block.hash, block.hash)); + }; + + for (const block of chain.slice(0, 3)) { + await deliverBlock(block); + } + }); + + afterAll(async () => { + await api?.close(); + }); + + // The cases build on each other, in order. + it("keeps the statuses up to the checkpointed tip while the proposed block is on its way", async () => { + await deliverTips(chain[4]); + await deliverBlock(chain[3]); + + expect(await degradedReason()).toBe("proposed boundary block 5 is missing"); + expect(await statusesOf([1, 2, 3, 4])).toEqual([ + "finalized", + "proven", + "checkpointed", + "unknown", + ]); + expect(await unknownInUiTable()).toEqual([4]); + // Storing block 4 validated again without counting another occurrence. + expect(await openMismatches(5)).toEqual([ + { bucket: "proposed", observedDbHash: null, occurrenceCount: 1 }, + ]); + }); + + it("counts the tips as valid once the block they name is stored", async () => { + await deliverBlock(chain[4]); + + expect(await degradedReason()).toBeUndefined(); + expect(await statusesOf([1, 4, 5])).toEqual([ + "finalized", + "proposed", + "proposed", + ]); + expect(await unknownInUiTable()).toEqual([]); + expect(await openMismatches(5)).toEqual([]); + }); + + it("keeps the tips degraded when the block stored at the proposed height has another hash", async () => { + const named = await buildBlock(6n, [freshTxHash()], { parent: chain[4] }); + const stored = await buildBlock(6n, [freshTxHash()], { parent: chain[4] }); + await deliverTips(named); + await deliverBlock(stored); + + expect(await degradedReason()).toBe( + `proposed boundary block 6 hash mismatch: db=${stored.hash} tip=${named.hash}`, + ); + expect(await statusesOf([1, 6])).toEqual(["unknown", "unknown"]); + chain.push(stored); + }); + + it("degrades healthy tips when a change demotes the block they name, and closes the mismatch the reorg explains", async () => { + const named = await buildBlock(7n, [freshTxHash()], { parent: chain[5] }); + await deliverBlock(named); + await deliverTips(named); + expect(await degradedReason()).toBeUndefined(); + + const replacing = await buildBlock(7n, [freshTxHash()], { + parent: chain[5], + }); + await deliverBlock(replacing); + + expect(await degradedReason()).toBe( + `proposed boundary block 7 hash mismatch: db=${replacing.hash} tip=${named.hash}`, + ); + expect(await statusesOf([1, 7])).toEqual(["unknown", "unknown"]); + expect(await openMismatches(7)).toEqual([]); + chain.push(replacing); + }); + + it("validates tips on the chain they are written against, so a demotion while they wait leaves them degraded", async () => { + const named = await buildBlock(8n, [freshTxHash()], { parent: chain[6] }); + await deliverBlock(named); + const release = await holdChainLock(); + const stored = deliverTips(named); + await untilLockWaiters(1, "the tips handler"); + await takeOffChain(named); + await release(); + await stored; + + expect(await degradedReason()).toBe("proposed boundary block 8 is missing"); + }); +}); diff --git a/services/explorer-api/tests/integration/late-replacing-block.integration.test.ts b/services/explorer-api/tests/integration/late-replacing-block.integration.test.ts index efc26f211..39e45b7ba 100644 --- a/services/explorer-api/tests/integration/late-replacing-block.integration.test.ts +++ b/services/explorer-api/tests/integration/late-replacing-block.integration.test.ts @@ -5,6 +5,7 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { type BuiltBlock, buildBlock, + buildChain, catchupEvent, freshTxHash, orderedEvent, @@ -37,6 +38,8 @@ describe("a replaced block that stays stored on a real database", () => { }, ) => Promise; let repairRequestCovers: (height: number) => Promise; + let lastSeenAgo: (height: number, ms: number) => Promise; + let mismatchOpenAt: (height: number) => Promise; beforeAll(async () => { api = await startExplorerApiForTest(); @@ -94,6 +97,24 @@ describe("a replaced block that stays stored on a real database", () => { ) ?? false ); }; + const { getDb } = await import("@chicmoz-pkg/postgres-helper"); + const { and, eq, isNull } = await import("drizzle-orm"); + const { l2TipBoundaryMismatchTable: mismatch } = await import( + "../../src/svcs/database/schema/l2/tips.js" + ); + lastSeenAgo = async (height, ms) => { + await getDb() + .update(mismatch) + .set({ lastSeenAt: new Date(Date.now() - ms) }) + .where(eq(mismatch.height, height)); + }; + mismatchOpenAt = async (height) => + ( + await getDb() + .select({ id: mismatch.id }) + .from(mismatch) + .where(and(eq(mismatch.height, height), isNull(mismatch.resolvedAt))) + ).length > 0; }); afterAll(async () => { @@ -172,4 +193,30 @@ describe("a replaced block that stays stored on a real database", () => { expect(await repairRequestCovers(403)).toBe(true); }, ); + + it("resolves a tip mismatch nothing fixed only a day after it was last seen", async () => { + const chain = await buildChain(500n, 4); + const [finalized, proven, checkpointed, stored] = chain; + for (const block of chain) { + await store(block); + } + const named = await buildBlock(503n, [freshTxHash()], { + parent: checkpointed, + }); + const tipsAt = (proposed: BuiltBlock) => + storeTips({ + proposed: { number: Number(proposed.height), hash: proposed.hash }, + finalized, + proven, + checkpointed, + }); + await tipsAt(named); + await tipsAt(stored); + expect(await mismatchOpenAt(503)).toBe(true); + + await lastSeenAgo(503, 25 * 60 * 60 * 1000); + await tipsAt(stored); + + expect(await mismatchOpenAt(503)).toBe(false); + }); }); diff --git a/services/explorer-api/tests/unit/l2-tips-native-status.test.ts b/services/explorer-api/tests/unit/l2-tips-native-status.test.ts index ee8132321..37243e082 100644 --- a/services/explorer-api/tests/unit/l2-tips-native-status.test.ts +++ b/services/explorer-api/tests/unit/l2-tips-native-status.test.ts @@ -26,9 +26,12 @@ const mocks = vi.hoisted(() => { return { onConflictDoUpdate }; }); const insert = vi.fn(() => ({ values })); + const update = vi.fn(() => ({ + set: () => ({ where: () => Promise.resolve() }), + })); return { - db: { insert, select }, + db: { insert, select, update }, from, limit, onConflictDoUpdate, @@ -49,6 +52,10 @@ vi.mock("../../src/environment.js", () => ({ L2_NETWORK_ID: "SANDBOX", })); +vi.mock("../../src/svcs/database/controllers/chain-lock.js", () => ({ + withChainLock: (fn: (dbTx: unknown) => Promise) => fn(mocks.db), +})); + vi.mock("../../src/logger.js", () => ({ logger: { debug: vi.fn(), @@ -162,7 +169,7 @@ describe("deriveNativeStatus", () => { expect( deriveNativeStatus( { hash: hash(1), height: 1n }, - { ...storedTips, degradedReason: "proposed boundary block 100 is missing" }, + { ...storedTips, degradedReason: "checkpointed boundary block 80 is missing" }, ), ).toBe("unknown"); expect( @@ -243,7 +250,7 @@ describe("upsertTips", () => { await upsertTips(tipsEvent); expect(mocks.getCurrentRollupVersionNumber).toHaveBeenCalledOnce(); - expect(mocks.where).toHaveBeenCalledTimes(4); + expect(mocks.limit).toHaveBeenCalledTimes(4); expect(mocks.state.insertValues[0]).toMatchObject({ degradedReason: null }); }); }); diff --git a/services/explorer-api/tests/unit/open-gap-scheduler.test.ts b/services/explorer-api/tests/unit/open-gap-scheduler.test.ts index 379ecdbce..c1547dc9c 100644 --- a/services/explorer-api/tests/unit/open-gap-scheduler.test.ts +++ b/services/explorer-api/tests/unit/open-gap-scheduler.test.ts @@ -4,7 +4,6 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; const INTERVAL_MS = 120_000; const TIP = 104_595; -const PROVEN_TIP = 104_539; const dialect = new PgDialect(); const render = (condition: unknown) => dialect.sqlToQuery(condition as SQL); @@ -37,7 +36,7 @@ const mocks = vi.hoisted(() => { deleted: [] as unknown[], updates: [] as Array>, updateTargets: [] as unknown[][], - tips: {} as { degradedReason?: string; provenTip?: number }, + unresolvedHeights: [] as number[], publishFails: false, order: [] as string[], }; @@ -159,12 +158,8 @@ vi.mock( () => ({ getCurrentRollupVersionNumber: () => Promise.resolve(1) }), ); vi.mock("../../src/svcs/database/controllers/l2/tips.js", () => ({ - getTips: () => - Promise.resolve({ - proposed: { number: TIP }, - proven: { block: { number: mocks.state.tips.provenTip ?? PROVEN_TIP } }, - degradedReason: mocks.state.tips.degradedReason, - }), + getUnresolvedBoundaryHeights: () => + Promise.resolve(mocks.state.unresolvedHeights), })); vi.mock("../../src/svcs/database/controllers/l2block/get-latest.js", () => ({ getLatestHeight: () => Promise.resolve(BigInt(TIP)), @@ -239,7 +234,7 @@ beforeEach(() => { deleted: [], updates: [], updateTargets: [], - tips: {}, + unresolvedHeights: [], publishFails: false, order: [], }); @@ -613,20 +608,8 @@ describe("selection", () => { }); describe("buildTipBoundaryRepairRequest", () => { - it("sends the window for a hash mismatch above the proven tip too", async () => { - mocks.state.tips = { - degradedReason: `proposed boundary block ${TIP - 2} hash mismatch: db=0x1 tip=0x2`, - }; - - const planned = await buildTipBoundaryRepairRequest(); - - expect(planned?.request.ranges).toEqual([range(TIP - 7, TIP + 3)]); - }); - - it("sends the window for a missing block", async () => { - mocks.state.tips = { - degradedReason: `proposed boundary block ${TIP - 2} is missing`, - }; + it("sends the window around the most recently seen open mismatch", async () => { + mocks.state.unresolvedHeights = [TIP - 2, 98106]; const planned = await buildTipBoundaryRepairRequest(); @@ -636,10 +619,8 @@ describe("buildTipBoundaryRepairRequest", () => { expect(mocks.state.upserts[0].set).not.toHaveProperty("requestCount"); }); - it("backs off while its row is not due", async () => { - mocks.state.tips = { - degradedReason: "finalized boundary block 98106 is missing", - }; + it("passes over a window that is backing off, and sends nothing while every one is", async () => { + mocks.state.unresolvedHeights = [98106, TIP - 2]; mocks.state.gaps = [ gap({ id: "MAINNET:tip_boundary_mismatch:98101:98111", @@ -650,6 +631,10 @@ describe("buildTipBoundaryRepairRequest", () => { }), ]; + const planned = await buildTipBoundaryRepairRequest(); + expect(planned?.request.ranges).toEqual([range(TIP - 7, TIP + 3)]); + + mocks.state.unresolvedHeights = [98106]; await expect(buildTipBoundaryRepairRequest()).resolves.toBeNull(); }); }); From 8dc2b402881284228d597231b14d1e8a655e8415 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 02:45:54 +0000 Subject: [PATCH 04/34] fix: retire cached chain reads when the chain changes 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 --- .../src/events/received/on-block/index.ts | 4 + services/explorer-api/src/start.ts | 3 + .../src/svcs/cache/chain-revision.ts | 31 +++++++ .../http-server/routes/controllers/blocks.ts | 5 +- .../routes/controllers/contract-instances.ts | 24 +++-- .../routes/controllers/tx-effects.ts | 6 +- .../svcs/http-server/routes/controllers/ui.ts | 2 +- .../routes/controllers/utils/db-wrapper.ts | 36 +++++++- .../consumer-replay.corpus.test.ts | 5 + .../chain-cache.integration.test.ts | 91 +++++++++++++++++++ .../recorded-blocks.integration.test.ts | 44 +++++---- .../explorer-api/tests/unit/start-up.test.ts | 64 +++++++++++++ .../src/hooks/websocket/message-callbacks.ts | 34 ++++--- .../tests/characterization/ws-frame.test.ts | 50 +++++++--- 14 files changed, 340 insertions(+), 59 deletions(-) create mode 100644 services/explorer-api/src/svcs/cache/chain-revision.ts create mode 100644 services/explorer-api/tests/integration/chain-cache.integration.test.ts create mode 100644 services/explorer-api/tests/unit/start-up.test.ts diff --git a/services/explorer-api/src/events/received/on-block/index.ts b/services/explorer-api/src/events/received/on-block/index.ts index 7bec3f7ac..5bcb92a84 100644 --- a/services/explorer-api/src/events/received/on-block/index.ts +++ b/services/explorer-api/src/events/received/on-block/index.ts @@ -11,6 +11,7 @@ import { z } from "zod"; import { SERVICE_NAME } from "../../../constants.js"; import { L2_NETWORK_ID } from "../../../environment.js"; import { logger } from "../../../logger.js"; +import { bumpChainRevision } from "../../../svcs/cache/chain-revision.js"; import { observeRollupVersion } from "../../../svcs/database/controllers/l2/chain-info/rollup-version-cache.js"; import { applyCatchupBlock, @@ -52,6 +53,9 @@ const afterCommit = async ( { block }: IncomingBlock, { canonical }: ChainOutcome, ) => { + // Any applied block can change a cached chain read: the statuses it + // changed, the txs and contracts it took, its children's orphan flags. + await bumpChainRevision(); if (!canonical) { return; } diff --git a/services/explorer-api/src/start.ts b/services/explorer-api/src/start.ts index 1c604fdec..16e606c36 100644 --- a/services/explorer-api/src/start.ts +++ b/services/explorer-api/src/start.ts @@ -7,6 +7,7 @@ import { } from "./environment.js"; import { subscribeHandlers } from "./events/received/index.js"; import { logger } from "./logger.js"; +import { bumpChainRevision } from "./svcs/cache/chain-revision.js"; import { removeMinedDroppedTxs } from "./svcs/database/controllers/dropped-tx/remove.js"; import { updateContractInstanceAztecScanNotes } from "./svcs/database/controllers/l2/aztec-scan-notes.js"; import { initializeRollupVersionCache } from "./svcs/database/controllers/l2/chain-info/rollup-version-cache.js"; @@ -47,6 +48,8 @@ ORIGIN: ${notes.origin}`); return; } + // A crash between a block's commit and its bump left that bump undone. + await bumpChainRevision(); await subscribeHandlers(); // Through the reconciliation ticks, so a shutdown during startup waits for // these requests and no interval is armed after it. diff --git a/services/explorer-api/src/svcs/cache/chain-revision.ts b/services/explorer-api/src/svcs/cache/chain-revision.ts new file mode 100644 index 000000000..c9bf03a5e --- /dev/null +++ b/services/explorer-api/src/svcs/cache/chain-revision.ts @@ -0,0 +1,31 @@ +import { getEntry, setEntry } from "@chicmoz-pkg/redis-helper"; +import { randomUUID } from "node:crypto"; +import { logger } from "../../logger.js"; + +const CHAIN_REVISION = "chainRevision"; +const NO_REVISION = "none"; +// Longer than any entry it keys lives: a revision that expired back to +// NO_REVISION would serve the entries cached under it before the last bump. +const CHAIN_REVISION_TTL_SECONDS = 7 * 24 * 60 * 60; + +/** The last part of a chain read's cache key: a chain change retires it. */ +export const getChainRevision = async (): Promise => + (await getEntry([CHAIN_REVISION])).value ?? NO_REVISION; + +/** + * Retires every chain read cached so far. A random value, not a counter: the + * cache client has no atomic increment, and the keys only need a value never + * used before. A failed bump is logged, and those reads live out their TTL. + */ +export const bumpChainRevision = async (): Promise => { + const stored = await setEntry( + [CHAIN_REVISION], + randomUUID(), + CHAIN_REVISION_TTL_SECONDS, + ); + if (!stored) { + logger.warn( + "Could not bump the chain revision: cached chain reads live out their TTL", + ); + } +}; diff --git a/services/explorer-api/src/svcs/http-server/routes/controllers/blocks.ts b/services/explorer-api/src/svcs/http-server/routes/controllers/blocks.ts index f99df5a1a..a6dec8df1 100644 --- a/services/explorer-api/src/svcs/http-server/routes/controllers/blocks.ts +++ b/services/explorer-api/src/svcs/http-server/routes/controllers/blocks.ts @@ -89,8 +89,9 @@ export const openapi_GET_BLOCK: OpenAPIObject["paths"] = { export const GET_BLOCK = asyncHandler(async (req, res) => { const { heightOrHash } = getBlockByHeightOrHashSchema.parse(req).params; - const blockData = await dbWrapper.get(["l2", "blocks", heightOrHash], () => - db.l2Block.getBlock(heightOrHash), + const blockData = await dbWrapper.getOnChain( + ["l2", "blocks", heightOrHash], + () => db.l2Block.getBlock(heightOrHash), ); res.status(200).json(await parseWithFreshNativeStatuses(blockData)); }); diff --git a/services/explorer-api/src/svcs/http-server/routes/controllers/contract-instances.ts b/services/explorer-api/src/svcs/http-server/routes/controllers/contract-instances.ts index 00784e43a..056dbe75e 100644 --- a/services/explorer-api/src/svcs/http-server/routes/controllers/contract-instances.ts +++ b/services/explorer-api/src/svcs/http-server/routes/controllers/contract-instances.ts @@ -156,11 +156,13 @@ export const GET_L2_CONTRACT_INSTANCE = asyncHandler(async (req, res) => { }); return; } - const instanceData = await dbWrapper.get(contractInstanceKeys(address), () => - db.l2Contract.getL2DeployedContractInstanceByAddress( - address, - includeArtifactJson, - ), + const instanceData = await dbWrapper.getOnChain( + contractInstanceKeys(address), + () => + db.l2Contract.getL2DeployedContractInstanceByAddress( + address, + includeArtifactJson, + ), ); res.status(200).json(JSON.parse(instanceData)); }); @@ -276,7 +278,7 @@ export const GET_L2_CONTRACT_INSTANCES_BY_BLOCK_HASH = asyncHandler( getContractInstancesByBlockHashSchema.parse(req).params; const { includeArtifactJson } = getContractInstancesByBlockHashSchema.parse(req).query; - const instances = await dbWrapper.get( + const instances = await dbWrapper.getOnChain( ["l2", "contract-instances", "block", blockHash], () => db.l2Contract.getL2DeployedContractInstancesByBlockHash( @@ -348,7 +350,7 @@ export const POST_L2_VERIFY_CONTRACT_INSTANCE_DEPLOYMENT = asyncHandler( }, }, } = postVerifiedContractInstanceSchema.parse(req); - const instanceData = await dbWrapper.get( + const instanceData = await dbWrapper.getOnChain( ["l2", "contract-instances", address], () => db.l2Contract.getL2DeployedContractInstanceByAddress(address), ); @@ -508,11 +510,15 @@ export const POST_L2_VERIFY_CONTRACT_INSTANCE_DEPLOYMENT = asyncHandler( constructorArgs, }); + // Keyed before the read, as `onChainKeys` requires. + const instanceKeys = await dbWrapper.onChainKeys( + contractInstanceKeys(address), + ); if (!deployerMetadata) { const freshInstance = await l2Contract.getL2DeployedContractInstanceByAddress(address, true); await setEntry( - contractInstanceKeys(address), + instanceKeys, JSON.stringify(freshInstance), CACHE_TTL_SECONDS, ).catch((err) => { @@ -547,7 +553,7 @@ export const POST_L2_VERIFY_CONTRACT_INSTANCE_DEPLOYMENT = asyncHandler( await l2Contract.getL2DeployedContractInstanceByAddress(address, true); await setEntry( - contractInstanceKeys(address), + instanceKeys, JSON.stringify(newContractInstance), CACHE_TTL_SECONDS, ).catch((err) => { diff --git a/services/explorer-api/src/svcs/http-server/routes/controllers/tx-effects.ts b/services/explorer-api/src/svcs/http-server/routes/controllers/tx-effects.ts index cb36470ef..a15b91c59 100644 --- a/services/explorer-api/src/svcs/http-server/routes/controllers/tx-effects.ts +++ b/services/explorer-api/src/svcs/http-server/routes/controllers/tx-effects.ts @@ -54,7 +54,7 @@ export const openapi_GET_L2_TX_EFFECTS_BY_BLOCK_HEIGHT: OpenAPIObject["paths"] = export const GET_L2_TX_EFFECTS_BY_BLOCK_HEIGHT = asyncHandler( async (req, res) => { const { blockHeight } = getTxEffectsByBlockHeightSchema.parse(req).params; - const txEffectsData = await dbWrapper.get( + const txEffectsData = await dbWrapper.getOnChain( ["l2", "blocks", blockHeight, "txEffects"], () => db.l2TxEffect.getTxEffectsByBlockHeight(blockHeight), ); @@ -95,7 +95,7 @@ export const GET_L2_TX_EFFECT_BY_BLOCK_HEIGHT_AND_INDEX = asyncHandler( async (req, res) => { const { blockHeight, txEffectIndex } = getTxEffectByBlockHeightAndIndexSchema.parse(req).params; - const txEffectsData = await dbWrapper.get( + const txEffectsData = await dbWrapper.getOnChain( ["l2", "blocks", blockHeight, "txEffects", txEffectIndex], () => db.l2TxEffect.getTxEffectByBlockHeightAndIndex( @@ -132,7 +132,7 @@ export const openapi_GET_L2_TX_EFFECT_BY_TX_EFFECT_HASH: OpenAPIObject["paths"] export const GET_L2_TX_EFFECT_BY_TX_EFFECT_HASH = asyncHandler( async (req, res) => { const { txEffectHash } = getTxEffectsByTxHashSchema.parse(req).params; - const txEffectsData = await dbWrapper.get( + const txEffectsData = await dbWrapper.getOnChain( ["l2", "txEffects", txEffectHash], () => db.l2TxEffect.getTxEffectByHash(txEffectHash), ); diff --git a/services/explorer-api/src/svcs/http-server/routes/controllers/ui.ts b/services/explorer-api/src/svcs/http-server/routes/controllers/ui.ts index bb0d99db6..996dde0b7 100644 --- a/services/explorer-api/src/svcs/http-server/routes/controllers/ui.ts +++ b/services/explorer-api/src/svcs/http-server/routes/controllers/ui.ts @@ -122,7 +122,7 @@ export const openapi_GET_TX_EFFECTS_BY_BLOCK_HEIGHT_UI_TABLE: OpenAPIObject["pat export const GET_TX_EFFECTS_BY_BLOCK_HEIGHT_UI_TABLE = asyncHandler( async (req, res) => { const { blockHeight } = getTxEffectsByBlockHeightSchema.parse(req).params; - const txEffectsData = await dbWrapper.get( + const txEffectsData = await dbWrapper.getOnChain( ["l2", "blocks", blockHeight, "txEffects"], () => db.ui.getTxEffectForUiTable({ blockHeight, getType: 1 }), ); diff --git a/services/explorer-api/src/svcs/http-server/routes/controllers/utils/db-wrapper.ts b/services/explorer-api/src/svcs/http-server/routes/controllers/utils/db-wrapper.ts index 9b3f529e8..024c161d6 100644 --- a/services/explorer-api/src/svcs/http-server/routes/controllers/utils/db-wrapper.ts +++ b/services/explorer-api/src/svcs/http-server/routes/controllers/utils/db-wrapper.ts @@ -5,13 +5,25 @@ import { CACHE_TTL_SECONDS, } from "../../../../../environment.js"; import { logger } from "../../../../../logger.js"; +import { getChainRevision } from "../../../../cache/chain-revision.js"; import { dbParseErrorCallback } from "../../../../database/controllers/utils.js"; import { controllers as db } from "../../../../database/index.js"; const LATEST_HEIGHT = "latestHeight"; -export const getLatestHeight = async () => { - const cacheRes = await getEntry([LATEST_HEIGHT]); +/** + * Keys for a read whose answer depends on which blocks are canonical. Take + * them before reading the data: a read that sees a bumped revision then sees + * the commit the bump follows. + */ +export const onChainKeys = async (keys: CacheKeys): Promise => [ + ...keys, + await getChainRevision(), +]; + +const latestHeightAt = async (revision: string) => { + const keys = [LATEST_HEIGHT, revision]; + const cacheRes = await getEntry(keys); const cachedVal = cacheRes.value; const isCached = cachedVal !== null && cachedVal !== undefined; if (isCached) { @@ -20,22 +32,30 @@ export const getLatestHeight = async () => { const dbVal = await db.l2Block.getLatestHeight().catch(dbParseErrorCallback); if (dbVal) { - await setEntry([LATEST_HEIGHT], dbVal.toString(), CACHE_LATEST_TTL_SECONDS); + await setEntry(keys, dbVal.toString(), CACHE_LATEST_TTL_SECONDS); return dbVal; } throw new Error("CACHE_ERROR: latest height not found"); }; +export const getLatestHeight = async () => + latestHeightAt(await getChainRevision()); + export const getLatest = async ( keys: CacheKeys, dbFn: () => Promise, ): Promise => { - const latestHeight = await getLatestHeight(); + const revision = await getChainRevision(); + const latestHeight = await latestHeightAt(revision); if (!latestHeight) { throw new Error("CACHE_ERROR: latest height not found"); } // NOTE: we add one second to the TTL to ensure that stale cache is not stored - return get([...keys, latestHeight], dbFn, CACHE_LATEST_TTL_SECONDS + 1); + return get( + [...keys, latestHeight, revision], + dbFn, + CACHE_LATEST_TTL_SECONDS + 1, + ); }; export const get = async ( @@ -61,3 +81,9 @@ export const get = async ( } throw new Error(`CACHE_ERROR: ${keys.toString()} not found`); }; + +/** `get` for a read whose answer depends on which blocks are canonical. */ +export const getOnChain = async ( + keys: CacheKeys, + dbFn: () => Promise, +): Promise => get(await onChainKeys(keys), dbFn); diff --git a/services/explorer-api/tests/characterization/consumer-replay.corpus.test.ts b/services/explorer-api/tests/characterization/consumer-replay.corpus.test.ts index 7307317ce..4da8f7429 100644 --- a/services/explorer-api/tests/characterization/consumer-replay.corpus.test.ts +++ b/services/explorer-api/tests/characterization/consumer-replay.corpus.test.ts @@ -96,6 +96,11 @@ vi.mock("../../src/svcs/database/controllers/chain-lock.js", () => ({ withChainLock: (fn: (dbTx: unknown) => Promise) => fn("chain-locked transaction"), })); +// The block consumers bump it; its real module reads the Redis environment on +// import. +vi.mock("../../src/svcs/cache/chain-revision.js", () => ({ + bumpChainRevision: seam.record("bumpChainRevision"), +})); // Only the compile-result consumer uses it; its real module reads the Redis // environment on import. vi.mock( diff --git a/services/explorer-api/tests/integration/chain-cache.integration.test.ts b/services/explorer-api/tests/integration/chain-cache.integration.test.ts new file mode 100644 index 000000000..19ae9e709 --- /dev/null +++ b/services/explorer-api/tests/integration/chain-cache.integration.test.ts @@ -0,0 +1,91 @@ +import { type HexString } from "@chicmoz-pkg/types"; +import { deliver } from "@chicmoz/test-harness"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { + type BuiltBlock, + buildBlock, + freshTxHash, + orderedEvent, +} from "./support/blocks.js"; +import { loadChainReads } from "./support/chain.js"; +import { + type ExplorerApiForTest, + startExplorerApiForTest, +} from "./support/explorer-api.js"; + +type Holder = { blockHash: HexString; isOrphaned: boolean }; + +describe("cached chain reads on a real database and Redis", () => { + let api: ExplorerApiForTest; + let store: (b: BuiltBlock) => Promise; + let reads: Awaited>; + + const body = async (path: string): Promise => { + const res = await api.request.get(path); + expect(res.status, `GET ${path}: ${res.text.slice(0, 300)}`).toBe(200); + return res.body as T; + }; + const holder = ({ blockHash, isOrphaned }: Holder) => [blockHash, isOrphaned]; + + beforeAll(async () => { + api = await startExplorerApiForTest(); + const { blockHandler } = await import( + "../../src/events/received/on-block/index.js" + ); + reads = await loadChainReads(); + store = (b) => deliver(blockHandler, orderedEvent(b)); + }); + + afterAll(async () => { + await api?.close(); + }); + + // The prune leaves the tip's height, and so the latest height in the + // latest-block keys, as it was. + it("serves the block that replaced the tip, and the tx and instance it took, from a warm cache", async () => { + const parent = await buildBlock(1n, [freshTxHash()], { + effect: "publishesClass", + }); + const deployTx = freshTxHash(); + const atTip = () => + buildBlock(2n, [deployTx], { parent, effect: "deploysInstance" }); + const replaced = await atTip(); + const replacing = await atTip(); + await store(parent); + await store(replaced); + const [address] = await reads.instancesOf(replaced.hash); + const served = async () => ({ + latest: (await body<{ hash: HexString }>("/l2/blocks/latest")).hash, + atHeight: (await body<{ hash: HexString }>("/l2/blocks/2")).hash, + replacedOnChain: !( + await body<{ orphan?: unknown }>(`/l2/blocks/${replaced.hash}`) + ).orphan, + txEffectsAtHeight: (await body("/l2/blocks/2/tx-effects")).map( + holder, + ), + txEffectAtIndex: holder(await body("/l2/blocks/2/tx-effects/0")), + txEffect: holder(await body(`/l2/tx-effects/${deployTx}`)), + instance: holder(await body(`/l2/contract-instances/${address}`)), + instancesOfReplaced: ( + await body<{ address: HexString }[]>( + `/l2/blocks/${replaced.hash}/contract-instances`, + ) + ).map((i) => i.address), + }); + const servedWith = (tip: BuiltBlock) => ({ + latest: tip.hash, + atHeight: tip.hash, + replacedOnChain: tip === replaced, + txEffectsAtHeight: [[tip.hash, false]], + txEffectAtIndex: [tip.hash, false], + txEffect: [tip.hash, false], + instance: [tip.hash, false], + instancesOfReplaced: tip === replaced ? [address] : [], + }); + expect(await served()).toEqual(servedWith(replaced)); + + await store(replacing); + + expect(await served()).toEqual(servedWith(replacing)); + }); +}); diff --git a/services/explorer-api/tests/integration/recorded-blocks.integration.test.ts b/services/explorer-api/tests/integration/recorded-blocks.integration.test.ts index fb04551d3..4a681b417 100644 --- a/services/explorer-api/tests/integration/recorded-blocks.integration.test.ts +++ b/services/explorer-api/tests/integration/recorded-blocks.integration.test.ts @@ -11,6 +11,7 @@ import { type L1L2ValidatorEvent, type PendingTxsEvent, } from "@chicmoz-pkg/message-registry"; +import { type CacheKeys } from "@chicmoz-pkg/redis-helper"; import { BSON } from "bson"; import { existsSync, readFileSync } from "node:fs"; import { @@ -132,6 +133,14 @@ describe("recorded chain data read back through Postgres and Redis", () => { return body; }; + /** A chain read's keys at the current chain revision, which every stored block moves. */ + const chainKeys = async (keys: CacheKeys) => { + const { onChainKeys } = await import( + "../../src/svcs/http-server/routes/controllers/utils/db-wrapper.js" + ); + return onChainKeys(keys); + }; + beforeAll(async () => { api = await startExplorerApiForTest(); }); @@ -284,8 +293,12 @@ describe("recorded chain data read back through Postgres and Redis", () => { describe("contract instance verification", () => { const [address] = INSTANCES; const artifact = rawArtifact("auth_registry_contract-AuthRegistry"); - const instanceEntry = () => - cacheAt(api.stack, api.namespace, ["l2", "contract-instances", address]); + const instanceEntry = async () => + cacheAt( + api.stack, + api.namespace, + await chainKeys(["l2", "contract-instances", address]), + ); let deploymentArguments: { publicKeysString: string; salt: string; @@ -315,7 +328,7 @@ describe("recorded chain data read back through Postgres and Redis", () => { // The POST reads the instance through the cache; a 200 while the row's // salt disagrees proves the answer came from the committed string. it("POST verifies the recorded deployment from the committed string of its cache entry", async () => { - const entry = instanceEntry(); + const entry = await instanceEntry(); await entry.remove(); const first = await verify({ verifiedDeploymentArguments: { @@ -416,7 +429,7 @@ describe("recorded chain data read back through Postgres and Redis", () => { // The entry now carries the notes and metadata, which the POST's reader // parses too; the salt control proves the committed string answered. it("POST verifies from the committed cache string that carries the notes and metadata", async () => { - const entry = instanceEntry(); + const entry = await instanceEntry(); await entry.remove(); const miss = await verify({ verifiedDeploymentArguments: { @@ -460,7 +473,7 @@ describe("recorded chain data read back through Postgres and Redis", () => { // Their cache entries are removed, as when they expire, so the routes // read the rows the verification left. it("class and instance read back with the stored artifact, deployment arguments and notes", async () => { - await instanceEntry().remove(); + await (await instanceEntry()).remove(); expect( snapshotOf( await get( @@ -513,11 +526,11 @@ describe("recorded chain data read back through Postgres and Redis", () => { it("GET /l2/rpc-nodes answers from the committed string of its cache entry", async () => { const path = "/l2/rpc-nodes"; await deliverRpcNode(); - const entry = cacheAt(api.stack, api.namespace, [ - "l2", - "rpc-nodes", - LOCAL_TIP, - ]); + const entry = cacheAt( + api.stack, + api.namespace, + await chainKeys(["l2", "rpc-nodes", LOCAL_TIP]), + ); await entry.remove(); expect(await get(path, path)).toHaveLength(1); const committed = await pinCacheString(entry, "rpc-nodes"); @@ -533,12 +546,11 @@ describe("recorded chain data read back through Postgres and Redis", () => { await deliverRpcNode(); const { rpcNodeName } = RPC_NODE.rpcNode; const path = `/l2/rpc-nodes/${rpcNodeName}`; - const entry = cacheAt(api.stack, api.namespace, [ - "l2", - "rpc-nodes", - rpcNodeName, - LOCAL_TIP, - ]); + const entry = cacheAt( + api.stack, + api.namespace, + await chainKeys(["l2", "rpc-nodes", rpcNodeName, LOCAL_TIP]), + ); await entry.remove(); await get(path, "/l2/rpc-nodes/:rpcNodeName"); // The node's own times come from its payload and the frozen clock; only diff --git a/services/explorer-api/tests/unit/start-up.test.ts b/services/explorer-api/tests/unit/start-up.test.ts new file mode 100644 index 000000000..c102d3bb6 --- /dev/null +++ b/services/explorer-api/tests/unit/start-up.test.ts @@ -0,0 +1,64 @@ +import { describe, expect, it, vi } from "vitest"; + +const steps = vi.hoisted(() => { + const order: string[] = []; + const step = (name: string) => () => { + order.push(name); + return Promise.resolve(); + }; + return { order, step }; +}); + +vi.mock("../../src/environment.js", () => ({ + ARCHIVE_MODE: false, + L1_GOVERNANCE_URI_RECONCILIATION_ENABLED: false, + L2_BLOCK_RECONCILIATION_ENABLED: false, + L2_NETWORK_ID: "SANDBOX", +})); +vi.mock("../../src/constants.js", () => ({ AZTEC_SCAN_NOTES: {} })); +vi.mock("../../src/logger.js", () => ({ logger: { info: vi.fn() } })); +vi.mock("../../src/svcs/database/controllers/l2Tx/delete-all-txs.js", () => ({ + deleteAllTxs: vi.fn(), +})); +vi.mock("../../src/svcs/database/controllers/dropped-tx/remove.js", () => ({ + removeMinedDroppedTxs: steps.step("sweep"), +})); +vi.mock( + "../../src/svcs/database/controllers/l2/chain-info/rollup-version-cache.js", + () => ({ initializeRollupVersionCache: vi.fn() }), +); +vi.mock("../../src/utils/protocol-contracts.js", () => ({ + initializeProtocolContracts: vi.fn(), +})); +vi.mock("../../src/svcs/database/controllers/l2/aztec-scan-notes.js", () => ({ + updateContractInstanceAztecScanNotes: vi.fn(), +})); +vi.mock("../../src/svcs/cache/chain-revision.js", () => ({ + bumpChainRevision: steps.step("bump"), +})); +vi.mock("../../src/events/received/index.js", () => ({ + subscribeHandlers: steps.step("subscribe"), +})); +vi.mock("../../src/svcs/reconciliation/l2-block-reconciliation.js", () => ({ + runL2BlockReconciliationOnce: vi.fn(), + startL2BlockReconciliation: vi.fn(), +})); +vi.mock( + "../../src/svcs/reconciliation/governance-uri-reconciliation.js", + () => ({ + runGovernanceUriReconciliationOnce: vi.fn(), + startGovernanceUriReconciliation: vi.fn(), + }), +); + +describe("explorer-api start-up", () => { + // A crash between a block's commit and its bump leaves cached chain reads + // from before that commit; the sweep's deletions change them too. + it("bumps the chain revision after the dropped-tx sweep, before it consumes", async () => { + const { start } = await import("../../src/start.js"); + + await start(); + + expect(steps.order).toEqual(["sweep", "bump", "subscribe"]); + }); +}); diff --git a/services/explorer-ui-v2/src/hooks/websocket/message-callbacks.ts b/services/explorer-ui-v2/src/hooks/websocket/message-callbacks.ts index 981d63168..abd5496e5 100644 --- a/services/explorer-ui-v2/src/hooks/websocket/message-callbacks.ts +++ b/services/explorer-ui-v2/src/hooks/websocket/message-callbacks.ts @@ -1,6 +1,25 @@ import type { QueryClient } from "@tanstack/react-query"; import { queryKeyGenerator } from "~/hooks/api"; +const prefixOf = (queryKey: readonly unknown[]) => queryKey.slice(0, 1); + +// Refreshed on a block or tips frame. Either can follow a prune, which changes +// the reorg lists and any block or tx already shown: the detail queries go by +// prefix, whatever block or tx they name. +const CHAIN_QUERIES = [ + queryKeyGenerator.latestBlock, + queryKeyGenerator.latestTableBlocks, + queryKeyGenerator.blocksByNativeStatus, + queryKeyGenerator.l2TipsHealth, + queryKeyGenerator.reorgs, + queryKeyGenerator.orphanedBlocks, + prefixOf(queryKeyGenerator.blockByHeight("")), + prefixOf(queryKeyGenerator.txEffectsByBlockHeight(undefined)), + prefixOf(queryKeyGenerator.txEffectByHash("")), + prefixOf(queryKeyGenerator.pendingTxsByHash("")), + prefixOf(queryKeyGenerator.droppedTxByHash("")), +]; + /** * The websocket publisher sends compact payloads such as `{ block }` and * `{ txs }`. Older/alternate publishers may send a `{ topic }` envelope, so we @@ -37,18 +56,9 @@ export const handleWebSocketMessage = async ( const hasStatsUpdate = topic?.includes("stats") ?? false; if (hasBlockUpdate || hasTipsUpdate) { - await queryClient.invalidateQueries({ - queryKey: queryKeyGenerator.latestBlock, - }); - await queryClient.invalidateQueries({ - queryKey: queryKeyGenerator.latestTableBlocks, - }); - await queryClient.invalidateQueries({ - queryKey: queryKeyGenerator.blocksByNativeStatus, - }); - await queryClient.invalidateQueries({ - queryKey: queryKeyGenerator.l2TipsHealth, - }); + for (const queryKey of CHAIN_QUERIES) { + await queryClient.invalidateQueries({ queryKey }); + } } if (hasTxUpdate) { diff --git a/services/explorer-ui-v2/tests/characterization/ws-frame.test.ts b/services/explorer-ui-v2/tests/characterization/ws-frame.test.ts index f5168c38c..e71f70158 100644 --- a/services/explorer-ui-v2/tests/characterization/ws-frame.test.ts +++ b/services/explorer-ui-v2/tests/characterization/ws-frame.test.ts @@ -19,27 +19,55 @@ const PUBLISHED_BLOCK_FRAME = new URL( import.meta.url, ); +const TX = `0x${"cd".repeat(32)}`; +// Views a prune can change: the reorg lists, and block and tx details by +// height and by hash. +const CHAIN_VIEWS = [ + queryKeyGenerator.reorgs, + queryKeyGenerator.orphanedBlocks, + queryKeyGenerator.blockByHeight("7"), + queryKeyGenerator.blockByHeight(`0x${"ab".repeat(32)}`), + queryKeyGenerator.txEffectsByBlockHeight(7), + queryKeyGenerator.txEffectByHash(TX), + queryKeyGenerator.pendingTxsByHash(TX), + queryKeyGenerator.droppedTxByHash(TX), +]; +// A block frame says nothing about it. +const UNRELATED = queryKeyGenerator.averageFees; + +const staleAfter = async (frame: string, views: unknown[][]) => { + const queryClient = new QueryClient(); + for (const key of [...views, UNRELATED]) { + queryClient.setQueryData(key, []); + } + await handleWebSocketMessage(queryClient, frame); + return { + views: views.map((key) => queryClient.getQueryState(key)?.isInvalidated), + unrelated: queryClient.getQueryState(UNRELATED)?.isInvalidated, + }; +}; + // The handler drops a frame it cannot parse or whose keys it does not know, // without a word, so a change to the publisher's frame would silently stop // live updates. A hand-written frame here would not follow the publisher. describe("websocket frames from the publisher", () => { - it("a published block frame marks the latest-block and block-table queries stale", async () => { - const queryClient = new QueryClient(); + it("a published block frame marks the latest-block, block-table and chain detail queries stale", async () => { const views = [ queryKeyGenerator.latestBlock, queryKeyGenerator.latestTableBlocks, + ...CHAIN_VIEWS, ]; - for (const key of views) { - queryClient.setQueryData(key, []); - } - await handleWebSocketMessage( - queryClient, - readFileSync(PUBLISHED_BLOCK_FRAME, "utf8"), - ); + expect( + await staleAfter(readFileSync(PUBLISHED_BLOCK_FRAME, "utf8"), views), + ).toEqual({ views: views.map(() => true), unrelated: false }); + }); + // No publisher test records a tips frame. The publisher sends `{ l2Tips }` + // (`sendL2TipsToClients`), and the handler reads only that key. + it("a tips frame marks the reorg lists and the chain detail queries stale", async () => { expect( - views.map((key) => queryClient.getQueryState(key)?.isInvalidated), - ).toEqual([true, true]); + await staleAfter(JSON.stringify({ l2Tips: {} }), CHAIN_VIEWS), + ).toEqual({ views: CHAIN_VIEWS.map(() => true), unrelated: false }); }); }); From fdfa1d8a07e69595267de6702b95f71bbc4ec95f Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 02:50:03 +0000 Subject: [PATCH 05/34] test(explorer-api): expect a replaced tip height cleared and requested 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 --- .../late-replacing-block.integration.test.ts | 75 ++++++++++--------- 1 file changed, 39 insertions(+), 36 deletions(-) diff --git a/services/explorer-api/tests/integration/late-replacing-block.integration.test.ts b/services/explorer-api/tests/integration/late-replacing-block.integration.test.ts index 39e45b7ba..ae66b1e5c 100644 --- a/services/explorer-api/tests/integration/late-replacing-block.integration.test.ts +++ b/services/explorer-api/tests/integration/late-replacing-block.integration.test.ts @@ -10,6 +10,7 @@ import { freshTxHash, orderedEvent, } from "./support/blocks.js"; +import { loadChainReads } from "./support/chain.js"; import { type ExplorerApiForTest, startExplorerApiForTest, @@ -40,9 +41,11 @@ describe("a replaced block that stays stored on a real database", () => { let repairRequestCovers: (height: number) => Promise; let lastSeenAgo: (height: number, ms: number) => Promise; let mismatchOpenAt: (height: number) => Promise; + let reads: Awaited>; beforeAll(async () => { api = await startExplorerApiForTest(); + reads = await loadChainReads(); const { blockHandler, catchupHandler } = await import( "../../src/events/received/on-block/index.js" ); @@ -156,43 +159,43 @@ describe("a replaced block that stays stored on a real database", () => { expect(await isDropped(t)).toBe(false); }); - it.fails( - "still requests a replaced height after the next tips validate at other heights", - async () => { - const chain: BuiltBlock[] = []; - for (let height = 400n; height <= 403n; height++) { - chain.push( - await buildBlock(height, [freshTxHash()], { parent: chain.at(-1) }), - ); - } - const [finalized, proven, checkpointed, replaced] = chain; - for (const block of chain) { - await store(block); - } - const replacing = await buildBlock(403n, [freshTxHash()], { - parent: checkpointed, - }); - const next = await buildBlock(404n, [freshTxHash()], { - parent: replacing, + it("still requests a replaced height after the next tips validate at other heights", async () => { + const chain: BuiltBlock[] = []; + for (let height = 400n; height <= 403n; height++) { + chain.push( + await buildBlock(height, [freshTxHash()], { parent: chain.at(-1) }), + ); + } + const [finalized, proven, checkpointed] = chain; + for (const block of chain) { + await store(block); + } + const replacing = await buildBlock(403n, [freshTxHash()], { + parent: checkpointed, + }); + const next = await buildBlock(404n, [freshTxHash()], { + parent: replacing, + }); + const tipsAt = (proposed: BuiltBlock) => + storeTips({ + proposed: { number: Number(proposed.height), hash: proposed.hash }, + finalized, + proven, + checkpointed, }); - const tipsAt = (proposed: BuiltBlock) => - storeTips({ - proposed: { number: Number(proposed.height), hash: proposed.hash }, - finalized, - proven, - checkpointed, - }); - - await tipsAt(replacing); - expect(await repairRequestCovers(403)).toBe(true); - - await store(next); - await tipsAt(next); - - expect(await canonicalHash(403n)).toBe(replaced.hash); - expect(await repairRequestCovers(403)).toBe(true); - }, - ); + + await tipsAt(replacing); + expect(await repairRequestCovers(403)).toBe(true); + + await store(next); + await tipsAt(next); + + // The next ordered block names a parent that is not stored, so the + // stored block at 403 leaves the chain and its height is asked for. + expect(await canonicalHash(403n)).toBeUndefined(); + expect(await reads.repairOpen(403)).toBe(true); + expect(await repairRequestCovers(403)).toBe(true); + }); it("resolves a tip mismatch nothing fixed only a day after it was last seen", async () => { const chain = await buildChain(500n, 4); From 70e836e2519f4f7e951c917039a660001a1f97ec Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 03:26:58 +0000 Subject: [PATCH 06/34] fix(explorer-api): read tx effects by height from canonical blocks only 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 --- .../controllers/l2TxEffect/get-tx-effect.ts | 8 +++- .../chain-cache.integration.test.ts | 43 ++++++++++++------- 2 files changed, 34 insertions(+), 17 deletions(-) diff --git a/services/explorer-api/src/svcs/database/controllers/l2TxEffect/get-tx-effect.ts b/services/explorer-api/src/svcs/database/controllers/l2TxEffect/get-tx-effect.ts index 4874b8b8b..673d62c8c 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2TxEffect/get-tx-effect.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2TxEffect/get-tx-effect.ts @@ -147,6 +147,10 @@ const _getTxEffects = async ( const rollupVersion = await getCurrentRollupVersionNumber(); const versionFilter = rollupVersion !== null ? eq(l2Block.version, rollupVersion) : undefined; + // A block off the chain keeps the effects no canonical block took: they + // are its history, not what its height holds. The latest list keeps them, + // flagged `isOrphaned`. + const heightFilter = and(isNull(l2Block.orphan_timestamp), versionFilter); let whereQuery; @@ -154,7 +158,7 @@ const _getTxEffects = async ( case GetTypes.BlockHeightRange: if (args.from ?? args.to) { whereQuery = joinQuery - .where(and(generateWhereQuery(args.from, args.to), versionFilter)) + .where(and(generateWhereQuery(args.from, args.to), heightFilter)) .orderBy(desc(l2Block.height), desc(txEffect.index)) .limit(DB_MAX_TX_EFFECTS); } else { @@ -170,7 +174,7 @@ const _getTxEffects = async ( and( eq(l2Block.height, args.blockHeight), eq(txEffect.index, args.txEffectIndex), - versionFilter, + heightFilter, ), ) .limit(1); diff --git a/services/explorer-api/tests/integration/chain-cache.integration.test.ts b/services/explorer-api/tests/integration/chain-cache.integration.test.ts index 19ae9e709..d2aa7a7ce 100644 --- a/services/explorer-api/tests/integration/chain-cache.integration.test.ts +++ b/services/explorer-api/tests/integration/chain-cache.integration.test.ts @@ -14,6 +14,7 @@ import { } from "./support/explorer-api.js"; type Holder = { blockHash: HexString; isOrphaned: boolean }; +type Effect = Holder & { txHash: HexString }; describe("cached chain reads on a real database and Redis", () => { let api: ExplorerApiForTest; @@ -26,6 +27,7 @@ describe("cached chain reads on a real database and Redis", () => { return res.body as T; }; const holder = ({ blockHash, isOrphaned }: Holder) => [blockHash, isOrphaned]; + const held = ({ txHash, ...rest }: Effect) => [txHash, ...holder(rest)]; beforeAll(async () => { api = await startExplorerApiForTest(); @@ -42,13 +44,17 @@ describe("cached chain reads on a real database and Redis", () => { // The prune leaves the tip's height, and so the latest height in the // latest-block keys, as it was. - it("serves the block that replaced the tip, and the tx and instance it took, from a warm cache", async () => { + it("serves the block that replaced the tip, the tx and instance it took, and none of the replaced block's own txs, from a warm cache", async () => { const parent = await buildBlock(1n, [freshTxHash()], { effect: "publishesClass", }); const deployTx = freshTxHash(); + // Both blocks include the deploy tx, which moves; each has a tx of its own. const atTip = () => - buildBlock(2n, [deployTx], { parent, effect: "deploysInstance" }); + buildBlock(2n, [deployTx, freshTxHash()], { + parent, + effect: "deploysInstance", + }); const replaced = await atTip(); const replacing = await atTip(); await store(parent); @@ -60,10 +66,10 @@ describe("cached chain reads on a real database and Redis", () => { replacedOnChain: !( await body<{ orphan?: unknown }>(`/l2/blocks/${replaced.hash}`) ).orphan, - txEffectsAtHeight: (await body("/l2/blocks/2/tx-effects")).map( - holder, + txEffectsAtHeight: (await body("/l2/blocks/2/tx-effects")).map( + held, ), - txEffectAtIndex: holder(await body("/l2/blocks/2/tx-effects/0")), + txEffectAtIndex: held(await body("/l2/blocks/2/tx-effects/1")), txEffect: holder(await body(`/l2/tx-effects/${deployTx}`)), instance: holder(await body(`/l2/contract-instances/${address}`)), instancesOfReplaced: ( @@ -72,20 +78,27 @@ describe("cached chain reads on a real database and Redis", () => { ) ).map((i) => i.address), }); - const servedWith = (tip: BuiltBlock) => ({ - latest: tip.hash, - atHeight: tip.hash, - replacedOnChain: tip === replaced, - txEffectsAtHeight: [[tip.hash, false]], - txEffectAtIndex: [tip.hash, false], - txEffect: [tip.hash, false], - instance: [tip.hash, false], - instancesOfReplaced: tip === replaced ? [address] : [], - }); + const servedWith = (tip: BuiltBlock) => { + const [shared, own] = tip.txHashes; + return { + latest: tip.hash, + atHeight: tip.hash, + replacedOnChain: tip === replaced, + txEffectsAtHeight: [ + [own, tip.hash, false], + [shared, tip.hash, false], + ], + txEffectAtIndex: [own, tip.hash, false], + txEffect: [tip.hash, false], + instance: [tip.hash, false], + instancesOfReplaced: tip === replaced ? [address] : [], + }; + }; expect(await served()).toEqual(servedWith(replaced)); await store(replacing); + // The bump retired every warm entry: these reads come from the database. expect(await served()).toEqual(servedWith(replacing)); }); }); From 0173d279b430b5b66b168753abc3723973226619 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 03:30:59 +0000 Subject: [PATCH 07/34] fix(explorer-api): resolve tip mismatches a chain change fixed while 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 --- .../src/svcs/database/controllers/l2/tips.ts | 5 +++-- .../integration/late-replacing-block.integration.test.ts | 9 ++++++++- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/services/explorer-api/src/svcs/database/controllers/l2/tips.ts b/services/explorer-api/src/svcs/database/controllers/l2/tips.ts index dcdcea9b9..989d16245 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2/tips.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2/tips.ts @@ -308,8 +308,8 @@ export const upsertTips = async (event: L2TipsEvent) => { /** * Validates the stored tips again inside a chain change, healthy or * degraded: the change may have stored a block they name, or demoted one. - * An unchanged result writes nothing, so a mismatch's occurrence count - * counts tips events. + * An unchanged result records no mismatch, so a mismatch's occurrence count + * counts tips events, but the change may still have resolved an open one. */ export const revalidateTips = async (dbTx: DbTx) => { const [row] = await dbTx @@ -328,6 +328,7 @@ export const revalidateTips = async (dbTx: DbTx) => { ); const degradedReason = mismatch?.reason ?? null; if (degradedReason === row.degradedReason) { + await resolveBoundaryMismatches(dbTx); return; } await dbTx diff --git a/services/explorer-api/tests/integration/late-replacing-block.integration.test.ts b/services/explorer-api/tests/integration/late-replacing-block.integration.test.ts index ae66b1e5c..0c293f669 100644 --- a/services/explorer-api/tests/integration/late-replacing-block.integration.test.ts +++ b/services/explorer-api/tests/integration/late-replacing-block.integration.test.ts @@ -159,7 +159,7 @@ describe("a replaced block that stays stored on a real database", () => { expect(await isDropped(t)).toBe(false); }); - it("still requests a replaced height after the next tips validate at other heights", async () => { + it("requests a replaced height while the tips validate at other heights, until the block they named arrives", async () => { const chain: BuiltBlock[] = []; for (let height = 400n; height <= 403n; height++) { chain.push( @@ -195,6 +195,13 @@ describe("a replaced block that stays stored on a real database", () => { expect(await canonicalHash(403n)).toBeUndefined(); expect(await reads.repairOpen(403)).toBe(true); expect(await repairRequestCovers(403)).toBe(true); + + // The stored tips stay valid, and the block they named fills the height. + await storeLate(replacing); + + expect(await canonicalHash(403n)).toBe(replacing.hash); + expect(await mismatchOpenAt(403)).toBe(false); + expect(await repairRequestCovers(403)).toBe(false); }); it("resolves a tip mismatch nothing fixed only a day after it was last seen", async () => { From 12af1e61aa333d7f54016fdc2de002149dfc916f Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 03:34:11 +0000 Subject: [PATCH 08/34] fix(explorer-ui-v2): show a tx only an orphaned block holds as not mined 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 --- .../explorer-ui-v2/src/api/dropped-tx.test.ts | 73 ++++++++++++++ services/explorer-ui-v2/src/api/dropped-tx.ts | 22 +++-- .../src/hooks/api/dropped-tx.ts | 4 +- .../src/pages/tx-detail/index.test.tsx | 96 +++++++++++++++++++ .../src/pages/tx-detail/index.tsx | 64 ++++++++----- 5 files changed, 225 insertions(+), 34 deletions(-) create mode 100644 services/explorer-ui-v2/src/api/dropped-tx.test.ts create mode 100644 services/explorer-ui-v2/src/pages/tx-detail/index.test.tsx diff --git a/services/explorer-ui-v2/src/api/dropped-tx.test.ts b/services/explorer-ui-v2/src/api/dropped-tx.test.ts new file mode 100644 index 000000000..bcc0d011f --- /dev/null +++ b/services/explorer-ui-v2/src/api/dropped-tx.test.ts @@ -0,0 +1,73 @@ +import { QueryClient } from "@tanstack/react-query"; +import { AxiosError, type AxiosAdapter, type AxiosResponse } from "axios"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import client from "./client"; +import { DroppedTxAPI } from "./dropped-tx"; + +vi.mock("~/service/constants", () => ({ + API_URL: "https://api.test/key", + aztecExplorer: { + getL2DroppedTxByHash: (hash: string) => `/l2/dropped-txs/${hash}`, + }, +})); + +const TX = `0x${"cd".repeat(32)}`; + +// A custom adapter must reject on its own: axios applies validateStatus only in its built-in adapters. +const answer = + (status: number, data: unknown): AxiosAdapter => + (config) => { + const response: AxiosResponse = { + data, + status, + statusText: "", + headers: {}, + config, + }; + return status < 400 + ? Promise.resolve(response) + : Promise.reject( + new AxiosError( + `Request failed with status code ${status}`, + AxiosError.ERR_BAD_REQUEST, + config, + {}, + response, + ), + ); + }; + +const { adapter } = client.defaults; +afterEach(() => { + client.defaults.adapter = adapter; +}); + +describe("DroppedTxAPI.getDroppedTxByHash", () => { + it("answers null once the tx has no dropped row, so a refetch clears the drop it found before", async () => { + const queryClient = new QueryClient(); + const lookup = { + queryKey: ["droppedTxByHash", TX], + queryFn: () => DroppedTxAPI.getDroppedTxByHash(TX), + retry: false, + }; + client.defaults.adapter = answer(200, { + txHash: TX, + createdAsPendingAt: 1, + droppedAt: 2, + }); + await queryClient.fetchQuery(lookup); + + client.defaults.adapter = answer(404, "not found"); + await queryClient.refetchQueries({ queryKey: lookup.queryKey }); + + expect(queryClient.getQueryData(lookup.queryKey)).toBeNull(); + }); + + it("still fails on any other error", async () => { + client.defaults.adapter = answer(500, "boom"); + + await expect(DroppedTxAPI.getDroppedTxByHash(TX)).rejects.toMatchObject({ + status: 500, + }); + }); +}); diff --git a/services/explorer-ui-v2/src/api/dropped-tx.ts b/services/explorer-ui-v2/src/api/dropped-tx.ts index 202d87ab2..653145008 100644 --- a/services/explorer-ui-v2/src/api/dropped-tx.ts +++ b/services/explorer-ui-v2/src/api/dropped-tx.ts @@ -3,13 +3,23 @@ import { chicmozL2DroppedTxSchema, } from "@chicmoz-pkg/types"; import { aztecExplorer } from "~/service/constants"; -import client, { validateResponse } from "./client"; +import client, { isNotFoundError, validateResponse } from "./client"; export const DroppedTxAPI = { - getDroppedTxByHash: async (hash: string): Promise => { - const response = await client.get( - aztecExplorer.getL2DroppedTxByHash(hash), - ); - return validateResponse(chicmozL2DroppedTxSchema, response.data); + /** `null` for a tx with no dropped row: a failed refetch would keep the drop it last found. */ + getDroppedTxByHash: async ( + hash: string, + ): Promise => { + try { + const response = await client.get( + aztecExplorer.getL2DroppedTxByHash(hash), + ); + return validateResponse(chicmozL2DroppedTxSchema, response.data); + } catch (error) { + if (isNotFoundError(error)) { + return null; + } + throw error; + } }, }; diff --git a/services/explorer-ui-v2/src/hooks/api/dropped-tx.ts b/services/explorer-ui-v2/src/hooks/api/dropped-tx.ts index 987380aa1..04ba85e39 100644 --- a/services/explorer-ui-v2/src/hooks/api/dropped-tx.ts +++ b/services/explorer-ui-v2/src/hooks/api/dropped-tx.ts @@ -5,8 +5,8 @@ import { queryKeyGenerator } from "./utils"; export const useDroppedTxByHash = ( hash: string, -): UseQueryResult => { - return useQuery({ +): UseQueryResult => { + return useQuery({ queryKey: queryKeyGenerator.droppedTxByHash(hash), queryFn: () => DroppedTxAPI.getDroppedTxByHash(hash), enabled: !!hash, diff --git a/services/explorer-ui-v2/src/pages/tx-detail/index.test.tsx b/services/explorer-ui-v2/src/pages/tx-detail/index.test.tsx new file mode 100644 index 000000000..13b7fabde --- /dev/null +++ b/services/explorer-ui-v2/src/pages/tx-detail/index.test.tsx @@ -0,0 +1,96 @@ +import { type ReactNode } from "react"; +import { renderToStaticMarkup } from "react-dom/server"; +import { describe, expect, it, vi } from "vitest"; + +const TX = `0x${"cd".repeat(32)}`; +const BLOCK = `0x${"ab".repeat(32)}`; +const found = vi.hoisted(() => ({ effect: undefined as unknown })); + +vi.mock("@tanstack/react-router", async () => { + const { createElement } = await import("react"); + return { + Link: ({ + to, + params, + children, + }: { + to: string; + params?: Record; + children: ReactNode; + }) => + createElement( + "a", + { + href: to.replace( + /\$(\w+)/g, + (_, name: string) => params?.[name] ?? "", + ), + }, + children, + ), + useParams: () => ({ hash: TX }), + }; +}); +vi.mock("~/components/layout", () => ({ + Shell: ({ children }: { children: ReactNode }) => children, + ConsoleHead: () => null, +})); +vi.mock("~/hooks/api", () => ({ + usePendingTxsByHash: () => ({ data: undefined }), + useGetTxEffectByHash: () => ({ data: found.effect }), + useDroppedTxByHash: () => ({ data: null }), + usePublicCallRequestsByTxHash: () => ({ data: [] }), + useChainInfo: () => ({ data: undefined }), +})); + +// The components read these from the env at import. +vi.stubEnv("VITE_L2_NETWORK_ID", "SANDBOX"); +vi.stubEnv("VITE_API_URL", "https://api.test"); +vi.stubEnv("VITE_API_KEY", "dev-api-key"); + +const { TxDetailPage } = await import("./index"); + +const render = (isOrphaned: boolean) => { + found.effect = { + txHash: TX, + blockHash: BLOCK, + blockHeight: 7n, + timestamp: 1_700_000_000_000, + isOrphaned, + transactionFee: "1000", + revertCode: { code: 0 }, + noteHashes: [], + nullifiers: [], + publicDataWrites: [], + l2ToL1Msgs: [], + privateLogs: [], + publicLogs: [], + contractClassLogs: [], + }; + const html = renderToStaticMarkup(); + return { + status: /class="status-pill (\w+)"/.exec(html)?.[1], + blockLinks: [...html.matchAll(/href="\/blocks\/([^"]+)"/g)].map( + ([, block]) => block, + ), + notFound: html.includes("tx not found"), + }; +}; + +describe("TxDetailPage", () => { + it("shows a tx whose effect only an orphaned block keeps as not mined, and links that block by hash", () => { + expect(render(true)).toEqual({ + status: "orphaned", + blockLinks: [BLOCK, BLOCK, BLOCK], + notFound: false, + }); + }); + + it("links a mined tx's block by height", () => { + expect(render(false)).toEqual({ + status: "mined", + blockLinks: ["7", "7", "7"], + notFound: false, + }); + }); +}); diff --git a/services/explorer-ui-v2/src/pages/tx-detail/index.tsx b/services/explorer-ui-v2/src/pages/tx-detail/index.tsx index e219ba3f0..a220bbe4b 100644 --- a/services/explorer-ui-v2/src/pages/tx-detail/index.tsx +++ b/services/explorer-ui-v2/src/pages/tx-detail/index.tsx @@ -1,3 +1,4 @@ +import { type ChicmozL2TxEffectDeluxe } from "@chicmoz-pkg/types"; import { Link, useParams } from "@tanstack/react-router"; import { type FC, useState } from "react"; import { @@ -31,6 +32,22 @@ import { type Tab = "notes" | "nulls" | "public" | "l1" | "logs" | "calls"; +// An orphaned block's height now names the block that replaced it. +const EffectBlockLink: FC<{ effect: ChicmozL2TxEffectDeluxe }> = ({ + effect, +}) => ( + + #{fmtNum(Number(effect.blockHeight))} + +); + export const TxDetailPage: FC = () => { const { hash = "" } = useParams({ strict: false }); const [tab, setTab] = useState("notes"); @@ -46,14 +63,18 @@ export const TxDetailPage: FC = () => { const feeJuiceSymbol = getFeeJuiceSymbol(chainInfo?.feeJuiceSymbol); const feeJuiceAddress = chainInfo?.l1ContractAddresses?.feeJuiceAddress; - const mined = !!effect; + // Only a block on the chain mines a tx: an orphaned block's effect is history. + const historical = effect?.isOrphaned === true; + const mined = !!effect && !historical; const status = mined ? "mined" : dropped ? "dropped" : pending ? "pending" - : "pending"; + : historical + ? "orphaned" + : "pending"; const ts = effect?.timestamp ? effect.timestamp @@ -89,15 +110,9 @@ export const TxDetailPage: FC = () => {

{hash}

- {mined && effect?.blockHeight !== undefined && ( + {effect?.blockHeight !== undefined && ( - in{" "} - - #{fmtNum(Number(effect.blockHeight))} - + {historical ? "was in" : "in"} )} {dropped && ( @@ -108,7 +123,7 @@ export const TxDetailPage: FC = () => {
- {mined && effect && ( + {effect && ( <>
@@ -132,12 +147,7 @@ export const TxDetailPage: FC = () => {
Block
- - #{fmtNum(Number(effect.blockHeight))} - +
@@ -153,7 +163,10 @@ export const TxDetailPage: FC = () => {

- Transactionmined transaction + Transaction + + {historical ? "in an orphaned block" : "mined transaction"} +

@@ -161,15 +174,14 @@ export const TxDetailPage: FC = () => { {effect.txHash} - mined + {historical ? ( + orphaned + ) : ( + mined + )} - - #{fmtNum(Number(effect.blockHeight))} - + {effect.blockHash} @@ -398,7 +410,7 @@ export const TxDetailPage: FC = () => {
)} - {!mined && !pending && !dropped && ( + {!effect && !pending && !dropped && (
tx not found
From 2da731e291f16e5294af77b1f63589881585e694 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 03:37:12 +0000 Subject: [PATCH 09/34] fix(explorer-api): keep each tip repair window within the request's block 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 --- .../controllers/l2block/missing-ranges.ts | 30 ++++++++++++------- .../tests/unit/open-gap-scheduler.test.ts | 27 ++++++++++++++++- 2 files changed, 45 insertions(+), 12 deletions(-) diff --git a/services/explorer-api/src/svcs/database/controllers/l2block/missing-ranges.ts b/services/explorer-api/src/svcs/database/controllers/l2block/missing-ranges.ts index f5582f421..93bba344a 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2block/missing-ranges.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2block/missing-ranges.ts @@ -590,22 +590,30 @@ export const buildMissingBlockRangeRequest = async ({ */ export const buildTipBoundaryRepairRequest = async (): Promise => { - const repairWindow = L2_BLOCK_RECONCILIATION_TIP_REPAIR_WINDOW; + // The listener fetches a request from its lowest height until `maxBlocks` + // runs out, so a window wider than that never reaches its mismatch. + const repairWindow = Math.min( + L2_BLOCK_RECONCILIATION_TIP_REPAIR_WINDOW, + Math.floor((L2_BLOCK_RECONCILIATION_MAX_BLOCKS - 1) / 2), + ); const windows = ( await getUnresolvedBoundaryHeights( await getCurrentRollupVersionNumber(), CANDIDATE_GAP_LIMIT, ) - ).map((height) => { - const from = Math.max(1, height - repairWindow); - const to = height + repairWindow; - return { - height, - from, - to, - id: gapId({ from, to, reason: TIP_BOUNDARY_REASON }), - }; - }); + ) + // The listener fetches no height below 1. + .filter((height) => height >= 1) + .map((height) => { + const from = Math.max(1, height - repairWindow); + const to = height + repairWindow; + return { + height, + from, + to, + id: gapId({ from, to, reason: TIP_BOUNDARY_REASON }), + }; + }); if (windows.length === 0) { return null; } diff --git a/services/explorer-api/tests/unit/open-gap-scheduler.test.ts b/services/explorer-api/tests/unit/open-gap-scheduler.test.ts index c1547dc9c..1760e95a0 100644 --- a/services/explorer-api/tests/unit/open-gap-scheduler.test.ts +++ b/services/explorer-api/tests/unit/open-gap-scheduler.test.ts @@ -37,6 +37,7 @@ const mocks = vi.hoisted(() => { updates: [] as Array>, updateTargets: [] as unknown[][], unresolvedHeights: [] as number[], + tipRepairWindow: 5, publishFails: false, order: [] as string[], }; @@ -148,7 +149,9 @@ vi.mock("../../src/environment.js", () => ({ L2_BLOCK_RECONCILIATION_MAX_BLOCKS: 200, L2_BLOCK_RECONCILIATION_MAX_RANGES: 10, L2_BLOCK_RECONCILIATION_SCAN_WINDOW: 10_000, - L2_BLOCK_RECONCILIATION_TIP_REPAIR_WINDOW: 5, + get L2_BLOCK_RECONCILIATION_TIP_REPAIR_WINDOW() { + return mocks.state.tipRepairWindow; + }, })); vi.mock("../../src/logger.js", () => ({ logger: { debug: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() }, @@ -235,6 +238,7 @@ beforeEach(() => { updates: [], updateTargets: [], unresolvedHeights: [], + tipRepairWindow: 5, publishFails: false, order: [], }); @@ -637,6 +641,27 @@ describe("buildTipBoundaryRepairRequest", () => { mocks.state.unresolvedHeights = [98106]; await expect(buildTipBoundaryRepairRequest()).resolves.toBeNull(); }); + + // The listener fetches from the lowest height until 200 blocks are sent. + it("narrows a window wider than the block budget until it reaches its mismatch", async () => { + mocks.state.tipRepairWindow = 300; + mocks.state.unresolvedHeights = [TIP - 2]; + + const planned = await buildTipBoundaryRepairRequest(); + + expect(planned?.request).toMatchObject({ + ranges: [range(TIP - 101, TIP + 97)], + maxBlocks: 199, + }); + }); + + it("passes over a mismatch at height 0, which the listener never fetches", async () => { + mocks.state.unresolvedHeights = [0, TIP - 2]; + + const planned = await buildTipBoundaryRepairRequest(); + + expect(planned?.request.ranges).toEqual([range(TIP - 7, TIP + 3)]); + }); }); describe("recordRepairHeights", () => { From 302ade6bcf44f84894aad814c99984f363726308 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 03:40:28 +0000 Subject: [PATCH 10/34] fix(explorer-api): heartbeat between the txs of a pending or dropped 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 --- .../src/events/received/on-dropped-txs.ts | 8 ++- .../src/events/received/on-pending-txs.ts | 8 ++- .../tests/unit/mempool-heartbeats.test.ts | 72 +++++++++++++++++++ 3 files changed, 82 insertions(+), 6 deletions(-) create mode 100644 services/explorer-api/tests/unit/mempool-heartbeats.test.ts diff --git a/services/explorer-api/src/events/received/on-dropped-txs.ts b/services/explorer-api/src/events/received/on-dropped-txs.ts index b9a7b2095..b5e87f745 100644 --- a/services/explorer-api/src/events/received/on-dropped-txs.ts +++ b/services/explorer-api/src/events/received/on-dropped-txs.ts @@ -1,4 +1,4 @@ -import { EventHandler } from "@chicmoz-pkg/message-bus"; +import { type EventHandler, type Heartbeat } from "@chicmoz-pkg/message-bus"; import { DroppedTxsEvent, generateL2TopicName, @@ -14,10 +14,12 @@ import { txEffectExists } from "../../svcs/database/controllers/l2TxEffect/get-t import { deletePublicCall } from "../../svcs/database/controllers/l2Public-call/delete.js"; import { deleteL2ToL1Msgs } from "../../svcs/database/controllers/l2PendingL2ToL1Msg/delete.js"; -const onDroppedTxs = async ({ txs }: DroppedTxsEvent) => { +const onDroppedTxs = async ({ txs }: DroppedTxsEvent, heartbeat: Heartbeat) => { logger.info(`๐Ÿ—‘๏ธ Received ${txs.length} dropped txs to handle`); for (const droppedTx of txs) { + // Each tx waits for the chain lock on its own. + await heartbeat(); await withChainLock(async (dbTx) => { if (await txEffectExists(droppedTx.txHash, dbTx)) { logger.info(`๐Ÿ—‘๏ธ Dropped tx ${droppedTx.txHash} is mined, skipping`); @@ -38,5 +40,5 @@ export const droppedTxHandler: EventHandler = { handlerName: "droppedTxHandler", }), topic: generateL2TopicName(L2_NETWORK_ID, "DROPPED_TXS_EVENT"), - cb: onDroppedTxs as (arg0: unknown) => Promise, + cb: onDroppedTxs as (arg0: unknown, heartbeat: Heartbeat) => Promise, }; diff --git a/services/explorer-api/src/events/received/on-pending-txs.ts b/services/explorer-api/src/events/received/on-pending-txs.ts index a60738b38..8d6e7b9e8 100644 --- a/services/explorer-api/src/events/received/on-pending-txs.ts +++ b/services/explorer-api/src/events/received/on-pending-txs.ts @@ -1,4 +1,4 @@ -import { EventHandler } from "@chicmoz-pkg/message-bus"; +import { type EventHandler, type Heartbeat } from "@chicmoz-pkg/message-bus"; import { PendingTxsEvent, generateL2TopicName, @@ -13,10 +13,12 @@ import { storeOrUpdateL2Tx } from "../../svcs/database/controllers/l2Tx/index.js import { removeDroppedTxByHash } from "../../svcs/database/controllers/dropped-tx/index.js"; import { txEffectExists } from "../../svcs/database/controllers/l2TxEffect/get-tx-effect.js"; -const onPendingTxs = async ({ txs }: PendingTxsEvent) => { +const onPendingTxs = async ({ txs }: PendingTxsEvent, heartbeat: Heartbeat) => { logger.info(`๐Ÿ• Received ${txs.length} pending txs to store`); for (const tx of txs) { + // Each tx waits for the chain lock on its own. + await heartbeat(); const parsed = chicmozL2PendingTxSchema.safeParse(tx); if (!parsed.success) { logger.error( @@ -51,5 +53,5 @@ export const pendingTxHandler: EventHandler = { handlerName: "pendingTxHandler", }), topic: generateL2TopicName(L2_NETWORK_ID, "PENDING_TXS_EVENT"), - cb: onPendingTxs as (arg0: unknown) => Promise, + cb: onPendingTxs as (arg0: unknown, heartbeat: Heartbeat) => Promise, }; diff --git a/services/explorer-api/tests/unit/mempool-heartbeats.test.ts b/services/explorer-api/tests/unit/mempool-heartbeats.test.ts new file mode 100644 index 000000000..fd7ba0833 --- /dev/null +++ b/services/explorer-api/tests/unit/mempool-heartbeats.test.ts @@ -0,0 +1,72 @@ +import { describe, expect, it, vi } from "vitest"; + +const order = vi.hoisted(() => [] as string[]); + +vi.mock("../../src/environment.js", () => ({ L2_NETWORK_ID: "SANDBOX" })); +vi.mock("../../src/logger.js", () => ({ + logger: { debug: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() }, +})); +vi.mock("../../src/svcs/database/controllers/chain-lock.js", () => ({ + withChainLock: (write: (dbTx: unknown) => Promise) => { + order.push("lock"); + return write({}); + }, +})); +vi.mock( + "../../src/svcs/database/controllers/l2TxEffect/get-tx-effect.js", + () => ({ txEffectExists: () => Promise.resolve(false) }), +); +vi.mock("../../src/svcs/database/controllers/l2Tx/index.js", () => ({ + deleteTx: vi.fn(), + storeOrUpdateL2Tx: vi.fn(), +})); +vi.mock("../../src/svcs/database/controllers/dropped-tx/index.js", () => ({ + removeDroppedTxByHash: () => Promise.resolve(0), +})); +vi.mock("../../src/svcs/database/controllers/dropped-tx/store.js", () => ({ + storeDroppedTx: vi.fn(), +})); +vi.mock("../../src/svcs/database/controllers/l2Public-call/delete.js", () => ({ + deletePublicCall: vi.fn(), +})); +vi.mock( + "../../src/svcs/database/controllers/l2PendingL2ToL1Msg/delete.js", + () => ({ deleteL2ToL1Msgs: vi.fn() }), +); +// The loop under test starts after parsing; any tx object passes here. +vi.mock("@chicmoz-pkg/types", async (importOriginal) => ({ + ...(await importOriginal()), + chicmozL2PendingTxSchema: { + safeParse: (data: unknown) => ({ success: true, data }), + }, +})); + +const { pendingTxHandler } = await import( + "../../src/events/received/on-pending-txs.js" +); +const { droppedTxHandler } = await import( + "../../src/events/received/on-dropped-txs.js" +); + +// Each tx takes the chain lock in its own transaction, and may wait for it: +// a heartbeat between them keeps the consumer's partition through a long +// frame. +describe("the pending and dropped tx handlers", () => { + it.each([ + ["pending", pendingTxHandler], + ["dropped", droppedTxHandler], + ])( + "heartbeat before taking the chain lock for each %s tx", + async (_kind, handler) => { + order.length = 0; + const frame = { txs: [{ txHash: "0x01" }, { txHash: "0x02" }] }; + + await handler.cb(frame as never, () => { + order.push("beat"); + return Promise.resolve(); + }); + + expect(order).toEqual(["beat", "lock", "beat", "lock"]); + }, + ); +}); From 0522b931a5f5a83138423a5b5c48b3d9b0a6d81d Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 03:44:42 +0000 Subject: [PATCH 11/34] fix(explorer-ui-v2): refresh open block pages and contract instances 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 --- .../src/hooks/websocket/message-callbacks.ts | 8 ++- .../pages/contract-instance/index.test.tsx | 72 +++++++++++++++++++ .../src/pages/contract-instance/index.tsx | 3 + .../tests/characterization/ws-frame.test.ts | 9 ++- 4 files changed, 88 insertions(+), 4 deletions(-) create mode 100644 services/explorer-ui-v2/src/pages/contract-instance/index.test.tsx diff --git a/services/explorer-ui-v2/src/hooks/websocket/message-callbacks.ts b/services/explorer-ui-v2/src/hooks/websocket/message-callbacks.ts index abd5496e5..f0f3083ae 100644 --- a/services/explorer-ui-v2/src/hooks/websocket/message-callbacks.ts +++ b/services/explorer-ui-v2/src/hooks/websocket/message-callbacks.ts @@ -4,8 +4,8 @@ import { queryKeyGenerator } from "~/hooks/api"; const prefixOf = (queryKey: readonly unknown[]) => queryKey.slice(0, 1); // Refreshed on a block or tips frame. Either can follow a prune, which changes -// the reorg lists and any block or tx already shown: the detail queries go by -// prefix, whatever block or tx they name. +// the reorg lists and any block, tx or contract instance already shown: the +// detail and page queries go by prefix, whatever they name. const CHAIN_QUERIES = [ queryKeyGenerator.latestBlock, queryKeyGenerator.latestTableBlocks, @@ -13,11 +13,15 @@ const CHAIN_QUERIES = [ queryKeyGenerator.l2TipsHealth, queryKeyGenerator.reorgs, queryKeyGenerator.orphanedBlocks, + prefixOf(queryKeyGenerator.paginatedTableBlocks(0, 0, undefined)), prefixOf(queryKeyGenerator.blockByHeight("")), prefixOf(queryKeyGenerator.txEffectsByBlockHeight(undefined)), prefixOf(queryKeyGenerator.txEffectByHash("")), prefixOf(queryKeyGenerator.pendingTxsByHash("")), prefixOf(queryKeyGenerator.droppedTxByHash("")), + prefixOf(queryKeyGenerator.contractInstance("")), + prefixOf(queryKeyGenerator.deployedContractInstances("")), + queryKeyGenerator.latestContractInstances, ]; /** diff --git a/services/explorer-ui-v2/src/pages/contract-instance/index.test.tsx b/services/explorer-ui-v2/src/pages/contract-instance/index.test.tsx new file mode 100644 index 000000000..ee86798a4 --- /dev/null +++ b/services/explorer-ui-v2/src/pages/contract-instance/index.test.tsx @@ -0,0 +1,72 @@ +import { type ReactNode } from "react"; +import { renderToStaticMarkup } from "react-dom/server"; +import { describe, expect, it, vi } from "vitest"; + +const ADDRESS = `0x${"ef".repeat(32)}`; +const found = vi.hoisted(() => ({ instance: undefined as unknown })); + +vi.mock("@tanstack/react-router", () => ({ + Link: ({ children }: { children: ReactNode }) => children, + useParams: () => ({ address: ADDRESS }), +})); +vi.mock("~/components/layout", () => ({ + Shell: ({ children }: { children: ReactNode }) => children, + ConsoleHead: () => null, +})); +vi.mock("~/components/ui/tooltip", () => ({ + Tooltip: ({ children }: { children: ReactNode }) => children, + TooltipContent: () => null, + TooltipTrigger: ({ children }: { children: ReactNode }) => children, +})); +vi.mock("~/hooks/api", () => { + const none = () => ({ data: undefined }); + return { + useContractInstance: () => ({ + data: found.instance, + isLoading: false, + isError: false, + error: null, + isFetching: false, + refetch: () => Promise.resolve(), + }), + useContractInstanceBalance: none, + useContractInstanceBalanceHistory: none, + useContractInstanceFpcRelationships: none, + useContractInstanceFpcTransactions: none, + useChainInfo: none, + useL2ToL1MsgsByContract: none, + usePublicCallRequestsByContract: none, + useL1FeeJuicePortalDepositsByAddress: none, + }; +}); + +// The components read these from the env at import. +vi.stubEnv("VITE_L2_NETWORK_ID", "SANDBOX"); +vi.stubEnv("VITE_API_URL", "https://api.test"); +vi.stubEnv("VITE_API_KEY", "dev-api-key"); + +const { ContractInstancePage } = await import("./index"); + +const statusOf = (isOrphaned: boolean) => { + found.instance = { + address: ADDRESS, + blockHash: `0x${"ab".repeat(32)}`, + contractClassId: `0x${"12".repeat(32)}`, + version: 1, + deployer: `0x${"34".repeat(32)}`, + salt: `0x${"56".repeat(32)}`, + initializationHash: `0x${"78".repeat(32)}`, + immutablesHash: `0x${"9a".repeat(32)}`, + isOrphaned, + }; + const html = renderToStaticMarkup(); + return /Status<\/span>([^<]*)<\/span>/.exec( + html, + )?.[1]; +}; + +describe("ContractInstancePage", () => { + it("shows whether the instance's deployment is orphaned, as the instance lists do", () => { + expect([statusOf(true), statusOf(false)]).toEqual(["orphaned", "active"]); + }); +}); diff --git a/services/explorer-ui-v2/src/pages/contract-instance/index.tsx b/services/explorer-ui-v2/src/pages/contract-instance/index.tsx index af162aa57..826b74e76 100644 --- a/services/explorer-ui-v2/src/pages/contract-instance/index.tsx +++ b/services/explorer-ui-v2/src/pages/contract-instance/index.tsx @@ -325,6 +325,9 @@ export const ContractInstancePage: FC = () => { + + {instance.isOrphaned ? "orphaned" : "active"} + {instance.artifactHash} diff --git a/services/explorer-ui-v2/tests/characterization/ws-frame.test.ts b/services/explorer-ui-v2/tests/characterization/ws-frame.test.ts index e71f70158..e2f105a49 100644 --- a/services/explorer-ui-v2/tests/characterization/ws-frame.test.ts +++ b/services/explorer-ui-v2/tests/characterization/ws-frame.test.ts @@ -20,17 +20,22 @@ const PUBLISHED_BLOCK_FRAME = new URL( ); const TX = `0x${"cd".repeat(32)}`; -// Views a prune can change: the reorg lists, and block and tx details by -// height and by hash. +const ADDRESS = `0x${"ef".repeat(32)}`; +// Views a prune can change: the reorg lists, the block pages, block and tx +// details by height and by hash, and the contract instances and their lists. const CHAIN_VIEWS = [ queryKeyGenerator.reorgs, queryKeyGenerator.orphanedBlocks, + queryKeyGenerator.paginatedTableBlocks(2, 20, undefined), queryKeyGenerator.blockByHeight("7"), queryKeyGenerator.blockByHeight(`0x${"ab".repeat(32)}`), queryKeyGenerator.txEffectsByBlockHeight(7), queryKeyGenerator.txEffectByHash(TX), queryKeyGenerator.pendingTxsByHash(TX), queryKeyGenerator.droppedTxByHash(TX), + queryKeyGenerator.contractInstance(ADDRESS), + queryKeyGenerator.deployedContractInstances(`0x${"12".repeat(32)}`), + queryKeyGenerator.paginatedContractInstances(20, 20, "all"), ]; // A block frame says nothing about it. const UNRELATED = queryKeyGenerator.averageFees; From cf120343051f4a1585f7c8b0f8a30a41dfe14700 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 03:49:17 +0000 Subject: [PATCH 12/34] fix(explorer-api): bump the chain revision at start-up in archive mode 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 --- services/explorer-api/src/start.ts | 5 +- .../integration/start-up.integration.test.ts | 74 +++++++++++++++++++ 2 files changed, 77 insertions(+), 2 deletions(-) create mode 100644 services/explorer-api/tests/integration/start-up.integration.test.ts diff --git a/services/explorer-api/src/start.ts b/services/explorer-api/src/start.ts index 16e606c36..6bf730e7d 100644 --- a/services/explorer-api/src/start.ts +++ b/services/explorer-api/src/start.ts @@ -40,6 +40,9 @@ ORIGIN: ${notes.origin}`); }); } } + // In archive mode too: a crash between a block's commit and its bump left + // that bump undone, and the writes above change cached reads as well. + await bumpChainRevision(); if (ARCHIVE_MODE) { logger.info( @@ -48,8 +51,6 @@ ORIGIN: ${notes.origin}`); return; } - // A crash between a block's commit and its bump left that bump undone. - await bumpChainRevision(); await subscribeHandlers(); // Through the reconciliation ticks, so a shutdown during startup waits for // these requests and no interval is armed after it. diff --git a/services/explorer-api/tests/integration/start-up.integration.test.ts b/services/explorer-api/tests/integration/start-up.integration.test.ts new file mode 100644 index 000000000..878bfb2eb --- /dev/null +++ b/services/explorer-api/tests/integration/start-up.integration.test.ts @@ -0,0 +1,74 @@ +import { type HexString } from "@chicmoz-pkg/types"; +import { deliver } from "@chicmoz/test-harness"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { + type BuiltBlock, + buildBlock, + freshTxHash, + orderedEvent, +} from "./support/blocks.js"; +import { + type ExplorerApiForTest, + startExplorerApiForTest, +} from "./support/explorer-api.js"; + +type ChainRevision = typeof import("../../src/svcs/cache/chain-revision.js"); + +const crash = vi.hoisted(() => ({ beforeBump: false })); + +// A crash right after a block's commit: the block is stored, and nothing +// after the commit runs. +vi.mock("../../src/svcs/cache/chain-revision.js", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + bumpChainRevision: () => + crash.beforeBump + ? Promise.reject(new Error("crashed before the bump")) + : actual.bumpChainRevision(), + }; +}); + +describe("explorer-api start-up on a real database and Redis", () => { + let api: ExplorerApiForTest; + let store: (b: BuiltBlock) => Promise; + + beforeAll(async () => { + // Archive mode starts without consuming or reconciling. + vi.stubEnv("ARCHIVE_MODE", "true"); + api = await startExplorerApiForTest(); + const { blockHandler } = await import( + "../../src/events/received/on-block/index.js" + ); + store = (b) => deliver(blockHandler, orderedEvent(b)); + }); + + afterAll(async () => { + await api?.close(); + vi.unstubAllEnvs(); + }); + + it("serves the block that replaced a cached one once it starts, after a crash cut off that block's bump", async () => { + const atHeight = async () => { + const res = await api.request.get("/l2/blocks/2"); + expect(res.status, res.text.slice(0, 300)).toBe(200); + return (res.body as { hash: HexString }).hash; + }; + const parent = await buildBlock(1n, [freshTxHash()]); + const replaced = await buildBlock(2n, [freshTxHash()], { parent }); + const replacing = await buildBlock(2n, [freshTxHash()], { parent }); + await store(parent); + await store(replaced); + expect(await atHeight()).toBe(replaced.hash); + + crash.beforeBump = true; + await expect(store(replacing)).rejects.toThrow("crashed before the bump"); + crash.beforeBump = false; + expect(await atHeight()).toBe(replaced.hash); + + const { start } = await import("../../src/start.js"); + await start(); + + expect(await atHeight()).toBe(replacing.hash); + }); +}); From ec13970b59a4c33f98902090bb14d1efaa93bc9e Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 03:51:23 +0000 Subject: [PATCH 13/34] docs(explorer-api): keep the chain lock and contract store comments to 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 --- .../src/events/received/on-pending-txs.ts | 1 - .../src/svcs/database/controllers/chain-lock.ts | 11 +++++------ .../svcs/database/controllers/l2Public-call/delete.ts | 1 - .../src/svcs/database/controllers/l2contract/store.ts | 7 ++----- .../routes/controllers/contract-instances.ts | 1 - 5 files changed, 7 insertions(+), 14 deletions(-) diff --git a/services/explorer-api/src/events/received/on-pending-txs.ts b/services/explorer-api/src/events/received/on-pending-txs.ts index 8d6e7b9e8..c58e2bc05 100644 --- a/services/explorer-api/src/events/received/on-pending-txs.ts +++ b/services/explorer-api/src/events/received/on-pending-txs.ts @@ -39,7 +39,6 @@ const onPendingTxs = async ({ txs }: PendingTxsEvent, heartbeat: Heartbeat) => { `๐Ÿ”„ Resubmitted tx ${res.txHash}: removed from dropped table`, ); } - // Store/update in pending table (handles both new and resubmitted transactions) await storeOrUpdateL2Tx(res, dbTx); logger.debug(`โœ… Stored/updated pending tx: ${res.txHash}`); }); diff --git a/services/explorer-api/src/svcs/database/controllers/chain-lock.ts b/services/explorer-api/src/svcs/database/controllers/chain-lock.ts index be0c7433c..658d9ddb3 100644 --- a/services/explorer-api/src/svcs/database/controllers/chain-lock.ts +++ b/services/explorer-api/src/svcs/database/controllers/chain-lock.ts @@ -6,12 +6,11 @@ import { type DbTx } from "./utils.js"; const LOCK_NAMESPACE = 1_815_307_112; /** - * Runs `fn` in one transaction that first takes the network's chain lock. - * Every chain change takes it, and so does every write that depends on - * which blocks are canonical: the dropped- and pending-tx handlers, the - * start-up sweep and the tips. `lock_timeout` bounds every lock wait in the - * transaction, this one included: a wait over 10 s throws, so the message is - * redelivered. + * Runs `fn` in one transaction that takes the network's chain lock before + * any other: every write that depends on which blocks are canonical takes + * it first, so those writers queue on it rather than deadlock over rows. + * `lock_timeout` bounds every lock wait in the transaction, this one + * included: a wait over 10 s throws. */ export const withChainLock = (fn: (dbTx: DbTx) => Promise): Promise => db().transaction(async (dbTx) => { diff --git a/services/explorer-api/src/svcs/database/controllers/l2Public-call/delete.ts b/services/explorer-api/src/svcs/database/controllers/l2Public-call/delete.ts index be92b4d0d..303e5153c 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2Public-call/delete.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2Public-call/delete.ts @@ -7,7 +7,6 @@ export const deletePublicCall = async ( txHash: ChicmozL2PendingTx["txHash"], executor: ReturnType = db(), ): Promise => { - // Delete existing public call requests for this txHash await executor .delete(l2TxPublicCallRequest) .where(eq(l2TxPublicCallRequest.txHash, txHash)); diff --git a/services/explorer-api/src/svcs/database/controllers/l2contract/store.ts b/services/explorer-api/src/svcs/database/controllers/l2contract/store.ts index 6eae1a5ca..c60a13f8e 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2contract/store.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2contract/store.ts @@ -169,11 +169,8 @@ export type BlockContracts = { }; /** - * Stores a canonical block's contract rows inside its transaction, each in a - * savepoint: a row another canonical block keeps is logged, and one that - * fails (an instance whose class was never stored) is logged and skipped - * without aborting the block; a failed heartbeat, taken before each row, - * aborts it. + * Stores a canonical block's contract rows, each in a savepoint: a row that + * fails is logged and skipped, and a failed heartbeat aborts the block. */ export const storeBlockContracts = async ( dbTx: DbTx, diff --git a/services/explorer-api/src/svcs/http-server/routes/controllers/contract-instances.ts b/services/explorer-api/src/svcs/http-server/routes/controllers/contract-instances.ts index 056dbe75e..72d4b3fb4 100644 --- a/services/explorer-api/src/svcs/http-server/routes/controllers/contract-instances.ts +++ b/services/explorer-api/src/svcs/http-server/routes/controllers/contract-instances.ts @@ -510,7 +510,6 @@ export const POST_L2_VERIFY_CONTRACT_INSTANCE_DEPLOYMENT = asyncHandler( constructorArgs, }); - // Keyed before the read, as `onChainKeys` requires. const instanceKeys = await dbWrapper.onChainKeys( contractInstanceKeys(address), ); From 64f2094b383d14582ea6fb5d99678103b9e3158a Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 04:25:57 +0000 Subject: [PATCH 14/34] fix(explorer-api): accept a tip tier at block 0 as valid 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 --- .../src/svcs/database/controllers/l2/tips.ts | 5 ++ .../young-chain-tips.integration.test.ts | 84 +++++++++++++++++++ 2 files changed, 89 insertions(+) create mode 100644 services/explorer-api/tests/integration/young-chain-tips.integration.test.ts diff --git a/services/explorer-api/src/svcs/database/controllers/l2/tips.ts b/services/explorer-api/src/svcs/database/controllers/l2/tips.ts index 989d16245..089d3a731 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2/tips.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2/tips.ts @@ -139,6 +139,11 @@ const validateBoundary = async ( rollupVersion: number | null, ): Promise => { const tip = bucket === "proposed" ? tips.proposed : tips[bucket].block; + // A tier at block 0 names the genesis block, which is never stored: there + // is nothing to check it against. + if (tip.number === 0) { + return null; + } const boundaryHash = await getBoundaryBlock( executor, tip.number, diff --git a/services/explorer-api/tests/integration/young-chain-tips.integration.test.ts b/services/explorer-api/tests/integration/young-chain-tips.integration.test.ts new file mode 100644 index 000000000..2c8b9f254 --- /dev/null +++ b/services/explorer-api/tests/integration/young-chain-tips.integration.test.ts @@ -0,0 +1,84 @@ +import { type L2TipsEvent } from "@chicmoz-pkg/message-registry"; +import { type HexString } from "@chicmoz-pkg/types"; +import { deliver } from "@chicmoz/test-harness"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { type BuiltBlock, buildChain, orderedEvent } from "./support/blocks.js"; +import { + type ExplorerApiForTest, + startExplorerApiForTest, +} from "./support/explorer-api.js"; + +const word = (n: number): HexString => `0x${n.toString(16).padStart(64, "0")}`; + +// Until a tier moves past block 0 it names the genesis block, which the +// chain never stores. +describe("the tips of a young chain on a real database", () => { + let api: ExplorerApiForTest; + let store: (block: BuiltBlock) => Promise; + let storeTips: (tips: L2TipsEvent["tips"]) => Promise; + let degradedReason: () => Promise; + let openMismatchHeights: () => Promise; + let statusesOf: (heights: number[]) => Promise; + + beforeAll(async () => { + api = await startExplorerApiForTest(); + const { blockHandler } = await import( + "../../src/events/received/on-block/index.js" + ); + const { l2TipsHandler } = await import( + "../../src/events/received/on-l2-tips.js" + ); + const { getBlock } = await import( + "../../src/svcs/database/controllers/l2block/get-block.js" + ); + const tips = await import("../../src/svcs/database/controllers/l2/tips.js"); + store = (block) => deliver(blockHandler, orderedEvent(block)); + storeTips = (tipsOf) => + deliver(l2TipsHandler, { + tips: tipsOf, + observedAt: Date.now(), + source: { rpcNodeName: "node", aztecNodeVersion: "test" }, + } satisfies L2TipsEvent); + degradedReason = async () => (await tips.getTips())?.degradedReason; + openMismatchHeights = async () => + (await tips.getRecentBoundaryMismatches()) + .filter((mismatch) => !mismatch.resolvedAt) + .map((mismatch) => mismatch.height); + statusesOf = (heights) => + Promise.all( + heights.map( + async (height) => + (await getBlock(BigInt(height)))?.nativeStatus ?? "absent", + ), + ); + }); + + afterAll(async () => { + await api?.close(); + }); + + it("keeps the tips healthy while the proven and finalized tiers are at block 0", async () => { + const [first, second, third] = await buildChain(1n, 3); + await store(first); + await store(second); + const genesis = { + block: { number: 0, hash: word(0x10) }, + checkpoint: { number: 0, hash: word(0x500) }, + }; + await storeTips({ + proposed: { number: 2, hash: second.hash }, + checkpointed: { + block: { number: 1, hash: first.hash }, + checkpoint: { number: 1, hash: word(0x501) }, + }, + proven: genesis, + finalized: genesis, + }); + // A chain change validates the stored tips again. + await store(third); + + expect(await degradedReason()).toBeUndefined(); + expect(await openMismatchHeights()).toEqual([]); + expect(await statusesOf([1, 2])).toEqual(["checkpointed", "proposed"]); + }); +}); From 541675c78e45ada19324254342de4063fbdcadbb Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 04:33:01 +0000 Subject: [PATCH 15/34] fix(explorer-api): read the tx effects at height 0 as a bounded read 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 --- .../database/controllers/l2TxEffect/get-tx-effect.ts | 9 +++++---- .../tests/integration/block-ingest.integration.test.ts | 6 ++++++ 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/services/explorer-api/src/svcs/database/controllers/l2TxEffect/get-tx-effect.ts b/services/explorer-api/src/svcs/database/controllers/l2TxEffect/get-tx-effect.ts index 673d62c8c..c527af812 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2TxEffect/get-tx-effect.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2TxEffect/get-tx-effect.ts @@ -106,14 +106,15 @@ export const getLatestTxEffects = async (): Promise< }); }; +// Height 0 is a bound like any other, so presence is checked, not truthiness. const generateWhereQuery = (from?: bigint, to?: bigint) => { - if (from && !to) { + if (from !== undefined && to === undefined) { return gte(l2Block.height, from); - } else if (!from && to) { + } else if (from === undefined && to !== undefined) { return lt(l2Block.height, to); } assert( - from && to, + from !== undefined && to !== undefined, "FATAL: cannot have both from and to undefined when generating where query", ); return and(gte(l2Block.height, from), lt(l2Block.height, to)); @@ -156,7 +157,7 @@ const _getTxEffects = async ( switch (args.getType) { case GetTypes.BlockHeightRange: - if (args.from ?? args.to) { + if (args.from !== undefined || args.to !== undefined) { whereQuery = joinQuery .where(and(generateWhereQuery(args.from, args.to), heightFilter)) .orderBy(desc(l2Block.height), desc(txEffect.index)) diff --git a/services/explorer-api/tests/integration/block-ingest.integration.test.ts b/services/explorer-api/tests/integration/block-ingest.integration.test.ts index 82dae0d91..c8260109b 100644 --- a/services/explorer-api/tests/integration/block-ingest.integration.test.ts +++ b/services/explorer-api/tests/integration/block-ingest.integration.test.ts @@ -55,6 +55,12 @@ describe("recorded blocks through the block handler", () => { }, ); + it("serves no tx effects at height 0", async () => { + const res = await api.request.get("/l2/blocks/0/tx-effects"); + expect(res.status).toBe(200); + expect(JSON.parse(res.text)).toEqual([]); + }); + it("links each published class and deployed instance to the block that carries it", async () => { const classes = recorded.flatMap(({ expected }) => expected.contractClassIds.map((id) => ({ id, blockHash: expected.hash })), From 9ff14f229c2d3e77980fc802f3fd753e4f4958b6 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 04:35:39 +0000 Subject: [PATCH 16/34] test(explorer-api): hold the mempool heartbeat open to show the lock 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 --- .../tests/unit/mempool-heartbeats.test.ts | 29 +++++++++++++------ 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/services/explorer-api/tests/unit/mempool-heartbeats.test.ts b/services/explorer-api/tests/unit/mempool-heartbeats.test.ts index fd7ba0833..d6878e12f 100644 --- a/services/explorer-api/tests/unit/mempool-heartbeats.test.ts +++ b/services/explorer-api/tests/unit/mempool-heartbeats.test.ts @@ -48,25 +48,36 @@ const { droppedTxHandler } = await import( "../../src/events/received/on-dropped-txs.js" ); -// Each tx takes the chain lock in its own transaction, and may wait for it: -// a heartbeat between them keeps the consumer's partition through a long -// frame. +// Each tx's lock wait can be long, so each starts after a heartbeat. describe("the pending and dropped tx handlers", () => { it.each([ ["pending", pendingTxHandler], ["dropped", droppedTxHandler], ])( - "heartbeat before taking the chain lock for each %s tx", + "wait for a heartbeat before each %s tx's chain lock, and stop when one fails", async (_kind, handler) => { order.length = 0; + const beats: Array<{ pass: () => void; fail: (e: Error) => void }> = []; const frame = { txs: [{ txHash: "0x01" }, { txHash: "0x02" }] }; - await handler.cb(frame as never, () => { - order.push("beat"); - return Promise.resolve(); - }); + const handled = handler.cb( + frame as never, + () => + new Promise((pass, fail) => { + order.push("beat"); + beats.push({ pass, fail }); + }), + ); + // Let anything not waiting for the heartbeat run. + await new Promise((settle) => setTimeout(settle, 20)); + expect(order).toEqual(["beat"]); - expect(order).toEqual(["beat", "lock", "beat", "lock"]); + beats[0].pass(); + await vi.waitFor(() => expect(order).toEqual(["beat", "lock", "beat"])); + + beats[1].fail(new Error("rebalancing")); + await expect(handled).rejects.toThrow("rebalancing"); + expect(order).toEqual(["beat", "lock", "beat"]); }, ); }); From da4850f1c0b922d30fc761278bd7c0fa754a79c1 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 04:44:21 +0000 Subject: [PATCH 17/34] fix(explorer-api): ask for a tip repair's mismatch height before its 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 --- .../controllers/l2block/missing-ranges.ts | 16 +++++++-- .../tests/unit/open-gap-scheduler.test.ts | 35 +++++++++++++++---- 2 files changed, 42 insertions(+), 9 deletions(-) diff --git a/services/explorer-api/src/svcs/database/controllers/l2block/missing-ranges.ts b/services/explorer-api/src/svcs/database/controllers/l2block/missing-ranges.ts index 93bba344a..daee959df 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2block/missing-ranges.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2block/missing-ranges.ts @@ -590,8 +590,8 @@ export const buildMissingBlockRangeRequest = async ({ */ export const buildTipBoundaryRepairRequest = async (): Promise => { - // The listener fetches a request from its lowest height until `maxBlocks` - // runs out, so a window wider than that never reaches its mismatch. + // A window fits one request's block budget: wider, it would name heights + // no request could carry. const repairWindow = Math.min( L2_BLOCK_RECONCILIATION_TIP_REPAIR_WINDOW, Math.floor((L2_BLOCK_RECONCILIATION_MAX_BLOCKS - 1) / 2), @@ -649,12 +649,22 @@ export const buildTipBoundaryRepairRequest = logger.warn( `Requesting L2 tip-boundary repair around block ${height}: ${from}-${to}`, ); + // The listener sends ranges in order, each from its lowest height, and + // its own width and block limits can be lower than the API's: the + // mismatch goes first, so a truncated request still carries it. + const ranges = [ + { from: height, to: height }, + { from, to: height - 1 }, + { from: height + 1, to }, + ] + .filter((part) => part.from <= part.to) + .map((part) => ({ ...part, statusHint: "proposed" as const })); return { request: { requestId: randomUUID(), requestedAt: Date.now(), reason: TIP_BOUNDARY_REASON, - ranges: [range], + ranges, maxBlocks: Math.min(L2_BLOCK_RECONCILIATION_MAX_BLOCKS, to - from + 1), }, markRequested: () => markGapsRequested([id]), diff --git a/services/explorer-api/tests/unit/open-gap-scheduler.test.ts b/services/explorer-api/tests/unit/open-gap-scheduler.test.ts index 1760e95a0..e8ab2a943 100644 --- a/services/explorer-api/tests/unit/open-gap-scheduler.test.ts +++ b/services/explorer-api/tests/unit/open-gap-scheduler.test.ts @@ -612,12 +612,34 @@ describe("selection", () => { }); describe("buildTipBoundaryRepairRequest", () => { + // The mismatch, then the heights below it, then those above it. + const windowAround = (height: number, radius: number) => [ + range(height, height), + range(height - radius, height - 1), + range(height + 1, height + radius), + ]; + // What a listener with a lower limit than the API's sends for a request: the + // ranges in order, each from its lowest height and at most `limit` wide, + // until `limit` heights in all. + const listenerSends = ( + request: + | { ranges: Array<{ from: number; to: number }>; maxBlocks?: number } + | undefined, + limit: number, + ) => + (request?.ranges ?? []) + .flatMap(({ from, to }) => { + const first = Math.max(1, from); + return heights(first, Math.min(to, first + limit - 1)); + }) + .slice(0, Math.min(request?.maxBlocks ?? limit, limit)); + it("sends the window around the most recently seen open mismatch", async () => { mocks.state.unresolvedHeights = [TIP - 2, 98106]; const planned = await buildTipBoundaryRepairRequest(); - expect(planned?.request.ranges).toEqual([range(TIP - 7, TIP + 3)]); + expect(planned?.request.ranges).toEqual(windowAround(TIP - 2, 5)); // Reopening a tip row keeps its backoff: it is fulfilled as soon as its // heights are present, mismatch or not. expect(mocks.state.upserts[0].set).not.toHaveProperty("requestCount"); @@ -636,21 +658,22 @@ describe("buildTipBoundaryRepairRequest", () => { ]; const planned = await buildTipBoundaryRepairRequest(); - expect(planned?.request.ranges).toEqual([range(TIP - 7, TIP + 3)]); + expect(planned?.request.ranges).toEqual(windowAround(TIP - 2, 5)); mocks.state.unresolvedHeights = [98106]; await expect(buildTipBoundaryRepairRequest()).resolves.toBeNull(); }); - // The listener fetches from the lowest height until 200 blocks are sent. - it("narrows a window wider than the block budget until it reaches its mismatch", async () => { + it("asks for the mismatch before its neighbors, so a listener sending fewer heights than the window still sends it", async () => { mocks.state.tipRepairWindow = 300; mocks.state.unresolvedHeights = [TIP - 2]; const planned = await buildTipBoundaryRepairRequest(); + expect(listenerSends(planned?.request, 50)).toContain(TIP - 2); + // The window still fits the API's own block budget. expect(planned?.request).toMatchObject({ - ranges: [range(TIP - 101, TIP + 97)], + ranges: windowAround(TIP - 2, 99), maxBlocks: 199, }); }); @@ -660,7 +683,7 @@ describe("buildTipBoundaryRepairRequest", () => { const planned = await buildTipBoundaryRepairRequest(); - expect(planned?.request.ranges).toEqual([range(TIP - 7, TIP + 3)]); + expect(planned?.request.ranges).toEqual(windowAround(TIP - 2, 5)); }); }); From c2601f040c097246353029f479226256a37041a3 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 04:58:56 +0000 Subject: [PATCH 18/34] fix(explorer-api): pick a tip repair among due windows before the limit 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 --- .../src/svcs/database/controllers/l2/tips.ts | 29 ------ .../controllers/l2block/missing-ranges.ts | 91 +++++++++++-------- .../integration/open-gap.integration.test.ts | 63 ++++++++++++- .../tests/unit/open-gap-scheduler.test.ts | 55 ++++------- 4 files changed, 129 insertions(+), 109 deletions(-) diff --git a/services/explorer-api/src/svcs/database/controllers/l2/tips.ts b/services/explorer-api/src/svcs/database/controllers/l2/tips.ts index 089d3a731..5baf5fad8 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2/tips.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2/tips.ts @@ -348,35 +348,6 @@ export const revalidateTips = async (dbTx: DbTx) => { await recordValidation(dbTx, mismatch, rollupVersion); }; -/** - * The heights of the open mismatches, most recently seen first: those of - * `rollupVersion`, and those recorded before mismatches carried a version. - */ -export const getUnresolvedBoundaryHeights = async ( - rollupVersion: number | null, - limit: number, -): Promise => { - const mismatch = l2TipBoundaryMismatchTable; - const rows = await db() - .select({ height: mismatch.height }) - .from(mismatch) - .where( - and( - eq(mismatch.l2NetworkId, L2_NETWORK_ID), - isNull(mismatch.resolvedAt), - rollupVersion === null - ? undefined - : or( - isNull(mismatch.rollupVersion), - eq(mismatch.rollupVersion, rollupVersion), - ), - ), - ) - .orderBy(desc(mismatch.lastSeenAt)) - .limit(limit); - return [...new Set(rows.map(({ height }) => height))]; -}; - export const getRecentBoundaryMismatches = async ( l2NetworkId: L2NetworkId = L2_NETWORK_ID, ) => { diff --git a/services/explorer-api/src/svcs/database/controllers/l2block/missing-ranges.ts b/services/explorer-api/src/svcs/database/controllers/l2block/missing-ranges.ts index daee959df..6a6e9af46 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2block/missing-ranges.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2block/missing-ranges.ts @@ -6,6 +6,7 @@ import { getDb as db } from "@chicmoz-pkg/postgres-helper"; import { and, asc, + desc, eq, gte, inArray, @@ -13,6 +14,7 @@ import { lte, ne, not, + notExists, or, sql, } from "drizzle-orm"; @@ -27,9 +29,9 @@ import { } from "../../../../environment.js"; import { logger } from "../../../../logger.js"; import { l2OpenGapTable } from "../../schema/l2/open-gap.js"; +import { l2TipBoundaryMismatchTable } from "../../schema/l2/tips.js"; import { l2Block } from "../../schema/l2block/index.js"; import { getCurrentRollupVersionNumber } from "../l2/chain-info/rollup-version-cache.js"; -import { getUnresolvedBoundaryHeights } from "../l2/tips.js"; import { getLatestBlockRollupVersion, getLatestHeight } from "./get-latest.js"; type GapRange = { from: number; to: number; statusHint: "proposed" }; @@ -596,48 +598,57 @@ export const buildTipBoundaryRepairRequest = L2_BLOCK_RECONCILIATION_TIP_REPAIR_WINDOW, Math.floor((L2_BLOCK_RECONCILIATION_MAX_BLOCKS - 1) / 2), ); - const windows = ( - await getUnresolvedBoundaryHeights( - await getCurrentRollupVersionNumber(), - CANDIDATE_GAP_LIMIT, - ) - ) - // The listener fetches no height below 1. - .filter((height) => height >= 1) - .map((height) => { - const from = Math.max(1, height - repairWindow); - const to = height + repairWindow; - return { - height, - from, - to, - id: gapId({ from, to, reason: TIP_BOUNDARY_REASON }), - }; - }); - if (windows.length === 0) { - return null; - } - const backingOff = new Set( - ( - await db() - .select({ id: l2OpenGapTable.id }) - .from(l2OpenGapTable) - .where( - and( - inArray( - l2OpenGapTable.id, - windows.map(({ id }) => id), + const rollupVersion = await getCurrentRollupVersionNumber(); + const mismatch = l2TipBoundaryMismatchTable; + // Every filter, the backoff included, applies before the limit: rows a + // tick would pass over must not hide one it would send. + const [candidate] = await db() + .select({ height: mismatch.height }) + .from(mismatch) + .where( + and( + eq(mismatch.l2NetworkId, L2_NETWORK_ID), + isNull(mismatch.resolvedAt), + // This version's, and those recorded before mismatches carried one. + rollupVersion === null + ? undefined + : or( + isNull(mismatch.rollupVersion), + eq(mismatch.rollupVersion, rollupVersion), ), - not(gapDueSql(Date.now())), - ), - ) - ).map(({ id }) => id), - ); - const window = windows.find(({ id }) => !backingOff.has(id)); - if (!window) { + // The listener fetches no height below 1. + gte(mismatch.height, 1), + notExists( + db() + .select({ one: sql`1` }) + .from(l2OpenGapTable) + .where( + and( + eq(l2OpenGapTable.l2NetworkId, L2_NETWORK_ID), + eq(l2OpenGapTable.reason, TIP_BOUNDARY_REASON), + eq( + l2OpenGapTable.fromHeight, + sql`greatest(1, ${mismatch.height} - ${repairWindow})`, + ), + eq( + l2OpenGapTable.toHeight, + sql`${mismatch.height} + ${repairWindow}`, + ), + not(gapDueSql(Date.now())), + ), + ), + ), + ), + ) + .orderBy(desc(mismatch.lastSeenAt)) + .limit(1); + if (!candidate) { return null; } - const { height, from, to, id } = window; + const { height } = candidate; + const from = Math.max(1, height - repairWindow); + const to = height + repairWindow; + const id = gapId({ from, to, reason: TIP_BOUNDARY_REASON }); const range = { from, to, statusHint: "proposed" as const }; // Reopening must not reset the backoff here: the row is "fulfilled" as // soon as its heights are present, mismatch or not. diff --git a/services/explorer-api/tests/integration/open-gap.integration.test.ts b/services/explorer-api/tests/integration/open-gap.integration.test.ts index 1bd7abdba..b67993570 100644 --- a/services/explorer-api/tests/integration/open-gap.integration.test.ts +++ b/services/explorer-api/tests/integration/open-gap.integration.test.ts @@ -32,6 +32,10 @@ const byFrom = (ranges: Range[] | null) => describe("open gap scheduling on a real database", () => { let api: ExplorerApiForTest; let tick: () => Promise; + let repairTick: () => Promise; + let mismatches: ( + rows: Array<{ height: number; seenAgoMs: number; version?: number }>, + ) => Promise; let blocks: (heights: number[], version?: number) => Promise; let arrive: (height: number) => Promise; let orphan: (height: number) => Promise; @@ -49,6 +53,7 @@ describe("open gap scheduling on a real database", () => { L2_BLOCK_RECONCILIATION_MAX_BLOCKS: "200", L2_BLOCK_RECONCILIATION_MAX_RANGES: "10", L2_BLOCK_RECONCILIATION_SCAN_WINDOW: "10000", + L2_BLOCK_RECONCILIATION_TIP_REPAIR_WINDOW: "5", }); api = await startExplorerApiForTest(); const { getDb } = await import("@chicmoz-pkg/postgres-helper"); @@ -56,11 +61,15 @@ describe("open gap scheduling on a real database", () => { const { l2OpenGapTable } = await import( "../../src/svcs/database/schema/l2/open-gap.js" ); + const { l2TipBoundaryMismatchTable } = await import( + "../../src/svcs/database/schema/l2/tips.js" + ); const { l2Block } = await import( "../../src/svcs/database/schema/l2block/index.js" ); const { buildMissingBlockRangeRequest, + buildTipBoundaryRepairRequest, fulfilRepairHeight, markOpenGapsFulfilledByHeight, recordRepairHeights, @@ -79,15 +88,36 @@ describe("open gap scheduling on a real database", () => { const db = getDb(); const hashOf = (height: number, version: number): HexString => `0x${version.toString(16).padStart(2, "0")}${height.toString(16).padStart(62, "0")}`; - // A cadence tick whose publish succeeds: what it would send, then the - // marking that follows the send. - tick = async () => { - const planned = await buildMissingBlockRangeRequest({ reason: "cadence" }); + // A tick whose publish succeeds: what it would send, then the marking + // that follows the send. + const sent = async ( + planned: Awaited>, + ) => { await planned?.markRequested(); return planned ? planned.request.ranges.map(({ from, to }): Range => [from, to]) : null; }; + tick = async () => + sent(await buildMissingBlockRangeRequest({ reason: "cadence" })); + repairTick = async () => sent(await buildTipBoundaryRepairRequest()); + mismatches = async (rows) => { + const now = Date.now(); + await db.insert(l2TipBoundaryMismatchTable).values( + rows.map(({ height, seenAgoMs, version = CURRENT }) => ({ + id: `SANDBOX:proposed:${height}`, + l2NetworkId: "SANDBOX" as const, + bucket: "proposed" as const, + height, + expectedHash: hashOf(height, version), + observedDbHash: null, + reason: `proposed boundary block ${height} is missing`, + firstSeenAt: new Date(now - seenAgoMs), + lastSeenAt: new Date(now - seenAgoMs), + rollupVersion: version, + })), + ); + }; blocks = async (heights, version = CURRENT) => { await db.insert(l2Block).values( heights.map((height) => ({ @@ -145,6 +175,7 @@ describe("open gap scheduling on a real database", () => { ).map(({ from, to }): Range => [from, to]); reset = async () => { await db.delete(l2OpenGapTable); + await db.delete(l2TipBoundaryMismatchTable); await db.delete(l2Block); }; }); @@ -235,6 +266,30 @@ describe("open gap scheduling on a real database", () => { expect(await tick()).toEqual([[170, 170], [180, 180]]); }); + it("sends a due tip repair past more backed-off windows than the scheduler's candidates", async () => { + // Each seen more recently than the due mismatch at 900, and more of them + // than the scheduler's 50 candidates. The first ticks request, and so + // back off, these windows; the one at 3 starts at height 1. + const backedOff = [3, ...span(1_001, 1_050)]; + await mismatches([ + // Never fetched: the listener starts at height 1. + { height: 0, seenAgoMs: 0 }, + ...backedOff.map((height, i) => ({ height, seenAgoMs: (i + 1) * 1_000 })), + { height: 950, seenAgoMs: 30 * MINUTE, version: OLD }, + { height: 900, seenAgoMs: 60 * MINUTE }, + ]); + + for (const height of backedOff) { + expect((await repairTick())?.[0]).toEqual([height, height]); + } + expect(await repairTick()).toEqual([ + [900, 900], + [895, 899], + [901, 905], + ]); + expect(await repairTick()).toBeNull(); + }); + it("does not let old-version blocks or old-chain gap rows hide a current-version gap", async () => { // The old chain is ahead of the current one, as right after an upgrade. await blocks(span(1, 120), OLD); diff --git a/services/explorer-api/tests/unit/open-gap-scheduler.test.ts b/services/explorer-api/tests/unit/open-gap-scheduler.test.ts index e8ab2a943..d27423d49 100644 --- a/services/explorer-api/tests/unit/open-gap-scheduler.test.ts +++ b/services/explorer-api/tests/unit/open-gap-scheduler.test.ts @@ -36,7 +36,7 @@ const mocks = vi.hoisted(() => { deleted: [] as unknown[], updates: [] as Array>, updateTargets: [] as unknown[][], - unresolvedHeights: [] as number[], + candidateHeights: [] as number[], tipRepairWindow: 5, publishFails: false, order: [] as string[], @@ -82,6 +82,20 @@ const mocks = vi.hoisted(() => { select: (fields?: Record) => ({ from: (table: object) => ({ where: (condition: unknown) => { + // The tip repair's candidate query filters and orders in SQL, which + // the integration tests run; here it yields the heights given. + if (tableName(table) === "l2_tip_boundary_mismatch") { + return { + orderBy: () => ({ + limit: (limit: number) => + Promise.resolve( + state.candidateHeights + .slice(0, limit) + .map((height) => ({ height })), + ), + }), + }; + } if (tableName(table) !== "l2_open_gap") { return Object.assign(Promise.resolve(heightRows()), { orderBy: () => Promise.resolve(heightRows()), @@ -160,10 +174,6 @@ vi.mock( "../../src/svcs/database/controllers/l2/chain-info/rollup-version-cache.js", () => ({ getCurrentRollupVersionNumber: () => Promise.resolve(1) }), ); -vi.mock("../../src/svcs/database/controllers/l2/tips.js", () => ({ - getUnresolvedBoundaryHeights: () => - Promise.resolve(mocks.state.unresolvedHeights), -})); vi.mock("../../src/svcs/database/controllers/l2block/get-latest.js", () => ({ getLatestHeight: () => Promise.resolve(BigInt(TIP)), getLatestBlockRollupVersion: () => Promise.resolve(1), @@ -237,7 +247,7 @@ beforeEach(() => { deleted: [], updates: [], updateTargets: [], - unresolvedHeights: [], + candidateHeights: [], tipRepairWindow: 5, publishFails: false, order: [], @@ -634,8 +644,8 @@ describe("buildTipBoundaryRepairRequest", () => { }) .slice(0, Math.min(request?.maxBlocks ?? limit, limit)); - it("sends the window around the most recently seen open mismatch", async () => { - mocks.state.unresolvedHeights = [TIP - 2, 98106]; + it("sends the window around the picked mismatch, keeping its row's backoff", async () => { + mocks.state.candidateHeights = [TIP - 2]; const planned = await buildTipBoundaryRepairRequest(); @@ -645,28 +655,9 @@ describe("buildTipBoundaryRepairRequest", () => { expect(mocks.state.upserts[0].set).not.toHaveProperty("requestCount"); }); - it("passes over a window that is backing off, and sends nothing while every one is", async () => { - mocks.state.unresolvedHeights = [98106, TIP - 2]; - mocks.state.gaps = [ - gap({ - id: "MAINNET:tip_boundary_mismatch:98101:98111", - fromHeight: 98101, - toHeight: 98111, - reason: "tip_boundary_mismatch", - due: false, - }), - ]; - - const planned = await buildTipBoundaryRepairRequest(); - expect(planned?.request.ranges).toEqual(windowAround(TIP - 2, 5)); - - mocks.state.unresolvedHeights = [98106]; - await expect(buildTipBoundaryRepairRequest()).resolves.toBeNull(); - }); - it("asks for the mismatch before its neighbors, so a listener sending fewer heights than the window still sends it", async () => { mocks.state.tipRepairWindow = 300; - mocks.state.unresolvedHeights = [TIP - 2]; + mocks.state.candidateHeights = [TIP - 2]; const planned = await buildTipBoundaryRepairRequest(); @@ -677,14 +668,6 @@ describe("buildTipBoundaryRepairRequest", () => { maxBlocks: 199, }); }); - - it("passes over a mismatch at height 0, which the listener never fetches", async () => { - mocks.state.unresolvedHeights = [0, TIP - 2]; - - const planned = await buildTipBoundaryRepairRequest(); - - expect(planned?.request.ranges).toEqual(windowAround(TIP - 2, 5)); - }); }); describe("recordRepairHeights", () => { From 29e9181bcb4b1adb4f77ff564a44536399919755 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 04:59:33 +0000 Subject: [PATCH 19/34] fix(explorer-ui-v2): list a block's own txs on its page 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 --- .../src/pages/block-detail/index.test.tsx | 134 ++++++++++++++++++ .../src/pages/block-detail/index.tsx | 53 ++++--- 2 files changed, 164 insertions(+), 23 deletions(-) create mode 100644 services/explorer-ui-v2/src/pages/block-detail/index.test.tsx diff --git a/services/explorer-ui-v2/src/pages/block-detail/index.test.tsx b/services/explorer-ui-v2/src/pages/block-detail/index.test.tsx new file mode 100644 index 000000000..768dcc2e5 --- /dev/null +++ b/services/explorer-ui-v2/src/pages/block-detail/index.test.tsx @@ -0,0 +1,134 @@ +import { type ReactNode } from "react"; +import { renderToStaticMarkup } from "react-dom/server"; +import { describe, expect, it, vi } from "vitest"; + +const BLOCK = `0x${"ab".repeat(32)}`; +const tx = (byte: string) => `0x${byte.repeat(32)}`; +const [TX_A, TX_B, TX_C] = [tx("0a"), tx("0b"), tx("0c")]; +const ONE = (10n ** 18n).toString(); +const TWO = (2n * 10n ** 18n).toString(); +const shown = vi.hoisted(() => ({ + block: undefined as unknown, + heightRead: undefined as unknown, +})); + +vi.mock("@tanstack/react-router", async () => { + const { createElement } = await import("react"); + return { + Link: ({ + to, + params, + children, + }: { + to: string; + params?: Record; + children: ReactNode; + }) => + createElement( + "a", + { + href: to.replace( + /\$(\w+)/g, + (_, name: string) => params?.[name] ?? "", + ), + }, + children, + ), + useParams: () => ({ blockNumber: BLOCK }), + }; +}); +vi.mock("~/components/layout", () => ({ + Shell: ({ children }: { children: ReactNode }) => children, + ConsoleHead: () => null, +})); +vi.mock("~/hooks/api", () => ({ + useGetBlockByIdentifier: () => ({ data: shown.block }), + useGetTableTxEffectsByBlockHeight: () => ({ data: shown.heightRead }), + useChainInfo: () => ({ data: undefined }), +})); + +// The components read these from the env at import. +vi.stubEnv("VITE_L2_NETWORK_ID", "SANDBOX"); +vi.stubEnv("VITE_API_URL", "https://api.test"); +vi.stubEnv("VITE_API_KEY", "dev-api-key"); + +const { BlockDetailPage } = await import("./index"); +const { formatFees } = await import("~/lib/utils"); + +// The tx rows, as [tx hash, fee]. +const render = ({ + body, + orphaned, + heightRead, +}: { + body: string[]; + orphaned: boolean; + heightRead: Array<[txHash: string, fee: string]>; +}) => { + shown.block = { + hash: BLOCK, + height: 7n, + nativeStatus: "proposed", + orphan: orphaned + ? { timestamp: 1_700_000_000_000, hasOrphanedParent: false } + : undefined, + archive: { root: BLOCK }, + header: { + lastArchive: { root: BLOCK }, + totalFees: "0", + totalManaUsed: 0n, + globalVariables: { + timestamp: 1_700_000_000n, + version: 1, + slotNumber: 1, + coinbase: BLOCK, + feeRecipient: BLOCK, + gasFees: { feePerDaGas: 0, feePerL2Gas: 0 }, + }, + }, + body: { txEffects: body.map((txHash) => ({ txHash })) }, + }; + shown.heightRead = heightRead.map(([txHash, transactionFee]) => ({ + blockNumber: 7n, + txHash, + transactionFee, + timestamp: 1_700_000_000_000, + })); + const html = renderToStaticMarkup(); + return [ + ...html.matchAll( + /href="\/tx-effects\/([^"]+)">.*?(.*?) [txHash, fee]); +}; + +describe("BlockDetailPage", () => { + it("lists an orphaned block's own txs, not those of the block its height now names", () => { + expect( + render({ + body: [TX_A], + orphaned: true, + heightRead: [ + [TX_B, ONE], + [TX_C, TWO], + ], + }), + ).toEqual([[TX_A, "โ€”"]]); + }); + + it("lists a block's txs in its order, each with its own fee", () => { + expect( + render({ + body: [TX_B, TX_C], + orphaned: false, + heightRead: [ + [TX_C, TWO], + [TX_B, ONE], + ], + }), + ).toEqual([ + [TX_B, formatFees(ONE)], + [TX_C, formatFees(TWO)], + ]); + }); +}); diff --git a/services/explorer-ui-v2/src/pages/block-detail/index.tsx b/services/explorer-ui-v2/src/pages/block-detail/index.tsx index 313eb8216..6528d9b57 100644 --- a/services/explorer-ui-v2/src/pages/block-detail/index.tsx +++ b/services/explorer-ui-v2/src/pages/block-detail/index.tsx @@ -91,6 +91,10 @@ export const BlockDetailPage: FC = () => { const totalFees = formatFees(block.header.totalFees, feeJuiceDecimals); const totalManaUsed = block.header.totalManaUsed?.toString?.() ?? "0"; const txCount = block.body.txEffects.length; + // The height read lists the canonical block's txs, which for an orphaned + // block are its replacement's: the body says which txs this block holds, + // and the read only adds their fees. + const feeByTxHash = new Map(txs?.map((t) => [t.txHash, t.transactionFee])); const l1Anchor = block.proposedOnL1 ?? block.proofVerifiedOnL1; const blockRollupVersion = BigInt(block.header.globalVariables.version); const isOldRollup = @@ -388,29 +392,32 @@ export const BlockDetailPage: FC = () => {
Idx
Fee ({feeJuiceSymbol})
- {(txs ?? []).map((t, i) => ( - - - {i} - - {formatFees(t.transactionFee, feeJuiceDecimals)} - - - - ))} - {(!txs || txs.length === 0) && ( -
- {txs ? "no tx-effects in this block" : "loading tx-effectsโ€ฆ"} -
+ {block.body.txEffects.map(({ txHash }, i) => { + const fee = feeByTxHash.get(txHash); + return ( + + + {i} + + {fee === undefined + ? "โ€”" + : formatFees(fee, feeJuiceDecimals)} + + + + ); + })} + {txCount === 0 && ( +
no tx-effects in this block
)} )} From 246df316b389693d947e594811619fa28db9dc3a Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 05:03:26 +0000 Subject: [PATCH 20/34] fix(explorer-ui-v2): show only the tx page's selected status 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 --- ...ped-tx.test.ts => by-hash-lookups.test.ts} | 39 ++++++---- services/explorer-ui-v2/src/api/tx.ts | 22 ++++-- services/explorer-ui-v2/src/hooks/api/tx.ts | 4 +- .../src/pages/tx-detail/index.test.tsx | 76 ++++++++++++++++--- .../src/pages/tx-detail/index.tsx | 18 ++--- 5 files changed, 113 insertions(+), 46 deletions(-) rename services/explorer-ui-v2/src/api/{dropped-tx.test.ts => by-hash-lookups.test.ts} (59%) diff --git a/services/explorer-ui-v2/src/api/dropped-tx.test.ts b/services/explorer-ui-v2/src/api/by-hash-lookups.test.ts similarity index 59% rename from services/explorer-ui-v2/src/api/dropped-tx.test.ts rename to services/explorer-ui-v2/src/api/by-hash-lookups.test.ts index bcc0d011f..39f6da185 100644 --- a/services/explorer-ui-v2/src/api/dropped-tx.test.ts +++ b/services/explorer-ui-v2/src/api/by-hash-lookups.test.ts @@ -3,11 +3,13 @@ import { AxiosError, type AxiosAdapter, type AxiosResponse } from "axios"; import { afterEach, describe, expect, it, vi } from "vitest"; import client from "./client"; import { DroppedTxAPI } from "./dropped-tx"; +import { TxAPI } from "./tx"; vi.mock("~/service/constants", () => ({ API_URL: "https://api.test/key", aztecExplorer: { getL2DroppedTxByHash: (hash: string) => `/l2/dropped-txs/${hash}`, + getL2PendingTxsByHash: (hash: string) => `/l2/txs/${hash}`, }, })); @@ -42,32 +44,37 @@ afterEach(() => { client.defaults.adapter = adapter; }); -describe("DroppedTxAPI.getDroppedTxByHash", () => { - it("answers null once the tx has no dropped row, so a refetch clears the drop it found before", async () => { +describe.each([ + { + name: "DroppedTxAPI.getDroppedTxByHash", + lookup: DroppedTxAPI.getDroppedTxByHash, + row: { txHash: TX, createdAsPendingAt: 1, droppedAt: 2 }, + }, + { + name: "TxAPI.getPendingTxsByHash", + lookup: TxAPI.getPendingTxsByHash, + row: { txHash: TX, feePayer: `0x${"0e".repeat(32)}`, birthTimestamp: 1 }, + }, +])("$name", ({ name, lookup, row }) => { + it("answers null once the tx has no row, so a refetch clears the row it found before", async () => { const queryClient = new QueryClient(); - const lookup = { - queryKey: ["droppedTxByHash", TX], - queryFn: () => DroppedTxAPI.getDroppedTxByHash(TX), + const query = { + queryKey: [name, TX], + queryFn: (): Promise => lookup(TX), retry: false, }; - client.defaults.adapter = answer(200, { - txHash: TX, - createdAsPendingAt: 1, - droppedAt: 2, - }); - await queryClient.fetchQuery(lookup); + client.defaults.adapter = answer(200, row); + await queryClient.fetchQuery(query); client.defaults.adapter = answer(404, "not found"); - await queryClient.refetchQueries({ queryKey: lookup.queryKey }); + await queryClient.refetchQueries({ queryKey: query.queryKey }); - expect(queryClient.getQueryData(lookup.queryKey)).toBeNull(); + expect(queryClient.getQueryData(query.queryKey)).toBeNull(); }); it("still fails on any other error", async () => { client.defaults.adapter = answer(500, "boom"); - await expect(DroppedTxAPI.getDroppedTxByHash(TX)).rejects.toMatchObject({ - status: 500, - }); + await expect(lookup(TX)).rejects.toMatchObject({ status: 500 }); }); }); diff --git a/services/explorer-ui-v2/src/api/tx.ts b/services/explorer-ui-v2/src/api/tx.ts index ab1441ee3..81bfbc228 100644 --- a/services/explorer-ui-v2/src/api/tx.ts +++ b/services/explorer-ui-v2/src/api/tx.ts @@ -8,18 +8,28 @@ import { } from "@chicmoz-pkg/types"; import { z } from "zod"; import { aztecExplorer } from "~/service/constants"; -import client, { validateResponse } from "./client"; +import client, { isNotFoundError, validateResponse } from "./client"; export const TxAPI = { getPendingTxs: async (): Promise => { const response = await client.get(aztecExplorer.getL2PendingTxs); return validateResponse(z.array(chicmozL2PendingTxSchema), response.data); }, - getPendingTxsByHash: async (hash: string): Promise => { - const response = await client.get( - aztecExplorer.getL2PendingTxsByHash(hash), - ); - return validateResponse(chicmozL2PendingTxSchema, response.data); + /** `null` for a tx with no pending row: a failed refetch would keep the row it last found. */ + getPendingTxsByHash: async ( + hash: string, + ): Promise => { + try { + const response = await client.get( + aztecExplorer.getL2PendingTxsByHash(hash), + ); + return validateResponse(chicmozL2PendingTxSchema, response.data); + } catch (error) { + if (isNotFoundError(error)) { + return null; + } + throw error; + } }, getPublicCallRequestsByTxHash: async ( diff --git a/services/explorer-ui-v2/src/hooks/api/tx.ts b/services/explorer-ui-v2/src/hooks/api/tx.ts index 8853db903..51b754a44 100644 --- a/services/explorer-ui-v2/src/hooks/api/tx.ts +++ b/services/explorer-ui-v2/src/hooks/api/tx.ts @@ -24,8 +24,8 @@ export const usePendingTxs = (): UseQueryResult< export const usePendingTxsByHash = ( hash: string, -): UseQueryResult => { - return useQuery({ +): UseQueryResult => { + return useQuery({ queryKey: queryKeyGenerator.pendingTxsByHash(hash), queryFn: () => TxAPI.getPendingTxsByHash(hash), enabled: !!hash, diff --git a/services/explorer-ui-v2/src/pages/tx-detail/index.test.tsx b/services/explorer-ui-v2/src/pages/tx-detail/index.test.tsx index 13b7fabde..5277d6c2a 100644 --- a/services/explorer-ui-v2/src/pages/tx-detail/index.test.tsx +++ b/services/explorer-ui-v2/src/pages/tx-detail/index.test.tsx @@ -4,7 +4,11 @@ import { describe, expect, it, vi } from "vitest"; const TX = `0x${"cd".repeat(32)}`; const BLOCK = `0x${"ab".repeat(32)}`; -const found = vi.hoisted(() => ({ effect: undefined as unknown })); +const found = vi.hoisted(() => ({ + effect: undefined as unknown, + pending: null as unknown, + dropped: null as unknown, +})); vi.mock("@tanstack/react-router", async () => { const { createElement } = await import("react"); @@ -36,9 +40,9 @@ vi.mock("~/components/layout", () => ({ ConsoleHead: () => null, })); vi.mock("~/hooks/api", () => ({ - usePendingTxsByHash: () => ({ data: undefined }), + usePendingTxsByHash: () => ({ data: found.pending }), useGetTxEffectByHash: () => ({ data: found.effect }), - useDroppedTxByHash: () => ({ data: null }), + useDroppedTxByHash: () => ({ data: found.dropped }), usePublicCallRequestsByTxHash: () => ({ data: [] }), useChainInfo: () => ({ data: undefined }), })); @@ -50,13 +54,26 @@ vi.stubEnv("VITE_API_KEY", "dev-api-key"); const { TxDetailPage } = await import("./index"); -const render = (isOrphaned: boolean) => { - found.effect = { +// Each panel by the API path its head names. +const PANELS = { pending: "/api/l2/txs/", dropped: "/api/l2/dropped-txs/" }; + +// What the lookups hold for the tx: its effect (in a block on the chain, or +// only in an orphaned one), and whether it has a pending and a dropped row. +const render = ({ + effect, + pending = false, + dropped = false, +}: { + effect?: "mined" | "orphaned"; + pending?: boolean; + dropped?: boolean; +}) => { + found.effect = effect && { txHash: TX, blockHash: BLOCK, blockHeight: 7n, timestamp: 1_700_000_000_000, - isOrphaned, + isOrphaned: effect === "orphaned", transactionFee: "1000", revertCode: { code: 0 }, noteHashes: [], @@ -67,29 +84,68 @@ const render = (isOrphaned: boolean) => { publicLogs: [], contractClassLogs: [], }; + found.pending = pending + ? { txHash: TX, feePayer: BLOCK, birthTimestamp: 1_700_000_000_000 } + : null; + found.dropped = dropped + ? { + txHash: TX, + createdAsPendingAt: 1_700_000_000_000, + droppedAt: 1_700_000_100_000, + dropReason: "expired", + } + : null; const html = renderToStaticMarkup(); return { status: /class="status-pill (\w+)"/.exec(html)?.[1], blockLinks: [...html.matchAll(/href="\/blocks\/([^"]+)"/g)].map( ([, block]) => block, ), + droppedAt: html.includes("dropped at "), + panels: Object.entries(PANELS) + .filter(([, path]) => html.includes(path)) + .map(([panel]) => panel), notFound: html.includes("tx not found"), }; }; describe("TxDetailPage", () => { it("shows a tx whose effect only an orphaned block keeps as not mined, and links that block by hash", () => { - expect(render(true)).toEqual({ + expect(render({ effect: "orphaned" })).toEqual({ status: "orphaned", blockLinks: [BLOCK, BLOCK, BLOCK], + droppedAt: false, + panels: [], notFound: false, }); }); - it("links a mined tx's block by height", () => { - expect(render(false)).toEqual({ + it("shows a mined tx as mined, links its block by hash, and shows no drop it once had", () => { + expect(render({ effect: "mined", dropped: true })).toEqual({ status: "mined", - blockLinks: ["7", "7", "7"], + blockLinks: [BLOCK, BLOCK, BLOCK], + droppedAt: false, + panels: [], + notFound: false, + }); + }); + + it("shows a dropped tx's drop, not the pending row it still has", () => { + expect(render({ pending: true, dropped: true })).toEqual({ + status: "dropped", + blockLinks: [], + droppedAt: true, + panels: ["dropped"], + notFound: false, + }); + }); + + it("shows a pending tx's pending row", () => { + expect(render({ pending: true })).toEqual({ + status: "pending", + blockLinks: [], + droppedAt: false, + panels: ["pending"], notFound: false, }); }); diff --git a/services/explorer-ui-v2/src/pages/tx-detail/index.tsx b/services/explorer-ui-v2/src/pages/tx-detail/index.tsx index a220bbe4b..1913c9cbc 100644 --- a/services/explorer-ui-v2/src/pages/tx-detail/index.tsx +++ b/services/explorer-ui-v2/src/pages/tx-detail/index.tsx @@ -32,18 +32,12 @@ import { type Tab = "notes" | "nulls" | "public" | "l1" | "logs" | "calls"; -// An orphaned block's height now names the block that replaced it. +// By hash: a height names whichever block is canonical there when the link +// is followed, which can be another block by then. const EffectBlockLink: FC<{ effect: ChicmozL2TxEffectDeluxe }> = ({ effect, }) => ( - + #{fmtNum(Number(effect.blockHeight))} ); @@ -115,7 +109,7 @@ export const TxDetailPage: FC = () => { {historical ? "was in" : "in"}
)} - {dropped && ( + {status === "dropped" && dropped && ( dropped at {toIsoUtc(dropped.droppedAt)} @@ -317,7 +311,7 @@ export const TxDetailPage: FC = () => { )} - {!mined && pending && ( + {status === "pending" && pending && ( <>
@@ -381,7 +375,7 @@ export const TxDetailPage: FC = () => { )} - {!mined && !pending && dropped && ( + {status === "dropped" && dropped && (

From bb8cf54a5243de1a03b7c2d1306dc963caa9cb96 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 05:33:40 +0000 Subject: [PATCH 21/34] fix(explorer-api): send the least recently seen due tip repair first 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 --- .../controllers/l2block/missing-ranges.ts | 9 ++++--- .../integration/open-gap.integration.test.ts | 25 ++++++++++++++----- 2 files changed, 24 insertions(+), 10 deletions(-) diff --git a/services/explorer-api/src/svcs/database/controllers/l2block/missing-ranges.ts b/services/explorer-api/src/svcs/database/controllers/l2block/missing-ranges.ts index 6a6e9af46..7c7db724a 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2block/missing-ranges.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2block/missing-ranges.ts @@ -6,7 +6,6 @@ import { getDb as db } from "@chicmoz-pkg/postgres-helper"; import { and, asc, - desc, eq, gte, inArray, @@ -584,8 +583,10 @@ export const buildMissingBlockRangeRequest = async ({ }; /** - * Asks for the window around an open tip-boundary mismatch: the most recently - * seen one whose window is not backing off. A window is re-sent whole while + * Asks for the window around an open tip-boundary mismatch: the least + * recently seen one whose window is not backing off. While the block + * consumer lags, a newer mismatch can appear on every tick; oldest first, it + * cannot keep an older one waiting. A window is re-sent whole while * its mismatch stays open (its heights may be present but wrong), with the * same backoff as other gaps, whatever the window row's status: blocks * landing in the window fulfil it without resolving a mismatch. @@ -640,7 +641,7 @@ export const buildTipBoundaryRepairRequest = ), ), ) - .orderBy(desc(mismatch.lastSeenAt)) + .orderBy(asc(mismatch.lastSeenAt)) .limit(1); if (!candidate) { return null; diff --git a/services/explorer-api/tests/integration/open-gap.integration.test.ts b/services/explorer-api/tests/integration/open-gap.integration.test.ts index b67993570..52a0378e2 100644 --- a/services/explorer-api/tests/integration/open-gap.integration.test.ts +++ b/services/explorer-api/tests/integration/open-gap.integration.test.ts @@ -266,16 +266,29 @@ describe("open gap scheduling on a real database", () => { expect(await tick()).toEqual([[170, 170], [180, 180]]); }); + it("sends the least recently seen of two due tip repairs first", async () => { + await mismatches([ + { height: 700, seenAgoMs: 10 * MINUTE }, + { height: 600, seenAgoMs: 20 * MINUTE }, + ]); + + expect((await repairTick())?.[0]).toEqual([600, 600]); + expect((await repairTick())?.[0]).toEqual([700, 700]); + }); + it("sends a due tip repair past more backed-off windows than the scheduler's candidates", async () => { - // Each seen more recently than the due mismatch at 900, and more of them - // than the scheduler's 50 candidates. The first ticks request, and so - // back off, these windows; the one at 3 starts at height 1. + // Each seen before the due mismatch at 900, and more of them than the + // scheduler's 50 candidates. The first ticks request, and so back off, + // these windows; the one at 3 starts at height 1. const backedOff = [3, ...span(1_001, 1_050)]; await mismatches([ // Never fetched: the listener starts at height 1. - { height: 0, seenAgoMs: 0 }, - ...backedOff.map((height, i) => ({ height, seenAgoMs: (i + 1) * 1_000 })), - { height: 950, seenAgoMs: 30 * MINUTE, version: OLD }, + { height: 0, seenAgoMs: 180 * MINUTE }, + ...backedOff.map((height, i) => ({ + height, + seenAgoMs: 120 * MINUTE - i * 1_000, + })), + { height: 950, seenAgoMs: 90 * MINUTE, version: OLD }, { height: 900, seenAgoMs: 60 * MINUTE }, ]); From 4b7b6a788df4e13b20f8e7e039476b1b1c18884c Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 05:38:24 +0000 Subject: [PATCH 22/34] test(explorer-api): send a tip repair again once its window's backoff 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 --- .../tests/integration/open-gap.integration.test.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/services/explorer-api/tests/integration/open-gap.integration.test.ts b/services/explorer-api/tests/integration/open-gap.integration.test.ts index 52a0378e2..bd16ec1cd 100644 --- a/services/explorer-api/tests/integration/open-gap.integration.test.ts +++ b/services/explorer-api/tests/integration/open-gap.integration.test.ts @@ -276,6 +276,16 @@ describe("open gap scheduling on a real database", () => { expect((await repairTick())?.[0]).toEqual([700, 700]); }); + it("sends a tip repair again once its window's backoff has passed, and not before", async () => { + await mismatches([{ height: 500, seenAgoMs: MINUTE }]); + expect((await repairTick())?.[0]).toEqual([500, 500]); + + // One request: the window waits two cadences. + expect(await repairTick()).toBeNull(); + await elapse(2 * CADENCE_MS); + expect((await repairTick())?.[0]).toEqual([500, 500]); + }); + it("sends a due tip repair past more backed-off windows than the scheduler's candidates", async () => { // Each seen before the due mismatch at 900, and more of them than the // scheduler's 50 candidates. The first ticks request, and so back off, From f2cbbc25b30b3a1909ceb7e23e52da0649e8bd98 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 05:38:44 +0000 Subject: [PATCH 23/34] fix(explorer-ui-v2): show no index or fee on an orphaned block's page 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 --- .../src/pages/block-detail/index.test.tsx | 41 ++++++++++++------- .../src/pages/block-detail/index.tsx | 17 +++++--- services/explorer-ui-v2/src/styles/pages.css | 7 ++++ 3 files changed, 46 insertions(+), 19 deletions(-) diff --git a/services/explorer-ui-v2/src/pages/block-detail/index.test.tsx b/services/explorer-ui-v2/src/pages/block-detail/index.test.tsx index 768dcc2e5..803c47d9e 100644 --- a/services/explorer-ui-v2/src/pages/block-detail/index.test.tsx +++ b/services/explorer-ui-v2/src/pages/block-detail/index.test.tsx @@ -55,7 +55,8 @@ vi.stubEnv("VITE_API_KEY", "dev-api-key"); const { BlockDetailPage } = await import("./index"); const { formatFees } = await import("~/lib/utils"); -// The tx rows, as [tx hash, fee]. +// The tx rows, as [tx hash, index, fee], and whether the page notes where a +// tx mined again is listed. const render = ({ body, orphaned, @@ -95,28 +96,37 @@ const render = ({ timestamp: 1_700_000_000_000, })); const html = renderToStaticMarkup(); - return [ - ...html.matchAll( - /href="\/tx-effects\/([^"]+)">.*?(.*?) [txHash, fee]); + return { + rows: [ + ...html.matchAll( + /href="\/tx-effects\/([^"]+)">.*?(.*?)<\/span>(.*?) [txHash, index, fee]), + note: html.includes("a later block also mined"), + }; }; describe("BlockDetailPage", () => { - it("lists an orphaned block's own txs, not those of the block its height now names", () => { + it("lists an orphaned block's own txs with no index or fee, and notes where a tx mined again is listed", () => { expect( render({ - body: [TX_A], + body: [TX_A, TX_B], orphaned: true, heightRead: [ [TX_B, ONE], [TX_C, TWO], ], }), - ).toEqual([[TX_A, "โ€”"]]); + ).toEqual({ + rows: [ + [TX_A, "โ€”", "โ€”"], + [TX_B, "โ€”", "โ€”"], + ], + note: true, + }); }); - it("lists a block's txs in its order, each with its own fee", () => { + it("lists a block's txs in its order, each with its index and its own fee", () => { expect( render({ body: [TX_B, TX_C], @@ -126,9 +136,12 @@ describe("BlockDetailPage", () => { [TX_B, ONE], ], }), - ).toEqual([ - [TX_B, formatFees(ONE)], - [TX_C, formatFees(TWO)], - ]); + ).toEqual({ + rows: [ + [TX_B, "0", formatFees(ONE)], + [TX_C, "1", formatFees(TWO)], + ], + note: false, + }); }); }); diff --git a/services/explorer-ui-v2/src/pages/block-detail/index.tsx b/services/explorer-ui-v2/src/pages/block-detail/index.tsx index 6528d9b57..7da789b1b 100644 --- a/services/explorer-ui-v2/src/pages/block-detail/index.tsx +++ b/services/explorer-ui-v2/src/pages/block-detail/index.tsx @@ -91,9 +91,11 @@ export const BlockDetailPage: FC = () => { const totalFees = formatFees(block.header.totalFees, feeJuiceDecimals); const totalManaUsed = block.header.totalManaUsed?.toString?.() ?? "0"; const txCount = block.body.txEffects.length; - // The height read lists the canonical block's txs, which for an orphaned - // block are its replacement's: the body says which txs this block holds, - // and the read only adds their fees. + // The body says which txs this block holds; the height read, the canonical + // block's, only adds their fees. A tx's effect moves to the block that + // mines it again, so an orphaned body keeps only the rest: its positions + // are not their indexes, and a fee by hash can be the later block's. + const orphaned = !!block.orphan; const feeByTxHash = new Map(txs?.map((t) => [t.txHash, t.transactionFee])); const l1Anchor = block.proposedOnL1 ?? block.proofVerifiedOnL1; const blockRollupVersion = BigInt(block.header.globalVariables.version); @@ -392,8 +394,13 @@ export const BlockDetailPage: FC = () => {
Idx
Fee ({feeJuiceSymbol})

+ {orphaned && ( +
+ a tx that a later block also mined is listed under that block +
+ )} {block.body.txEffects.map(({ txHash }, i) => { - const fee = feeByTxHash.get(txHash); + const fee = orphaned ? undefined : feeByTxHash.get(txHash); return ( { params={{ hash: txHash }} > - {i} + {orphaned ? "โ€”" : i} {fee === undefined ? "โ€”" diff --git a/services/explorer-ui-v2/src/styles/pages.css b/services/explorer-ui-v2/src/styles/pages.css index b037f7a6a..00c17e23c 100644 --- a/services/explorer-ui-v2/src/styles/pages.css +++ b/services/explorer-ui-v2/src/styles/pages.css @@ -809,6 +809,13 @@ color: var(--ink-3); text-align: right; } +.block-tx-note { + padding: 10px 18px; + border-bottom: 1px solid var(--line-soft); + font-family: var(--mono); + font-size: 11px; + color: var(--ink-3); +} /* ==================================================================== * CONTRACTS From 2c9b6192c146b12e6b67946ae804a0bf816d15cd Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 05:39:04 +0000 Subject: [PATCH 24/34] fix(explorer-ui-v2): show no status for a tx no lookup found 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 --- .../explorer-ui-v2/src/pages/tx-detail/index.test.tsx | 10 ++++++++++ services/explorer-ui-v2/src/pages/tx-detail/index.tsx | 5 +++-- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/services/explorer-ui-v2/src/pages/tx-detail/index.test.tsx b/services/explorer-ui-v2/src/pages/tx-detail/index.test.tsx index 5277d6c2a..3a499bae4 100644 --- a/services/explorer-ui-v2/src/pages/tx-detail/index.test.tsx +++ b/services/explorer-ui-v2/src/pages/tx-detail/index.test.tsx @@ -140,6 +140,16 @@ describe("TxDetailPage", () => { }); }); + it("shows no status for a tx no lookup found", () => { + expect(render({})).toEqual({ + status: undefined, + blockLinks: [], + droppedAt: false, + panels: [], + notFound: true, + }); + }); + it("shows a pending tx's pending row", () => { expect(render({ pending: true })).toEqual({ status: "pending", diff --git a/services/explorer-ui-v2/src/pages/tx-detail/index.tsx b/services/explorer-ui-v2/src/pages/tx-detail/index.tsx index 1913c9cbc..b96b98538 100644 --- a/services/explorer-ui-v2/src/pages/tx-detail/index.tsx +++ b/services/explorer-ui-v2/src/pages/tx-detail/index.tsx @@ -60,6 +60,7 @@ export const TxDetailPage: FC = () => { // Only a block on the chain mines a tx: an orphaned block's effect is history. const historical = effect?.isOrphaned === true; const mined = !!effect && !historical; + // No status while no lookup has found the tx. const status = mined ? "mined" : dropped @@ -68,7 +69,7 @@ export const TxDetailPage: FC = () => { ? "pending" : historical ? "orphaned" - : "pending"; + : undefined; const ts = effect?.timestamp ? effect.timestamp @@ -103,7 +104,7 @@ export const TxDetailPage: FC = () => {
Tx effect ยท {ts ? ageStr(ts) : "โ€”"}

{hash}

- + {status && } {effect?.blockHeight !== undefined && ( {historical ? "was in" : "in"} From c28a2d783077e2d4b7e6b9b5f41baa88288749cb Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 05:39:44 +0000 Subject: [PATCH 25/34] docs(explorer-api): describe the tip repair request and the mismatch 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 --- .../src/svcs/database/controllers/l2/tips.ts | 6 ++++-- .../svcs/database/controllers/l2block/missing-ranges.ts | 9 +++++---- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/services/explorer-api/src/svcs/database/controllers/l2/tips.ts b/services/explorer-api/src/svcs/database/controllers/l2/tips.ts index 5baf5fad8..73b3dd653 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2/tips.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2/tips.ts @@ -313,8 +313,10 @@ export const upsertTips = async (event: L2TipsEvent) => { /** * Validates the stored tips again inside a chain change, healthy or * degraded: the change may have stored a block they name, or demoted one. - * An unchanged result records no mismatch, so a mismatch's occurrence count - * counts tips events, but the change may still have resolved an open one. + * A result that differs from the stored one is recorded, so a mismatch's + * occurrence count counts the chain changes that found it as well as tips + * events. An unchanged result records nothing, though the change may still + * have resolved an open mismatch. */ export const revalidateTips = async (dbTx: DbTx) => { const [row] = await dbTx diff --git a/services/explorer-api/src/svcs/database/controllers/l2block/missing-ranges.ts b/services/explorer-api/src/svcs/database/controllers/l2block/missing-ranges.ts index 7c7db724a..8c78d7fe2 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2block/missing-ranges.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2block/missing-ranges.ts @@ -586,10 +586,11 @@ export const buildMissingBlockRangeRequest = async ({ * Asks for the window around an open tip-boundary mismatch: the least * recently seen one whose window is not backing off. While the block * consumer lags, a newer mismatch can appear on every tick; oldest first, it - * cannot keep an older one waiting. A window is re-sent whole while - * its mismatch stays open (its heights may be present but wrong), with the - * same backoff as other gaps, whatever the window row's status: blocks - * landing in the window fulfil it without resolving a mismatch. + * cannot keep an older one waiting. The request names the mismatch height + * first, then the rest of its window, and is sent again while the mismatch + * stays open (its heights may be present but wrong), with the same backoff + * as other gaps, whatever the window row's status: blocks landing in the + * window fulfil the row without resolving the mismatch. */ export const buildTipBoundaryRepairRequest = async (): Promise => { From d242ff7e79108e61bba648c885e716721a3bdc0b Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 07:02:59 +0000 Subject: [PATCH 26/34] fix(explorer-api): roll back the block when a contract row hits a retryable 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 --- .../database/controllers/l2contract/store.ts | 26 +++++++- .../unit/block-contract-row-errors.test.ts | 59 +++++++++++++++++++ 2 files changed, 84 insertions(+), 1 deletion(-) create mode 100644 services/explorer-api/tests/unit/block-contract-row-errors.test.ts diff --git a/services/explorer-api/src/svcs/database/controllers/l2contract/store.ts b/services/explorer-api/src/svcs/database/controllers/l2contract/store.ts index c60a13f8e..4d45c7df8 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2contract/store.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2contract/store.ts @@ -168,9 +168,30 @@ export type BlockContracts = { instancesUpdated: ChicmozL2ContractInstanceUpdatedEvent[]; }; +const RETRYABLE_CLASSES = new Set(["08", "40", "53", "57"]); + +/** + * Whether a rerun of the block can clear `e`: SQLSTATE classes 08 + * (connection), 40 (serialization failure, deadlock), 53 (insufficient + * resources) and 57 (operator intervention), and 55P03 (lock timeout). + */ +const retryable = (e: unknown): boolean => { + // drizzle-orm 0.44 and later wrap pg's error, keeping it as `cause`. + const { code, cause } = (e ?? {}) as { + code?: unknown; + cause?: { code?: unknown }; + }; + const state = code ?? cause?.code; + return ( + typeof state === "string" && + (RETRYABLE_CLASSES.has(state.slice(0, 2)) || state === "55P03") + ); +}; + /** * Stores a canonical block's contract rows, each in a savepoint: a row that - * fails is logged and skipped, and a failed heartbeat aborts the block. + * fails on its own data is logged and skipped, while a failed heartbeat or an + * error a retry can cure aborts the block. */ export const storeBlockContracts = async ( dbTx: DbTx, @@ -191,6 +212,9 @@ export const storeBlockContracts = async ( ); } } catch (e) { + if (retryable(e)) { + throw e; + } logger.error( `Failed to store ${label(row)}: ${(e as Error).stack ?? String(e)}`, ); diff --git a/services/explorer-api/tests/unit/block-contract-row-errors.test.ts b/services/explorer-api/tests/unit/block-contract-row-errors.test.ts new file mode 100644 index 000000000..faf611101 --- /dev/null +++ b/services/explorer-api/tests/unit/block-contract-row-errors.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, it, vi } from "vitest"; + +vi.mock("@chicmoz-pkg/postgres-helper", () => ({ getDb: vi.fn() })); +vi.mock("../../src/logger.js", () => ({ + logger: { debug: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() }, +})); +vi.mock("../../src/utils/resolve-artifact-names.js", () => ({ + buildSelectorMap: vi.fn(), + selectorMapValueToFunctionName: vi.fn(), +})); + +const { storeBlockContracts } = await import( + "../../src/svcs/database/controllers/l2contract/store.js" +); + +type DbTx = Parameters[0]; + +const contracts = { + classes: [{ contractClassId: "0x0a" }, { contractClassId: "0x0b" }], + instancesDeployed: [], + instancesUpdated: [], +} as unknown as Parameters[1]; + +// pg's error for a failed statement carries its SQLSTATE as `code`. +const pgError = (code: string, message: string) => + Object.assign(new Error(message), { code }); + +// The first row's savepoint rejects with `error`; every later one stores. +const failFirstSavepoint = (error: Error) => { + const transaction = vi + .fn() + .mockRejectedValueOnce(error) + .mockResolvedValue(true); + return { transaction, dbTx: { transaction } as unknown as DbTx }; +}; + +describe("a contract row whose savepoint fails", () => { + it("aborts the block on a lock timeout, so the bus redelivers it", async () => { + const lockTimeout = pgError( + "55P03", + "canceling statement due to lock timeout", + ); + const { transaction, dbTx } = failFirstSavepoint(lockTimeout); + + await expect( + storeBlockContracts(dbTx, contracts, () => Promise.resolve()), + ).rejects.toBe(lockTimeout); + expect(transaction).toHaveBeenCalledTimes(1); + }); + + it("skips a row that fails on its own data and stores the next", async () => { + const { transaction, dbTx } = failFirstSavepoint( + pgError("23505", "duplicate key value violates unique constraint"), + ); + + await storeBlockContracts(dbTx, contracts, () => Promise.resolve()); + expect(transaction).toHaveBeenCalledTimes(2); + }); +}); From ce1d8e46c392e7aeefab351d9cff780c55c6ad88 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 07:09:02 +0000 Subject: [PATCH 27/34] fix(explorer-ui-v2): keep refetching a tx effect while it is orphaned 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 --- .../src/hooks/api/tx-effect.test.tsx | 39 +++++++++++++++++++ .../explorer-ui-v2/src/hooks/api/tx-effect.ts | 9 ++++- 2 files changed, 46 insertions(+), 2 deletions(-) create mode 100644 services/explorer-ui-v2/src/hooks/api/tx-effect.test.tsx diff --git a/services/explorer-ui-v2/src/hooks/api/tx-effect.test.tsx b/services/explorer-ui-v2/src/hooks/api/tx-effect.test.tsx new file mode 100644 index 000000000..d14c186f0 --- /dev/null +++ b/services/explorer-ui-v2/src/hooks/api/tx-effect.test.tsx @@ -0,0 +1,39 @@ +import { renderToStaticMarkup } from "react-dom/server"; +import { describe, expect, it, vi } from "vitest"; +import { REFETCH_INTERVAL } from "./utils"; + +type RefetchInterval = (query: { + state: { data?: { isOrphaned: boolean } }; +}) => number | false; + +const passed = vi.hoisted(() => ({ options: undefined as unknown })); + +vi.mock("@tanstack/react-query", () => ({ + useQuery: (options: unknown) => { + passed.options = options; + return {}; + }, +})); +vi.mock("~/api", () => ({ TxEffectsAPI: {} })); + +const { useGetTxEffectByHash } = await import("./tx-effect"); + +// react-query asks for the interval again after each fetch, with its data. +const intervalAfterFetching = (isOrphaned: boolean) => { + const TxPage = () => { + useGetTxEffectByHash(`0x${"cd".repeat(32)}`); + return null; + }; + renderToStaticMarkup(); + const { refetchInterval } = passed.options as { + refetchInterval: RefetchInterval; + }; + return refetchInterval({ state: { data: { isOrphaned } } }); +}; + +describe("useGetTxEffectByHash", () => { + it("refetches an effect while only an orphaned block holds it, and stops once it is canonical", () => { + expect(intervalAfterFetching(true)).toBe(REFETCH_INTERVAL); + expect(intervalAfterFetching(false)).toBe(false); + }); +}); diff --git a/services/explorer-ui-v2/src/hooks/api/tx-effect.ts b/services/explorer-ui-v2/src/hooks/api/tx-effect.ts index 4a3f68f1a..edc3aab83 100644 --- a/services/explorer-ui-v2/src/hooks/api/tx-effect.ts +++ b/services/explorer-ui-v2/src/hooks/api/tx-effect.ts @@ -18,9 +18,14 @@ export const useGetTxEffectByHash = ( queryKey: queryKeyGenerator.txEffectByHash(hash), queryFn: () => TxEffectsAPI.getTxEffectByHash(hash), enabled: !!hash, + // A catch-up block can move an orphaned effect back onto the chain, and + // no websocket frame announces a catch-up block. refetchInterval: ({ state }) => - refetchUntilFound && !state.data ? LIVE_REFETCH_INTERVAL : false, - // Mined tx effects are immutable โ€” cache for 5min. + refetchUntilFound && !state.data + ? LIVE_REFETCH_INTERVAL + : state.data?.isOrphaned + ? REFETCH_INTERVAL + : false, staleTime: 5 * 60_000, }); }; From 6196ec1c07ff1d4553338a432b992cfe356627ac Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 07:23:55 +0000 Subject: [PATCH 28/34] refactor(explorer-api): take the chain walk bound from the message registry 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 --- .../src/svcs/database/controllers/l2block/canonical.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts b/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts index 29d4e8d1c..15a0b0561 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts @@ -1,4 +1,5 @@ import { type Heartbeat } from "@chicmoz-pkg/message-bus"; +import { CHAIN_WALK_BOUND } from "@chicmoz-pkg/message-registry"; import { type ChicmozL2Block, type HexString } from "@chicmoz-pkg/types"; import { and, asc, eq, gt, inArray, isNotNull, isNull, sql } from "drizzle-orm"; import { alias } from "drizzle-orm/pg-core"; @@ -50,7 +51,7 @@ import { store, writeTxEffect } from "./store.js"; // descends from carries that chain's authority over the heights below it. /** Walks stop after this many steps; more canonical blocks than this above a tip is corrupted state. */ -export const WALK_BOUND = 10_000; +export const WALK_BOUND = CHAIN_WALK_BOUND; const HEARTBEAT_EVERY = 500; const ROWS_PER_STATEMENT = 1_000; From 12c01315493e0e2cbcc5fee4a75bf85d9034f5bc Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 07:24:16 +0000 Subject: [PATCH 29/34] docs(explorer-ui-v2): say what refreshes a cached block A block changes with the chain, so the cache comment no longer claims it never does. Co-Authored-By: Claude Opus 5.5 --- services/explorer-ui-v2/src/hooks/api/block.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/explorer-ui-v2/src/hooks/api/block.ts b/services/explorer-ui-v2/src/hooks/api/block.ts index 72f468483..4ebee7377 100644 --- a/services/explorer-ui-v2/src/hooks/api/block.ts +++ b/services/explorer-ui-v2/src/hooks/api/block.ts @@ -36,8 +36,8 @@ export const useGetBlockByIdentifier = ( ? BlockAPI.getBlockByHash(heightOrHash) : BlockAPI.getBlockByHeight(heightOrHash), enabled: !!heightOrHash, - // Historical blocks don't mutate; cache them for a while so walking - // next/prev on the detail page is instant. + // Cached so walking next/prev on the detail page is instant; block and + // tips frames refresh it when the chain changes. staleTime: 5 * 60_000, }); }; From b5d85cc7e3208bd3b72e538f3c49786821b290ad Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 07:37:16 +0000 Subject: [PATCH 30/34] test(explorer-api): cover a retryable error wrapped as a query error'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 --- .../unit/block-contract-row-errors.test.ts | 31 ++++++++++++------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/services/explorer-api/tests/unit/block-contract-row-errors.test.ts b/services/explorer-api/tests/unit/block-contract-row-errors.test.ts index faf611101..0449984d3 100644 --- a/services/explorer-api/tests/unit/block-contract-row-errors.test.ts +++ b/services/explorer-api/tests/unit/block-contract-row-errors.test.ts @@ -35,18 +35,27 @@ const failFirstSavepoint = (error: Error) => { }; describe("a contract row whose savepoint fails", () => { - it("aborts the block on a lock timeout, so the bus redelivers it", async () => { - const lockTimeout = pgError( - "55P03", - "canceling statement due to lock timeout", - ); - const { transaction, dbTx } = failFirstSavepoint(lockTimeout); + it.each([ + { shape: "as pg throws it", wrap: (e: Error) => e }, + { + shape: "wrapped as a query error's cause", + wrap: (e: Error) => + Object.assign(new Error("Failed query"), { cause: e }), + }, + ])( + "aborts the block on a lock timeout $shape, so the bus redelivers it", + async ({ wrap }) => { + const lockTimeout = wrap( + pgError("55P03", "canceling statement due to lock timeout"), + ); + const { transaction, dbTx } = failFirstSavepoint(lockTimeout); - await expect( - storeBlockContracts(dbTx, contracts, () => Promise.resolve()), - ).rejects.toBe(lockTimeout); - expect(transaction).toHaveBeenCalledTimes(1); - }); + await expect( + storeBlockContracts(dbTx, contracts, () => Promise.resolve()), + ).rejects.toBe(lockTimeout); + expect(transaction).toHaveBeenCalledTimes(1); + }, + ); it("skips a row that fails on its own data and stores the next", async () => { const { transaction, dbTx } = failFirstSavepoint( From b16b13c0147e6a5dd6ba80635e4d457d5d3316e6 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 07:39:46 +0000 Subject: [PATCH 31/34] fix(explorer-api): roll back the block when a contract row hits a system 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 --- .../database/controllers/l2contract/store.ts | 5 ++-- .../unit/block-contract-row-errors.test.ts | 25 +++++++++++-------- 2 files changed, 17 insertions(+), 13 deletions(-) diff --git a/services/explorer-api/src/svcs/database/controllers/l2contract/store.ts b/services/explorer-api/src/svcs/database/controllers/l2contract/store.ts index 4d45c7df8..dc7b65d74 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2contract/store.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2contract/store.ts @@ -168,12 +168,13 @@ export type BlockContracts = { instancesUpdated: ChicmozL2ContractInstanceUpdatedEvent[]; }; -const RETRYABLE_CLASSES = new Set(["08", "40", "53", "57"]); +const RETRYABLE_CLASSES = new Set(["08", "40", "53", "57", "58"]); /** * Whether a rerun of the block can clear `e`: SQLSTATE classes 08 * (connection), 40 (serialization failure, deadlock), 53 (insufficient - * resources) and 57 (operator intervention), and 55P03 (lock timeout). + * resources), 57 (operator intervention) and 58 (system error, such as I/O), + * and 55P03 (lock timeout). */ const retryable = (e: unknown): boolean => { // drizzle-orm 0.44 and later wrap pg's error, keeping it as `cause`. diff --git a/services/explorer-api/tests/unit/block-contract-row-errors.test.ts b/services/explorer-api/tests/unit/block-contract-row-errors.test.ts index 0449984d3..98f6686ed 100644 --- a/services/explorer-api/tests/unit/block-contract-row-errors.test.ts +++ b/services/explorer-api/tests/unit/block-contract-row-errors.test.ts @@ -34,25 +34,28 @@ const failFirstSavepoint = (error: Error) => { return { transaction, dbTx: { transaction } as unknown as DbTx }; }; +const lockTimeout = () => + pgError("55P03", "canceling statement due to lock timeout"); + describe("a contract row whose savepoint fails", () => { it.each([ - { shape: "as pg throws it", wrap: (e: Error) => e }, + { fault: "a lock timeout as pg throws it", error: lockTimeout() }, + { + fault: "a lock timeout wrapped as a query error's cause", + error: Object.assign(new Error("Failed query"), { cause: lockTimeout() }), + }, { - shape: "wrapped as a query error's cause", - wrap: (e: Error) => - Object.assign(new Error("Failed query"), { cause: e }), + fault: "an I/O error", + error: pgError("58030", "could not read block 0 in file: I/O error"), }, ])( - "aborts the block on a lock timeout $shape, so the bus redelivers it", - async ({ wrap }) => { - const lockTimeout = wrap( - pgError("55P03", "canceling statement due to lock timeout"), - ); - const { transaction, dbTx } = failFirstSavepoint(lockTimeout); + "aborts the block on $fault, so the bus redelivers it", + async ({ error }) => { + const { transaction, dbTx } = failFirstSavepoint(error); await expect( storeBlockContracts(dbTx, contracts, () => Promise.resolve()), - ).rejects.toBe(lockTimeout); + ).rejects.toBe(error); expect(transaction).toHaveBeenCalledTimes(1); }, ); From f7656c91cc55edbadf6450ba303df829a99450f2 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 07:49:21 +0000 Subject: [PATCH 32/34] fix(explorer-ui-v2): refetch open tx and block pages that a catch-up 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 --- .../explorer-ui-v2/src/hooks/api/block.ts | 5 +- .../src/hooks/api/tx-effect.test.tsx | 53 ++++++++++++++----- .../explorer-ui-v2/src/hooks/api/tx-effect.ts | 16 +++--- 3 files changed, 52 insertions(+), 22 deletions(-) diff --git a/services/explorer-ui-v2/src/hooks/api/block.ts b/services/explorer-ui-v2/src/hooks/api/block.ts index 4ebee7377..eb881fc43 100644 --- a/services/explorer-ui-v2/src/hooks/api/block.ts +++ b/services/explorer-ui-v2/src/hooks/api/block.ts @@ -36,8 +36,9 @@ export const useGetBlockByIdentifier = ( ? BlockAPI.getBlockByHash(heightOrHash) : BlockAPI.getBlockByHeight(heightOrHash), enabled: !!heightOrHash, - // Cached so walking next/prev on the detail page is instant; block and - // tips frames refresh it when the chain changes. + // Cached so walking next/prev is instant; frames refresh it, but none + // announces a catch-up block, which can orphan it or fill its txs. + refetchInterval: SLOW_REFETCH_INTERVAL, staleTime: 5 * 60_000, }); }; diff --git a/services/explorer-ui-v2/src/hooks/api/tx-effect.test.tsx b/services/explorer-ui-v2/src/hooks/api/tx-effect.test.tsx index d14c186f0..06b36d1f1 100644 --- a/services/explorer-ui-v2/src/hooks/api/tx-effect.test.tsx +++ b/services/explorer-ui-v2/src/hooks/api/tx-effect.test.tsx @@ -1,39 +1,64 @@ import { renderToStaticMarkup } from "react-dom/server"; import { describe, expect, it, vi } from "vitest"; -import { REFETCH_INTERVAL } from "./utils"; +import { REFETCH_INTERVAL, SLOW_REFETCH_INTERVAL } from "./utils"; type RefetchInterval = (query: { state: { data?: { isOrphaned: boolean } }; }) => number | false; -const passed = vi.hoisted(() => ({ options: undefined as unknown })); +const passed = vi.hoisted(() => ({ options: [] as unknown[] })); vi.mock("@tanstack/react-query", () => ({ useQuery: (options: unknown) => { - passed.options = options; + passed.options.push(options); return {}; }, })); -vi.mock("~/api", () => ({ TxEffectsAPI: {} })); +vi.mock("~/api", () => ({ BlockAPI: {}, TxEffectsAPI: {} })); -const { useGetTxEffectByHash } = await import("./tx-effect"); +const { useGetBlockByIdentifier } = await import("./block"); +const { useGetTableTxEffectsByBlockHeight, useGetTxEffectByHash } = + await import("./tx-effect"); + +// The refetchInterval of each query `Page` renders, in call order. +const intervalsOf = (Page: () => null) => { + passed.options = []; + renderToStaticMarkup(); + return passed.options.map( + (options) => (options as { refetchInterval: unknown }).refetchInterval, + ); +}; // react-query asks for the interval again after each fetch, with its data. -const intervalAfterFetching = (isOrphaned: boolean) => { +const intervalAfterFetching = (data?: { isOrphaned: boolean }) => { const TxPage = () => { useGetTxEffectByHash(`0x${"cd".repeat(32)}`); return null; }; - renderToStaticMarkup(); - const { refetchInterval } = passed.options as { - refetchInterval: RefetchInterval; - }; - return refetchInterval({ state: { data: { isOrphaned } } }); + const [refetchInterval] = intervalsOf(TxPage) as [RefetchInterval]; + return refetchInterval({ state: { data } }); }; describe("useGetTxEffectByHash", () => { - it("refetches an effect while only an orphaned block holds it, and stops once it is canonical", () => { - expect(intervalAfterFetching(true)).toBe(REFETCH_INTERVAL); - expect(intervalAfterFetching(false)).toBe(false); + it("refetches an orphaned effect every 10 s and a canonical one every minute, but not a missing one", () => { + expect(intervalAfterFetching({ isOrphaned: true })).toBe(REFETCH_INTERVAL); + expect(intervalAfterFetching({ isOrphaned: false })).toBe( + SLOW_REFETCH_INTERVAL, + ); + expect(intervalAfterFetching()).toBe(false); + }); +}); + +describe("the block page's queries", () => { + it("refetch every minute", () => { + const BlockPage = () => { + useGetBlockByIdentifier("7"); + useGetTableTxEffectsByBlockHeight(7n); + return null; + }; + expect(intervalsOf(BlockPage)).toEqual([ + SLOW_REFETCH_INTERVAL, + SLOW_REFETCH_INTERVAL, + ]); }); }); diff --git a/services/explorer-ui-v2/src/hooks/api/tx-effect.ts b/services/explorer-ui-v2/src/hooks/api/tx-effect.ts index edc3aab83..809f60180 100644 --- a/services/explorer-ui-v2/src/hooks/api/tx-effect.ts +++ b/services/explorer-ui-v2/src/hooks/api/tx-effect.ts @@ -7,6 +7,7 @@ import { TxEffectsAPI } from "~/api"; import { LIVE_REFETCH_INTERVAL, REFETCH_INTERVAL, + SLOW_REFETCH_INTERVAL, queryKeyGenerator, } from "./utils"; @@ -18,14 +19,16 @@ export const useGetTxEffectByHash = ( queryKey: queryKeyGenerator.txEffectByHash(hash), queryFn: () => TxEffectsAPI.getTxEffectByHash(hash), enabled: !!hash, - // A catch-up block can move an orphaned effect back onto the chain, and - // no websocket frame announces a catch-up block. + // Detail queries poll, since catch-up blocks move effects and fill + // blocks' txs with no websocket frame. refetchInterval: ({ state }) => - refetchUntilFound && !state.data - ? LIVE_REFETCH_INTERVAL - : state.data?.isOrphaned + !state.data + ? refetchUntilFound + ? LIVE_REFETCH_INTERVAL + : false + : state.data.isOrphaned ? REFETCH_INTERVAL - : false, + : SLOW_REFETCH_INTERVAL, staleTime: 5 * 60_000, }); }; @@ -54,6 +57,7 @@ export const useGetTableTxEffectsByBlockHeight = ( ? Promise.resolve([]) : TxEffectsAPI.getTableTxEffectsByBlockHeight(BigInt(height)), enabled: height !== undefined, + refetchInterval: SLOW_REFETCH_INTERVAL, staleTime: 5 * 60_000, }); }; From c8df0d0342563a45c15b2adc4ab8604f067b4437 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 08:13:41 +0000 Subject: [PATCH 33/34] fix(explorer-ui-v2): refetch a tx page that has found nothing every minute 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 --- services/explorer-ui-v2/src/hooks/api/tx-effect.test.tsx | 4 ++-- services/explorer-ui-v2/src/hooks/api/tx-effect.ts | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/services/explorer-ui-v2/src/hooks/api/tx-effect.test.tsx b/services/explorer-ui-v2/src/hooks/api/tx-effect.test.tsx index 06b36d1f1..7d1651ad7 100644 --- a/services/explorer-ui-v2/src/hooks/api/tx-effect.test.tsx +++ b/services/explorer-ui-v2/src/hooks/api/tx-effect.test.tsx @@ -40,12 +40,12 @@ const intervalAfterFetching = (data?: { isOrphaned: boolean }) => { }; describe("useGetTxEffectByHash", () => { - it("refetches an orphaned effect every 10 s and a canonical one every minute, but not a missing one", () => { + it("refetches an orphaned effect every 10 s, and a canonical or missing one every minute", () => { expect(intervalAfterFetching({ isOrphaned: true })).toBe(REFETCH_INTERVAL); expect(intervalAfterFetching({ isOrphaned: false })).toBe( SLOW_REFETCH_INTERVAL, ); - expect(intervalAfterFetching()).toBe(false); + expect(intervalAfterFetching()).toBe(SLOW_REFETCH_INTERVAL); }); }); diff --git a/services/explorer-ui-v2/src/hooks/api/tx-effect.ts b/services/explorer-ui-v2/src/hooks/api/tx-effect.ts index 809f60180..0d4982022 100644 --- a/services/explorer-ui-v2/src/hooks/api/tx-effect.ts +++ b/services/explorer-ui-v2/src/hooks/api/tx-effect.ts @@ -19,13 +19,13 @@ export const useGetTxEffectByHash = ( queryKey: queryKeyGenerator.txEffectByHash(hash), queryFn: () => TxEffectsAPI.getTxEffectByHash(hash), enabled: !!hash, - // Detail queries poll, since catch-up blocks move effects and fill - // blocks' txs with no websocket frame. + // Detail queries poll, since catch-up blocks index and move effects and + // fill blocks' txs with no websocket frame. refetchInterval: ({ state }) => !state.data ? refetchUntilFound ? LIVE_REFETCH_INTERVAL - : false + : SLOW_REFETCH_INTERVAL : state.data.isOrphaned ? REFETCH_INTERVAL : SLOW_REFETCH_INTERVAL, From a71876871ce134668d994fd3061259f368b89757 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 09:27:29 +0000 Subject: [PATCH 34/34] test(explorer-api): load start.js before the start-up test runs 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 --- services/explorer-api/tests/unit/start-up.test.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/services/explorer-api/tests/unit/start-up.test.ts b/services/explorer-api/tests/unit/start-up.test.ts index c102d3bb6..f8aa828de 100644 --- a/services/explorer-api/tests/unit/start-up.test.ts +++ b/services/explorer-api/tests/unit/start-up.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it, vi } from "vitest"; +import { start } from "../../src/start.js"; const steps = vi.hoisted(() => { const order: string[] = []; @@ -55,8 +56,6 @@ describe("explorer-api start-up", () => { // A crash between a block's commit and its bump leaves cached chain reads // from before that commit; the sweep's deletions change them too. it("bumps the chain revision after the dropped-tx sweep, before it consumes", async () => { - const { start } = await import("../../src/start.js"); - await start(); expect(steps.order).toEqual(["sweep", "bump", "subscribe"]);