Files
Thomas KarnerandClaude Opus 5 ec9ef9b3a6 Add the thumbnail worker, and stop tests leaking jobs (Phase 2)
Captures now get a WebP thumbnail: 400px on the long edge, written to
thumbs/<uuid>_400.webp (SPEC 3.3). /ingest enqueues the job in the same
transaction as the capture row, so the worker never sees a job for a capture
that was rolled back, and decoding stays off the request path - it is the one
genuinely expensive part of a capture, and the device is waiting with a burst
still to upload.

api/images.py moves up to poorbird/images.py. Both sides use it now, and a
worker importing from api would be the wrong way round. The split by cost
stays: everything the ingest path touches still reads nine bytes of JPEG
header, and Pillow appears only in the thumbnail half.

Handler behaviour is about which failures are worth retrying:

  - An undecodable frame returns rather than raises. The handler contract
    makes a raise mean "retry", and a frame that will never decode should not
    spend three attempts proving it. Logged, thumb_path left NULL.
  - A missing source file raises, because it should be there and a mount that
    has not come back yet is worth retrying for.
  - A capture deleted between enqueue and run is not an error. Retention will
    do that routinely in Phase 5.
  - A malformed payload is validated with a Pydantic model and recorded, not
    retried (SEC-003 applied to a job payload).
  - Never upscales: blowing a 100px frame up to 400px produces a blurry lie.
  - Fills in width/height when the ingest header parse could not. This is the
    first full decode, so it is the chance to fix that.

Verified end to end against a real device row, a real HTTP ingest and the
real worker dispatch path - claim, _run_one, complete - not just the handler
called directly: 1600x1200 JPEG in, WEBP 400x300 on disk, job marked done.
That run is what caught the rest of this commit.

Tests were leaking jobs into the shared queue, which broke test_queue.py once
/ingest started enqueuing. Three separate causes, all the same shape as the
teardown bug fixed in 269a6ea:

  - test_ingest cleaned captures but not their thumbnail jobs, and one test
    hand-rolled teardown for a second device and forgot half of it. Devices
    now come from a fixture that cleans frames, captures and jobs for every
    device a test makes.
  - test_queue claimed jobs without checking they were its own, so a leftover
    thumbnail job could be failed on its behalf, and one test claimed a
    second job to prove the first did not recur and then stranded it in
    'running' forever. It now enqueues at a priority that wins, asserts every
    claim is its own, and releases anything else it touches.

The suite now runs twice in a row leaving zero jobs behind, which is the
assertion that actually matters here.

Tests: 175 -> 193.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 14:49:15 +02:00

327 lines
9.4 KiB
Python

