Skip to content

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

fix(tasks): 释放长任务数据库连接并扩容连接池

yic22657bb1382
diff --git a/backend/.env.example b/backend/.env.example
index ef64860..f784a8f 100644
--- a/backend/.env.example
+++ b/backend/.env.example
@@ -18,9 +18,10 @@ DATABASE_URL_SYNC=postgresql+psycopg2://printfilm:change-me-strong-db-password@1
# 此开关独立于 TASK_RUNTIME_ENABLED;本地共享库联调通常同时关闭任务运行器。
DATABASE_BOOTSTRAP_ENABLED=true
# Postgres 生产建议:API uvicorn --workers 1,任务调度与 API 共用进程内连接池
-# 生产建议与任务并发对齐(杭州现网:100+20,PG max_connections≥250)
-# DB_POOL_SIZE=100
-# DB_MAX_OVERFLOW=20
+# 单进程最多 70 条;PG max_connections=100 时给调试、迁移等保留 30 条。
+# 多进程/多实例各自建池,须把所有进程的上限相加后核对数据库总预算。
+DB_POOL_SIZE=50
+DB_MAX_OVERFLOW=20
REDIS_URL=redis://127.0.0.1:16379/0
CORS_ORIGINS=http://localhost:5173,http://127.0.0.1:5173,http://localhost:5174,http://127.0.0.1:5174
PUBLIC_BASE_URL=http://127.0.0.1:8000
diff --git a/backend/app/config.py b/backend/app/config.py
index 49d7fff..74e7ea1 100644
--- a/backend/app/config.py
+++ b/backend/app/config.py
@@ -25,9 +25,9 @@ class Settings(BaseSettings):
database_url_sync: str = "postgresql+psycopg2://printfilm:[email protected]:15432/printfilm"
# 连接已初始化的共享库时可关闭建表/补列/种子数据;仍加载数据库中的模型配置。
database_bootstrap_enabled: bool = True
- # Postgres 连接池(统一任务平台 / API 共用)
- db_pool_size: int = 5
- db_max_overflow: int = 5
+ # 每个 API 进程与任务平台共用;默认最多 70,PG 上限 100 时保留 30 给其他连接。
+ db_pool_size: int = 50
+ db_max_overflow: int = 20
db_pool_recycle_sec: int = 1800
db_pool_timeout_sec: int = 30
redis_url: str = "redis://127.0.0.1:6379/0"
diff --git a/backend/app/services/drama/jobs.py b/backend/app/services/drama/jobs.py
index 9828697..48eee10 100644
--- a/backend/app/services/drama/jobs.py
+++ b/backend/app/services/drama/jobs.py
@@ -1827,6 +1827,9 @@ async def run_asset_image_job(
asset_id,
len(resolved_prompt),
)
+ # refresh/查询会开启读事务;等待上游生图和并发槽位前归还连接。
+ # expire_on_commit=False 保留已加载数据,生成结果随后另开事务写回。
+ await db.commit()
asset = await generate_asset_image(
db,
user,
diff --git a/backend/app/services/tasks/executor.py b/backend/app/services/tasks/executor.py
index 4b99b3b..647a91d 100644
--- a/backend/app/services/tasks/executor.py
+++ b/backend/app/services/tasks/executor.py
@@ -100,8 +100,12 @@ async def execute_task_run(task_id: int) -> None:
if not task:
return
handler = get_task_handler(task.domain, task.task_type)
- result = await handler.executor(task) if handler else {"ok": False, "error": "missing_handler"}
- # 重新加载(含 selectinload steps);勿 refresh,会卸掉关系再触发懒加载。
+ # Handlers read the loaded task snapshot and own their database sessions.
+ # Release this read transaction before waiting on a provider or its semaphore.
+ result = await handler.executor(task) if handler else {"ok": False, "error": "missing_handler"}
+ async with AsyncSessionLocal() as db:
+ # A new session also observes cancellation/provider state committed by handlers.
+ # Reload steps with selectinload; refresh would unload the relationship.
task = await get_task_for_runtime(db, task_id)
if not task:
return
diff --git a/backend/requirements-dev.txt b/backend/requirements-dev.txt
index d47c87f..3e40b48 100644
--- a/backend/requirements-dev.txt
+++ b/backend/requirements-dev.txt
@@ -1,3 +1,4 @@
-r requirements.txt
pytest==8.3.5
pytest-asyncio==0.25.3
+aiosqlite==0.21.0
diff --git a/backend/tests/test_asset_image_connection_lifetime.py b/backend/tests/test_asset_image_connection_lifetime.py
new file mode 100644
index 0000000..d54ab7e
--- /dev/null
+++ b/backend/tests/test_asset_image_connection_lifetime.py
@@ -0,0 +1,88 @@
+"""Waiting for image generation must leave database connections available to HTTP reads."""
+
+import asyncio
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+from sqlalchemy import select, text
+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
+
+from app import models_teams # noqa: F401 - resolve team foreign key column types
+from app.models import User
+from app.models_drama import DramaAsset, DramaProject, DramaScript
+from app.services.drama import generation, jobs
+
+
[email protected]("existing_asset", [True, False])
+async def test_asset_image_wait_releases_connection(tmp_path, monkeypatch, existing_asset):
+ engine = create_async_engine(
+ f"sqlite+aiosqlite:///{(tmp_path / 'image.sqlite3').as_posix()}",
+ pool_size=1,
+ max_overflow=0,
+ pool_timeout=0.2,
+ )
+ sessions = async_sessionmaker(engine, expire_on_commit=False)
+ image_started = asyncio.Event()
+ release_image = asyncio.Event()
+
+ async def generate(*args, **kwargs):
+ image_started.set()
+ await release_image.wait()
+ return SimpleNamespace(local_url="https://cdn.example/new.png", remote_url=None)
+
+ monkeypatch.setattr(jobs, "AsyncSessionLocal", sessions)
+ monkeypatch.setattr(jobs, "resolve_visual_prompt_for_asset", AsyncMock(return_value="saved prompt"))
+ monkeypatch.setattr(generation, "get_ark", lambda: SimpleNamespace(gen_image=generate))
+ monkeypatch.setattr(generation, "resolve_seedream_model_endpoint", lambda _: "image-model")
+ monkeypatch.setattr(generation, "resolve_seedream_size", lambda **kwargs: "1536x2048")
+ monkeypatch.setattr(generation, "resolve_image_style_board_url", lambda _: None)
+ monkeypatch.setattr(generation, "build_generation_prompt", lambda prompt, **kwargs: prompt)
+ monkeypatch.setattr(generation, "record_seedream_image_usage", AsyncMock())
+ monkeypatch.setattr("app.services.storage.republish_url", lambda url, **kwargs: url)
+
+ worker = None
+ try:
+ async with engine.begin() as conn:
+ for model in (User, DramaProject, DramaScript, DramaAsset):
+ await conn.run_sync(model.__table__.create)
+ async with sessions() as db:
+ user = User(email="[email protected]", hashed_password="test")
+ db.add(user)
+ await db.flush()
+ project = DramaProject(user_id=user.id, title="Pool regression", params={})
+ db.add(project)
+ await db.flush()
+ asset = DramaAsset(project_id=project.id, type="character", name="portrait", params={})
+ if existing_asset:
+ db.add(asset)
+ await db.commit()
+ project_id, user_id = project.id, user.id
+ asset_id = asset.id if existing_asset else None
+
+ worker = asyncio.create_task(jobs.run_asset_image_job(project_id, user_id, "portrait", asset_id))
+ await asyncio.wait_for(image_started.wait(), timeout=3)
+
+ # A separate request must succeed while the provider call is still pending.
+ async with sessions() as request_db:
+ assert await request_db.scalar(text("SELECT 1")) == 1
+ if asset_id:
+ saved = await request_db.get(DramaAsset, asset_id)
+ assert saved.params["visualPrompt"] == "saved prompt"
+ assert saved.params["generation"]["status"] == "generating"
+
+ release_image.set()
+ result = await asyncio.wait_for(worker, timeout=3)
+ assert result["ok"] is True
+ async with sessions() as db:
+ saved = await db.scalar(select(DramaAsset).where(DramaAsset.id == result["asset_id"]))
+ assert saved.url == "https://cdn.example/new.png"
+ assert saved.params["generation"]["status"] == "done"
+ finally:
+ release_image.set()
+ if worker is not None and not worker.done():
+ worker.cancel()
+ if worker is not None:
+ await asyncio.gather(worker, return_exceptions=True)
+ await engine.dispose()
diff --git a/backend/tests/test_task_executor_sessions.py b/backend/tests/test_task_executor_sessions.py
new file mode 100644
index 0000000..19c9c71
--- /dev/null
+++ b/backend/tests/test_task_executor_sessions.py
@@ -0,0 +1,199 @@
+"""Long provider calls must release executor connections and reload current task state."""
+
+from __future__ import annotations
+
+import asyncio
+from pathlib import Path
+
+import pytest
+import pytest_asyncio
+from sqlalchemy import select, update
+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
+from sqlalchemy.pool import AsyncAdaptedQueuePool
+
+import app.models_teams # noqa: F401 — resolve team foreign keys for isolated SQLite DDL
+from app.config import get_settings
+from app.models import UsageEvent, User
+from app.models_tasks import TaskEvent, TaskRun, TaskStep, TaskTarget
+from app.services.tasks.executor import execute_task_run
+from app.services.tasks.handlers import TaskHandler
+from app.services.tasks.service import get_task_for_runtime
+
+
+@pytest_asyncio.fixture
+async def executor_database(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
+ """Real, deliberately small pool; no application database is contacted."""
+ engine = create_async_engine(
+ f"sqlite+aiosqlite:///{(tmp_path / 'executor.sqlite3').as_posix()}",
+ poolclass=AsyncAdaptedQueuePool,
+ pool_size=2,
+ max_overflow=0,
+ pool_timeout=0.2,
+ )
+ models = (User, TaskRun, TaskStep, TaskTarget, TaskEvent, UsageEvent)
+ async with engine.begin() as connection:
+ for model in models:
+ await connection.run_sync(model.__table__.create)
+ sessions = async_sessionmaker(engine, expire_on_commit=False)
+ monkeypatch.setattr("app.services.tasks.executor.AsyncSessionLocal", sessions)
+ monkeypatch.setattr(get_settings(), "billing_enabled", False)
+ async with sessions() as db:
+ db.add(User(id=1, email="[email protected]", hashed_password="unused"))
+ await db.commit()
+ try:
+ yield sessions
+ finally:
+ await engine.dispose()
+
+
+async def _new_task(sessions) -> int:
+ async with sessions() as db:
+ task = TaskRun(
+ domain="tools", task_type="mock_delay", requested_by=1,
+ status="leased", payload={},
+ )
+ db.add(task)
+ await db.flush()
+ db.add(TaskStep(task_id=task.id, step_key="main", step_type="job", status="pending"))
+ await db.commit()
+ return int(task.id)
+
+
+async def test_concurrent_provider_waits_leave_connections_for_api_queries(
+ executor_database, monkeypatch: pytest.MonkeyPatch,
+):
+ """Two long tasks must not consume both pooled connections while awaiting providers."""
+ sessions = executor_database
+ task_ids = [await _new_task(sessions) for _ in range(2)]
+ entered = {task_id: asyncio.Event() for task_id in task_ids}
+ release_provider = asyncio.Event()
+
+ async def provider_wait(task):
+ entered[task.id].set()
+ await release_provider.wait()
+ return {"ok": True}
+
+ handler = TaskHandler("tools", "mock_delay", provider_wait)
+ monkeypatch.setattr("app.services.tasks.executor.get_task_handler", lambda *_: handler)
+ jobs = []
+ try:
+ for task_id in task_ids:
+ jobs.append(asyncio.create_task(execute_task_run(task_id)))
+ await asyncio.wait_for(entered[task_id].wait(), timeout=2)
+ # This uses the same real pool as executors, like an authenticated API query.
+ async with sessions() as api_db:
+ rows = (await api_db.execute(select(TaskRun.id))).scalars().all()
+ assert sorted(rows) == task_ids
+ finally:
+ release_provider.set()
+ await asyncio.gather(*jobs)
+
+ async with sessions() as db:
+ statuses = list((await db.execute(select(TaskRun.status))).scalars())
+ assert statuses == ["succeeded", "succeeded"]
+
+
+ ("updates", "expected_status", "expected_step_status"),
+ [
+ ({"cancel_requested": True, "status": "cancel_requested"}, "cancelled", "done"),
+ ({"status": "awaiting_poll"}, "awaiting_poll", "submitting"),
+ ],
+ ids=["cancellation-during-provider-call", "handler-registered-provider-poll"],
+)
+async def test_finalization_uses_changes_committed_by_another_session(
+ executor_database, monkeypatch: pytest.MonkeyPatch,
+ updates, expected_status: str, expected_step_status: str,
+):
+ """A fresh read must preserve provider IDs, cancellation and deferred polling state."""
+ sessions = executor_database
+ task_id = await _new_task(sessions)
+
+ async def provider_result(task):
+ async with sessions() as writer:
+ await writer.execute(update(TaskRun).where(TaskRun.id == task.id).values(
+ **updates, provider_task_id="provider-created-by-handler",
+ ))
+ await writer.commit()
+ return {"ok": True}
+
+ handler = TaskHandler("tools", "mock_delay", provider_result)
+ monkeypatch.setattr("app.services.tasks.executor.get_task_handler", lambda *_: handler)
+ await execute_task_run(task_id)
+
+ async with sessions() as db:
+ task = await get_task_for_runtime(db, task_id)
+ assert task.status == expected_status
+ assert task.provider_task_id == "provider-created-by-handler"
+ assert task.cancel_requested is bool(updates.get("cancel_requested"))
+ assert task.steps[0].status == expected_step_status
+ if expected_status == "awaiting_poll":
+ assert task.result_payload is None
+ assert task.finished_at is None
+
+
+async def test_provider_failure_still_marks_task_and_step_failed(
+ executor_database, monkeypatch: pytest.MonkeyPatch,
+):
+ sessions = executor_database
+ task_id = await _new_task(sessions)
+
+ async def provider_failure(_task):
+ raise RuntimeError("provider connection failed")
+
+ handler = TaskHandler("tools", "mock_delay", provider_failure)
+ monkeypatch.setattr("app.services.tasks.executor.get_task_handler", lambda *_: handler)
+ await execute_task_run(task_id)
+
+ async with sessions() as db:
+ task = await get_task_for_runtime(db, task_id)
+ assert task.status == "failed"
+ assert task.error_code == "RuntimeError"
+ assert "provider connection failed" in task.error_message
+ assert task.steps[0].status == "failed"
+ assert task.billing_status == "settled"
+
+
[email protected]("cancel_requested", [False, True], ids=["shutdown", "user-cancel"])
+async def test_interrupted_provider_wait_uses_latest_cancellation_and_preserves_provider_id(
+ executor_database, monkeypatch: pytest.MonkeyPatch, cancel_requested: bool,
+):
+ sessions = executor_database
+ task_id = await _new_task(sessions)
+ entered_provider = asyncio.Event()
+ release_provider = asyncio.Event()
+
+ async def provider_wait(_task):
+ entered_provider.set()
+ await release_provider.wait()
+
+ handler = TaskHandler("tools", "mock_delay", provider_wait)
+ monkeypatch.setattr("app.services.tasks.executor.get_task_handler", lambda *_: handler)
+ job = asyncio.create_task(execute_task_run(task_id))
+ try:
+ await asyncio.wait_for(entered_provider.wait(), timeout=2)
+ async with sessions() as writer:
+ await writer.execute(update(TaskRun).where(TaskRun.id == task_id).values(
+ provider_task_id="accepted-before-interruption",
+ cancel_requested=cancel_requested,
+ status="cancel_requested" if cancel_requested else "running",
+ ))
+ await writer.commit()
+ job.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await job
+ finally:
+ release_provider.set()
+ await asyncio.gather(job, return_exceptions=True)
+
+ async with sessions() as db:
+ task = await get_task_for_runtime(db, task_id)
+ assert task.status == ("cancelled" if cancel_requested else "pending")
+ assert task.provider_task_id == "accepted-before-interruption"
+ if cancel_requested:
+ assert task.steps[0].status == "cancelled"
+ assert task.finished_at is not None
+ else:
+ assert task.steps[0].status == "pending"
+ assert task.payload["provider_task_id"] == "accepted-before-interruption"
+ assert task.next_action_at is not None
diff --git a/deploy/.env.docker.example b/deploy/.env.docker.example
index ee0f1f2..53a860c 100644
--- a/deploy/.env.docker.example
+++ b/deploy/.env.docker.example
@@ -9,6 +9,10 @@ POSTGRES_DB=printfilm
SECRET_KEY=change-me-to-a-long-random-string
+# 单 API 进程与任务平台共用;最多 70 条,PG 上限 100 时保留 30 条余量。
+DB_POOL_SIZE=50
+DB_MAX_OVERFLOW=20
+
# 用户端 nginx :8080;管理端 :8081;API 文档 :8000
CORS_ORIGINS=http://localhost:8080,http://127.0.0.1:8080,http://localhost:8081,http://127.0.0.1:8081,http://localhost:8000,http://127.0.0.1:8000
PUBLIC_BASE_URL=http://localhost:8080
diff --git a/deploy/.env.prod.example b/deploy/.env.prod.example
index 5a490f2..c23d35c 100644
--- a/deploy/.env.prod.example
+++ b/deploy/.env.prod.example
@@ -9,8 +9,9 @@ SECRET_KEY=change-me-to-a-long-random-string
DATABASE_URL=postgresql+asyncpg://printfilm:[email protected]:15432/printfilm
DATABASE_URL_SYNC=postgresql+psycopg2://printfilm:[email protected]:15432/printfilm
# API 与进程内任务平台共用连接池(uvicorn 建议 --workers 1)
-DB_POOL_SIZE=5
-DB_MAX_OVERFLOW=5
+# 单进程最多 70 条,PG max_connections=100 时保留 30 条余量。
+DB_POOL_SIZE=50
+DB_MAX_OVERFLOW=20
REDIS_URL=redis://127.0.0.1:16379/0
PUBLIC_BASE_URL=https://your-site.example.com
diff --git a/deploy/README.md b/deploy/README.md
index cee7570..a6fd26d 100644
--- a/deploy/README.md
+++ b/deploy/README.md
@@ -37,8 +37,12 @@ DATABASE_URL_SYNC=postgresql+psycopg2://printfilm:<密码>@127.0.0.1:5432/printf
REDIS_URL=redis://127.0.0.1:6379/0
TASK_RUNTIME_MAX_CONCURRENCY=4
TASK_USER_MAX_CONCURRENCY=4
+DB_POOL_SIZE=50
+DB_MAX_OVERFLOW=20
```
+连接池按需建立连接,每个 API 进程最多使用 `50 + 20 = 70` 条;PostgreSQL `max_connections=100` 时保留 30 条给其他应用、迁移、调试和管理连接。增加进程或实例时,各自有独立连接池,须按所有进程的最大连接数之和重新核对数据库预算。修改连接池环境变量后,宿主服务重启 API;Docker 部署重建 API 容器以重新加载环境变量。连接池扩容仍需配合长任务在等待上游前释放数据库事务。
+
需本机已安装:Python 3.12、FFmpeg(PATH)、Node.js。
**中文字幕字体(必装)**:科普成片用 FFmpeg `drawtext` 烧录叠字/口播字幕。Ubuntu 示例:
@@ -106,7 +110,7 @@ docker compose -f deploy/docker-compose.yml --env-file deploy/.env.prod down -v
任务并发:通过 `backend/.env` 中的 `TASK_RUNTIME_MAX_CONCURRENCY`、`TASK_USER_MAX_CONCURRENCY` 调整统一任务平台并发。
-测试环境由 Jenkins 轮询 **GitHub 仓库 `yi1108/printfilm` 的 `dev` 分支**自动发布;日常测试发版提交并推送代码即可,不需要手动上传补丁或更新服务器容器。本仓库的 `origin` 指向 GitCC,单独 `git push origin dev` 不会触发测试发版;提交后还需 `git push github dev`,再核对 Jenkins 构建版本与运行中的镜像标签一致。
+测试环境由 Jenkins 轮询 **GitHub 仓库 `yi1108/printfilm` 的 `dev` 分支**自动发布;日常测试发版提交并推送代码即可,不需要手动上传补丁或更新服务器容器。推送前用 `git remote -v` 确认目标;`origin` 指向该 GitHub 仓库时执行 `git push origin dev`,若 `origin` 指向 GitCC,则还需推送到对应 GitHub remote(例如 `git push github dev`)。推送后核对 Jenkins 构建版本与运行中的镜像标签一致。
本地 API 联调连接共享测试数据库时,设置 `TASK_RUNTIME_ENABLED=false`,只保留测试服务器执行调度、轮询和孤儿恢复。已由服务器初始化的共享数据库还可设 `DATABASE_BOOTSTRAP_ENABLED=false`,本机只读取模型缓存,不再重复建表、补列、seed 或提升管理员。本地仍能创建和查询任务,执行与产物存储由测试服务器负责;本地页面应能访问服务器返回的媒体地址。独立本地数据库或实际执行节点保持两个开关为 `true`(默认)。不要让多个调试实例同时恢复同一队列。