Skip to content

feat(billing): enforce recurring trial policy and safe workspace cancellation - #37

Merged
SirNarsh merged 4 commits into
mainfrom
feature/subscription-trial-policy
Nov 3, 2026
Merged

SirNarsh merged 4 commits into
mainfrom
feature/subscription-trial-policy

Conversation

@SirNarsh

@SirNarsh SirNarsh commented Oct 18, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Enforce opt-in single-subscription/trial-once policies with short atomic checkout reservations, without holding database connections during Stripe I/O.
  • Save secret-free provider forms for stable-key recovery; distinguish definitive failures from unknown outcomes. Never infer non-purchase from elapsed time alone.
  • Add scoped user cancellation and machine workspace cancellation with durable partial-failure recovery. Success permits later resubscription; independent manual grants remain intact.
  • Keep archival separate: subscriptions and unsettled Checkout must be reconciled/cancelled first, including completed Checkout awaiting its subscription webhook.
  • Add audited control-only confirmation that an old unresolved Checkout was never created, following explicit provider investigation.
  • Return typed subject billing summaries/provider identifiers and stable past-due observations; align TypeScript, Go, PHP and Python machine clients.
  • Expose immutable-price checkout configuration and selectable, persistent credential notices, including current invitation URLs.

Compatibility

  • Complete previous implementation rebased onto v0.7.1. Released migrations 00001-00010 are unchanged; new migrations are 00011 checkout recovery/cancellation and 00012 subscription observations.
  • Earlier unreleased revisions of this branch require recreated development databases.
  • Preserve current Stripe ignore/retry handling and atomic receipt normalizers; signed event timestamps drive subscription observations.
  • Cancellation is not permanent billing closure. It blocks Checkout only while pending and requires Idempotency-Key for machine batches.
  • Stable-key replay stops at 23 hours; older unknowns require customer-scoped reconciliation or privileged attestation after 25 hours. No automatic clearing based on age or empty lists.

Verification

  • Fresh Claude rebase review and final delta review found no substantive blockers; these are static reviews, not test execution.
  • Full local PostgreSQL Go race suite, SDK tests, lint and static admin build pass. Focused browser tests cover persistent client secrets, invitation URLs and immutable price configuration.
  • PostgreSQL regressions cover concurrent checkout, recovery, cancellation/resubscription, manual grants, policy eligibility, archival boundaries, provider expiration, grace/stale observations, schema-10 upgrade and summary contracts.
  • Additional signed HTTP regression covers receipt rollback/retry and stale subscription events with a one-connection pool.
  • Route/contract/terminology checks pass for 509 operations. Exact-head CI must finish before merge.
  • Patch available chi, fast-uri and zod advisories; full-history Gitleaks passes with an exact verified public-schema value/path exception.
  • Provider calls are mocked; no live purchase or external account activation is claimed.

No release, deployment, purchase, credential rotation or real-account changes are included.

@claude

claude Bot commented Oct 18, 2026

Copy link
Copy Markdown

Code review

No issues found. Checked for bugs and CLAUDE.md compliance.

@SirNarsh

Copy link
Copy Markdown
Member Author

@copilot Please review the latest billing changes, focusing on workspace isolation, direct-API trial eligibility/concurrent checkout, cancellation recovery, and the past-due grace timestamp. Do not change code or merge.

@SirNarsh

Copy link
Copy Markdown
Member Author

@claude Please independently review the current billing PR for concrete correctness/security issues and fit with existing product semantics. Read-only review; do not edit, merge, release or deploy. Trace actual request paths and PostgreSQL behavior: recurring checkout serialization and retries, opt-in price policies, completed versus abandoned trials, webhook delay/replay, scheduled/immediate cancellation and preservation of manual grants, workspace archival versus permanent billing closure, billing-summary contracts and grace timestamps. Check migration numbering against current main (v0.5.0 now owns migration 00008), and tests that actually reproduce claimed behavior. Identify substantive defects with source references; avoid speculative redesign. Also inspect durable one-time credential notices and checkout-policy UI. All examples and discussion must remain generic.

@claude

claude Bot commented Oct 18, 2026 •

Copy link
Copy Markdown

Claude finished @SirNarsh's task in 1m 13s —— View job


Review of the recurring checkout and cancellation PR

I read the code and traced the request paths. I did not run the Go tests or the PostgreSQL-backed tests. A shallow checkout meant origin/main...HEAD had no merge base, so I compared against the origin/main tree instead.

