Skip to content

[Sites] Meter Sites operations with credit reservations and spending limits #2105

Open

Description

@sidneyswift

Parent epic: #2093

Priority

P0 — First shared Sites and external Widgets release.

User journey

Customer or agent requests a cost estimate → approves a maximum charge → credits are reserved → work completes or fails → customer sees the final charge and released remainder.

Acceptance criteria

  • Close the current Sites generation/revision billing gap across HTTP, MCP, and UI using the same balance, usage-to-credit calculation, deduction, and usage audit as chat. No separate wallet or Sites-only multiplier.
  • Implement atomic reservation, settlement, release, and reconciliation with stable operation/idempotency IDs; concurrent requests cannot overspend a balance or double-charge a retry.
  • Record pricing version, billing owner, operation/application/site identifiers, provider usage, retries, and actual versus estimated cost. No paid work starts without a successful authorization/reservation.
  • Enforce authorized spending, repair-attempt, and concurrency limits using shared billing rules. Do not restore the removed four-minute generation timeout. Document remaining hosting/provider limits and use a background workflow for longer reliable runs. Define cancellation and provider-failure billing explicitly, including costs incurred without a usable output.
  • Keep published Sites hosted while the billing customer has active Pro. Measure hosting/storage/traffic separately from generation credits; baseline usage is included and automatic paid overage blocks with a customer-set ceiling are approved. The Sites allowance is 100,000 monthly sessions across the billing customer’s Sites; paid block sizes/prices and other resource allowances remain open. Public fan requests cannot trigger unrestricted model spending. Return machine-readable insufficient-credit/budget errors and receipts.
  • Use the shared chat pricing calculation for Sites token generation. No separate 2× Sites multiplier is approved. Measure model, infrastructure, payment, and failure costs; propose any future shared pricing changes explicitly rather than promising guaranteed profitability.

Blocking dependencies

None. This foundation ticket can start now.

These are completion prerequisites, mirrored in GitHub’s blocked-by links. Design and contract work may start earlier. Other coordination references are not blockers.

Validation

Exercise concurrent reservations, duplicate deliveries, worker crashes, partial provider failure, settlement retries, cancellation, stale quotes, accounting outages, and reconciliation. Validate actual measured costs before setting prices.

Delivery conventions

API owns business logic and billing; HTTP and MCP share it. Chat/embeds/SDKs are clients. Database changes use the database repository PR workflow. Update marketing-owned docs and generated indexes. Use Vercel Workflows for new durable background work. No automatic publication or unbounded customer spending.

Fan points coordination

