Context
The admin monitoring page read a JSON blob in AppSetting seeded with sample rows; nothing wrote real calls to it (#116). The free monthly AI quota set in /admin/billing/plans was never checked, charged or reset (#115); the only limit was AiClient's global daily token budget, whose refusal the tutor turned into a generic "AI đang bận" reply. The M6 tables (AiGeneration, QuotaPeriod, AiCreditBalance, AiUsageLedger) existed but were unused.
Decision
- Attribution travels with the call.
CallOptions.attribution(action,userId,courseId,generationId,quotaUnits,requestId,jobId) is echoed unchanged into theai.callevent, which also gainsrequestHash(SHA-256 of the normalised request, the cache key's hash). Identifiers only, never content, and not part of the cache key. - One subscriber per process.
AiUsageRecorder(packages/ai) turns eachai.callevent into anAiUsageRecord, writes it off the call's path, and never throws into it;flush()for tests and shutdown. The api builds it inAiService(every client it creates, fallback ones included) and fillsuserId/requestIdfrom the request context; the worker builds it inruntime.tsand flushes it before Prisma disconnects. Each app maps the record to anAiGenerationrow with its own Prisma client and prices it withcalculateTokenCostUsd. - Monitoring reads
AiGeneration. Filters and paging run in SQL; metrics aggregate at most 50 000 rows of the range. The sample rows are gone from the API. - Quota buckets: this ICT month's
QuotaPeriod(Asia/Ho_Chi_Minh, UTC+7, no DST:periodStart= the 1st,periodEnd= the last day, inclusive), then the never-expiringAiCreditBalance. A period is opened on first use with the role's free allowance fromai.pricing(student / instructor), snapshotted for that month, with aGRANT_FREEledger rowfree:<userId>:<YYYY-MM>. A new month is a new row: the quota resets without a cron. Admins and zero-cost actions are exempt. - Charge before the call, atomically.
AiQuotaService.reserveruns one conditional `UPDATE … SET creditsUsed = creditsUsed + cost WHERE … AND creditsUsed + cost <= creditsGranted
RETURNING per bucket, plus a SPEND ledger row spend:<generationId>, in one transaction. The UPDATE's row lock serialises concurrent charges and each re-checks the condition, so two calls at the edge cannot both pass. Nothing covers the cost → 429 AI_QUOTA_EXCEEDED, "Bạn đã dùng hết hạn mức AI tháng này … cấp lại vào ngày 01/MM/YYYY", before any message is stored or any provider called. The answer call carries the same generationId`, so its usage row and the ledger key name each other.
- Refund what was not answered. The tutor refunds (
REFUND,refund:<generationId>, once) when the model produced no answer: retrieval down, nothing in the material, provider failure, or an error after the call. A failed call recordsquotaUnits = 0. If a fallback provider answers after the primary failed, the charged id ends on the answering row. - Migration
20261121120000_ai_quota_usage_log(additive):AiActionKind.GRADING_FEEDBACKandOTHER; the M6 bucket CHECKs fromconstraints.sql.
Consequences
Proven on real Postgres by apps/api/test/integration/ai-quota.int-spec.ts: 10 concurrent tutor questions against a quota of 8 → exactly 8 answered, 8 SPEND rows with distinct balances, 8 charged usage rows; the refused two made no provider call. Only the tutor answer is charged today; other priced actions call reserve the same way when they reach the online path. The ledger rows leave aiGenerationId NULL (the usage row is written after the charge commits); the spend:<id> key is the link. An allowance change applies from the next month. One charge comes from one bucket (no split). dailyCallCap is still not enforced (follow-up). The usage write adds one INSERT per AI call; it is asynchronous and a failure is logged, never surfaced.