2026-05-21 12:27:07 +00:00
|
|
|
|
import { existsSync } from "node:fs";
|
|
|
|
|
|
import { fileURLToPath } from "node:url";
|
2026-05-29 18:04:42 +07:00
|
|
|
|
import type { Client } from "discord.js-selfbot-v13";
|
2026-05-28 01:09:57 +07:00
|
|
|
|
import { AbortError } from "p-retry";
|
2026-05-25 22:14:05 +07:00
|
|
|
|
import { Piscina } from "piscina";
|
2026-05-21 12:03:31 +00:00
|
|
|
|
import { config } from "../config.js";
|
|
|
|
|
|
import { createChildLogger } from "../logger.js";
|
2026-05-27 23:25:37 +07:00
|
|
|
|
import { retryWithBackoff } from "../retry.js";
|
2026-05-29 18:04:42 +07:00
|
|
|
|
import { attemptAutoDeleteFlaggedMessage } from "./autoDeleteManager.js";
|
2026-05-25 23:23:12 +07:00
|
|
|
|
import {
|
2026-05-27 23:25:37 +07:00
|
|
|
|
buildConversationContext,
|
2026-05-25 23:23:12 +07:00
|
|
|
|
estimateTokens,
|
|
|
|
|
|
formatMessageForPrompt,
|
|
|
|
|
|
} from "./conversationContext.js";
|
2026-05-27 23:25:37 +07:00
|
|
|
|
import { runModerationAnalysis } from "./llmModerationClient.js";
|
2026-05-14 15:02:23 +07:00
|
|
|
|
import {
|
2026-05-27 23:25:37 +07:00
|
|
|
|
getAttachmentsForMessages,
|
|
|
|
|
|
getConversationContextBefore,
|
2026-05-27 23:32:38 +07:00
|
|
|
|
getConversationKeysWithIncompleteAnalysis,
|
|
|
|
|
|
getIncompleteMessagesByConversation,
|
2026-05-14 19:39:25 +07:00
|
|
|
|
getMessageById,
|
2026-05-14 19:32:44 +07:00
|
|
|
|
getPendingConversationKeys,
|
|
|
|
|
|
getPendingMessagesByConversation,
|
2026-05-27 23:25:37 +07:00
|
|
|
|
updateMessagesAIAnalysisBulk,
|
2026-05-21 12:03:31 +00:00
|
|
|
|
} from "./messageStore.js";
|
2026-05-15 07:13:37 +07:00
|
|
|
|
import type {
|
|
|
|
|
|
AnalysisQueueStatus,
|
|
|
|
|
|
MessageRecord,
|
|
|
|
|
|
ModerationBroadcaster,
|
2026-05-21 12:03:31 +00:00
|
|
|
|
} from "./types.js";
|
2026-05-14 02:31:16 +07:00
|
|
|
|
|
|
|
|
|
|
const logger = createChildLogger("ai-analyzer");
|
2026-05-14 19:32:44 +07:00
|
|
|
|
|
2026-05-15 07:13:37 +07:00
|
|
|
|
type ModerationGlobal = typeof globalThis & {
|
|
|
|
|
|
moderationBroadcaster?: ModerationBroadcaster;
|
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|
|
function getModerationBroadcaster(): ModerationBroadcaster | undefined {
|
|
|
|
|
|
return (globalThis as ModerationGlobal).moderationBroadcaster;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-05-29 18:04:42 +07:00
|
|
|
|
function scheduleAutoDelete(row: MessageRecord): void {
|
|
|
|
|
|
if (row.ai_status !== "flagged") return;
|
|
|
|
|
|
const run = () => {
|
|
|
|
|
|
attemptAutoDeleteFlaggedMessage(moderationClient, row).catch((error) => {
|
|
|
|
|
|
logger.error(
|
|
|
|
|
|
{
|
|
|
|
|
|
messageId: row.id,
|
|
|
|
|
|
error: error instanceof Error ? error.message : String(error),
|
|
|
|
|
|
},
|
|
|
|
|
|
"Unexpected auto-delete error",
|
|
|
|
|
|
);
|
|
|
|
|
|
});
|
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|
|
if (config.AUTO_DELETE_FLAGGED_DELAY_MS > 0) {
|
|
|
|
|
|
setTimeout(run, config.AUTO_DELETE_FLAGGED_DELAY_MS);
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
setImmediate(run);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-05-27 23:32:38 +07:00
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
// Batch pipeline state
|
|
|
|
|
|
// ---------------------------------------------------------------------------
|
2026-05-14 19:32:44 +07:00
|
|
|
|
|
2026-05-27 23:32:38 +07:00
|
|
|
|
/** Debounce timer handle per conversation key. */
|
|
|
|
|
|
const conversationDebounceTimers = new Map<string, NodeJS.Timeout>();
|
|
|
|
|
|
/** Timestamp of when processing started per conversation key. */
|
|
|
|
|
|
const conversationProcessing = new Map<string, number>();
|
|
|
|
|
|
/** Cooldown expiry timestamp per conversation key after an error. */
|
|
|
|
|
|
const conversationErrorCooldown = new Map<string, number>();
|
2026-05-21 02:39:28 +07:00
|
|
|
|
|
2026-05-14 03:54:12 +07:00
|
|
|
|
let activeRequests = 0;
|
2026-05-14 19:32:44 +07:00
|
|
|
|
let lastError: string | null = null;
|
2026-05-29 18:04:42 +07:00
|
|
|
|
let moderationClient: Client | undefined;
|
2026-05-14 02:31:16 +07:00
|
|
|
|
|
2026-05-27 23:32:38 +07:00
|
|
|
|
// Batch circuit breaker
|
2026-05-25 22:14:05 +07:00
|
|
|
|
let consecutiveErrors = 0;
|
|
|
|
|
|
const MAX_CONSECUTIVE_ERRORS = 5;
|
|
|
|
|
|
let globalCooldownUntil = 0;
|
|
|
|
|
|
|
2026-05-27 23:25:37 +07:00
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
// Individual fallback queue — runs PARALLEL to the batch pipeline.
|
|
|
|
|
|
//
|
2026-05-27 23:32:38 +07:00
|
|
|
|
// Design guarantees:
|
|
|
|
|
|
// • Concurrency is capped at config.AI_ANALYSIS_INDIVIDUAL_MAX_CONCURRENT.
|
|
|
|
|
|
// • A flat Set<messageId> de-duplicates so the same message can't be
|
|
|
|
|
|
// in-flight twice (Discord snowflakes are globally unique, but be safe).
|
|
|
|
|
|
// • A Map<conversationKey, count> lets the recovery worker skip conversations
|
|
|
|
|
|
// that already have individual work in progress (#4 fix).
|
|
|
|
|
|
// • A separate circuit breaker prevents a cascade of individual failures
|
|
|
|
|
|
// from hammering a down/rate-limited LLM endpoint (#1+#5 fix).
|
2026-05-27 23:25:37 +07:00
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
|
2026-05-27 23:32:38 +07:00
|
|
|
|
/** IDs currently being processed one-by-one. */
|
2026-05-27 23:25:37 +07:00
|
|
|
|
const individualInFlight = new Set<string>();
|
|
|
|
|
|
|
2026-05-27 23:32:38 +07:00
|
|
|
|
/**
|
|
|
|
|
|
* Per-conversation count of in-flight individual messages.
|
|
|
|
|
|
* Used by the recovery worker to avoid re-scheduling a conversation that
|
|
|
|
|
|
* already has individual fallback work running for it.
|
|
|
|
|
|
*/
|
|
|
|
|
|
const individualInFlightByConversation = new Map<string, number>();
|
|
|
|
|
|
|
|
|
|
|
|
/** Counter for observability. */
|
2026-05-27 23:25:37 +07:00
|
|
|
|
let activeIndividualRequests = 0;
|
|
|
|
|
|
|
2026-05-27 23:32:38 +07:00
|
|
|
|
// Individual fallback circuit breaker (independent of batch CB)
|
|
|
|
|
|
let individualConsecutiveErrors = 0;
|
|
|
|
|
|
let individualCooldownUntil = 0;
|
|
|
|
|
|
const INDIVIDUAL_COOLDOWN_MS = 30000;
|
|
|
|
|
|
|
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
// Piscina worker pool (batch path only)
|
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
|
2026-05-25 22:14:05 +07:00
|
|
|
|
function getAnalysisWorkerUrl(): URL {
|
|
|
|
|
|
const candidates = [
|
|
|
|
|
|
new URL("./aiAnalysisWorker.js", import.meta.url),
|
|
|
|
|
|
new URL("../aiAnalysisWorker.js", import.meta.url),
|
|
|
|
|
|
new URL("./aiAnalysisWorker.ts", import.meta.url),
|
|
|
|
|
|
];
|
|
|
|
|
|
|
|
|
|
|
|
for (const candidate of candidates) {
|
|
|
|
|
|
if (existsSync(fileURLToPath(candidate))) {
|
|
|
|
|
|
return candidate;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
return candidates[2];
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
const workerPool = new Piscina({
|
|
|
|
|
|
filename: fileURLToPath(getAnalysisWorkerUrl()),
|
|
|
|
|
|
execArgv: process.execArgv,
|
|
|
|
|
|
});
|
|
|
|
|
|
|
2026-05-15 21:40:20 +07:00
|
|
|
|
interface AnalysisWorkerResponse {
|
|
|
|
|
|
ok: boolean;
|
|
|
|
|
|
conversationKey: string;
|
|
|
|
|
|
rows: MessageRecord[];
|
|
|
|
|
|
error?: string;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-05-27 23:32:38 +07:00
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
// Exported helpers
|
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
|
2026-05-14 19:32:44 +07:00
|
|
|
|
/**
|
2026-05-27 23:32:38 +07:00
|
|
|
|
* Gets the conversation key for a message (thread_id or channel_id).
|
2026-05-14 19:32:44 +07:00
|
|
|
|
*/
|
|
|
|
|
|
export function getConversationKey(message: MessageRecord): string {
|
|
|
|
|
|
return message.thread_id || message.channel_id;
|
2026-05-14 02:31:16 +07:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-05-14 19:32:44 +07:00
|
|
|
|
/**
|
2026-05-27 23:32:38 +07:00
|
|
|
|
* Picks a batch of messages within a token budget.
|
|
|
|
|
|
* `tokensPerMessage` accounts for JSON structure overhead around each entry.
|
2026-05-14 19:32:44 +07:00
|
|
|
|
*/
|
|
|
|
|
|
export function pickBatchWithinBudget(
|
2026-05-14 15:02:23 +07:00
|
|
|
|
messages: MessageRecord[],
|
2026-05-14 19:32:44 +07:00
|
|
|
|
maxTokens: number,
|
|
|
|
|
|
tokensPerMessage: number,
|
|
|
|
|
|
): MessageRecord[] {
|
|
|
|
|
|
const batch: MessageRecord[] = [];
|
|
|
|
|
|
let usedTokens = 0;
|
2026-05-14 04:23:11 +07:00
|
|
|
|
|
2026-05-14 19:32:44 +07:00
|
|
|
|
for (const msg of messages) {
|
2026-05-25 23:23:12 +07:00
|
|
|
|
const formatted = formatMessageForPrompt(msg, "target");
|
|
|
|
|
|
const msgTokens = estimateTokens(formatted) + tokensPerMessage;
|
2026-05-14 04:24:19 +07:00
|
|
|
|
|
2026-05-14 19:32:44 +07:00
|
|
|
|
if (usedTokens + msgTokens <= maxTokens) {
|
|
|
|
|
|
batch.push(msg);
|
|
|
|
|
|
usedTokens += msgTokens;
|
2026-05-14 04:08:41 +07:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-05-14 19:32:44 +07:00
|
|
|
|
return batch;
|
2026-05-14 02:31:16 +07:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-05-27 23:32:38 +07:00
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
// Conversation lock helpers
|
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
|
2026-05-21 02:39:28 +07:00
|
|
|
|
function isConversationProcessingLocked(conversationKey: string): boolean {
|
|
|
|
|
|
const startedAt = conversationProcessing.get(conversationKey);
|
2026-05-27 23:32:38 +07:00
|
|
|
|
// FIX #7: use configurable timeout that exceeds (LLM timeout × max retries).
|
|
|
|
|
|
// Old hardcoded value was 30 000 ms — shorter than a single LLM call under retries.
|
2026-05-21 02:39:28 +07:00
|
|
|
|
return Boolean(
|
2026-05-27 23:32:38 +07:00
|
|
|
|
startedAt &&
|
|
|
|
|
|
Date.now() - startedAt < config.AI_ANALYSIS_PROCESSING_TIMEOUT_MS,
|
2026-05-21 02:39:28 +07:00
|
|
|
|
);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-05-27 23:32:38 +07:00
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
// Individual fallback pipeline
|
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
|
2026-05-14 19:32:44 +07:00
|
|
|
|
/**
|
2026-05-27 23:32:38 +07:00
|
|
|
|
* Processes a single message directly in the main process (no IPC/worker
|
|
|
|
|
|
* pool overhead). Never called from the batch path.
|
|
|
|
|
|
*
|
|
|
|
|
|
* FIX #1+#5: Increments the individual circuit breaker on failure so a
|
|
|
|
|
|
* sustained outage stops hammering the LLM endpoint.
|
2026-05-28 00:07:55 +07:00
|
|
|
|
*
|
|
|
|
|
|
* Infinite-loop prevention: if the LLM consistently drops the single target
|
|
|
|
|
|
* message across all retries (analysis_incomplete), we write a terminal flag
|
|
|
|
|
|
* 'individual_analysis_exhausted' to DB instead of 'analysis_incomplete'.
|
|
|
|
|
|
* The recovery worker only queries for 'analysis_incomplete', so exhausted
|
|
|
|
|
|
* messages are permanently excluded from the reprocessing loop.
|
|
|
|
|
|
* Transient failures (network/parse/DB) are NOT written as exhausted — they
|
|
|
|
|
|
* stay as 'analysis_incomplete' so the circuit-breaker-throttled recovery
|
|
|
|
|
|
* cycle can retry them later.
|
2026-05-27 23:25:37 +07:00
|
|
|
|
*/
|
|
|
|
|
|
async function processIndividualFallback(
|
|
|
|
|
|
message: MessageRecord,
|
|
|
|
|
|
): Promise<void> {
|
|
|
|
|
|
const { id: messageId } = message;
|
2026-05-27 23:32:38 +07:00
|
|
|
|
const conversationKey = getConversationKey(message);
|
|
|
|
|
|
|
2026-05-27 23:25:37 +07:00
|
|
|
|
activeIndividualRequests++;
|
2026-05-27 23:32:38 +07:00
|
|
|
|
// Increment per-conversation counter so the recovery worker can see it.
|
|
|
|
|
|
individualInFlightByConversation.set(
|
|
|
|
|
|
conversationKey,
|
|
|
|
|
|
(individualInFlightByConversation.get(conversationKey) ?? 0) + 1,
|
|
|
|
|
|
);
|
|
|
|
|
|
|
2026-05-28 00:07:55 +07:00
|
|
|
|
// Track whether all retries were exhausted specifically because the LLM
|
|
|
|
|
|
// consistently returned no result for this message (vs. a transient error).
|
|
|
|
|
|
let exhaustedOnIncomplete = false;
|
|
|
|
|
|
|
2026-05-27 23:25:37 +07:00
|
|
|
|
try {
|
|
|
|
|
|
const contextBefore = await getConversationContextBefore({
|
|
|
|
|
|
channelId: message.channel_id,
|
|
|
|
|
|
threadId: message.thread_id,
|
|
|
|
|
|
beforeCreatedAt: message.created_at,
|
|
|
|
|
|
limit: config.AI_ANALYSIS_CONTEXT_MESSAGE_LIMIT,
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
const contextLines = buildConversationContext({
|
|
|
|
|
|
contextBefore,
|
|
|
|
|
|
targets: [message],
|
|
|
|
|
|
maxTokens: config.AI_ANALYSIS_MAX_CONTEXT_TOKENS,
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
const contextIds = contextBefore.map((m) => m.id);
|
|
|
|
|
|
const attachments = await getAttachmentsForMessages([
|
|
|
|
|
|
messageId,
|
|
|
|
|
|
...contextIds,
|
|
|
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
|
|
const analysisResult = await retryWithBackoff(
|
2026-05-28 00:07:55 +07:00
|
|
|
|
async () => {
|
2026-05-28 01:09:57 +07:00
|
|
|
|
try {
|
|
|
|
|
|
const result = await runModerationAnalysis({
|
|
|
|
|
|
targets: [message],
|
|
|
|
|
|
contextText: contextLines.join("\n"),
|
|
|
|
|
|
attachments,
|
|
|
|
|
|
});
|
2026-05-28 00:07:55 +07:00
|
|
|
|
|
2026-05-28 01:09:57 +07:00
|
|
|
|
// If the LLM still dropped our only target, convert to a retryable
|
|
|
|
|
|
// throw so backoff kicks in. Track this so the catch block can
|
|
|
|
|
|
// distinguish it from a transient network/parse failure.
|
|
|
|
|
|
const stillIncomplete = result.results.some((r) =>
|
|
|
|
|
|
r.flags.includes("analysis_incomplete"),
|
2026-05-28 00:07:55 +07:00
|
|
|
|
);
|
2026-05-28 01:09:57 +07:00
|
|
|
|
if (stillIncomplete) {
|
|
|
|
|
|
exhaustedOnIncomplete = true;
|
|
|
|
|
|
throw new Error(
|
|
|
|
|
|
`LLM returned no result for single-target message ${messageId} — will retry with backoff`,
|
|
|
|
|
|
);
|
|
|
|
|
|
}
|
2026-05-28 00:07:55 +07:00
|
|
|
|
|
2026-05-28 01:09:57 +07:00
|
|
|
|
// Got a real result — clear the incomplete flag.
|
|
|
|
|
|
exhaustedOnIncomplete = false;
|
|
|
|
|
|
|
|
|
|
|
|
return result;
|
|
|
|
|
|
} catch (err: any) {
|
|
|
|
|
|
// Propagate AbortError so outer retry is immediately cancelled on 429.
|
|
|
|
|
|
if (err instanceof AbortError) {
|
|
|
|
|
|
throw err;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (
|
|
|
|
|
|
err?.status === 429 ||
|
|
|
|
|
|
err?.status === 401 ||
|
|
|
|
|
|
err?.status === 403
|
|
|
|
|
|
) {
|
|
|
|
|
|
throw new AbortError(err);
|
|
|
|
|
|
}
|
|
|
|
|
|
throw err;
|
|
|
|
|
|
}
|
2026-05-28 00:07:55 +07:00
|
|
|
|
},
|
2026-05-27 23:25:37 +07:00
|
|
|
|
{
|
|
|
|
|
|
retries: 2,
|
|
|
|
|
|
minTimeout: 2000,
|
|
|
|
|
|
maxTimeout: 15000,
|
|
|
|
|
|
logger,
|
|
|
|
|
|
},
|
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
|
|
const updates = analysisResult.results.map((r) => ({
|
|
|
|
|
|
messageId: r.messageId,
|
|
|
|
|
|
result: {
|
|
|
|
|
|
status: r.status,
|
|
|
|
|
|
flags: JSON.stringify(r.flags),
|
|
|
|
|
|
score: r.score,
|
|
|
|
|
|
raw: JSON.stringify(analysisResult.raw),
|
|
|
|
|
|
analysis: r.analysis,
|
2026-05-30 01:02:51 +07:00
|
|
|
|
categories: r.categories,
|
|
|
|
|
|
severity: r.severity,
|
|
|
|
|
|
confidence: r.confidence,
|
|
|
|
|
|
recommendedAction: r.recommendedAction,
|
|
|
|
|
|
policyVersion: r.policyVersion,
|
|
|
|
|
|
evidence: r.evidence,
|
2026-05-27 23:25:37 +07:00
|
|
|
|
analyzedAt: Date.now(),
|
|
|
|
|
|
error: null,
|
|
|
|
|
|
},
|
|
|
|
|
|
}));
|
|
|
|
|
|
|
|
|
|
|
|
const rows = await updateMessagesAIAnalysisBulk(updates);
|
|
|
|
|
|
for (const row of rows) {
|
|
|
|
|
|
getModerationBroadcaster()?.messageAnalyzed(row);
|
2026-05-29 18:04:42 +07:00
|
|
|
|
scheduleAutoDelete(row);
|
2026-05-27 23:25:37 +07:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-05-27 23:32:38 +07:00
|
|
|
|
// Reset individual CB on success.
|
|
|
|
|
|
individualConsecutiveErrors = 0;
|
|
|
|
|
|
|
2026-05-27 23:25:37 +07:00
|
|
|
|
logger.info(
|
|
|
|
|
|
{ messageId, status: analysisResult.results[0]?.status },
|
|
|
|
|
|
"Individual fallback analysis complete",
|
|
|
|
|
|
);
|
|
|
|
|
|
} catch (error) {
|
2026-05-27 23:32:38 +07:00
|
|
|
|
// FIX #5: individual failures now feed their own circuit breaker.
|
|
|
|
|
|
individualConsecutiveErrors++;
|
|
|
|
|
|
if (
|
|
|
|
|
|
individualConsecutiveErrors >= config.AI_ANALYSIS_INDIVIDUAL_CB_THRESHOLD
|
|
|
|
|
|
) {
|
|
|
|
|
|
individualCooldownUntil = Date.now() + INDIVIDUAL_COOLDOWN_MS;
|
|
|
|
|
|
logger.warn(
|
|
|
|
|
|
{
|
|
|
|
|
|
threshold: config.AI_ANALYSIS_INDIVIDUAL_CB_THRESHOLD,
|
|
|
|
|
|
cooldownUntil: new Date(individualCooldownUntil).toISOString(),
|
|
|
|
|
|
},
|
|
|
|
|
|
"Individual fallback circuit breaker triggered",
|
|
|
|
|
|
);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-05-27 23:25:37 +07:00
|
|
|
|
lastError = error instanceof Error ? error.message : String(error);
|
2026-05-28 00:07:55 +07:00
|
|
|
|
|
|
|
|
|
|
// Infinite-loop prevention: if all retries were exhausted because the LLM
|
|
|
|
|
|
// consistently dropped this specific message (not a transient error),
|
|
|
|
|
|
// overwrite the DB entry with a terminal flag that the recovery query
|
|
|
|
|
|
// does NOT match. This permanently removes it from the recovery loop
|
|
|
|
|
|
// while keeping it visible as an error in the dashboard.
|
|
|
|
|
|
if (exhaustedOnIncomplete) {
|
|
|
|
|
|
await updateMessagesAIAnalysisBulk([
|
|
|
|
|
|
{
|
|
|
|
|
|
messageId,
|
|
|
|
|
|
result: {
|
|
|
|
|
|
status: "error",
|
|
|
|
|
|
flags: JSON.stringify(["individual_analysis_exhausted"]),
|
|
|
|
|
|
score: 0,
|
|
|
|
|
|
raw: null,
|
|
|
|
|
|
analysis:
|
|
|
|
|
|
"Individual fallback exhausted all retries: LLM consistently dropped this message even in single-target mode",
|
2026-05-30 01:02:51 +07:00
|
|
|
|
categories: ["individual_analysis_exhausted"],
|
|
|
|
|
|
severity: "none",
|
|
|
|
|
|
confidence: 0,
|
|
|
|
|
|
recommendedAction: "review",
|
|
|
|
|
|
policyVersion: "default-2026-05-30",
|
|
|
|
|
|
evidence: [],
|
2026-05-28 00:07:55 +07:00
|
|
|
|
analyzedAt: Date.now(),
|
|
|
|
|
|
error: lastError,
|
|
|
|
|
|
},
|
|
|
|
|
|
},
|
|
|
|
|
|
]).catch((dbErr) => {
|
|
|
|
|
|
logger.error(
|
|
|
|
|
|
{ messageId, error: String(dbErr) },
|
|
|
|
|
|
"Failed to write terminal exhausted status — message may re-enter recovery loop",
|
|
|
|
|
|
);
|
|
|
|
|
|
});
|
|
|
|
|
|
logger.warn(
|
|
|
|
|
|
{ messageId },
|
|
|
|
|
|
"Individual fallback exhausted — marked as individual_analysis_exhausted to stop recovery loop",
|
|
|
|
|
|
);
|
|
|
|
|
|
} else {
|
|
|
|
|
|
// Transient failure (network/parse/DB): do NOT write terminal status.
|
|
|
|
|
|
// Message stays as error/analysis_incomplete in DB and will be retried
|
|
|
|
|
|
// by the recovery worker, subject to the individual circuit breaker.
|
|
|
|
|
|
logger.error(
|
|
|
|
|
|
{
|
|
|
|
|
|
messageId,
|
|
|
|
|
|
error: lastError,
|
|
|
|
|
|
stack: error instanceof Error ? error.stack : undefined,
|
|
|
|
|
|
},
|
|
|
|
|
|
"Individual fallback analysis failed (transient) — will be retried by recovery worker",
|
|
|
|
|
|
);
|
|
|
|
|
|
}
|
2026-05-27 23:25:37 +07:00
|
|
|
|
} finally {
|
|
|
|
|
|
activeIndividualRequests--;
|
|
|
|
|
|
individualInFlight.delete(messageId);
|
2026-05-27 23:32:38 +07:00
|
|
|
|
|
|
|
|
|
|
// Decrement per-conversation counter; remove key when it hits zero.
|
|
|
|
|
|
const prev = individualInFlightByConversation.get(conversationKey) ?? 1;
|
|
|
|
|
|
if (prev <= 1) {
|
|
|
|
|
|
individualInFlightByConversation.delete(conversationKey);
|
|
|
|
|
|
} else {
|
|
|
|
|
|
individualInFlightByConversation.set(conversationKey, prev - 1);
|
|
|
|
|
|
}
|
2026-05-27 23:25:37 +07:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
2026-05-27 23:32:38 +07:00
|
|
|
|
* Fans out message records to the individual fallback queue.
|
|
|
|
|
|
*
|
|
|
|
|
|
* FIX #1: Checks concurrency cap before admitting new work.
|
|
|
|
|
|
* FIX #5: Checks individual circuit breaker before admitting new work.
|
|
|
|
|
|
* Messages that cannot be admitted remain as `error/analysis_incomplete` in
|
|
|
|
|
|
* the DB and will be picked up by the recovery worker on the next interval.
|
2026-05-27 23:25:37 +07:00
|
|
|
|
*/
|
|
|
|
|
|
function enqueueIndividualFallbacks(messages: MessageRecord[]): void {
|
2026-05-27 23:32:38 +07:00
|
|
|
|
// FIX #5: Honour the individual circuit breaker.
|
|
|
|
|
|
if (Date.now() < individualCooldownUntil) {
|
|
|
|
|
|
logger.warn(
|
|
|
|
|
|
{
|
|
|
|
|
|
until: new Date(individualCooldownUntil).toISOString(),
|
|
|
|
|
|
skipped: messages.length,
|
|
|
|
|
|
},
|
|
|
|
|
|
"Individual fallback circuit breaker active — messages will be recovered later",
|
|
|
|
|
|
);
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-05-27 23:25:37 +07:00
|
|
|
|
const newMessages = messages.filter((m) => !individualInFlight.has(m.id));
|
|
|
|
|
|
if (newMessages.length === 0) return;
|
|
|
|
|
|
|
2026-05-27 23:32:38 +07:00
|
|
|
|
// FIX #1: Enforce concurrency cap.
|
|
|
|
|
|
const availableSlots =
|
|
|
|
|
|
config.AI_ANALYSIS_INDIVIDUAL_MAX_CONCURRENT - individualInFlight.size;
|
|
|
|
|
|
if (availableSlots <= 0) {
|
|
|
|
|
|
logger.warn(
|
|
|
|
|
|
{
|
|
|
|
|
|
cap: config.AI_ANALYSIS_INDIVIDUAL_MAX_CONCURRENT,
|
|
|
|
|
|
inFlight: individualInFlight.size,
|
|
|
|
|
|
skipped: newMessages.length,
|
|
|
|
|
|
},
|
|
|
|
|
|
"Individual fallback concurrency cap reached — messages will be recovered by recovery worker",
|
|
|
|
|
|
);
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
const toProcess = newMessages.slice(0, availableSlots);
|
|
|
|
|
|
const skipped = newMessages.length - toProcess.length;
|
|
|
|
|
|
|
2026-05-27 23:25:37 +07:00
|
|
|
|
logger.info(
|
|
|
|
|
|
{
|
2026-05-27 23:32:38 +07:00
|
|
|
|
count: toProcess.length,
|
|
|
|
|
|
skipped,
|
|
|
|
|
|
messageIds: toProcess.map((m) => m.id),
|
2026-05-27 23:25:37 +07:00
|
|
|
|
},
|
|
|
|
|
|
"Enqueueing individual fallback analysis for batch-incomplete messages",
|
|
|
|
|
|
);
|
|
|
|
|
|
|
2026-05-27 23:32:38 +07:00
|
|
|
|
for (const msg of toProcess) {
|
2026-05-27 23:25:37 +07:00
|
|
|
|
individualInFlight.add(msg.id);
|
2026-05-27 23:32:38 +07:00
|
|
|
|
// Fire-and-forget: processIndividualFallback handles all errors internally.
|
2026-05-27 23:25:37 +07:00
|
|
|
|
processIndividualFallback(msg).catch((err) => {
|
2026-05-27 23:32:38 +07:00
|
|
|
|
// Belt-and-suspenders guard — should never reach here.
|
2026-05-27 23:25:37 +07:00
|
|
|
|
logger.error(
|
|
|
|
|
|
{ messageId: msg.id, error: String(err) },
|
2026-05-27 23:32:38 +07:00
|
|
|
|
"Unexpected uncaught error escaping processIndividualFallback",
|
2026-05-27 23:25:37 +07:00
|
|
|
|
);
|
|
|
|
|
|
individualInFlight.delete(msg.id);
|
2026-05-27 23:32:38 +07:00
|
|
|
|
const ck = getConversationKey(msg);
|
|
|
|
|
|
const prev = individualInFlightByConversation.get(ck) ?? 1;
|
|
|
|
|
|
if (prev <= 1) {
|
|
|
|
|
|
individualInFlightByConversation.delete(ck);
|
|
|
|
|
|
} else {
|
|
|
|
|
|
individualInFlightByConversation.set(ck, prev - 1);
|
|
|
|
|
|
}
|
2026-05-27 23:25:37 +07:00
|
|
|
|
});
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-05-27 23:32:38 +07:00
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
// Batch pipeline
|
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
|
2026-05-14 19:32:44 +07:00
|
|
|
|
async function processBatch(
|
|
|
|
|
|
conversationKey: string,
|
|
|
|
|
|
messages: MessageRecord[],
|
|
|
|
|
|
): Promise<void> {
|
2026-05-14 04:08:41 +07:00
|
|
|
|
if (messages.length === 0) return;
|
2026-05-25 22:14:05 +07:00
|
|
|
|
if (Date.now() < globalCooldownUntil) {
|
2026-05-25 23:23:12 +07:00
|
|
|
|
return;
|
2026-05-25 22:14:05 +07:00
|
|
|
|
}
|
2026-05-14 04:08:41 +07:00
|
|
|
|
|
2026-05-14 03:54:12 +07:00
|
|
|
|
activeRequests++;
|
2026-05-21 02:56:41 +07:00
|
|
|
|
let shouldScheduleNext = false;
|
2026-05-21 02:39:28 +07:00
|
|
|
|
const processingStartedAt = Date.now();
|
|
|
|
|
|
conversationProcessing.set(conversationKey, processingStartedAt);
|
2026-05-14 02:31:16 +07:00
|
|
|
|
try {
|
2026-05-25 23:23:12 +07:00
|
|
|
|
const result = (await workerPool.run({
|
|
|
|
|
|
conversationKey,
|
|
|
|
|
|
messages,
|
|
|
|
|
|
})) as AnalysisWorkerResponse;
|
2026-05-14 04:08:41 +07:00
|
|
|
|
|
2026-05-15 21:40:20 +07:00
|
|
|
|
for (const row of result.rows) {
|
2026-05-15 07:13:37 +07:00
|
|
|
|
getModerationBroadcaster()?.messageAnalyzed(row);
|
2026-05-29 18:04:42 +07:00
|
|
|
|
scheduleAutoDelete(row);
|
2026-05-14 19:32:44 +07:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-05-15 21:40:20 +07:00
|
|
|
|
if (!result.ok) {
|
2026-05-25 22:14:05 +07:00
|
|
|
|
consecutiveErrors++;
|
|
|
|
|
|
if (consecutiveErrors >= MAX_CONSECUTIVE_ERRORS) {
|
|
|
|
|
|
globalCooldownUntil = Date.now() + 60000;
|
2026-05-25 23:23:12 +07:00
|
|
|
|
logger.warn(
|
|
|
|
|
|
"Global circuit breaker triggered due to consecutive errors",
|
|
|
|
|
|
);
|
2026-05-25 22:14:05 +07:00
|
|
|
|
}
|
2026-05-25 23:23:12 +07:00
|
|
|
|
|
2026-05-27 23:25:37 +07:00
|
|
|
|
// Batch failed entirely — fall back all messages to individual queue
|
|
|
|
|
|
// so no message is permanently lost behind a cooldown.
|
|
|
|
|
|
logger.warn(
|
|
|
|
|
|
{
|
|
|
|
|
|
conversationKey,
|
|
|
|
|
|
messageCount: messages.length,
|
|
|
|
|
|
error: result.error,
|
|
|
|
|
|
},
|
|
|
|
|
|
"Batch failed entirely — routing all messages to individual fallback queue",
|
|
|
|
|
|
);
|
|
|
|
|
|
enqueueIndividualFallbacks(messages);
|
|
|
|
|
|
|
2026-05-15 21:40:20 +07:00
|
|
|
|
lastError = result.error ?? "Analysis worker failed";
|
|
|
|
|
|
conversationErrorCooldown.set(
|
|
|
|
|
|
conversationKey,
|
2026-05-21 01:55:50 +07:00
|
|
|
|
Date.now() + config.AI_ANALYSIS_ERROR_COOLDOWN_MS,
|
2026-05-15 21:40:20 +07:00
|
|
|
|
);
|
|
|
|
|
|
logger.error(
|
2026-05-18 23:48:02 +07:00
|
|
|
|
{
|
|
|
|
|
|
conversationKey,
|
|
|
|
|
|
error: lastError,
|
|
|
|
|
|
messageCount: messages.length,
|
|
|
|
|
|
messageIds: messages.map((m) => m.id),
|
2026-05-21 01:55:50 +07:00
|
|
|
|
cooldownUntil: new Date(
|
|
|
|
|
|
Date.now() + config.AI_ANALYSIS_ERROR_COOLDOWN_MS,
|
|
|
|
|
|
).toISOString(),
|
2026-05-18 23:48:02 +07:00
|
|
|
|
timestamp: new Date().toISOString(),
|
|
|
|
|
|
},
|
2026-05-18 23:46:51 +07:00
|
|
|
|
"Batch analysis failed, will retry after cooldown",
|
2026-05-15 21:40:20 +07:00
|
|
|
|
);
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-05-27 23:25:37 +07:00
|
|
|
|
// Batch succeeded — but check for messages the LLM silently dropped.
|
|
|
|
|
|
// Rows with flag "analysis_incomplete" were produced by parseModerationResponse
|
|
|
|
|
|
// as synthetic errors; they must be re-processed individually.
|
|
|
|
|
|
const incompleteMessages = messages.filter((msg) => {
|
|
|
|
|
|
const row = result.rows.find((r) => r.id === msg.id);
|
|
|
|
|
|
if (!row) {
|
|
|
|
|
|
// The DB update row is missing entirely — treat as incomplete.
|
|
|
|
|
|
return true;
|
|
|
|
|
|
}
|
|
|
|
|
|
const flags: string[] = (() => {
|
|
|
|
|
|
try {
|
|
|
|
|
|
return JSON.parse(row.ai_moderation_flags ?? "[]") as string[];
|
|
|
|
|
|
} catch {
|
|
|
|
|
|
return [];
|
|
|
|
|
|
}
|
|
|
|
|
|
})();
|
|
|
|
|
|
return row.ai_status === "error" && flags.includes("analysis_incomplete");
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
if (incompleteMessages.length > 0) {
|
|
|
|
|
|
logger.warn(
|
|
|
|
|
|
{
|
|
|
|
|
|
conversationKey,
|
|
|
|
|
|
incompleteCount: incompleteMessages.length,
|
|
|
|
|
|
incompleteIds: incompleteMessages.map((m) => m.id),
|
|
|
|
|
|
totalBatchSize: messages.length,
|
|
|
|
|
|
},
|
|
|
|
|
|
"Batch returned incomplete results — fanning out to individual fallback queue",
|
|
|
|
|
|
);
|
|
|
|
|
|
enqueueIndividualFallbacks(incompleteMessages);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-05-27 23:32:38 +07:00
|
|
|
|
consecutiveErrors = 0; // Reset batch circuit breaker
|
2026-05-14 19:39:25 +07:00
|
|
|
|
conversationErrorCooldown.delete(conversationKey);
|
2026-05-21 02:56:41 +07:00
|
|
|
|
shouldScheduleNext = true;
|
2026-05-14 19:32:44 +07:00
|
|
|
|
} catch (error) {
|
2026-05-25 22:14:05 +07:00
|
|
|
|
consecutiveErrors++;
|
|
|
|
|
|
if (consecutiveErrors >= MAX_CONSECUTIVE_ERRORS) {
|
|
|
|
|
|
globalCooldownUntil = Date.now() + 60000;
|
|
|
|
|
|
logger.warn("Global circuit breaker triggered due to consecutive errors");
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-05-27 23:25:37 +07:00
|
|
|
|
// Unhandled exception — route everything to individual fallback.
|
|
|
|
|
|
logger.warn(
|
|
|
|
|
|
{ conversationKey, messageCount: messages.length },
|
|
|
|
|
|
"Batch threw exception — routing all messages to individual fallback queue",
|
|
|
|
|
|
);
|
|
|
|
|
|
enqueueIndividualFallbacks(messages);
|
|
|
|
|
|
|
2026-05-14 19:32:44 +07:00
|
|
|
|
lastError = error instanceof Error ? error.message : String(error);
|
2026-05-18 23:48:02 +07:00
|
|
|
|
const errorStack = error instanceof Error ? error.stack : undefined;
|
2026-05-15 21:40:20 +07:00
|
|
|
|
conversationErrorCooldown.set(
|
|
|
|
|
|
conversationKey,
|
2026-05-21 01:55:50 +07:00
|
|
|
|
Date.now() + config.AI_ANALYSIS_ERROR_COOLDOWN_MS,
|
2026-05-15 21:40:20 +07:00
|
|
|
|
);
|
2026-05-14 19:32:44 +07:00
|
|
|
|
logger.error(
|
2026-05-18 23:48:02 +07:00
|
|
|
|
{
|
|
|
|
|
|
conversationKey,
|
|
|
|
|
|
error: lastError,
|
|
|
|
|
|
stack: errorStack,
|
|
|
|
|
|
messageCount: messages.length,
|
|
|
|
|
|
messageIds: messages.map((m) => m.id),
|
2026-05-21 01:55:50 +07:00
|
|
|
|
cooldownUntil: new Date(
|
|
|
|
|
|
Date.now() + config.AI_ANALYSIS_ERROR_COOLDOWN_MS,
|
|
|
|
|
|
).toISOString(),
|
2026-05-18 23:48:02 +07:00
|
|
|
|
timestamp: new Date().toISOString(),
|
|
|
|
|
|
},
|
2026-05-18 23:46:51 +07:00
|
|
|
|
"Analysis worker failed, will retry after cooldown",
|
2026-05-14 19:32:44 +07:00
|
|
|
|
);
|
2026-05-14 03:54:12 +07:00
|
|
|
|
} finally {
|
|
|
|
|
|
activeRequests--;
|
2026-05-21 02:39:28 +07:00
|
|
|
|
if (conversationProcessing.get(conversationKey) === processingStartedAt) {
|
|
|
|
|
|
conversationProcessing.delete(conversationKey);
|
|
|
|
|
|
}
|
2026-05-21 02:56:41 +07:00
|
|
|
|
if (shouldScheduleNext) {
|
|
|
|
|
|
setImmediate(() => scheduleConversationAnalysis(conversationKey));
|
|
|
|
|
|
}
|
2026-05-14 02:31:16 +07:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-05-27 23:32:38 +07:00
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
// Scheduling
|
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
|
2026-05-14 19:32:44 +07:00
|
|
|
|
/**
|
2026-05-27 23:32:38 +07:00
|
|
|
|
* Schedules a debounced analysis run for a conversation.
|
|
|
|
|
|
*
|
|
|
|
|
|
* FIX #3: The async work inside setTimeout is now wrapped in an explicit
|
|
|
|
|
|
* .catch() so DB errors don't produce unhandled promise rejections.
|
|
|
|
|
|
* FIX #6: Calls pickBatchWithinBudget after fetching messages so token budget
|
|
|
|
|
|
* is respected before handing the batch to the LLM.
|
2026-05-14 19:32:44 +07:00
|
|
|
|
*/
|
|
|
|
|
|
function scheduleConversationAnalysis(conversationKey: string): void {
|
2026-05-21 02:39:28 +07:00
|
|
|
|
if (isConversationProcessingLocked(conversationKey)) {
|
2026-05-14 19:39:25 +07:00
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-05-25 23:23:12 +07:00
|
|
|
|
const convoCooldown = conversationErrorCooldown.get(conversationKey) || 0;
|
|
|
|
|
|
const activeCooldown = Math.max(convoCooldown, globalCooldownUntil);
|
|
|
|
|
|
|
|
|
|
|
|
if (activeCooldown && Date.now() < activeCooldown) {
|
|
|
|
|
|
if (!conversationDebounceTimers.has(conversationKey)) {
|
|
|
|
|
|
const remaining = activeCooldown - Date.now();
|
|
|
|
|
|
const timer = setTimeout(() => {
|
|
|
|
|
|
conversationDebounceTimers.delete(conversationKey);
|
|
|
|
|
|
scheduleConversationAnalysis(conversationKey);
|
2026-05-27 23:32:38 +07:00
|
|
|
|
}, remaining + 500);
|
2026-05-25 23:23:12 +07:00
|
|
|
|
conversationDebounceTimers.set(conversationKey, timer);
|
|
|
|
|
|
}
|
2026-05-14 19:39:25 +07:00
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-05-14 19:32:44 +07:00
|
|
|
|
const existingTimer = conversationDebounceTimers.get(conversationKey);
|
|
|
|
|
|
if (existingTimer) {
|
|
|
|
|
|
clearTimeout(existingTimer);
|
2026-05-14 02:31:16 +07:00
|
|
|
|
}
|
2026-05-14 19:32:44 +07:00
|
|
|
|
|
2026-05-27 23:32:38 +07:00
|
|
|
|
const timer = setTimeout(() => {
|
2026-05-14 19:32:44 +07:00
|
|
|
|
conversationDebounceTimers.delete(conversationKey);
|
|
|
|
|
|
|
2026-05-27 23:32:38 +07:00
|
|
|
|
// FIX #3: explicit .catch() — no async arrow function to avoid unhandled rejection.
|
|
|
|
|
|
getPendingMessagesByConversation(
|
2026-05-14 19:32:44 +07:00
|
|
|
|
conversationKey,
|
2026-05-21 01:55:50 +07:00
|
|
|
|
config.AI_ANALYSIS_MAX_BATCH_SIZE,
|
2026-05-27 23:32:38 +07:00
|
|
|
|
)
|
|
|
|
|
|
.then((messages) => {
|
|
|
|
|
|
if (messages.length === 0) return;
|
2026-05-14 19:32:44 +07:00
|
|
|
|
|
2026-05-27 23:32:38 +07:00
|
|
|
|
// FIX #6: trim to token budget before sending to LLM.
|
|
|
|
|
|
// 50 tokens overhead accounts for JSON structure + id/username fields.
|
2026-05-28 00:07:55 +07:00
|
|
|
|
let trimmed = pickBatchWithinBudget(
|
2026-05-27 23:32:38 +07:00
|
|
|
|
messages,
|
|
|
|
|
|
config.AI_ANALYSIS_MAX_TARGET_TOKENS,
|
|
|
|
|
|
50,
|
|
|
|
|
|
);
|
2026-05-28 00:07:55 +07:00
|
|
|
|
|
|
|
|
|
|
// FIX #10: if every message individually exceeds the token budget,
|
|
|
|
|
|
// pickBatchWithinBudget returns [] — which would leave them permanently
|
|
|
|
|
|
// stuck as `pending`. Fall back to the first message alone so at
|
|
|
|
|
|
// least one makes progress; the rest will be processed in later ticks.
|
|
|
|
|
|
if (trimmed.length === 0 && messages.length > 0) {
|
|
|
|
|
|
trimmed = messages.slice(0, 1);
|
|
|
|
|
|
logger.warn(
|
|
|
|
|
|
{
|
|
|
|
|
|
conversationKey,
|
|
|
|
|
|
messageId: messages[0]?.id,
|
|
|
|
|
|
tokenBudget: config.AI_ANALYSIS_MAX_TARGET_TOKENS,
|
|
|
|
|
|
},
|
|
|
|
|
|
"All messages exceed token budget — processing first message alone to avoid stuck-pending deadlock",
|
|
|
|
|
|
);
|
|
|
|
|
|
}
|
2026-05-27 23:32:38 +07:00
|
|
|
|
|
|
|
|
|
|
return processBatch(conversationKey, trimmed);
|
|
|
|
|
|
})
|
|
|
|
|
|
.catch((err) => {
|
|
|
|
|
|
logger.error(
|
|
|
|
|
|
{
|
|
|
|
|
|
conversationKey,
|
|
|
|
|
|
error: err instanceof Error ? err.message : String(err),
|
|
|
|
|
|
},
|
|
|
|
|
|
"Failed to fetch or dispatch pending messages for scheduled analysis",
|
|
|
|
|
|
);
|
|
|
|
|
|
});
|
|
|
|
|
|
}, config.AI_ANALYSIS_DEBOUNCE_MS);
|
2026-05-14 19:32:44 +07:00
|
|
|
|
|
|
|
|
|
|
conversationDebounceTimers.set(conversationKey, timer);
|
2026-05-14 02:31:16 +07:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-05-27 23:32:38 +07:00
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
// Public API
|
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
|
2026-05-14 19:32:44 +07:00
|
|
|
|
/**
|
2026-05-27 23:32:38 +07:00
|
|
|
|
* Queues a message for analysis (debounced by conversation).
|
2026-05-14 19:32:44 +07:00
|
|
|
|
*/
|
2026-05-14 19:39:25 +07:00
|
|
|
|
export async function queueMessageAnalysis(messageId: string): Promise<void> {
|
2026-05-14 02:31:16 +07:00
|
|
|
|
if (!config.AI_ANALYSIS_ENABLED) return;
|
2026-05-14 19:32:44 +07:00
|
|
|
|
|
2026-05-14 19:39:25 +07:00
|
|
|
|
try {
|
|
|
|
|
|
const message = await getMessageById(messageId);
|
|
|
|
|
|
if (!message) {
|
|
|
|
|
|
logger.warn({ messageId }, "Message not found for analysis queue");
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
2026-05-27 23:32:38 +07:00
|
|
|
|
queueConversationAnalysis(getConversationKey(message));
|
2026-05-14 19:39:25 +07:00
|
|
|
|
} catch (error) {
|
|
|
|
|
|
logger.error(
|
|
|
|
|
|
{
|
|
|
|
|
|
messageId,
|
|
|
|
|
|
error: error instanceof Error ? error.message : String(error),
|
|
|
|
|
|
},
|
|
|
|
|
|
"Failed to queue message for analysis",
|
|
|
|
|
|
);
|
|
|
|
|
|
}
|
2026-05-14 02:31:16 +07:00
|
|
|
|
}
|
2026-05-14 02:44:26 +07:00
|
|
|
|
|
2026-05-14 19:32:44 +07:00
|
|
|
|
/**
|
2026-05-27 23:32:38 +07:00
|
|
|
|
* Queues a conversation for analysis (debounced).
|
2026-05-14 19:32:44 +07:00
|
|
|
|
*/
|
|
|
|
|
|
export function queueConversationAnalysis(conversationKey: string): void {
|
|
|
|
|
|
if (!config.AI_ANALYSIS_ENABLED) return;
|
|
|
|
|
|
scheduleConversationAnalysis(conversationKey);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
2026-05-27 23:32:38 +07:00
|
|
|
|
* Returns current status of both the batch and individual fallback queues.
|
2026-05-14 19:32:44 +07:00
|
|
|
|
*/
|
|
|
|
|
|
export function getAnalysisQueueStatus(): AnalysisQueueStatus {
|
|
|
|
|
|
return {
|
|
|
|
|
|
queuedConversations: conversationDebounceTimers.size,
|
|
|
|
|
|
activeRequests,
|
2026-05-27 23:25:37 +07:00
|
|
|
|
activeIndividualRequests,
|
|
|
|
|
|
individualInFlightCount: individualInFlight.size,
|
2026-05-27 23:32:38 +07:00
|
|
|
|
individualCircuitBreakerActive: Date.now() < individualCooldownUntil,
|
2026-05-14 19:32:44 +07:00
|
|
|
|
lastError,
|
|
|
|
|
|
};
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
2026-05-27 23:32:38 +07:00
|
|
|
|
* Starts the periodic recovery worker.
|
|
|
|
|
|
*
|
|
|
|
|
|
* FIX #4: Now also recovers messages stuck in `error/analysis_incomplete`
|
|
|
|
|
|
* state (not just `pending`), and skips conversations that already have
|
|
|
|
|
|
* individual fallback work in progress to avoid DB last-write-wins races.
|
2026-05-14 19:32:44 +07:00
|
|
|
|
*/
|
2026-05-29 18:04:42 +07:00
|
|
|
|
export function startPendingAIAnalysisWorker(client?: Client): void {
|
|
|
|
|
|
moderationClient = client;
|
2026-05-15 22:23:29 +07:00
|
|
|
|
if (!config.AI_ANALYSIS_ENABLED) return;
|
2026-05-14 19:32:44 +07:00
|
|
|
|
|
2026-05-27 23:32:38 +07:00
|
|
|
|
setInterval(() => {
|
|
|
|
|
|
// FIX #3 pattern: no async arrow — chain promises explicitly.
|
|
|
|
|
|
Promise.all([
|
|
|
|
|
|
getPendingConversationKeys(100),
|
|
|
|
|
|
getConversationKeysWithIncompleteAnalysis(50),
|
|
|
|
|
|
])
|
|
|
|
|
|
.then(([pendingKeys, incompleteKeys]) => {
|
2026-05-28 00:07:55 +07:00
|
|
|
|
const now = Date.now();
|
|
|
|
|
|
|
|
|
|
|
|
// FIX #9: Prune stale entries from state maps to prevent unbounded
|
|
|
|
|
|
// memory growth from channels/threads that are no longer active.
|
|
|
|
|
|
for (const [key, expiry] of conversationErrorCooldown) {
|
|
|
|
|
|
if (now >= expiry) conversationErrorCooldown.delete(key);
|
|
|
|
|
|
}
|
|
|
|
|
|
for (const [key, startedAt] of conversationProcessing) {
|
|
|
|
|
|
if (now - startedAt >= config.AI_ANALYSIS_PROCESSING_TIMEOUT_MS) {
|
|
|
|
|
|
conversationProcessing.delete(key);
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// FIX #8: Build a set of keys already targeted for individual recovery
|
|
|
|
|
|
// so the batch loop below skips them, preventing a race where batch
|
|
|
|
|
|
// scheduling and individual scheduling collide on the same conversation.
|
|
|
|
|
|
const incompleteKeySet = new Set(incompleteKeys);
|
|
|
|
|
|
|
2026-05-27 23:32:38 +07:00
|
|
|
|
// --- Batch recovery for `pending` messages ---
|
|
|
|
|
|
for (const key of pendingKeys) {
|
|
|
|
|
|
if (conversationDebounceTimers.has(key)) continue;
|
|
|
|
|
|
if (isConversationProcessingLocked(key)) continue;
|
|
|
|
|
|
// FIX #4: skip if individual fallback already running for this conversation.
|
|
|
|
|
|
if (individualInFlightByConversation.has(key)) continue;
|
2026-05-28 00:07:55 +07:00
|
|
|
|
// FIX #8: skip if this conversation also needs individual recovery
|
|
|
|
|
|
// (batch processing would conflict with in-flight individual work).
|
|
|
|
|
|
if (incompleteKeySet.has(key)) continue;
|
2026-05-27 23:32:38 +07:00
|
|
|
|
const cooldownUntil = conversationErrorCooldown.get(key);
|
2026-05-28 00:07:55 +07:00
|
|
|
|
if (cooldownUntil && now < cooldownUntil) continue;
|
2026-05-27 23:32:38 +07:00
|
|
|
|
scheduleConversationAnalysis(key);
|
2026-05-14 19:32:44 +07:00
|
|
|
|
}
|
2026-05-14 19:39:25 +07:00
|
|
|
|
|
2026-05-27 23:32:38 +07:00
|
|
|
|
// --- Individual recovery for `error/analysis_incomplete` messages ---
|
|
|
|
|
|
// Circuit breaker check: no point iterating if individual CB is active.
|
2026-05-28 00:07:55 +07:00
|
|
|
|
if (now >= individualCooldownUntil) {
|
2026-05-27 23:32:38 +07:00
|
|
|
|
const promises: Promise<void>[] = [];
|
|
|
|
|
|
for (const key of incompleteKeys) {
|
|
|
|
|
|
// Skip if individual work is already running for this conversation.
|
|
|
|
|
|
if (individualInFlightByConversation.has(key)) continue;
|
|
|
|
|
|
// Skip if batch processing is running (it will fan-out if it finds more incomplete).
|
|
|
|
|
|
if (isConversationProcessingLocked(key)) continue;
|
2026-05-14 19:39:25 +07:00
|
|
|
|
|
2026-05-27 23:32:38 +07:00
|
|
|
|
promises.push(
|
|
|
|
|
|
getIncompleteMessagesByConversation(
|
|
|
|
|
|
key,
|
|
|
|
|
|
config.AI_ANALYSIS_INDIVIDUAL_MAX_CONCURRENT,
|
|
|
|
|
|
)
|
|
|
|
|
|
.then((msgs) => {
|
|
|
|
|
|
if (msgs.length > 0) {
|
|
|
|
|
|
enqueueIndividualFallbacks(msgs);
|
|
|
|
|
|
}
|
|
|
|
|
|
})
|
|
|
|
|
|
.catch((err) => {
|
|
|
|
|
|
logger.error(
|
|
|
|
|
|
{ key, error: String(err) },
|
|
|
|
|
|
"Failed to fetch incomplete messages for recovery",
|
|
|
|
|
|
);
|
|
|
|
|
|
}),
|
|
|
|
|
|
);
|
|
|
|
|
|
}
|
|
|
|
|
|
// Errors are handled per-key; return the combined promise for observability.
|
|
|
|
|
|
return Promise.all(promises);
|
2026-05-14 19:39:25 +07:00
|
|
|
|
}
|
2026-05-27 23:32:38 +07:00
|
|
|
|
})
|
|
|
|
|
|
.catch((err) => {
|
|
|
|
|
|
logger.error(
|
|
|
|
|
|
{ error: err instanceof Error ? err.message : String(err) },
|
|
|
|
|
|
"Pending AI analysis recovery worker failed",
|
|
|
|
|
|
);
|
|
|
|
|
|
});
|
2026-05-21 01:55:50 +07:00
|
|
|
|
}, config.AI_ANALYSIS_RECOVERY_INTERVAL_MS);
|
2026-05-14 02:44:26 +07:00
|
|
|
|
}
|