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>
This commit is contained in:
Thomas KarnerandClaude Opus 5 committed 2026-09-21 14:49:15 +02:00
1 parent e326dd8226
commit ec9ef9b3a6
12 files changed
+603 -94

No files matched your search

+16 -8
View File
@@ -25,17 +25,18 @@ from fastapi import APIRouter, Body, Depends, Header, HTTPException, status
from pydantic import ValidationError
from sqlalchemy import select
from ...models.captures import Capture
from .. import ratelimit
from ..deps import DbDep, DeviceDep, SettingsDep
from ..envelope import build_envelope
from ..images import (
from ...images import (
MAX_IMAGE_BYTES,
jpeg_dimensions,
looks_like_jpeg,
relative_image_path,
write_atomically,
)
from ...models.captures import Capture
from ...worker.queue import enqueue
from .. import ratelimit
from ..deps import DbDep, DeviceDep, SettingsDep
from ..envelope import build_envelope
from ..schemas import Envelope, IngestMeta
log = logging.getLogger(__name__)
@@ -158,9 +159,9 @@ def ingest(
id=capture_id,
device_id=device.id,
path=relative,
# Filled in by the thumbnail worker, which does not exist yet. A NULL
# here means "no thumbnail yet", which the gallery must handle anyway:
# a capture is visible the moment it lands, not once it is processed.
# Filled in by the thumbnail job below. NULL means "not yet", which
# the gallery has to handle regardless: a capture is visible the
# moment it lands, not once it has been processed.
thumb_path=None,
sha256=digest,
width=dimensions[0] if dimensions else None,
@@ -185,6 +186,13 @@ def ingest(
if meta.rssi is not None:
device.rssi = meta.rssi
# Off the request path on purpose: decoding a frame to resize it is the
# one genuinely expensive thing about a capture, and the device is
# waiting on this response with a burst still to upload. Enqueued in the
# same transaction as the row, so the worker never sees a job for a
# capture that was rolled back.
enqueue(db, "thumbnail", {"capture_id": str(capture_id)})
envelope = build_envelope(db, device, capture_id=str(capture_id))
try:
@@ -1,10 +1,14 @@
"""Where capture bytes go, and the little we can learn from them.
"""Where capture bytes go, and what can be read back out of them.
Deliberately no imaging library. Everything here needs to work on the ingest
path, which runs once per frame and must not be the reason a burst is slow.
Decoding a JPEG to learn its dimensions would be wasteful when the header
already says so in nine bytes. Pillow belongs in the thumbnail worker, off the
request path, where the image has to be decoded anyway.
Lives at package level rather than under ``api`` because both sides use it:
the ingest route writes frames, and the worker reads them back to build
thumbnails. A worker importing from ``api`` would be the wrong way round.
Split by cost, deliberately. Everything above the thumbnail section runs on
the ingest path, once per frame, and must never be the reason a burst is
slow -- so it reads nine bytes of JPEG header rather than decoding an image.
Pillow appears only below, in the worker, where the frame has to be decoded
anyway.
"""
from __future__ import annotations
@@ -102,3 +106,66 @@ def write_atomically(destination: Path, data: bytes) -> None:
except BaseException:
temporary.unlink(missing_ok=True)
raise
# --- thumbnails -------------------------------------------------------------
#
# Worker only. Nothing above this line imports Pillow, so the ingest path
# never pays for it.
# 400px on the long edge, WebP, matching the /thumbs/<uuid>_400.webp pattern
# in SPEC 3.3. The number is in the filename, so changing it means writing to
# a new name rather than silently serving a differently-sized image from the
# old one.
THUMB_EDGE = 400
THUMB_QUALITY = 80
class UndecodableImage(Exception):
"""The bytes are not an image this build of Pillow can read.
Distinct from an I/O error on purpose: a frame that cannot be decoded
will never decode, so retrying is pointless and the worker should record
the fact rather than burn its attempts.
"""
def relative_thumb_path(capture_id: uuid.UUID) -> str:
"""``<uuid>_400.webp`` (SPEC 3.3), flat rather than dated.
Thumbnails are addressed by capture id alone and there are far fewer of
them per byte, so the dated tree that keeps the image directories to a
sane size buys nothing here.
"""
return f"{capture_id}_{THUMB_EDGE}.webp"
def make_thumbnail(source: Path) -> tuple[bytes, tuple[int, int]]:
"""Encode a WebP thumbnail. Returns the bytes and the SOURCE dimensions.
The source size is returned because the worker is the first place that
truly decodes the frame: ingest reads the JPEG header, which can be
absent or unparseable, and this is the chance to fill in what it missed.
"""
import io
from PIL import Image, UnidentifiedImageError
try:
with Image.open(source) as img:
img.load()
original = (img.width, img.height)
# Never upscale. A frame smaller than the thumbnail box should
# stay its own size rather than be blown up into a blurry one.
thumb = img.convert("RGB")
thumb.thumbnail((THUMB_EDGE, THUMB_EDGE), Image.Resampling.LANCZOS)
buffer = io.BytesIO()
thumb.save(buffer, format="WEBP", quality=THUMB_QUALITY, method=4)
return buffer.getvalue(), original
except (UnidentifiedImageError, OSError, ValueError) as exc:
# Pillow raises OSError for a truncated file as well as for a real
# I/O fault, and the two are not worth separating here: either way
# this frame is not going to produce a thumbnail.
raise UndecodableImage(f"{type(exc).__name__}: {exc}") from exc
+6 -6
View File
@@ -11,9 +11,11 @@ import logging
import sys
from datetime import UTC, datetime
_RESERVED = set(
logging.LogRecord("", 0, "", 0, "", None, None).__dict__
) | {"message", "asctime", "taskName"}
_RESERVED = set(logging.LogRecord("", 0, "", 0, "", None, None).__dict__) | {
"message",
"asctime",
"taskName",
}
class JsonFormatter(logging.Formatter):
@@ -37,9 +39,7 @@ def configure_logging(level: str = "INFO", fmt: str = "text") -> None:
if fmt == "json":
handler.setFormatter(JsonFormatter())
else:
handler.setFormatter(
logging.Formatter("%(asctime)s %(levelname)-8s %(name)s %(message)s")
)
handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)-8s %(name)s %(message)s"))
root = logging.getLogger()
root.handlers.clear()
+2 -6
View File
@@ -90,9 +90,7 @@ class Capture(Base):
# Soft reject. Drives retention -- see TODO Phase 5 and open question 8.
kept: Mapped[bool] = mapped_column(Boolean, default=True, server_default="true")
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now()
)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
observations: Mapped[list[Observation]] = relationship(
back_populates="capture", cascade="all, delete-orphan"
@@ -138,9 +136,7 @@ class Observation(Base):
bbox: Mapped[dict | None] = mapped_column(JSONB)
created_by: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"))
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now()
)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
)
+2 -6
View File
@@ -66,9 +66,7 @@ class BackupRun(Base):
__tablename__ = "backup_runs"
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
started_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now()
)
started_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
finished_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
status: Mapped[str] = mapped_column(String(16), default="running")
bytes: Mapped[int | None] = mapped_column(BigInteger)
@@ -106,7 +104,5 @@ class Job(Base):
locked_by: Mapped[str | None] = mapped_column(String(128))
last_error: Mapped[str | None] = mapped_column(Text)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now()
)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
finished_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
+2 -6
View File
@@ -46,9 +46,7 @@ class User(Base):
theme: Mapped[str] = mapped_column(String(16), default="light", server_default="'light'")
locale: Mapped[str] = mapped_column(String(8), default="de", server_default="'de'")
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now()
)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
last_login_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
@@ -57,9 +55,7 @@ class Session(Base):
id: Mapped[uuid.UUID] = mapped_column(Uuid(as_uuid=True), primary_key=True, default=uuid.uuid4)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now()
)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), index=True)
ip: Mapped[str | None] = mapped_column(String(45))
user_agent: Mapped[str | None] = mapped_column(String(255))
+76
View File
@@ -10,12 +10,18 @@ Phase 2 adds ``thumbnail``. Phase 5 adds ``backup``, ``retention`` and
from __future__ import annotations
import logging
import uuid
from collections.abc import Callable
from typing import Any
from pydantic import BaseModel, ValidationError
from sqlalchemy import text
from sqlalchemy.orm import Session
from ..config import get_settings
from ..images import UndecodableImage, make_thumbnail, relative_thumb_path, write_atomically
from ..models import Capture
log = logging.getLogger(__name__)
Handler = Callable[[Session, dict[str, Any]], None]
@@ -38,6 +44,76 @@ def _noop(session: Session, payload: dict[str, Any]) -> None:
log.info("noop job ran", extra={"payload": payload})
class ThumbnailPayload(BaseModel):
"""Validated job payload (REVIEW SEC-003).
Job payloads are JSONB and nothing stops a malformed one being enqueued,
so a handler that indexes straight into the dict fails with a KeyError
three retries later instead of saying what was wrong.
"""
capture_id: uuid.UUID
@handler("thumbnail")
def _thumbnail(session: Session, payload: dict[str, Any]) -> None:
"""Build the WebP thumbnail for one capture.
Enqueued by /ingest after the frame is on disk and in the same
transaction as the capture row, so by the time this runs both exist.
"""
try:
job = ThumbnailPayload.model_validate(payload)
except ValidationError as exc:
# Permanently wrong, not transient. Raising would spend three
# attempts rediscovering that the payload is still malformed.
log.error("thumbnail job payload is invalid", extra={"payload": payload, "error": str(exc)})
return
capture = session.get(Capture, job.capture_id)
if capture is None:
# Deleted between enqueue and now. Retention will do this routinely
# once Phase 5 exists, and it is not a failure.
log.info("thumbnail skipped, capture is gone", extra={"capture_id": str(job.capture_id)})
return
settings = get_settings()
source = settings.image_root / capture.path
if not source.is_file():
# The file should be there: ingest writes it before committing the
# row. Its absence is a real fault, and transient causes (a mount
# that has not come back yet) are worth retrying for.
raise FileNotFoundError(f"capture file missing: {source}")
try:
data, (width, height) = make_thumbnail(source)
except UndecodableImage as exc:
# A frame that cannot be decoded will never decode. Record it and
# finish, rather than retrying twice more to learn the same thing.
log.warning(
"capture could not be decoded, leaving it without a thumbnail",
extra={"capture_id": str(capture.id), "path": capture.path, "error": str(exc)},
)
return
relative = relative_thumb_path(capture.id)
write_atomically(settings.thumb_root / relative, data)
capture.thumb_path = relative
# Ingest reads dimensions from the JPEG header, which can be missing or
# unparseable. This is the first full decode, so fill in what it missed.
if capture.width is None or capture.height is None:
capture.width, capture.height = width, height
session.commit()
log.info(
"thumbnail written",
extra={"capture_id": str(capture.id), "path": relative, "bytes": len(data)},
)
@handler("prune_expired_commands")
def _prune_expired_commands(session: Session, payload: dict[str, Any]) -> None:
"""Expire commands the device never came back for.
+1 -2
View File
@@ -76,8 +76,7 @@ def claim(session: Session) -> dict[str, Any] | None:
def complete(session: Session, job_id: int) -> None:
session.execute(
text(
"UPDATE jobs SET status = 'done', finished_at = now(), "
"last_error = NULL WHERE id = :id"
"UPDATE jobs SET status = 'done', finished_at = now(), last_error = NULL WHERE id = :id"
),
{"id": job_id},
)