review: ffprobe out of the write transaction, and three tests that were watching nothing

All three bugs confirmed; the two suggestions taken.

[bug] `video_modeler` awaited ffprobe -- a subprocess per video, up to 20
per batch -- inside its `commit=True` session.  With IMMEDIATE as the
default that holds the write lock for the whole batch, which is the same
starvation this branch is curing in `video_cleanup`.  (It was already
partly true before: the batch's first `session.flush([video])` took the
lock ahead of the remaining ffprobes.)  The batch is now read, ffprobed
with no transaction open, then written.  `get_or_create_ffprobe_json` in
modules/videos/common.py is the path-only entry point that makes that
possible; `Video.get_ffprobe_json` delegates to it and keeps appending
the cache file to its FileGroup.  `validate()` -- and the poster
generation it can trigger -- is still inside the write transaction, and
now says so.

[bug] `test_download_dispatched_outside_immediate_transaction` probed
`getattr(_immediate_txn, 'active', False)`, which a ContextVar never has,
so it passed unconditionally.  It now probes the actual write lock from a
competing connection under `production_like_sessions`.  Mutation-checked:
moving the dispatch back inside the claim transaction fails it.

[bug] `asyncio.create_task` snapshots the current Context, so a flag held
for a write session's lifetime was inherited by every task spawned inside
it -- and the parent's `reset()` cannot reach a child's copy, leaving
that task issuing BEGIN IMMEDIATE for its *read* sessions.
`create_downloads` spawns `dispatch_downloads` exactly that way, so every
user-created download hit it.  The flag now lives only across the
session's opening `connection()` call, which also means the write lock is
taken when the session opens rather than at the caller's first statement.

[suggestion] `renew_recurring_downloads` scanned every recurring Download
under the write lock, including the usual cycle where nothing is due.  It
reads first now and takes the lock only for the rows that change,
re-checking status since the dispatcher may have claimed one in between.

[nit] Parenthesized the directory OR in the claim join.

`probe_write_lock_is_held` moved to conftest alongside
`write_lock_held_briefly`; three suites use it now.

Suite: 1712 passed, 5 skipped.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Roland 2026-08-07 20:04:40 -06:00 • committed by lrnselfreliance
parent daf2ba39d4
commit 06ac0d2055
9 changed files with 263 additions and 101 deletions

View file

