Bỏ qua, tới nội dung chính

Kiến trúc · ADR 0044

One AI usage log from AiClient events; the free monthly quota charged before the call

Trạng thái
accepted; partly superseded by ADR-0057 (the free quota counts AI uses, and the
Ngày
2026-11-21
Người quyết định
SmartLearn team (#115, #116)

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 the ai.call event, which also gains requestHash (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 each ai.call event into an AiUsageRecord, writes it off the call's path, and never throws into it; flush() for tests and shutdown. The api builds it in AiService (every client it creates, fallback ones included) and fills userId/requestId from the request context; the worker builds it in runtime.ts and flushes it before Prisma disconnects. Each app maps the record to an AiGeneration row with its own Prisma client and prices it with calculateTokenCostUsd.
  • 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-expiring AiCreditBalance. A period is opened on first use with the role's free allowance from ai.pricing (student / instructor), snapshotted for that month, with a GRANT_FREE ledger row free:<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.reserve runs 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 records quotaUnits = 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_FEEDBACK and OTHER; the M6 bucket CHECKs from constraints.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.