/** * In-process overlap check for consult preparation. * * This does not measure local Postgres. Those medians were not collected, * so the switches stay at their code defaults. */ import { register } from "node:module"; await register(new URL("../../tests/support/stub-server-only.mjs", import.meta.url).href, import.meta.url); const { loadConsultTurnHead } = await import("../../src/lib/consult/turn-prep.ts"); const delays = { deletion: 50, session: 80, model: 80 }; async function run(parallel: boolean) { let now = 0; const waiters: Array<{ at: number; resolve: () => void }> = []; let finished = false; let inFlight = 0; let maxInFlight = 0; function sleep(ms: number) { return new Promise((resolve) => { waiters.push({ at: now + ms, resolve }); }); } async function occupy(ms: number) { inFlight += 1; maxInFlight = Math.max(maxInFlight, inFlight); await sleep(ms); inFlight -= 1; } const pending = loadConsultTurnHead({ parallel, getUser: async () => ({ data: { user: { id: "user-1" } }, error: null }), readPendingDeletion: () => occupy(delays.deletion).then(() => null), readBody: async () => ({ success: true as const, data: { sessionId: "s", modelId: "m" } }), readSession: () => occupy(delays.session).then(() => ({ data: { model_id: "m", model_config_version: 2, session_type: "consultation" }, error: null, })), resolveModel: () => occupy(delays.model).then(() => ({ id: "m" })), }).then((head) => { finished = true; return head; }); for (let guard = 0; guard < 40 && !finished; guard += 1) { await Promise.resolve(); await Promise.resolve(); if (!waiters.length) continue; waiters.sort((left, right) => left.at - right.at); now = waiters[0]!.at; const due: Array<() => void> = []; while (waiters.length && waiters[0]!.at <= now) due.push(waiters.shift()!.resolve); for (const resolve of due) resolve(); } if (!finished) throw new Error("clock did not settle"); const head = await pending; if (!head.ok) throw new Error("head failed"); return { elapsed: now, maxInFlight }; } const on = await run(true); const off = await run(false); const report = { kind: "logical-clock", delays, parallelElapsed: on.elapsed, serialElapsed: off.elapsed, parallelMaxInFlight: on.maxInFlight, serialMaxInFlight: off.maxInFlight, postgresMedians: "not-measured", aliyunKey: "absent", moderationSimulationMs: [300, 1500], decision: { CONSULT_PREP_PARALLEL: "off", MODEL_VERSION_CACHE_TTL_MS: 0, reason: "开启条件要求本机 Postgres 中位数。本轮没有量到,默认保持关闭。", }, }; console.log(JSON.stringify(report));