@ -1,10 +1,12 @@
import asyncio
import json
import pathlib
from typing import Callable, List, Tuple
from sqlalchemy import or_
from sqlalchemy.orm import Session
from modules.videos.common import get_or_create_ffprobe_json
from modules.videos.models import Video
from wrolpi.common import logger, limit_concurrent, register_modeler, register_refresh_cleanup
from wrolpi.db import get_db_curs, get_db_session
@ -23,18 +25,37 @@ VIDEO_PROCESSING_LIMIT = 20
async def video_modeler(progress_callback: Callable[[int], None] = None):
total_processed = 0
while True:
with get_db_session(commit=True) as session:
file_groups = session.query(FileGroup, Video).filter(
# Read the batch; nothing is claimed yet, so the write lock stays free while ffprobe runs.
with get_db_session() as session:
batch: List[Tuple[int, pathlib.Path]] = list(session.query(FileGroup.id, FileGroup.primary_path).filter(
FileGroup.indexed != True,
or_(FileGroup.mimetype.like('video/%'), FileGroup.mimetype.like('audio/%')),
).outerjoin(Video, Video.file_group_id == FileGroup.id) \
.limit(VIDEO_PROCESSING_LIMIT)
file_groups: List[Tuple[FileGroup, Video]] = list(file_groups)
).limit(VIDEO_PROCESSING_LIMIT).all())
if not batch:
break
# ffprobe each file with no transaction open. This is a subprocess per video and can run
# for seconds; inside the write transaction below it would hold the write lock for the whole
# batch, and every other writer on the box would wait out `busy_timeout` (30s).
probed = dict()
for file_group_id, primary_path in batch:
try:
probed[file_group_id] = await get_or_create_ffprobe_json(pathlib.Path(str(primary_path)))
except Exception as e:
if PYTEST:
raise
logger.error(f'Unable to ffprobe Video: {primary_path}', exc_info=e)
# Sleep to catch cancel.
await asyncio.sleep(0)
with get_db_session(commit=True) as session:
file_groups: List[Tuple[FileGroup, Video]] = list(
session.query(FileGroup, Video)
.filter(FileGroup.id.in_([i for i, _ in batch]))
.outerjoin(Video, Video.file_group_id == FileGroup.id))
processed = 0
for file_group, video in file_groups:
processed += 1
video_id = None
try:
if not video:
@ -45,12 +66,16 @@ async def video_modeler(progress_callback: Callable[[int], None] = None):
if not Session.object_session(video):
session.add(video)
video.flush()
# Extract ffprobe data.
await video.get_ffprobe_json()
# Store the ffprobe data gathered above.
if (result := probed.get(file_group.id)) is not None:
video.ffprobe_json, ffprobe_file = result
if ffprobe_file:
# Track the .ffprobe.json cache file that was just written.
file_group.append_files(ffprobe_file)
video.flush(session)
# Validate and index subtitles.
# Validate and index subtitles. (Poster generation happens here when a Channel
# asks for it; it is the remaining slow work inside this transaction.)
video.validate(session)
processed += 1
except Exception as e:
if PYTEST:
raise
@ -59,18 +84,16 @@ async def video_modeler(progress_callback: Callable[[int], None] = None):
file_group.indexed = True
session.commit()
# Report batch progress
total_processed += len(batch)
if progress_callback:
progress_callback(total_processed)
# Report batch progress
total_processed += len(file_groups)
if progress_callback and len(file_groups) > 0:
progress_callback(total_processed)
logger.debug(f'Modeled {len(batch)} videos')
if processed < VIDEO_PROCESSING_LIMIT:
# Did not reach limit, do not query again.
break
logger.debug(f'Modeled {processed} videos')
if len(batch) < VIDEO_PROCESSING_LIMIT:
# Did not reach limit, do not query again.
break
# Sleep to catch cancel.
await asyncio.sleep(0)
@ -127,8 +150,9 @@ _UNCLAIMED_VIDEOS_SQL = '''
SELECT v.id, c.id
FROM video v
INNER JOIN file_group fg ON fg.id = v.file_group_id
INNER JOIN collection col ON fg.directory = col.directory
OR fg.directory LIKE col.directory || '/%'
INNER JOIN collection col
ON (fg.directory = col.directory
OR fg.directory LIKE col.directory || '/%')
INNER JOIN channel c ON c.collection_id = col.id
WHERE v.channel_id IS NULL
'''

View file

@ -319,6 +319,31 @@ def write_ffprobe_json_file(path: Path, data: dict):
json.dump(data, f, indent=2)
async def get_or_create_ffprobe_json(video_path: Path) -> Tuple[dict, Optional[Path]]:
"""Return `(ffprobe data, the cache file written)` for a video file.
Deliberately takes a path and touches no session: ffprobe is a subprocess that runs for
seconds, and a caller holding a write transaction while it runs blocks every other writer
until `busy_timeout` expires. The caller persists the returned data afterwards, in a short
write transaction of its own.
"""
ffprobe_path = video_path.with_suffix('.ffprobe.json')
if ffprobe_path.is_file() and (cached_data := read_ffprobe_json_file(ffprobe_path)):
return cached_data, None
data = await ffprobe_json(video_path)
written = None
from wrolpi.common import get_wrolpi_config
if get_wrolpi_config().save_ffprobe_json:
try:
write_ffprobe_json_file(ffprobe_path, data)
written = ffprobe_path
except IOError as e:
logger.warning(f'Failed to write ffprobe json cache file {ffprobe_path}', exc_info=e)
return data, written
def extract_video_duration(video_path: Path) -> Optional[int]:
"""Get the duration of a video in seconds. Do this using ffprobe."""
if not isinstance(video_path, Path):

