Skip to content

Return the pending invoice for a repeated renew request - #449

Open
douglaz wants to merge 1 commit into
LNVPS:masterfrom
douglaz:renew-pending-invoice
Open

douglaz wants to merge 1 commit into
LNVPS:masterfrom
douglaz:renew-pending-invoice

Conversation

@douglaz

@douglaz douglaz commented Nov 28, 2026

Copy link
Copy Markdown

Problem

A client asks for a Lightning invoice or an on-chain address to pay a subscription, either the first purchase of a new VM or a renewal. The client may repeat the request: a retry after a lost reply, a second click, a second tab. For a first purchase each repeat got another unpaid invoice for the same terms, because the existing lookup for a pending payment only considered renewal rows. For a VM renewal that lookup already returned a pending renewal, but it and the creation of a new invoice were separate steps, so two overlapping requests could each create one.

What this changes

For an interactive Lightning or on-chain request without a discount code, the handler now takes a per-subscription database lock around the lookup and the creation. Under the lock it returns an unpaid, unexpired payment of the same subscription when all of these match:

  • payment method and payment type (first purchase or renewal);
  • period (time_value, which must be non-zero, so only subscriptions with a VM can match);
  • amount, tax, processing fee and currency;
  • renewal source Manual;
  • no discount redemption and no account credit debit attached to the payment.

Otherwise it runs the existing creation path, still under the lock. A second overlapping request on any API process sharing the database waits for the lock, prices the request again and gets the first one's row back if that row still matches on all of the terms above and is still unpaid and unexpired; otherwise it follows the existing renewal path, which prices the request again and can still return a pending renewal from the existing lookup. A request after that invoice was paid or expired creates a new one, as before. If a pending renewal is already found by the pricing engine's existing renewal lookup, it is returned as before, without the lock.

The lock is a MySQL named lock (GET_LOCK) taken on its own connection outside the pool and held while the payment row is created. It is released when that connection closes, including when the process dies. The locked section runs in a spawned task, so a client that disconnects does not cancel it halfway. The in-process database used by the existing unit tests holds no lock.

Scope

Affected routes: GET /api/v1/vm/{id}/renew and GET /api/v1/subscriptions/{id}/renew, which both reach renew_subscription_with_discount. No request or response field changes; an in-scope repeat gets back the payment object of the invoice already issued. The "Renew/Extend VM" and "Renew Subscription" sections of API_DOCUMENTATION.md describe the behaviour.

These take the existing path unchanged:

  • saved-method and automatic collection, card checkouts, swaps, the Gateway payment method and any other method (an otherwise eligible on-chain request whose address comes from a configured payment gateway is in scope);
  • requests with a discount code;
  • requests whose quote uses account credit;
  • Lightning requests on an account with an enabled saved wallet, because its invoices may be in collection;
  • renewals started by the workers, the DVM handler, the payment gateway and the provisioner, which do not go through this entry point.

Compatibility and database

No migration and no API shape change. Each in-scope request opens one extra database connection, outside the pool, for as long as it holds or waits for the lock. A request that cannot get the lock within 30 seconds fails and creates nothing. The client sees the generic internal error (HTTP 500, "An internal error occurred"); the specific reason, that another payment request for the subscription is in progress, is only logged.

Testing

  • One new database test, overlapping_invoice_requests_share_one_pending_invoice, runs two independent pools against one MariaDB 12.3.3 database as two API processes would, with the existing mock Lightning node. It checks that overlapping requests give one pending row and the same invoice with one node call, that a sequential repeat returns it, that a request after expiry gets one new invoice, and that saved-method requests do not wait on the lock or receive the interactive invoice.

  • On the base commit with only this test added, it fails: the overlap created two pending payments. With the change it passes (1 passed, 0 failed). The rest of the test suite was not run for this change.

  • Like the other database tests, the test runs when LNVPS_TEST_DATABASE_URL is set and returns early, passing, when it is not. It creates its own uniquely named schema on the server in that URL, so the account needs to be able to create and drop databases; it migrates and seeds that schema and drops it at the end, also when a check fails. To run it, set the variable to a MariaDB database URL and run the lnvps_api library tests filtered to pending_renewal::overlapping_invoice_requests_share_one_pending_invoice, with --test-threads=1. With the variable unset it returned early and passed.

  • A signed HTTP run against two API processes sharing one migrated MariaDB, on loopback with stand-in Lightning and on-chain backends. Overlapping Lightning requests shared one payment row and one invoice. A sequential repeat and a restart kept it, and expiry allowed exactly one replacement. Overlapping on-chain requests shared one address, a repeat kept it, and expiry allowed one new address. A saved-method request and a request with an unknown discount code created nothing and gave the same replies as the base build. The same run against the base build created two pending rows and two invoices for the overlap.

  • This change also runs on a private instance. The records available when this text was written do not show a repeated invoice request there, so no result from that instance is claimed.

  • The branch was then rebased onto the current master without conflicts and compile-checked (the lnvps_api library, binaries and tests). The tests were not run again after the rebase.

