Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
129 changes: 108 additions & 21 deletions open-sse/services/batchProcessor.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,20 @@
import { v4 as uuidv4 } from "uuid";
import type { BatchRecord } from "@/lib/localDb";
import type { BatchItemCheckpoint, BatchRecord } from "@/lib/localDb";
import {
countBatchItemCheckpoints,
createFile,
deleteFile,
ensureBatchItemCheckpoints,
getApiKeyById,
getBatch,
getFileContent,
getPendingBatches,
getTerminalBatches,
listBatchItemCheckpoints,
listFiles,
markBatchItemError,
markBatchItemProcessing,
markBatchItemResult,
updateBatch,
} from "@/lib/localDb";
import { dispatch } from "@/lib/batches/dispatch";
Expand Down Expand Up @@ -67,28 +73,12 @@ export async function processPendingBatches(): Promise<void> {
const pending = getPendingBatches();

// Phase 1: Stale recovery — in_progress/finalizing batches not in activeBatches
// are from a previous session; reset them to validating so they get picked up fresh
// are from a previous session; reset checkpointed batches to validating so they
// can be completed without replaying already-dispatched items.
for (const batch of pending) {
if (batch.status === "in_progress" || batch.status === "finalizing") {
if (!activeBatches.has(batch.id)) {
console.log(`[BATCH] Recovering stale batch ${batch.id} (${batch.status}) → validating`);

if (batch.outputFileId) {
deleteFile(batch.outputFileId);
}
if (batch.errorFileId) {
deleteFile(batch.errorFileId);
}

updateBatch(batch.id, {
status: "validating",
inProgressAt: null,
finalizingAt: null,
outputFileId: null,
errorFileId: null,
requestCountsCompleted: 0,
requestCountsFailed: 0,
});
recoverStaleBatch(batch);
}
}
}
Expand Down Expand Up @@ -116,6 +106,49 @@ export async function processPendingBatches(): Promise<void> {
await cleanupExpiredBatches();
}

function recoverStaleBatch(batch: BatchRecord): void {
const checkpointCount = countBatchItemCheckpoints(batch.id);
const hasPotentialExternalEffects =
batch.requestCountsTotal > 0 ||
batch.requestCountsCompleted > 0 ||
batch.requestCountsFailed > 0 ||
batch.status === "finalizing";

if (checkpointCount === 0 && hasPotentialExternalEffects) {
console.warn(
`[BATCH] Stale batch ${batch.id} has no item checkpoints; failing instead of replaying provider calls`
);
failBatch(
batch.id,
"Cannot safely recover stale batch because item checkpoints are unavailable; create a new batch to retry intentionally."
);
return;
}

console.log(`[BATCH] Recovering stale batch ${batch.id} (${batch.status}) → validating`);

if (batch.outputFileId) {
deleteFile(batch.outputFileId);
}
if (batch.errorFileId) {
deleteFile(batch.errorFileId);
}

updateBatch(batch.id, {
status: "validating",
inProgressAt: null,
finalizingAt: null,
outputFileId: null,
errorFileId: null,
...(checkpointCount === 0
? {
requestCountsCompleted: 0,
requestCountsFailed: 0,
}
: {}),
});
}

function parseBatchWindowSeconds(window: string | null | undefined): number {
if (!window) return DEFAULT_BATCH_WINDOW_SECONDS;
const match = /^(\d+)([hdm])$/.exec(window);
Expand Down Expand Up @@ -285,6 +318,8 @@ async function startBatch(batch: any): Promise<void> {

console.log(`[BATCH] Batch ${batch.id} contains (${total} items)`);

ensureBatchItemCheckpoints(batch.id, parsedItems.items);

updateBatch(batch.id, {
status: "in_progress",
inProgressAt: Math.floor(Date.now() / 1000),
Expand Down Expand Up @@ -316,12 +351,21 @@ const HEADERS_CACHE_TTL_MS = 60_000;

async function processBatchItems(batch: BatchRecord, items: BatchRequestItem[]): Promise<void> {
const state = createBatchState(batch);
const checkpoints = new Map<number, BatchItemCheckpoint>(
listBatchItemCheckpoints(batch.id).map((checkpoint) => [checkpoint.lineNumber, checkpoint])
);

const apiKey = await resolveApiKey(batch);

for (const item of items) {
if (isBatchCancelled(batch.id)) break;

const checkpoint = checkpoints.get(item.lineNumber);
if (checkpoint && applyRecoveredCheckpoint(batch.id, item, checkpoint, state)) {
maybePersistProgress(batch.id, state);
continue;
}

const cachedHeaders =
prevHeaders && Date.now() - prevHeadersTimestamp < HEADERS_CACHE_TTL_MS ? prevHeaders : null;
if (cachedHeaders) {
Expand All @@ -331,6 +375,8 @@ async function processBatchItems(batch: BatchRecord, items: BatchRequestItem[]):
}
}

markBatchItemProcessing(batch.id, item);

try {
const response = await processSingleItemWithRetry(item, apiKey);
let responseBody: unknown;
Expand All @@ -352,13 +398,17 @@ async function processBatchItems(batch: BatchRecord, items: BatchRequestItem[]):
},
};

markBatchItemResult(batch.id, item, wrapped);
state.results.push(wrapped);
applyItemResult(state, response.status, responseBody);
prevHeaders = response.headers;
prevHeadersTimestamp = Date.now();
} catch (exception) {
// Track processing-level errors separately (items that failed to be processed)
state.errors.push({ custom_id: item.customId ?? null, error: String(exception) });
const error = { custom_id: item.customId ?? null, error: String(exception) };
markBatchItemError(batch.id, item, error);
state.errors.push(error);
state.failed++;
prevHeaders = null;
prevHeadersTimestamp = 0;
}
Expand All @@ -369,6 +419,43 @@ async function processBatchItems(batch: BatchRecord, items: BatchRequestItem[]):
return finalizeBatch(batch.id, state.results, state.errors);
}

function applyRecoveredCheckpoint(
batchId: string,
item: BatchRequestItem,
checkpoint: BatchItemCheckpoint,
state: ReturnType<typeof createBatchState>
): boolean {
if (checkpoint.status === "completed" && checkpoint.result) {
state.results.push(checkpoint.result);
applyItemResult(
state,
checkpoint.result.response?.status_code ?? 500,
checkpoint.result.response?.body
);
return true;
}

if (checkpoint.status === "errored" && checkpoint.error) {
state.errors.push(checkpoint.error);
state.failed++;
return true;
}

if (checkpoint.status === "processing") {
const error = {
custom_id: item.customId ?? null,
error:
"Batch item was interrupted before its provider response was recorded; it was not replayed to avoid duplicate provider work.",
};
markBatchItemError(batchId, item, error);
state.errors.push(error);
state.failed++;
return true;
}

return false;
}

function isBatchCancelled(batchId: string): boolean {
const current = getBatch(batchId);

Expand Down
164 changes: 164 additions & 0 deletions src/lib/db/batches.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,42 @@ export interface BatchRecord {
outputExpiresAfterAnchor?: string | null;
}

export type BatchItemCheckpointStatus = "pending" | "processing" | "completed" | "errored";

export interface BatchItemCheckpoint {
batchId: string;
lineNumber: number;
customId: string | null;
status: BatchItemCheckpointStatus;
result: any | null;
error: any | null;
createdAt: number;
updatedAt: number;
}

function parseJsonColumn(value: unknown): any | null {
if (value == null) return null;
if (typeof value !== "string") return value;
try {
return JSON.parse(value);
} catch {
return null;
}
}

function parseBatchItemCheckpoint(row: any): BatchItemCheckpoint {
return {
batchId: row.batch_id,
lineNumber: Number(row.line_number),
customId: row.custom_id ?? null,
status: row.status,
result: parseJsonColumn(row.result_json),
error: parseJsonColumn(row.error_json),
createdAt: Number(row.created_at),
updatedAt: Number(row.updated_at),
};
}

export function createBatch(
batch: Omit<
BatchRecord,
Expand Down Expand Up @@ -156,6 +192,128 @@ export function updateBatch(id: string, updates: Partial<BatchRecord>): boolean
return result.changes > 0;
}

export function ensureBatchItemCheckpoints(
batchId: string,
items: Array<{ lineNumber: number; customId: string | null }>
): void {
if (items.length === 0) return;

const db = getDbInstance();
const now = Math.floor(Date.now() / 1000);
const insert = db.prepare(`
INSERT OR IGNORE INTO batch_item_checkpoints (
batch_id,
line_number,
custom_id,
status,
result_json,
error_json,
created_at,
updated_at
)
VALUES (?, ?, ?, 'pending', NULL, NULL, ?, ?)
`);

const tx = db.transaction(() => {
for (const item of items) {
insert.run(batchId, item.lineNumber, item.customId, now, now);
}
});
tx();
}

export function countBatchItemCheckpoints(batchId: string): number {
const db = getDbInstance();
const row = db
.prepare("SELECT COUNT(*) AS c FROM batch_item_checkpoints WHERE batch_id = ?")
.get(batchId) as { c: number } | undefined;
return row ? Number(row.c) : 0;
}

export function listBatchItemCheckpoints(batchId: string): BatchItemCheckpoint[] {
const db = getDbInstance();
const rows = db
.prepare(
`
SELECT batch_id, line_number, custom_id, status, result_json, error_json, created_at, updated_at
FROM batch_item_checkpoints
WHERE batch_id = ?
ORDER BY line_number ASC
`
)
.all(batchId);
return rows.map((row) => parseBatchItemCheckpoint(row));
}

export function markBatchItemProcessing(
batchId: string,
item: { lineNumber: number; customId: string | null }
): void {
const db = getDbInstance();
const now = Math.floor(Date.now() / 1000);
db.prepare(
`
INSERT INTO batch_item_checkpoints (
batch_id,
line_number,
custom_id,
status,
result_json,
error_json,
created_at,
updated_at
)
VALUES (?, ?, ?, 'processing', NULL, NULL, ?, ?)
ON CONFLICT(batch_id, line_number) DO UPDATE SET
custom_id = excluded.custom_id,
status = 'processing',
result_json = NULL,
error_json = NULL,
updated_at = excluded.updated_at
`
).run(batchId, item.lineNumber, item.customId, now, now);
}

export function markBatchItemResult(
batchId: string,
item: { lineNumber: number; customId: string | null },
result: any
): void {
const db = getDbInstance();
const now = Math.floor(Date.now() / 1000);
db.prepare(
`
UPDATE batch_item_checkpoints
SET custom_id = ?,
status = 'completed',
result_json = ?,
error_json = NULL,
updated_at = ?
WHERE batch_id = ? AND line_number = ?
`
).run(item.customId, JSON.stringify(result), now, batchId, item.lineNumber);
}

export function markBatchItemError(
batchId: string,
item: { lineNumber: number; customId: string | null },
error: any
): void {
const db = getDbInstance();
const now = Math.floor(Date.now() / 1000);
db.prepare(
`
UPDATE batch_item_checkpoints
SET custom_id = ?,
status = 'errored',
result_json = NULL,
error_json = ?,
updated_at = ?
WHERE batch_id = ? AND line_number = ?
`
).run(item.customId, JSON.stringify(error), now, batchId, item.lineNumber);
}

export function listBatches(apiKeyId?: string, limit: number = 20, after?: string): BatchRecord[] {
const db = getDbInstance();
const afterBatch = after ? getBatch(after) : null;
Expand Down Expand Up @@ -224,6 +382,8 @@ export function deleteBatch(id: string): boolean {
const batch = getBatch(id);
if (!batch) return false;

db.prepare("DELETE FROM batch_item_checkpoints WHERE batch_id = ?").run(id);

// Soft-delete associated files (input, output, error)
if (batch.inputFileId) {
try {
Expand Down Expand Up @@ -281,6 +441,10 @@ export function deleteCompletedBatches(): { deletedBatches: number; deletedFiles
}
}

db.prepare(
"DELETE FROM batch_item_checkpoints WHERE batch_id IN (SELECT id FROM batches WHERE status = 'completed')"
).run();

const result = db.prepare("DELETE FROM batches WHERE status = 'completed'").run();
return { deletedBatches: result.changes, deletedFiles };
}
Loading