AI generation and revisions use existing chat credits. Hosting, Fans, Widgets, and points-processing infrastructure consume approved Pro allowances and purchased capacity; do not also debit AI credits for that infrastructure unless a separate pricing change is explicitly approved. Fan reward points (#2113) never pay Recoup charges. Exact infrastructure quantities and rates remain open; do not invent another wallet.

Cost decision reference

The Hosting and credit decisions section of epic #2093 is authoritative. Resolve numeric Pro allowances and overage prices, failure/refund rules, exact exhaustion behavior, and subscription lifecycle before activating charges or disabling hosted experiences. External Widgets/Fans baseline access and the automatic paid usage-block approach are approved in the epic. These open questions do not change the confirmed requirement to use chat’s credit system for Sites token generation.

Approved billing and enforcement requirements

Approved following the customer review and four-expert council. This is a product specification, not a claim that enforcement has shipped.

Included usage and billing ownership

  • Pro includes 100,000 billable Sites sessions per subscription month across all Sites belonging to the paying account or organization. This is a session allowance, not a promise of 100,000 distinct people or unlimited resources. Specify the monthly reset rule in the billing contract.
  • The paying account/organization owns usage, invoices and purchased capacity, not the individual who created a site. A new site, application or environment cannot reset its allowances. Keep unrelated customers separate.
  • Standalone Fans/Widgets access is included in Pro. Its included quantity remains open; do not silently assume it shares the 100,000 Sites session pool. Define both pools under the same billing owner and spending controls.
  • AI generation/revisions use the existing chat credits and accounting rules. Fan points remain separate. Sites continue hosting with active Pro, subject to the disclosed usage limits and funded overages.

Session counting and transparency

  • Define inactivity, maximum session duration, monthly boundary and cross-site recognition rules before billing goes live. Refreshes, multiple tabs, authentication redirects and a Site's embedded player must not create duplicate charges within a recognized session.
  • Combine cross-site activity when the same fan can be reliably recognized within that customer. Do not promise perfect anonymous cross-domain or cross-device recognition; do not use fingerprinting to fulfill that promise. Never merge unrelated customers' fan identities for billing.
  • External Widget billing counts meaningful fan use, not merely displaying a widget. Define the qualifying action and failed-attempt treatment before launch. Passive loads and rejected/failed attempts still need abuse and infrastructure limits even where they are not billable.
  • Use trustworthy server/delivery measurements; browser events alone cannot set bills. Show included capacity remaining, purchased capacity remaining, extra spending this month, and usage by site/application. Billing measurements are P0 in [Sites] Meter Sites operations with credit reservations and spending limits #2105; later campaign analytics [Sites] Measure Sites visits, interactions, and campaign attribution #2095 is not a prerequisite.

Automatic top-ups and purchased capacity

  • Automatic top-ups require explicit customer enablement showing the block size, price, monthly extra-spending ceiling and exhaustion behavior. A saved payment card alone is not approval. Only authorized billing members can raise the ceiling.
  • Consume included capacity first, then purchased capacity. Unused purchased capacity carries forward while Pro is active; do not buy another block while applicable purchased capacity remains. Define cancellation, downgrade, reactivation and retention treatment explicitly before selling blocks; do not silently erase purchased balances. Service continues through the paid subscription period.
  • Keep top-up price and block size open. Consider smaller blocks so a small overage does not require purchasing another 100,000 sessions. Customer approval of the included 100,000 allowance is not approval of a 100,000-session purchase block.
  • Collect payment before granting additional capacity. Allow at most one top-up purchase in progress per billing customer; retries and repeated payment notifications cannot charge or grant twice. Concurrent arrivals must consume one shared balance safely.
  • Notify the billing owner and relevant campaign operator before exhaustion, on each purchase and immediately on payment failure. Include current usage, remaining capacity, extra spend and recovery action. Final warning thresholds remain part of the launch configuration.

Campaign continuity and essential account access

  • At failed payment or an exhausted spending ceiling, keep a lightweight cached release page available with artwork/listening links while pausing new expensive interactive sessions. Maintain a short, explicitly bounded allowance for the Recoup services used by already-running games. Already-delivered game code may continue playing locally; enforcement restricts new admissions and future Recoup media, event, and points requests. Essential returning-user access follows its separate controls. An indefinitely open tab does not earn unlimited Recoup service.
  • External websites remain usable when Recoup limits are reached. Our widget reports its limited state and offers an appropriate fallback rather than blocking the host website.
  • If Recoup provides sign-in for the host application, preserve returning-user account access, recovery and disconnect separately from campaign capacity. Apply independent authentication abuse/rate limits; this is not unlimited free authentication. Define new-registration behavior at exhaustion before launch.
  • Preserve customer data and access to billing/export/recovery. Storage exhaustion blocks new uploads, not deletion of existing files. Subscription end-of-life and retention rules must be disclosed separately.

Cost and abuse protections required before first paid external release

  • Bound stored bytes, delivered media bytes, requests, event volume/retention and concurrent work per billing customer in addition to session counts. Purchased sessions do not purchase unlimited media or activity. Reserve upload capacity before accepting bytes; count abandoned/unattached uploads and preserve assets referenced by saved/published versions during cleanup.
  • Enforce direct asset delivery limits as well as page access. Public audio links cannot bypass customer restrictions; expiring URLs alone do not prevent repeated downloads. Avoid a database query for every file request.
  • Cache published content, with reliable invalidation on publish/unpublish/restriction; keep personalized identity/authentication data out of public caches. Serve limited-state pages cheaply.
  • Check customer capacity before admitting new expensive sessions. Explicitly bound exposure caused by concurrent arrivals, delayed measurements and payment processing. Do not promise an absolute zero-overshoot infrastructure bill.
  • Register authorized widget websites and issue short-lived sessions. Origin registration is one protection, not proof that traffic is legitimate. Keep secret/billing authority out of public widget keys.
  • Block or limit abusive traffic before costly application/database work. Pause repeated automatic purchases on suspicious spikes and alert the customer; do not automatically turn an apparent attack into successive charges. Provide a path to review suspected abusive charges. Excluding recognized bots from invoices does not eliminate their infrastructure cost.
  • Isolate customers so one viral campaign cannot exhaust shared service capacity. Provider-wide spending controls are emergency backups, not the primary customer limit.
  • Test simultaneous arrivals, duplicate/late payment notifications, failed payments, delayed usage reporting, direct-file access, full/expired sessions, cross-domain recognition, and recovery. Confirm exactly one intended purchase and bounded exposure.
  • Measure complete ordinary and expensive-but-legitimate sessions before setting top-up prices and resource allowances: anonymous visits, Spotify sign-in plus gameplay, long event-heavy sessions, hosted audio/replay, and external Widgets. Separately measure complex generation/revisions/failures. The 100,000-session Pro offer is approved; its economics still need validation before paid launch.

Implementation evidence and ownership

The reviewed local implementation serves public pages through the Recoup app/API without caching and stores uploads in Supabase's site-assets bucket, not Vercel Blob. File-size limits do not establish aggregate customer quotas. Spotify delivers its own audio; Recoup-hosted fallback audio consumes Recoup delivery resources.

#2105 owns billing, session admission and enforcement. #2104 owns customer/application access boundaries. #2111 preserves fan identity and essential access. #2108 supplies widget fallbacks and delivery enforcement. #2110 verifies the full policy in Recoup Sites and an independently hosted app. Existing dependency ordering is unchanged; identity contracts can be designed before billing is integrated.

Ordered implementation milestones

This ticket retains its existing completion dependencies and P0 paid-release scope. Track each milestone separately with tests/evidence; early contract work and capped non-billing pilots do not mark this ticket complete or bypass the paid-release gate.

  1. AI accounting: chat-compatible generation/revision reservations, usage capture, settlement/release and failure reconciliation; duplicate/retry tests and operation receipts.
  2. Usage measurement and admission: authoritative customer ownership, separate allowance pools, documented session rules and request/event limits; duplicate-counting, concurrent admission and bounded-exposure tests. Independent of P1 campaign analytics.
  3. Prepaid purchases: explicit opt-in, approved rates/block sizes, ceiling, one in-flight purchase, payment-confirmed capacity and receipts; duplicate/late/failed payment tests. Requires milestone 2.
  4. Delivery and storage protection: cached published/limited pages, aggregate upload/storage and enforceable media delivery, suspicious-traffic purchase pause and isolation; direct-link, abandoned-upload and burst tests. Uses milestone 2; can progress alongside milestone 3.
  5. Lifecycle and reconciliation: approved reset/carry-forward, cancellation/reactivation, registration-at-exhaustion and retention rules, notifications, returning-user continuity and correction/recovery; reconcile measured usage, provider cost and charges. Requires integrated milestones 1–4.

#2110 requires evidence for all five before paid external release. Contract design/mocks and an explicitly bounded non-billing pilot may proceed earlier, but no automatic overage charging or claim of launch readiness until lifecycle rules, allowances/rates and complete-session economics are approved. No new prices or limits are approved by this breakdown.

Context Engine consumer of shared AI accounting

Context Engine epic #2116 is another consumer of milestone 1 above. Context accounting #2123 adds context request/module/provider-attempt references, authorized request/pilot ceilings, stable settlement and reconciliation using the same wallet and usage ledger.

Implement common reservation/settlement primitives once here and reuse them there. A bounded context pilot requires demonstrated AI-accounting milestone behavior, but does not wait for this ticket's unrelated Sites session/hosting/top-up milestones. Track that milestone evidence explicitly; this does not mark all of #2105 complete or waive the existing paid Sites/Widgets release gate.

Existing song-analysis endpoint charging must be composed without a second orchestration debit. No new pricing, automatic top-up authority or parallel credit system is approved by the context epic.

Stable charge receipt prerequisite — October 8, 7:29 PM ET

Database87, head dd34cf0d956e5b585a68b864f2936fd08b3b11fa, and API976, head 59c11a2f, implement an opt-in stable charge receipt using the existing wallet and usage log. Same billing owner/work key/normalized payload returns the saved receipt; changed input conflicts. Database tests exercise duplicate/concurrent delivery, rollback and denied browser roles. The API adapter preserves uncertainty without retrying or generating another charge identity. No live caller is changed or connected.

Read-only production schema inspection found that credits_usage has an integer primary key but no unique account index. The new function rejects zero/multiple wallet records and debits the exact locked row ID, instead of calling the legacy account-wide debit. This prevents this operation from debiting multiple records, but does not repair existing records, constrain future legacy creation, or complete wallet identity enforcement. Before reservations, resolve that shared ownership invariant explicitly; do not infer duplicate production rows from a missing constraint. No real balances were read or changed.

Validation: eleven real transaction tests pass on disposable PostgreSQL 15/17; CI receipt checks pass on 15/16. Thirteen new API adapter cases plus eleven existing billing cases, full API lint, scoped format and diff checks pass. Remaining CI/review pending. Neither PR is merged or production-deployed. These receipts depend on retaining audit events unchanged. No new wallet, prices, top-ups, spending flags or provider calls.

This is only the duplicate-charge/reconciliation prerequisite. Remaining shared AI accounting: before-call reservations, request/pilot ceilings, interactions with refill/legacy writers, retained identities, provider-expense versus customer-charge reporting, and approved failure/cancellation policy. Existing debit behavior can still yield a negative balance; the new unused receipt function is not spending authorization. Next batch: inspect exact-head reviews/checks, fix valid findings and prepare explicit approval for these two PRs before rollout.

Charge receipt release verified — October 8, 10:33 PM ET

Sidney explicitly approved Database87 and API976. Database87 merged at f446984ab6933716b8fcc0aae8ef87493d84b9c7; normal Supabase integration applied 20261009000000_record_credit_charge_once. Production migration history, function body SHA-256 18f5657dc93408e03c0d8fc9731d73d11e5fc22924f98b5c8f41389155aa4ab9, invoker execution and pinned search path match the reviewed function. service_role may execute; anon/authenticated cannot. No charge function was invoked against a real wallet.

API976 was refreshed against released main for strict branch protection, retested (24 focused cases and full lint), and merged only after all final-head checks passed and no unresolved reviews remained. Checked head aeff080e6c21db7ddb18072219fc59187c1a0108; squash merge 348c481e0efb96293c66c305310222155ef8602f has the same tree. Vercel production dpl_AzNHCH2QQp99yzLxsLfJyFxQkDGm is READY; api.recoupable.dev maps to that commit. Unauthenticated release-case list still returns HTTP401.

No live caller uses the new charge adapter. No balances, prices, paid-provider flags or auto-top-up settings changed. This release supplies retry-safe charge identity, not a completed reservation/budget system or hosted payment test. Next approved batch: inspect wallet creation/refill writers and implement the smallest shared reservation prerequisite under #2105/#2123, preserving stable receipts and leaving paid Context collection off. Account-level wallet uniqueness, legacy writer compatibility, request/pilot limits, retained charge identities and explicit failure policies still need completion.

Mono257 now contains the released API/Database references at c422daa10bf8df9a34920b6a1ae4fac799044bad, still only three platform gitlinks and separately unapproved/unmerged. The heartbeat resumes after this approved release.

Single-wallet prerequisite — October 8, 10:51 PM ET

Database88, head fb4dd28ec3ee43053505651232e033531ac3d7ef, enforces one credits_usage row per non-null billing account. The migration changes no balances, usage receipts, prices or role grants. Existing duplicates fail installation for explicit review; it never merges/deletes balances. Installation has bounded lock/work timeouts. Nullable-owner behavior is preserved, and those rows are not valid charge payers.

A read-only aggregate production preflight found zero duplicate account groups and zero unassigned rows; no account identities or balances were returned. This is a point-in-time observation, not a deployed constraint. All 18 new/existing credit transaction tests pass on disposable PostgreSQL 15/17. Five new regression assertions failed before the migration, including all twelve concurrent initial inserts succeeding. CI on 15/16, Supabase preview and review are pending. Worktree .worktrees/database/credit-wallet-identity, branch codex/credit-wallet-identity, is pushed and clean. No merge or production migration; this PR requires its own approval.

Source audit confirms the API's initial-read fallback already rereads after a failed insert. A concurrent legacy admin grant may now fail and roll back instead of creating a second wallet; no grant retry is introduced. Remaining hazards: refill writes an absolute balance based on an earlier read; top-up increments and unaudited deductions also use read-modify-write. Account uniqueness does not fix those lost updates, coordinate old spenders with holds, or implement request/pilot ceilings. Inventory, rollout checks and limits are in the PR's tests/CREDIT-WALLET-IDENTITY.md.

Next bounded batch: inspect Database88 exact-head CI/preview/review, address valid findings, then prepare explicit approval. Continue scoped refill/legacy writer engineering afterward without enabling paid callers. No budget values, prices, provider collection, top-ups, financial mutations or duplicate Records intake occurred. Mono257 remains separately unapproved.

Activity

  1. added
    priority:P0Required for the first shared Sites and external Widgets release
    on Sep 19, 2026
  2. stringsofthemind-oss commented on Sep 22, 2026

    @stringsofthemind-oss
  3. sidneyswift commented on Nov 6, 2026

    @sidneyswift
    CollaboratorAuthor

    Shipped: retry-safe charge receipts on the existing wallet (recoupable/database#87, recoupable/api#976). No live caller uses them yet.

    Open and idle since early October: one wallet per account (recoupable/database#88), shared before-call reservations (recoupable/database#115, recoupable/api#1026) and atomic refill and top-up writers (recoupable/database#101, recoupable/api#1009).

    Release Packs shipped its own pack-only budget holds (recoupable/database#119, recoupable/api#1064) instead of the shared primitive this ticket asks for.

    Sites generation already deducts through the chat credit path after each model call, but has no reservation, ceiling or repair-attempt limit. All five milestones remain open.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    priority:P0Required for the first shared Sites and external Widgets release

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions