diff --git a/server/prisma/migrations/20261203120000_platform_ai_calls/migration.sql b/server/prisma/migrations/20261203120000_platform_ai_calls/migration.sql new file mode 100644 index 000000000..3ae6c0811 --- /dev/null +++ b/server/prisma/migrations/20261203120000_platform_ai_calls/migration.sql @@ -0,0 +1,20 @@ +-- CreateTable +CREATE TABLE "PlatformAiCall" ( + "id" TEXT NOT NULL, + "feature" TEXT NOT NULL, + "userId" TEXT NOT NULL, + "inputTokens" INTEGER NOT NULL DEFAULT 0, + "outputTokens" INTEGER NOT NULL DEFAULT 0, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "PlatformAiCall_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE INDEX "PlatformAiCall_feature_createdAt_idx" ON "PlatformAiCall"("feature", "createdAt"); + +-- CreateIndex +CREATE INDEX "PlatformAiCall_userId_feature_createdAt_idx" ON "PlatformAiCall"("userId", "feature", "createdAt"); + +-- AddForeignKey +ALTER TABLE "PlatformAiCall" ADD CONSTRAINT "PlatformAiCall_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/server/prisma/schema.prisma b/server/prisma/schema.prisma index 3896beca7..3c95d862d 100644 --- a/server/prisma/schema.prisma +++ b/server/prisma/schema.prisma @@ -345,6 +345,7 @@ model User { aiCredential AiCredential? aiInterviewSessions AiInterviewSession[] learnerQuestions LearnerQuestion[] + platformAiCalls PlatformAiCall[] personalizedPrompts PersonalizedPrompt[] capstoneChecks CapstoneCheck[] shellLabProgress ShellLabProgress[] @@ -1878,6 +1879,22 @@ model LearnerQuestion { @@index([userId, createdAt]) } +/// One model call paid for with the platform's own AI key (short-answer grading without a +/// learner key, suggested help replies). Reserved before the call so daily caps hold across +/// replicas; released only when the provider did not bill the call. +model PlatformAiCall { + id String @id @default(cuid()) + feature String + userId String + user User @relation(fields: [userId], references: [id], onDelete: Cascade) + inputTokens Int @default(0) + outputTokens Int @default(0) + createdAt DateTime @default(now()) + + @@index([feature, createdAt]) + @@index([userId, feature, createdAt]) +} + /// A learner's own wording of an open question that opted into `personalize`, written by /// the model from their earlier answers. One row per learner and block; it stays put once /// the learner has answered, so the question they see never changes under them. diff --git a/server/src/config/env.ts b/server/src/config/env.ts index d3b21ed8e..6702acc4f 100644 --- a/server/src/config/env.ts +++ b/server/src/config/env.ts @@ -182,6 +182,15 @@ const schema = z.object({ HELP_REPLY_MODEL: z.string().trim().min(1).default("claude-sonnet-5-5"), /** Drafts the whole platform may make per UTC day, the cap on the Anthropic bill. */ AI_REVIEW_DAILY_LIMIT: z.coerce.number().int().min(1).max(20_000).default(1_000), + /** + * Short answers graded on the platform's key (learners without their own key). Counted in + * the PlatformAiCall table before the model is called, so they hold across restarts and replicas. + */ + SHORT_ANSWER_PLATFORM_DAILY_LIMIT: z.coerce.number().int().min(1).max(1_000).default(40), + SHORT_ANSWER_PLATFORM_GLOBAL_DAILY_LIMIT: z.coerce.number().int().min(1).max(200_000).default(3_000), + /** Suggested help replies one mentor may ask for per UTC day, and the whole platform. */ + HELP_REPLY_DRAFT_DAILY_LIMIT: z.coerce.number().int().min(1).max(2_000).default(60), + HELP_REPLY_DRAFT_GLOBAL_DAILY_LIMIT: z.coerce.number().int().min(1).max(50_000).default(500), /** Optional fine-grained GitHub token, public read only. Without it the API allows 60 calls an hour, about 12 checks. */ GITHUB_TOKEN: optionalString, /** Edorax's LinkedIn company id for Add to profile; without it LinkedIn gets the name "Edorax" as text. */ diff --git a/server/src/services/ai/chapter-qa/practice-quiz.ts b/server/src/services/ai/chapter-qa/practice-quiz.ts index ef7a92108..b0633f840 100644 --- a/server/src/services/ai/chapter-qa/practice-quiz.ts +++ b/server/src/services/ai/chapter-qa/practice-quiz.ts @@ -343,6 +343,7 @@ export async function generatePracticeQuiz( messages: [{ role: "user", content: userPrompt }], }); + keepReservation = true; await recordTokens(reservation, { inputTokens: message.usage.input_tokens, outputTokens: message.usage.output_tokens, @@ -374,8 +375,12 @@ export async function generatePracticeQuiz( }, fetchImpl: deps.fetchImpl, }); + keepReservation = true; } + // From here the provider has answered and billed the call, so the quiz stays counted even if + // the answer cannot be used. Otherwise a crafted `focus` that breaks the JSON would give + // unlimited free generations. let parsedJson: unknown; try { parsedJson = parseModelJson(rawText); diff --git a/server/src/services/ai/chapter-qa/service.ts b/server/src/services/ai/chapter-qa/service.ts index 68d2f2994..273b0002d 100644 --- a/server/src/services/ai/chapter-qa/service.ts +++ b/server/src/services/ai/chapter-qa/service.ts @@ -133,6 +133,9 @@ function failure(error: unknown, chapterId: string): AppError { export async function askAboutChapter(input: AskInput, deps: ChapterQaDeps = {}): Promise { const prepared = await prepareQuestion(input); + // Once the provider has answered, the call is paid for: the question stays counted even if + // the answer is unusable, so nobody gets free calls by making answers fail. + let billed = false; try { const provider = resolveQaProvider(deps.client); if (!provider) throw new AppError(NOT_AVAILABLE, 503, "QA_UNAVAILABLE"); @@ -140,6 +143,7 @@ export async function askAboutChapter(input: AskInput, deps: ChapterQaDeps = {}) let answer: string; if (provider.kind === "anthropic") { const message = await provider.client.messages.create(prepared.params); + billed = true; await recordTokens(prepared.reservation, { inputTokens: message.usage.input_tokens, outputTokens: message.usage.output_tokens }); const text = message.content .flatMap((block) => (block.type === "text" ? [block.text] : [])) @@ -156,12 +160,13 @@ export async function askAboutChapter(input: AskInput, deps: ChapterQaDeps = {}) temperature: 0.3, fetchImpl: deps.fetchImpl, }); + billed = true; } if (!answer) throw new AppError(TRY_LATER, 502, "QA_FAILED"); return { answer, ...(await remainingToday(prepared.learnerId)) }; } catch (error) { - await releaseQuestion(prepared.reservation).catch(() => undefined); + if (!billed) await releaseQuestion(prepared.reservation).catch(() => undefined); throw failure(error, prepared.chapterId); } } @@ -184,6 +189,7 @@ export async function streamAnswerAboutChapter(input: AskInput, deps: ChapterQaD const prepared = await prepareQuestion(input); const run = async (write: (chunk: string) => void) => { let wrote = false; + let billed = false; try { const provider = resolveQaProvider(deps.client); if (!provider) throw new AppError(NOT_AVAILABLE, 503, "QA_UNAVAILABLE"); @@ -196,6 +202,7 @@ export async function streamAnswerAboutChapter(input: AskInput, deps: ChapterQaD write(delta); }); const message = await stream.finalMessage(); + billed = true; await recordTokens(prepared.reservation, { inputTokens: message.usage.input_tokens, outputTokens: message.usage.output_tokens }); if (message.stop_reason === "refusal" && !wrote) write(DECLINED); else if (!wrote) throw new AppError(TRY_LATER, 502, "QA_FAILED"); @@ -209,12 +216,14 @@ export async function streamAnswerAboutChapter(input: AskInput, deps: ChapterQaD temperature: 0.3, fetchImpl: deps.fetchImpl, }); + billed = true; if (!answer.trim()) throw new AppError(TRY_LATER, 502, "QA_FAILED"); wrote = true; write(answer); } } catch (error) { - await releaseQuestion(prepared.reservation).catch(() => undefined); + // Text already streamed means the provider was generating, and billing, this answer. + if (!billed && !wrote) await releaseQuestion(prepared.reservation).catch(() => undefined); write(STREAM_ERROR_MARK + failure(error, prepared.chapterId).message); } }; diff --git a/server/src/services/ai/platform-usage.ts b/server/src/services/ai/platform-usage.ts new file mode 100644 index 000000000..0ea77e952 --- /dev/null +++ b/server/src/services/ai/platform-usage.ts @@ -0,0 +1,64 @@ +import { prisma } from "../../db/prisma.js"; +import { AppError, TooManyRequestsError } from "../../utils/errors.js"; +import { startOfUtcDay } from "./chapter-qa/usage.js"; + +// Daily caps for model calls paid with the platform's own key. A row is reserved under a +// lock before the model is called, so parallel requests cannot all pass the check at once, +// and the caps hold across restarts and replicas. A row is released only when the provider +// refused the call before doing any work; a call that got an answer (even one we could not +// use) stays counted, so nobody can get free calls by making the answer fail. + +export type PlatformFeature = "short-answer" | "help-reply"; + +export type PlatformLimits = { + perUserDaily: number; + globalDaily: number; + /** Calls one user may start in any 60 seconds. */ + perMinute?: number; + /** What the user sees at their own daily cap. */ + userMessage: string; + /** What the user sees when the platform-wide cap is reached. */ + globalMessage: string; +}; + +const MINUTE_MS = 60_000; + +export async function reservePlatformCall( + input: { userId: string; feature: PlatformFeature; limits: PlatformLimits }, + now = new Date() +): Promise { + const { userId, feature, limits } = input; + return prisma.$transaction(async (tx) => { + await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtext(${`platform-ai:${feature}`}))`; + const dayStart = startOfUtcDay(now); + const today = await tx.platformAiCall.count({ where: { feature, createdAt: { gte: dayStart } } }); + if (today >= limits.globalDaily) throw new AppError(limits.globalMessage, 503, "AI_DAILY_CAP"); + const perUser = await tx.platformAiCall.count({ where: { userId, feature, createdAt: { gte: dayStart } } }); + if (perUser >= limits.perUserDaily) throw new TooManyRequestsError(limits.userMessage); + if (limits.perMinute) { + const lastMinute = await tx.platformAiCall.count({ + where: { userId, feature, createdAt: { gte: new Date(now.getTime() - MINUTE_MS) } }, + }); + if (lastMinute >= limits.perMinute) throw new TooManyRequestsError("You are going quickly. Wait a minute and try again."); + } + const row = await tx.platformAiCall.create({ data: { userId, feature }, select: { id: true } }); + return row.id; + }); +} + +export async function recordPlatformTokens(id: string, usage: { inputTokens: number; outputTokens: number }): Promise { + await prisma.platformAiCall.update({ where: { id }, data: usage }).catch(() => undefined); +} + +/** Give the call back. Use only when the provider did not bill it (see providerDidNotBill). */ +export async function releasePlatformCall(id: string): Promise { + await prisma.platformAiCall.deleteMany({ where: { id } }); +} + +/** Codes where the provider rejected the request before generating anything. */ +const NOT_BILLED = new Set(["AI_NOT_CONFIGURED", "AI_KEY_INVALID", "AI_OUT_OF_CREDIT", "AI_RATE_LIMITED", "AI_MODEL_UNAVAILABLE"]); + +export function providerDidNotBill(error: unknown): boolean { + const code = (error as { code?: unknown } | null)?.code; + return typeof code === "string" && NOT_BILLED.has(code); +} diff --git a/server/src/services/ai/short-answer/grade.ts b/server/src/services/ai/short-answer/grade.ts index 9c249d851..263281e66 100644 --- a/server/src/services/ai/short-answer/grade.ts +++ b/server/src/services/ai/short-answer/grade.ts @@ -4,6 +4,7 @@ import { DEFAULT_HINT_AFTER_ATTEMPTS } from "../../../shared/blocks/open-questio import { env, shortAnswerPlatformKeyAvailable } from "../../../config/env.js"; import { loadAiKeyForUse } from "../credentials.js"; import { AiError, createChatCompletion, type AiProviderName } from "../openrouter.js"; +import { providerDidNotBill, recordPlatformTokens, releasePlatformCall, reservePlatformCall } from "../platform-usage.js"; // Instant short-answer grading with the learner's OpenRouter key. The model // only decides correct/incorrect and a short "why"; authored hints are chosen @@ -114,6 +115,7 @@ async function callModel(input: { sampleAnswer?: string; rubric?: string; fetchImpl?: typeof fetch; + onUsage?: (usage: { inputTokens: number; outputTokens: number }) => void; }): Promise<{ correct: boolean; why: string; guidance: string }> { const content = await createChatCompletion({ apiKey: input.apiKey, @@ -132,6 +134,7 @@ async function callModel(input: { responseFormat: { type: "json_schema", json_schema: gradeJsonSchema }, timeoutMs: 30_000, fetchImpl: input.fetchImpl, + onUsage: input.onUsage, }); let parsedJson: unknown; @@ -152,12 +155,12 @@ async function callModel(input: { async function loadKeyOrPlatform( userId: string, deps: Deps -): Promise<{ provider: AiProviderName; apiKey: string; model: string }> { +): Promise<{ provider: AiProviderName; apiKey: string; model: string; platform: boolean }> { try { - return await loadAiKeyForUse(userId, deps); + return { ...(await loadAiKeyForUse(userId, deps)), platform: false }; } catch (error) { if (error instanceof AiError && error.code === "AI_KEY_REQUIRED" && shortAnswerPlatformKeyAvailable) { - return { provider: "ANTHROPIC", apiKey: env.ANTHROPIC_API_KEY!, model: env.AI_REVIEW_MODEL }; + return { provider: "ANTHROPIC", apiKey: env.ANTHROPIC_API_KEY!, model: env.AI_REVIEW_MODEL, platform: true }; } throw error; } @@ -182,20 +185,45 @@ export async function gradeShortAnswerWithLlm(input: { ); } - const { provider, apiKey, model } = + const { provider, apiKey, model, platform } = deps.apiKey && deps.model - ? { provider: "OPENROUTER" as const, apiKey: deps.apiKey, model: deps.model } + ? { provider: "OPENROUTER" as const, apiKey: deps.apiKey, model: deps.model, platform: false } : await loadKeyOrPlatform(userId, deps); - const gradeFn = deps.gradeFn ?? ((args) => callModel({ ...args, fetchImpl: deps.fetchImpl })); - const graded = await gradeFn({ - apiKey, - provider, - model, - prompt: config.prompt, - answer, - sampleAnswer: config.sampleAnswer, - rubric: config.rubric, - }); + + // On the platform's key every call is counted before it is made: per learner, per minute and + // platform-wide. A learner's own key is their own bill, so it is not capped here. + const reservation = platform + ? await reservePlatformCall({ + userId, + feature: "short-answer", + limits: { + perUserDaily: env.SHORT_ANSWER_PLATFORM_DAILY_LIMIT, + globalDaily: env.SHORT_ANSWER_PLATFORM_GLOBAL_DAILY_LIMIT, + perMinute: 6, + userMessage: `You have used today's ${env.SHORT_ANSWER_PLATFORM_DAILY_LIMIT} instant checks. Add your own AI key in settings for more, or try again tomorrow.`, + globalMessage: "Instant feedback is paused for today. Please try again tomorrow, or add your own AI key in settings.", + }, + }) + : null; + const usage: { value: { inputTokens: number; outputTokens: number } | null } = { value: null }; + const gradeFn = deps.gradeFn ?? ((args) => callModel({ ...args, fetchImpl: deps.fetchImpl, onUsage: (value) => { usage.value = value; } })); + let graded: Awaited>>; + try { + graded = await gradeFn({ + apiKey, + provider, + model, + prompt: config.prompt, + answer, + sampleAnswer: config.sampleAnswer, + rubric: config.rubric, + }); + } catch (error) { + if (reservation && providerDidNotBill(error)) await releasePlatformCall(reservation).catch(() => undefined); + throw error; + } finally { + if (reservation && usage.value) await recordPlatformTokens(reservation, usage.value); + } const why = graded.why.slice(0, 800); if (graded.correct) { diff --git a/server/src/services/blocks/respond.ts b/server/src/services/blocks/respond.ts index 18ed70a25..667a95ebb 100644 --- a/server/src/services/blocks/respond.ts +++ b/server/src/services/blocks/respond.ts @@ -44,6 +44,9 @@ export type BlockResponseResult = { type Graded = GradeResult & Omit; +/** Longest open answer accepted. About 4,000 words: far past any real answer, small for a model bill. */ +export const OPEN_ANSWER_MAX_CHARS = 20_000; + /** Parse the payload with the block's own schema and grade it — pure, no I/O. */ function gradeBlock(type: string, config: unknown, payload: unknown): Graded { switch (type) { @@ -150,6 +153,11 @@ export async function submitBlockResponse(input: { } }); + // Open answers go to AI grading and AI review drafts, so a huge paste would be a huge bill. + if (block.type === "OPEN_QUESTION" && typeof payload.text === "string" && payload.text.length > OPEN_ANSWER_MAX_CHARS) { + throw new BadRequestError(`Keep your answer under ${OPEN_ANSWER_MAX_CHARS.toLocaleString("en-US")} characters.`, "ANSWER_TOO_LONG"); + } + const previousAttempts = await prisma.response.count({ where: { blockId, userId: learner.id } }); const attempt = previousAttempts + 1; diff --git a/server/src/services/teach/ai/auto-draft.ts b/server/src/services/teach/ai/auto-draft.ts index 42003c075..5e2ab8c77 100644 --- a/server/src/services/teach/ai/auto-draft.ts +++ b/server/src/services/teach/ai/auto-draft.ts @@ -56,7 +56,8 @@ export async function loadReviewDraftContext(responseId: string): Promise { - const used = await prisma.response.count({ where: { aiDraftAt: { gte: startOfUtcDay(now) } } }); + // Failed tries count too: most of them reached the model and were billed, and "Try again" + // must not become a way around the cap. + const dayStart = startOfUtcDay(now); + const used = await prisma.response.count({ + where: { OR: [{ aiDraftAt: { gte: dayStart } }, { aiDraftFailedAt: { gte: dayStart } }] }, + }); return used < env.AI_REVIEW_DAILY_LIMIT; } diff --git a/server/src/services/teach/ai/help-reply-draft.ts b/server/src/services/teach/ai/help-reply-draft.ts index a07945745..e2a36eaef 100644 --- a/server/src/services/teach/ai/help-reply-draft.ts +++ b/server/src/services/teach/ai/help-reply-draft.ts @@ -5,6 +5,7 @@ import { NotFoundError, UnprocessableError } from "../../../utils/errors.js"; import type { SessionUser } from "../../../types/auth.js"; import { AiError, createChatCompletion, forPlatformKey } from "../../ai/openrouter.js"; import { costMicroUsd } from "../../capstone/grade.js"; +import { providerDidNotBill, recordPlatformTokens, releasePlatformCall, reservePlatformCall } from "../../ai/platform-usage.js"; import { requireCourseById } from "../access.js"; // A suggested mentor reply to a learner's question, written by Claude from the chapter @@ -119,6 +120,18 @@ ${conversation} Write the mentor's next reply to the learner's latest message, and classify the message.`; + // Counted before the call, per mentor and platform-wide: this runs on the platform's key. + const reservation = await reservePlatformCall({ + userId: user.id, + feature: "help-reply", + limits: { + perUserDaily: env.HELP_REPLY_DRAFT_DAILY_LIMIT, + globalDaily: env.HELP_REPLY_DRAFT_GLOBAL_DAILY_LIMIT, + perMinute: 6, + userMessage: `You have used today's ${env.HELP_REPLY_DRAFT_DAILY_LIMIT} suggested replies. They reset at midnight UTC.`, + globalMessage: "Suggested replies are paused for today. They reset at midnight UTC.", + }, + }); let usage = { inputTokens: 0, outputTokens: 0 }; let content: string; try { @@ -138,12 +151,15 @@ Write the mentor's next reply to the learner's latest message, and classify the }, }); } catch (error) { + if (providerDidNotBill(error)) await releasePlatformCall(reservation).catch(() => undefined); throw new UnprocessableError( error instanceof AiError ? `Claude could not write a reply: ${forPlatformKey(error.message)}` : "Claude could not write a reply. Try again in a moment.", "AI_DRAFT_UNAVAILABLE" ); } + if (usage.inputTokens || usage.outputTokens) await recordPlatformTokens(reservation, usage); + let parsed: { reply?: unknown; feedbackScope?: unknown; feedbackNote?: unknown }; try { parsed = JSON.parse(content) as typeof parsed; diff --git a/server/tests/services/platform-ai-usage.test.ts b/server/tests/services/platform-ai-usage.test.ts new file mode 100644 index 000000000..d543de275 --- /dev/null +++ b/server/tests/services/platform-ai-usage.test.ts @@ -0,0 +1,68 @@ +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { prisma } from "../../src/db/prisma.js"; +import { AiError } from "../../src/services/ai/openrouter.js"; +import { providerDidNotBill, releasePlatformCall, reservePlatformCall, type PlatformLimits } from "../../src/services/ai/platform-usage.js"; + +const limits: PlatformLimits = { + perUserDaily: 3, + globalDaily: 1_000, + userMessage: "user cap", + globalMessage: "global cap", +}; + +describe("platform AI call caps", () => { + const tag = `pac-${Date.now()}`; + let userId = ""; + let otherId = ""; + + beforeAll(async () => { + userId = (await prisma.user.create({ data: { email: `a-${tag}@test.local`, name: "A", role: "MENTEE" } })).id; + otherId = (await prisma.user.create({ data: { email: `b-${tag}@test.local`, name: "B", role: "MENTEE" } })).id; + }); + + afterAll(async () => { + await prisma.user.deleteMany({ where: { id: { in: [userId, otherId] } } }); + }); + + it("lets exactly the daily number through, even when the requests arrive together", async () => { + const results = await Promise.allSettled( + Array.from({ length: 8 }, () => reservePlatformCall({ userId, feature: "short-answer", limits })) + ); + expect(results.filter((r) => r.status === "fulfilled")).toHaveLength(3); + const rejected = results.filter((r): r is PromiseRejectedResult => r.status === "rejected"); + expect(rejected).toHaveLength(5); + expect(rejected[0]!.reason).toMatchObject({ statusCode: 429, message: "user cap" }); + }); + + it("counts each feature on its own", async () => { + await expect(reservePlatformCall({ userId, feature: "help-reply", limits })).resolves.toEqual(expect.any(String)); + }); + + it("stops everyone once the platform-wide cap is reached", async () => { + const used = await prisma.platformAiCall.count({ where: { feature: "short-answer" } }); + await expect( + reservePlatformCall({ userId: otherId, feature: "short-answer", limits: { ...limits, globalDaily: used } }) + ).rejects.toMatchObject({ statusCode: 503, code: "AI_DAILY_CAP" }); + }); + + it("applies the per-minute limit", async () => { + const minute = { ...limits, perUserDaily: 100, perMinute: 1 }; + await reservePlatformCall({ userId: otherId, feature: "help-reply", limits: minute }); + await expect(reservePlatformCall({ userId: otherId, feature: "help-reply", limits: minute })).rejects.toMatchObject({ statusCode: 429 }); + }); + + it("frees a slot when a call is released", async () => { + const id = await reservePlatformCall({ userId: otherId, feature: "short-answer", limits }); + const before = await prisma.platformAiCall.count({ where: { userId: otherId, feature: "short-answer" } }); + await releasePlatformCall(id); + expect(await prisma.platformAiCall.count({ where: { userId: otherId, feature: "short-answer" } })).toBe(before - 1); + }); + + it("treats only refusals before any work as not billed", () => { + expect(providerDidNotBill(new AiError("AI_RATE_LIMITED"))).toBe(true); + expect(providerDidNotBill(new AiError("AI_KEY_INVALID"))).toBe(true); + expect(providerDidNotBill(new AiError("AI_BAD_OUTPUT"))).toBe(false); + expect(providerDidNotBill(new AiError("AI_PROVIDER_TIMEOUT"))).toBe(false); + expect(providerDidNotBill(new Error("anything"))).toBe(false); + }); +}); diff --git a/server/tests/unit/services/ai/short-answer-platform-key.test.ts b/server/tests/unit/services/ai/short-answer-platform-key.test.ts index 693d1d4e5..733148268 100644 --- a/server/tests/unit/services/ai/short-answer-platform-key.test.ts +++ b/server/tests/unit/services/ai/short-answer-platform-key.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it, vi } from "vitest"; +import { beforeEach, describe, expect, it, vi } from "vitest"; vi.mock("../../../../src/config/env.js", async (importOriginal) => { const actual = await importOriginal(); @@ -19,6 +19,20 @@ vi.mock("../../../../src/services/ai/credentials.js", async () => { }; }); +const reserve = vi.fn(async () => "call1"); +const release = vi.fn(async () => undefined); +vi.mock("../../../../src/services/ai/platform-usage.js", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + reservePlatformCall: (...args: unknown[]) => (reserve as (...a: unknown[]) => Promise)(...args), + releasePlatformCall: (...args: unknown[]) => (release as (...a: unknown[]) => Promise)(...args), + recordPlatformTokens: vi.fn(async () => undefined), + }; +}); + +const { AiError } = await import("../../../../src/services/ai/openrouter.js"); +const { TooManyRequestsError } = await import("../../../../src/utils/errors.js"); const { gradeShortAnswerWithLlm } = await import("../../../../src/services/ai/short-answer/grade.js"); const { OpenQuestionConfigSchema } = await import("../../../../src/shared/blocks/open-question/schema.js"); @@ -29,7 +43,15 @@ const config = OpenQuestionConfigSchema.parse({ maxAttempts: 3, }); +const grade = (userId: string, gradeFn: () => Promise<{ correct: boolean; why: string }>) => + gradeShortAnswerWithLlm({ userId, config, answer: "It keeps the API and UI changes together.", attempt: 1, deps: { gradeFn } }); + describe("short-answer grading without a learner key", () => { + beforeEach(() => { + reserve.mockReset().mockResolvedValue("call1"); + release.mockClear(); + }); + it("grades on the platform Claude key when the learner has saved none", async () => { const gradeFn = vi.fn(async () => ({ correct: true, why: "Matches." })); const result = await gradeShortAnswerWithLlm({ @@ -58,4 +80,31 @@ describe("short-answer grading without a learner key", () => { expect.objectContaining({ provider: "OPENROUTER", apiKey: "own-key", model: "own-model" }) ); }); + + it("counts every platform-key grade before calling the model", async () => { + await grade("learner-without-key", async () => ({ correct: true, why: "Matches." })); + expect(reserve).toHaveBeenCalledWith(expect.objectContaining({ userId: "learner-without-key", feature: "short-answer" })); + }); + + it("does not count grades on the learner's own key", async () => { + await grade("learner-with-key", async () => ({ correct: true, why: "Matches." })); + expect(reserve).not.toHaveBeenCalled(); + }); + + it("stops before the model call when the daily cap is reached", async () => { + reserve.mockRejectedValue(new TooManyRequestsError("cap")); + const gradeFn = vi.fn(async () => ({ correct: true, why: "Matches." })); + await expect(grade("learner-without-key", gradeFn)).rejects.toMatchObject({ statusCode: 429 }); + expect(gradeFn).not.toHaveBeenCalled(); + }); + + it("keeps the call counted when the model answered with something unusable", async () => { + await expect(grade("learner-without-key", async () => { throw new AiError("AI_BAD_OUTPUT"); })).rejects.toThrow(); + expect(release).not.toHaveBeenCalled(); + }); + + it("gives the call back when the provider refused it before any work", async () => { + await expect(grade("learner-without-key", async () => { throw new AiError("AI_RATE_LIMITED"); })).rejects.toThrow(); + expect(release).toHaveBeenCalledWith("call1"); + }); }); diff --git a/server/tests/unit/services/chapter-qa-stream.test.ts b/server/tests/unit/services/chapter-qa-stream.test.ts index 331d5b515..976a5debc 100644 --- a/server/tests/unit/services/chapter-qa-stream.test.ts +++ b/server/tests/unit/services/chapter-qa-stream.test.ts @@ -99,19 +99,27 @@ describe("streamed chapter answers", () => { expect(params.messages.map((message) => message.role)).toEqual(["user", "assistant", "user"]); }); - it("releases the question and writes the failure after a late error, without the provider's text", async () => { + it("keeps the question counted and writes the failure after a late error, without the provider's text", async () => { + // Text already streamed, so the provider was billing this answer: a late failure must not refund it. const { client } = fakeClient(["Half"], new Error("upstream said: secret detail")); const { text } = await collect(client); expect(text.startsWith("Half" + STREAM_ERROR_MARK)).toBe(true); expect(text).not.toContain("secret detail"); + expect(release).not.toHaveBeenCalled(); + }); + + it("releases the question when the provider fails before any text", async () => { + const { client } = fakeClient([], new Error("connection reset")); + const { text } = await collect(client); + expect(text.startsWith(STREAM_ERROR_MARK)).toBe(true); expect(release).toHaveBeenCalledWith("row1"); }); - it("releases the question when the model returns no text", async () => { + it("keeps the question counted when the model answers with no text", async () => { const { client } = fakeClient([], {}); const { text } = await collect(client); expect(text.startsWith(STREAM_ERROR_MARK)).toBe(true); - expect(release).toHaveBeenCalledWith("row1"); + expect(release).not.toHaveBeenCalled(); }); it("answers a refusal with the friendly decline and keeps the question counted", async () => { diff --git a/server/tests/unit/services/practice-quiz.test.ts b/server/tests/unit/services/practice-quiz.test.ts index 2c0fd642a..55e6be28c 100644 --- a/server/tests/unit/services/practice-quiz.test.ts +++ b/server/tests/unit/services/practice-quiz.test.ts @@ -290,12 +290,13 @@ describe("generatePracticeQuiz & checkPracticeQuiz", () => { ).rejects.toMatchObject({ code: "PRACTICE_QUIZ_EXPIRED" }); }); - it("releases the question reservation on malformed JSON or provider error", async () => { + it("keeps the reservation on malformed JSON and releases it on a provider error", async () => { + // The model answered, so the call was billed: a focus crafted to break the JSON must not get free quizzes. const { client: badClient } = fakeClient({ text: "not-json" }); await expect(generatePracticeQuiz({ chapterId: "ch1", user }, { client: badClient, sealKey: SEAL_KEY })).rejects.toMatchObject({ code: "PRACTICE_QUIZ_FAILED", }); - expect(release).toHaveBeenCalledWith("row1"); + expect(release).not.toHaveBeenCalled(); release.mockClear(); const { client: errClient } = fakeClient(new Error("boom"));