Skip to content

fix(backend): gate app generate-prompts on the free chat quota - #12749

Merged
undivisible merged 1 commit into
BasedHardware:mainfrom
aryanorastar:fix/12715-generate-prompts-quota
Sep 5, 2026
Merged

undivisible merged 1 commit into
BasedHardware:mainfrom
aryanorastar:fix/12715-generate-prompts-quota

Conversation

@aryanorastar

@aryanorastar aryanorastar commented Sep 4, 2026 •

Copy link
Copy Markdown
Collaborator

Follow-up to #12739, which fixed #12715.

What changed and why

/v1/app/generate-prompts runs the same billable Features.APP_GENERATOR spend as the other AI-app generators, but sat behind auth.with_rate_limit(...) alone with no enforce_chat_quota call:

async def generate_sample_prompts_endpoint(
    uid: str = Depends(auth.with_rate_limit(auth.get_current_user_uid, "apps:generate_prompts")),
):
    ...
    with track_usage(uid, Features.APP_GENERATOR):

track_usage attributes spend; it does not block. #12739 closed /v1/app/generate and /v1/app/generate-icon, and correctly left this one alone because it was outside #12715's scope. That makes it the last ungated APP_GENERATOR route in the router — a free user past the monthly cap can keep drawing LLM-generated app suggestions from it indefinitely.

Correction. This originally read "the last ungated managed-spend route in the router", which is wrong, as Git-on-my-level caught. /v1/personas/twitter/initial-message (apps.py:1744) also runs tracked LLM spend, under Features.PERSONA, and is gated by neither a quota nor a rate limiter — strictly less protected than this route was. It is out of scope here and tracked separately; the claim above is now scoped to APP_GENERATOR, which it can actually support.

This adds the same gate the other four generators use, in the shape #12739 established: enforce_chat_quota(uid, platform=x_app_platform) before any provider work, with the X-App-Platform header accepted so the desktop trial paywall applies here too rather than silently never firing on platform=None.

Rate limiting and quota enforcement solve different problems, which is why one does not substitute for the other: the limiter bounds request frequency, the quota bounds monthly billable spend against the user's plan.

On the generated-client churn

The six generated artifacts change by a reordering, not an addition. X-App-Platform was already advertised on this route through the shared auth dependency; declaring it explicitly on the handler moves it ahead of the injected headers. That is exactly the ordering the sibling routes already have:

POST /v1/app/generate              ['X-App-Platform', 'authorization', 'X-Device-Id-Hash', 'X-App-Version']
POST /v1/app/generate-icon         ['X-App-Platform', 'authorization', 'X-Device-Id-Hash', 'X-App-Version']
POST /v1/app/generate-description  ['X-App-Platform', 'authorization', 'X-Device-Id-Hash', 'X-App-Version']
GET  /v1/app/generate-prompts      ['X-App-Platform', 'authorization', 'X-Device-Id-Hash', 'X-App-Version']  ← this PR

So the route converges on the router's existing convention rather than introducing a new shape. No wire-level parameter is added or removed.

How it was verified

Mutation-checked — with the gate removed, both new tests fail:

2 failed, 14 deselected
  • pytest tests/unit/test_free_quota_gate_wiring.py — 16 passed
  • scripts/openapi_runner.sh scripts/export_openapi.py --surface app-client --check — up to date
  • Swift, TypeScript (×4) and Dart generators re-run; only the four TS/Swift artifacts changed, Dart models unaffected

Tests

  • test_generate_prompts_blocked_past_cap — asserts the 402 propagates and that get_llm is never called, so the gate precedes spend rather than merely accompanying it
  • test_generate_prompts_proceeds_within_cap — asserts the proceed path still reaches the provider, and pins enforce_chat_quota('u1', platform='macos') so the platform argument cannot be silently dropped

Honest gaps

  • No live free-tier Firebase/Redis integration run (hermetic gate patching only).
  • Physical / on-device smoke not run — backend-only change.

Failure-Class: none

Line-Count-Exception: backend/routers/apps.py | 2468 -> 2472 | Four lines: the X-App-Platform header parameter and the enforce_chat_quota call, matching the four sibling generators in this router. Splitting the file is a larger refactor than a one-gate wiring fix should carry.

Review in cubic

/v1/app/generate-prompts runs the same billable Features.APP_GENERATOR spend
as its siblings but sat behind rate limiting alone, with no enforce_chat_quota
call. BasedHardware#12739 closed /v1/app/generate and /v1/app/generate-icon for BasedHardware#12715 and
correctly left this one, since it was outside that issue's scope. It is now the
only ungated managed-spend route in the router: a free user past the monthly cap
can still draw LLM-generated app suggestions from it indefinitely.