Findings, most severe first

  1. The branch is not rebased on current main.

    • Diffing against origin/main shows this branch removing the OAuth-resource routes in internal/httpapi/server.go, the OAuthResources UI and resource_authorization_enabled in web/app/page.tsx, and AND NOT resource_only in billingRedirectAllowed (billing.go, around line 768). This is the feat(auth): add resource authorization and connected applications #36 work, which the branch simply doesn't have yet.
    • Migration numbering: you said v0.5.0 owns 00008. I couldn't list main's migrations, so I haven't confirmed that. If it's right, migrations/00008_billing_subject_closure.sql collides, and 00009_subscription_payment_grace.sql will need to move up too.
    • Rebase onto main, renumber to the next free pair (0000N+1 and 0000N+2), and regenerate openapi.gen.go and the SDK.
    • Check that the rebase doesn't silently drop or revert the feat(auth): add resource authorization and connected applications #36 pieces.
  2. A pending checkout blocks purchase and workspace cancellation for 25 hours, even after a definite provider failure. Compare the removed status='failed' update in billing.go (around line 295) with expireSubjectCheckouts (billing_service_cancel.go:122-125).

    • Any error from stripeRequest now leaves the row pending, including 4xx rejections, config errors and a crash between insert and response. The PR description only justifies this for an ambiguous timeout.
    • guardRecurringCheckout counts that row as open. The user's retry gets 409 subscription_exists until the row is 25 hours old.
    • serviceCancelSubjectBilling calls expireSubjectCheckouts, which returns an error for any pending row with no provider_session_id. Cancellation then fails with 503 for the same window. For an immediate cancel the closure row is already committed, so the caller gets an error that retrying can't clear.
    • Suggested fix: mark the row failed when the error is a definite non-retryable provider response, and keep pending only for transport errors or timeouts. Alternatively, reconcile by looking the session up by client_reference_id or the idempotency key.
    • expireSubjectCheckouts also selects every pending or open checkout for the subject, including one-time ones, so the same failure mode applies to them.
  3. The advisory-lock guard holds a pool connection across the Stripe call.

    • guardRecurringCheckout (checkout_policy.go:16-34) keeps a pooled connection and an open transaction until the handler returns. The handler then calls s.app.DB.Exec, which needs a second connection, and the Stripe HTTP request also runs in between.
    • MaxConns is 20 (internal/database/database.go:22). Requests for the same subject wait on pg_advisory_xact_lock while holding a connection.
    • So 20 or more concurrent recurring checkouts, for one subject or across subjects, can all hold a connection and wait for a second one. Nothing moves until context timeouts fire.
    • Suggested fix: do the eligibility check and the checkout_sessions insert in one transaction with the lock, then release the connection before calling Stripe. The inserted pending row already serializes later requests, so the lock doesn't need to cover the provider call.
  4. unpaid subscriptions are not treated as active by the guard, but cancellation does cancel them.

    • The eligibility query (checkout_policy.go:53) uses ('active','trialing','past_due','paused','incomplete'). serviceCancelSubjectBilling (billing_service_cancel.go:53) also includes 'unpaid'.
    • A subject whose subscription is unpaid can start a second recurring checkout under single_subscription, even though Stripe still holds the unpaid subscription.
    • The fix is to add 'unpaid' to the guard's status list.
  5. past_due_since is stamped with now() at processing time and isn't cleaned up on every path.

    • billing_stripe_events.go (the CASE WHEN $9='past_due' THEN now() clause) sets the timestamp when the webhook is processed.
    • A delayed or retried first past_due event starts the grace window later than the real first failed renewal. Stripe's event created time or the invoice failure time would be the better anchor.
    • cancelSubscription (billing_lifecycle.go:285) and serviceCancelSubjectBilling (billing_service_cancel.go:95) write status directly and never touch past_due_since. A subscription that is past_due and then cancelled keeps a non-null past_due_since while canceled. The new serviceSubjectBilling exposes that value.
    • The service path also doesn't store cancel_at or canceled_at, unlike cancelSubscription, which does. The next webhook normally fixes the row, but the billing summary is stale until then.
    • Suggested fix: clear past_due_since whenever the written status isn't past_due, and reuse the same update as cancelSubscription.
  6. Tests don't reproduce several claimed behaviours. checkout_policy_test.go covers policy validation, the machine-permission 403s, one table-driven eligibility run, and a 404 for an unrelated subscription. It does not cover:

    • concurrent checkouts for the same subject;
    • the open-session resume branch (all four "open" cases use checkout_uri IS NULL, so the 409 path is what actually runs);
    • workspace subjects, closure rows and the billing_subject_closed 409;
    • unpaid and trialing subscriptions;
    • a used trial detected through subscriptions.trial_end rather than a completed checkout;
    • expireSubjectCheckouts with the provider mocked (open, complete, expired, pending with no provider id);
    • a successful owner-authorised cancel, or a workspace-manager cancel versus a non-manager;
    • webhook replay or delay against the grace timestamp (only the sequence past_due, past_due, active exists).
    • Finding 2 is not exercised either; a test for it would be the failing one.
  7. Smaller points

    • There is no way to reopen a closed billing subject (billing_subject_closures has no delete path), so a mistaken immediate cancel is permanent.
    • Resume only looks at checkouts created in the last 24 hours, while the "in progress" window is 25 hours. In that one hour the user gets a 409 with nothing to resume.
    • The toast persistence in Toast (web/app/page.tsx:3286) matches message text with the regex /one-time|store this secret now|store it now/i. It covers the current secret messages (lines 1184, 1276, 1615, 2685) but not future wording. The result path that falls back to JSON.stringify(result) at line 1276 would auto-dismiss in 4 seconds if a secret appeared there. A flag passed to setMessage would be sturdier than matching text.
    • PriceCreator now accepts raw checkout-config JSON, which is fine. The server-side validateCheckoutPolicy rejects non-boolean flags and non-recurring modes. Nothing in the UI hints at single_subscription or trial_once_per_subject, and docs/recurring-checkout-policy.md is the only place they're described.

