Skip to content

Enforce the free-tier monthly chat quota at every managed-AI boundary - #9581

Merged
undivisible merged 2 commits into
BasedHardware:mainfrom
skanderkaroui:fix/free-quota-boundary-enforcement
Aug 12, 2026
Merged

undivisible merged 2 commits into
BasedHardware:mainfrom
skanderkaroui:fix/free-quota-boundary-enforcement

Conversation

@skanderkaroui

@skanderkaroui skanderkaroui commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

Enforce the free-tier monthly chat quota at every managed-AI boundary

Problem

The free plan's 30-questions/month quota was enforced only on Python /v2/messages + /v2/voice-messages and the desktop ChatProvider path. Every Rust desktop-backend lane behind PaywalledAuthUser (chat completions, realtime session mint, agent ask, Gemini proxy, screen-activity search, TTS) checked only the trial paywall (TRIAL_PAYWALL_ENABLED, off by default), and several Python endpoints (daily-summary test/regenerate, goal progress extraction, app description generation, the omni realtime relay) had no quota check at all. A free user past the cap could keep driving managed LLM spend through voice conversations, agents, and those endpoints — realtime turns even counted toward the quota (desktop_chat_realtime) while never being blocked by it.

Root cause (failure class)

Quota enforcement was opt-in per call site instead of living at the boundary where the spend happens. Every new surface (realtime hub, agents, task chat, proxied lanes) shipped ungated by default. Recurrence evidence: the same class produced the desktop nested-map counting bug (71ccb35) and the counting/acceptance split (44220ae, a4cc12e) — counting kept getting fixed while enforcement coverage silently lagged.

Durable guard

  • Rust (src/quota.rs): ChatQuotaChecker wired into the shared PaywalledAuthUser extractor — every current and future route using that extractor is gated automatically. It consults the Python quota SoT (GET /v1/users/me/usage-quota) with the request's own bearer token (no duplicated counting logic), caches per-uid (60s fresh / 30s fail-open with last-known-good), blocks only plan_type=basic && allowed=false with 402 quota_exceeded. BYOK-active requests skip it; failures fail open + record_fallback. Kill switch: CHAT_QUOTA_ENFORCEMENT_ENABLED=false.
  • Python: enforce_chat_quota added to daily-summary test/regenerate, goals extract-progress, app description generators; omni relay closes 1008 quota_exceeded (BYOK-exempt). Deliberately not gated: /v2/voice-message/transcribe (existing in-code decision — STT-only, feeds the already-gated send) and MCP surfaces (separate auth surface; needs its own product decision — tracked below).
  • Desktop (Swift): realtime hub skips managed session warms when the limit is reached (quiet — popup still comes from the existing PTT/chat action gates). BYOK/client-direct exempt.

Verification

  • cargo test — 333 pass, incl. new unit tests: free-past-cap blocked; paid plans (unlimited/operator/architect) never blocked (overage stays Python-owned); missing fields / missing BASE_API_URL fail open.
  • PYTHON=… bash backend/test.sh — full suite exit 0, incl. new tests/unit/test_free_quota_gate_wiring.py (10 tests: each endpoint 402s before touching LLM/DB work when the gate raises; proceeds when allowed; relay closes 1008 and skips quota for BYOK).
  • scan_async_blockers.py, check_module_stub_pollution.py, scan_import_time_side_effects.py — clean.
  • OpenAPI: snapshots regenerated (additive optional X-App-Platform headers only); check_app_client_openapi_compatibility.py vs origin/main — passed.
  • xcrun swift build -c debug clean; swift test --filter FloatingBarUsageLimiterTests — 16 pass.
  • Live e2e (hermetic stack): Firestore + Auth emulators on isolated ports, this branch's Python backend (uvicorn) and Rust backend (cargo run, BASE_API_URL → local Python), free user seeded with backend_chat.quota_questions=31 in llm_usage/{today}:
    • GET /v1/users/me/usage-quota → used=31, limit=30, allowed=false (fresh user: allowed=true).
    • Over-cap user: daily-summary regenerate → 402, daily-summary test → 402, goals extract-progress → 402, app generate-description → 402; /v2/messages sanity → 200 canned "you've reached your 30 monthly chat question limit" reply (designed behavior).
    • Fresh user (control): regenerate → 404, generate-description(empty name) → 422 — both prove the gate passed and the endpoint proceeded.
    • Omni relay WS: over-cap → server log omni relay quota exceeded uid=…, socket closed pre-accept; fresh user passes the gate (no quota log).
    • Rust /v2/chat/completions with real emulator-issued Firebase ID tokens: over-cap → 402 {"error":"quota_exceeded"} through the full Rust extractor → Python quota endpoint → Firestore chain; fresh user → 200.

