From d829be998f997bc77d35afeacbb9a069f11f7639 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 08:55:28 +0000 Subject: [PATCH] fix: don't let stale syncing flags stall mempool tx processing At startup the mempool handler waits in waitForSyncing until its addresses' `syncing` flag clears. That wait had no timeout and only checked `initializing` on entry, and syncAddresses never cleared the flag for addresses it hadn't reached when it failed. A sync that died left addresses flagged, so a tx to one of them arriving during startup waited forever; two such handlers (MAX_MEMPOOL_TXS_TO_PROCESS_AT_A_TIME) stalled all mempool processing, delaying triggers to block time and leaving client payments pending until restart. - waitForSyncing stops waiting once initialization ends or after CHRONIK_SYNCING_WAIT_TIMEOUT_MS (2 min), logging the addresses still flagged. Proceeding is safe: the live upsert and the bulk createMany (skipDuplicates) both tolerate the other inserting first. - syncAddresses clears the flag in a finally for every address it didn't release, so a failed sync no longer leaves addresses flagged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019G564fZdU5yXdFx9sELPdd --- constants/index.ts | 3 + services/chronikService.ts | 34 +++++++- tests/unittests/chronikService.test.ts | 111 ++++++++++++++++++++++++- 3 files changed, 146 insertions(+), 2 deletions(-) diff --git a/constants/index.ts b/constants/index.ts index 290ec3c0..93f08a13 100644 --- a/constants/index.ts +++ b/constants/index.ts @@ -277,6 +277,9 @@ export const BCH_TX_EXPLORER_URL = 'https://blockchair.com/bitcoin-cash/transact export const MAX_MEMPOOL_TXS_TO_PROCESS_AT_A_TIME = 2 export const MAX_CONFIRMED_TXS_TO_PROCESS_AT_A_TIME = 20 export const CHRONIK_INITIALIZATION_DELAY = 2000 +// Longest a mempool tx handler waits at startup for its addresses' `syncing` flag +// to clear. The flag can be left set by a sync that died, so never wait forever. +export const CHRONIK_SYNCING_WAIT_TIMEOUT_MS = 120000 export const MEMPOOL_PROCESS_DELAY = 100 export const CONFIRMED_TX_PROCESS_DELAY = 100 diff --git a/services/chronikService.ts b/services/chronikService.ts index 1ad969ee..8b2bdbf3 100644 --- a/services/chronikService.ts +++ b/services/chronikService.ts @@ -1,7 +1,7 @@ import { BlockInfo, ChronikClient, ConnectionStrategy, ScriptUtxo, Tx, WsConfig, WsEndpoint, WsMsgClient, WsSubScriptClient } from 'chronik-client' import { encodeCashAddress, decodeCashAddress } from 'ecashaddrjs' import { AddressWithTransaction, BlockchainInfo, TransactionDetails, ProcessedMessages, SubbedAddressesLog, SyncAndSubscriptionReturn, SubscriptionReturn, SimpleBlockInfo } from 'types/chronikTypes' -import { CHRONIK_MESSAGE_CACHE_DELAY, RESPONSE_MESSAGES, XEC_TIMESTAMP_THRESHOLD, XEC_NETWORK_ID, BCH_NETWORK_ID, BCH_TIMESTAMP_THRESHOLD, CHRONIK_FETCH_N_TXS_PER_PAGE, KeyValueT, NETWORK_IDS_FROM_SLUGS, SOCKET_MESSAGES, NETWORK_IDS, NETWORK_TICKERS, MainNetworkSlugsType, MAX_MEMPOOL_TXS_TO_PROCESS_AT_A_TIME, MAX_CONFIRMED_TXS_TO_PROCESS_AT_A_TIME, MEMPOOL_PROCESS_DELAY, CONFIRMED_TX_PROCESS_DELAY, CHRONIK_INITIALIZATION_DELAY, LATENCY_TEST_CHECK_DELAY, INITIAL_ADDRESS_SYNC_FETCH_CONCURRENTLY, TX_EMIT_BATCH_SIZE, DB_COMMIT_BATCH_SIZE, MAX_TXS_PER_ADDRESS, TX_BATCH_POLLING_DELAY, SLOW_ADDRESS_SYNC_LOG_THRESHOLD, SLOWEST_ADDRESSES_TO_LOG, CHRONIK_HTTP_MAX_TRIES, CHRONIK_HTTP_BASE_DELAY_MS, CHRONIK_WS_BASE_DELAY_MS, CHRONIK_WS_MAX_DELAY_MS } from 'constants/index' +import { CHRONIK_MESSAGE_CACHE_DELAY, RESPONSE_MESSAGES, XEC_TIMESTAMP_THRESHOLD, XEC_NETWORK_ID, BCH_NETWORK_ID, BCH_TIMESTAMP_THRESHOLD, CHRONIK_FETCH_N_TXS_PER_PAGE, KeyValueT, NETWORK_IDS_FROM_SLUGS, SOCKET_MESSAGES, NETWORK_IDS, NETWORK_TICKERS, MainNetworkSlugsType, MAX_MEMPOOL_TXS_TO_PROCESS_AT_A_TIME, MAX_CONFIRMED_TXS_TO_PROCESS_AT_A_TIME, MEMPOOL_PROCESS_DELAY, CONFIRMED_TX_PROCESS_DELAY, CHRONIK_INITIALIZATION_DELAY, CHRONIK_SYNCING_WAIT_TIMEOUT_MS, LATENCY_TEST_CHECK_DELAY, INITIAL_ADDRESS_SYNC_FETCH_CONCURRENTLY, TX_EMIT_BATCH_SIZE, DB_COMMIT_BATCH_SIZE, MAX_TXS_PER_ADDRESS, TX_BATCH_POLLING_DELAY, SLOW_ADDRESS_SYNC_LOG_THRESHOLD, SLOWEST_ADDRESSES_TO_LOG, CHRONIK_HTTP_MAX_TRIES, CHRONIK_HTTP_BASE_DELAY_MS, CHRONIK_WS_BASE_DELAY_MS, CHRONIK_WS_MAX_DELAY_MS } from 'constants/index' import { productionAddresses } from 'prisma-local/seeds/addresses' import prisma from 'prisma-local/clientInstance' import { @@ -906,15 +906,34 @@ export class ChronikBlockchainClient { return result } + // At startup, lets a running sync of the tx's addresses finish before the + // mempool handler persists it. Both paths tolerate the other inserting first + // (upsert / createMany skipDuplicates), so this is only an ordering nicety and + // must never block for good: a sync that died leaves `syncing` set, and with + // MAX_MEMPOOL_TXS_TO_PROCESS_AT_A_TIME handlers stuck here all mempool + // processing would stall. Stop waiting once initialization ends or on timeout. public async waitForSyncing (txId: string, addressStringArray: string[]): Promise { if (!this.initializing) return console.log(`${this.CHRONIK_MSG_PREFIX}: Waiting unblocking addresses for ${txId}`) + const deadline = Date.now() + CHRONIK_SYNCING_WAIT_TIMEOUT_MS while (true) { const addresses = await fetchAddressesArray(addressStringArray) if (addresses.every(a => !a.syncing)) { console.log(`${this.CHRONIK_MSG_PREFIX}: Finished unblocking addresses for ${txId}`) return } + if (!this.initializing) { + console.log(`${this.CHRONIK_MSG_PREFIX}: Initialization finished, no longer waiting on addresses for ${txId}`) + return + } + if (Date.now() >= deadline) { + const stillSyncing = addresses.filter(a => a.syncing).map(a => a.address) + console.warn( + `${this.CHRONIK_MSG_PREFIX}: Gave up waiting after ${CHRONIK_SYNCING_WAIT_TIMEOUT_MS / 1000}s ` + + `for addresses still marked syncing for ${txId}: ${stillSyncing.join(', ')}` + ) + return + } await new Promise(resolve => setTimeout(resolve, CHRONIK_INITIALIZATION_DELAY)) } } @@ -1357,6 +1376,9 @@ export class ChronikBlockchainClient { console.log(`${this.CHRONIK_MSG_PREFIX} Syncing ${addresses.length} addresses...`) console.time(`${this.CHRONIK_MSG_PREFIX} syncAddresses`) await setSyncingBatch(addresses.map(a => a.address), true) + // Addresses whose `syncing` flag this run has cleared; the rest are cleared in + // the finally below so a failed sync doesn't leave them flagged indefinitely. + const releasedAddresses = new Set() const perAddrCount = new Map() addresses.forEach(a => perAddrCount.set(a.id, 0)) @@ -1387,6 +1409,7 @@ export class ChronikBlockchainClient { if (batch.phase === 'addresses-synced') { // marcador de slice => desmarca syncing await setSyncingBatch(batch.addressesSynced, false) + batch.addressesSynced.forEach(a => releasedAddresses.add(a)) progress?.addressesDone(this.networkSlug, batch.addressesSynced.length) continue } @@ -1455,6 +1478,15 @@ export class ChronikBlockchainClient { failedAddressesWithErrors[a.address] = err.stack ?? String(err) } }) + } finally { + const unreleased = addresses.map(a => a.address).filter(a => !releasedAddresses.has(a)) + if (unreleased.length > 0) { + try { + await setSyncingBatch(unreleased, false) + } catch (err: any) { + console.error(`${this.CHRONIK_MSG_PREFIX}: Failed to clear syncing flag for ${unreleased.length} addresses: ${err.message as string}`) + } + } } progress?.addressesFailed(this.networkSlug, failedAddressesWithErrors) diff --git a/tests/unittests/chronikService.test.ts b/tests/unittests/chronikService.test.ts index cbe08ed7..0ddeb2ed 100644 --- a/tests/unittests/chronikService.test.ts +++ b/tests/unittests/chronikService.test.ts @@ -9,7 +9,8 @@ import { multiBlockchainClient } from '../../services/chronikService' import { Address, Prisma } from '@prisma/client' -import { fetchAddressesArray } from '../../services/addressService' +import { fetchAddressesArray, setSyncingBatch } from '../../services/addressService' +import { CHRONIK_SYNCING_WAIT_TIMEOUT_MS } from '../../constants/index' import { fetchUnconfirmedTransactions, deleteTransactions, upsertTransaction, connectTransactionsToPricesForAddresses, connectTransactionsListToPrices, createManyTransactionsForSync, invalidateCachesForAddresses } from '../../services/transactionService' import prisma from '../../prisma-local/clientInstance' import { executeAddressTriggers } from '../../services/triggerService' @@ -2027,3 +2028,111 @@ describe('changed addresses reported by the sync', () => { await expect(multiBlockchainClient.syncMissedTransactions()).resolves.toBeUndefined() }) }) + +describe('stale syncing flags', () => { + const ADDR = 'ecash:qqkv9wr69ry2p9l53lxp635va4h86wv435995w8p2h' + + beforeEach(() => { + process.env.WS_AUTH_KEY = 'test-auth-key' + jest.spyOn(console, 'log').mockImplementation(() => {}) + jest.spyOn(console, 'warn').mockImplementation(() => {}) + jest.spyOn(console, 'error').mockImplementation(() => {}) + ;(fetchAddressesArray as jest.Mock).mockReset() + }) + + afterEach(() => { + jest.useRealTimers() + jest.restoreAllMocks() + }) + + describe('waitForSyncing', () => { + it('gives up after the timeout when an address stays marked syncing', async () => { + jest.useFakeTimers() + ;(fetchAddressesArray as jest.Mock).mockResolvedValue([{ address: ADDR, syncing: true }]) + const client = new ChronikBlockchainClient('ecash') + client.initializing = true + + let done = false + const p = client.waitForSyncing('tx1', [ADDR]).then(() => { done = true }) + + await jest.advanceTimersByTimeAsync(CHRONIK_SYNCING_WAIT_TIMEOUT_MS - 5000) + expect(done).toBe(false) + await jest.advanceTimersByTimeAsync(10000) + await p + expect(done).toBe(true) + expect(console.warn).toHaveBeenCalledWith(expect.stringContaining('Gave up waiting')) + }) + + it('stops waiting once the client finishes initializing', async () => { + jest.useFakeTimers() + ;(fetchAddressesArray as jest.Mock).mockResolvedValue([{ address: ADDR, syncing: true }]) + const client = new ChronikBlockchainClient('ecash') + client.initializing = true + + let done = false + const p = client.waitForSyncing('tx1', [ADDR]).then(() => { done = true }) + await jest.advanceTimersByTimeAsync(3000) + expect(done).toBe(false) + + client.setInitialized() + await jest.advanceTimersByTimeAsync(3000) + await p + expect(done).toBe(true) + expect(console.warn).not.toHaveBeenCalled() + }) + + it('returns as soon as the addresses are no longer syncing', async () => { + ;(fetchAddressesArray as jest.Mock).mockResolvedValue([{ address: ADDR, syncing: false }]) + const client = new ChronikBlockchainClient('ecash') + client.initializing = true + + await expect(client.waitForSyncing('tx1', [ADDR])).resolves.toBeUndefined() + expect(fetchAddressesArray).toHaveBeenCalledTimes(1) + }) + + it('does not wait at all when not initializing', async () => { + const client = new ChronikBlockchainClient('ecash') + client.setInitialized() + + await client.waitForSyncing('tx1', [ADDR]) + expect(fetchAddressesArray).not.toHaveBeenCalled() + }) + }) + + describe('syncAddresses', () => { + const a1 = { id: 'addr-1', address: 'ecash:addr-1', networkId: 1 } as any + const a2 = { id: 'addr-2', address: 'ecash:addr-2', networkId: 1 } as any + + beforeEach(() => { + jest.spyOn(prisma.address, 'findMany').mockResolvedValue([] as any) + ;(setSyncingBatch as jest.Mock).mockReset().mockResolvedValue(undefined) + }) + + it('clears the syncing flag of addresses the sync never finished when it fails', async () => { + const client = new ChronikBlockchainClient('ecash') + jest.spyOn(client as any, 'fetchLatestTxsForAddresses').mockImplementation(async function * () { + yield { phase: 'addresses-synced', chronikTxs: [], addressesSynced: ['ecash:addr-1'] } + throw new Error('chronik down') + }) + + await client.syncAddresses([a1, a2]) + + expect(setSyncingBatch).toHaveBeenNthCalledWith(1, ['ecash:addr-1', 'ecash:addr-2'], true) + expect(setSyncingBatch).toHaveBeenNthCalledWith(2, ['ecash:addr-1'], false) + expect(setSyncingBatch).toHaveBeenNthCalledWith(3, ['ecash:addr-2'], false) + expect(setSyncingBatch).toHaveBeenCalledTimes(3) + }) + + it('does not clear flags again when every address finished', async () => { + const client = new ChronikBlockchainClient('ecash') + jest.spyOn(client as any, 'fetchLatestTxsForAddresses').mockImplementation(async function * () { + yield { phase: 'addresses-synced', chronikTxs: [], addressesSynced: ['ecash:addr-1', 'ecash:addr-2'] } + }) + + await client.syncAddresses([a1, a2]) + + expect(setSyncingBatch).toHaveBeenCalledTimes(2) + expect(setSyncingBatch).toHaveBeenLastCalledWith(['ecash:addr-1', 'ecash:addr-2'], false) + }) + }) +})