File size: 41,561 Bytes
f90228b 2b62b0c bede2fc 2b62b0c bede2fc 2858397 72e7de2 2858397 72e7de2 2858397 2b62b0c 2858397 2b62b0c 36b41bf f2d1fea ef46e44 ff49634 ef46e44 f90228b b87cbc7 2858397 62fdec8 2858397 62fdec8 2858397 f90228b 36b41bf 72e7de2 92a1d83 2858397 92a1d83 2858397 36b41bf 92a1d83 2858397 92a1d83 2858397 ef46e44 2858397 ef46e44 2858397 ef46e44 2858397 ef46e44 2858397 f2d1fea 2858397 ef46e44 2858397 ef46e44 2858397 ef46e44 2858397 f2d1fea bede2fc 2b62b0c bede2fc 2858397 36b41bf 2858397 36b41bf 2858397 36b41bf ef46e44 36b41bf 2858397 bede2fc 2858397 36b41bf 2858397 bede2fc 36b41bf 2858397 f90228b 36b41bf 2858397 ef46e44 2858397 36b41bf 2858397 36b41bf 2858397 ef46e44 2858397 36b41bf 2858397 36b41bf 2858397 36b41bf b762c97 2858397 b762c97 2858397 b762c97 2858397 b762c97 72e7de2 2858397 36b41bf 72e7de2 f2d1fea f90228b 2858397 72e7de2 2858397 f2d1fea f90228b 0c932f9 2858397 0c932f9 f90228b 2858397 34f01ec c1e702e 2858397 c1e702e 2858397 f90228b c1e702e 2858397 72e7de2 2858397 c1e702e 2858397 c1e702e 72e7de2 c1e702e 72e7de2 62fdec8 72e7de2 62fdec8 72e7de2 c1e702e 62fdec8 c1e702e 72e7de2 c1e702e 62fdec8 c1e702e 34f01ec 2858397 c1e702e f90228b 2858397 f90228b 2858397 f90228b 2858397 ef46e44 2858397 ef46e44 2858397 f90228b 2858397 ef46e44 2858397 f90228b 2858397 ef46e44 2858397 ef46e44 2858397 ef46e44 2858397 f90228b ef46e44 2858397 f90228b 2858397 ef46e44 ff49634 ef46e44 c1e702e ef46e44 72e7de2 ef46e44 72e7de2 2858397 ef46e44 2858397 ef46e44 2858397 ef46e44 2858397 ef46e44 2858397 f90228b 2858397 f90228b ef46e44 2858397 85cb661 2858397 f2d1fea ef46e44 f2d1fea 2858397 72e7de2 2858397 72e7de2 f2d1fea 2858397 72e7de2 2858397 f2d1fea 2858397 72e7de2 2858397 72e7de2 2858397 bede2fc 2858397 f90228b 2858397 36b41bf 0c932f9 2858397 0c932f9 f90228b 2858397 f90228b ef46e44 36b41bf f90228b b87cbc7 2858397 f90228b f2d1fea f90228b f2d1fea f90228b 2858397 f90228b 2858397 f90228b ef46e44 f90228b f2d1fea bede2fc f2d1fea | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 | import { Queue, Worker, type Job } from "bullmq";
import IORedis from "ioredis";
import { env } from "@pram/env/server";
async function log(level: "debug" | "warn", message: string, meta?: Record<string, unknown>) {
const mod = await import("@pram/api/logger");
(mod.logger as any)[level](message, meta);
}
import {
generateQuestionsQuick,
generateQuestionsAgentic,
generatePassageForInput,
generateQuestionsAgenticFromPassage,
GenerationError,
type AgenticProgress,
type GenerationInput,
type GenerationResult,
} from "@pram/ai";
import { db } from "@pram/db";
import {
generationJob,
question,
testPackage,
packageSection,
sectionQuestion,
} from "@pram/db";
import { and, eq, notInArray } from "drizzle-orm";
import { encryptApiKey, decryptApiKey } from "./lib/encryption";
import {
collectShardFailureCause,
isNonRetryableProviderError,
resolveGenerationJobOutcome,
sectionsWithNoQuestions,
} from "./lib/generation-outcome";
const connectionOptions = { maxRetriesPerRequest: null };
const FAST_QUEUE_NAME = "generation-fast";
const QUALITY_QUEUE_NAME = "generation-quality";
const CANCEL_POLL_MS = 500;
const HEARTBEAT_MS = 10_000;
const MAX_QUESTIONS_PER_SHARD = 8;
const FAST_SHARD_CONCURRENCY = 3;
const QUALITY_SECTION_CONCURRENCY = 2;
const QUICK_PARSE_FALLBACK_TO_AGENTIC = false;
export const MAX_SHARD_RETRIES = 1;
interface SectionSplit {
section: string;
count: number;
}
interface ShardPlan extends SectionSplit {
sectionIndex: number;
shardIndex: number;
shardCount: number;
}
interface PersistableQuestion {
section: string;
format: string;
passageText: string;
questionText: string;
options: unknown;
correctAnswer: string;
explanation: string;
difficulty: number;
skillTags: string[];
aiModel: string;
}
interface FastJobData {
input: GenerationInput;
jobId: string;
}
interface QualityJobData {
input: GenerationInput;
jobId: string;
sectionSplits: SectionSplit[];
fastQuestions: PersistableQuestion[];
fastMeta: {
tokensUsed: number;
durationMs: number;
approxTokens: number;
};
}
/** Thrown when the job was cancelled (DB status or cooperative poll). */
export class GenerationJobCancelledError extends Error {
constructor() {
super("JOB_CANCELLED");
this.name = "GenerationJobCancelledError";
}
}
const AGENTIC_STEP_FRACTIONS = [0.12, 0.28, 0.62, 0.92] as const;
const AGENTIC_STEP_LABELS: Record<string, string> = {
generate_passage: "Menulis bacaan...",
validate_passage: "Memvalidasi bacaan...",
generate_questions: "Membuat soal...",
self_validate: "Validasi kualitas...",
};
function mapAgenticProgressInShard(
agentic: AgenticProgress,
completedShards: number,
totalShards: number,
): { progress: number; message: string } {
const shardSpan = 65 / Math.max(totalShards, 1);
const shardBase = 15 + completedShards * shardSpan;
const stepFrac = AGENTIC_STEP_FRACTIONS[agentic.currentStep] ?? 0.5;
const progress = Math.min(Math.round(shardBase + shardSpan * stepFrac), 84);
const step = agentic.steps[agentic.currentStep];
const message =
step?.message ??
AGENTIC_STEP_LABELS[step?.step ?? ""] ??
"Agentic generation...";
return { progress, message };
}
function mapAgenticProgressInQuality(agentic: AgenticProgress): { progress: number; message: string } {
const stepFrac = AGENTIC_STEP_FRACTIONS[agentic.currentStep] ?? 0.5;
const progress = Math.min(86 + Math.round(stepFrac * 10), 96);
const step = agentic.steps[agentic.currentStep];
const message =
step?.message ??
AGENTIC_STEP_LABELS[step?.step ?? ""] ??
"Quality validation...";
return { progress, message };
}
function createAgenticProgressHandler(
updateProgress: (progress: number, progressMessage: string) => Promise<void>,
pushLog: (
step: string,
message: string,
status: "running" | "done" | "error",
details?: string,
) => Promise<void>,
mapProgress: (agentic: AgenticProgress) => { progress: number; message: string },
) {
const seenSteps = new Set<string>();
return (agentic: AgenticProgress) => {
const { progress, message } = mapProgress(agentic);
void updateProgress(progress, message).catch(() => {});
for (const step of agentic.steps) {
if (!step || step.status === "pending") continue;
const key = `${step.step}:${step.status}`;
if (seenSteps.has(key)) continue;
seenSteps.add(key);
void pushLog(
step.step,
step.message ?? AGENTIC_STEP_LABELS[step.step] ?? step.step,
step.status as "running" | "done" | "error",
step.output,
).catch(() => {});
}
};
}
export function computeSectionSplit(
selectedSections: string[],
count: number,
): SectionSplit[] {
const sections = selectedSections.length > 0 ? selectedSections : ["READING"];
if (count < 20 || sections.length <= 1) {
return [{ section: sections[0]!, count }];
}
const base = Math.floor(count / sections.length);
const remainder = count % sections.length;
return sections.map((section, i) => ({
section,
count: base + (i < remainder ? 1 : 0),
}));
}
export function splitIntoShards(sectionSplits: SectionSplit[]): ShardPlan[] {
const shards: ShardPlan[] = [];
for (let sectionIndex = 0; sectionIndex < sectionSplits.length; sectionIndex++) {
const split = sectionSplits[sectionIndex]!;
const shardCount = Math.ceil(split.count / MAX_QUESTIONS_PER_SHARD);
let remaining = split.count;
for (let shardIndex = 0; shardIndex < shardCount; shardIndex++) {
const count = Math.min(MAX_QUESTIONS_PER_SHARD, remaining);
remaining -= count;
shards.push({
section: split.section,
count,
sectionIndex,
shardIndex,
shardCount,
});
}
}
return shards;
}
function createCancellationPoller(jobId: string) {
let cancelled = false;
const interval = setInterval(() => {
db
.select({ status: generationJob.status })
.from(generationJob)
.where(eq(generationJob.id, jobId))
.limit(1)
.then(([row]) => {
if (row?.status === "cancelled") cancelled = true;
})
.catch(() => {});
}, CANCEL_POLL_MS);
return {
stop: () => clearInterval(interval),
check: () => {
if (cancelled) throw new GenerationJobCancelledError();
},
};
}
export async function runWithConcurrency<T, R>(
items: T[],
concurrency: number,
worker: (item: T, index: number) => Promise<R>,
): Promise<R[]> {
const results: R[] = new Array(items.length);
let nextIndex = 0;
const runners = Array.from({ length: Math.max(1, concurrency) }, async () => {
while (true) {
const index = nextIndex++;
if (index >= items.length) return;
results[index] = await worker(items[index]!, index);
}
});
await Promise.all(runners);
return results;
}
export function normalizeQuestions(
section: string,
model: string,
result: GenerationResult,
): PersistableQuestion[] {
return result.questions.map((q) => ({
section,
format: q.format,
passageText: q.passageText,
questionText: q.questionText,
options: (q as any).options ?? null,
correctAnswer: q.correctAnswer,
explanation: q.explanation,
difficulty: q.difficulty,
skillTags: q.skillTags,
aiModel: model,
}));
}
async function saveGeneratedArtifacts(
jobId: string,
input: GenerationInput,
allQuestions: PersistableQuestion[],
sectionSplits: SectionSplit[],
): Promise<{ savedQuestionIds: string[]; generatedPackageId: string | null }> {
const [existingJob] = await db
.select({ resultJson: generationJob.resultJson })
.from(generationJob)
.where(eq(generationJob.id, jobId))
.limit(1);
const alreadySaved =
existingJob?.resultJson &&
typeof existingJob.resultJson === "object" &&
"savedQuestionIds" in (existingJob.resultJson as any) &&
Array.isArray((existingJob.resultJson as any).savedQuestionIds) &&
(existingJob.resultJson as any).savedQuestionIds.length > 0;
if (alreadySaved) {
const savedQuestionIds = (existingJob!.resultJson as any).savedQuestionIds as string[];
return {
savedQuestionIds,
generatedPackageId: ((existingJob!.resultJson as any).generatedPackageId ?? null) as string | null,
};
}
const [jobRow] = await db
.select({ userId: generationJob.userId })
.from(generationJob)
.where(eq(generationJob.id, jobId))
.limit(1);
const userId = jobRow?.userId;
if (!userId) return { savedQuestionIds: [], generatedPackageId: null };
const inserted = await db
.insert(question)
.values(
allQuestions.map((q) => ({
examTypeId: input.examType,
sectionTypeId: q.section,
format: q.format,
passageText: q.passageText,
questionText: q.questionText,
options: q.options,
correctAnswer: q.correctAnswer,
explanation: q.explanation,
difficulty: q.difficulty,
skillTags: q.skillTags,
source: "ai" as const,
aiModel: q.aiModel,
creatorUserId: userId,
isPublic: false,
})) as any,
)
.returning({ id: question.id });
const savedQuestionIds = inserted.map((r) => r.id);
if (!savedQuestionIds.length) {
return { savedQuestionIds, generatedPackageId: null };
}
let generatedPackageId: string | null = null;
try {
const dateStr = new Date().toLocaleDateString("id-ID", {
day: "numeric",
month: "short",
year: "numeric",
});
const sectionLabel =
sectionSplits.length > 1 ? `${sectionSplits.length} sections` : input.section;
const pkgTitle = `AI Generated - ${input.examType} ${sectionLabel} - ${dateStr}`;
const [pkg] = await db
.insert(testPackage)
.values({
title: pkgTitle,
description: `Paket latihan AI-generated dengan ${savedQuestionIds.length} soal ${input.examType}.`,
examTypeId: input.examType,
creatorUserId: userId,
isPublic: false,
totalQuestions: savedQuestionIds.length,
totalSections: sectionSplits.length,
estimatedDurationMin: Math.ceil(savedQuestionIds.length * 1.5),
})
.returning();
if (!pkg) return { savedQuestionIds, generatedPackageId };
generatedPackageId = pkg.id;
for (let i = 0; i < sectionSplits.length; i++) {
const split = sectionSplits[i]!;
const sectionQuestions = allQuestions
.map((q, idx) => ({ ...q, _globalIndex: idx }))
.filter((q) => q.section === split.section);
const [sec] = await db
.insert(packageSection)
.values({
packageId: pkg.id,
sectionTypeId: split.section,
title: `${split.section} Section`,
orderIndex: i,
})
.returning();
if (sec) {
const sectionQuestionRows = sectionQuestions
.map((q, idx) => ({
sectionId: sec.id,
questionId: savedQuestionIds[q._globalIndex],
orderIndex: idx,
}))
.filter((q) => q.questionId != null);
if (sectionQuestionRows.length > 0) {
await db.insert(sectionQuestion).values(sectionQuestionRows as any);
}
}
}
} catch (packageErr: any) {
// eslint-disable-next-line no-console
console.warn("[GENERATION] Failed to auto-create package, but questions were saved.", {
error: packageErr?.message ?? String(packageErr),
jobId,
examType: input.examType,
section: input.section,
});
}
return { savedQuestionIds, generatedPackageId };
}
function shardKey(shard: ShardPlan): string {
return `${shard.sectionIndex}:${shard.shardIndex}`;
}
async function failGenerationJob(params: {
jobId: string;
errorMessage: string;
tokensUsed?: number;
durationMs: number;
}) {
await db
.update(generationJob)
.set({
status: "failed",
progress: 100,
progressMessage: "Generation failed",
errorMessage: params.errorMessage,
tokensUsed: params.tokensUsed,
durationMs: params.durationMs,
completedAt: new Date(),
})
.where(eq(generationJob.id, params.jobId));
}
async function completeJobWithResult(params: {
jobId: string;
input: GenerationInput;
status?: "completed" | "completed_partial";
statusMessage?: string;
errorMessage?: string | null;
allQuestions: PersistableQuestion[];
sectionSplits: SectionSplit[];
totalTokens: number;
durationMs: number;
metrics?: Record<string, unknown>;
}) {
const [currentJob] = await db
.select({ status: generationJob.status })
.from(generationJob)
.where(eq(generationJob.id, params.jobId))
.limit(1);
if (currentJob?.status === "cancelled") return;
const { savedQuestionIds, generatedPackageId } = await saveGeneratedArtifacts(
params.jobId,
params.input,
params.allQuestions,
params.sectionSplits,
);
const result: GenerationResult = {
questions: params.allQuestions as any,
meta: {
model: params.input.apiKeyConfig.model,
tokensUsed: params.totalTokens,
durationMs: params.durationMs,
mode: params.input.mode,
},
};
await db
.update(generationJob)
.set({
status: params.status ?? "completed",
progress: 100,
progressMessage: params.statusMessage ?? "Completed",
errorMessage: params.errorMessage ?? null,
resultJson: {
...result,
savedQuestionIds,
generatedPackageId,
sectionSplits: params.sectionSplits,
qualityPhase: "final",
metrics: params.metrics,
isPartial: params.status === "completed_partial",
requestedQuestionCount: params.input.questionCount,
} as any,
tokensUsed: params.totalTokens,
durationMs: params.durationMs,
completedAt: new Date(),
})
.where(
and(
eq(generationJob.id, params.jobId),
notInArray(generationJob.status, ["cancelled"]),
),
);
// Deduct from user credit if using platform generation
const inputAny = params.input as any;
if (inputAny._isPlatformGeneration && params.totalTokens > 0) {
const [jobRow] = await db
.select({ userId: generationJob.userId })
.from(generationJob)
.where(eq(generationJob.id, params.jobId))
.limit(1);
if (jobRow) {
const { deductCredit } = await import("@pram/api/lib/credit");
await deductCredit(jobRow.userId, params.totalTokens).catch(() => {});
}
}
}
export type CancelGenerationJobResult =
| { ok: true }
| { ok: false; reason: "not_found" | "forbidden" | "not_cancellable" };
export const generationQueue = new Queue<FastJobData>(FAST_QUEUE_NAME, {
connection: new IORedis(env.REDIS_URL, connectionOptions),
});
export const generationQualityQueue = new Queue<QualityJobData>(QUALITY_QUEUE_NAME, {
connection: new IORedis(env.REDIS_URL, connectionOptions),
});
/**
* Marks the job cancelled in Postgres, then removes queued jobs.
* Active jobs are stopped cooperatively by the worker (cancellation poller).
*/
export async function cancelGenerationJob(
userId: string,
jobId: string,
): Promise<CancelGenerationJobResult> {
const [row] = await db
.select({
id: generationJob.id,
userId: generationJob.userId,
status: generationJob.status,
})
.from(generationJob)
.where(eq(generationJob.id, jobId))
.limit(1);
if (!row) return { ok: false, reason: "not_found" };
if (row.userId !== userId) return { ok: false, reason: "forbidden" };
if (row.status === "completed" || row.status === "completed_partial" || row.status === "failed" || row.status === "cancelled") {
return { ok: false, reason: "not_cancellable" };
}
await db
.update(generationJob)
.set({
status: "cancelled",
errorMessage: "Dibatalkan pengguna",
completedAt: new Date(),
})
.where(eq(generationJob.id, jobId));
for (const queue of [generationQueue, generationQualityQueue]) {
try {
const bullJob = await queue.getJob(jobId);
if (bullJob) {
try {
await bullJob.remove();
} catch {
log("debug", "[QUEUE] Could not remove active job.", { jobId });
}
}
} catch {
log("warn", "[QUEUE] Failed to access queue during cancellation.", { jobId });
}
}
return { ok: true };
}
export const generationWorker = new Worker<FastJobData>(
FAST_QUEUE_NAME,
async (job: Job<FastJobData>) => {
const { input, jobId } = job.data;
const start = Date.now();
const [initialRow] = await db
.select({ status: generationJob.status })
.from(generationJob)
.where(eq(generationJob.id, jobId))
.limit(1);
if (
!initialRow ||
initialRow.status === "cancelled" ||
initialRow.status === "completed" ||
initialRow.status === "completed_partial"
) {
return;
}
const claimed = await db
.update(generationJob)
.set({ status: "running_fast" })
.where(
and(
eq(generationJob.id, jobId),
notInArray(generationJob.status, ["cancelled", "completed", "completed_partial"]),
),
)
.returning({ id: generationJob.id });
if (!claimed.length) return;
const cancelPoll = createCancellationPoller(jobId);
let heartbeatInterval: ReturnType<typeof setInterval> | null = null;
const startHeartbeat = () => {
if (heartbeatInterval) clearInterval(heartbeatInterval);
heartbeatInterval = setInterval(() => {
db
.update(generationJob)
.set({ updatedAt: new Date() })
.where(eq(generationJob.id, jobId))
.catch(() => {});
}, HEARTBEAT_MS);
};
const stopHeartbeat = () => {
if (heartbeatInterval) {
clearInterval(heartbeatInterval);
heartbeatInterval = null;
}
};
const pushLog = async (
step: string,
message: string,
status: "running" | "done" | "error",
details?: string,
) => {
const entry = {
step,
message,
status,
timestamp: new Date().toISOString(),
details,
};
const [row] = await db
.select({ logs: generationJob.logs })
.from(generationJob)
.where(eq(generationJob.id, jobId))
.limit(1);
const existing = (row?.logs ?? []) as Array<{
step: string;
message: string;
status: string;
timestamp: string;
details?: string;
}>;
await db
.update(generationJob)
.set({ logs: [...existing, entry] })
.where(eq(generationJob.id, jobId));
};
let maxProgress = 0;
const updateProgress = async (
progress: number,
progressMessage: string,
status?: string,
resultJson?: unknown,
) => {
cancelPoll.check();
const next = Math.max(maxProgress, progress);
maxProgress = next;
await job.updateProgress(next);
const [updated] = await db
.update(generationJob)
.set({
progress: next,
progressMessage,
...(status ? { status } : {}),
...(resultJson !== undefined ? { resultJson: resultJson as any } : {}),
})
.where(
and(
eq(generationJob.id, jobId),
notInArray(generationJob.status, ["cancelled"]),
),
)
.returning({ id: generationJob.id });
if (!updated) throw new GenerationJobCancelledError();
};
let approxTokens = 0;
const tokenCounter = (token: string) => {
cancelPoll.check();
approxTokens += Math.ceil(token.length / 4);
};
try {
startHeartbeat();
const selectedMode = input.mode;
const activeSections = input.selectedSections ?? [input.section];
const sectionSplits = computeSectionSplit(activeSections, input.questionCount);
const shards = splitIntoShards(sectionSplits);
const minPartialThreshold = Math.min(3, input.questionCount);
await updateProgress(
5,
`Planning ${sectionSplits.length} section(s), ${shards.length} shard(s)...`,
);
await pushLog(
"plan",
`Section plan: ${sectionSplits
.map((s) => `${s.section}(${s.count})`)
.join(", ")} | shards=${shards.length}`,
"done",
);
let totalTokens = 0;
let totalDurationMs = 0;
let completedShards = 0;
let partialPublished = false;
let timeToFirstValidQuestionMs: number | null = null;
const sectionPassages = new Map<string, string>();
if (selectedMode === "agentic") {
for (const split of sectionSplits) {
if (sectionPassages.has(split.section)) continue;
await updateProgress(8, `Menulis bacaan ${split.section}...`);
const passageInput: GenerationInput = {
...input,
section: split.section as GenerationInput["section"],
questionCount: split.count,
};
const passageResult = await generatePassageForInput(passageInput, tokenCounter);
totalTokens += passageResult.tokensUsed ?? 0;
sectionPassages.set(split.section, passageResult.passage);
await pushLog(
"generate_passage",
`Bacaan siap: ${passageResult.title}`,
"done",
passageResult.passage.slice(0, 400),
);
}
}
const shardResults: Array<{
shard: ShardPlan;
questions: PersistableQuestion[];
}> = [];
const runShard = async (shard: ShardPlan): Promise<void> => {
cancelPoll.check();
await pushLog(
"generate_shard",
`[${shard.section}] shard ${shard.shardIndex + 1}/${shard.shardCount} generating ${shard.count} question(s)`,
"running",
);
const subInput: GenerationInput = {
...input,
section: shard.section as any,
questionCount: shard.count,
};
let sectionResult: GenerationResult;
const onAgenticProgress = createAgenticProgressHandler(
(progress, progressMessage) => updateProgress(progress, progressMessage),
pushLog,
(agentic) => mapAgenticProgressInShard(agentic, completedShards, shards.length),
);
try {
if (selectedMode === "agentic") {
const sharedPassage = sectionPassages.get(shard.section);
if (sharedPassage) {
sectionResult = await generateQuestionsAgenticFromPassage(
subInput,
sharedPassage,
onAgenticProgress,
tokenCounter,
{ strategy: "lean", maxRegenerateAttempts: 1 },
);
} else {
sectionResult = await generateQuestionsAgentic(
subInput,
onAgenticProgress,
tokenCounter,
{ strategy: "lean", maxRegenerateAttempts: 1 },
);
}
} else {
sectionResult = await generateQuestionsQuick(subInput, {
onToken: tokenCounter,
});
}
} catch (quickErr: any) {
const quickErrorMessage = quickErr?.message ?? String(quickErr);
const shouldFallbackToAgentic =
QUICK_PARSE_FALLBACK_TO_AGENTIC &&
selectedMode === "quick" &&
(/Failed to parse AI response as JSON/i.test(quickErrorMessage) ||
/Unterminated string/i.test(quickErrorMessage) ||
/Missing 'questions' array/i.test(quickErrorMessage));
if (!shouldFallbackToAgentic) {
throw quickErr;
}
sectionResult = await generateQuestionsAgentic(
{ ...subInput, mode: "agentic" },
onAgenticProgress,
tokenCounter,
{ strategy: "lean", maxRegenerateAttempts: 1 },
);
}
const normalized = normalizeQuestions(
shard.section,
input.apiKeyConfig.model,
sectionResult,
);
shardResults.push({ shard, questions: normalized });
totalTokens += sectionResult.meta.tokensUsed ?? 0;
totalDurationMs += sectionResult.meta.durationMs;
completedShards += 1;
const progress = Math.min(
15 + Math.round((completedShards / shards.length) * 65),
80,
);
const generatedCount = shardResults.reduce(
(acc, item) => acc + item.questions.length,
0,
);
if (generatedCount > 0 && timeToFirstValidQuestionMs == null) {
timeToFirstValidQuestionMs = Date.now() - start;
}
await updateProgress(
progress,
`Fast generation: ${generatedCount}/${input.questionCount} soal`,
);
await pushLog(
"generate_shard",
`[${shard.section}] shard ${shard.shardIndex + 1}/${shard.shardCount} completed`,
"done",
);
if (!partialPublished && generatedCount >= minPartialThreshold) {
partialPublished = true;
const partialQuestions = shardResults
.sort((a, b) => {
if (a.shard.sectionIndex !== b.shard.sectionIndex) {
return a.shard.sectionIndex - b.shard.sectionIndex;
}
return a.shard.shardIndex - b.shard.shardIndex;
})
.flatMap((r) => r.questions)
.slice(0, input.questionCount);
const partialResult: GenerationResult = {
questions: partialQuestions as any,
meta: {
model: input.apiKeyConfig.model,
tokensUsed: totalTokens || approxTokens,
durationMs: Date.now() - start,
mode: input.mode,
},
};
await updateProgress(
70,
`Partial ready: ${partialQuestions.length} soal`,
"partial_ready",
{
...partialResult,
sectionSplits,
qualityPhase: "fast",
isPartial: true,
metrics: {
timeToFirstValidQuestionMs: timeToFirstValidQuestionMs ?? Date.now() - start,
shardCount: shards.length,
shardRetryBudget: MAX_SHARD_RETRIES,
},
},
);
}
};
const failedShards: ShardPlan[] = [];
const shardFailureInfo = new Map<string, { error: string; nonRetryable: boolean }>();
await runWithConcurrency(shards, FAST_SHARD_CONCURRENCY, async (shard) => {
try {
await runShard(shard);
} catch (err: any) {
const message = err?.message ?? String(err);
shardFailureInfo.set(shardKey(shard), {
error: message,
nonRetryable: isNonRetryableProviderError(err),
});
log("warn", "[GENERATION] Fast shard failed.", {
jobId,
section: shard.section,
nonRetryable: isNonRetryableProviderError(err),
});
failedShards.push(shard);
}
});
if (failedShards.length > 0) {
const retryableCount = failedShards.filter(
(shard) => !shardFailureInfo.get(shardKey(shard))?.nonRetryable,
).length;
if (retryableCount > 0) {
await pushLog(
"retry_budget",
`Retrying ${retryableCount} failed shard(s), budget=${MAX_SHARD_RETRIES}`,
"running",
);
}
}
for (const failedShard of failedShards) {
const failure = shardFailureInfo.get(shardKey(failedShard));
if (failure?.nonRetryable) {
await pushLog(
"retry_budget",
`[${failedShard.section}] provider error — skipping retries`,
"error",
failure.error.slice(0, 300),
);
continue;
}
let success = false;
for (let attempt = 1; attempt <= MAX_SHARD_RETRIES; attempt++) {
try {
await runShard(failedShard);
success = true;
break;
} catch (retryErr: any) {
const retryMessage = retryErr?.message ?? String(retryErr);
if (isNonRetryableProviderError(retryErr)) {
await pushLog(
"retry_budget",
`[${failedShard.section}] provider error — stopping retries`,
"error",
retryMessage.slice(0, 300),
);
break;
}
await pushLog(
"retry_budget",
`[${failedShard.section}] shard retry ${attempt}/${MAX_SHARD_RETRIES} failed: ${retryMessage}`,
"error",
);
}
}
if (!success && !failure?.nonRetryable) {
await pushLog(
"retry_budget",
`[${failedShard.section}] exhausted retry budget`,
"error",
);
}
}
const allQuestions = shardResults
.sort((a, b) => {
if (a.shard.sectionIndex !== b.shard.sectionIndex) {
return a.shard.sectionIndex - b.shard.sectionIndex;
}
return a.shard.shardIndex - b.shard.shardIndex;
})
.flatMap((r) => r.questions)
.slice(0, input.questionCount);
const outcome = resolveGenerationJobOutcome({
requestedCount: input.questionCount,
generatedCount: allQuestions.length,
failedSections: sectionsWithNoQuestions(sectionSplits, allQuestions),
cause: collectShardFailureCause(
failedShards.map((shard) => shardFailureInfo.get(shardKey(shard))),
),
});
if (outcome.status === "failed") {
await pushLog("save", outcome.errorMessage ?? "Generation failed", "error");
await failGenerationJob({
jobId,
errorMessage: outcome.errorMessage ?? "Generation failed",
tokensUsed: totalTokens || approxTokens || undefined,
durationMs: Date.now() - start,
});
return;
}
const finalizeParams = {
jobId,
input,
allQuestions,
sectionSplits,
totalTokens: totalTokens || approxTokens,
durationMs: Date.now() - start,
status: outcome.status,
statusMessage: outcome.progressMessage,
errorMessage: outcome.errorMessage,
metrics: {
timeToFirstValidQuestionMs: timeToFirstValidQuestionMs ?? Date.now() - start,
shardCount: shards.length,
shardRetryBudget: MAX_SHARD_RETRIES,
shardFailures: failedShards.length,
requestedQuestionCount: input.questionCount,
generatedQuestionCount: allQuestions.length,
...(selectedMode === "agentic" ? { singlePassAgentic: true } : {}),
},
};
if (selectedMode === "agentic") {
await pushLog("save", "Saving agentic result...", "running");
await completeJobWithResult(finalizeParams);
await pushLog(
"save",
outcome.status === "completed_partial"
? `Saved ${allQuestions.length}/${input.questionCount} questions (partial)`
: `Saved ${allQuestions.length} questions`,
outcome.status === "completed_partial" ? "error" : "done",
);
return;
}
await pushLog("save", "Saving quick result...", "running");
await completeJobWithResult(finalizeParams);
await pushLog(
"save",
outcome.status === "completed_partial"
? `Saved ${allQuestions.length}/${input.questionCount} questions (partial)`
: `Saved ${allQuestions.length} questions`,
outcome.status === "completed_partial" ? "error" : "done",
);
} catch (err: any) {
if (
err instanceof GenerationJobCancelledError ||
err?.name === "GenerationJobCancelledError"
) {
await db
.update(generationJob)
.set({
status: "cancelled",
errorMessage: "Dibatalkan pengguna",
durationMs: Date.now() - start,
completedAt: new Date(),
})
.where(eq(generationJob.id, jobId));
return;
}
let failedTokens: number | undefined;
if (err instanceof GenerationError) failedTokens = err.tokensUsed ?? undefined;
if (failedTokens == null && approxTokens > 0) failedTokens = approxTokens;
await db
.update(generationJob)
.set({
status: "failed",
errorMessage: err?.message ?? String(err),
tokensUsed: failedTokens,
durationMs: Date.now() - start,
completedAt: new Date(),
})
.where(eq(generationJob.id, jobId));
return;
} finally {
stopHeartbeat();
cancelPoll.stop();
}
},
{
connection: new IORedis(env.REDIS_URL, connectionOptions),
concurrency: 5,
},
);
export const generationQualityWorker = new Worker<QualityJobData>(
QUALITY_QUEUE_NAME,
async (job: Job<QualityJobData>) => {
const { input, jobId, sectionSplits, fastQuestions, fastMeta } = job.data;
const qualityStart = Date.now();
const [initialRow] = await db
.select({ status: generationJob.status })
.from(generationJob)
.where(eq(generationJob.id, jobId))
.limit(1);
if (
!initialRow ||
initialRow.status === "cancelled" ||
initialRow.status === "completed" ||
initialRow.status === "completed_partial"
) {
return;
}
const cancelPoll = createCancellationPoller(jobId);
let approxTokens = 0;
let maxProgress = 0;
const tokenCounter = (token: string) => {
cancelPoll.check();
approxTokens += Math.ceil(token.length / 4);
};
const updateProgress = async (progress: number, progressMessage: string) => {
cancelPoll.check();
const next = Math.max(maxProgress, progress);
maxProgress = next;
await job.updateProgress(next);
const [updated] = await db
.update(generationJob)
.set({
status: "running_quality",
progress: next,
progressMessage,
})
.where(
and(
eq(generationJob.id, jobId),
notInArray(generationJob.status, ["cancelled"]),
),
)
.returning({ id: generationJob.id });
if (!updated) throw new GenerationJobCancelledError();
};
const pushLog = async (
step: string,
message: string,
status: "running" | "done" | "error",
) => {
const entry = { step, message, status, timestamp: new Date().toISOString() };
const [row] = await db
.select({ logs: generationJob.logs })
.from(generationJob)
.where(eq(generationJob.id, jobId))
.limit(1);
const existing = (row?.logs ?? []) as Array<Record<string, unknown>>;
await db
.update(generationJob)
.set({ logs: [...existing, entry] as any })
.where(eq(generationJob.id, jobId));
};
try {
await updateProgress(86, "Quality phase started...");
await pushLog("quality_start", "Running deep quality validation...", "running");
let completedSections = 0;
const sectionResults = await runWithConcurrency(
sectionSplits,
QUALITY_SECTION_CONCURRENCY,
async (split) => {
try {
const sectionInput: GenerationInput = {
...input,
section: split.section as any,
questionCount: split.count,
mode: "agentic",
};
const onQualityProgress = createAgenticProgressHandler(
updateProgress,
pushLog,
mapAgenticProgressInQuality,
);
const result = await generateQuestionsAgentic(
sectionInput,
onQualityProgress,
tokenCounter,
{ strategy: "full", maxRegenerateAttempts: 2 },
);
return {
section: split.section,
questions: normalizeQuestions(
split.section,
input.apiKeyConfig.model,
result,
),
tokensUsed: result.meta.tokensUsed ?? 0,
};
} catch {
log("warn", "[GENERATION] Quality phase failed, using fast questions.", { jobId, section: split.section });
const fallbackQuestions = fastQuestions
.filter((q) => q.section === split.section)
.slice(0, split.count);
return {
section: split.section,
questions: fallbackQuestions,
tokensUsed: 0,
usedFallback: true,
};
} finally {
completedSections += 1;
const progress = Math.min(
86 + Math.round((completedSections / sectionSplits.length) * 10),
96,
);
await updateProgress(
progress,
`Quality phase ${completedSections}/${sectionSplits.length}`,
);
}
},
);
const mergedQuestions = sectionSplits
.flatMap((split) => {
const sectionEntry = sectionResults.find((r) => r.section === split.section);
return (sectionEntry?.questions ?? []).slice(0, split.count);
})
.slice(0, input.questionCount);
if (mergedQuestions.length === 0) {
throw new Error("Quality phase produced no questions");
}
const qualityTokens =
sectionResults.reduce((acc, cur) => acc + (cur.tokensUsed ?? 0), 0) +
(approxTokens > 0 ? approxTokens : 0);
const totalTokens =
(fastMeta.tokensUsed || fastMeta.approxTokens || 0) + qualityTokens;
await completeJobWithResult({
jobId,
input,
allQuestions: mergedQuestions,
sectionSplits,
totalTokens,
durationMs: Date.now() - qualityStart + fastMeta.durationMs,
statusMessage: "Completed (quality upgraded)",
metrics: {
qualityUpgraded: true,
qualitySections: sectionSplits.length,
qualityApproxTokens: approxTokens,
},
});
await pushLog("quality_done", "Quality upgrade completed", "done");
} catch (err: any) {
if (
err instanceof GenerationJobCancelledError ||
err?.name === "GenerationJobCancelledError"
) {
await db
.update(generationJob)
.set({
status: "cancelled",
errorMessage: "Dibatalkan pengguna",
completedAt: new Date(),
})
.where(eq(generationJob.id, jobId));
return;
}
// Fallback safety: complete using fast result if quality pass fails.
if (fastQuestions.length > 0) {
await completeJobWithResult({
jobId,
input,
allQuestions: fastQuestions.slice(0, input.questionCount),
sectionSplits,
totalTokens: fastMeta.tokensUsed || fastMeta.approxTokens || 0,
durationMs: fastMeta.durationMs,
statusMessage: "Completed (fast result, quality fallback)",
metrics: {
qualityUpgraded: false,
qualityFallback: true,
},
});
return;
}
await db
.update(generationJob)
.set({
status: "failed",
errorMessage: err?.message ?? String(err),
durationMs: Date.now() - qualityStart,
completedAt: new Date(),
})
.where(eq(generationJob.id, jobId));
return;
} finally {
cancelPoll.stop();
}
},
{
connection: new IORedis(env.REDIS_URL, connectionOptions),
concurrency: 1,
},
);
export async function enqueueGeneration(
userId: string,
input: GenerationInput,
): Promise<string> {
const encryptedInput = {
...input,
apiKeyConfig: {
...input.apiKeyConfig,
apiKey: encryptApiKey(input.apiKeyConfig.apiKey),
},
};
const [jobRecord] = await db
.insert(generationJob)
.values({
userId,
mode: input.mode,
examTypeId: input.examType,
sectionTypeId: input.section,
questionCount: input.questionCount,
status: "pending",
progress: 0,
inputJson: encryptedInput as any,
})
.returning();
if (!jobRecord) throw new Error("Failed to create generation job");
await generationQueue.add(
"generate-fast",
{ input, jobId: jobRecord.id },
{
jobId: jobRecord.id,
removeOnComplete: { count: 100 },
removeOnFail: { count: 100 },
attempts: 1,
},
);
return jobRecord.id;
}
export function decryptInputFromDb(inputJson: unknown): GenerationInput {
const data = inputJson as Record<string, unknown>;
const apiKeyConfig = data.apiKeyConfig as Record<string, unknown>;
if (apiKeyConfig?.apiKey && typeof apiKeyConfig.apiKey === "string") {
try {
return {
...(data as unknown as GenerationInput),
apiKeyConfig: {
...(apiKeyConfig as unknown as GenerationInput["apiKeyConfig"]),
apiKey: decryptApiKey(apiKeyConfig.apiKey),
},
};
} catch {
log("debug", "[QUEUE] API key decryption failed (legacy data).");
return data as unknown as GenerationInput;
}
}
return data as unknown as GenerationInput;
}
|