Checked and found fine

  • The closure insert and the checkout guard take the same app:subject_type:subject_id advisory lock. An immediate cancel that commits its closure first blocks later checkouts, and a checkout already holding the lock is persisted before the closure can commit, so expireSubjectCheckouts sees it.
  • Eligibility denies a new trial after a completed trial checkout or any subscription with trial_end, and allows one after failed or expired checkouts.
  • Provider idempotency keys are now per application and session.
  • User-subject cancellation requires the actor to be the subject; workspace cancellation requires workspace billing management; the machine endpoint requires billing/write and workspace-only subjects.
    · branch feature/subscription-trial-policy

@SirNarsh

Copy link
Copy Markdown
Member Author

Independent review confirms substantive issues that need correction before merge: migration 00008 now collides with released main; the recurring guard can exhaust the database pool by holding one connection while requesting another; unresolved provider creation failures lack a safe retry/reconciliation path; unpaid subscriptions are omitted from duplicate prevention; and cancellation should normalize subscription/entitlement state rather than update status alone. Subject billing responses also need runtime schema tests and provider subscription identifiers. Permanent billing closure on immediate cancellation requires a product-semantics decision rather than being treated as ordinary cancellation. Credential notices should have explicit persistence rather than wording-dependent behavior. Claude review corroborates the concurrency, retry and coverage gaps. The branch being behind main is not itself evidence that its intended merge deletes resource authorization; rebase and regenerate while preserving the released feature. Existing checks are for the old base. No merge or release at this stage.

@SirNarsh

Copy link
Copy Markdown
Member Author

@claude Please review the fixes at e4566a8 against current main. Read-only; do not edit, merge, release or deploy. Product decision: cancellation allows later resubscription; archival is separate. The PR now merges released main, preserves migrations 00001-00008 and adds 00009/00010. Review short atomic checkout reservation (no pooled connection held during provider I/O), saved provider forms/stable replay keys, definitive versus ambiguous provider errors, old-key/legacy reconciliation without assuming 25-hour expiry proves non-purchase, temporary cancellation records cleared on success, provider entitlement normalization and independent manual grants, archival rejection while billing is unsettled, signed-event grace timestamps/stale observation rejection, actual summary schema/provider identifiers, and explicit persistent credential notices. New real PostgreSQL HTTP regressions exercise concurrency with MaxConns=2, recovery, cancellation/resubscription, trial-only versus single-subscription policy, unpaid subscriptions, archive boundaries, expiration and generated summary schema. Focus on reproducible remaining defects and compatibility, not speculative features.

@claude

claude Bot commented Oct 18, 2026 •

Copy link
Copy Markdown

Claude finished @SirNarsh's task in 1m 23s —— View job


Review of e4566a8 (read-only)

I traced the code paths against current origin/main. I did not run the Go or PostgreSQL tests, because compound shell commands were blocked here. Everything below comes from reading the code. The "reproducible" items are traced paths, not executed runs.

What looks right

  • Migrations: 00001–00008 are untouched, and 00009 and 00010 are new. The feat(auth): add resource authorization and connected applications #36 resource-authorization work is present again.
  • Pool use: the guard transaction in guardRecurringCheckout covers only the eligibility checks and the checkout_sessions insert. tx.Commit runs before persistCheckoutRequest and stripeRequest, so no connection is held across provider I/O.
  • Replay keys: provider keys are now platform93-checkout-<app>-<session id>, with the request form saved first. Replay is bounded to 23 hours.
  • Rejected requests: only non-retryable 4xx responses mark a checkout failed. Timeouts, 408, 409, 429 and 5xx leave it pending.
  • Stale events: the provider_event_at guard skips older events before any grant change. past_due_since is LEAST-merged and cleared when the status leaves past_due.
  • Cancellation flow: the billing_subject_cancellations row is deleted only on success. The guard and persistCheckoutRequest both check it under the same advisory lock.
  • Summary: the subscription summary now returns the provider identifiers.