Known limits

A repeat can still get a second unpaid invoice

These are limits of the new matcher, which runs only when the existing renewal lookup finds nothing. In these cases a repeat misses the pending invoice and the existing creation path runs, as before this change.

  • Exchange-rate refresh. Amounts are compared after conversion. Rates refresh every minute, while Lightning invoices live 600 s and on-chain addresses 3600 s, so a repeat after a refresh misses whenever the refresh changed the converted amount, tax or fee. A rate-independent term (the list price or the interval count) is not stored on the payment; storing it needs a migration.
  • Subscriptions without a VM. App-only and IP-range-only subscriptions price with time_value 0, which does not identify the period, so they never match.
  • Calendar periods. When the period starts now, as on a first purchase, a monthly or yearly plan's time_value is measured in calendar time from now. A repeat on the other side of some UTC midnights (month ends) gets a different time_value and misses. Storing the interval count would fix this and the two cases above.
  • Saved wallet. On an account with an enabled saved wallet, interactive Lightning requests are not protected.

Requests outside the scope (swaps, cards, the Gateway payment method, saved-method requests, requests with a discount code and requests that use account credit) keep their existing behaviour, whatever that is for the method.

Other edge cases

  • Saved wallet disabled. If a saved wallet is disabled while an invoice submitted through it is still pending, that invoice can be returned to an interactive repeat. It is the same invoice, so it settles once. The payment does not record how it is collected, so this case and the one above cannot be told apart from current data.
  • Credit-funded payment in flight. A request that uses account credit (outside the lock) inserts its payment and then attaches the credit debit. In that window a repeat priced without credit and with no processing fee can match the row and get the credit-funded payment back. It is the same payment, not a second charge.
  • Unknown method. An unparseable method is resolved to interactive Lightning before this code sees it, so such a request now reuses a pending Lightning invoice. It already got a Lightning invoice before this change.
  • Existing renewal lookup. The pricing engine's renewal lookup, which this change does not alter and which runs first, matches a pending renewal by method, type and time_value only. A request without a discount code can therefore still get a pending renewal created with a discount code or with credit, as it can today.

Cost and coverage

  • Cost under the lock. The lookup loads all payments of the subscription and filters them in code while holding the lock, and a miss prices the request more than once. The gateway or node call also runs under the lock, so a slow call delays a repeat and can push it past the 30-second wait.
  • Connections. There is no process-wide bound on lock connections: many in-scope requests across many subscriptions open one server connection each, limited by the account rate limits where they apply and by the server's max_connections. The subscription renew route has no account rate limit.
  • Test coverage. The database test covers a Lightning first purchase only. On-chain overlap, a renewal of an active subscription, a subscription without a VM, a credit-funded request and the early return of an existing pending renewal are not covered by a database test; on-chain overlap, repeat and expiry were covered by the HTTP run above.

Two overlapping deliveries of the same Lightning or on-chain renew
request could each create a pending payment: the pending lookup and
the invoice creation were separate steps, and the lookup only
considered renewal rows.

An interactive Lightning or on-chain request without a discount code
now takes a per-subscription database lock (a named lock on its own
connection, released when the connection closes) around the lookup
and the creation. Under the lock the request is priced again, and an
unpaid, unexpired payment of the same subscription from an earlier
manual request, with the same method, payment type, period, currency
and amounts and with no credit or discount attached, is returned
instead of creating another. The first purchase is included. Requests
after that invoice was paid or expired create a new one as before.

Saved-method, card, swap, gateway and discounted requests, requests
that use account credit, and Lightning requests on an account with an
enabled saved wallet take the existing path unchanged. No migration.

The renew sections of the API documentation describe the behaviour,
and a database test covers the overlap.
@douglaz
douglaz marked this pull request as ready for review November 28, 2026 23:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant