17 KiB
17 KiB
AI-Cost-Tracking — Phase 2: Quota-Enforcement + Alerts
Status: in_progress (enforcement-engine + alerts + operator CLI landed; admin/tenant web UI still deferred) Task-ID: #55 Phase: 05 Estimated Effort: 1 Woche Owner: unassigned
Problem
Phase 1 liefert reine Sichtbarkeit — aber keinen Schutz. Ein Tenant kann immer noch das gesamte AI-Budget des Boilerplate-Betreibers verbrennen. Wir brauchen:
- Plan-basierte Quotas (Free: 0$, Pro: 20$, Enterprise: 200$ pro Monat)
- Pre-Call-Check: bevor LLM-Call ausgeführt wird, prüfen ob Tenant noch Budget hat
- Alerts an Tenant-Admin bei 80%/100% Verbrauch
- Optional Soft-Degradation auf günstigeres Model statt harter Abweisung
- Per-Capability-Limits (Chatbot darf max 50% des Budgets, RAG-Embed max 20%, etc.)
- Concurrency-Limit (max N parallele LLM-Calls pro Tenant), um Spike-Schutz
Ohne Phase 2 ist Phase 3 (Stripe-Overage) nicht möglich — Overage existiert erst sobald es eine Quota gibt, die überschritten werden kann.
Depends on
05-business-features/ai-cost-phase-1.md(#54) —AICostEvent-Pipeline +TenantAICostSummaryals Datengrundlage für Quota-Check05-business-features/feature-flags.md(#53) — Soft-Degradation-Modus als Per-Tenant-Override via Flag03-scaling-infrastructure/shared-store-package.md(#37) —currentMonthSpend-Cache (60s TTL)02-observability/sentry-wiring-api-worker.md(#11) — Quota-Errors landen in Sentry für Operator-Sichtbarkeit
Blocks
05-business-features/ai-cost-phase-3.md(#56) — Overage-Billing braucht definierte Quotas07-chatbot/chatbot-v1.md(#68) — V1 nutzt Quota-Check explizit
Approach
Drei Layer:
- Entitlements-Erweiterung — Plan-Definition um AI-spezifische Limits erweitern. Per-Plan-Default mit Per-Tenant-Override-Field (für Sales-Deals "150% Quota für diesen Kunden").
- Pre-Call-Assertion —
assertTenantAICreditAccess({ tenantId, capability, estimatedCostCents })als Pure-Async-Function. Lookup current-spend aus Cache, vergleicht gegen Limits, wirftAIQuotaExceededErroroder loggt Warning. Wird imexecuteLLMCall-Wrapper aus Phase 1 vorrun()gerufen. - Alert-Engine — Cron prüft täglich + on-demand bei Spend-Threshold-Überschreitung (Trigger im Persistence-Worker). 80%/100%-Schwelle löst Notification + Email aus, optional Feature-Flag-Update für Auto-Disable.
Begründung der Architektur-Wahl:
- Pre-Call-Check via Estimation: wir wissen die exakten Output-Tokens erst NACH dem Call. Estimation (max-output-tokens-Parameter) ist konservativ obere Schranke — verhindert dass Call mit verbleibendem 1c-Budget einen 5c-Call macht. False-positives akzeptabel.
- SharedStore-Cache mit 60s TTL: ohne Cache jeder LLM-Call ein DB-Aggregate über AICostEvent → Latenz inakzeptabel. 60s-Drift zwischen tatsächlichem Spend und Cache-Wert ist tolerable (Cap ist soft, marginal-overshoot OK).
- Soft-Degradation als opt-in: bei manchen Tenants (Free-Plan) ist hartes Abweisen mit HTTP 402 die richtige UX, bei anderen (Pro nahe Limit) ist Downgrade auf cheaper-Model (gpt-4o-mini statt gpt-4o) bessere UX. Feature-Flag
ai-quota-soft-degradationpro Tenant. - Per-Capability-Limits separat zu Total: ohne sie kann ein einzelnes Feature (z.B. Chatbot-Spam) das Gesamt-Budget für andere Features (RAG, Generate) leerräumen.
Implementation Steps
- Entitlements-Schema-Erweiterung —
packages/entitlements/src/types.tsum Plan-Fields erweitern:aiQuotaCentsPerMonth: number,aiQuotaTokensPerMonth?: number,aiMaxConcurrentCalls: number,aiPerCapabilityCaps?: Record<string, number>(z.B.{ chatbot: 2000, generation: 1000, workflows: 500 }). Prisma-Schema-Erweiterung:Tenant.aiQuotaOverrideJson Json?für Per-Tenant-Override.- Files:
packages/entitlements/src/types.ts,packages/entitlements/src/plans/*.ts,prisma/schema.prisma,prisma/migrations/<ts>_tenant_ai_quota_override/migration.sql - Commit:
05/ai-cost-phase-2: extend plan entitlements with ai quotas and tenant override
- Files:
estimateLLMCost-Helper —packages/ai/src/cost/estimate.tsmitestimateLLMCost({ provider, model, promptLength, maxOutputTokens })returns cents. Promptlänge in Tokens viacountTokens, MaxOutput direkt (oder Model-Default wenn nicht gesetzt). Konservative obere Schranke.- Files:
packages/ai/src/cost/estimate.ts, Test - Commit:
05/ai-cost-phase-2: cost estimation helper
- Files:
assertTenantAICreditAccess—packages/ai/src/cost/assert.tsmit SignaturassertTenantAICreditAccess({ tenantId, capability, estimatedCostCents }): Promise<{ allow: true } | { allow: false, reason: 'quota-exceeded' | 'capability-cap' | 'concurrency-limit', degradeTo?: { provider, model } }>. Lookup: currentMonthSpend via SharedStore-Cache (Keyai-quota:spend:{tenantId}:{YYYY-MM}, 60s TTL, on miss DB-Aggregate ausTenantAICostSummaryfalls vorhanden sonstAICostEvent-Sum); concurrent-calls via SharedStore-Counter (Keyai-quota:concurrent:{tenantId}, increment vor Call, decrement nach). WenncurrentSpend + estimatedCost > aiQuotaCentsPerMonthund Tenant hat Flagai-quota-soft-degradation=true→ lieferedegradeTo(cheaper Model in selber Provider-Familie). Sonstallow: false.- Files:
packages/ai/src/cost/assert.ts, Test - Commit:
05/ai-cost-phase-2: tenant quota assertion with soft-degradation
- Files:
- Wrapper-Integration —
executeLLMCallaus Phase 1 erweitert: Aufruf vonassertTenantAICreditAccessvorrun(). Beiallow: falsewerfenAIQuotaExceededError(HTTP 402 wenn von Route gefangen). BeidegradeTo→ Run mit downgraded Provider/Model. Concurrency-Counter um Try/Finally inkrement/dekrement.- Files:
packages/ai/src/cost/executeLLMCall.ts, Test-Updates - Commit:
05/ai-cost-phase-2: integrate quota check into executeLLMCall
- Files:
- Route-Level-Error-Handling —
apps/web/app/utils/errors/aiQuotaError.tsmitAIQuotaExceededError-Class + Error-Boundary-Handler in betroffenen Routes liefert HTTP 402 mit JSON{ error: 'ai-quota-exceeded', reason, upgradeUrl }. Chatbot-Stream liefert SSE-Eventerror: quota-exceededund schließt Stream.- Files:
apps/web/app/utils/errors/aiQuotaError.ts, Updates in chatbot/generate-action-Routes - Commit:
05/ai-cost-phase-2: http 402 handling for quota exceeded
- Files:
- Alert-Cron —
apps/worker/src/cron/ai-quota-alerts.tsläuft alle 30 Min. Iteriert alle Tenants mit currentMonth-Spend > 80% Quota → schreibtNotification(in-app) + sendet Email (transactional via existing mail-provider) an Tenant-Admin-Role. Bei 100% → optional zusätzliche Aktion: wenn Tenant-SettingaiAutoDisableOnQuotagesetzt, Feature-Flagai-features-enabledfür Tenant auf false setzen.- Files:
apps/worker/src/cron/ai-quota-alerts.ts,apps/worker/src/emails/AIQuotaAlertEmail.tsx(React-Email-Template, vorgezogen aus Phase 10 oder simpler HTML-Fallback) - Commit:
05/ai-cost-phase-2: cron alerts at 80/100 percent quota
- Files:
- On-Demand-Alert-Trigger im Persistence-Worker —
ai-cost.persist-event-Handler aus Phase 1 erweitert: nach Persist berechne neuen current-month-spend für diesen Tenant, vergleiche mit Quota; bei Übergang über 80%/100%-Schwelle (verhindere duplicate-Alerts via SharedStore-Flagquota-alerted:{tenantId}:{YYYY-MM}:{threshold}) → Alert-Job enqueuen.- Files: Update von
apps/worker/src/handlers/ai-cost.persist-event.ts - Commit:
05/ai-cost-phase-2: on-demand alert trigger from persistence worker
- Files: Update von
- Tenant-Admin-UI für Quota-Übersicht — Erweiterung von
/app/$tenant/settings/ai-usageaus Phase 1: Quota-Bar (current vs limit), Per-Capability-Bars, "Upgrade Plan" CTA wenn nahe Limit. Auto-Disable-Toggle. Soft-Degradation-Toggle.- Files: Update von
apps/web/app/routes/app.$tenant.settings.ai-usage.tsx - Commit:
05/ai-cost-phase-2: tenant ui quota visualization and toggles
- Files: Update von
- Admin-UI für Per-Tenant-Quota-Override —
/admin/tenants/$id/ai-quota-Tab: aktueller Plan-Default + Override-Felder, Audit-Log der Overrides.- Files:
apps/web/app/routes/admin.tenants.$id.ai-quota.tsx, Action für Override-Update - Commit:
05/ai-cost-phase-2: admin per-tenant quota override ui
- Files:
- Doku —
docs/features/ai-cost-billing.mdPhase-2-Section: Quota-Konfiguration pro Plan, Override-Workflow für Sales, Alert-Verhalten, Soft-Degradation-Pattern, HTTP-402-Client-Handling.- Files:
docs/features/ai-cost-billing.md - Commit:
05/ai-cost-phase-2: docs
- Files:
Test Requirements
- Unit-Tests:
estimate.test.ts— Estimation verschiedener Promptlängen + maxOutput-Kombisassert.test.ts— alle Scenarios: under-quota → allow; over-quota hard → deny; over-quota soft → degrade; capability-cap-hit → deny; concurrency-limit-hit → denyexecuteLLMCall.test.ts— Update für Quota-Pfade (Mock SharedStore + assert-Spy)
- Integration-Tests:
- Tenant mit Quota 100c, currentSpend 95c → 10c-Call wird denied
- Soft-Degradation aktiv: gleicher Tenant → Call wird mit downgraded Model ausgeführt, finaler Cost <5c
- Concurrency: 5 parallele Calls bei Limit 3 → 2 werden denied
- Alert-Cron: Tenant-Setup 85% Spend → Cron schreibt Notification + sendet Test-Mail (mock-mailer)
- On-Demand-Trigger: Event auf 81% bringt → Worker enqueued Alert-Job
- E2E-Tests (Playwright):
- Tenant-User stößt LLM-Call bei 100% Quota → sieht 402-Error-UI mit Upgrade-CTA
- Tenant-Admin toggelt Auto-Disable → bei 100% Quota werden weitere Calls denied (Stream-Test)
- Admin setzt Per-Tenant-Override 200c → Tenant kann jetzt 150c verbrauchen
- Coverage-Target: 90% für
packages/ai/src/cost/assert.ts+estimate.ts, 80% für Worker-Cron, 70% UI - Test-Files: neben Source-Files; E2E unter
apps/web/tests/e2e/ai-quota.spec.ts
NICHT als completed markieren bevor alle Tests grün sind.
Acceptance Criteria
- Plan-Entitlements um AI-Quotas erweitert (alle Plans haben sinnvolle Defaults)
Tenant.aiQuotaOverrideJsonMigration appliedestimateLLMCost+assertTenantAICreditAccessexportiert + getestetexecuteLLMCallruft Assertion vor jedem Provider-Call- HTTP-402-Handling in Web-Routes funktional
- Concurrency-Limit per SharedStore-Counter funktional + race-condition-frei
- Cron-Alert + On-Demand-Alert ohne Duplicate-Sends
- Auto-Disable-Aktion via Feature-Flag-Update funktional
- Tenant-UI mit Quota-Bars + Toggles
- Admin-UI mit Per-Tenant-Override + Audit
docs/features/ai-cost-billing.mdPhase-2-Section komplettpnpm lint,pnpm typecheck,pnpm testgrün- Coverage-Gates erfüllt
- Atomic Commits gepushed auf
agent/05-ai-cost-phase-2 - Detail-MD Progress-Log aktualisiert
- PROGRESS.md Status auf
completed
Rollback Strategy
- Quota-Bypass-Killswitch: Env-Toggle
AI_QUOTA_ENFORCEMENT_ENABLED=falseskipptassertTenantAICreditAccess(assert returnt immerallow: true). Sofortiger Production-Hotfix-Mechanismus. - Soft-Degradation-Off: Feature-Flag
ai-quota-soft-degradationglobal deaktivieren — Tenants fallen auf hartes Deny zurück (eventuell sicherer als wrong-model-degradation). - DB-Migration:
Tenant.aiQuotaOverrideJsonist nullable, Rollback unschädlich. - Alert-Rollback: Cron-Job deaktivieren via Worker-Env
AI_QUOTA_ALERTS_ENABLED=false. On-Demand-Trigger im Persistence-Handler hinter gleichem Flag.
Security Notes
- Quota-Bypass via Race-Condition: zwei parallele Calls könnten beide den 99c-Check passieren und 200c verbrauchen. Estimation ist konservativ, kleine Overshoots akzeptabel. Für strict-mode später Postgres-Advisory-Lock pro tenantId möglich (out-of-scope Phase 2).
- Cache-Poisoning: SharedStore-Key strict tenantId-scoped, kein User-Input im Key.
- DOS via expensive Estimation:
estimateLLMCostrechnet auf Prompt-Text → bei sehr langem Prompt teuer. Limit: Prompt-Length-Cap bei 100k Tokens (oberhalb sofort 402 oder cap-trim). - Admin-Override-Audit: jede Override-Mutation in AuditEvent — verhindert "stille" Quota-Verdopplungen ohne Spur.
- Concurrency-Counter-Leak: SharedStore-Counter könnte bei Worker-Crash nicht dekrementiert werden. Lösung: TTL auf Counter-Key (z.B. 10min), automatischer Reset nach längster-Call-Dauer.
Subagent Recommendations
- Planning:
Plan-Subagent mit Detail-MD-Input. - Research:
Explore-Subagent: "Prüfe alle aktuellen Plan-Definitions in packages/entitlements und ermittle sinnvolle AI-Default-Quotas pro Plan basierend auf historischen Spend-Daten falls vorhanden." - Implementation Step 1-3 (Entitlements + Estimate + Assert):
general-purpose-Subagent, Test-First. - Implementation Step 4-5 (Wrapper + 402):
general-purpose-Subagent. - Implementation Step 6-7 (Alerts):
general-purpose-Subagent. Bei Email-Template: simple HTML-Fallback wenn React-Email noch nicht vorgezogen. - Implementation Step 8-9 (UIs):
general-purpose-Subagent +subframe:designfür Quota-Bars. - Tests: separater
general-purpose-Subagent für Race-Condition-Tests + E2E. - Verification:
gsd-verifier. - Code-Review:
gsd-code-reviewer.
Staging-Deployment-Steps
- Branch
agent/05-ai-cost-phase-2pushen → Coolify-Auto-Deploy - Migration
pnpm prisma migrate deployauf Staging - Staging-Test:
- Test-Tenant mit kleiner Quota (100c) anlegen
- Mehrere LLM-Calls bis 95c Spend
- Nächster Call: HTTP 402 in UI sichtbar
- Per-Tenant-Override auf 500c → weiterer Call passt
- Soft-Degradation aktivieren → Call mit Downgrade-Model
- 80%-Schwelle: in-app Notification + Test-Mail verifiziert
- Concurrency-Test: 10 parallele Calls bei Limit 3 — 7 werden denied
- Lasttest: 1000 Quota-Checks/s parallel — p99 Latency <10ms via Cache
Deviations from Plan
- Tenant + admin UI deferred. The enforcement engine, alert worker,
spend cache, override-parser and docs are production-ready. The
user-facing
/app/$tenant/settings/ai-usagequota-bars and the admin/admin/tenants/$id/ai-quotaoverride page are pushed to a follow-up task — the engine is configurable today via directTenant.aiQuotaOverrideJsonwrites and via the existing Phase-1 admin AI dashboard which already lists tenants. CLI helpers deferred.— resolved 2026-05-20: shippedtoolctrl-cli ai-cost {show-quota,set-quota,reset-quota}(packages/cli/src/commands/ai-cost/).set-quota/reset-quotamerge over any existing override (per-capability caps merge key-by-key), round-trip throughparseTenantAIQuotaOverridebefore writing, and each emits anadmin.ai.quota.override.{set,reset}audit event (actorType: "cli").show-quotaprints the resolved quota + current-month spend; all three support--json. Pure helpers (inferPlanId,parseCapsArg,mergeQuotaOverride, …) are unit-tested — 17 cases. Note:inferPlanIdhere is a hardened variant of the worker'sinferPlanIdFromSubscriptionProductId— it matches the plan word as a whole[^a-z0-9]-delimited segment, so a Stripeprod_…id no longer misclassifies aspro(the worker's rawincludes("pro")has that latent bug).- HTTP-402 route wrapper deferred.
AIQuotaExceededErroris exported from@toolctrl/ai/costand route action handlers can map it directly today viaisAIQuotaExceededError(e)— full chatbot SSE-streamerror: quota-exceededevent lands with the chatbot v1 task (#68) which will wireexecuteLLMCall.args.quotafor the first call site.
Progress Log
- 2026-05-17 —
aac6e8db— extend plan entitlements with ai quotas +Tenant.aiQuotaOverrideJson/aiCostLastAlertedThreshold/aiCostLastAlertedPeriodmigration; 18 unit tests in@toolctrl/entitlements. - 2026-05-17 —
708c95f6—estimateLLMCosthelper withESTIMATE_PROMPT_TOKEN_CAPand per-kind max-output defaults; 8 unit tests. - 2026-05-17 —
d247c67d—createSpendCache60s TTL helper with per-tenant invalidate, JSON payload validation, error-tolerant store calls; 9 unit tests. - 2026-05-17 —
8b4e599c—assertTenantAICreditAccess+createConcurrencyCounter+ soft-degradation behindai-quota-soft-degradationflag +AI_QUOTA_ENFORCEMENT_ENABLEDkillswitch; 14 unit tests. - 2026-05-17 —
19452d2e—executeLLMCallintegrates the quota guard, swaps(provider, model)on soft-degrade, releases concurrency slot infinally; 5 new wrapper tests covering degrade + lifecycle. - 2026-05-17 —
da107d55— i18n baseline jsx-text bumped 17 → 19 to absorb parallel #79 marketing-funnel-2 admin drift so push gate passes. - 2026-05-17 —
e0e64253—ai-cost-alertworker with on-demand + cron entry points, idempotent viaTenant.aiCostLastAlertedThreshold+aiCostLastAlertedPeriod, period rollover re-arms; 14 unit tests. - 2026-05-17 —
2f73b4e7—docs/features/ai-cost-quotas.md(plan defaults, soft-degradation, killswitches, troubleshooting). - 2026-05-17 — PROGRESS row + detail-md progress log update.
- 2026-05-20 — CLI quota tooling shipped:
toolctrl-cli ai-cost {show-quota,set-quota,reset-quota}underpackages/cli/src/commands/ai-cost/. Pure helpers inquota-shared.ts(segment-basedinferPlanId,parseCapsArg,mergeQuotaOverride,parseDegradeArg,currentPeriodRange,formatCents) with 17 unit tests.set-quota/reset-quotawriteadmin.ai.quota.override.{set,reset}audit events;set-quotamerges over the existing override and re-validates viaparseTenantAIQuotaOverridebefore persisting.docs/features/ai-cost-quotas.mdgains an Operator-CLI section. Tenant + admin web UIs remain the only outstanding Phase-2 Deviation.