Add the same gate the other four generators use, in the same shape BasedHardware#12739
established -- enforce_chat_quota(uid, platform=x_app_platform) before any
provider work, with the X-App-Platform header accepted so the desktop trial
paywall applies here too rather than silently never firing on platform=None.

The generated-client churn is a reordering, not an addition. X-App-Platform was
already advertised on this route through the shared auth dependency; declaring
it explicitly moves it ahead of the injected headers, which is exactly the
ordering /v1/app/generate, /v1/app/generate-icon and /v1/app/generate-description
already have. This route now matches its siblings byte for byte.

Verified by mutation: with the gate removed, both new tests fail.

Failure-Class: none

Co-Authored-By: Claude Opus 5 <[email protected]>
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2 issues found across 8 files

Confidence score: 2/5

  • In backend/routers/apps.py, free users can bypass quota enforcement by calling only /v1/app/generate-prompts, allowing usage beyond the intended limit—include app-generator telemetry in the chat quota snapshot and atomically increment the shared quota_questions counter.
  • In backend/routers/apps.py, synchronous Firestore quota reads run on the event loop for ordinary requests, which can block concurrent request handling—offload the quota check through run_blocking on the database executor.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="backend/routers/apps.py">

<violation number="1" location="backend/routers/apps.py:1545">
P2: For ordinary requests, this line performs synchronous Firestore quota reads on the event loop before awaiting the LLM. Offload the blocking quota check through `run_blocking` on the database executor.</violation>

<violation number="2" location="backend/routers/apps.py:1545">
P1: When a free user calls only `/v1/app/generate-prompts`, this gate never sees those calls because app-generator telemetry is not part of the chat quota snapshot. Increment the shared `quota_questions` counter atomically for app-generation requests, or make the quota calculation include app-generator usage.</violation>
</file>

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread backend/routers/apps.py
import json

# User-initiated LLM generation — same free-tier gate as chat (402 past cap).
enforce_chat_quota(uid, platform=x_app_platform)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: When a free user calls only /v1/app/generate-prompts, this gate never sees those calls because app-generator telemetry is not part of the chat quota snapshot. Increment the shared quota_questions counter atomically for app-generation requests, or make the quota calculation include app-generator usage.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/routers/apps.py, line 1545:

<comment>When a free user calls only `/v1/app/generate-prompts`, this gate never sees those calls because app-generator telemetry is not part of the chat quota snapshot. Increment the shared `quota_questions` counter atomically for app-generation requests, or make the quota calculation include app-generator usage.</comment>

