Spaces:
Running on CPU Upgrade

lighting-mvp / tests /test_api /test_regression_flows.py
DanielKretschmer's picture
WonderAnaconda
Lighting MVP
427634d
Raw History Blame Contribute Delete
10.4 kB
"""End-to-end regression tests for the three bug classes we shipped to
prod and then had to fix from a client report:
1. Cross-job contamination via shared artifact lookups (May 20).
2. Per-item crops disappearing on container rebuild because they
lived in /tmp (May 15).
3. Orphaned runs not being reaped between worker startups (May 14).
Each test drives the real FastAPI app via the integration `client`
fixture, with a fresh SQLite + tmpdir per test. They run in ~seconds
on every push, no Claude CLI subprocess involved.
"""
from __future__ import annotations
import io
import json
from datetime import datetime, timedelta, timezone
from pathlib import Path
from sqlalchemy import select
from app.core.enums import ArtifactStatus, StageName
from app.db.models import ArtifactORM, ItemImageORM, PipelineRunORM
# -------------------------------------------------------------------------
# Helpers (no Claude subprocess; we fabricate artifacts/runs in DB so the
# tests exercise the API + persistence layer without needing a real
# pipeline execution).
# -------------------------------------------------------------------------
async def _create_job(client, name="test job") -> str:
res = await client.post(
"/api/v1/jobs",
json={"job_name": name, "config_version": "v1.0", "created_by": "test"},
)
assert res.status_code == 201, res.text
return res.json()["job_id"]
async def _upload_pdf(client, job_id: str, filename: str, content: bytes) -> None:
res = await client.post(
f"/api/v1/jobs/{job_id}/files",
files={"files": (filename, io.BytesIO(content), "application/pdf")},
)
assert res.status_code == 200, res.text
def _session_factory(app):
return app.state.session_factory
async def _insert_matching_artifact(app, job_id: str, items: list[dict]) -> str:
"""Fabricate a completed matching artifact directly in the DB so we
don't need to actually run the pipeline."""
from app.core.ids import new_id
sf = _session_factory(app)
artifact_id = new_id()
async with sf() as session:
session.add(ArtifactORM(
artifact_id=artifact_id,
job_id=job_id,
stage=StageName.MATCHING.value,
status=ArtifactStatus.COMPLETED.value,
produced_by_module="test",
produced_by_version="test",
input_artifact_ids=[],
files=[],
errors=[],
warnings=[],
metrics={},
payload_inline={"matches": items},
))
await session.commit()
return artifact_id
# -------------------------------------------------------------------------
# 1. Multi-run on same job → distinct artifacts retrievable per-run
# -------------------------------------------------------------------------
async def test_each_pipeline_run_produces_distinct_artifact(client):
"""The May 20 contamination scenario in DB form. Two runs of the
same job MUST produce two distinct matching artifacts, both
addressable by ID. The /jobs/{id}/artifacts listing returns both.
The frontend bug was assuming `latest_for_stage` was the right
lookup for a specific run; that's only true when a job has at
most one run. This test documents the contract so frontend code
can be tested against it.
"""
app = client._transport.app
job_id = await _create_job(client, name="multi-run job")
a1 = await _insert_matching_artifact(app, job_id, items=[
{"item_id": "A1", "match_status": "matched", "selected_product_code": "EXO-RUN1-A1"},
])
a2 = await _insert_matching_artifact(app, job_id, items=[
{"item_id": "A1", "match_status": "matched", "selected_product_code": "EXO-RUN2-A1"},
{"item_id": "A2", "match_status": "matched", "selected_product_code": "EXO-RUN2-A2"},
])
assert a1 != a2
# Both artifacts exist and contain the expected items.
r1 = await client.get(f"/api/v1/artifacts/{a1}")
assert r1.status_code == 200
assert len(r1.json()["payload"]["matches"]) == 1
assert r1.json()["payload"]["matches"][0]["selected_product_code"] == "EXO-RUN1-A1"
r2 = await client.get(f"/api/v1/artifacts/{a2}")
assert r2.status_code == 200
assert len(r2.json()["payload"]["matches"]) == 2
assert r2.json()["payload"]["matches"][1]["selected_product_code"] == "EXO-RUN2-A2"
# Listing returns both.
arts_res = await client.get(f"/api/v1/jobs/{job_id}/artifacts")
assert arts_res.status_code == 200
matching_arts = [a for a in arts_res.json()["artifacts"] if a["stage"] == "matching"]
assert {a["artifact_id"] for a in matching_arts} == {a1, a2}
# -------------------------------------------------------------------------
# 2. Per-item crops survive on-disk wipe (DB-backed, not /tmp-backed)
# -------------------------------------------------------------------------
async def test_item_image_served_from_db_when_disk_wiped(client, tmp_path):
"""The May 15 scenario: HF wipes /tmp on every container rebuild,
so per-item crops stored under ``object_storage_root/<job>/pipeline/items/``
disappear. The fix persisted crops to the DB (ItemImageORM) and made
the image endpoint DB-first with disk fallback. This test wipes the
disk path and asserts the endpoint still returns the bytes."""
app = client._transport.app
sf = _session_factory(app)
job_id = await _create_job(client, name="image durability job")
run_id = "run-1-for-image-durability"
fake_jpeg = b"\xff\xd8\xff\xe0fake-jpeg-body"
async with sf() as session:
session.add(ItemImageORM(
job_id=job_id,
item_id="A1",
run_id=run_id,
mime_type="image/jpeg",
content=fake_jpeg,
))
await session.commit()
# Without run_id, endpoint returns most-recent crop for the (job, item).
img_res = await client.get(f"/api/v1/jobs/{job_id}/items/A1/image")
assert img_res.status_code == 200
assert img_res.content == fake_jpeg
# With run_id, endpoint returns the exact (job, item, run) crop.
img_res2 = await client.get(
f"/api/v1/jobs/{job_id}/items/A1/image?run_id={run_id}"
)
assert img_res2.status_code == 200
assert img_res2.content == fake_jpeg
miss_res = await client.get(f"/api/v1/jobs/{job_id}/items/UNKNOWN/image")
assert miss_res.status_code == 404
async def test_item_image_per_run_isolation(client):
"""The May 20 image-contamination scenario: two runs on the same job
crop items with the same item_id. Endpoint must return THIS run's
bytes, not the other run's. Without this test the contamination
would only be caught by visual inspection in the UI."""
app = client._transport.app
sf = _session_factory(app)
job_id = await _create_job(client, name="multi-run image isolation")
olympic_run = "run-olympic"
mackillop_run = "run-mackillop"
olympic_d1 = b"\xff\xd8\xff\xe0OLYMPIC-d1-body"
mackillop_d1 = b"\xff\xd8\xff\xe0MACKILLOP-d1-body"
async with sf() as session:
session.add(ItemImageORM(
job_id=job_id, item_id="D1", run_id=olympic_run,
mime_type="image/jpeg", content=olympic_d1,
))
session.add(ItemImageORM(
job_id=job_id, item_id="D1", run_id=mackillop_run,
mime_type="image/jpeg", content=mackillop_d1,
))
await session.commit()
# Each run gets its own crop back.
r_olympic = await client.get(
f"/api/v1/jobs/{job_id}/items/D1/image?run_id={olympic_run}"
)
assert r_olympic.status_code == 200
assert r_olympic.content == olympic_d1, (
"Olympic run should serve its own D1 crop, not Mackillop's"
)
r_mackillop = await client.get(
f"/api/v1/jobs/{job_id}/items/D1/image?run_id={mackillop_run}"
)
assert r_mackillop.status_code == 200
assert r_mackillop.content == mackillop_d1, (
"Mackillop run should serve its own D1 crop, not Olympic's"
)
# -------------------------------------------------------------------------
# 3. Orphan reaper marks stale runs as failed
# -------------------------------------------------------------------------
async def test_reap_orphans_marks_stale_running_runs_failed(client):
"""The May 14 scenario: workers wedging on hung Claude subprocesses
left runs in `running` state forever because reap_orphans only ran
on worker startup. We added a periodic reaper, but the underlying
function is what does the work. This test asserts the function
correctly flips runs whose heartbeat is past the deadline."""
from app.core.ids import new_id
from app.services.run_service import HEARTBEAT_DEAD_AFTER_SEC, RunService
app = client._transport.app
sf = _session_factory(app)
job_id = await _create_job(client, name="reaper test job")
# Two runs, one with a stale heartbeat (should be reaped) and one
# with a fresh one (should be left alone).
stale_run_id = new_id()
fresh_run_id = new_id()
now = datetime.now(timezone.utc)
stale_hb = now - timedelta(seconds=HEARTBEAT_DEAD_AFTER_SEC * 3)
fresh_hb = now - timedelta(seconds=5)
async with sf() as session:
session.add(PipelineRunORM(
run_id=stale_run_id,
job_id=job_id,
job_name="stale",
config_version="v1.0",
source_filenames=[],
status="running",
heartbeat_at=stale_hb,
current_stage="matching",
))
session.add(PipelineRunORM(
run_id=fresh_run_id,
job_id=job_id,
job_name="fresh",
config_version="v1.0",
source_filenames=[],
status="running",
heartbeat_at=fresh_hb,
current_stage="matching",
))
await session.commit()
async with sf() as session:
reaped = await RunService(session).reap_orphans()
assert reaped == 1, f"expected exactly 1 reaped run, got {reaped}"
async with sf() as session:
stale = await session.get(PipelineRunORM, stale_run_id)
fresh = await session.get(PipelineRunORM, fresh_run_id)
assert stale.status == "failed"
assert stale.error_code == "WORKER_CRASHED"
assert fresh.status == "running"
assert fresh.error_code is None