View file

@ -413,28 +413,13 @@ class Video(ModelHelper, Base):
if self.ffprobe_json:
return self.ffprobe_json
from modules.videos.common import ffprobe_json, read_ffprobe_json_file, write_ffprobe_json_file
from modules.videos.common import get_or_create_ffprobe_json
# 2. Check if .ffprobe.json file exists
ffprobe_path = self.ffprobe_json_path
if ffprobe_path and ffprobe_path.is_file():
cached_data = read_ffprobe_json_file(ffprobe_path)
if cached_data:
self.ffprobe_json = cached_data
return self.ffprobe_json
# 3. Run ffprobe and cache the result
self.ffprobe_json = await ffprobe_json(self.video_path)
if ffprobe_path:
# Check if saving ffprobe json files is enabled
from wrolpi.common import get_wrolpi_config
if get_wrolpi_config().save_ffprobe_json:
try:
write_ffprobe_json_file(ffprobe_path, self.ffprobe_json)
# Add the new file to the FileGroup so it's tracked
self.file_group.append_files(ffprobe_path)
except IOError as e:
logger.warning(f'Failed to write ffprobe json cache file {ffprobe_path}', exc_info=e)
# 2/3. Read the cached .ffprobe.json, or run ffprobe and cache it.
self.ffprobe_json, written = await get_or_create_ffprobe_json(self.video_path)
if written:
# Track the new cache file in the FileGroup.
self.file_group.append_files(written)
return self.ffprobe_json

View file

@ -9,6 +9,7 @@ from PIL import Image
from modules.videos.models import Channel, Video
from wrolpi.collections import Collection
from wrolpi.conftest import probe_write_lock_is_held, production_like_sessions
from wrolpi.common import get_absolute_media_path, get_wrolpi_config, get_relative_to_media_directory
from wrolpi.downloader import Download, DownloadFrequency
from wrolpi.vars import PROJECT_DIR
@ -608,3 +609,38 @@ def test_get_custom_videos_directory(test_directory, test_wrolpi_config):
assert common.get_videos_directory() == (test_directory / 'custom/directory/videos')
assert (test_directory / 'custom/directory/videos').is_dir()
assert not (test_directory / 'videos').is_dir()
@pytest.mark.asyncio
async def test_video_modeler_does_not_hold_write_lock_during_ffprobe(async_client, test_session, video_factory):
"""Modeling must not hold the SQLite write lock while ffprobe runs.
`video_modeler` opened one write session per batch and `await`ed `get_ffprobe_json` -- an ffprobe
subprocess -- for up to 20 videos inside it. Every other writer on the box waits on that lock
and gives up after `busy_timeout` (30s). ffprobe belongs outside the transaction: read the
batch, probe the files, then write what was learned.
"""
import modules.videos as videos_module
from modules.videos import video_modeler
video = video_factory(with_video_file=True)
video.file_group.indexed = False
video.file_group.model = None
test_session.delete(video)
test_session.commit()
db_file = test_session.get_bind().url.database
lock_held_during_ffprobe = []
real_get_or_create_ffprobe_json = videos_module.get_or_create_ffprobe_json
async def probing_ffprobe(video_path):
lock_held_during_ffprobe.append(probe_write_lock_is_held(db_file))
return await real_get_or_create_ffprobe_json(video_path)
with production_like_sessions(test_session):
with mock.patch.object(videos_module, 'get_or_create_ffprobe_json', probing_ffprobe):
await video_modeler()
assert lock_held_during_ffprobe, 'ffprobe never ran, so the test proves nothing'
assert not any(lock_held_during_ffprobe), \
'the write lock was held while ffprobe ran; every other writer waits out busy_timeout'