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

404 lines
13 KiB
Python

"""POST /api/v1/ingest -- raw JPEG body, metadata in headers."""
from __future__ import annotations
import hashlib
import io
import secrets
import struct
from pathlib import Path
import pytest
from conftest import needs_db
from sqlalchemy import select
from poorbird.api.deps import hash_credential, new_credential
from poorbird.config import get_settings
from poorbird.images import jpeg_dimensions, looks_like_jpeg
from poorbird.models.captures import Capture
from poorbird.models.devices import Device, DeviceCommand, DeviceStatus
from poorbird.models.ops import Job
def make_jpeg(width: int = 800, height: int = 600, noise: bytes = b"") -> bytes:
"""A byte string with a valid SOI and SOF0, enough to be parsed as a JPEG.
Not a decodable image: nothing on the ingest path decodes one, which is
the point of parsing the header rather than pulling in Pillow.
"""
out = io.BytesIO()
out.write(b"\xff\xd8\xff") # SOI + start of the next marker
out.write(b"\xe0") # APP0
out.write(struct.pack(">H", 16))
out.write(b"JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00")
out.write(b"\xff\xc0") # SOF0
out.write(struct.pack(">H", 17))
out.write(b"\x08") # precision
out.write(struct.pack(">HH", height, width))
out.write(b"\x03\x01\x11\x00\x02\x11\x01\x03\x11\x01")
out.write(b"\xff\xd9") # EOI
out.write(noise) # makes the sha256 differ between frames
return out.getvalue()
@pytest.fixture
def db():
from poorbird.db import SessionLocal
with SessionLocal() as session:
yield session
@pytest.fixture
def make_device(db):
"""Devices, their captures, their frames and their jobs -- all cleaned up.
Every device a test makes goes through here, so a test that needs a
second one does not have to hand-roll teardown and forget half of it.
"""
created: list[Device] = []
def make(name: str = "cam"):
token = new_credential()
d = Device(
device_uid=secrets.token_hex(6),
name=name,
token_hash=hash_credential(token),
enabled=True,
)
db.add(d)
db.commit()
db.refresh(d)
created.append(d)
return d, {"Authorization": f"Bearer {token}"}
yield make
root = get_settings().image_root
for d in created:
capture_ids = []
for cap in db.scalars(select(Capture).where(Capture.device_id == d.id)):
(root / cap.path).unlink(missing_ok=True)
capture_ids.append(str(cap.id))
# Ingest enqueues a thumbnail job per capture. Leaving those behind
# breaks test_queue.py, which claims from the same shared queue.
# Matched on payload so this never touches a job it did not create.
if capture_ids:
db.query(Job).filter(
Job.kind == "thumbnail",
Job.payload["capture_id"].astext.in_(capture_ids),
).delete(synchronize_session=False)
db.execute(Capture.__table__.delete().where(Capture.device_id == d.id))
db.execute(DeviceStatus.__table__.delete().where(DeviceStatus.device_id == d.id))
db.execute(DeviceCommand.__table__.delete().where(DeviceCommand.device_id == d.id))
existing = db.get(Device, d.id)
if existing is not None:
db.delete(existing)
db.commit()
@pytest.fixture
def device(make_device):
return make_device()
def post(client, auth, data=None, **headers):
h = {"Content-Type": "image/jpeg", **auth}
h.update({k.replace("_", "-"): str(v) for k, v in headers.items()})
return client.post(
"/api/v1/ingest", content=data if data is not None else make_jpeg(), headers=h
)
# --- the header parser, in isolation ----------------------------------------
def test_jpeg_dimensions_reads_the_header():
assert jpeg_dimensions(make_jpeg(1600, 1200)) == (1600, 1200)
assert jpeg_dimensions(make_jpeg(320, 240)) == (320, 240)
def test_jpeg_dimensions_gives_up_quietly_on_rubbish():
"""None is not an error: a frame we cannot measure is still worth keeping."""
assert jpeg_dimensions(b"\xff\xd8\xff") is None
assert jpeg_dimensions(b"\xff\xd8\xff\xe0\x00\x10" + b"\x00" * 14) is None
assert jpeg_dimensions(b"") is None
def test_jpeg_dimensions_terminates_on_hostile_input():
"""A zero-length segment must not loop forever."""
assert jpeg_dimensions(b"\xff\xd8\xff\xe0\x00\x00" + b"\x41" * 100) is None
assert jpeg_dimensions(b"\xff\xd8" + b"\xff" * 5000) is None
def test_magic_bytes_are_what_decide_it_is_a_jpeg():
assert looks_like_jpeg(make_jpeg())
assert not looks_like_jpeg(b"GIF89a")
assert not looks_like_jpeg(b"")
# --- the happy path ---------------------------------------------------------
@needs_db
def test_a_frame_is_stored_and_the_envelope_comes_back(client, device, db):
d, auth = device
r = post(client, auth, X_Trigger="radar", X_Burst_Id="a0b765-3-91204", X_Burst_Index=0)
assert r.status_code == 201
envelope = r.json()
assert envelope["capture_id"]
assert envelope["server_time"] > 1_700_000_000_000
assert envelope["commands"] == []
cap = db.scalar(select(Capture).where(Capture.device_id == d.id))
assert str(cap.id) == envelope["capture_id"]
assert cap.trigger == "radar"
assert cap.burst_id == "a0b765-3-91204"
assert cap.width == 800 and cap.height == 600
@needs_db
def test_the_bytes_land_on_disk_under_a_dated_path(client, device, db):
d, auth = device
body = make_jpeg(noise=secrets.token_bytes(8))
assert post(client, auth, data=body).status_code == 201
cap = db.scalar(select(Capture).where(Capture.device_id == d.id))
# Relative to the configured root, dated by received_at (SPEC 3.3).
assert cap.path == f"{cap.received_at:%Y/%m/%d}/{cap.id}.jpg"
assert not Path(cap.path).is_absolute()
on_disk = get_settings().image_root / cap.path
assert on_disk.is_file()
assert on_disk.read_bytes() == body
assert cap.bytes == len(body)
assert cap.sha256 == hashlib.sha256(body).hexdigest()
@needs_db
def test_no_part_file_is_left_behind(client, device, db):
d, auth = device
post(client, auth)
cap = db.scalar(select(Capture).where(Capture.device_id == d.id))
folder = (get_settings().image_root / cap.path).parent
assert not list(folder.glob(".*.part"))
@needs_db
def test_ingest_delivers_commands_like_heartbeat_does(client, device, db):
"""Same envelope on purpose: a capture that was going to happen anyway
also drains the queue at no extra cost (SPEC 4.1)."""
d, auth = device
db.add(DeviceCommand(device_id=d.id, type="capture_now"))
db.commit()
envelope = post(client, auth).json()
assert [c["type"] for c in envelope["commands"]] == ["capture_now"]
# --- the clock ---------------------------------------------------------------
@needs_db
def test_captured_at_zero_means_unsynced_not_1970(client, device, db):
"""Storing an epoch date would bury the frame at the bottom of every
chronological view forever."""
d, auth = device
post(client, auth, X_Captured_At=0)
cap = db.scalar(select(Capture).where(Capture.device_id == d.id))
assert cap.captured_at_device is None
assert cap.received_at is not None # server time stays authoritative
@needs_db
def test_a_synced_device_clock_is_recorded(client, device, db):
d, auth = device
post(client, auth, X_Captured_At=1758376267123)
cap = db.scalar(select(Capture).where(Capture.device_id == d.id))
assert cap.captured_at_device is not None
assert cap.captured_at_device.year == 2025 or cap.captured_at_device.year == 2026
@needs_db
def test_received_at_is_server_time_regardless(client, device, db):
"""SPEC C7. Even a device claiming to be in 1998."""
d, auth = device
post(client, auth, X_Captured_At=915148800000) # 1999
cap = db.scalar(select(Capture).where(Capture.device_id == d.id))
assert cap.received_at.year >= 2026
assert cap.path.startswith(f"{cap.received_at:%Y}")
# --- metadata ---------------------------------------------------------------
@needs_db
def test_pre_trigger_is_recorded(client, device, db):
"""1 means the frame predates the trigger, out of the PSRAM ring -- often
the good one, because the bird is still arriving."""
d, auth = device
post(client, auth, X_Pre_Trigger=1)
cap = db.scalar(select(Capture).where(Capture.device_id == d.id))
assert cap.pre_trigger is True
@needs_db
def test_radar_and_signal_metadata_are_recorded(client, device, db):
d, auth = device
post(
client,
auth,
X_Radar_State=2,
X_Radar_Distance_Cm=180,
X_Radar_Energy=77,
X_Frame_Seq=42,
X_Rssi=-61,
)
cap = db.scalar(select(Capture).where(Capture.device_id == d.id))
assert (cap.radar_state, cap.radar_distance_cm, cap.radar_energy) == (2, 180, 77)
assert cap.frame_seq == 42
assert cap.rssi == -61
db.refresh(d)
assert d.rssi == -61
assert d.last_seen_at is not None
@needs_db
def test_an_unknown_trigger_is_422(client, device):
_, auth = device
assert post(client, auth, X_Trigger="motion").status_code == 422
@needs_db
def test_an_out_of_range_radar_state_is_422(client, device):
_, auth = device
assert post(client, auth, X_Radar_State=9).status_code == 422
@needs_db
def test_the_trigger_defaults_when_the_header_is_absent(client, device, db):
d, auth = device
r = client.post(
"/api/v1/ingest", content=make_jpeg(), headers={"Content-Type": "image/jpeg", **auth}
)
assert r.status_code == 201
# --- retries ----------------------------------------------------------------
@needs_db
def test_the_same_frame_twice_is_one_capture(client, device, db):
"""The device retries an upload whose response was lost and cannot tell
that case from a real failure."""
d, auth = device
body = make_jpeg(noise=secrets.token_bytes(8))
first = post(client, auth, data=body).json()
second = post(client, auth, data=body).json()
assert second["capture_id"] == first["capture_id"]
assert len(db.scalars(select(Capture).where(Capture.device_id == d.id)).all()) == 1
@needs_db
def test_a_retry_still_receives_pending_commands(client, device, db):
"""The retry is still the device asking; it must not lose the queue."""
d, auth = device
body = make_jpeg(noise=secrets.token_bytes(8))
post(client, auth, data=body)
db.add(DeviceCommand(device_id=d.id, type="reboot"))
db.commit()
envelope = post(client, auth, data=body).json()
assert [c["type"] for c in envelope["commands"]] == ["reboot"]
@needs_db
def test_different_frames_are_separate_captures(client, device, db):
"""Frames in a burst differ by sensor noise alone, so they must not
collapse into one."""
d, auth = device
post(client, auth, data=make_jpeg(noise=b"frame-one"))
post(client, auth, data=make_jpeg(noise=b"frame-two"))
assert len(db.scalars(select(Capture).where(Capture.device_id == d.id)).all()) == 2
@needs_db
def test_one_devices_frame_does_not_deduplicate_against_anothers(client, device, make_device):
_, auth = device
_, other_auth = make_device("other")
body = make_jpeg(noise=b"identical")
a = post(client, auth, data=body).json()
b = post(client, other_auth, data=body).json()
assert a["capture_id"] != b["capture_id"]
# --- refusals ---------------------------------------------------------------
@needs_db
def test_an_empty_body_is_400(client, device):
_, auth = device
assert post(client, auth, data=b"").status_code == 400
@needs_db
def test_a_body_that_is_not_a_jpeg_is_400_not_401(client, device):
"""400 specifically: a 401 would make the device clear a good token."""
_, auth = device
r = post(client, auth, data=b"GIF89a" + b"\x00" * 100)
assert r.status_code == 400
@needs_db
def test_an_oversized_body_is_413(client, device):
"""Mirrors `request_body max_size 12MB` in the Caddyfile, because a limit
that only exists in the proxy is not a limit."""
_, auth = device
assert post(client, auth, data=make_jpeg() + b"\x00" * (12 * 1024 * 1024)).status_code == 413
@needs_db
def test_nothing_is_written_when_the_body_is_rejected(client, device, db):
"""No row, and nothing left on disk either."""
d, auth = device
before = set(get_settings().image_root.rglob("*.jpg"))
assert post(client, auth, data=b"not a jpeg at all").status_code == 400
assert db.scalars(select(Capture).where(Capture.device_id == d.id)).all() == []
assert set(get_settings().image_root.rglob("*.jpg")) == before
@needs_db
def test_ingest_requires_a_bearer_token(client):
assert (
client.post(
"/api/v1/ingest", content=make_jpeg(), headers={"Content-Type": "image/jpeg"}
).status_code
== 401
)
@needs_db
def test_a_disabled_device_cannot_ingest(client, device, db):
d, auth = device
d.enabled = False
db.commit()
assert post(client, auth).status_code == 403