Remaining defects, most severe first

  1. A saved-form checkout with an unknown outcome can stay unresolved forever (checkout_recovery.go, resolveCheckoutAttempt).

    • Once a row is 23 hours old or more, it takes the customer-list branch. If the list finds no matching session, the code returns provider outcome requires administrator reconciliation. No code path ever moves the row out of pending.
    • A crash after persistCheckoutRequest but before the POST reaches Stripe produces such a row, as does a 5xx that never created a session.
    • While that row exists:
      • guardRecurringCheckout counts it as open, so a policy price returns 409.
      • recoverCheckoutAttempts returns 503 on every later policy-price checkout for the product, because it scans all unresolved attempts and one failing row aborts the loop.
      • expireSubjectCheckouts fails, so workspace cancellation fails.
      • deleteWorkspace returns workspace_billing_unsettled.
    • If the full customer-scoped list pages to the end without finding client_reference_id == a.id for a row that has a saved form, that does show the session was never created. Marking it failed in that case seems safe and would not rely on a 25-hour expiry. Whether Stripe's list retains every session you'd need to search is worth checking.
    • The legacy case (legacy_unknown) is harder. SELECT ... FROM billing_customers returns ErrNoRows if the old checkout failed before a customer existed. That gives a permanent error with no recovery action either. Legacy rows need an authorised administrative resolve path, or a clearly documented manual procedure.
  2. A pending checkout with no saved form makes a cancellation fail once for no reason (billing_service_cancel.go, expireSubjectCheckouts).

    • For a pending row older than 1 minute with no provider_request, resolveCheckoutAttempt first sets it to failed and returns nil, nil.
    • The caller then runs UPDATE ... SET status='expired' ... WHERE status='pending'. That affects 0 rows, so it returns checkout changed concurrently; retry, which surfaces as a 503.
    • A retry succeeds, since the row is now failed. The first attempt fails, though, and the new test does not appear to cover this age. Treating RowsAffected()==0 as acceptable when the row is already terminal would fix it.
  3. Archival can succeed while a recurring purchase is still settling (workspace_management.go, deleteWorkspace).

    • The archive check blocks on live subscriptions, pending/open checkouts and cancellation rows.
    • It ignores a completed recurring checkout whose subscription webhook has not been processed yet. guardRecurringCheckout already counts that state as active, via the NOT EXISTS (subscriptions ... platform93_checkout_id) clause.
    • Sequence: checkout.session.completed is processed, the workspace is archived, then the subscription event arrives. Billing then continues for an archived workspace. serviceCancelSubjectBilling does not filter on deleted_at, so the machine endpoint might still cancel it. The owner-facing path depends on canManageWorkspaceBillingFor, which I did not check for archived workspaces.
    • Adding the same "completed without a subscription" predicate to the archive check would make the two consistent.
  4. The cancel endpoint requires an Idempotency-Key but never uses it (serviceCancelSubjectBilling).

    • The key is only checked for presence. The operation id comes from the subject row, so any caller with any key resumes or reuses the same operation.
    • Messages say "retry with the same idempotency key". That is harmless for correctness, since the provider keys derive from the operation id. It does make the contract slightly misleading, and the OpenAPI description should say so.
  5. Credential notices: the generic path can still leak a secret into a timed toast (web/app/page.tsx, ResourceRow).

    • ResourceRow only treats secret or client_secret as one-time credentials. CreateResource also handles invitation_token.
    • Any row action whose response carries an invitation_token, or any other credential field, still falls through to setMessage(JSON.stringify(result)). That message auto-dismisses after 4 seconds.
    • I did not confirm that any current row action returns one. If none does, this is future-proofing. Sharing one extraction helper across all call sites would close it.
    • Also, Toast sets const persistent = failed;, which is a no-op alias, so it is dead code.
  6. Minor: a user-facing cancel can report a Stripe failure after Stripe succeeded (billing_lifecycle.go, cancelSubscription).

    • Any normalizeStripeSubscription error, including a local database failure, is returned as 502 subscription_cancel_failed ("Stripe could not cancel the subscription"). Retrying is safe, but the message is wrong.

Checks that came out fine

  • Cancellation reconciles an already-canceled subscription through the GET fallback and validates cancel_at_period_end or canceled.
  • Manual grants are separate rows keyed by source, so provider normalization does not touch them.
  • Checkout resume requires the same actor and request hash. A changed payload with the same key is rejected.

Test coverage gap: I could not tell from reading whether the new regression tests cover items 1–3. The ones most worth adding are:

  • a saved-form pending row older than 23 hours with an empty provider list;
  • a form-less pending row older than 1 minute during workspace cancellation;
  • archival right after a completed recurring checkout and before its subscription event.
    · branch feature/subscription-trial-policy

@SirNarsh

Copy link
Copy Markdown
Member Author

@claude Follow-up review requested on 2e60301 (plus typed SDK follow-up bb1a971). The abandoned-preparation cancellation now accepts terminal state after recovery; archival also blocks completed recurring checkout before its subscription is normalized. Empty provider lists deliberately do not automatically prove non-purchase: a new control-only resolve-not-created action requires explicit provider-investigation attestation/reason, a pending attempt older than 25 hours with no provider ID, Idempotency-Key, and atomic audit/state change. New PostgreSQL regressions cover this escape path, no unsafe old-key recreation, archive-before-subscription, and first-attempt cancellation of abandoned preparation. The generic HTTP idempotency middleware does use caller keys; durable cancellation operation IDs separately preserve provider keys across partial batch retries. Added invitation-token handling and corrected reconciliation error wording. Four server SDKs now expose typed summary fields and workspace cancellation, with runtime tests. Review remaining substantive security/correctness issues; do not edit, merge, release or deploy.

@claude

claude Bot commented Oct 18, 2026 •

Copy link
Copy Markdown

Claude finished @SirNarsh's task in 38s —— View job


Review of 2e60301 and bb1a971 (read-only)

I read the code and did not run the Go or PostgreSQL tests. I read checkout_recovery.go, checkout_resolution.go, billing_service_cancel.go, the archive check in workspace_management.go and the resolve route in server.go. I did not read the SDK diffs, the web UI, the migrations or the new regression tests. Nothing below comes from running code.

