From 42ed600f7bad57911ea97a52053a54d48084c96f Mon Sep 17 00:00:00 2001 From: ABHAY PANDEY Date: Fri, 27 Nov 2026 19:37:10 +0530 Subject: [PATCH] fix(peering): retry serialization failures in invoice settlement - detect PostgreSQL SQLSTATE 40001 through wrapped errors\n- retry the whole confirmation transaction up to three times\n- keep deterministic settlement failures and underpayments on the existing path\n- do not count transient serialization conflicts as peering settlement failures\n- add unit coverage and docs --- .changeset/peering-serialization-retry.md | 9 ++ docs/PEERING.md | 4 +- src/services/payments-service.ts | 39 ++++++- src/utils/database-errors.ts | 20 ++++ test/unit/services/payments-service.spec.ts | 113 ++++++++++++++++++++ test/unit/utils/database-errors.spec.ts | 20 ++++ 6 files changed, 203 insertions(+), 2 deletions(-) create mode 100644 .changeset/peering-serialization-retry.md create mode 100644 src/utils/database-errors.ts create mode 100644 test/unit/utils/database-errors.spec.ts diff --git a/.changeset/peering-serialization-retry.md b/.changeset/peering-serialization-retry.md new file mode 100644 index 000000000..d10f6b1ee --- /dev/null +++ b/.changeset/peering-serialization-retry.md @@ -0,0 +1,9 @@ +--- +"nostream": patch +--- + +fix(peering): retry serialization conflicts in invoice settlement + +A serializable peering settlement that loses a concurrent race now retries the +whole confirmation transaction up to three times. Deterministic failures +(missing peer, missing term snapshot) and underpayments are not retried. diff --git a/docs/PEERING.md b/docs/PEERING.md index 977817ea9..6feb580cb 100644 --- a/docs/PEERING.md +++ b/docs/PEERING.md @@ -278,7 +278,9 @@ Only completed invoices that are still unconfirmed are counted; a pending row checked through the processor recheck path stays on the pending page. If the processor later reports a non-completed status for a completed but unconfirmed peering invoice, the worker ignores the downgrade and keeps the completed -marker so settlement remains retryable. +marker so settlement remains retryable. A serialization conflict (SQLSTATE +40001) replays the whole settlement transaction a bounded number of times; +deterministic failures and underpayments are not retried. The worker pages through unconfirmed settlements with an offset cursor. A full page advances the cursor so one repeatedly failing invoice cannot starve later diff --git a/src/services/payments-service.ts b/src/services/payments-service.ts index 6eab6165a..c5304754d 100644 --- a/src/services/payments-service.ts +++ b/src/services/payments-service.ts @@ -24,6 +24,8 @@ import { import { IPaymentsService } from '../@types/services' import { PeeringPaymentStatus } from '../@types/peering' import { Transaction } from '../database/transaction' +import { isSerializationFailure } from '../utils/database-errors' +import { delayMs } from '../utils/misc' import { applyPayment, findSubscriptionPlan } from '../utils/subscription' import { resolveInvoiceExpiry } from '../utils/invoice' import { @@ -37,6 +39,10 @@ const logger = createLogger('payments-service') /** Invoices per maintenance pass. Small because each one is a processor round trip. */ export const PENDING_INVOICE_PAGE_SIZE = 10 +/** A serializable settlement can lose a race; retry the whole transaction a few times. */ +const INVOICE_CONFIRM_SERIALIZATION_ATTEMPTS = 3 +const INVOICE_CONFIRM_SERIALIZATION_DELAY_MS = 10 + export class PaymentsService implements IPaymentsService { public constructor( private readonly dbClient: DatabaseClient, @@ -302,6 +308,10 @@ export class PaymentsService implements IPaymentsService { } public async confirmInvoice(invoice: Invoice): Promise { + await this.withSerializationRetry(() => this.confirmInvoiceOnce(invoice)) + } + + private async confirmInvoiceOnce(invoice: Invoice): Promise { logger('confirm invoice %s: %O', invoice.id, invoice) const transaction = new Transaction(this.dbClient) @@ -444,7 +454,7 @@ export class PaymentsService implements IPaymentsService { logger.error('Unable to confirm invoice. Reason:', error) await transaction.rollback() - if (peeringSettlementStarted && stored) { + if (peeringSettlementStarted && stored && !isSerializationFailure(error)) { await this.recordPeeringSettlementFailure(stored, error) } @@ -452,6 +462,33 @@ export class PaymentsService implements IPaymentsService { } } + /** + * Serialization conflicts are transient: the transaction rolled back, so the + * whole confirmation is safe to replay. Deterministic failures propagate + * immediately and are not retried. + */ + private async withSerializationRetry(operation: () => Promise): Promise { + for (let attempt = 1; attempt <= INVOICE_CONFIRM_SERIALIZATION_ATTEMPTS; attempt += 1) { + try { + await operation() + return + } catch (error) { + if (!isSerializationFailure(error) || attempt === INVOICE_CONFIRM_SERIALIZATION_ATTEMPTS) { + throw error + } + + logger.warn( + 'retrying invoice confirmation after serialization failure (%d/%d)', + attempt, + INVOICE_CONFIRM_SERIALIZATION_ATTEMPTS, + ) + await delayMs(INVOICE_CONFIRM_SERIALIZATION_DELAY_MS * attempt) + } + } + + throw new Error('invoice confirmation retry exhausted') + } + /** * A completed peering invoice can keep failing settlement (missing term * snapshot, missing peer row, a database error). Record every failure outside diff --git a/src/utils/database-errors.ts b/src/utils/database-errors.ts new file mode 100644 index 000000000..4d0f29c31 --- /dev/null +++ b/src/utils/database-errors.ts @@ -0,0 +1,20 @@ +/** + * PostgreSQL aborts the losing transaction with SQLSTATE 40001 when two + * serializable transactions conflict. Knex and pg can wrap the original error, + * so walk the usual `original`/`cause` chain. + */ +export const isSerializationFailure = (error: unknown): boolean => { + const seen = new Set() + let current: unknown = error + + while (current && typeof current === 'object' && !seen.has(current)) { + seen.add(current) + const candidate = current as { code?: unknown; original?: unknown; cause?: unknown } + if (candidate.code === '40001' || candidate.code === 40001) { + return true + } + current = candidate.original ?? candidate.cause + } + + return false +} diff --git a/test/unit/services/payments-service.spec.ts b/test/unit/services/payments-service.spec.ts index 313f2a72c..d357f2176 100644 --- a/test/unit/services/payments-service.spec.ts +++ b/test/unit/services/payments-service.spec.ts @@ -1277,6 +1277,119 @@ describe('PaymentsService', () => { ) }) + it('retries a serialization conflict for a non-peering invoice and succeeds', async () => { + const serializationFailure = Object.assign(new Error('could not serialize access'), { + code: '40001', + }) + settings.returns({ payments: { enabled: true, feeSchedules: { admission: [] } } }) + invoiceRepository.findById.resolves(stubInvoice()) + invoiceRepository.confirmInvoice.onFirstCall().rejects(serializationFailure) + invoiceRepository.confirmInvoice.onSecondCall().resolves() + + await service.confirmInvoice(makeCompletedInvoice()) + + expect(invoiceRepository.confirmInvoice).to.have.been.calledTwice + expect(mockTrx.rollback).to.have.been.calledOnce + expect(mockTrx.commit).to.have.been.calledOnce + }) + + it('stops after the bounded serialization retries', async () => { + const serializationFailure = Object.assign(new Error('could not serialize access'), { + code: '40001', + }) + settings.returns({ payments: { enabled: true, feeSchedules: { admission: [] } } }) + invoiceRepository.findById.resolves(stubInvoice()) + invoiceRepository.confirmInvoice.rejects(serializationFailure) + + await expect(service.confirmInvoice(makeCompletedInvoice())).to.be.rejectedWith( + 'could not serialize access', + ) + + expect(invoiceRepository.confirmInvoice).to.have.been.calledThrice + }) + + it('retries a serialization conflict during peering settlement and commits once', async () => { + const serializationFailure = Object.assign(new Error('could not serialize access'), { + code: '40001', + }) + const transactions: Array<{ commit: Sinon.SinonStub; rollback: Sinon.SinonStub }> = [] + dbClient.transaction.callsFake(async () => { + const trx = { + commit: sandbox.stub().resolves([]), + rollback: sandbox.stub().resolves([]), + } + transactions.push(trx) + return trx + }) + settings.returns({ + payments: { enabled: true, feeSchedules: { admission: [] } }, + peering: { settlementFailureThreshold: 5 }, + }) + invoiceRepository.findById.resolves( + stubInvoice({ + purpose: InvoicePurpose.PEERING, + termAmountMsats: 21000n, + termPeriodSeconds: 2592000, + unit: InvoiceUnit.MSATS, + }), + ) + peeringPaymentRepository.lockByPeer + .onFirstCall() + .rejects(serializationFailure) + .onSecondCall() + .resolves(peeringRow()) + + await peeringService.confirmInvoice(makeCompletedInvoice()) + + expect(transactions).to.have.length(2) + expect(transactions[0].rollback).to.have.been.calledOnce + expect(transactions[1].commit).to.have.been.calledOnce + expect(peeringPaymentRepository.lockByPeer).to.have.been.calledTwice + expect(peeringPaymentRepository.save).to.have.been.calledOnceWith( + Sinon.match({ + status: 'active', + lastSettledInvoiceId: 'invoice-id', + }), + transactions[1], + ) + expect(invoiceRepository.updatePeriod).to.have.been.calledOnceWith( + 'invoice-id', + Sinon.match.instanceOf(Date), + Sinon.match.instanceOf(Date), + transactions[1], + ) + expect(notificationOutboxRepository.enqueue).to.have.been.calledOnceWith( + OperatorNotificationEventType.PEERING_INVOICE_PAID, + Sinon.match({ invoiceId: 'invoice-id' }), + transactions[1], + ) + expect(invoiceRepository.recordPeeringSettlementFailure).not.to.have.been.called + }) + + it('does not count a serialization conflict as a peering settlement failure', async () => { + const serializationFailure = Object.assign(new Error('could not serialize access'), { + code: '40001', + }) + settings.returns({ + payments: { enabled: true, feeSchedules: { admission: [] } }, + peering: { settlementFailureThreshold: 5 }, + }) + invoiceRepository.findById.resolves( + stubInvoice({ + purpose: InvoicePurpose.PEERING, + termAmountMsats: 21000n, + termPeriodSeconds: 2592000, + }), + ) + invoiceRepository.confirmInvoice.rejects(serializationFailure) + + await expect(peeringService.confirmInvoice(makeCompletedInvoice())).to.be.rejectedWith( + 'could not serialize access', + ) + + expect(invoiceRepository.recordPeeringSettlementFailure).not.to.have.been.called + }) + it('counts a confirmation-write failure for an eligible peering invoice', async () => { settings.returns({ payments: { enabled: true, feeSchedules: { admission: [] } }, diff --git a/test/unit/utils/database-errors.spec.ts b/test/unit/utils/database-errors.spec.ts new file mode 100644 index 000000000..c5c52961a --- /dev/null +++ b/test/unit/utils/database-errors.spec.ts @@ -0,0 +1,20 @@ +import { expect } from 'chai' + +import { isSerializationFailure } from '../../../src/utils/database-errors' + +describe('database errors', () => { + it('recognizes PostgreSQL serialization failures', () => { + expect(isSerializationFailure({ code: '40001' })).to.equal(true) + }) + + it('walks wrapped errors', () => { + expect(isSerializationFailure({ original: { code: '40001' } })).to.equal(true) + expect(isSerializationFailure({ cause: { original: { code: '40001' } } })).to.equal(true) + }) + + it('ignores unrelated and malformed errors', () => { + expect(isSerializationFailure(new Error('boom'))).to.equal(false) + expect(isSerializationFailure({ code: '23505' })).to.equal(false) + expect(isSerializationFailure(undefined)).to.equal(false) + }) +})