Run the chroma-key placeholder check off the event loop (#4899)

* Run the chroma-key placeholder check off the event loop

_discard_if_chroma_key decoded every stored media image synchronously
inside an async method, so each check (about 15 to 35 ms for a 1024px
screenshot or box face) stalled the event loop and every other request or
scan task running on it. The decode now runs through asyncio.to_thread,
like the cover and logo work in the same handler.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015vP3HFKWQsJZv9F9SKeAWu

* Hold the file lock across the chroma-key check and delete

With the check awaited on a worker thread, a concurrent writer could
replace the file between the verdict and the delete, and the replacement
was then removed on the old file's verdict. The existence check, the
decode and the unlink now run under the path's lock, and a test replaces
the file mid-check to prove the new artwork survives.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015vP3HFKWQsJZv9F9SKeAWu

* Make the chroma-key replacement test independent of timing

The test slept 0.2s and hoped the writer had run by then; a slow writer
would let unlocked code pass. It now asserts the path lock is held during
the check before the writer starts, and that the writer cannot finish
while the check runs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015vP3HFKWQsJZv9F9SKeAWu

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Sam Dornan
2026-09-28 16:36:14 -04:00
committed by GitHub
parent 6d9438b456
commit 33c10f5d6c
2 changed files with 74 additions and 6 deletions

View File

@@ -250,14 +250,20 @@ class FSResourcesHandler(FSHandler):
Returns True when the file was discarded, so callers can treat the
artwork as missing (falling back to the dark placeholder).
"""
if not await self.file_exists(relative_path):
return False
full_path = self.validate_path(relative_path)
# Held from the check to the delete, so a file replaced while the check
# runs is never removed on the old file's verdict.
lock = await self._get_file_lock(str(full_path))
async with lock:
if not full_path.is_file():
return False
if not _is_chroma_key_placeholder(self.validate_path(relative_path)):
return False
# Decoding the full image would otherwise stall the event loop
if not await asyncio.to_thread(_is_chroma_key_placeholder, full_path):
return False
log.debug(f"Discarding chroma-key placeholder image {relative_path}")
await self.remove_file(relative_path)
log.debug(f"Discarding chroma-key placeholder image {relative_path}")
full_path.unlink()
return True
async def _discard_partial_file(self, relative_path: str) -> None:

View File

@@ -2,6 +2,7 @@ import asyncio
import errno
import os
import struct
import threading
import zlib
from io import BytesIO
from pathlib import Path
@@ -897,6 +898,67 @@ class TestChromaKeyDetection:
assert discarded is False
assert (tmp_path / rel).exists()
@pytest.mark.asyncio
async def test_discard_checks_the_image_off_the_event_loop(
self, handler: FSResourcesHandler, tmp_path
):
handler.base_path = tmp_path
rel = "roms/1/1/box2d_back/box2d_back.png"
self._write_image(tmp_path / rel, (85, 62, 152))
threads: list[threading.Thread] = []
def record_thread(_path: Path) -> bool:
threads.append(threading.current_thread())
return False
with patch(
"handler.filesystem.resources_handler._is_chroma_key_placeholder",
side_effect=record_thread,
):
await handler._discard_if_chroma_key(rel)
assert threads and threads[0] is not threading.main_thread()
@pytest.mark.asyncio
async def test_discard_keeps_a_file_replaced_during_the_check(
self, handler: FSResourcesHandler, tmp_path
):
handler.base_path = tmp_path
folder, name = "roms/1/1/box2d_back", "box2d_back.png"
self._write_image(tmp_path / folder / name, (0, 255, 0))
checking, release = threading.Event(), threading.Event()
def slow_check(_path: Path) -> bool:
checking.set()
release.wait(5)
return True
async def replace() -> None:
async with handler.write_file_streamed(path=folder, filename=name) as f:
await f.write(b"real artwork")
with patch(
"handler.filesystem.resources_handler._is_chroma_key_placeholder",
side_effect=slow_check,
):
discard = asyncio.create_task(
handler._discard_if_chroma_key(f"{folder}/{name}")
)
await asyncio.to_thread(checking.wait, 5)
lock = await handler._get_file_lock(
str(handler.validate_path(f"{folder}/{name}"))
)
assert lock.locked()
writer = asyncio.create_task(replace())
for _ in range(20):
await asyncio.sleep(0)
assert not writer.done()
release.set()
assert await discard is True
await writer
assert (tmp_path / folder / name).read_bytes() == b"real artwork"
@pytest.mark.asyncio
async def test_discard_missing_file_is_noop(
self, handler: FSResourcesHandler, tmp_path