Earlier findings that now look fixed

  • First-attempt cancellation of abandoned preparation: expireSubjectCheckouts (billing_service_cancel.go:174-179) now accepts a row that is already failed or expired after recovery. Before, it returned "changed concurrently" on the first call.
  • Archive before subscription: the completed recurring checkout predicate was added to the archive check (workspace_management.go:121). It matches the one in recoverCheckoutAttempts.
  • Resolve-not-created: it locks the row with FOR UPDATE, and requires a control user, an Idempotency-Key, an explicit attestation and a reason. It also requires pending, no provider ID and an age of at least 25 hours. The audit insert and the status change share one transaction, and a missing audit row aborts the change. The route is wrapped in s.idempotent.

Remaining issues, most severe first

  1. There is a gap between 23 and 25 hours where cancellation and archival fail with no recovery action. (checkout_recovery.go:152-172, checkout_resolution.go:56)

    • Replay stops at 23 hours and the resolve action only works from 25 hours.
    • For a saved-form pending row aged 23–25 hours, the code takes the list branch. If the list finds nothing, it returns "requires administrator reconciliation". The resolve endpoint then returns 409.
    • Cancellation (503), archival and policy-price checkout (409/503) are all blocked for those 2 hours. That's bounded and probably acceptable, but the error text should say when resolution becomes available.
    • Please confirm the Stripe constraint. The 23-hour replay cutoff comes from the 24-hour idempotency-key lifetime. Check whether a lost response at hour 22:59 can still be replayed safely. The POST in resolveCheckoutAttempt could be sent for the first time at 22:59 and outlive the key by minutes. That is harmless, because a replay with the same key inside the window returns the same session.
  2. A saved-form pending row whose list lookup is incomplete can be attested as "not created" while a session exists. (checkout_resolution.go:47-58)

    • The endpoint trusts the operator's attestation and checks nothing server-side.
    • The list lookup filters on customer=form.Get("customer"). If a saved form has no customer (I did not check whether billing.go always sets one), the filter is empty. reconcileStripeList then pages every session on the account, or may fail.
    • Also, reconcileStripeList returns early on error. A list that is only partly paged returns an error rather than found == nil, so the "no session" message is not triggered by a partial list. I could not check this in the function, so please confirm it.
    • Suggestion: when the form has no customer, fail with a clear error instead of listing without a filter. Optionally have the resolve action call the same provider list and refuse if it finds a matching client_reference_id. That would catch an operator mistake and keep the audit trail.
  3. resolveCheckoutNotCreated does not check that the row belongs to a recurring or policy price, and it does not touch billing_subject_cancellations. (checkout_resolution.go:44-68)

    • After a successful resolve, a pending workspace cancellation can proceed. That's the intended outcome.
    • The UPDATE does not repeat AND status='pending'. This is safe today because the row is locked in the same transaction, but adding the predicate would be sturdier.
    • The resolve action only records an audit row. No reason field is written to checkout_sessions, so the checkout row alone does not show why it failed.
  4. Idempotency is only as strong as the middleware. (billing_service_cancel.go:30)

    • The handler only checks that Idempotency-Key is non-empty. Operation identity comes from the billing_subject_cancellations row, which is keyed by subject, not by the caller's key.
    • You said the generic middleware uses caller keys, so I take that as fixed. I did not check how the middleware scopes its cache. Please confirm it keys on the application and actor as well as the header, so a key reused across subjects can't replay another subject's response.
    • A second concurrent call with a different key but the same at_period_end joins the same operation. That is intentional per the comment.
  5. Minor: expireSubjectCheckouts does not select completed recurring checkouts that are awaiting their subscription. (billing_service_cancel.go:146)

    • It only selects pending and open. If cancellation runs after checkout.session.completed but before the subscription event, the loop of subscriptions at lines 76-77 finds nothing. The cancellation row is then deleted, and the subscription arrives afterward.
    • The archive check and the checkout guard treat that state as active. Cancellation could treat it the same way, for example by running recoverCheckoutAttempts-style normalization for it before it proceeds.
    • Alternatively, return a retryable error while such a checkout exists, so the cancel is not reported as complete.
  6. Minor: idle details. Toast setting persistent = failed looked like a no-op in the previous revision. I did not recheck the web code in this pass, so please confirm that and the invitation_token handling are covered by the new tests.

Not verified

  • Whether the new tests actually cover items 1, 2 and 5. The cases most worth a test are a saved-form row aged 24 hours with an empty provider list, and a completed recurring checkout with no subscription at the moment of a machine cancel.
  • The four server SDKs, the OpenAPI schema for the new route and the migrations.
    · branch feature/subscription-trial-policy

@SirNarsh

Copy link
Copy Markdown
Member Author

@claude Final focused follow-up on b48983a: cancellation now also reconciles completed recurring checkout awaiting subscription before reporting success (matching archive/eligibility predicates), with a PostgreSQL HTTP regression proving provider cancellation and subsequent archival. Customer-less provider-list recovery fails closed. Added negative tests for auditor access, recent/known/completed-session resolution rejection, forced audit failure rollback, and upgrade/down/up from released schema 8 preserving legacy unknown outcomes. Confirm the intentional 23–25 hour safety interval and privileged investigation/attestation contract, not automatic absence inference. HTTP idempotency records are scoped to application+actor+key and validate method/path/body hashes; durable subject operations intentionally allow authorized same-mode retries to join. Credential notices are separate from transient toast styling and covered across navigation. A single exact generated-schema byte string/path exception fixes a verified Gitleaks false positive; the payload was decoded as the public OpenAPI document and full-history scanning repeated. Please report only remaining substantive issues in these final changes. No edits, merge, release or deployment.

