Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Heuristic:869413421 Ai moive studio Session Isolation For Workers

From Leeroopedia
Knowledge Sources
Domains Optimization, Concurrency, Database
Last Updated 2026-10-23 14:00 GMT

Overview

Use independent database sessions per concurrent worker to avoid "Session is already flushing" errors and DetachedInstanceError in batch asyncio.gather operations.

Description

SQLAlchemy AsyncSession is not safe for concurrent access from multiple coroutines. When batch processing uses asyncio.gather with a shared session, concurrent flush/commit calls cause Session is already flushing errors. The platform's pattern is to: (1) load shared data (script, API key, characters) in the main session, (2) extract plain data into dicts to avoid accessing ORM objects in coroutines, (3) create an independent session per worker via get_async_db() context manager, (4) re-load ORM objects inside the worker session, and (5) commit each worker session independently.

Usage

Use this heuristic when:

  • Batch processing entities with asyncio.gather and each worker needs to read/write to the database.
  • You encounter Session is already flushing errors during concurrent operations.
  • Workers need to access ORM objects (must re-load them in their own session to avoid DetachedInstanceError).
  • Pattern used by TransitionService, VisualIdentityService, and SceneImageService.

The Insight (Rule of Thumb)

  • Action:' Create an independent session per worker using async with get_async_db() as worker_session:. Extract plain data into dicts before passing to coroutines.
  • Value: Main session for shared reads; independent session per worker for writes. Each worker commits independently.
  • Trade-off: More database connections and slightly higher overhead, but eliminates session conflicts and allows independent rollback per worker.
  • Compatibility: Requires the get_async_db() async context manager from src.core.database.

Reasoning

SQLAlchemy AsyncSession serializes operations on a single connection. When multiple coroutines call flush() or commit() on the same session concurrently:

  • The first flush locks the session; a second concurrent flush raises Session is already flushing.
  • ORM objects loaded in one session become detached when that session closes or when accessed from a different context (DetachedInstanceError).

The isolation pattern:

  1. Main session loads all shared data and extracts primitive fields into dicts.
  2. Each worker creates its own session, re-loads ORM objects, performs operations, and commits.
  3. If one worker fails, only its session rolls back — others are unaffected.
  4. This also improves throughput since workers don't block on session locks.

Code Evidence

Transition service pattern from `transition_service.py:529-574`:

# 4. 提取过渡数据(避免在协程中访问ORM对象)
transition_data_list = []
for t in transitions:
    transition_data_list.append({
        'id': t.id, 'from_shot_id': t.from_shot_id,
        'to_shot_id': t.to_shot_id, 'video_prompt': t.video_prompt,
        'script_id': t.script_id
    })

async def _generate_worker_with_session(transition_data: dict):
    async with semaphore:
        async with get_async_db() as worker_session:
            try:
                transition = await worker_session.get(
                    MovieShotTransition, transition_data['id']
                )
                worker_service = TransitionService(worker_session)
                result = await worker_service._generate_single_transition_video(
                    transition, api_key_id, str(user_id), video_model, provider
                )
                await worker_session.commit()
                return result
            except Exception as e:
                await worker_session.rollback()

Keyframe session isolation from `visual_identity_service.py:285-289`:

async def process_scene_with_session(scene_id: str, scene_data: dict):
    async with get_async_db() as scene_session:
        try:
            shot_in_session = await scene_session.get(MovieShot, shot_id, options=[
                joinedload(MovieShot.scene)
            ])
            # ... process and commit per scene
            await scene_session.commit()

Flush avoidance comment from `video_synthesis.py:287-288`:

# 注意:这里只更新对象状态,不要 flush,避免并发 flush 导致
# "Session is already flushing" 错误。统一在主流程中 flush
sentence.save_video_cache(video_key, duration)

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment