Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .changeset/peering-serialization-retry.md
Original file line number Diff line number Diff line change
@@ -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.
4 changes: 3 additions & 1 deletion docs/PEERING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
39 changes: 38 additions & 1 deletion src/services/payments-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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,
Expand Down Expand Up @@ -302,6 +308,10 @@ export class PaymentsService implements IPaymentsService {
}

public async confirmInvoice(invoice: Invoice): Promise<void> {
await this.withSerializationRetry(() => this.confirmInvoiceOnce(invoice))
}

private async confirmInvoiceOnce(invoice: Invoice): Promise<void> {
logger('confirm invoice %s: %O', invoice.id, invoice)

const transaction = new Transaction(this.dbClient)
Expand Down Expand Up @@ -444,14 +454,41 @@ 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)
}

throw error
}
}

/**
* 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<void>): Promise<void> {
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
Expand Down
20 changes: 20 additions & 0 deletions src/utils/database-errors.ts
Original file line number Diff line number Diff line change
@@ -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<unknown>()
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
}
113 changes: 113 additions & 0 deletions test/unit/services/payments-service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Comment thread
Ferryx349 marked this conversation as resolved.
Resolved

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: [] } },
Expand Down
20 changes: 20 additions & 0 deletions test/unit/utils/database-errors.spec.ts
Original file line number Diff line number Diff line change
@@ -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)
})
})
Loading