Files
HiveGrid-Wireframes/hivegrid-cloud/docs/improvement-plan/05-business-features/ai-cost-phase-2.md
T

205 lines
17 KiB
Markdown

# 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 + `TenantAICostSummary` als Datengrundlage für Quota-Check
- `05-business-features/feature-flags.md` (#53) — Soft-Degradation-Modus als Per-Tenant-Override via Flag
- `03-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 Quotas
- `07-chatbot/chatbot-v1.md` (#68) — V1 nutzt Quota-Check explizit
## Approach
Drei Layer:
1. **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").
2. **Pre-Call-Assertion** — `assertTenantAICreditAccess({ tenantId, capability, estimatedCostCents })` als Pure-Async-Function. Lookup current-spend aus Cache, vergleicht gegen Limits, wirft `AIQuotaExceededError` oder loggt Warning. Wird im `executeLLMCall`-Wrapper aus Phase 1 vor `run()` gerufen.
3. **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-degradation` pro 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
1. **Entitlements-Schema-Erweiterung** — `packages/entitlements/src/types.ts` um 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`
2. **`estimateLLMCost`-Helper** — `packages/ai/src/cost/estimate.ts` mit `estimateLLMCost({ provider, model, promptLength, maxOutputTokens })` returns cents. Promptlänge in Tokens via `countTokens`, 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`
3. **`assertTenantAICreditAccess`** — `packages/ai/src/cost/assert.ts` mit Signatur `assertTenantAICreditAccess({ tenantId, capability, estimatedCostCents }): Promise<{ allow: true } | { allow: false, reason: 'quota-exceeded' | 'capability-cap' | 'concurrency-limit', degradeTo?: { provider, model } }>`. Lookup: currentMonthSpend via SharedStore-Cache (Key `ai-quota:spend:{tenantId}:{YYYY-MM}`, 60s TTL, on miss DB-Aggregate aus `TenantAICostSummary` falls vorhanden sonst `AICostEvent`-Sum); concurrent-calls via SharedStore-Counter (Key `ai-quota:concurrent:{tenantId}`, increment vor Call, decrement nach). Wenn `currentSpend + estimatedCost > aiQuotaCentsPerMonth` und Tenant hat Flag `ai-quota-soft-degradation=true` → liefere `degradeTo` (cheaper Model in selber Provider-Familie). Sonst `allow: false`.
- Files: `packages/ai/src/cost/assert.ts`, Test
- Commit: `05/ai-cost-phase-2: tenant quota assertion with soft-degradation`
4. **Wrapper-Integration** — `executeLLMCall` aus Phase 1 erweitert: Aufruf von `assertTenantAICreditAccess` vor `run()`. Bei `allow: false` werfen `AIQuotaExceededError` (HTTP 402 wenn von Route gefangen). Bei `degradeTo` → 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`
5. **Route-Level-Error-Handling** — `apps/web/app/utils/errors/aiQuotaError.ts` mit `AIQuotaExceededError`-Class + Error-Boundary-Handler in betroffenen Routes liefert HTTP 402 mit JSON `{ error: 'ai-quota-exceeded', reason, upgradeUrl }`. Chatbot-Stream liefert SSE-Event `error: quota-exceeded` und 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`
6. **Alert-Cron** — `apps/worker/src/cron/ai-quota-alerts.ts` läuft alle 30 Min. Iteriert alle Tenants mit currentMonth-Spend > 80% Quota → schreibt `Notification` (in-app) + sendet Email (transactional via existing mail-provider) an Tenant-Admin-Role. Bei 100% → optional zusätzliche Aktion: wenn Tenant-Setting `aiAutoDisableOnQuota` gesetzt, Feature-Flag `ai-features-enabled` fü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`
7. **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-Flag `quota-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`
8. **Tenant-Admin-UI für Quota-Übersicht** — Erweiterung von `/app/$tenant/settings/ai-usage` aus 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`
9. **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`
10. **Doku** — `docs/features/ai-cost-billing.md` Phase-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`
## Test Requirements
- **Unit-Tests:**
- `estimate.test.ts` — Estimation verschiedener Promptlängen + maxOutput-Kombis
- `assert.test.ts` — alle Scenarios: under-quota → allow; over-quota hard → deny; over-quota soft → degrade; capability-cap-hit → deny; concurrency-limit-hit → deny
- `executeLLMCall.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.aiQuotaOverrideJson` Migration applied
- [ ] `estimateLLMCost` + `assertTenantAICreditAccess` exportiert + getestet
- [ ] `executeLLMCall` ruft 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.md` Phase-2-Section komplett
- [ ] `pnpm lint`, `pnpm typecheck`, `pnpm test` grü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=false` skippt `assertTenantAICreditAccess` (assert returnt immer `allow: true`). Sofortiger Production-Hotfix-Mechanismus.
- **Soft-Degradation-Off:** Feature-Flag `ai-quota-soft-degradation` global deaktivieren — Tenants fallen auf hartes Deny zurück (eventuell sicherer als wrong-model-degradation).
- **DB-Migration:** `Tenant.aiQuotaOverrideJson` ist 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:** `estimateLLMCost` rechnet 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:design` fü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
1. Branch `agent/05-ai-cost-phase-2` pushen → Coolify-Auto-Deploy
2. Migration `pnpm prisma migrate deploy` auf Staging
3. 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
4. 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-usage` quota-bars and the
admin `/admin/tenants/$id/ai-quota` override page are pushed to a
follow-up task — the engine is configurable today via direct
`Tenant.aiQuotaOverrideJson` writes and via the existing Phase-1
admin AI dashboard which already lists tenants.
- ~~**CLI helpers deferred.**~~ — **resolved 2026-05-20**: shipped
`toolctrl-cli ai-cost {show-quota,set-quota,reset-quota}`
(`packages/cli/src/commands/ai-cost/`). `set-quota`/`reset-quota`
merge over any existing override (per-capability caps merge
key-by-key), round-trip through `parseTenantAIQuotaOverride` before
writing, and each emits an `admin.ai.quota.override.{set,reset}`
audit event (`actorType: "cli"`). `show-quota` prints the resolved
quota + current-month spend; all three support `--json`. Pure
helpers (`inferPlanId`, `parseCapsArg`, `mergeQuotaOverride`, …) are
unit-tested — 17 cases. Note: `inferPlanId` here is a **hardened**
variant of the worker's `inferPlanIdFromSubscriptionProductId` — it
matches the plan word as a whole `[^a-z0-9]`-delimited segment, so a
Stripe `prod_…` id no longer misclassifies as `pro` (the worker's
raw `includes("pro")` has that latent bug).
- **HTTP-402 route wrapper deferred.** `AIQuotaExceededError` is
exported from `@toolctrl/ai/cost` and route action handlers can map
it directly today via `isAIQuotaExceededError(e)` — full chatbot
SSE-stream `error: quota-exceeded` event lands with the chatbot v1
task (#68) which will wire `executeLLMCall.args.quota` for the
first call site.
## Progress Log
- 2026-05-17 — `aac6e8db` — extend plan entitlements with ai quotas + `Tenant.aiQuotaOverrideJson` / `aiCostLastAlertedThreshold` / `aiCostLastAlertedPeriod` migration; 18 unit tests in `@toolctrl/entitlements`.
- 2026-05-17 — `708c95f6` — `estimateLLMCost` helper with `ESTIMATE_PROMPT_TOKEN_CAP` and per-kind max-output defaults; 8 unit tests.
- 2026-05-17 — `d247c67d` — `createSpendCache` 60s TTL helper with per-tenant invalidate, JSON payload validation, error-tolerant store calls; 9 unit tests.
- 2026-05-17 — `8b4e599c` — `assertTenantAICreditAccess` + `createConcurrencyCounter` + soft-degradation behind `ai-quota-soft-degradation` flag + `AI_QUOTA_ENFORCEMENT_ENABLED` killswitch; 14 unit tests.
- 2026-05-17 — `19452d2e` — `executeLLMCall` integrates the quota guard, swaps `(provider, model)` on soft-degrade, releases concurrency slot in `finally`; 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-alert` worker with on-demand + cron entry points, idempotent via `Tenant.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}` under `packages/cli/src/commands/ai-cost/`. Pure helpers in `quota-shared.ts` (segment-based `inferPlanId`, `parseCapsArg`, `mergeQuotaOverride`, `parseDegradeArg`, `currentPeriodRange`, `formatCents`) with 17 unit tests. `set-quota`/`reset-quota` write `admin.ai.quota.override.{set,reset}` audit events; `set-quota` merges over the existing override and re-validates via `parseTenantAIQuotaOverride` before persisting. `docs/features/ai-cost-quotas.md` gains an Operator-CLI section. Tenant + admin web UIs remain the only outstanding Phase-2 Deviation.