fix(reports): deploys hand running report jobs back and retries resume finished sections (BUG-2352, #347)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8
This commit is contained in:
@@ -40,6 +40,9 @@ services:
|
||||
NEXT_PUBLIC_SUPABASE_URL: ${NEXT_PUBLIC_SUPABASE_URL:-}
|
||||
NEXT_PUBLIC_SUPABASE_ANON_KEY: ${NEXT_PUBLIC_SUPABASE_ANON_KEY:-}
|
||||
restart: unless-stopped
|
||||
# BUG-2352 (#347): on stop, the app hands running report jobs back before exiting
|
||||
# (src/lib/graceful-shutdown.ts gives them up to 35 s); Docker waits 40 s before SIGKILL.
|
||||
stop_grace_period: 40s
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
@@ -51,6 +54,7 @@ services:
|
||||
GITHUB_SHA: ${GITHUB_SHA}
|
||||
PORT: 3000
|
||||
JYOTISH_API_BASE: http://api:5200
|
||||
NEXT_MANUAL_SIG_HANDLE: "true"
|
||||
expose:
|
||||
- "3000"
|
||||
healthcheck:
|
||||
|
||||
@@ -32072,3 +32072,23 @@
|
||||
- 相关记录:BUG-1505(租约过期退点)、BUG-2352(部署打断报告)、#345(压测)。
|
||||
- 复发自:无
|
||||
- 修复版本:分支 `claude/ops-resilience-2350`(基于 staging `049614ffa`);含数据库迁移。
|
||||
|
||||
## BUG-2352 | 部署或重启会打断正在生成的报告:要等 10 分钟租约过期,还占一次机会;年运和合盘重试从头重写(#347)
|
||||
|
||||
- 状态:resolved(单元测试;staging 部署时的真实交接待复核)
|
||||
- 首次发现 / 最近更新:2026-11-23 / 2026-11-25(Gitea #347,负责人 2026-11-23 同意上线后做;临时做法是尽量不在有人生成报告时部署)
|
||||
- 影响面:个人报告、年运、合盘;所有部署和重启。
|
||||
- 用户现象(按代码推断):部署时正在生成的报告停住,10 分钟后才重新开始;如果正好是第三次机会,直接失败。年运、合盘重试时已经写好的章节全部重写,模型费用白花,用户多等一轮。
|
||||
- 触发条件:`docker compose up` 换掉 web 容器时向进程发 SIGTERM。
|
||||
- 根因(读码确认):Next.js 收到 SIGTERM 立即 `process.exit(143)`(`next/dist/server/lib/start-server.js`),报告 worker 没有机会交还任务;任务只能等租约(生产 600 秒)过期,由回收函数按一次失败的机会处理(BUG-1505)。年运 `writeAnnualReport` 每次从空的 `sections` 开始;合盘 `writeSynastryLanguage` 每次重写全部初稿。
|
||||
- 修复:
|
||||
- web 容器设 `NEXT_MANUAL_SIG_HANDLE=true` 和 `stop_grace_period: 40s`(`deploy/docker-compose.server.yml`),Next.js 不再自己退出。
|
||||
- 新增 `frontend/src/lib/graceful-shutdown.ts`,由 `instrumentation.ts` 安装(只在上述变量为真时):收到 SIGTERM / SIGINT 后让报告 worker 停止领取新任务,手上的任务有 20 秒宽限做完;还没做完的停下,用 `deferRetry(worker_shutdown)` 交还,这次机会退回、马上可以被新进程领取(BUG-2351 的迁移同时允许这一代码);然后按原来的退出码 143 / 130 退出。总时限 35 秒,到点一定退出。
|
||||
- worker 新结果 `handed_back`;交还被拒时租约不动,仍由过期回收处理(与修复前一样)。
|
||||
- 年运:新一轮先读上一轮保存的快照,出生资料版本、事实包哈希、提示词哈希、等级哈希、章节计划都相同时,按顺序保留已经写好并通过检查的章节,只写没写完的(`applyAnnualResume`);进度按已有章节数显示。
|
||||
- 合盘:中文初稿边写边存到 `personal_report_sections` 的 `resume-synastry-zh-drafts` 行(键覆盖提示词和每节证据),重试时只写缺的初稿,联合检查和改写照旧跑全部章节;报告存好后清空这一行。`resume-` 开头的行不会显示成报告章节。
|
||||
- 验证:新增 `frontend/tests/report-shutdown-resume-2352.test.tsx`(宽限期结束仍在写的任务被交还、机会退回、不退点;宽限期内写完的照常完成;SIGTERM 先等 worker 再以 143 退出、第二次信号不重复、总时限一定装上、没开变量时不安装;容器配置与接线;年运中途打断后只写剩下的章节、事实变了全部重写;`resume-` 行不当章节);`synastry-full-report.test.ts` 新增 1 项(合盘中途打断后已存初稿不重写);`annual-report`、`annual-grade-20261114`、`personal-report-worker`、Python `test_railway_deployment` / `test_beta_safety_net` 通过;`health-deployment` 两项和 `synastry-full-report` 一项在本机因缺 docker / swisseph 失败,改动前同样失败。
|
||||
- 防复发:上述测试锁住信号处理、容器宽限时间和续写条件。
|
||||
- 相关记录:BUG-1505、BUG-2351、#348(蓝绿发布)、#345(压测中途部署一组)。
|
||||
- 复发自:无
|
||||
- 修复版本:分支 `claude/ops-resilience-2350`(基于 staging `049614ffa`);生产配置变化:web 容器 `stop_grace_period: 40s`、`NEXT_MANUAL_SIG_HANDLE=true`(随部署生效,部署时 web 停止最多多等约 35 秒)。
|
||||
|
||||
@@ -13,7 +13,11 @@ export async function register(): Promise<void> {
|
||||
resolveLiveJyotishSkill();
|
||||
|
||||
const { startPersonalReportWorker } = await import("./lib/personal-report-worker");
|
||||
startPersonalReportWorker();
|
||||
const reportWorker = startPersonalReportWorker();
|
||||
// BUG-2352 (#347): the web image sets NEXT_MANUAL_SIG_HANDLE, so Next.js no longer exits on the
|
||||
// first SIGTERM. Hand running report jobs back first, then exit with the usual code.
|
||||
const { installGracefulShutdown } = await import("./lib/graceful-shutdown");
|
||||
installGracefulShutdown({ shutdownReports: (timeoutMs) => reportWorker.shutdown(timeoutMs) });
|
||||
|
||||
// Account deletion: permanent purge after the 7-day cooling-off period.
|
||||
const { startAccountDeletionWorker } = await import("./lib/account-deletion-worker");
|
||||
|
||||
@@ -985,7 +985,13 @@ export async function writeAnnualReport(input: Readonly<{
|
||||
signal: AbortSignal;
|
||||
onSection?: (snapshot: AnnualSnapshot, sectionId: string) => Promise<void> | void;
|
||||
timeoutMs?: number;
|
||||
}>): Promise<Readonly<{ snapshot: AnnualSnapshot; inputTokens: number; outputTokens: number }>> {
|
||||
/**
|
||||
* BUG-2352 (#347): the snapshot an interrupted earlier run saved. Sections it already wrote (and
|
||||
* that passed every check) are kept when the facts, the prompt and the grades are the same and
|
||||
* the plan is unchanged; only the missing sections are written.
|
||||
*/
|
||||
resume?: AnnualSnapshot | null;
|
||||
}>): Promise<Readonly<{ snapshot: AnnualSnapshot; inputTokens: number; outputTokens: number; resumedSections: number }>> {
|
||||
const cards = record(record(input.facts).cards);
|
||||
if (cards.status !== "computed") throw new Error("annual_facts_blocked");
|
||||
const timeoutMs = input.timeoutMs ?? 120_000;
|
||||
@@ -1008,6 +1014,15 @@ export async function writeAnnualReport(input: Readonly<{
|
||||
const gradeCorrections: AnnualGradeCorrection[] = [];
|
||||
let inputTokens = 0;
|
||||
let outputTokens = 0;
|
||||
const resumedSections = applyAnnualResume({
|
||||
resume: input.resume ?? null,
|
||||
factsSha256: str(record(input.facts).package_sha256),
|
||||
promptSha256,
|
||||
gradesSha256: str(gradeBlock.sha256),
|
||||
planIds: plan.map((entry) => entry.id),
|
||||
sections,
|
||||
gradeCorrections,
|
||||
});
|
||||
|
||||
const snapshot = (status: AnnualSnapshot["status"]): AnnualSnapshot => ({
|
||||
kind: "annual_report_snapshot",
|
||||
@@ -1095,6 +1110,7 @@ export async function writeAnnualReport(input: Readonly<{
|
||||
}
|
||||
|
||||
for (const entry of plan) {
|
||||
if (entry.id in sections) continue; // BUG-2352: kept from the interrupted run.
|
||||
if (entry.disposition === "skip_by_choice") {
|
||||
sections[entry.id] = { skipped: true };
|
||||
continue;
|
||||
@@ -1136,5 +1152,35 @@ export async function writeAnnualReport(input: Readonly<{
|
||||
sections[entry.id] = annualReaderLayer(entry, body);
|
||||
await input.onSection?.(snapshot("writing"), entry.id);
|
||||
}
|
||||
return { snapshot: snapshot("ready"), inputTokens, outputTokens };
|
||||
return { snapshot: snapshot("ready"), inputTokens, outputTokens, resumedSections };
|
||||
}
|
||||
|
||||
/**
|
||||
* BUG-2352: copy an interrupted run's finished sections into `sections` when nothing they depend
|
||||
* on changed. Returns how many were kept (0 when the snapshot does not match).
|
||||
*/
|
||||
export function applyAnnualResume(input: Readonly<{
|
||||
resume: AnnualSnapshot | null;
|
||||
factsSha256: string;
|
||||
promptSha256: string;
|
||||
gradesSha256: string;
|
||||
planIds: readonly string[];
|
||||
sections: Record<string, unknown>;
|
||||
gradeCorrections: AnnualGradeCorrection[];
|
||||
}>): number {
|
||||
const resume = input.resume;
|
||||
if (!resume || resume.kind !== "annual_report_snapshot" || resume.version !== 2 || resume.status !== "writing") return 0;
|
||||
if (!input.factsSha256 || resume.factsSha256 !== input.factsSha256) return 0;
|
||||
if (resume.promptSha256 !== input.promptSha256 || resume.gradesSha256 !== input.gradesSha256) return 0;
|
||||
const savedPlan = Array.isArray(resume.plan) ? resume.plan.map((entry) => entry.id) : [];
|
||||
if (savedPlan.length !== input.planIds.length || savedPlan.some((id, index) => id !== input.planIds[index])) return 0;
|
||||
const saved = record(resume.sections);
|
||||
let kept = 0;
|
||||
for (const id of input.planIds) {
|
||||
if (!(id in saved)) break; // sections are written in plan order; stop at the first gap
|
||||
input.sections[id] = saved[id];
|
||||
kept += 1;
|
||||
}
|
||||
if (kept > 0 && Array.isArray(resume.gradeCorrections)) input.gradeCorrections.push(...resume.gradeCorrections);
|
||||
return kept;
|
||||
}
|
||||
|
||||
@@ -457,6 +457,10 @@ export async function runAnnualReport(input: Readonly<{
|
||||
if (saved.error) throw new PersonalReportWorkerError("calculation_unavailable", true);
|
||||
};
|
||||
const subject = { name: (text(resolved.name) || (resolved.role === "self" ? "你" : "TA")).slice(0, 40), isSelf: resolved.role === "self" };
|
||||
// BUG-2352 (#347): a run cut off by a deploy left its finished sections in the snapshot; keep them
|
||||
// when the subject's birth input is the same (writeAnnualReport also checks facts, prompt, grades).
|
||||
const earlier = await readAnnualSnapshot(input.admin, input.report).catch(() => null);
|
||||
const resume = earlier && record(earlier).birthInputRevision === revision ? earlier : null;
|
||||
let written;
|
||||
let completed = 0;
|
||||
// The chart is done; the waiting card moves on to "writing" before the first section lands.
|
||||
@@ -471,8 +475,9 @@ export async function runAnnualReport(input: Readonly<{
|
||||
birthTime,
|
||||
write: input.writer ?? createAnnualSectionWriter(model),
|
||||
signal: input.signal,
|
||||
resume,
|
||||
onSection: async (snapshot) => {
|
||||
completed += 1;
|
||||
completed = Object.keys(snapshot.sections).length;
|
||||
await writeSnapshot(snapshot);
|
||||
await input.onProgress?.({ phase: "writing_report", completed, total: snapshot.plan.length });
|
||||
},
|
||||
@@ -486,6 +491,7 @@ export async function runAnnualReport(input: Readonly<{
|
||||
console.error(`[annual-report] section write failed reason=${error instanceof Error ? error.name : "UnknownError"} completed=${completed}`);
|
||||
throw new PersonalReportWorkerError("model_unavailable", true);
|
||||
}
|
||||
if (written.resumedSections > 0) console.info(`[annual-report] resumed sections=${written.resumedSections}`);
|
||||
await writeSnapshot(written.snapshot);
|
||||
return {
|
||||
status: "synastry_persisted" as const,
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
/**
|
||||
* BUG-2352 (#347): what the web process does when Docker stops it (deploy or restart).
|
||||
*
|
||||
* Next.js normally exits on the first SIGTERM, which cut running report jobs off; they then sat
|
||||
* until their 10-minute lease expired and were retried as a used attempt. The web container now
|
||||
* sets NEXT_MANUAL_SIG_HANDLE=true, so Next.js leaves the signal to us: the report worker stops
|
||||
* claiming, gives the job in hand its grace period, hands back what is still running, and only
|
||||
* then does the process exit (143 for SIGTERM, 130 for SIGINT, as Next.js did).
|
||||
*
|
||||
* Without NEXT_MANUAL_SIG_HANDLE (local dev, tests) nothing is installed and Next.js keeps its own
|
||||
* handlers. A hard deadline makes sure the process always exits, even if a shutdown step hangs.
|
||||
*/
|
||||
|
||||
export type GracefulShutdownProcess = Readonly<{
|
||||
env: Readonly<Record<string, string | undefined>>;
|
||||
once: (signal: "SIGTERM" | "SIGINT", listener: () => void) => unknown;
|
||||
exit: (code: number) => never | void;
|
||||
}>;
|
||||
|
||||
export type GracefulShutdownOptions = Readonly<{
|
||||
shutdownReports: (timeoutMs: number) => Promise<void>;
|
||||
/** Time given to the report worker; below the container's 40 s stop_grace_period. */
|
||||
reportTimeoutMs?: number;
|
||||
/** Absolute limit before the process exits regardless. */
|
||||
hardDeadlineMs?: number;
|
||||
process?: GracefulShutdownProcess;
|
||||
setTimeout?: (callback: () => void, ms: number) => unknown;
|
||||
log?: (line: string) => void;
|
||||
}>;
|
||||
|
||||
const INSTALLED = Symbol.for("jyotisha.gracefulShutdownInstalled");
|
||||
|
||||
export function manualSignalHandling(env: Readonly<Record<string, string | undefined>>): boolean {
|
||||
const value = env.NEXT_MANUAL_SIG_HANDLE?.trim().toLowerCase();
|
||||
return value === "true" || value === "1";
|
||||
}
|
||||
|
||||
export function installGracefulShutdown(options: GracefulShutdownOptions): boolean {
|
||||
const proc = options.process ?? (process as unknown as GracefulShutdownProcess);
|
||||
if (!manualSignalHandling(proc.env)) return false;
|
||||
const state = globalThis as typeof globalThis & { [INSTALLED]?: boolean };
|
||||
if (!options.process && state[INSTALLED]) return false;
|
||||
if (!options.process) state[INSTALLED] = true;
|
||||
|
||||
const reportTimeoutMs = options.reportTimeoutMs ?? 30_000;
|
||||
const hardDeadlineMs = options.hardDeadlineMs ?? 35_000;
|
||||
const schedule = options.setTimeout ?? ((callback: () => void, ms: number) => {
|
||||
const timer = globalThis.setTimeout(callback, ms) as ReturnType<typeof globalThis.setTimeout> & { unref?: () => void };
|
||||
timer.unref?.();
|
||||
return timer;
|
||||
});
|
||||
const log = options.log ?? ((line: string) => console.info(line));
|
||||
let exiting = false;
|
||||
|
||||
const onSignal = (signal: "SIGTERM" | "SIGINT") => {
|
||||
if (exiting) return;
|
||||
exiting = true;
|
||||
const code = signal === "SIGINT" ? 130 : 143;
|
||||
log(`[shutdown] ${signal} received; handing back running report jobs`);
|
||||
schedule(() => {
|
||||
log("[shutdown] deadline reached; exiting");
|
||||
proc.exit(code);
|
||||
}, hardDeadlineMs);
|
||||
void options.shutdownReports(reportTimeoutMs)
|
||||
.catch(() => undefined)
|
||||
.then(() => {
|
||||
log("[shutdown] report worker stopped; exiting");
|
||||
proc.exit(code);
|
||||
});
|
||||
};
|
||||
proc.once("SIGTERM", () => onSignal("SIGTERM"));
|
||||
proc.once("SIGINT", () => onSignal("SIGINT"));
|
||||
return true;
|
||||
}
|
||||
@@ -98,6 +98,11 @@ export async function hasReadingFacts(client: ReadingFactsReader, identity: Omit
|
||||
* Server-owned rows of a personal report that are not chapters a writer produced: lists of
|
||||
* section progress skip them.
|
||||
*/
|
||||
/**
|
||||
* Server-only rows that never show as report chapters: the reading facts, and (BUG-2352) the
|
||||
* `resume-` checkpoints an interrupted run leaves for its retry.
|
||||
*/
|
||||
export function isServerOwnedLongformSection(sectionId: unknown): boolean {
|
||||
return sectionId === REPORT_READING_FACTS_SECTION_ID;
|
||||
return sectionId === REPORT_READING_FACTS_SECTION_ID
|
||||
|| (typeof sectionId === "string" && sectionId.startsWith("resume-"));
|
||||
}
|
||||
|
||||
@@ -121,6 +121,16 @@ export type PersonalReportWorkerDeps = Readonly<{
|
||||
heartbeatIntervalMs?: number;
|
||||
recoveryLimit?: number;
|
||||
retryDelayMs?: (job: PersonalReportJobRecord, errorCode: string) => number;
|
||||
/**
|
||||
* BUG-2352 (#347): aborted when the web process is stopping (deploy/restart). The job in hand
|
||||
* gets `shutdownGraceMs` to finish; after that it is stopped and handed back with its attempt
|
||||
* returned (`worker_shutdown`), so the next process picks it up at once instead of after the
|
||||
* lease expires, and it does not count as a failed attempt.
|
||||
*/
|
||||
shutdownSignal?: AbortSignal;
|
||||
shutdownGraceMs?: number;
|
||||
setTimeout?: typeof globalThis.setTimeout;
|
||||
clearTimeout?: typeof globalThis.clearTimeout;
|
||||
/** BUG-2351: wait before retrying after the compute service said it is busy (429). */
|
||||
busyDelayMs?: (job: PersonalReportJobRecord, nowMs: number) => number;
|
||||
now?: () => Date;
|
||||
@@ -137,6 +147,7 @@ export type PersonalReportWorkerTickResult = Readonly<{
|
||||
| "retry_scheduled"
|
||||
| "reconcile_deferred"
|
||||
| "refund_deferred"
|
||||
| "handed_back"
|
||||
| "lease_lost";
|
||||
jobId: string | null;
|
||||
}>;
|
||||
@@ -262,6 +273,9 @@ export function createPersonalReportWorker(deps: PersonalReportWorkerDeps) {
|
||||
const clearIntervalFn = deps.clearInterval ?? globalThis.clearInterval.bind(globalThis);
|
||||
const now = deps.now ?? (() => new Date());
|
||||
const retryDelayMs = deps.retryDelayMs ?? defaultRetryDelayMs;
|
||||
const shutdownGraceMs = positiveInteger(deps.shutdownGraceMs, 20_000, "shutdownGraceMs");
|
||||
const setTimeoutFn = deps.setTimeout ?? globalThis.setTimeout.bind(globalThis);
|
||||
const clearTimeoutFn = deps.clearTimeout ?? globalThis.clearTimeout.bind(globalThis);
|
||||
const busyDelayMs = deps.busyDelayMs ?? ((job: PersonalReportJobRecord, nowMs: number) => defaultBusyDelayMs(job, nowMs));
|
||||
const logObservability = deps.logObservability ?? logAgentObservability;
|
||||
|
||||
@@ -294,6 +308,26 @@ export function createPersonalReportWorker(deps: PersonalReportWorkerDeps) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* BUG-2352: give the job back because this process is stopping. Not a failure: the attempt is
|
||||
* returned and the job is due now. If the give-back is refused, the lease is left alone and the
|
||||
* expiry sweep retries it as before.
|
||||
*/
|
||||
async function handBack(job: PersonalReportJobRecord): Promise<PersonalReportWorkerTickResult["outcome"]> {
|
||||
if (!job.leaseToken || !deps.jobs.deferRetry) return "lease_lost";
|
||||
try {
|
||||
const handed = await deps.jobs.deferRetry({
|
||||
jobId: job.id,
|
||||
leaseToken: job.leaseToken,
|
||||
reason: "worker_shutdown",
|
||||
nextAttemptAt: now(),
|
||||
});
|
||||
return handed.kind === "deferred" ? "handed_back" : "lease_lost";
|
||||
} catch {
|
||||
return "lease_lost";
|
||||
}
|
||||
}
|
||||
|
||||
async function settleFailure(
|
||||
job: PersonalReportJobRecord,
|
||||
report: PersonalReportRecord | null,
|
||||
@@ -379,6 +413,18 @@ export function createPersonalReportWorker(deps: PersonalReportWorkerDeps) {
|
||||
}
|
||||
|
||||
const controller = new AbortController();
|
||||
// BUG-2352: on shutdown, wait the grace period, then stop this job and hand it back.
|
||||
let handingBack = false;
|
||||
let graceTimer: ReturnType<typeof globalThis.setTimeout> | null = null;
|
||||
const onShutdown = () => {
|
||||
if (graceTimer !== null) return;
|
||||
graceTimer = setTimeoutFn(() => {
|
||||
handingBack = true;
|
||||
controller.abort(new Error("worker_shutdown"));
|
||||
}, shutdownGraceMs);
|
||||
};
|
||||
if (deps.shutdownSignal?.aborted) onShutdown();
|
||||
else deps.shutdownSignal?.addEventListener("abort", onShutdown, { once: true });
|
||||
let heartbeatError: unknown = null;
|
||||
let heartbeatChain = Promise.resolve();
|
||||
const refreshLease = async () => {
|
||||
@@ -554,6 +600,7 @@ export function createPersonalReportWorker(deps: PersonalReportWorkerDeps) {
|
||||
}
|
||||
return "ready";
|
||||
} catch (error) {
|
||||
if (handingBack && report?.status !== "ready") return handBack(job);
|
||||
if (report?.status === "ready") {
|
||||
// A ready report is the source of truth. If the projection-only job
|
||||
// reconciliation fails, keep the live lease untouched so expiry
|
||||
@@ -563,6 +610,8 @@ export function createPersonalReportWorker(deps: PersonalReportWorkerDeps) {
|
||||
return settleFailure(job, report, error);
|
||||
} finally {
|
||||
clearIntervalFn(heartbeatTimer);
|
||||
if (graceTimer !== null) clearTimeoutFn(graceTimer);
|
||||
deps.shutdownSignal?.removeEventListener("abort", onShutdown);
|
||||
controller.abort();
|
||||
await heartbeatChain;
|
||||
}
|
||||
|
||||
@@ -57,8 +57,16 @@ export type PersonalReportWorkerHandle = Readonly<{
|
||||
workerId: string;
|
||||
done: Promise<void>;
|
||||
stop: () => void;
|
||||
/**
|
||||
* BUG-2352 (#347): stop claiming, let the job in hand finish within the grace period, hand back
|
||||
* whatever is still running, and resolve when every lane has stopped (or `timeoutMs` passed).
|
||||
*/
|
||||
shutdown: (timeoutMs?: number) => Promise<void>;
|
||||
}>;
|
||||
|
||||
/** Matches the web container's stop_grace_period (40 s) with room to exit. */
|
||||
export const PERSONAL_REPORT_SHUTDOWN_GRACE_MS = 20_000;
|
||||
|
||||
function text(value: unknown): string | null {
|
||||
if (typeof value !== "string") return null;
|
||||
const trimmed = value.trim();
|
||||
@@ -271,10 +279,12 @@ async function generateProductionReport(
|
||||
return generateLongformReport(context, candidateRange, admin);
|
||||
}
|
||||
|
||||
function createProductionWorker(workerId: string, lane: ReportLane, primary: boolean) {
|
||||
function createProductionWorker(workerId: string, lane: ReportLane, primary: boolean, shutdownSignal: AbortSignal) {
|
||||
const admin = createAdminSupabaseClient();
|
||||
return createPersonalReportWorker({
|
||||
workerId,
|
||||
shutdownSignal,
|
||||
shutdownGraceMs: PERSONAL_REPORT_SHUTDOWN_GRACE_MS,
|
||||
reportTypes: lane.reportTypes,
|
||||
leaseSeconds: 600,
|
||||
heartbeatIntervalMs: 20_000,
|
||||
@@ -398,6 +408,7 @@ export function startPersonalReportWorker(): PersonalReportWorkerHandle {
|
||||
if (state.jyotishaPersonalReportWorker) return state.jyotishaPersonalReportWorker;
|
||||
|
||||
const controller = new AbortController();
|
||||
const shutdownController = new AbortController();
|
||||
const workerId = `personal-report:${globalThis.crypto.randomUUID()}`;
|
||||
// A few lanes run side by side (report queue, 2026-11-05); writing is mostly
|
||||
// waiting on the model, so the server stays light. The heavy chart step is
|
||||
@@ -407,7 +418,7 @@ export function startPersonalReportWorker(): PersonalReportWorkerHandle {
|
||||
let worker: ReturnType<typeof createProductionWorker> | null = null;
|
||||
const lazyWorker = {
|
||||
tick: async () => {
|
||||
worker ??= createProductionWorker(`${workerId}:${lane.id}`, lane, index === 0);
|
||||
worker ??= createProductionWorker(`${workerId}:${lane.id}`, lane, index === 0, shutdownController.signal);
|
||||
return worker.tick();
|
||||
},
|
||||
};
|
||||
@@ -418,10 +429,21 @@ export function startPersonalReportWorker(): PersonalReportWorkerHandle {
|
||||
},
|
||||
});
|
||||
});
|
||||
const done = Promise.all(loops).then(() => undefined);
|
||||
const handle: PersonalReportWorkerHandle = {
|
||||
workerId,
|
||||
done: Promise.all(loops).then(() => undefined),
|
||||
done,
|
||||
stop: () => controller.abort(),
|
||||
shutdown: async (timeoutMs = PERSONAL_REPORT_SHUTDOWN_GRACE_MS + 10_000) => {
|
||||
controller.abort();
|
||||
shutdownController.abort();
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
await Promise.race([
|
||||
done,
|
||||
new Promise<void>((resolve) => { timer = setTimeout(resolve, timeoutMs); }),
|
||||
]);
|
||||
if (timer) clearTimeout(timer);
|
||||
},
|
||||
};
|
||||
state.jyotishaPersonalReportWorker = handle;
|
||||
return handle;
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
* the failed sections, once. The timeline basis lines stay program-owned.
|
||||
*/
|
||||
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { SALVAGEABLE_CODES, salvageSynastryDraft } from "./synastry-salvage.ts";
|
||||
import type { SynastryMatchingProfiles } from "./synastry-matching-profiles.ts";
|
||||
import { buildTechnicalBasis, type TechnicalBlock } from "./synastry-full-technical.ts";
|
||||
@@ -378,6 +380,11 @@ export function repairNotes(
|
||||
return [...new Set(notes)].slice(0, REPAIR_NOTE_LIMIT);
|
||||
}
|
||||
|
||||
export type SynastryDraftCheckpoint = Readonly<{
|
||||
load: (key: string) => Promise<Readonly<Record<string, unknown>> | null>;
|
||||
save: (key: string, drafts: Readonly<Record<string, unknown>>) => Promise<void>;
|
||||
}>;
|
||||
|
||||
export async function writeSynastryLanguage(input: Readonly<{
|
||||
language: "zh" | "en";
|
||||
names: Readonly<{ a: string; b: string }>;
|
||||
@@ -391,6 +398,12 @@ export async function writeSynastryLanguage(input: Readonly<{
|
||||
onProgress?: (phase: string) => Promise<void> | void;
|
||||
timeoutMs?: number;
|
||||
structure?: SynastryStructure;
|
||||
/**
|
||||
* BUG-2352 (#347): first drafts survive an interrupted run. `key` covers the prompt and every
|
||||
* section's evidence, so a saved draft is only reused for exactly the same input; the joint
|
||||
* reader gate and its rewrites still run over all sections as before.
|
||||
*/
|
||||
checkpoint?: SynastryDraftCheckpoint;
|
||||
}>): Promise<Readonly<{ snapshotParts: Pick<SynastrySnapshot, "sections" | "timeline" | "practices" | "technical" | "gate" | "structure" | "scope" | "events" | "actually_loaded">; inputTokens: number; outputTokens: number }>> {
|
||||
const timeoutMs = input.timeoutMs ?? 90_000;
|
||||
const structure = input.structure ?? "skill_v3";
|
||||
@@ -453,7 +466,25 @@ export async function writeSynastryLanguage(input: Readonly<{
|
||||
}
|
||||
|
||||
await input.onProgress?.("writing_report");
|
||||
await pool(order, 3, (sectionId) => writeOne(sectionId));
|
||||
const checkpointKey = createHash("sha256")
|
||||
.update(JSON.stringify({ language: input.language, structure, system, evidence }))
|
||||
.digest("hex");
|
||||
const saved = input.checkpoint ? await input.checkpoint.load(checkpointKey).catch(() => null) : null;
|
||||
for (const sectionId of order) {
|
||||
if (saved && saved[sectionId] !== undefined && saved[sectionId] !== null) drafts.set(sectionId, saved[sectionId]);
|
||||
}
|
||||
let saving = Promise.resolve();
|
||||
const saveDrafts = () => {
|
||||
if (!input.checkpoint) return;
|
||||
const snapshot = Object.fromEntries(drafts);
|
||||
// One write at a time, latest state last; a failed save only costs the resume, never the report.
|
||||
saving = saving.then(() => input.checkpoint!.save(checkpointKey, snapshot)).catch(() => undefined);
|
||||
};
|
||||
await pool(order.filter((sectionId) => !drafts.has(sectionId)), 3, async (sectionId) => {
|
||||
await writeOne(sectionId);
|
||||
saveDrafts();
|
||||
});
|
||||
await saving;
|
||||
|
||||
function materialize(): Map<SynastrySectionId, Record<string, unknown>> {
|
||||
const parts = new Map<SynastrySectionId, Record<string, unknown>>();
|
||||
|
||||
@@ -20,7 +20,7 @@ import type { PersonalReportRecord } from "@/lib/personal-report-service-core";
|
||||
import { loadSynastrySubjectBirth, marriageMatchBirthBody } from "@/lib/marriage-match-service";
|
||||
import { hasRamanMatchingProfile, RAMAN_MATCHING_PROFILE, synastryMatchingProfiles } from "@/lib/synastry-matching-profiles";
|
||||
import { SYNASTRY_ORDER_SECTION, synastryDisplaySubjectIds } from "@/lib/synastry-display-order";
|
||||
import { SynastryGateRejected, timelineForPair, writeSynastryLanguage, type SynastrySnapshot } from "@/lib/synastry-full-generate";
|
||||
import { SynastryGateRejected, timelineForPair, writeSynastryLanguage, type SynastryDraftCheckpoint, type SynastrySnapshot } from "@/lib/synastry-full-generate";
|
||||
import { gateFailureRows } from "@/lib/synastry-gate-diagnostics";
|
||||
import { currentSynastryEvents } from "@/lib/synastry-full-timeline";
|
||||
import { currentSynastryTechnicalBlocks } from "@/lib/synastry-full-technical";
|
||||
@@ -135,6 +135,40 @@ async function writeSnapshot(admin: AdminClient, report: PersonalReportRecord, p
|
||||
if (saved.error) throw new PersonalReportWorkerError("calculation_unavailable", true);
|
||||
}
|
||||
|
||||
/**
|
||||
* BUG-2352 (#347): the Chinese first drafts of an interrupted run, in a server-only row (hidden from
|
||||
* progress lists by the `resume-` prefix). Reused only for the same checkpoint key.
|
||||
*/
|
||||
export const SYNASTRY_DRAFTS_CHECKPOINT_SECTION = "resume-synastry-zh-drafts";
|
||||
|
||||
export function synastryDraftCheckpoint(admin: AdminClient, report: PersonalReportRecord): SynastryDraftCheckpoint {
|
||||
return {
|
||||
load: async (key) => {
|
||||
const result = await admin.from("personal_report_sections")
|
||||
.select("payload")
|
||||
.eq("user_id", report.userId)
|
||||
.eq("request_id", report.requestId)
|
||||
.eq("section_id", SYNASTRY_DRAFTS_CHECKPOINT_SECTION)
|
||||
.maybeSingle();
|
||||
if (result.error) return null;
|
||||
const payload = asRecord(asRecord(result.data)?.payload);
|
||||
if (payload?.kind !== "synastry_drafts_checkpoint" || payload.key !== key) return null;
|
||||
return asRecord(payload.drafts);
|
||||
},
|
||||
save: async (key, drafts) => {
|
||||
await admin.from("personal_report_sections").upsert({
|
||||
user_id: report.userId,
|
||||
request_id: report.requestId,
|
||||
section_id: SYNASTRY_DRAFTS_CHECKPOINT_SECTION,
|
||||
status: "ready",
|
||||
payload: { kind: "synastry_drafts_checkpoint", key, drafts },
|
||||
attempt_count: 1,
|
||||
max_attempts: 2,
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function publicSynastryView(payload: unknown): SynastrySnapshot | null {
|
||||
const row = asRecord(payload);
|
||||
const names = asRecord(row?.names);
|
||||
@@ -264,6 +298,7 @@ export async function runSynastryFullReport(input: Readonly<{
|
||||
return { ok: result?.ok === true, failures };
|
||||
},
|
||||
onProgress: (phase) => input.onProgress?.({ phase, completed: 0, total: SYNASTRY_V3_ORDER.length }),
|
||||
checkpoint: synastryDraftCheckpoint(input.admin, input.report),
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof PersonalReportWorkerError) throw error;
|
||||
@@ -302,6 +337,8 @@ export async function runSynastryFullReport(input: Readonly<{
|
||||
throw error;
|
||||
}
|
||||
}, () => writeSnapshot(input.admin, input.report, payload));
|
||||
// The drafts are in the snapshot now; empty the checkpoint so the row does not keep a second copy.
|
||||
await synastryDraftCheckpoint(input.admin, input.report).save("done", {}).catch(() => undefined);
|
||||
const storedMatch = await input.admin.from("synastry_reports")
|
||||
.select("id")
|
||||
.eq("user_id", input.report.userId)
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import test from "node:test";
|
||||
|
||||
import { writeAnnualReport, type AnnualSectionWriter, type AnnualSnapshot } from "../src/lib/annual-report-generate.ts";
|
||||
import { annualDependencyReasons } from "../src/lib/annual-report-grade.ts";
|
||||
import { buildAnnualPlan, type AnnualPlanEntry } from "../src/lib/annual-report-sections.ts";
|
||||
import { EMPTY_ANNUAL_SITUATION, type AnnualBirthTime } from "../src/lib/annual-report-shared.ts";
|
||||
import { installGracefulShutdown, manualSignalHandling } from "../src/lib/graceful-shutdown.ts";
|
||||
import type { PersonalReportJobRecord } from "../src/lib/personal-report-job-service-core.ts";
|
||||
import type { PersonalReportRecord } from "../src/lib/personal-report-service-core.ts";
|
||||
import type { GeneratePersonalReportResult } from "../src/lib/personal-report-generation.ts";
|
||||
import { isServerOwnedLongformSection } from "../src/lib/personal-report-reading-facts-store.ts";
|
||||
import { createPersonalReportWorker } from "../src/lib/personal-report-worker-core.ts";
|
||||
|
||||
// BUG-2352 (#347): a deploy used to cut running report jobs off. They waited for the 10-minute
|
||||
// lease to expire, were retried as a used attempt, and annual/synastry retries rewrote every
|
||||
// section from scratch. Now the job in hand gets a grace period, is handed back without using an
|
||||
// attempt, and the retry keeps the sections the interrupted run already finished.
|
||||
|
||||
const USER_ID = "11111111-1111-4111-8111-111111111111";
|
||||
const REQUEST_ID = "22222222-2222-4222-8222-222222222222";
|
||||
const JOB_ID = "44444444-4444-4444-8444-444444444444";
|
||||
const FINGERPRINT = "a".repeat(64);
|
||||
const NOW = Date.parse("2026-11-25T03:00:00.000Z");
|
||||
|
||||
function report(): PersonalReportRecord {
|
||||
return {
|
||||
id: "33333333-3333-4333-8333-333333333333", userId: USER_ID, sessionId: null, chartProfileId: null,
|
||||
requestId: REQUEST_ID, requestFingerprint: FINGERPRINT, reportType: "annual_full", status: "generating",
|
||||
schemaVersion: "report_document.v2", presentationMode: "default", depth: "standard", requestedThemes: [],
|
||||
reportDocument: null, calculationHash: null, evidenceHash: null, skillName: "x", skillVersion: "1",
|
||||
skillSourceCommit: null, skillSnapshotSha256: "b".repeat(64), failureCode: null,
|
||||
createdAt: new Date(NOW).toISOString(), updatedAt: new Date(NOW).toISOString(), completedAt: null,
|
||||
};
|
||||
}
|
||||
|
||||
function shutdownHarness() {
|
||||
let job: PersonalReportJobRecord = {
|
||||
id: JOB_ID, userId: USER_ID, requestId: REQUEST_ID, requestFingerprint: FINGERPRINT,
|
||||
status: "queued", attemptCount: 0, maxAttempts: 3, leaseToken: null, leaseOwner: null, leaseAcquiredAt: null,
|
||||
leaseExpiresAt: null, heartbeatAt: null, nextAttemptAt: null, progressPhase: "queued", progressPercent: 0,
|
||||
lastErrorCode: null, lastErrorAt: null, startedAt: null, finishedAt: null,
|
||||
createdAt: new Date(NOW).toISOString(), updatedAt: new Date(NOW).toISOString(),
|
||||
};
|
||||
const events: string[] = [];
|
||||
let billingRelease = 0;
|
||||
const timers: Array<() => void> = [];
|
||||
const free = { leaseToken: null, leaseOwner: null, leaseExpiresAt: null };
|
||||
const jobs = {
|
||||
async recoverExpiredLeases() { return { retryingCount: 0, failedCount: 0 }; },
|
||||
async claimLease() {
|
||||
if (job.status !== "queued" && job.status !== "retrying") return null;
|
||||
job = { ...job, status: "running", attemptCount: job.attemptCount + 1, leaseToken: "55555555-5555-4555-8555-555555555555", leaseExpiresAt: new Date(NOW + 600_000).toISOString() };
|
||||
return job;
|
||||
},
|
||||
async heartbeatLease() { return job; },
|
||||
async updateProgress() { return job; },
|
||||
async markReady() { job = { ...job, status: "ready", ...free }; return job; },
|
||||
async completeReportReady() { events.push("ready"); job = { ...job, status: "ready", ...free }; return job; },
|
||||
async completeReportFailed() { events.push("failed"); job = { ...job, status: "failed", ...free }; return job; },
|
||||
async markFailed() { events.push("failed"); job = { ...job, status: "failed", ...free }; return job; },
|
||||
async scheduleRetry() { events.push("retry"); job = { ...job, status: "retrying", ...free }; return { kind: "scheduled" as const, job }; },
|
||||
async deferRetry({ reason }: { reason: string }) {
|
||||
events.push(`defer:${reason}`);
|
||||
job = { ...job, status: "retrying", attemptCount: job.attemptCount - 1, lastErrorCode: reason, ...free };
|
||||
return { kind: "deferred" as const, job };
|
||||
},
|
||||
};
|
||||
return { jobs, events, timers, get job() { return job; }, get billingRelease() { return billingRelease; }, release: () => { billingRelease += 1; return true; } };
|
||||
}
|
||||
|
||||
test("a job still running when the grace period ends is handed back with its attempt returned", async () => {
|
||||
const harness = shutdownHarness();
|
||||
const shutdown = new AbortController();
|
||||
let started!: () => void;
|
||||
const generationStarted = new Promise<void>((resolve) => { started = resolve; });
|
||||
const worker = createPersonalReportWorker({
|
||||
workerId: "worker-old",
|
||||
jobs: harness.jobs,
|
||||
reports: { async getByUserAndRequestId() { return report(); } },
|
||||
loadProfile: async () => ({ id: "self" }),
|
||||
generate: ({ signal }) => new Promise<GeneratePersonalReportResult>((_resolve, reject) => {
|
||||
started();
|
||||
signal.addEventListener("abort", () => reject(signal.reason ?? new Error("aborted")), { once: true });
|
||||
}),
|
||||
billing: { async complete() { return true; }, async release() { return harness.release(); } } as never,
|
||||
shutdownSignal: shutdown.signal,
|
||||
shutdownGraceMs: 20_000,
|
||||
setTimeout: ((callback: () => void) => { harness.timers.push(callback); return 0; }) as unknown as typeof globalThis.setTimeout,
|
||||
clearTimeout: (() => undefined) as unknown as typeof globalThis.clearTimeout,
|
||||
setInterval: (() => 0) as unknown as typeof globalThis.setInterval,
|
||||
clearInterval: (() => undefined) as unknown as typeof globalThis.clearInterval,
|
||||
now: () => new Date(NOW),
|
||||
});
|
||||
const tick = worker.tick();
|
||||
await generationStarted;
|
||||
shutdown.abort();
|
||||
assert.equal(harness.timers.length, 1, "the grace timer starts on shutdown");
|
||||
harness.timers[0]();
|
||||
const result = await tick;
|
||||
assert.equal(result.outcome, "handed_back");
|
||||
assert.deepEqual(harness.events, ["defer:worker_shutdown"]);
|
||||
assert.equal(harness.job.status, "retrying");
|
||||
assert.equal(harness.job.attemptCount, 0, "the interrupted run does not count");
|
||||
assert.equal(harness.billingRelease, 0, "credits stay reserved for the retry");
|
||||
});
|
||||
|
||||
test("a job that finishes inside the grace period completes normally", async () => {
|
||||
const harness = shutdownHarness();
|
||||
const shutdown = new AbortController();
|
||||
shutdown.abort();
|
||||
const worker = createPersonalReportWorker({
|
||||
workerId: "worker-old",
|
||||
jobs: harness.jobs,
|
||||
reports: { async getByUserAndRequestId() { return { ...report(), reportType: "personal_full" }; } },
|
||||
loadProfile: async () => ({ id: "self" }),
|
||||
generate: async () => ({
|
||||
status: "ready",
|
||||
document: { schemaVersion: "report_document.v2" },
|
||||
usage: { inputTokens: 1, outputTokens: 1, actualModelId: "m" },
|
||||
}) as unknown as GeneratePersonalReportResult,
|
||||
shutdownSignal: shutdown.signal,
|
||||
setTimeout: ((callback: () => void) => { harness.timers.push(callback); return 0; }) as unknown as typeof globalThis.setTimeout,
|
||||
clearTimeout: (() => undefined) as unknown as typeof globalThis.clearTimeout,
|
||||
setInterval: (() => 0) as unknown as typeof globalThis.setInterval,
|
||||
clearInterval: (() => undefined) as unknown as typeof globalThis.clearInterval,
|
||||
now: () => new Date(NOW),
|
||||
});
|
||||
const result = await worker.tick();
|
||||
assert.equal(result.outcome, "ready");
|
||||
assert.deepEqual(harness.events, ["ready"]);
|
||||
});
|
||||
|
||||
test("SIGTERM hands the report worker its time, then exits 143; nothing is installed without the flag", async () => {
|
||||
assert.equal(manualSignalHandling({}), false);
|
||||
assert.equal(manualSignalHandling({ NEXT_MANUAL_SIG_HANDLE: "true" }), true);
|
||||
const listeners = new Map<string, () => void>();
|
||||
const exits: number[] = [];
|
||||
const order: string[] = [];
|
||||
const deadlines: Array<() => void> = [];
|
||||
const fakeProcess = {
|
||||
env: { NEXT_MANUAL_SIG_HANDLE: "true" },
|
||||
once: (signal: "SIGTERM" | "SIGINT", listener: () => void) => { listeners.set(signal, listener); },
|
||||
exit: (code: number) => { exits.push(code); },
|
||||
};
|
||||
let finish!: () => void;
|
||||
const installed = installGracefulShutdown({
|
||||
process: fakeProcess,
|
||||
shutdownReports: async (timeoutMs) => {
|
||||
order.push(`reports:${timeoutMs}`);
|
||||
await new Promise<void>((resolve) => { finish = resolve; });
|
||||
order.push("reports-done");
|
||||
},
|
||||
setTimeout: (callback) => { deadlines.push(callback); return 0; },
|
||||
log: () => undefined,
|
||||
});
|
||||
assert.equal(installed, true);
|
||||
listeners.get("SIGTERM")!();
|
||||
listeners.get("SIGTERM")!(); // a second signal does not start a second shutdown
|
||||
assert.deepEqual(order, ["reports:30000"]);
|
||||
assert.deepEqual(exits, [], "no exit before the worker is done");
|
||||
finish();
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
assert.deepEqual(order, ["reports:30000", "reports-done"]);
|
||||
assert.deepEqual(exits, [143]);
|
||||
assert.equal(deadlines.length, 1, "a hard deadline is always armed");
|
||||
|
||||
const plain = installGracefulShutdown({
|
||||
process: { ...fakeProcess, env: {} },
|
||||
shutdownReports: async () => undefined,
|
||||
});
|
||||
assert.equal(plain, false);
|
||||
});
|
||||
|
||||
test("the web container gives the shutdown its time", () => {
|
||||
const compose = readFileSync(new URL("../../deploy/docker-compose.server.yml", import.meta.url), "utf8");
|
||||
const web = compose.slice(compose.indexOf("\n web:"), compose.indexOf("\n caddy:"));
|
||||
assert.match(web, /stop_grace_period: 40s/);
|
||||
assert.match(web, /NEXT_MANUAL_SIG_HANDLE: "true"/);
|
||||
const instrumentation = readFileSync(new URL("../src/instrumentation.ts", import.meta.url), "utf8");
|
||||
assert.match(instrumentation, /installGracefulShutdown\(\{ shutdownReports: \(timeoutMs\) => reportWorker\.shutdown\(timeoutMs\) \}\)/);
|
||||
});
|
||||
|
||||
// --- Annual resume -------------------------------------------------------------------------
|
||||
|
||||
const fixture = JSON.parse(readFileSync(new URL("./fixtures/annual-report-facts.json", import.meta.url), "utf8"));
|
||||
const facts = fixture.facts;
|
||||
facts.cards.evidence_grades = JSON.parse(readFileSync(new URL("./fixtures/annual-report-grade-20261114.json", import.meta.url), "utf8"));
|
||||
const BIRTH: AnnualBirthTime = { known: true, beforeMinutes: 15, afterMinutes: 15, source: "family_exact", rectification: "none" };
|
||||
|
||||
function rated(entry: AnnualPlanEntry, evidence: string, id?: string) {
|
||||
const plan = entry.grade!;
|
||||
const cap = (id ? plan.rows?.[id] : undefined) ?? plan.cap;
|
||||
return { evidence: [evidence, ...annualDependencyReasons(cap).map((reason) => `${reason}。`)].join(" "), claims: [plan.claim], grade: cap.cap };
|
||||
}
|
||||
function prose(entry: AnnualPlanEntry, text: string, evidence = "木星落在第四宫。") {
|
||||
return { paragraphs: [{ text, ...rated(entry, evidence) }] };
|
||||
}
|
||||
function fakeBody(entry: AnnualPlanEntry): unknown {
|
||||
switch (entry.kind) {
|
||||
case "person": return prose(entry, "做事稳,先想清楚再动手。");
|
||||
case "overview": return prose(entry, "这一年前半段事情多,换年盘后节奏慢下来。", "年主落年盘第 9 宫。");
|
||||
case "area": return { ...rated(entry, "土星小运管第 10 宫。"), text: "5 月以前事情多,先把手上的收尾。", timing: "Vimshottari 指向 5 月下旬;Narayana 看不出。", remember: "5 月下旬起责任变重。" };
|
||||
case "domain": return { base: "底子稳。", segments: (entry.segments ?? []).map((segment) => ({ id: segment.id, text: segment.id === "lookback" ? "这段时间是否出现了新的安排?" : "可能有调整。" })) };
|
||||
case "windows": return { items: (entry.windowIds ?? []).map((id) => ({ window_id: id, theme: "工作上可能有调整", action: "先把手上的事收尾", ...rated(entry, "慢星行运发生变化。", id) })) };
|
||||
case "remaining": return { rows: (entry.rowIds ?? []).map((id) => ({ row_id: id, matter: "节奏放慢", arrange: "重要决定留到后半段", ...rated(entry, "本命运限换段。", id) })) };
|
||||
case "close": return { line: "慢一点也是往前。" };
|
||||
default: return {};
|
||||
}
|
||||
}
|
||||
|
||||
test("a retried annual report writes only the sections the interrupted run had not finished", async () => {
|
||||
const plan = buildAnnualPlan(facts, EMPTY_ANNUAL_SITUATION);
|
||||
const calls: string[] = [];
|
||||
const write: AnnualSectionWriter = async ({ sectionId }) => {
|
||||
calls.push(sectionId);
|
||||
return { body: fakeBody(plan.find((entry) => entry.id === sectionId)!), inputTokens: 10, outputTokens: 5 };
|
||||
};
|
||||
// First run: cut off (deploy) after three sections were saved.
|
||||
const cut = new AbortController();
|
||||
let saved = null as AnnualSnapshot | null;
|
||||
let count = 0;
|
||||
await assert.rejects(writeAnnualReport({
|
||||
facts, situation: EMPTY_ANNUAL_SITUATION, subject: { name: "阿宁", isSelf: false }, rangeKind: "birthday_year",
|
||||
rangeKey: "annual:birthday_year:2026", birthTime: BIRTH, write, signal: cut.signal,
|
||||
onSection: (snapshot) => {
|
||||
saved = snapshot;
|
||||
count += 1;
|
||||
if (count === 3) cut.abort();
|
||||
},
|
||||
}));
|
||||
assert.ok(saved);
|
||||
const firstRunCalls = calls.length;
|
||||
assert.equal(firstRunCalls, 3);
|
||||
|
||||
// Retry with the saved snapshot: only the rest is written.
|
||||
calls.length = 0;
|
||||
const resumed = await writeAnnualReport({
|
||||
facts, situation: EMPTY_ANNUAL_SITUATION, subject: { name: "阿宁", isSelf: false }, rangeKind: "birthday_year",
|
||||
rangeKey: "annual:birthday_year:2026", birthTime: BIRTH, write, signal: new AbortController().signal, resume: saved,
|
||||
});
|
||||
const writable = plan.filter((entry) => entry.disposition === "write").map((entry) => entry.id);
|
||||
assert.equal(resumed.resumedSections, 3);
|
||||
assert.deepEqual(calls, writable.slice(3), "only the unfinished sections call the model");
|
||||
assert.equal(resumed.inputTokens, calls.length * 10);
|
||||
assert.equal(resumed.snapshot.status, "ready");
|
||||
assert.deepEqual(Object.keys(resumed.snapshot.sections).sort(), plan.map((entry) => entry.id).sort());
|
||||
|
||||
// Different facts: nothing is reused.
|
||||
calls.length = 0;
|
||||
const changed = { ...(saved as AnnualSnapshot), factsSha256: "0".repeat(64) } as AnnualSnapshot;
|
||||
const fresh = await writeAnnualReport({
|
||||
facts, situation: EMPTY_ANNUAL_SITUATION, subject: { name: "阿宁", isSelf: false }, rangeKind: "birthday_year",
|
||||
rangeKey: "annual:birthday_year:2026", birthTime: BIRTH, write, signal: new AbortController().signal, resume: changed,
|
||||
});
|
||||
assert.equal(fresh.resumedSections, 0);
|
||||
assert.deepEqual(calls, writable);
|
||||
});
|
||||
|
||||
test("resume checkpoints never show as report chapters", () => {
|
||||
assert.equal(isServerOwnedLongformSection("resume-synastry-zh-drafts"), true);
|
||||
assert.equal(isServerOwnedLongformSection("person"), false);
|
||||
});
|
||||
@@ -898,3 +898,51 @@ test("产品 2026-11-07 占星师方案:the writer sees each person's promise
|
||||
assert.ok(timeline.parallel_personal_timing);
|
||||
assert.ok(timeline.event_resonance_gate);
|
||||
});
|
||||
|
||||
// BUG-2352 (#347): an interrupted synastry run keeps its first drafts; the retry writes only the rest.
|
||||
test("a retried synastry run reuses the saved first drafts and writes only the missing sections", async () => {
|
||||
const segments = [
|
||||
{ id: "s1", start: "2026-01", end: "2027-01", basis: "甲。" },
|
||||
{ id: "s2", start: "2027-01", end: "2028-01", basis: "甲。" },
|
||||
{ id: "s3", start: "2028-01", end: "2029-01", basis: "甲。" },
|
||||
];
|
||||
const body = (sectionId: string) => {
|
||||
if (sectionId === "timeline") {
|
||||
return { segments: [{ id: "s1", phase: "靠近", text: "先把节奏说清楚。" }, { id: "s2", phase: "磨合", text: "把分歧说完。" }, { id: "s3", phase: "协作", text: "一起写下来。" }] };
|
||||
}
|
||||
if (sectionId === "practices") return { items: [{ text: "每周谈一次。", evidence: "证据甲" }] };
|
||||
return prose();
|
||||
};
|
||||
const store = new Map<string, Readonly<Record<string, unknown>>>();
|
||||
const checkpoint = {
|
||||
load: async (key: string) => store.get(key) ?? null,
|
||||
save: async (key: string, drafts: Readonly<Record<string, unknown>>) => { store.set(key, drafts); },
|
||||
};
|
||||
const run = (write: Parameters<typeof writeSynastryLanguage>[0]["write"], signal: AbortSignal) => writeSynastryLanguage({
|
||||
language: "zh", structure: "skill_v2", names: { a: "甲", b: "乙" }, dossier: {}, segments, signal, timeoutMs: 1000,
|
||||
write, gate: async () => ({ ok: true, failures: [] }), checkpoint,
|
||||
});
|
||||
|
||||
// First run: the deploy stops it after a few sections are written.
|
||||
const first: string[] = [];
|
||||
const cut = new AbortController();
|
||||
await assert.rejects(run(async ({ sectionId }) => {
|
||||
first.push(sectionId);
|
||||
if (first.length >= 4) {
|
||||
cut.abort();
|
||||
throw new Error("aborted");
|
||||
}
|
||||
return { body: body(sectionId), inputTokens: 1, outputTokens: 1 };
|
||||
}, cut.signal));
|
||||
const savedDrafts = [...store.values()].at(-1) ?? {};
|
||||
const savedIds = Object.keys(savedDrafts);
|
||||
assert.ok(savedIds.length >= 1 && savedIds.length < SYNASTRY_SECTION_IDS.length);
|
||||
|
||||
const second: string[] = [];
|
||||
await run(async ({ sectionId }) => {
|
||||
second.push(sectionId);
|
||||
return { body: body(sectionId), inputTokens: 1, outputTokens: 1 };
|
||||
}, new AbortController().signal);
|
||||
for (const id of savedIds) assert.equal(second.includes(id as SynastrySectionId), false, `${id} is not written again`);
|
||||
assert.equal(second.length, SYNASTRY_SECTION_IDS.length - savedIds.length);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user