From 46e2cbc153baa23432bae35fc2ed6a7cd19ad4b0 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Thu, 26 Nov 2026 20:23:52 +0000 Subject: [PATCH 01/31] feat(explorer-api): add block link indexes and reorg record tables Link lookups match a block's last archive root to its parent's archive root; both columns get an index, as only the foreign keys had one. l2_tip_boundary_mismatch gains a nullable rollup_version and an index for unresolved rows. l2_reorg holds one row per demotion of canonical blocks, with the lowest demoted block, the count removed, the time it was applied and the time every listed block was canonical again; l2_reorg_block lists the demoted blocks. Co-Authored-By: Claude Opus 5.5 --- .../migrations/0038_block_link_indexes.sql | 4 ++ .../explorer-api/migrations/0039_l2_reorg.sql | 18 ++++++ .../migrations/meta/_journal.json | 14 +++++ .../src/svcs/database/schema/index.ts | 1 + .../src/svcs/database/schema/l2/reorg.ts | 58 +++++++++++++++++++ .../src/svcs/database/schema/l2/tips.ts | 17 +++++- .../svcs/database/schema/l2block/header.ts | 1 + .../src/svcs/database/schema/l2block/root.ts | 1 + .../src/svcs/database/schema/utils.ts | 4 ++ 9 files changed, 116 insertions(+), 2 deletions(-) create mode 100644 services/explorer-api/migrations/0038_block_link_indexes.sql create mode 100644 services/explorer-api/migrations/0039_l2_reorg.sql create mode 100644 services/explorer-api/src/svcs/database/schema/l2/reorg.ts diff --git a/services/explorer-api/migrations/0038_block_link_indexes.sql b/services/explorer-api/migrations/0038_block_link_indexes.sql new file mode 100644 index 00000000..fb647c88 --- /dev/null +++ b/services/explorer-api/migrations/0038_block_link_indexes.sql @@ -0,0 +1,4 @@ +CREATE INDEX IF NOT EXISTS "archive_root_idx" ON "archive" USING btree ("root");--> statement-breakpoint +CREATE INDEX IF NOT EXISTS "last_archive_root_idx" ON "last_archive" USING btree ("root");--> statement-breakpoint +ALTER TABLE "l2_tip_boundary_mismatch" ADD COLUMN IF NOT EXISTS "rollup_version" bigint;--> statement-breakpoint +CREATE INDEX IF NOT EXISTS "l2_tip_boundary_mismatch_unresolved_idx" ON "l2_tip_boundary_mismatch" USING btree ("l2_network_id","height") WHERE "resolved_at" IS NULL; diff --git a/services/explorer-api/migrations/0039_l2_reorg.sql b/services/explorer-api/migrations/0039_l2_reorg.sql new file mode 100644 index 00000000..3ab3b2c7 --- /dev/null +++ b/services/explorer-api/migrations/0039_l2_reorg.sql @@ -0,0 +1,18 @@ +CREATE TABLE IF NOT EXISTS "l2_reorg" ( + "id" bigint PRIMARY KEY GENERATED ALWAYS AS IDENTITY, + "l2_network_id" varchar NOT NULL, + "rollup_version" bigint NOT NULL, + "root_height" bigint NOT NULL, + "root_hash" varchar NOT NULL, + "removed_count" integer NOT NULL, + "observed_at" timestamp NOT NULL, + "revived_at" timestamp +);--> statement-breakpoint +CREATE INDEX IF NOT EXISTS "l2_reorg_network_observed_idx" ON "l2_reorg" USING btree ("l2_network_id","observed_at" DESC);--> statement-breakpoint +CREATE TABLE IF NOT EXISTS "l2_reorg_block" ( + "reorg_id" bigint NOT NULL REFERENCES "l2_reorg"("id") ON DELETE CASCADE, + "height" bigint NOT NULL, + "hash" varchar NOT NULL, + CONSTRAINT "l2_reorg_block_pkey" PRIMARY KEY ("reorg_id","hash") +);--> statement-breakpoint +CREATE INDEX IF NOT EXISTS "l2_reorg_block_hash_idx" ON "l2_reorg_block" USING btree ("hash"); diff --git a/services/explorer-api/migrations/meta/_journal.json b/services/explorer-api/migrations/meta/_journal.json index d145c6b7..af7aabd3 100644 --- a/services/explorer-api/migrations/meta/_journal.json +++ b/services/explorer-api/migrations/meta/_journal.json @@ -267,6 +267,20 @@ "when": 1779960000010, "tag": "0037_reset_open_gap_request_history", "breakpoints": true + }, + { + "idx": 38, + "version": "7", + "when": 1779960000011, + "tag": "0038_block_link_indexes", + "breakpoints": true + }, + { + "idx": 39, + "version": "7", + "when": 1779960000012, + "tag": "0039_l2_reorg", + "breakpoints": true } ] } diff --git a/services/explorer-api/src/svcs/database/schema/index.ts b/services/explorer-api/src/svcs/database/schema/index.ts index 52405039..21369dfc 100644 --- a/services/explorer-api/src/svcs/database/schema/index.ts +++ b/services/explorer-api/src/svcs/database/schema/index.ts @@ -5,6 +5,7 @@ export * from "./dropped-tx/index.js"; export * from "./l2/chain-info.js"; export * from "./l2/rollup-version-observation.js"; export * from "./l2/open-gap.js"; +export * from "./l2/reorg.js"; export * from "./l2/tips.js"; export * from "./l2block/index.js"; export * from "./l2contract/index.js"; diff --git a/services/explorer-api/src/svcs/database/schema/l2/reorg.ts b/services/explorer-api/src/svcs/database/schema/l2/reorg.ts new file mode 100644 index 00000000..0e3943c8 --- /dev/null +++ b/services/explorer-api/src/svcs/database/schema/l2/reorg.ts @@ -0,0 +1,58 @@ +import { HexString, L2NetworkId } from "@chicmoz-pkg/types"; +import { + bigint, + index, + integer, + pgTable, + primaryKey, + timestamp, + varchar, +} from "drizzle-orm/pg-core"; +import { generateBoundedIntegerColumn, l2NetworkIdDbEnum } from "../utils.js"; + +/** + * One row per ordered block that demoted canonical blocks: what the explorer + * had as canonical and removed, not the node's prune depth. `revived_at` is + * the only later write, set once every listed block is canonical again. + */ +export const l2ReorgTable = pgTable( + "l2_reorg", + { + id: bigint("id", { mode: "number" }) + .primaryKey() + .generatedAlwaysAsIdentity(), + l2NetworkId: l2NetworkIdDbEnum("l2_network_id") + .notNull() + .$type(), + rollupVersion: generateBoundedIntegerColumn("rollup_version").notNull(), + rootHeight: bigint("root_height", { mode: "bigint" }).notNull(), + rootHash: varchar("root_hash").notNull().$type(), + removedCount: integer("removed_count").notNull(), + observedAt: timestamp("observed_at").notNull(), + revivedAt: timestamp("revived_at"), + }, + (t) => ({ + networkObservedIdx: index("l2_reorg_network_observed_idx").on( + t.l2NetworkId, + t.observedAt.desc(), + ), + }), +); + +export const l2ReorgBlockTable = pgTable( + "l2_reorg_block", + { + reorgId: bigint("reorg_id", { mode: "number" }) + .notNull() + .references(() => l2ReorgTable.id, { onDelete: "cascade" }), + height: bigint("height", { mode: "bigint" }).notNull(), + hash: varchar("hash").notNull().$type(), + }, + (t) => ({ + pk: primaryKey({ + name: "l2_reorg_block_pkey", + columns: [t.reorgId, t.hash], + }), + hashIdx: index("l2_reorg_block_hash_idx").on(t.hash), + }), +); diff --git a/services/explorer-api/src/svcs/database/schema/l2/tips.ts b/services/explorer-api/src/svcs/database/schema/l2/tips.ts index d0f041d2..3d9254a7 100644 --- a/services/explorer-api/src/svcs/database/schema/l2/tips.ts +++ b/services/explorer-api/src/svcs/database/schema/l2/tips.ts @@ -1,6 +1,15 @@ import { ChicmozL2Tips, HexString, L2NetworkId } from "@chicmoz-pkg/types"; -import { bigint, integer, pgTable, timestamp, uniqueIndex, varchar } from "drizzle-orm/pg-core"; -import { l2NetworkIdDbEnum } from "../utils.js"; +import { sql } from "drizzle-orm"; +import { + bigint, + index, + integer, + pgTable, + timestamp, + uniqueIndex, + varchar, +} from "drizzle-orm/pg-core"; +import { generateBoundedIntegerColumn, l2NetworkIdDbEnum } from "../utils.js"; const blockNumber = (name: string) => bigint(name, { mode: "number" }); @@ -63,6 +72,7 @@ export const l2TipBoundaryMismatchTable = pgTable( lastSeenAt: timestamp("last_seen_at").notNull().defaultNow(), occurrenceCount: integer("occurrence_count").notNull().default(1), resolvedAt: timestamp("resolved_at"), + rollupVersion: generateBoundedIntegerColumn("rollup_version"), }, (table) => ({ l2TipBoundaryMismatchKey: uniqueIndex("l2_tip_boundary_mismatch_key").on( @@ -72,6 +82,9 @@ export const l2TipBoundaryMismatchTable = pgTable( table.expectedHash, table.observedDbHash, ), + unresolvedIdx: index("l2_tip_boundary_mismatch_unresolved_idx") + .on(table.l2NetworkId, table.height) + .where(sql`${table.resolvedAt} IS NULL`), }), ); diff --git a/services/explorer-api/src/svcs/database/schema/l2block/header.ts b/services/explorer-api/src/svcs/database/schema/l2block/header.ts index 6eefb193..3dac1cda 100644 --- a/services/explorer-api/src/svcs/database/schema/l2block/header.ts +++ b/services/explorer-api/src/svcs/database/schema/l2block/header.ts @@ -35,6 +35,7 @@ export const lastArchive = generateTreeTable( .notNull() .references(() => header.id, { onDelete: "cascade" }), "last_archive_header_id_idx", + "last_archive_root_idx", ); export const state = pgTable( diff --git a/services/explorer-api/src/svcs/database/schema/l2block/root.ts b/services/explorer-api/src/svcs/database/schema/l2block/root.ts index 53754ae3..a7faea19 100644 --- a/services/explorer-api/src/svcs/database/schema/l2block/root.ts +++ b/services/explorer-api/src/svcs/database/schema/l2block/root.ts @@ -40,4 +40,5 @@ export const archive = generateTreeTable( .notNull() .references(() => l2Block.hash, { onDelete: "cascade" }), "archive_block_hash_idx", + "archive_root_idx", ); diff --git a/services/explorer-api/src/svcs/database/schema/utils.ts b/services/explorer-api/src/svcs/database/schema/utils.ts index 874f7386..a5007db7 100644 --- a/services/explorer-api/src/svcs/database/schema/utils.ts +++ b/services/explorer-api/src/svcs/database/schema/utils.ts @@ -39,6 +39,7 @@ export const generateTreeTable = ( object >, indexName?: string, + rootIndexName?: string, ) => pgTable( name, @@ -52,6 +53,9 @@ export const generateTreeTable = ( ...(indexName ? { fkIdx: index(indexName).on(table.fk) } : {}), + ...(rootIndexName + ? { rootIdx: index(rootIndexName).on(table.root) } + : {}), }), ); From 77d6c70c27bf3a3d6be48a7b71aa1a9812fbbcc1 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Thu, 26 Nov 2026 21:23:05 +0000 Subject: [PATCH 02/31] test(explorer-api): give built blocks their own archives and a parent link Every built block shared one archive and one last archive, so no two built blocks linked. As in 6fd18994, each now gets an archive of its own (or a given one), and `parent` makes its last archive the parent's archive. `buildChain` builds linked runs, and `orderedEvent` and `catchupEvent` build the two block messages. Co-Authored-By: Claude Opus 5.5 --- .../tests/integration/support/blocks.ts | 74 ++++++++++++++++++- 1 file changed, 70 insertions(+), 4 deletions(-) diff --git a/services/explorer-api/tests/integration/support/blocks.ts b/services/explorer-api/tests/integration/support/blocks.ts index ef2da52d..532ba91d 100644 --- a/services/explorer-api/tests/integration/support/blocks.ts +++ b/services/explorer-api/tests/integration/support/blocks.ts @@ -2,12 +2,17 @@ import { BlockNumber } from "@aztec-labs/foundation/branded-types"; import { Fr } from "@aztec-labs/foundation/curves/bn254"; import { EthAddress } from "@aztec-labs/foundation/eth-address"; import { Body, L2Block } from "@aztec-labs/stdlib/block"; +import { AppendOnlyTreeSnapshot } from "@aztec-labs/stdlib/trees"; import { BlockHeader, GlobalVariables, TxEffect, TxHash, } from "@aztec-labs/stdlib/tx"; +import { + type CatchupBlockEvent, + type NewBlockEvent, +} from "@chicmoz-pkg/message-registry"; import { type HexString } from "@chicmoz-pkg/types"; import { listFixtures, loadFixture } from "@chicmoz/test-harness"; @@ -16,6 +21,7 @@ export type BuiltBlock = { hash: HexString; height: bigint; txHashes: HexString[]; + archive: AppendOnlyTreeSnapshot; }; // A recorded effect with public logs and no contract-class logs, so storing a @@ -40,12 +46,22 @@ let base: L2Block | undefined; /** * The coinbase is salted to tell headers at one height apart. The handler * does not recompute the body's commitments, so cloned effects are accepted. - * `version` replaces the recorded rollup version. + * `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. */ export const buildBlock = async ( height: bigint, txHashes: HexString[], - { version }: { version?: number } = {}, + { + version, + parent, + archive: sharedArchive, + }: { + version?: number; + parent?: Pick; + archive?: AppendOnlyTreeSnapshot; + } = {}, ): Promise => { base ??= baseBlock(); const [effect] = base.body.txEffects; @@ -58,9 +74,16 @@ export const buildBlock = async ( coinbase: EthAddress.random(), ...(version === undefined ? {} : { version: new Fr(version) }), }); + const archive = + sharedArchive ?? + new AppendOnlyTreeSnapshot(Fr.random(), base.archive.nextAvailableLeafIndex); const block = new L2Block( - base.archive, - BlockHeader.from({ ...base.header, globalVariables: globals }), + archive, + BlockHeader.from({ + ...base.header, + ...(parent ? { lastArchive: parent.archive } : {}), + globalVariables: globals, + }), new Body( txHashes.map((h) => TxEffect.from({ ...effect, txHash: TxHash.fromString(h) })), ), @@ -74,6 +97,7 @@ export const buildBlock = async ( hash: (await decoded.hash()).toString(), height: BigInt(decoded.number), txHashes: decoded.body.txEffects.map((t) => t.txHash.toString()), + archive: decoded.archive, }; if (built.height !== height || built.txHashes.join() !== txHashes.join()) { throw new Error(`built block does not round-trip: height ${built.height}, txs ${built.txHashes.join()}`); @@ -82,3 +106,45 @@ export const buildBlock = async ( }; export const freshTxHash = (): HexString => TxHash.random().toString(); + +/** `count` linked blocks from `from` up, one fresh tx each; the first links to `parent`. */ +export const buildChain = async ( + from: bigint, + count: number, + { + version, + parent, + }: { version?: number; parent?: Pick } = {}, +): Promise => { + const chain: BuiltBlock[] = []; + for (let i = 0; i < count; i++) { + chain.push( + await buildBlock(from + BigInt(i), [freshTxHash()], { + version, + parent: chain[i - 1] ?? parent, + }), + ); + } + return chain; +}; + +/** As the hash-following listener sends it: `tip` defaults to the block's own height. */ +export const orderedEvent = ( + b: BuiltBlock, + tip = Number(b.height), +): NewBlockEvent => ({ + block: b.hex, + blockNumber: Number(b.height), + statusHint: "proposed", + ordered: { tip }, +}); + +export const catchupEvent = ( + b: BuiltBlock, + { final }: { final?: true } = {}, +): CatchupBlockEvent => ({ + block: b.hex, + blockNumber: Number(b.height), + statusHint: "proposed", + ...(final ? { final } : {}), +}); From 4d0647c75bc657fdd3f4a629cbb625aab43cdcbf Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Thu, 26 Nov 2026 21:23:41 +0000 Subject: [PATCH 03/31] feat(explorer-api): decide the canonical chain from ordered blocks A block from the ordered stream carries its pass's tip and is canonical at its height. It demotes the block it replaces with that block's linked descendants, and any canonical holder of its txs above it with theirs; it brings back its stored ancestors, demoting their competitors and clearing the height of a missing parent; and it demotes every canonical block above the tip. Catch-up blocks only fill empty heights: when the canonical chain above descends from them, or, when final, on the canonical parent below. They never demote. Block events without `ordered` are ignored. Each change runs in one transaction under a per-network advisory lock with a 10 s lock timeout, and the block's rows, tx effects and contracts are written inside it. Walks stop after 10,000 steps and heartbeat every 500; more than 10,000 canonical blocks above a tip throws. A tx effect held by an off-chain block moves to the canonical one, and off-chain blocks are kept, not deleted. Each demotion writes one `l2_reorg` record, marked revived once all its blocks are canonical again, and `/l2/reorgs` is computed from the records. A block made canonical without its own message gets a `reorg_repair` gap row, requested until its message attaches its txs. The height-based reorg handler, orphaning and block deletion are gone, with their unit tests. Co-Authored-By: Claude Opus 5.5 --- .../src/events/received/on-block/contracts.ts | 75 +- .../src/events/received/on-block/index.ts | 270 ++---- .../events/received/on-block/reorg-handler.ts | 47 - .../explorer-api/src/events/received/utils.ts | 68 +- .../l2Tx/remove-pending-and-dropped.ts | 82 +- .../database/controllers/l2block/canonical.ts | 815 ++++++++++++++++++ .../database/controllers/l2block/delete.ts | 61 -- .../database/controllers/l2block/get-block.ts | 98 +-- .../controllers/l2block/missing-ranges.ts | 22 +- .../database/controllers/l2block/orphan.ts | 216 ----- .../database/controllers/l2block/store.ts | 299 ++++--- .../database/controllers/l2contract/store.ts | 61 +- .../src/svcs/database/controllers/utils.ts | 5 + .../block-ingest.integration.test.ts | 4 +- .../block-reorg.integration.test.ts | 122 ++- ...rollup-version-scoping.integration.test.ts | 37 +- .../tests/integration/support/chain.ts | 148 ++++ .../integration/support/recorded-blocks.ts | 15 +- .../tests/unit/block-tx-conflict.test.ts | 283 ------ .../tests/unit/duplicate-block-error.test.ts | 107 --- 20 files changed, 1449 insertions(+), 1386 deletions(-) delete mode 100644 services/explorer-api/src/events/received/on-block/reorg-handler.ts create mode 100644 services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts delete mode 100644 services/explorer-api/src/svcs/database/controllers/l2block/delete.ts delete mode 100644 services/explorer-api/src/svcs/database/controllers/l2block/orphan.ts create mode 100644 services/explorer-api/tests/integration/support/chain.ts delete mode 100644 services/explorer-api/tests/unit/block-tx-conflict.test.ts delete mode 100644 services/explorer-api/tests/unit/duplicate-block-error.test.ts diff --git a/services/explorer-api/src/events/received/on-block/contracts.ts b/services/explorer-api/src/events/received/on-block/contracts.ts index 5498b534..6a487db5 100644 --- a/services/explorer-api/src/events/received/on-block/contracts.ts +++ b/services/explorer-api/src/events/received/on-block/contracts.ts @@ -11,13 +11,10 @@ import { chicmozL2ContractInstanceUpdatedEventSchema, type ChicmozL2ContractClassRegisteredEvent, type ChicmozL2ContractInstanceDeployedEvent, - type ChicmozL2PrivateFunctionBroadcastedEvent, - type ChicmozL2UtilityFunctionBroadcastedEvent, } from "@chicmoz-pkg/types"; import { z } from "zod"; import { logger } from "../../../logger.js"; -import { controllers } from "../../../svcs/database/index.js"; -import { handleDuplicateError } from "../utils.js"; +import { type BlockContracts } from "../../../svcs/database/controllers/l2contract/store.js"; const AZTEC_CONTRACT_CLASS_VERSION = 1; @@ -45,22 +42,11 @@ const parseObjs = ( return parsedObjs; }; -const storeObj = async ( - objs: T[], - storeFn: (obj: T) => Promise, - objType: string, - objId: keyof T, -) => { - for (const obj of objs) { - await storeFn(obj).catch((e) => { - const duplicateErrorId = obj[objId] as string; - handleDuplicateError(e as Error, `${objType} ${duplicateErrorId}`); - }); - } -}; - // NOTE: reference for parsing in aztec-packages: yarn-project/archiver/src/archiver/archiver.ts -export const storeContracts = async (b: L2Block, blockHash: string) => { +export const parseBlockContracts = async ( + b: L2Block, + blockHash: string, +): Promise => { const privateLogs = b.body.txEffects.flatMap( (txEffect) => txEffect.privateLogs, ); @@ -99,9 +85,6 @@ export const storeContracts = async (b: L2Block, blockHash: string) => { contractClassRegisteredEvents.map((e) => e.toContractClassPublic()), ); - const privateFnEvents: unknown[] = []; - const utilityFnEvents: unknown[] = []; - if (contractClasses.length > 0) { logger.info( `๐Ÿ“œ Parsing and storing ${contractClasses.length} contract classes`, @@ -117,16 +100,6 @@ export const storeContracts = async (b: L2Block, blockHash: string) => { `โฌ†๏ธ Parsing and storing ${contractInstanceUpdated.length} contract instances updated`, ); } - if (privateFnEvents.length > 0) { - logger.info( - `๐Ÿ”’ Parsing and storing ${privateFnEvents.length} private function events`, - ); - } - if (utilityFnEvents.length > 0) { - logger.info( - `๐Ÿ’ช Parsing and storing ${utilityFnEvents.length} utility function events`, - ); - } const contractClassesWithId = contractClasses.map((contractClass) => { return { @@ -189,37 +162,9 @@ export const storeContracts = async (b: L2Block, blockHash: string) => { newContractClassId: contractInstance.newContractClassId.toString(), } as ChicmozL2ContractInstanceUpdatedEvent), ); - const parsedPrivateFnEvents: ChicmozL2PrivateFunctionBroadcastedEvent[] = []; - const parsedUtilityFnEvents: ChicmozL2UtilityFunctionBroadcastedEvent[] = []; - - await storeObj( - parsedContractClasses, - controllers.l2Contract.storeContractClass, - "contractClass", - "contractClassId", - ); - await storeObj( - parsedContractInstancesDeployed, - controllers.l2Contract.storeContractInstanceDeployed, - "contractInstanceDeployed", - "address", - ); - await storeObj( - parsedContractInstanceUpdate, - controllers.l2Contract.storeContractInstanceUpdated, - "contractInstanceUpdated", - "address", - ); - await storeObj( - parsedPrivateFnEvents, - controllers.l2Contract.storePrivateFunction, - "privateFunction", - "artifactMetadataHash", - ); - await storeObj( - parsedUtilityFnEvents, - controllers.l2Contract.storeUtilityFunction, - "utilityFunction", - "artifactMetadataHash", - ); + return { + classes: parsedContractClasses, + instancesDeployed: parsedContractInstancesDeployed, + instancesUpdated: parsedContractInstanceUpdate, + }; }; 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 8673b474..46fa67d0 100644 --- a/services/explorer-api/src/events/received/on-block/index.ts +++ b/services/explorer-api/src/events/received/on-block/index.ts @@ -1,260 +1,105 @@ import { blockFromBuffer, parseBlock } from "@chicmoz-pkg/backend-utils"; -import { type EventHandler } from "@chicmoz-pkg/message-bus"; +import { type EventHandler, type Heartbeat } from "@chicmoz-pkg/message-bus"; import { generateL2TopicName, getConsumerGroupId, + type CatchupBlockEvent, type NewBlockEvent, } from "@chicmoz-pkg/message-registry"; -import { - chicmozChainInfoSchema, - type ChicmozL2Block, - type ChicmozL2TxEffect, -} from "@chicmoz-pkg/types"; +import { chicmozChainInfoSchema } from "@chicmoz-pkg/types"; +import { z } from "zod"; import { SERVICE_NAME } from "../../../constants.js"; import { L2_NETWORK_ID } from "../../../environment.js"; import { logger } from "../../../logger.js"; import { observeRollupVersion } from "../../../svcs/database/controllers/l2/chain-info/rollup-version-cache.js"; import { - deleteL2BlockByHash, - deleteL2BlockByHeight, - getTxEffectOwners, - type TxEffectOwner, -} from "../../../svcs/database/controllers/l2block/delete.js"; -import { unOrphanBlock } from "../../../svcs/database/controllers/l2block/orphan.js"; + applyCatchupBlock, + applyOrderedBlock, + type ChainOutcome, + type IncomingBlock, +} from "../../../svcs/database/controllers/l2block/canonical.js"; import { controllers } from "../../../svcs/database/index.js"; -import { handleDuplicateBlockError, type PartialDbError } from "../utils.js"; -import { storeContracts } from "./contracts.js"; -import { detectReorg, handleReorg } from "./reorg-handler.js"; -import { type L2Block } from "@aztec-labs/aztec.js/block"; - -const truncateString = (value: string) => { - const startHash = value.substring(0, 100); - const endHash = value.substring(value.length - 100, value.length); - return `${startHash}...${endHash}`; -}; +import { parseBlockContracts } from "./contracts.js"; -// eslint-disable-next-line @typescript-eslint/no-unused-vars -const hackyLogBlock = (b: L2Block) => { - const blockString = JSON.stringify(b, null, 2); - const logString = blockString - .split(":") - .map((v) => { - if (v.length > 200 && v.includes(",")) { - return truncateString(v); - } - - return v; - }) - .join(":"); - logger.error(`๐Ÿšซ Block: ${logString}`); - b.body.txEffects.forEach((txEffect) => { - txEffect.privateLogs.forEach((log) => { - log.toFields().forEach((field) => { - logger.error(`๐Ÿšซ TxEffect: ${field.toString()}`); - }); - }); - }); -}; +const orderedSchema = z.object({ tip: z.number().int().nonnegative() }); -const onBlock = async ({ +const decode = async ({ block, blockNumber, -}: NewBlockEvent) => { +}: NewBlockEvent | CatchupBlockEvent): Promise => { if (!block) { logger.error("๐Ÿšซ Block is empty"); - return; + return undefined; } logger.info(`๐Ÿ‘“ Parsing block ${blockNumber}`); const b = blockFromBuffer(block); - let parsedBlock; + let parsed; try { - parsedBlock = await parseBlock(b); + parsed = await parseBlock(b); } catch (e) { logger.error( // eslint-disable-next-line @typescript-eslint/restrict-template-expressions `Failed to parse block ${blockNumber}: ${(e as Error)?.stack ?? e}`, ); - return; + return undefined; } + return { block: parsed, contracts: await parseBlockContracts(b, parsed.hash) }; +}; - const stored = await storeBlock(parsedBlock); - if (!stored) { +const afterCommit = async ( + { block }: IncomingBlock, + { canonical }: ChainOutcome, +) => { + if (!canonical) { return; } - await controllers.l2Block.markOpenGapsFulfilledByHeight(parsedBlock.height); + await controllers.l2Block.markOpenGapsFulfilledByHeight(block.height); await observeRollupVersion({ l2NetworkId: L2_NETWORK_ID, rollupVersion: chicmozChainInfoSchema.shape.rollupVersion.parse( - parsedBlock.header.globalVariables.version, + block.header.globalVariables.version, ), source: "block", }); - await storeContracts(b, parsedBlock.hash); - await pendingTxsHook(parsedBlock.body.txEffects); }; -/** - * @returns false when the block was skipped (see - * pruneConflictingOrphanedTxOwners); true when it is stored. - */ -const storeBlock = async ( - parsedBlock: ChicmozL2Block, - haveRetried = false, -): Promise => { - logger.info( - `๐Ÿงข Storing block ${parsedBlock.height} (hash: ${parsedBlock.hash})`, - ); - - const reorgDetected = await detectReorg(parsedBlock); - - // Decided before handleReorg writes anything, so a skip changes nothing. - const blockingOwners = await findBlockingTxOwners(parsedBlock, reorgDetected); - if (blockingOwners.length > 0) { - logSkippedTxConflict(parsedBlock, blockingOwners); - return false; - } - - if (reorgDetected) { - await handleReorg(parsedBlock); +// Only the hash-following listener marks its blocks ordered. An unordered +// block carries no chain authority, and storing it could build runs of +// unlinked blocks that a later walk would have to cross. +const onBlock = async (event: NewBlockEvent, heartbeat: Heartbeat) => { + if (event.ordered === undefined) { + logger.warn(`Ignoring block ${event.blockNumber}: not from the ordered stream`); + return; } - - // Set orphan fields to null/false for the new block - parsedBlock.orphan = undefined; - - // Store the new block - try { - await controllers.l2Block.store(parsedBlock); - return true; - } catch (e) { - if (haveRetried) { - throw new Error( - // eslint-disable-next-line @typescript-eslint/restrict-template-expressions - `Failed to store block ${parsedBlock.height} after retry: ${e}`, - ); - } - // Only duplicates are resolved below. Anything else propagates, so the - // message bus redelivers the block instead of it being lost. - if ((e as PartialDbError).code !== "23505") { - throw e; - } - - // If we still get an error, we'll try the old approach as fallback - const outcome = await handleDuplicateBlockError( - e as Error, - `block ${parsedBlock.height}`, - async () => { - logger.warn( - `Deleting block ${parsedBlock.height} (hash: ${parsedBlock.hash})`, - ); - await deleteL2BlockByHeight(parsedBlock.height); - }, - async () => { - // The block hash already exists but is orphaned โ€” un-orphan it - // since the node is serving it as the canonical block. - await unOrphanBlock(parsedBlock.hash); - }, - async () => pruneConflictingOrphanedTxOwners(parsedBlock), + const ordered = orderedSchema.safeParse(event.ordered); + if (!ordered.success) { + logger.error( + `Ignoring block ${event.blockNumber}: invalid ordered field ${JSON.stringify(event.ordered)}`, ); - - if (outcome === "retry") { - return storeBlock(parsedBlock, true); - } - return outcome === "done"; + return; } -}; - -const ownerSummary = (owners: TxEffectOwner[]) => - owners - .map( - (owner) => - `${owner.txHash} in active block ${owner.blockHeight} (${owner.blockHash})`, - ) - .join(", "); - -const logSkippedTxConflict = ( - parsedBlock: ChicmozL2Block, - activeOwners: TxEffectOwner[], -) => { - logger.error( - `SKIPPED_BLOCK_TX_CONFLICT height=${parsedBlock.height} hash=${parsedBlock.hash} owners=${ownerSummary(activeOwners)}`, + const incoming = await decode(event); + if (!incoming) { + return; + } + await afterCommit( + incoming, + await applyOrderedBlock(incoming, ordered.data.tip, heartbeat), ); }; -/** - * Active blocks holding the block's txs that its own reorg would leave - * active. handleReorg orphans the active block at the block's height and - * the blocks above it; an active holder elsewhere (below the height, on - * another rollup version, or anywhere when there is no reorg) means the - * block is skipped, as deciding which of the two is canonical is out of - * scope here. - */ -const findBlockingTxOwners = async ( - parsedBlock: ChicmozL2Block, - reorgDetected: boolean, +const onCatchupBlock = async ( + event: CatchupBlockEvent, + heartbeat: Heartbeat, ) => { - const owners = await getTxEffectOwners( - parsedBlock.body.txEffects.map((txEffect) => txEffect.txHash), - ); - const rollupVersion = parsedBlock.header.globalVariables.version; - return owners.filter( - (owner) => - !owner.isOrphaned && - owner.blockHash !== parsedBlock.hash && - !( - reorgDetected && - owner.rollupVersion === rollupVersion && - owner.blockHeight >= parsedBlock.height - ), - ); -}; - -/** - * Frees the block's txs from orphaned blocks still holding them, so the - * retry can store it (the multi-block reorg case). - * - * @returns false when an ACTIVE block holds one of its txs. The block is - * then skipped (the message is acked, not redelivered forever as before, - * which wedged mainnet for ~23h) and logged as SKIPPED_BLOCK_TX_CONFLICT; - * its height stays empty until something stores it. - */ -const pruneConflictingOrphanedTxOwners = async ( - parsedBlock: ChicmozL2Block, -): Promise => { - const incomingTxHashes = parsedBlock.body.txEffects.map( - (txEffect) => txEffect.txHash, - ); - const owners = await getTxEffectOwners(incomingTxHashes); - - if (owners.length === 0) { - logger.error( - `Duplicate tx_hash while storing block ${parsedBlock.height}, but no existing tx owner was found`, - ); - throw new Error( - `Duplicate tx_hash while storing block ${parsedBlock.height}, but no existing tx owner was found`, - ); - } - - // Normally caught up front by findBlockingTxOwners; checked again in case - // a holder became active in between. - const activeOwners = owners.filter((owner) => !owner.isOrphaned); - if (activeOwners.length > 0) { - logSkippedTxConflict(parsedBlock, activeOwners); - return false; + const incoming = await decode(event); + if (!incoming) { + return; } - - const orphanedOwnerHashes = [...new Set(owners.map((owner) => owner.blockHash))]; - logger.warn( - `Pruning ${orphanedOwnerHashes.length} orphaned tx owner block(s) before retrying block ${parsedBlock.height}: ${orphanedOwnerHashes.join(", ")}`, + await afterCommit( + incoming, + await applyCatchupBlock(incoming, event.final === true, heartbeat), ); - - for (const blockHash of orphanedOwnerHashes) { - await deleteL2BlockByHash(blockHash); - } - return true; -}; - -const pendingTxsHook = async (txEffects: ChicmozL2TxEffect[]) => { - await controllers.l2Tx.removePendingAndDroppedTx(txEffects); }; export const blockHandler: EventHandler = { @@ -264,7 +109,7 @@ export const blockHandler: EventHandler = { handlerName: "blockHandler", }), topic: generateL2TopicName(L2_NETWORK_ID, "NEW_BLOCK_EVENT"), - cb: onBlock as (arg0: unknown) => Promise, + cb: onBlock as (arg0: unknown, heartbeat: Heartbeat) => Promise, }; export const catchupHandler: EventHandler = { @@ -274,8 +119,5 @@ export const catchupHandler: EventHandler = { handlerName: "catchupHandler", }), topic: generateL2TopicName(L2_NETWORK_ID, "CATCHUP_BLOCK_EVENT"), - cb: ((event: NewBlockEvent) => { - logger.info(`Catchup block event`); - return onBlock(event); - }) as (arg0: unknown) => Promise, + cb: onCatchupBlock as (arg0: unknown, heartbeat: Heartbeat) => Promise, }; diff --git a/services/explorer-api/src/events/received/on-block/reorg-handler.ts b/services/explorer-api/src/events/received/on-block/reorg-handler.ts deleted file mode 100644 index 0866a7bc..00000000 --- a/services/explorer-api/src/events/received/on-block/reorg-handler.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { ChicmozL2Block } from "@chicmoz-pkg/types"; -import { logger } from "../../../logger.js"; -import { getBlock } from "../../../svcs/database/controllers/l2block/get-block.js"; -import { handleReorgOrphaning } from "../../../svcs/database/controllers/l2block/orphan.js"; - -/** - * Detects if there's a re-org at the given block height - */ -export const detectReorg = async ( - parsedBlock: ChicmozL2Block, -): Promise => { - // Check if a block with the same height but different hash already exists - const existingBlock = await getBlock(parsedBlock.height, { - rollupVersion: parsedBlock.header.globalVariables.version, - }); - return !!(existingBlock && existingBlock.hash !== parsedBlock.hash); -}; - -/** - * Handles a re-org by marking the existing block and higher blocks of the - * parsed block's rollup version as orphaned and storing their transactions - * as dropped - */ -export const handleReorg = async ( - parsedBlock: ChicmozL2Block, -): Promise => { - const rollupVersion = parsedBlock.header.globalVariables.version; - const existingBlock = await getBlock(parsedBlock.height, { rollupVersion }); - - if (!existingBlock) { - return; - } - - logger.warn( - `Re-org detected at height ${parsedBlock.height}. Existing hash: ${existingBlock.hash}, new hash: ${parsedBlock.hash}`, - ); - - // Handle the orphaning in a database transaction - const totalOrphaned = await handleReorgOrphaning( - existingBlock.hash, - parsedBlock.height, - rollupVersion, - ); - logger.warn( - `Completed re-org handling at height ${parsedBlock.height}. Total orphaned blocks: ${totalOrphaned}`, - ); -}; diff --git a/services/explorer-api/src/events/received/utils.ts b/services/explorer-api/src/events/received/utils.ts index b1e8f02c..9091b45f 100644 --- a/services/explorer-api/src/events/received/utils.ts +++ b/services/explorer-api/src/events/received/utils.ts @@ -1,76 +1,10 @@ import { logger } from "../../logger.js"; -export type PartialDbError = { +type PartialDbError = { code: string; detail: string; }; -/** - * What storing a block should do after a duplicate-key error: - * - "retry": the conflict was cleared; store the block again. - * - "done": the block is already stored (un-orphaned if needed). - * - "skip": the block is not stored; skip it and its hooks. - */ -export type DuplicateBlockOutcome = "retry" | "done" | "skip"; - -export const handleDuplicateBlockError = async ( - e: Error | PartialDbError, - additionalInfo: string, - deleteBlockCallback: () => Promise, - unOrphanCallback?: () => Promise, - // Resolves false when the conflict cannot be cleared and the block is skipped. - resolveDuplicateTxHashCallback?: () => Promise, -): Promise => { - if ((e as PartialDbError).code === "23505") { - const detail = (e as PartialDbError).detail; - if (detail.includes("(hash)")) { - // Block with exact same hash already exists. - // If the existing block is orphaned, un-orphan it instead of skipping. - if (unOrphanCallback) { - logger.info( - `DB duplicate hash for "${additionalInfo}": attempting to un-orphan existing block. [${detail}]`, - ); - await unOrphanCallback(); - } else { - logger.warn( - `DB duplicate for "${additionalInfo}" skipping... [${detail}]`, - ); - } - return "done"; - } else if (detail.includes("(tx_hash)")) { - // tx_hash duplicate: a transaction from this block already exists. Prefer - // resolving the actual owning block over deleting the incoming height. - if (resolveDuplicateTxHashCallback) { - logger.warn( - `DB duplicate tx_hash for "${additionalInfo}": resolving tx owner and retrying. [${detail}]`, - ); - return (await resolveDuplicateTxHashCallback()) ? "retry" : "skip"; - } - - logger.warn( - `DB duplicate tx_hash for "${additionalInfo}": deleting block at height and retrying. [${detail}]`, - ); - await deleteBlockCallback(); - return "retry"; - } else if (detail.includes("(height)")) { - // height duplicate: same as before. - logger.warn( - `DB duplicate for "${additionalInfo}": deleting block at height and retrying. [${detail}]`, - ); - await deleteBlockCallback(); - return "retry"; - } - // A key this handler does not know: the block was not stored, and - // counting it as stored would run its hooks and fulfil its gap. - logger.error( - `DB duplicate on an unexpected key for "${additionalInfo}": not stored, skipping. [${detail}]`, - ); - return "skip"; - } - handleOtherError(e as Error, additionalInfo); - return "skip"; -}; - export const handleDuplicateError = ( e: Error | PartialDbError, additionalInfo: string, diff --git a/services/explorer-api/src/svcs/database/controllers/l2Tx/remove-pending-and-dropped.ts b/services/explorer-api/src/svcs/database/controllers/l2Tx/remove-pending-and-dropped.ts index 2f8f3a32..24313b95 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2Tx/remove-pending-and-dropped.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2Tx/remove-pending-and-dropped.ts @@ -1,46 +1,48 @@ -import { getDb as db } from "@chicmoz-pkg/postgres-helper"; -import { type ChicmozL2TxEffect } from "@chicmoz-pkg/types"; -import { eq } from "drizzle-orm"; +import { type HexString } from "@chicmoz-pkg/types"; +import { eq, inArray } from "drizzle-orm"; import { logger } from "../../../../logger.js"; -import { l2Tx } from "../../../database/schema/l2tx/index.js"; +import { droppedTx } from "../../../database/schema/dropped-tx/index.js"; import { txEffect } from "../../../database/schema/l2block/body.js"; -import { removeDroppedTxByHash } from "../../controllers/dropped-tx/remove.js"; +import { l2Tx } from "../../../database/schema/l2tx/index.js"; +import { type DbTx } from "../utils.js"; +/** + * For txs now mined on the canonical chain: deletes their pending rows, + * copying each pending tx's fee and identity fields onto its tx effect, and + * their dropped rows, whether or not a pending row existed. + */ export const removePendingAndDroppedTx = async ( - txEffects: ChicmozL2TxEffect[], + dbTx: DbTx, + txHashes: HexString[], ): Promise => { - return await db().transaction(async (dbTx) => { - for (const txEffectRow of Object.values(txEffects)) { - const deleted = await dbTx - .delete(l2Tx) - .where(eq(l2Tx.txHash, txEffectRow.txHash)) - .returning(); - - if (!deleted || deleted.length === 0) { - continue; - } - - logger.info(`๐Ÿ•๐Ÿ”ฅ deleted pending tx ${txEffectRow.txHash}`); - - const pendingTx = deleted[0]; - - // Copy fee/identity fields from the deleted pending tx onto the mined tx effect row. - await dbTx - .update(txEffect) - .set({ - feePayer: pendingTx.feePayer ?? null, - feePaymentMethod: pendingTx.feePaymentMethod ?? null, - initiator: pendingTx.initiator ?? null, - }) - .where(eq(txEffect.txHash, txEffectRow.txHash)); - - try { - await removeDroppedTxByHash(txEffectRow.txHash); - } catch (e) { - logger.error( - `Error removing dropped tx ${txEffectRow.txHash}: ${(e as Error).stack}`, - ); - } - } - }); + if (txHashes.length === 0) { + return; + } + const pending = await dbTx + .delete(l2Tx) + .where(inArray(l2Tx.txHash, txHashes)) + .returning({ + txHash: l2Tx.txHash, + feePayer: l2Tx.feePayer, + feePaymentMethod: l2Tx.feePaymentMethod, + initiator: l2Tx.initiator, + }); + for (const pendingTx of pending) { + logger.info(`๐Ÿ•๐Ÿ”ฅ deleted pending tx ${pendingTx.txHash}`); + await dbTx + .update(txEffect) + .set({ + feePayer: pendingTx.feePayer ?? null, + feePaymentMethod: pendingTx.feePaymentMethod ?? null, + initiator: pendingTx.initiator ?? null, + }) + .where(eq(txEffect.txHash, pendingTx.txHash)); + } + const dropped = await dbTx + .delete(droppedTx) + .where(inArray(droppedTx.txHash, txHashes)) + .returning({ txHash: droppedTx.txHash }); + for (const { txHash } of dropped) { + logger.info(`๐Ÿ—‘๏ธ๐Ÿ”ฅ removed dropped tx ${txHash}`); + } }; diff --git a/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts b/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts new file mode 100644 index 00000000..805d3554 --- /dev/null +++ b/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts @@ -0,0 +1,815 @@ +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"; +import { L2_NETWORK_ID } from "../../../../environment.js"; +import { logger } from "../../../../logger.js"; +import { droppedTx } from "../../schema/dropped-tx/index.js"; +import { l2ReorgBlockTable, l2ReorgTable } from "../../schema/l2/reorg.js"; +import { + archive, + body, + header, + l2Block, + lastArchive, + txEffect, +} from "../../schema/l2block/index.js"; +import { + storeBlockContracts, + type BlockContracts, +} from "../l2contract/store.js"; +import { removePendingAndDroppedTx } from "../l2Tx/remove-pending-and-dropped.js"; +import { type DbTx } from "../utils.js"; +import { recordRepairHeights } from "./missing-ranges.js"; +import { store, writeTxEffect } from "./store.js"; + +// Every change to which blocks are canonical goes through this module. +// +// Invariant: once a listener pass is applied, the canonical blocks of each +// rollup version (orphan_timestamp IS NULL) hold at most one block per +// height, any two at adjacent heights are linked, and none sits above the +// pass's tip. Linked: child.last_archive.root = parent.archive.root, one +// height apart, same version. The child's hash covers its last archive; the +// parent's archive root is outside the parent's hash, so two stored parents +// make a lookup ambiguous. +// +// Ordered blocks are the listener's chain, sent in order: each is canonical +// at its height and nothing canonical stays above its tip. Catch-up blocks +// only fill empty heights and never demote anything. + +/** 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: + * every chain mutation, and every write that depends on one, serializes on + * it. A lock 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; +}; + +/** `canonical`: the block ends on the chain, its txs attached from its message. */ +export type ChainOutcome = { canonical: boolean }; + +type ChainBlock = { + hash: HexString; + height: bigint; + version: number; + canonical: boolean; + archiveRoot: string | null; + lastArchiveRoot: string | null; +}; + +type StoredBlock = ChainBlock & { bodyId: string }; + +type Change = { + dbTx: DbTx; + version: number; + now: number; + heartbeat: Heartbeat; + steps: number; + demoted: Map; + promoted: Map; + // Made canonical without their own message: their moved txs need it back. + walked: Map; + repairs: Set; +}; + +type TxOwner = { + txHash: HexString; + blockHash: HexString; + height: bigint; + canonical: boolean; +}; + +class TxConflict extends Error { + constructor( + readonly block: ChicmozL2Block, + readonly owners: TxOwner[], + ) { + super(`block ${block.height} shares txs with canonical blocks`); + } +} + +const chunks = (items: T[]): T[][] => { + const parts: T[][] = []; + for (let i = 0; i < items.length; i += ROWS_PER_STATEMENT) { + parts.push(items.slice(i, i + ROWS_PER_STATEMENT)); + } + return parts; +}; + +const step = async (change: Change) => { + change.steps++; + if (change.steps % HEARTBEAT_EVERY === 0) { + await change.heartbeat(); + } +}; + +const chainBlocks = (dbTx: DbTx) => + dbTx + .select({ + hash: l2Block.hash, + height: l2Block.height, + version: l2Block.version, + orphanTimestamp: l2Block.orphan_timestamp, + archiveRoot: archive.root, + lastArchiveRoot: lastArchive.root, + }) + .from(l2Block) + .innerJoin(archive, eq(archive.fk, l2Block.hash)) + .innerJoin(header, eq(header.blockHash, l2Block.hash)) + .innerJoin(lastArchive, eq(lastArchive.fk, header.id)); + +const toChainBlock = ({ + orphanTimestamp, + ...row +}: { + hash: HexString; + height: bigint; + version: number; + orphanTimestamp: number | null; + archiveRoot: string | null; + lastArchiveRoot: string | null; +}): ChainBlock => ({ ...row, canonical: orphanTimestamp === null }); + +const canonicalAt = async (change: Change, height: bigint) => + ( + await chainBlocks(change.dbTx).where( + and( + eq(l2Block.version, change.version), + eq(l2Block.height, height), + isNull(l2Block.orphan_timestamp), + ), + ) + ).map(toChainBlock); + +const storedParents = async (change: Change, child: ChainBlock) => + child.lastArchiveRoot === null + ? [] + : ( + await chainBlocks(change.dbTx) + .where( + and( + eq(archive.root, child.lastArchiveRoot), + eq(l2Block.height, child.height - 1n), + eq(l2Block.version, child.version), + ), + ) + .limit(2) + ).map(toChainBlock); + +const canonicalChildren = async ( + change: Change, + parents: ChainBlock[], + height: bigint, +) => { + const roots = parents.flatMap((p) => (p.archiveRoot ? [p.archiveRoot] : [])); + if (roots.length === 0) { + return []; + } + return ( + await chainBlocks(change.dbTx).where( + and( + inArray(lastArchive.root, roots), + eq(l2Block.height, height), + eq(l2Block.version, change.version), + isNull(l2Block.orphan_timestamp), + ), + ) + ).map(toChainBlock); +}; + +const txOwners = async (dbTx: DbTx, txHashes: HexString[]) => + txHashes.length === 0 + ? [] + : ( + await dbTx + .select({ + txHash: txEffect.txHash, + blockHash: l2Block.hash, + height: l2Block.height, + orphanTimestamp: l2Block.orphan_timestamp, + }) + .from(txEffect) + .innerJoin(body, eq(txEffect.bodyId, body.id)) + .innerJoin(l2Block, eq(body.blockHash, l2Block.hash)) + .where(inArray(txEffect.txHash, txHashes)) + ).map( + ({ orphanTimestamp, ...owner }): TxOwner => ({ + ...owner, + canonical: orphanTimestamp === null, + }), + ); + +const ownedTxs = async (dbTx: DbTx, blockHashes: HexString[]) => { + const owned: { txHash: HexString; birth: number }[] = []; + for (const part of chunks(blockHashes)) { + owned.push( + ...(await dbTx + .select({ txHash: txEffect.txHash, birth: txEffect.txBirthTimestamp }) + .from(txEffect) + .innerJoin(body, eq(txEffect.bodyId, body.id)) + .where(inArray(body.blockHash, part))), + ); + } + return owned; +}; + +const demote = async (change: Change, blocks: { hash: HexString }[]) => { + const hashes = blocks + .map((b) => b.hash) + .filter((hash) => !change.demoted.has(hash)); + for (const part of chunks(hashes)) { + const rows = await change.dbTx + .update(l2Block) + .set({ orphan_timestamp: change.now, orphan_hasOrphanedParent: false }) + .where(and(inArray(l2Block.hash, part), isNull(l2Block.orphan_timestamp))) + .returning({ hash: l2Block.hash, height: l2Block.height }); + rows.forEach((row) => change.demoted.set(row.hash, row.height)); + } +}; + +const promote = async ( + change: Change, + block: ChainBlock, + { walked }: { walked: boolean }, +) => { + const rows = await change.dbTx + .update(l2Block) + .set({ orphan_timestamp: null, orphan_hasOrphanedParent: false }) + .where( + and(eq(l2Block.hash, block.hash), isNotNull(l2Block.orphan_timestamp)), + ) + .returning({ hash: l2Block.hash }); + if (rows.length > 0) { + change.promoted.set(block.hash, block.height); + if (walked) { + change.walked.set(block.hash, block.height); + } + } +}; + +/** Demotes `start` and the canonical blocks linked above it, up to `ceiling`. */ +const demoteLinkedRun = async ( + change: Change, + start: ChainBlock, + ceiling: bigint, +) => { + const run = [start]; + let frontier = [start]; + for ( + let height = start.height + 1n, steps = 0; + height <= ceiling && frontier.length > 0 && steps < WALK_BOUND; + height++, steps++ + ) { + await step(change); + frontier = await canonicalChildren(change, frontier, height); + run.push(...frontier); + } + await demote(change, run); +}; + +/** + * Brings back the stored, off-chain ancestors of a block that just became + * canonical, demoting their competitors. Ends at a canonical parent; at a + * missing one it clears that height, whose block cannot be the parent, and + * asks for the parent. + */ +const reviveAncestors = async (change: Change, start: ChainBlock) => { + let child = start; + for (let steps = 0; child.height > 1n; steps++) { + const below = child.height - 1n; + if (steps === WALK_BOUND) { + change.repairs.add(below); + return; + } + await step(change); + const parents = await storedParents(change, child); + if (parents.length > 1) { + logger.error( + `CHAIN_LINK_CONFLICT: several stored blocks at ${below} have the archive root that block ${child.height} (${child.hash}) names; height ${below} left as it is`, + ); + return; + } + const [parent] = parents; + if (parent?.canonical) { + return; + } + await demote(change, await canonicalAt(change, below)); + if (!parent) { + change.repairs.add(below); + return; + } + await promote(change, parent, { walked: true }); + child = parent; + } +}; + +const demoteAbove = async (change: Change, ceiling: bigint) => { + const above = await change.dbTx + .select({ hash: l2Block.hash }) + .from(l2Block) + .where( + and( + eq(l2Block.version, change.version), + gt(l2Block.height, ceiling), + isNull(l2Block.orphan_timestamp), + ), + ) + .limit(WALK_BOUND + 1); + if (above.length > WALK_BOUND) { + throw new Error( + `More than ${WALK_BOUND} canonical blocks of rollup version ${change.version} above tip ${ceiling}: refusing to demote them`, + ); + } + await demote(change, above); +}; + +type Link = { walked: ChainBlock[] } | "excludes" | "undecided"; + +/** + * Whether the lowest canonical block above an empty height descends from + * `block`, through the stored, off-chain blocks between them. + */ +const linkFromAbove = async ( + change: Change, + block: ChainBlock, +): Promise => { + const [lowest] = await chainBlocks(change.dbTx) + .where( + and( + eq(l2Block.version, change.version), + gt(l2Block.height, block.height), + isNull(l2Block.orphan_timestamp), + ), + ) + .orderBy(asc(l2Block.height)) + .limit(1); + if (!lowest) { + return "undecided"; + } + const walked: ChainBlock[] = []; + let child = toChainBlock(lowest); + for (let steps = 0; steps < WALK_BOUND; steps++) { + await step(change); + const parents = await storedParents(change, child); + if (child.height === block.height + 1n) { + if (parents.length > 1) { + return "undecided"; + } + return parents[0]?.hash === block.hash ? { walked } : "excludes"; + } + const [parent] = parents; + if (parents.length !== 1 || parent.canonical) { + return "undecided"; + } + walked.push(parent); + child = parent; + } + return "undecided"; +}; + +const storeIfAbsent = async ( + change: Change, + block: ChicmozL2Block, + { ordered }: { ordered: boolean }, +): Promise => { + const node = { + hash: block.hash, + height: block.height, + version: change.version, + archiveRoot: block.archive.root , + lastArchiveRoot: block.header.lastArchive.root , + }; + const [existing] = await change.dbTx + .select({ + orphanTimestamp: l2Block.orphan_timestamp, + archiveId: archive.id, + archiveRoot: archive.root, + bodyId: body.id, + }) + .from(l2Block) + .innerJoin(archive, eq(archive.fk, l2Block.hash)) + .innerJoin(body, eq(body.blockHash, l2Block.hash)) + .where(eq(l2Block.hash, block.hash)) + .limit(1); + if (!existing) { + const bodyId = await store(change.dbTx, block, change.now); + return { ...node, canonical: false, bodyId }; + } + const stored = { + ...node, + canonical: existing.orphanTimestamp === null, + bodyId: existing.bodyId, + }; + if (existing.archiveRoot === node.archiveRoot) { + return stored; + } + // The archive root is outside the block hash: the ordered stream's copy wins. + logger.warn( + `Block ${block.height} (${block.hash}) arrived with archive root ${node.archiveRoot}, stored with ${existing.archiveRoot}; keeping the ${ordered ? "ordered" : "stored"} one`, + ); + if (!ordered) { + return { ...stored, archiveRoot: existing.archiveRoot }; + } + await change.dbTx + .update(archive) + .set({ + root: block.archive.root, + nextAvailableLeafIndex: block.archive.nextAvailableLeafIndex, + }) + .where(eq(archive.id, existing.archiveId)); + return stored; +}; + +/** + * Writes the block's tx effects from its message. A canonical block takes + * every one, moving those that off-chain blocks hold; an off-chain block + * only takes those no block holds. + */ +const attachTxs = async ( + change: Change, + stored: StoredBlock, + block: ChicmozL2Block, + { canonical }: { canonical: boolean }, +) => { + const effects = block.body.txEffects; + const owners = new Map( + (await txOwners(change.dbTx, effects.map((e) => e.txHash))).map((o) => [ + o.txHash, + o, + ]), + ); + if (canonical) { + const conflicts = [...owners.values()].filter( + (o) => o.canonical && o.blockHash !== block.hash, + ); + if (conflicts.length > 0) { + throw new TxConflict(block, conflicts); + } + } + for (const [index, effect] of effects.entries()) { + const owner = owners.get(effect.txHash); + if (owner?.blockHash === block.hash || (owner && !canonical)) { + continue; + } + await writeTxEffect(change.dbTx, { + bodyId: stored.bodyId, + index, + effect, + held: owner !== undefined, + }); + } +}; + +const recordReorg = async (change: Change) => { + const blocks = [...change.demoted] + .map(([hash, height]) => ({ hash, height })) + .sort((a, b) => + a.height === b.height + ? a.hash.localeCompare(b.hash) + : a.height < b.height + ? -1 + : 1, + ); + const [root] = blocks; + const [record] = await change.dbTx + .insert(l2ReorgTable) + .values({ + l2NetworkId: L2_NETWORK_ID, + rollupVersion: change.version, + rootHeight: root.height, + rootHash: root.hash, + removedCount: blocks.length, + observedAt: new Date(change.now), + }) + .returning({ id: l2ReorgTable.id }); + for (const part of chunks(blocks)) { + await change.dbTx + .insert(l2ReorgBlockTable) + .values(part.map((b) => ({ reorgId: record.id, ...b }))); + } + logger.warn( + `L2 reorg at height ${root.height}: ${blocks.length} block(s) left the chain, the lowest ${root.hash}`, + ); +}; + +const markDemotedTxsDropped = async (change: Change) => { + const orphaned = await ownedTxs(change.dbTx, [...change.demoted.keys()]); + for (const part of chunks(orphaned)) { + await change.dbTx + .insert(droppedTx) + .values( + part.map(({ txHash, birth }) => ({ + txHash, + createdAsPendingAt: birth, + droppedAt: change.now, + dropReason: "orphaned", + })), + ) + .onConflictDoNothing(); + } +}; + +/** A record is revived once every block it lists is stored and canonical again. */ +const reviveRecords = async (change: Change) => { + for (const part of chunks([...change.promoted.keys()])) { + await change.dbTx + .update(l2ReorgTable) + .set({ revivedAt: new Date(change.now) }) + .where( + and( + eq(l2ReorgTable.l2NetworkId, L2_NETWORK_ID), + isNull(l2ReorgTable.revivedAt), + inArray( + l2ReorgTable.id, + change.dbTx + .select({ id: l2ReorgBlockTable.reorgId }) + .from(l2ReorgBlockTable) + .where(inArray(l2ReorgBlockTable.hash, part)), + ), + sql`NOT EXISTS (SELECT 1 FROM ${l2ReorgBlockTable} LEFT JOIN ${l2Block} ON ${l2Block.hash} = ${l2ReorgBlockTable.hash} WHERE ${l2ReorgBlockTable.reorgId} = ${l2ReorgTable.id} AND (${l2Block.hash} IS NULL OR ${l2Block.orphan_timestamp} IS NOT NULL))`, + ), + ); + } +}; + +const setHasOrphanedParent = async ( + change: Change, + hashes: HexString[], + value: boolean, +) => { + for (const part of chunks(hashes)) { + await change.dbTx + .update(l2Block) + .set({ orphan_hasOrphanedParent: value }) + .where(and(inArray(l2Block.hash, part), isNotNull(l2Block.orphan_timestamp))); + } +}; + +/** + * `orphan_hasOrphanedParent` of an off-chain block: its stored parent is off + * the chain too. Refreshed for the demoted blocks and for the off-chain + * children of every block this call moved. + */ +const refreshOrphanFlags = async (change: Change) => { + const parent = alias(l2Block, "parent"); + const parentArchive = alias(archive, "parent_archive"); + const deadParent: HexString[] = []; + for (const part of chunks([...change.demoted.keys()])) { + const rows = await change.dbTx + .selectDistinct({ hash: l2Block.hash }) + .from(l2Block) + .innerJoin(header, eq(header.blockHash, l2Block.hash)) + .innerJoin(lastArchive, eq(lastArchive.fk, header.id)) + .innerJoin(parentArchive, eq(parentArchive.root, lastArchive.root)) + .innerJoin( + parent, + and( + eq(parent.hash, parentArchive.fk), + eq(parent.height, sql`${l2Block.height} - 1`), + eq(parent.version, l2Block.version), + ), + ) + .where(and(inArray(l2Block.hash, part), isNotNull(parent.orphan_timestamp))); + deadParent.push(...rows.map((r) => r.hash)); + } + + const child = alias(l2Block, "child"); + const childHeader = alias(header, "child_header"); + const childLastArchive = alias(lastArchive, "child_last_archive"); + const moved = [...change.demoted.keys(), ...change.promoted.keys()]; + const liveParent: HexString[] = []; + for (const part of chunks(moved)) { + const rows = await change.dbTx + .selectDistinct({ + hash: child.hash, + parentOrphanTimestamp: l2Block.orphan_timestamp, + }) + .from(l2Block) + .innerJoin(archive, eq(archive.fk, l2Block.hash)) + .innerJoin(childLastArchive, eq(childLastArchive.root, archive.root)) + .innerJoin(childHeader, eq(childHeader.id, childLastArchive.fk)) + .innerJoin( + child, + and( + eq(child.hash, childHeader.blockHash), + eq(child.height, sql`${l2Block.height} + 1`), + eq(child.version, l2Block.version), + ), + ) + .where(and(inArray(l2Block.hash, part), isNotNull(child.orphan_timestamp))); + for (const row of rows) { + (row.parentOrphanTimestamp === null ? liveParent : deadParent).push( + row.hash, + ); + } + } + await setHasOrphanedParent(change, deadParent, true); + await setHasOrphanedParent(change, liveParent, false); +}; + +/** The writes that follow the decision, in the same transaction. */ +const settle = async (change: Change, attached: ChicmozL2Block | undefined) => { + if (change.demoted.size > 0) { + await recordReorg(change); + } + await markDemotedTxsDropped(change); + const mined = new Set( + (await ownedTxs(change.dbTx, [...change.promoted.keys()])).map( + (t) => t.txHash, + ), + ); + attached?.body.txEffects.forEach((e) => mined.add(e.txHash)); + for (const part of chunks([...mined])) { + await removePendingAndDroppedTx(change.dbTx, part); + } + await reviveRecords(change); + await refreshOrphanFlags(change); + await recordRepairHeights(change.dbTx, [ + ...change.walked.values(), + ...change.repairs, + ]); +}; + +const ownerSummary = (owners: TxOwner[]) => + owners + .map( + (o) => `${o.txHash} in active block ${o.height} (${o.blockHash})`, + ) + .join(", "); + +/** + * Stores the block if absent, lets `decide` move the chain, then attaches + * the block's txs and contracts when it ends canonical. + */ +const apply = async ( + { block, contracts }: IncomingBlock, + heartbeat: Heartbeat, + { ordered }: { ordered: boolean }, + decide: (change: Change, stored: StoredBlock) => Promise, +): Promise => { + try { + return await withChainLock(async (dbTx) => { + const change: Change = { + dbTx, + version: block.header.globalVariables.version, + now: Date.now(), + heartbeat, + steps: 0, + demoted: new Map(), + promoted: new Map(), + walked: new Map(), + repairs: new Set(), + }; + const stored = await storeIfAbsent(change, block, { ordered }); + const canonical = await decide(change, stored); + await attachTxs(change, stored, block, { canonical }); + if (canonical) { + await storeBlockContracts(dbTx, contracts); + } + await settle(change, canonical ? block : undefined); + logger.info( + `๐Ÿงข Applied ${ordered ? "ordered" : "catch-up"} block ${block.height} (${block.hash}): ${canonical ? "canonical" : "off the chain"}; demoted ${change.demoted.size}, made canonical ${change.promoted.size}`, + ); + return { canonical }; + }); + } catch (e) { + if (e instanceof TxConflict) { + logger.error( + `SKIPPED_BLOCK_TX_CONFLICT height=${block.height} hash=${block.hash} owners=${ownerSummary(e.owners)}`, + ); + return { canonical: false }; + } + throw e; + } +}; + +/** + * An ordered block is canonical at its height. It replaces the block there, + * that block's linked descendants and every canonical holder of its txs + * above it (a tx is included once per chain), brings back its stored + * ancestors, and demotes every canonical block above `tip`. + */ +export const applyOrderedBlock = ( + incoming: IncomingBlock, + tip: number, + heartbeat: Heartbeat, +): Promise => { + const { height, hash } = incoming.block; + let ceiling = BigInt(tip); + if (ceiling < height) { + logger.warn( + `Ordered block ${height} (${hash}) carries tip ${tip}, below its height; using ${height}`, + ); + ceiling = height; + } + return apply( + incoming, + heartbeat, + { ordered: true }, + async (change, stored) => { + if (!stored.canonical) { + for (const replaced of await canonicalAt(change, height)) { + await demoteLinkedRun(change, replaced, ceiling); + } + const txHashes = incoming.block.body.txEffects.map((e) => e.txHash); + const holders = new Map( + (await txOwners(change.dbTx, txHashes)) + .filter( + (o) => o.canonical && o.height > height && o.blockHash !== hash, + ) + .map((o) => [o.blockHash, o]), + ); + for (const holder of holders.values()) { + const [run] = ( + await chainBlocks(change.dbTx).where( + and( + eq(l2Block.hash, holder.blockHash), + eq(l2Block.version, change.version), + isNull(l2Block.orphan_timestamp), + ), + ) + ).map(toChainBlock); + if (run) { + await demoteLinkedRun(change, run, ceiling); + } + } + await promote(change, stored, { walked: false }); + await reviveAncestors(change, stored); + } + await demoteAbove(change, ceiling); + return true; + }, + ); +}; + +/** + * A catch-up block never demotes anything. It joins only at an empty + * height: when the lowest canonical block above descends from it, or, with + * `final` (at or below the serving node's own finalized tip), when the + * canonical block below, if any, is its parent. + */ +export const applyCatchupBlock = ( + incoming: IncomingBlock, + final: boolean, + heartbeat: Heartbeat, +): Promise => + apply(incoming, heartbeat, { ordered: false }, async (change, stored) => { + if (stored.canonical) { + return true; + } + if ((await canonicalAt(change, stored.height)).length > 0) { + return false; + } + const link = await linkFromAbove(change, stored); + if (link === "excludes") { + if (final) { + logger.warn( + `CHAIN_LINK_CONFLICT: final catch-up block ${stored.height} (${stored.hash}) is not the parent of the canonical chain above it; left off the chain`, + ); + } + return false; + } + if (link !== "undecided") { + await promote(change, stored, { walked: false }); + for (const walked of link.walked) { + await promote(change, walked, { walked: true }); + } + return true; + } + if (!final) { + return false; + } + const below = await canonicalAt(change, stored.height - 1n); + if (below.some((b) => b.archiveRoot !== stored.lastArchiveRoot)) { + return false; + } + await promote(change, stored, { walked: false }); + return true; + }); diff --git a/services/explorer-api/src/svcs/database/controllers/l2block/delete.ts b/services/explorer-api/src/svcs/database/controllers/l2block/delete.ts deleted file mode 100644 index 25611428..00000000 --- a/services/explorer-api/src/svcs/database/controllers/l2block/delete.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { getDb as db } from "@chicmoz-pkg/postgres-helper"; -import { type HexString } from "@chicmoz-pkg/types"; -import { eq, inArray } from "drizzle-orm"; -import { logger } from "../../../../logger.js"; -import { - body, - l2Block, - txEffect, -} from "../../../database/schema/l2block/index.js"; - -export const deleteAllBlocks = async (): Promise => { - const res = (await db().delete(l2Block).execute()).rowCount; - logger.info(`๐Ÿ—‘๏ธ Deleted ${res} blocks`); -}; - -export const deleteL2BlockByHeight = async (height: bigint): Promise => { - await db().delete(l2Block).where(eq(l2Block.height, height)).execute(); -}; - -export const deleteL2BlockByHash = async (hash: HexString): Promise => { - await db().delete(l2Block).where(eq(l2Block.hash, hash)).execute(); -}; - -export type TxEffectOwner = { - txHash: HexString; - blockHash: HexString; - blockHeight: bigint; - rollupVersion: number; - isOrphaned: boolean; -}; - -export const getTxEffectOwners = async ( - txHashes: HexString[], -): Promise => { - if (txHashes.length === 0) { - return []; - } - - const uniqueTxHashes = [...new Set(txHashes)]; - - const owners = await db() - .select({ - txHash: txEffect.txHash, - blockHash: l2Block.hash, - blockHeight: l2Block.height, - rollupVersion: l2Block.version, - orphanTimestamp: l2Block.orphan_timestamp, - }) - .from(txEffect) - .innerJoin(body, eq(txEffect.bodyId, body.id)) - .innerJoin(l2Block, eq(body.blockHash, l2Block.hash)) - .where(inArray(txEffect.txHash, uniqueTxHashes)); - - return owners.map((owner) => ({ - txHash: owner.txHash, - blockHash: owner.blockHash, - blockHeight: owner.blockHeight, - rollupVersion: owner.rollupVersion, - isOrphaned: owner.orphanTimestamp !== null, - })); -}; 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 fb876a30..e9409c19 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 @@ -6,15 +6,16 @@ import { } from "@chicmoz-pkg/types"; import { and, - count, desc, eq, getTableColumns, isNotNull, isNull, + or, sql, } from "drizzle-orm"; -import { DB_MAX_BLOCKS } from "../../../../environment.js"; +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 { getLatestBlockRollupVersion } from "./get-latest.js"; @@ -387,62 +388,63 @@ export const getOrphanedBlocks = async ( return blocks; }; +type Reorg = { + orphanedBlockHash: HexString; + height: bigint; + timestamp: Date; + nbrOfOrphanedBlocks: number; +}; + /** - * Get information about reorgs - * @returns Array of reorg events with details about orphaned blocks + * Active reorg records, newest first, each shown by its listed blocks still + * off the chain (a block no longer stored counts as off). A block counts + * only for the newest record that lists it, so a block that died again + * shows once. */ -export const getReorgs = async (): Promise< - { - orphanedBlockHash: HexString; - height: bigint; - timestamp: Date; - nbrOfOrphanedBlocks: number; - }[] -> => { - // Get all root orphaned blocks (those with hasOrphanedParent = false) - const rootOrphanedBlocks = await db() +export const getReorgs = async (): Promise => { + const rows = await db() .select({ - hash: l2Block.hash, - height: l2Block.height, - timestamp: l2Block.orphan_timestamp, + id: l2ReorgTable.id, + observedAt: l2ReorgTable.observedAt, + hash: l2ReorgBlockTable.hash, + height: l2ReorgBlockTable.height, }) - .from(l2Block) + .from(l2ReorgTable) + .innerJoin( + l2ReorgBlockTable, + eq(l2ReorgBlockTable.reorgId, l2ReorgTable.id), + ) + .leftJoin(l2Block, eq(l2Block.hash, l2ReorgBlockTable.hash)) .where( and( - isNotNull(l2Block.orphan_timestamp), - eq(l2Block.orphan_hasOrphanedParent, false), + eq(l2ReorgTable.l2NetworkId, L2_NETWORK_ID), + isNull(l2ReorgTable.revivedAt), + or(isNull(l2Block.hash), isNotNull(l2Block.orphan_timestamp)), + sql`NOT EXISTS (SELECT 1 FROM ${l2ReorgBlockTable} AS newer WHERE newer."hash" = ${l2ReorgBlockTable.hash} AND newer."reorg_id" > ${l2ReorgTable.id})`, ), ) - .orderBy(desc(l2Block.orphan_timestamp)) - .execute(); + .orderBy(desc(l2ReorgTable.observedAt), desc(l2ReorgTable.id)); - const result = []; - - // For each root orphaned block, count how many children it has - for (const rootBlock of rootOrphanedBlocks) { - if (!rootBlock.timestamp) { + const reorgs = new Map(); + for (const row of rows) { + const reorg = reorgs.get(row.id); + if (!reorg) { + reorgs.set(row.id, { + orphanedBlockHash: row.hash, + height: row.height, + timestamp: row.observedAt, + nbrOfOrphanedBlocks: 1, + }); continue; } - - // Count orphaned blocks with the same timestamp (these are all part of the same re-org) - const childCount = await db() - .select({ count: count() }) - .from(l2Block) - .where( - and( - eq(l2Block.orphan_timestamp, rootBlock.timestamp), - eq(l2Block.orphan_hasOrphanedParent, true), - ), - ) - .execute(); - - result.push({ - orphanedBlockHash: rootBlock.hash, - height: rootBlock.height, - timestamp: new Date(rootBlock.timestamp), - nbrOfOrphanedBlocks: (childCount[0]?.count || 0) + 1, // +1 for the root block itself - }); + reorg.nbrOfOrphanedBlocks++; + if ( + row.height < reorg.height || + (row.height === reorg.height && row.hash < reorg.orphanedBlockHash) + ) { + reorg.orphanedBlockHash = row.hash; + reorg.height = row.height; + } } - - return result; + return [...reorgs.values()]; }; 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 617992d1..3cc80f20 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 @@ -141,6 +141,26 @@ const MAX_GAP_BACKOFF_MS = 60 * 60 * 1000; // requested first. const CANDIDATE_GAP_LIMIT = 50; const TIP_BOUNDARY_REASON: L2BlockRangeRequestReason = "tip_boundary_mismatch"; +// One height whose block message must come back: the canonical block there +// lacks it, or the height was cleared under a block whose parent is missing. +// Requested whole, present or not, until a canonical attach from a block +// message fulfils it (markOpenGapsFulfilledByHeight). +const REPAIR_REASON: L2BlockRangeRequestReason = "reorg_repair"; + +export const recordRepairHeights = async ( + executor: ReturnType, + heights: Iterable, +) => { + await upsertOpenGaps({ + ranges: [...heights].map((height) => ({ + from: Number(height), + to: Number(height), + statusHint: "proposed" as const, + })), + reason: REPAIR_REASON, + executor, + }); +}; /** * Whether a gap may be requested again at `now` (epoch ms): never requested, @@ -364,7 +384,7 @@ const selectGapRequest = async ({ const upper = Math.min(gap.toHeight, chainTip); const missing: number[] = []; for (let height = gap.fromHeight; height <= upper; height++) { - if (!present.has(height)) { + if (gap.reason === REPAIR_REASON || !present.has(height)) { missing.push(height); } } diff --git a/services/explorer-api/src/svcs/database/controllers/l2block/orphan.ts b/services/explorer-api/src/svcs/database/controllers/l2block/orphan.ts deleted file mode 100644 index 0300889c..00000000 --- a/services/explorer-api/src/svcs/database/controllers/l2block/orphan.ts +++ /dev/null @@ -1,216 +0,0 @@ -import { getDb as db } from "@chicmoz-pkg/postgres-helper"; -import { HexString } from "@chicmoz-pkg/types"; -import { and, eq, gt, isNull } from "drizzle-orm"; -import { logger } from "../../../../logger.js"; -import { - body, - l2Block, - txEffect, -} from "../../../database/schema/l2block/index.js"; -import { storeDroppedTx } from "../../controllers/dropped-tx/store.js"; - -/** - * Mark a block as orphaned with the specified parent status - */ -export const markBlockAsOrphaned = async ( - blockHash: HexString, - timestamp: number, - hasOrphanedParent: boolean, -): Promise => { - logger.info( - `Marking block ${blockHash} as orphaned. hasOrphanedParent: ${hasOrphanedParent}`, - ); - - await db() - .update(l2Block) - .set({ - orphan_timestamp: timestamp, - orphan_hasOrphanedParent: hasOrphanedParent, - }) - .where(eq(l2Block.hash, blockHash)); -}; - -/** - * Mark all blocks with height > targetHeight and orphan_timestamp === null as orphaned - * @returns The number of blocks that were marked as orphaned - */ -export const markHigherBlocksAsOrphaned = async ( - targetHeight: bigint, - timestamp: number, -): Promise => { - logger.info( - `Marking all blocks with height > ${targetHeight} as orphaned with parent`, - ); - - // Find all blocks with higher height that aren't already orphaned - const higherBlocks = await db() - .select({ hash: l2Block.hash }) - .from(l2Block) - .where( - and(gt(l2Block.height, targetHeight), isNull(l2Block.orphan_timestamp)), - ); - - const orphanedCount = higherBlocks.length; - - // Mark them all as orphaned with hasOrphanedParent=true - for (const block of higherBlocks) { - await markBlockAsOrphaned(block.hash, timestamp, true); - } - - logger.info(`Marked ${orphanedCount} child blocks as orphaned`); - return orphanedCount; -}; - -/** - * Handle a re-org by marking the specified block and all higher blocks of its - * rollup version as orphaned - * Uses a transaction to ensure all operations are atomic - * - * @param originalBlockHash The hash of the block being replaced (original block at the height) - * @param targetHeight The height at which the re-org occurred - * @param rollupVersion The rollup version of the re-orged chain; other versions' chains are left as they are - * @returns The number of total blocks orphaned (including the original) - */ -export const handleReorgOrphaning = async ( - originalBlockHash: HexString, - targetHeight: bigint, - rollupVersion: number, -): Promise => { - const now = new Date().getTime(); - - return await db().transaction(async (dbTx) => { - logger.info( - `Starting orphan transaction for re-org at height ${targetHeight}`, - ); - - // 1. Mark the original block as orphaned (root of orphaned chain) - await dbTx - .update(l2Block) - .set({ - orphan_timestamp: now, - orphan_hasOrphanedParent: false, - }) - .where(eq(l2Block.hash, originalBlockHash)); - - // Find transaction effects in the orphaned block and store them as dropped - await storeOrphanedTxEffectsAsDropped(dbTx, originalBlockHash, now); - - // 2. Find and mark all higher blocks as orphaned with parent - const higherBlocks = await dbTx - .select({ hash: l2Block.hash }) - .from(l2Block) - .where( - and( - gt(l2Block.height, targetHeight), - eq(l2Block.version, rollupVersion), - isNull(l2Block.orphan_timestamp), - ), - ); - - const orphanedChildrenCount = higherBlocks.length; - - // Mark all children as orphaned with parent=true - for (const block of higherBlocks) { - await dbTx - .update(l2Block) - .set({ - orphan_timestamp: now, - orphan_hasOrphanedParent: true, - }) - .where(eq(l2Block.hash, block.hash)); - - // Store transaction effects from this block as dropped - await storeOrphanedTxEffectsAsDropped(dbTx, block.hash, now); - } - - const totalOrphaned = orphanedChildrenCount + 1; // +1 for the original block - logger.info( - `Completed orphan transaction. Total orphaned: ${totalOrphaned} (1 root + ${orphanedChildrenCount} children)`, - ); - - return totalOrphaned; - }); -}; - -/** - * Un-orphan a block by clearing its orphan_timestamp and orphan_hasOrphanedParent fields. - * This is used when we receive a block with the same hash as an already-orphaned block, - * meaning the orphaned block is actually the canonical one. - */ -export const unOrphanBlock = async (blockHash: HexString): Promise => { - logger.info(`Un-orphaning block ${blockHash}`); - await db() - .update(l2Block) - .set({ - orphan_timestamp: null, - orphan_hasOrphanedParent: false, - }) - .where(eq(l2Block.hash, blockHash)); -}; - -type DB = ReturnType; -type DBTransactionFunction = DB["transaction"]; -type DBTransactionFunctionCallback = Parameters[0]; -type DBTransactionFunctionCallbackParameter = - Parameters[0]; - -/** - * Find transaction effects in an orphaned block and store them as dropped transactions - */ -const storeOrphanedTxEffectsAsDropped = async ( - dbTx: DBTransactionFunctionCallbackParameter, - blockHash: HexString, - timestamp: number, -): Promise => { - // Find the body ID for this block - const blockBody = await dbTx - .select({ id: body.id }) - .from(body) - .where(eq(body.blockHash, blockHash)) - .limit(1); - - if (blockBody.length === 0) { - logger.warn(`No body found for orphaned block ${blockHash}`); - return; - } - - const bodyId = blockBody[0].id; - - // Find all transaction effects in this body - const txEffects = await dbTx - .select({ - txHash: txEffect.txHash, - txBirthTimestamp: txEffect.txBirthTimestamp, - }) - .from(txEffect) - .where(eq(txEffect.bodyId, bodyId)); - - if (txEffects.length === 0) { - logger.info(`No transaction effects found in orphaned block ${blockHash}`); - return; - } - - logger.info( - `Found ${txEffects.length} transaction effects to mark as dropped in block ${blockHash}`, - ); - - // Store each transaction effect as a dropped transaction - for (const tx of txEffects) { - try { - await storeDroppedTx({ - txHash: tx.txHash, - createdAsPendingAt: tx.txBirthTimestamp, - droppedAt: timestamp, - // Block was reorged out โ€” tx returns to dropped-state with this - // reason so the UI can show "(reorg)" rather than just a timestamp. - dropReason: "orphaned", - }); - } catch (error) { - const errorMessage = - error instanceof Error ? error.message : String(error); - logger.error( - `Failed to store dropped transaction ${tx.txHash}: ${errorMessage}`, - ); - } - } -}; diff --git a/services/explorer-api/src/svcs/database/controllers/l2block/store.ts b/services/explorer-api/src/svcs/database/controllers/l2block/store.ts index d76af476..f1fa83e8 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2block/store.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2block/store.ts @@ -1,5 +1,9 @@ -import { getDb as db } from "@chicmoz-pkg/postgres-helper"; -import { HexString, type ChicmozL2Block } from "@chicmoz-pkg/types"; +import { + type ChicmozL2Block, + type ChicmozL2TxEffect, + type HexString, +} from "@chicmoz-pkg/types"; +import { eq } from "drizzle-orm"; import { randomUUID } from "node:crypto"; import { archive, @@ -18,157 +22,170 @@ import { state, txEffect, } from "../../../database/schema/l2block/index.js"; +import { type DbTx } from "../utils.js"; -export const store = async (block: ChicmozL2Block): Promise => { - return await db().transaction(async (dbTx) => { - // Insert l2Block - await dbTx.insert(l2Block).values({ - hash: block.hash, - height: BigInt(block.header.globalVariables.blockNumber), - version: block.header.globalVariables.version, - orphan_timestamp: block.orphan?.timestamp ?? null, - orphan_hasOrphanedParent: block.orphan?.hasOrphanedParent ?? false, - }); - - const headerId = randomUUID(); - // Insert header - await dbTx.insert(header).values({ - id: headerId, - blockHash: block.hash, - totalFees: block.header.totalFees.toString(), - totalManaUsed: block.header.totalManaUsed.toString(), - // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment - spongeBlobHash: block.header.spongeBlobHash, - }); - - // Insert archive - await dbTx.insert(archive).values({ - root: block.archive.root, - nextAvailableLeafIndex: block.archive.nextAvailableLeafIndex, - fk: block.hash, - }); +/** + * Inserts every row of a block except its tx effects, off the chain since + * `orphanTimestamp`: the caller decides its status and attaches its effects. + * Returns the body id. + */ +export const store = async ( + dbTx: DbTx, + block: ChicmozL2Block, + orphanTimestamp: number, +): Promise => { + await dbTx.insert(l2Block).values({ + hash: block.hash, + height: BigInt(block.header.globalVariables.blockNumber), + version: block.header.globalVariables.version, + orphan_timestamp: orphanTimestamp, + orphan_hasOrphanedParent: false, + }); - const lastArchiveId = randomUUID(); - // Insert last archive - await dbTx.insert(lastArchive).values({ - id: lastArchiveId, - root: block.header.lastArchive.root, - nextAvailableLeafIndex: block.header.lastArchive.nextAvailableLeafIndex, - fk: headerId, - }); + const headerId = randomUUID(); + await dbTx.insert(header).values({ + id: headerId, + blockHash: block.hash, + totalFees: block.header.totalFees.toString(), + totalManaUsed: block.header.totalManaUsed.toString(), + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + spongeBlobHash: block.header.spongeBlobHash, + }); - const stateId = randomUUID(); - // Insert state - await dbTx.insert(state).values({ - id: stateId, - headerId, - }); + await dbTx.insert(archive).values({ + root: block.archive.root, + nextAvailableLeafIndex: block.archive.nextAvailableLeafIndex, + fk: block.hash, + }); - const l1ToL2MessageTreeId = randomUUID(); - // Insert l1ToL2MessageTree - await dbTx.insert(l1ToL2MessageTree).values({ - id: l1ToL2MessageTreeId, - root: block.header.state.l1ToL2MessageTree.root, - nextAvailableLeafIndex: - block.header.state.l1ToL2MessageTree.nextAvailableLeafIndex, - fk: stateId, - }); + await dbTx.insert(lastArchive).values({ + id: randomUUID(), + root: block.header.lastArchive.root, + nextAvailableLeafIndex: block.header.lastArchive.nextAvailableLeafIndex, + fk: headerId, + }); - const partialId = randomUUID(); - // Insert partial - await dbTx.insert(partial).values({ - id: partialId, - stateId, - }); + const stateId = randomUUID(); + await dbTx.insert(state).values({ + id: stateId, + headerId, + }); - const noteHashTreeId = randomUUID(); - // Insert partial state trees - await dbTx.insert(noteHashTree).values({ - id: noteHashTreeId, - root: block.header.state.partial.noteHashTree.root, - nextAvailableLeafIndex: - block.header.state.partial.noteHashTree.nextAvailableLeafIndex, - fk: partialId, - }); + await dbTx.insert(l1ToL2MessageTree).values({ + id: randomUUID(), + root: block.header.state.l1ToL2MessageTree.root, + nextAvailableLeafIndex: + block.header.state.l1ToL2MessageTree.nextAvailableLeafIndex, + fk: stateId, + }); - const nullifierTreeId = randomUUID(); - await dbTx.insert(nullifierTree).values({ - id: nullifierTreeId, - root: block.header.state.partial.nullifierTree.root, - nextAvailableLeafIndex: - block.header.state.partial.nullifierTree.nextAvailableLeafIndex, - fk: partialId, - }); + const partialId = randomUUID(); + await dbTx.insert(partial).values({ + id: partialId, + stateId, + }); - const publicDataTreeId = randomUUID(); - await dbTx.insert(publicDataTree).values({ - id: publicDataTreeId, - root: block.header.state.partial.publicDataTree.root, - nextAvailableLeafIndex: - block.header.state.partial.publicDataTree.nextAvailableLeafIndex, - fk: partialId, - }); + await dbTx.insert(noteHashTree).values({ + id: randomUUID(), + root: block.header.state.partial.noteHashTree.root, + nextAvailableLeafIndex: + block.header.state.partial.noteHashTree.nextAvailableLeafIndex, + fk: partialId, + }); - const globalVariablesId = randomUUID(); - // Insert global variables - await dbTx.insert(globalVariables).values({ - id: globalVariablesId, - headerId, - chainId: block.header.globalVariables.chainId, - version: block.header.globalVariables.version, - blockNumber: block.header.globalVariables.blockNumber, - slotNumber: block.header.globalVariables.slotNumber, - timestamp: block.header.globalVariables.timestamp, - coinbase: block.header.globalVariables.coinbase, - feeRecipient: block.header.globalVariables.feeRecipient, - }); + await dbTx.insert(nullifierTree).values({ + id: randomUUID(), + root: block.header.state.partial.nullifierTree.root, + nextAvailableLeafIndex: + block.header.state.partial.nullifierTree.nextAvailableLeafIndex, + fk: partialId, + }); - const gasFeesId = randomUUID(); - // Insert gas fees - await dbTx.insert(gasFees).values({ - id: gasFeesId, - globalVariablesId, - feePerDaGas: block.header.globalVariables.gasFees.feePerDaGas, - feePerL2Gas: block.header.globalVariables.gasFees.feePerL2Gas, - }); + await dbTx.insert(publicDataTree).values({ + id: randomUUID(), + root: block.header.state.partial.publicDataTree.root, + nextAvailableLeafIndex: + block.header.state.partial.publicDataTree.nextAvailableLeafIndex, + fk: partialId, + }); - const bodyId = randomUUID(); - // Insert body - await dbTx.insert(body).values({ - id: bodyId, - blockHash: block.hash, - }); + const globalVariablesId = randomUUID(); + await dbTx.insert(globalVariables).values({ + id: globalVariablesId, + headerId, + chainId: block.header.globalVariables.chainId, + version: block.header.globalVariables.version, + blockNumber: block.header.globalVariables.blockNumber, + slotNumber: block.header.globalVariables.slotNumber, + timestamp: block.header.globalVariables.timestamp, + coinbase: block.header.globalVariables.coinbase, + feeRecipient: block.header.globalVariables.feeRecipient, + }); - // Insert txEffects and create junction entries - for (const [i, txEff] of Object.entries(block.body.txEffects)) { - if (isNaN(Number(i))) { - throw new Error("Invalid txEffect index"); - } - await dbTx.insert(txEffect).values({ - txHash: txEff.txHash, - bodyId, - index: Number(i), - revertCode: txEff.revertCode.code, - transactionFee: txEff.transactionFee, - noteHashes: txEff.noteHashes as HexString[], - nullifiers: txEff.nullifiers as HexString[], - l2ToL1Msgs: txEff.l2ToL1Msgs as HexString[], - privateLogs: txEff.privateLogs, - publicLogs: txEff.publicLogs, - contractClassLogs: txEff.contractClassLogs, - }); + await dbTx.insert(gasFees).values({ + id: randomUUID(), + globalVariablesId, + feePerDaGas: block.header.globalVariables.gasFees.feePerDaGas, + feePerL2Gas: block.header.globalVariables.gasFees.feePerL2Gas, + }); - // Insert public data writes - for (const [pdwIndex, pdw] of Object.entries(txEff.publicDataWrites)) { - const publicDataWriteId = randomUUID(); - await dbTx.insert(publicDataWrite).values({ - id: publicDataWriteId, - txEffectHash: txEff.txHash, - index: Number(pdwIndex), - leafSlot: pdw.leafSlot, - value: pdw.value, - }); - } - } + const bodyId = randomUUID(); + await dbTx.insert(body).values({ + id: bodyId, + blockHash: block.hash, }); + return bodyId; +}; + +/** + * Writes a tx effect into a body: inserted when no block holds it, otherwise + * moved from its holder. A moved effect keeps its birth time and the fields + * copied from its pending tx. + */ +export const writeTxEffect = async ( + dbTx: DbTx, + { + bodyId, + index, + effect, + held, + }: { + bodyId: string; + index: number; + effect: ChicmozL2TxEffect; + held: boolean; + }, +): Promise => { + const content = { + bodyId, + index, + revertCode: effect.revertCode.code, + transactionFee: effect.transactionFee, + noteHashes: effect.noteHashes as HexString[], + nullifiers: effect.nullifiers as HexString[], + l2ToL1Msgs: effect.l2ToL1Msgs as HexString[], + privateLogs: effect.privateLogs, + publicLogs: effect.publicLogs, + contractClassLogs: effect.contractClassLogs, + }; + if (held) { + await dbTx + .update(txEffect) + .set(content) + .where(eq(txEffect.txHash, effect.txHash)); + await dbTx + .delete(publicDataWrite) + .where(eq(publicDataWrite.txEffectHash, effect.txHash)); + } else { + await dbTx.insert(txEffect).values({ txHash: effect.txHash, ...content }); + } + for (const [pdwIndex, pdw] of effect.publicDataWrites.entries()) { + await dbTx.insert(publicDataWrite).values({ + id: randomUUID(), + txEffectHash: effect.txHash, + index: pdwIndex, + leafSlot: pdw.leafSlot, + value: pdw.value, + }); + } }; 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 e74277e4..93024d63 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2contract/store.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2contract/store.ts @@ -23,20 +23,23 @@ import { selectorMapValueToFunctionName, } from "../../../../utils/resolve-artifact-names.js"; import { logger } from "../../../../logger.js"; +import { type DbTx } from "../utils.js"; export const storeContractInstanceDeployed = async ( instance: ChicmozL2ContractInstanceDeployedEvent, + executor: ReturnType = db(), ): Promise => { const { publicKeys, ...rest } = instance; - await db() + await executor .insert(l2ContractInstanceDeployed) .values({ ...publicKeys, ...rest }); }; export const storeContractInstanceUpdated = async ( instance: ChicmozL2ContractInstanceUpdatedEvent, + executor: ReturnType = db(), ): Promise => { - await db() + await executor .insert(l2ContractInstanceUpdate) .values({ ...instance }); }; @@ -60,14 +63,66 @@ export const storeContractInstanceVerifiedDeploymentArguments = async ( export const storeContractClass = async ( contractClass: ChicmozL2ContractClassRegisteredEvent, + executor: ReturnType = db(), ): Promise => { - await db() + await executor .insert(l2ContractClassRegistered) .values({ ...contractClass, }); }; +export type BlockContracts = { + classes: ChicmozL2ContractClassRegisteredEvent[]; + instancesDeployed: ChicmozL2ContractInstanceDeployedEvent[]; + instancesUpdated: ChicmozL2ContractInstanceUpdatedEvent[]; +}; + +/** + * 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. + */ +export const storeBlockContracts = async ( + dbTx: DbTx, + { classes, instancesDeployed, instancesUpdated }: BlockContracts, +): Promise => { + const each = async ( + rows: T[], + label: (row: T) => string, + write: (row: T, executor: DbTx) => Promise, + ) => { + for (const row of rows) { + 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)}`, + ); + } + } + } + }; + await each( + classes, + (c) => `contractClass ${c.contractClassId}`, + storeContractClass, + ); + await each( + instancesDeployed, + (i) => `contractInstanceDeployed ${i.address}`, + storeContractInstanceDeployed, + ); + await each( + instancesUpdated, + (i) => `contractInstanceUpdated ${i.address}`, + storeContractInstanceUpdated, + ); +}; + export const addArtifactData = async ({ contractClassId, version, diff --git a/services/explorer-api/src/svcs/database/controllers/utils.ts b/services/explorer-api/src/svcs/database/controllers/utils.ts index b6753e78..c077a907 100644 --- a/services/explorer-api/src/svcs/database/controllers/utils.ts +++ b/services/explorer-api/src/svcs/database/controllers/utils.ts @@ -1,10 +1,15 @@ import { BadRequestError } from "@chicmoz-pkg/error-middleware"; +import { type getDb } from "@chicmoz-pkg/postgres-helper"; import { Table, and, getTableColumns, gte, lt } from "drizzle-orm"; import { ZodError } from "zod"; import { DB_MAX_BLOCKS } from "../../../environment.js"; import { logger } from "../../../logger.js"; import { l2Block } from "../schema/index.js"; +export type DbTx = Parameters< + Parameters["transaction"]>[0] +>[0]; + export const dbParseErrorCallback = (e: unknown) => { if (e instanceof ZodError) { const newError = new Error("Internal server error (DB)"); 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 3bdccdd7..c612b52e 100644 --- a/services/explorer-api/tests/integration/block-ingest.integration.test.ts +++ b/services/explorer-api/tests/integration/block-ingest.integration.test.ts @@ -8,10 +8,11 @@ import { // Local-network blocks only: one database serves one rollup version. Hashes, // archives and tx hashes are the node's RPC fields; class ids and instance // addresses were decoded from logs and confirmed by node lookups. Delivered -// by height, as a deployment needs its class stored first. +// by height as one ordered pass: a deployment needs its class stored first. const recorded = listFixtures("local-network", "l2-block") .map((name) => loadFixture("local-network", "l2-block", name).data) .sort((a, b) => a.expected.height - b.expected.height); +const tip = Math.max(...recorded.map(({ expected }) => expected.height)); describe("recorded blocks through the block handler", () => { let api: ExplorerApiForTest; @@ -26,6 +27,7 @@ describe("recorded blocks through the block handler", () => { block: hex, blockNumber: expected.height, statusHint: "proposed", + ordered: { tip }, }); } }); 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 1350228f..27d624d9 100644 --- a/services/explorer-api/tests/integration/block-reorg.integration.test.ts +++ b/services/explorer-api/tests/integration/block-reorg.integration.test.ts @@ -1,124 +1,100 @@ -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 } from "./support/blocks.js"; +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"; -// A tx hash is a primary key across the database, and a reorg orphans every -// active block of its rollup version above its height, so the cases use -// disjoint txs and ascending, disjoint heights, in file order. +// A tx hash is a primary key across the database, and an ordered block +// demotes every canonical block of its rollup version above its tip, so the +// cases use disjoint txs and ascending, disjoint heights, in file order. describe("block conflicts on a real database", () => { let api: ExplorerApiForTest; let store: (b: BuiltBlock) => Promise; - let canonicalHash: (height: bigint) => Promise; - let orphanOf: ( - hash: HexString, - ) => Promise<{ hasOrphanedParent: boolean } | "active" | "absent">; - let owners: (txHash: HexString) => Promise<{ blockHash: HexString; isOrphaned: boolean }[]>; + let reads: Awaited>; beforeAll(async () => { api = await startExplorerApiForTest(); const { blockHandler } = await import( "../../src/events/received/on-block/index.js" ); - // Controllers, not routes: route reads are cached for a minute. - const { getBlock } = await import( - "../../src/svcs/database/controllers/l2block/get-block.js" - ); - const { getTxEffectOwners } = await import( - "../../src/svcs/database/controllers/l2block/delete.js" - ); - store = (b) => - deliver(blockHandler, { - block: b.hex, - blockNumber: Number(b.height), - statusHint: "proposed", - }); - canonicalHash = async (height) => (await getBlock(height))?.hash; - orphanOf = async (hash) => { - const block = await getBlock(hash); - if (!block) { - return "absent"; - } - return block.orphan - ? { hasOrphanedParent: block.orphan.hasOrphanedParent } - : "active"; - }; - owners = async (txHash) => - (await getTxEffectOwners([txHash])).map((o) => ({ - blockHash: o.blockHash, - isOrphaned: o.isOrphaned, - })); + reads = await loadChainReads(); + store = (b) => deliver(blockHandler, orderedEvent(b)); }); afterAll(async () => { await api?.close(); }); - it("skips a block whose tx an active block below holds, and keeps the block at its height", async () => { + it("skips a block whose tx a canonical block below holds, and keeps the block at its height", async () => { const t = freshTxHash(); const below = await buildBlock(100n, [t]); - const current = await buildBlock(101n, [freshTxHash()]); - const incoming = await buildBlock(101n, [t]); - expect(incoming.hash).not.toBe(current.hash); + const current = await buildBlock(101n, [freshTxHash()], { parent: below }); + const incoming = await buildBlock(101n, [t], { parent: below }); await store(below); await store(current); await expect(store(incoming)).resolves.toBeUndefined(); - expect(await canonicalHash(101n)).toBe(current.hash); - expect(await orphanOf(incoming.hash)).toBe("absent"); - expect(await owners(t)).toEqual([{ blockHash: below.hash, isOrphaned: false }]); - - await expect(store(incoming)).resolves.toBeUndefined(); - expect(await canonicalHash(101n)).toBe(current.hash); + expect(await reads.stateOf(current.hash)).toBe("canonical"); + expect(await reads.stateOf(incoming.hash)).toBe("absent"); + expect(await reads.ownerOf(t)).toBe(below.hash); }); - it("stores a reorg block that reuses the replaced block's tx, deleting the replaced block", async () => { + it("moves a tx the replacing block includes again, and keeps the replaced block", async () => { const t = freshTxHash(); const replaced = await buildBlock(200n, [t]); const incoming = await buildBlock(200n, [t]); - expect(incoming.hash).not.toBe(replaced.hash); await store(replaced); - expect(await owners(t)).toEqual([{ blockHash: replaced.hash, isOrphaned: false }]); - await expect(store(incoming)).resolves.toBeUndefined(); - expect(await canonicalHash(200n)).toBe(incoming.hash); - expect(await orphanOf(replaced.hash)).toBe("absent"); - expect(await owners(t)).toEqual([{ blockHash: incoming.hash, isOrphaned: false }]); + await store(incoming); + expect(await reads.stateOf(incoming.hash)).toBe("canonical"); + expect(await reads.stateOf(replaced.hash)).toEqual({ + hasOrphanedParent: false, + }); + expect(await reads.ownerOf(t)).toBe(incoming.hash); + expect(await reads.isDropped(t)).toBe(false); }); - it("resolves a two-block reorg, then the redelivery of its second block", async () => { + it("records a two-block reorg once, then resolves the redelivery of its second block", async () => { const t2 = freshTxHash(); const old300 = await buildBlock(300n, [freshTxHash()]); - const old301 = await buildBlock(301n, [t2]); + const old301 = await buildBlock(301n, [t2], { parent: old300 }); const new300 = await buildBlock(300n, [freshTxHash()]); - const new301 = await buildBlock(301n, [t2]); - expect(new300.hash).not.toBe(old300.hash); - expect(new301.hash).not.toBe(old301.hash); + const new301 = await buildBlock(301n, [t2], { parent: new300 }); await store(old300); await store(old301); - await expect(store(new300)).resolves.toBeUndefined(); - expect(await canonicalHash(300n)).toBe(new300.hash); - expect(await canonicalHash(301n)).toBeUndefined(); - expect(await orphanOf(old300.hash)).toEqual({ hasOrphanedParent: false }); - expect(await orphanOf(old301.hash)).toEqual({ hasOrphanedParent: true }); - expect(await owners(t2)).toEqual([{ blockHash: old301.hash, isOrphaned: true }]); + await store(new300); + expect(await reads.stateOf(new300.hash)).toBe("canonical"); + expect(await reads.stateOf(old300.hash)).toEqual({ + hasOrphanedParent: false, + }); + expect(await reads.stateOf(old301.hash)).toEqual({ + hasOrphanedParent: true, + }); + expect(await reads.ownerOf(t2)).toBe(old301.hash); - await expect(store(new301)).resolves.toBeUndefined(); + await store(new301); const settled = async () => { - expect(await canonicalHash(300n)).toBe(new300.hash); - expect(await canonicalHash(301n)).toBe(new301.hash); - expect(await orphanOf(old301.hash)).toBe("absent"); - expect(await orphanOf(old300.hash)).toEqual({ hasOrphanedParent: false }); - expect(await owners(t2)).toEqual([{ blockHash: new301.hash, isOrphaned: false }]); + expect(await reads.stateOf(new301.hash)).toBe("canonical"); + expect(await reads.stateOf(old301.hash)).toEqual({ + hasOrphanedParent: true, + }); + expect(await reads.ownerOf(t2)).toBe(new301.hash); + expect(await reads.listed([old300, old301])).toEqual([ + { orphanedBlockHash: old300.hash, height: 300n, nbrOfOrphanedBlocks: 2 }, + ]); }; await settled(); - await expect(store(new301)).resolves.toBeUndefined(); + await store(new301); await settled(); }); }); diff --git a/services/explorer-api/tests/integration/rollup-version-scoping.integration.test.ts b/services/explorer-api/tests/integration/rollup-version-scoping.integration.test.ts index 4760ed06..927058ce 100644 --- a/services/explorer-api/tests/integration/rollup-version-scoping.integration.test.ts +++ b/services/explorer-api/tests/integration/rollup-version-scoping.integration.test.ts @@ -2,7 +2,12 @@ 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, freshTxHash } from "./support/blocks.js"; +import { + type BuiltBlock, + buildBlock, + freshTxHash, + orderedEvent, +} from "./support/blocks.js"; import { type ExplorerApiForTest, startExplorerApiForTest, @@ -43,7 +48,11 @@ describe("reads scoped to the current rollup version on a real database", () => let storedTips: () => Promise<{ degradedReason?: string; proposed: { number: number } } | null>; let current: BuiltBlock[]; let old: BuiltBlock[]; - let store: (height: bigint, version: number) => Promise; + let store: ( + height: bigint, + version: number, + parent?: BuiltBlock, + ) => Promise; let orphanOf: ( hash: HexString, ) => Promise<{ hasOrphanedParent: boolean } | "active" | "absent">; @@ -128,25 +137,25 @@ describe("reads scoped to the current rollup version on a real database", () => }, }); - store = async (height, version) => { - const block = await buildBlock(height, [freshTxHash()], { version }); - await deliver(blockHandler, { - block: block.hex, - blockNumber: Number(block.height), - statusHint: "proposed", + store = async (height, version, parent) => { + const block = await buildBlock(height, [freshTxHash()], { + version, + parent, }); + await deliver(blockHandler, orderedEvent(block)); return block; }; // Stored first, so a lookup at height 1 that ignores the version meets it // before the current block. old = [await store(1n, OLD)]; - current = [await store(1n, CURRENT), await store(2n, CURRENT)]; - const replaced = await store(3n, CURRENT); - current.push(await store(3n, CURRENT)); + current = [await store(1n, CURRENT)]; + current.push(await store(2n, CURRENT, current[0])); + const replaced = await store(3n, CURRENT, current[1]); + current.push(await store(3n, CURRENT, current[1])); // Old blocks arriving after current ones at the same heights, as a // replayed backlog would, are not a reorg of the current chain. for (const height of [2n, 3n, 4n, 5n]) { - old.push(await store(height, OLD)); + old.push(await store(height, OLD, old[old.length - 1])); } expect((await getBlock(replaced.hash))?.orphan).toBeDefined(); orphanOf = async (hash) => { @@ -318,10 +327,10 @@ describe("reads scoped to the current rollup version on a real database", () => // The two reorg cases change the seed, so they run last. it("orphans only current-version blocks on a reorg of the current chain", async () => { - const [, block2, block3] = current; + const [block1, block2, block3] = current; const oldAbove = old.filter((b) => b.height > 2n); - await store(2n, CURRENT); + await store(2n, CURRENT, block1); expect(await orphanOf(block2.hash)).toEqual({ hasOrphanedParent: false }); expect(await orphanOf(block3.hash)).toEqual({ hasOrphanedParent: true }); diff --git a/services/explorer-api/tests/integration/support/chain.ts b/services/explorer-api/tests/integration/support/chain.ts new file mode 100644 index 00000000..dd22c484 --- /dev/null +++ b/services/explorer-api/tests/integration/support/chain.ts @@ -0,0 +1,148 @@ +import { type HexString } from "@chicmoz-pkg/types"; +import { type BuiltBlock } from "./blocks.js"; + +export type Head = { height: bigint; hash: HexString }; + +export const heads = (blocks: BuiltBlock[]): Head[] => + blocks.map(({ height, hash }) => ({ height, hash })); + +export type BlockState = "canonical" | "absent" | { hasOrphanedParent: boolean }; + +export type ReorgRecord = { active: boolean; blocks: HexString[] }; + +export type ListedReorg = { + orphanedBlockHash: HexString; + height: bigint; + nbrOfOrphanedBlocks: number; +}; + +/** + * Chain state read straight from the database: route reads are cached, and + * the block reads skip blocks without a body. Call after + * startExplorerApiForTest, like any explorer-api import. + */ +export const loadChainReads = async () => { + const { getDb } = await import("@chicmoz-pkg/postgres-helper"); + const { and, asc, eq, isNull } = await import("drizzle-orm"); + const { body, l2Block, txEffect } = await import( + "../../../src/svcs/database/schema/l2block/index.js" + ); + const { droppedTx } = await import( + "../../../src/svcs/database/schema/dropped-tx/index.js" + ); + const { l2ReorgBlockTable, l2ReorgTable } = await import( + "../../../src/svcs/database/schema/l2/reorg.js" + ); + const { l2OpenGapTable } = await import( + "../../../src/svcs/database/schema/l2/open-gap.js" + ); + const { getReorgs } = await import( + "../../../src/svcs/database/controllers/l2block/get-block.js" + ); + const db = getDb(); + + /** The canonical blocks of a rollup version, lowest first. */ + const chainOf = (version: number): Promise => + db + .select({ height: l2Block.height, hash: l2Block.hash }) + .from(l2Block) + .where(and(eq(l2Block.version, version), isNull(l2Block.orphan_timestamp))) + .orderBy(asc(l2Block.height)); + + const stateOf = async (hash: HexString): Promise => { + const [row] = await db + .select({ + orphanTimestamp: l2Block.orphan_timestamp, + hasOrphanedParent: l2Block.orphan_hasOrphanedParent, + }) + .from(l2Block) + .where(eq(l2Block.hash, hash)); + if (!row) { + return "absent"; + } + return row.orphanTimestamp === null + ? "canonical" + : { hasOrphanedParent: row.hasOrphanedParent ?? false }; + }; + + /** The block whose body holds the tx effect. */ + const ownerOf = async (txHash: HexString): Promise => { + const [row] = await db + .select({ blockHash: body.blockHash }) + .from(txEffect) + .innerJoin(body, eq(txEffect.bodyId, body.id)) + .where(eq(txEffect.txHash, txHash)); + return row?.blockHash; + }; + + const isDropped = async (txHash: HexString) => + ( + await db + .select({ txHash: droppedTx.txHash }) + .from(droppedTx) + .where(eq(droppedTx.txHash, txHash)) + ).length > 0; + + /** The reorg records of a rollup version, oldest first, blocks by height. */ + const recordsOf = async (version: number): Promise => { + const rows = await db + .select({ + id: l2ReorgTable.id, + revivedAt: l2ReorgTable.revivedAt, + hash: l2ReorgBlockTable.hash, + }) + .from(l2ReorgTable) + .innerJoin(l2ReorgBlockTable, eq(l2ReorgBlockTable.reorgId, l2ReorgTable.id)) + .where(eq(l2ReorgTable.rollupVersion, version)) + .orderBy( + asc(l2ReorgTable.id), + asc(l2ReorgBlockTable.height), + asc(l2ReorgBlockTable.hash), + ); + const records = new Map(); + for (const row of rows) { + const record = records.get(row.id) ?? { + active: row.revivedAt === null, + blocks: [], + }; + record.blocks.push(row.hash); + records.set(row.id, record); + } + return [...records.values()]; + }; + + /** The `/l2/reorgs` entries that show one of `blocks`. */ + const listed = async (blocks: BuiltBlock[]): Promise => + (await getReorgs()) + .filter((r) => blocks.some((b) => b.hash === r.orphanedBlockHash)) + .map(({ orphanedBlockHash, height, nbrOfOrphanedBlocks }) => ({ + orphanedBlockHash, + height, + nbrOfOrphanedBlocks, + })); + + const repairOpen = async (height: number) => + ( + await db + .select({ id: l2OpenGapTable.id }) + .from(l2OpenGapTable) + .where( + and( + eq(l2OpenGapTable.reason, "reorg_repair"), + eq(l2OpenGapTable.fromHeight, height), + eq(l2OpenGapTable.toHeight, height), + eq(l2OpenGapTable.status, "open"), + ), + ) + ).length > 0; + + return { + chainOf, + stateOf, + ownerOf, + isDropped, + recordsOf, + listed, + repairOpen, + }; +}; diff --git a/services/explorer-api/tests/integration/support/recorded-blocks.ts b/services/explorer-api/tests/integration/support/recorded-blocks.ts index c16f6149..244d1793 100644 --- a/services/explorer-api/tests/integration/support/recorded-blocks.ts +++ b/services/explorer-api/tests/integration/support/recorded-blocks.ts @@ -19,19 +19,24 @@ import { join } from "node:path"; // explorer-api modules read their environment at import, so everything from // src is imported dynamically, after startExplorerApiForTest(). -/** The recorded blocks of one source in chain order, as aztec-listener publishes them. */ -export const recordedBlocks = (source: FixtureSource) => - listFixtures(source, "l2-block") - .map((name) => { - const { data } = loadFixture(source, "l2-block", name); +/** The recorded blocks of one source in chain order, as one ordered pass of aztec-listener. */ +export const recordedBlocks = (source: FixtureSource) => { + const fixtures = listFixtures(source, "l2-block").map( + (name) => [name, loadFixture(source, "l2-block", name).data] as const, + ); + const tip = Math.max(...fixtures.map(([, data]) => data.expected.height)); + return fixtures + .map(([name, data]) => { const event: NewBlockEvent = { blockNumber: data.expected.height, statusHint: "proposed", block: data.hex, + ordered: { tip }, }; return { name, expected: data.expected, event }; }) .sort((a, b) => a.expected.height - b.expected.height); +}; /** Bytecode, artifacts and class-publish logs run to hundreds of kilobytes per copy. */ const BULKY_KEYS = new Set([ diff --git a/services/explorer-api/tests/unit/block-tx-conflict.test.ts b/services/explorer-api/tests/unit/block-tx-conflict.test.ts deleted file mode 100644 index 47c27de3..00000000 --- a/services/explorer-api/tests/unit/block-tx-conflict.test.ts +++ /dev/null @@ -1,283 +0,0 @@ -import { type NewBlockEvent } from "@chicmoz-pkg/message-registry"; -import { beforeEach, describe, expect, it, vi } from "vitest"; - -const mocks = vi.hoisted(() => ({ - logger: { debug: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() }, - store: vi.fn<() => Promise>(), - markOpenGapsFulfilledByHeight: vi.fn(() => Promise.resolve()), - removePendingAndDroppedTx: vi.fn(() => Promise.resolve()), - storeContracts: vi.fn(() => Promise.resolve()), - deleteL2BlockByHash: vi.fn(() => Promise.resolve()), - deleteL2BlockByHeight: vi.fn(() => Promise.resolve()), - getTxEffectOwners: vi.fn(), - unOrphanBlock: vi.fn(() => Promise.resolve()), - detectReorg: vi.fn(() => Promise.resolve(false)), - handleReorg: vi.fn(() => Promise.resolve()), - parseBlock: vi.fn(), -})); - -vi.mock("../../src/environment.js", () => ({ L2_NETWORK_ID: "SANDBOX" })); -vi.mock("../../src/logger.js", () => ({ logger: mocks.logger })); -vi.mock("@chicmoz-pkg/backend-utils", () => ({ - blockFromBuffer: () => ({}), - parseBlock: mocks.parseBlock, -})); -vi.mock("../../src/svcs/database/index.js", () => ({ - controllers: { - l2Block: { - store: mocks.store, - markOpenGapsFulfilledByHeight: mocks.markOpenGapsFulfilledByHeight, - }, - l2Tx: { removePendingAndDroppedTx: mocks.removePendingAndDroppedTx }, - }, -})); -vi.mock("../../src/svcs/database/controllers/l2block/delete.js", () => ({ - deleteL2BlockByHash: mocks.deleteL2BlockByHash, - deleteL2BlockByHeight: mocks.deleteL2BlockByHeight, - getTxEffectOwners: mocks.getTxEffectOwners, -})); -vi.mock("../../src/svcs/database/controllers/l2block/orphan.js", () => ({ - unOrphanBlock: mocks.unOrphanBlock, -})); -vi.mock( - "../../src/svcs/database/controllers/l2/chain-info/rollup-version-cache.js", - () => ({ observeRollupVersion: () => Promise.resolve() }), -); -vi.mock("../../src/events/received/on-block/contracts.js", () => ({ - storeContracts: mocks.storeContracts, -})); -vi.mock("../../src/events/received/on-block/reorg-handler.js", () => ({ - detectReorg: mocks.detectReorg, - handleReorg: mocks.handleReorg, -})); - -const { blockHandler, catchupHandler } = await import( - "../../src/events/received/on-block/index.js" -); - -const noHeartbeat = () => Promise.resolve(); - -// Block 103158 from the 2026-09-29 incident: its tx was held by the active, -// stale-fork block 103172. -const parsed = () => ({ - height: 103158n, - hash: "0x0394", - header: { globalVariables: { version: 4248422647 } }, - body: { txEffects: [{ txHash: "0x2ba1" }, { txHash: "0x2ba2" }] }, -}); -const event: NewBlockEvent = { - block: "00", - blockNumber: 103158, - statusHint: "proposed", -}; -const txHashConflict = { - code: "23505", - detail: "Key (tx_hash)=(0x2ba1) already exists.", -}; -const owner = (overrides: object) => ({ - txHash: "0x2ba1", - blockHash: "0x2c3d", - blockHeight: 103172n, - rollupVersion: 4248422647, - isOrphaned: false, - ...overrides, -}); -const hooks = () => [ - mocks.markOpenGapsFulfilledByHeight, - mocks.storeContracts, - mocks.removePendingAndDroppedTx, -]; - -beforeEach(() => { - vi.clearAllMocks(); - mocks.detectReorg.mockResolvedValue(false); - mocks.parseBlock.mockImplementation(() => Promise.resolve(parsed())); - mocks.store - .mockReset() - .mockRejectedValueOnce(txHashConflict) - .mockResolvedValue(undefined); -}); - -describe("a tx held by an active block", () => { - it.each([ - ["live", () => blockHandler.cb(event, noHeartbeat)], - ["catch-up", () => catchupHandler.cb(event, noHeartbeat)], - ])( - "skips the %s block: acked, nothing stored or deleted, logged", - async (_name, run) => { - mocks.getTxEffectOwners.mockResolvedValue([owner({})]); - - await expect(run()).resolves.toBeUndefined(); - - // Decided before any write: not even an insert attempt. - expect(mocks.store).not.toHaveBeenCalled(); - expect(mocks.deleteL2BlockByHash).not.toHaveBeenCalled(); - for (const hook of hooks()) { - expect(hook).not.toHaveBeenCalled(); - } - expect(mocks.logger.error).toHaveBeenCalledWith( - "SKIPPED_BLOCK_TX_CONFLICT height=103158 hash=0x0394 owners=0x2ba1 in active block 103172 (0x2c3d)", - ); - }, - ); - - it("skips without pruning the orphaned holders among them either", async () => { - mocks.getTxEffectOwners.mockResolvedValue([ - owner({ blockHash: "0xorphan", isOrphaned: true }), - owner({ txHash: "0x2ba2" }), - ]); - - await expect(blockHandler.cb(event, noHeartbeat)).resolves.toBeUndefined(); - - expect(mocks.deleteL2BlockByHash).not.toHaveBeenCalled(); - expect(mocks.store).not.toHaveBeenCalled(); - }); -}); - -describe("a holder that turns active between the check and the insert", () => { - it("is still skipped, as the conflict's outcome, with no hooks", async () => { - mocks.getTxEffectOwners - .mockResolvedValueOnce([]) - .mockResolvedValue([owner({})]); - - await expect(blockHandler.cb(event, noHeartbeat)).resolves.toBeUndefined(); - - expect(mocks.store).toHaveBeenCalledOnce(); - expect(mocks.deleteL2BlockByHash).not.toHaveBeenCalled(); - for (const hook of hooks()) { - expect(hook).not.toHaveBeenCalled(); - } - expect(mocks.logger.error).toHaveBeenCalledWith( - expect.stringMatching(/^SKIPPED_BLOCK_TX_CONFLICT /), - ); - }); -}); - -describe("a reorg at the block's height", () => { - beforeEach(() => { - mocks.detectReorg.mockResolvedValue(true); - }); - - it("lets its own reorg orphan an active holder above it, then prunes it and stores", async () => { - const holders = [owner({ blockHeight: 103159n })]; - mocks.getTxEffectOwners.mockImplementation(() => - Promise.resolve(holders.map((holder) => ({ ...holder }))), - ); - // handleReorg orphans the block at the height and the ones above it. - mocks.handleReorg.mockImplementation(() => { - holders[0] = { ...holders[0], isOrphaned: true }; - return Promise.resolve(); - }); - - await blockHandler.cb(event, noHeartbeat); - - expect(mocks.handleReorg).toHaveBeenCalled(); - expect(mocks.deleteL2BlockByHash).toHaveBeenCalledWith("0x2c3d"); - expect(mocks.store).toHaveBeenCalledTimes(2); - expect(mocks.logger.error).not.toHaveBeenCalled(); - }); - - it.each([ - ["below the height", owner({ blockHeight: 103157n })], - ["on another rollup version", owner({ rollupVersion: 1 })], - ])( - "skips before the reorg writes anything when the holder is %s", - async (_name, holder) => { - mocks.getTxEffectOwners.mockResolvedValue([holder]); - - await expect( - blockHandler.cb(event, noHeartbeat), - ).resolves.toBeUndefined(); - - expect(mocks.handleReorg).not.toHaveBeenCalled(); - expect(mocks.store).not.toHaveBeenCalled(); - expect(mocks.logger.error).toHaveBeenCalledWith( - expect.stringMatching(/^SKIPPED_BLOCK_TX_CONFLICT height=103158 /), - ); - }, - ); -}); - -describe("the block itself already stored and active (redelivery)", () => { - it("is not a conflict: the duplicate hash counts as stored and the hooks run", async () => { - mocks.getTxEffectOwners.mockResolvedValue([ - owner({ blockHash: "0x0394", blockHeight: 103158n }), - ]); - mocks.store.mockReset().mockRejectedValue({ - code: "23505", - detail: "Key (hash)=(0x0394) already exists.", - }); - - await blockHandler.cb(event, noHeartbeat); - - expect(mocks.unOrphanBlock).toHaveBeenCalledWith("0x0394"); - for (const hook of hooks()) { - expect(hook).toHaveBeenCalledOnce(); - } - }); -}); - -describe("a duplicate on a key the handler does not know", () => { - it("does not count as stored: no hooks, logged", async () => { - mocks.getTxEffectOwners.mockResolvedValue([]); - mocks.store.mockReset().mockRejectedValue({ - code: "23505", - detail: "Key (address)=(0x01) already exists.", - }); - - await expect(blockHandler.cb(event, noHeartbeat)).resolves.toBeUndefined(); - - for (const hook of hooks()) { - expect(hook).not.toHaveBeenCalled(); - } - expect(mocks.logger.error).toHaveBeenCalledWith( - expect.stringContaining("DB duplicate on an unexpected key"), - ); - }); -}); - -describe("txs held only by orphaned blocks (multi-block reorg)", () => { - it("prunes them and stores the rebuilt block", async () => { - // A reorg at 103157 orphaned 103157-103159; the rebuilt 103158 - // re-includes txs from the old 103158 and 103159. - mocks.getTxEffectOwners.mockResolvedValue([ - owner({ - blockHash: "0xold-103158", - blockHeight: 103158n, - isOrphaned: true, - }), - owner({ - txHash: "0x2ba2", - blockHash: "0xold-103159", - blockHeight: 103159n, - isOrphaned: true, - }), - ]); - - await blockHandler.cb(event, noHeartbeat); - - expect(mocks.deleteL2BlockByHash.mock.calls).toEqual([ - ["0xold-103158"], - ["0xold-103159"], - ]); - expect(mocks.store).toHaveBeenCalledTimes(2); - for (const hook of hooks()) { - expect(hook).toHaveBeenCalledOnce(); - } - }); -}); - -describe("store errors that are not duplicates", () => { - it("are rethrown so the message bus redelivers the block", async () => { - mocks.store.mockReset().mockRejectedValue(new Error("connection reset")); - - await expect(blockHandler.cb(event, noHeartbeat)).rejects.toThrow( - "connection reset", - ); - - expect(mocks.store).toHaveBeenCalledOnce(); - for (const hook of hooks()) { - expect(hook).not.toHaveBeenCalled(); - } - }); -}); diff --git a/services/explorer-api/tests/unit/duplicate-block-error.test.ts b/services/explorer-api/tests/unit/duplicate-block-error.test.ts deleted file mode 100644 index 5a8fc84e..00000000 --- a/services/explorer-api/tests/unit/duplicate-block-error.test.ts +++ /dev/null @@ -1,107 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from "vitest"; - -const mocks = vi.hoisted(() => ({ - error: vi.fn(), - info: vi.fn(), - warn: vi.fn(), -})); - -vi.mock("../../src/logger.js", () => ({ - logger: mocks, -})); - -const { handleDuplicateBlockError } = await import( - "../../src/events/received/utils.js" -); - -const duplicate = (detail: string) => ({ code: "23505", detail }); -const callbacks = (resolves = true) => ({ - deleteIncomingHeight: vi.fn<() => Promise>(() => Promise.resolve()), - unOrphan: vi.fn<() => Promise>(() => Promise.resolve()), - resolveDuplicateTxOwner: vi.fn<() => Promise>(() => - Promise.resolve(resolves), - ), -}); -const handle = ( - error: { code: string; detail: string }, - cb: ReturnType, -) => - handleDuplicateBlockError( - error, - "block 9897", - cb.deleteIncomingHeight, - cb.unOrphan, - cb.resolveDuplicateTxOwner, - ); - -beforeEach(() => { - mocks.error.mockClear(); - mocks.info.mockClear(); - mocks.warn.mockClear(); -}); - -describe("handleDuplicateBlockError", () => { - it("uses the tx owner resolver for duplicate tx_hash errors", async () => { - const cb = callbacks(); - - const outcome = await handle( - duplicate("Key (tx_hash)=(0xabc) already exists."), - cb, - ); - - expect(outcome).toBe("retry"); - expect(cb.resolveDuplicateTxOwner).toHaveBeenCalledOnce(); - expect(cb.deleteIncomingHeight).not.toHaveBeenCalled(); - expect(cb.unOrphan).not.toHaveBeenCalled(); - }); - - it("skips when the tx owner resolver cannot clear the conflict", async () => { - await expect( - handle( - duplicate("Key (tx_hash)=(0xabc) already exists."), - callbacks(false), - ), - ).resolves.toBe("skip"); - }); - - it("keeps the existing height-delete retry path for duplicate height errors", async () => { - const cb = callbacks(); - - const outcome = await handle( - duplicate("Key (height)=(9897) already exists."), - cb, - ); - - expect(outcome).toBe("retry"); - expect(cb.deleteIncomingHeight).toHaveBeenCalledOnce(); - expect(cb.resolveDuplicateTxOwner).not.toHaveBeenCalled(); - }); - - it("un-orphans an existing block with the same hash, which counts as stored", async () => { - const cb = callbacks(); - - const outcome = await handle( - duplicate("Key (hash)=(0x0394) already exists."), - cb, - ); - - expect(outcome).toBe("done"); - expect(cb.unOrphan).toHaveBeenCalledOnce(); - }); - - it("does not count a duplicate on an unexpected key as stored", async () => { - const cb = callbacks(); - - const outcome = await handle( - duplicate("Key (address)=(0x01) already exists."), - cb, - ); - - expect(outcome).toBe("skip"); - expect(mocks.error).toHaveBeenCalledWith( - expect.stringContaining("DB duplicate on an unexpected key"), - ); - expect(cb.unOrphan).not.toHaveBeenCalled(); - expect(cb.deleteIncomingHeight).not.toHaveBeenCalled(); - }); -}); From fb5e5a3597f07d573c860a04d569a2c9eed81210 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Thu, 26 Nov 2026 21:24:17 +0000 Subject: [PATCH 04/31] test(explorer-api): cover a replaced block that stays stored The cases of 6fd18994, on the new rules: the stream's blocks go in as ordered blocks and the late copy as a catch-up block. A replacing chain stays canonical when its block at the replaced height arrives after its children, and a block's txs stop being listed as dropped once it is canonical again. The third case, a replaced height still requested after the next tips validate elsewhere, is still marked as failing. Co-Authored-By: Claude Opus 5.5 --- .../late-replacing-block.integration.test.ts | 164 ++++++++++++++++++ 1 file changed, 164 insertions(+) create mode 100644 services/explorer-api/tests/integration/late-replacing-block.integration.test.ts 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 new file mode 100644 index 00000000..bd3e0b91 --- /dev/null +++ b/services/explorer-api/tests/integration/late-replacing-block.integration.test.ts @@ -0,0 +1,164 @@ +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, + catchupEvent, + freshTxHash, + 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")}`; + +// A block at a height the chain replaced can stay stored while the replacing +// chain's next blocks are stored above it. Every canonical block of the +// version above an ordered block's tip is demoted, so the cases use +// ascending, disjoint heights, in file order. it.fails marks the current +// behaviour; drop it once fixed. +describe("a replaced block that stays stored on a real database", () => { + let api: ExplorerApiForTest; + let store: (b: BuiltBlock) => Promise; + let storeLate: (b: BuiltBlock) => Promise; + let canonicalHash: (height: bigint) => Promise; + let orphanOf: ( + hash: HexString, + ) => Promise<{ hasOrphanedParent: boolean } | "active" | "absent">; + let isDropped: (txHash: HexString) => Promise; + let storeTips: ( + tips: Pick & { + finalized: BuiltBlock; + proven: BuiltBlock; + checkpointed: BuiltBlock; + }, + ) => Promise; + let repairRequestCovers: (height: number) => Promise; + + beforeAll(async () => { + api = await startExplorerApiForTest(); + const { blockHandler, catchupHandler } = 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 { getDroppedTxByHash } = await import( + "../../src/svcs/database/controllers/dropped-tx/get-tx.js" + ); + const { buildTipBoundaryRepairRequest } = await import( + "../../src/svcs/database/controllers/l2block/missing-ranges.js" + ); + store = (b) => deliver(blockHandler, orderedEvent(b)); + storeLate = (b) => deliver(catchupHandler, catchupEvent(b)); + canonicalHash = async (height) => (await getBlock(height))?.hash; + orphanOf = async (hash) => { + const block = await getBlock(hash); + if (!block) { + return "absent"; + } + return block.orphan + ? { hasOrphanedParent: block.orphan.hasOrphanedParent } + : "active"; + }; + isDropped = async (txHash) => (await getDroppedTxByHash(txHash)) !== null; + const at = (block: BuiltBlock) => ({ + block: { number: Number(block.height), hash: block.hash }, + checkpoint: { number: Number(block.height), hash: word(Number(block.height)) }, + }); + storeTips = ({ proposed, finalized, proven, checkpointed }) => + deliver(l2TipsHandler, { + tips: { + proposed, + checkpointed: at(checkpointed), + proven: at(proven), + finalized: at(finalized), + }, + observedAt: Date.now(), + source: { rpcNodeName: "node", aztecNodeVersion: "test" }, + } satisfies L2TipsEvent); + repairRequestCovers = async (height) => { + const planned = await buildTipBoundaryRepairRequest(); + return ( + planned?.request.ranges.some( + (range) => range.from <= height && height <= range.to, + ) ?? false + ); + }; + }); + + afterAll(async () => { + await api?.close(); + }); + + it("keeps the replacing chain's stored blocks active when its block at the replaced height arrives after them", async () => { + const replaced = await buildBlock(100n, [freshTxHash()]); + const replacing = await buildBlock(100n, [freshTxHash()]); + const child = await buildBlock(101n, [freshTxHash()], { parent: replacing }); + const grandchild = await buildBlock(102n, [freshTxHash()], { parent: child }); + await store(replaced); + await store(child); + await store(grandchild); + + await storeLate(replacing); + + expect(await orphanOf(replaced.hash)).toEqual({ hasOrphanedParent: false }); + expect( + await Promise.all([100n, 101n, 102n].map((h) => canonicalHash(h))), + ).toEqual([replacing.hash, child.hash, grandchild.hash]); + }); + + it("stops listing a block's txs as dropped once that block is canonical again", async () => { + const t = freshTxHash(); + const first = await buildBlock(200n, [t]); + const second = await buildBlock(200n, [freshTxHash()]); + await store(first); + await store(second); + expect(await isDropped(t)).toBe(true); + + await store(first); + + expect(await canonicalHash(200n)).toBe(first.hash); + 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 }); + 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); + }); +}); From d1c655e722ecd1bf3ccac11d2d61f13d119ad034 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Thu, 26 Nov 2026 21:24:36 +0000 Subject: [PATCH 05/31] test(explorer-api): cover the chain rules, their bounds and repair requests One case per rule of ordered and catch-up blocks, each on its own rollup version: replacement and the tip, replays and flips, gaps, final catch-up blocks, walks that bring blocks back, records and their revival, tx holders above a gap, ambiguous parents, unordered events and concurrent consumers. The bound cases run on bare chains inserted in bulk: a 10,000-step walk keeps its partition in a consumer group whose session is shorter than the walk, and rolls back when a heartbeat fails; more canonical blocks above a tip than the bound throw; a lock wait over 10 s rethrows. The gap scheduler requests a repair row while its block is present, until a block message fulfils it. Co-Authored-By: Claude Opus 5.5 --- .../chain-head.integration.test.ts | 616 ++++++++++++++++++ .../integration/open-gap.integration.test.ts | 25 +- 2 files changed, 637 insertions(+), 4 deletions(-) create mode 100644 services/explorer-api/tests/integration/chain-head.integration.test.ts diff --git a/services/explorer-api/tests/integration/chain-head.integration.test.ts b/services/explorer-api/tests/integration/chain-head.integration.test.ts new file mode 100644 index 00000000..44c30624 --- /dev/null +++ b/services/explorer-api/tests/integration/chain-head.integration.test.ts @@ -0,0 +1,616 @@ +import { type Heartbeat } from "@chicmoz-pkg/message-bus"; +import { type NewBlockEvent } from "@chicmoz-pkg/message-registry"; +import { deliver } from "@chicmoz/test-harness"; +import { BSON } from "bson"; +import { type SQL } from "drizzle-orm"; +import { Kafka, logLevel } from "kafkajs"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { + type BuiltBlock, + buildBlock, + buildChain, + catchupEvent, + freshTxHash, + orderedEvent, +} from "./support/blocks.js"; +import { heads, loadChainReads } from "./support/chain.js"; +import { + type ExplorerApiForTest, + startExplorerApiForTest, +} from "./support/explorer-api.js"; + +// Each case runs on a rollup version of its own, because an ordered block +// demotes every canonical block of its version above its tip, and on heights +// of its own, because repair rows are per network. +let lastVersion = 1_000; +const freshVersion = () => ++lastVersion; + +describe("the canonical chain on a real database", () => { + let api: ExplorerApiForTest; + let reads: Awaited>; + let ordered: (b: BuiltBlock, tip?: number) => Promise; + let catchup: (b: BuiltBlock, options?: { final?: true }) => Promise; + let orderedWith: (event: NewBlockEvent, heartbeat: Heartbeat) => Promise; + let ignoredUnordered: (b: BuiltBlock) => Promise; + let setOrphaned: (blocks: BuiltBlock[], orphaned: boolean) => Promise; + let bareChain: (chain: { + version: number; + from: bigint; + count: number; + parent?: BuiltBlock; + }) => Promise; + let throughBroker: ( + event: NewBlockEvent, + ) => Promise<{ deliveries: number; rebalances: number; beats: number }>; + let holdChainLock: () => Promise<() => Promise>; + let walkBound: number; + + beforeAll(async () => { + api = await startExplorerApiForTest(); + const { blockHandler, catchupHandler } = await import( + "../../src/events/received/on-block/index.js" + ); + const { WALK_BOUND, withChainLock } = await import( + "../../src/svcs/database/controllers/l2block/canonical.js" + ); + const { l2Block } = await import( + "../../src/svcs/database/schema/l2block/index.js" + ); + const { getDb } = await import("@chicmoz-pkg/postgres-helper"); + const { inArray, sql } = await import("drizzle-orm"); + const db = getDb(); + reads = await loadChainReads(); + walkBound = WALK_BOUND; + + ordered = (b, tip) => deliver(blockHandler, orderedEvent(b, tip)); + catchup = (b, options) => deliver(catchupHandler, catchupEvent(b, options)); + orderedWith = (event, heartbeat) => blockHandler.cb(event, heartbeat); + ignoredUnordered = (b) => + deliver(blockHandler, { + block: b.hex, + blockNumber: Number(b.height), + statusHint: "proposed", + } satisfies NewBlockEvent); + setOrphaned = async (blocks, orphaned) => { + await db + .update(l2Block) + .set({ + orphan_timestamp: orphaned ? Date.now() : null, + orphan_hasOrphanedParent: orphaned ? false : null, + }) + .where( + inArray( + l2Block.hash, + blocks.map((b) => b.hash), + ), + ); + }; + // Canonical blocks with only the rows a link lookup reads, inserted in + // bulk: delivering thousands of blocks would take minutes. + bareChain = async ({ version, from, count, parent }) => { + const to = from + BigInt(count - 1); + const tag = version.toString(16).padStart(8, "0"); + const hashOf = (n: SQL) => + sql`'0x' || ${tag}::text || '00' || lpad(to_hex(${n}), 54, '0')`; + const rootOf = (n: SQL) => + sql`'0x' || ${tag}::text || 'ff' || lpad(to_hex(${n}), 54, '0')`; + const n = sql`n`; + const heights = sql`generate_series(${from}::bigint, ${to}::bigint) AS n`; + await db.execute( + sql`INSERT INTO "l2Block" ("hash", "height", "version") SELECT ${hashOf(n)}, n, ${version}::bigint FROM ${heights}`, + ); + await db.execute( + sql`INSERT INTO "archive" ("root", "next_available_leaf_index", "block_hash") SELECT ${rootOf(n)}, 0, ${hashOf(n)} FROM ${heights}`, + ); + await db.execute( + sql`INSERT INTO "header" ("block_hash", "total_fees", "total_mana_used", "sponge_blob_hash") SELECT ${hashOf(n)}, 0, 0, '0x00' FROM ${heights}`, + ); + const height = sql`b."height"`; + const lowestLastArchive = parent + ? sql`${parent.archive.root.toString()}::text` + : rootOf(sql`${height} - 1`); + await db.execute( + sql`INSERT INTO "last_archive" ("root", "next_available_leaf_index", "header_id") + SELECT CASE WHEN ${height} = ${from}::bigint THEN ${lowestLastArchive} ELSE ${rootOf(sql`${height} - 1`)} END, 0, h."id" + FROM "header" h JOIN "l2Block" b ON b."hash" = h."block_hash" + WHERE b."version" = ${version}::bigint AND ${height} BETWEEN ${from}::bigint AND ${to}::bigint AND b."hash" = ${hashOf(height)}`, + ); + }; + const kafka = new Kafka({ + clientId: `${api.namespace}-chain-walk`, + brokers: [api.stack.env.KAFKA_CONNECTION], + sasl: { + mechanism: "plain", + username: api.stack.env.KAFKA_SASL_USERNAME, + password: api.stack.env.KAFKA_SASL_PASSWORD, + }, + logLevel: logLevel.NOTHING, + }); + // Two members of one group whose session is shorter than a long walk: + // only the handler's heartbeats keep the walking member, and losing it + // would hand the partition, and the message again, to the other. + throughBroker = async (event) => { + const topic = `${api.namespace}.chain-walk`; + const groupId = `${api.namespace}-chain-walk`; + const admin = kafka.admin(); + await admin.connect(); + await admin.createTopics({ + topics: [{ topic, numPartitions: 1 }], + waitForLeaders: true, + }); + const outcome = { deliveries: 0, rebalances: 0, beats: 0 }; + let sent = false; + let settle: (error?: unknown) => void = () => undefined; + const handled = new Promise((resolve, reject) => { + settle = (error) => (error === undefined ? resolve() : reject(error)); + }); + const members = [0, 1].map(() => + kafka.consumer({ groupId, sessionTimeout: 6_000, heartbeatInterval: 1_000 }), + ); + try { + for (const member of members) { + member.on(member.events.REBALANCING, () => { + if (sent) { + outcome.rebalances++; + } + }); + await member.connect(); + await member.subscribe({ topic, fromBeginning: true }); + await member.run({ + eachMessage: async ({ message, heartbeat }) => { + outcome.deliveries++; + try { + await blockHandler.cb( + BSON.deserialize(message.value ?? Buffer.alloc(0)) as NewBlockEvent, + () => { + outcome.beats++; + return heartbeat(); + }, + ); + settle(); + } catch (e) { + settle(e); + throw e; + } + }, + }); + } + const deadline = Date.now() + 30_000; + for (;;) { + const { + groups: [group], + } = await admin.describeGroups([groupId]); + if (group?.state === "Stable" && group.members.length === 2) { + break; + } + if (Date.now() > deadline) { + throw new Error(`group ${groupId} never settled with both members`); + } + await new Promise((resolve) => setTimeout(resolve, 100)); + } + sent = true; + const producer = kafka.producer(); + await producer.connect(); + await producer.send({ + topic, + messages: [{ value: Buffer.from(BSON.serialize(event)) }], + }); + await producer.disconnect(); + await handled; + // Leaving the group below rebalances it too. + return { ...outcome }; + } finally { + for (const member of members) { + await member.disconnect(); + } + 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; + }; + }; + }); + + afterAll(async () => { + await api?.close(); + }); + + it("replaces the block at its height and its linked descendants, and demotes every block above its tip, in one record", async () => { + const version = freshVersion(); + const a = await buildChain(1_000n, 4, { version }); + const above = await buildBlock(1_005n, [freshTxHash()], { version }); + for (const block of [...a, above]) { + await ordered(block); + } + const b1 = await buildBlock(1_001n, [freshTxHash()], { + version, + parent: a[0], + }); + + await ordered(b1, 1_002); + + expect(await reads.chainOf(version)).toEqual(heads([a[0], b1])); + expect(await reads.recordsOf(version)).toEqual([ + { active: true, blocks: [a[1], a[2], a[3], above].map((b) => b.hash) }, + ]); + expect( + await Promise.all([a[1], a[2], above].map((b) => reads.stateOf(b.hash))), + ).toEqual([ + { hasOrphanedParent: false }, + { hasOrphanedParent: true }, + { hasOrphanedParent: false }, + ]); + }); + + it("changes nothing for an ordered block already canonical, and ends a replay and a flip with the listener's chain and one active record", async () => { + const version = freshVersion(); + const a = await buildChain(2_000n, 4, { version }); + const b = await buildChain(2_001n, 2, { version, parent: a[0] }); + const pass = async () => { + for (const block of a) { + await ordered(block); + } + for (const block of b) { + await ordered(block, 2_002); + } + }; + const active = async () => + (await reads.recordsOf(version)).filter((r) => r.active).map((r) => r.blocks); + await pass(); + expect(await reads.chainOf(version)).toEqual(heads([a[0], ...b])); + expect(await active()).toEqual([[a[1], a[2], a[3]].map((x) => x.hash)]); + + await ordered(b[1], 2_002); + expect(await reads.chainOf(version)).toEqual(heads([a[0], ...b])); + expect(await reads.recordsOf(version)).toHaveLength(1); + + await pass(); + expect(await reads.chainOf(version)).toEqual(heads([a[0], ...b])); + expect(await active()).toEqual([[a[1], a[2], a[3]].map((x) => x.hash)]); + + for (const block of a.slice(1)) { + await ordered(block, 2_003); + } + expect(await reads.chainOf(version)).toEqual(heads(a)); + expect(await active()).toEqual([b.map((x) => x.hash)]); + }); + + it("demotes the old blocks above the tip with the first replacing block, and those between a gap and the tip when the pass reaches them", async () => { + const version = freshVersion(); + const [a0, a1, missing, a3, a4] = await buildChain(3_000n, 5, { version }); + for (const block of [a0, a1, a3, a4]) { + await ordered(block); + } + expect(await reads.stateOf(missing.hash)).toBe("absent"); + const b = await buildChain(3_001n, 3, { version, parent: a0 }); + + await ordered(b[0], 3_003); + expect(await reads.chainOf(version)).toEqual(heads([a0, b[0], a3])); + expect(await reads.recordsOf(version)).toEqual([ + { active: true, blocks: [a1.hash, a4.hash] }, + ]); + + await ordered(b[1], 3_003); + await ordered(b[2], 3_003); + expect(await reads.chainOf(version)).toEqual(heads([a0, ...b])); + expect(await reads.recordsOf(version)).toEqual([ + { active: true, blocks: [a1.hash, a4.hash] }, + { active: true, blocks: [a3.hash] }, + ]); + }); + + it("never demotes the live chain above a gap for an ordered block below it", async () => { + const version = freshVersion(); + const live = await buildChain(4_000n, 4, { version }); + await ordered(live[2]); + await ordered(live[3]); + + await ordered(live[0], 4_003); + expect(await reads.chainOf(version)).toEqual( + heads([live[0], live[2], live[3]]), + ); + + await ordered(live[1], 4_003); + expect(await reads.chainOf(version)).toEqual(heads(live)); + expect(await reads.recordsOf(version)).toEqual([]); + }); + + it("keeps a final catch-up block at a canonical height off the chain until its ordered copy arrives", async () => { + const version = freshVersion(); + const a = await buildChain(5_000n, 3, { version }); + for (const block of a) { + await ordered(block); + } + const b1 = await buildBlock(5_001n, [freshTxHash()], { + version, + parent: a[0], + }); + + await catchup(b1, { final: true }); + expect(await reads.chainOf(version)).toEqual(heads(a)); + expect(await reads.recordsOf(version)).toEqual([]); + + await ordered(b1); + expect(await reads.chainOf(version)).toEqual(heads([a[0], b1])); + expect(await reads.recordsOf(version)).toEqual([ + { active: true, blocks: [a[1].hash, a[2].hash] }, + ]); + }); + + it("joins a catch-up block at an empty height only when the chain above descends from it, without demoting or recording", async () => { + const version = freshVersion(); + const c = await buildChain(6_000n, 4, { version }); + for (const block of [c[0], c[2], c[3]]) { + await ordered(block); + } + const stranger = await buildBlock(6_001n, [freshTxHash()], { + version, + parent: c[0], + }); + + await catchup(stranger, { final: true }); + expect(await reads.stateOf(stranger.hash)).toEqual({ + hasOrphanedParent: false, + }); + + await catchup(c[1]); + expect(await reads.chainOf(version)).toEqual(heads(c)); + expect(await reads.recordsOf(version)).toEqual([]); + expect(await reads.ownerOf(c[1].txHashes[0])).toBe(c[1].hash); + }); + + it("fills history from block 1 with final catch-up blocks, each only on the canonical block below as its parent", async () => { + const version = freshVersion(); + const c = await buildChain(1n, 6, { version }); + await ordered(c[4], 6); + await ordered(c[5], 6); + const stranger = await buildBlock(3n, [freshTxHash()], { version }); + + for (const block of [c[0], c[1], stranger, c[2], c[3]]) { + await catchup(block, { final: true }); + } + + expect(await reads.chainOf(version)).toEqual(heads(c)); + expect(await reads.stateOf(stranger.hash)).toEqual({ + hasOrphanedParent: false, + }); + expect(await reads.recordsOf(version)).toEqual([]); + }); + + it("clears the dropped rows of the effects a walk-made-canonical block owns, and attaches the rest from its repair", async () => { + const version = freshVersion(); + const kept = freshTxHash(); + const shared = freshTxHash(); + const a0 = await buildBlock(7_000n, [freshTxHash()], { version }); + const a1 = await buildBlock(7_001n, [kept, shared], { version, parent: a0 }); + const b1 = await buildBlock(7_001n, [shared], { version, parent: a0 }); + const a2 = await buildBlock(7_002n, [freshTxHash()], { version, parent: a1 }); + await ordered(a0); + await ordered(a1); + await ordered(b1); + expect(await reads.isDropped(kept)).toBe(true); + expect(await reads.ownerOf(shared)).toBe(b1.hash); + + await ordered(a2); + expect(await reads.chainOf(version)).toEqual(heads([a0, a1, a2])); + expect(await reads.isDropped(kept)).toBe(false); + expect(await reads.ownerOf(shared)).toBe(b1.hash); + expect(await reads.isDropped(shared)).toBe(true); + expect(await reads.repairOpen(7_001)).toBe(true); + + await catchup(a1); + expect(await reads.ownerOf(shared)).toBe(a1.hash); + expect(await reads.isDropped(shared)).toBe(false); + expect(await reads.repairOpen(7_001)).toBe(false); + }); + + it("brings back a live block the old code orphaned without demoting the chain above it", async () => { + const version = freshVersion(); + const live = await buildChain(8_000n, 5, { version }); + const wrong = await buildChain(8_001n, 2, { version, parent: live[0] }); + for (const block of live) { + await ordered(block); + } + for (const block of wrong) { + await catchup(block); + } + // What the height rule left behind: live blocks orphaned under wrong ones. + await setOrphaned([live[1], live[2]], true); + await setOrphaned(wrong, false); + + await ordered(live[2], 8_004); + + expect(await reads.chainOf(version)).toEqual(heads(live)); + expect(await reads.recordsOf(version)).toEqual([ + { active: true, blocks: wrong.map((b) => b.hash) }, + ]); + }); + + it("keeps a partly revived record active with only its blocks still off the chain, and lists a block that died twice once", async () => { + const version = freshVersion(); + const a = await buildChain(9_000n, 4, { version }); + const b1 = await buildBlock(9_001n, [freshTxHash()], { + version, + parent: a[0], + }); + for (const block of a) { + await ordered(block); + } + await ordered(b1); + + await ordered(a[1]); + expect((await reads.recordsOf(version)).map((r) => r.active)).toEqual([ + true, + true, + ]); + expect(await reads.listed([...a, b1])).toEqual([ + { orphanedBlockHash: b1.hash, height: 9_001n, nbrOfOrphanedBlocks: 1 }, + { orphanedBlockHash: a[2].hash, height: 9_002n, nbrOfOrphanedBlocks: 2 }, + ]); + + await ordered(b1); + expect(await reads.listed([...a, b1])).toEqual([ + { orphanedBlockHash: a[1].hash, height: 9_001n, nbrOfOrphanedBlocks: 1 }, + { orphanedBlockHash: a[2].hash, height: 9_002n, nbrOfOrphanedBlocks: 2 }, + ]); + }); + + it("demotes a canonical holder of an ordered block's tx above it, across a gap, so no block of the pass is skipped", async () => { + const version = freshVersion(); + const [x, y] = [freshTxHash(), freshTxHash()]; + const a5 = await buildBlock(10_005n, [freshTxHash()], { version }); + const a6 = await buildBlock(10_006n, [freshTxHash()], { version, parent: a5 }); + const a7 = await buildBlock(10_007n, [freshTxHash()], { version, parent: a6 }); + const a8 = await buildBlock(10_008n, [x, y], { version, parent: a7 }); + for (const block of [a5, a6, a8]) { + await ordered(block); + } + const b6 = await buildBlock(10_006n, [x], { version, parent: a5 }); + const b7 = await buildBlock(10_007n, [y], { version, parent: b6 }); + const b8 = await buildBlock(10_008n, [freshTxHash()], { version, parent: b7 }); + + for (const block of [b6, b7, b8]) { + await ordered(block, 10_008); + } + + expect(await reads.chainOf(version)).toEqual(heads([a5, b6, b7, b8])); + expect([await reads.ownerOf(x), await reads.ownerOf(y)]).toEqual([ + b6.hash, + b7.hash, + ]); + }); + + it("treats a parent lookup that finds two blocks as a missing parent", async () => { + const version = freshVersion(); + const [p] = await buildChain(11_000n, 1, { version }); + const twin = await buildBlock(11_001n, [freshTxHash()], { version, parent: p }); + const other = await buildBlock(11_001n, [freshTxHash()], { + version, + parent: p, + archive: twin.archive, + }); + const child = await buildBlock(11_002n, [freshTxHash()], { + version, + parent: twin, + }); + await ordered(p); + await catchup(twin); + await catchup(other); + await ordered(child); + expect(await reads.chainOf(version)).toEqual(heads([p, child])); + + await catchup(twin); + expect(await reads.chainOf(version)).toEqual(heads([p, child])); + + await catchup(twin, { final: true }); + expect(await reads.chainOf(version)).toEqual(heads([p, twin, child])); + }); + + it("ignores a block event that is not from the ordered stream", async () => { + const version = freshVersion(); + const [block] = await buildChain(12_000n, 1, { version }); + + await ignoredUnordered(block); + + expect(await reads.stateOf(block.hash)).toBe("absent"); + }); + + it("leaves one canonical block when the block and catch-up consumers store one height at once", async () => { + // Ten heights at once, so that without the lock some height's two + // transactions overlap. + const races = await Promise.all( + Array.from({ length: 10 }, async () => { + const version = freshVersion(); + const [p] = await buildChain(13_000n, 1, { version }); + const [fromStream, fromCatchup] = await Promise.all( + [0, 1].map(() => + buildBlock(13_001n, [freshTxHash()], { version, parent: p }), + ), + ); + return { version, p, fromStream, fromCatchup }; + }), + ); + for (const { p } of races) { + await ordered(p); + } + + await Promise.all( + races.flatMap(({ fromStream, fromCatchup }) => [ + ordered(fromStream), + catchup(fromCatchup, { final: true }), + ]), + ); + + for (const { version, p, fromStream } of races) { + expect(await reads.chainOf(version)).toEqual(heads([p, fromStream])); + } + }); + + describe("bounds", () => { + it("stops a walk at the bound without throwing, keeps its partition through it, and rolls back when a heartbeat fails", async () => { + const version = freshVersion(); + const from = 100_000n; + const [base] = await buildChain(from, 1, { version }); + await ordered(base); + await bareChain({ version, from: from + 1n, count: walkBound + 2, parent: base }); + const replacing = await buildBlock(from + 1n, [freshTxHash()], { + version, + parent: base, + }); + const event = orderedEvent(replacing, Number(from) + 2 * walkBound); + + await expect( + orderedWith(event, () => Promise.reject(new Error("rebalancing"))), + ).rejects.toThrow("rebalancing"); + expect(await reads.stateOf(replacing.hash)).toBe("absent"); + + const { beats, ...delivery } = await throughBroker(event); + + expect(delivery).toEqual({ deliveries: 1, rebalances: 0 }); + expect(beats).toBeGreaterThanOrEqual(walkBound / 500); + const chain = await reads.chainOf(version); + expect(chain.slice(0, 2)).toEqual(heads([base, replacing])); + expect(chain.slice(2).map((b) => b.height)).toEqual([ + from + BigInt(walkBound) + 2n, + ]); + }, 300_000); + + it("throws, changing nothing, on more canonical blocks above a tip than the bound", async () => { + const version = freshVersion(); + const from = 200_000n; + await bareChain({ version, from: from + 1n, count: walkBound + 1 }); + const [block] = await buildChain(from, 1, { version }); + + await expect(ordered(block)).rejects.toThrow( + `More than ${walkBound} canonical blocks`, + ); + expect(await reads.stateOf(block.hash)).toBe("absent"); + expect(await reads.chainOf(version)).toHaveLength(walkBound + 1); + }, 300_000); + + it("rethrows a chain lock wait over 10 s", async () => { + const version = freshVersion(); + const [block] = await buildChain(300_000n, 1, { version }); + const release = await holdChainLock(); + try { + await expect(ordered(block)).rejects.toThrow("lock timeout"); + } finally { + await release(); + } + expect(await reads.stateOf(block.hash)).toBe("absent"); + }, 30_000); + }); +}); 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 027e17ff..26423d2f 100644 --- a/services/explorer-api/tests/integration/open-gap.integration.test.ts +++ b/services/explorer-api/tests/integration/open-gap.integration.test.ts @@ -35,6 +35,8 @@ describe("open gap scheduling on a real database", () => { let blocks: (heights: number[], version?: number) => Promise; let arrive: (height: number) => Promise; let orphan: (height: number) => Promise; + let repair: (height: number) => Promise; + let fulfil: (height: number) => Promise; let seedGaps: (rows: SeededGap[]) => Promise; let elapse: (ms: number) => Promise; let openGaps: () => Promise; @@ -57,10 +59,13 @@ describe("open gap scheduling on a real database", () => { const { l2Block } = await import( "../../src/svcs/database/schema/l2block/index.js" ); - const { buildMissingBlockRangeRequest, markOpenGapsFulfilledByHeight } = - await import( - "../../src/svcs/database/controllers/l2block/missing-ranges.js" - ); + const { + buildMissingBlockRangeRequest, + markOpenGapsFulfilledByHeight, + recordRepairHeights, + } = await import( + "../../src/svcs/database/controllers/l2block/missing-ranges.js" + ); const { observeRollupVersion } = await import( "../../src/svcs/database/controllers/l2/chain-info/rollup-version-cache.js" ); @@ -102,6 +107,9 @@ describe("open gap scheduling on a real database", () => { .set({ orphan_timestamp: Date.now(), orphan_hasOrphanedParent: false }) .where(eq(l2Block.hash, hashOf(height, CURRENT))); }; + repair = (height) => recordRepairHeights(db, [BigInt(height)]); + // What blockHandler does after a block message makes its block canonical. + fulfil = (height) => markOpenGapsFulfilledByHeight(BigInt(height)); seedGaps = async (rows) => { const now = Date.now(); await db.insert(l2OpenGapTable).values( @@ -197,6 +205,15 @@ describe("open gap scheduling on a real database", () => { expect(await tick()).toEqual([[90, 90]]); }); + it("requests a repair row while its block is present, until a block message there fulfils it", async () => { + await blocks(span(1, 100)); + await repair(50); + + expect(await tick()).toEqual([[50, 50]]); + await fulfil(50); + expect(await openGaps()).toEqual([]); + }); + it("selects due rows before the candidate limit, with the backoff capped at an hour", async () => { const backedOff = span(101, 160); await blocks(except(span(1, 200), [...backedOff, 170, 180])); From 380de54c5897ed579eba40160c1482a5d0876139 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Thu, 26 Nov 2026 22:12:44 +0000 Subject: [PATCH 06/31] style(explorer-api): format the chain files with prettier Prettier's own output for the canonical chain module, its reorg schema, its test files and the contract store. No other change. Co-Authored-By: Claude Opus 5.5 --- .../database/controllers/l2block/canonical.ts | 41 +++++----- .../database/controllers/l2contract/store.ts | 12 +-- .../chain-head.integration.test.ts | 56 +++++++++++--- .../late-replacing-block.integration.test.ts | 74 +++++++++++-------- .../tests/integration/support/chain.ts | 14 +++- 5 files changed, 122 insertions(+), 75 deletions(-) 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 805d3554..e1430de0 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts @@ -1,16 +1,7 @@ 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 { and, asc, eq, gt, inArray, isNotNull, isNull, sql } from "drizzle-orm"; import { alias } from "drizzle-orm/pg-core"; import { L2_NETWORK_ID } from "../../../../environment.js"; import { logger } from "../../../../logger.js"; @@ -403,8 +394,8 @@ const storeIfAbsent = async ( hash: block.hash, height: block.height, version: change.version, - archiveRoot: block.archive.root , - lastArchiveRoot: block.header.lastArchive.root , + archiveRoot: block.archive.root, + lastArchiveRoot: block.header.lastArchive.root, }; const [existing] = await change.dbTx .select({ @@ -460,10 +451,12 @@ const attachTxs = async ( ) => { const effects = block.body.txEffects; const owners = new Map( - (await txOwners(change.dbTx, effects.map((e) => e.txHash))).map((o) => [ - o.txHash, - o, - ]), + ( + await txOwners( + change.dbTx, + effects.map((e) => e.txHash), + ) + ).map((o) => [o.txHash, o]), ); if (canonical) { const conflicts = [...owners.values()].filter( @@ -568,7 +561,9 @@ const setHasOrphanedParent = async ( await change.dbTx .update(l2Block) .set({ orphan_hasOrphanedParent: value }) - .where(and(inArray(l2Block.hash, part), isNotNull(l2Block.orphan_timestamp))); + .where( + and(inArray(l2Block.hash, part), isNotNull(l2Block.orphan_timestamp)), + ); } }; @@ -596,7 +591,9 @@ const refreshOrphanFlags = async (change: Change) => { eq(parent.version, l2Block.version), ), ) - .where(and(inArray(l2Block.hash, part), isNotNull(parent.orphan_timestamp))); + .where( + and(inArray(l2Block.hash, part), isNotNull(parent.orphan_timestamp)), + ); deadParent.push(...rows.map((r) => r.hash)); } @@ -623,7 +620,9 @@ const refreshOrphanFlags = async (change: Change) => { eq(child.version, l2Block.version), ), ) - .where(and(inArray(l2Block.hash, part), isNotNull(child.orphan_timestamp))); + .where( + and(inArray(l2Block.hash, part), isNotNull(child.orphan_timestamp)), + ); for (const row of rows) { (row.parentOrphanTimestamp === null ? liveParent : deadParent).push( row.hash, @@ -659,9 +658,7 @@ const settle = async (change: Change, attached: ChicmozL2Block | undefined) => { const ownerSummary = (owners: TxOwner[]) => owners - .map( - (o) => `${o.txHash} in active block ${o.height} (${o.blockHash})`, - ) + .map((o) => `${o.txHash} in active block ${o.height} (${o.blockHash})`) .join(", "); /** 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 93024d63..4ed653e9 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2contract/store.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2contract/store.ts @@ -39,9 +39,7 @@ export const storeContractInstanceUpdated = async ( instance: ChicmozL2ContractInstanceUpdatedEvent, executor: ReturnType = db(), ): Promise => { - await executor - .insert(l2ContractInstanceUpdate) - .values({ ...instance }); + await executor.insert(l2ContractInstanceUpdate).values({ ...instance }); }; export const storeContractInstanceVerifiedDeploymentArguments = async ( @@ -65,11 +63,9 @@ export const storeContractClass = async ( contractClass: ChicmozL2ContractClassRegisteredEvent, executor: ReturnType = db(), ): Promise => { - await executor - .insert(l2ContractClassRegistered) - .values({ - ...contractClass, - }); + await executor.insert(l2ContractClassRegistered).values({ + ...contractClass, + }); }; export type BlockContracts = { 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 44c30624..29ec386e 100644 --- a/services/explorer-api/tests/integration/chain-head.integration.test.ts +++ b/services/explorer-api/tests/integration/chain-head.integration.test.ts @@ -30,7 +30,10 @@ describe("the canonical chain on a real database", () => { let reads: Awaited>; let ordered: (b: BuiltBlock, tip?: number) => Promise; let catchup: (b: BuiltBlock, options?: { final?: true }) => Promise; - let orderedWith: (event: NewBlockEvent, heartbeat: Heartbeat) => Promise; + let orderedWith: ( + event: NewBlockEvent, + heartbeat: Heartbeat, + ) => Promise; let ignoredUnordered: (b: BuiltBlock) => Promise; let setOrphaned: (blocks: BuiltBlock[], orphaned: boolean) => Promise; let bareChain: (chain: { @@ -145,7 +148,11 @@ describe("the canonical chain on a real database", () => { settle = (error) => (error === undefined ? resolve() : reject(error)); }); const members = [0, 1].map(() => - kafka.consumer({ groupId, sessionTimeout: 6_000, heartbeatInterval: 1_000 }), + kafka.consumer({ + groupId, + sessionTimeout: 6_000, + heartbeatInterval: 1_000, + }), ); try { for (const member of members) { @@ -161,7 +168,9 @@ describe("the canonical chain on a real database", () => { outcome.deliveries++; try { await blockHandler.cb( - BSON.deserialize(message.value ?? Buffer.alloc(0)) as NewBlockEvent, + BSON.deserialize( + message.value ?? Buffer.alloc(0), + ) as NewBlockEvent, () => { outcome.beats++; return heartbeat(); @@ -268,7 +277,9 @@ describe("the canonical chain on a real database", () => { } }; const active = async () => - (await reads.recordsOf(version)).filter((r) => r.active).map((r) => r.blocks); + (await reads.recordsOf(version)) + .filter((r) => r.active) + .map((r) => r.blocks); await pass(); expect(await reads.chainOf(version)).toEqual(heads([a[0], ...b])); expect(await active()).toEqual([[a[1], a[2], a[3]].map((x) => x.hash)]); @@ -395,9 +406,15 @@ describe("the canonical chain on a real database", () => { const kept = freshTxHash(); const shared = freshTxHash(); const a0 = await buildBlock(7_000n, [freshTxHash()], { version }); - const a1 = await buildBlock(7_001n, [kept, shared], { version, parent: a0 }); + const a1 = await buildBlock(7_001n, [kept, shared], { + version, + parent: a0, + }); const b1 = await buildBlock(7_001n, [shared], { version, parent: a0 }); - const a2 = await buildBlock(7_002n, [freshTxHash()], { version, parent: a1 }); + const a2 = await buildBlock(7_002n, [freshTxHash()], { + version, + parent: a1, + }); await ordered(a0); await ordered(a1); await ordered(b1); @@ -472,15 +489,24 @@ describe("the canonical chain on a real database", () => { const version = freshVersion(); const [x, y] = [freshTxHash(), freshTxHash()]; const a5 = await buildBlock(10_005n, [freshTxHash()], { version }); - const a6 = await buildBlock(10_006n, [freshTxHash()], { version, parent: a5 }); - const a7 = await buildBlock(10_007n, [freshTxHash()], { version, parent: a6 }); + const a6 = await buildBlock(10_006n, [freshTxHash()], { + version, + parent: a5, + }); + const a7 = await buildBlock(10_007n, [freshTxHash()], { + version, + parent: a6, + }); const a8 = await buildBlock(10_008n, [x, y], { version, parent: a7 }); for (const block of [a5, a6, a8]) { await ordered(block); } const b6 = await buildBlock(10_006n, [x], { version, parent: a5 }); const b7 = await buildBlock(10_007n, [y], { version, parent: b6 }); - const b8 = await buildBlock(10_008n, [freshTxHash()], { version, parent: b7 }); + const b8 = await buildBlock(10_008n, [freshTxHash()], { + version, + parent: b7, + }); for (const block of [b6, b7, b8]) { await ordered(block, 10_008); @@ -496,7 +522,10 @@ describe("the canonical chain on a real database", () => { it("treats a parent lookup that finds two blocks as a missing parent", async () => { const version = freshVersion(); const [p] = await buildChain(11_000n, 1, { version }); - const twin = await buildBlock(11_001n, [freshTxHash()], { version, parent: p }); + const twin = await buildBlock(11_001n, [freshTxHash()], { + version, + parent: p, + }); const other = await buildBlock(11_001n, [freshTxHash()], { version, parent: p, @@ -565,7 +594,12 @@ describe("the canonical chain on a real database", () => { const from = 100_000n; const [base] = await buildChain(from, 1, { version }); await ordered(base); - await bareChain({ version, from: from + 1n, count: walkBound + 2, parent: base }); + await bareChain({ + version, + from: from + 1n, + count: walkBound + 2, + parent: base, + }); const replacing = await buildBlock(from + 1n, [freshTxHash()], { version, parent: base, 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 bd3e0b91..31295f22 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 @@ -71,7 +71,10 @@ describe("a replaced block that stays stored on a real database", () => { isDropped = async (txHash) => (await getDroppedTxByHash(txHash)) !== null; const at = (block: BuiltBlock) => ({ block: { number: Number(block.height), hash: block.hash }, - checkpoint: { number: Number(block.height), hash: word(Number(block.height)) }, + checkpoint: { + number: Number(block.height), + hash: word(Number(block.height)), + }, }); storeTips = ({ proposed, finalized, proven, checkpointed }) => deliver(l2TipsHandler, { @@ -101,8 +104,12 @@ describe("a replaced block that stays stored on a real database", () => { it("keeps the replacing chain's stored blocks active when its block at the replaced height arrives after them", async () => { const replaced = await buildBlock(100n, [freshTxHash()]); const replacing = await buildBlock(100n, [freshTxHash()]); - const child = await buildBlock(101n, [freshTxHash()], { parent: replacing }); - const grandchild = await buildBlock(102n, [freshTxHash()], { parent: child }); + const child = await buildBlock(101n, [freshTxHash()], { + parent: replacing, + }); + const grandchild = await buildBlock(102n, [freshTxHash()], { + parent: child, + }); await store(replaced); await store(child); await store(grandchild); @@ -129,36 +136,41 @@ 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 }); - const tipsAt = (proposed: BuiltBlock) => - storeTips({ - proposed: { number: Number(proposed.height), hash: proposed.hash }, - finalized, - proven, - checkpointed, + 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, }); + 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 tipsAt(replacing); + expect(await repairRequestCovers(403)).toBe(true); - await store(next); - await tipsAt(next); + await store(next); + await tipsAt(next); - expect(await canonicalHash(403n)).toBe(replaced.hash); - expect(await repairRequestCovers(403)).toBe(true); - }); + expect(await canonicalHash(403n)).toBe(replaced.hash); + expect(await repairRequestCovers(403)).toBe(true); + }, + ); }); diff --git a/services/explorer-api/tests/integration/support/chain.ts b/services/explorer-api/tests/integration/support/chain.ts index dd22c484..7f6503c4 100644 --- a/services/explorer-api/tests/integration/support/chain.ts +++ b/services/explorer-api/tests/integration/support/chain.ts @@ -6,7 +6,10 @@ export type Head = { height: bigint; hash: HexString }; export const heads = (blocks: BuiltBlock[]): Head[] => blocks.map(({ height, hash }) => ({ height, hash })); -export type BlockState = "canonical" | "absent" | { hasOrphanedParent: boolean }; +export type BlockState = + | "canonical" + | "absent" + | { hasOrphanedParent: boolean }; export type ReorgRecord = { active: boolean; blocks: HexString[] }; @@ -46,7 +49,9 @@ export const loadChainReads = async () => { db .select({ height: l2Block.height, hash: l2Block.hash }) .from(l2Block) - .where(and(eq(l2Block.version, version), isNull(l2Block.orphan_timestamp))) + .where( + and(eq(l2Block.version, version), isNull(l2Block.orphan_timestamp)), + ) .orderBy(asc(l2Block.height)); const stateOf = async (hash: HexString): Promise => { @@ -92,7 +97,10 @@ export const loadChainReads = async () => { hash: l2ReorgBlockTable.hash, }) .from(l2ReorgTable) - .innerJoin(l2ReorgBlockTable, eq(l2ReorgBlockTable.reorgId, l2ReorgTable.id)) + .innerJoin( + l2ReorgBlockTable, + eq(l2ReorgBlockTable.reorgId, l2ReorgTable.id), + ) .where(eq(l2ReorgTable.rollupVersion, version)) .orderBy( asc(l2ReorgTable.id), From 139630ff4df0a1fce487b91558a8ed80511d8098 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Thu, 26 Nov 2026 22:20:22 +0000 Subject: [PATCH 07/31] fix(explorer-api): heartbeat through a chain change's settlement The writes a change makes in statements of up to a thousand rows (demotions, reorg records, dropped txs, orphan flags, repair requests) ran without a heartbeat, so a change that demoted thousands of blocks could outlast the consumer's session after its walk ended. Each such statement now heartbeats first; KafkaJS sends at most one heartbeat per interval, so the extra calls cost nothing. Open-gap rows are now upserted in one statement per call instead of one per row, so a change's repair requests take one statement per thousand heights. The scheduler's unit fake takes multi-row inserts and counts statements. The rebalance test reads its counters only once the broker holds the offset commit, so a member lost before the commit is counted. Co-Authored-By: Claude Opus 5.5 --- .../database/controllers/l2block/canonical.ts | 73 +++++++++-------- .../controllers/l2block/missing-ranges.ts | 82 +++++++++++-------- .../chain-head.integration.test.ts | 31 ++++++- .../tests/unit/open-gap-scheduler.test.ts | 52 +++++++++--- 4 files changed, 157 insertions(+), 81 deletions(-) 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 e1430de0..d0196b57 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts @@ -106,12 +106,20 @@ class TxConflict extends Error { } } -const chunks = (items: T[]): T[][] => { - const parts: T[][] = []; +/** + * Runs `write` over `items` in statements of at most ROWS_PER_STATEMENT rows, + * heartbeating before each: KafkaJS sends at most one heartbeat per interval, + * so the calls cost nothing in between. + */ +const inStatements = async ( + change: Change, + items: T[], + write: (part: T[]) => Promise, +) => { for (let i = 0; i < items.length; i += ROWS_PER_STATEMENT) { - parts.push(items.slice(i, i + ROWS_PER_STATEMENT)); + await change.heartbeat(); + await write(items.slice(i, i + ROWS_PER_STATEMENT)); } - return parts; }; const step = async (change: Change) => { @@ -217,17 +225,17 @@ const txOwners = async (dbTx: DbTx, txHashes: HexString[]) => }), ); -const ownedTxs = async (dbTx: DbTx, blockHashes: HexString[]) => { +const ownedTxs = async (change: Change, blockHashes: HexString[]) => { const owned: { txHash: HexString; birth: number }[] = []; - for (const part of chunks(blockHashes)) { + await inStatements(change, blockHashes, async (part) => { owned.push( - ...(await dbTx + ...(await change.dbTx .select({ txHash: txEffect.txHash, birth: txEffect.txBirthTimestamp }) .from(txEffect) .innerJoin(body, eq(txEffect.bodyId, body.id)) .where(inArray(body.blockHash, part))), ); - } + }); return owned; }; @@ -235,14 +243,14 @@ const demote = async (change: Change, blocks: { hash: HexString }[]) => { const hashes = blocks .map((b) => b.hash) .filter((hash) => !change.demoted.has(hash)); - for (const part of chunks(hashes)) { + await inStatements(change, hashes, async (part) => { const rows = await change.dbTx .update(l2Block) .set({ orphan_timestamp: change.now, orphan_hasOrphanedParent: false }) .where(and(inArray(l2Block.hash, part), isNull(l2Block.orphan_timestamp))) .returning({ hash: l2Block.hash, height: l2Block.height }); rows.forEach((row) => change.demoted.set(row.hash, row.height)); - } + }); }; const promote = async ( @@ -502,19 +510,19 @@ const recordReorg = async (change: Change) => { observedAt: new Date(change.now), }) .returning({ id: l2ReorgTable.id }); - for (const part of chunks(blocks)) { + await inStatements(change, blocks, async (part) => { await change.dbTx .insert(l2ReorgBlockTable) .values(part.map((b) => ({ reorgId: record.id, ...b }))); - } + }); logger.warn( `L2 reorg at height ${root.height}: ${blocks.length} block(s) left the chain, the lowest ${root.hash}`, ); }; const markDemotedTxsDropped = async (change: Change) => { - const orphaned = await ownedTxs(change.dbTx, [...change.demoted.keys()]); - for (const part of chunks(orphaned)) { + const orphaned = await ownedTxs(change, [...change.demoted.keys()]); + await inStatements(change, orphaned, async (part) => { await change.dbTx .insert(droppedTx) .values( @@ -526,12 +534,12 @@ const markDemotedTxsDropped = async (change: Change) => { })), ) .onConflictDoNothing(); - } + }); }; /** A record is revived once every block it lists is stored and canonical again. */ const reviveRecords = async (change: Change) => { - for (const part of chunks([...change.promoted.keys()])) { + await inStatements(change, [...change.promoted.keys()], async (part) => { await change.dbTx .update(l2ReorgTable) .set({ revivedAt: new Date(change.now) }) @@ -549,7 +557,7 @@ const reviveRecords = async (change: Change) => { sql`NOT EXISTS (SELECT 1 FROM ${l2ReorgBlockTable} LEFT JOIN ${l2Block} ON ${l2Block.hash} = ${l2ReorgBlockTable.hash} WHERE ${l2ReorgBlockTable.reorgId} = ${l2ReorgTable.id} AND (${l2Block.hash} IS NULL OR ${l2Block.orphan_timestamp} IS NOT NULL))`, ), ); - } + }); }; const setHasOrphanedParent = async ( @@ -557,14 +565,14 @@ const setHasOrphanedParent = async ( hashes: HexString[], value: boolean, ) => { - for (const part of chunks(hashes)) { + await inStatements(change, hashes, async (part) => { await change.dbTx .update(l2Block) .set({ orphan_hasOrphanedParent: value }) .where( and(inArray(l2Block.hash, part), isNotNull(l2Block.orphan_timestamp)), ); - } + }); }; /** @@ -576,7 +584,7 @@ const refreshOrphanFlags = async (change: Change) => { const parent = alias(l2Block, "parent"); const parentArchive = alias(archive, "parent_archive"); const deadParent: HexString[] = []; - for (const part of chunks([...change.demoted.keys()])) { + await inStatements(change, [...change.demoted.keys()], async (part) => { const rows = await change.dbTx .selectDistinct({ hash: l2Block.hash }) .from(l2Block) @@ -595,14 +603,14 @@ const refreshOrphanFlags = async (change: Change) => { and(inArray(l2Block.hash, part), isNotNull(parent.orphan_timestamp)), ); deadParent.push(...rows.map((r) => r.hash)); - } + }); const child = alias(l2Block, "child"); const childHeader = alias(header, "child_header"); const childLastArchive = alias(lastArchive, "child_last_archive"); const moved = [...change.demoted.keys(), ...change.promoted.keys()]; const liveParent: HexString[] = []; - for (const part of chunks(moved)) { + await inStatements(change, moved, async (part) => { const rows = await change.dbTx .selectDistinct({ hash: child.hash, @@ -628,7 +636,7 @@ const refreshOrphanFlags = async (change: Change) => { row.hash, ); } - } + }); await setHasOrphanedParent(change, deadParent, true); await setHasOrphanedParent(change, liveParent, false); }; @@ -640,20 +648,19 @@ const settle = async (change: Change, attached: ChicmozL2Block | undefined) => { } await markDemotedTxsDropped(change); const mined = new Set( - (await ownedTxs(change.dbTx, [...change.promoted.keys()])).map( - (t) => t.txHash, - ), + (await ownedTxs(change, [...change.promoted.keys()])).map((t) => t.txHash), ); attached?.body.txEffects.forEach((e) => mined.add(e.txHash)); - for (const part of chunks([...mined])) { - await removePendingAndDroppedTx(change.dbTx, part); - } + await inStatements(change, [...mined], (part) => + removePendingAndDroppedTx(change.dbTx, part), + ); await reviveRecords(change); await refreshOrphanFlags(change); - await recordRepairHeights(change.dbTx, [ - ...change.walked.values(), - ...change.repairs, - ]); + await inStatements( + change, + [...new Set([...change.walked.values(), ...change.repairs])], + (part) => recordRepairHeights(change.dbTx, part), + ); }; const ownerSummary = (owners: TxOwner[]) => 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 3cc80f20..26d4c83b 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 @@ -92,42 +92,54 @@ const upsertOpenGaps = async ({ resetOnReopen?: boolean; executor?: ReturnType; }) => { - for (const range of ranges) { - const values = { - id: gapId({ ...range, reason }), - l2NetworkId: L2_NETWORK_ID, - fromHeight: range.from, - toHeight: range.to, - reason, - statusHint: range.statusHint, - status: "open" as const, - lastSeenAt: new Date(), - fulfilledAt: null, - lastError: null, - }; - - await executor - .insert(l2OpenGapTable) - .values(values) - .onConflictDoUpdate({ - target: l2OpenGapTable.id, - set: { - status: "open", - lastSeenAt: values.lastSeenAt, - statusHint: values.statusHint, - fulfilledAt: null, - lastError: null, - // A row reopened after being fulfilled is a new gap: its earlier - // requests say nothing about it, so its backoff starts over. - ...(resetOnReopen - ? { - requestCount: sql`case when ${l2OpenGapTable.status} = 'fulfilled' then 0 else ${l2OpenGapTable.requestCount} end`, - lastRequestedAt: sql`case when ${l2OpenGapTable.status} = 'fulfilled' then null else ${l2OpenGapTable.lastRequestedAt} end`, - } - : {}), - }, - }); + const lastSeenAt = new Date(); + // One row per id: a statement cannot update the same row twice. + const rows = [ + ...new Map( + ranges.map((range) => { + const id = gapId({ ...range, reason }); + return [ + id, + { + id, + l2NetworkId: L2_NETWORK_ID, + fromHeight: range.from, + toHeight: range.to, + reason, + statusHint: range.statusHint, + status: "open" as const, + lastSeenAt, + fulfilledAt: null, + lastError: null, + }, + ] as const; + }), + ).values(), + ]; + if (rows.length === 0) { + return; } + await executor + .insert(l2OpenGapTable) + .values(rows) + .onConflictDoUpdate({ + target: l2OpenGapTable.id, + set: { + status: "open", + lastSeenAt, + statusHint: sql`excluded.status_hint`, + fulfilledAt: null, + lastError: null, + // A row reopened after being fulfilled is a new gap: its earlier + // requests say nothing about it, so its backoff starts over. + ...(resetOnReopen + ? { + requestCount: sql`case when ${l2OpenGapTable.status} = 'fulfilled' then 0 else ${l2OpenGapTable.requestCount} end`, + lastRequestedAt: sql`case when ${l2OpenGapTable.status} = 'fulfilled' then null else ${l2OpenGapTable.lastRequestedAt} end`, + } + : {}), + }, + }); }; // Backoff after a gap's Nth request: interval * 2^min(N, 8), capped at 1h. 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 29ec386e..09502b19 100644 --- a/services/explorer-api/tests/integration/chain-head.integration.test.ts +++ b/services/explorer-api/tests/integration/chain-head.integration.test.ts @@ -206,6 +206,22 @@ describe("the canonical chain on a real database", () => { }); await producer.disconnect(); await handled; + // Read once the broker holds the commit: a member lost before it + // would have the message delivered again. + const committedBy = Date.now() + 30_000; + for (;;) { + const offsets = await admin.fetchOffsets({ + groupId, + topics: [topic], + }); + if (offsets[0]?.partitions[0]?.offset === "1") { + break; + } + if (Date.now() > committedBy) { + throw new Error(`group ${groupId} never committed the message`); + } + await new Promise((resolve) => setTimeout(resolve, 100)); + } // Leaving the group below rebalances it too. return { ...outcome }; } finally { @@ -622,7 +638,7 @@ describe("the canonical chain on a real database", () => { ]); }, 300_000); - it("throws, changing nothing, on more canonical blocks above a tip than the bound", async () => { + it("throws, changing nothing, on more canonical blocks above a tip than the bound, and heartbeats through demoting exactly the bound", async () => { const version = freshVersion(); const from = 200_000n; await bareChain({ version, from: from + 1n, count: walkBound + 1 }); @@ -633,6 +649,19 @@ describe("the canonical chain on a real database", () => { ); expect(await reads.stateOf(block.hash)).toBe("absent"); expect(await reads.chainOf(version)).toHaveLength(walkBound + 1); + + // No walk to heartbeat in: one replaced block, the bound above the tip. + const replacing = await buildBlock(from + 1n, [freshTxHash()], { + version, + }); + let beats = 0; + await orderedWith(orderedEvent(replacing), () => { + beats++; + return Promise.resolve(); + }); + + expect(await reads.chainOf(version)).toEqual(heads([replacing])); + expect(beats).toBeGreaterThan(0); }, 300_000); it("rethrows a chain lock wait over 10 s", async () => { 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 caf24083..379ecdbc 100644 --- a/services/explorer-api/tests/unit/open-gap-scheduler.test.ts +++ b/services/explorer-api/tests/unit/open-gap-scheduler.test.ts @@ -33,6 +33,7 @@ const mocks = vi.hoisted(() => { set: Record; }>, inserted: [] as Array>, + insertStatements: 0, deleted: [] as unknown[], updates: [] as Array>, updateTargets: [] as unknown[][], @@ -98,18 +99,25 @@ const mocks = vi.hoisted(() => { }, }), }), - insert: () => ({ - values: (values: Record) => ({ - onConflictDoUpdate: ({ set }: { set: Record }) => { - state.upserts.push({ values, set }); - return Promise.resolve(); - }, - onConflictDoNothing: () => { - state.inserted.push(values); - return Promise.resolve(); - }, - }), - }), + insert: () => { + state.insertStatements++; + return { + values: ( + values: Record | Record[], + ) => ({ + onConflictDoUpdate: ({ set }: { set: Record }) => { + for (const row of [values].flat()) { + state.upserts.push({ values: row, set }); + } + return Promise.resolve(); + }, + onConflictDoNothing: () => { + state.inserted.push(...[values].flat()); + return Promise.resolve(); + }, + }), + }; + }, update: () => ({ set: (values: Record) => ({ where: (condition: unknown) => { @@ -178,11 +186,13 @@ const { buildTipBoundaryRepairRequest, coverageOf, gapRowMaxWidth, + recordRepairHeights, requestableGapFilter, splitRange, } = await import( "../../src/svcs/database/controllers/l2block/missing-ranges.js" ); +const { getDb } = await import("@chicmoz-pkg/postgres-helper"); const { l2BlockRangeRequest } = await import( "../../src/events/emitted/index.js" ); @@ -225,6 +235,7 @@ beforeEach(() => { presentHeights: heights(1, TIP), upserts: [], inserted: [], + insertStatements: 0, deleted: [], updates: [], updateTargets: [], @@ -642,3 +653,20 @@ describe("buildTipBoundaryRepairRequest", () => { await expect(buildTipBoundaryRepairRequest()).resolves.toBeNull(); }); }); + +describe("recordRepairHeights", () => { + it("records its heights in one statement, once each", async () => { + await recordRepairHeights(getDb(), [5n, 6n, 5n]); + + expect(mocks.state.insertStatements).toBe(1); + expect( + mocks.state.upserts.map(({ values }) => [ + values.reason, + values.fromHeight, + ]), + ).toEqual([ + ["reorg_repair", 5], + ["reorg_repair", 6], + ]); + }); +}); From ce3e488fb64ee69e5090a36d40161fb4b292aa95 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Thu, 26 Nov 2026 22:23:23 +0000 Subject: [PATCH 08/31] fix(explorer-api): demote every stale holder of an ordered block's txs An ordered block that includes a tx again, held by a stale canonical block below it, was skipped when its missing parent stopped the ancestor walk before that block: the tx conflict rolled the change back and the message was acknowledged. Every other canonical block of the version up to the tip that holds one of its txs now leaves the chain with its linked run, also when the block is already canonical, and every height below the block that this leaves without a canonical block is requested. Co-Authored-By: Claude Opus 5.5 --- .../database/controllers/l2block/canonical.ts | 96 ++++++++++++++----- .../block-reorg.integration.test.ts | 2 +- .../chain-head.integration.test.ts | 36 +++++++ 3 files changed, 107 insertions(+), 27 deletions(-) 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 d0196b57..a3bfec29 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts @@ -293,6 +293,45 @@ const demoteLinkedRun = async ( await demote(change, run); }; +/** + * Demotes every other canonical block of the version up to `ceiling` that + * holds one of `block`'s txs, with its linked run up to `ceiling`: a tx is + * included once per chain, so no such holder is on the chain `block` is + * canonical on. + */ +const demoteHolders = async ( + change: Change, + block: ChicmozL2Block, + ceiling: bigint, +) => { + const holders = new Set( + ( + await txOwners( + change.dbTx, + block.body.txEffects.map((e) => e.txHash), + ) + ) + .filter( + (o) => o.canonical && o.blockHash !== block.hash && o.height <= ceiling, + ) + .map((o) => o.blockHash), + ); + for (const hash of holders) { + const [holder] = ( + await chainBlocks(change.dbTx).where( + and( + eq(l2Block.hash, hash), + eq(l2Block.version, change.version), + isNull(l2Block.orphan_timestamp), + ), + ) + ).map(toChainBlock); + if (holder) { + await demoteLinkedRun(change, holder, ceiling); + } + } +}; + /** * Brings back the stored, off-chain ancestors of a block that just became * canonical, demoting their competitors. Ends at a canonical parent; at a @@ -329,6 +368,28 @@ const reviveAncestors = async (change: Change, start: ChainBlock) => { } }; +/** Asks for every height below `height` that this change left without a canonical block. */ +const requestEmptied = async (change: Change, height: bigint) => { + const emptied = [ + ...new Set([...change.demoted.values()].filter((h) => h < height)), + ]; + const occupied = new Set(); + await inStatements(change, emptied, async (part) => { + const rows = await change.dbTx + .selectDistinct({ height: l2Block.height }) + .from(l2Block) + .where( + and( + eq(l2Block.version, change.version), + inArray(l2Block.height, part), + isNull(l2Block.orphan_timestamp), + ), + ); + rows.forEach((row) => occupied.add(row.height)); + }); + emptied.filter((h) => !occupied.has(h)).forEach((h) => change.repairs.add(h)); +}; + const demoteAbove = async (change: Change, ceiling: bigint) => { const above = await change.dbTx .select({ hash: l2Block.hash }) @@ -715,10 +776,11 @@ const apply = async ( }; /** - * An ordered block is canonical at its height. It replaces the block there, - * that block's linked descendants and every canonical holder of its txs - * above it (a tx is included once per chain), brings back its stored - * ancestors, and demotes every canonical block above `tip`. + * An ordered block is canonical at its height. It replaces the block there + * with that block's linked descendants, and every other canonical holder of + * its txs with theirs; brings back its stored ancestors; asks for the heights + * below it that this leaves empty; and demotes every canonical block above + * `tip`. */ export const applyOrderedBlock = ( incoming: IncomingBlock, @@ -742,31 +804,13 @@ export const applyOrderedBlock = ( for (const replaced of await canonicalAt(change, height)) { await demoteLinkedRun(change, replaced, ceiling); } - const txHashes = incoming.block.body.txEffects.map((e) => e.txHash); - const holders = new Map( - (await txOwners(change.dbTx, txHashes)) - .filter( - (o) => o.canonical && o.height > height && o.blockHash !== hash, - ) - .map((o) => [o.blockHash, o]), - ); - for (const holder of holders.values()) { - const [run] = ( - await chainBlocks(change.dbTx).where( - and( - eq(l2Block.hash, holder.blockHash), - eq(l2Block.version, change.version), - isNull(l2Block.orphan_timestamp), - ), - ) - ).map(toChainBlock); - if (run) { - await demoteLinkedRun(change, run, ceiling); - } - } + } + await demoteHolders(change, incoming.block, ceiling); + if (!stored.canonical) { await promote(change, stored, { walked: false }); await reviveAncestors(change, stored); } + await requestEmptied(change, height); await demoteAbove(change, ceiling); return true; }, 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 27d624d9..5e5bd9bc 100644 --- a/services/explorer-api/tests/integration/block-reorg.integration.test.ts +++ b/services/explorer-api/tests/integration/block-reorg.integration.test.ts @@ -33,7 +33,7 @@ describe("block conflicts on a real database", () => { await api?.close(); }); - it("skips a block whose tx a canonical block below holds, and keeps the block at its height", async () => { + it("skips a block whose tx its canonical parent holds, and keeps the block at its height", async () => { const t = freshTxHash(); const below = await buildBlock(100n, [t]); const current = await buildBlock(101n, [freshTxHash()], { parent: below }); 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 09502b19..13a86f1a 100644 --- a/services/explorer-api/tests/integration/chain-head.integration.test.ts +++ b/services/explorer-api/tests/integration/chain-head.integration.test.ts @@ -535,6 +535,42 @@ describe("the canonical chain on a real database", () => { ]); }); + it("demotes a stale canonical holder of an ordered block's tx below it, and requests the heights that leaves empty", async () => { + const version = freshVersion(); + const x = freshTxHash(); + const a0 = await buildBlock(15_000n, [freshTxHash()], { version }); + const a1 = await buildBlock(15_001n, [x], { version, parent: a0 }); + const a2 = await buildBlock(15_002n, [freshTxHash()], { + version, + parent: a1, + }); + const a3 = await buildBlock(15_003n, [freshTxHash()], { + version, + parent: a2, + }); + for (const block of [a0, a1, a2, a3]) { + await ordered(block); + } + const b1 = await buildBlock(15_001n, [freshTxHash()], { + version, + parent: a0, + }); + const b2 = await buildBlock(15_002n, [freshTxHash()], { + version, + parent: b1, + }); + const b3 = await buildBlock(15_003n, [x], { version, parent: b2 }); + + await ordered(b3); + + expect(await reads.chainOf(version)).toEqual(heads([a0, b3])); + expect(await reads.ownerOf(x)).toBe(b3.hash); + expect([ + await reads.repairOpen(15_001), + await reads.repairOpen(15_002), + ]).toEqual([true, true]); + }); + it("treats a parent lookup that finds two blocks as a missing parent", async () => { const version = freshVersion(); const [p] = await buildChain(11_000n, 1, { version }); From 8d616f7547489350b2ad1697b57084234e586c17 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Thu, 26 Nov 2026 22:26:07 +0000 Subject: [PATCH 09/31] fix(explorer-api): keep catch-up blocks above the canonical head off the chain With no canonical block above it, a final catch-up block whose parent was the head joined the chain, so catch-up could extend the chain past the last ordered pass. A catch-up block now joins only below a canonical block. Co-Authored-By: Claude Opus 5.5 --- .../database/controllers/l2block/canonical.ts | 18 +++++++++++------- .../integration/chain-head.integration.test.ts | 10 ++++++++++ 2 files changed, 21 insertions(+), 7 deletions(-) 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 a3bfec29..22994b59 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts @@ -36,7 +36,7 @@ import { store, writeTxEffect } from "./store.js"; // // Ordered blocks are the listener's chain, sent in order: each is canonical // at its height and nothing canonical stays above its tip. Catch-up blocks -// only fill empty heights and never demote anything. +// only fill empty heights below the canonical head and never demote anything. /** Walks stop after this many steps; more canonical blocks than this above a tip is corrupted state. */ export const WALK_BOUND = 10_000; @@ -410,7 +410,8 @@ const demoteAbove = async (change: Change, ceiling: bigint) => { await demote(change, above); }; -type Link = { walked: ChainBlock[] } | "excludes" | "undecided"; +// `head`: no canonical block above, so nothing to descend from. +type Link = { walked: ChainBlock[] } | "excludes" | "undecided" | "head"; /** * Whether the lowest canonical block above an empty height descends from @@ -431,7 +432,7 @@ const linkFromAbove = async ( .orderBy(asc(l2Block.height)) .limit(1); if (!lowest) { - return "undecided"; + return "head"; } const walked: ChainBlock[] = []; let child = toChainBlock(lowest); @@ -818,10 +819,10 @@ export const applyOrderedBlock = ( }; /** - * A catch-up block never demotes anything. It joins only at an empty - * height: when the lowest canonical block above descends from it, or, with - * `final` (at or below the serving node's own finalized tip), when the - * canonical block below, if any, is its parent. + * A catch-up block never demotes anything. It joins only at an empty height + * below the canonical head: when the lowest canonical block above descends + * from it, or, with `final` (at or below the serving node's own finalized + * tip), when the canonical block below, if any, is its parent. */ export const applyCatchupBlock = ( incoming: IncomingBlock, @@ -836,6 +837,9 @@ export const applyCatchupBlock = ( return false; } const link = await linkFromAbove(change, stored); + if (link === "head") { + return false; + } if (link === "excludes") { if (final) { logger.warn( 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 13a86f1a..46c6a7d4 100644 --- a/services/explorer-api/tests/integration/chain-head.integration.test.ts +++ b/services/explorer-api/tests/integration/chain-head.integration.test.ts @@ -399,6 +399,16 @@ describe("the canonical chain on a real database", () => { expect(await reads.ownerOf(c[1].txHashes[0])).toBe(c[1].hash); }); + it("keeps a final catch-up block above the canonical head off the chain", async () => { + const version = freshVersion(); + const [head, above] = await buildChain(16_000n, 2, { version }); + await ordered(head); + + await catchup(above, { final: true }); + + expect(await reads.chainOf(version)).toEqual(heads([head])); + }); + it("fills history from block 1 with final catch-up blocks, each only on the canonical block below as its parent", async () => { const version = freshVersion(); const c = await buildChain(1n, 6, { version }); From 0f876a788b14925181e39130d2ef12b7f41509ae Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Thu, 26 Nov 2026 22:28:49 +0000 Subject: [PATCH 10/31] fix(explorer-api): apply the ordered rule below a catch-up block joined from above A catch-up block that the canonical chain above descends from joined without looking below it: it could sit on a canonical block that is not its parent, and a backward repair stopped after one attach. It now carries that chain's authority below its height, as an ordered block does: other canonical holders of its txs there leave with their linked runs, its stored ancestors come back, the block below that is not its parent leaves, and its parent and every height left empty are requested. Such a join can now demote blocks and record a reorg. Co-Authored-By: Claude Opus 5.5 --- .../database/controllers/l2block/canonical.ts | 17 ++-- .../chain-head.integration.test.ts | 81 ++++++++++++++++++- 2 files changed, 92 insertions(+), 6 deletions(-) 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 22994b59..1d8cdf46 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts @@ -36,7 +36,8 @@ import { store, writeTxEffect } from "./store.js"; // // Ordered blocks are the listener's chain, sent in order: each is canonical // at its height and nothing canonical stays above its tip. Catch-up blocks -// only fill empty heights below the canonical head and never demote anything. +// only fill empty heights below the canonical head; one that the chain above +// 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; @@ -819,10 +820,13 @@ export const applyOrderedBlock = ( }; /** - * A catch-up block never demotes anything. It joins only at an empty height - * below the canonical head: when the lowest canonical block above descends - * from it, or, with `final` (at or below the serving node's own finalized - * tip), when the canonical block below, if any, is its parent. + * A catch-up block never replaces a canonical block. It joins only at an + * empty height below the canonical head: when the lowest canonical block + * above descends from it, with that block's authority below its height, so + * the holders of its txs there go, its stored ancestors come back and the + * heights left empty are asked for, as for an ordered block; or, with + * `final` (at or below the serving node's own finalized tip), when the + * canonical block below, if any, is its parent. */ export const applyCatchupBlock = ( incoming: IncomingBlock, @@ -849,10 +853,13 @@ export const applyCatchupBlock = ( return false; } if (link !== "undecided") { + await demoteHolders(change, incoming.block, stored.height - 1n); await promote(change, stored, { walked: false }); for (const walked of link.walked) { await promote(change, walked, { walked: true }); } + await reviveAncestors(change, stored); + await requestEmptied(change, stored.height); return true; } if (!final) { 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 46c6a7d4..e5edc308 100644 --- a/services/explorer-api/tests/integration/chain-head.integration.test.ts +++ b/services/explorer-api/tests/integration/chain-head.integration.test.ts @@ -377,7 +377,7 @@ describe("the canonical chain on a real database", () => { ]); }); - it("joins a catch-up block at an empty height only when the chain above descends from it, without demoting or recording", async () => { + it("joins a catch-up block at an empty height only when the chain above descends from it", async () => { const version = freshVersion(); const c = await buildChain(6_000n, 4, { version }); for (const block of [c[0], c[2], c[3]]) { @@ -409,6 +409,48 @@ describe("the canonical chain on a real database", () => { expect(await reads.chainOf(version)).toEqual(heads([head])); }); + it("demotes the block below a catch-up block joined from above when it is not its parent, and requests the parent", async () => { + const version = freshVersion(); + const [a0, a1] = await buildChain(17_000n, 2, { version }); + const b1 = await buildBlock(17_001n, [freshTxHash()], { + version, + parent: a0, + }); + const [b2, b3] = await buildChain(17_002n, 2, { version, parent: b1 }); + await ordered(a0); + await ordered(a1); + await ordered(b3); + + await catchup(b2); + + expect(await reads.chainOf(version)).toEqual(heads([a0, b2, b3])); + expect(await reads.recordsOf(version)).toEqual([ + { active: true, blocks: [a1.hash] }, + ]); + expect(await reads.repairOpen(17_001)).toBe(true); + }); + + it("walks repairs back from an ordered block far above the head, one per attach, until they meet the old chain", async () => { + const version = freshVersion(); + const [a0, a1] = await buildChain(18_000n, 2, { version }); + const b = await buildChain(18_001n, 5, { version, parent: a0 }); + await ordered(a0); + await ordered(a1); + await ordered(b[4]); + + for (const block of b.slice(0, 4).reverse()) { + const height = Number(block.height); + expect([ + await reads.repairOpen(height), + await reads.repairOpen(height - 1), + ]).toEqual([true, false]); + await catchup(block); + } + + expect(await reads.chainOf(version)).toEqual(heads([a0, ...b])); + expect(await reads.repairOpen(18_001)).toBe(false); + }); + it("fills history from block 1 with final catch-up blocks, each only on the canonical block below as its parent", async () => { const version = freshVersion(); const c = await buildChain(1n, 6, { version }); @@ -581,6 +623,43 @@ describe("the canonical chain on a real database", () => { ]).toEqual([true, true]); }); + it("demotes a stale canonical holder of a tx below a catch-up block joined from above, and requests the heights that leaves empty", async () => { + const version = freshVersion(); + const x = freshTxHash(); + const a0 = await buildBlock(21_000n, [freshTxHash()], { version }); + const a1 = await buildBlock(21_001n, [x], { version, parent: a0 }); + const a2 = await buildBlock(21_002n, [freshTxHash()], { + version, + parent: a1, + }); + for (const block of [a0, a1, a2]) { + await ordered(block); + } + const b1 = await buildBlock(21_001n, [freshTxHash()], { + version, + parent: a0, + }); + const b2 = await buildBlock(21_002n, [freshTxHash()], { + version, + parent: b1, + }); + const b3 = await buildBlock(21_003n, [x], { version, parent: b2 }); + const b4 = await buildBlock(21_004n, [freshTxHash()], { + version, + parent: b3, + }); + await ordered(b4); + + await catchup(b3); + + expect(await reads.chainOf(version)).toEqual(heads([a0, b3, b4])); + expect(await reads.ownerOf(x)).toBe(b3.hash); + expect([ + await reads.repairOpen(21_001), + await reads.repairOpen(21_002), + ]).toEqual([true, true]); + }); + it("treats a parent lookup that finds two blocks as a missing parent", async () => { const version = freshVersion(); const [p] = await buildChain(11_000n, 1, { version }); From 5000fd03ce28c2f33f3b0134aee31a3ddd4cdb74 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Thu, 26 Nov 2026 22:31:31 +0000 Subject: [PATCH 11/31] fix(explorer-api): flag a new off-chain block whose stored parent is off the chain The parent flag was refreshed only around the blocks a change moved, so a block stored off the chain under an off-chain parent kept `false`. The block a change stores and leaves off the chain is now refreshed with them. Co-Authored-By: Claude Opus 5.5 --- .../database/controllers/l2block/canonical.ts | 76 +++++++++++-------- .../chain-head.integration.test.ts | 32 ++++++++ 2 files changed, 78 insertions(+), 30 deletions(-) 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 1d8cdf46..7bbd86c5 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts @@ -76,7 +76,7 @@ type ChainBlock = { lastArchiveRoot: string | null; }; -type StoredBlock = ChainBlock & { bodyId: string }; +type StoredBlock = ChainBlock & { bodyId: string; created: boolean }; type Change = { dbTx: DbTx; @@ -482,12 +482,13 @@ const storeIfAbsent = async ( .limit(1); if (!existing) { const bodyId = await store(change.dbTx, block, change.now); - return { ...node, canonical: false, bodyId }; + return { ...node, canonical: false, bodyId, created: true }; } const stored = { ...node, canonical: existing.orphanTimestamp === null, bodyId: existing.bodyId, + created: false, }; if (existing.archiveRoot === node.archiveRoot) { return stored; @@ -640,38 +641,47 @@ const setHasOrphanedParent = async ( /** * `orphan_hasOrphanedParent` of an off-chain block: its stored parent is off - * the chain too. Refreshed for the demoted blocks and for the off-chain - * children of every block this call moved. + * the chain too. Refreshed for the blocks this call demoted or stored off the + * chain, and for the off-chain children of those and of the blocks it made + * canonical. */ -const refreshOrphanFlags = async (change: Change) => { +const refreshOrphanFlags = async (change: Change, storedOff: HexString[]) => { const parent = alias(l2Block, "parent"); const parentArchive = alias(archive, "parent_archive"); const deadParent: HexString[] = []; - await inStatements(change, [...change.demoted.keys()], async (part) => { - const rows = await change.dbTx - .selectDistinct({ hash: l2Block.hash }) - .from(l2Block) - .innerJoin(header, eq(header.blockHash, l2Block.hash)) - .innerJoin(lastArchive, eq(lastArchive.fk, header.id)) - .innerJoin(parentArchive, eq(parentArchive.root, lastArchive.root)) - .innerJoin( - parent, - and( - eq(parent.hash, parentArchive.fk), - eq(parent.height, sql`${l2Block.height} - 1`), - eq(parent.version, l2Block.version), - ), - ) - .where( - and(inArray(l2Block.hash, part), isNotNull(parent.orphan_timestamp)), - ); - deadParent.push(...rows.map((r) => r.hash)); - }); + await inStatements( + change, + [...change.demoted.keys(), ...storedOff], + async (part) => { + const rows = await change.dbTx + .selectDistinct({ hash: l2Block.hash }) + .from(l2Block) + .innerJoin(header, eq(header.blockHash, l2Block.hash)) + .innerJoin(lastArchive, eq(lastArchive.fk, header.id)) + .innerJoin(parentArchive, eq(parentArchive.root, lastArchive.root)) + .innerJoin( + parent, + and( + eq(parent.hash, parentArchive.fk), + eq(parent.height, sql`${l2Block.height} - 1`), + eq(parent.version, l2Block.version), + ), + ) + .where( + and(inArray(l2Block.hash, part), isNotNull(parent.orphan_timestamp)), + ); + deadParent.push(...rows.map((r) => r.hash)); + }, + ); const child = alias(l2Block, "child"); const childHeader = alias(header, "child_header"); const childLastArchive = alias(lastArchive, "child_last_archive"); - const moved = [...change.demoted.keys(), ...change.promoted.keys()]; + const moved = [ + ...change.demoted.keys(), + ...change.promoted.keys(), + ...storedOff, + ]; const liveParent: HexString[] = []; await inStatements(change, moved, async (part) => { const rows = await change.dbTx @@ -705,7 +715,11 @@ const refreshOrphanFlags = async (change: Change) => { }; /** The writes that follow the decision, in the same transaction. */ -const settle = async (change: Change, attached: ChicmozL2Block | undefined) => { +const settle = async ( + change: Change, + block: ChicmozL2Block, + { canonical, created }: { canonical: boolean; created: boolean }, +) => { if (change.demoted.size > 0) { await recordReorg(change); } @@ -713,12 +727,14 @@ const settle = async (change: Change, attached: ChicmozL2Block | undefined) => { const mined = new Set( (await ownedTxs(change, [...change.promoted.keys()])).map((t) => t.txHash), ); - attached?.body.txEffects.forEach((e) => mined.add(e.txHash)); + if (canonical) { + block.body.txEffects.forEach((e) => mined.add(e.txHash)); + } await inStatements(change, [...mined], (part) => removePendingAndDroppedTx(change.dbTx, part), ); await reviveRecords(change); - await refreshOrphanFlags(change); + await refreshOrphanFlags(change, created && !canonical ? [block.hash] : []); await inStatements( change, [...new Set([...change.walked.values(), ...change.repairs])], @@ -760,7 +776,7 @@ const apply = async ( if (canonical) { await storeBlockContracts(dbTx, contracts); } - await settle(change, canonical ? block : undefined); + await settle(change, block, { canonical, created: stored.created }); logger.info( `๐Ÿงข Applied ${ordered ? "ordered" : "catch-up"} block ${block.height} (${block.hash}): ${canonical ? "canonical" : "off the chain"}; demoted ${change.demoted.size}, made canonical ${change.promoted.size}`, ); 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 e5edc308..0584bbe8 100644 --- a/services/explorer-api/tests/integration/chain-head.integration.test.ts +++ b/services/explorer-api/tests/integration/chain-head.integration.test.ts @@ -502,6 +502,38 @@ describe("the canonical chain on a real database", () => { expect(await reads.repairOpen(7_001)).toBe(false); }); + it("flags a new off-chain block whose stored parent is off the chain, whichever of the two arrives first", async () => { + const version = freshVersion(); + const live = await buildChain(20_000n, 3, { version }); + for (const block of live) { + await ordered(block); + } + const offChainPair = async () => { + const parent = await buildBlock(20_001n, [freshTxHash()], { + version, + parent: live[0], + }); + const child = await buildBlock(20_002n, [freshTxHash()], { + version, + parent, + }); + return { parent, child }; + }; + const parentFirst = await offChainPair(); + const childFirst = await offChainPair(); + + await catchup(parentFirst.parent); + await catchup(parentFirst.child); + await catchup(childFirst.child); + await catchup(childFirst.parent); + + expect( + await Promise.all( + [parentFirst.child, childFirst.child].map((b) => reads.stateOf(b.hash)), + ), + ).toEqual([{ hasOrphanedParent: true }, { hasOrphanedParent: true }]); + }); + it("brings back a live block the old code orphaned without demoting the chain above it", async () => { const version = freshVersion(); const live = await buildChain(8_000n, 5, { version }); From a2ee6dfc9bd44b81c02640480e22f3ff02ed04cd Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Thu, 26 Nov 2026 22:34:31 +0000 Subject: [PATCH 12/31] fix(explorer-api): close a repair in the change that makes its block canonical The post-commit height hook closed a repair whenever any block stood at its height, so a delayed hook could close a repair that a later change opened for another block. A repair now closes inside the change whose block message made the block at its height canonical, and the hook leaves repairs alone. Repair rows carry no rollup version, so a block of another version at that height still closes one. Co-Authored-By: Claude Opus 5.5 --- .../database/controllers/l2block/canonical.ts | 5 +++- .../controllers/l2block/missing-ranges.ts | 28 +++++++++++++++++-- .../chain-head.integration.test.ts | 28 +++++++++++++++++++ .../integration/open-gap.integration.test.ts | 5 ++-- 4 files changed, 61 insertions(+), 5 deletions(-) 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 7bbd86c5..14cf0710 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts @@ -21,7 +21,7 @@ import { } from "../l2contract/store.js"; import { removePendingAndDroppedTx } from "../l2Tx/remove-pending-and-dropped.js"; import { type DbTx } from "../utils.js"; -import { recordRepairHeights } from "./missing-ranges.js"; +import { fulfilRepairHeight, recordRepairHeights } from "./missing-ranges.js"; import { store, writeTxEffect } from "./store.js"; // Every change to which blocks are canonical goes through this module. @@ -740,6 +740,9 @@ const settle = async ( [...new Set([...change.walked.values(), ...change.repairs])], (part) => recordRepairHeights(change.dbTx, part), ); + if (canonical) { + await fulfilRepairHeight(change.dbTx, block.height); + } }; const ownerSummary = (owners: TxOwner[]) => 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 26d4c83b..392a3101 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 @@ -155,8 +155,8 @@ const CANDIDATE_GAP_LIMIT = 50; const TIP_BOUNDARY_REASON: L2BlockRangeRequestReason = "tip_boundary_mismatch"; // One height whose block message must come back: the canonical block there // lacks it, or the height was cleared under a block whose parent is missing. -// Requested whole, present or not, until a canonical attach from a block -// message fulfils it (markOpenGapsFulfilledByHeight). +// Requested whole, present or not, until a block message makes the block at +// that height canonical (fulfilRepairHeight, inside that change). const REPAIR_REASON: L2BlockRangeRequestReason = "reorg_repair"; export const recordRepairHeights = async ( @@ -174,6 +174,29 @@ export const recordRepairHeights = async ( }); }; +/** + * Closes the repair of `height`, in the transaction whose block message made + * the block there canonical. Repair rows carry no rollup version, so any + * version's block at the height closes it. + */ +export const fulfilRepairHeight = async ( + executor: ReturnType, + height: bigint, +) => { + await executor + .update(l2OpenGapTable) + .set({ status: "fulfilled", fulfilledAt: new Date(), lastError: null }) + .where( + and( + eq(l2OpenGapTable.l2NetworkId, L2_NETWORK_ID), + eq(l2OpenGapTable.reason, REPAIR_REASON), + eq(l2OpenGapTable.status, "open"), + eq(l2OpenGapTable.fromHeight, Number(height)), + eq(l2OpenGapTable.toHeight, Number(height)), + ), + ); +}; + /** * Whether a gap may be requested again at `now` (epoch ms): never requested, * or its backoff has passed. In SQL so the candidate query can filter on it @@ -623,6 +646,7 @@ export const markOpenGapsFulfilledByHeight = async (height: bigint) => { and( eq(l2OpenGapTable.l2NetworkId, L2_NETWORK_ID), eq(l2OpenGapTable.status, "open"), + ne(l2OpenGapTable.reason, REPAIR_REASON), lte(l2OpenGapTable.fromHeight, Number(height)), gte(l2OpenGapTable.toHeight, Number(height)), ), 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 0584bbe8..0faab3c0 100644 --- a/services/explorer-api/tests/integration/chain-head.integration.test.ts +++ b/services/explorer-api/tests/integration/chain-head.integration.test.ts @@ -46,6 +46,7 @@ describe("the canonical chain on a real database", () => { event: NewBlockEvent, ) => Promise<{ deliveries: number; rebalances: number; beats: number }>; let holdChainLock: () => Promise<() => Promise>; + let fulfilByHeight: (height: bigint) => Promise; let walkBound: number; beforeAll(async () => { @@ -56,6 +57,9 @@ describe("the canonical chain on a real database", () => { const { WALK_BOUND, withChainLock } = await import( "../../src/svcs/database/controllers/l2block/canonical.js" ); + const { markOpenGapsFulfilledByHeight } = await import( + "../../src/svcs/database/controllers/l2block/missing-ranges.js" + ); const { l2Block } = await import( "../../src/svcs/database/schema/l2block/index.js" ); @@ -247,6 +251,7 @@ describe("the canonical chain on a real database", () => { await held; }; }; + fulfilByHeight = markOpenGapsFulfilledByHeight; }); afterAll(async () => { @@ -502,6 +507,29 @@ describe("the canonical chain on a real database", () => { expect(await reads.repairOpen(7_001)).toBe(false); }); + it("keeps a repair open when a stale post-commit hook runs after a walk revived its height", async () => { + const version = freshVersion(); + const [p, a] = await buildChain(19_000n, 2, { version }); + const b = await buildBlock(19_001n, [freshTxHash()], { + version, + parent: p, + }); + const next = await buildBlock(19_002n, [freshTxHash()], { + version, + parent: b, + }); + await ordered(p); + await ordered(a); + await catchup(b); + await ordered(next); + expect(await reads.repairOpen(19_001)).toBe(true); + + // `a`'s hook, delayed past the change that replaced it. + await fulfilByHeight(19_001n); + + expect(await reads.repairOpen(19_001)).toBe(true); + }); + it("flags a new off-chain block whose stored parent is off the chain, whichever of the two arrives first", async () => { const version = freshVersion(); const live = await buildChain(20_000n, 3, { version }); 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 26423d2f..1bd7abdb 100644 --- a/services/explorer-api/tests/integration/open-gap.integration.test.ts +++ b/services/explorer-api/tests/integration/open-gap.integration.test.ts @@ -61,6 +61,7 @@ describe("open gap scheduling on a real database", () => { ); const { buildMissingBlockRangeRequest, + fulfilRepairHeight, markOpenGapsFulfilledByHeight, recordRepairHeights, } = await import( @@ -108,8 +109,8 @@ describe("open gap scheduling on a real database", () => { .where(eq(l2Block.hash, hashOf(height, CURRENT))); }; repair = (height) => recordRepairHeights(db, [BigInt(height)]); - // What blockHandler does after a block message makes its block canonical. - fulfil = (height) => markOpenGapsFulfilledByHeight(BigInt(height)); + // What a block message's change does when it makes its block canonical. + fulfil = (height) => fulfilRepairHeight(db, BigInt(height)); seedGaps = async (rows) => { const now = Date.now(); await db.insert(l2OpenGapTable).values( From ca0d3788c16084fa4e7459bbad1f3c7ad3a81489 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Thu, 26 Nov 2026 22:37:23 +0000 Subject: [PATCH 13/31] test(explorer-api): observe the chain lock wait in the serialization test The test also passed without the lock whenever the two transactions ran one after the other. It now holds the chain lock, waits until both consumers queue on it with neither finished, then releases it and checks that the height ends with one canonical block. Co-Authored-By: Claude Opus 5.5 --- .../chain-head.integration.test.ts | 68 ++++++++++++------- 1 file changed, 42 insertions(+), 26 deletions(-) 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 0faab3c0..6a36421a 100644 --- a/services/explorer-api/tests/integration/chain-head.integration.test.ts +++ b/services/explorer-api/tests/integration/chain-head.integration.test.ts @@ -46,6 +46,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 fulfilByHeight: (height: bigint) => Promise; let walkBound: number; @@ -251,6 +252,14 @@ describe("the canonical chain on a real database", () => { 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; + }; fulfilByHeight = markOpenGapsFulfilledByHeight; }); @@ -758,35 +767,42 @@ describe("the canonical chain on a real database", () => { expect(await reads.stateOf(block.hash)).toBe("absent"); }); - it("leaves one canonical block when the block and catch-up consumers store one height at once", async () => { - // Ten heights at once, so that without the lock some height's two - // transactions overlap. - const races = await Promise.all( - Array.from({ length: 10 }, async () => { - const version = freshVersion(); - const [p] = await buildChain(13_000n, 1, { version }); - const [fromStream, fromCatchup] = await Promise.all( - [0, 1].map(() => - buildBlock(13_001n, [freshTxHash()], { version, parent: p }), - ), - ); - return { version, p, fromStream, fromCatchup }; - }), - ); - for (const { p } of races) { - await ordered(p); - } - - await Promise.all( - races.flatMap(({ fromStream, fromCatchup }) => [ - ordered(fromStream), - catchup(fromCatchup, { final: true }), - ]), + it("serializes the block and catch-up consumers storing one height on the chain lock", async () => { + const version = freshVersion(); + const [p] = await buildChain(13_000n, 1, { version }); + const [fromStream, fromCatchup] = await Promise.all( + [0, 1].map(() => + buildBlock(13_001n, [freshTxHash()], { version, parent: p }), + ), ); + const above = await buildBlock(13_002n, [freshTxHash()], { + version, + parent: fromCatchup, + }); + await ordered(p); + await ordered(above); - for (const { version, p, fromStream } of races) { - expect(await reads.chainOf(version)).toEqual(heads([p, fromStream])); + const release = await holdChainLock(); + const finished: string[] = []; + const delivered = Promise.all([ + ordered(fromStream).then(() => finished.push("block")), + 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)); + } + expect(finished).toEqual([]); + } finally { + await release(); } + await delivered; + + expect(await reads.chainOf(version)).toEqual(heads([p, fromStream])); }); describe("bounds", () => { From 0656b3f394141753e9d465f12a38a2347b1d242f Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Thu, 26 Nov 2026 22:38:35 +0000 Subject: [PATCH 14/31] docs(explorer-api): state what the chain lock covers The dropped- and pending-tx handlers write without the chain lock, and lock_timeout bounds every lock wait in the transaction, not only the lock's own. Drops two summaries that restated their code, and the late-replacing test's note on its expected failure, keeping the fixture's height constraint. Co-Authored-By: Claude Opus 5.5 --- .../svcs/database/controllers/l2block/canonical.ts | 12 ++++-------- .../late-replacing-block.integration.test.ts | 3 +-- 2 files changed, 5 insertions(+), 10 deletions(-) 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 14cf0710..19be7692 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts @@ -46,9 +46,10 @@ 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: - * every chain mutation, and every write that depends on one, serializes on - * it. A lock wait over 10 s throws, so the message is redelivered. + * 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) => { @@ -714,7 +715,6 @@ const refreshOrphanFlags = async (change: Change, storedOff: HexString[]) => { await setHasOrphanedParent(change, liveParent, false); }; -/** The writes that follow the decision, in the same transaction. */ const settle = async ( change: Change, block: ChicmozL2Block, @@ -750,10 +750,6 @@ const ownerSummary = (owners: TxOwner[]) => .map((o) => `${o.txHash} in active block ${o.height} (${o.blockHash})`) .join(", "); -/** - * Stores the block if absent, lets `decide` move the chain, then attaches - * the block's txs and contracts when it ends canonical. - */ const apply = async ( { block, contracts }: IncomingBlock, heartbeat: Heartbeat, 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 31295f22..efc26f21 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 @@ -19,8 +19,7 @@ const word = (n: number): HexString => `0x${n.toString(16).padStart(64, "0")}`; // A block at a height the chain replaced can stay stored while the replacing // chain's next blocks are stored above it. Every canonical block of the // version above an ordered block's tip is demoted, so the cases use -// ascending, disjoint heights, in file order. it.fails marks the current -// behaviour; drop it once fixed. +// ascending, disjoint heights, in file order. describe("a replaced block that stays stored on a real database", () => { let api: ExplorerApiForTest; let store: (b: BuiltBlock) => Promise; From fefe4b1d59b0665e124387ab85c27f46ed83f6b8 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Thu, 26 Nov 2026 23:16:38 +0000 Subject: [PATCH 15/31] test(explorer-api): pin how the next ordered block heals a stale catch-up A catch-up block that links to a stale canonical block above a gap can undo an ordered block: it brings the replaced block back and demotes the ordered one. The next ordered block puts it back. The test pins both steps, and that /l2/reorgs then lists only the record rooted at the replaced block. Co-Authored-By: Claude Opus 5.5 --- .../chain-head.integration.test.ts | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) 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 6a36421a..8499eb51 100644 --- a/services/explorer-api/tests/integration/chain-head.integration.test.ts +++ b/services/explorer-api/tests/integration/chain-head.integration.test.ts @@ -444,6 +444,34 @@ describe("the canonical chain on a real database", () => { expect(await reads.repairOpen(17_001)).toBe(true); }); + it("puts back an ordered block that a stale catch-up undid once the next ordered block arrives, listing one reorg", async () => { + const version = freshVersion(); + const [a1, a2, a3, a4] = await buildChain(24_001n, 4, { version }); + const [b2, b3] = await buildChain(24_002n, 2, { version, parent: a1 }); + for (const block of [a1, a2, a4]) { + await ordered(block); + } + // A4 stays canonical across the gap at 24_003, above B2. + await ordered(b2, 24_004); + // A3 links to A4, so it brings A2 back and demotes B2. + await catchup(a3); + expect(await reads.chainOf(version)).toEqual(heads([a1, a2, a3, a4])); + + await ordered(b3, 24_004); + + expect(await reads.chainOf(version)).toEqual(heads([a1, b2, b3])); + expect( + await Promise.all([a2, a3, a4].map((b) => reads.stateOf(b.hash))), + ).toEqual([ + { hasOrphanedParent: false }, + { hasOrphanedParent: true }, + { hasOrphanedParent: true }, + ]); + expect(await reads.listed([a2, a3, a4, b2, b3])).toEqual([ + { orphanedBlockHash: a2.hash, height: 24_002n, nbrOfOrphanedBlocks: 3 }, + ]); + }); + it("walks repairs back from an ordered block far above the head, one per attach, until they meet the old chain", async () => { const version = freshVersion(); const [a0, a1] = await buildChain(18_000n, 2, { version }); From 0cad20de4507e2cc182413285aa348092886a5a5 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Thu, 26 Nov 2026 23:21:29 +0000 Subject: [PATCH 16/31] fix(explorer-api): clear the height a walk down stops at before requesting it A walk that brought back WALK_BOUND blocks asked for the height below the last one but left that height's canonical block in place, so the parent the request brought back could never join there. The bound now clears the height first, as a missing parent does. The test's bulk chain can now be inserted off the chain and returns its top block as a parent for a built block. Co-Authored-By: Claude Opus 5.5 --- .../database/controllers/l2block/canonical.ts | 10 +--- .../chain-head.integration.test.ts | 60 +++++++++++++++++-- 2 files changed, 58 insertions(+), 12 deletions(-) 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 19be7692..75fe37d6 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts @@ -337,17 +337,13 @@ const demoteHolders = async ( /** * Brings back the stored, off-chain ancestors of a block that just became * canonical, demoting their competitors. Ends at a canonical parent; at a - * missing one it clears that height, whose block cannot be the parent, and - * asks for the parent. + * missing one, or after WALK_BOUND blocks, it clears that height, whose block + * cannot be the parent, and asks for the parent. */ const reviveAncestors = async (change: Change, start: ChainBlock) => { let child = start; for (let steps = 0; child.height > 1n; steps++) { const below = child.height - 1n; - if (steps === WALK_BOUND) { - change.repairs.add(below); - return; - } await step(change); const parents = await storedParents(change, child); if (parents.length > 1) { @@ -361,7 +357,7 @@ const reviveAncestors = async (change: Change, start: ChainBlock) => { return; } await demote(change, await canonicalAt(change, below)); - if (!parent) { + if (!parent || steps === WALK_BOUND) { change.repairs.add(below); return; } 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 8499eb51..a8dd414c 100644 --- a/services/explorer-api/tests/integration/chain-head.integration.test.ts +++ b/services/explorer-api/tests/integration/chain-head.integration.test.ts @@ -1,3 +1,6 @@ +import { TreeLeafIndex } from "@aztec-labs/foundation/branded-types"; +import { Fr } from "@aztec-labs/foundation/curves/bn254"; +import { AppendOnlyTreeSnapshot } from "@aztec-labs/stdlib/trees"; import { type Heartbeat } from "@chicmoz-pkg/message-bus"; import { type NewBlockEvent } from "@chicmoz-pkg/message-registry"; import { deliver } from "@chicmoz/test-harness"; @@ -41,7 +44,8 @@ describe("the canonical chain on a real database", () => { from: bigint; count: number; parent?: BuiltBlock; - }) => Promise; + offChain?: true; + }) => Promise>; let throughBroker: ( event: NewBlockEvent, ) => Promise<{ deliveries: number; rebalances: number; beats: number }>; @@ -93,9 +97,10 @@ describe("the canonical chain on a real database", () => { ), ); }; - // Canonical blocks with only the rows a link lookup reads, inserted in - // bulk: delivering thousands of blocks would take minutes. - bareChain = async ({ version, from, count, parent }) => { + // Linked blocks, canonical unless `offChain`, with only the rows a link + // lookup reads, inserted in bulk: delivering thousands of blocks would + // take minutes. Returns the top block, as a parent for a built block. + bareChain = async ({ version, from, count, parent, offChain }) => { const to = from + BigInt(count - 1); const tag = version.toString(16).padStart(8, "0"); const hashOf = (n: SQL) => @@ -104,8 +109,9 @@ describe("the canonical chain on a real database", () => { sql`'0x' || ${tag}::text || 'ff' || lpad(to_hex(${n}), 54, '0')`; const n = sql`n`; const heights = sql`generate_series(${from}::bigint, ${to}::bigint) AS n`; + const orphanedAt = offChain ? sql`${Date.now()}::bigint` : sql`NULL`; await db.execute( - sql`INSERT INTO "l2Block" ("hash", "height", "version") SELECT ${hashOf(n)}, n, ${version}::bigint FROM ${heights}`, + sql`INSERT INTO "l2Block" ("hash", "height", "version", "orphan_timestamp", "orphan_hasOrphanedParent") SELECT ${hashOf(n)}, n, ${version}::bigint, ${orphanedAt}, ${offChain ? sql`false` : sql`NULL`} FROM ${heights}`, ); await db.execute( sql`INSERT INTO "archive" ("root", "next_available_leaf_index", "block_hash") SELECT ${rootOf(n)}, 0, ${hashOf(n)} FROM ${heights}`, @@ -123,6 +129,13 @@ describe("the canonical chain on a real database", () => { FROM "header" h JOIN "l2Block" b ON b."hash" = h."block_hash" WHERE b."version" = ${version}::bigint AND ${height} BETWEEN ${from}::bigint AND ${to}::bigint AND b."hash" = ${hashOf(height)}`, ); + const top = `0x${tag}ff${to.toString(16).padStart(54, "0")}`; + return { + archive: new AppendOnlyTreeSnapshot( + Fr.fromHexString(top), + TreeLeafIndex(0), + ), + }; }; const kafka = new Kafka({ clientId: `${api.namespace}-chain-walk`, @@ -867,6 +880,43 @@ describe("the canonical chain on a real database", () => { ]); }, 300_000); + it("stops a walk down at the bound, clearing and requesting the height below it, where the parent's catch-up then joins", async () => { + const version = freshVersion(); + const from = 400_000n; + const [base] = await buildChain(from - 1n, 1, { version }); + const [parent, competitor] = await Promise.all( + [0, 1].map(() => + buildBlock(from, [freshTxHash()], { version, parent: base }), + ), + ); + await ordered(base); + await ordered(competitor); + const top = await bareChain({ + version, + from: from + 1n, + count: walkBound, + parent, + offChain: true, + }); + const head = await buildBlock( + from + BigInt(walkBound) + 1n, + [freshTxHash()], + { version, parent: top }, + ); + + await ordered(head); + expect( + await Promise.all( + [competitor, parent].map((b) => reads.stateOf(b.hash)), + ), + ).toEqual([{ hasOrphanedParent: false }, "absent"]); + expect(await reads.repairOpen(Number(from))).toBe(true); + + await catchup(parent); + expect(await reads.stateOf(parent.hash)).toBe("canonical"); + expect(await reads.repairOpen(Number(from))).toBe(false); + }, 300_000); + it("throws, changing nothing, on more canonical blocks above a tip than the bound, and heartbeats through demoting exactly the bound", async () => { const version = freshVersion(); const from = 200_000n; From 74adf5e94866cecda4227a808f62687b934a1e0d Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Thu, 26 Nov 2026 23:29:13 +0000 Subject: [PATCH 17/31] fix(explorer-api): keep an older rollup version's block from closing a repair Repair rows carry no rollup version, so a canonical block of an older version at a repaired height closed a newer version's repair, and the txs a walked block had moved stayed dropped. A block now closes a repair only while no newer version is stored. The check reads max(version), one entry of l2block_version_idx: a NOT EXISTS on newer versions is planned as a seq scan past every older version's row, inside the chain lock. Co-Authored-By: Claude Opus 5.5 --- .../database/controllers/l2block/canonical.ts | 2 +- .../controllers/l2block/missing-ranges.ts | 9 +++++++-- .../chain-head.integration.test.ts | 19 +++++++++++++++++++ .../integration/open-gap.integration.test.ts | 2 +- 4 files changed, 28 insertions(+), 4 deletions(-) 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 75fe37d6..14360f4b 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts @@ -737,7 +737,7 @@ const settle = async ( (part) => recordRepairHeights(change.dbTx, part), ); if (canonical) { - await fulfilRepairHeight(change.dbTx, block.height); + await fulfilRepairHeight(change.dbTx, block.height, change.version); } }; 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 392a3101..3523b43c 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 @@ -176,12 +176,14 @@ export const recordRepairHeights = async ( /** * Closes the repair of `height`, in the transaction whose block message made - * the block there canonical. Repair rows carry no rollup version, so any - * version's block at the height closes it. + * the block of rollup `version` there canonical. Repair rows carry no + * version, so the block closes one only while no newer version is stored: + * an older version's block must not close a newer version's repair. */ export const fulfilRepairHeight = async ( executor: ReturnType, height: bigint, + version: number, ) => { await executor .update(l2OpenGapTable) @@ -193,6 +195,9 @@ export const fulfilRepairHeight = async ( eq(l2OpenGapTable.status, "open"), eq(l2OpenGapTable.fromHeight, Number(height)), eq(l2OpenGapTable.toHeight, Number(height)), + // max() reads one entry of l2block_version_idx; a NOT EXISTS on newer + // versions is planned as a scan past every older version's row. + lte(sql`(SELECT max(${l2Block.version}) FROM ${l2Block})`, version), ), ); }; 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 a8dd414c..3e146e77 100644 --- a/services/explorer-api/tests/integration/chain-head.integration.test.ts +++ b/services/explorer-api/tests/integration/chain-head.integration.test.ts @@ -580,6 +580,25 @@ describe("the canonical chain on a real database", () => { expect(await reads.repairOpen(19_001)).toBe(true); }); + it("keeps a repair open when an older rollup version's block fills its height, and closes it with the newer version's", async () => { + const older = freshVersion(); + const newer = freshVersion(); + const [o1, o2] = await buildChain(22_001n, 2, { version: older }); + const [n1, n2] = await buildChain(22_001n, 2, { version: newer }); + // Each version's block at 22_002 lacks its parent, so 22_001 is requested. + await ordered(o2); + await ordered(n2); + expect(await reads.repairOpen(22_001)).toBe(true); + + await catchup(o1); + expect(await reads.stateOf(o1.hash)).toBe("canonical"); + expect(await reads.repairOpen(22_001)).toBe(true); + + await catchup(n1); + expect(await reads.stateOf(n1.hash)).toBe("canonical"); + expect(await reads.repairOpen(22_001)).toBe(false); + }); + it("flags a new off-chain block whose stored parent is off the chain, whichever of the two arrives first", async () => { const version = freshVersion(); const live = await buildChain(20_000n, 3, { version }); 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 1bd7abdb..56618cdd 100644 --- a/services/explorer-api/tests/integration/open-gap.integration.test.ts +++ b/services/explorer-api/tests/integration/open-gap.integration.test.ts @@ -110,7 +110,7 @@ describe("open gap scheduling on a real database", () => { }; repair = (height) => recordRepairHeights(db, [BigInt(height)]); // What a block message's change does when it makes its block canonical. - fulfil = (height) => fulfilRepairHeight(db, BigInt(height)); + fulfil = (height) => fulfilRepairHeight(db, BigInt(height), CURRENT); seedGaps = async (rows) => { const now = Date.now(); await db.insert(l2OpenGapTable).values( From 8982fd38c8a95aa41c56fedc2d3477e99f4e3a2a Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Thu, 26 Nov 2026 23:42:01 +0000 Subject: [PATCH 18/31] fix(explorer-api): let a walked block's catch-up take its txs from stale holders below A block a walk made canonical gets its txs back from its own message, the catch-up its repaired height asks for. A canonical block of another chain below it could still hold one of those txs: attaching them threw TxConflict, the change rolled back, and the repair was asked for again without end. A canonical block with a canonical child linked to it now has the chain above's authority below its height, as a catch-up joined from above has: its catch-up demotes the holders of its txs below it, with their linked runs, and asks for the heights that leaves empty. Without such a child it is handled as before. Co-Authored-By: Claude Opus 5.5 --- .../database/controllers/l2block/canonical.ts | 14 +++++- .../chain-head.integration.test.ts | 46 +++++++++++++++++++ 2 files changed, 59 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 14360f4b..263e425d 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts @@ -837,7 +837,10 @@ export const applyOrderedBlock = ( * the holders of its txs there go, its stored ancestors come back and the * heights left empty are asked for, as for an ordered block; or, with * `final` (at or below the serving node's own finalized tip), when the - * canonical block below, if any, is its parent. + * canonical block below, if any, is its parent. A canonical block with a + * canonical child linked to it, as one a walk brought back, has the same + * authority: the holders of its txs below it go, and the heights left empty + * are asked for. */ export const applyCatchupBlock = ( incoming: IncomingBlock, @@ -846,6 +849,15 @@ export const applyCatchupBlock = ( ): Promise => apply(incoming, heartbeat, { ordered: false }, async (change, stored) => { if (stored.canonical) { + const children = await canonicalChildren( + change, + [stored], + stored.height + 1n, + ); + if (children.length > 0) { + await demoteHolders(change, incoming.block, stored.height - 1n); + await requestEmptied(change, stored.height); + } return true; } if ((await canonicalAt(change, stored.height)).length > 0) { 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 3e146e77..e38daeed 100644 --- a/services/explorer-api/tests/integration/chain-head.integration.test.ts +++ b/services/explorer-api/tests/integration/chain-head.integration.test.ts @@ -789,6 +789,52 @@ describe("the canonical chain on a real database", () => { ]).toEqual([true, true]); }); + it("demotes a stale canonical holder of a tx below a block a walk made canonical when its catch-up arrives, requesting the heights that leaves empty and closing the block's repair", async () => { + const version = freshVersion(); + const x = freshTxHash(); + const a0 = await buildBlock(23_000n, [freshTxHash()], { version }); + const a1 = await buildBlock(23_001n, [x], { version, parent: a0 }); + const a2 = await buildBlock(23_002n, [freshTxHash()], { + version, + parent: a1, + }); + const a3 = await buildBlock(23_003n, [freshTxHash()], { + version, + parent: a2, + }); + for (const block of [a0, a1, a2, a3]) { + await ordered(block); + } + const b1 = await buildBlock(23_001n, [freshTxHash()], { + version, + parent: a0, + }); + const b2 = await buildBlock(23_002n, [freshTxHash()], { + version, + parent: b1, + }); + const b3 = await buildBlock(23_003n, [x], { version, parent: b2 }); + const b4 = await buildBlock(23_004n, [freshTxHash()], { + version, + parent: b3, + }); + await catchup(b3); + await ordered(b4); + expect(await reads.chainOf(version)).toEqual(heads([a0, a1, b3, b4])); + expect(await reads.repairOpen(23_003)).toBe(true); + + await catchup(b3); + + expect(await reads.chainOf(version)).toEqual(heads([a0, b3, b4])); + expect(await reads.ownerOf(x)).toBe(b3.hash); + expect(await reads.stateOf(a1.hash)).toEqual({ hasOrphanedParent: false }); + expect([ + await reads.repairOpen(23_001), + await reads.repairOpen(23_002), + await reads.repairOpen(23_003), + ]).toEqual([true, true, false]); + }); + it("treats a parent lookup that finds two blocks as a missing parent", async () => { const version = freshVersion(); const [p] = await buildChain(11_000n, 1, { version }); From 834f64008249eb8d822fdbc3df0c59d051fc7d08 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Thu, 26 Nov 2026 23:47:35 +0000 Subject: [PATCH 19/31] test(explorer-api): name the repair chaining test for what it delivers The test hands each catch-up block to the handler itself, so its name says what each joining block opens, not that repairs are walked back one per attach. Co-Authored-By: Claude Opus 5.5 --- .../tests/integration/chain-head.integration.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 e38daeed..0abd600e 100644 --- a/services/explorer-api/tests/integration/chain-head.integration.test.ts +++ b/services/explorer-api/tests/integration/chain-head.integration.test.ts @@ -485,7 +485,7 @@ describe("the canonical chain on a real database", () => { ]); }); - it("walks repairs back from an ordered block far above the head, one per attach, until they meet the old chain", async () => { + it("opens a repair at the parent height of each catch-up block that joins below an ordered block far above the head, until one joins on the old chain", async () => { const version = freshVersion(); const [a0, a1] = await buildChain(18_000n, 2, { version }); const b = await buildChain(18_001n, 5, { version, parent: a0 }); From 85ceb79718a8f7307c8b4c0327b5d448e078ca4a Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Thu, 26 Nov 2026 23:56:58 +0000 Subject: [PATCH 20/31] fix(explorer-api): heartbeat inside a chain change's per-row write loops Inside the chain lock, removePendingAndDroppedTx runs one UPDATE per pending tx and storeBlockContracts one savepoint per contract row, with no heartbeat between them. Both now heartbeat before each row. In storeBlockContracts the heartbeat sits outside the row's error handling, so a failed heartbeat aborts the change instead of being logged as a failed row. The settlement heartbeat test counted the beats of demoting the bound, which come before settlement, so it passed with settlement's heartbeats removed. Its own test now settles a block that walks and demotes nothing, where every beat comes from settlement; the bound test keeps only the bound. Co-Authored-By: Claude Opus 5.5 --- .../l2Tx/remove-pending-and-dropped.ts | 3 + .../database/controllers/l2block/canonical.ts | 4 +- .../database/controllers/l2contract/store.ts | 6 +- .../chain-head.integration.test.ts | 25 ++++-- .../tests/unit/chain-write-heartbeats.test.ts | 85 +++++++++++++++++++ 5 files changed, 112 insertions(+), 11 deletions(-) create mode 100644 services/explorer-api/tests/unit/chain-write-heartbeats.test.ts diff --git a/services/explorer-api/src/svcs/database/controllers/l2Tx/remove-pending-and-dropped.ts b/services/explorer-api/src/svcs/database/controllers/l2Tx/remove-pending-and-dropped.ts index 24313b95..c1af0ef3 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2Tx/remove-pending-and-dropped.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2Tx/remove-pending-and-dropped.ts @@ -1,3 +1,4 @@ +import { type Heartbeat } from "@chicmoz-pkg/message-bus"; import { type HexString } from "@chicmoz-pkg/types"; import { eq, inArray } from "drizzle-orm"; import { logger } from "../../../../logger.js"; @@ -14,6 +15,7 @@ import { type DbTx } from "../utils.js"; export const removePendingAndDroppedTx = async ( dbTx: DbTx, txHashes: HexString[], + heartbeat: Heartbeat, ): Promise => { if (txHashes.length === 0) { return; @@ -29,6 +31,7 @@ export const removePendingAndDroppedTx = async ( }); for (const pendingTx of pending) { logger.info(`๐Ÿ•๐Ÿ”ฅ deleted pending tx ${pendingTx.txHash}`); + await heartbeat(); await dbTx .update(txEffect) .set({ 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 263e425d..c54ff899 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts @@ -727,7 +727,7 @@ const settle = async ( block.body.txEffects.forEach((e) => mined.add(e.txHash)); } await inStatements(change, [...mined], (part) => - removePendingAndDroppedTx(change.dbTx, part), + removePendingAndDroppedTx(change.dbTx, part, change.heartbeat), ); await reviveRecords(change); await refreshOrphanFlags(change, created && !canonical ? [block.hash] : []); @@ -769,7 +769,7 @@ const apply = async ( const canonical = await decide(change, stored); await attachTxs(change, stored, block, { canonical }); if (canonical) { - await storeBlockContracts(dbTx, contracts); + await storeBlockContracts(dbTx, contracts, heartbeat); } await settle(change, block, { canonical, created: stored.created }); logger.info( 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 4ed653e9..348f452c 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2contract/store.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2contract/store.ts @@ -1,3 +1,4 @@ +import { type Heartbeat } from "@chicmoz-pkg/message-bus"; import { getDb as db } from "@chicmoz-pkg/postgres-helper"; import { ChicmozL2ContractInstanceUpdatedEvent, @@ -77,11 +78,13 @@ 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. + * stored) is logged and skipped without aborting the block; a failed + * heartbeat, taken before each row, aborts it. */ export const storeBlockContracts = async ( dbTx: DbTx, { classes, instancesDeployed, instancesUpdated }: BlockContracts, + heartbeat: Heartbeat, ): Promise => { const each = async ( rows: T[], @@ -89,6 +92,7 @@ export const storeBlockContracts = async ( write: (row: T, executor: DbTx) => Promise, ) => { for (const row of rows) { + await heartbeat(); try { await dbTx.transaction((savepoint) => write(row, savepoint)); } catch (e) { 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 0abd600e..dd4dd4f0 100644 --- a/services/explorer-api/tests/integration/chain-head.integration.test.ts +++ b/services/explorer-api/tests/integration/chain-head.integration.test.ts @@ -911,6 +911,20 @@ describe("the canonical chain on a real database", () => { expect(await reads.chainOf(version)).toEqual(heads([p, fromStream])); }); + it("heartbeats while settling a block that walks and demotes nothing", async () => { + const version = freshVersion(); + const [block] = await buildChain(25_000n, 1, { version }); + let beats = 0; + + await orderedWith(orderedEvent(block), () => { + beats++; + return Promise.resolve(); + }); + + expect(await reads.stateOf(block.hash)).toBe("canonical"); + expect(beats).toBeGreaterThan(0); + }); + describe("bounds", () => { it("stops a walk at the bound without throwing, keeps its partition through it, and rolls back when a heartbeat fails", async () => { const version = freshVersion(); @@ -982,7 +996,7 @@ describe("the canonical chain on a real database", () => { expect(await reads.repairOpen(Number(from))).toBe(false); }, 300_000); - it("throws, changing nothing, on more canonical blocks above a tip than the bound, and heartbeats through demoting exactly the bound", async () => { + it("throws, changing nothing, on more canonical blocks above a tip than the bound, and demotes exactly the bound", async () => { const version = freshVersion(); const from = 200_000n; await bareChain({ version, from: from + 1n, count: walkBound + 1 }); @@ -994,18 +1008,13 @@ describe("the canonical chain on a real database", () => { expect(await reads.stateOf(block.hash)).toBe("absent"); expect(await reads.chainOf(version)).toHaveLength(walkBound + 1); - // No walk to heartbeat in: one replaced block, the bound above the tip. + // Replacing the lowest of them leaves exactly the bound above the tip. const replacing = await buildBlock(from + 1n, [freshTxHash()], { version, }); - let beats = 0; - await orderedWith(orderedEvent(replacing), () => { - beats++; - return Promise.resolve(); - }); + await ordered(replacing); expect(await reads.chainOf(version)).toEqual(heads([replacing])); - expect(beats).toBeGreaterThan(0); }, 300_000); it("rethrows a chain lock wait over 10 s", async () => { diff --git a/services/explorer-api/tests/unit/chain-write-heartbeats.test.ts b/services/explorer-api/tests/unit/chain-write-heartbeats.test.ts new file mode 100644 index 00000000..09e274f0 --- /dev/null +++ b/services/explorer-api/tests/unit/chain-write-heartbeats.test.ts @@ -0,0 +1,85 @@ +import { type HexString } from "@chicmoz-pkg/types"; +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 { removePendingAndDroppedTx } = await import( + "../../src/svcs/database/controllers/l2Tx/remove-pending-and-dropped.js" +); +const { storeBlockContracts } = await import( + "../../src/svcs/database/controllers/l2contract/store.js" +); + +type DbTx = Parameters[0]; + +// A chain change runs these loops inside the chain lock, one statement per +// row: a heartbeat before each keeps the consumer's partition. +describe("the per-row write loops of a chain change", () => { + it("heartbeats before copying each pending tx's fields onto its tx effect", async () => { + const order: string[] = []; + const txHashes: HexString[] = ["0x01", "0x02"]; + let deletes = 0; + const dbTx = { + delete: () => ({ + where: () => ({ + returning: () => + Promise.resolve( + deletes++ === 0 ? txHashes.map((txHash) => ({ txHash })) : [], + ), + }), + }), + update: () => ({ + set: () => ({ + where: () => { + order.push("copy"); + return Promise.resolve(); + }, + }), + }), + } as unknown as DbTx; + + await removePendingAndDroppedTx(dbTx, txHashes, () => { + order.push("beat"); + return Promise.resolve(); + }); + + expect(order).toEqual(["beat", "copy", "beat", "copy"]); + }); + + it("heartbeats before each contract row's savepoint, and lets a failed heartbeat abort the block", async () => { + const order: string[] = []; + const savepoint = { insert: () => ({ values: () => Promise.resolve() }) }; + const dbTx = { + transaction: (write: (executor: unknown) => Promise) => { + order.push("row"); + return write(savepoint); + }, + } as unknown as DbTx; + const contracts = { + classes: [{ contractClassId: "0x0a" }, { contractClassId: "0x0b" }], + instancesDeployed: [{ address: "0x0c" }], + instancesUpdated: [], + } as unknown as Parameters[1]; + + await storeBlockContracts(dbTx, contracts, () => { + order.push("beat"); + return Promise.resolve(); + }); + expect(order).toEqual(["beat", "row", "beat", "row", "beat", "row"]); + + order.length = 0; + await expect( + storeBlockContracts(dbTx, contracts, () => + Promise.reject(new Error("rebalancing")), + ), + ).rejects.toThrow("rebalancing"); + expect(order).toEqual([]); + }); +}); From 4e1f5879d92fe8fc4e37b42e898165ee0518f4db Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Thu, 26 Nov 2026 23:58:03 +0000 Subject: [PATCH 21/31] docs(explorer-api): say which blocks a catch-up block can demote The doc said a catch-up block never replaces a canonical block. One the chain above descends from demotes, below its height, the other holders of its txs and the blocks its stored ancestors come back in place of; only the canonical block at its own height is never replaced. Co-Authored-By: Claude Opus 5.5 --- .../svcs/database/controllers/l2block/canonical.ts | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) 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 c54ff899..c0843075 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts @@ -831,12 +831,14 @@ export const applyOrderedBlock = ( }; /** - * A catch-up block never replaces a canonical block. It joins only at an - * empty height below the canonical head: when the lowest canonical block - * above descends from it, with that block's authority below its height, so - * the holders of its txs there go, its stored ancestors come back and the - * heights left empty are asked for, as for an ordered block; or, with - * `final` (at or below the serving node's own finalized tip), when the + * A catch-up block never replaces the canonical block at its own height: it + * joins only where that height is empty, below the canonical head. It joins + * when the lowest canonical block above descends from it, and then has that + * block's authority below its height, as an ordered block has below its + * own: it demotes the other canonical holders of its txs there, with their + * linked runs, brings back its stored ancestors in place of the blocks at + * their heights, and asks for the heights left empty. With `final` (at or + * below the serving node's own finalized tip), it also joins when the * canonical block below, if any, is its parent. A canonical block with a * canonical child linked to it, as one a walk brought back, has the same * authority: the holders of its txs below it go, and the heights left empty From 42dc46952d8550f3b77c5dd9a0b78452c8777f24 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 00:28:03 +0000 Subject: [PATCH 22/31] revert(explorer-api): close a repair by its height again, whatever the version This reverts commit 25686c42 ("fix(explorer-api): keep an older rollup version's block from closing a repair"). Rollup versions are not ordered numbers: the registry maps an index to an arbitrary version. After an upgrade to a numerically lower version, the max(version) check kept the current version's repairs open for good, and an older version's block could still close them. A repair closes again in the change that makes any block at its height canonical. Its test goes with it. Co-Authored-By: Claude Opus 5.5 --- .../database/controllers/l2block/canonical.ts | 2 +- .../controllers/l2block/missing-ranges.ts | 9 ++------- .../chain-head.integration.test.ts | 19 ------------------- .../integration/open-gap.integration.test.ts | 2 +- 4 files changed, 4 insertions(+), 28 deletions(-) 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 c0843075..6ac27a13 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts @@ -737,7 +737,7 @@ const settle = async ( (part) => recordRepairHeights(change.dbTx, part), ); if (canonical) { - await fulfilRepairHeight(change.dbTx, block.height, change.version); + await fulfilRepairHeight(change.dbTx, block.height); } }; 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 3523b43c..392a3101 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 @@ -176,14 +176,12 @@ export const recordRepairHeights = async ( /** * Closes the repair of `height`, in the transaction whose block message made - * the block of rollup `version` there canonical. Repair rows carry no - * version, so the block closes one only while no newer version is stored: - * an older version's block must not close a newer version's repair. + * the block there canonical. Repair rows carry no rollup version, so any + * version's block at the height closes it. */ export const fulfilRepairHeight = async ( executor: ReturnType, height: bigint, - version: number, ) => { await executor .update(l2OpenGapTable) @@ -195,9 +193,6 @@ export const fulfilRepairHeight = async ( eq(l2OpenGapTable.status, "open"), eq(l2OpenGapTable.fromHeight, Number(height)), eq(l2OpenGapTable.toHeight, Number(height)), - // max() reads one entry of l2block_version_idx; a NOT EXISTS on newer - // versions is planned as a scan past every older version's row. - lte(sql`(SELECT max(${l2Block.version}) FROM ${l2Block})`, version), ), ); }; 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 dd4dd4f0..d49762eb 100644 --- a/services/explorer-api/tests/integration/chain-head.integration.test.ts +++ b/services/explorer-api/tests/integration/chain-head.integration.test.ts @@ -580,25 +580,6 @@ describe("the canonical chain on a real database", () => { expect(await reads.repairOpen(19_001)).toBe(true); }); - it("keeps a repair open when an older rollup version's block fills its height, and closes it with the newer version's", async () => { - const older = freshVersion(); - const newer = freshVersion(); - const [o1, o2] = await buildChain(22_001n, 2, { version: older }); - const [n1, n2] = await buildChain(22_001n, 2, { version: newer }); - // Each version's block at 22_002 lacks its parent, so 22_001 is requested. - await ordered(o2); - await ordered(n2); - expect(await reads.repairOpen(22_001)).toBe(true); - - await catchup(o1); - expect(await reads.stateOf(o1.hash)).toBe("canonical"); - expect(await reads.repairOpen(22_001)).toBe(true); - - await catchup(n1); - expect(await reads.stateOf(n1.hash)).toBe("canonical"); - expect(await reads.repairOpen(22_001)).toBe(false); - }); - it("flags a new off-chain block whose stored parent is off the chain, whichever of the two arrives first", async () => { const version = freshVersion(); const live = await buildChain(20_000n, 3, { version }); 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 56618cdd..1bd7abdb 100644 --- a/services/explorer-api/tests/integration/open-gap.integration.test.ts +++ b/services/explorer-api/tests/integration/open-gap.integration.test.ts @@ -110,7 +110,7 @@ describe("open gap scheduling on a real database", () => { }; repair = (height) => recordRepairHeights(db, [BigInt(height)]); // What a block message's change does when it makes its block canonical. - fulfil = (height) => fulfilRepairHeight(db, BigInt(height), CURRENT); + fulfil = (height) => fulfilRepairHeight(db, BigInt(height)); seedGaps = async (rows) => { const now = Date.now(); await db.insert(l2OpenGapTable).values( From 8c688dacaf1a10a0c3ccd67b585caa48860df804 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 00:36:24 +0000 Subject: [PATCH 23/31] fix(explorer-api): ask for the empty height below a final catch-up block A final catch-up block whose link from above is undecided joins when the canonical block below, if any, is its parent. With no canonical block below, it joined over an empty height and asked for nothing, so the gap waited for the cadence scan. It now records a repair for that height, above height 1. Co-Authored-By: Claude Opus 5.5 --- .../svcs/database/controllers/l2block/canonical.ts | 11 +++++++---- .../integration/chain-head.integration.test.ts | 13 +++++++++++++ 2 files changed, 20 insertions(+), 4 deletions(-) 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 6ac27a13..e061fed4 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts @@ -839,10 +839,10 @@ export const applyOrderedBlock = ( * linked runs, brings back its stored ancestors in place of the blocks at * their heights, and asks for the heights left empty. With `final` (at or * below the serving node's own finalized tip), it also joins when the - * canonical block below, if any, is its parent. A canonical block with a - * canonical child linked to it, as one a walk brought back, has the same - * authority: the holders of its txs below it go, and the heights left empty - * are asked for. + * canonical block below, if any, is its parent, and asks for that height + * when it is empty. A canonical block with a canonical child linked to it, + * as one a walk brought back, has the same authority: the holders of its + * txs below it go, and the heights left empty are asked for. */ export const applyCatchupBlock = ( incoming: IncomingBlock, @@ -895,5 +895,8 @@ export const applyCatchupBlock = ( return false; } await promote(change, stored, { walked: false }); + if (below.length === 0 && stored.height > 1n) { + change.repairs.add(stored.height - 1n); + } return true; }); 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 d49762eb..f8f540d8 100644 --- a/services/explorer-api/tests/integration/chain-head.integration.test.ts +++ b/services/explorer-api/tests/integration/chain-head.integration.test.ts @@ -524,6 +524,19 @@ describe("the canonical chain on a real database", () => { expect(await reads.recordsOf(version)).toEqual([]); }); + it("opens a repair at the empty height below a final catch-up block that joins with its link from above undecided", async () => { + const version = freshVersion(); + // Its parent is not stored, so the walk down from it cannot decide. + const head = await buildBlock(26_004n, [freshTxHash()], { version }); + const block = await buildBlock(26_002n, [freshTxHash()], { version }); + await ordered(head); + + await catchup(block, { final: true }); + + expect(await reads.stateOf(block.hash)).toBe("canonical"); + expect(await reads.repairOpen(26_001)).toBe(true); + }); + it("clears the dropped rows of the effects a walk-made-canonical block owns, and attaches the rest from its repair", async () => { const version = freshVersion(); const kept = freshTxHash(); From ee93c45a3b20a982885b79e049a20ad700625732 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 00:46:38 +0000 Subject: [PATCH 24/31] fix(explorer-api): heartbeat before each tx effect a block change writes Attaching a block's tx effects ran with no heartbeat: two statements an effect plus one per public data write, for every effect of the block, inside the chain lock. The change now heartbeats before each effect it writes; the protocol caps public data writes at 64 a tx, so that bounds the statements between two heartbeats. A second test fails a heartbeat after a block's effect and class row are written, and finds the block, the effect and the class row gone. Co-Authored-By: Claude Opus 5.5 --- .../database/controllers/l2block/canonical.ts | 3 ++ .../chain-head.integration.test.ts | 48 +++++++++++++++++++ .../tests/integration/support/blocks.ts | 47 +++++++++++++----- .../tests/integration/support/chain.ts | 13 +++++ 4 files changed, 98 insertions(+), 13 deletions(-) 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 e061fed4..ea8350b0 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts @@ -540,6 +540,9 @@ const attachTxs = async ( if (owner?.blockHash === block.hash || (owner && !canonical)) { continue; } + // An effect is at most two statements plus one per public data write, + // which the protocol caps at 64 a tx. + await change.heartbeat(); await writeTxEffect(change.dbTx, { bodyId: stored.bodyId, index, 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 f8f540d8..ce5a00ca 100644 --- a/services/explorer-api/tests/integration/chain-head.integration.test.ts +++ b/services/explorer-api/tests/integration/chain-head.integration.test.ts @@ -919,6 +919,54 @@ describe("the canonical chain on a real database", () => { expect(beats).toBeGreaterThan(0); }); + it("heartbeats before each tx effect it writes", async () => { + const beatsFor = async (block: BuiltBlock) => { + let beats = 0; + await orderedWith(orderedEvent(block), () => { + beats++; + return Promise.resolve(); + }); + return beats; + }; + const one = await buildBlock(27_000n, [freshTxHash()], { + version: freshVersion(), + }); + const four = await buildBlock( + 27_010n, + [freshTxHash(), freshTxHash(), freshTxHash(), freshTxHash()], + { version: freshVersion() }, + ); + + // The rest of each change beats once per statement of up to a thousand + // rows, as often for one tx as for four. + expect((await beatsFor(four)) - (await beatsFor(one))).toBe(3); + }); + + it("rolls back a block with its tx effects and contract rows when a heartbeat fails after they are written", async () => { + const tx = freshTxHash(); + const block = await buildBlock(28_000n, [tx], { + version: freshVersion(), + publishesClass: true, + }); + let beats = 0; + // The beats before its effect and before its class row pass; the next, + // settlement's first, fails. + const failsThird = () => + ++beats > 2 + ? Promise.reject(new Error("rebalancing")) + : Promise.resolve(); + + await expect(orderedWith(orderedEvent(block), failsThird)).rejects.toThrow( + "rebalancing", + ); + expect(await reads.stateOf(block.hash)).toBe("absent"); + expect(await reads.ownerOf(tx)).toBeUndefined(); + expect(await reads.classesOf(block.hash)).toEqual([]); + + await ordered(block); + expect(await reads.classesOf(block.hash)).toHaveLength(1); + }); + describe("bounds", () => { it("stops a walk at the bound without throwing, keeps its partition through it, and rolls back when a heartbeat fails", async () => { const version = freshVersion(); diff --git a/services/explorer-api/tests/integration/support/blocks.ts b/services/explorer-api/tests/integration/support/blocks.ts index 532ba91d..74881102 100644 --- a/services/explorer-api/tests/integration/support/blocks.ts +++ b/services/explorer-api/tests/integration/support/blocks.ts @@ -14,7 +14,11 @@ import { type NewBlockEvent, } from "@chicmoz-pkg/message-registry"; import { type HexString } from "@chicmoz-pkg/types"; -import { listFixtures, loadFixture } from "@chicmoz/test-harness"; +import { + type FixtureData, + listFixtures, + loadFixture, +} from "@chicmoz/test-harness"; export type BuiltBlock = { hex: string; @@ -24,24 +28,38 @@ export type BuiltBlock = { archive: AppendOnlyTreeSnapshot; }; -// A recorded effect with public logs and no contract-class logs, so storing a -// clone adds no contract rows that would collide across blocks. -const baseBlock = (): L2Block => { +const recorded = ( + what: string, + wanted: (expected: FixtureData["l2-block"]["expected"]) => boolean, +): L2Block => { const fixture = listFixtures("local-network", "l2-block") .map((name) => loadFixture("local-network", "l2-block", name)) - .find( - (f) => - f.data.expected.counts.publicLogs > 0 && - f.data.expected.counts.contractClassLogs === 0 && - f.data.expected.contractInstanceAddresses.length === 0, - ); + .find((f) => wanted(f.data.expected)); if (!fixture) { - throw new Error("no recorded local-network block with public logs and no contract logs"); + throw new Error(`no recorded local-network block with ${what}`); } return L2Block.fromBuffer(Buffer.from(fixture.data.hex, "hex")); }; -let base: L2Block | undefined; +// 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, + )); /** * The coinbase is salted to tell headers at one height apart. The handler @@ -49,6 +67,7 @@ let base: L2Block | undefined; * `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. */ export const buildBlock = async ( height: bigint, @@ -57,13 +76,15 @@ export const buildBlock = async ( version, parent, archive: sharedArchive, + publishesClass, }: { version?: number; parent?: Pick; archive?: AppendOnlyTreeSnapshot; + publishesClass?: true; } = {}, ): Promise => { - base ??= baseBlock(); + const base = baseBlock(publishesClass === true); 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 7f6503c4..962fbff0 100644 --- a/services/explorer-api/tests/integration/support/chain.ts +++ b/services/explorer-api/tests/integration/support/chain.ts @@ -39,6 +39,9 @@ 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 { getReorgs } = await import( "../../../src/svcs/database/controllers/l2block/get-block.js" ); @@ -80,6 +83,15 @@ export const loadChainReads = async () => { return row?.blockHash; }; + /** The contract classes stored with a block. */ + const classesOf = async (blockHash: HexString) => + ( + await db + .select({ id: l2ContractClassRegistered.contractClassId }) + .from(l2ContractClassRegistered) + .where(eq(l2ContractClassRegistered.blockHash, blockHash)) + ).map(({ id }) => id); + const isDropped = async (txHash: HexString) => ( await db @@ -148,6 +160,7 @@ export const loadChainReads = async () => { chainOf, stateOf, ownerOf, + classesOf, isDropped, recordsOf, listed, From b86fb80f1a60501081c1c75f7bab858585f18129 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 00:47:26 +0000 Subject: [PATCH 25/31] docs(explorer-api): state the catch-up block rule in four sentences The applyCatchupBlock doc had grown a clause at a time. It now says which heights a catch-up block fills, the authority it carries below its height when linked to the chain above, that an already-canonical block with a linked canonical child has the same, and when a final block also joins. Co-Authored-By: Claude Opus 5.5 --- .../database/controllers/l2block/canonical.ts | 21 ++++++++----------- 1 file changed, 9 insertions(+), 12 deletions(-) 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 ea8350b0..c255eb08 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts @@ -834,18 +834,15 @@ export const applyOrderedBlock = ( }; /** - * A catch-up block never replaces the canonical block at its own height: it - * joins only where that height is empty, below the canonical head. It joins - * when the lowest canonical block above descends from it, and then has that - * block's authority below its height, as an ordered block has below its - * own: it demotes the other canonical holders of its txs there, with their - * linked runs, brings back its stored ancestors in place of the blocks at - * their heights, and asks for the heights left empty. With `final` (at or - * below the serving node's own finalized tip), it also joins when the - * canonical block below, if any, is its parent, and asks for that height - * when it is empty. A canonical block with a canonical child linked to it, - * as one a walk brought back, has the same authority: the holders of its - * txs below it go, and the heights left empty are asked for. + * A catch-up block fills an empty height below the canonical head, never a + * held one. Linked to the canonical chain above, it carries that chain's + * authority below its height, as an ordered block does: the other holders of + * its txs there go, its stored ancestors come back, and the heights left + * empty are asked for. An already-canonical block with a linked canonical + * child has the same authority. With `final` (at or below the serving node's + * own finalized tip), it also joins when the link is undecided and the + * canonical block below, if any, is its parent, asking for that height when + * it is empty. */ export const applyCatchupBlock = ( incoming: IncomingBlock, From 9b76282773e3b4f2d260221eb2122757a584f417 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 16:33:46 +0000 Subject: [PATCH 26/31] refactor(explorer-api): read the ordered block's proposedTip and the catch-up block's finalized The block handler validates `ordered.proposedTip` and passes it to `applyOrderedBlock` as its ceiling; the catch-up handler passes `finalized`. The test event builders and the chain tests use the new field names. Co-Authored-By: Claude Opus 5.5 --- .../src/events/received/on-block/index.ts | 8 +++-- .../database/controllers/l2block/canonical.ts | 20 ++++++------ .../block-ingest.integration.test.ts | 4 +-- .../chain-head.integration.test.ts | 31 ++++++++++--------- .../tests/integration/support/blocks.ts | 10 +++--- .../integration/support/recorded-blocks.ts | 4 +-- 6 files changed, 40 insertions(+), 37 deletions(-) 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 46fa67d0..7bec3f7a 100644 --- a/services/explorer-api/src/events/received/on-block/index.ts +++ b/services/explorer-api/src/events/received/on-block/index.ts @@ -21,7 +21,9 @@ import { import { controllers } from "../../../svcs/database/index.js"; import { parseBlockContracts } from "./contracts.js"; -const orderedSchema = z.object({ tip: z.number().int().nonnegative() }); +const orderedSchema = z.object({ + proposedTip: z.number().int().nonnegative(), +}); const decode = async ({ block, @@ -84,7 +86,7 @@ const onBlock = async (event: NewBlockEvent, heartbeat: Heartbeat) => { } await afterCommit( incoming, - await applyOrderedBlock(incoming, ordered.data.tip, heartbeat), + await applyOrderedBlock(incoming, ordered.data.proposedTip, heartbeat), ); }; @@ -98,7 +100,7 @@ const onCatchupBlock = async ( } await afterCommit( incoming, - await applyCatchupBlock(incoming, event.final === true, heartbeat), + await applyCatchupBlock(incoming, event.finalized === true, heartbeat), ); }; 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 c255eb08..c9f8b0d4 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts @@ -796,18 +796,18 @@ const apply = async ( * with that block's linked descendants, and every other canonical holder of * its txs with theirs; brings back its stored ancestors; asks for the heights * below it that this leaves empty; and demotes every canonical block above - * `tip`. + * `proposedTip`. */ export const applyOrderedBlock = ( incoming: IncomingBlock, - tip: number, + proposedTip: number, heartbeat: Heartbeat, ): Promise => { const { height, hash } = incoming.block; - let ceiling = BigInt(tip); + let ceiling = BigInt(proposedTip); if (ceiling < height) { logger.warn( - `Ordered block ${height} (${hash}) carries tip ${tip}, below its height; using ${height}`, + `Ordered block ${height} (${hash}) carries proposed tip ${proposedTip}, below its height; using ${height}`, ); ceiling = height; } @@ -839,14 +839,14 @@ export const applyOrderedBlock = ( * authority below its height, as an ordered block does: the other holders of * its txs there go, its stored ancestors come back, and the heights left * empty are asked for. An already-canonical block with a linked canonical - * child has the same authority. With `final` (at or below the serving node's - * own finalized tip), it also joins when the link is undecided and the + * child has the same authority. With `finalized` (at or below the serving + * node's own finalized tip), it also joins when the link is undecided and the * canonical block below, if any, is its parent, asking for that height when * it is empty. */ export const applyCatchupBlock = ( incoming: IncomingBlock, - final: boolean, + finalized: boolean, heartbeat: Heartbeat, ): Promise => apply(incoming, heartbeat, { ordered: false }, async (change, stored) => { @@ -870,9 +870,9 @@ export const applyCatchupBlock = ( return false; } if (link === "excludes") { - if (final) { + if (finalized) { logger.warn( - `CHAIN_LINK_CONFLICT: final catch-up block ${stored.height} (${stored.hash}) is not the parent of the canonical chain above it; left off the chain`, + `CHAIN_LINK_CONFLICT: finalized catch-up block ${stored.height} (${stored.hash}) is not the parent of the canonical chain above it; left off the chain`, ); } return false; @@ -887,7 +887,7 @@ export const applyCatchupBlock = ( await requestEmptied(change, stored.height); return true; } - if (!final) { + if (!finalized) { return false; } const below = await canonicalAt(change, stored.height - 1n); 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 c612b52e..82dae0d9 100644 --- a/services/explorer-api/tests/integration/block-ingest.integration.test.ts +++ b/services/explorer-api/tests/integration/block-ingest.integration.test.ts @@ -12,7 +12,7 @@ import { const recorded = listFixtures("local-network", "l2-block") .map((name) => loadFixture("local-network", "l2-block", name).data) .sort((a, b) => a.expected.height - b.expected.height); -const tip = Math.max(...recorded.map(({ expected }) => expected.height)); +const proposedTip = Math.max(...recorded.map(({ expected }) => expected.height)); describe("recorded blocks through the block handler", () => { let api: ExplorerApiForTest; @@ -27,7 +27,7 @@ describe("recorded blocks through the block handler", () => { block: hex, blockNumber: expected.height, statusHint: "proposed", - ordered: { tip }, + ordered: { proposedTip }, }); } }); 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 ce5a00ca..3ce9b3a5 100644 --- a/services/explorer-api/tests/integration/chain-head.integration.test.ts +++ b/services/explorer-api/tests/integration/chain-head.integration.test.ts @@ -23,16 +23,16 @@ import { } from "./support/explorer-api.js"; // Each case runs on a rollup version of its own, because an ordered block -// demotes every canonical block of its version above its tip, and on heights -// of its own, because repair rows are per network. +// demotes every canonical block of its version above its proposed tip, and +// on heights of its own, because repair rows are per network. let lastVersion = 1_000; const freshVersion = () => ++lastVersion; describe("the canonical chain on a real database", () => { let api: ExplorerApiForTest; let reads: Awaited>; - let ordered: (b: BuiltBlock, tip?: number) => Promise; - let catchup: (b: BuiltBlock, options?: { final?: true }) => Promise; + let ordered: (b: BuiltBlock, proposedTip?: number) => Promise; + let catchup: (b: BuiltBlock, options?: { finalized?: true }) => Promise; let orderedWith: ( event: NewBlockEvent, heartbeat: Heartbeat, @@ -74,7 +74,8 @@ describe("the canonical chain on a real database", () => { reads = await loadChainReads(); walkBound = WALK_BOUND; - ordered = (b, tip) => deliver(blockHandler, orderedEvent(b, tip)); + ordered = (b, proposedTip) => + deliver(blockHandler, orderedEvent(b, proposedTip)); catchup = (b, options) => deliver(catchupHandler, catchupEvent(b, options)); orderedWith = (event, heartbeat) => blockHandler.cb(event, heartbeat); ignoredUnordered = (b) => @@ -382,7 +383,7 @@ describe("the canonical chain on a real database", () => { expect(await reads.recordsOf(version)).toEqual([]); }); - it("keeps a final catch-up block at a canonical height off the chain until its ordered copy arrives", async () => { + it("keeps a finalized catch-up block at a canonical height off the chain until its ordered copy arrives", async () => { const version = freshVersion(); const a = await buildChain(5_000n, 3, { version }); for (const block of a) { @@ -393,7 +394,7 @@ describe("the canonical chain on a real database", () => { parent: a[0], }); - await catchup(b1, { final: true }); + await catchup(b1, { finalized: true }); expect(await reads.chainOf(version)).toEqual(heads(a)); expect(await reads.recordsOf(version)).toEqual([]); @@ -415,7 +416,7 @@ describe("the canonical chain on a real database", () => { parent: c[0], }); - await catchup(stranger, { final: true }); + await catchup(stranger, { finalized: true }); expect(await reads.stateOf(stranger.hash)).toEqual({ hasOrphanedParent: false, }); @@ -426,12 +427,12 @@ describe("the canonical chain on a real database", () => { expect(await reads.ownerOf(c[1].txHashes[0])).toBe(c[1].hash); }); - it("keeps a final catch-up block above the canonical head off the chain", async () => { + it("keeps a finalized catch-up block above the canonical head off the chain", async () => { const version = freshVersion(); const [head, above] = await buildChain(16_000n, 2, { version }); await ordered(head); - await catchup(above, { final: true }); + await catchup(above, { finalized: true }); expect(await reads.chainOf(version)).toEqual(heads([head])); }); @@ -506,7 +507,7 @@ describe("the canonical chain on a real database", () => { expect(await reads.repairOpen(18_001)).toBe(false); }); - it("fills history from block 1 with final catch-up blocks, each only on the canonical block below as its parent", async () => { + it("fills history from block 1 with finalized catch-up blocks, each only on the canonical block below as its parent", async () => { const version = freshVersion(); const c = await buildChain(1n, 6, { version }); await ordered(c[4], 6); @@ -514,7 +515,7 @@ describe("the canonical chain on a real database", () => { const stranger = await buildBlock(3n, [freshTxHash()], { version }); for (const block of [c[0], c[1], stranger, c[2], c[3]]) { - await catchup(block, { final: true }); + await catchup(block, { finalized: true }); } expect(await reads.chainOf(version)).toEqual(heads(c)); @@ -524,14 +525,14 @@ describe("the canonical chain on a real database", () => { expect(await reads.recordsOf(version)).toEqual([]); }); - it("opens a repair at the empty height below a final catch-up block that joins with its link from above undecided", async () => { + it("opens a repair at the empty height below a finalized catch-up block that joins with its link from above undecided", async () => { const version = freshVersion(); // Its parent is not stored, so the walk down from it cannot decide. const head = await buildBlock(26_004n, [freshTxHash()], { version }); const block = await buildBlock(26_002n, [freshTxHash()], { version }); await ordered(head); - await catchup(block, { final: true }); + await catchup(block, { finalized: true }); expect(await reads.stateOf(block.hash)).toBe("canonical"); expect(await reads.repairOpen(26_001)).toBe(true); @@ -854,7 +855,7 @@ describe("the canonical chain on a real database", () => { await catchup(twin); expect(await reads.chainOf(version)).toEqual(heads([p, child])); - await catchup(twin, { final: true }); + await catchup(twin, { finalized: true }); expect(await reads.chainOf(version)).toEqual(heads([p, twin, child])); }); diff --git a/services/explorer-api/tests/integration/support/blocks.ts b/services/explorer-api/tests/integration/support/blocks.ts index 74881102..121ea023 100644 --- a/services/explorer-api/tests/integration/support/blocks.ts +++ b/services/explorer-api/tests/integration/support/blocks.ts @@ -149,23 +149,23 @@ export const buildChain = async ( return chain; }; -/** As the hash-following listener sends it: `tip` defaults to the block's own height. */ +/** As the hash-following listener sends it: `proposedTip` defaults to the block's own height. */ export const orderedEvent = ( b: BuiltBlock, - tip = Number(b.height), + proposedTip = Number(b.height), ): NewBlockEvent => ({ block: b.hex, blockNumber: Number(b.height), statusHint: "proposed", - ordered: { tip }, + ordered: { proposedTip }, }); export const catchupEvent = ( b: BuiltBlock, - { final }: { final?: true } = {}, + { finalized }: { finalized?: true } = {}, ): CatchupBlockEvent => ({ block: b.hex, blockNumber: Number(b.height), statusHint: "proposed", - ...(final ? { final } : {}), + ...(finalized ? { finalized } : {}), }); diff --git a/services/explorer-api/tests/integration/support/recorded-blocks.ts b/services/explorer-api/tests/integration/support/recorded-blocks.ts index 244d1793..dbebd55d 100644 --- a/services/explorer-api/tests/integration/support/recorded-blocks.ts +++ b/services/explorer-api/tests/integration/support/recorded-blocks.ts @@ -24,14 +24,14 @@ export const recordedBlocks = (source: FixtureSource) => { const fixtures = listFixtures(source, "l2-block").map( (name) => [name, loadFixture(source, "l2-block", name).data] as const, ); - const tip = Math.max(...fixtures.map(([, data]) => data.expected.height)); + const proposedTip = Math.max(...fixtures.map(([, data]) => data.expected.height)); return fixtures .map(([name, data]) => { const event: NewBlockEvent = { blockNumber: data.expected.height, statusHint: "proposed", block: data.hex, - ordered: { tip }, + ordered: { proposedTip }, }; return { name, expected: data.expected, event }; }) From 654cab2ae252087764f8d1499d5c221d450bc4b3 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 16:35:27 +0000 Subject: [PATCH 27/31] refactor(explorer-api): record a reorg's cause instead of its derivable root `l2_reorg` drops `root_height`, `root_hash` and `removed_count`: nothing read them, and `getReorgs` derives the lowest block and the count from `l2_reorg_block`. It gains what cannot be derived later: `cause_hash`, the hash of the incoming block whose change wrote the record, and `cause_kind`, whether that block came on the ordered stream or as a catch-up block. Both are NOT NULL; `cause_kind` is typed as `"ordered" | "catchup"`. Every record is written by `apply`, for one incoming ordered or catch-up block, so each has a cause. The schema's TSDoc now says catch-up blocks write records too. Migration 0039 has not shipped and changes in place. Co-Authored-By: Claude Opus 5.5 --- .../explorer-api/migrations/0039_l2_reorg.sql | 5 ++--- .../database/controllers/l2block/canonical.ts | 18 ++++++++++++------ .../src/svcs/database/schema/l2/reorg.ts | 16 +++++++++------- .../integration/chain-head.integration.test.ts | 6 ++++++ .../tests/integration/support/chain.ts | 9 +++++++++ 5 files changed, 38 insertions(+), 16 deletions(-) diff --git a/services/explorer-api/migrations/0039_l2_reorg.sql b/services/explorer-api/migrations/0039_l2_reorg.sql index 3ab3b2c7..ccc91bf6 100644 --- a/services/explorer-api/migrations/0039_l2_reorg.sql +++ b/services/explorer-api/migrations/0039_l2_reorg.sql @@ -2,9 +2,8 @@ CREATE TABLE IF NOT EXISTS "l2_reorg" ( "id" bigint PRIMARY KEY GENERATED ALWAYS AS IDENTITY, "l2_network_id" varchar NOT NULL, "rollup_version" bigint NOT NULL, - "root_height" bigint NOT NULL, - "root_hash" varchar NOT NULL, - "removed_count" integer NOT NULL, + "cause_hash" varchar NOT NULL, + "cause_kind" varchar NOT NULL, "observed_at" timestamp NOT NULL, "revived_at" timestamp );--> statement-breakpoint 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 c9f8b0d4..1bb8c658 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts @@ -6,7 +6,11 @@ import { alias } from "drizzle-orm/pg-core"; import { L2_NETWORK_ID } from "../../../../environment.js"; import { logger } from "../../../../logger.js"; import { droppedTx } from "../../schema/dropped-tx/index.js"; -import { l2ReorgBlockTable, l2ReorgTable } from "../../schema/l2/reorg.js"; +import { + type ReorgCauseKind, + l2ReorgBlockTable, + l2ReorgTable, +} from "../../schema/l2/reorg.js"; import { archive, body, @@ -83,6 +87,8 @@ type Change = { dbTx: DbTx; version: number; now: number; + /** The incoming block this change applies: its reorg record names it. */ + cause: { hash: HexString; kind: ReorgCauseKind }; heartbeat: Heartbeat; steps: number; demoted: Map; @@ -562,15 +568,13 @@ const recordReorg = async (change: Change) => { ? -1 : 1, ); - const [root] = blocks; const [record] = await change.dbTx .insert(l2ReorgTable) .values({ l2NetworkId: L2_NETWORK_ID, rollupVersion: change.version, - rootHeight: root.height, - rootHash: root.hash, - removedCount: blocks.length, + causeHash: change.cause.hash, + causeKind: change.cause.kind, observedAt: new Date(change.now), }) .returning({ id: l2ReorgTable.id }); @@ -579,8 +583,9 @@ const recordReorg = async (change: Change) => { .insert(l2ReorgBlockTable) .values(part.map((b) => ({ reorgId: record.id, ...b }))); }); + const [lowest] = blocks; logger.warn( - `L2 reorg at height ${root.height}: ${blocks.length} block(s) left the chain, the lowest ${root.hash}`, + `L2 reorg at height ${lowest.height}: ${blocks.length} block(s) left the chain, the lowest ${lowest.hash}, applying ${change.cause.kind} block ${change.cause.hash}`, ); }; @@ -761,6 +766,7 @@ const apply = async ( dbTx, version: block.header.globalVariables.version, now: Date.now(), + cause: { hash: block.hash, kind: ordered ? "ordered" : "catchup" }, heartbeat, steps: 0, demoted: new Map(), diff --git a/services/explorer-api/src/svcs/database/schema/l2/reorg.ts b/services/explorer-api/src/svcs/database/schema/l2/reorg.ts index 0e3943c8..5d3107b0 100644 --- a/services/explorer-api/src/svcs/database/schema/l2/reorg.ts +++ b/services/explorer-api/src/svcs/database/schema/l2/reorg.ts @@ -2,7 +2,6 @@ import { HexString, L2NetworkId } from "@chicmoz-pkg/types"; import { bigint, index, - integer, pgTable, primaryKey, timestamp, @@ -10,10 +9,14 @@ import { } from "drizzle-orm/pg-core"; import { generateBoundedIntegerColumn, l2NetworkIdDbEnum } from "../utils.js"; +/** The stream the block whose application wrote a reorg record came on. */ +export type ReorgCauseKind = "ordered" | "catchup"; + /** - * One row per ordered block that demoted canonical blocks: what the explorer - * had as canonical and removed, not the node's prune depth. `revived_at` is - * the only later write, set once every listed block is canonical again. + * One row per applied block, ordered or catch-up, that demoted canonical + * blocks: what the explorer had as canonical and removed, not the node's + * prune depth. `cause_hash` is that block's hash. `revived_at` is the only + * later write, set once every listed block is canonical again. */ export const l2ReorgTable = pgTable( "l2_reorg", @@ -25,9 +28,8 @@ export const l2ReorgTable = pgTable( .notNull() .$type(), rollupVersion: generateBoundedIntegerColumn("rollup_version").notNull(), - rootHeight: bigint("root_height", { mode: "bigint" }).notNull(), - rootHash: varchar("root_hash").notNull().$type(), - removedCount: integer("removed_count").notNull(), + causeHash: varchar("cause_hash").notNull().$type(), + causeKind: varchar("cause_kind").notNull().$type(), observedAt: timestamp("observed_at").notNull(), revivedAt: timestamp("revived_at"), }, 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 3ce9b3a5..fcf49baa 100644 --- a/services/explorer-api/tests/integration/chain-head.integration.test.ts +++ b/services/explorer-api/tests/integration/chain-head.integration.test.ts @@ -299,6 +299,9 @@ describe("the canonical chain on a real database", () => { expect(await reads.recordsOf(version)).toEqual([ { active: true, blocks: [a[1], a[2], a[3], above].map((b) => b.hash) }, ]); + expect(await reads.causesOf(version)).toEqual([ + { hash: b1.hash, kind: "ordered" }, + ]); expect( await Promise.all([a[1], a[2], above].map((b) => reads.stateOf(b.hash))), ).toEqual([ @@ -455,6 +458,9 @@ describe("the canonical chain on a real database", () => { expect(await reads.recordsOf(version)).toEqual([ { active: true, blocks: [a1.hash] }, ]); + expect(await reads.causesOf(version)).toEqual([ + { hash: b2.hash, kind: "catchup" }, + ]); expect(await reads.repairOpen(17_001)).toBe(true); }); diff --git a/services/explorer-api/tests/integration/support/chain.ts b/services/explorer-api/tests/integration/support/chain.ts index 962fbff0..b60dd999 100644 --- a/services/explorer-api/tests/integration/support/chain.ts +++ b/services/explorer-api/tests/integration/support/chain.ts @@ -131,6 +131,14 @@ export const loadChainReads = async () => { return [...records.values()]; }; + /** The block that wrote each reorg record of a rollup version, oldest first. */ + const causesOf = (version: number) => + db + .select({ hash: l2ReorgTable.causeHash, kind: l2ReorgTable.causeKind }) + .from(l2ReorgTable) + .where(eq(l2ReorgTable.rollupVersion, version)) + .orderBy(asc(l2ReorgTable.id)); + /** The `/l2/reorgs` entries that show one of `blocks`. */ const listed = async (blocks: BuiltBlock[]): Promise => (await getReorgs()) @@ -165,5 +173,6 @@ export const loadChainReads = async () => { recordsOf, listed, repairOpen, + causesOf, }; }; From 03592bd91ee59ed2b152a0570b370c5907573222 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 16:37:14 +0000 Subject: [PATCH 28/31] feat(explorer-api): hold one canonical block per height with a unique index Migration 0040 adds `l2block_one_canonical_per_height_idx`, a unique partial index on `"l2Block"(version, height) WHERE orphan_timestamp IS NULL`, also declared in the Drizzle schema. Until now only the chain code held the rule. Every write that makes a block canonical is `promote` in canonical.ts, and each caller first demotes the canonical blocks at that height in the same transaction; `store` inserts blocks off the chain. A violation is a unique violation from `promote`'s UPDATE: it propagates out of the chain transaction and the handler, so the message is redelivered. No catch on that path reads a 23505 as a duplicate. A new chain test hides a canonical row from the chain reads and delivers an ordered block at its height: the database refuses it, the handler rethrows the refusal, and nothing of the block is kept. Co-Authored-By: Claude Opus 5.5 --- .../0040_one_canonical_block_per_height.sql | 1 + .../migrations/meta/_journal.json | 7 ++++ .../database/controllers/l2block/canonical.ts | 5 +++ .../src/svcs/database/schema/l2block/root.ts | 16 +++++++++- .../chain-head.integration.test.ts | 32 +++++++++++++++++++ 5 files changed, 60 insertions(+), 1 deletion(-) create mode 100644 services/explorer-api/migrations/0040_one_canonical_block_per_height.sql diff --git a/services/explorer-api/migrations/0040_one_canonical_block_per_height.sql b/services/explorer-api/migrations/0040_one_canonical_block_per_height.sql new file mode 100644 index 00000000..064a5b50 --- /dev/null +++ b/services/explorer-api/migrations/0040_one_canonical_block_per_height.sql @@ -0,0 +1 @@ +CREATE UNIQUE INDEX IF NOT EXISTS "l2block_one_canonical_per_height_idx" ON "l2Block" USING btree ("version","height") WHERE "l2Block"."orphan_timestamp" IS NULL; diff --git a/services/explorer-api/migrations/meta/_journal.json b/services/explorer-api/migrations/meta/_journal.json index af7aabd3..9b3a583c 100644 --- a/services/explorer-api/migrations/meta/_journal.json +++ b/services/explorer-api/migrations/meta/_journal.json @@ -281,6 +281,13 @@ "when": 1779960000012, "tag": "0039_l2_reorg", "breakpoints": true + }, + { + "idx": 40, + "version": "7", + "when": 1779960000013, + "tag": "0040_one_canonical_block_per_height", + "breakpoints": true } ] } 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 1bb8c658..90ba720b 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts @@ -38,6 +38,11 @@ import { store, writeTxEffect } from "./store.js"; // parent's archive root is outside the parent's hash, so two stored parents // make a lookup ambiguous. // +// One canonical block per height also holds after every statement: the +// unique index l2block_one_canonical_per_height_idx refuses a second. So a +// change demotes a height's canonical block before it promotes another +// there, and a violation propagates, failing the change for redelivery. +// // Ordered blocks are the listener's chain, sent in order: each is canonical // at its height and nothing canonical stays above its tip. Catch-up blocks // only fill empty heights below the canonical head; one that the chain above diff --git a/services/explorer-api/src/svcs/database/schema/l2block/root.ts b/services/explorer-api/src/svcs/database/schema/l2block/root.ts index a7faea19..4fa4045d 100644 --- a/services/explorer-api/src/svcs/database/schema/l2block/root.ts +++ b/services/explorer-api/src/svcs/database/schema/l2block/root.ts @@ -1,5 +1,12 @@ import { HexString } from "@chicmoz-pkg/types"; -import { bigint, boolean, index, pgTable, varchar } from "drizzle-orm/pg-core"; +import { + bigint, + boolean, + index, + pgTable, + uniqueIndex, + varchar, +} from "drizzle-orm/pg-core"; import { sql } from "drizzle-orm"; import { @@ -31,6 +38,13 @@ export const l2Block = pgTable( t.height, t.orphan_timestamp, ), + // A chain change demotes a height's canonical block before it promotes + // another there; a statement that would leave two fails the change. + oneCanonicalPerHeightIdx: uniqueIndex( + "l2block_one_canonical_per_height_idx", + ) + .on(t.version, t.height) + .where(sql`${t.orphan_timestamp} IS NULL`), }), ); 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 fcf49baa..912905fc 100644 --- a/services/explorer-api/tests/integration/chain-head.integration.test.ts +++ b/services/explorer-api/tests/integration/chain-head.integration.test.ts @@ -39,6 +39,10 @@ describe("the canonical chain on a real database", () => { ) => Promise; let ignoredUnordered: (b: BuiltBlock) => Promise; let setOrphaned: (blocks: BuiltBlock[], orphaned: boolean) => Promise; + let unseenCanonical: ( + height: bigint, + version: number, + ) => Promise; let bareChain: (chain: { version: number; from: bigint; @@ -98,6 +102,20 @@ describe("the canonical chain on a real database", () => { ), ); }; + // Only the block row, without the header and archive rows every chain + // read joins, so no change sees it to demote it. + unseenCanonical = async (height, version) => { + const tag = version.toString(16).padStart(8, "0"); + const hash = `0x${tag}ee${height.toString(16).padStart(54, "0")}` as const; + await db.insert(l2Block).values({ + hash, + height, + version, + orphan_timestamp: null, + orphan_hasOrphanedParent: null, + }); + return hash; + }; // Linked blocks, canonical unless `offChain`, with only the rows a link // lookup reads, inserted in bulk: delivering thousands of blocks would // take minutes. Returns the top block, as a parent for a built block. @@ -874,6 +892,20 @@ describe("the canonical chain on a real database", () => { expect(await reads.stateOf(block.hash)).toBe("absent"); }); + it("refuses a second canonical block at a height in the database, and the block handler rethrows the refusal", async () => { + const version = freshVersion(); + const [block] = await buildChain(29_000n, 1, { version }); + const unseen = await unseenCanonical(block.height, version); + + await expect(ordered(block)).rejects.toMatchObject({ + code: "23505", + constraint: "l2block_one_canonical_per_height_idx", + }); + + expect(await reads.stateOf(block.hash)).toBe("absent"); + expect(await reads.stateOf(unseen)).toBe("canonical"); + }); + it("serializes the block and catch-up consumers storing one height on the chain lock", async () => { const version = freshVersion(); const [p] = await buildChain(13_000n, 1, { version }); From 6096e8d96fe5f8157d7026a1beb794c090bfbe65 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 16:40:22 +0000 Subject: [PATCH 29/31] docs(types): say what a reorg record's count and lowest block cover `/l2/reorgs` now serves records whose blocks can return to the chain: an entry's count and lowest block cover only its blocks still orphaned, and an entry disappears once all of them are canonical again. The schema's descriptions say so, and the OpenAPI spec carries them. The response shape is unchanged. Co-Authored-By: Claude Opus 5.5 --- packages/types/src/aztec/reorg.ts | 22 ++++++++++++++----- .../__snapshots__/open-api-spec.json.snap | 5 ++++- 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/packages/types/src/aztec/reorg.ts b/packages/types/src/aztec/reorg.ts index 57cda62b..7fab567e 100644 --- a/packages/types/src/aztec/reorg.ts +++ b/packages/types/src/aztec/reorg.ts @@ -1,11 +1,21 @@ import { z } from "zod"; import { hexStringSchema } from "../general.js"; -export const chicmozReorgSchema = z.object({ - orphanedBlockHash: hexStringSchema, - height: z.coerce.bigint().nonnegative(), - timestamp: z.coerce.date(), - nbrOfOrphanedBlocks: z.number().int().nonnegative(), -}); +export const chicmozReorgSchema = z + .object({ + orphanedBlockHash: hexStringSchema.describe( + "The lowest of the record's blocks that are still orphaned.", + ), + height: z.coerce.bigint().nonnegative(), + timestamp: z.coerce.date(), + nbrOfOrphanedBlocks: z + .number() + .int() + .nonnegative() + .describe("How many of the record's blocks are still orphaned."), + }) + .describe( + "One chain change that orphaned canonical blocks. Its count and lowest block cover only the blocks still orphaned, and the record disappears once all its blocks are back on the chain.", + ); export type ChicmozReorg = z.infer; diff --git a/services/explorer-api/tests/characterization/__snapshots__/open-api-spec.json.snap b/services/explorer-api/tests/characterization/__snapshots__/open-api-spec.json.snap index 6d48a486..315e37bb 100644 --- a/services/explorer-api/tests/characterization/__snapshots__/open-api-spec.json.snap +++ b/services/explorer-api/tests/characterization/__snapshots__/open-api-spec.json.snap @@ -8389,11 +8389,14 @@ "type": "string" }, "nbrOfOrphanedBlocks": { + "description": "How many of the record's blocks are still orphaned.", "maximum": 9007199254740991, "minimum": 0, "type": "integer" }, - "orphanedBlockHash": {}, + "orphanedBlockHash": { + "description": "The lowest of the record's blocks that are still orphaned." + }, "timestamp": { "format": "date-time", "type": "string" From 751e31a695a83fd1b951b29c3f4bbd2b0bada6c4 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 19:14:16 +0000 Subject: [PATCH 30/31] fix(explorer-api): create the one-canonical-block index without IF NOT EXISTS With IF NOT EXISTS, an index of the same name and another definition would let migration 0040 pass without enforcing one canonical block per rollup version and height. Without it, such an index fails the migration. Co-Authored-By: Claude Opus 5.5 --- .../migrations/0040_one_canonical_block_per_height.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/explorer-api/migrations/0040_one_canonical_block_per_height.sql b/services/explorer-api/migrations/0040_one_canonical_block_per_height.sql index 064a5b50..87c04a3e 100644 --- a/services/explorer-api/migrations/0040_one_canonical_block_per_height.sql +++ b/services/explorer-api/migrations/0040_one_canonical_block_per_height.sql @@ -1 +1 @@ -CREATE UNIQUE INDEX IF NOT EXISTS "l2block_one_canonical_per_height_idx" ON "l2Block" USING btree ("version","height") WHERE "l2Block"."orphan_timestamp" IS NULL; +CREATE UNIQUE INDEX "l2block_one_canonical_per_height_idx" ON "l2Block" USING btree ("version","height") WHERE "l2Block"."orphan_timestamp" IS NULL; From 092a783e24d786ac351b21fc1e700f64d7106fcc Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 19:43:18 +0000 Subject: [PATCH 31/31] refactor(explorer-api): adapt the reorg response schema to zod 4 In zod 4, `.extend()` returns a schema without the base schema's description, so the OpenAPI document described a reorg record's two fields but no longer the record itself. The response schema now carries the record's metadata over, and `/l2/reorgs` documents all three again. Co-Authored-By: Claude Opus 5.5 --- .../routes/controllers/utils/open-api-responses.ts | 11 +++++++---- .../__snapshots__/open-api-spec.json.snap | 1 + 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/services/explorer-api/src/svcs/http-server/routes/controllers/utils/open-api-responses.ts b/services/explorer-api/src/svcs/http-server/routes/controllers/utils/open-api-responses.ts index 50314f62..0f1e8f38 100644 --- a/services/explorer-api/src/svcs/http-server/routes/controllers/utils/open-api-responses.ts +++ b/services/explorer-api/src/svcs/http-server/routes/controllers/utils/open-api-responses.ts @@ -245,10 +245,13 @@ export const l1L2ValidatorHistoryResponse = getResponse( "l1L2ValidatorHistory", ); -// Clean BigInt fields in Reorg schema -const cleanedReorgSchema = chicmozReorgSchema.extend({ - height: z.string(), // Convert height from BigInt to string -}); +// Clean BigInt fields in Reorg schema. `.extend()` returns a schema without +// the record's description, so it is carried over. +const cleanedReorgSchema = chicmozReorgSchema + .extend({ + height: z.string(), // Convert height from BigInt to string + }) + .meta(chicmozReorgSchema.meta() ?? {}); export const reorgResponse = getResponse(cleanedReorgSchema, "reorg"); export const reorgResponseArray = getResponse( z.array(cleanedReorgSchema), diff --git a/services/explorer-api/tests/characterization/__snapshots__/open-api-spec.json.snap b/services/explorer-api/tests/characterization/__snapshots__/open-api-spec.json.snap index 315e37bb..493331a5 100644 --- a/services/explorer-api/tests/characterization/__snapshots__/open-api-spec.json.snap +++ b/services/explorer-api/tests/characterization/__snapshots__/open-api-spec.json.snap @@ -8384,6 +8384,7 @@ "application/json": { "schema": { "items": { + "description": "One chain change that orphaned canonical blocks. Its count and lowest block cover only the blocks still orphaned, and the record disappears once all its blocks are back on the chain.", "properties": { "height": { "type": "string"