From 8d2b52c5469e2b1ca510d63f5ecd9bc29207b433 Mon Sep 17 00:00:00 2001 From: David White Date: Wed, 18 Nov 2026 13:24:51 +0000 Subject: [PATCH 1/5] fix(explorer): a failed block is retried at the poll's pace, and a block fluxd does not hold yet is waited for A block fluxd refuses was recovered from with no wait, and recovery asked for it again with none, so the processor restored its database and retried as fast as fluxd answered for as long as fluxd read as synced. Recovery from a failed block now waits POLL_INTERVAL_MS. A block fluxd answers out of range (-8) is asked for again by the poller, before anything is written for it, with nothing restored. Co-Authored-By: Claude Opus 5.5 --- ZelBack/src/services/explorerService.js | 35 ++++++++++++++++--------- tests/unit/explorerService.test.js | 35 +++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 13 deletions(-) diff --git a/ZelBack/src/services/explorerService.js b/ZelBack/src/services/explorerService.js index 5db3b09423..148854085f 100644 --- a/ZelBack/src/services/explorerService.js +++ b/ZelBack/src/services/explorerService.js @@ -108,6 +108,16 @@ const BOOTSTRAP_RETRY_MS = 60_000; const RECOVERY_RETRY_MS = 15 * 60 * 1000; // How long a block waits for fluxd to sync before it is asked for again. const BLOCK_SYNC_RETRY_MS = 2 * 60 * 1000; +// How long the explorer waits before asking again whether the chain has moved, +// and before it recovers from a block that failed, so a block fluxd keeps +// refusing is retried at this pace rather than as fast as fluxd answers. +// +// This is the floor on how fast a node can process blocks: a block is not looked +// at until the next poll, so nothing downstream of block processing - expiring +// app records, trimming surplus instances, the give-up pass - can run more often +// than this however fast blocks are produced. Production wants 5s against a 30s +// block; a harness driving its own chain sets it shorter. +const POLL_INTERVAL_MS = config.fluxapps.explorerPollIntervalMs ?? 5000; /** * The block processor's steps. Each step function answers `{ next, waitMs }`: @@ -521,7 +531,8 @@ async function scheduleUpnpBench(tipBlock, period) { * The block processor's step for one block. * @param {number} blockHeight * @returns {Promise<{next: object, waitMs: number}>} The next block while fluxd - * holds one, the poll at the tip, the recovery when this block fails. + * holds one, the poll at the tip or while fluxd does not hold this block yet, + * the recovery when this block fails, after POLL_INTERVAL_MS. */ async function processBlock(blockHeight) { try { @@ -532,7 +543,15 @@ async function processBlock(blockHeight) { const database = db.db(config.database.daemon.database); // get Block information const verbosity = 2; - const blockDataVerbose = await getVerboseBlock(blockHeight, verbosity); + let blockDataVerbose; + try { + blockDataVerbose = await getVerboseBlock(blockHeight, verbosity); + } catch (error) { + // fluxd's chain does not reach this height yet. Nothing has been written + // for the block, so there is nothing to restore: the poller asks again. + if (error?.code === -8) return after(Step.poll(), POLL_INTERVAL_MS); + throw error; + } const parent = await scannedBlockAt(database, blockDataVerbose.height - 1); if (parent && blockDataVerbose.previousblockhash !== parent.hash) { const restoredHeight = await rewindToFork(database, parent); @@ -630,7 +649,7 @@ async function processBlock(blockHeight) { log.error('Block processor encountered an error.'); log.error(error); const deep = Boolean(error.message && error.message.includes('duplicate key')); - return after(Step.recover(true, deep)); + return after(Step.recover(true, deep), POLL_INTERVAL_MS); } } @@ -1160,16 +1179,6 @@ async function rewindToFork(database, parent) { return height; } -// How long the explorer waits before asking again whether the chain has moved. -// -// This is the floor on how fast a node can process blocks: a block is not looked -// at until the next poll, so nothing downstream of block processing - expiring -// app records, trimming surplus instances, the give-up pass - can run more often -// than this however fast blocks are produced. Production wants 5s against a 30s -// block; a harness driving its own chain wants it far shorter, and had no way to -// say so. -const POLL_INTERVAL_MS = config.fluxapps.explorerPollIntervalMs ?? 5000; - /** * The block processor's step at the tip: whether fluxd holds a block the * explorer has not processed, or a reorganisation moved the explorer back. diff --git a/tests/unit/explorerService.test.js b/tests/unit/explorerService.test.js index c53c3f5737..b8bc5efb26 100644 --- a/tests/unit/explorerService.test.js +++ b/tests/unit/explorerService.test.js @@ -924,6 +924,41 @@ describe('explorerService tests', () => { sinon.assert.notCalled(removeDocumentsStub); }); }); + + describe('a block fluxd does not give', () => { + const pollIntervalMs = config.fluxapps.explorerPollIntervalMs; + const blockHeight = 100000; + + beforeEach(() => { + daemonServiceMiscRpcsStub.returns({ data: { synced: true, height: blockHeight } }); + }); + + it('is asked for again at the next poll, with nothing written, while fluxd\'s chain does not reach it', async () => { + daemonServiceBlockchainRpcsStub.resolves({ status: 'error', data: { code: -8, name: 'RPCError', message: 'Block height out of range' } }); + + const step = await explorerService.processBlock(blockHeight); + + expect(step).to.deep.equal({ next: explorerService.Step.poll(), waitMs: pollIntervalMs }); + sinon.assert.notCalled(dbStubUpdate); + }); + + it('is recovered from one poll interval later when fluxd refuses it for another reason', async () => { + daemonServiceBlockchainRpcsStub.resolves({ status: 'error', data: { code: -28, name: 'RPCError', message: 'Loading block index...' } }); + + const step = await explorerService.processBlock(blockHeight); + + expect(step).to.deep.equal({ next: explorerService.Step.recover(true, false), waitMs: pollIntervalMs }); + }); + + it('is recovered from when out of range is raised after the block was fetched', async () => { + daemonServiceBlockchainRpcsStub.resolves({ status: 'success', data: { tx: [], height: blockHeight, confirmations: 1 } }); + sinon.stub(fluxnodeAddressRecord, 'recordBlock').rejects(Object.assign(new Error('Block height out of range'), { code: -8 })); + + const step = await explorerService.processBlock(blockHeight); + + expect(step).to.deep.equal({ next: explorerService.Step.recover(true, false), waitMs: pollIntervalMs }); + }); + }); }); describe('the fluxnode address record', () => { From 6115c4196ca084f2aa6ef98971e7b543b1f04c4d Mon Sep 17 00:00:00 2001 From: David White Date: Wed, 18 Nov 2026 13:24:57 +0000 Subject: [PATCH 2/5] test(harness): 4005 a block fluxd refuses is asked for again at the pace of the explorer's poll Co-Authored-By: Claude Opus 5.5 --- ...again-at-the-pace-of-the-explorers-poll.js | 89 +++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 test-infra/runner/tests/4005-a-block-fluxd-refuses-is-asked-for-again-at-the-pace-of-the-explorers-poll.js diff --git a/test-infra/runner/tests/4005-a-block-fluxd-refuses-is-asked-for-again-at-the-pace-of-the-explorers-poll.js b/test-infra/runner/tests/4005-a-block-fluxd-refuses-is-asked-for-again-at-the-pace-of-the-explorers-poll.js new file mode 100644 index 0000000000..3262120024 --- /dev/null +++ b/test-infra/runner/tests/4005-a-block-fluxd-refuses-is-asked-for-again-at-the-pace-of-the-explorers-poll.js @@ -0,0 +1,89 @@ +/* + * A block fluxd refuses is asked for again no faster than the explorer polls for a + * new block, however long fluxd goes on refusing it, and once fluxd gives it the + * explorer processes it and reaches the tip. + * + * fluxd answers every call but getblock for the node under test, so the node keeps + * reading fluxd as synced and its sync wait never paces the retry. The window is the + * time between two of the node's reads of fluxd's height (daemonInfoIntervalMs): + * paced by explorerPollIntervalMs, the explorer asks for the block at most + * window / poll + 1 times in it. + * + * The daemon stub's refusal is a generic RPC error. fluxd's out-of-range answer + * (-8), which the explorer waits on instead of recovering from, is covered by the + * unit suite: the stub serves a block at any height. + */ +import { describe, it, before } from 'mocha'; +import { expect } from 'chai'; +import { createTestEnv } from '../framework/test-env.js'; +import { bootAndPeer } from '../framework/reconciler-suite.js'; +import { + stopTicker, advanceBlock, getState, failRpc, clearRpcFailures, getJournal, clearJournal, +} from '../framework/daemon-control.js'; +import { loadSharedConfig } from '../framework/coupled-knobs.js'; +import { dumpLogsOnFailure } from '../framework/log-on-failure.js'; +import { afterTeardown } from '../framework/teardown-hook.js'; + +const NODES = 3; +// The middle of the ring: every backward arc wraps onto index 0. +const NODE = 1; +const { daemonInfoIntervalMs, explorerPollIntervalMs } = loadSharedConfig().fluxapps; + +describe('a block fluxd refuses is asked for again at the pace of the explorer\'s poll', function () { + let env; + let client; + let ip; + + dumpLogsOnFailure(() => env); + + before(async function () { + this.timeout(420000); + env = await createTestEnv({ hookCtx: this, nodes: NODES, tickerAutostart: false }); + await bootAndPeer(env); + await stopTicker(); + client = env.clients[NODE]; + ip = client.ip; + }); + + afterTeardown(async function () { + await clearRpcFailures(ip).catch(() => {}); + await env?.teardown(); + }); + + async function tipProcessed(afterId) { + const { currentHeight } = await getState(); + await client.waitForEvent('block:processed', (d) => d.height === currentHeight, 120000, { afterId }); + return currentHeight; + } + + const nextDaemonPoll = (afterId) => client.waitForEvent('daemon:polled', () => true, daemonInfoIntervalMs * 4, { afterId }); + + it('asks for the refused block once a poll at most, and processes it once fluxd gives it', async function () { + this.timeout(240000); + let mark = client.getLastEventId(); + await advanceBlock(); + await tipProcessed(mark); + + await failRpc(ip, 'getblock', { times: 1000000 }); + mark = client.getLastEventId(); + await advanceBlock(); + const { currentHeight: refused } = await getState(); + // The node has read the new height: from its next poll the explorer asks for + // the block fluxd refuses. + const learned = await client.waitForEvent('daemon:polled', (d) => d.height === refused, daemonInfoIntervalMs * 4, { afterId: mark }); + const opened = await nextDaemonPoll(learned.id); + await clearJournal(); + const openedAt = Date.now(); + await nextDaemonPoll(opened.id); + const { total: asked } = await getJournal({ method: 'getblock', sourceIp: ip }); + + const windowMs = Date.now() - openedAt; + const ceiling = Math.floor(windowMs / explorerPollIntervalMs) + 1; + expect(asked, 'the explorer never asked for the refused block').to.be.at.least(1); + expect(asked, `getblock asked ${asked} times in ${windowMs}ms against a poll of ${explorerPollIntervalMs}ms`).to.be.at.most(ceiling); + + mark = client.getLastEventId(); + await clearRpcFailures(ip); + expect(await tipProcessed(mark)).to.equal(refused); + }); +}); From e757543355adf543abc28f86142e67a3a599e65c Mon Sep 17 00:00:00 2001 From: David White Date: Wed, 18 Nov 2026 13:34:53 +0000 Subject: [PATCH 3/5] test(harness): the daemon stub refuses a block above the asking node's chain as fluxd does getblock by height above the node's chain answers -8 "Block height out of range", and a handler's thrown RPC code reaches the caller. Co-Authored-By: Claude Opus 5.5 --- test-infra/daemon-stub/index.js | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/test-infra/daemon-stub/index.js b/test-infra/daemon-stub/index.js index 1abfffc078..b19586c737 100644 --- a/test-infra/daemon-stub/index.js +++ b/test-infra/daemon-stub/index.js @@ -55,6 +55,12 @@ function hashAt(height) { return forkedHashes.get(height) ?? `000000000000stub${height}`; } +// An error a handler throws to answer with fluxd's RPC error code; any other +// throw answers -1. +function rpcError(code, message) { + return Object.assign(new Error(message), { rpcCode: code }); +} + // height -> block time, epoch seconds. A block's time is fixed when it is mined, // or when it is first asked about if it predates this stub, and every later read // returns the same value - as the chain does, where every node reads one header @@ -397,10 +403,13 @@ const rpcHandlers = { return pending?.hash ?? hashAt(height); }, - getblock: (params) => { + // A height above the asking node's chain is refused as fluxd refuses it. + getblock: (params, sourceIp) => { const hashOrHeight = params[0]; const verbosity = params[1] || 1; const asNum = Number(hashOrHeight); + const byHeight = typeof hashOrHeight === 'number' || /^\d{1,12}$/.test(String(hashOrHeight)); + if (byHeight && asNum > localHeightFor(sourceIp)) throw rpcError(-8, 'Block height out of range'); const pending = pendingBlocks.find((b) => b.height === asNum || b.height === hashOrHeight || b.hash === hashOrHeight); if (pending) { @@ -715,7 +724,7 @@ async function answerRpc(handlers, request, sourceIp, port) { return { body: { result, error: null, id } }; } catch (e) { console.error(`RPC error for ${method} from ${sourceIp}:`, e.message); - return { body: { result: null, error: { code: -1, message: e.message }, id } }; + return { body: { result: null, error: { code: e.rpcCode ?? -1, message: e.message }, id } }; } } From 93459aa2e4e2f8c01fa07350b72d8f0292d7e856 Mon Sep 17 00:00:00 2001 From: David White Date: Wed, 18 Nov 2026 13:34:53 +0000 Subject: [PATCH 4/5] test(harness): 4005 a block above fluxd's chain is waited for without a recovery recoverAndRestart counts each recovery it runs (explorer:recovery). Co-Authored-By: Claude Opus 5.5 --- ZelBack/src/services/explorerService.js | 1 + ...again-at-the-pace-of-the-explorers-poll.js | 44 +++++++++++++++++-- 2 files changed, 41 insertions(+), 4 deletions(-) diff --git a/ZelBack/src/services/explorerService.js b/ZelBack/src/services/explorerService.js index 148854085f..fe54cb791a 100644 --- a/ZelBack/src/services/explorerService.js +++ b/ZelBack/src/services/explorerService.js @@ -1214,6 +1214,7 @@ async function pollForNewBlocks() { async function recoverAndRestart(restoreDatabase, deepRestore) { const syncWaitMs = untilDaemonSyncedMs(); if (syncWaitMs) return after(Step.recover(restoreDatabase, deepRestore), syncWaitMs); + fluxEventBus.count('explorer:recovery'); try { const db = dbHelper.databaseConnection(); const database = db.db(config.database.daemon.database); diff --git a/test-infra/runner/tests/4005-a-block-fluxd-refuses-is-asked-for-again-at-the-pace-of-the-explorers-poll.js b/test-infra/runner/tests/4005-a-block-fluxd-refuses-is-asked-for-again-at-the-pace-of-the-explorers-poll.js index 3262120024..2db50084d3 100644 --- a/test-infra/runner/tests/4005-a-block-fluxd-refuses-is-asked-for-again-at-the-pace-of-the-explorers-poll.js +++ b/test-infra/runner/tests/4005-a-block-fluxd-refuses-is-asked-for-again-at-the-pace-of-the-explorers-poll.js @@ -9,18 +9,21 @@ * paced by explorerPollIntervalMs, the explorer asks for the block at most * window / poll + 1 times in it. * - * The daemon stub's refusal is a generic RPC error. fluxd's out-of-range answer - * (-8), which the explorer waits on instead of recovering from, is covered by the - * unit suite: the stub serves a block at any height. + * A block above fluxd's chain is answered out of range (-8), and the explorer waits + * for it at the poll without recovering. The fixture holds the explorer's request + * for the next block, takes fluxd's chain back to the tip, then lets fluxd answer; + * the recovery count (explorer:recovery) must not move. */ import { describe, it, before } from 'mocha'; import { expect } from 'chai'; import { createTestEnv } from '../framework/test-env.js'; import { bootAndPeer } from '../framework/reconciler-suite.js'; import { - stopTicker, advanceBlock, getState, failRpc, clearRpcFailures, getJournal, clearJournal, + stopTicker, advanceBlock, getState, setHeight, failRpc, clearRpcFailures, holdRpc, releaseRpc, + getJournal, clearJournal, } from '../framework/daemon-control.js'; import { loadSharedConfig } from '../framework/coupled-knobs.js'; +import { waitFor, assertNoEvent } from '../framework/wait.js'; import { dumpLogsOnFailure } from '../framework/log-on-failure.js'; import { afterTeardown } from '../framework/teardown-hook.js'; @@ -47,6 +50,7 @@ describe('a block fluxd refuses is asked for again at the pace of the explorer\' afterTeardown(async function () { await clearRpcFailures(ip).catch(() => {}); + await releaseRpc(ip).catch(() => {}); await env?.teardown(); }); @@ -86,4 +90,36 @@ describe('a block fluxd refuses is asked for again at the pace of the explorer\' await clearRpcFailures(ip); expect(await tipProcessed(mark)).to.equal(refused); }); + + it('waits for a block above fluxd\'s chain without recovering, and processes it once fluxd holds it', async function () { + this.timeout(240000); + let mark = client.getLastEventId(); + await advanceBlock(); + const tip = await tipProcessed(mark); + + // The explorer asks for the next block, and fluxd's chain is back at the tip + // by the time it answers: out of range. + await holdRpc(ip, 'getblock'); + await clearJournal(); + mark = client.getLastEventId(); + await advanceBlock(); + await waitFor(async () => (await getJournal({ method: 'getblock', sourceIp: ip })).total >= 1, { + timeout: daemonInfoIntervalMs * 4, interval: 200, label: `the explorer asking for block ${tip + 1}`, + }); + const lowered = client.getLastEventId(); + await setHeight(tip); + const recoveries = (await client.getTestCounters())['explorer:recovery'] ?? 0; + await releaseRpc(ip); + + // The node reads fluxd's height as the tip again: from here the poller asks + // for nothing above it. + await client.waitForEvent('daemon:polled', (d) => d.height === tip, daemonInfoIntervalMs * 4, { afterId: lowered }); + await nextDaemonPoll(client.getLastEventId()); + expect((await client.getTestCounters())['explorer:recovery'] ?? 0, 'recoveries from a block fluxd does not hold').to.equal(recoveries); + await assertNoEvent(client, 'block:processed', (d) => d.height > tip, 0, { afterId: mark }); + + mark = client.getLastEventId(); + await advanceBlock(); + expect(await tipProcessed(mark)).to.equal(tip + 1); + }); }); From 13f9deca976fa91e8b7419a22de95121f7bd2128 Mon Sep 17 00:00:00 2001 From: David White Date: Wed, 18 Nov 2026 15:45:08 +0000 Subject: [PATCH 5/5] test(harness): 2268 loses the delete only once every standby has applied it whole Setup waits for both standbys to hold the stale files before the primary deletes them, and reads the other standby's sequence only once the directory is gone there and its folder is idle with nothing needed. Co-Authored-By: Claude Opus 5.5 --- ...t-lost-a-delete-hears-the-primary-again.js | 23 +++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/test-infra/runner/tests/2268-a-standby-that-lost-a-delete-hears-the-primary-again.js b/test-infra/runner/tests/2268-a-standby-that-lost-a-delete-hears-the-primary-again.js index ca7875f494..a498d77d9a 100644 --- a/test-infra/runner/tests/2268-a-standby-that-lost-a-delete-hears-the-primary-again.js +++ b/test-infra/runner/tests/2268-a-standby-that-lost-a-delete-hears-the-primary-again.js @@ -111,8 +111,16 @@ describe('a standby that lost a delete hears the primary again', function () { `mkdir -p ${primaryRoot}/${STALE} && head -c 70000 /dev/urandom > ${primaryRoot}/${STALE}/world.sav && echo meta > ${primaryRoot}/${STALE}/meta.sav && chown -R 1000:1000 ${primaryRoot}/${STALE}`); expect(made.exitCode).to.equal(0); await scanFolder(env.clients[primary], folder); - await waitFor(async () => (await onLeaver(`${STALE}/meta.sav`)) !== null, { - timeout: 120000, interval: 2000, label: 'the standby holds the backup', + // Both standbys hold the files before they are deleted. A standby that never held + // them takes the delete in its own order, so its directory's delete can land after + // the sequence read below and reach the leaver on its own, which syncthing cannot + // apply while the directory holds the files. + const standbys = HOLDERS.filter((i) => i !== primary); + const rootOf = Object.fromEntries(await Promise.all(standbys.map(async (i) => [i, (await getFolderConfig(env.clients[i], folder)).path]))); + const staleFiles = staleItems.filter((name) => name !== STALE); + await waitFor(async () => (await Promise.all(standbys.flatMap((i) => staleFiles.map((name) => readPath(env.clients[i], `${rootOf[i]}/${name}`))))) + .every((content) => content !== null), { + timeout: 120000, interval: 2000, label: 'every standby holds the backup', }); // The delete is lost from every device that holds it, which needs a record of // each in the standby's index: every holder's index has reached it. @@ -126,8 +134,15 @@ describe('a standby that lost a delete hears the primary again', function () { await execInContainer(env.clients[primary].container, `rm -rf ${primaryRoot}/${STALE}`); await scanFolder(env.clients[primary], folder); const other = HOLDERS.find((i) => i !== primary && i !== leaver); - await waitFor(async () => (await readPath(env.clients[other], `${path}/${STALE}/meta.sav`)) === null, { - timeout: 120000, interval: 2000, label: 'the other standby took the delete', + // Its sequence is read once it has applied the whole delete, directory included, so + // it holds no record of the delete above that sequence. + await waitFor(async () => { + const gone = await execInContainer(env.clients[other].container, `test ! -e "${rootOf[other]}/${STALE}"`); + if (gone.exitCode !== 0) return false; + const { state, needTotalItems } = await getFolderStatus(env.clients[other], folder); + return state === 'idle' && needTotalItems === 0; + }, { + timeout: 120000, interval: 2000, label: 'the other standby took the whole delete', }); // Every device that holds the delete would otherwise repeat it. // eslint-disable-next-line no-restricted-syntax