"""The thumbnail worker job.
Unlike the ingest path, this really decodes the frame, so these tests use
real JPEGs rather than the hand-built headers in test_ingest.py.
"""
from __future__ import annotations
import io
import secrets
import uuid
import pytest
from conftest import needs_db
from PIL import Image
from poorbird.config import get_settings
from poorbird.images import (
THUMB_EDGE,
UndecodableImage,
make_thumbnail,
relative_thumb_path,
)
from poorbird.models.captures import Capture
from poorbird.models.devices import Device
from poorbird.worker.handlers import HANDLERS
def real_jpeg(width: int = 1600, height: int = 1200) -> bytes:
"""An actual decodable JPEG, not just a plausible header."""
img = Image.new("RGB", (width, height))
for x in range(0, width, 64): # some structure, so it is not a solid block
for y in range(0, height, 64):
img.putpixel((x, y), (x % 256, y % 256, 128))
out = io.BytesIO()
img.save(out, format="JPEG", quality=85)
return out.getvalue()
# --- the encoder ------------------------------------------------------------
def test_the_long_edge_is_capped_and_the_aspect_ratio_is_kept(tmp_path):
source = tmp_path / "wide.jpg"
source.write_bytes(real_jpeg(1600, 1200))
data, original = make_thumbnail(source)
assert original == (1600, 1200)
with Image.open(io.BytesIO(data)) as thumb:
assert max(thumb.size) == THUMB_EDGE
assert thumb.size == (400, 300) # 4:3 preserved
def test_a_portrait_frame_is_capped_on_its_own_long_edge(tmp_path):
source = tmp_path / "tall.jpg"
source.write_bytes(real_jpeg(600, 1200))
data, _ = make_thumbnail(source)
with Image.open(io.BytesIO(data)) as thumb:
assert thumb.size == (200, 400)
def test_a_small_frame_is_never_upscaled(tmp_path):
"""Blowing a 100px frame up to 400px produces a blurry lie."""
source = tmp_path / "small.jpg"
source.write_bytes(real_jpeg(100, 80))
data, original = make_thumbnail(source)
assert original == (100, 80)
with Image.open(io.BytesIO(data)) as thumb:
assert thumb.size == (100, 80)
def test_the_output_is_webp(tmp_path):
source = tmp_path / "x.jpg"
source.write_bytes(real_jpeg(800, 600))
data, _ = make_thumbnail(source)
with Image.open(io.BytesIO(data)) as thumb:
assert thumb.format == "WEBP"
def test_a_thumbnail_is_much_smaller_than_its_source(tmp_path):
source = tmp_path / "x.jpg"
source.write_bytes(real_jpeg(1600, 1200))
data, _ = make_thumbnail(source)
assert len(data) < source.stat().st_size
def test_rubbish_raises_undecodable_rather_than_something_generic(tmp_path):
"""The distinction matters: undecodable is permanent, so the worker must
not spend three attempts rediscovering it."""
source = tmp_path / "not-an-image.jpg"
source.write_bytes(b"\xff\xd8\xff" + b"garbage" * 100)
with pytest.raises(UndecodableImage):
make_thumbnail(source)
def test_a_truncated_jpeg_is_also_undecodable(tmp_path):
source = tmp_path / "half.jpg"
source.write_bytes(real_jpeg(1600, 1200)[:200])
with pytest.raises(UndecodableImage):
make_thumbnail(source)
def test_the_thumb_name_carries_its_size(tmp_path):
"""The size is in the filename, so changing it writes a new name rather
than silently serving a different image from the old one."""
cid = uuid.uuid4()
assert relative_thumb_path(cid) == f"{cid}_400.webp"
# --- the handler ------------------------------------------------------------
@pytest.fixture
def db():
from poorbird.db import SessionLocal
with SessionLocal() as session:
yield session
@pytest.fixture
def capture(db):
"""A capture with its frame genuinely on disk, cleaned up either way."""
settings = get_settings()
device = Device(device_uid=secrets.token_hex(6), name="cam")
db.add(device)
db.commit()
db.refresh(device)
created: list[Capture] = []
def make(data: bytes | None = None, *, width=None, height=None):
cid = uuid.uuid4()
relative = f"2026/09/21/{cid}.jpg"
path = settings.image_root / relative
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(real_jpeg(1600, 1200) if data is None else data)
cap = Capture(
id=cid,
device_id=device.id,
path=relative,
sha256="0" * 64,
bytes=path.stat().st_size,
trigger="radar",
width=width,
height=height,
)
db.add(cap)
db.commit()
db.refresh(cap)
created.append(cap)
return cap
yield make
for cap in created:
(settings.image_root / cap.path).unlink(missing_ok=True)
if cap.thumb_path:
(settings.thumb_root / cap.thumb_path).unlink(missing_ok=True)
db.execute(Capture.__table__.delete().where(Capture.device_id == device.id))
db.delete(db.get(Device, device.id))
db.commit()
def run_job(db, capture_id) -> None:
HANDLERS["thumbnail"](db, {"capture_id": str(capture_id)})
@needs_db
def test_the_handler_writes_a_thumbnail_and_records_it(db, capture):
cap = capture()
assert cap.thumb_path is None
run_job(db, cap.id)
db.refresh(cap)
assert cap.thumb_path == f"{cap.id}_400.webp"
on_disk = get_settings().thumb_root / cap.thumb_path
assert on_disk.is_file()
with Image.open(on_disk) as thumb:
assert thumb.format == "WEBP"
assert max(thumb.size) == THUMB_EDGE
@needs_db
def test_it_fills_in_dimensions_ingest_could_not_read(db, capture):
"""Ingest reads the JPEG header, which can be absent or unparseable.
This is the first full decode, so it is the chance to fix that."""
cap = capture(width=None, height=None)
run_job(db, cap.id)
db.refresh(cap)
assert (cap.width, cap.height) == (1600, 1200)
@needs_db
def test_it_does_not_overwrite_dimensions_ingest_already_had(db, capture):
cap = capture(width=1600, height=1200)
run_job(db, cap.id)
db.refresh(cap)
assert (cap.width, cap.height) == (1600, 1200)
@needs_db
def test_running_it_twice_is_harmless(db, capture):
"""Jobs get retried, and a partially written thumbnail must not survive."""
cap = capture()
run_job(db, cap.id)
first = (get_settings().thumb_root / cap.thumb_path).read_bytes()
run_job(db, cap.id)
second = (get_settings().thumb_root / cap.thumb_path).read_bytes()
assert first == second
@needs_db
def test_no_part_file_is_left_behind(db, capture):
cap = capture()
run_job(db, cap.id)
assert not list(get_settings().thumb_root.glob(".*.part"))
@needs_db
def test_an_undecodable_frame_is_recorded_not_retried(db, capture):
"""Returning rather than raising is the point: the handler contract makes
a raise mean 'retry', and this will never decode."""
cap = capture(data=b"\xff\xd8\xff" + b"garbage" * 100)
run_job(db, cap.id) # must not raise
db.refresh(cap)
assert cap.thumb_path is None
@needs_db
def test_a_missing_source_raises_so_the_job_retries(db, capture):
"""The opposite case: the file should be there, and a mount that has not
come back yet is worth retrying for."""
cap = capture()
(get_settings().image_root / cap.path).unlink()
with pytest.raises(FileNotFoundError):
run_job(db, cap.id)
@needs_db
def test_a_capture_that_has_since_been_deleted_is_not_an_error(db):
"""Retention will do this routinely once Phase 5 exists."""
run_job(db, uuid.uuid4()) # must not raise
@needs_db
def test_a_malformed_payload_is_recorded_not_retried(db):
"""SEC-003. Raising would spend three attempts rediscovering that the
payload is still malformed."""
HANDLERS["thumbnail"](db, {})
HANDLERS["thumbnail"](db, {"capture_id": "not-a-uuid"})
HANDLERS["thumbnail"](db, {"wrong_key": 1})
# --- wired to ingest --------------------------------------------------------
@needs_db
def test_ingest_enqueues_the_job(client, db):
"""Off the request path: decoding to resize is the one genuinely
expensive part of a capture, and the device is waiting with a burst
still to upload."""
from sqlalchemy import text
from poorbird.api.deps import hash_credential, new_credential
token = new_credential()
device = Device(
device_uid=secrets.token_hex(6),
name="cam",
token_hash=hash_credential(token),
enabled=True,
)
db.add(device)
db.commit()
db.refresh(device)
r = client.post(
"/api/v1/ingest",
content=real_jpeg(800, 600),
headers={"Content-Type": "image/jpeg", "Authorization": f"Bearer {token}"},
)
assert r.status_code == 201
capture_id = r.json()["capture_id"]
queued = db.execute(
text(
"SELECT kind, status FROM jobs "
"WHERE kind = 'thumbnail' AND payload->>'capture_id' = :cid"
),
{"cid": capture_id},
).first()
assert queued is not None, "ingest must queue the thumbnail"
assert queued.status == "queued"
settings = get_settings()
cap = db.get(Capture, uuid.UUID(capture_id))
(settings.image_root / cap.path).unlink(missing_ok=True)
db.execute(
text("DELETE FROM jobs WHERE kind = 'thumbnail' AND payload->>'capture_id' = :cid"),
{"cid": capture_id},
)
db.execute(Capture.__table__.delete().where(Capture.device_id == device.id))
db.delete(db.get(Device, device.id))
db.commit()