From e5456864457cee0b42b541145e688a8e0df0e107 Mon Sep 17 00:00:00 2001 From: David Klakurka Date: Wed, 25 Nov 2026 20:55:59 -0700 Subject: [PATCH 1/4] fix: link prices per sync batch and in chunks so txs don't stay unpriced Production had ~168k txs with no price links. The startup sync job only linked prices after syncing every address, and on prod that sync ran 45+ minutes and was restarted (deploys) before finishing, so every run's txs were left unpriced and the next run started over. Linking itself would also have failed at that size: all links were written in one interactive DB transaction with a 30s timeout, so it rolled back entirely. Meanwhile batch inserts were hitting the 15s transaction timeout when MySQL stalled, dropping those batches. - Bulk sync: link prices for each committed batch right after inserting it (before triggers), so an interrupted sync leaves nothing unpriced. Failures are logged and retried later. - connectTransactionsListToPrices: write links in chunks of 500 txs, each in its own DB transaction; a failed chunk is logged and skipped instead of rolling back the whole list. Skip the unlink step for txs known to have no links. Log one summary line instead of several per call. Returns the number of txs linked. - connectAllTransactionsToPrices: page unpriced txs by id (5k at a time) instead of loading them all; a concurrent call waits for the run in progress. - New repeating job (immediately at boot, then hourly) that links txs still without prices, independent of the startup sync, so the existing backlog clears after deploy. - persistManyTransactionRows: retry once when the insert transaction times out (Prisma P2028) instead of dropping the batch. Co-Authored-By: Claude Opus 5.5 --- constants/index.ts | 10 + jobs/initJobs.ts | 23 ++- jobs/workers.ts | 20 ++ services/chronikService.ts | 17 +- services/transactionService.ts | 211 +++++++++++++-------- tests/unittests/chronikService.test.ts | 54 +++++- tests/unittests/transactionService.test.ts | 139 ++++++++++++++ 7 files changed, 389 insertions(+), 85 deletions(-) diff --git a/constants/index.ts b/constants/index.ts index 4565777b..8d153d72 100644 --- a/constants/index.ts +++ b/constants/index.ts @@ -306,6 +306,16 @@ export const TRIGGER_LOG_BATCH_SIZE = 200 export const PRICES_CONNECTION_BATCH_SIZE = 1_000 // interactive $transaction timeout in ms (for batched delete + createMany of prices) export const PRICES_CONNECTION_TIMEOUT = 30_000 +// Txs whose price links are replaced per DB transaction (2 links per tx). Small +// chunks keep each transaction well under PRICES_CONNECTION_TIMEOUT and mean a +// failure only loses that chunk, not the whole run. +export const PRICES_CONNECTION_TX_CHUNK_SIZE = 500 +// Unpriced txs loaded into memory per page by connectAllTransactionsToPrices. +export const UNPRICED_TXS_PAGE_SIZE = 5_000 +// How often the jobs process retries linking prices for txs that still have none. +export const PRICE_LINKING_REPEAT_DELAY = 60 * 60 * 1000 +// Wait before retrying a sync insert whose DB transaction timed out. +export const SYNC_INSERT_RETRY_DELAY = 2_000 export const CLIENT_PAYMENT_EXPIRATION_TIME = (7) * (24 * 60 * 60 * 1000) // (number of days) * (24 * 60 * 60 * 1000) diff --git a/jobs/initJobs.ts b/jobs/initJobs.ts index 3d7a0c1d..9997b511 100644 --- a/jobs/initJobs.ts +++ b/jobs/initJobs.ts @@ -1,8 +1,8 @@ -import { CLIENT_PAYMENT_EXPIRATION_TIME, CURRENT_PRICE_REPEAT_DELAY } from 'constants/index' +import { CLIENT_PAYMENT_EXPIRATION_TIME, CURRENT_PRICE_REPEAT_DELAY, PRICE_LINKING_REPEAT_DELAY } from 'constants/index' import { Queue } from 'bullmq' import { redisBullMQ } from 'redis/clientInstance' import EventEmitter from 'events' -import { syncCurrentPricesWorker, syncBlockchainAndPricesWorker, cleanupClientPaymentsWorker } from './workers' +import { syncCurrentPricesWorker, syncBlockchainAndPricesWorker, cleanupClientPaymentsWorker, linkUnpricedTransactionsWorker } from './workers' EventEmitter.defaultMaxListeners = 20 @@ -11,10 +11,12 @@ const main = async (): Promise => { const pricesQueue = new Queue('pricesSync', { connection: redisBullMQ }) const blockchainQueue = new Queue('blockchainSync', { connection: redisBullMQ }) const cleanupQueue = new Queue('clientPaymentCleanup', { connection: redisBullMQ }) + const priceLinkingQueue = new Queue('priceLinking', { connection: redisBullMQ }) await pricesQueue.obliterate({ force: true }) await blockchainQueue.obliterate({ force: true }) await cleanupQueue.obliterate({ force: true }) + await priceLinkingQueue.obliterate({ force: true }) // Start blockchain sync first; current prices job starts only after it completes await blockchainQueue.add('syncBlockchainAndPrices', @@ -54,6 +56,23 @@ const main = async (): Promise => { ) await cleanupClientPaymentsWorker(cleanupQueue.name) + + // Runs right away and then periodically, independent of the blockchain sync, + // so unpriced txs get linked even if that sync is interrupted before its end. + await priceLinkingQueue.add( + 'linkUnpricedTransactions', + {}, + { + jobId: 'linkUnpricedTransactions', + removeOnComplete: true, + removeOnFail: true, + repeat: { + every: PRICE_LINKING_REPEAT_DELAY, + immediately: true + } + } + ) + await linkUnpricedTransactionsWorker(priceLinkingQueue.name) } void main() diff --git a/jobs/workers.ts b/jobs/workers.ts index 25ec1a71..cb576304 100644 --- a/jobs/workers.ts +++ b/jobs/workers.ts @@ -143,6 +143,26 @@ export const syncBlockchainAndPricesWorker = async (queueName: string, onComplet }) } +// Links txs that still have no prices (e.g. a failed per-batch link during sync, +// or a startup sync that was interrupted before finishing). +export const linkUnpricedTransactionsWorker = async (queueName: string): Promise => { + const worker = new Worker( + queueName, + async (job) => { + console.log(`[PRICES] job ${job.id as string}: linking txs without prices...`) + await connectAllTransactionsToPrices() + }, + { + connection: redisBullMQ, + lockDuration: DEFAULT_WORKER_LOCK_DURATION + } + ) + + worker.on('failed', (job, err) => { + console.error(`[PRICES] job ${job?.id as string}: linking txs without prices FAILED — ${err.message}`) + }) +} + export const cleanupClientPaymentsWorker = async (queueName: string): Promise => { const worker = new Worker( queueName, diff --git a/services/chronikService.ts b/services/chronikService.ts index 1f77f7a7..35133118 100644 --- a/services/chronikService.ts +++ b/services/chronikService.ts @@ -16,7 +16,8 @@ import { upsertTransaction, getSimplifiedTransactions, getSimplifiedTrasaction, - connectTransactionsToPricesForAddresses + connectTransactionsToPricesForAddresses, + connectTransactionsListToPrices } from './transactionService' import { CacheSet } from 'redis/index' import { @@ -1107,6 +1108,20 @@ export class ChronikBlockchainClient { `${commitTuples.length}` ) + // Link prices batch by batch instead of only at the end of the sync job, so + // an interrupted sync (restart, deploy) doesn't leave everything unpriced. + // A failure here is not fatal: connectAllTransactionsToPrices retries later. + if (syncResult.inserted.length > 0) { + try { + await connectTransactionsListToPrices( + syncResult.inserted.map(t => ({ ...t, address: { networkId: this.networkId } })), + { skipUnlink: true } + ) + } catch (err: any) { + console.error(`${this.CHRONIK_MSG_PREFIX}: Failed to link prices for ${syncResult.inserted.length} synced txs: ${err.message as string}`) + } + } + const createdForProd = syncResult.inserted.filter(t => productionAddressesIds.includes(t.addressId) ) diff --git a/services/transactionService.ts b/services/transactionService.ts index 90d54865..e6ec3e09 100644 --- a/services/transactionService.ts +++ b/services/transactionService.ts @@ -1,6 +1,6 @@ import prisma from 'prisma-local/clientInstance' import { Prisma, Transaction } from '@prisma/client' -import { RESPONSE_MESSAGES, USD_QUOTE_ID, CAD_QUOTE_ID, N_OF_QUOTES, UPSERT_TRANSACTION_PRICES_ON_DB_TIMEOUT, SupportedQuotesType, NETWORK_IDS, PRICES_CONNECTION_BATCH_SIZE, PRICES_CONNECTION_TIMEOUT, HUMAN_READABLE_DATE_FORMAT } from 'constants/index' +import { RESPONSE_MESSAGES, USD_QUOTE_ID, CAD_QUOTE_ID, N_OF_QUOTES, UPSERT_TRANSACTION_PRICES_ON_DB_TIMEOUT, SupportedQuotesType, NETWORK_IDS, PRICES_CONNECTION_BATCH_SIZE, PRICES_CONNECTION_TIMEOUT, PRICES_CONNECTION_TX_CHUNK_SIZE, UNPRICED_TXS_PAGE_SIZE, SYNC_INSERT_RETRY_DELAY, HUMAN_READABLE_DATE_FORMAT } from 'constants/index' import { fetchAddressBySubstring, fetchAddressById, fetchAddressesByPaybuttonId } from 'services/addressService' import { AllPrices, QuoteValues, fetchAndStoreMissingPrices, fetchPricesForNetworkAndTimestamp, flattenTimestamp } from 'services/priceService' import _ from 'lodash' @@ -447,29 +447,16 @@ export async function upsertTransaction ( } } -function buildPriceTxConnectionInput (tx: Transaction, allPrices: AllPrices): Prisma.PricesOnTransactionsCreateManyInput[] { +function buildPriceTxConnectionInput (tx: Pick, allPrices: AllPrices): Prisma.PricesOnTransactionsCreateManyInput[] { return [ { transactionId: tx.id, priceId: allPrices.usd.id }, { transactionId: tx.id, priceId: allPrices.cad.id } ] } -async function deletePriceTxConnectionsInChunks ( - client: Prisma.TransactionClient, - transactionIds: string[] -): Promise { - let pricesUnlinkedCount = 0 - console.log( - `[PRICES] Disconnecting existing price links for ${transactionIds.length} txs...` - ) - for (let i = 0; i < transactionIds.length; i += PRICES_CONNECTION_BATCH_SIZE) { - const slice = transactionIds.slice(i, i + PRICES_CONNECTION_BATCH_SIZE) - const result = await client.pricesOnTransactions.deleteMany({ - where: { transactionId: { in: slice } } - }) - pricesUnlinkedCount += result.count - } - console.log(`[PRICES] Disconnected ${pricesUnlinkedCount} price links.`) +/** The fields connectTransactionsListToPrices needs from a tx. */ +export type PriceLinkableTransaction = Pick & { + address: { networkId: number } } async function createPriceTxConnectionInChunks ( @@ -532,12 +519,24 @@ async function fetchStoredPricesForNetworkAndTimestamps ( return complete } -export async function connectTransactionsListToPrices ( - txList: TransactionWithNetwork[] -): Promise { - if (txList.length === 0) return +export interface ConnectPricesOptions { + // Set when every tx is known to have no price links yet (e.g. just inserted, + // or selected by `prices: none`), so the per-chunk unlink can be skipped. + skipUnlink?: boolean +} - console.log(`[PRICES] Preparing to connect ${txList.length} txs to prices...`) +/** + * Link each tx to the USD and CAD prices of its day, replacing any existing links. + * Writes in chunks of PRICES_CONNECTION_TX_CHUNK_SIZE txs, each in its own short + * DB transaction: a chunk that fails is logged and skipped (its txs stay unpriced + * for the next run to retry) instead of rolling back the whole list. + * Returns how many txs were linked. + */ +export async function connectTransactionsListToPrices ( + txList: PriceLinkableTransaction[], + { skipUnlink = false }: ConnectPricesOptions = {} +): Promise { + if (txList.length === 0) return 0 // collect UNIQUE (networkId, timestamp) pairs const networkIdToTimestamps = new Map>() @@ -551,11 +550,9 @@ export async function connectTransactionsListToPrices ( // ---- efficient fetch ---- const priceByNetworkTs = new Map() - let pairs = 0 for (const [networkId, timestamps] of networkIdToTimestamps.entries()) { const tsArray = [...timestamps] - pairs += tsArray.length let storedPrices = await fetchStoredPricesForNetworkAndTimestamps(networkId, tsArray) @@ -583,61 +580,106 @@ export async function connectTransactionsListToPrices ( } } - console.log(`[PRICES] Loaded prices for ${pairs} (network,timestamp) pairs.`) - - // Build all join rows (2 per tx: USD + CAD) - const rows: Prisma.PricesOnTransactionsCreateManyInput[] = [] - const txIdsToConnect: string[] = [] + const txsToConnect: Array<{ id: string, rows: Prisma.PricesOnTransactionsCreateManyInput[] }> = [] for (const t of txList) { - const ts = flattenTimestamp(t.timestamp) - const allPrices = priceByNetworkTs.get(`${t.address.networkId}:${ts}`) + const allPrices = priceByNetworkTs.get(`${t.address.networkId}:${flattenTimestamp(t.timestamp)}`) if (allPrices == null) { continue } - rows.push(...buildPriceTxConnectionInput(t, allPrices)) - txIdsToConnect.push(t.id) + txsToConnect.push({ id: t.id, rows: buildPriceTxConnectionInput(t, allPrices) }) } - - if (txIdsToConnect.length < txList.length) { - console.warn(`[PRICES] Skipped ${txList.length - txIdsToConnect.length} txs due to missing price data.`) + const skippedNoPrice = txList.length - txsToConnect.length + + let linked = 0 + let failedChunks = 0 + for (let i = 0; i < txsToConnect.length; i += PRICES_CONNECTION_TX_CHUNK_SIZE) { + const chunk = txsToConnect.slice(i, i + PRICES_CONNECTION_TX_CHUNK_SIZE) + const ids = chunk.map(c => c.id) + const rows = chunk.flatMap(c => c.rows) + try { + await prisma.$transaction( + async (tx) => { + if (!skipUnlink) { + await tx.pricesOnTransactions.deleteMany({ where: { transactionId: { in: ids } } }) + } + await createPriceTxConnectionInChunks(tx, rows) + }, + { timeout: PRICES_CONNECTION_TIMEOUT } + ) + linked += chunk.length + } catch (err: any) { + failedChunks++ + console.error(`[PRICES] Failed to link prices for a chunk of ${chunk.length} txs (first: ${ids[0]}): ${err.message as string}`) + } } - if (txIdsToConnect.length === 0) { - console.warn('[PRICES] No txs to connect after filtering — all had missing prices.') - return + const failedTxs = txsToConnect.length - linked + if (skippedNoPrice > 0 || failedChunks > 0 || txList.length >= PRICES_CONNECTION_TX_CHUNK_SIZE) { + console.log( + `[PRICES] Linked ${linked}/${txList.length} txs to prices` + + (skippedNoPrice > 0 ? `, ${skippedNoPrice} skipped (no price data)` : '') + + (failedChunks > 0 ? `, ${failedTxs} failed in ${failedChunks} chunks` : '') + + '.' + ) } + return linked +} - console.log(`[PRICES] Built ${rows.length} price links (2 per tx).`) +let connectAllTransactionsToPricesRun: Promise | undefined - await prisma.$transaction( - async (tx) => { - await deletePriceTxConnectionsInChunks(tx, txIdsToConnect) - await createPriceTxConnectionInChunks(tx, rows) - }, - { timeout: PRICES_CONNECTION_TIMEOUT } - ) +/** + * Link every tx that has no prices, or an incomplete set, to its day's prices. + * Unpriced txs are paged (UNPRICED_TXS_PAGE_SIZE at a time) rather than loaded + * all at once. Runs from the startup sync job and from a repeating job; a call + * made while a run is in progress in this process waits for that run instead of + * starting another one. + */ +export async function connectAllTransactionsToPrices (): Promise { + if (connectAllTransactionsToPricesRun !== undefined) { + console.log('[PRICES] Linking txs to prices is already running, waiting for it.') + return await connectAllTransactionsToPricesRun + } + connectAllTransactionsToPricesRun = runConnectAllTransactionsToPrices() + try { + await connectAllTransactionsToPricesRun + } finally { + connectAllTransactionsToPricesRun = undefined + } } -export async function connectAllTransactionsToPrices (): Promise { +async function runConnectAllTransactionsToPrices (): Promise { console.log('[PRICES] Started connecting txs to prices.') - const noPricesTxs = await fetchAllTransactionsWithNoPrices() - console.log(`[PRICES] Found ${noPricesTxs.length} txs with no prices.`) + let found = 0 + let linked = 0 + let cursor: string | undefined + while (true) { + const page = await prisma.transaction.findMany({ + where: { + prices: { none: {} }, + ...(cursor !== undefined ? { id: { gt: cursor } } : {}) + }, + orderBy: { id: 'asc' }, + take: UNPRICED_TXS_PAGE_SIZE, + select: { id: true, timestamp: true, address: { select: { networkId: true } } } + }) + if (page.length === 0) break + cursor = page[page.length - 1].id + found += page.length + linked += await connectTransactionsListToPrices(page, { skipUnlink: true }) + console.log(`[PRICES] Txs with no prices: ${linked}/${found} linked so far.`) + } + console.log(`[PRICES] Found ${found} txs with no prices, linked ${linked}.`) + const wrongNumberOfPricesTxs = await fetchAllTransactionsWithIrregularPrices() console.log(`[PRICES] Found ${wrongNumberOfPricesTxs.length} txs with irregular prices.`) - const txs = [ - ...noPricesTxs, - ...wrongNumberOfPricesTxs - ] - console.log('[PRICES] Connecting txs to prices...') - void await connectTransactionsListToPrices(txs) - console.log('[PRICES] Finished connecting txs to prices.') + const relinked = await connectTransactionsListToPrices(wrongNumberOfPricesTxs) + console.log(`[PRICES] Finished connecting txs to prices (${linked} unpriced and ${relinked} irregular txs linked).`) } /** * Link prices for the given addresses' txs that have none (or an incomplete set). - * The bulk sync path (createManyTransactionsForSync) leaves txs unpriced; the - * sync job fixes that globally with connectAllTransactionsToPrices, but on-demand - * syncs (syncAndSubscribeAddresses) must do it for their own addresses. + * Catches txs from an on-demand sync (syncAndSubscribeAddresses) whose per-batch + * price linking failed, without waiting for the repeating linking job. */ export async function connectTransactionsToPricesForAddresses (addressIds: string[]): Promise { if (addressIds.length === 0) return @@ -663,6 +705,24 @@ export async function connectTransactionsToPricesForAddresses (addressIds: strin await connectTransactionsListToPrices([...noPricesTxs, ...irregularTxs]) } +// Prisma's error code for an interactive transaction that expired or was closed. +const PRISMA_TRANSACTION_API_ERROR = 'P2028' + +const isTransactionTimeoutError = (err: unknown): boolean => + err instanceof Prisma.PrismaClientKnownRequestError && err.code === PRISMA_TRANSACTION_API_ERROR + +/** Runs `fn`; if it fails with a transaction timeout, waits and runs it once more. */ +export async function retryOnTransactionTimeout (fn: () => Promise): Promise { + try { + return await fn() + } catch (err) { + if (!isTransactionTimeoutError(err)) throw err + console.warn(`[TRANSACTIONS] DB transaction timed out, retrying once in ${SYNC_INSERT_RETRY_DELAY}ms...`) + await new Promise(resolve => setTimeout(resolve, SYNC_INSERT_RETRY_DELAY)) + return await fn() + } +} + interface ExistingTxSnapshot { confirmed: boolean timestamp: number @@ -845,7 +905,10 @@ async function persistManyTransactionRows ( let updatedCount = 0 if (newTxs.length > 0) { - await prisma.$transaction( + // Retried once if the DB transaction times out (e.g. MySQL briefly stalled + // under load), instead of dropping the whole batch. Safe to repeat: the + // timed-out attempt was rolled back and the inserts skip duplicates. + const createdTxs = await retryOnTransactionTimeout(async () => await prisma.$transaction( async (tx) => { await tx.transaction.createMany({ data: newTxs, @@ -902,14 +965,13 @@ async function persistManyTransactionRows ( }) } - for (const createdTx of createdTxs) { - inserted.push(createdTx) - } + return createdTxs }, { timeout: UPSERT_TRANSACTION_PRICES_ON_DB_TIMEOUT } - ) + )) + inserted.push(...createdTxs) } if (toUpdate.length > 0) { @@ -957,8 +1019,9 @@ async function persistManyTransactionRows ( } /** - * Bulk sync path: persist txs + inputs only. Prices, Redis cache, and paybutton - * graphs are deferred to connectAllTransactionsToPrices after the sync job. + * Bulk sync path: persist txs + inputs only. The caller (commitTransactionsBatch) + * links prices per batch; the Redis cache is invalidated after the sync, and + * connectAllTransactionsToPrices retries any txs left unpriced. */ export async function createManyTransactionsForSync ( transactionsData: Prisma.TransactionUncheckedCreateInput[] @@ -1039,18 +1102,6 @@ export async function markTransactionsOrphaned (hash: string): Promise { }) } -async function fetchAllTransactionsWithNoPrices (): Promise { - const x = await prisma.transaction.findMany({ - where: { - prices: { - none: {} - } - }, - include: includeNetwork - }) - return x -} - export async function fetchAllTransactionsWithIrregularPrices (): Promise { const grouped = await prisma.pricesOnTransactions.groupBy({ by: ['transactionId'], diff --git a/tests/unittests/chronikService.test.ts b/tests/unittests/chronikService.test.ts index 9f43d70e..e6c4aed7 100644 --- a/tests/unittests/chronikService.test.ts +++ b/tests/unittests/chronikService.test.ts @@ -10,7 +10,8 @@ import { } from '../../services/chronikService' import { Address, Prisma } from '@prisma/client' import { fetchAddressesArray } from '../../services/addressService' -import { fetchUnconfirmedTransactions, deleteTransactions, upsertTransaction, connectTransactionsToPricesForAddresses } from '../../services/transactionService' +import { fetchUnconfirmedTransactions, deleteTransactions, upsertTransaction, connectTransactionsToPricesForAddresses, connectTransactionsListToPrices, createManyTransactionsForSync } from '../../services/transactionService' +import prisma from '../../prisma-local/clientInstance' import { executeAddressTriggers } from '../../services/triggerService' import { CacheSet } from '../../redis/index' @@ -73,7 +74,8 @@ jest.mock('../../services/transactionService', () => ({ getSimplifiedTransactions: jest.fn(), getSimplifiedTrasaction: jest.fn(), connectAllTransactionsToPrices: jest.fn(), - connectTransactionsToPricesForAddresses: jest.fn() + connectTransactionsToPricesForAddresses: jest.fn(), + connectTransactionsListToPrices: jest.fn() })) jest.mock('../../redis/index', () => ({ @@ -1708,3 +1710,51 @@ describe('chronik WebSocket reconnection', () => { expect(endpoint.waitForOpen).toHaveBeenCalledTimes(16) }) }) + +describe('commitTransactionsBatch price linking', () => { + const inserted = [{ + id: 'tx-1', + hash: 'hash-1', + addressId: 'addr-1', + amount: new Prisma.Decimal(1), + timestamp: 1700000000, + confirmed: true + }] + const commitTuples = [{ + row: { hash: 'hash-1', addressId: 'addr-1', timestamp: 1700000000, amount: 1 }, + raw: {}, + addressString: 'ecash:addr-1' + }] + + beforeEach(() => { + process.env.WS_AUTH_KEY = 'test-auth-key' + ;(createManyTransactionsForSync as jest.Mock).mockResolvedValueOnce({ insertedCount: 1, inserted }) + jest.spyOn(prisma.address, 'findMany').mockResolvedValue([] as any) + jest.spyOn(console, 'log').mockImplementation(() => {}) + }) + + afterEach(() => { + jest.restoreAllMocks() + }) + + it('links prices for the txs it just inserted, with the client network', async () => { + const link = (connectTransactionsListToPrices as jest.Mock).mockReset().mockResolvedValue(1) + const client = new ChronikBlockchainClient('ecash') + + await (client as any).commitTransactionsBatch(commitTuples, [], false) + + expect(link).toHaveBeenCalledWith( + [{ ...inserted[0], address: { networkId: 1 } }], + { skipUnlink: true } + ) + }) + + it('still commits the batch when price linking fails', async () => { + ;(connectTransactionsListToPrices as jest.Mock).mockReset().mockRejectedValue(new Error('price API down')) + const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {}) + const client = new ChronikBlockchainClient('ecash') + + await expect((client as any).commitTransactionsBatch(commitTuples, [], false)).resolves.toBeUndefined() + expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('price API down')) + }) +}) diff --git a/tests/unittests/transactionService.test.ts b/tests/unittests/transactionService.test.ts index df320dac..c493b2c9 100644 --- a/tests/unittests/transactionService.test.ts +++ b/tests/unittests/transactionService.test.ts @@ -595,3 +595,142 @@ describe('connectTransactionsListToPrices', () => { expect(prismaMock.pricesOnTransactions.createMany).not.toHaveBeenCalled() }) }) + +describe('connectTransactionsListToPrices chunking', () => { + const dayTs = moment.utc('2026-08-02').unix() + const usd = { ...mockedUSDPriceOnTransaction.price, id: 11, timestamp: dayTs, networkId: 1 } + const cad = { ...mockedCADPriceOnTransaction.price, id: 12, timestamp: dayTs, networkId: 1 } + const makeTxs = (n: number): any[] => Array.from({ length: n }, (_, i) => ({ + id: `tx-${i}`, timestamp: dayTs + 60, address: { networkId: 1 } + })) + + beforeEach(() => { + prisma.$transaction = prismaMock.$transaction + prisma.price.findMany = prismaMock.price.findMany + prisma.pricesOnTransactions.deleteMany = prismaMock.pricesOnTransactions.deleteMany + prisma.pricesOnTransactions.createMany = prismaMock.pricesOnTransactions.createMany + prisma.pricesOnTransactions.groupBy = prismaMock.pricesOnTransactions.groupBy + prisma.transaction.findMany = prismaMock.transaction.findMany + prismaMock.price.findMany.mockResolvedValue([usd, cad]) + prismaMock.pricesOnTransactions.deleteMany.mockResolvedValue({ count: 0 }) + prismaMock.pricesOnTransactions.createMany.mockResolvedValue({ count: 0 }) + prismaMock.$transaction.mockImplementation(async (fn: any) => fn(prismaMock)) + }) + + it('writes each chunk of txs in its own DB transaction', async () => { + const linked = await transactionService.connectTransactionsListToPrices(makeTxs(501)) + + expect(linked).toBe(501) + expect(prismaMock.$transaction).toHaveBeenCalledTimes(2) + const createManyCalls = prismaMock.pricesOnTransactions.createMany.mock.calls as any[] + expect(createManyCalls[0][0].data).toHaveLength(1000) + expect(createManyCalls[1][0].data).toHaveLength(2) + }) + + it('keeps linking the remaining chunks when one chunk fails', async () => { + const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {}) + prismaMock.$transaction + .mockRejectedValueOnce(new Error('Transaction already closed')) + .mockImplementation(async (fn: any) => fn(prismaMock)) + + const linked = await transactionService.connectTransactionsListToPrices(makeTxs(501)) + + expect(linked).toBe(1) + expect(prismaMock.$transaction).toHaveBeenCalledTimes(2) + expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('Transaction already closed')) + errorSpy.mockRestore() + }) + + it('only unlinks existing prices when skipUnlink is not set', async () => { + await transactionService.connectTransactionsListToPrices(makeTxs(2), { skipUnlink: true }) + expect(prismaMock.pricesOnTransactions.deleteMany).not.toHaveBeenCalled() + + await transactionService.connectTransactionsListToPrices(makeTxs(2)) + expect(prismaMock.pricesOnTransactions.deleteMany).toHaveBeenCalledWith({ + where: { transactionId: { in: ['tx-0', 'tx-1'] } } + }) + }) +}) + +describe('connectAllTransactionsToPrices', () => { + const dayTs = moment.utc('2026-08-02').unix() + const usd = { ...mockedUSDPriceOnTransaction.price, id: 11, timestamp: dayTs, networkId: 1 } + const cad = { ...mockedCADPriceOnTransaction.price, id: 12, timestamp: dayTs, networkId: 1 } + const page = [ + { id: 'a', timestamp: dayTs + 60, address: { networkId: 1 } }, + { id: 'b', timestamp: dayTs + 120, address: { networkId: 1 } } + ] + + beforeEach(() => { + prisma.$transaction = prismaMock.$transaction + prisma.price.findMany = prismaMock.price.findMany + prisma.pricesOnTransactions.deleteMany = prismaMock.pricesOnTransactions.deleteMany + prisma.pricesOnTransactions.createMany = prismaMock.pricesOnTransactions.createMany + prisma.pricesOnTransactions.groupBy = prismaMock.pricesOnTransactions.groupBy + prisma.transaction.findMany = prismaMock.transaction.findMany + prismaMock.price.findMany.mockResolvedValue([usd, cad]) + prismaMock.pricesOnTransactions.createMany.mockResolvedValue({ count: 0 }) + ;(prismaMock.pricesOnTransactions.groupBy as unknown as jest.Mock).mockResolvedValue([]) + prismaMock.$transaction.mockImplementation(async (fn: any) => fn(prismaMock)) + prismaMock.transaction.findMany + .mockResolvedValueOnce(page as any) + .mockResolvedValue([]) + }) + + it('pages through unpriced txs by id and links them without unlinking', async () => { + await transactionService.connectAllTransactionsToPrices() + + const firstQuery = prismaMock.transaction.findMany.mock.calls[0][0] as any + const secondQuery = prismaMock.transaction.findMany.mock.calls[1][0] as any + expect(firstQuery.where).toEqual({ prices: { none: {} } }) + expect(firstQuery.orderBy).toEqual({ id: 'asc' }) + expect(secondQuery.where).toEqual({ prices: { none: {} }, id: { gt: 'b' } }) + expect(prismaMock.pricesOnTransactions.createMany).toHaveBeenCalledWith({ + data: [ + { transactionId: 'a', priceId: 11 }, { transactionId: 'a', priceId: 12 }, + { transactionId: 'b', priceId: 11 }, { transactionId: 'b', priceId: 12 } + ], + skipDuplicates: true + }) + expect(prismaMock.pricesOnTransactions.deleteMany).not.toHaveBeenCalled() + }) + + it('makes a concurrent call wait for the run in progress instead of starting another', async () => { + await Promise.all([ + transactionService.connectAllTransactionsToPrices(), + transactionService.connectAllTransactionsToPrices() + ]) + + expect(prismaMock.pricesOnTransactions.groupBy).toHaveBeenCalledTimes(1) + }) +}) + +describe('retryOnTransactionTimeout', () => { + let timeoutSpy: jest.SpyInstance + let warnSpy: jest.SpyInstance + + beforeEach(() => { + timeoutSpy = jest.spyOn(global, 'setTimeout').mockImplementation(((fn: () => void) => { fn(); return 0 }) as any) + warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {}) + }) + + afterEach(() => { + timeoutSpy.mockRestore() + warnSpy.mockRestore() + }) + + it('retries once when the DB transaction timed out', async () => { + const timeout = new Prisma.PrismaClientKnownRequestError('Transaction already closed', { code: 'P2028', clientVersion: 'test' }) + const fn = jest.fn().mockRejectedValueOnce(timeout).mockResolvedValueOnce('ok') + + await expect(transactionService.retryOnTransactionTimeout(fn)).resolves.toBe('ok') + expect(fn).toHaveBeenCalledTimes(2) + }) + + it('does not retry other errors', async () => { + const fn = jest.fn().mockRejectedValue(new Error('unique constraint')) + + await expect(transactionService.retryOnTransactionTimeout(fn)).rejects.toThrow('unique constraint') + expect(fn).toHaveBeenCalledTimes(1) + }) +}) From e07107aa7cdea685396611e1c25ac85e67c611b9 Mon Sep 17 00:00:00 2001 From: David Klakurka Date: Wed, 25 Nov 2026 21:01:44 -0700 Subject: [PATCH 2/4] fix: invalidate caches of addresses whose txs get linked to prices Cached payments are built while txs are unpriced and leave them out. When connectAllTransactionsToPrices (startup job or the new repeating job) links those txs, drop the caches of the affected addresses and their users' dashboards so they rebuild with the newly priced payments. Previously only the end of a completed startup sync cleared caches, which on prod never happened. connectTransactionsListToPrices now returns the ids of the txs it linked, so only addresses with actually linked txs are invalidated (not ones whose txs still have no price data, which would otherwise be rebuilt every hour). Co-Authored-By: Claude Opus 5.5 --- services/transactionService.ts | 56 ++++++++++++++-------- tests/unittests/chronikService.test.ts | 2 +- tests/unittests/transactionService.test.ts | 30 ++++++++++-- 3 files changed, 63 insertions(+), 25 deletions(-) diff --git a/services/transactionService.ts b/services/transactionService.ts index e6ec3e09..483c7b3d 100644 --- a/services/transactionService.ts +++ b/services/transactionService.ts @@ -113,12 +113,6 @@ const includeNetwork = { } } -const transactionWithNetwork = Prisma.validator()( - { include: includeNetwork } -) - -type TransactionWithNetwork = Prisma.TransactionGetPayload - const transactionWithAddressAndPrices = Prisma.validator()( { include: includeAddressAndPrices } ) @@ -530,13 +524,13 @@ export interface ConnectPricesOptions { * Writes in chunks of PRICES_CONNECTION_TX_CHUNK_SIZE txs, each in its own short * DB transaction: a chunk that fails is logged and skipped (its txs stay unpriced * for the next run to retry) instead of rolling back the whole list. - * Returns how many txs were linked. + * Returns the ids of the txs that were linked. */ export async function connectTransactionsListToPrices ( txList: PriceLinkableTransaction[], { skipUnlink = false }: ConnectPricesOptions = {} -): Promise { - if (txList.length === 0) return 0 +): Promise { + if (txList.length === 0) return [] // collect UNIQUE (networkId, timestamp) pairs const networkIdToTimestamps = new Map>() @@ -590,7 +584,7 @@ export async function connectTransactionsListToPrices ( } const skippedNoPrice = txList.length - txsToConnect.length - let linked = 0 + const linkedIds: string[] = [] let failedChunks = 0 for (let i = 0; i < txsToConnect.length; i += PRICES_CONNECTION_TX_CHUNK_SIZE) { const chunk = txsToConnect.slice(i, i + PRICES_CONNECTION_TX_CHUNK_SIZE) @@ -606,23 +600,23 @@ export async function connectTransactionsListToPrices ( }, { timeout: PRICES_CONNECTION_TIMEOUT } ) - linked += chunk.length + linkedIds.push(...ids) } catch (err: any) { failedChunks++ console.error(`[PRICES] Failed to link prices for a chunk of ${chunk.length} txs (first: ${ids[0]}): ${err.message as string}`) } } - const failedTxs = txsToConnect.length - linked + const failedTxs = txsToConnect.length - linkedIds.length if (skippedNoPrice > 0 || failedChunks > 0 || txList.length >= PRICES_CONNECTION_TX_CHUNK_SIZE) { console.log( - `[PRICES] Linked ${linked}/${txList.length} txs to prices` + + `[PRICES] Linked ${linkedIds.length}/${txList.length} txs to prices` + (skippedNoPrice > 0 ? `, ${skippedNoPrice} skipped (no price data)` : '') + (failedChunks > 0 ? `, ${failedTxs} failed in ${failedChunks} chunks` : '') + '.' ) } - return linked + return linkedIds } let connectAllTransactionsToPricesRun: Promise | undefined @@ -649,6 +643,16 @@ export async function connectAllTransactionsToPrices (): Promise { async function runConnectAllTransactionsToPrices (): Promise { console.log('[PRICES] Started connecting txs to prices.') + // Addresses whose cached payments were built while these txs were unpriced + // (and so left them out); their caches are dropped once the txs are linked. + const addressesToInvalidate = new Set() + const trackLinked = (txs: Array<{ id: string, address: { address: string } }>, linkedIds: string[]): void => { + const linked = new Set(linkedIds) + for (const t of txs) { + if (linked.has(t.id)) addressesToInvalidate.add(t.address.address) + } + } + let found = 0 let linked = 0 let cursor: string | undefined @@ -660,20 +664,32 @@ async function runConnectAllTransactionsToPrices (): Promise { }, orderBy: { id: 'asc' }, take: UNPRICED_TXS_PAGE_SIZE, - select: { id: true, timestamp: true, address: { select: { networkId: true } } } + select: { id: true, timestamp: true, address: { select: { networkId: true, address: true } } } }) if (page.length === 0) break cursor = page[page.length - 1].id found += page.length - linked += await connectTransactionsListToPrices(page, { skipUnlink: true }) + const linkedIds = await connectTransactionsListToPrices(page, { skipUnlink: true }) + linked += linkedIds.length + trackLinked(page, linkedIds) console.log(`[PRICES] Txs with no prices: ${linked}/${found} linked so far.`) } console.log(`[PRICES] Found ${found} txs with no prices, linked ${linked}.`) const wrongNumberOfPricesTxs = await fetchAllTransactionsWithIrregularPrices() console.log(`[PRICES] Found ${wrongNumberOfPricesTxs.length} txs with irregular prices.`) - const relinked = await connectTransactionsListToPrices(wrongNumberOfPricesTxs) - console.log(`[PRICES] Finished connecting txs to prices (${linked} unpriced and ${relinked} irregular txs linked).`) + const relinkedIds = await connectTransactionsListToPrices(wrongNumberOfPricesTxs) + trackLinked(wrongNumberOfPricesTxs, relinkedIds) + console.log(`[PRICES] Finished connecting txs to prices (${linked} unpriced and ${relinkedIds.length} irregular txs linked).`) + + if (addressesToInvalidate.size > 0) { + try { + await CacheSet.addressesSynced([...addressesToInvalidate]) + console.log(`[PRICES] Invalidated caches for ${addressesToInvalidate.size} addresses with newly priced txs.`) + } catch (err: any) { + console.error(`[PRICES] Failed to invalidate caches after linking prices: ${err.message as string}`) + } + } } /** @@ -1102,7 +1118,7 @@ export async function markTransactionsOrphaned (hash: string): Promise { }) } -export async function fetchAllTransactionsWithIrregularPrices (): Promise { +export async function fetchAllTransactionsWithIrregularPrices (): Promise> { const grouped = await prisma.pricesOnTransactions.groupBy({ by: ['transactionId'], _count: { transactionId: true }, @@ -1113,7 +1129,7 @@ export async function fetchAllTransactionsWithIrregularPrices (): Promise { }) it('links prices for the txs it just inserted, with the client network', async () => { - const link = (connectTransactionsListToPrices as jest.Mock).mockReset().mockResolvedValue(1) + const link = (connectTransactionsListToPrices as jest.Mock).mockReset().mockResolvedValue(['tx-1']) const client = new ChronikBlockchainClient('ecash') await (client as any).commitTransactionsBatch(commitTuples, [], false) diff --git a/tests/unittests/transactionService.test.ts b/tests/unittests/transactionService.test.ts index c493b2c9..f34ea6a1 100644 --- a/tests/unittests/transactionService.test.ts +++ b/tests/unittests/transactionService.test.ts @@ -620,7 +620,7 @@ describe('connectTransactionsListToPrices chunking', () => { it('writes each chunk of txs in its own DB transaction', async () => { const linked = await transactionService.connectTransactionsListToPrices(makeTxs(501)) - expect(linked).toBe(501) + expect(linked).toHaveLength(501) expect(prismaMock.$transaction).toHaveBeenCalledTimes(2) const createManyCalls = prismaMock.pricesOnTransactions.createMany.mock.calls as any[] expect(createManyCalls[0][0].data).toHaveLength(1000) @@ -635,7 +635,7 @@ describe('connectTransactionsListToPrices chunking', () => { const linked = await transactionService.connectTransactionsListToPrices(makeTxs(501)) - expect(linked).toBe(1) + expect(linked).toEqual(['tx-500']) expect(prismaMock.$transaction).toHaveBeenCalledTimes(2) expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('Transaction already closed')) errorSpy.mockRestore() @@ -657,9 +657,10 @@ describe('connectAllTransactionsToPrices', () => { const usd = { ...mockedUSDPriceOnTransaction.price, id: 11, timestamp: dayTs, networkId: 1 } const cad = { ...mockedCADPriceOnTransaction.price, id: 12, timestamp: dayTs, networkId: 1 } const page = [ - { id: 'a', timestamp: dayTs + 60, address: { networkId: 1 } }, - { id: 'b', timestamp: dayTs + 120, address: { networkId: 1 } } + { id: 'a', timestamp: dayTs + 60, address: { networkId: 1, address: 'ecash:addr-a' } }, + { id: 'b', timestamp: dayTs + 120, address: { networkId: 1, address: 'ecash:addr-b' } } ] + let invalidate: jest.SpyInstance beforeEach(() => { prisma.$transaction = prismaMock.$transaction @@ -675,6 +676,11 @@ describe('connectAllTransactionsToPrices', () => { prismaMock.transaction.findMany .mockResolvedValueOnce(page as any) .mockResolvedValue([]) + invalidate = jest.spyOn(CacheSet, 'addressesSynced').mockResolvedValue() + }) + + afterEach(() => { + invalidate.mockRestore() }) it('pages through unpriced txs by id and links them without unlinking', async () => { @@ -695,6 +701,22 @@ describe('connectAllTransactionsToPrices', () => { expect(prismaMock.pricesOnTransactions.deleteMany).not.toHaveBeenCalled() }) + it('invalidates the caches of addresses whose txs got linked', async () => { + await transactionService.connectAllTransactionsToPrices() + + expect(invalidate).toHaveBeenCalledWith(['ecash:addr-a', 'ecash:addr-b']) + }) + + it('does not invalidate caches when no tx could be linked', async () => { + prismaMock.price.findMany.mockResolvedValue([]) + const fetchMissing = jest.spyOn(priceService, 'fetchAndStoreMissingPrices').mockResolvedValue([]) + + await transactionService.connectAllTransactionsToPrices() + + expect(invalidate).not.toHaveBeenCalled() + fetchMissing.mockRestore() + }) + it('makes a concurrent call wait for the run in progress instead of starting another', async () => { await Promise.all([ transactionService.connectAllTransactionsToPrices(), From faa89a042893865bf84f6c57c7cd16e5fd834b38 Mon Sep 17 00:00:00 2001 From: David Klakurka Date: Wed, 25 Nov 2026 21:37:16 -0700 Subject: [PATCH 3/4] fix: don't lose cache invalidations or failed relinks in price linking Review follow-ups for connectAllTransactionsToPrices / connectTransactionsListToPrices: - Invalidate caches in a finally block, so addresses whose txs were linked before a later page query or price fetch failed still get their caches dropped (later runs no longer see those txs as unpriced). - When cache invalidation fails, keep the addresses and retry them on the next run instead of dropping them. Kept in memory: linking only runs in the jobs process, and a failed invalidation usually means Redis is unreachable. - When replacing existing links fails, the rollback keeps the old links, which may be for the wrong day; neither the no-prices nor the irregular-count pass would find those txs again. Record their ids in a Redis set (the failure can happen in the app process) and relink them on the next run, removing them once relinked or deleted. Co-Authored-By: Claude Opus 5.5 --- redis/clientInstance.ts | 20 ++++ services/transactionService.ts | 129 +++++++++++++++------ tests/unittests/transactionService.test.ts | 76 ++++++++++++ 3 files changed, 192 insertions(+), 33 deletions(-) diff --git a/redis/clientInstance.ts b/redis/clientInstance.ts index 148f11e8..64a19bdc 100755 --- a/redis/clientInstance.ts +++ b/redis/clientInstance.ts @@ -3,10 +3,30 @@ import IORedis, { ScanStream } from 'ioredis' import { ScanStreamOptions } from 'ioredis/built/types' class RedisMocked { + private readonly sets = new Map>() + async get (_: string): Promise { return null } + async sadd (key: string, ...members: string[]): Promise { + const set = this.sets.get(key) ?? new Set() + const before = set.size + members.forEach(m => set.add(m)) + this.sets.set(key, set) + return set.size - before + } + + async smembers (key: string): Promise { + return [...(this.sets.get(key) ?? [])] + } + + async srem (key: string, ...members: string[]): Promise { + const set = this.sets.get(key) + if (set === undefined) return 0 + return members.filter(m => set.delete(m)).length + } + async del (key: string, data: any): Promise { } diff --git a/services/transactionService.ts b/services/transactionService.ts index 483c7b3d..83f055f5 100644 --- a/services/transactionService.ts +++ b/services/transactionService.ts @@ -5,6 +5,7 @@ import { fetchAddressBySubstring, fetchAddressById, fetchAddressesByPaybuttonId import { AllPrices, QuoteValues, fetchAndStoreMissingPrices, fetchPricesForNetworkAndTimestamp, flattenTimestamp } from 'services/priceService' import _ from 'lodash' import { CacheSet } from 'redis/index' +import { redis } from 'redis/clientInstance' import { SimplifiedTransaction } from 'ws-service/types' import { OpReturnData, parseAddress } from 'utils/validators' import { generatePaymentFromTxWithInvoices } from 'redis/paymentCache' @@ -448,6 +449,20 @@ function buildPriceTxConnectionInput (tx: Pick, allPrices: Al ] } +// Txs whose link replacement failed. Their old links stay (rolled back) and may +// be for the wrong day, so neither the no-prices nor the irregular-count pass of +// connectAllTransactionsToPrices would find them. Kept in Redis because the +// failure can happen in the app process while the retry runs in the jobs process. +const PRICE_RELINK_PENDING_KEY = 'prices:relinkPending' + +async function recordPendingRelinks (txIds: string[]): Promise { + try { + await redis.sadd(PRICE_RELINK_PENDING_KEY, ...txIds) + } catch (err: any) { + console.error(`[PRICES] Failed to record ${txIds.length} txs for relinking: ${err.message as string}`) + } +} + /** The fields connectTransactionsListToPrices needs from a tx. */ export type PriceLinkableTransaction = Pick & { address: { networkId: number } @@ -604,6 +619,11 @@ export async function connectTransactionsListToPrices ( } catch (err: any) { failedChunks++ console.error(`[PRICES] Failed to link prices for a chunk of ${chunk.length} txs (first: ${ids[0]}): ${err.message as string}`) + // Txs selected as unlinked are found again by the no-prices pass; replaced + // links are not, so record them for connectAllTransactionsToPrices to retry. + if (!skipUnlink) { + await recordPendingRelinks(ids) + } } } @@ -621,6 +641,24 @@ export async function connectTransactionsListToPrices ( let connectAllTransactionsToPricesRun: Promise | undefined +// Addresses with newly priced txs whose cache invalidation hasn't succeeded yet. +// Once linked, those txs aren't found by later runs, so the addresses must not be +// dropped: they're retried on the next run. Kept in memory because this only runs +// in the jobs process and a failed invalidation usually means Redis is unreachable. +const addressesPendingCacheInvalidation = new Set() + +async function flushPendingCacheInvalidations (): Promise { + if (addressesPendingCacheInvalidation.size === 0) return + const addresses = [...addressesPendingCacheInvalidation] + try { + await CacheSet.addressesSynced(addresses) + addresses.forEach(a => addressesPendingCacheInvalidation.delete(a)) + console.log(`[PRICES] Invalidated caches for ${addresses.length} addresses with newly priced txs.`) + } catch (err: any) { + console.error(`[PRICES] Failed to invalidate caches after linking prices, will retry on the next run: ${err.message as string}`) + } +} + /** * Link every tx that has no prices, or an incomplete set, to its day's prices. * Unpriced txs are paged (UNPRICED_TXS_PAGE_SIZE at a time) rather than loaded @@ -645,50 +683,75 @@ async function runConnectAllTransactionsToPrices (): Promise { console.log('[PRICES] Started connecting txs to prices.') // Addresses whose cached payments were built while these txs were unpriced // (and so left them out); their caches are dropped once the txs are linked. - const addressesToInvalidate = new Set() const trackLinked = (txs: Array<{ id: string, address: { address: string } }>, linkedIds: string[]): void => { const linked = new Set(linkedIds) for (const t of txs) { - if (linked.has(t.id)) addressesToInvalidate.add(t.address.address) + if (linked.has(t.id)) addressesPendingCacheInvalidation.add(t.address.address) } } + const priceLinkableSelect = { id: true, timestamp: true, address: { select: { networkId: true, address: true } } } as const - let found = 0 - let linked = 0 - let cursor: string | undefined - while (true) { - const page = await prisma.transaction.findMany({ - where: { - prices: { none: {} }, - ...(cursor !== undefined ? { id: { gt: cursor } } : {}) - }, - orderBy: { id: 'asc' }, - take: UNPRICED_TXS_PAGE_SIZE, - select: { id: true, timestamp: true, address: { select: { networkId: true, address: true } } } - }) - if (page.length === 0) break - cursor = page[page.length - 1].id - found += page.length - const linkedIds = await connectTransactionsListToPrices(page, { skipUnlink: true }) - linked += linkedIds.length - trackLinked(page, linkedIds) - console.log(`[PRICES] Txs with no prices: ${linked}/${found} linked so far.`) - } - console.log(`[PRICES] Found ${found} txs with no prices, linked ${linked}.`) + try { + let found = 0 + let linked = 0 + let cursor: string | undefined + while (true) { + const page = await prisma.transaction.findMany({ + where: { + prices: { none: {} }, + ...(cursor !== undefined ? { id: { gt: cursor } } : {}) + }, + orderBy: { id: 'asc' }, + take: UNPRICED_TXS_PAGE_SIZE, + select: priceLinkableSelect + }) + if (page.length === 0) break + cursor = page[page.length - 1].id + found += page.length + const linkedIds = await connectTransactionsListToPrices(page, { skipUnlink: true }) + linked += linkedIds.length + trackLinked(page, linkedIds) + console.log(`[PRICES] Txs with no prices: ${linked}/${found} linked so far.`) + } + console.log(`[PRICES] Found ${found} txs with no prices, linked ${linked}.`) - const wrongNumberOfPricesTxs = await fetchAllTransactionsWithIrregularPrices() - console.log(`[PRICES] Found ${wrongNumberOfPricesTxs.length} txs with irregular prices.`) - const relinkedIds = await connectTransactionsListToPrices(wrongNumberOfPricesTxs) - trackLinked(wrongNumberOfPricesTxs, relinkedIds) - console.log(`[PRICES] Finished connecting txs to prices (${linked} unpriced and ${relinkedIds.length} irregular txs linked).`) + const wrongNumberOfPricesTxs = await fetchAllTransactionsWithIrregularPrices() + console.log(`[PRICES] Found ${wrongNumberOfPricesTxs.length} txs with irregular prices.`) + const relinkedIds = await connectTransactionsListToPrices(wrongNumberOfPricesTxs) + trackLinked(wrongNumberOfPricesTxs, relinkedIds) - if (addressesToInvalidate.size > 0) { + // Txs whose link replacement failed earlier (possibly in another process). + let pendingRelinked = 0 try { - await CacheSet.addressesSynced([...addressesToInvalidate]) - console.log(`[PRICES] Invalidated caches for ${addressesToInvalidate.size} addresses with newly priced txs.`) + const pendingIds = await redis.smembers(PRICE_RELINK_PENDING_KEY) + if (pendingIds.length > 0) { + const pendingTxs = await prisma.transaction.findMany({ + where: { id: { in: pendingIds } }, + select: priceLinkableSelect + }) + const pendingLinkedIds = await connectTransactionsListToPrices(pendingTxs) + trackLinked(pendingTxs, pendingLinkedIds) + pendingRelinked = pendingLinkedIds.length + // Done: relinked now, or deleted since. Failures stay recorded for the next run. + const existing = new Set(pendingTxs.map(t => t.id)) + const relinked = new Set(pendingLinkedIds) + const done = pendingIds.filter(id => relinked.has(id) || !existing.has(id)) + if (done.length > 0) { + await redis.srem(PRICE_RELINK_PENDING_KEY, ...done) + } + console.log(`[PRICES] Relinked ${pendingRelinked}/${pendingIds.length} txs whose earlier link replacement failed.`) + } } catch (err: any) { - console.error(`[PRICES] Failed to invalidate caches after linking prices: ${err.message as string}`) + console.error(`[PRICES] Failed to relink txs recorded as pending: ${err.message as string}`) } + + console.log( + `[PRICES] Finished connecting txs to prices (${linked} unpriced, ${relinkedIds.length} irregular ` + + `and ${pendingRelinked} pending txs linked).` + ) + } finally { + // Also on failure: txs linked before it must still get their caches dropped. + await flushPendingCacheInvalidations() } } diff --git a/tests/unittests/transactionService.test.ts b/tests/unittests/transactionService.test.ts index f34ea6a1..ab5e136c 100644 --- a/tests/unittests/transactionService.test.ts +++ b/tests/unittests/transactionService.test.ts @@ -9,6 +9,13 @@ import * as addressService from 'services/addressService' import { RESPONSE_MESSAGES } from 'constants/index' import moment from 'moment-timezone' import * as priceService from 'services/priceService' +import { redis } from 'redis/clientInstance' + +const PRICE_RELINK_PENDING_KEY = 'prices:relinkPending' +const clearPendingRelinks = async (): Promise => { + const pending = await redis.smembers(PRICE_RELINK_PENDING_KEY) + if (pending.length > 0) await redis.srem(PRICE_RELINK_PENDING_KEY, ...pending) +} const includePrices = { prices: { @@ -650,6 +657,29 @@ describe('connectTransactionsListToPrices chunking', () => { where: { transactionId: { in: ['tx-0', 'tx-1'] } } }) }) + + it('records txs whose link replacement failed so a later run relinks them', async () => { + await clearPendingRelinks() + const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {}) + prismaMock.$transaction.mockRejectedValue(new Error('Transaction already closed')) + + await transactionService.connectTransactionsListToPrices(makeTxs(2)) + + expect((await redis.smembers(PRICE_RELINK_PENDING_KEY)).sort((a, b) => a.localeCompare(b))).toEqual(['tx-0', 'tx-1']) + await clearPendingRelinks() + errorSpy.mockRestore() + }) + + it('does not record failed txs that had no links (the no-prices pass finds them)', async () => { + await clearPendingRelinks() + const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {}) + prismaMock.$transaction.mockRejectedValue(new Error('Transaction already closed')) + + await transactionService.connectTransactionsListToPrices(makeTxs(2), { skipUnlink: true }) + + expect(await redis.smembers(PRICE_RELINK_PENDING_KEY)).toEqual([]) + errorSpy.mockRestore() + }) }) describe('connectAllTransactionsToPrices', () => { @@ -717,6 +747,52 @@ describe('connectAllTransactionsToPrices', () => { fetchMissing.mockRestore() }) + it('still invalidates addresses linked before a later page query fails', async () => { + prismaMock.transaction.findMany.mockReset() + prismaMock.transaction.findMany + .mockResolvedValueOnce(page as any) + .mockRejectedValueOnce(new Error('db down')) + + await expect(transactionService.connectAllTransactionsToPrices()).rejects.toThrow('db down') + + expect(invalidate).toHaveBeenCalledWith(['ecash:addr-a', 'ecash:addr-b']) + }) + + it('retries a failed cache invalidation on the next run', async () => { + const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {}) + invalidate.mockRejectedValueOnce(new Error('redis down')) + + await transactionService.connectAllTransactionsToPrices() + // Nothing left to link on the second run; the pending addresses are retried. + await transactionService.connectAllTransactionsToPrices() + + expect(invalidate).toHaveBeenCalledTimes(2) + expect(invalidate.mock.calls[1][0]).toEqual(['ecash:addr-a', 'ecash:addr-b']) + errorSpy.mockRestore() + }) + + it('relinks txs recorded as pending and clears them from the pending set', async () => { + await clearPendingRelinks() + await redis.sadd(PRICE_RELINK_PENDING_KEY, 'r1', 'deleted-tx') + const pendingTx = { id: 'r1', timestamp: dayTs + 60, address: { networkId: 1, address: 'ecash:addr-r' } } + prismaMock.pricesOnTransactions.deleteMany.mockResolvedValue({ count: 2 }) + prismaMock.transaction.findMany.mockReset() + prismaMock.transaction.findMany + .mockResolvedValueOnce([]) // no unpriced txs + .mockResolvedValueOnce([]) // no irregular txs + .mockResolvedValueOnce([pendingTx] as any) // pending relinks (deleted-tx no longer exists) + + await transactionService.connectAllTransactionsToPrices() + + expect(prismaMock.pricesOnTransactions.deleteMany).toHaveBeenCalledWith({ where: { transactionId: { in: ['r1'] } } }) + expect(prismaMock.pricesOnTransactions.createMany).toHaveBeenCalledWith({ + data: [{ transactionId: 'r1', priceId: 11 }, { transactionId: 'r1', priceId: 12 }], + skipDuplicates: true + }) + expect(await redis.smembers(PRICE_RELINK_PENDING_KEY)).toEqual([]) + expect(invalidate).toHaveBeenCalledWith(['ecash:addr-r']) + }) + it('makes a concurrent call wait for the run in progress instead of starting another', async () => { await Promise.all([ transactionService.connectAllTransactionsToPrices(), From 9bc157166a6bb6a85db0925db076e9a42d7bcfc9 Mon Sep 17 00:00:00 2001 From: David Klakurka Date: Wed, 25 Nov 2026 21:50:05 -0700 Subject: [PATCH 4/4] fix: invalidate caches per sync batch and only report rows this sync created Review follow-ups: - After a sync batch's new txs are linked to prices, drop the caches of their addresses right away. The bulk path never adds txs to cached payments, and the only other invalidation is at the end of the sync, which an interrupted sync (the prod case) never reaches. Uses a shared invalidateCachesForAddresses that keeps failed addresses queued for retry. - persistManyTransactionRows looked created rows up by (hash, addressId) after a skipDuplicates insert, so when two syncs inserted the same tx concurrently both reported it as inserted (triggers and the seed-file append ran twice). Generate the ids in the app and report only rows that carry them. Co-Authored-By: Claude Opus 5.5 --- services/chronikService.ts | 18 ++++++-- services/transactionService.ts | 28 +++++++++---- tests/unittests/chronikService.test.ts | 25 ++++++++++- tests/unittests/transactionService.test.ts | 49 ++++++++++++++++++++++ 4 files changed, 107 insertions(+), 13 deletions(-) diff --git a/services/chronikService.ts b/services/chronikService.ts index 35133118..fa6223ef 100644 --- a/services/chronikService.ts +++ b/services/chronikService.ts @@ -17,7 +17,8 @@ import { getSimplifiedTransactions, getSimplifiedTrasaction, connectTransactionsToPricesForAddresses, - connectTransactionsListToPrices + connectTransactionsListToPrices, + invalidateCachesForAddresses } from './transactionService' import { CacheSet } from 'redis/index' import { @@ -1113,10 +1114,21 @@ export class ChronikBlockchainClient { // A failure here is not fatal: connectAllTransactionsToPrices retries later. if (syncResult.inserted.length > 0) { try { - await connectTransactionsListToPrices( + const linkedIds = new Set(await connectTransactionsListToPrices( syncResult.inserted.map(t => ({ ...t, address: { networkId: this.networkId } })), { skipUnlink: true } - ) + )) + // The bulk path doesn't add txs to cached payments, so drop the caches of + // addresses whose new txs are now priced instead of waiting for the end of + // the sync, which an interrupted sync never reaches. Txs left unpriced are + // invalidated by connectAllTransactionsToPrices once it links them. + const addressStringById = new Map(commitTuples.map(t => [t.row.addressId, t.addressString])) + const linkedAddresses = [...new Set( + syncResult.inserted.filter(t => linkedIds.has(t.id)).map(t => addressStringById.get(t.addressId)) + )].filter((a): a is string => a !== undefined) + if (linkedAddresses.length > 0) { + await invalidateCachesForAddresses(linkedAddresses) + } } catch (err: any) { console.error(`${this.CHRONIK_MSG_PREFIX}: Failed to link prices for ${syncResult.inserted.length} synced txs: ${err.message as string}`) } diff --git a/services/transactionService.ts b/services/transactionService.ts index 83f055f5..5e5a56f3 100644 --- a/services/transactionService.ts +++ b/services/transactionService.ts @@ -11,6 +11,7 @@ import { OpReturnData, parseAddress } from 'utils/validators' import { generatePaymentFromTxWithInvoices } from 'redis/paymentCache' import { ButtonDisplayData, Payment } from 'redis/types' import moment from 'moment-timezone' +import { v4 as uuidv4 } from 'uuid' export function getTransactionValue (transaction: TransactionWithPrices | TransactionsWithPaybuttonsAndPrices | SimplifiedTransaction): QuoteValues { const ret: QuoteValues = { @@ -647,13 +648,23 @@ let connectAllTransactionsToPricesRun: Promise | undefined // in the jobs process and a failed invalidation usually means Redis is unreachable. const addressesPendingCacheInvalidation = new Set() +/** + * Drop the payment, balance and dashboard caches of these addresses. Addresses + * whose invalidation fails stay queued and are retried by the next call (or the + * next connectAllTransactionsToPrices run in this process). + */ +export async function invalidateCachesForAddresses (addresses: string[]): Promise { + addresses.forEach(a => addressesPendingCacheInvalidation.add(a)) + await flushPendingCacheInvalidations() +} + async function flushPendingCacheInvalidations (): Promise { if (addressesPendingCacheInvalidation.size === 0) return const addresses = [...addressesPendingCacheInvalidation] try { await CacheSet.addressesSynced(addresses) addresses.forEach(a => addressesPendingCacheInvalidation.delete(a)) - console.log(`[PRICES] Invalidated caches for ${addresses.length} addresses with newly priced txs.`) + console.log(`[CACHE] Invalidated caches for ${addresses.length} addresses with newly priced txs.`) } catch (err: any) { console.error(`[PRICES] Failed to invalidate caches after linking prices, will retry on the next run: ${err.message as string}`) } @@ -984,23 +995,24 @@ async function persistManyTransactionRows ( let updatedCount = 0 if (newTxs.length > 0) { + // Ids are generated here so only rows this call created are reported as + // inserted: if a concurrent sync inserted the same (hash, addressId) first, + // skipDuplicates keeps that row (with its own id) and it is left out, so its + // price linking, seed-file append and triggers aren't run twice. + const newTxsWithIds = newTxs.map(row => ({ ...row, id: uuidv4() })) + const newIds = newTxsWithIds.map(row => row.id) // Retried once if the DB transaction times out (e.g. MySQL briefly stalled // under load), instead of dropping the whole batch. Safe to repeat: the // timed-out attempt was rolled back and the inserts skip duplicates. const createdTxs = await retryOnTransactionTimeout(async () => await prisma.$transaction( async (tx) => { await tx.transaction.createMany({ - data: newTxs, + data: newTxsWithIds, skipDuplicates: true }) const createdTxs = await tx.transaction.findMany({ - where: { - OR: newTxs.map(row => ({ - hash: row.hash, - addressId: row.addressId - })) - }, + where: { id: { in: newIds } }, select: syncPersistedTxSelect }) diff --git a/tests/unittests/chronikService.test.ts b/tests/unittests/chronikService.test.ts index 1b6bf12d..ac643180 100644 --- a/tests/unittests/chronikService.test.ts +++ b/tests/unittests/chronikService.test.ts @@ -10,7 +10,7 @@ import { } from '../../services/chronikService' import { Address, Prisma } from '@prisma/client' import { fetchAddressesArray } from '../../services/addressService' -import { fetchUnconfirmedTransactions, deleteTransactions, upsertTransaction, connectTransactionsToPricesForAddresses, connectTransactionsListToPrices, createManyTransactionsForSync } from '../../services/transactionService' +import { fetchUnconfirmedTransactions, deleteTransactions, upsertTransaction, connectTransactionsToPricesForAddresses, connectTransactionsListToPrices, createManyTransactionsForSync, invalidateCachesForAddresses } from '../../services/transactionService' import prisma from '../../prisma-local/clientInstance' import { executeAddressTriggers } from '../../services/triggerService' import { CacheSet } from '../../redis/index' @@ -75,7 +75,8 @@ jest.mock('../../services/transactionService', () => ({ getSimplifiedTrasaction: jest.fn(), connectAllTransactionsToPrices: jest.fn(), connectTransactionsToPricesForAddresses: jest.fn(), - connectTransactionsListToPrices: jest.fn() + connectTransactionsListToPrices: jest.fn(), + invalidateCachesForAddresses: jest.fn() })) jest.mock('../../redis/index', () => ({ @@ -1749,6 +1750,26 @@ describe('commitTransactionsBatch price linking', () => { ) }) + it('invalidates the caches of addresses whose new txs got linked', async () => { + ;(connectTransactionsListToPrices as jest.Mock).mockReset().mockResolvedValue(['tx-1']) + const invalidate = (invalidateCachesForAddresses as jest.Mock).mockReset() + const client = new ChronikBlockchainClient('ecash') + + await (client as any).commitTransactionsBatch(commitTuples, [], false) + + expect(invalidate).toHaveBeenCalledWith(['ecash:addr-1']) + }) + + it('does not invalidate caches when no new tx could be linked', async () => { + ;(connectTransactionsListToPrices as jest.Mock).mockReset().mockResolvedValue([]) + const invalidate = (invalidateCachesForAddresses as jest.Mock).mockReset() + const client = new ChronikBlockchainClient('ecash') + + await (client as any).commitTransactionsBatch(commitTuples, [], false) + + expect(invalidate).not.toHaveBeenCalled() + }) + it('still commits the batch when price linking fails', async () => { ;(connectTransactionsListToPrices as jest.Mock).mockReset().mockRejectedValue(new Error('price API down')) const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {}) diff --git a/tests/unittests/transactionService.test.ts b/tests/unittests/transactionService.test.ts index ab5e136c..fd765d55 100644 --- a/tests/unittests/transactionService.test.ts +++ b/tests/unittests/transactionService.test.ts @@ -832,3 +832,52 @@ describe('retryOnTransactionTimeout', () => { expect(fn).toHaveBeenCalledTimes(1) }) }) + +describe('createManyTransactionsForSync with an overlapping sync', () => { + const row = (hash: string): any => ({ hash, addressId: 'addr-1', amount: new Prisma.Decimal(1), timestamp: 1700000000, confirmed: true }) + + beforeEach(() => { + prisma.$transaction = prismaMock.$transaction + prisma.transaction.findMany = prismaMock.transaction.findMany + prisma.transaction.createMany = prismaMock.transaction.createMany + prismaMock.$transaction.mockImplementation(async (fn: any) => fn(prismaMock)) + prismaMock.transaction.createMany.mockResolvedValue({ count: 1 }) + }) + + it('only reports the rows this call created, identified by the ids it generated', async () => { + prismaMock.transaction.findMany + .mockResolvedValueOnce([]) // neither tx existed when checked + .mockImplementationOnce((async (args: any) => { + // A concurrent sync inserted h2 first, so only our h1 row exists with one of our ids. + const ourIds: string[] = args.where.id.in + return [{ id: ourIds[0], hash: 'h1', addressId: 'addr-1', amount: new Prisma.Decimal(1), timestamp: 1700000000, confirmed: true }] + }) as any) + + const result = await transactionService.createManyTransactionsForSync([row('h1'), row('h2')]) + + const createManyData = (prismaMock.transaction.createMany.mock.calls[0][0] as any).data + expect(createManyData).toHaveLength(2) + expect(createManyData.every((r: any) => typeof r.id === 'string' && r.id.length > 0)).toBe(true) + const lookup = prismaMock.transaction.findMany.mock.calls[1][0] as any + expect(lookup.where).toEqual({ id: { in: createManyData.map((r: any) => r.id) } }) + expect(result.inserted.map(t => t.hash)).toEqual(['h1']) + expect(result.insertedCount).toBe(1) + }) +}) + +describe('invalidateCachesForAddresses', () => { + it('keeps addresses whose invalidation failed and retries them on the next call', async () => { + const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {}) + const invalidate = jest.spyOn(CacheSet, 'addressesSynced') + .mockRejectedValueOnce(new Error('redis down')) + .mockResolvedValue() + + await transactionService.invalidateCachesForAddresses(['ecash:a']) + await transactionService.invalidateCachesForAddresses(['ecash:b']) + + expect(invalidate).toHaveBeenCalledTimes(2) + expect(invalidate.mock.calls[1][0]).toEqual(['ecash:a', 'ecash:b']) + invalidate.mockRestore() + errorSpy.mockRestore() + }) +})