diff --git a/.changeset/peering-lifecycle-sweep-cursor.md b/.changeset/peering-lifecycle-sweep-cursor.md new file mode 100644 index 000000000..3c914a1ac --- /dev/null +++ b/.changeset/peering-lifecycle-sweep-cursor.md @@ -0,0 +1,5 @@ +--- +"nostream": patch +--- + +The peering lifecycle sweep now resumes after the last row it read instead of counting the rows it could not handle. A renewed peer keeps its `period_end` and only gains a `renewal_invoice_id`, so it stayed in the query that found it: the old offset never moved past it, each page re-read the same ten rows, and every peer behind them was never sent a renewal and was later lapsed. diff --git a/src/@types/repositories.ts b/src/@types/repositories.ts index 9b51a808d..b1834cbd9 100644 --- a/src/@types/repositories.ts +++ b/src/@types/repositories.ts @@ -95,6 +95,15 @@ export interface IInvoiceRepository { claimPeeringSettlementAlert(id: string, threshold: number, client?: DatabaseClient): Promise } +/** + * The last row a page of peering payments ended on. Pages are ordered by + * `(period_end, peer_pubkey)` and the next one starts strictly after this. + */ +export interface PeeringPaymentCursor { + periodEnd: Date + peerPubkey: Pubkey +} + export interface IPeeringPaymentRepository { findByPeer(pubkey: Pubkey, client?: DatabaseClient): Promise /** Inserts an unpaid row when one does not exist, so the following lock always finds it. */ @@ -105,10 +114,16 @@ export interface IPeeringPaymentRepository { /** Updates only the processor-check diagnostics, so a concurrent settlement is not overwritten. */ recordCheck(pubkey: Pubkey, checkedAt: Date, error: string | null, client?: DatabaseClient): Promise list(): Promise - /** Active or renewal-pending relationships whose period ends by `before`. */ - findDueForRenewal(before: Date, limit: number, offset: number): Promise - /** Active or renewal-pending relationships whose period has ended by `now`. */ - findPeriodEnded(now: Date, limit: number, offset: number): Promise + /** + * Active or renewal-pending relationships whose period ends by `before`, ordered by + * `(period_end, peer_pubkey)`. Pass the last row of a page as `after` to continue. + */ + findDueForRenewal(before: Date, limit: number, after?: PeeringPaymentCursor): Promise + /** + * Active or renewal-pending relationships whose period has ended by `now`, ordered by + * `(period_end, peer_pubkey)`. Pass the last row of a page as `after` to continue. + */ + findPeriodEnded(now: Date, limit: number, after?: PeeringPaymentCursor): Promise } export interface IPeeringAttestationRepository { diff --git a/src/repositories/peering-payment-repository.ts b/src/repositories/peering-payment-repository.ts index 95d136b1f..8c161910e 100644 --- a/src/repositories/peering-payment-repository.ts +++ b/src/repositories/peering-payment-repository.ts @@ -1,6 +1,6 @@ import { DatabaseClient, Pubkey } from '../@types/base' import { DBPeeringPayment, PeeringPayment, PeeringPaymentDirection, PeeringPaymentStatus } from '../@types/peering' -import { IPeeringPaymentRepository } from '../@types/repositories' +import { IPeeringPaymentRepository, PeeringPaymentCursor } from '../@types/repositories' import { createLogger } from '../factories/logger-factory' import { fromDBPeeringPayment, toBuffer } from '../utils/transform' @@ -108,31 +108,62 @@ export class PeeringPaymentRepository implements IPeeringPaymentRepository { return rows.map(fromDBPeeringPayment) } - public async findDueForRenewal(before: Date, limit: number, offset: number): Promise { - const rows = await this.dbClient('peering_payments') - .where('direction', PeeringPaymentDirection.SELL) - .whereIn('status', [PeeringPaymentStatus.ACTIVE, PeeringPaymentStatus.RENEWAL_PENDING]) - .whereNotNull('period_end') - .where('period_end', '<=', before) - .orderBy('period_end', 'asc') - .offset(offset) - .limit(limit) + public async findDueForRenewal( + before: Date, + limit: number, + after?: PeeringPaymentCursor, + ): Promise { + const rows = await this.pageEndingBy(this.dbClient, before, limit, after) return rows.map(fromDBPeeringPayment) } - public async findPeriodEnded(now: Date, limit: number, offset: number): Promise { - const rows = await this.dbClient('peering_payments') + public async findPeriodEnded( + now: Date, + limit: number, + after?: PeeringPaymentCursor, + ): Promise { + const rows = await this.pageEndingBy(this.dbClient, now, limit, after) + + logger('found %d peering period end(s)', rows.length) + + return rows.map(fromDBPeeringPayment) + } + + /** + * One page of relationships whose period ends by `before`, ordered by + * `(period_end, peer_pubkey)`. The ordering is part of the contract: the sweep resumes + * after the last row of the page, so it must be total and stable even when rows leave + * the result set between pages. + */ + private async pageEndingBy( + client: DatabaseClient, + before: Date, + limit: number, + after?: PeeringPaymentCursor, + ): Promise { + const query = client('peering_payments') .where('direction', PeeringPaymentDirection.SELL) .whereIn('status', [PeeringPaymentStatus.ACTIVE, PeeringPaymentStatus.RENEWAL_PENDING]) .whereNotNull('period_end') - .where('period_end', '<=', now) + .where('period_end', '<=', before) .orderBy('period_end', 'asc') - .offset(offset) + .orderBy('peer_pubkey', 'asc') .limit(limit) - logger('found %d peering period end(s)', rows.length) + if (after) { + const cursorPubkey = toBuffer(after.peerPubkey) + query.where((builder) => + builder + .where('period_end', '>', after.periodEnd) + .orWhere((samePeriod) => + samePeriod + .where('period_end', '=', after.periodEnd) + .andWhere('peer_pubkey', '>', cursorPubkey), + ), + ) + } - return rows.map(fromDBPeeringPayment) + return query } } diff --git a/src/services/peering-billing-service.ts b/src/services/peering-billing-service.ts index 52036ad57..c6e267d0f 100644 --- a/src/services/peering-billing-service.ts +++ b/src/services/peering-billing-service.ts @@ -2,7 +2,12 @@ import { DatabaseClient, Pubkey } from '../@types/base' import { Invoice, InvoicePurpose, InvoiceStatus } from '../@types/invoice' import { OperatorNotificationEventType } from '../@types/operator-notifications' import { PeeringAccess, PeeringPayment, PeeringPaymentStatus, PeeringTermSnapshot } from '../@types/peering' -import { IInvoiceRepository, INotificationOutboxRepository, IPeeringPaymentRepository } from '../@types/repositories' +import { + IInvoiceRepository, + INotificationOutboxRepository, + IPeeringPaymentRepository, + PeeringPaymentCursor, +} from '../@types/repositories' import { IPaymentsService, IPeeringBillingService } from '../@types/services' import { Settings } from '../@types/settings' import { Transaction } from '../database/transaction' @@ -27,7 +32,10 @@ const isExpiredAt = (invoice: Invoice, now: Date): boolean => invoice.expiresAt instanceof Date && invoice.expiresAt.getTime() <= now.getTime() export class PeeringBillingService implements IPeeringBillingService { - private readonly cursors = { renewal: 0, ended: 0 } + private readonly cursors: Record<'renewal' | 'ended', PeeringPaymentCursor | undefined> = { + renewal: undefined, + ended: undefined, + } public constructor( private readonly dbClient: DatabaseClient, @@ -339,7 +347,7 @@ export class PeeringBillingService implements IPeeringBillingService { return this.sweep( 'ended', - (limit, offset) => this.peeringPaymentRepository.findPeriodEnded(now, limit, offset), + (limit, after) => this.peeringPaymentRepository.findPeriodEnded(now, limit, after), (payment) => this.handlePeriodEnded(payment.peerPubkey, now), ) } @@ -363,11 +371,11 @@ export class PeeringBillingService implements IPeeringBillingService { const renewalChanged = await this.sweep( 'renewal', - (limit, offset) => + (limit, after) => this.peeringPaymentRepository.findDueForRenewal( new Date(now.getTime() + PEERING_RENEWAL_LEAD_SECONDS * 1000), limit, - offset, + after, ), async (payment) => { // The ended-period sweep owns already-ended rows; issuing a renewal for one @@ -487,40 +495,50 @@ export class PeeringBillingService implements IPeeringBillingService { await this.enqueueFailed(invoice, 'expired') } + /** + * Runs one lifecycle pass in pages of `SWEEP_PAGE_SIZE`, resuming after the last row it + * read rather than after the rows it could not handle. + * + * A handled renewal keeps its `period_end` and only gains a `renewal_invoice_id`, so it + * stays in the query that found it. Counting skipped rows as an offset therefore never + * moved past it: a pass re-read the same first page and every peer behind it was starved. + * The cursor is `(period_end, peer_pubkey)` — the query's own ordering — so a row that + * stays behind cannot hold the rest of the list back, and a row that leaves the result + * set cannot make the next page miss one. + */ private async sweep( name: 'renewal' | 'ended', - find: (limit: number, offset: number) => Promise, + find: (limit: number, after?: PeeringPaymentCursor) => Promise, handle: (payment: PeeringPayment) => Promise, ): Promise { let changed = 0 - let skipped = this.cursors[name] - let reachedEnd = false + let cursor = this.cursors[name] for (let page = 0; page < SWEEP_MAX_PAGES; page++) { - const payments = await find(SWEEP_PAGE_SIZE, skipped) + const payments = await find(SWEEP_PAGE_SIZE, cursor) for (const payment of payments) { - let handled = false try { - handled = await handle(payment) + if (await handle(payment)) { + changed++ + } } catch (error) { logger.error('unable to process peering lifecycle for %s: %o', payment.peerPubkey, error) } - - if (handled) { - changed++ - } else { - skipped++ - } } - if (payments.length < SWEEP_PAGE_SIZE) { - reachedEnd = true + const last = payments[payments.length - 1] + // Continue strictly after the last row read, whatever its handler returned. + cursor = last?.periodEnd ? { periodEnd: last.periodEnd, peerPubkey: last.peerPubkey } : undefined + + if (payments.length < SWEEP_PAGE_SIZE || cursor === undefined) { + // A short page is the end of the list: the next pass starts from the front again. + cursor = undefined break } } - this.cursors[name] = reachedEnd ? 0 : skipped + this.cursors[name] = cursor return changed } diff --git a/test/integration/features/peering/paid-peering-ledger.feature b/test/integration/features/peering/paid-peering-ledger.feature index e8fe87825..eeac6a1dc 100644 --- a/test/integration/features/peering/paid-peering-ledger.feature +++ b/test/integration/features/peering/paid-peering-ledger.feature @@ -19,6 +19,10 @@ Feature: Paid peering billing ledger When the peer pays a 21000 msat peering invoice Then the lifecycle offers a renewal without moving the paid period + Scenario: A renewal backlog larger than one page renews every peer + When a peering renewal backlog of 12 peers is due + Then the lifecycle renews every peer in the backlog + Scenario: A reconnect during a running period does not buy another period When the peer pays a 21000 msat peering invoice Then requesting an invoice during the running period creates nothing diff --git a/test/integration/features/peering/paid-peering-ledger.feature.ts b/test/integration/features/peering/paid-peering-ledger.feature.ts index 7d21beed3..daaa18e8f 100644 --- a/test/integration/features/peering/paid-peering-ledger.feature.ts +++ b/test/integration/features/peering/paid-peering-ledger.feature.ts @@ -167,6 +167,7 @@ Before({ tags: '@paid-peering-ledger' }, function (this: World 0) { - await db('peering_payments') - .whereIn( - 'peer_pubkey', - peers.map((peer) => Buffer.from(peer, 'hex')), - ) - .delete() + const peerPubkeys = peers.map((peer) => Buffer.from(peer, 'hex')) + // Collect the invoices from the rows before deleting them: a failed assertion in a + // scenario must not leave the invoices it minted behind in the test database. + const billed = await db('peering_payments') + .whereIn('peer_pubkey', peerPubkeys) + .select('current_invoice_id', 'renewal_invoice_id') + + for (const row of billed) { + for (const invoiceId of [row.current_invoice_id, row.renewal_invoice_id]) { + if (typeof invoiceId === 'string' && !invoices.includes(invoiceId)) { + invoices.push(invoiceId) + } + } + } + + await db('peering_payments').whereIn('peer_pubkey', peerPubkeys).delete() } if (db && invoices.length > 0) { await db('invoices').whereIn('id', invoices).delete() @@ -237,6 +248,7 @@ After({ tags: '@paid-peering-ledger' }, async function (this: World payment.peerPubkey === peer)).to.equal(true) const before = new Date(Date.now() + 2 * seconds * 1000) - const due = await repository.findDueForRenewal(before, 10, 0) + const due = await repository.findDueForRenewal(before, 10) expect(due.some((payment) => payment.peerPubkey === peer)).to.equal(true) - const ended = await repository.findPeriodEnded(before, 10, 0) + const ended = await repository.findPeriodEnded(before, 10) expect(ended.some((payment) => payment.peerPubkey === peer)).to.equal(true) }, ) @@ -347,6 +359,68 @@ Then( }, ) +When( + 'a peering renewal backlog of {int} peers is due', + async function (this: World>, count: number) { + const db = this.parameters.peeringDb + const now = new Date() + const peers = Array.from({ length: count }, () => randomPeer()) + + for (const peer of peers) { + this.parameters.peeringPeerPubkeys.push(peer) + this.parameters.peeringUserPubkeys.push(peer) + } + + await db('users') + .insert(peers.map((peer) => ({ pubkey: Buffer.from(peer, 'hex') }))) + .onConflict('pubkey') + .ignore() + await db('peering_payments').insert( + peers.map((peer) => ({ + peer_pubkey: Buffer.from(peer, 'hex'), + direction: 'sell', + status: 'active', + period_start: new Date(now.getTime() - TERM_SECONDS * 1000), + // Running, but inside the renewal lead: the ended-period sweep must not own it. + period_end: new Date(now.getTime() + 60_000), + term_amount_msats: TERM_MSATS.toString(), + term_period_seconds: TERM_SECONDS, + created_at: now, + updated_at: now, + })), + ) + + this.parameters.peeringBacklogPeers = peers + }, +) + +Then( + 'the lifecycle renews every peer in the backlog', + async function (this: World>) { + const billing = this.parameters.peeringBillingService as PeeringBillingService + const db = this.parameters.peeringDb + const peers: string[] = this.parameters.peeringBacklogPeers ?? [] + + // One pass reads at most SWEEP_PAGE_SIZE rows per page; the backlog is larger than one page. + const changed = await billing.processLifecycle(new Date()) + expect(changed).to.be.greaterThanOrEqual(peers.length) + + for (const peer of peers) { + const row = await peerRow(this, peer) + expect(row.status, `peer ${peer} was not renewed`).to.equal('renewal_pending') + expect(row.renewal_invoice_id, `peer ${peer} has no renewal invoice`).to.be.a('string') + } + + const renewed = await db('peering_payments') + .whereIn( + 'peer_pubkey', + peers.map((peer) => Buffer.from(peer, 'hex')), + ) + .where('status', 'renewal_pending') + expect(renewed).to.have.length(peers.length) + }, +) + Then( 'requesting an invoice during the running period creates nothing', async function (this: World>) { diff --git a/test/unit/repositories/peering-payment-repository.spec.ts b/test/unit/repositories/peering-payment-repository.spec.ts index 20f5b311a..43197b892 100644 --- a/test/unit/repositories/peering-payment-repository.spec.ts +++ b/test/unit/repositories/peering-payment-repository.spec.ts @@ -119,12 +119,39 @@ describe('PeeringPaymentRepository', () => { const repository = new PeeringPaymentRepository(recording.db) recording.respondWith([row], [row]) - await repository.findDueForRenewal(now, 10, 0) - await repository.findPeriodEnded(now, 10, 0) + await repository.findDueForRenewal(now, 10) + await repository.findPeriodEnded(now, 10) expect(recording.queries[0].sql).to.include('"status" in') expect(recording.queries[0].sql).to.include('"period_end" <=') expect(recording.queries[1].sql).to.include('"status" in') expect(recording.queries[1].sql).to.include('"period_end" <=') }) + + it('orders pages by period end and peer pubkey so a cursor is total', async () => { + const recording = createRecordingKnex() + const repository = new PeeringPaymentRepository(recording.db) + recording.respondWith([row], [row]) + + await repository.findDueForRenewal(now, 10) + await repository.findPeriodEnded(now, 10) + + for (const query of recording.queries) { + expect(query.sql).to.include('order by "period_end" asc, "peer_pubkey" asc') + } + }) + + it('resumes strictly after the cursor instead of counting rows', async () => { + const recording = createRecordingKnex() + const repository = new PeeringPaymentRepository(recording.db) + recording.respondWith([row]) + + await repository.findDueForRenewal(now, 10, { periodEnd: now, peerPubkey: pubkey }) + + const sql = recording.queries[0].sql + expect(sql).to.include('"period_end" >') + expect(sql).to.include('"period_end" =') + expect(sql).to.include('"peer_pubkey" >') + expect(sql).to.not.include('offset') + }) }) diff --git a/test/unit/services/peering-billing-service.spec.ts b/test/unit/services/peering-billing-service.spec.ts index 1f44d6548..ef4f63cc0 100644 --- a/test/unit/services/peering-billing-service.spec.ts +++ b/test/unit/services/peering-billing-service.spec.ts @@ -721,5 +721,123 @@ describe('PeeringBillingService', () => { expect(await service.processLifecycle(now)).to.equal(3) }) + + it('renews every due peer instead of re-reading the first page', async () => { + const peerAt = (index: number): string => index.toString(16).padStart(2, '0').repeat(32) + // Due inside the renewal lead but not yet ended: the ended sweep owns expired rows. + const periodEnd = new Date(now.getTime() + 86_400_000) + const due = Array.from({ length: 25 }, (_, index) => + payment({ + peerPubkey: peerAt(index), + status: PeeringPaymentStatus.ACTIVE, + periodEnd, + }), + ) + + // Mirrors the repository: ordered by (period_end, peer_pubkey), resumed after the cursor. + paymentRepository.findDueForRenewal.callsFake( + async ( + _before: Date, + limit: number, + after?: { periodEnd: Date; peerPubkey: string }, + ) => { + const sorted = [...due].sort( + (left, right) => + (left.periodEnd as Date).getTime() - (right.periodEnd as Date).getTime() || + left.peerPubkey.localeCompare(right.peerPubkey), + ) + const start = after + ? sorted.findIndex( + (row) => + (row.periodEnd as Date).getTime() > after.periodEnd.getTime() || + ((row.periodEnd as Date).getTime() === after.periodEnd.getTime() && + row.peerPubkey > after.peerPubkey), + ) + : 0 + const from = start === -1 ? sorted.length : start + + return sorted.slice(from, from + limit) + }, + ) + paymentRepository.findPeriodEnded.resolves([]) + const renewed: string[] = [] + sandbox.stub(service, 'ensureInvoice').callsFake(async (peerPubkey: string) => { + renewed.push(peerPubkey) + + return invoice() + }) + + const changed = await service.processLifecycle(now) + + expect(renewed).to.have.length(25) + expect(new Set(renewed).size).to.equal(25) + expect(changed).to.equal(25) + // The second page starts behind the tenth row, not at the same offset again. + expect(paymentRepository.findDueForRenewal.secondCall.args[2]).to.deep.include({ + peerPubkey: peerAt(9), + }) + }) + + it('stops after an empty page instead of re-reading it', async () => { + paymentRepository.findDueForRenewal.resolves([]) + paymentRepository.findPeriodEnded.resolves([]) + sandbox.stub(service, 'processLapses').resolves(0) + + expect(await service.processLifecycle(now)).to.equal(0) + expect(paymentRepository.findDueForRenewal).to.have.been.calledOnce + }) + + it('carries the cursor into the next pass when a pass runs out of pages', async () => { + const peerAt = (index: number): string => index.toString(16).padStart(4, '0').repeat(16) + const periodEnd = new Date(now.getTime() + 86_400_000) + const due = Array.from({ length: 150 }, (_, index) => + payment({ + peerPubkey: peerAt(index), + status: PeeringPaymentStatus.ACTIVE, + periodEnd, + }), + ) + + paymentRepository.findDueForRenewal.callsFake( + async ( + _before: Date, + limit: number, + after?: { periodEnd: Date; peerPubkey: string }, + ) => { + const sorted = [...due].sort( + (left, right) => + (left.periodEnd as Date).getTime() - (right.periodEnd as Date).getTime() || + left.peerPubkey.localeCompare(right.peerPubkey), + ) + const start = after + ? sorted.findIndex( + (row) => + (row.periodEnd as Date).getTime() > after.periodEnd.getTime() || + ((row.periodEnd as Date).getTime() === after.periodEnd.getTime() && + row.peerPubkey > after.peerPubkey), + ) + : 0 + const from = start === -1 ? sorted.length : start + + return sorted.slice(from, from + limit) + }, + ) + paymentRepository.findPeriodEnded.resolves([]) + const renewed: string[] = [] + sandbox.stub(service, 'ensureInvoice').callsFake(async (peerPubkey: string) => { + renewed.push(peerPubkey) + + return invoice() + }) + + // One pass is capped at SWEEP_PAGE_SIZE * SWEEP_MAX_PAGES rows. + await service.processLifecycle(now) + expect(renewed).to.have.length(100) + + // The next pass continues behind the last row the first one read. + await service.processLifecycle(now) + expect(renewed).to.have.length(150) + expect(new Set(renewed).size).to.equal(150) + }) }) })