@claude

claude Bot commented Oct 18, 2026 •

Copy link
Copy Markdown

Claude finished @SirNarsh's task in 39s —— View job


Final review of b48983a (read-only)

I found no substantive remaining defects in these changes. This is from reading the code. I did not run the Go, PostgreSQL, SDK or Playwright tests. I also did not read the new regression tests, the SDK diffs, the web UI or the idempotency middleware. Your statements about those, and about the Gitleaks decoding and history scan, are unchecked.

Confirmed from source

  • Cancellation reconciles a completed recurring checkout.
    • expireSubjectCheckouts (billing_service_cancel.go:143-147) now selects completed recurring checkouts that have no subscription yet. The predicate matches checkout_recovery.go:75, checkout_policy.go:46 and the archive check at workspace_management.go:121.
    • resolveCheckoutAttempt normalizes the checkout and the subscription. expireSubjectCheckouts skips any session that is not open. The subscription query at line 76 then runs after reconciliation, so the new subscription is cancelled before the cancellation row is deleted.
    • The metadata link relied on by the NOT EXISTS clause is set in billing.go:271 and :284.
  • Customer-less recovery fails closed. checkout_recovery.go:160-162 returns an error before any unfiltered provider list, so it can't produce a false "not found".
  • The legacy list lookup is valid. The legacy match on client_reference_id and platform93_application_id works for pre-upgrade rows. Both are set on origin/main's checkout code (billing.go:242, :244) as well as on this branch.
  • The 23–25 hour interval is sound.
    • Before 23 hours: replay uses the same Stripe idempotency key, which is safe inside Stripe's 24-hour window.
    • From 23 hours: the code only searches by customer. It never recreates the session.
    • Resolve window (25 hours): an empty list returns "requires administrator reconciliation", and resolve stays closed until 25 hours.
    • Nothing infers non-purchase from absence or elapsed time.
    • The 2-hour block on cancellation, archival and policy-price checkout is bounded. It would help if the error text said when resolution opens.
  • The resolve-not-created contract holds.
    • It requires a control_user, an Idempotency-Key, the attestation and a reason of 10–512 characters.
    • It locks the row with FOR UPDATE. It requires pending, no provider ID and an age of at least 25 hours.
    • The audit insert must affect exactly one row, and the audit and the status change commit in one transaction. A repeat call on an already failed row returns 204 without a second audit, which is fine.
    • The route is wrapped in s.idempotent.
  • The legacy migration is conservative. 00009 marks every pending row with no provider ID as legacy_unknown. Those rows are only ever resolved by a customer-scoped lookup or the privileged attestation.
  • The Gitleaks changes are narrow. They are one exact regex anchored to internal/generated/openapi.gen.go, plus commit-pinned fingerprints in .gitleaksignore. I did not decode the string.

Non-blocking notes

  1. Legacy rows with no customer.
    • A legacy pending row whose checkout failed before a billing customer existed gets a raw sql.ErrNoRows from resolveCheckoutAttempt (line 144). Cancellation returns it as a 503 until the row is 25 hours old. Archival and policy-price checkout are blocked the same way.
    • After 25 hours, the attestation path clears it. A distinct error message, like the customer-less case, would make the failure clearer for operators.
  2. Optional hardening for resolve.
    • The UPDATE at checkout_resolution.go:68 doesn't repeat AND status='pending'. It's safe today because the row is locked.
    • The status change and audit record don't store the reason on checkout_sessions. It lives only in audit_records.
  3. Cancel idempotency. serviceCancelSubjectBilling only checks that the Idempotency-Key header is non-empty. Operation identity comes from the durable per-subject row. You described that as intentional, so I'd just make sure the OpenAPI description says it.

I did not confirm whether the new tests cover the 24-hour saved-form case with an empty list, or the legacy no-customer case in note 1.

No edits, merge, release or deployment were made.
· branch feature/subscription-trial-policy

@SirNarsh

Copy link
Copy Markdown
Member Author

Claude final review at b48983a reports no substantive remaining defects. Its optional points are intentional/documented: no automatic non-purchase inference from an empty list, a conservative 23–25 hour safety interval, and actor/application-scoped HTTP idempotency alongside durable subject-operation keys. Confirmed provider forms always contain a nonempty customer; list pagination errors fail rather than treating partial results as absence. Administrative resolution is a trusted, reasoned attestation with atomic audit, not automated proof of absence. Additional negative PostgreSQL tests reject auditors and ineligible states and prove audit failure rolls back resolution; schema-8 upgrade/down/up and completed-checkout-before-subscription cancellation regressions pass. Local browser suite: 76 passed, 4 optional skipped; current CI runs the real bootstrap flow separately. 7126a74 changes only the exact verified public-schema Gitleaks capture (not a source exclusion). Latest-head checks are pending. No merge/release/deployment.

@SirNarsh

Copy link
Copy Markdown
Member Author

