The transcode cache under concurrent plays and discards
The transcode cache (api/video/transcode_cache.py) is written by every web process: a play of a video the browser cannot decode starts a background conversion in a daemon thread (ensure_cached), and a photo deletion, rescan rebuild, probe repair or file re-key discards the video's copy (discard). Three things keep it consistent:
- One lock for the folder.
_lockedtakes an OS file lock on.transcode-cache.lockin the cache folder (librephotos.instance_lock.try_lock, so it holds across processes and threads and is dropped when a process dies). Claiming a conversion (count, make room, create), finishing one (_finish) and discarding a video run under it. - An output per conversion.
_claim_outputcreates the claim marker<hash>.mp4.claimwithO_EXCL, writes a fresh token into it, and creates the conversion's own output<hash>.mp4.<token>.part, which ffmpeg writes. The concurrency cap counts the.partoutputs, so a discard, which removes only the finished file and the marker, does not free a slot while ffmpeg still runs. - Publish by token.
_finishrenames the output to<hash>.mp4only while the marker holds the conversion's token, and deletes it otherwise. A conversion whose video was discarded meanwhile therefore never publishes, and never publishes another conversion's file.
_drop_stale_parts removes outputs not written for six hours and markers whose output is gone, so a killed worker does not keep its video uncacheable.
Up to 1.7.0 every conversion of a video wrote to <hash>.mp4.part, which was also the claim. After a discard the next play claimed the same name, and the first conversion's rename published the second one's half-written file; every serve refreshes a cached file's mtime, so the eviction never removed it. The cap was counted before the claim was created, so two plays at once both started a conversion.
The model is verification/caches/TranscodeCache.tla; the tests are api/tests/media_serving/test_transcode_cache_races.py.