PRINTFILM: AI short-video marketing and AI short-drama creation platform
fix: 避免维护阻塞任务调度并展示真实上游请求与计费耗时
yie199a08a28a0
diff --git a/admin/src/api/types/tasks.ts b/admin/src/api/types/tasks.tsindex 4d78063..8d4a67e 100644--- a/admin/src/api/types/tasks.ts+++ b/admin/src/api/types/tasks.ts@@ -15,6 +15,8 @@ export type AdminTaskRow = {cancelable: boolean;current_step_key?: string | null;current_step_status?: string | null;+ next_action_at?: string | null;+ provider_task_id?: string | null;error_message?: string | null;project_id?: number | null;drama_project_id?: number | null;@@ -25,6 +27,7 @@ export type AdminTaskRow = {created_at?: string | null;started_at?: string | null;finished_at?: string | null;+ updated_at?: string | null;billing_estimate_fen?: number;billing_charged_fen?: number;billing_refunded_fen?: number;@@ -33,6 +36,8 @@ export type AdminTaskRow = {payload?: Record<string, unknown> | null;/** 执行结果 */result_payload?: Record<string, unknown> | null;+ steps?: AdminTaskStep[];+ events?: AdminTaskEvent[];};export type AdminTaskStep = {@@ -43,6 +48,8 @@ export type AdminTaskStep = {attempt_count: number;provider_name?: string | null;provider_task_id?: string | null;+ input_payload?: Record<string, unknown> | null;+ output_payload?: Record<string, unknown> | null;error_message?: string | null;started_at?: string | null;finished_at?: string | null;@@ -85,6 +92,10 @@ export type AdminTaskDetail = AdminTaskRow & {export type AdminTaskStats = {pending_count: number;+ pending_ready_count?: number;+ pending_deferred_count?: number;+ pending_delayed_count?: number;+ oldest_ready_wait_sec?: number;active_count: number;leased_count: number;running_count: number;@@ -95,6 +106,12 @@ export type AdminTaskStats = {cancelled_count: number;scheduler_running_jobs: number;max_concurrency: number;+ scheduler?: string;+ poller?: string;+ watchdog?: string;+ runtime_healthy?: boolean;+ scheduler_success_age_sec?: number | null;+ scheduler_consecutive_failures?: number;domains: Array<{domain: string;pending: number;diff --git a/admin/src/components/tasks/TaskDetailDialog.tsx b/admin/src/components/tasks/TaskDetailDialog.tsxindex 646f03c..60ed93e 100644--- a/admin/src/components/tasks/TaskDetailDialog.tsx+++ b/admin/src/components/tasks/TaskDetailDialog.tsx@@ -12,9 +12,14 @@ import { api, type AdminTaskDetail } from "@/api/client";import { AdminEntityLink } from "@/components/admin/AdminEntityLink";import { AdminModal } from "@/components/admin/AdminModal";import { Button } from "@/components/ui/button";+import { Badge } from "@/components/ui/badge";+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";+import { TaskUpstreamPanel } from "@/components/tasks/TaskUpstreamPanel";+import { useTaskClock } from "@/hooks/useTaskClock";import { taskDomainLabel, taskStatusLabel, taskTypeLabel } from "@/lib/statusLabels";import { hasJsonContent, prettyJson } from "@/lib/jsonPreview";import { cn, fenToYuan } from "@/lib/utils";+import { formatTaskDuration, redactTaskData, redactTaskText, taskBilling, taskDurations, taskUpstream } from "@/lib/taskObservability";type TaskDetailDialogProps = {taskId: number | null;@@ -23,7 +28,7 @@ type TaskDetailDialogProps = {onCancelled?: () => void;};-type DetailTab = "overview" | "billing" | "steps" | "events" | "json";+type DetailTab = "overview" | "upstream" | "billing" | "steps" | "events" | "json";const TERMINAL = new Set(["succeeded", "failed", "cancelled"]);@@ -57,7 +62,11 @@ function fmtTime(value: string | null | undefined): string {// 美化 JSON 展示function fmtJson(value: unknown): string {- return prettyJson(value);+ return prettyJson(redactTaskData(value));+}++function money(value: number | null | undefined): string {+ return value == null ? "未记录" : `¥${fenToYuan(value)}`;}// 状态 pill 样式@@ -128,6 +137,10 @@ export function TaskDetailDialog({ taskId, open, onOpenChange, onCancelled }: Taconst [loading, setLoading] = useState(false);const [tab, setTab] = useState<DetailTab>("overview");const [cancelling, setCancelling] = useState(false);+ const now = useTaskClock(open && Boolean(task) && !TERMINAL.has(task?.status || ""));+ const duration = task ? taskDurations(task, now) : null;+ const billing = taskBilling(task || {});+ const upstream = useMemo(() => taskUpstream(task || {}), [task]);async function loadDetail(id: number) {setLoading(true);@@ -150,17 +163,39 @@ export function TaskDetailDialog({ taskId, open, onOpenChange, onCancelled }: Tavoid loadDetail(taskId);}, [open, taskId]);+ useEffect(() => {+ if (!open || !taskId || !task || (TERMINAL.has(task.status) && task.billing_status !== "frozen")) return;+ let cancelled = false;+ let inFlight = false;+ const timer = window.setInterval(async () => {+ if (inFlight) return;+ inFlight = true;+ try {+ const current = await api<AdminTaskDetail>(`/api/admin/tasks/${taskId}`);+ if (!cancelled) setTask(current);+ } catch {+ // A transient refresh failure keeps the last verified snapshot visible.+ } finally {+ inFlight = false;+ }+ }, 5000);+ return () => {+ cancelled = true;+ window.clearInterval(timer);+ };+ }, [open, taskId, task?.status, task?.billing_status]);+const canCancel = useMemo(() => {if (!task) return false;return task.cancelable && !TERMINAL.has(task.status);}, [task]);- const waitingChain = useMemo(() => {+ const waitingActivation = useMemo(() => {if (!task) return false;- return task.status === "pending" && !task.next_action_at && Boolean(task.batch_key);+ return task.status === "pending" && task.next_action_at === null;}, [task]);- const payloadRows = useMemo(() => payloadSummaryRows(task?.payload ?? null), [task?.payload]);+ const payloadRows = useMemo(() => payloadSummaryRows(redactTaskData(task?.payload) as Record<string, unknown> | null), [task?.payload]);async function handleCancel() {if (!task || !canCancel) return;@@ -222,43 +257,42 @@ export function TaskDetailDialog({ taskId, open, onOpenChange, onCancelled }: Ta<span>加载任务详情…</span></div>) : task ? (- <div className="task-detail-body">- <div className="task-detail-tabs" role="tablist">+ <Tabs className="task-detail-body" value={tab} onValueChange={(value) => setTab(value as DetailTab)}>+ <TabsList className="task-detail-tabs !h-auto !justify-start !rounded-none !bg-white !p-0">{([["overview", "概览"],+ ["upstream", `上游请求 (${upstream.records.length})`],["billing", `计费 (${task.usage_lines?.length ?? 0})`],["steps", `步骤 (${task.steps?.length ?? 0})`],["events", `事件 (${task.events?.length ?? 0})`],- ["json", "原始 JSON"],+ ["json", "任务 JSON(脱敏)"],] as const).map(([key, label]) => (- <button+ <TabsTriggerkey={key}- type="button"- role="tab"+ value={key}className={cn("task-detail-tab", tab === key && "is-active")}- onClick={() => setTab(key)}>{label}- </button>+ </TabsTrigger>))}- </div>+ </TabsList>- <div className="task-detail-panel">+ <TabsContent value={tab} className="task-detail-panel !mt-0">{tab === "overview" ? (<div className="task-detail-grid"><section className="task-detail-section"><h4>状态</h4><div className="flex flex-wrap items-center gap-2"><span className={`admin-status-pill ${statusClass(task.status)}`}>- {taskStatusLabel(task.status)}+ {waitingActivation ? "待激活" : taskStatusLabel(task.status)}</span><span className="text-sm text-[#606266]">进度 {task.progress_percent}%</span>- {waitingChain ? (- <span className="admin-status-pill is-warn">等待前置(序列批次)</span>- ) : null}</div>+ {waitingActivation ? (+ <p className="task-detail-meta">任务尚未激活,等待前置条件或可用并发空位。</p>+ ) : null}{task.current_step_key ? (<p className="task-detail-meta">当前步骤 {task.current_step_key}@@ -267,11 +301,43 @@ export function TaskDetailDialog({ taskId, open, onOpenChange, onCancelled }: Ta) : null}{task.error_code || task.error_message ? (<pre className="task-detail-error">- {[task.error_code, task.error_message].filter(Boolean).join(" · ")}+ {redactTaskText([task.error_code, task.error_message].filter(Boolean).join(" · "))}</pre>) : null}</section>+ <section className="task-detail-section">+ <h4>执行耗时 {duration?.live ? <span className="ml-2 text-xs font-normal text-[var(--admin-muted)]">实时计时</span> : null}</h4>+ <dl className="task-detail-dl tabular-nums">+ <div><dt>开始前等待</dt><dd>{formatTaskDuration(duration?.waitingMs)}</dd></div>+ <div><dt>运行</dt><dd>{duration?.runningMs == null && !task.started_at && duration?.live ? "尚未开始" : formatTaskDuration(duration?.runningMs)}</dd></div>+ <div><dt>总耗时</dt><dd className="font-semibold">{formatTaskDuration(duration?.totalMs)}</dd></div>+ </dl>+ <p className="task-detail-meta">运行包含准备、上游生成与结果写回;单次 HTTP 耗时见“上游请求”。</p>+ </section>++ <section className="task-detail-section">+ <h4>最近上游记录</h4>+ <Badge variant={upstream.latest?.phase === "failed" ? "destructive" : upstream.records.length ? "info" : "secondary"}>{upstream.phase}</Badge>+ <dl className="task-detail-dl mt-3">+ <div><dt>{upstream.modelFromRequest ? "实际模型" : "任务选择模型"}</dt><dd>{upstream.model || "未记录"}</dd></div>+ <div><dt>Provider</dt><dd>{upstream.provider || "未记录"}</dd></div>+ <div><dt>上游任务 ID</dt><dd className="break-all font-mono text-xs">{upstream.providerTaskId || "未记录"}</dd></div>+ </dl>+ <Button variant="outline" size="sm" className="mt-3" onClick={() => setTab("upstream")}>查看请求与响应</Button>+ </section>++ <section className="task-detail-section">+ <h4>计费与结算</h4>+ <Badge variant={billing.settled ? "success" : "warning"}>{billing.label}</Badge>+ <dl className="task-detail-dl mt-3">+ <div><dt>预估 / 当前冻结</dt><dd>{money(billing.estimateFen)} / {money(billing.frozenFen)}</dd></div>+ <div><dt>实扣</dt><dd>{billing.settled || (billing.chargedFen ?? 0) > 0 ? money(billing.chargedFen) : "尚未结算"}</dd></div>+ <div><dt>退还</dt><dd>{billing.settled || (billing.refundedFen ?? 0) > 0 ? money(billing.refundedFen) : "尚未结算"}</dd></div>+ </dl>+ <Button variant="outline" size="sm" className="mt-3" onClick={() => setTab("billing")}>查看用量与结算</Button>+ </section>+<DetailSection title="调度"><DlRow label="优先级">{task.priority}</DlRow><DlRow label="scheduled_at">{task.scheduled_at ? fmtTime(task.scheduled_at) : null}</DlRow>@@ -279,7 +345,7 @@ export function TaskDetailDialog({ taskId, open, onOpenChange, onCancelled }: Ta<DlRow label="租约到期">{task.lease_until ? fmtTime(task.lease_until) : null}</DlRow><DlRow label="provider_task_id">{task.provider_task_id ? (- <span className="font-mono text-xs break-all">{task.provider_task_id}</span>+ <span className="font-mono text-xs break-all">{redactTaskText(task.provider_task_id)}</span>) : null}</DlRow></DetailSection>@@ -340,7 +406,8 @@ export function TaskDetailDialog({ taskId, open, onOpenChange, onCancelled }: Ta</section><section className="task-detail-section task-detail-section--full">- <h4>提交参数</h4>+ <h4>任务参数(入队 payload)</h4>+ <p className="mb-3 text-xs text-[var(--admin-muted)]">这是内部调度参数;实际发往上游的请求请查看“上游请求”。</p>{payloadRows.length > 0 ? (<dl className="task-detail-dl task-detail-dl--payload mb-3">{payloadRows.map((row) => (@@ -356,7 +423,7 @@ export function TaskDetailDialog({ taskId, open, onOpenChange, onCancelled }: Ta{hasJsonContent(task.payload) ? (<pre className="task-detail-json">{fmtJson(task.payload)}</pre>) : (- <p className="task-detail-meta">无提交参数</p>+ <p className="task-detail-meta">未记录任务参数</p>)}</section>@@ -371,6 +438,8 @@ export function TaskDetailDialog({ taskId, open, onOpenChange, onCancelled }: Ta</div>) : null}+ {tab === "upstream" ? <TaskUpstreamPanel task={task} /> : null}+{tab === "billing" ? (<div className="task-detail-grid"><section className="task-detail-section">@@ -378,25 +447,30 @@ export function TaskDetailDialog({ taskId, open, onOpenChange, onCancelled }: Ta<dl className="task-detail-dl"><div><dt>计费状态</dt>- <dd>{task.billing_status ?? "none"}</dd>+ <dd><Badge variant={billing.settled ? "success" : "warning"}>{billing.label}</Badge></dd></div><div>- <dt>预扣估算</dt>- <dd>¥{fenToYuan(task.billing_estimate_fen ?? 0)}</dd>+ <dt>预估</dt>+ <dd>{money(billing.estimateFen)}</dd>+ </div>+ <div>+ <dt>当前冻结</dt>+ <dd>{money(billing.frozenFen)}</dd></div><div><dt>实扣</dt>- <dd>¥{fenToYuan(task.billing_charged_fen ?? 0)}</dd>+ <dd>{billing.settled || (billing.chargedFen ?? 0) > 0 ? money(billing.chargedFen) : "尚未结算"}</dd></div><div><dt>退回</dt>- <dd>¥{fenToYuan(task.billing_refunded_fen ?? 0)}</dd>+ <dd>{billing.settled || (billing.refundedFen ?? 0) > 0 ? money(billing.refundedFen) : "尚未结算"}</dd></div></dl></section><section className="task-detail-section task-detail-section--full"><h4>用量明细</h4>+ <p className="mb-3 text-xs text-[var(--admin-muted)]">用量记录表示调用计费依据;钱包实际扣款与退还以任务结算摘要为准。</p><div className="admin-table-wrap"><table><thead>@@ -472,12 +546,12 @@ export function TaskDetailDialog({ taskId, open, onOpenChange, onCancelled }: Ta</span></td><td className="text-xs">{step.attempt_count}</td>- <td className="max-w-[140px] truncate font-mono text-[11px]" title={step.provider_task_id ?? ""}>- {step.provider_name ?? "—"}- {step.provider_task_id ? ` · ${step.provider_task_id}` : ""}+ <td className="max-w-[140px] truncate font-mono text-[11px]" title={redactTaskText(step.provider_task_id ?? "")}>+ {redactTaskText(step.provider_name ?? "—")}+ {step.provider_task_id ? ` · ${redactTaskText(step.provider_task_id)}` : ""}</td>- <td className="max-w-[200px] truncate text-[11px] text-[#f56c6c]" title={step.error_message ?? ""}>- {step.error_message ?? "—"}+ <td className="max-w-[200px] truncate text-[11px] text-[#f56c6c]" title={redactTaskText(step.error_message ?? "")}>+ {redactTaskText(step.error_message ?? "—")}</td><td className="text-[11px] text-[#909399]"><div>始 {fmtTime(step.started_at)}</div>@@ -508,7 +582,7 @@ export function TaskDetailDialog({ taskId, open, onOpenChange, onCancelled }: Ta{ev.status ? <span>status={ev.status}</span> : null}{ev.phase ? <span>phase={ev.phase}</span> : null}</div>- {ev.message ? <p className="mt-1 text-sm text-[#606266]">{ev.message}</p> : null}+ {ev.message ? <p className="mt-1 text-sm text-[#606266]">{redactTaskText(ev.message)}</p> : null}{ev.payload ? (<pre className="task-detail-json task-detail-json--compact">{fmtJson(ev.payload)}</pre>) : null}@@ -534,8 +608,8 @@ export function TaskDetailDialog({ taskId, open, onOpenChange, onCancelled }: Ta</div></div>) : null}- </div>- </div>+ </TabsContent>+ </Tabs>) : null}</AdminModal>);diff --git a/admin/src/components/tasks/TaskUpstreamPanel.tsx b/admin/src/components/tasks/TaskUpstreamPanel.tsxnew file mode 100644index 0000000..9cb0aea--- /dev/null+++ b/admin/src/components/tasks/TaskUpstreamPanel.tsx@@ -0,0 +1,75 @@+import { useMemo } from "react";+import type { AdminTaskDetail } from "@/api/client";+import { Badge } from "@/components/ui/badge";+import { prettyJson } from "@/lib/jsonPreview";+import { groupUpstreamRecords, redactTaskData, redactTaskText, taskUpstream, upstreamStateLabel, UPSTREAM_PHASE_LABELS } from "@/lib/taskObservability";++function time(value?: string | null) {+ return value ? new Date(value).toLocaleString() : "未记录";+}++function JsonRecord({ title, value }: { title: string; value: unknown }) {+ return (+ <details className="rounded-lg border border-[var(--admin-border)] bg-white p-3">+ <summary className="cursor-pointer text-xs font-semibold text-[var(--admin-text)]">{title}(脱敏)</summary>+ {value === undefined ? <p className="mt-3 text-xs text-[var(--admin-muted)]">未记录</p> : <pre className="task-detail-json mt-3">{prettyJson(redactTaskData(value))}</pre>}+ </details>+ );+}++/** Only dedicated HTTP events are treated as evidence of actual upstream requests. */+export function TaskUpstreamPanel({ task }: { task: AdminTaskDetail }) {+ const summary = useMemo(() => taskUpstream(task), [task]);+ const requests = useMemo(() => groupUpstreamRecords(summary.records), [summary]);+ return (+ <div className="space-y-4">+ <section className="task-detail-section">+ <h4>实际上游请求</h4>+ <p className="text-xs leading-6 text-[var(--admin-muted)]">按请求 ID 关联提交与响应;查询事件可能为采样记录。缺失内容显示“未记录”。任务参数与步骤参数保留在各自页签。</p>+ <dl className="mt-3 grid gap-3 text-xs sm:grid-cols-3">+ <div><dt className="text-[var(--admin-muted)]">最近记录阶段</dt><dd className="mt-1 font-medium">{summary.phase}</dd></div>+ <div><dt className="text-[var(--admin-muted)]">上游任务 ID</dt><dd className="mt-1 break-all font-mono">{summary.providerTaskId || "未记录"}</dd></div>+ <div><dt className="text-[var(--admin-muted)]">请求记录</dt><dd className="mt-1">{requests.length} 组 · {summary.records.length} 个事件</dd></div>+ </dl>+ </section>++ {requests.length === 0 ? (+ <div className="rounded-xl border border-dashed border-[var(--admin-border)] px-5 py-8 text-sm text-[var(--admin-muted)]">未记录上游 HTTP 请求。已有上游任务 ID 或任务已完成,也不能据此还原实际请求体。</div>+ ) : requests.map((request) => (+ <section key={request.key} className="task-detail-section">+ <div className="flex flex-wrap items-center justify-between gap-3">+ <div className="flex flex-wrap items-center gap-2">+ <Badge variant={request.latest.phase === "failed" ? "destructive" : request.latest.phase === "started" ? "warning" : "info"}>{UPSTREAM_PHASE_LABELS[request.latest.phase]}</Badge>+ {request.latest.upstreamStatus ? <Badge variant="secondary">{upstreamStateLabel(request.latest.upstreamStatus)}</Badge> : null}+ <span className="font-mono text-xs">{request.requestId || `事件 #${request.latest.id} · 请求 ID 未记录`}</span>+ </div>+ <span className="text-xs text-[var(--admin-muted)]">{time(request.latest.createdAt)}</span>+ </div>+ <div className="mt-3 break-all rounded-lg bg-[var(--admin-bg)] px-3 py-2 font-mono text-xs"><strong>{request.method || "METHOD未记录"}</strong> {request.endpoint || "Endpoint未记录"}</div>+ <dl className="mt-4 grid gap-3 text-xs sm:grid-cols-2 xl:grid-cols-4">+ <div><dt className="text-[var(--admin-muted)]">实际模型 / Provider</dt><dd className="mt-1 break-all">{request.model || "未记录"} / {request.provider || "未记录"}</dd></div>+ <div><dt className="text-[var(--admin-muted)]">上游任务 ID</dt><dd className="mt-1 break-all font-mono">{request.providerTaskId || "未记录"}</dd></div>+ <div><dt className="text-[var(--admin-muted)]">HTTP 状态</dt><dd className="mt-1">{request.httpStatus ?? "未记录"}</dd></div>+ <div><dt className="text-[var(--admin-muted)]">本次 HTTP 耗时</dt><dd className="mt-1 tabular-nums">{request.elapsedMs == null ? "未记录" : `${request.elapsedMs} ms`}</dd></div>+ </dl>+ <ol className="my-4 space-y-2 border-l-2 border-[var(--admin-border)] pl-3">+ {request.records.map((record) => <li key={record.id} className="flex flex-wrap gap-x-3 gap-y-1 text-[11px]"><span>{UPSTREAM_PHASE_LABELS[record.phase]}</span>{record.upstreamStatus ? <span>{upstreamStateLabel(record.upstreamStatus)}</span> : null}<span className="text-[var(--admin-muted)]">{time(record.createdAt)}</span>{record.elapsedMs != null ? <span className="text-[var(--admin-muted)]">{record.elapsedMs} ms</span> : null}</li>)}+ </ol>+ <div className="grid items-start gap-3 xl:grid-cols-2">+ <JsonRecord title="请求" value={request.request} />+ <JsonRecord title="响应" value={request.response} />+ </div>+ {request.error !== undefined ? <div className="mt-3"><JsonRecord title="错误" value={request.error} /></div> : null}+ </section>+ ))}++ {(task.steps || []).some((step) => step.input_payload || step.output_payload) ? (+ <details className="task-detail-section">+ <summary className="cursor-pointer text-sm font-semibold">已有步骤数据(内部执行记录)</summary>+ <p className="my-3 text-xs text-[var(--admin-muted)]">以下是步骤输入与结果,不代表实际发往上游的 HTTP 请求体。</p>+ <div className="space-y-4">{task.steps.filter((step) => step.input_payload || step.output_payload).map((step) => <section key={step.id}><h5 className="mb-2 text-xs font-semibold">{step.step_key}{step.provider_name ? ` · ${redactTaskText(step.provider_name)}` : ""}</h5><div className="grid items-start gap-3 xl:grid-cols-2"><JsonRecord title="步骤输入" value={step.input_payload ?? undefined} /><JsonRecord title="步骤结果" value={step.output_payload ?? undefined} /></div></section>)}</div>+ </details>+ ) : null}+ </div>+ );+}diff --git a/admin/src/hooks/useTaskClock.ts b/admin/src/hooks/useTaskClock.tsnew file mode 100644index 0000000..8cc564a--- /dev/null+++ b/admin/src/hooks/useTaskClock.ts@@ -0,0 +1,13 @@+import { useEffect, useState } from "react";++/** Keep durations live between server refreshes without making network requests. */+export function useTaskClock(active: boolean): number {+ const [now, setNow] = useState(Date.now);+ useEffect(() => {+ if (!active) return;+ setNow(Date.now());+ const timer = window.setInterval(() => setNow(Date.now()), 1000);+ return () => window.clearInterval(timer);+ }, [active]);+ return active ? now : Date.now();+}diff --git a/admin/src/lib/taskObservability.ts b/admin/src/lib/taskObservability.tsnew file mode 100644index 0000000..8abc74e--- /dev/null+++ b/admin/src/lib/taskObservability.ts@@ -0,0 +1,191 @@+import type { AdminTaskEvent, AdminTaskRow } from "../api/types/tasks";++const TERMINAL = new Set(["succeeded", "failed", "cancelled"]);+const SENSITIVE_KEY = /(?:authorization|cookie|apikey|accesstoken|refreshtoken|securitytoken|password|passwd|secret|signature|credential|privatekey)|^(?:(?:api|x)?token|sig|sign|auth|sessionkey)$/i;++/** Redact credentials and every URL query value before data reaches text or tooltips. */+export function redactTaskText(text: string): string {+ return text+ .replace(/https?:\/\/[^\s"'<>]+/gi, (raw) => {+ try {+ const url = new URL(raw);+ url.username = "";+ url.password = "";+ for (const key of [...url.searchParams.keys()]) url.searchParams.set(key, "[REDACTED]");+ if (url.hash) url.hash = "#REDACTED";+ return url.toString();+ } catch {+ return "[URL REDACTED]";+ }+ })+ .replace(/(["'](?:authorization|api[-_]?key|access[-_]?token|refresh[-_]?token|token|secret|signature|password)["']\s*:\s*["'])[^"']*/gi, "$1[REDACTED]")+ .replace(/\b(Bearer|Basic)\s+[A-Za-z0-9._~+\/-]+=*/gi, "$1 [REDACTED]")+ .replace(/\b((?:authorization|cookie|api[-_ ]?key|access[-_ ]?token|refresh[-_ ]?token|secret|signature|password)\s*[=:]\s*)[^\s,;"'}]+/gi, "$1[REDACTED]");+}++export function redactTaskData(value: unknown, depth = 0): unknown {+ if (depth > 12) return "[TRUNCATED]";+ if (typeof value === "string") {+ const safe = redactTaskText(value);+ return safe.length > 32_000 ? `${safe.slice(0, 32_000)}…[TRUNCATED]` : safe;+ }+ if (Array.isArray(value)) return value.slice(0, 100).map((item) => redactTaskData(item, depth + 1));+ if (!value || typeof value !== "object") return value;+ return Object.fromEntries(Object.entries(value).slice(0, 150).map(([key, item]) => {+ const normalized = key.replace(/[^a-z0-9]/gi, "");+ const sensitive = SENSITIVE_KEY.test(normalized) || (typeof item === "string" && /token$/i.test(normalized)) || /^(?:xamz|xoss).*(?:signature|credential|securitytoken)$/i.test(normalized);+ return [key, sensitive ? "[REDACTED]" : redactTaskData(item, depth + 1)];+ }));+}++export function formatTaskDuration(milliseconds: number | null | undefined): string {+ if (milliseconds == null || !Number.isFinite(milliseconds)) return "未记录";+ const seconds = Math.max(0, Math.floor(milliseconds / 1000));+ if (seconds < 60) return `${seconds}秒`;+ if (seconds < 3600) return `${Math.floor(seconds / 60)}分${seconds % 60}秒`;+ return `${Math.floor(seconds / 3600)}小时${Math.floor((seconds % 3600) / 60)}分`;+}++function timestamp(value: string | null | undefined): number | null {+ if (!value) return null;+ const result = Date.parse(value);+ return Number.isFinite(result) ? result : null;+}++export function taskDurations(task: Pick<AdminTaskRow, "status" | "created_at" | "started_at" | "finished_at">, now = Date.now()) {+ const created = timestamp(task.created_at);+ const started = timestamp(task.started_at);+ const end = timestamp(task.finished_at) ?? (TERMINAL.has(task.status) ? null : now);+ const difference = (a: number | null, b: number | null) => a == null || b == null ? null : Math.max(0, a - b);+ return {+ waitingMs: difference(started ?? end, created),+ runningMs: difference(end, started),+ totalMs: difference(end, created),+ live: !TERMINAL.has(task.status),+ };+}++export function taskBilling(task: Pick<AdminTaskRow, "billing_status" | "billing_estimate_fen" | "billing_charged_fen" | "billing_refunded_fen">) {+ const status = task.billing_status;+ const labels: Record<string, string> = { none: "未预扣 · 尚未结算", frozen: "已冻结 · 尚未结算", settled: "已结算", skipped: "已跳过预扣 · 尚未结算" };+ return {+ label: status ? labels[status] || status : "计费状态未记录",+ settled: status === "settled",+ estimateFen: task.billing_estimate_fen,+ frozenFen: status === "frozen" ? task.billing_estimate_fen : status ? 0 : undefined,+ chargedFen: task.billing_charged_fen,+ refundedFen: task.billing_refunded_fen,+ };+}++export type UpstreamPhase = "started" | "accepted" | "failed" | "poll";+export type UpstreamRecord = {+ id: number;+ phase: UpstreamPhase;+ createdAt?: string | null;+ requestId?: string;+ method?: string;+ endpoint?: string;+ model?: string;+ provider?: string;+ providerTaskId?: string;+ elapsedMs?: number;+ httpStatus?: number;+ upstreamStatus?: string;+ request?: unknown;+ response?: unknown;+ error?: unknown;+};++function textField(value: unknown): string | undefined {+ return typeof value === "string" && value.trim() ? redactTaskText(value.trim()) : undefined;+}++export function upstreamRecords(events: AdminTaskEvent[] | undefined): UpstreamRecord[] {+ return (events || []).flatMap((event) => {+ const match = event.event_type.match(/^upstream\.request\.(started|accepted|failed|poll)$/);+ if (!match) return [];+ const payload = event.payload || {};+ const response = payload.response && typeof payload.response === "object" ? payload.response as Record<string, unknown> : {};+ const body = response.body && typeof response.body === "object" ? response.body as Record<string, unknown> : {};+ const data = body.data && typeof body.data === "object" ? body.data as Record<string, unknown> : {};+ const statusCode = payload.http_status ?? payload.status_code ?? response.status_code;+ return [{+ id: event.id,+ phase: match[1] as UpstreamPhase,+ createdAt: event.created_at,+ requestId: textField(payload.request_id),+ method: textField(payload.method),+ endpoint: textField(payload.endpoint),+ model: textField(payload.model),+ provider: textField(payload.provider),+ providerTaskId: textField(payload.provider_task_id),+ elapsedMs: typeof payload.elapsed_ms === "number" ? payload.elapsed_ms : undefined,+ httpStatus: typeof statusCode === "number" ? statusCode : undefined,+ upstreamStatus: textField(payload.upstream_status) || textField(body.status) || textField(data.status),+ request: payload.request == null ? undefined : redactTaskData(payload.request),+ response: payload.response == null ? undefined : redactTaskData(payload.response),+ error: payload.error == null ? undefined : redactTaskData(payload.error),+ }];+ }).sort((a, b) => a.id - b.id);+}++export const UPSTREAM_PHASE_LABELS: Record<UpstreamPhase, string> = {+ started: "开始请求", accepted: "上游响应", failed: "请求失败", poll: "查询结果",+};++export function upstreamStateLabel(status: string): string {+ const labels: Record<string, string> = {+ pending: "上游排队", queued: "上游排队", submitted: "上游排队", waiting: "上游排队",+ running: "上游生成中", processing: "上游生成中", generating: "上游生成中", in_progress: "上游生成中",+ succeeded: "上游完成", success: "上游完成", completed: "上游完成", done: "上游完成", finished: "上游完成",+ failed: "上游失败", error: "上游失败", failure: "上游失败", cancelled: "上游已取消", canceled: "上游已取消",+ };+ return labels[status.toLowerCase()] || `上游状态:${redactTaskText(status)}`;+}++export function groupUpstreamRecords(records: UpstreamRecord[]) {+ const grouped = new Map<string, UpstreamRecord[]>();+ for (const record of records) {+ const key = record.requestId || `event-${record.id}`;+ grouped.set(key, [...(grouped.get(key) || []), record]);+ }+ return [...grouped.entries()].map(([key, items]) => {+ const latest = items.at(-1)!;+ const reverse = [...items].reverse();+ return {+ key, records: items, latest,+ requestId: latest.requestId,+ method: reverse.find((item) => item.method)?.method,+ endpoint: reverse.find((item) => item.endpoint)?.endpoint,+ model: reverse.find((item) => item.model)?.model,+ provider: reverse.find((item) => item.provider)?.provider,+ providerTaskId: reverse.find((item) => item.providerTaskId)?.providerTaskId,+ request: reverse.find((item) => item.request !== undefined)?.request,+ response: reverse.find((item) => item.response !== undefined)?.response,+ error: reverse.find((item) => item.error !== undefined)?.error,+ elapsedMs: reverse.find((item) => item.elapsedMs !== undefined)?.elapsedMs,+ httpStatus: reverse.find((item) => item.httpStatus !== undefined)?.httpStatus,+ };+ }).reverse();+}++export function taskUpstream(task: Pick<AdminTaskRow, "events" | "steps" | "payload" | "provider_task_id">) {+ const records = upstreamRecords(task.events);+ const latest = records.at(-1);+ const modelRecord = [...records].reverse().find((record) => record.model);+ const providerRecord = [...records].reverse().find((record) => record.provider);+ const taskIdRecord = [...records].reverse().find((record) => record.providerTaskId);+ const providerStep = [...(task.steps || [])].reverse().find((step) => step.provider_name);+ const taskIdStep = [...(task.steps || [])].reverse().find((step) => step.provider_task_id);+ const providerTaskId = taskIdRecord?.providerTaskId || textField(task.provider_task_id) || textField(taskIdStep?.provider_task_id);+ return {+ records,+ latest,+ model: modelRecord?.model || textField(task.payload?.model_id) || textField(task.payload?.model),+ modelFromRequest: Boolean(modelRecord),+ provider: providerRecord?.provider || textField(providerStep?.provider_name),+ providerTaskId,+ phase: latest?.upstreamStatus ? upstreamStateLabel(latest.upstreamStatus) : latest ? UPSTREAM_PHASE_LABELS[latest.phase] : providerTaskId ? "已有上游任务 · HTTP未记录" : "尚无上游请求记录",+ };+}diff --git a/admin/src/pages/QueuesPage.tsx b/admin/src/pages/QueuesPage.tsxindex 218c8fd..972b758 100644--- a/admin/src/pages/QueuesPage.tsx+++ b/admin/src/pages/QueuesPage.tsx@@ -8,10 +8,12 @@ import { AdminUserSearchSelect } from "@/components/admin/AdminUserSearchSelect"import { StatCard } from "@/components/admin/StatCard";import { PageSection } from "@/components/admin/PageSection";import { TaskDetailDialog } from "@/components/tasks/TaskDetailDialog";+import { Badge } from "@/components/ui/badge";import { PageHeader, Toolbar } from "@/components/ui/page";import { PaginationBar } from "@/components/PaginationBar";import { useAdminDetailQuery } from "@/hooks/useAdminDetailQuery";-import { compactJsonPreview, hasJsonContent } from "@/lib/jsonPreview";+import { useTaskClock } from "@/hooks/useTaskClock";+import { formatTaskDuration, redactTaskText, taskBilling, taskDurations, taskUpstream } from "@/lib/taskObservability";import { cn, fenToYuan } from "@/lib/utils";import { DEFAULT_PAGE_SIZE } from "@/lib/pagination";import { taskDomainLabel, taskStatusLabel, taskTypeLabel } from "@/lib/statusLabels";@@ -33,6 +35,21 @@ function formatTime(value: string | null | undefined): string {return new Date(value).toLocaleString();}+function formatElapsed(seconds: number | null | undefined): string {+ if (seconds == null || !Number.isFinite(seconds)) return "暂无记录";+ const value = Math.max(0, Math.floor(seconds));+ if (value < 60) return `${value}秒`;+ if (value < 3600) return `${Math.floor(value / 60)}分${value % 60}秒`;+ return `${Math.floor(value / 3600)}小时${Math.floor((value % 3600) / 60)}分`;+}++function queueStatusLabel(task: AdminTaskRow): string {+ if (task.status !== "pending") return taskStatusLabel(task.status);+ if (task.next_action_at === undefined) return "待处理";+ if (task.next_action_at === null) return "待激活";+ return new Date(task.next_action_at).getTime() > Date.now() ? "延时等待" : "待调度";+}+// 阻止冒泡到行 onClick,避免链接跳转时同时打开详情function stopRowClick(e: { stopPropagation: () => void }) {e.stopPropagation();@@ -71,18 +88,8 @@ function canCancel(task: AdminTaskRow): boolean {return task.cancelable && !TERMINAL_STATUSES.has(task.status);}-// 列表单元格:参数/结果单行摘要;title 也截断,避免巨 payload 塞进 DOM-function jsonCell(value: Record<string, unknown> | null | undefined) {- if (!hasJsonContent(value)) {- return <span className="text-[#909399]">—</span>;- }- const preview = compactJsonPreview(value, 72);- const tip = compactJsonPreview(value, 280);- return (- <pre className="task-list-json" title={tip}>- {preview}- </pre>- );+function money(value: number | undefined): string {+ return value == null ? "未记录" : `¥${fenToYuan(value)}`;}// 统一任务平台监控页@@ -112,7 +119,10 @@ export function QueuesPage() {const [taskType, setTaskType] = useState("");const [viewTab, setViewTab] = useState<"all" | "active">("all");const [cancelLoading, setCancelLoading] = useState<number | null>(null);+ const apiOnlyNode = stats?.scheduler === "disabled";const taskDetail = useAdminDetailQuery("task");+ const taskViews = useMemo(() => (data?.items || []).map((task) => ({ task, upstream: taskUpstream(task), billing: taskBilling(task) })), [data]);+ const now = useTaskClock(data?.items.some((task) => !TERMINAL_STATUSES.has(task.status)) ?? false);const loadStats = useCallback(async () => {const res = await api<AdminTaskStats>("/api/admin/tasks/stats");@@ -201,7 +211,7 @@ export function QueuesPage() {return (<div className="admin-page"><PageHeader- description={`统一任务平台 · 自动刷新 ${REFRESH_MS / 1000}s · 并发 ${stats?.scheduler_running_jobs ?? 0}/${stats?.max_concurrency ?? 0}`}+ description={`统一任务平台 · 自动刷新 ${REFRESH_MS / 1000}s · ${apiOnlyNode ? "本节点仅 API / 队列由执行节点处理" : `本节点并发 ${stats?.scheduler_running_jobs ?? 0}/${stats?.max_concurrency ?? 0}`}`}actions={<buttontype="button"@@ -224,28 +234,28 @@ export function QueuesPage() {<><div className="grid gap-3 md:grid-cols-2 xl:grid-cols-4"><StatCard- label="排队中"+ label="待处理"value={stats?.pending_count ?? 0}- hint="含待调度 pending"+ hint={`待调度 ${stats?.pending_ready_count ?? "—"} · 待激活 ${stats?.pending_deferred_count ?? "—"} · 延时 ${stats?.pending_delayed_count ?? "—"}`}icon={Layers}tone="warn"/><StatCardlabel="进行中"value={stats?.active_count ?? 0}- hint={`执行 ${stats?.running_count ?? 0} · 轮询 ${stats?.awaiting_poll_count ?? 0}`}+ hint={`执行 ${stats?.running_count ?? 0} · 轮询 ${stats?.awaiting_poll_count ?? 0} · 取消中 ${stats?.cancel_requested_count ?? 0}`}icon={Activity}tone="info"/><StatCard- label="运行时槽位"+ label="本节点执行槽位"value={- <>+ apiOnlyNode ? <span className="text-lg">仅 API</span> : <>{stats?.scheduler_running_jobs ?? 0}<span className="text-lg text-[var(--admin-muted)]"> / {stats?.max_concurrency ?? 0}</span></>}- hint={`已租约 ${stats?.leased_count ?? 0}`}+ hint={apiOnlyNode ? "队列由执行节点处理" : `全站已租约 ${stats?.leased_count ?? 0}`}icon={RefreshCw}/><div className="admin-panel admin-stat-card tone-success">@@ -263,6 +273,19 @@ export function QueuesPage() {</div></div>+ <div className="admin-panel mt-3 flex flex-wrap items-center gap-x-5 gap-y-2 px-4 py-3 text-xs text-[var(--admin-muted)]">+ <span className={cn("admin-status-pill", stats?.runtime_healthy === undefined ? "" : stats.runtime_healthy ? "is-done" : "is-fail")}>+ {apiOnlyNode ? "本节点仅 API" : `运行时${stats?.runtime_healthy === undefined ? "状态未知" : stats.runtime_healthy ? "正常" : "异常"}`}+ </span>+ {apiOnlyNode ? <span>本节点仅 API / 队列由执行节点处理</span> : <>+ <span>调度器 {stats?.scheduler ?? "—"} · 轮询器 {stats?.poller ?? "—"} · 看门狗 {stats?.watchdog ?? "—"}</span>+ <span>最近成功调度:{stats?.scheduler_success_age_sec == null ? "暂无记录" : `${formatElapsed(stats.scheduler_success_age_sec)}前`}</span>+ <span>连续失败:{stats?.scheduler_consecutive_failures ?? "—"}</span>+ </>}+ <span>最老到期待调度已等待:{formatElapsed(stats?.oldest_ready_wait_sec)}</span>+ <span>待激活表示前置条件或并发空位尚未满足;延时表示尚未到调度时间。</span>+ </div>+{(stats?.domains.length ?? 0) > 0 ? (<PageSection title="各领域任务" bodyClassName="!pt-0"><div className="grid gap-3 md:grid-cols-2 xl:grid-cols-4">@@ -283,7 +306,7 @@ export function QueuesPage() {</span></div><div className="mt-2 text-xs text-[var(--admin-muted)]">- 排队 {d.pending} · 进行 {d.active} · 成功 {d.succeeded}+ 待处理 {d.pending} · 进行 {d.active} · 成功 {d.succeeded}</div></div>))}@@ -297,7 +320,7 @@ export function QueuesPage() {<div className="flex flex-wrap gap-2">{([- ["active", `进行中 (${stats?.pending_count ?? 0}+${stats?.active_count ?? 0})`],+ ["active", `未结束 (${stats?.pending_count ?? 0}+${stats?.active_count ?? 0})`],["all", "全部"],] as const).map(([key, label]) => (@@ -345,7 +368,7 @@ export function QueuesPage() {><option value="">全部状态</option>{Object.entries({- pending: "排队中",+ pending: "待处理",leased: "已租约",running: "执行中",awaiting_poll: "等待轮询",@@ -404,22 +427,20 @@ export function QueuesPage() {<thead><tr><th>ID</th>- <th>领域 / 类型</th>+ <th>任务 / 模型</th><th>用户</th><th>关联</th>- <th>状态</th>- <th>进度</th>- <th>费用</th>- <th>提交参数</th>- <th>结果</th>- <th>时间</th>+ <th>状态 / 当前阶段</th>+ <th>上游请求 / 最近记录</th>+ <th>计费 / 结算</th>+ <th>等待 / 运行 / 总耗时</th><th>操作</th></tr></thead><tbody>{(data?.items.length ?? 0) === 0 ? (<tr>- <td colSpan={11}>+ <td colSpan={9}><div className="admin-empty !py-10"><div className="admin-empty-title">暂无任务</div><div className="admin-empty-desc">切换到「全部」查看历史任务</div>@@ -427,7 +448,10 @@ export function QueuesPage() {</td></tr>) : (- data?.items.map((task) => (+ taskViews.map(({ task, upstream, billing }) => {+ const duration = taskDurations(task, now);+ const error = task.error_message ? redactTaskText(task.error_message) : "";+ return (<trkey={task.id}className="cursor-pointer hover:bg-[#f8faf9]"@@ -439,6 +463,8 @@ export function QueuesPage() {<div className="font-mono text-[11px] text-[#909399]">{taskTypeLabel(task.task_type)}</div>+ <div className="mt-2 max-w-[230px] break-all text-xs font-medium">{upstream.model || "模型未记录"}</div>+ <div className="text-[11px] text-[var(--admin-muted)]">{upstream.modelFromRequest ? "实际请求模型" : upstream.model ? "任务选择模型" : ""}{upstream.provider ? ` · ${upstream.provider}` : ""}</div></td><td onClick={stopRowClick}><AdminEntityLink@@ -453,27 +479,33 @@ export function QueuesPage() {</td><td><span className={`admin-status-pill ${statusClass(task.status)}`}>- {taskStatusLabel(task.status)}+ {queueStatusLabel(task)}</span>- {task.error_message ? (- <div className="mt-1 max-w-[200px] truncate text-[11px] text-[#f56c6c]" title={task.error_message}>- {task.error_message}+ <div className="mt-2 text-xs">{task.current_step_key || "步骤未记录"}{task.current_step_status ? ` · ${task.current_step_status}` : ""}</div>+ <div className="mt-1 text-[11px] text-[var(--admin-muted)]">进度 {task.progress_percent}%</div>+ {error ? (+ <div className="mt-1 max-w-[200px] truncate text-[11px] text-[#f56c6c]" title={error}>+ {error}</div>) : null}</td>- <td className="text-xs">{task.progress_percent}%</td>- <td className="text-xs">- {task.billing_charged_fen != null && task.billing_charged_fen > 0- ? `¥${fenToYuan(task.billing_charged_fen)}`- : task.billing_status === "frozen"- ? `预扣 ¥${fenToYuan(task.billing_estimate_fen ?? 0)}`- : "—"}+ <td className="max-w-[260px] text-xs">+ <Badge variant={upstream.latest?.phase === "failed" ? "destructive" : upstream.records.length ? "info" : "secondary"}>{upstream.phase}</Badge>+ {upstream.latest?.method || upstream.latest?.endpoint ? <div className="mt-2 break-all font-mono text-[11px]">{upstream.latest.method} {upstream.latest.endpoint}</div> : null}+ <div className="mt-2 break-all font-mono text-[11px] text-[var(--admin-muted)]">{upstream.providerTaskId ? `任务ID ${upstream.providerTaskId}` : "上游任务ID未记录"}</div>+ {upstream.latest?.elapsedMs != null ? <div className="mt-1 text-[11px] text-[var(--admin-muted)]">最近请求 {upstream.latest.elapsedMs}ms{upstream.latest.httpStatus ? ` · HTTP ${upstream.latest.httpStatus}` : ""}</div> : null}+ </td>+ <td className="min-w-[190px] text-xs">+ <Badge variant={billing.settled ? "success" : "warning"}>{billing.label}</Badge>+ <div className="mt-2">预估 {money(billing.estimateFen)} · 冻结 {money(billing.frozenFen)}</div>+ <div className="mt-1">实扣 {billing.settled || (billing.chargedFen ?? 0) > 0 ? money(billing.chargedFen) : "待结算"}</div>+ <div className="mt-1 text-[var(--admin-muted)]">退还 {billing.settled || (billing.refundedFen ?? 0) > 0 ? money(billing.refundedFen) : "待结算"}</div></td>- <td className="task-list-json-cell">{jsonCell(task.payload)}</td>- <td className="task-list-json-cell">{jsonCell(task.result_payload)}</td>- <td className="text-xs text-[#909399]">- <div>创建 {formatTime(task.created_at)}</div>- {task.started_at ? <div>开始 {formatTime(task.started_at)}</div> : null}+ <td className="min-w-[160px] text-xs tabular-nums">+ <div>等待 {formatTaskDuration(duration.waitingMs)}</div>+ <div className="mt-1">运行 {duration.runningMs == null && !task.started_at && duration.live ? "尚未开始" : formatTaskDuration(duration.runningMs)}</div>+ <div className="mt-1 font-medium">总计 {formatTaskDuration(duration.totalMs)}{duration.live ? " · 计时中" : ""}</div>+ <div className="mt-2 text-[11px] text-[var(--admin-muted)]">创建 {formatTime(task.created_at)}</div></td><td onClick={(e) => e.stopPropagation()}><div className="flex flex-wrap gap-1">@@ -498,7 +530,7 @@ export function QueuesPage() {</div></td></tr>- ))+ );}))}</tbody></table>diff --git a/admin/tests/taskObservability.test.mjs b/admin/tests/taskObservability.test.mjsnew file mode 100644index 0000000..14441ac--- /dev/null+++ b/admin/tests/taskObservability.test.mjs@@ -0,0 +1,76 @@+import assert from 'node:assert/strict';+import test from 'node:test';+import { groupUpstreamRecords, redactTaskData, taskBilling, taskDurations, taskUpstream, upstreamRecords, upstreamStateLabel } from '../src/lib/taskObservability.ts';++test('request and response credentials and signed URL values never reach presentation data', () => {+ const source = {+ headers: { Authorization: 'Bearer top-secret', 'x-api-key': 'key-value', Cookie: 'session-secret' },+ nested: { access_token: 'token-secret', client_secret: 'client-secret', 'x-client-token': 'header-secret' },+ result: 'https://user:[email protected]/file.png?X-Amz-Signature=signed-secret&expires=other-secret#fragment-secret',+ message: 'HTTP error Bearer message-secret api_key=plain-secret',+ body: '{"api_key":"json-secret"}',+ total_tokens: 42,+ };+ const result = JSON.stringify(redactTaskData(source));+ for (const secret of ['top-secret', 'key-value', 'session-secret', 'token-secret', 'client-secret', 'header-secret', 'signed-secret', 'other-secret', 'fragment-secret', 'message-secret', 'plain-secret', 'json-secret', 'user:pass']) {+ assert.ok(!result.includes(secret), `leaked ${secret}`);+ }+ assert.ok(result.includes('file.png'));+ assert.ok(result.includes('42'));+ assert.equal(source.headers.Authorization, 'Bearer top-secret');+});++test('queued, active and terminal tasks retain distinct waiting and running durations', () => {+ const created_at = '2026-10-20T00:00:00Z';+ const now = Date.parse('2026-10-20T00:01:00Z');+ assert.deepEqual(taskDurations({ status: 'pending', created_at }, now), { waitingMs: 60_000, runningMs: null, totalMs: 60_000, live: true });+ assert.deepEqual(taskDurations({ status: 'awaiting_poll', created_at, started_at: '2026-10-20T00:00:10Z' }, now), { waitingMs: 10_000, runningMs: 50_000, totalMs: 60_000, live: true });+ assert.deepEqual(taskDurations({ status: 'succeeded', created_at, started_at: '2026-10-20T00:00:10Z', finished_at: '2026-10-20T00:00:40Z' }, now), { waitingMs: 10_000, runningMs: 30_000, totalMs: 40_000, live: false });+ assert.equal(taskDurations({ status: 'failed', created_at }, now).totalMs, null);+});++test('frozen zero charge is unsettled, while settled zero is a real final amount', () => {+ const frozen = taskBilling({ billing_status: 'frozen', billing_estimate_fen: 200, billing_charged_fen: 0 });+ assert.equal(frozen.settled, false);+ assert.equal(frozen.frozenFen, 200);+ const settled = taskBilling({ billing_status: 'settled', billing_estimate_fen: 200, billing_charged_fen: 0, billing_refunded_fen: 200 });+ assert.equal(settled.settled, true);+ assert.equal(settled.frozenFen, 0);+ assert.equal(settled.refundedFen, 200);+});++test('upstream evidence comes only from recorded HTTP events, never task or step payloads', () => {+ const task = { payload: { model_id: 'requested-model', prompt: 'internal-task-payload' }, steps: [{ provider_name: 'legacy-provider', input_payload: { request: 'not-an-http-record' } }] };+ assert.deepEqual(taskUpstream(task).records, []);+ assert.equal(taskUpstream(task).modelFromRequest, false);+ assert.equal(taskUpstream(task).model, 'requested-model');+ const events = [+ { id: 3, event_type: 'upstream.request.accepted', payload: { request_id: 'request-1', model: 'resolved-model', provider_task_id: 'provider-1', elapsed_ms: 125, response: { status_code: 202, body: { status: 'pending' } } } },+ { id: 1, event_type: 'task.started', payload: { request: 'not-an-http-record' } },+ { id: 2, event_type: 'upstream.request.started', payload: { request_id: 'request-1', method: 'POST', endpoint: 'https://example.test/tasks?api_key=secret', request: { model: 'resolved-model' } } },+ ];+ const summary = taskUpstream({ ...task, events });+ assert.equal(summary.records.length, 2);+ assert.equal(summary.model, 'resolved-model');+ assert.equal(summary.modelFromRequest, true);+ assert.equal(summary.providerTaskId, 'provider-1');+ assert.equal(summary.latest.elapsedMs, 125);+ assert.equal(summary.latest.httpStatus, 202);+ assert.equal(summary.phase, '上游排队');+ const groups = groupUpstreamRecords(summary.records);+ assert.equal(groups.length, 1);+ assert.equal(groups[0].requestId, 'request-1');+ assert.equal(groups[0].method, 'POST');+ assert.equal(groups[0].request.model, 'resolved-model');+ assert.equal(groups[0].response.body.status, 'pending');+ assert.ok(!JSON.stringify(summary).includes('api_key=secret'));+ assert.equal(upstreamRecords([events[0]]).length, 1, 'missing started event does not hide accepted evidence');+});++test('provider response status determines visible upstream phase without inventing task progress', () => {+ const events = [{ id: 1, event_type: 'upstream.request.poll', payload: { response: { body: { data: { status: 'running' } } } } }];+ assert.equal(taskUpstream({ events }).phase, '上游生成中');+ assert.equal(upstreamStateLabel('completed'), '上游完成');+ assert.equal(upstreamStateLabel('failed'), '上游失败');+ assert.equal(taskUpstream({}).phase, '尚无上游请求记录');+});diff --git a/backend/.env.example b/backend/.env.exampleindex cb902dd..00f5884 100644--- a/backend/.env.example+++ b/backend/.env.example@@ -1,10 +1,16 @@SECRET_KEY=dev-secret-change-me+# 本地联调若连接共享测试库,请设为 false,由测试服务器统一执行后台任务。+TASK_RUNTIME_ENABLED=true# DEBUG=true 时应用日志更详细;SQL_ECHO=true 才打印原始 SQL(默认关,避免刷屏)# DEBUG=true# SQL_ECHO=false# 仅支持 PostgreSQL(Docker 见 deploy/docker-compose.yml)DATABASE_URL=postgresql+asyncpg://printfilm:[email protected]:15432/printfilmDATABASE_URL_SYNC=postgresql+psycopg2://printfilm:[email protected]:15432/printfilm+# 默认 true:启动时建表、补列、初始化模板/管理员/导演技能,服务器保持开启。+# 本地 API 连接已初始化的共享测试库时可设 false:仅加载模型配置,不修改库结构或种子数据。+# 此开关独立于 TASK_RUNTIME_ENABLED;本地共享库联调通常同时关闭任务运行器。+DATABASE_BOOTSTRAP_ENABLED=true# Postgres 生产建议:API uvicorn --workers 1,任务调度与 API 共用进程内连接池# 生产建议与任务并发对齐(杭州现网:100+20,PG max_connections≥250)# DB_POOL_SIZE=100diff --git a/backend/.env.test.example b/backend/.env.test.exampleindex e8d3fb2..4faeeb1 100644--- a/backend/.env.test.example+++ b/backend/.env.test.example@@ -1,6 +1,8 @@# Local automated tests. Copy to .env.test; run python scripts/run_tests.py.SECRET_KEY=local-test-secret-not-for-productionDEBUG=false+TASK_RUNTIME_ENABLED=true+DATABASE_BOOTSTRAP_ENABLED=trueSQL_ECHO=falseDATABASE_URL=postgresql+asyncpg://printfilm:[email protected]:15432/printfilm_testDATABASE_URL_SYNC=postgresql+psycopg2://printfilm:[email protected]:15432/printfilm_testdiff --git a/backend/app/api/admin/tasks.py b/backend/app/api/admin/tasks.pyindex 77fa473..5f7a2d1 100644--- a/backend/app/api/admin/tasks.py+++ b/backend/app/api/admin/tasks.py@@ -73,6 +73,8 @@ async def admin_task_stats(poller=str(runtime.get("poller") or "stopped"),watchdog=str(runtime.get("watchdog") or "stopped"),runtime_healthy=bool(runtime.get("healthy")),+ scheduler_success_age_sec=runtime.get("scheduler_success_age_sec"),+ scheduler_consecutive_failures=int(runtime.get("scheduler_consecutive_failures") or 0),fetched_at=datetime.now(UTC),)diff --git a/backend/app/config.py b/backend/app/config.pyindex 58eac0a..1c75a32 100644--- a/backend/app/config.py+++ b/backend/app/config.py@@ -23,6 +23,8 @@ class Settings(BaseSettings):database_url: str = "postgresql+asyncpg://printfilm:[email protected]:15432/printfilm"database_url_sync: str = "postgresql+psycopg2://printfilm:[email protected]:15432/printfilm"+ # 连接已初始化的共享库时可关闭建表/补列/种子数据;仍加载数据库中的模型配置。+ database_bootstrap_enabled: bool = True# Postgres 连接池(统一任务平台 / API 共用)db_pool_size: int = 5db_max_overflow: int = 5@@ -70,6 +72,8 @@ class Settings(BaseSettings):kepu_seedance_sfx_audio: bool = Trueark_mock: bool = False+ # 本地连接共享测试库时关闭,避免本机和服务器同时消费、恢复同一队列。+ task_runtime_enabled: bool = True# 内置任务平台的进程内并发上限(全站 Worker 槽位)。task_runtime_max_concurrency: int = 4# 单用户同时进行中的 Worker 槽位(不含 awaiting_poll 注册项)。diff --git a/backend/app/main.py b/backend/app/main.pyindex 9cd3497..ef7d992 100644--- a/backend/app/main.py+++ b/backend/app/main.py@@ -16,6 +16,7 @@ from app.config import get_settingsfrom app.database import AsyncSessionLocal, engine, init_dbfrom app.logging_setup import configure_loggingfrom app.models import Template, User+from app.startup_database_retry import run_database_startup_stepsfrom app.services.tasks.runtime import runtime_summary, start_task_runtime, stop_task_runtimefrom app.services.templates_seed import TEMPLATES@@ -94,17 +95,31 @@ app.include_router(drama_router, prefix="/api")app.include_router(admin_router, prefix="/api")[email protected]_event("startup")-async def on_startup() -> None:- await init_db()- await _apply_schema_patches()+async def _load_startup_model_settings() -> None:async with AsyncSessionLocal() as db:from app.services.model_settings import load_model_settings_cacheawait load_model_settings_cache(db)- await seed_templates()- await bootstrap_admins()- await seed_agent_skills()++[email protected]_event("startup")+async def on_startup() -> None:+ database_steps = (_load_startup_model_settings,)+ if settings.database_bootstrap_enabled:+ database_steps = (+ init_db,+ _apply_schema_patches,+ _load_startup_model_settings,+ seed_templates,+ bootstrap_admins,+ seed_agent_skills,+ )+ else:+ logger.info("Database bootstrap disabled; loading model settings from the existing database")+ await run_database_startup_steps(+ database_steps,+ dispose=engine.dispose,+ )try:from app.services import oss as oss_svcdiff --git a/backend/app/schemas_tasks.py b/backend/app/schemas_tasks.pyindex f5acd05..473ee87 100644--- a/backend/app/schemas_tasks.py+++ b/backend/app/schemas_tasks.py@@ -306,6 +306,10 @@ class AdminTaskStatsOut(BaseModel):"""Task platform aggregate stats for admin monitoring."""pending_count: int = 0+ pending_ready_count: int = 0+ pending_deferred_count: int = 0+ pending_delayed_count: int = 0+ oldest_ready_wait_sec: int = 0active_count: int = 0leased_count: int = 0running_count: int = 0@@ -320,5 +324,7 @@ class AdminTaskStatsOut(BaseModel):poller: str = "stopped"watchdog: str = "stopped"runtime_healthy: bool = False+ scheduler_success_age_sec: float | None = None+ scheduler_consecutive_failures: int = 0domains: list[AdminTaskDomainStatsOut] = Field(default_factory=list)fetched_at: datetime | None = Nonediff --git a/backend/app/services/ark.py b/backend/app/services/ark.pyindex 4913ac0..292806e 100644--- a/backend/app/services/ark.py+++ b/backend/app/services/ark.py@@ -16,6 +16,8 @@ from urllib.parse import urlparseimport httpx+from app.services.tasks.upstream import observed_request+from app.config import Settings, get_settingsfrom app.services.billing.pricing import parse_upstream_cost_fen, parse_usage_dictfrom app.schemas_routing import ResolvedModelRoute@@ -1029,7 +1031,7 @@ class ArkGateway:async with httpx.AsyncClient(timeout=_upstream_timeout(IMAGE_GEN_READ_SEC)) as client:async def _post():# 单次上游 POST,限流重试由外层包住- return await client.post(+ return await observed_request(client, "POST",self._route_url(path, route),headers=self._route_headers(route),json=body,@@ -1341,7 +1343,7 @@ class ArkGateway:try:async with httpx.AsyncClient(timeout=_upstream_timeout(VIDEO_CREATE_READ_SEC)) as client:- resp = await client.post(+ resp = await observed_request(client, "POST",self._route_url("/contents/generations/tasks", route),headers=self._route_headers(route),json=self._video_json(body, route),@@ -1349,7 +1351,7 @@ class ArkGateway:if resp.status_code >= 400 and prompt_as_json:# Fallback: plain text promptbody["content"][0]["text"] = plain- resp = await client.post(+ resp = await observed_request(client, "POST",self._route_url("/contents/generations/tasks", route),headers=self._route_headers(route),json=self._video_json(body, route),@@ -1364,7 +1366,7 @@ class ArkGateway:if cg_content is not None:logger.warning("Seedance i2v text policy hit; retrying with CG style")body = {**body, "content": cg_content}- resp = await client.post(+ resp = await observed_request(client, "POST",self._route_url("/contents/generations/tasks", route),headers=self._route_headers(route),json=self._video_json(body, route),@@ -1382,7 +1384,7 @@ class ArkGateway:and "ratio" in body):body.pop("ratio", None)- resp = await client.post(+ resp = await observed_request(client, "POST",self._route_url("/contents/generations/tasks", route),headers=self._route_headers(route),json=self._video_json(body, route),@@ -1391,7 +1393,7 @@ class ArkGateway:# 无目标画幅时的兼容回退;有竖屏目标时禁止 adaptive,避免再次出横屏body["content"][1].pop("role", None)body["ratio"] = "adaptive"- resp = await client.post(+ resp = await observed_request(client, "POST",self._route_url("/contents/generations/tasks", route),headers=self._route_headers(route),json=self._video_json(body, route),@@ -1485,7 +1487,7 @@ class ArkGateway:try:async with httpx.AsyncClient(timeout=_upstream_timeout(VIDEO_CREATE_READ_SEC)) as client:- resp = await client.post(+ resp = await observed_request(client, "POST",self._route_url("/contents/generations/tasks", route),headers=self._route_headers(route),json=self._video_json(payload, route),@@ -1510,7 +1512,7 @@ class ArkGateway:project_id,)payload = {**payload, "content": cg_content}- resp = await client.post(+ resp = await observed_request(client, "POST",self._route_url("/contents/generations/tasks", route),headers=self._route_headers(route),json=self._video_json(payload, route),@@ -1637,7 +1639,7 @@ class ArkGateway:async with httpx.AsyncClient(timeout=_upstream_timeout(VIDEO_POLL_READ_SEC, connect=15.0)) as client:while time.monotonic() < deadline:try:- resp = await client.get(+ resp = await observed_request(client, "GET",self._url(f"/contents/generations/tasks/{task_id}"),headers=self._headers(),)@@ -1695,7 +1697,7 @@ class ArkGateway:)try:async with httpx.AsyncClient(timeout=_upstream_timeout(VIDEO_FETCH_READ_SEC, connect=15.0)) as client:- resp = await client.get(+ resp = await observed_request(client, "GET",self._url(f"/contents/generations/tasks/{task_id}"),headers=self._headers(),)@@ -1868,7 +1870,7 @@ class ArkGateway:if tokenfree_tts_uses_chat_audio(model_id):return await self._tts_openai_chat_audio(text, voice, dest, model=model_id)async with httpx.AsyncClient(timeout=120.0) as client:- resp = await client.post(+ resp = await observed_request(client, "POST",f"{base}/audio/speech",headers=self._headers(),json={@@ -1914,7 +1916,7 @@ class ArkGateway:})async with httpx.AsyncClient(timeout=120.0) as client:- resp = await client.post(f"{base}/chat/completions", headers=self._headers(), json=body)+ resp = await observed_request(client, "POST", f"{base}/chat/completions", headers=self._headers(), json=body)if resp.status_code >= 400:logger.warning("OpenAI chat-audio HTTP %s model=%s: %s",diff --git a/backend/app/services/billing/ephemeral.py b/backend/app/services/billing/ephemeral.pyindex 5fa56dd..5f593ad 100644--- a/backend/app/services/billing/ephemeral.py+++ b/backend/app/services/billing/ephemeral.py@@ -18,6 +18,7 @@ from app.services.billing.context import billing_scopefrom app.services.billing.settlement import freeze_for_task, settle_taskfrom app.services.tasks.handlers import get_task_handlerfrom app.services.tasks.service import append_task_event, build_task_event, build_task_step+from app.services.tasks.upstream import upstream_event_sessionT = TypeVar("T")@@ -138,7 +139,7 @@ async def run_billed_ephemeral(result: Ttry:- async with billing_scope(task.id):+ async with billing_scope(task.id), upstream_event_session(db):result = await executor()task.status = "succeeded"task.progress_percent = 100@@ -240,7 +241,7 @@ async def run_billed_ephemeral_deferred(result: Ttry:- async with billing_scope(task.id):+ async with billing_scope(task.id), upstream_event_session(db):result = await executor()provider_id = _extract_provider_task_id(result)if not provider_id:diff --git a/backend/app/services/llm_client.py b/backend/app/services/llm_client.pyindex 9394b8a..224f982 100644--- a/backend/app/services/llm_client.py+++ b/backend/app/services/llm_client.py@@ -10,6 +10,7 @@ import httpxfrom app.config import get_settingsfrom app.services.logical_model_router import resolve_logical_model, resolve_logical_model_id+from app.services.tasks.upstream import observed_requestlogger = logging.getLogger(__name__)@@ -113,7 +114,7 @@ async def chat_completions(max_tokens,)async with httpx.AsyncClient(timeout=timeout) as client:- res = await client.post(+ res = await observed_request(client, "POST",f"{base}/chat/completions",headers={"Authorization": f"Bearer {api_key}",diff --git a/backend/app/services/tasks/poller.py b/backend/app/services/tasks/poller.pyindex 832c227..a216481 100644--- a/backend/app/services/tasks/poller.py+++ b/backend/app/services/tasks/poller.py@@ -12,6 +12,7 @@ from sqlalchemy import or_, selectfrom app.config import get_settingsfrom app.database import AsyncSessionLocalfrom app.models_tasks import TaskRun+from app.services.billing.context import billing_scopefrom app.services.billing.settlement import settle_taskfrom app.services.tasks.service import append_task_event@@ -277,7 +278,9 @@ async def _poll_one_ephemeral_task(task_id: int, *, now, timeout_sec: float) ->if not user or not provider_id:return- data = await poll_video_task(user, provider_id)+ # 后台轮询与提交请求共用任务上下文,便于关联真实上游状态和计费。+ async with billing_scope(task_id):+ data = await poll_video_task(user, provider_id)status = str(data.get("status") or "").strip().lower()if status in {"", "running", "queued"}:task.next_action_at = now + timedelta(diff --git a/backend/app/services/tasks/runtime.py b/backend/app/services/tasks/runtime.pyindex 5de77b2..a6d52bd 100644--- a/backend/app/services/tasks/runtime.py+++ b/backend/app/services/tasks/runtime.py@@ -21,6 +21,7 @@ from app.services.tasks.scheduler import (scheduler_status,scheduler_tick_age_sec,scheduler_tick_stale,+ scheduler_diagnostics,start_scheduler,stop_scheduler,)@@ -34,6 +35,9 @@ _watchdog_intentionally_stopped: bool = True# 启动统一任务平台运行时(Worker 调度 + Selector 轮询 + 看门狗)。async def start_task_runtime() -> None:+ if not getattr(get_settings(), "task_runtime_enabled", True):+ logger.info("task runtime disabled for this API process")+ return# 逐个登记已启动组件;后续启动失败或取消时按依赖逆序清理。async with AsyncExitStack() as startup:await start_scheduler()@@ -114,17 +118,33 @@ async def _watchdog_once() -> None:# 返回任务平台运行时摘要(槽位 + 循环存活 + 心跳年龄)。def runtime_summary() -> dict[str, int | str | float | bool]:+ if not getattr(get_settings(), "task_runtime_enabled", True):+ return {+ "enabled": False,+ "healthy": True,+ "scheduler": "disabled",+ "poller": "disabled",+ "watchdog": "disabled",+ "scheduler_running_jobs": 0,+ "scheduler_tick_age_sec": 0.0,+ "scheduler_success_age_sec": 0.0,+ "scheduler_consecutive_failures": 0,+ "poller_tick_age_sec": 0.0,+ }sched = scheduler_status()poll = poller_status()dog = watchdog_status()+ diagnostics = scheduler_diagnostics()healthy = (sched == "running"and poll == "running"and dog == "running"and not scheduler_tick_stale()and not poller_tick_stale()+ and diagnostics["scheduler_consecutive_failures"] == 0)return {+ "enabled": True,"healthy": healthy,"scheduler": sched,"scheduler_running_jobs": running_count(),@@ -132,4 +152,5 @@ def runtime_summary() -> dict[str, int | str | float | bool]:"poller": poll,"poller_tick_age_sec": round(poller_tick_age_sec(), 1),"watchdog": dog,+ **diagnostics,}diff --git a/backend/app/services/tasks/scheduler.py b/backend/app/services/tasks/scheduler.pyindex 538c08f..e4f6ba5 100644--- a/backend/app/services/tasks/scheduler.py+++ b/backend/app/services/tasks/scheduler.py@@ -8,18 +8,22 @@ import timeimport uuidfrom datetime import UTC, datetime, timedelta-from sqlalchemy import and_, or_, select, update+from sqlalchemy import and_, func, or_, select, update+from sqlalchemy.orm import aliasedfrom app.config import get_settingsfrom app.database import AsyncSessionLocalfrom app.models_tasks import TaskRunfrom app.services.billing.settlement import reconcile_terminal_frozen_tasks-from app.services.tasks.executor import execute_task_run+from app.services.tasks.executor import _mark_cancelled, execute_task_runfrom app.services.tasks.service import (+ FINALIZING_UNTIL_KEY,append_task_event,count_user_active_runtime_tasks,+ get_task_for_runtime,reconcile_sequential_batches,reconcile_stale_pending_tasks,+ task_finalizing_window_open,)logger = logging.getLogger("app.tasks.scheduler")@@ -27,21 +31,34 @@ logger = logging.getLogger("app.tasks.scheduler")# 调度循环句柄、进程内执行槽、停机信号、心跳与孤儿扫描时间戳_scheduler_task: asyncio.Task | None = None_running_jobs: dict[int, asyncio.Task] = {}+_cancel_jobs: dict[int, asyncio.Task] = {}+_maintenance_task: asyncio.Task | None = None_stop_event = asyncio.Event()_last_tick_mono: float = 0.0-_last_orphan_check_mono: float = 0.0+_last_success_mono: float = 0.0+_loop_started_mono: float = 0.0+_consecutive_failures: int = 0_intentionally_stopped: bool = True+_MAINTENANCE_TIMEOUT_SEC = 5.0+_MAX_CLAIM_PAGES = 4+_MAX_CANDIDATES_PER_PAGE = 128+_MAX_CANCEL_JOBS = 16# 启动任务调度循环。async def start_scheduler() -> None:global _scheduler_task, _intentionally_stopped, _last_tick_mono+ global _last_success_mono, _consecutive_failures+ global _loop_started_monoif _scheduler_task and not _scheduler_task.done():return_intentionally_stopped = False- await recover_orphaned_tasks()_stop_event.clear()_last_tick_mono = time.monotonic()+ _loop_started_mono = _last_tick_mono+ _last_success_mono = 0.0+ _consecutive_failures = 0+ _ensure_maintenance_loop()_scheduler_task = asyncio.create_task(_scheduler_loop(), name="task-scheduler")@@ -56,31 +73,35 @@ async def stop_scheduler() -> None:await _scheduler_taskexcept asyncio.CancelledError:pass- running_jobs = list(_running_jobs.values())+ if _maintenance_task and not _maintenance_task.done():+ _maintenance_task.cancel()+ await asyncio.gather(_maintenance_task, return_exceptions=True)+ running_jobs = list(_running_jobs.values()) + list(_cancel_jobs.values())for task in running_jobs:if not task.done():task.cancel()if running_jobs:await asyncio.gather(*running_jobs, return_exceptions=True)_running_jobs.clear()+ _cancel_jobs.clear()# 仅重启调度循环(保留进程内仍在跑的 job),用于看门狗拉起卡死 tick。async def restart_scheduler_loop(*, reason: str = "watchdog") -> None:- global _scheduler_task, _intentionally_stopped, _last_tick_mono+ global _scheduler_task, _intentionally_stopped+ global _loop_started_monoif _intentionally_stopped:returnlogger.warning("restarting task scheduler loop reason=%s", reason)- _stop_event.set()if _scheduler_task and not _scheduler_task.done():_scheduler_task.cancel()try:await _scheduler_taskexcept asyncio.CancelledError:pass- await recover_orphaned_tasks()_stop_event.clear()- _last_tick_mono = time.monotonic()+ _ensure_maintenance_loop()+ _loop_started_mono = time.monotonic()_scheduler_task = asyncio.create_task(_scheduler_loop(), name="task-scheduler")@@ -105,12 +126,23 @@ def scheduler_tick_age_sec() -> float:return max(0.0, time.monotonic() - _last_tick_mono)+# 返回最近成功调度的年龄与连续失败数;失败不能伪装成成功心跳。+def scheduler_diagnostics() -> dict[str, int | float]:+ age = time.monotonic() - _last_success_mono if _last_success_mono > 0 else 1e9+ return {+ "scheduler_success_age_sec": round(max(0.0, age), 1),+ "scheduler_consecutive_failures": _consecutive_failures,+ }++# 是否因心跳过期应视为卡死(供看门狗判断)。def scheduler_tick_stale() -> bool:if _intentionally_stopped:return Falsestale_sec = max(15, int(get_settings().task_runtime_tick_stale_sec))- return scheduler_tick_age_sec() > stale_sec+ # 重启保留真实失败记录,但给新循环一次完整执行机会,避免 watchdog 连续掐断重试。+ heartbeat = max(_last_tick_mono, _loop_started_mono)+ return time.monotonic() - heartbeat > stale_sec# 本地是否仍持有该任务的执行协程。@@ -121,46 +153,73 @@ def _job_alive(task_id: int) -> bool:# 周期扫描到期任务并交给执行器。async def _scheduler_loop() -> None:- global _last_tick_mono+ global _last_tick_mono, _last_success_mono, _consecutive_failureswhile not _stop_event.is_set():- _last_tick_mono = time.monotonic()timeout = max(20.0, float(get_settings().task_runtime_tick_stale_sec) - 10.0)try:await asyncio.wait_for(_tick(), timeout=timeout)except asyncio.TimeoutError:+ _consecutive_failures += 1logger.error("task scheduler tick timed out after %.0fs", timeout)except asyncio.CancelledError:raiseexcept Exception: # noqa: BLE001+ _consecutive_failures += 1logger.exception("task scheduler tick failed")- finally:+ else:_last_tick_mono = time.monotonic()+ _last_success_mono = _last_tick_mono+ _consecutive_failures = 0await asyncio.sleep(1.0)+# 保持唯一维护协程;watchdog 只重启调度循环时复用仍存活的维护任务。+def _ensure_maintenance_loop() -> None:+ global _maintenance_task+ if _maintenance_task is None or _maintenance_task.done():+ _maintenance_task = asyncio.create_task(_maintenance_loop(), name="task-maintenance")+++# 每项维护独占短事务;超时退出时由 session 上下文回滚,释放已持有的锁。+async def _run_maintenance_operation(name: str) -> None:+ if name == "orphan_recovery":+ await recover_orphaned_tasks()+ return+ operations = {+ "sequential_queue": reconcile_sequential_batches,+ "stale_fragments": reconcile_stale_pending_tasks,+ "billing_reconcile": reconcile_terminal_frozen_tasks,+ }+ async with AsyncSessionLocal() as db:+ await operations[name](db)+++# 低频维护与任务领取隔离,单项锁等待不得阻塞新任务和取消请求。+async def _maintenance_loop() -> None:+ while not _stop_event.is_set():+ for name in ("orphan_recovery", "sequential_queue", "stale_fragments", "billing_reconcile"):+ try:+ await asyncio.wait_for(_run_maintenance_operation(name), timeout=_MAINTENANCE_TIMEOUT_SEC)+ except asyncio.CancelledError:+ raise+ except asyncio.TimeoutError:+ logger.warning("task maintenance timed out operation=%s", name)+ except Exception: # noqa: BLE001+ logger.exception("task maintenance failed operation=%s", name)+ interval = max(5, int(get_settings().task_runtime_orphan_check_sec))+ await asyncio.sleep(interval)++# 扫描并租约抢占可执行任务。async def _tick() -> None:- global _last_orphan_check_mononow = datetime.now(UTC)- orphan_every = max(5, int(get_settings().task_runtime_orphan_check_sec))- if time.monotonic() - _last_orphan_check_mono >= orphan_every:- await recover_orphaned_tasks()- # 低频对账:收敛 settle 异常中断遗留的"终态 + frozen"任务(幂等)- async with AsyncSessionLocal() as reconcile_db:- await reconcile_terminal_frozen_tasks(reconcile_db)- _last_orphan_check_mono = time.monotonic()-- async with AsyncSessionLocal() as db:- await reconcile_sequential_batches(db)- await reconcile_stale_pending_tasks(db)for task_id, job in list(_running_jobs.items()):if job.done():_running_jobs.pop(task_id, None)- async with AsyncSessionLocal() as db:- cancel_stmt = select(TaskRun.id).where(TaskRun.status == "cancel_requested")- cancel_ids = [int(item) for item in (await db.execute(cancel_stmt)).scalars().all()]- for task_id in cancel_ids:- await cancel_running_task(task_id)+ for task_id, job in list(_cancel_jobs.items()):+ if job.done():+ _cancel_jobs.pop(task_id, None)+ await _claim_cancel_requests()capacity = max(1, int(get_settings().task_runtime_max_concurrency))user_limit = max(1, int(get_settings().task_user_max_concurrency))@@ -170,55 +229,69 @@ async def _tick() -> None:claimed_ids: list[int] = []async with AsyncSessionLocal() as db:- stmt = (- select(TaskRun.id, TaskRun.status, TaskRun.requested_by)- .where(- TaskRun.status.in_(("pending", "cancel_requested")),- TaskRun.next_action_at.is_not(None),- TaskRun.next_action_at <= now,- )- .order_by(TaskRun.priority.asc(), TaskRun.created_at.asc(), TaskRun.id.asc())- .limit(max(available_slots * 4, available_slots))- )- candidates = list((await db.execute(stmt)).all())user_active_cache: dict[int, int] = {}- for row in candidates:- if len(claimed_ids) >= available_slots:+ seen_ids: set[int] = set()+ full_users: set[int] = set()+ active = aliased(TaskRun)+ active_count = (+ select(func.count(active.id))+ .where(active.requested_by == TaskRun.requested_by, active.status.in_(("leased", "running")))+ .correlate(TaskRun)+ .scalar_subquery()+ )+ for _ in range(_MAX_CLAIM_PAGES):+ remaining = available_slots - len(claimed_ids)+ if remaining <= 0:break- task_id = int(row.id)- current_status = str(row.status)- user_id = int(row.requested_by)- if task_id in _running_jobs and not _running_jobs[task_id].done():- continue- if user_id not in user_active_cache:- user_active_cache[user_id] = await count_user_active_runtime_tasks(db, user_id)- if user_active_cache[user_id] >= user_limit:- continue- lease_token = uuid.uuid4().hex- next_status = "leased" if current_status != "cancel_requested" else "cancel_requested"- claim = (- update(TaskRun)- .where(TaskRun.id == task_id, TaskRun.status == current_status)- .values(- status=next_status,- lease_token=lease_token,- lease_until=now + timedelta(minutes=10),+ stmt = (+ select(TaskRun.id, TaskRun.status, TaskRun.requested_by)+ .where(+ TaskRun.status == "pending",+ TaskRun.cancel_requested.is_(False),+ TaskRun.next_action_at.is_not(None),+ TaskRun.next_action_at <= now,+ active_count < user_limit,)+ .order_by(TaskRun.priority.asc(), TaskRun.created_at.asc(), TaskRun.id.asc())+ .limit(min(_MAX_CANDIDATES_PER_PAGE, max(remaining * 4, remaining)))+ .with_for_update(skip_locked=True, of=TaskRun))- result = await db.execute(claim)- if int(result.rowcount or 0) != 1:- continue- task = await db.get(TaskRun, task_id)- await append_task_event(- db,- task_id,- event_type="task.leased",- status=next_status,- phase=getattr(task, "current_step_key", None),- message="任务已被调度器领取",- )- claimed_ids.append(task_id)- user_active_cache[user_id] += 1+ if seen_ids:+ stmt = stmt.where(TaskRun.id.not_in(sorted(seen_ids)))+ if full_users:+ stmt = stmt.where(TaskRun.requested_by.not_in(sorted(full_users)))+ candidates = list((await db.execute(stmt)).all())+ if not candidates:+ break+ for row in candidates:+ if len(claimed_ids) >= available_slots:+ break+ task_id = int(row.id)+ seen_ids.add(task_id)+ user_id = int(row.requested_by)+ if _job_alive(task_id):+ continue+ if user_id not in user_active_cache:+ user_active_cache[user_id] = await count_user_active_runtime_tasks(db, user_id)+ if user_active_cache[user_id] >= user_limit:+ full_users.add(user_id)+ continue+ result = await db.execute(+ update(TaskRun)+ .where(TaskRun.id == task_id, TaskRun.status == "pending", TaskRun.cancel_requested.is_(False))+ .values(status="leased", lease_token=uuid.uuid4().hex, lease_until=now + timedelta(minutes=10))+ )+ if int(result.rowcount or 0) != 1:+ continue+ task = await db.get(TaskRun, task_id)+ await append_task_event(+ db, task_id, event_type="task.leased", status="leased",+ phase=getattr(task, "current_step_key", None), message="任务已被调度器领取",+ )+ claimed_ids.append(task_id)+ user_active_cache[user_id] += 1+ if user_active_cache[user_id] >= user_limit:+ full_users.add(user_id)if claimed_ids:await db.commit()@@ -228,6 +301,52 @@ async def _tick() -> None:_running_jobs[task_id] = asyncio.create_task(_run_one(task_id))+# 取消使用独立且有上限的槽位,满额用户或普通队列积压不能阻挡取消。+async def _claim_cancel_requests() -> None:+ available = max(0, _MAX_CANCEL_JOBS - len(_cancel_jobs))+ if available <= 0:+ return+ claimed: list[int] = []+ async with AsyncSessionLocal() as db:+ stmt = (+ select(TaskRun.id)+ .where(+ TaskRun.status == "cancel_requested",+ or_(TaskRun.next_action_at.is_(None), TaskRun.next_action_at <= datetime.now(UTC)),+ )+ .order_by(TaskRun.id.asc())+ .limit(available)+ .with_for_update(skip_locked=True, of=TaskRun)+ )+ if _cancel_jobs:+ stmt = stmt.where(TaskRun.id.not_in(sorted(_cancel_jobs)))+ ids = [int(item) for item in (await db.execute(stmt)).scalars().all()]+ for task_id in ids:+ if await cancel_running_task(task_id):+ continue+ claimed.append(task_id)+ for task_id in claimed:+ _cancel_jobs[task_id] = asyncio.create_task(_run_cancel_request(task_id), name=f"task-cancel-{task_id}")+++# 取消路径只调用状态/结算收敛,绝不进入业务 handler 或重新提交上游。+async def _run_cancel_request(task_id: int) -> None:+ try:+ async with AsyncSessionLocal() as db:+ task = await get_task_for_runtime(db, task_id)+ if task and task.status == "cancel_requested":+ if task_finalizing_window_open(task):+ until = datetime.fromisoformat(str(task.payload[FINALIZING_UNTIL_KEY]))+ task.next_action_at = until if until.tzinfo else until.replace(tzinfo=UTC)+ await db.commit()+ return+ await _mark_cancelled(db, task)+ except Exception: # noqa: BLE001+ logger.exception("task cancellation failed task_id=%s", task_id)+ finally:+ _cancel_jobs.pop(task_id, None)++# 包装执行器并在结束后释放运行槽位。async def _run_one(task_id: int) -> None:try:@@ -251,8 +370,6 @@ async def recover_orphaned_tasks() -> int:grace_sec = max(5, int(get_settings().task_runtime_recover_grace_sec))stale_before = now - timedelta(seconds=grace_sec)async with AsyncSessionLocal() as db:- await reconcile_sequential_batches(db)- await reconcile_stale_pending_tasks(db)stmt = select(TaskRun).where(or_(and_(diff --git a/backend/app/services/tasks/service.py b/backend/app/services/tasks/service.pyindex 973a663..0b6384e 100644--- a/backend/app/services/tasks/service.py+++ b/backend/app/services/tasks/service.py@@ -182,9 +182,9 @@ async def create_task(# 串行 batch 中上一镜完成后激活下一镜任务。-async def activate_next_sequential_task(db: AsyncSession, batch_key: str | None, completed_index: int) -> None:+async def activate_next_sequential_task(db: AsyncSession, batch_key: str | None, completed_index: int) -> bool:if not batch_key:- return+ return Falsefrom app.config import get_settingsfrom app.services.drama.access import count_user_inflight_fragment_video_tasks@@ -194,18 +194,23 @@ async def activate_next_sequential_task(db: AsyncSession, batch_key: str | None,.where(TaskRun.batch_key == batch_key,TaskRun.status == "pending",+ TaskRun.next_action_at.is_(None),+ TaskRun.cancel_requested.is_(False),).order_by(TaskRun.id.asc())+ .with_for_update(skip_locked=True))rows = list((await db.execute(stmt)).scalars().all())for task in rows:+ if task.next_action_at is not None or task.cancel_requested:+ continuepayload = task.payload if isinstance(task.payload, dict) else {}if int(payload.get("batch_index", -1)) != next_index:continuelimit = max(1, int(get_settings().drama_user_video_job_limit or 12))inflight = await count_user_inflight_fragment_video_tasks(db, int(task.requested_by))if inflight >= limit:- return+ return Falsetask.next_action_at = datetime.now(UTC)await append_task_event(db,@@ -216,7 +221,8 @@ async def activate_next_sequential_task(db: AsyncSession, batch_key: str | None,message=f"前置分镜已完成,激活 batch 第 {next_index + 1} 镜",)await db.commit()- return+ return True+ return False# 串行 batch 中某一镜失败后,终止后续仍 pending 的兄弟任务。@@ -622,18 +628,17 @@ async def reconcile_sequential_batches(db: AsyncSession) -> int:)continue+ if uses_episode_rebalance:+ # 分镜仅按真实镜序及前置尾帧重排,不能同时由 batch 分支重复点亮。+ continue+succeeded_indices = [int((t.payload or {}).get("batch_index", -1))for t in tasksif t.status == "succeeded" and isinstance(t.payload, dict)]if succeeded_indices:- await activate_next_sequential_task(db, batch_key, max(succeeded_indices))- changed += 1- continue-- if uses_episode_rebalance:- # 无论能否登记项目,都不要把连续点击当成独立首镜点亮+ changed += int(await activate_next_sequential_task(db, batch_key, max(succeeded_indices)))continuefirst = by_index.get(0)@@ -1112,8 +1117,12 @@ async def cancel_tasks_for_scope(async def get_task_for_runtime(db: AsyncSession, task_id: int) -> TaskRun | None:- """Load one task with full details for runtime loops."""- stmt = select(TaskRun).options(*task_detail_options()).where(TaskRun.id == task_id)+ """执行器仅加载步骤与目标,避免重复读取整段上游/激活事件历史。"""+ stmt = (+ select(TaskRun)+ .options(selectinload(TaskRun.steps), selectinload(TaskRun.targets))+ .where(TaskRun.id == task_id)+ )return (await db.execute(stmt)).scalar_one_or_none()@@ -1207,11 +1216,28 @@ async def cancel_task_admin(db: AsyncSession, task_id: int) -> TaskRun:async def get_task_stats_admin(db: AsyncSession) -> dict[str, Any]:"""Aggregate task platform stats for admin dashboard."""+ now = datetime.now(UTC)status_rows = (await db.execute(select(TaskRun.status, func.count()).group_by(TaskRun.status))).all()status_counts = {str(status): int(count) for status, count in status_rows}+ ready_count, deferred_count, delayed_count, oldest_ready_at = (+ await db.execute(+ select(+ func.count().filter(TaskRun.next_action_at <= now),+ func.count().filter(TaskRun.next_action_at.is_(None)),+ func.count().filter(TaskRun.next_action_at > now),+ func.min(TaskRun.next_action_at).filter(TaskRun.next_action_at <= now),+ ).where(TaskRun.status == "pending")+ )+ ).one()+ oldest_ready_wait_sec = 0+ if oldest_ready_at is not None:+ if oldest_ready_at.tzinfo is None:+ oldest_ready_at = oldest_ready_at.replace(tzinfo=UTC)+ oldest_ready_wait_sec = max(0, int((now - oldest_ready_at).total_seconds()))+domain_rows = (await db.execute(select(TaskRun.domain, TaskRun.status, func.count()).group_by(TaskRun.domain, TaskRun.status)@@ -1239,6 +1265,10 @@ async def get_task_stats_admin(db: AsyncSession) -> dict[str, Any]:return {"pending_count": status_counts.get("pending", 0),+ "pending_ready_count": int(ready_count),+ "pending_deferred_count": int(deferred_count),+ "pending_delayed_count": int(delayed_count),+ "oldest_ready_wait_sec": oldest_ready_wait_sec,"active_count": sum(status_counts.get(s, 0) for s in ACTIVE_TASK_STATUSES if s != "pending"),"leased_count": status_counts.get("leased", 0),"running_count": status_counts.get("running", 0),diff --git a/backend/app/services/tasks/upstream.py b/backend/app/services/tasks/upstream.pynew file mode 100644index 0000000..d2666fb--- /dev/null+++ b/backend/app/services/tasks/upstream.py@@ -0,0 +1,204 @@+"""真实上游 HTTP 请求的脱敏 TaskEvent 留痕;日志故障不改变网络请求结果。"""++from __future__ import annotations++import asyncio+import logging+import time+import uuid+from collections import OrderedDict+from collections.abc import AsyncIterator+from contextlib import asynccontextmanager+from contextvars import ContextVar+from typing import Any+from urllib.parse import unquote, urlsplit++from sqlalchemy import select++from app.database import AsyncSessionLocal+from app.models_tasks import TaskEvent, TaskRun, TaskStep+from app.services.billing.context import get_current_task_run_id+from app.services.tokenfree_video import extract_video_task_id, unwrap_video_task_payload+from app.services.upstream_sanitize import sanitize_upstream_value++logger = logging.getLogger(__name__)+_EVENT_TIMEOUT_SEC = 1.0+_POLL_SAMPLE_SEC = 60.0+_MAX_POLL_SAMPLES = 20+_POLL_CACHE_MAX = 2048+_poll_cache: OrderedDict[tuple, tuple[str, float, int]] = OrderedDict()+_event_session: ContextVar[Any | None] = ContextVar("upstream_event_session", default=None)+++@asynccontextmanager+async def upstream_event_session(db: Any) -> AsyncIterator[None]:+ """内联任务尚未提交时,把事件附加到调用者事务,禁止日志独自提交业务数据。"""+ token = _event_session.set(db)+ try:+ yield+ finally:+ _event_session.reset(token)+++def _append_event(+ db: Any, task_id: int, task: TaskRun | None, step: TaskStep | None,+ event_type: str, payload: dict[str, Any],+) -> None:+ """仅修改内存对象并 add 事件,不查询、不 flush、不 commit。"""+ provider_id = payload.get("provider_task_id")+ if event_type == "upstream.request.accepted" and payload.get("is_video_submit") and provider_id:+ if task is not None:+ task.provider_task_id = str(provider_id)+ if step is not None:+ step.provider_task_id = str(provider_id)+ step.provider_name = str(payload.get("provider") or "tokenfree")+ db.add(TaskEvent(+ task_id=task_id, event_type=event_type,+ status=task.status if task is not None else None,+ phase=task.current_step_key if task is not None else None,+ message=event_type, payload=payload,+ ))+++def _append_to_caller_session(db: Any, task_id: int, event_type: str, payload: dict[str, Any]) -> None:+ """只查看已加载/新建对象,避免未提交任务不可见及日志触发 autoflush。"""+ objects = list(db.identity_map.values()) + list(db.new)+ task = next((item for item in objects if isinstance(item, TaskRun) and item.id == task_id), None)+ if task is not None:+ objects.extend(task.__dict__.get("steps") or [])+ step = next((+ item for item in objects+ if isinstance(item, TaskStep) and item.task_id == task_id+ and (task is None or not task.current_step_key or item.step_key == task.current_step_key)+ ), None)+ _append_event(db, task_id, task, step, event_type, payload)+++def _video_request(method: str, endpoint: str) -> tuple[bool, bool, str | None]:+ """识别视频建单与轮询路径,只对异步视频响应回填 provider ID。"""+ path = urlsplit(endpoint).path.rstrip("/")+ for suffix in ("/videos", "/contents/generations/tasks"):+ if path.endswith(suffix):+ return method == "POST", False, None+ marker = f"{suffix}/"+ if marker in path and method == "GET":+ task_id = unquote(path.split(marker, 1)[1].split("/", 1)[0])+ return False, True, task_id+ return False, False, None+++def _response_body(response: Any) -> Any:+ """读取响应用于留痕,解析失败时保留文本;二进制只存类型和长度。"""+ try:+ return response.json()+ except Exception: # noqa: BLE001+ content_type = str(getattr(response, "headers", {}).get("content-type", ""))+ if content_type and not any(kind in content_type for kind in ("json", "text", "xml")):+ return getattr(response, "content", b"")+ return getattr(response, "text", "")+++def _should_record_poll(task_id: int, endpoint: str, provider_id: str | None, state: str) -> bool:+ """只记录状态变化与有限的一分钟采样,避免每轮轮询都写事件。"""+ key = (task_id, endpoint.split("?", 1)[0], provider_id)+ now = time.monotonic()+ previous = _poll_cache.get(key)+ changed = previous is None or previous[0] != state+ sampled = previous is not None and previous[2] < _MAX_POLL_SAMPLES and now - previous[1] >= _POLL_SAMPLE_SEC+ if not changed and not sampled:+ return False+ _poll_cache[key] = (state, now, (previous[2] if previous else 0) + 1)+ _poll_cache.move_to_end(key)+ while len(_poll_cache) > _POLL_CACHE_MAX:+ _poll_cache.popitem(last=False)+ return True+++async def _persist_event(task_id: int, event_type: str, payload: dict[str, Any]) -> None:+ """使用独立短事务追加事件;仅回填视频上游 ID,不改业务状态或计费字段。"""+ caller_session = _event_session.get()+ if caller_session is not None:+ _append_to_caller_session(caller_session, task_id, event_type, payload)+ return+ async with AsyncSessionLocal() as db:+ task = await db.get(TaskRun, task_id)+ if task is None:+ return+ provider_id = payload.get("provider_task_id")+ step = None+ if event_type == "upstream.request.accepted" and payload.get("is_video_submit") and provider_id:+ stmt = select(TaskStep).where(TaskStep.task_id == task_id)+ if task.current_step_key:+ stmt = stmt.where(TaskStep.step_key == task.current_step_key)+ step = (await db.execute(stmt.order_by(TaskStep.id.asc()).limit(1))).scalar_one_or_none()+ _append_event(db, task_id, task, step, event_type, payload)+ await db.commit()+++async def _safe_record(task_id: int, event_type: str, payload: dict[str, Any]) -> None:+ """脱敏与写入均为尽力记录,失败或锁超时不能触发真实请求重试。"""+ try:+ safe = sanitize_upstream_value(payload)+ await asyncio.wait_for(_persist_event(task_id, event_type, safe), timeout=_EVENT_TIMEOUT_SEC)+ except Exception: # noqa: BLE001+ logger.warning("upstream event unavailable task_id=%s event_type=%s", task_id, event_type)+++async def observed_request(+ client: Any, method: str, endpoint: str, *, provider: str = "tokenfree", **kwargs: Any+) -> Any:+ """透明包装一次真实 HTTP 调用,保留参数、返回对象、异常和原重试策略。"""+ method = method.upper()+ send = getattr(client, method.lower())+ task_id = get_current_task_run_id()+ if task_id is None:+ return await send(endpoint, **kwargs)+ is_submit, is_poll, provider_id = _video_request(method, endpoint)+ body = kwargs.get("json", kwargs.get("data", kwargs.get("content")))+ model = str(body.get("model") or "") if isinstance(body, dict) else None+ payload = {+ "request_id": uuid.uuid4().hex,+ "method": method, "endpoint": endpoint, "model": model or None,+ "provider": provider, "provider_task_id": provider_id,+ "elapsed_ms": 0, "status_code": None, "is_video_submit": is_submit,+ "request": {"headers": kwargs.get("headers") or {}, "body": body,+ "params": kwargs.get("params"), "files": kwargs.get("files")},+ "response": None, "error": None,+ }+ if not is_poll:+ await _safe_record(task_id, "upstream.request.started", payload)+ started = time.perf_counter()+ try:+ response = await send(endpoint, **kwargs)+ except Exception as exc:+ payload = {**payload, "elapsed_ms": round((time.perf_counter() - started) * 1000, 1),+ "error": {"type": type(exc).__name__, "message": str(exc)}}+ if not is_poll or _should_record_poll(task_id, endpoint, provider_id, f"network:{type(exc).__name__}"):+ await _safe_record(task_id, "upstream.request.poll" if is_poll else "upstream.request.failed", payload)+ raise+ elapsed_ms = round((time.perf_counter() - started) * 1000, 1)+ # 以下留痕处理不得改变已成功返回的 HTTP 请求,避免业务据异常重复提交。+ try:+ data = _response_body(response)+ code = int(response.status_code)+ unwrapped = unwrap_video_task_payload(data) if isinstance(data, dict) else {}+ state = str(unwrapped.get("status") or "").lower()+ error = unwrapped.get("error")+ failed = code >= 400 or bool(error) or state in {"failed", "error", "cancelled"}+ if is_submit and not failed:+ provider_id = extract_video_task_id(data)+ payload = {+ **payload, "provider_task_id": provider_id,+ "status_code": code,+ "elapsed_ms": elapsed_ms,+ "response": {"status_code": code, "headers": dict(getattr(response, "headers", {})), "body": data},+ "error": error or (f"HTTP {code}" if code >= 400 else None),+ }+ if is_poll:+ if _should_record_poll(task_id, endpoint, provider_id, f"{code}:{state}"):+ await _safe_record(task_id, "upstream.request.poll", payload)+ else:+ await _safe_record(task_id, "upstream.request.failed" if failed else "upstream.request.accepted", payload)+ except Exception: # noqa: BLE001+ logger.warning("upstream response observation unavailable task_id=%s", task_id)+ return responsediff --git a/backend/app/services/upstream_sanitize.py b/backend/app/services/upstream_sanitize.pynew file mode 100644index 0000000..f28d22e--- /dev/null+++ b/backend/app/services/upstream_sanitize.py@@ -0,0 +1,96 @@+"""上游请求留痕的纯脱敏器:保留业务正文,移除凭据并摘要化二进制媒体。"""++from __future__ import annotations++import re+from itertools import islice+from collections.abc import Mapping+from typing import Any+from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit++_REDACTED = "[REDACTED]"+_MAX_STRING = 12_000+_MAX_ITEMS = 80+_MAX_DEPTH = 8+_URL_RE = re.compile(r"https?://[^\s<>\"']+")+_DATA_URI_RE = re.compile(r"data:([^;,\s]+)(?:;[^,]*)?;base64,([A-Za-z0-9+/=\r\n]+)", re.I)+_DATA_URI_HEADER_RE = re.compile(r"^data:([^;,\s]+)(?:;[^,]*)?;base64,", re.I)+_SECRET_KEYS = frozenset({+ "authorization", "proxyauthorization", "cookie", "setcookie", "apikey", "key",+ "token", "accesstoken", "refreshtoken", "securitytoken", "password", "passwd",+ "secret", "clientsecret", "credential", "credentials", "signature", "sign",+ "ossaccesskeyid", "accesskey", "accesskeyid", "secretaccesskey",+})+++def _secret_key(key: str) -> bool:+ """统一大小写与分隔符,识别凭据字段及云存储签名参数。"""+ normalized = re.sub(r"[^a-z0-9]", "", key.lower())+ return normalized in _SECRET_KEYS or normalized.endswith((+ "apikey", "token", "signature", "credential", "secret", "password", "authorization",+ ))+++def _safe_url(value: str) -> str:+ """脱敏 URL 用户信息、敏感查询参数和含凭据的片段,保留非敏感业务参数。"""+ try:+ parts = urlsplit(value)+ netloc = parts.netloc.rsplit("@", 1)[-1]+ if "@" in parts.netloc:+ netloc = f"{_REDACTED}@{netloc}"+ query = urlencode([+ (key, _REDACTED if _secret_key(key) else _safe_text(val))+ for key, val in parse_qsl(parts.query, keep_blank_values=True)+ ])+ fragment = _REDACTED if any(_secret_key(key) for key, _ in parse_qsl(parts.fragment)) else parts.fragment+ return urlunsplit((parts.scheme, netloc, parts.path, query, fragment))+ except ValueError:+ return "[INVALID URL]"+++def _safe_text(value: str) -> str:+ """清理错误等自由文本中的 URL、Bearer 凭据和键值形式的秘密。"""+ text = _URL_RE.sub(lambda match: _safe_url(match[0]), value)+ text = re.sub(r"\bBearer\s+[^\s,;\"']+", f"Bearer {_REDACTED}", text, flags=re.I)+ text = re.sub(+ r"\b(api[-_\s]*key|authorization|access[-_]?token|password|client[-_]?secret|token|signature|cookie|set-cookie)[\"']?\s*[:=]\s*(?:\"[^\"]*\"|'[^']*'|[^\s&;,\"']+)",+ lambda match: f"{match[1]}={_REDACTED}", text, flags=re.I,+ )+ text = re.sub(r"\bsk-[A-Za-z0-9_-]{12,}", _REDACTED, text)+ text = _DATA_URI_RE.sub(lambda match: f"[data:{match[1]};base64 length={len(match[2])}]", text)+ return text if len(text) <= _MAX_STRING else text[:_MAX_STRING] + f"…[truncated; length={len(text)}]"+++def sanitize_upstream_value(value: Any, *, _depth: int = 0, _key: str = "") -> Any:+ """递归复制并脱敏 JSON/headers;不改变真实请求,限制深度、条数和正文长度。"""+ if _secret_key(_key):+ return _REDACTED+ if isinstance(value, (bytes, bytearray, memoryview)):+ return {"type": "bytes", "length": len(value)}+ if isinstance(value, str):+ media = _DATA_URI_HEADER_RE.match(value)+ if media:+ return {"type": "data_uri", "media_type": media[1], "encoding": "base64", "length": len(value) - media.end()}+ if "base64" in _key.lower() or "b64" in _key.lower() or (+ len(value) >= 128 and len(value) % 4 == 0 and re.fullmatch(r"[A-Za-z0-9+/=\r\n]+", value)+ ):+ return {"type": "base64", "length": len(value)}+ return _safe_text(value)+ if value is None or isinstance(value, (bool, int, float)):+ return value+ if _depth >= _MAX_DEPTH:+ return {"type": "truncated", "reason": "max_depth"}+ if isinstance(value, Mapping):+ result = {+ str(key): sanitize_upstream_value(item, _depth=_depth + 1, _key=str(key))+ for key, item in islice(value.items(), _MAX_ITEMS)+ }+ if len(value) > _MAX_ITEMS:+ result["_truncated_items"] = len(value) - _MAX_ITEMS+ return result+ if isinstance(value, (list, tuple)):+ result = [sanitize_upstream_value(item, _depth=_depth + 1) for item in value[:_MAX_ITEMS]]+ if len(value) > _MAX_ITEMS:+ result.append({"_truncated_items": len(value) - _MAX_ITEMS})+ return result+ return {"type": type(value).__name__}diff --git a/backend/app/startup_database_retry.py b/backend/app/startup_database_retry.pynew file mode 100644index 0000000..80d370e--- /dev/null+++ b/backend/app/startup_database_retry.py@@ -0,0 +1,93 @@+"""Bounded connection recovery for idempotent database startup steps only."""++from __future__ import annotations++import asyncio+import errno+import logging+from collections.abc import Awaitable, Callable, Sequence++from sqlalchemy.exc import DBAPIError, DisconnectionError++logger = logging.getLogger(__name__)++_TRANSIENT_SQLSTATES = frozenset({"08003", "08006", "08007", "57P01", "57P02", "57P03"})+_NETWORK_ERRNOS = frozenset(+ {errno.ECONNRESET, errno.ECONNABORTED, errno.ENETRESET, errno.EPIPE, errno.ETIMEDOUT, errno.ECONNREFUSED}+)+_NETWORK_WINERRORS = frozenset({121, 10053, 10054, 10060, 10061})+_MAX_ATTEMPTS = 3+++def is_transient_database_disconnect(error: BaseException) -> bool:+ """Recognize driver disconnects without treating every DB error as transient.++ Inspect SQLAlchemy's driver wrapper and chained OS errors. A definite server+ error such as invalid credentials, syntax or a missing table takes priority+ over a generic connection-invalidated flag.+ """+ pending = [error]+ seen: set[int] = set()+ disconnected = False+ while pending:+ current = pending.pop()+ if id(current) in seen:+ continue+ seen.add(id(current))+ sqlstate = getattr(current, "sqlstate", None) or getattr(current, "pgcode", None)+ if sqlstate:+ if sqlstate not in _TRANSIENT_SQLSTATES:+ return False+ disconnected = True+ if isinstance(current, DisconnectionError) or (+ isinstance(current, DBAPIError) and current.connection_invalidated+ ):+ disconnected = True+ if isinstance(current, OSError) and (+ getattr(current, "winerror", None) in _NETWORK_WINERRORS+ or current.errno in _NETWORK_ERRNOS+ ):+ disconnected = True+ original = getattr(current, "orig", None)+ if isinstance(original, BaseException):+ pending.append(original)+ if current.__cause__ is not None:+ pending.append(current.__cause__)+ elif not current.__suppress_context__ and current.__context__ is not None:+ pending.append(current.__context__)+ return disconnected+++async def run_database_startup_steps(+ steps: Sequence[Callable[[], Awaitable[object]]],+ *,+ dispose: Callable[[], Awaitable[None]],+) -> None:+ """Retry the failed step at most three times; never replay successful steps.++ Callers must supply only idempotent DB initialization callbacks. Runtime and+ external service startup belong outside this function. Dispose after every+ disconnect, including the final failure, so no broken pool remains reusable.+ """+ for step in steps:+ for attempt in range(1, _MAX_ATTEMPTS + 1):+ try:+ await step()+ except Exception as error:+ if not is_transient_database_disconnect(error):+ raise+ await dispose()+ if attempt == _MAX_ATTEMPTS:+ raise+ delay = 0.25 * (2 ** (attempt - 1))+ logger.warning(+ "Database startup step %s disconnected (%s), retry %s/%s in %.2fs",+ getattr(step, "__name__", type(step).__name__),+ type(error).__name__,+ attempt + 1,+ _MAX_ATTEMPTS,+ delay,+ )+ await asyncio.sleep(delay)+ else:+ breakdiff --git a/backend/tests/test_admin_task_queue_stats.py b/backend/tests/test_admin_task_queue_stats.pynew file mode 100644index 0000000..470da31--- /dev/null+++ b/backend/tests/test_admin_task_queue_stats.py@@ -0,0 +1,73 @@+"""Queue monitoring aggregates use an isolated in-memory database."""++from datetime import UTC, datetime, timedelta+from types import SimpleNamespace+from unittest.mock import AsyncMock++import pytest+from sqlalchemy import Column, DateTime, Integer, MetaData, String, Table, create_engine++from app.services.tasks.service import get_task_stats_admin+++async def _queue_stats(rows):+ # Only the columns read by monitoring are needed; no application DB connection.+ engine = create_engine("sqlite:///:memory:")+ metadata = MetaData()+ task_runs = Table(+ "task_runs",+ metadata,+ Column("id", Integer, primary_key=True),+ Column("domain", String),+ Column("status", String),+ Column("next_action_at", DateTime),+ )+ try:+ with engine.begin() as connection:+ metadata.create_all(connection)+ if rows:+ connection.execute(task_runs.insert(), rows)+ db = SimpleNamespace(execute=AsyncMock(side_effect=connection.execute))+ return await get_task_stats_admin(db)+ finally:+ engine.dispose()+++async def test_pending_stats_distinguish_activation_from_due_and_delayed_tasks():+ now = datetime.now(UTC)+ rows = [+ {"domain": "drama", "status": "pending", "next_action_at": now - timedelta(seconds=120)},+ {"domain": "tools", "status": "pending", "next_action_at": now - timedelta(seconds=30)},+ {"domain": "drama", "status": "pending", "next_action_at": None},+ {"domain": "drama", "status": "pending", "next_action_at": now + timedelta(minutes=5)},+ {"domain": "drama", "status": "running", "next_action_at": now - timedelta(minutes=10)},+ {"domain": "drama", "status": "cancel_requested", "next_action_at": None},+ ]++ stats = await _queue_stats(rows)++ assert stats["pending_count"] == 4+ assert stats["pending_ready_count"] == 2+ assert stats["pending_deferred_count"] == 1+ assert stats["pending_delayed_count"] == 1+ assert 120 <= stats["oldest_ready_wait_sec"] <= 122+ assert stats["running_count"] == 1+ assert stats["cancel_requested_count"] == 1++[email protected]("include_deferred", [False, True])+async def test_no_due_tasks_reports_zero_wait_age(include_deferred):+ rows = []+ if include_deferred:+ rows = [+ {"domain": "drama", "status": "pending", "next_action_at": None},+ {"domain": "drama", "status": "pending", "next_action_at": datetime.now(UTC) + timedelta(hours=1)},+ ]++ stats = await _queue_stats(rows)++ assert stats["pending_ready_count"] == 0+ assert stats["oldest_ready_wait_sec"] == 0+ assert stats["pending_count"] == stats["pending_deferred_count"] + stats["pending_delayed_count"]diff --git a/backend/tests/test_database_bootstrap_mode.py b/backend/tests/test_database_bootstrap_mode.pynew file mode 100644index 0000000..408b3f0--- /dev/null+++ b/backend/tests/test_database_bootstrap_mode.py@@ -0,0 +1,73 @@+"""Existing shared DB mode: offline tests with isolated, fully mocked startup."""++import ast+from pathlib import Path+from types import ModuleType, SimpleNamespace+from unittest.mock import AsyncMock, Mock++import pytest++import app.services+from app.config import Settings+from app.startup_database_retry import run_database_startup_steps+++def test_bootstrap_is_enabled_by_default(monkeypatch):+ monkeypatch.delenv("DATABASE_BOOTSTRAP_ENABLED", raising=False)+ assert Settings(_env_file=None).database_bootstrap_enabled is True+++def test_bootstrap_can_be_disabled_explicitly(monkeypatch):+ monkeypatch.setenv("DATABASE_BOOTSTRAP_ENABLED", "false")+ assert Settings(_env_file=None).database_bootstrap_enabled is False+++def _isolated_startup(monkeypatch, bootstrap_enabled):+ # Compile only this function with mocked globals. Importing app.main would+ # construct the real app and engine, which this offline regression avoids.+ path = Path(__file__).resolve().parents[1] / "app" / "main.py"+ tree = ast.parse(path.read_text(encoding="utf-8"))+ startup = next(node for node in tree.body if isinstance(node, ast.AsyncFunctionDef) and node.name == "on_startup")+ startup.decorator_list = []+ callbacks = {+ name: AsyncMock(name=name)+ for name in (+ "init_db", "_apply_schema_patches", "_load_startup_model_settings",+ "seed_templates", "bootstrap_admins", "seed_agent_skills", "start_task_runtime",+ )+ }+ oss = ModuleType("app.services.oss")+ oss.ensure_browser_cors = Mock()+ monkeypatch.setattr(app.services, "oss", oss, raising=False)+ globals_ = {+ **callbacks,+ "settings": SimpleNamespace(database_bootstrap_enabled=bootstrap_enabled),+ "engine": SimpleNamespace(dispose=AsyncMock()),+ "logger": Mock(),+ "run_database_startup_steps": run_database_startup_steps,+ }+ exec(compile(ast.Module(body=[startup], type_ignores=[]), str(path), "exec"), globals_)+ return globals_["on_startup"], callbacks, oss++[email protected]("enabled", [True, False])+async def test_mode_controls_mutations_but_always_loads_cache_and_starts_runtime(monkeypatch, enabled):+ startup, callbacks, oss = _isolated_startup(monkeypatch, enabled)+ await startup()++ callbacks["_load_startup_model_settings"].assert_awaited_once()+ callbacks["start_task_runtime"].assert_awaited_once()+ oss.ensure_browser_cors.assert_called_once()+ for name in ("init_db", "_apply_schema_patches", "seed_templates", "bootstrap_admins", "seed_agent_skills"):+ assert callbacks[name].await_count == int(enabled), name+++async def test_existing_database_mode_still_propagates_model_cache_failures(monkeypatch):+ startup, callbacks, oss = _isolated_startup(monkeypatch, False)+ original = RuntimeError("missing model settings table")+ callbacks["_load_startup_model_settings"].side_effect = original+ with pytest.raises(RuntimeError) as caught:+ await startup()+ assert caught.value is original+ callbacks["start_task_runtime"].assert_not_awaited()+ oss.ensure_browser_cors.assert_not_called()diff --git a/backend/tests/test_sequential_fragment_wait.py b/backend/tests/test_sequential_fragment_wait.pyindex 7275459..24dd77a 100644--- a/backend/tests/test_sequential_fragment_wait.py+++ b/backend/tests/test_sequential_fragment_wait.py@@ -6,6 +6,7 @@ from unittest.mock import AsyncMock, patchimport pytestfrom app.services.tasks.service import (+ activate_next_sequential_task,_sequential_fragment_video_project_id,pick_sequential_episode_head,reconcile_sequential_batches,@@ -213,3 +214,42 @@ async def test_reconcile_still_activates_non_fragment_sequential_head():assert other.next_action_at is not Noneappend_event.assert_awaited()rebalance.assert_not_awaited()+++async def test_activate_next_is_idempotent_for_already_ready_task():+ """已激活的任务不能每秒更新时间并重复追加事件。"""+ from datetime import UTC, datetime++ ready_at = datetime.now(UTC)+ shot = _task(id=12, next_action_at=ready_at, payload={"batch_index": 1})+ db = SimpleNamespace(execute=AsyncMock(return_value=_rows([shot])), commit=AsyncMock())+ event = AsyncMock()+ with (+ patch("app.services.tasks.service.append_task_event", new=event),+ patch("app.services.drama.access.count_user_inflight_fragment_video_tasks", new=AsyncMock(return_value=0)),+ ):+ await activate_next_sequential_task(db, "batch", 0)+ assert shot.next_action_at == ready_at+ event.assert_not_awaited()+ db.commit.assert_not_awaited()+++async def test_video_batch_with_successful_predecessor_only_uses_episode_rebalance():+ """分镜按前置视频/尾帧就绪激活,不能再被 batch 逐秒反复激活。"""+ done = _task(id=10, status="succeeded", payload={"sequential": True, "batch_index": 0})+ waiting = _task(id=11, payload={"sequential": True, "batch_index": 1})+ db = SimpleNamespace(+ execute=AsyncMock(side_effect=[_rows(["batch"]), _rows([done, waiting])]),+ commit=AsyncMock(),+ )+ rebalance = AsyncMock(return_value={"pending": 1, "activated": 0, "deferred": 0})+ activate = AsyncMock()+ with (+ patch("app.services.tasks.service.rebalance_project_fragment_video_queue", new=rebalance),+ patch("app.services.tasks.service.activate_next_sequential_task", new=activate),+ ):+ await reconcile_sequential_batches(db)+ activate.assert_not_awaited()+ rebalance.assert_awaited_once()diff --git a/backend/tests/test_startup_database_retry.py b/backend/tests/test_startup_database_retry.pynew file mode 100644index 0000000..476b268--- /dev/null+++ b/backend/tests/test_startup_database_retry.py@@ -0,0 +1,193 @@+"""Startup connection recovery without databases, app startup or network calls."""++import asyncio+import errno+from unittest.mock import AsyncMock, call++import asyncpg+import pytest+from sqlalchemy.exc import DBAPIError, DisconnectionError, ProgrammingError++from app.startup_database_retry import (+ is_transient_database_disconnect,+ run_database_startup_steps,+)+++def _win121():+ error = OSError("semaphore timeout")+ error.winerror = 121+ return error+++ "error",+ [+ asyncpg.ConnectionDoesNotExistError("closed during operation"),+ asyncpg.ConnectionFailureError("connection failed"),+ asyncpg.AdminShutdownError("server restarting"),+ asyncpg.CannotConnectNowError("server starting"),+ DBAPIError("SELECT 1", {}, Exception("closed"), connection_invalidated=True),+ DisconnectionError("closed"),+ _win121(),+ ConnectionResetError(errno.ECONNRESET, "reset"),+ ConnectionAbortedError(errno.ECONNABORTED, "aborted"),+ ],+)+def test_only_clear_disconnects_are_transient(error):+ assert is_transient_database_disconnect(error)+++ "error",+ [+ asyncpg.InvalidPasswordError("bad password"),+ asyncpg.InvalidCatalogNameError("missing database"),+ asyncpg.UndefinedTableError("missing table"),+ asyncpg.InsufficientPrivilegeError("access denied"),+ ProgrammingError("bad SQL", {}, Exception("syntax")),+ DBAPIError("SELECT 1", {}, Exception("unknown driver failure")),+ TimeoutError("a slow query alone does not prove a disconnect"),+ RuntimeError("bad schema configuration"),+ FileNotFoundError("missing seed file"),+ ],+)+def test_authentication_schema_and_other_errors_are_not_retried(error):+ assert not is_transient_database_disconnect(error)+++def test_checks_wrapped_driver_and_os_error_without_message_matching():+ driver_error = DBAPIError("SELECT current_schema()", {}, Exception("driver wrapper"))+ driver_error.orig.__cause__ = _win121()+ assert is_transient_database_disconnect(driver_error)+++def test_driver_sqlstate_overrides_a_generic_disconnect_flag():+ error = DBAPIError("SELECT 1", {}, asyncpg.InvalidPasswordError("bad"), connection_invalidated=True)+ assert not is_transient_database_disconnect(error)+++def test_exception_cycles_do_not_loop():+ error = RuntimeError("unknown")+ error.__cause__ = error+ assert not is_transient_database_disconnect(error)+++def test_os_disconnect_in_implicit_exception_context_is_recognized():+ error = DBAPIError("SELECT 1", {}, Exception("driver wrapper"))+ error.__context__ = _win121()+ assert is_transient_database_disconnect(error)+++async def test_success_runs_steps_in_order_without_cleanup_or_delay(monkeypatch):+ events = []++ async def first():+ events.append("first")++ async def second():+ events.append("second")++ dispose = AsyncMock()+ sleep = AsyncMock()+ monkeypatch.setattr("app.startup_database_retry.asyncio.sleep", sleep)+ await run_database_startup_steps([first, second], dispose=dispose)+ assert events == ["first", "second"]+ dispose.assert_not_awaited()+ sleep.assert_not_awaited()+++async def test_recovers_only_failed_step_without_replaying_successful_steps(monkeypatch):+ first = AsyncMock()+ failed_step = AsyncMock(side_effect=[_win121(), asyncpg.ConnectionDoesNotExistError(), None])+ last = AsyncMock()+ dispose = AsyncMock()+ sleep = AsyncMock()+ monkeypatch.setattr("app.startup_database_retry.asyncio.sleep", sleep)++ await run_database_startup_steps([first, failed_step, last], dispose=dispose)++ first.assert_awaited_once()+ assert failed_step.await_count == 3+ last.assert_awaited_once()+ assert dispose.await_count == 2+ assert sleep.await_args_list == [call(0.25), call(0.5)]+++async def test_exhaustion_disposes_each_failed_pool_and_raises_original(monkeypatch):+ original = asyncpg.ConnectionDoesNotExistError("original error")+ step = AsyncMock(side_effect=original)+ next_step = AsyncMock()+ dispose = AsyncMock()+ sleep = AsyncMock()+ monkeypatch.setattr("app.startup_database_retry.asyncio.sleep", sleep)++ with pytest.raises(asyncpg.ConnectionDoesNotExistError) as caught:+ await run_database_startup_steps([step, next_step], dispose=dispose)++ assert caught.value is original+ assert step.await_count == 3+ assert dispose.await_count == 3+ assert sleep.await_args_list == [call(0.25), call(0.5)]+ next_step.assert_not_awaited()++[email protected]("original", [asyncpg.InvalidPasswordError(), ProgrammingError("bad SQL", {}, Exception()), RuntimeError()])+async def test_fatal_failure_propagates_immediately(original, monkeypatch):+ step = AsyncMock(side_effect=original)+ dispose = AsyncMock()+ sleep = AsyncMock()+ monkeypatch.setattr("app.startup_database_retry.asyncio.sleep", sleep)+ with pytest.raises(type(original)) as caught:+ await run_database_startup_steps([step], dispose=dispose)+ assert caught.value is original+ step.assert_awaited_once()+ dispose.assert_not_awaited()+ sleep.assert_not_awaited()+++async def test_cancellation_is_never_retried(monkeypatch):+ step = AsyncMock(side_effect=asyncio.CancelledError())+ dispose = AsyncMock()+ sleep = AsyncMock()+ monkeypatch.setattr("app.startup_database_retry.asyncio.sleep", sleep)+ with pytest.raises(asyncio.CancelledError):+ await run_database_startup_steps([step], dispose=dispose)+ step.assert_awaited_once()+ dispose.assert_not_awaited()+ sleep.assert_not_awaited()+++async def test_failed_pool_is_disposed_before_waiting_and_retrying(monkeypatch):+ events = []++ async def step():+ events.append("step")+ if events.count("step") == 1:+ raise _win121()++ async def dispose():+ events.append("dispose")++ async def sleep(_delay):+ events.append("sleep")++ monkeypatch.setattr("app.startup_database_retry.asyncio.sleep", sleep)+ await run_database_startup_steps([step], dispose=dispose)+ assert events == ["step", "dispose", "sleep", "step"]+++async def test_cleanup_failure_stops_instead_of_reusing_a_broken_pool(monkeypatch):+ original = _win121()+ cleanup_error = RuntimeError("pool cleanup failed")+ step = AsyncMock(side_effect=original)+ dispose = AsyncMock(side_effect=cleanup_error)+ sleep = AsyncMock()+ monkeypatch.setattr("app.startup_database_retry.asyncio.sleep", sleep)+ with pytest.raises(RuntimeError) as caught:+ await run_database_startup_steps([step], dispose=dispose)+ assert caught.value is cleanup_error+ assert cleanup_error.__context__ is original+ step.assert_awaited_once()+ dispose.assert_awaited_once()+ sleep.assert_not_awaited()diff --git a/backend/tests/test_task_runtime_lifecycle.py b/backend/tests/test_task_runtime_lifecycle.pyindex 976c9ff..39b1419 100644--- a/backend/tests/test_task_runtime_lifecycle.py+++ b/backend/tests/test_task_runtime_lifecycle.py@@ -1,6 +1,7 @@"""任务平台启动回滚、关闭清理与健康摘要的回归测试。"""import asyncio+from types import SimpleNamespacefrom unittest.mock import AsyncMockimport pytest@@ -12,6 +13,10 @@ from app.services.tasks import runtimedef components(monkeypatch):"""替换组件生命周期,避免测试连接数据库或启动后台任务。"""mocks = {}+ monkeypatch.setattr(runtime, "get_settings", lambda: SimpleNamespace(task_runtime_enabled=True))+ monkeypatch.setattr(runtime, "scheduler_diagnostics", lambda: {+ "scheduler_success_age_sec": 0.0, "scheduler_consecutive_failures": 0,+ })for name in ("scheduler", "poller", "watchdog"):for action in ("start", "stop"):key = f"{action}_{name}"@@ -20,6 +25,27 @@ def components(monkeypatch):return mocks+async def test_disabled_runtime_does_not_start_components(components, monkeypatch):+ """共享数据库的本地 API 可以关闭任务消费,同时继续提供健康检查。"""+ monkeypatch.setattr(runtime, "get_settings", lambda: SimpleNamespace(task_runtime_enabled=False))+ await runtime.start_task_runtime()+ for name in ("scheduler", "poller", "watchdog"):+ components[f"start_{name}"].assert_not_awaited()+ summary = runtime.runtime_summary()+ assert summary["enabled"] is False+ assert summary["healthy"] is True+ assert [summary[name] for name in ("scheduler", "poller", "watchdog")] == ["disabled"] * 3+++async def test_missing_enabled_setting_preserves_existing_startup(components, monkeypatch):+ """旧配置替身没有开关字段时,仍按启用处理。"""+ monkeypatch.setattr(runtime, "get_settings", lambda: SimpleNamespace())+ await runtime.start_task_runtime()+ components["start_scheduler"].assert_awaited_once()++@pytest.mark.asyncioasync def test_successful_start_keeps_components_running(components):"""启动成功后不应触发回滚。"""@@ -67,6 +93,10 @@ def test_health_requires_live_components_and_fresh_heartbeats(monkeypatch, scheduler_running, poller_running, watchdog_running, scheduler_stale, poller_stale,):"""运行状态与心跳都正常时,健康摘要才能报告 healthy。"""+ monkeypatch.setattr(runtime, "get_settings", lambda: SimpleNamespace(task_runtime_enabled=True))+ monkeypatch.setattr(runtime, "scheduler_diagnostics", lambda: {+ "scheduler_success_age_sec": 1.0, "scheduler_consecutive_failures": 0,+ })for name, running in (("scheduler", scheduler_running), ("poller", poller_running), ("watchdog", watchdog_running)):monkeypatch.setattr(runtime, f"{name}_status", lambda running=running: "running" if running else "stopped")monkeypatch.setattr(runtime, "scheduler_tick_stale", lambda: scheduler_stale)diff --git a/backend/tests/test_task_runtime_loading.py b/backend/tests/test_task_runtime_loading.pynew file mode 100644index 0000000..154ce29--- /dev/null+++ b/backend/tests/test_task_runtime_loading.py@@ -0,0 +1,31 @@+"""执行器读取任务时无需载入不断增长的审计历史。"""++from types import SimpleNamespace+from unittest.mock import AsyncMock++from sqlalchemy import create_engine, inspect+from sqlalchemy.orm import Session++from app.models_tasks import TaskEvent, TaskRun, TaskStep, TaskTarget+from app.services.tasks.service import get_task_for_runtime+++async def test_runtime_loads_steps_and_targets_without_loading_event_history():+ """历史激活事件再多,也不能让每次领取/轮询重新载入整段历史。"""+ engine = create_engine("sqlite:///:memory:")+ try:+ for model in (TaskRun, TaskStep, TaskTarget, TaskEvent):+ model.__table__.create(engine)+ with Session(engine) as db:+ db.add(TaskRun(id=1, requested_by=1, domain="drama", task_type="fragment_video"))+ db.add_all(TaskEvent(task_id=1, event_type="task.activated") for _ in range(1000))+ db.commit()+ with Session(engine) as db:+ async_db = SimpleNamespace(execute=AsyncMock(side_effect=db.execute))+ task = await get_task_for_runtime(async_db, 1)+ assert task is not None+ assert "events" in inspect(task).unloaded+ assert task.steps == []+ assert task.targets == []+ finally:+ engine.dispose()diff --git a/backend/tests/test_task_runtime_watchdog.py b/backend/tests/test_task_runtime_watchdog.pyindex 8d0e8fd..49d386d 100644--- a/backend/tests/test_task_runtime_watchdog.py+++ b/backend/tests/test_task_runtime_watchdog.py@@ -14,8 +14,12 @@ from app.services.tasks import scheduler as scheduler_mod@pytest.fixture(autouse=True)-async def _reset_runtime_state():+async def _reset_runtime_state(monkeypatch):"""每个用例前后停掉调度/轮询/看门狗,避免泄漏协程。"""+ monkeypatch.setattr(runtime_mod, "get_settings", lambda: SimpleNamespace(+ task_runtime_enabled=True, task_runtime_watchdog_interval_sec=2,+ ))+ monkeypatch.setattr(scheduler_mod, "_run_maintenance_operation", AsyncMock())await runtime_mod.stop_task_runtime()scheduler_mod._running_jobs.clear()poller_mod._poll_inflight.clear()diff --git a/backend/tests/test_task_scheduler_dispatch.py b/backend/tests/test_task_scheduler_dispatch.pynew file mode 100644index 0000000..42dde86--- /dev/null+++ b/backend/tests/test_task_scheduler_dispatch.py@@ -0,0 +1,252 @@+"""调度维护隔离、成功心跳、公平领取与取消路径;全部使用内存替身。"""++import asyncio+from datetime import UTC, datetime, timedelta+from types import SimpleNamespace+from unittest.mock import AsyncMock++import pytest+from sqlalchemy.dialects import postgresql+from sqlalchemy.sql.dml import Update++from app.services.tasks import scheduler++[email protected](autouse=True)+async def isolated_scheduler(monkeypatch):+ """隔离进程内调度状态,并在退出时清理所有后台协程。"""+ monkeypatch.setattr(scheduler, "_scheduler_task", None)+ monkeypatch.setattr(scheduler, "_maintenance_task", None)+ monkeypatch.setattr(scheduler, "_running_jobs", {})+ monkeypatch.setattr(scheduler, "_cancel_jobs", {})+ monkeypatch.setattr(scheduler, "_stop_event", asyncio.Event())+ monkeypatch.setattr(scheduler, "_intentionally_stopped", False)+ monkeypatch.setattr(scheduler, "_loop_started_mono", 0.0)+ monkeypatch.setattr(scheduler, "get_settings", lambda: SimpleNamespace(+ task_runtime_max_concurrency=4,+ task_user_max_concurrency=1,+ task_runtime_tick_stale_sec=60,+ task_runtime_orphan_check_sec=30,+ ))+ yield+ await scheduler.stop_scheduler()+++class _Rows:+ """模拟查询结果,避免触发真实数据库。"""++ def __init__(self, rows):+ self.rows = rows++ def scalars(self):+ """兼容单列查询。"""+ return self++ def all(self):+ """返回预设查询行。"""+ return self.rows+++class _QueueSession:+ """按页返回候选任务,记录领取 SQL 和成功领取的 ID。"""++ def __init__(self, pages, *, rowcount=1):+ self.pages = list(pages)+ self.rowcount = rowcount+ self.selects = []+ self.claimed = []++ async def __aenter__(self):+ """进入内存事务。"""+ return self++ async def __aexit__(self, *_args):+ """无需提交真实资源。"""+ return False++ async def execute(self, statement):+ """模拟领取 CAS 与有上限的候选查询。"""+ if isinstance(statement, Update):+ return SimpleNamespace(rowcount=self.rowcount)+ self.selects.append(statement)+ return _Rows(self.pages.pop(0) if self.pages else [])++ async def get(self, _model, task_id):+ """记录领取成功的任务。"""+ self.claimed.append(task_id)+ return SimpleNamespace(current_step_key="submit")++ async def commit(self):+ """模拟短事务提交。"""+ return None+++async def test_claim_pages_past_user_filled_by_this_tick(monkeypatch):+ """本轮第一名用户占满后,应继续领取后页其他用户,而非闲置槽位。"""+ first_page = [SimpleNamespace(id=i, status="pending", requested_by=1) for i in range(1, 17)]+ other_user = SimpleNamespace(id=17, status="pending", requested_by=2)+ db = _QueueSession([first_page, [other_user], []])+ monkeypatch.setattr(scheduler, "AsyncSessionLocal", lambda: db)+ monkeypatch.setattr(scheduler, "_claim_cancel_requests", AsyncMock())+ monkeypatch.setattr(scheduler, "count_user_active_runtime_tasks", AsyncMock(return_value=0))+ monkeypatch.setattr(scheduler, "append_task_event", AsyncMock())+ monkeypatch.setattr(scheduler, "_run_one", AsyncMock())+ await scheduler._tick()+ assert db.claimed == [1, 17]+ sql = str(db.selects[0].compile(dialect=postgresql.dialect(), compile_kwargs={"literal_binds": True}))+ assert "count(" in sql and "requested_by" in sql+ assert "FOR UPDATE OF task_runs SKIP LOCKED" in sql+ assert "task_runs.priority ASC, task_runs.created_at ASC, task_runs.id ASC" in sql+ next_sql = str(db.selects[1].compile(compile_kwargs={"literal_binds": True}))+ assert "requested_by NOT IN (1)" in next_sql+++async def test_failed_compare_and_swap_never_launches_executor(monkeypatch):+ """并发领取失手时不能重复执行;候选扫描有固定页数上限。"""+ pages = [[SimpleNamespace(id=i, status="pending", requested_by=i)] for i in range(1, 20)]+ db = _QueueSession(pages, rowcount=0)+ executor = AsyncMock()+ monkeypatch.setattr(scheduler, "AsyncSessionLocal", lambda: db)+ monkeypatch.setattr(scheduler, "_claim_cancel_requests", AsyncMock())+ monkeypatch.setattr(scheduler, "count_user_active_runtime_tasks", AsyncMock(return_value=0))+ monkeypatch.setattr(scheduler, "_run_one", executor)+ await scheduler._tick()+ assert len(db.selects) == scheduler._MAX_CLAIM_PAGES+ assert db.claimed == []+ executor.assert_not_awaited()+++async def test_cancellation_runs_when_normal_capacity_is_full(monkeypatch):+ """取消独立于普通容量,并且只执行取消收敛,不进入业务 handler。"""+ active = asyncio.create_task(asyncio.Event().wait())+ scheduler._running_jobs.update({i: active for i in range(1, 5)})+ db = _QueueSession([[9]])+ cancelled = AsyncMock()+ business = AsyncMock()+ monkeypatch.setattr(scheduler, "AsyncSessionLocal", lambda: db)+ monkeypatch.setattr(scheduler, "get_task_for_runtime", AsyncMock(return_value=SimpleNamespace(status="cancel_requested")))+ monkeypatch.setattr(scheduler, "_mark_cancelled", cancelled)+ monkeypatch.setattr(scheduler, "execute_task_run", business)+ await scheduler._tick()+ await asyncio.sleep(0)+ cancelled.assert_awaited_once()+ business.assert_not_awaited()+++async def test_finalizing_cancellation_waits_until_its_existing_deadline(monkeypatch):+ """收尾认领内的取消等待既有期限,不每秒重复领取或提前退款。"""+ until = datetime.now(UTC) + timedelta(minutes=5)+ task = SimpleNamespace(status="cancel_requested", payload={"finalizing_until": until.isoformat()})+ db = _QueueSession([])+ cancelled = AsyncMock()+ monkeypatch.setattr(scheduler, "AsyncSessionLocal", lambda: db)+ monkeypatch.setattr(scheduler, "get_task_for_runtime", AsyncMock(return_value=task))+ monkeypatch.setattr(scheduler, "_mark_cancelled", cancelled)+ await scheduler._run_cancel_request(9)+ assert task.next_action_at == until+ cancelled.assert_not_awaited()+++async def test_timed_out_tick_does_not_refresh_success_heartbeat(monkeypatch):+ """反复超时不能伪装成正常心跳,看门狗必须可识别老化。"""+ monkeypatch.setattr(scheduler.time, "monotonic", lambda: 100.0)+ monkeypatch.setattr(scheduler, "_last_tick_mono", 10.0)+ monkeypatch.setattr(scheduler, "_last_success_mono", 10.0)+ monkeypatch.setattr(scheduler, "_consecutive_failures", 0)+ monkeypatch.setattr(scheduler, "_tick", AsyncMock(side_effect=asyncio.TimeoutError()))++ async def stop_after_tick(_seconds):+ """一轮后退出,不等待真实定时器。"""+ scheduler._stop_event.set()++ monkeypatch.setattr(scheduler.asyncio, "sleep", stop_after_tick)+ await scheduler._scheduler_loop()+ assert scheduler.scheduler_tick_age_sec() == 90+ assert scheduler.scheduler_tick_stale()+ assert scheduler.scheduler_diagnostics() == {+ "scheduler_success_age_sec": 90.0, "scheduler_consecutive_failures": 1,+ }+++async def test_successful_tick_resets_failure_count(monkeypatch):+ """调度恢复后清除失败计数并记录真实成功时间。"""+ monkeypatch.setattr(scheduler.time, "monotonic", lambda: 100.0)+ monkeypatch.setattr(scheduler, "_consecutive_failures", 3)+ monkeypatch.setattr(scheduler, "_tick", AsyncMock())++ async def stop_after_tick(_seconds):+ """一轮后退出。"""+ scheduler._stop_event.set()++ monkeypatch.setattr(scheduler.asyncio, "sleep", stop_after_tick)+ await scheduler._scheduler_loop()+ assert scheduler.scheduler_diagnostics() == {+ "scheduler_success_age_sec": 0.0, "scheduler_consecutive_failures": 0,+ }+++async def test_one_blocked_maintenance_operation_does_not_skip_others(monkeypatch):+ """单项维护超时后继续其他维护,不永久卡在第一项。"""+ visited = []++ async def operation(name):+ """首项模拟锁等待,其余直接完成。"""+ visited.append(name)+ if name == "orphan_recovery":+ await asyncio.Event().wait()+ if name == "billing_reconcile":+ scheduler._stop_event.set()++ monkeypatch.setattr(scheduler, "_run_maintenance_operation", operation)+ monkeypatch.setattr(scheduler, "_MAINTENANCE_TIMEOUT_SEC", 0.001)+ monkeypatch.setattr(scheduler.asyncio, "sleep", AsyncMock())+ await scheduler._maintenance_loop()+ assert visited == ["orphan_recovery", "sequential_queue", "stale_fragments", "billing_reconcile"]+++async def test_restart_reuses_maintenance_and_stop_cleans_it_up(monkeypatch):+ """维护阻塞不挡住调度;watchdog 重启不复制维护,停机必须结束它。"""+ dispatched = asyncio.Event()+ maintenance_entered = asyncio.Event()++ async def blocked_maintenance(_name):+ """模拟维护持锁等待。"""+ maintenance_entered.set()+ await asyncio.Event().wait()++ async def dispatch():+ """模拟成功领取,证明维护没有挡在调度前面。"""+ dispatched.set()++ monkeypatch.setattr(scheduler, "_run_maintenance_operation", blocked_maintenance)+ monkeypatch.setattr(scheduler, "_tick", dispatch)+ await scheduler.start_scheduler()+ await asyncio.wait_for(maintenance_entered.wait(), timeout=1)+ await asyncio.wait_for(dispatched.wait(), timeout=1)+ maintenance = scheduler._maintenance_task+ await scheduler.restart_scheduler_loop(reason="test")+ assert scheduler._maintenance_task is maintenance+ assert not maintenance.done()+ await scheduler.stop_scheduler()+ assert maintenance.done()+++def test_watchdog_restart_grace_does_not_erase_failure_diagnostics(monkeypatch):+ """重启宽限只防止反复中断重试,不能把成功时间或失败计数清零。"""+ monkeypatch.setattr(scheduler.time, "monotonic", lambda: 100.0)+ monkeypatch.setattr(scheduler, "_last_tick_mono", 10.0)+ monkeypatch.setattr(scheduler, "_last_success_mono", 10.0)+ monkeypatch.setattr(scheduler, "_loop_started_mono", 99.0)+ monkeypatch.setattr(scheduler, "_consecutive_failures", 3)+ assert not scheduler.scheduler_tick_stale()+ assert scheduler.scheduler_diagnostics() == {+ "scheduler_success_age_sec": 90.0, "scheduler_consecutive_failures": 3,+ }diff --git a/backend/tests/test_upstream_observability.py b/backend/tests/test_upstream_observability.pynew file mode 100644index 0000000..376e1d8--- /dev/null+++ b/backend/tests/test_upstream_observability.py@@ -0,0 +1,338 @@+"""上游真实请求留痕:脱敏、单次提交、轮询限流与独立短事务,全部离线。"""++import asyncio+import json+from types import SimpleNamespace+from unittest.mock import AsyncMock, Mock++import httpx+import pytest++from app.models_tasks import TaskRun, TaskStep+from app.services.billing.context import billing_scope+from app.services.tasks import upstream+from app.services.upstream_sanitize import sanitize_upstream_value+++def test_sanitizer_redacts_credentials_and_signed_urls_without_mutation():+ """嵌套凭据、签名 URL、内嵌错误文本都不落密钥;计费 token 数保留。"""+ raw = {+ "headers": {"Authorization": "Bearer private-key", "X-Api-Key": "private-api", "Cookie": "sid=private-cookie"},+ "body": {"access_token": "private-token", "max_tokens": 8000, "nested": {"clientSecret": "private-secret"}},+ "image": "https://user:[email protected]/a.png?X-Tos-Signature=private-sign&width=100",+ "error": "request https://cdn.test/a?api_key=private-query failed; Authorization: Bearer private-error",+ "raw_error": '{"api_key":"private-json","password": "private-json-pass"}',+ }+ original = json.dumps(raw)+ safe = sanitize_upstream_value(raw)+ serialized = json.dumps(safe)+ for secret in ("private-key", "private-api", "private-cookie", "private-token", "private-secret", "private-password", "private-sign", "private-query", "private-error", "private-json", "private-json-pass"):+ assert secret not in serialized+ assert safe["body"]["max_tokens"] == 8000+ assert "width=100" in safe["image"]+ assert json.dumps(raw) == original+++def test_sanitizer_summarizes_base64_and_binary_instead_of_saving_content():+ """媒体内容只保留类型和长度,避免图像/音频正文进入任务事件。"""+ safe = sanitize_upstream_value({+ "image": "data:image/png;base64,cHJpdmF0ZS1pbWFnZQ==",+ "b64_json": "YWJj",+ "binary": b"private-bytes",+ })+ assert safe["image"]["media_type"] == "image/png"+ assert safe["image"]["length"] == 20+ assert safe["b64_json"] == {"type": "base64", "length": 4}+ assert safe["binary"] == {"type": "bytes", "length": 13}+ assert "cHJpdmF0ZS1pbWFnZQ" not in json.dumps(safe)++[email protected]("text,secret", [+ ('{"api_key": "abcdef-secret"}', "abcdef-secret"),+ ('password="foo"', "foo"),+ ("password='a secret with spaces'", "a secret with spaces"),+ ('{"client_secret":"unprefixed-credential"}', "unprefixed-credential"),+ ("API Key: arbitrary-credential", "arbitrary-credential"),+])+def test_free_text_json_and_quoted_credentials_are_redacted(text, secret):+ """上游错误回显中的引号/JSON凭据也必须脱敏,不能依赖 sk- 前缀。"""+ assert secret not in json.dumps(sanitize_upstream_value({"error": {"message": text}}))++[email protected](autouse=True)+def reset_poll_cache():+ """隔离轮询去重状态。"""+ upstream._poll_cache.clear()+ yield+ upstream._poll_cache.clear()+++async def test_multipart_request_records_attachment_metadata_without_media_bytes(monkeypatch):+ """实际 multipart 请求保留文件名/媒体类型,附件正文仅留长度。"""+ persist = AsyncMock()+ monkeypatch.setattr(upstream, "_persist_event", persist)+ response = httpx.Response(200, json={"data": []})+ client = SimpleNamespace(post=AsyncMock(return_value=response))+ files = {"image": ("reference.png", b"private-image-content", "image/png")}+ async with billing_scope(42):+ await upstream.observed_request(client, "POST", "https://gateway.test/v1/images/edits", data={"model": "gpt-image-2"}, files=files)+ client.post.assert_awaited_once_with("https://gateway.test/v1/images/edits", data={"model": "gpt-image-2"}, files=files)+ recorded = persist.await_args_list[0].args[2]["request"]+ assert recorded["files"]["image"] == ["reference.png", {"type": "bytes", "length": 21}, "image/png"]+ assert "private-image-content" not in json.dumps(recorded)+++async def test_submit_records_actual_body_and_response_and_preserves_network_call(monkeypatch):+ """日志来自实际 HTTP 参数;请求成功只执行一次且记录接收的上游 ID。"""+ persist = AsyncMock()+ monkeypatch.setattr(upstream, "_persist_event", persist)+ response = httpx.Response(200, json={"task_id": "provider-123", "status": "queued"}, headers={"x-request-id": "trace-1"})+ client = SimpleNamespace(post=AsyncMock(return_value=response))+ body = {"model": "MiniMax-H3", "prompt": "松鼠捧起松果", "seconds": "6"}+ headers = {"Authorization": "Bearer private-key", "Content-Type": "application/json"}+ async with billing_scope(42):+ actual = await upstream.observed_request(client, "POST", "https://gateway.test/v1/videos", headers=headers, json=body)+ assert actual is response+ client.post.assert_awaited_once_with("https://gateway.test/v1/videos", headers=headers, json=body)+ calls = persist.await_args_list+ assert [call.args[1] for call in calls] == ["upstream.request.started", "upstream.request.accepted"]+ started, accepted = [call.args[2] for call in calls]+ assert started["request"]["body"] == body+ assert started["request"]["headers"]["Authorization"] == "[REDACTED]"+ assert accepted["provider_task_id"] == "provider-123"+ assert accepted["response"]["status_code"] == 200+ assert accepted["status_code"] == 200+ assert accepted["elapsed_ms"] >= 0+ assert started["request_id"] == accepted["request_id"]+++async def test_logging_failure_cannot_repeat_successful_request(monkeypatch):+ """记录器故障不允许冒泡到业务重试路径。"""+ monkeypatch.setattr(upstream, "_persist_event", AsyncMock(side_effect=RuntimeError("log database offline")))+ response = httpx.Response(200, json={"id": "accepted-1"})+ client = SimpleNamespace(post=AsyncMock(return_value=response))+ async with billing_scope(42):+ assert await upstream.observed_request(client, "POST", "https://gateway.test/v1/videos", json={"model": "seedance-2.0"}) is response+ client.post.assert_awaited_once()+++async def test_logging_timeout_is_bounded_and_keeps_request_success(monkeypatch):+ """事件写入锁等待只消耗短预算,不阻塞真实请求完成。"""+ async def blocked_write(*_args, **_kwargs):+ """模拟事件事务等待锁。"""+ await asyncio.Event().wait()++ monkeypatch.setattr(upstream, "_persist_event", blocked_write)+ monkeypatch.setattr(upstream, "_EVENT_TIMEOUT_SEC", 0.001)+ response = httpx.Response(200, json={"id": "accepted-1"})+ client = SimpleNamespace(post=AsyncMock(return_value=response))+ async with billing_scope(42):+ assert await asyncio.wait_for(upstream.observed_request(client, "POST", "https://gateway.test/v1/videos", json={}), timeout=1) is response+ client.post.assert_awaited_once()+++async def test_network_error_records_failed_event_and_keeps_original_exception(monkeypatch):+ """网络异常仍由原业务处理,留痕中不得保留错误 URL 的签名。"""+ persist = AsyncMock()+ monkeypatch.setattr(upstream, "_persist_event", persist)+ error = httpx.ReadTimeout("read timeout https://gateway.test/v1/videos?token=private-token")+ client = SimpleNamespace(post=AsyncMock(side_effect=error))+ async with billing_scope(42):+ with pytest.raises(httpx.ReadTimeout) as caught:+ await upstream.observed_request(client, "POST", "https://gateway.test/v1/videos", json={"model": "seedance-2.0"})+ assert caught.value is error+ failed = persist.await_args_list[-1].args[2]+ assert persist.await_args_list[-1].args[1] == "upstream.request.failed"+ assert "private-token" not in json.dumps(failed)+++async def test_poll_records_status_changes_and_http_code_without_each_tick_events(monkeypatch):+ """持续 running 不刷屏,状态变为 succeeded 时保留新的响应。"""+ persist = AsyncMock()+ monkeypatch.setattr(upstream, "_persist_event", persist)+ responses = [httpx.Response(200, json={"id": "provider-1", "status": status}) for status in ["running"] * 5 + ["succeeded"]]+ client = SimpleNamespace(get=AsyncMock(side_effect=responses))+ async with billing_scope(42):+ for _ in responses:+ await upstream.observed_request(client, "GET", "https://gateway.test/v1/videos/provider-1")+ assert client.get.await_count == 6+ assert persist.await_count == 2+ assert {call.args[1] for call in persist.await_args_list} == {"upstream.request.poll"}+ assert [call.args[2]["response"]["status_code"] for call in persist.await_args_list] == [200, 200]+++async def test_without_task_context_does_not_open_logging_transaction(monkeypatch):+ """非任务请求不触发日志数据库 I/O。"""+ persist = AsyncMock()+ monkeypatch.setattr(upstream, "_persist_event", persist)+ response = httpx.Response(200, json={"id": "provider-1"})+ client = SimpleNamespace(post=AsyncMock(return_value=response))+ async with billing_scope(None):+ assert await upstream.observed_request(client, "POST", "https://gateway.test/v1/videos", json={}) is response+ persist.assert_not_awaited()+++async def test_uncommitted_inline_task_records_to_caller_without_query_flush_or_commit(monkeypatch):+ """未提交 TaskRun 的事件沿调用者事务保存,日志不能另开连接或提交。"""+ task = TaskRun(id=42, status="running", current_step_key="submit")+ step = TaskStep(id=7, task_id=42, step_key="submit", step_type="job")+ events = []+ db = SimpleNamespace(identity_map={}, new={task, step}, add=events.append,+ commit=AsyncMock(), flush=AsyncMock(), execute=AsyncMock(), get=AsyncMock())+ independent_session = Mock(side_effect=AssertionError("must not open another session"))+ monkeypatch.setattr(upstream, "AsyncSessionLocal", independent_session)+ response = httpx.Response(200, json={"task_id": "inline-provider"})+ client = SimpleNamespace(post=AsyncMock(return_value=response))+ async with billing_scope(42), upstream.upstream_event_session(db):+ assert await upstream.observed_request(client, "POST", "https://gateway.test/v1/videos", json={"model": "MiniMax-H3"}) is response+ assert [event.event_type for event in events] == ["upstream.request.started", "upstream.request.accepted"]+ assert task.provider_task_id == step.provider_task_id == "inline-provider"+ assert task.status == "running"+ for operation in (db.commit, db.flush, db.execute, db.get):+ operation.assert_not_awaited()+ independent_session.assert_not_called()+ assert upstream._event_session.get() is None+++async def test_caller_session_logging_error_does_not_repeat_network_request(monkeypatch):+ """调用者 session 的日志 add 异常不能让已成功请求重试。"""+ db = SimpleNamespace(identity_map={}, new=set(), add=Mock(side_effect=RuntimeError("event unavailable")),+ commit=AsyncMock(), flush=AsyncMock())+ response = httpx.Response(200, json={"task_id": "inline-provider"})+ client = SimpleNamespace(post=AsyncMock(return_value=response))+ async with billing_scope(42), upstream.upstream_event_session(db):+ assert await upstream.observed_request(client, "POST", "https://gateway.test/v1/videos", json={}) is response+ client.post.assert_awaited_once()+ db.commit.assert_not_awaited()+ db.flush.assert_not_awaited()++[email protected]("deferred", [False, True])+async def test_ephemeral_executor_installs_caller_event_session(monkeypatch, deferred):+ """同步和异步轻量任务都在未提交事务内记录,不由日志增加提交或 flush。"""+ from app.services.billing import ephemeral++ task = TaskRun(id=42, status="pending", current_step_key="submit")+ events = []+ db = SimpleNamespace(identity_map={42: task}, new=set(), add=events.append,+ flush=AsyncMock(), commit=AsyncMock(), refresh=AsyncMock())+ monkeypatch.setattr(ephemeral, "create_ephemeral_task_row", AsyncMock(return_value=task))+ monkeypatch.setattr(ephemeral, "freeze_for_task", AsyncMock())+ monkeypatch.setattr(ephemeral, "settle_task", AsyncMock())+ monkeypatch.setattr(ephemeral, "append_task_event", AsyncMock())+ response = httpx.Response(200, json={"task_id": "inline-provider"})+ client = SimpleNamespace(post=AsyncMock(return_value=response))++ async def executor():+ """发出唯一实际请求,检查事务上下文已正确传播。"""+ assert upstream._event_session.get() is db+ await upstream.observed_request(client, "POST", "https://gateway.test/v1/videos", json={"model": "MiniMax-H3"})+ return {"task_id": "inline-provider"}++ run = ephemeral.run_billed_ephemeral_deferred if deferred else ephemeral.run_billed_ephemeral+ await run(db, SimpleNamespace(id=9), domain="api", task_type="v1_video", executor=executor, commit=False)+ assert [event.event_type for event in events] == ["upstream.request.started", "upstream.request.accepted"]+ assert db.flush.await_count == 1 # 仅业务已有的 task.started flush。+ db.commit.assert_not_awaited()+ assert upstream._event_session.get() is None+++async def test_accepted_video_id_is_written_to_current_step_without_state_change(monkeypatch):+ """补齐任务与步骤上游 ID,但不能把同步资产视频任务改成 awaiting_poll。"""+ task = TaskRun(id=42, domain="drama", task_type="asset_video", status="running", current_step_key="asset_video")+ step = TaskStep(id=7, task_id=42, step_key="asset_video", step_type="job", status="submitting")+ events = []++ class Session:+ """模拟独立短事务。"""++ async def __aenter__(self):+ """进入内存 session。"""+ return self++ async def __aexit__(self, *_args):+ """释放内存 session。"""+ return False++ async def get(self, _model, _task_id):+ """返回任务替身。"""+ return task++ async def execute(self, _statement):+ """返回当前步骤。"""+ return SimpleNamespace(scalar_one_or_none=lambda: step)++ def add(self, event):+ """记录追加的事件。"""+ events.append(event)++ async def commit(self):+ """模拟独立提交。"""+ return None++ monkeypatch.setattr(upstream, "AsyncSessionLocal", Session)+ payload = {"provider_task_id": "provider-1", "provider": "tokenfree", "is_video_submit": True}+ await upstream._persist_event(42, "upstream.request.accepted", payload)+ assert task.provider_task_id == step.provider_task_id == "provider-1"+ assert step.provider_name == "tokenfree"+ assert task.status == "running"+ assert step.status == "submitting"+ assert len(events) == 1++[email protected]("model", ["MiniMax-H3", "seedance-2.0"])+async def test_actual_ark_video_submit_records_gateway_body_and_provider_id(monkeypatch, model):+ """覆盖真实 MiniMax/Seedance POST 入口,记录转换后的网关 body 而非任务参数。"""+ from app.services import ark as ark_module++ persist = AsyncMock()+ monkeypatch.setattr(upstream, "_persist_event", persist)+ response = httpx.Response(200, json={"task_id": f"provider-{model}", "status": "queued"})+ post = AsyncMock(return_value=response)++ class Client:+ """模拟 ArkGateway 使用的 HTTP 客户端。"""++ def __init__(self, **_kwargs):+ """接收原超时配置。"""+ self.post = post++ async def __aenter__(self):+ """进入 HTTP 上下文。"""+ return self++ async def __aexit__(self, *_args):+ """结束 HTTP 上下文。"""+ return False++ gateway = ark_module.ArkGateway(SimpleNamespace(ark_base_url="https://www.tokenfree.com/v1"))+ monkeypatch.setattr(ark_module.ArkGateway, "mock", property(lambda _self: False))+ monkeypatch.setattr(gateway, "_resolve_ark_route", lambda *_args: None)+ monkeypatch.setattr(gateway, "_route_headers", lambda *_args: {"Authorization": "Bearer private-key"})+ monkeypatch.setattr(gateway, "_seedance_duration", lambda value, **_kwargs: int(value))+ body = {"model": model, "duration": 6, "content": [{"type": "text", "text": "真实视频提示词"}]}+ monkeypatch.setattr(gateway, "_resolve_seedance_content_items", AsyncMock(return_value=body["content"]))+ monkeypatch.setattr("app.services.drama.voice_reference_audio.validate_seedance_body_reference_audios", AsyncMock())+ monkeypatch.setattr(ark_module.httpx, "AsyncClient", Client)+ async with billing_scope(42):+ provider_id = await gateway.gen_video_seedance_body(body)+ assert provider_id == f"provider-{model}"+ post.assert_awaited_once()+ actual_body = post.await_args.kwargs["json"]+ assert actual_body["prompt"] == "真实视频提示词"+ assert actual_body["seconds"] == "6"+ assert "content" not in actual_body+ events = persist.await_args_list+ assert events[0].args[2]["request"]["body"] == actual_body+ assert events[-1].args[2]["provider_task_id"] == provider_iddiff --git a/deploy/README.md b/deploy/README.mdindex a26718d..5ed1400 100644--- a/deploy/README.md+++ b/deploy/README.md@@ -89,6 +89,12 @@ docker compose -f deploy/docker-compose.yml --env-file deploy/.env.prod down -v任务并发:通过 `backend/.env` 中的 `TASK_RUNTIME_MAX_CONCURRENCY`、`TASK_USER_MAX_CONCURRENCY` 调整统一任务平台并发。+测试环境由 `dev` 分支 push 自动发布;日常测试发版提交并推送代码即可,不需要手动上传补丁或更新服务器容器。++本地 API 联调连接共享测试数据库时,设置 `TASK_RUNTIME_ENABLED=false`,只保留测试服务器执行调度、轮询和孤儿恢复。已由服务器初始化的共享数据库还可设 `DATABASE_BOOTSTRAP_ENABLED=false`,本机只读取模型缓存,不再重复建表、补列、seed 或提升管理员。本地仍能创建和查询任务,执行与产物存储由测试服务器负责;本地页面应能访问服务器返回的媒体地址。独立本地数据库或实际执行节点保持两个开关为 `true`(默认)。不要让多个调试实例同时恢复同一队列。++任务中心区分「待调度」(已到期)、「待激活」(尚无调度时间,可能等前置镜或额度)和「延时等待」。排查积压时一起查看调度最近成功时间、连续失败次数、数据库锁等待;增加并发无法解决调度停滞或锁等待。+## OSS(成片 / 分镜 / 前端)在 `backend/.env` 开启:diff --git a/docs/BILLING.md b/docs/BILLING.mdindex 4c4a29c..4982e57 100644--- a/docs/BILLING.md+++ b/docs/BILLING.md@@ -80,6 +80,12 @@ billing_expr USD sell = official_CNY / 7.3 * 1.5## TaskRun 计费流程+任务中心分别展示「预估」「冻结状态」「实扣」「退款」与用量计费依据;未结算时实扣应显示未结算,而不是已消费 0 元。冻结是任务的预留金额,不是额外收费;总费用不能把冻结和实扣相加。取消/失败后按既有结算逻辑释放冻结,并保留真实已发生的上游用量。++上游请求记录使用 `task_events` 的 `upstream.request.started/accepted/failed/poll` 事件,与 `billing_scope` 内的任务关联。记录真实 HTTP 方法、路径、模型、上游任务 ID、HTTP 响应码与耗时,以及脱敏后的请求/响应;内部任务参数不是实际 HTTP 请求体。轮询按状态变化采样,不按每轮重复刷事件。没有历史记录时显示「未记录」,不能事后伪造。请求日志不替代 `usage_events` 的真实计费依据,也不因日志写入失败重新提交上游。++运行时间分为排队等待(创建→开始)、执行时间(开始→结束或现在)、总耗时(创建→结束或现在)。HTTP 请求耗时与上游排队/生成时间分别展示,不将本地 Worker 运行时间等同于上游处理时间。+每个 `TaskRun` 独立走「预扣 → 记录用量 → 结算」:```mermaiddiff --git a/frontend/src/components/drama/DramaGenQueuePanel.tsx b/frontend/src/components/drama/DramaGenQueuePanel.tsxindex 40133ba..bd3ae73 100644--- a/frontend/src/components/drama/DramaGenQueuePanel.tsx+++ b/frontend/src/components/drama/DramaGenQueuePanel.tsx@@ -20,7 +20,7 @@ const OPEN_STORAGE_KEY = 'drama-gen-queue-fab-open'const POS_STORAGE_KEY = 'drama-gen-queue-fab-pos'const STATUS_LABEL: Record<string, string> = {- queued: '排队中',+ queued: '待处理',running: '生成中',done: '已完成',failed: '失败',@@ -75,19 +75,11 @@ export function DramaGenQueuePanel() {)const failed = useMemo(() => queue.filter((j) => j.status === 'failed'), [queue])- // 列表按入队时间倒序(最新在上);排队序号仍按先入先出+ // 列表按入队时间倒序;本地列表不代表服务端资源调度顺序。const sortedQueue = useMemo(() => [...queue].sort((a, b) => b.createdAt - a.createdAt),[queue],)- const queuedOnly = useMemo(- () =>- queue- .filter((j) => j.status === 'queued' || j.status === 'running')- .sort((a, b) => a.createdAt - b.createdAt),- [queue],- )-useEffect(() => {try {localStorage.setItem(OPEN_STORAGE_KEY, open ? '1' : '0')@@ -205,7 +197,6 @@ export function DramaGenQueuePanel() {<ul className="drama-gen-fab-list">{sortedQueue.map((job) => {- const queueIndex = queuedOnly.findIndex((j) => j.id === job.id)const errView = job.status === 'failed' ? formatDramaGenError(job.error) : nullreturn (<li key={job.id}>@@ -227,11 +218,7 @@ export function DramaGenQueuePanel() {) : null}</div><span className="drama-gen-fab-status">- {job.status === 'queued' && queueIndex >= 0- ? queuedOnly.length <= 1 || queueIndex === 0- ? '排队中'- : `排队 #${queueIndex + 1}`- : STATUS_LABEL[job.status]}+ {STATUS_LABEL[job.status]}</span></div>{errView ? (