Skip to content

PRINTFILM: AI short-video marketing and AI short-drama creation platform

feat(tasks): 任务平台调度重构——直接执行、队列与执行策略

yi1899babcecd2
diff --git a/admin/src/api/types/tasks.ts b/admin/src/api/types/tasks.ts
index 2569b3e..d03c719 100644
--- a/admin/src/api/types/tasks.ts
+++ b/admin/src/api/types/tasks.ts
@@ -6,6 +6,10 @@ export type AdminTaskRow = {
id: number;
domain: string;
task_type: string;
+ execution_mode?: "direct" | "queued";
+ queue_type?: "text" | "image" | "video";
+ provider_name?: string | null;
+ provider_status?: string | null;
status: string;
priority: number;
requested_by: number;
@@ -94,6 +98,7 @@ export type AdminTaskDetail = AdminTaskRow & {
events: AdminTaskEvent[];
targets: Array<{ id: number; target_type: string; target_id: number }>;
usage_lines?: AdminUsageEventBrief[];
+ billing_snapshot?: { mode: string; price_version: number | null; items: Array<{ model_id: string; capability: string; params: { resolution: string; duration?: number; count: number }; route: { channel_id: string; channel_name: string; upstream_model: string } }> } | null;
billing_estimate_fen?: number;
billing_charged_fen?: number;
billing_refunded_fen?: number;
@@ -101,6 +106,7 @@ export type AdminTaskDetail = AdminTaskRow & {
};
export type AdminTaskStats = {
+ queues?: Array<{ name: string; label: string; max_concurrency: number; pending: number; active: number; awaiting_poll: number }>;
pending_count: number;
pending_ready_count?: number;
pending_deferred_count?: number;
diff --git a/admin/src/components/tasks/TaskDetailDialog.tsx b/admin/src/components/tasks/TaskDetailDialog.tsx
index f40549e..4a9e692 100644
--- a/admin/src/components/tasks/TaskDetailDialog.tsx
+++ b/admin/src/components/tasks/TaskDetailDialog.tsx
@@ -415,6 +415,10 @@ export function TaskDetailDialog({ taskId, open, onOpenChange, onCancelled }: Ta
<section className="task-detail-section task-detail-section--full">
<h4>用量明细</h4>
+ {task.billing_snapshot && <div className="mb-3 text-xs text-[var(--admin-muted)]">
+ <p>受理时计费模式:{task.billing_snapshot.mode === 'fixed_media' ? `站内价格 #${task.billing_snapshot.price_version}` : '原计费规则'} · 路由固定,失败不自动切换</p>
+ {task.billing_snapshot.items.map((item, index) => <p key={index}>{item.model_id} · {item.params.resolution} · {item.params.duration ? `${item.params.duration} 秒` : `${item.params.count} 张`} · {item.route.channel_name || item.route.channel_id} → {item.route.upstream_model}</p>)}
+ </div>}
<p className="mb-3 text-xs text-[var(--admin-muted)]">用量记录表示调用计费依据;钱包实际扣款与退还以任务结算摘要为准。</p>
<div className="admin-table-wrap">
<table>
@@ -446,8 +450,11 @@ export function TaskDetailDialog({ taskId, open, onOpenChange, onCancelled }: Ta
<td className="max-w-[120px] truncate text-xs">{line.model || "—"}</td>
<td>{line.total_tokens ?? 0}</td>
<td>¥{fenToYuan(line.charge_fen ?? 0)}</td>
- <td>¥{fenToYuan(line.cost_fen ?? 0)}</td>
- <td>{line.billing_basis_label ?? (line.estimated ? "估算" : "实测")}</td>
+ <td>{line.cost_status === 'pending' ? '待核实' : `¥${fenToYuan(line.cost_fen ?? 0)}`}</td>
+ <td>{line.billing_detail?.mode === 'fixed_media' ? <>
+ <div>{line.billing_detail.resolution} · ¥{line.billing_detail.unit_price_yuan} × {line.billing_detail.duration ?? 1}{line.billing_detail.duration ? ' 秒' : ' 张'}</div>
+ <div className="text-xs text-[var(--admin-muted)]">价格 #{line.billing_detail.price_version} · {line.billing_detail.route.channel_name || line.billing_detail.route.channel_id} · {line.billing_detail.delivered ? '已交付' : '未交付'}</div>
+ </> : line.billing_basis_label ?? (line.estimated ? "估算" : "实测")}</td>
</tr>
))
)}
diff --git a/admin/src/components/tasks/TaskDetailSummary.tsx b/admin/src/components/tasks/TaskDetailSummary.tsx
index 50a1d95..2bf2fdf 100644
--- a/admin/src/components/tasks/TaskDetailSummary.tsx
+++ b/admin/src/components/tasks/TaskDetailSummary.tsx
@@ -55,10 +55,11 @@ export function TaskDetailSummary({ task, now, onJump }: TaskDetailSummaryProps)
</div>
<div className="task-progress"><span style={{ width: `${task.progress_percent}%` }} /></div>
<span className="task-summary-sub font-mono">{task.current_step_key || "步骤未记录"}{task.current_step_status ? ` · ${task.current_step_status}` : ""}</span>
+ {task.execution_mode === "direct" ? <span className="task-summary-sub">?? LLM ? ????</span> : task.queue_type ? <span className="task-summary-sub">{{ text: "文字", image: "图片", video: "视频" }[task.queue_type]}队列{task.provider_status ? ` · 上游 ${task.provider_status}` : ""}</span> : null}
</div>
<div className="task-summary-item">
- <span className="task-summary-label">{upstream.modelFromRequest ? "实际模型" : "任务选择模型"}</span>
+ <span className="task-summary-label">{upstream.latest?.phase === "simulated" ? "模拟模型" : upstream.modelFromRequest ? "实际模型" : "任务选择模型"}</span>
<span className="task-summary-value break-all">{upstream.model || "未记录"}</span>
<span className="task-summary-sub">Provider · {upstream.provider || "未记录"}</span>
</div>
diff --git a/admin/src/components/tasks/TaskListRow.tsx b/admin/src/components/tasks/TaskListRow.tsx
index 57a301a..c91bc99 100644
--- a/admin/src/components/tasks/TaskListRow.tsx
+++ b/admin/src/components/tasks/TaskListRow.tsx
@@ -94,6 +94,7 @@ export function TaskListRow({ task, upstream, billing, now, cancelling, onOpen,
<td className="min-w-[200px]">
<div className="flex items-baseline gap-2">
<span className="font-mono text-xs font-semibold">#{task.id}</span>
+ {task.execution_mode === "direct" ? <Badge variant="secondary">????</Badge> : task.queue_type ? <Badge variant="secondary">{{ text: "文字", image: "图片", video: "视频" }[task.queue_type]}队列</Badge> : null}
<span className="task-cell-main">{taskDomainLabel(task.domain)} · {taskTypeLabel(task.task_type)}</span>
</div>
<div
diff --git a/admin/src/components/tasks/TaskUpstreamPanel.tsx b/admin/src/components/tasks/TaskUpstreamPanel.tsx
index 3ddfdeb..1f6e056 100644
--- a/admin/src/components/tasks/TaskUpstreamPanel.tsx
+++ b/admin/src/components/tasks/TaskUpstreamPanel.tsx
@@ -22,7 +22,7 @@ function JsonRecord({ title, value, paginated = false }: { title: string; value:
);
}
-/** Only dedicated HTTP events are treated as evidence of actual upstream requests. */
+/** 展示真实 HTTP 留痕及明确标记的本地模拟参数,模拟事件不代表实际网络请求。 */
export function TaskUpstreamPanel({ task }: { task: AdminTaskDetail }) {
const summary = useMemo(() => taskUpstream(task), [task]);
const refreshToken = `${task.upstream_events_total}:${task.updated_at}:${task.status}`;
@@ -42,19 +42,20 @@ export function TaskUpstreamPanel({ task }: { task: AdminTaskDetail }) {
{history.error ? <div className="rounded-lg bg-red-50 p-3 text-sm text-red-700" role="alert">{history.error}<Button className="ml-3" variant="outline" size="sm" onClick={history.refresh}>重试</Button></div> : null}
{history.loading ? <p className="py-8 text-center text-sm text-[var(--admin-muted)]" role="status">正在加载本页上游事件…</p> : history.error ? null : 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>
+ <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) => {
const failed = request.latest.phase === "failed" || (request.httpStatus ?? 0) >= 400;
+ const simulated = request.latest.phase === "simulated";
return (
<section key={request.key} className={cn("task-upstream-card", failed && "is-fail")}>
<header className="task-upstream-head">
<Badge variant={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}
<code className="task-upstream-endpoint" title={request.endpoint}>
- <strong>{request.method || "METHOD?"}</strong> {request.endpoint ? shortEndpoint(request.endpoint) : "Endpoint未记录"}
+ <strong>{request.method || (simulated ? "本地模拟" : "METHOD?")}</strong> {request.endpoint ? shortEndpoint(request.endpoint) : simulated ? request.operation || "媒体生成" : "Endpoint未记录"}
</code>
<span className="ml-auto flex items-center gap-3 text-xs tabular-nums">
- <span className={cn("task-http-chip", failed && "is-fail")}>{request.httpStatus ?? "—"}</span>
+ <span className={cn("task-http-chip", failed && "is-fail")}>{simulated ? "未发送 HTTP" : request.httpStatus ?? "—"}</span>
<span>{request.elapsedMs == null ? "—" : `${Math.round(request.elapsedMs)} ms`}</span>
<span className="text-[var(--admin-muted)]">{time(request.latest.createdAt)}</span>
</span>
@@ -76,9 +77,10 @@ export function TaskUpstreamPanel({ task }: { task: AdminTaskDetail }) {
))}
</ol>
) : null}
- <div className="grid items-start gap-2 xl:grid-cols-2">
- <JsonRecord title="请求" value={request.request} paginated />
- <JsonRecord title="响应" value={request.response} paginated />
+ {simulated ? <p className="mb-3 text-sm text-[var(--admin-muted)]">{request.endpoint ? "以下为完成渠道路由、模型映射和协议转换后,准备发送的实际 URL、请求头和 JSON 请求体(凭据已脱敏)。在 HTTP 发送前拦截,使用默认媒体结果。" : "历史记录仅保存了业务输入参数,不是最终 HTTP 请求体;之后新建的模拟任务会记录最终请求参数。"}</p> : null}
+ <div className={cn("grid items-start gap-2", !simulated && "xl:grid-cols-2")}>
+ <JsonRecord title={simulated ? "模拟请求参数" : "请求"} value={request.request} paginated />
+ {!simulated ? <JsonRecord title="响应" value={request.response} paginated /> : null}
</div>
{request.error !== undefined ? <div className="mt-2"><JsonRecord title="错误" value={request.error} paginated /></div> : null}
</section>
diff --git a/admin/src/lib/taskObservability.ts b/admin/src/lib/taskObservability.ts
index 9cf6888..2145fb4 100644
--- a/admin/src/lib/taskObservability.ts
+++ b/admin/src/lib/taskObservability.ts
@@ -103,7 +103,7 @@ export function taskBilling(task: Pick<AdminTaskRow, "billing_status" | "billing
};
}
-export type UpstreamPhase = "started" | "accepted" | "failed" | "poll";
+export type UpstreamPhase = "started" | "accepted" | "failed" | "poll" | "simulated";
export type UpstreamRecord = {
id: number;
phase: UpstreamPhase;
@@ -111,6 +111,7 @@ export type UpstreamRecord = {
requestId?: string;
method?: string;
endpoint?: string;
+ operation?: string;
model?: string;
provider?: string;
providerTaskId?: string;
@@ -128,7 +129,7 @@ function textField(value: unknown): string | undefined {
export function upstreamRecords(events: AdminTaskEvent[] | undefined): UpstreamRecord[] {
return (events || []).flatMap((event) => {
- const match = event.event_type.match(/^upstream\.request\.(started|accepted|failed|poll)$/);
+ const match = event.event_type.match(/^upstream\.request\.(started|accepted|failed|poll|simulated)$/);
if (!match) return [];
const payload = event.payload || {};
const response = payload.response && typeof payload.response === "object" ? payload.response as Record<string, unknown> : {};
@@ -142,6 +143,7 @@ export function upstreamRecords(events: AdminTaskEvent[] | undefined): UpstreamR
requestId: textField(payload.request_id),
method: textField(payload.method),
endpoint: textField(payload.endpoint),
+ operation: textField(payload.operation),
model: textField(payload.model),
provider: textField(payload.provider),
providerTaskId: textField(payload.provider_task_id),
@@ -157,6 +159,7 @@ export function upstreamRecords(events: AdminTaskEvent[] | undefined): UpstreamR
export const UPSTREAM_PHASE_LABELS: Record<UpstreamPhase, string> = {
started: "开始请求", accepted: "上游响应", failed: "请求失败", poll: "查询结果",
+ simulated: "本地模拟 · 参数已记录",
};
export function upstreamStateLabel(status: string): string {
@@ -183,6 +186,7 @@ export function groupUpstreamRecords(records: UpstreamRecord[]) {
requestId: latest.requestId,
method: reverse.find((item) => item.method)?.method,
endpoint: reverse.find((item) => item.endpoint)?.endpoint,
+ operation: reverse.find((item) => item.operation)?.operation,
model: reverse.find((item) => item.model)?.model,
provider: reverse.find((item) => item.provider)?.provider,
providerTaskId: reverse.find((item) => item.providerTaskId)?.providerTaskId,
diff --git a/admin/src/pages/QueuesPage.tsx b/admin/src/pages/QueuesPage.tsx
index 01ec023..19d09a4 100644
--- a/admin/src/pages/QueuesPage.tsx
+++ b/admin/src/pages/QueuesPage.tsx
@@ -222,6 +222,13 @@ export function QueuesPage() {
<span>待激活表示前置条件或并发空位尚未满足;延时表示尚未到调度时间。</span>
</div>
+ {stats?.queues?.length ? <PageSection title="调度队列" bodyClassName="!pt-0">
+ <div className="grid gap-3 md:grid-cols-3">{stats.queues.map((queue) => <div key={queue.name} className="admin-panel px-4 py-3">
+ <div className="text-sm font-medium">{queue.label}队列 <span className="font-mono text-xs text-[var(--admin-muted)]">{queue.name}</span></div>
+ <div className="mt-2 text-xs text-[var(--admin-muted)]">排队 {queue.pending} · 在途 {queue.active} · 并发 {queue.max_concurrency}</div>
+ {queue.awaiting_poll ? <div className="mt-1 text-xs text-[var(--admin-muted)]">等待上游 {queue.awaiting_poll}</div> : null}
+ </div>)}</div>
+ </PageSection> : null}
{(stats?.domains.length ?? 0) > 0 ? (
<PageSection title="各领域任务" bodyClassName="!pt-0">
<div className="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
diff --git a/admin/tests/taskObservability.test.mjs b/admin/tests/taskObservability.test.mjs
index e7d16b5..33941ef 100644
--- a/admin/tests/taskObservability.test.mjs
+++ b/admin/tests/taskObservability.test.mjs
@@ -2,6 +2,26 @@ 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('existing local simulation events expose generation parameters without claiming a real HTTP request', () => {
+ const event = { id: 3717, event_type: 'upstream.request.simulated', payload: {
+ request_id: 'mock-request', operation: 'video.i2v', provider: 'local-mock', model: 'MiniMax-H3', simulated: true,
+ request: { body: { prompt: '镜头缓慢推进', image_url: 'https://example.test/ref.jpg?token=secret', duration: 15, ratio: '9:16', generate_audio: false } },
+ } };
+ const summary = taskUpstream({ upstream_events: [event], provider_task_id: 'local-media-id' });
+ assert.equal(summary.records.length, 1);
+ assert.equal(summary.phase, '本地模拟 · 参数已记录');
+ assert.equal(summary.provider, 'local-mock');
+ const record = groupUpstreamRecords(summary.records)[0];
+ assert.equal(record.operation, 'video.i2v');
+ assert.equal(record.request.body.prompt, '镜头缓慢推进');
+ assert.equal(record.request.body.duration, 15);
+ assert.equal(record.request.body.generate_audio, false);
+ assert.equal(record.httpStatus, undefined);
+ assert.equal(record.method, undefined);
+ assert.equal(record.response, undefined);
+ assert.ok(!JSON.stringify(record).includes('secret'));
+});
+
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' },
diff --git a/backend/app/api/admin/queues.py b/backend/app/api/admin/queues.py
index 2418400..4d42f79 100644
--- a/backend/app/api/admin/queues.py
+++ b/backend/app/api/admin/queues.py
@@ -3,14 +3,18 @@ from datetime import UTC, datetime
from fastapi import APIRouter, Depends, Query
from sqlalchemy.ext.asyncio import AsyncSession
+from sqlalchemy import func, select
from app.config import get_settings
from app.database import get_db
from app.deps import get_current_admin
from app.models import User
+from app.models_tasks import TaskRun
from app.schemas import AdminQueuesOut
from app.services.tasks.runtime import runtime_summary
from app.services.tasks.service import get_task_stats_admin
+from app.services.tasks.queues import QUEUE_LABELS, QUEUE_TYPES, queue_capacity
+from app.services.tasks.execution_policy import llm_task_condition
router = APIRouter()
@@ -27,7 +31,11 @@ async def admin_queues(
stats = await get_task_stats_admin(db)
runtime = runtime_summary()
running_jobs = int(runtime.get("scheduler_running_jobs") or 0)
- max_concurrency = int(settings.task_runtime_max_concurrency)
+ max_concurrency = sum(queue_capacity(settings, queue) for queue in QUEUE_TYPES)
+ queue_rows = (await db.execute(select(TaskRun.queue_type, TaskRun.status, func.count())
+ .where(~llm_task_condition(TaskRun))
+ .group_by(TaskRun.queue_type, TaskRun.status))).all()
+ counts = {(queue, status): count for queue, status, count in queue_rows}
pending = int(stats.get("pending_count") or 0)
active = int(stats.get("active_count") or 0)
return AdminQueuesOut.model_validate(
@@ -40,12 +48,14 @@ async def admin_queues(
"reserved_count": int(stats.get("leased_count") or 0),
"queues": [
{
- "name": item["domain"],
- "label": item["domain"],
- "pending": item["pending"],
+ "name": queue,
+ "label": QUEUE_LABELS[queue],
+ "pending": counts.get((queue, "pending"), 0),
+ "active": sum(counts.get((queue, state), 0) for state in ("leased", "running", "awaiting_poll")),
+ "max_concurrency": queue_capacity(settings, queue),
"sample": [],
}
- for item in stats.get("domains") or []
+ for queue in QUEUE_TYPES
],
"pending_tasks": [],
"active_tasks": [],
diff --git a/backend/app/api/admin/tasks.py b/backend/app/api/admin/tasks.py
index ce3c905..b385a4a 100644
--- a/backend/app/api/admin/tasks.py
+++ b/backend/app/api/admin/tasks.py
@@ -14,6 +14,7 @@ from app.schemas_tasks import AdminTaskEventListOut, AdminTaskListOut, AdminTask
from app.services.billing.display import billing_basis_label, resolve_billing_basis
from app.services.tasks.admin_events import AdminEventSummary, list_admin_task_events, load_admin_event_summaries
from app.services.tasks.runtime import runtime_summary
+from app.services.tasks.queues import QUEUE_TYPES, queue_capacity, queue_stats, task_queue
from app.services.tasks.service import cancel_task_admin, get_task_admin, get_task_stats_admin, list_tasks_admin
router = APIRouter()
@@ -29,10 +30,12 @@ def _task_to_admin_out(
"""组装有界响应,不读取或替换 ORM events,避免全历史加载与孤儿删除。"""
# 单独提取其余字段,Pydantic 不会访问被禁用的 events 懒加载关系。
fields = {name: getattr(task, name) for name in TaskRunOut.model_fields if name != "events"}
+ fields["queue_type"] = fields.get("queue_type") or task_queue(task.task_type, task.payload)
summary = event_summary or AdminEventSummary()
return AdminTaskRunOut(
**fields,
user_email=user_email,
+ billing_snapshot=getattr(task, "billing_snapshot", None),
usage_lines=usage_lines or [],
events=summary.events,
events_total=summary.events_total,
@@ -51,10 +54,12 @@ async def _load_usage_lines(db: AsyncSession, task_id: int) -> list[AdminUsageEv
).scalars().all()
items: list[AdminUsageEventBriefOut] = []
for row in rows:
- basis = resolve_billing_basis(estimated=bool(row.estimated), raw_usage_json=row.raw_usage_json)
+ basis = "fixed_media" if (row.billing_detail or {}).get("mode") == "fixed_media" else resolve_billing_basis(estimated=bool(row.estimated), raw_usage_json=row.raw_usage_json)
items.append(
AdminUsageEventBriefOut(
id=row.id,
+ billing_detail=row.billing_detail,
+ cost_status=row.cost_status,
billing_key=row.billing_key,
capability=row.capability,
model=row.model or "",
@@ -82,7 +87,8 @@ async def admin_task_stats(
return AdminTaskStatsOut(
**stats,
scheduler_running_jobs=int(runtime.get("scheduler_running_jobs") or 0),
- max_concurrency=int(settings.task_runtime_max_concurrency),
+ max_concurrency=sum(queue_capacity(settings, queue) for queue in QUEUE_TYPES),
+ queues=await queue_stats(db, settings),
scheduler=str(runtime.get("scheduler") or "stopped"),
poller=str(runtime.get("poller") or "stopped"),
watchdog=str(runtime.get("watchdog") or "stopped"),
diff --git a/backend/app/api/tasks.py b/backend/app/api/tasks.py
index 9bb98f6..e1149ee 100644
--- a/backend/app/api/tasks.py
+++ b/backend/app/api/tasks.py
@@ -2,9 +2,10 @@
from __future__ import annotations
import asyncio
+import re
from app.config import get_settings
-from fastapi import APIRouter, Depends, HTTPException, Query
+from fastapi import APIRouter, Depends, Header, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession
from app.database import get_db
@@ -13,6 +14,7 @@ from app.models import User
from app.schemas_tasks import MockDelayTaskRequest, TaskCreateRequest, TaskListOut, TaskRunOut
from app.services.billing.http import http_exception_for_value_error
from app.services.tasks.service import (
+ TaskAccessContext,
cancel_task_for_user,
count_active_tasks_for_user,
create_task,
@@ -24,6 +26,55 @@ router = APIRouter(prefix="/tasks", tags=["tasks"])
_mock_delay_create_lock = asyncio.Lock()
+_MONEY_KEYS = frozenset({"billing", "ledger", "money", "cost", "price", "charge", "charged", "refund", "refunded", "amount", "balance", "frozen", "spent", "reserved", "budget", "fee", "quota"})
+_MONEY_MESSAGE = re.compile(r"[¥¥]|\b(?:charge|charged|cost|refund|amount|billing|balance|quota)\b|余额|费用|金额|扣费|退款|额度", re.IGNORECASE)
+
+
+def _without_money(value):
+ """Remove nested monetary metadata without mutating persisted lifecycle events."""
+ if isinstance(value, dict):
+ return {
+ key: _without_money(item)
+ for key, item in value.items()
+ if not (
+ bool(set(re.sub(r"([a-z])([A-Z])", r"\1_\2", str(key)).lower().split("_")) & _MONEY_KEYS)
+ or str(key).lower().endswith(("_fen", "_yuan", "_cents"))
+ or str(key).lower().startswith("billing_")
+ )
+ }
+ if isinstance(value, list):
+ return [_without_money(item) for item in value]
+ return value
+
+
+def _owner_id(task, viewer: User, context: TaskAccessContext) -> int | None:
+ access = context.get((task.team_id, int(viewer.id))) if task.team_id is not None else None
+ return int(access[0].owner_user_id) if access is not None else None
+
+
+def public_task(task, *, viewer: User | None = None, owner_user_id: int | None = None) -> TaskRunOut:
+ """Team collaborators receive progress and results without internal upstream traces."""
+ output = TaskRunOut.model_validate(task)
+ if output.team_id is not None:
+ output.events = [event for event in output.events if not event.event_type.startswith("upstream.")]
+ output.lease_token = None
+ for step in output.steps:
+ step.input_payload = None
+ step.output_payload = None
+ can_view_money = viewer is not None and (
+ int(viewer.id) == output.requested_by or int(viewer.id) == owner_user_id
+ )
+ if not can_view_money:
+ output.billing_estimate_fen = None
+ output.billing_charged_fen = None
+ output.billing_refunded_fen = None
+ for event in output.events:
+ event.payload = _without_money(event.payload)
+ if event.message and _MONEY_MESSAGE.search(event.message):
+ event.message = "任务状态已更新"
+ return output
+
+
# 创建一个延时完成的模拟任务,便于联调任务平台。
@router.post("/mock-delay", response_model=TaskRunOut)
async def create_mock_delay_task(
@@ -61,7 +112,7 @@ async def create_mock_delay_task(
)
except ValueError as exc:
raise http_exception_for_value_error(exc) from exc
- return TaskRunOut.model_validate(task)
+ return public_task(task, viewer=user)
# 查询单个任务详情(含 steps/targets/events)
@@ -71,11 +122,12 @@ async def get_task_run(
db: AsyncSession = Depends(get_db),
user: User = Depends(get_current_user),
) -> TaskRunOut:
+ access: TaskAccessContext = {}
try:
- task = await get_task_for_user(db, user, task_id)
+ task = await get_task_for_user(db, user, task_id, access_context=access)
except LookupError as exc:
raise HTTPException(status_code=404, detail="任务不存在") from exc
- return TaskRunOut.model_validate(task)
+ return public_task(task, viewer=user, owner_user_id=_owner_id(task, user, access))
# 当前用户的统一任务列表,支持 domain/target/project 维度筛选
@@ -86,13 +138,20 @@ async def list_task_runs(
domain: str | None = Query(default=None),
status: str | None = Query(default=None),
task_type: str | None = Query(default=None),
+ queue_type: str | None = Query(default=None, pattern="^(text|image|video)$"),
target_type: str | None = Query(default=None),
target_id: int | None = Query(default=None, ge=1),
project_id: int | None = Query(default=None, ge=1),
drama_project_id: int | None = Query(default=None, ge=1),
+ team_id: int | None = Query(default=None, ge=1),
+ workspace_team_id: int | None = Header(default=None, alias="X-Team-Id", ge=1),
db: AsyncSession = Depends(get_db),
user: User = Depends(get_current_user),
) -> TaskListOut:
+ if team_id is not None and workspace_team_id is not None and team_id != workspace_team_id:
+ raise HTTPException(status_code=422, detail="团队空间参数不一致")
+ selected_team_id = team_id if team_id is not None else workspace_team_id
+ access: TaskAccessContext = {}
rows, total = await list_tasks_for_user(
db,
user,
@@ -101,13 +160,16 @@ async def list_task_runs(
domain=domain,
status=status,
task_type=task_type,
+ queue_type=queue_type,
target_type=target_type,
target_id=target_id,
project_id=project_id,
drama_project_id=drama_project_id,
+ team_id=selected_team_id,
+ access_context=access,
)
return TaskListOut(
- items=[TaskRunOut.model_validate(item) for item in rows],
+ items=[public_task(item, viewer=user, owner_user_id=_owner_id(item, user, access)) for item in rows],
total=total,
page=page,
page_size=page_size,
@@ -121,13 +183,14 @@ async def cancel_task_run(
db: AsyncSession = Depends(get_db),
user: User = Depends(get_current_user),
) -> TaskRunOut:
+ access: TaskAccessContext = {}
try:
- task = await cancel_task_for_user(db, user, task_id)
+ task = await cancel_task_for_user(db, user, task_id, access_context=access)
except LookupError as exc:
raise HTTPException(status_code=404, detail="任务不存在") from exc
except ValueError as exc:
raise http_exception_for_value_error(exc) from exc
- return TaskRunOut.model_validate(task)
+ return public_task(task, viewer=user, owner_user_id=_owner_id(task, user, access))
diff --git a/backend/app/models_tasks.py b/backend/app/models_tasks.py
index 0dfe8f6..80e0315 100644
--- a/backend/app/models_tasks.py
+++ b/backend/app/models_tasks.py
@@ -15,12 +15,25 @@ class TaskRun(Base):
__tablename__ = "task_runs"
+ @property
+ def execution_mode(self) -> str:
+ """文字任务保留记录,但不属于调度队列。"""
+ from app.services.tasks.execution_policy import execution_mode
+ return execution_mode(self.domain, self.task_type, self.payload)
+
id: Mapped[int] = mapped_column(Integer, primary_key=True)
domain: Mapped[str] = mapped_column(String(32), index=True, default="drama")
task_type: Mapped[str] = mapped_column(String(64), index=True)
+ queue_type: Mapped[str] = mapped_column(String(16), index=True, default="text")
+ provider_name: Mapped[str | None] = mapped_column(String(64), nullable=True)
+ provider_status: Mapped[str | None] = mapped_column(String(32), nullable=True)
status: Mapped[str] = mapped_column(String(32), index=True, default="pending")
priority: Mapped[int] = mapped_column(Integer, default=100)
requested_by: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
+ team_id: Mapped[int | None] = mapped_column(ForeignKey("teams.id"), nullable=True, index=True)
+ billing_enabled_snapshot: Mapped[bool | None] = mapped_column(Boolean, nullable=True)
+ billing_period: Mapped[str | None] = mapped_column(String(7), nullable=True)
+ billing_payer_user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"), nullable=True, index=True)
client_request_id: Mapped[str | None] = mapped_column(String(128), nullable=True, index=True)
dedupe_key: Mapped[str | None] = mapped_column(String(128), nullable=True, index=True)
batch_key: Mapped[str | None] = mapped_column(String(128), nullable=True, index=True)
@@ -63,6 +76,8 @@ class TaskRun(Base):
billing_charged_fen: Mapped[int] = mapped_column(Integer, default=0)
billing_refunded_fen: Mapped[int] = mapped_column(Integer, default=0)
billing_status: Mapped[str] = mapped_column(String(16), default="none", index=True)
+ billing_snapshot: Mapped[dict | None] = mapped_column(JSON, nullable=True)
+ media_provider_tasks: Mapped[dict | None] = mapped_column(JSON, nullable=True)
targets: Mapped[list["TaskTarget"]] = relationship(
back_populates="task", cascade="all, delete-orphan"
diff --git a/backend/app/schemas_tasks.py b/backend/app/schemas_tasks.py
index 3d7714c..d7c8c55 100644
--- a/backend/app/schemas_tasks.py
+++ b/backend/app/schemas_tasks.py
@@ -37,6 +37,7 @@ class TaskCreateRequest(BaseModel):
)
payload: dict[str, Any] | None = None
result_payload: dict[str, Any] | None = None
+ team_id: int | None = Field(default=None, ge=1)
project_id: int | None = Field(default=None, ge=1)
drama_project_id: int | None = Field(default=None, ge=1)
script_id: int | None = Field(default=None, ge=1)
@@ -139,7 +140,11 @@ class TaskRunBriefOut(BaseModel):
id: int
domain: str
+ team_id: int | None = None
task_type: str
+ queue_type: str = "text"
+ provider_name: str | None = None
+ provider_status: str | None = None
status: str
current_step_key: str | None = None
current_step_status: str | None = None
@@ -164,7 +169,12 @@ class TaskRunOut(BaseModel):
id: int
domain: str
+ team_id: int | None = None
task_type: str
+ queue_type: str = "text"
+ execution_mode: str = "queued"
+ provider_name: str | None = None
+ provider_status: str | None = None
status: str
priority: int
requested_by: int
@@ -196,9 +206,9 @@ class TaskRunOut(BaseModel):
updated_at: datetime | None = None
started_at: datetime | None = None
finished_at: datetime | None = None
- billing_estimate_fen: int = 0
- billing_charged_fen: int = 0
- billing_refunded_fen: int = 0
+ billing_estimate_fen: int | None = 0
+ billing_charged_fen: int | None = 0
+ billing_refunded_fen: int | None = 0
billing_status: str = "none"
steps: list[TaskStepOut] = Field(default_factory=list)
targets: list[TaskTargetOut] = Field(default_factory=list)
@@ -230,6 +240,7 @@ class AdminTaskRunOut(TaskRunOut):
"""管理员任务投影,事件数组有界,完整历史通过分页接口获取。"""
user_email: str | None = None
+ billing_snapshot: dict | None = None
usage_lines: list["AdminUsageEventBriefOut"] = Field(default_factory=list)
events_total: int = 0
upstream_events: list[TaskEventOut] = Field(default_factory=list)
@@ -246,6 +257,8 @@ class AdminTaskEventListOut(BaseModel):
class AdminUsageEventBriefOut(BaseModel):
+ billing_detail: dict | None = None
+ cost_status: str | None = None
"""Compact usage line for task billing tab."""
id: int
@@ -314,7 +327,17 @@ class AdminTaskDomainStatsOut(BaseModel):
cancelled: int = 0
+class TaskQueueStatsOut(BaseModel):
+ name: str
+ label: str
+ max_concurrency: int
+ pending: int = 0
+ active: int = 0
+ awaiting_poll: int = 0
+
+
class AdminTaskStatsOut(BaseModel):
+ queues: list[TaskQueueStatsOut] = Field(default_factory=list)
"""Task platform aggregate stats for admin monitoring."""
pending_count: int = 0
diff --git a/backend/app/services/tasks/direct.py b/backend/app/services/tasks/direct.py
new file mode 100644
index 0000000..83278ec
--- /dev/null
+++ b/backend/app/services/tasks/direct.py
@@ -0,0 +1,44 @@
+"""事务提交后立即启动文字任务,不提交的任务绝不调用上游。"""
+from sqlalchemy import event
+
+_PENDING = "direct_llm_after_commit"
+_REGISTERED = "direct_llm_hooks_registered"
+
+
+def launch_direct_task(task_id: int, lease_token: str) -> None:
+ """复用运行协程的租约、取消和停机处理,不经过调度器领取。"""
+ from app.services.tasks.scheduler import start_direct_task
+ start_direct_task(task_id, lease_token)
+
+
+def defer_until_commit(db, task_id: int, lease_token: str) -> None:
+ """支持调用方 commit=False 的业务原子提交,回滚清除待启动任务。"""
+ session = db.sync_session
+ transaction = session.get_nested_transaction() or session.get_transaction()
+ session.info.setdefault(_PENDING, {}).setdefault(transaction, []).append((task_id, lease_token))
+ if session.info.get(_REGISTERED):
+ return
+ session.info[_REGISTERED] = True
+
+ def after_commit(committed_session):
+ """仅在提交成功后启动,任务使用独立数据库会话。"""
+ current = committed_session.get_nested_transaction() or committed_session.get_transaction()
+ pending = committed_session.info.get(_PENDING, {})
+ entries = pending.pop(current, [])
+ if current is not None and current.nested:
+ pending.setdefault(current.parent, []).extend(entries)
+ return
+ committed_session.info.pop(_PENDING, None)
+ for ident, token in entries:
+ launch_direct_task(ident, token)
+
+ def after_rollback(rolled_back_session):
+ """业务或额度验证回滚时不产生后台模型调用。"""
+ current = rolled_back_session.get_nested_transaction() or rolled_back_session.get_transaction()
+ if current is not None and current.nested:
+ rolled_back_session.info.get(_PENDING, {}).pop(current, None)
+ else:
+ rolled_back_session.info.pop(_PENDING, None)
+
+ event.listen(session, "after_commit", after_commit)
+ event.listen(session, "after_rollback", after_rollback)
diff --git a/backend/app/services/tasks/execution_policy.py b/backend/app/services/tasks/execution_policy.py
new file mode 100644
index 0000000..a9daf5f
--- /dev/null
+++ b/backend/app/services/tasks/execution_policy.py
@@ -0,0 +1,30 @@
+"""文字 LLM 直接执行;媒体生成和混合流水线继续受队列限流。"""
+from sqlalchemy import and_, func, or_
+
+DIRECT_DRAMA_TYPES = ("script_summary", "episode_script", "fragment_plan", "seed_assets")
+INLINE_DRAMA_TYPES = ("agent_chat", "skill_optimize", "voice_prompt")
+
+
+def is_direct_llm_task(domain: str, task_type: str, payload: dict | None = None) -> bool:
+ """只包含有真实执行器的纯文字任务,不能按 text 队列笼统绕过配音限流。"""
+ return (domain == "drama" and task_type in DIRECT_DRAMA_TYPES) or (
+ domain == "kepu" and task_type == "project_pipeline" and (payload or {}).get("phase") == "script"
+ )
+
+
+def llm_task_condition(model, *, runnable_only: bool = False):
+ """SQL 口径与入口分类一致;内联聊天记录也不占队列容量。"""
+ types = DIRECT_DRAMA_TYPES if runnable_only else DIRECT_DRAMA_TYPES + INLINE_DRAMA_TYPES
+ terms = [
+ and_(model.domain == "drama", model.task_type.in_(types)),
+ and_(model.domain == "kepu", model.task_type == "project_pipeline", func.coalesce(model.payload["phase"].as_string(), "") == "script"),
+ ]
+ if not runnable_only:
+ terms.append(and_(model.domain == "kepu", model.task_type == "content_expand"))
+ return or_(*terms)
+
+
+def execution_mode(domain: str, task_type: str, payload: dict | None = None) -> str:
+ """对外区分即时文字执行与调度队列,仍保留原任务类型和历史记录。"""
+ inline = (domain == "drama" and task_type in INLINE_DRAMA_TYPES) or (domain == "kepu" and task_type == "content_expand")
+ return "direct" if inline or is_direct_llm_task(domain, task_type, payload) else "queued"
diff --git a/backend/app/services/tasks/executor.py b/backend/app/services/tasks/executor.py
index 2da108a..a6f4929 100644
--- a/backend/app/services/tasks/executor.py
+++ b/backend/app/services/tasks/executor.py
@@ -30,8 +30,9 @@ async def execute_task_run(task_id: int) -> None:
task.error_code = "handler_missing"
task.error_message = f"未注册任务处理器: {task.domain}/{task.task_type}"
task.finished_at = datetime.now(UTC)
- # 未进入预扣,保持 none
- task.billing_status = "none"
+ # Team queue reservations must be released even when a handler is unavailable.
+ if task.team_id is None:
+ task.billing_status = "none"
await append_task_event(
db,
task.id,
@@ -40,6 +41,8 @@ async def execute_task_run(task_id: int) -> None:
phase=task.current_step_key,
message=task.error_message,
)
+ if task.team_id is not None:
+ await settle_task(db, task.id)
await db.commit()
return
@@ -48,6 +51,11 @@ async def execute_task_run(task_id: int) -> None:
step = task.steps[0] if task.steps else None
try:
+ if task.team_id is not None and not task.provider_task_id:
+ from app.services.tasks.team_scope import ensure_task_may_submit
+ await ensure_task_may_submit(db, task)
+ from app.services.teams.edit_locks import validate_task_locks
+ await validate_task_locks(db, task)
await freeze_for_task(db, task)
except ValueError as exc:
# 余额不足:可预期失败,专用错误码便于前端引导充值
@@ -73,7 +81,7 @@ async def execute_task_run(task_id: int) -> None:
task.status = "running"
task.started_at = task.started_at or now
task.next_action_at = None
- task.lease_until = None
+ task.lease_until = now + timedelta(minutes=10)
set_task_step_state(task, step, status="submitting", now=now)
await append_task_event(
db,
@@ -86,7 +94,7 @@ async def execute_task_run(task_id: int) -> None:
await db.commit()
try:
- async with billing_scope(task_id):
+ async with billing_scope(task_id, team_id=task.team_id, snapshot=task.billing_snapshot):
async with AsyncSessionLocal() as db:
task = await get_task_for_runtime(db, task_id)
if not task:
@@ -168,7 +176,7 @@ async def _fail_task_before_start(db, task, step, *, error_code: str, message: s
task.error_message = message[:500]
task.finished_at = now
# frozen 之后的异常(如落流水失败)保留 frozen 交 settle_task 对账;未预扣成功保持 none
- if task.billing_status != "frozen":
+ if task.billing_status not in {"frozen", "reserved"}:
task.billing_status = "none"
await append_task_event(
db,
diff --git a/backend/app/services/tasks/handlers.py b/backend/app/services/tasks/handlers.py
index 25d77a1..aab80e3 100644
--- a/backend/app/services/tasks/handlers.py
+++ b/backend/app/services/tasks/handlers.py
@@ -271,6 +271,11 @@ async def _noop_ephemeral(task: TaskRun) -> dict[str, Any] | None:
return {"ok": True, "ephemeral": True}
+async def _run_studio_generation(task: TaskRun) -> dict[str, Any] | None:
+ from app.services.studio_generation import execute_generation
+ return await execute_generation(task)
+
+
# 确保关键主键字段存在。
def _require_int(value: int | None, field_name: str) -> int:
if isinstance(value, int) and value > 0:
@@ -290,12 +295,14 @@ TASK_HANDLERS: dict[tuple[str, str], TaskHandler] = {
("drama", "skill_optimize"): TaskHandler("drama", "skill_optimize", _noop_ephemeral),
("drama", "voice_prompt"): TaskHandler("drama", "voice_prompt", _noop_ephemeral),
("drama", "voice_synthesis"): TaskHandler("drama", "voice_synthesis", _noop_ephemeral),
+ ("drama", "episode_compose"): TaskHandler("drama", "episode_compose", _noop_ephemeral),
("kepu", "content_expand"): TaskHandler("kepu", "content_expand", _noop_ephemeral),
("api", "v1_image"): TaskHandler("api", "v1_image", _noop_ephemeral),
("api", "v1_video"): TaskHandler("api", "v1_video", _noop_ephemeral),
("api", "v1_seedance"): TaskHandler("api", "v1_seedance", _noop_ephemeral),
- ("studio", "tool_image"): TaskHandler("studio", "tool_image", _noop_ephemeral),
- ("studio", "tool_video"): TaskHandler("studio", "tool_video", _noop_ephemeral),
+ ("studio", "tool_image"): TaskHandler("studio", "tool_image", _run_studio_generation),
+ ("studio", "tool_video"): TaskHandler("studio", "tool_video", _run_studio_generation),
+ ("studio", "tool_audio"): TaskHandler("studio", "tool_audio", _run_studio_generation),
("kepu", "project_pipeline"): TaskHandler("kepu", "project_pipeline", _run_kepu_project_pipeline),
("kepu", "shot_regen_image"): TaskHandler("kepu", "shot_regen_image", _run_kepu_shot_image),
("kepu", "shot_regen_video"): TaskHandler("kepu", "shot_regen_video", _run_kepu_shot_video),
diff --git a/backend/app/services/tasks/poller.py b/backend/app/services/tasks/poller.py
index a216481..3613d59 100644
--- a/backend/app/services/tasks/poller.py
+++ b/backend/app/services/tasks/poller.py
@@ -134,7 +134,11 @@ async def _select_and_poll_due() -> None:
select(TaskRun.id)
.where(
TaskRun.status == "awaiting_poll",
- TaskRun.task_type == "fragment_video",
+ or_(
+ TaskRun.task_type == "fragment_video",
+ (TaskRun.domain == "studio") & (TaskRun.task_type == "tool_video") &
+ TaskRun.payload["run_id"].as_integer().is_not(None),
+ ),
TaskRun.next_action_at.is_not(None),
TaskRun.next_action_at <= now,
)
@@ -192,7 +196,11 @@ async def _poll_one_task(task_id: int) -> None:
return
try:
- await poll_fragment_video_task(task_id)
+ if task.domain == "studio" and (task.payload or {}).get("run_id"):
+ from app.services.studio_generation import poll_generation_video
+ await poll_generation_video(task_id)
+ else:
+ await poll_fragment_video_task(task_id)
except Exception: # noqa: BLE001
logger.exception("selector poll failed task_id=%s", task_id)
async with AsyncSessionLocal() as db:
@@ -221,6 +229,8 @@ async def _poll_ephemeral_deferred_tasks() -> None:
TaskRun.status == "awaiting_poll",
TaskRun.domain.in_(["api", "studio"]),
TaskRun.billing_status == "frozen",
+ or_(TaskRun.domain != "studio", TaskRun.task_type != "tool_video",
+ TaskRun.payload["run_id"].as_integer().is_(None)),
or_(TaskRun.next_action_at.is_(None), TaskRun.next_action_at <= now),
)
.order_by(TaskRun.next_action_at.asc().nullsfirst(), TaskRun.id.asc())
@@ -243,7 +253,7 @@ async def _poll_ephemeral_deferred_tasks() -> None:
async def _poll_one_ephemeral_task(task_id: int, *, now, timeout_sec: float) -> None:
from app.models import User
from app.services.billing.ephemeral import settle_deferred_video_poll
- from app.services.studio_tools import poll_video_task
+ from app.services.studio_tools import poll_video_task, update_tool_run_task
async with AsyncSessionLocal() as db:
task = await db.get(TaskRun, task_id)
@@ -258,6 +268,9 @@ async def _poll_one_ephemeral_task(task_id: int, *, now, timeout_sec: float) ->
task.error_code = "poll_timeout"
task.error_message = "视频轮询超时,预扣已退回"
task.finished_at = now
+ if task.domain == "studio" and task.provider_task_id:
+ await update_tool_run_task(db, task.requested_by, task.provider_task_id,
+ {"status": "failed", "error": task.error_message})
await append_task_event(
db,
task.id,
@@ -279,7 +292,7 @@ async def _poll_one_ephemeral_task(task_id: int, *, now, timeout_sec: float) ->
return
# 后台轮询与提交请求共用任务上下文,便于关联真实上游状态和计费。
- async with billing_scope(task_id):
+ async with billing_scope(task_id, team_id=task.team_id, snapshot=task.billing_snapshot):
data = await poll_video_task(user, provider_id)
status = str(data.get("status") or "").strip().lower()
if status in {"", "running", "queued"}:
@@ -300,4 +313,7 @@ async def _poll_one_ephemeral_task(task_id: int, *, now, timeout_sec: float) ->
completion_tokens=int((data.get("usage") or {}).get("completion_tokens") or 0),
raw_usage=data.get("raw_usage") if isinstance(data.get("raw_usage"), dict) else None,
)
+ task.result_payload = data
+ if task.domain == "studio":
+ await update_tool_run_task(db, user.id, provider_id, data)
await db.commit()
diff --git a/backend/app/services/tasks/queues.py b/backend/app/services/tasks/queues.py
new file mode 100644
index 0000000..2fd37af
--- /dev/null
+++ b/backend/app/services/tasks/queues.py
@@ -0,0 +1,40 @@
+"""The three durable scheduling lanes. Audio synthesis shares the text lane."""
+
+from typing import Literal
+
+QueueType = Literal["text", "image", "video"]
+QUEUE_TYPES: tuple[QueueType, ...] = ("text", "image", "video")
+QUEUE_LABELS = {"text": "音频与其他", "image": "图片", "video": "视频"}
+
+
+def task_queue(task_type: str, payload: dict | None = None) -> QueueType:
+ if task_type == "project_pipeline":
+ phase = (payload or {}).get("phase")
+ if phase == "assets":
+ return "image"
+ if phase in {"videos", "compose", "produce"}:
+ return "video"
+ if task_type in {"v1_seedance", "project_compose_only"} or "video" in task_type:
+ return "video"
+ if "image" in task_type:
+ return "image"
+ return "text"
+
+
+def queue_capacity(settings, queue: str) -> int:
+ value = getattr(settings, f"task_queue_{queue}_concurrency", None)
+ return max(1, int(value if value is not None else settings.task_runtime_max_concurrency))
+
+
+async def queue_stats(db, settings) -> list[dict]:
+ from sqlalchemy import func, select
+ from app.models_tasks import TaskRun
+ from app.services.tasks.execution_policy import llm_task_condition
+ rows = (await db.execute(select(TaskRun.queue_type, TaskRun.status, func.count())
+ .where(~llm_task_condition(TaskRun))
+ .group_by(TaskRun.queue_type, TaskRun.status))).all()
+ counts = {(queue, status): count for queue, status, count in rows}
+ return [{"name": queue, "label": QUEUE_LABELS[queue], "max_concurrency": queue_capacity(settings, queue),
+ "pending": counts.get((queue, "pending"), 0),
+ "active": sum(counts.get((queue, state), 0) for state in ("leased", "running", "awaiting_poll")),
+ "awaiting_poll": counts.get((queue, "awaiting_poll"), 0)} for queue in QUEUE_TYPES]
diff --git a/backend/app/services/tasks/scheduler.py b/backend/app/services/tasks/scheduler.py
index e4f6ba5..83be8b9 100644
--- a/backend/app/services/tasks/scheduler.py
+++ b/backend/app/services/tasks/scheduler.py
@@ -8,12 +8,14 @@ import time
import uuid
from datetime import UTC, datetime, timedelta
-from sqlalchemy import and_, func, or_, select, update
+from sqlalchemy import and_, func, or_, select, text, update
from sqlalchemy.orm import aliased
from app.config import get_settings
from app.database import AsyncSessionLocal
from app.models_tasks import TaskRun
+from app.services.tasks.queues import QUEUE_TYPES, queue_capacity
+from app.services.tasks.execution_policy import llm_task_condition
from app.services.billing.settlement import reconcile_terminal_frozen_tasks
from app.services.tasks.executor import _mark_cancelled, execute_task_run
from app.services.tasks.service import (
@@ -31,6 +33,7 @@ logger = logging.getLogger("app.tasks.scheduler")
# 调度循环句柄、进程内执行槽、停机信号、心跳与孤儿扫描时间戳
_scheduler_task: asyncio.Task | None = None
_running_jobs: dict[int, asyncio.Task] = {}
+_running_queues: dict[int, str] = {}
_cancel_jobs: dict[int, asyncio.Task] = {}
_maintenance_task: asyncio.Task | None = None
_stop_event = asyncio.Event()
@@ -83,6 +86,7 @@ async def stop_scheduler() -> None:
if running_jobs:
await asyncio.gather(*running_jobs, return_exceptions=True)
_running_jobs.clear()
+ _running_queues.clear()
_cancel_jobs.clear()
@@ -107,7 +111,7 @@ async def restart_scheduler_loop(*, reason: str = "watchdog") -> None:
# 返回当前运行中的平台任务数量。
def running_count() -> int:
- return sum(1 for task in _running_jobs.values() if not task.done())
+ return sum(1 for ident, task in _running_jobs.items() if not task.done() and _running_queues.get(ident) != "direct")
# 调度循环是否存活。
@@ -216,41 +220,75 @@ async def _tick() -> None:
for task_id, job in list(_running_jobs.items()):
if job.done():
_running_jobs.pop(task_id, None)
+ _running_queues.pop(task_id, None)
for task_id, job in list(_cancel_jobs.items()):
if job.done():
_cancel_jobs.pop(task_id, None)
await _claim_cancel_requests()
+ await _claim_direct_llm_tasks(now)
- capacity = max(1, int(get_settings().task_runtime_max_concurrency))
+ # Each lane owns its capacity; a blocked image/video lane never blocks text.
+ for queue in QUEUE_TYPES:
+ await _claim_queue(queue, now)
+
+
+async def _claim_queue(queue: str, now: datetime) -> None:
+ capacity = queue_capacity(get_settings(), queue)
user_limit = max(1, int(get_settings().task_user_max_concurrency))
- available_slots = max(0, capacity - running_count())
- if available_slots <= 0:
+ team_limit = max(1, int(getattr(get_settings(), "task_team_max_concurrency", 4)))
+ local_active = sum(
+ 1 for tid, job in _running_jobs.items()
+ if not job.done() and _running_queues.get(tid, "text") == queue
+ )
+ available_slots = max(0, capacity - local_active)
+ if not available_slots:
return
claimed_ids: list[int] = []
+ claimed_tokens: dict[int, str] = {}
async with AsyncSessionLocal() as db:
+ # Serialize claims per lane across API processes, without blocking other lanes.
+ bind = getattr(db, "bind", None)
+ if bind is not None and bind.dialect.name == "postgresql":
+ locked = await db.scalar(text("SELECT pg_try_advisory_xact_lock(:key)"), {"key": 842100 + QUEUE_TYPES.index(queue)})
+ if not locked:
+ return
+ active_states = ("leased", "running", "awaiting_poll") if queue == "video" else ("leased", "running")
+ occupied = int(await db.scalar(select(func.count()).select_from(TaskRun).where(
+ TaskRun.queue_type == queue, TaskRun.status.in_(active_states),
+ ~llm_task_condition(TaskRun),
+ )) or 0)
+ available_slots = min(available_slots, max(0, capacity - occupied))
+ if not available_slots:
+ return
user_active_cache: dict[int, int] = {}
+ team_active_cache: dict[int, int] = {}
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")))
+ .where(active.requested_by == TaskRun.requested_by, active.status.in_(active_states), active.queue_type == queue, ~llm_task_condition(active))
.correlate(TaskRun)
.scalar_subquery()
)
+ team_active = aliased(TaskRun)
+ team_active_count = (select(func.count(team_active.id)).where(team_active.team_id == TaskRun.team_id, team_active.status.in_(("leased", "running", "awaiting_poll")), ~llm_task_condition(team_active)).correlate(TaskRun).scalar_subquery())
for _ in range(_MAX_CLAIM_PAGES):
remaining = available_slots - len(claimed_ids)
if remaining <= 0:
break
stmt = (
- select(TaskRun.id, TaskRun.status, TaskRun.requested_by)
+ select(TaskRun.id, TaskRun.status, TaskRun.requested_by, TaskRun.team_id)
.where(
TaskRun.status == "pending",
+ TaskRun.queue_type == queue,
+ ~llm_task_condition(TaskRun),
TaskRun.cancel_requested.is_(False),
TaskRun.next_action_at.is_not(None),
TaskRun.next_action_at <= now,
active_count < user_limit,
+ or_(TaskRun.team_id.is_(None), team_active_count < team_limit),
)
.order_by(TaskRun.priority.asc(), TaskRun.created_at.asc(), TaskRun.id.asc())
.limit(min(_MAX_CANDIDATES_PER_PAGE, max(remaining * 4, remaining)))
@@ -272,14 +310,25 @@ async def _tick() -> None:
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)
+ user_active_cache[user_id] = await count_user_active_runtime_tasks(db, user_id, queue_type=queue)
if user_active_cache[user_id] >= user_limit:
full_users.add(user_id)
continue
+ team_id = getattr(row, "team_id", None)
+ if team_id is not None:
+ if bind is not None and bind.dialect.name == "postgresql":
+ team_claimed = await db.scalar(text("SELECT pg_try_advisory_xact_lock(:key)"), {"key": 942100000 + int(team_id)})
+ if not team_claimed:
+ continue
+ if team_id not in team_active_cache:
+ team_active_cache[team_id] = int((await db.execute(select(func.count()).select_from(TaskRun).where(TaskRun.team_id == team_id, TaskRun.status.in_(("leased", "running", "awaiting_poll")), ~llm_task_condition(TaskRun)))).scalar_one() or 0)
+ if team_active_cache[team_id] >= team_limit:
+ continue
+ lease_token = uuid.uuid4().hex
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))
+ .values(status="leased", lease_token=lease_token, lease_until=now + timedelta(minutes=10))
)
if int(result.rowcount or 0) != 1:
continue
@@ -289,7 +338,10 @@ async def _tick() -> None:
phase=getattr(task, "current_step_key", None), message="任务已被调度器领取",
)
claimed_ids.append(task_id)
+ claimed_tokens[task_id] = lease_token
user_active_cache[user_id] += 1
+ if team_id is not None:
+ team_active_cache[team_id] += 1
if user_active_cache[user_id] >= user_limit:
full_users.add(user_id)
if claimed_ids:
@@ -298,7 +350,8 @@ async def _tick() -> None:
for task_id in claimed_ids:
if task_id in _running_jobs and not _running_jobs[task_id].done():
continue
- _running_jobs[task_id] = asyncio.create_task(_run_one(task_id))
+ _running_queues[task_id] = queue
+ _running_jobs[task_id] = asyncio.create_task(_run_one(task_id, claimed_tokens[task_id]), name=f"task-{queue}-{task_id}")
# 取消使用独立且有上限的槽位,满额用户或普通队列积压不能阻挡取消。
@@ -340,6 +393,12 @@ async def _run_cancel_request(task_id: int) -> None:
task.next_action_at = until if until.tzinfo else until.replace(tzinfo=UTC)
await db.commit()
return
+ lease_until = getattr(task, "lease_until", None)
+ if lease_until is not None and lease_until.tzinfo is None:
+ lease_until = lease_until.replace(tzinfo=UTC)
+ if getattr(task, "execution_mode", "queued") == "direct" and lease_until and lease_until > datetime.now(UTC):
+ # 其他进程正在调用模型,由租约持有者取消并结算,不能先退冻结。
+ return
await _mark_cancelled(db, task)
except Exception: # noqa: BLE001
logger.exception("task cancellation failed task_id=%s", task_id)
@@ -347,12 +406,91 @@ async def _run_cancel_request(task_id: int) -> None:
_cancel_jobs.pop(task_id, None)
+def start_direct_task(task_id: int, lease_token: str) -> None:
+ """显式提交的文字任务立即启动,不占调度队列槽位;保留取消和租约。"""
+ if _job_alive(task_id):
+ return
+ _running_queues[task_id] = "direct"
+ job = asyncio.create_task(_run_one(task_id, lease_token), name=f"llm-direct-{task_id}")
+ _running_jobs[task_id] = job
+
+ def completed(result):
+ """取出异常,避免后台协程异常无人处理。"""
+ if not result.cancelled() and result.exception():
+ logger.error("direct LLM task failed task_id=%s", task_id, exc_info=result.exception())
+
+ job.add_done_callback(completed)
+
+
+async def _claim_direct_llm_tasks(now: datetime) -> None:
+ """旧版待执行任务、定时任务及中断恢复直接启动,不等待媒体容量。"""
+ claimed = []
+ async with AsyncSessionLocal() as db:
+ rows = list((await db.execute(select(TaskRun).where(
+ llm_task_condition(TaskRun, runnable_only=True), TaskRun.status == "pending",
+ TaskRun.cancel_requested.is_(False), TaskRun.next_action_at.is_not(None), TaskRun.next_action_at <= now,
+ ).order_by(TaskRun.id).limit(128).with_for_update(skip_locked=True))).scalars().all())
+ for task in rows:
+ if _job_alive(task.id):
+ continue
+ task.status = "running"
+ task.started_at = task.started_at or now
+ task.next_action_at = None
+ task.lease_token = uuid.uuid4().hex
+ task.lease_until = now + timedelta(minutes=10)
+ claimed.append((task.id, task.lease_token))
+ if claimed:
+ await db.commit()
+ for task_id, token in claimed:
+ start_direct_task(task_id, token)
+
+
# 包装执行器并在结束后释放运行槽位。
-async def _run_one(task_id: int) -> None:
+async def _run_one(task_id: int, lease_token: str | None = None) -> None:
+ heartbeat = asyncio.create_task(_renew_lease(task_id, lease_token)) if lease_token else None
try:
await execute_task_run(task_id)
+ except asyncio.CancelledError:
+ # 直接执行可能在预扣阶段被取消,此时执行器尚未进入 handler 的取消收尾。
+ if _running_queues.get(task_id) == "direct":
+ from app.services.tasks.executor import _requeue_interrupted_task
+ async with AsyncSessionLocal() as db:
+ task = await get_task_for_runtime(db, task_id)
+ if task and task.status not in {"succeeded", "failed", "cancelled"}:
+ if task.cancel_requested:
+ await _mark_cancelled(db, task)
+ else:
+ await _requeue_interrupted_task(db, task)
+ raise
finally:
+ if heartbeat:
+ heartbeat.cancel()
+ await asyncio.gather(heartbeat, return_exceptions=True)
_running_jobs.pop(task_id, None)
+ _running_queues.pop(task_id, None)
+
+
+async def _renew_lease(task_id: int, lease_token: str) -> None:
+ while True:
+ await asyncio.sleep(10)
+ try:
+ async with AsyncSessionLocal() as db:
+ result = await db.execute(update(TaskRun).where(
+ TaskRun.id == task_id, TaskRun.lease_token == lease_token,
+ TaskRun.status.in_(("leased", "running")),
+ ).values(lease_until=datetime.now(UTC) + timedelta(minutes=10)))
+ await db.commit()
+ if not result.rowcount:
+ cancelled = await db.scalar(select(TaskRun.cancel_requested).where(
+ TaskRun.id == task_id, TaskRun.lease_token == lease_token,
+ ))
+ if cancelled:
+ await cancel_running_task(task_id)
+ return
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ logger.exception("task lease heartbeat failed task_id=%s", task_id)
# 取消指定任务的本地执行协程。
@@ -375,7 +513,7 @@ async def recover_orphaned_tasks() -> int:
and_(
TaskRun.status == "leased",
or_(
- and_(TaskRun.updated_at.is_not(None), TaskRun.updated_at < stale_before),
+ and_(TaskRun.lease_until.is_(None), TaskRun.updated_at < stale_before),
and_(TaskRun.lease_until.is_not(None), TaskRun.lease_until < now),
),
),
@@ -383,10 +521,11 @@ async def recover_orphaned_tasks() -> int:
TaskRun.status == "running",
TaskRun.updated_at.is_not(None),
TaskRun.updated_at < stale_before,
+ or_(TaskRun.lease_until.is_(None), TaskRun.lease_until < now),
),
)
)
- rows = list((await db.execute(stmt)).scalars().all())
+ rows = list((await db.execute(stmt.with_for_update(skip_locked=True))).scalars().all())
changed = 0
for task in rows:
if _job_alive(int(task.id)):
diff --git a/backend/app/services/tasks/service.py b/backend/app/services/tasks/service.py
index 0bf2c27..3c3aebf 100644
--- a/backend/app/services/tasks/service.py
+++ b/backend/app/services/tasks/service.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import logging
+import uuid
from datetime import UTC, datetime, timedelta
from typing import Any
@@ -15,6 +16,8 @@ from app.models_drama import DramaAsset, DramaEpisode, DramaEpisodeFragment, Dra
from app.models_tasks import TaskEvent, TaskRun, TaskStep, TaskTarget
from app.schemas_tasks import TaskCreateRequest, TaskEventCreate, TaskStepCreate
from app.services.tasks.handlers import get_task_handler
+from app.services.tasks.queues import task_queue
+from app.services.tasks.execution_policy import is_direct_llm_task, llm_task_condition
logger = logging.getLogger("app.tasks.service")
@@ -28,6 +31,27 @@ ACTIVE_TASK_STATUSES = {
"cancel_requested",
}
+# Created by each HTTP handler and passed explicitly; never cached across requests.
+TaskAccessContext = dict[tuple[int, int], tuple[Any, Any]]
+
+
+async def _task_team_access(
+ db: AsyncSession, team_id: int, user_id: int, *,
+ context: TaskAccessContext | None = None, roles: set[str] | None = None,
+):
+ from fastapi import HTTPException
+ from app.services.teams.access import get_team, member_role
+
+ identity = (int(team_id), int(user_id))
+ access = context.get(identity) if context is not None else None
+ if access is None:
+ access = await get_team(db, team_id, user_id)
+ if context is not None:
+ context[identity] = access
+ if roles is not None and member_role(*access) not in roles:
+ raise HTTPException(status_code=403, detail="没有团队操作权限")
+ return access
+
def task_detail_options() -> tuple:
return (
@@ -99,7 +123,12 @@ async def create_task(
*,
commit: bool = True,
) -> TaskRun:
- """创建任务并预写步骤。commit=False 时仅 flush,由调用方与业务状态同事务提交。"""
+ """创建任务;文字 LLM 提交后立即执行,媒体任务留给调度器。"""
+ if body.payload is not None:
+ body.payload = {key: value for key, value in body.payload.items() if not key.startswith("_team_")}
+ if body.drama_project_id is not None:
+ from app.services.tasks.team_scope import prepare_background_task
+ user = await prepare_background_task(db, int(body.drama_project_id), user)
await _validate_task_scope(db, user, body)
handler = get_task_handler(body.domain, body.task_type)
if handler is None:
@@ -110,6 +139,7 @@ async def create_task(
domain=body.domain,
task_type=body.task_type,
requested_by=user.id,
+ team_id=body.team_id,
payload=body.payload,
project_id=body.project_id,
drama_project_id=body.drama_project_id,
@@ -118,6 +148,8 @@ async def create_task(
asset_id=body.asset_id,
shot_id=body.shot_id,
)
+ from app.services.media_models.planning import prepare_task_media
+ await prepare_task_media(db, balance_probe)
estimate_fen = await ensure_balance_for_task(db, user, balance_probe)
planned_steps = handler.plan_steps(body)
first_step = planned_steps[0] if planned_steps else None
@@ -126,6 +158,7 @@ async def create_task(
task = TaskRun(
domain=body.domain,
task_type=body.task_type,
+ queue_type=task_queue(body.task_type, body.payload),
status="pending",
priority=body.priority,
requested_by=user.id,
@@ -148,9 +181,28 @@ async def create_task(
asset_id=body.asset_id,
shot_id=body.shot_id,
billing_estimate_fen=int(estimate_fen or 0),
+ team_id=body.team_id,
+ billing_enabled_snapshot=balance_probe.billing_enabled_snapshot,
+ billing_period=balance_probe.billing_period,
+ billing_payer_user_id=balance_probe.billing_payer_user_id,
+ billing_status=balance_probe.billing_status or "none",
+ billing_snapshot=balance_probe.billing_snapshot,
)
db.add(task)
await db.flush()
+ schedule = body.scheduled_at
+ if schedule is not None and schedule.tzinfo is None:
+ schedule = schedule.replace(tzinfo=UTC)
+ direct = is_direct_llm_task(body.domain, body.task_type, body.payload)
+ if direct and not body.defer_activation and (schedule is None or schedule <= now):
+ task.status = "running"
+ task.started_at = now
+ task.next_action_at = None
+ task.lease_token = uuid.uuid4().hex
+ task.lease_until = now + timedelta(minutes=10)
+ if task.team_id is not None:
+ from app.services.teams.edit_locks import claim_task_locks
+ await claim_task_locks(db, task, user.id)
for step in planned_steps:
db.add(build_task_step(task.id, step))
for item in body.targets:
@@ -171,10 +223,13 @@ async def create_task(
status=task.status,
phase=task.current_step_key,
message=f"创建任务 {task.task_type}",
- payload={"domain": task.domain},
+ payload={"domain": task.domain, "execution_mode": "direct" if direct else "queued"},
),
)
)
+ if direct and task.status == "running":
+ from app.services.tasks.direct import defer_until_commit
+ defer_until_commit(db, task.id, task.lease_token)
if not commit:
return task
await db.commit()
@@ -269,7 +324,7 @@ async def fail_remaining_sequential_batch(
phase=task.current_step_key,
message=reason[:500],
)
- if str(task.billing_status or "") == "frozen":
+ if str(task.billing_status or "") in {"frozen", "reserved"}:
from app.services.billing.settlement import settle_task
try:
@@ -354,7 +409,7 @@ async def _mark_task_cancelled_stale(db: AsyncSession, task: TaskRun, reason: st
message=reason[:500],
)
# 作废终态必须结算预扣,否则 frozen 余额悬挂(如 #3328)
- if str(task.billing_status or "") == "frozen":
+ if str(task.billing_status or "") in {"frozen", "reserved"}:
from app.services.billing.settlement import settle_task
try:
@@ -850,82 +905,106 @@ async def rebalance_project_fragment_video_queue(
# 统计用户当前占用 Worker 槽位的任务数(NIO:awaiting_poll 注册项不占槽)。
-async def count_user_active_runtime_tasks(db: AsyncSession, user_id: int) -> int:
+async def count_user_active_runtime_tasks(db: AsyncSession, user_id: int, *, queue_type: str | None = None) -> int:
stmt = select(func.count()).select_from(TaskRun).where(
TaskRun.requested_by == int(user_id),
- TaskRun.status.in_(("leased", "running")),
+ ~llm_task_condition(TaskRun),
+ TaskRun.status.in_(("leased", "running", "awaiting_poll") if queue_type == "video" else ("leased", "running")),
)
+ if queue_type:
+ stmt = stmt.where(TaskRun.queue_type == queue_type)
return int((await db.execute(stmt)).scalar_one() or 0)
async def _validate_task_scope(db: AsyncSession, user: User, body: TaskCreateRequest) -> None:
+ """Resolve every reference to its persisted project; never trust client team IDs."""
if body.project_id is not None:
project = await db.get(Project, body.project_id)
if not project or int(project.user_id) != int(user.id):
raise ValueError("科普项目不存在或无权限")
if body.shot_id is not None:
shot = await db.get(Shot, body.shot_id)
- if not shot:
- raise ValueError("镜头不存在")
- project = await db.get(Project, int(shot.project_id))
+ project = await db.get(Project, int(shot.project_id)) if shot else None
if not project or int(project.user_id) != int(user.id):
raise ValueError("镜头不存在或无权限")
if body.project_id is not None and int(shot.project_id) != int(body.project_id):
raise ValueError("镜头与项目不匹配")
-
- drama_project_id: int | None = body.drama_project_id
- if drama_project_id is not None:
- drama_project = await db.get(DramaProject, drama_project_id)
- if not drama_project or int(drama_project.user_id) != int(user.id):
- raise ValueError("漫剧项目不存在或无权限")
- if body.script_id is not None:
- script = await db.get(DramaScript, body.script_id)
- if not script:
- raise ValueError("剧本不存在")
- drama_project = await db.get(DramaProject, int(script.project_id))
- if not drama_project or int(drama_project.user_id) != int(user.id):
- raise ValueError("剧本不存在或无权限")
- if drama_project_id is not None and int(script.project_id) != int(drama_project_id):
- raise ValueError("剧本与漫剧项目不匹配")
- if body.episode_id is not None:
- episode = await db.get(DramaEpisode, body.episode_id)
- if not episode:
- raise ValueError("分集不存在")
- drama_project = await db.get(DramaProject, int(episode.project_id))
- if not drama_project or int(drama_project.user_id) != int(user.id):
- raise ValueError("分集不存在或无权限")
- if drama_project_id is not None and int(episode.project_id) != int(drama_project_id):
- raise ValueError("分集与漫剧项目不匹配")
+ project_ids: set[int] = set()
+ if body.drama_project_id is not None:
+ project_ids.add(int(body.drama_project_id))
+ for model, ident, label in ((DramaScript, body.script_id, "剧本"), (DramaEpisode, body.episode_id, "分集"), (DramaAsset, body.asset_id, "资产")):
+ if ident is None:
+ continue
+ entity = await db.get(model, ident)
+ if entity is None:
+ raise ValueError(f"{label}不存在")
+ project_ids.add(int(entity.project_id))
if body.fragment_id is not None:
fragment = await db.get(DramaEpisodeFragment, body.fragment_id)
- if not fragment:
+ episode = await db.get(DramaEpisode, int(fragment.episode_id)) if fragment else None
+ if episode is None:
raise ValueError("分镜不存在")
- episode = await db.get(DramaEpisode, int(fragment.episode_id))
- drama_project = await db.get(DramaProject, int(episode.project_id)) if episode else None
- if not episode or not drama_project or int(drama_project.user_id) != int(user.id):
- raise ValueError("分镜不存在或无权限")
- if body.episode_id is not None and int(fragment.episode_id) != int(body.episode_id):
+ if body.episode_id is not None and int(episode.id) != int(body.episode_id):
raise ValueError("分镜与分集不匹配")
- if body.asset_id is not None:
- asset = await db.get(DramaAsset, body.asset_id)
- if not asset:
- raise ValueError("资产不存在")
- drama_project = await db.get(DramaProject, int(asset.project_id))
- if not drama_project or int(drama_project.user_id) != int(user.id):
- raise ValueError("资产不存在或无权限")
- if drama_project_id is not None and int(asset.project_id) != int(drama_project_id):
- raise ValueError("资产与漫剧项目不匹配")
-
-
-async def get_task_for_user(db: AsyncSession, user: User, task_id: int) -> TaskRun:
+ project_ids.add(int(episode.project_id))
+ body.episode_id = int(episode.id)
+ payload = body.payload if isinstance(body.payload, dict) else {}
+ for raw_id in payload.get("fragment_ids") or []:
+ fragment = await db.get(DramaEpisodeFragment, int(raw_id))
+ episode = await db.get(DramaEpisode, int(fragment.episode_id)) if fragment else None
+ if episode is None or (body.episode_id is not None and episode.id != body.episode_id):
+ raise ValueError("分镜与分集不匹配")
+ project_ids.add(int(episode.project_id))
+ for raw_id in payload.get("reference_asset_ids") or []:
+ asset = await db.get(DramaAsset, int(raw_id))
+ if asset is None:
+ raise ValueError("引用资产不存在")
+ project_ids.add(int(asset.project_id))
+ if len(project_ids) > 1:
+ raise ValueError("任务资源与漫剧项目不匹配")
+ actual_team_id = None
+ if project_ids:
+ pid = project_ids.pop()
+ project = await db.get(DramaProject, pid)
+ if project is None:
+ raise ValueError("漫剧项目不存在或无权限")
+ actual_team_id = project.team_id
+ if actual_team_id is not None:
+ from app.services.teams.access import get_team
+ await get_team(db, int(actual_team_id), int(user.id), lock=True)
+ elif int(project.user_id) != int(user.id):
+ raise ValueError("漫剧项目不存在或无权限")
+ # Hold project ownership through task insertion. A concurrent personal transfer
+ # must either observe this active task or finish before our scope is accepted.
+ project = (await db.execute(select(DramaProject).where(DramaProject.id == pid).with_for_update().execution_options(populate_existing=True))).scalar_one_or_none()
+ if project is None or project.team_id != actual_team_id:
+ raise ValueError("项目归属已变化,请刷新页面后重试")
+ if actual_team_id is None and int(project.user_id) != int(user.id):
+ raise ValueError("漫剧项目不存在或无权限")
+ body.drama_project_id = pid
+ if body.team_id is not None and body.team_id != actual_team_id:
+ raise ValueError("任务与团队不匹配")
+ if actual_team_id is not None and body.domain != "drama":
+ raise ValueError("当前功能不支持团队空间")
+ body.team_id = actual_team_id
+
+
+async def get_task_for_user(
+ db: AsyncSession, user: User, task_id: int, *,
+ access_context: TaskAccessContext | None = None,
+) -> TaskRun:
stmt = (
select(TaskRun)
.options(*task_detail_options())
- .where(TaskRun.id == task_id, TaskRun.requested_by == user.id)
+ .where(TaskRun.id == task_id)
)
task = (await db.execute(stmt)).scalar_one_or_none()
if not task:
raise LookupError("任务不存在")
+ if task.team_id is not None:
+ await _task_team_access(db, int(task.team_id), int(user.id), context=access_context)
+ elif int(task.requested_by) != int(user.id):
+ raise LookupError("任务不存在")
return task
@@ -938,18 +1017,27 @@ async def list_tasks_for_user(
domain: str | None = None,
status: str | None = None,
task_type: str | None = None,
+ queue_type: str | None = None,
target_type: str | None = None,
target_id: int | None = None,
project_id: int | None = None,
drama_project_id: int | None = None,
+ team_id: int | None = None,
+ access_context: TaskAccessContext | None = None,
) -> tuple[list[TaskRun], int]:
- filters = [TaskRun.requested_by == user.id]
+ if team_id is not None:
+ await _task_team_access(db, team_id, int(user.id), context=access_context)
+ filters = [TaskRun.team_id == team_id]
+ else:
+ filters = [TaskRun.requested_by == user.id, TaskRun.team_id.is_(None)]
if domain:
filters.append(TaskRun.domain == domain)
if status:
filters.append(TaskRun.status == status)
if task_type:
filters.append(TaskRun.task_type == task_type)
+ if queue_type:
+ filters.append(TaskRun.queue_type == queue_type)
if project_id:
filters.append(TaskRun.project_id == project_id)
if drama_project_id:
@@ -995,8 +1083,14 @@ async def count_active_tasks_for_user(
return int((await db.execute(stmt)).scalar_one() or 0)
-async def cancel_task_for_user(db: AsyncSession, user: User, task_id: int) -> TaskRun:
- task = await get_task_for_user(db, user, task_id)
+async def cancel_task_for_user(
+ db: AsyncSession, user: User, task_id: int, *,
+ access_context: TaskAccessContext | None = None,
+) -> TaskRun:
+ context = access_context if access_context is not None else {}
+ task = await get_task_for_user(db, user, task_id, access_context=context)
+ if task.team_id is not None and int(task.requested_by) != int(user.id):
+ await _task_team_access(db, int(task.team_id), int(user.id), context=context, roles={"owner", "admin"})
if not task.cancelable:
raise ValueError("任务不支持取消")
if task.status in TERMINAL_TASK_STATUSES:
@@ -1016,16 +1110,24 @@ async def cancel_task_for_user(db: AsyncSession, user: User, task_id: int) -> Ta
)
)
await db.commit()
- return await get_task_for_user(db, user, task.id)
+ if is_direct_llm_task(task.domain, task.task_type, task.payload):
+ from app.services.tasks.scheduler import cancel_running_task
+ await cancel_running_task(task.id)
+ return await get_task_for_user(db, user, task.id, access_context=context)
# 共用用户隔离、活动态筛选和详情加载,保证单项目与列表查询语义一致。
-def _active_owner_tasks_statement(user_id: int, *scope_filters) -> Select:
+def _active_owner_tasks_statement(user_id: int, *scope_filters, include_teams: bool = False) -> Select:
+ ownership = (TaskRun.requested_by == user_id) & TaskRun.team_id.is_(None)
+ if include_teams:
+ from app.models_teams import TeamMember
+ memberships = select(TeamMember.team_id).where(TeamMember.user_id == user_id, TeamMember.active.is_(True))
+ ownership = or_(ownership, TaskRun.team_id.in_(memberships))
return (
select(TaskRun)
.options(*task_detail_options())
.where(
- TaskRun.requested_by == user_id,
+ ownership,
TaskRun.status.in_(tuple(ACTIVE_TASK_STATUSES)),
or_(*scope_filters),
)
@@ -1048,7 +1150,7 @@ async def list_active_tasks_for_owner(
scope_filters.append(TaskRun.drama_project_id == drama_project_id)
if not scope_filters:
return []
- stmt = _active_owner_tasks_statement(user_id, *scope_filters)
+ stmt = _active_owner_tasks_statement(user_id, *scope_filters, include_teams=drama_project_id is not None)
return list((await db.execute(stmt)).scalars().unique().all())
@@ -1079,11 +1181,14 @@ async def cancel_tasks_for_scope(
drama_project_id: int | None = None,
episode_id: int | None = None,
) -> list[TaskRun]:
- filters = [
- TaskRun.requested_by == user_id,
- TaskRun.status.in_(tuple(ACTIVE_TASK_STATUSES)),
- TaskRun.cancel_requested.is_(False),
- ]
+ ownership_filter = (TaskRun.requested_by == user_id) & TaskRun.team_id.is_(None)
+ if drama_project_id is not None:
+ project = await db.get(DramaProject, drama_project_id)
+ if project is not None and project.team_id is not None:
+ from app.services.teams.access import get_team
+ await get_team(db, int(project.team_id), user_id, roles={"owner", "admin"})
+ ownership_filter = TaskRun.team_id == project.team_id
+ filters = [ownership_filter, TaskRun.status.in_(tuple(ACTIVE_TASK_STATUSES)), TaskRun.cancel_requested.is_(False)]
if project_id is not None:
filters.append(TaskRun.project_id == project_id)
if domain is not None:
@@ -1215,6 +1320,9 @@ async def cancel_task_admin(db: AsyncSession, task_id: int) -> TaskRun:
)
)
await db.commit()
+ if is_direct_llm_task(task.domain, task.task_type, task.payload):
+ from app.services.tasks.scheduler import cancel_running_task
+ await cancel_running_task(task.id)
return await get_task_admin(db, task.id)
diff --git a/backend/app/services/tasks/upstream.py b/backend/app/services/tasks/upstream.py
index e6b414a..304ec90 100644
--- a/backend/app/services/tasks/upstream.py
+++ b/backend/app/services/tasks/upstream.py
@@ -45,9 +45,21 @@ def _append_event(
) -> None:
"""仅修改内存对象并 add 事件,不查询、不 flush、不 commit。"""
provider_id = payload.get("provider_task_id")
+ if task is not None:
+ task.provider_name = str(payload.get("provider") or "tokenfree")
+ response = payload.get("response") or {}
+ body = response.get("body") if isinstance(response, dict) else None
+ state = body.get("status") if isinstance(body, dict) else None
+ task.provider_status = str(state or ("failed" if event_type.endswith("failed") else "accepted"))[:32]
+ if step is not None:
+ step.provider_name = str(payload.get("provider") or "tokenfree")
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)
+ from app.services.media_models.runtime import current_operation
+ operation = current_operation.get()
+ if operation and operation["capability"] == "video":
+ task.media_provider_tasks = {**(task.media_provider_tasks or {}), operation["operation_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")
@@ -148,7 +160,7 @@ async def observed_request(
) -> Any:
"""透明包装一次真实 HTTP 调用,保留参数、返回对象、异常和原重试策略。"""
# 延迟导入:billing 包 __init__ 会反向导入本模块,模块级导入会形成循环
- from app.services.billing.context import get_current_task_run_id
+ from app.services.billing.context import get_current_task_run_id, get_current_team_id
method = method.upper()
send = getattr(client, method.lower())
@@ -156,6 +168,14 @@ async def observed_request(
if task_id is None:
return await send(endpoint, **kwargs)
is_submit, is_poll, provider_id = _video_request(method, endpoint)
+ if get_current_team_id() is not None and method not in {"GET", "HEAD", "OPTIONS"}:
+ from app.services.tasks.team_scope import ensure_upstream_submission_allowed
+ caller_db = _event_session.get()
+ if caller_db is not None:
+ await ensure_upstream_submission_allowed(caller_db, task_id)
+ else:
+ async with AsyncSessionLocal() as authorization_db:
+ await ensure_upstream_submission_allowed(authorization_db, task_id)
body = kwargs.get("json", kwargs.get("data", kwargs.get("content")))
model = str(body.get("model") or "") if isinstance(body, dict) else None
payload = {
@@ -167,6 +187,10 @@ async def observed_request(
"params": kwargs.get("params"), "files": kwargs.get("files")},
"response": None, "error": None,
}
+ from app.services.media_models.runtime import current_operation
+ media_operation = current_operation.get()
+ if media_operation is not None:
+ payload["media_operation_id"] = media_operation["operation_id"]
if not is_poll:
await _safe_record(task_id, "upstream.request.started", payload)
started = time.perf_counter()
diff --git a/backend/tests/test_admin_task_events.py b/backend/tests/test_admin_task_events.py
index 0653860..15840fc 100644
--- a/backend/tests/test_admin_task_events.py
+++ b/backend/tests/test_admin_task_events.py
@@ -150,7 +150,7 @@ def test_admin_serializer_does_not_touch_or_replace_events_relationship():
@pytest.mark.asyncio
async def test_cancel_reads_no_history_and_writes_one_new_event(monkeypatch):
"""取消只读取任务和执行数据,不因历史膨胀阻塞取消。"""
- task = SimpleNamespace(id=6807, cancelable=True, status="running", current_step_key="submit")
+ task = SimpleNamespace(id=6807, domain="tools", task_type="mock_delay", payload={}, cancelable=True, status="running", current_step_key="submit")
db = SimpleNamespace(add=AsyncMock(), commit=AsyncMock())
db.add = lambda _event: None
load = AsyncMock(return_value=task)
diff --git a/backend/tests/test_direct_llm_execution.py b/backend/tests/test_direct_llm_execution.py
new file mode 100644
index 0000000..6c137a7
--- /dev/null
+++ b/backend/tests/test_direct_llm_execution.py
@@ -0,0 +1,265 @@
+"""文字任务不排队:事务边界、媒体隔离、计费与可取消的真实执行生命周期。"""
+import asyncio
+from datetime import UTC, datetime, timedelta
+from unittest.mock import AsyncMock, Mock
+
+import pytest
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
+
+from app.config import get_settings
+from app.database import Base
+from app.models import UsageEvent, User
+from app.models_drama import DramaProject
+from app.models_tasks import TaskRun
+from app.schemas_tasks import TaskCreateRequest
+from app.services.tasks import direct, executor, scheduler, service
+from app.services.tasks.execution_policy import is_direct_llm_task, llm_task_condition
+from app.services.tasks.handlers import TaskHandler
+from app.services.tasks.queues import queue_stats
+
+
+async def direct_db(tmp_path, monkeypatch):
+ """独立文件库让请求会话与真实后台会话共享已提交记录,不访问上游。"""
+ import app.main # noqa: F401
+ engine = create_async_engine("sqlite+aiosqlite:///" + (tmp_path / "direct.db").as_posix())
+ async with engine.begin() as conn:
+ await conn.run_sync(Base.metadata.create_all)
+ sessions = async_sessionmaker(engine, expire_on_commit=False)
+ monkeypatch.setattr(scheduler, "AsyncSessionLocal", sessions)
+ monkeypatch.setattr(executor, "AsyncSessionLocal", sessions)
+ monkeypatch.setattr(scheduler, "_running_jobs", {})
+ monkeypatch.setattr(scheduler, "_running_queues", {})
+ monkeypatch.setattr(get_settings(), "task_runtime_enabled", False)
+ monkeypatch.setattr(get_settings(), "billing_enabled", True)
+ monkeypatch.setattr("app.services.billing.settlement.estimate_task_fen", AsyncMock(return_value=300))
+ yield sessions
+ jobs = list(scheduler._running_jobs.values())
+ for job in jobs:
+ job.cancel()
+ await asyncio.gather(*jobs, return_exceptions=True)
+ await engine.dispose()
+
+
[email protected]("domain,kind,payload,expected", [
+ ("drama", "script_summary", {}, True), ("drama", "episode_script", {}, True),
+ ("drama", "fragment_plan", {}, True), ("drama", "seed_assets", {}, True),
+ ("kepu", "project_pipeline", {"phase": "script"}, True),
+ ("kepu", "project_pipeline", {}, False), ("kepu", "project_pipeline", {"phase": "assets"}, False),
+ ("drama", "voice_synthesis", {}, False), ("studio", "tool_audio", {}, False),
+ ("drama", "asset_image", {}, False), ("drama", "fragment_video", {}, False),
+])
+def test_only_pure_llm_jobs_bypass_queue(domain, kind, payload, expected):
+ assert is_direct_llm_task(domain, kind, payload) is expected
+
+
+async def test_commit_false_rollback_and_savepoints_never_launch_uncommitted_tasks(direct_db, monkeypatch):
+ """内层提交等外层提交,内层回滚只撤回自己的任务,根回滚不调用模型。"""
+ launch = Mock()
+ monkeypatch.setattr(direct, "launch_direct_task", launch)
+ async with direct_db() as db:
+ await db.execute(select(1))
+ direct.defer_until_commit(db, 1, "one")
+ async with db.begin_nested():
+ direct.defer_until_commit(db, 2, "two")
+ launch.assert_not_called()
+ savepoint = await db.begin_nested()
+ direct.defer_until_commit(db, 3, "rolled-back")
+ await savepoint.rollback()
+ await db.commit()
+ assert launch.call_args_list == [((1, "one"),), ((2, "two"),)]
+ launch.reset_mock()
+ await db.execute(select(1))
+ direct.defer_until_commit(db, 4, "four")
+ await db.rollback()
+ await db.commit()
+ launch.assert_not_called()
+
+
[email protected]("task_type", ["script_summary", "fragment_plan"])
+async def test_immediate_llm_runs_with_runtime_disabled_and_media_full_and_settles(direct_db, monkeypatch, task_type):
+ """无需调度器 tick;文字真正执行、扣费且不计入媒体队列占用。"""
+ monkeypatch.setattr(direct, "launch_direct_task", scheduler.start_direct_task)
+ started, finish = asyncio.Event(), asyncio.Event()
+
+ async def run(task):
+ """模拟模型返回并持久化用量,只在允许结束后返回。"""
+ started.set()
+ await finish.wait()
+ async with direct_db() as db:
+ db.add(UsageEvent(user_id=task.requested_by, task_run_id=task.id, billing_key="llm_chat", charge_fen=100, settled=False))
+ await db.commit()
+ return {"ok": True, "summary": "真实执行结果"}
+
+ handler = TaskHandler("drama", task_type, run)
+ monkeypatch.setattr(service, "get_task_handler", lambda *_: handler)
+ monkeypatch.setattr(executor, "get_task_handler", lambda *_: handler)
+ async with direct_db() as db:
+ user = User(email="[email protected]", hashed_password="test", balance_fen=5000)
+ db.add(user)
+ await db.flush()
+ project = DramaProject(user_id=user.id, title="直接执行")
+ db.add(project)
+ # 同用户的文字/音频槽及图片/视频全部被占用,也不能阻塞新文字任务。
+ for kind, queue in (("tool_audio", "text"), ("tool_image", "image"), ("tool_video", "video")):
+ db.add(TaskRun(requested_by=user.id, domain="studio", task_type=kind, queue_type=queue, status="running", billing_status="skipped", payload={}))
+ await db.commit()
+ task = await service.create_task(db, user, TaskCreateRequest(domain="drama", task_type=task_type, drama_project_id=project.id))
+ ident, user_id = task.id, user.id
+ await asyncio.wait_for(started.wait(), 3)
+ assert task.execution_mode == "direct"
+ assert scheduler.running_count() == 0
+ assert await service.count_user_active_runtime_tasks(db, user_id, queue_type="text") == 1
+ assert (await queue_stats(db, get_settings()))[0]["active"] == 1
+ job = scheduler._running_jobs[ident]
+ finish.set()
+ await asyncio.wait_for(job, 3)
+ async with direct_db() as db:
+ task = await db.get(TaskRun, ident)
+ user = await db.get(User, user_id)
+ assert (task.status, task.billing_status, task.billing_charged_fen) == ("succeeded", "settled", 100)
+ assert (user.balance_fen, user.frozen_fen) == (4900, 0)
+ assert task.result_payload["summary"] == "真实执行结果"
+
+
+async def test_sql_policy_retains_mixed_pipeline_and_excludes_inline_llm(direct_db):
+ """JSON 缺少 phase 时不能被 SQL NULL 错误排除;聊天不能占配音槽。"""
+ async with direct_db() as db:
+ user = User(email="[email protected]", hashed_password="test")
+ db.add(user)
+ await db.flush()
+ for domain, kind, payload in (("kepu", "project_pipeline", {}), ("drama", "agent_chat", {}), ("kepu", "project_pipeline", {"phase": "script"}), ("studio", "tool_audio", {})):
+ db.add(TaskRun(requested_by=user.id, domain=domain, task_type=kind, status="running", payload=payload))
+ await db.commit()
+ queued = list((await db.execute(select(TaskRun.task_type).where(~llm_task_condition(TaskRun)))).scalars())
+ assert queued == ["project_pipeline", "tool_audio"]
+
+
[email protected]("admin", [False, True])
+async def test_direct_task_can_cancel_without_scheduler_and_refunds(direct_db, monkeypatch, admin):
+ """运行时关闭时取消也立即生效,预扣退回,不遗留冻结。"""
+ monkeypatch.setattr(direct, "launch_direct_task", scheduler.start_direct_task)
+ entered = asyncio.Event()
+
+ async def wait_model(task):
+ """模拟尚无用量返回的长模型调用。"""
+ entered.set()
+ await asyncio.Event().wait()
+
+ handler = TaskHandler("drama", "script_summary", wait_model)
+ monkeypatch.setattr(service, "get_task_handler", lambda *_: handler)
+ monkeypatch.setattr(executor, "get_task_handler", lambda *_: handler)
+ async with direct_db() as db:
+ user = User(email="[email protected]", hashed_password="test", balance_fen=1000)
+ db.add(user)
+ await db.flush()
+ project = DramaProject(user_id=user.id, title="取消直接执行")
+ db.add(project)
+ await db.commit()
+ task = await service.create_task(db, user, TaskCreateRequest(domain="drama", task_type="script_summary", drama_project_id=project.id))
+ await asyncio.wait_for(entered.wait(), 3)
+ job = scheduler._running_jobs[task.id]
+ if admin:
+ await service.cancel_task_admin(db, task.id)
+ else:
+ await service.cancel_task_for_user(db, user, task.id)
+ await asyncio.gather(job, return_exceptions=True)
+ ident, user_id = task.id, user.id
+ async with direct_db() as db:
+ task, user = await db.get(TaskRun, ident), await db.get(User, user_id)
+ assert (task.status, task.billing_status, user.balance_fen, user.frozen_fen) == ("cancelled", "settled", 1000, 0)
+
+
+async def test_old_pending_text_starts_even_when_media_slots_full(direct_db, monkeypatch):
+ """升级前 pending 文字任务无需等待旧的文字队列名额。"""
+ async with direct_db() as db:
+ user = User(email="[email protected]", hashed_password="test")
+ db.add(user)
+ await db.flush()
+ task = TaskRun(domain="drama", task_type="seed_assets", requested_by=user.id, status="pending", next_action_at=datetime.now(UTC), payload={})
+ db.add(task)
+ await db.commit()
+ ident = task.id
+ launch = Mock()
+ monkeypatch.setattr(scheduler, "start_direct_task", launch)
+ await scheduler._claim_direct_llm_tasks(datetime.now(UTC))
+ launch.assert_called_once()
+ assert launch.call_args.args[0] == ident
+ await scheduler._claim_direct_llm_tasks(datetime.now(UTC))
+ assert launch.call_count == 1
+ async with direct_db() as db:
+ row = await db.get(TaskRun, ident)
+ assert row.status == "running" and row.lease_token
+
+
+async def test_explicit_kepu_script_phase_never_falls_through_to_media(monkeypatch):
+ """已有脚本时,重试文字阶段不能隐式生成图片、配音或视频。"""
+ from contextlib import asynccontextmanager
+ from types import SimpleNamespace
+ from app.services import pipeline
+
+ @asynccontextmanager
+ async def session():
+ """只提供 phase 规范化所需项目查询。"""
+ yield SimpleNamespace(execute=AsyncMock(return_value=SimpleNamespace(scalar_one_or_none=lambda: SimpleNamespace(pipeline_mode="full"))))
+
+ monkeypatch.setattr(pipeline, "AsyncSessionLocal", session)
+ monkeypatch.setattr(pipeline, "_ensure_not_cancelled", AsyncMock())
+ monkeypatch.setattr(pipeline, "_resume_plan", AsyncMock(return_value=(False, True, False, False)))
+ monkeypatch.setattr(pipeline, "publish_progress", AsyncMock())
+ media = AsyncMock()
+ monkeypatch.setattr(pipeline, "_parallel_image_and_audio", media)
+ monkeypatch.setattr(pipeline, "_parallel_videos", media)
+ monkeypatch.setattr(pipeline, "_compose_stage", media)
+ await pipeline.run_pipeline(123, phase="script")
+ media.assert_not_awaited()
+ assert pipeline.publish_progress.call_args.args[1]["stage"] == "SCRIPT_READY"
+
+
+async def test_remote_cancel_waits_for_direct_lease_owner_before_refund(direct_db, monkeypatch):
+ """非执行节点不能提前退款;租约失效后才由恢复逻辑收尾。"""
+ async with direct_db() as db:
+ user = User(email="[email protected]", hashed_password="test")
+ db.add(user)
+ await db.flush()
+ task = TaskRun(domain="drama", task_type="script_summary", requested_by=user.id, status="cancel_requested", cancel_requested=True, payload={}, lease_until=datetime.now(UTC) + timedelta(minutes=10), lease_token="remote")
+ db.add(task)
+ await db.commit()
+ ident = task.id
+ cancel = AsyncMock()
+ monkeypatch.setattr(scheduler, "_mark_cancelled", cancel)
+ await scheduler._run_cancel_request(ident)
+ cancel.assert_not_awaited()
+ async with direct_db() as db:
+ task = await db.get(TaskRun, ident)
+ task.lease_until = datetime.now(UTC) - timedelta(seconds=1)
+ await db.commit()
+ await scheduler._run_cancel_request(ident)
+ cancel.assert_awaited_once()
+
+
+async def test_lease_heartbeat_notices_cancel_requested_by_another_node(monkeypatch):
+ """执行节点通过租约心跳接收远端取消,而非把状态变更误认为任务完成。"""
+ from contextlib import asynccontextmanager
+ from types import SimpleNamespace
+ db = SimpleNamespace(execute=AsyncMock(return_value=SimpleNamespace(rowcount=0)), scalar=AsyncMock(return_value=True), commit=AsyncMock())
+
+ @asynccontextmanager
+ async def session():
+ yield db
+
+ monkeypatch.setattr(scheduler, "AsyncSessionLocal", session)
+ monkeypatch.setattr(scheduler.asyncio, "sleep", AsyncMock())
+ cancel = AsyncMock()
+ monkeypatch.setattr(scheduler, "cancel_running_task", cancel)
+ await scheduler._renew_lease(123, "owner-token")
+ cancel.assert_awaited_once_with(123)
diff --git a/backend/tests/test_task_scheduler_dispatch.py b/backend/tests/test_task_scheduler_dispatch.py
index 42dde86..6b643d3 100644
--- a/backend/tests/test_task_scheduler_dispatch.py
+++ b/backend/tests/test_task_scheduler_dispatch.py
@@ -18,10 +18,12 @@ 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, "_running_queues", {})
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, "_claim_direct_llm_tasks", AsyncMock())
monkeypatch.setattr(scheduler, "get_settings", lambda: SimpleNamespace(
task_runtime_max_concurrency=4,
task_user_max_concurrency=1,
@@ -55,6 +57,7 @@ class _QueueSession:
self.rowcount = rowcount
self.selects = []
self.claimed = []
+ self.bind = SimpleNamespace(dialect=SimpleNamespace(name="sqlite"))
async def __aenter__(self):
"""进入内存事务。"""
@@ -64,6 +67,10 @@ class _QueueSession:
"""无需提交真实资源。"""
return False
+ async def scalar(self, _statement, _params=None):
+ """No pre-existing tasks occupy the per-lane database capacity."""
+ return 0
+
async def execute(self, statement):
"""模拟领取 CAS 与有上限的候选查询。"""
if isinstance(statement, Update):
@@ -92,7 +99,7 @@ async def test_claim_pages_past_user_filled_by_this_tick(monkeypatch):
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()
+ await scheduler._claim_queue("text", datetime.now(UTC))
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
@@ -112,7 +119,7 @@ async def test_failed_compare_and_swap_never_launches_executor(monkeypatch):
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()
+ await scheduler._claim_queue("text", datetime.now(UTC))
assert len(db.selects) == scheduler._MAX_CLAIM_PAGES
assert db.claimed == []
executor.assert_not_awaited()
@@ -122,7 +129,8 @@ async def test_failed_compare_and_swap_never_launches_executor(monkeypatch):
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)})
+ scheduler._running_jobs.update({i: active for i in range(100, 112)})
+ scheduler._running_queues.update({i: ("text", "image", "video")[(i - 100) // 4] for i in range(100, 112)})
db = _QueueSession([[9]])
cancelled = AsyncMock()
business = AsyncMock()
diff --git a/backend/tests/test_voice_probe_concurrency.py b/backend/tests/test_voice_probe_concurrency.py
new file mode 100644
index 0000000..cd605db
--- /dev/null
+++ b/backend/tests/test_voice_probe_concurrency.py
@@ -0,0 +1,71 @@
+"""音频探测的离线并发回归:不同分集共用项目目录时不得互相覆盖。"""
+import asyncio
+from unittest.mock import AsyncMock
+
+import pytest
+
+from app.services.drama import voice_reference_audio as audio
+
+
[email protected]("urls", [("first", "second"), ("first", "first")])
+async def test_parallel_voice_probes_keep_independent_files(monkeypatch, tmp_path, urls):
+ """模拟两次下载都落盘后才探测,确保时长来自各自请求的文件。"""
+ paths = []
+ both_downloaded = asyncio.Event()
+
+ async def download(url, *, dest):
+ """写入可识别的样本,等待另一下载完成以稳定复现共享路径错误。"""
+ dest.write_text(url, encoding="utf-8")
+ paths.append(dest)
+ if len(paths) == 2:
+ both_downloaded.set()
+ await both_downloaded.wait()
+ return dest
+
+ monkeypatch.setattr(audio, "resolve_voice_audio_local_path", download)
+ monkeypatch.setattr(audio, "probe_duration", lambda path: {"first": 2.5, "second": 7.5}[path.read_text(encoding="utf-8")])
+ result = await asyncio.gather(*(audio.probe_voice_url_duration(url, work_dir=tmp_path) for url in urls))
+ assert result == [{"first": 2.5, "second": 7.5}[url] for url in urls]
+ assert len(set(paths)) == 2
+ assert all(not path.exists() for path in paths)
+
+
[email protected]("unreadable", [False, True])
+async def test_probe_cleans_only_its_temporary_file_on_failure(monkeypatch, tmp_path, unreadable):
+ """探测或解析失败仍清理本次文件,保留项目中的原始音频。"""
+ source = tmp_path / "original.mp3"
+ source.write_bytes(b"source")
+ paths = []
+
+ async def download(_url, *, dest):
+ """模拟已经写入临时文件后返回失败或交给探测器。"""
+ dest.write_bytes(b"temporary")
+ paths.append(dest)
+ return None if unreadable else dest
+
+ def failed_probe(_path):
+ """模拟外部探测进程失败。"""
+ raise RuntimeError("probe failed")
+
+ monkeypatch.setattr(audio, "resolve_voice_audio_local_path", download)
+ monkeypatch.setattr(audio, "probe_duration", failed_probe)
+ if unreadable:
+ assert await audio.probe_voice_url_duration("sample", work_dir=tmp_path) is None
+ else:
+ with pytest.raises(RuntimeError, match="probe failed"):
+ await audio.probe_voice_url_duration("sample", work_dir=tmp_path)
+ assert source.read_bytes() == b"source"
+ assert all(not path.exists() for path in paths)
+
+
+async def test_body_validation_still_reuses_one_probe_per_url(monkeypatch, tmp_path):
+ """同次提交中的重复参考音仍按 URL 复用时长,避免重复下载。"""
+ probe = AsyncMock(return_value=2.5)
+ monkeypatch.setattr(audio, "probe_voice_url_duration", probe)
+ monkeypatch.setattr(audio.storage_svc, "project_dir", lambda _id: tmp_path)
+ item = {"type": "audio_url", "audio_url": {"url": "https://media.example.com/voice.mp3"}, "role": "reference_audio"}
+ await audio.validate_seedance_body_reference_audios({"content": [item, item]}, project_id=17)
+ probe.assert_awaited_once()
diff --git a/docs/TASK_SCHEDULING.md b/docs/TASK_SCHEDULING.md
new file mode 100644
index 0000000..595bcd2
--- /dev/null
+++ b/docs/TASK_SCHEDULING.md
@@ -0,0 +1,37 @@
+# 三队列任务调度与独立生成
+
+任务持久化在 `task_runs`,按 `queue_type` 分为 `text`、`image`、`video`。剧本、分镜规划与配音归文字队列;图片生成归图片队列;视频生成与合成归视频队列。科普流水线按当前 phase 分流。音频是前台独立分类,后台共享文字队列。
+
+各队列的全站并发分别由以下环境变量控制:
+
+```dotenv
+TASK_QUEUE_TEXT_CONCURRENCY=4
+TASK_QUEUE_IMAGE_CONCURRENCY=4
+TASK_QUEUE_VIDEO_CONCURRENCY=4
+```
+
+未配置时,各队列沿用 `TASK_RUNTIME_MAX_CONCURRENCY`,默认每队列 4,总容量 12。单用户限制按队列计算,团队限制仍跨队列共用。视频等待上游的 `awaiting_poll` 任务占视频队列容量,但不占本地执行协程。
+
+调度器使用 PostgreSQL 每队列事务级 advisory lock、任务行锁与状态条件更新领取任务。持有执行任务的进程每 10 秒续租;其他进程只恢复已经过期的租约。取消使用独立槽位。仍以内联方式响应的聊天及开放 API 请求保留原请求行为,并记录所属队列。
+
+## 生成与任务记录
+
+- `/tools/video`、`/tools/image`、`/tools/audio`:生成工作台;旧工具链接跳转到相应分类。
+- `/tasks`:当前用户的独立生成记录,支持分类、状态、本地/上游任务 ID、日期筛选和下载。
+- `POST /api/tools/run`:先创建 `ToolRun` 和同一条用于执行、计费的 `TaskRun`,事务提交后由调度器执行。响应中的 `task_id=task-<id>` 为本地查询标识,`platform_task_id` 为统一任务主键。
+- `TaskRun.provider_task_id` 为真实上游异步任务 ID;`provider_name`、`provider_status` 和任务事件记录上游状态。同步图片/音频接口可能没有上游异步任务 ID。
+- 视频提交后由服务端 poller 查询状态、保存结果和结算,浏览器只读取本地记录。旧视频记录仍兼容原 provider ID 查询,并由后台同步结果。
+- 图片/音频执行完成后先持久化结果和用量,再由执行器完成任务与结算。恢复时复用已保存结果;视频恢复时复用已有上游 ID。同步生成在上游已完成、结果尚未落库时崩溃,仍受上游幂等能力限制。
+
+启动迁移为既有任务回填 `queue_type`,新增上游信息列及队列查询索引。更新后需要在负责迁移的后端节点启用 `DATABASE_BOOTSTRAP_ENABLED` 并重启。连接共享库且关闭 bootstrap 的本地进程,应等待迁移节点完成后再使用新版本。
+
+验证:`backend/tests/test_studio_generation.py` 使用独立 SQLite 数据库和模拟上游,覆盖三类生成、队列隔离、持久化、恢复复用、预扣结算、列表筛选与用户归属;`test_task_scheduler_dispatch.py` 覆盖领取公平性、并发竞争与取消;实际付费生成需在配置好的环境进行联调。
+
+
+## ??????????
+
+??????????????????????????????????????????????????????commit=False ???????????????????????????? TASK_RUNTIME_ENABLED=false ??? API ?????????????????
+
+???????????10 ???????????????????????????????????????????????????????????????????????? API ????????????????????????????????????????????????????????????????????????????????
+
+?????????????????????????????????? phase ??????????????????????? backend/tests/test_direct_llm_execution.py??????????????????????????????/????????????????
diff --git a/frontend/src/api/tasks.ts b/frontend/src/api/tasks.ts
index c429402..9ada661 100644
--- a/frontend/src/api/tasks.ts
+++ b/frontend/src/api/tasks.ts
@@ -28,6 +28,10 @@ export type TaskRunOut = {
id: number
domain: string
task_type: string
+ execution_mode?: 'direct' | 'queued'
+ queue_type?: 'text' | 'image' | 'video'
+ provider_name?: string | null
+ provider_status?: string | null
status: string
progress_percent?: number
current_step_key?: string | null
@@ -64,6 +68,7 @@ export const tasksApi = {
page_size?: number
domain?: string
task_type?: string
+ queue_type?: 'text' | 'image' | 'video'
status?: string
target_type?: string
target_id?: number
@@ -74,6 +79,7 @@ export const tasksApi = {
if (params.page_size) q.set('page_size', String(params.page_size))
if (params.domain) q.set('domain', params.domain)
if (params.task_type) q.set('task_type', params.task_type)
+ if (params.queue_type) q.set('queue_type', params.queue_type)
if (params.status) q.set('status', params.status)
if (params.target_type) q.set('target_type', params.target_type)
if (params.target_id) q.set('target_id', String(params.target_id))