Final head 67e09ad passes all CI and Security checks, including browser flows, PostgreSQL/MinIO execution assertions, race tests, migration checks, SDK consumers, image and Helm smoke checks. Claude source review reports no substantive remaining defects; the automatic review also passes. Setup browser flows now explicitly dismiss credentials after reading them, while the separate navigation-persistence test remains. Cancellation allows later resubscription; archival is a separate operation requiring settled billing. Provider calls remain mocked in regression tests; live-provider acceptance is not claimed. This PR has not been merged, released or deployed.

@SirNarsh
SirNarsh force-pushed the feature/subscription-trial-policy branch from 67e09ad to 60fbb7e Compare November 3, 2026 20:16
@SirNarsh

SirNarsh commented Nov 3, 2026

Copy link
Copy Markdown
Member Author

@claude Please review the rebased head 60fbb7e against current main (v0.7.1). Read-only review: do not edit, merge, release or deploy. The complete previous snapshot was consolidated before rebase because substantive fixes lived in an old merge commit. Released migrations 00001-00010 are unchanged; new migrations are 00011/00012, with upgrade/down/up tested from schema 10. Preserve the v0.7.1 typed Stripe acknowledgements, ignored-event classification, row-locked receipts and single-transaction normalizers; signed event created timestamps now reach the existing grace/stale guards through that receipt processor. Inspect interaction correctness, cross-application isolation, no nested pool use, cancellation/resubscription, durable recovery, current invitation credentials and persistent notices. Added a real PostgreSQL HTTP regression for signed timestamp, rollback/retry and stale subscription events with a one-connection pool. Prior reviewed product decisions are unchanged: cancellation permits resubscription; archival is separate; old unknown checkout outcomes are not inferred absent automatically. Report substantive defects with source references. Do not treat workflow success as test execution.

@claude

claude Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Claude finished @SirNarsh's task in 1m 24s —— View job


Review of rebased head 60fbb7e (read-only)

I read the source and diffed against origin/main (v0.7.1, merge-base 59be1d1). I did not run any Go, PostgreSQL, SDK or browser tests. A workflow passing is not evidence that these paths were exercised, and I did not read the regression tests, SDK diffs, web/ changes, OpenAPI or generated code. The files I did read are checkout_policy.go, checkout_recovery.go, billing_service_cancel.go, migrations 00011/00012, and the diffs for billing.go, billing_lifecycle.go, billing_stripe_events.go, stripe_webhook.go and workspace_management.go. I did not read checkout_resolution.go this pass.

No substantive defects found in the interactions you asked about. Three non-blocking observations are below.

Confirmed from source

  • v0.7.1 receipt processing is preserved.
    • The webhook change is small: Created is added to stripeEvent, and stripe_webhook.go puts the signed created time in the context before calling the normalizer. That happens inside the existing row-locked receipt transaction.
    • normalizeStripeSubscription reads it with ctx.Value(stripeObservationTime{}). It falls back to s.app.Now() and clamps future timestamps. Both the webhook path and the reconcile path go through that function.
    • The ON CONFLICT ... WHERE provider_event_at IS NULL OR EXCLUDED >= existing guard turns a stale event into ErrNoRows, which is returned as nil. The receipt therefore completes without touching grants.
    • Because it returns early, the entitlement code after it doesn't run for stale events.
  • No nested pool use found on the paths I read.
    • guardRecurringCheckout holds its transaction only for the lock, the eligibility query and the checkout_sessions insert. It commits before persistCheckoutRequest and before stripeRequest.
    • persistCheckoutRequest opens a fresh short transaction.
    • serviceCancelSubjectBilling commits the reservation before any provider call. cancelProviderSubscription calls normalizeStripeSubscription, which opens its own transaction after the HTTP call.
    • In expireSubjectCheckouts and recoverCheckoutAttempts, rows.Close() runs before any further query.
  • Application isolation.
    • Provider idempotency keys include the application and session id (platform93-checkout-<app>-<id>).
    • Cancellation and user-facing keys are SHA-256 hashes over the operation, application, actor, path and key.
    • Every checkout and subscription query I read filters on application_id.
    • Recovered list results require metadata.platform93_application_id == app and a matching client_reference_id.
    • The advisory lock key is app:type:id.
  • Cancellation and resubscription.
    • The cancellation row blocks guardRecurringCheckout and persistCheckoutRequest under the same advisory lock. It is deleted only after all provider operations succeed.
    • Only same-at_period_end retries join the existing row, so a different mode gets 409.
    • Provider keys derive from the durable operation id, so partial-batch retries are stable.
    • cancelProviderSubscription confirms cancel_at_period_end or canceled before normalizing.
  • Archival is separate. deleteWorkspace blocks on a held lock, live subscriptions (including unpaid), pending/open checkouts, a completed recurring checkout awaiting its subscription, and a pending cancellation row. The predicates match checkout_policy.go:46, checkout_recovery.go:75 and billing_service_cancel.go:147.
  • Recovery never infers non-purchase. Replay is limited to rows under 23 hours with a saved form. Older rows and legacy_unknown rows only do a customer-scoped list. They fail closed if there is no customer or the list errors, and an empty list returns "requires administrator reconciliation".
  • Migrations. 00011 and 00012 are additive and have symmetric Down sections. 00011 marks every pending row without a provider id as legacy_unknown, which is conservative.