<file context>
@@ -1540,6 +1541,9 @@ async def generate_sample_prompts_endpoint(
     import json
 
+    # User-initiated LLM generation — same free-tier gate as chat (402 past cap).
+    enforce_chat_quota(uid, platform=x_app_platform)
+
     system_prompt = """Generate 5 creative and diverse ideas for apps that are either:
</file context>

Comment thread backend/routers/apps.py
import json

# User-initiated LLM generation — same free-tier gate as chat (402 past cap).
enforce_chat_quota(uid, platform=x_app_platform)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: For ordinary requests, this line performs synchronous Firestore quota reads on the event loop before awaiting the LLM. Offload the blocking quota check through run_blocking on the database executor.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/routers/apps.py, line 1545:

<comment>For ordinary requests, this line performs synchronous Firestore quota reads on the event loop before awaiting the LLM. Offload the blocking quota check through `run_blocking` on the database executor.</comment>

<file context>
@@ -1540,6 +1541,9 @@ async def generate_sample_prompts_endpoint(
     import json
 
+    # User-initiated LLM generation — same free-tier gate as chat (402 past cap).
+    enforce_chat_quota(uid, platform=x_app_platform)
+
     system_prompt = """Generate 5 creative and diverse ideas for apps that are either:
</file context>
Suggested change
enforce_chat_quota(uid, platform=x_app_platform)
await run_blocking(db_executor, enforce_chat_quota, uid, platform=x_app_platform)

@Git-on-my-level

Copy link
Copy Markdown
Member

Verified against head 3341508 — this closes the remaining spend leak from the #12739 sweep, in exactly the shape that PR established. Notes per file:

backend/routers/apps.py — enforce_chat_quota(uid, platform=x_app_platform) at line 1545 lands before get_llm and the track_usage(uid, Features.APP_GENERATOR) block (line 1564), so past-cap users are cut off before any provider work. The X-App-Platform param mirrors the four sibling generators (lines 1493/1516/1600/1647), the import already exists from #12739, and with_rate_limit is retained — limiter and quota stay orthogonal, as the description argues. All five APP_GENERATOR routes now gate identically.

backend/tests/unit/test_free_quota_gate_wiring.py — test_generate_prompts_blocked_past_cap asserts both the 402 and llm.assert_not_called(), proving the gate precedes spend rather than merely accompanying it; test_generate_prompts_proceeds_within_cap pins platform='macos' so the header argument can't be silently dropped and confirms the provider is still reached under cap. Consistent with the suite's existing module-seam approach.

Generated artifacts (desktop/macos/.../OmiApi.generated.swift, desktop/windows/.../omiApi.generated.ts, web/admin/..., web/app/src/lib/omiApi.generated.ts, web/personas-open-source/src/lib/omiApi.generated.ts) — reorder-only: X-App-Platform is now serialized ahead of authorization, matching the sibling routes; no parameter added or removed at the wire level. docs/api-reference/app-client-openapi.json — the same two-parameter swap on GET /v1/app/generate-prompts, and the public API contract check is green.

Two notes on the earlier automated review's suggestions, for the record — neither is a defect introduced by this diff:

One small accuracy nit on the description: "the last ungated managed-spend route in this router" — /v1/personas/twitter/initial-message (apps.py:1745) still runs Features.PERSONA-tracked LLM spend with no quota gate. Reasonable to leave out of this PR's scope, but it may deserve the same treatment in a follow-up.

Thanks for the thorough write-up, the mutation check, and the regression tests — tidy completion of the sweep. This is billing/quota enforcement surface, so maintainer sign-off before merge; no concerns from my side beyond the notes above.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level Git-on-my-level added positive-signal Automation verified a genuine fix/quality contribution backend Backend Task (python) labels Sep 4, 2026

@undivisible undivisible left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: approve

Closes the last ungated Features.APP_GENERATOR route in this router. Gate shape matches the #12739 siblings: X-App-Platform header + enforce_chat_quota(uid, platform=…) before any provider work, with tests that pin 402 before get_llm and the proceed path. Generated-client churn is header reordering only — matches sibling OpenAPI order. CI green across backend unit, hermetic, Swift, Windows/Linux smokes, OpenAPI.

On cubic

  • P1 (quota counter / prompts-only bypass): not a regression introduced here — same enforce_chat_quota + track_usage(APP_GENERATOR) pairing the other generators already use. If app-generator spend should increment quota_questions, that is a shared follow-up across the router, not a blocker for wiring parity.
  • P2 (sync Firestore on event loop): same call pattern as the sibling generators; out of scope for this one-route fix.

Not merging from here.

@aryanorastar

Copy link
Copy Markdown
Collaborator Author

The accuracy nit is right, and I have corrected the description in place rather than leaving the wrong claim standing above a correction.

"The last ungated managed-spend route in this router" was wrong. It is the last ungated APP_GENERATOR route. /v1/personas/twitter/initial-message (apps.py:1744) also runs tracked LLM spend under Features.PERSONA and has no quota gate.

I enumerated every track_usage site in the router rather than fix the one you named, since I had already made this claim twice — here and when closing #12717 — and a third partial version would be worse than the first:

route feature quota gate rate limit
POST /v1/app/generate-description APP_GENERATOR yes no
POST /v1/app/generate-description-emoji APP_GENERATOR yes no
POST /v1/app/generate APP_GENERATOR yes no
POST /v1/app/generate-icon APP_GENERATOR yes no
GET /v1/app/generate-prompts APP_GENERATOR this PR yes
GET /v1/personas/twitter/initial-message PERSONA no no

Worth noting it is less protected than this route was, not equally: generate-prompts at least sat behind auth.with_rate_limit(...), which bounded call frequency while the quota was missing. The personas route has neither bound.

Filed as #12781, split into the wiring step (give it the rate limiter its siblings have — no policy decision needed) and the policy question you and cubic both raised, which is whether generator and persona spend should increment quota_questions at all. As you note, today none of these routes accrue to the counter they are gated on, so a generators-only user never crosses the cap. That one needs an owner rather than a drive-by fix, so I have not touched it.

No code change here — the diff is unchanged and still the four lines. Only the description was inaccurate.

@undivisible
undivisible merged commit 7b2b204 into BasedHardware:main Sep 5, 2026
48 of 49 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend Backend Task (python) positive-signal Automation verified a genuine fix/quality contribution

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Free-tier chat quota not enforced on /v1/app/generate and /v1/app/generate-icon

3 participants