25 KiB
phase, reviewed, depth, review_kind, files_reviewed, files_reviewed_list, findings, status
| phase | reviewed | depth | review_kind | files_reviewed | files_reviewed_list | findings | status | ||||||||||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 18.1-payment-gateway-subscriptions | 2026-10-16T12:04:37Z | standard | re-review after gap closure (plans 18.1-07, 18.1-08, 18.1-09) | 44 |
|
|
issues_found |
Phase 18.1: Code Review Report (re-review after gap closure)
Reviewed: 2026-10-16T12:04:37Z Depth: standard Files Reviewed: 44 (four repositories; every path carries its repository prefix) Status: issues_found
Summary
This is the re-review after the gap closure. Plans 18.1-07, 18.1-08 and 18.1-09 targeted CR-01, CR-02, WR-01, WR-02, WR-03, WR-04, WR-06 and WR-07 of the first review (2026-10-14). Scope:
- summercms.go: commits after
929cfd8; - pgsub: commits after
472b75b; - pgstripe: commits after
baf3c55; - the layer: commits after
30046f5.
Called code outside the list was read where a finding depends on it: lagoon.Transaction, cabana's toolbar action path, sync_plan.go, conga's default attempts, and the pre-fix subscriptionplans.go and SyncPlan.
Both blockers are closed. The webhook job now retrieves the subscription's state from Stripe outside any transaction. It does this under a per-subscription session advisory lock, and the claim-first marker transaction is unchanged. Checkout no longer falls back to another currency's price.
The lock implementation holds up under tracing:
- Pinned connection. GORM's
Connectionkeeps the*sql.Conn. TheNewDBsession keeps theConnPool, andlagoon.Transactionbegins its transaction on that same connection. - Unlock and discard. The unlock runs with
context.WithoutCancel. A failed lock or unlock marks the connection bad throughConn.Rawreturningdriver.ErrBadConn, so database/sql closes it and the server releases the lock. - Framework change. The cabana
Detachedbranch keeps the list scope, the empty and partial-selection rules and the permission check. The new field isjson:"-"and opt-in, so existing consumers (theusersbulk actions in the apps) compile and behave as before. - Layer. The bfcache restore works in all three components, and the listener is removed on unmount.
No new blocker was found. The seven warnings are:
- Residual gaps in fixed findings (WR-01, WR-04, WR-06).
Service.Cancelstill writes a gateway-owned column without the subscription lock, so the spuriousreactivatedof CR-01 sequence 3 is still reachable through a race. The open-subscription guard cannot see unpaid Checkout Sessions. Checkout bills the last-synced amount, not the amount shown. - New behaviour introduced by the fixes (WR-02, WR-03, WR-05, WR-07):
- fresh-state retrieval can fire
SubscriptionCanceledtwice; - the detached plan sync dropped the row lock that serialised concurrent syncs of one plan;
- the strict price map makes plans in gbp, cad, aud or chf impossible to buy once they are synced;
- treating
incompleteas open locks a user out of checkout for up to about 23 hours.
- fresh-state retrieval can fire
Resolution of the first review's findings
| Finding | Status | Evidence |
|---|---|---|
| CR-01 stale webhook snapshots | Resolved (one residual race, WR-01 below) | sm-pgstripe-plugin/subscriptions/job.go:206-244 retrieves fresh state under classes.WithSessionLock. apply.go:191-195 retries an unknown deletion. Sequences 1 to 3 are covered by TestFreshStateSmoke and TestEventOrdering. Service.Cancel does not take the lock (WR-01). |
| CR-02 cross-currency checkout | Resolved for currency (amount residual, WR-06; side effect, WR-05) | models/subscription_plan.go:129-144 CheckoutPriceID has no fallback. The API answers 422 at api/subscription.go:128-131, and the gateway refuses with ErrNoPriceForCurrency at gateway.go:199-202. The yen is dropped from supportedCurrencies (gateway.go:44). |
| WR-01 Stripe calls inside the bulk transaction | Resolved (regression, WR-03) | controllers/subscriptionplans.go:55 sets Detached: true. The branch is at crud.go:370-373, 412-435. SyncPlan(ctx, nil, plan) saves with context.WithoutCancel (service.go:597-605), and a failed save becomes a failure line. |
| WR-02 duplicate Stripe customers | Resolved | user_subscribable.go writes the first value only and re-reads the stored one. gateway.go:163-164 sets an idempotency key on the customer create. ensureCustomer stores through WithoutCancel (service.go:631). |
| WR-03 already-subscribed guard | Partially resolved (WR-04 and WR-07 below) | ScopeOpen (models/subscription.go:114-121), CheckoutGuarded under SubscriberLockKey (service.go:319-344), and a checkout idempotency key (gateway.go:245-246). Unpaid open sessions are still not seen. |
| WR-04 subscriptions on archived prices | Resolved | apply.go:327-339 resolves the plan by price, then product, then plan code. decode.go carries product_id/plan_code. |
| WR-05 grace period from the advanced period end | Open (deferred) | models/subscription.go:149, unchanged and kept PHP-identical by user decision (deferred-items.md). Not counted again below. |
| WR-06 SyncSubscription lost update | Resolved | service.go:418-488: under the lock, FOR UPDATE re-read, Select of the gateway-owned columns, plan refreshed on the retriever path. |
| WR-07 buttons stuck after Back | Resolved | subscribe.ts:57-64, 66-71, 138, 195. All three components wire watchPageRestore in onMounted and remove it in onBeforeUnmount. MySubscription also refreshes its data. |
| IN-01 to IN-08 | Open (deferred) | deferred-items.md. Not counted again below. |
Narrative Findings (AI reviewer)
Warnings
WR-01: Service.Cancel writes cancel_at_period_end without the subscription lock, so a racing webhook job still fires a spurious SubscriptionReactivated (CR-01 sequence 3 residual)
Files:
sm-paymentgatewaysubscriptions-plugin/classes/service.go:373-395sm-pgstripe-plugin/subscriptions/job.go:219-243sm-paymentgatewaysubscriptions-plugin/classes/apply.go:143sm-paymentgatewaysubscriptions-plugin/classes/lock.go:25-28
Issue: The lock's documented rule is "every writer of the gateway state of that subscription takes it", and plan 07 made that the established pattern. Service.Cancel (used by POST /subscription/cancel) calls Stripe and then runs UPDATE ... SET cancel_at_period_end = true without SubscriptionLockKey. One interleaving reproduces the original sequence 3:
- A webhook job for an unrelated
customer.subscription.updatedtakes the lock and retrieves the subscription from Stripe (cancel_at_period_end: false). - The user cancels. Stripe sets the flag, and the local UPDATE commits
true. - The job opens its transaction.
Applyreads the rowFOR UPDATEwithpreviousCancel = true, writesfalseand firesSubscriptionReactivated(apply.go:143).
Stripe's own update event later restores true, but the listeners have already received a reactivation the user never asked for. Until then the row shows no scheduled cancellation. The window is the time between the job's Stripe response and its SELECT ... FOR UPDATE. It is short, but nothing closes it.
Fix: Take the subscription lock around the gateway call and the local write:
func (s *Service) Cancel(ctx context.Context, sub *models.Subscription, atPeriodEnd bool) error {
...
if sub.StripeSubscriptionID == nil || *sub.StripeSubscriptionID == "" { /* existing gateway refusal */ }
return WithSessionLock(ctx, s.db, SubscriptionLockKey(*sub.StripeSubscriptionID), func(conn *gorm.DB) error {
if err := gw.CancelSubscription(ctx, sub, atPeriodEnd); err != nil { ... }
if !atPeriodEnd { return nil }
return conn.WithContext(ctx).Model(&models.Subscription{}).Where("id = ?", sub.ID).
Update("cancel_at_period_end", true).Error
})
}
Add a TestEventOrdering case that blocks the fake's retrieve, runs Cancel and then releases the retrieve.
WR-02: With fresh-state retrieval, SubscriptionCanceled fires twice when a created/updated job runs after Stripe canceled the subscription but before its deletion job
Files:
sm-pgstripe-plugin/subscriptions/job.go:221-241sm-paymentgatewaysubscriptions-plugin/classes/apply.go:161-165, 208-211sm-pgstripe-plugin/subscriptions/ordering_test.go:115-152,fresh_state_smoke_test.go:130-170
Issue: A created or updated job now applies Stripe's current status. If Stripe already canceled the subscription, that status is canceled. fireStateChangeEvents sees a change to canceled and fires SubscriptionCanceled. The deletion job then runs ApplyDeleted, which fires SubscriptionCanceled unconditionally (apply.go:208-211, the PHP rule). Two sequences lead there:
- CR-01 sequence 2, the case plan 07 targeted: the deletion is retried with
ErrSubscriptionNotStored, the late created event storescanceledand fires once, and the retried deletion fires again. - An immediate cancel while an update job is queued, retrying, or simply wins the lock first.
Under PHP's snapshot semantics a created or updated snapshot practically never carried canceled, so the unconditional fire was harmless. The fresh path changes that. Both ordering tests assert activated == 0 but never count canceled, so the double fire passes the gate. Listeners such as a "your subscription ended" mail or an access revocation that writes an audit row run twice.
Fix: In ApplyDeleted, fire only on a transition (previous := sub.StripeStatus before the write; fire when previous != models.StatusCanceled). Record it as a deviation next to the D-21 amendment. Then add rec.Count(events.SubscriptionCanceledEventName) == 1 to both deleted_before_created subtests.
WR-03: The detached plan sync lost the row lock that serialised concurrent syncs of one plan; parallel syncs create duplicate Stripe products and prices
Files:
sm-paymentgatewaysubscriptions-plugin/controllers/subscriptionplans.go:48-57, 86-101, 162-176sm-paymentgatewaysubscriptions-plugin/classes/service.go:584-611summercms.go/modules/cabana/crud.go:412-435sm-pgstripe-plugin/subscriptions/sync_plan.go:92-117(called)
Issue: Before plan 08, sync_to_stripe ran inside cabana's transaction with the selected plans locked FOR UPDATE, so two admins, or two tabs, syncing the same plan were serialised. The detached branch loads the plans without locks (loadScoped(..., false)), and SyncPlan takes no lock of its own. Two concurrent syncs of a plan with no stripe_product_id each call V1Products.Create, which carries no idempotency key. Each then lists the prices by lookup key, finds none, and creates its own. The last Updates wins, and the other product and its prices stay active and orphaned in Stripe. This is the duplicate-product outcome WR-01 set out to prevent.
The toolbar sync_all_to_stripe never locked. It has no confirm dialog (subscriptionplans.go:59-63), so a double click starts two full syncs.
Fix: Serialise per plan with the existing helper, and sync from a fresh copy of the row:
func (s *Service) SyncPlan(ctx context.Context, tx *gorm.DB, plan *models.SubscriptionPlan) (map[string]string, error) {
...
if tx == nil {
var out map[string]string
err := WithSessionLock(ctx, s.db, lockKeyPrefix+"plan:"+strconv.FormatUint(uint64(plan.ID), 10), func(conn *gorm.DB) error {
if err := conn.WithContext(ctx).First(plan, plan.ID).Error; err != nil { return err } // fresh stripe ids
var err error
out, err = s.syncPlanLocked(ctx, conn, plan)
return err
})
return out, err
}
...
}
Also give V1Products.Create an idempotency key over the plan id, code and name, in the same window as the customer key.
WR-04: The open-subscription guard cannot see unpaid Checkout Sessions, so a subscriber can still complete two Checkouts and be billed twice (WR-03 partially resolved)
Files:
sm-paymentgatewaysubscriptions-plugin/classes/service.go:319-344sm-pgstripe-plugin/subscriptions/gateway.go:245-246sm-paymentgatewaysubscriptions-plugin/checkout_guard_test.go("two checkouts of one subscriber never overlap and share one customer")
Issue: CheckoutGuarded refuses only when a stored row is open. A Checkout Session creates no row until the customer pays and the webhook is applied. The subscriber lock serialises the two requests but does not make the second one fail: the test named above asserts that both checkouts succeed. The Stripe idempotency key returns the same session only when every parameter matches within the same 10-minute window. So these still produce two open sessions for one customer:
- two tabs with different plans or currencies;
- the same plan more than 10 minutes apart (sessions stay valid for 24 h);
- a second click in the gap between payment and webhook processing.
Completing both produces two live Stripe subscriptions, both billing. That is the outcome WR-03 described.
Fix: Before creating a new session for a customer, expire that customer's open subscription-mode sessions inside the subscriber lock (Stripe: list Checkout Sessions with customer and status=open, then Expire). Optionally, when Apply stores a new subscription for a subscriber who already has another open row, log at Error or fire a dedicated event so the duplicate is caught.
WR-05: Once synced, plans priced in gbp, cad, aud or chf can no longer be bought, although /plans lists them and SupportsCurrency accepts them
Files:
sm-paymentgatewaysubscriptions-plugin/models/subscription_plan.go:129-144sm-pgstripe-plugin/subscriptions/sync_plan.go:15, 55-69(called)sm-pgstripe-plugin/subscriptions/gateway.go:44sm-paymentgatewaysubscriptions-plugin/api/subscription.go:121-131
Issue: CheckoutPriceID lets a non-empty stripe_prices map decide alone. Plan sync fills that map only for usd, eur and pln, and it overwrites stripe_price_id with the USD price. A plan with currency: GBP therefore:
- sells correctly while it carries a hand-entered GBP
stripe_price_id; - after an admin presses "Sync to Stripe" (reported as successful), loses its GBP price id and gets a map without
gbp; - answers 422 "unavailable" to every checkout from then on, while
/plansstill shows29.99 GBPwith a Subscribe button.
The same happens to any currency_prices key outside the three sync currencies. This is no longer a wrong charge, but the strict map combined with the unchanged fixed sync list makes a supported currency unsellable without any visible error.
Fix: Sync every currency the plan prices that the gateway supports, instead of the fixed list:
currencies := []string{strings.ToLower(plan.Currency)}
for code := range plan.CurrencyPrices.Data { currencies = append(currencies, strings.ToLower(code)) }
// dedupe, keep only g.SupportsCurrency(code), then upsertPrice for each
At least report the currencies the plan lists but has no price for as a sync failure line. Alternatively, have /plans mark a price unbuyable when CheckoutPriceID is empty.
WR-06: Checkout bills the amount of the last sync, not the price the API shows; an edit of price_cents or currency_prices without a re-sync charges the old amount (CR-02 amount residual)
Files:
sm-paymentgatewaysubscriptions-plugin/models/subscription_plan.go:129-144sm-paymentgatewaysubscriptions-plugin/api/json.go:113-126sm-paymentgatewaysubscriptions-plugin/api/subscription.go:121-131
Issue: /plans renders currency_prices/price_cents from the row (planPrices). The checkout gate (priced) checks the same local amounts. The Stripe price comes from the stripe_prices id, whose unit_amount was fixed at the last sync. Nothing ties the two together: there is no save hook on the plan form, and CheckoutPriceID never compares amounts. An admin who raises a plan from 29.99 to 39.99 and forgets to press Sync leaves customers who are shown 39.99 being billed 29.99, and the reverse after a price cut. CR-02 was "charge a different currency or amount than the user was shown". The currency half is fixed; the amount half is not.
Fix: One of:
- Store the synced amount per currency next to the id (for example
stripe_pricesvalues as{id, amount}, or a parallelstripe_price_amountsmap). HaveCheckoutPriceIDreturn "" whenPriceCentsFor(currency)differs, which gives a 422 and an admin log line naming the plan. - In the gateway,
V1Prices.Retrieve(priceID)before the session and refuse withErrNoPriceForCurrencywhenUnitAmount != plan.PriceCentsFor(currency),Currencydiffers orActiveis false. - Clear
stripe_prices/stripe_price_idin aFormBeforeUpdatewhen a price field changes.
WR-07: Treating incomplete as open locks a user out of checkout for up to about 23 hours after an abandoned or failed first payment
Files:
sm-paymentgatewaysubscriptions-plugin/models/subscription.go:114-121sm-paymentgatewaysubscriptions-plugin/api/subscription.go:92-98sm-paymentgatewaysubscriptions-plugin/classes/service.go:325-332
Issue: ScopeOpen excludes only canceled and incomplete_expired. A subscription whose first invoice failed, or which needs 3-D Secure the customer abandoned, is stored as incomplete from the customer.subscription.created event. Stripe expires it after about 23 h. Until then every checkout answers 409, and the layer offers only the billing portal (SubscribeButton.vue:56). The portal is not a reliable way to finish the first payment of an incomplete subscription, so a customer with a declined card cannot retry with another card the same day. The other statuses that block (past_due, unpaid, paused) have an invoice the portal can settle; incomplete is the exception.
Fix: Leave incomplete out of the checkout guard. Stripe expires it, and an incomplete subscription never charges again on its own. If double billing through a later-completed incomplete subscription is a concern, have the guarded checkout cancel the subscriber's incomplete subscriptions at Stripe, inside the lock, before it creates the new session.
Info
IN-01: The ErrSubscriptionNotStored retry lasts only conga's 3 attempts; a deletion of a subscription that is never stored ends as a discarded job with error logs
Files:
sm-paymentgatewaysubscriptions-plugin/classes/apply.go:191-195summercms.go/modules/conga/client.go:18-19(called)
Issue: River retries the deletion 3 times with backoff, roughly 20 s in total. CR-01 sequence 2 is actually closed by the fresh retrieval of the late created event, not by this retry. A subscription that never gets a row (pre-cutover PHP subscriptions, or the untagged events of another application, IN-02 of the first review) now produces three Error lines and a discarded River job per deletion, where it used to leave a marker.
Fix: On the last attempt (river.JobFromContext(ctx).Attempt >= MaxAttempts), claim the marker and log at Warn instead of failing. Alternatively, document that the discarded jobs are expected.
IN-02: The session lock holds a pooled connection while it waits, and its holder needs a second one; with a capped pool or a re-entrant listener this stalls until the job timeout
Files:
sm-paymentgatewaysubscriptions-plugin/classes/lock.go:63-88sm-pgstripe-plugin/subscriptions/gateway.go:114-128sm-paymentgatewaysubscriptions-plugin/classes/service.go:325-339
Issue: Each waiter keeps a pinned connection blocked in pg_advisory_lock. The holder needs another connection: LoadSettings in client(), and in CheckoutGuarded the Open, Subscriber and ensureCustomer calls on s.db.
- Capped pool. With
MaxOpenConnsat or below the number of concurrent jobs for one subscription, the holder starves until River's job timeout. Each timeout uses one of only 3 attempts, so an event can be discarded. - Re-entrant listener. An event listener that calls
Service.SyncSubscriptionfor the same subscription waits on a lock its own job holds. That also lasts until the context deadline.
lagoon sets no cap today, so the default deployment is unaffected (plan 07 noted this).
Fix: Document the pool requirement (at least 2 x workers). Consider SET lock_timeout on the pinned connection before the lock call, or pg_try_advisory_lock with a River snooze. Note in the events doc that listeners must not call SyncSubscription or Cancel for the subscription they are handling.
IN-03: A plan changed between the handler's price check and the gateway call answers 502 instead of 422
File: sm-paymentgatewaysubscriptions-plugin/api/subscription.go:128-131, 141-148
Issue: ErrNoPriceForCurrency from the gateway (for example, the plan was re-synced without that currency in between) goes through writeGatewayError and becomes 502 "provider". It is logged without the error.
Fix: Map errors.Is(err, ErrNoPriceForCurrency) to the same 422 currency validation answer. That needs a gateway-neutral sentinel in contracts, because pgsub must not import pgstripe.
IN-04: The component wiring spec asserts source text, not behaviour
File: vue-paymentgateway-layer/tests/subscriptionComponents.test.ts:423-440
Issue: The test "the three components wire watchPageRestore on mount and remove it on unmount" matches regexes against the .vue sources. A refactor that keeps the strings but breaks the wiring, for example by registering on a different target, still passes. A correct rewrite, such as a composable usePageRestore(flow), fails.
Fix: Mount each component with @vue/test-utils (or the Nuxt test utils) and dispatch a pageshow with persisted: true on window. Assert that the button is enabled again and that removeEventListener runs on unmount.
IN-05: /plans still shows yen amounts divided by 100
File: sm-paymentgatewaysubscriptions-plugin/api/json.go:122, 126
Issue: Dropping jpy from supportedCurrencies stops yen checkouts, but a plan whose currency is JPY, or whose currency_prices include jpy, is still listed through money.FromMinor as one hundredth of its price (¥5 for 500). This was the second half of CR-02's yen note.
Fix: Leave out of planPrices any currency the stripe gateway does not support, or refuse jpy in the plan form's validation.
Reviewed: 2026-10-16T12:04:37Z Reviewer: Claude (msd-code-reviewer) Depth: standard