Non-blocking observations

  1. An abandoned open checkout blocks policy-price repurchase.
    • Where: checkout_policy.go:46-52, checkout_recovery.go:110.
    • With single_subscription or trial_once_per_subject, an open session counts as open until Stripe reports it expired or completed. Resume only happens when the caller's Idempotency-Key matches the original.
    • A user who abandons Checkout and retries with a new key gets 409 subscription_exists. That lasts until Stripe's session expiry (24 hours by default) or until they cancel it. This matches the reservation semantics you describe, but I didn't see an API or UI path to expire a user's own abandoned session. Confirm that is intended, and that the docs say so.
  2. Out-of-order past_due events can start the grace window late.
    • Where: billing_stripe_events.go, the past_due_since expression in the ON CONFLICT clause.
    • If a newer past_due observation is stored and an older past_due event arrives afterwards, the stale guard skips it before LEAST(...) can lower the timestamp. The grace anchor then stays at the later time.
    • This is conservative (it extends grace) and bounded by one webhook ordering. I would only change it if the product wants the earliest failure time to win.
  3. A checkout-resolution ErrNoRows is now silent.
    • Where: normalizeStripeCheckoutTx, if err == pgx.ErrNoRows { return nil }.
    • The added c.provider_connection_id=$5 and AND (c.status<>'completed' OR $1='completed') conditions make a mismatched connection, or a late expired event for a completed session, a no-op. That is the right isolation behaviour and a stale expired can't downgrade completed.
    • It also means a genuinely missing row no longer produces a retryable error. I did not check whether the earlier lookup in that function still errors for unknown ids.

Not verified

  • Whether the new regressions reproduce the claimed behaviour, including the one-connection-pool signed-timestamp test.
  • The checkout_resolution.go resolve-not-created route after the rebase. Please confirm it is unchanged from the version reviewed at b48983a.
  • The SDK typed fields, OpenAPI contract, web/ credential notices and invitation-token handling.
  • Schema-10 upgrade/down/up.

No edits, merge, release or deployment were made.
· branch feature/subscription-trial-policy

@SirNarsh

SirNarsh commented Nov 3, 2026

Copy link
Copy Markdown
Member Author

@claude Final delta review requested at 1f58d38. Your rebase review found no substantive interaction defects. Subsequent changes patch chi to 5.4.0, fast-uri to 3.1.9 and zod 4.x to 4.6.6; the exact generated OpenAPI finding was decoded as the public schema and narrowly allowlisted by value and path, with full-history scanning passing. Current main invitation responses use invitation_url, so both generic creation/action credential paths now retain that link in the existing persistent notice; a focused browser test verifies expiry does not hide it and explicit dismissal does. Three focused browser tests pass. Full PostgreSQL Go race suites and SDK/lint/contracts passed; exact-head CI remains required. Please confirm any remaining substantive blockers in these deltas, especially existing invitation/control workflows. No edits, merge, release or deployment.

@claude

claude Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Claude finished @SirNarsh's task in 30s —— View job


Final delta review of 1f58d38 (read-only)

No substantive blockers found in these deltas. I read the diff 60fbb7e..1f58d38, which touches 7 files. I did not run any Go, PostgreSQL, SDK or Playwright tests, and I did not decode the Gitleaks value. Exact-head CI is still required.

What I checked

  • Invitation links (web/app/page.tsx:1194, :1288):
    • Both the creation path and the row-action path now fall back to invitation_url. Both go through showCredential, the persistent notice.
    • The OpenAPI spec has invitation_url on InvitationDeliveryResult (platform93.yaml:10279) and InvitationRotationResult, described as a one-time credential URL. Those are the application invitation create and rotate responses.
    • The ?? chain order is unchanged, so a response carrying secret, client_secret or invitation_token behaves as before.
  • Other invitation flows: the organization and platform-user invitation handlers (page.tsx:2688, :2697, :2710) still read invitation_token and use showCredential. They are unchanged and consistent with the schemas that define invitation_token. I did not trace each of those endpoints' handlers or responses on the server.
  • E2E test (web/e2e/navigation.spec.ts): it creates an invitation and mocks a 201 response with invitation_url. It runs the clock forward 10 seconds, checks the link is still shown, then dismisses it and checks it is gone. That covers the previously timed-out toast case.
  • Gitleaks (.gitleaks.toml):
    • The change adds one more exact anchored ^…$ regex to the existing allowlist entry, which is limited to internal/generated/openapi.gen.go and uses condition = "AND". It is not a source-wide exclusion.
    • Your decode of the value as part of the public schema is unchecked by me.
  • Dependencies: chi goes from 5.3.1 to 5.4.0, fast-uri from 3.1.8 to 3.1.9, and zod@4 is overridden to 4.6.6. All are patch or minor bumps with matching go.sum and pnpm-lock.yaml edits.
    • The zod@4 selector only affects 4.x. It should not touch other major versions, but I did not inspect the lockfile for a surviving zod 3.
    • I did not check chi 5.4.0's changelog for routing changes.

Non-blocking note

  • ResourceRow still falls back to setMessage(JSON.stringify(result)) (page.tsx:1289) for any other credential-bearing field. This is future-proofing only. I found no current response that needs it.

No edits, merge, release or deployment were made.
· branch feature/subscription-trial-policy

@SirNarsh
SirNarsh merged commit dc06c7a into main Nov 3, 2026
15 checks passed
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