File size: 31,384 Bytes
f90228b 2858397 f90228b 2858397 36b41bf f90228b b87cbc7 2858397 f90228b 36b41bf 2858397 36b41bf 2858397 36b41bf 2858397 36b41bf 2858397 36b41bf 2858397 36b41bf 2858397 36b41bf 2858397 f90228b 36b41bf 2858397 36b41bf 2858397 36b41bf 2858397 36b41bf 2858397 36b41bf 2858397 36b41bf b762c97 2858397 b762c97 2858397 b762c97 2858397 b762c97 2858397 36b41bf f90228b 2858397 f90228b 0c932f9 2858397 0c932f9 f90228b 2858397 34f01ec c1e702e 2858397 c1e702e 2858397 f90228b c1e702e 2858397 c1e702e 2858397 c1e702e 2858397 c1e702e 2858397 c1e702e 2858397 c1e702e 34f01ec 2858397 c1e702e f90228b 2858397 f90228b 2858397 f90228b 2858397 f90228b 2858397 f90228b 2858397 f90228b 2858397 f90228b 2858397 f90228b 2858397 c1e702e 2858397 c1e702e 2858397 f90228b 2858397 f90228b 2858397 85cb661 2858397 f90228b 2858397 36b41bf 0c932f9 2858397 0c932f9 f90228b 2858397 f90228b 36b41bf f90228b b87cbc7 2858397 f90228b c96f44d f90228b 2858397 f90228b 2858397 f90228b | 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 | import { Queue, Worker, type Job } from "bullmq";
import IORedis from "ioredis";
import { env } from "@labas/env/server";
import {
generateQuestionsQuick,
generateQuestionsAgentic,
GenerationError,
type GenerationInput,
type GenerationResult,
} from "@labas/ai";
import { db } from "@labas/db";
import {
generationJob,
question,
testPackage,
packageSection,
sectionQuestion,
} from "@labas/db";
import { and, eq, notInArray } from "drizzle-orm";
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 = 6;
const FAST_SHARD_CONCURRENCY = 3;
const QUALITY_SECTION_CONCURRENCY = 2;
const MAX_SHARD_RETRIES = 2;
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";
}
}
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),
}));
}
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();
},
};
}
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;
}
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) {
await db.insert(sectionQuestion).values(
sectionQuestions
.map((q, idx) => ({
sectionId: sec.id,
questionId: savedQuestionIds[q._globalIndex],
orderIndex: idx,
}))
.filter((q) => q.questionId != null) 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 };
}
async function completeJobWithResult(params: {
jobId: string;
input: GenerationInput;
statusMessage?: string;
allQuestions: PersistableQuestion[];
sectionSplits: SectionSplit[];
totalTokens: number;
durationMs: number;
metrics?: Record<string, unknown>;
}) {
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: "completed",
progress: 100,
progressMessage: params.statusMessage ?? "Completed",
resultJson: {
...result,
savedQuestionIds,
generatedPackageId,
sectionSplits: params.sectionSplits,
qualityPhase: "final",
metrics: params.metrics,
} as any,
tokensUsed: params.totalTokens,
durationMs: params.durationMs,
completedAt: new Date(),
})
.where(eq(generationJob.id, params.jobId));
}
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 === "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 {
// Likely active; worker exits cooperatively.
}
}
} catch {
// Ignore queue hiccups.
}
}
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"
) {
return;
}
const claimed = await db
.update(generationJob)
.set({ status: "running_fast" })
.where(
and(
eq(generationJob.id, jobId),
notInArray(generationJob.status, ["cancelled", "completed"]),
),
)
.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));
};
const updateProgress = async (
progress: number,
progressMessage: string,
status?: string,
resultJson?: unknown,
) => {
cancelPoll.check();
await job.updateProgress(progress);
await db
.update(generationJob)
.set({
progress,
progressMessage,
...(status ? { status } : {}),
...(resultJson !== undefined ? { resultJson: resultJson as any } : {}),
})
.where(eq(generationJob.id, jobId));
};
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 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;
try {
if (selectedMode === "agentic") {
sectionResult = await generateQuestionsAgentic(
subInput,
undefined,
tokenCounter,
{ strategy: "lean", maxRegenerateAttempts: 1 },
);
} else {
sectionResult = await generateQuestionsQuick(subInput, {
onToken: tokenCounter,
});
}
} catch (quickErr: any) {
const quickErrorMessage = quickErr?.message ?? String(quickErr);
const shouldFallbackToAgentic =
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" },
undefined,
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[] = [];
await runWithConcurrency(shards, FAST_SHARD_CONCURRENCY, async (shard) => {
try {
await runShard(shard);
} catch {
failedShards.push(shard);
}
});
if (failedShards.length > 0) {
await pushLog(
"retry_budget",
`Retrying ${failedShards.length} failed shard(s), budget=${MAX_SHARD_RETRIES}`,
"running",
);
}
for (const failedShard of failedShards) {
let success = false;
for (let attempt = 1; attempt <= MAX_SHARD_RETRIES; attempt++) {
try {
await runShard(failedShard);
success = true;
break;
} catch (retryErr: any) {
await pushLog(
"retry_budget",
`[${failedShard.section}] shard retry ${attempt}/${MAX_SHARD_RETRIES} failed: ${retryErr?.message ?? String(retryErr)}`,
"error",
);
}
}
if (!success) {
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);
if (allQuestions.length === 0) {
throw new Error("No questions generated in fast phase");
}
const fastResult: GenerationResult = {
questions: allQuestions as any,
meta: {
model: input.apiKeyConfig.model,
tokensUsed: totalTokens || approxTokens,
durationMs: totalDurationMs || Date.now() - start,
mode: input.mode,
},
};
if (selectedMode === "agentic") {
await updateProgress(85, "Fast phase done, enqueuing quality phase...", "running_quality", {
...fastResult,
sectionSplits,
qualityPhase: "fast",
isPartial: true,
metrics: {
timeToFirstValidQuestionMs: timeToFirstValidQuestionMs ?? Date.now() - start,
shardCount: shards.length,
shardRetryBudget: MAX_SHARD_RETRIES,
},
});
await pushLog(
"quality_queue",
"Partial result ready, lanjut quality upgrade di background",
"done",
);
await generationQualityQueue.add(
"quality-upgrade",
{
input,
jobId,
sectionSplits,
fastQuestions: allQuestions,
fastMeta: {
tokensUsed: totalTokens,
durationMs: totalDurationMs || Date.now() - start,
approxTokens,
},
},
{
jobId,
removeOnComplete: { count: 100 },
removeOnFail: { count: 100 },
attempts: 2,
backoff: { type: "exponential", delay: 4000 },
},
);
return;
}
await pushLog("save", "Saving quick result...", "running");
await completeJobWithResult({
jobId,
input,
allQuestions,
sectionSplits,
totalTokens: totalTokens || approxTokens,
durationMs: Date.now() - start,
statusMessage: "Completed",
metrics: {
timeToFirstValidQuestionMs: timeToFirstValidQuestionMs ?? Date.now() - start,
shardCount: shards.length,
shardRetryBudget: MAX_SHARD_RETRIES,
shardFailures: failedShards.length,
},
});
await pushLog("save", `Saved ${allQuestions.length} questions`, "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));
throw err;
} 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 cancelPoll = createCancellationPoller(jobId);
let approxTokens = 0;
const tokenCounter = (token: string) => {
cancelPoll.check();
approxTokens += Math.ceil(token.length / 4);
};
const updateProgress = async (progress: number, progressMessage: string) => {
cancelPoll.check();
await job.updateProgress(progress);
await db
.update(generationJob)
.set({
status: "running_quality",
progress,
progressMessage,
})
.where(eq(generationJob.id, jobId));
};
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 result = await generateQuestionsAgentic(
sectionInput,
undefined,
tokenCounter,
{ strategy: "full", maxRegenerateAttempts: 2 },
);
return {
section: split.section,
questions: normalizeQuestions(
split.section,
input.apiKeyConfig.model,
result,
),
tokensUsed: result.meta.tokensUsed ?? 0,
};
} catch {
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));
throw err;
} finally {
cancelPoll.stop();
}
},
{
connection: new IORedis(env.REDIS_URL, connectionOptions),
concurrency: 1,
},
);
export async function enqueueGeneration(
userId: string,
input: GenerationInput,
): Promise<string> {
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: input 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: 3,
backoff: {
type: "exponential",
delay: 5000,
},
},
);
return jobRecord.id;
}
|