Deferred follow-ups (deliberate, high blast radius)

  • MCP/ChatGPT-connector surfaces: quota story needs a product decision (API-key auth, external clients).
  • get_monthly_chat_usage scans the whole llm_usage collection per check — needs a doc-ID range query or monthly aggregate (perf, not correctness).
  • /v1/users/me/usage-quota allowed semantics vs overage plans (desktop hard-blocks paid users past cap): separate fix, separate PR.

Independent review

Multi-agent review (8 finder angles: line-scan, removed-behavior, cross-file trace, reuse, simplification, efficiency, altitude, conventions; 3 verifier passes). Confirmed findings were all fixed in the follow-up commit: realtime-mint BYOK quota bypass (fake-fingerprint enrollment bought Omi-funded realtime), relay any-header BYOK exemption (deepgram-only header rode Omi's Gemini key), quota-exempting passive screen-activity sync (data-loss interaction with 7-day local retention) and the realtime usage-report telemetry route, Swift warm-guard scoping (paid overage users + barge-in replacement stranding), and fail-open hygiene (stale blocked=true replay, missing record_fallback, cache eviction). Refuted: 402-as-trial-paywall misrender; headerless-BYOK blocking (matches the deliberate per-request contract). Deferred with rationale: FastAPI Depends gate refactor (next-endpoint opt-in class — tracked below), get_monthly_chat_usage scan cost (below), Flutter 402 swallow on generator endpoints (client UX follow-up).

Product invariants

  • INV-CHAT-1 (path-based: RealtimeHubController.swift). The change is a managed-session warm guard only — no chat write-path, kernel projection, viewport, or pill-projection change; single-provider/single-timeline contract untouched. Guard tests: agent-logic-harness.sh --swift-only green.

Product invariants affected

  • INV-CHAT-1
  • INV-VOICE-1

Failure class

Failure-Class: none

(The fix closes free-tier quota enforcement gaps at managed-AI boundaries; no registered failure class covers quota/entitlement enforcement.)

@Git-on-my-level Git-on-my-level added security-review Touches auth, provider routing, secrets, or security-sensitive surfaces needs-maintainer-review Needs a human maintainer to sign off before merge labels Jul 12, 2026

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for tightening this — the direction looks valuable and it closes a real cost-control/security boundary gap across managed AI surfaces. The Rust extractor-level gate is the right kind of durable default for future desktop managed lanes, and the added Python call-site wiring/tests cover the obvious server endpoints.

I’m not approving this automatically because it touches quota/billing/security-sensitive enforcement paths and the current PR is still blocked by CI:

  • Formatting is failing: black --check --line-length 120 --skip-string-normalization would reformat backend/routers/apps.py.
  • This needs human maintainer review before merge because it changes when free-tier users are hard-blocked from voice/realtime/agent/managed AI lanes, including BYOK exemptions, fail-open behavior, cache TTLs, and client UX for quota_exceeded.
  • Before merge, please make sure maintainers are comfortable with the Rust side using /v1/users/me/usage-quota as the source of truth and with the intended fail-open behavior. For this kind of boundary, I’d also like to see/confirm route-level coverage that PaywalledAuthUser returns 402 on quota_exceeded and skips the quota call for validated BYOK, not only the pure JSON decision helper.

No signs of a supply-chain/security attack from the diff I reviewed; this is just a sensitive enforcement change that should not be auto-approved.

@kodjima33 kodjima33 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.

Free-tier quota enforcement across managed-AI boundaries — approve; auth/quota-sensitive + conflicts, leaving the merge decision to Nik.

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for the update here. I re-reviewed the current head after the latest CI run; the deterministic checks are now green, and the change still looks cohesive and well targeted at the free-tier managed-AI quota gap.

I’m leaving this as a positive signal rather than an approval because this is quota/billing/security-sensitive admission-control code across the Python API, Rust desktop backend, realtime voice, BYOK handling, and generated clients. Human maintainer sign-off is still warranted before merge, especially for the intended fail-open/cache behavior in the Rust quota checker and the exact BYOK exemptions for each managed/server-key lane.

I did not find signs of a supply-chain/security attack in the diff. The added Python wiring tests plus the Rust quota decision helper tests are helpful; if maintainers want another confidence bump before merge, route/extractor-level Rust coverage for PaywalledAuthUser returning 402 quota_exceeded for non-BYOK free users past cap, while preserving the intended BYOK/server-key-only lane behavior, would be the main area I’d add.

@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.

Approve

Quota finally lives at the spend boundary instead of playing whack-a-mole per route. Rust PaywalledAuthUser + Python wiring + BYOK that only exempts when this request rides the user’s key — deepgram-only free ride is dead, realtime mint re-checks quota_blocked. Fail-open + kill switch are the right blast-radius knobs. Rebase the one conflict in RealtimeHubController.swift and land; this is money-shaped correctness.

@undivisible

undivisible commented Jul 21, 2026 •

Copy link
Copy Markdown
Collaborator

Approved — quota at the spend boundary, not per-route roulette. BYOK exempt only when this request rides the user key; realtime mint re-checks quota_blocked. CI was fully green on the head I reviewed.

One conflict left: RealtimeHubController.swift. Rebase that single file, re-run the Swift filter for FloatingBarUsageLimiter if you touch it, then this is the first one I will merge — money-shaped correctness.

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for the continued work here. I’m changing the automation signal to changes requested for the current head, not because the quota-boundary direction looks wrong, but because this head is no longer merge-ready:

  • Public Developer API contract is failing: docs/api-reference/app-client-openapi.json is stale. Please rerun the app-client OpenAPI export and commit the regenerated file.
  • GitHub reports the PR as conflicting/dirty, and the desktop Swift aggregate check is red because its static/test jobs were cancelled rather than passing. Please resolve the conflict/rebase and rerun that lane.

The underlying quota fix still looks cohesive and security-relevant in the right way: moving enforcement to managed-AI spend boundaries, preserving BYOK only when the specific request rides user keys, and re-checking server-key realtime minting are all the right concerns. Human maintainer sign-off is still needed before merge because this touches quota/billing/security-sensitive behavior and fail-open/BYOK semantics, so I’m not approving this PR.


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

@undivisible
undivisible dismissed Git-on-my-level’s stale review July 29, 2026 06:50

Conflicts resolved: rebase on latest main, Rust quota files removed (Backend-Rust deleted in main), Python-side quota enforcement intact. Ready for merge.

@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.

Conflicts resolved. Quota enforcement at the spend boundary — apps, goals, daily summary, omni relay. Rust-side quota.rs removed since Backend-Rust was deleted in main; Python-side enforce_chat_quota wiring retained. BYOK exempt only when request rides user key. Ready to merge.

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for getting the quota-boundary change back to a mergeable branch shape. I’m still leaving this as changes requested for the current head, not because the quota enforcement direction looks wrong, but because this head is not merge-ready yet:

  • Desktop Swift Static & Test Contracts is failing: the required macOS manifest/static-contract phase reports FAIL: macOS manifest checks did not succeed (outcome=failure).
  • Desktop Swift Build & Tests is also red because it depends on that failed verification result.
  • The automation context for this run also flagged agent-instruction / agent-behavior documentation paths (.cursor/rules/arc.md, root/app/backend AGENTS.md/CLAUDE.md, and related agent docs). After fetching the current head locally against origin/main, I only see the focused quota/API diff and not those agent-doc files in the active local diff, so there is likely GitHub/cache/base-diff drift here. Please do not merge until that discrepancy is reconciled; if GitHub’s effective PR diff still includes those instruction files, they need explicit human maintainer review because they can change how Cursor/Codex/Claude-style agents behave in this repo.

What I verified locally: the current focused diff is 13 files / 442 additions / 82 deletions against origin/main, and backend/tests/unit/test_free_quota_gate_wiring.py passes (11 passed) using the available backend venv. The backend quota gate wiring itself looks cohesive: app description generation, goal extraction, daily summary test/regeneration, and omni realtime relay now gate before managed LLM work, with BYOK exempt only when this websocket session rides the user’s enrolled provider key.

Because this touches quota/billing/security-sensitive managed-AI admission behavior, fail-open/BYOK semantics, and the current checks are red, this still needs human maintainer sign-off before merge. I did not find signs of a malicious supply-chain/security attempt.


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

@undivisible

Copy link
Copy Markdown
Collaborator

The two Desktop Swift CI failures (Build & Tests, Static & Test Contracts) are flaky/pre-existing — this PR doesn't touch any Swift code. All 28 other checks pass clean.

@undivisible undivisible added human Human-authored pull request workflow-review Needs maintainer review for workflow, automation, hooks, or CI behavior docs-tooling Layer: Documentation, examples, dev tools privacy-review Touches user-data persistence, permissions, or privacy-sensitive surfaces labels Aug 10, 2026

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for continuing to tighten the managed-AI quota boundary. I’m requesting changes on the current head despite the existing human approval because I found one concrete managed-realtime bypass, and the desktop Swift checks are still red.

Blocking issue:

  • backend/routers/desktop_chat.py does the right thing for the new /v2/chat/completions surface: it calls enforce_chat_quota(uid, platform=x_app_platform) before metering and before dispatching to Anthropic, then records a desktop_chat_completions quota question. That matches the intended server-owned boundary.
  • backend/routers/desktop_realtime.py does not apply the same quota boundary. mint_session() only checks is_trial_paywalled(uid, "desktop") before minting OpenAI/Gemini realtime credentials, and report_usage() also only checks the trial paywall before recording usage. For a Free user already over the monthly chat-question cap, this can still mint a managed realtime session and only attempt to count/report after provider use. Because the realtime token is the admission boundary, it should call the shared chat quota enforcement/snapshot path before minting a managed provider token, with BYOK/paid-overage semantics matching the rest of chat.

Other reviewed surfaces:

  • desktop/windows/src/renderer/src/lib/chatQuotaGate.ts and desktop/windows/src/renderer/src/lib/chatQuotaGate.test.ts add the expected client-side pre-send/optimistic gate for typed and PTT bar sends, including fail-open behavior when the quota probe is unavailable. This is useful UX, but it cannot be the authoritative enforcement boundary.
  • .github/workflows/desktop-swift-ci.yml now collapses the static/test macOS work into Desktop Swift Static & Test Contracts and requires independent phase verdicts. The current PR checks show that new/changed path is failing (macOS manifest checks did not succeed), so this head is not merge-ready.
  • .github/actions/detect-changes/action.yml moves several hard-coded path decisions into scripts/pre_push_ci_prediction.py; that is a workflow-control change and should keep human sign-off.
  • .cursor/rules/arc.md adds Cursor/agent instructions that automatically call Arc/Notion/MCP tools and can write .env from Notion data. That changes how AI coding agents may behave in this repo. The guidance is broad enough that it needs maintainer review for safety/accuracy before merge.

I did not find evidence of a malicious supply-chain attempt, but this PR touches quota/billing/security-sensitive managed-AI admission, CI/workflow routing, and agent-instruction files. Please fix the realtime quota gate and get the desktop Swift checks green before merge; the workflow and agent-behavior changes also need human maintainer sign-off.


by AI on behalf of David — leaving this for human maintainer review because realtime quota enforcement, workflow routing, and agent-instruction changes need maintainer sign-off.

Gate user-initiated app, goal, daily-summary, and omni realtime managed-AI routes with the shared quota policy and refresh the app-client contracts.

Failure-Class: none

Verification:\n- backend/.venv/bin/python -m pytest tests/unit/test_free_quota_gate_wiring.py -q\n- python3 backend/scripts/generate_swift_openapi_types.py --check\n- python3 backend/scripts/generate_ts_openapi_types.py --check\n- PYTHON=backend/.venv/bin/python bash backend/test-preflight.sh
Apply the shared chat quota policy before realtime provider token minting and usage accounting so free users past the cap cannot reach managed realtime spend. Preserve paid overage and validated BYOK behavior through the shared helper.

Failure-Class: none

Verification:\n- backend/.venv/bin/python -m pytest backend/tests/unit/test_desktop_realtime.py -q\n- black --check --line-length 120 --skip-string-normalization backend/routers/desktop_realtime.py backend/tests/unit/test_desktop_realtime.py
@undivisible
undivisible force-pushed the fix/free-quota-boundary-enforcement branch from 772009f to 07c2000 Compare August 12, 2026 03:08
@undivisible
undivisible merged commit 2272662 into BasedHardware:main Aug 12, 2026
30 of 32 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs-tooling Layer: Documentation, examples, dev tools human Human-authored pull request needs-maintainer-review Needs a human maintainer to sign off before merge privacy-review Touches user-data persistence, permissions, or privacy-sensitive surfaces security-review Touches auth, provider routing, secrets, or security-sensitive surfaces workflow-review Needs maintainer review for workflow, automation, hooks, or CI behavior

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants