Добавить версионированный pipeline и проверку идемпотентности.

Трек 2 фиксирует дубль, устаревшую версию, падение до и после записи объекта и replay без второй копии результата.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-11-09 01:23:49 +03:00
co-authored by Cursor
parent 5617dca7d2
commit cf9d9a918f
10 changed files with 641 additions and 72 deletions
+6 -4
View File
@@ -34,13 +34,13 @@ def _public(row, variants=None) -> dict:
}
async def _variants(attachment_id) -> list:
async def _variants(attachment_id, pipeline_version: int) -> list:
async with db.require().acquire() as conn:
rows = await conn.fetch(
"""
SELECT name, content_type, size_bytes, width, height, sha256
FROM attachment_variants
WHERE attachment_id = $1 AND pipeline_version = 1
WHERE attachment_id = $1 AND pipeline_version = $2
ORDER BY CASE name
WHEN 'thumbnail' THEN 1
WHEN 'crop' THEN 2
@@ -49,6 +49,7 @@ async def _variants(attachment_id) -> list:
END
""",
attachment_id,
pipeline_version,
)
return [
{
@@ -64,7 +65,8 @@ async def _variants(attachment_id) -> list:
async def present(row) -> dict:
variants = await _variants(row["id"]) if row["status"] == "ready" else []
version = int(row["applied_pipeline_version"]) if "applied_pipeline_version" in row.keys() else 1
variants = await _variants(row["id"], version) if row["status"] == "ready" else []
return _public(row, variants)
@@ -175,7 +177,7 @@ async def get_for_member(attachment_id: str, user_id: str):
"""
SELECT a.id, a.chat_id, a.owner_id, a.filename, a.content_type,
a.size_bytes, a.sha256, a.object_key, a.status, a.error_code,
a.created_at, a.updated_at
a.applied_pipeline_version, a.created_at, a.updated_at
FROM attachments a
JOIN chat_members m ON m.chat_id = a.chat_id AND m.user_id = $2
WHERE a.id = $1
+223 -45
View File
@@ -155,10 +155,11 @@ async def claim(job_id: UUID, pipeline_version: int):
if row["status"] == "ready":
return "ready", row
attachment = await conn.fetchrow(
"SELECT status FROM attachments WHERE id = $1",
"SELECT status, applied_pipeline_version FROM attachments WHERE id = $1",
row["attachment_id"],
)
if attachment is not None and attachment["status"] == "ready":
applied = int(attachment["applied_pipeline_version"]) if attachment is not None else 0
if applied > int(row["pipeline_version"]):
await conn.execute(
"""
UPDATE attachment_jobs
@@ -338,15 +339,22 @@ async def _intent(key: str) -> None:
)
async def complete_job(job_id: UUID, lease_token: UUID, attachment_id: UUID, final_key: str, variants: list) -> bool:
async def complete_job(
job_id: UUID,
lease_token: UUID,
attachment_id: UUID,
final_key: str,
variants: list,
pipeline_version: int,
) -> bool:
async with db.require().acquire() as conn:
async with conn.transaction():
owned = await conn.fetchval(
owned = await conn.fetchrow(
"""
UPDATE attachment_jobs
SET status = 'ready', error_code = NULL, lease_token = NULL, lease_until = NULL, updated_at = now()
WHERE job_id = $1 AND lease_token = $2 AND status = 'processing'
RETURNING job_id
RETURNING pipeline_version
""",
job_id,
lease_token,
@@ -354,55 +362,71 @@ async def complete_job(job_id: UUID, lease_token: UUID, attachment_id: UUID, fin
if owned is None:
return False
current = await conn.fetchrow(
"SELECT status FROM attachments WHERE id = $1 FOR UPDATE",
"""
SELECT status, applied_pipeline_version
FROM attachments
WHERE id = $1
FOR UPDATE
""",
attachment_id,
)
if current is None:
raise PermanentJobError("invalid_image")
if current["status"] != "ready":
version = int(owned["pipeline_version"])
applied = int(current["applied_pipeline_version"])
superseded = applied > version
if not superseded:
await conn.execute(
"""
UPDATE attachments
SET status = 'ready', object_key = $2, error_code = NULL, updated_at = now()
WHERE id = $1 AND status <> 'ready'
SET status = 'ready',
object_key = CASE WHEN $2 = '' THEN object_key ELSE $2 END,
error_code = NULL,
applied_pipeline_version = $3,
updated_at = now()
WHERE id = $1 AND applied_pipeline_version <= $3
""",
attachment_id,
final_key,
version,
)
for variant in variants:
await conn.execute(
"""
INSERT INTO attachment_variants (
attachment_id, pipeline_version, name, content_type, size_bytes,
width, height, sha256, object_key
for variant in variants:
await conn.execute(
"""
INSERT INTO attachment_variants (
attachment_id, pipeline_version, name, content_type, size_bytes,
width, height, sha256, object_key
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
ON CONFLICT (attachment_id, pipeline_version, name) DO NOTHING
""",
attachment_id,
version,
variant["name"],
variant["content_type"],
variant["size_bytes"],
variant["width"],
variant["height"],
variant["sha256"],
variant["object_key"],
)
await conn.execute(
"UPDATE blob_writes SET committed = TRUE WHERE object_key = $1",
variant["object_key"],
)
if final_key:
await conn.execute(
"UPDATE blob_writes SET committed = TRUE WHERE object_key = $1",
final_key,
)
VALUES ($1, 1, $2, $3, $4, $5, $6, $7, $8)
ON CONFLICT (attachment_id, pipeline_version, name) DO NOTHING
""",
attachment_id,
variant["name"],
variant["content_type"],
variant["size_bytes"],
variant["width"],
variant["height"],
variant["sha256"],
variant["object_key"],
)
await conn.execute(
"UPDATE blob_writes SET committed = TRUE WHERE object_key = $1",
variant["object_key"],
)
await conn.execute(
"UPDATE blob_writes SET committed = TRUE WHERE object_key = $1",
final_key,
)
await conn.execute(
"""
INSERT INTO attachment_job_events (job_id, attachment_id, kind, detail)
VALUES ($1, $2, 'ready', 'variants committed')
VALUES ($1, $2, 'ready', $3)
""",
job_id,
attachment_id,
"superseded" if superseded else "variants committed",
)
return True
@@ -411,7 +435,8 @@ async def load_attachment(attachment_id: UUID):
async with db.require().acquire() as conn:
return await conn.fetchrow(
"""
SELECT id, filename, content_type, size_bytes, sha256, object_key, status
SELECT id, filename, content_type, size_bytes, sha256, object_key, status,
applied_pipeline_version
FROM attachments
WHERE id = $1
""",
@@ -442,11 +467,18 @@ async def _effect(row, lease: UUID) -> None:
attachment = await load_attachment(row["attachment_id"])
if attachment is None:
raise PermanentJobError("invalid_image")
if attachment["status"] == "ready":
committed = await complete_job(row["job_id"], lease, attachment["id"], attachment["object_key"], [])
version = int(row["pipeline_version"])
if int(attachment["applied_pipeline_version"]) > version:
committed = await complete_job(row["job_id"], lease, attachment["id"], "", [], version)
if not committed:
raise TransientJobError("processing_failed")
return
fault = await consume_fault()
if fault == "crash_before_s3":
logger.warning("injected crash before side effect job_id=%s", row["job_id"])
os._exit(1)
if fault == "fail_once":
raise PermanentJobError("processing_failed")
data = await s3.get_bytes(attachment["object_key"])
if len(data) != attachment["size_bytes"] or hashlib.sha256(data).hexdigest() != attachment["sha256"]:
raise PermanentJobError("invalid_image")
@@ -454,11 +486,11 @@ async def _effect(row, lease: UUID) -> None:
if attachment["object_key"] != final_key:
await _intent(final_key)
await s3.put_bytes(final_key, data, attachment["content_type"])
rendered = await asyncio.to_thread(pipeline.render, data, attachment["content_type"])
rendered = await asyncio.to_thread(pipeline.render, data, attachment["content_type"], version)
stored = []
for name, (payload, content_type, width, height) in rendered.items():
suffix = "webp" if content_type == "image/webp" else "jpg"
key = f"variants/{attachment['id']}/{name}.{suffix}"
key = f"variants/{attachment['id']}/v{version}/{name}.{suffix}"
await _intent(key)
await s3.put_bytes(key, payload, content_type)
stored.append(
@@ -472,13 +504,17 @@ async def _effect(row, lease: UUID) -> None:
"object_key": key,
}
)
if config.WORKER_CRASH_POINT == "after_s3":
if fault == "crash_after_s3" or config.WORKER_CRASH_POINT == "after_s3":
logger.warning("injected crash after object write before result commit job_id=%s", row["job_id"])
os._exit(1)
committed = await complete_job(row["job_id"], lease, attachment["id"], final_key, stored)
fresh = await load_attachment(attachment["id"])
if fresh is not None and int(fresh["applied_pipeline_version"]) > version:
stored = []
final_key = ""
committed = await complete_job(row["job_id"], lease, attachment["id"], final_key, stored, version)
if not committed:
raise TransientJobError("processing_failed")
if attachment["object_key"] != final_key:
if stored and attachment["object_key"] != final_key and final_key:
try:
await s3.delete_key(attachment["object_key"])
async with db.require().acquire() as conn:
@@ -487,12 +523,154 @@ async def _effect(row, lease: UUID) -> None:
logger.warning("staging object left for retention attachment_id=%s", attachment["id"])
async def consume_fault() -> str:
async with db.require().acquire() as conn:
row = await conn.fetchrow(
"""
UPDATE pipeline_faults
SET remaining = remaining - 1
WHERE id = 1 AND remaining > 0
RETURNING mode
"""
)
if row is None:
return ""
return row["mode"] or ""
async def arm_fault(mode: str, remaining: int) -> dict:
if mode not in ("", "crash_before_s3", "crash_after_s3", "fail_once"):
raise AppError(400, "invalid fault")
if remaining < 0 or remaining > 5:
raise AppError(400, "invalid fault")
async with db.require().acquire() as conn:
await conn.execute(
"""
INSERT INTO pipeline_faults (id, mode, remaining)
VALUES (1, $1, $2)
ON CONFLICT (id) DO UPDATE SET mode = EXCLUDED.mode, remaining = EXCLUDED.remaining
""",
mode,
remaining,
)
return {"mode": mode, "remaining": remaining}
async def bump_pipeline(attachment_id: UUID) -> dict:
created = datetime.now(timezone.utc)
async with db.require().acquire() as conn:
async with conn.transaction():
current = await conn.fetchval(
"SELECT COALESCE(MAX(pipeline_version), 0) FROM attachment_jobs WHERE attachment_id = $1",
attachment_id,
)
if current is None:
return {"result": "missing"}
exists = await conn.fetchval("SELECT 1 FROM attachments WHERE id = $1", attachment_id)
if exists is None:
return {"result": "missing"}
version = int(current) + 1
job_id = uuid4()
await conn.execute(
"""
INSERT INTO attachment_jobs (
job_id, attachment_id, pipeline_version, attempt, status,
next_attempt_at, created_at, updated_at
)
VALUES ($1, $2, $3, 1, 'queued', $4, $4, $4)
""",
job_id,
attachment_id,
version,
created,
)
await conn.execute(
"""
INSERT INTO attachment_job_events (job_id, attachment_id, kind, detail)
VALUES ($1, $2, 'queued', 'pipeline version bumped')
""",
job_id,
attachment_id,
)
kick_publish()
return {"result": "queued", "job_id": str(job_id), "pipeline_version": version}
async def redeliver(job_id: UUID) -> dict:
async with db.require().acquire() as conn:
row = await conn.fetchrow(
"""
SELECT job_id, attachment_id, pipeline_version, attempt, created_at, status
FROM attachment_jobs
WHERE job_id = $1
""",
job_id,
)
if row is None:
return {"result": "missing"}
await broker.publish_job(message_of(row))
return {
"result": "published",
"job_id": str(row["job_id"]),
"pipeline_version": int(row["pipeline_version"]),
"status": row["status"],
}
async def list_jobs(attachment_id: UUID) -> list:
async with db.require().acquire() as conn:
rows = await conn.fetch(
"""
SELECT job_id, pipeline_version, status, attempt
FROM attachment_jobs
WHERE attachment_id = $1
ORDER BY pipeline_version
""",
attachment_id,
)
variants = await conn.fetch(
"""
SELECT pipeline_version, name, sha256
FROM attachment_variants
WHERE attachment_id = $1
ORDER BY pipeline_version, name
""",
attachment_id,
)
applied = await conn.fetchval(
"SELECT applied_pipeline_version FROM attachments WHERE id = $1",
attachment_id,
)
return {
"applied_pipeline_version": applied,
"jobs": [
{
"job_id": str(row["job_id"]),
"pipeline_version": int(row["pipeline_version"]),
"status": row["status"],
"attempt": int(row["attempt"]),
}
for row in rows
],
"variants": [
{
"pipeline_version": int(row["pipeline_version"]),
"name": row["name"],
"sha256": row["sha256"],
}
for row in variants
],
}
async def replay_attachment(attachment_id: str) -> dict:
async with db.require().acquire() as conn:
job_id = await conn.fetchval(
"""
SELECT job_id FROM attachment_jobs
WHERE attachment_id = $1 AND pipeline_version = 1
WHERE attachment_id = $1 AND status = 'failed'
ORDER BY pipeline_version DESC
LIMIT 1
""",
UUID(attachment_id),
)
+8
View File
@@ -28,8 +28,12 @@ from app.routes import (
get_chat,
health_live,
health_ready,
lab_bump,
lab_fault,
lab_flags,
lab_jobs,
lab_metrics,
lab_redeliver,
lab_replay,
lab_sweep,
list_chats,
@@ -105,6 +109,10 @@ def build_app() -> Starlette:
Route("/api/v1/_lab/metrics", lab_metrics, methods=["GET"]),
Route("/api/v1/_lab/flags", lab_flags, methods=["POST"]),
Route("/api/v1/_lab/sweep", lab_sweep, methods=["POST"]),
Route("/api/v1/_lab/faults", lab_fault, methods=["POST"]),
Route("/api/v1/_lab/attachments/{attachment_id}/jobs", lab_jobs, methods=["GET"]),
Route("/api/v1/_lab/attachments/{attachment_id}/pipelines", lab_bump, methods=["POST"]),
Route("/api/v1/_lab/jobs/{job_id}/redeliver", lab_redeliver, methods=["POST"]),
Route("/api/v1/_lab/attachments/{attachment_id}/replay", lab_replay, methods=["POST"]),
],
exception_handlers={404: not_found_handler, AppError: app_error_handler},
+16 -10
View File
@@ -69,27 +69,33 @@ def _crop_square(image: Image.Image, side: int) -> Image.Image:
return cropped
def _jpeg(image: Image.Image) -> bytes:
def _jpeg(image: Image.Image, quality: int) -> bytes:
buffer = io.BytesIO()
image.save(buffer, format="JPEG", quality=90, optimize=True)
image.save(buffer, format="JPEG", quality=quality, optimize=True)
return buffer.getvalue()
def _webp(image: Image.Image) -> bytes:
# quality=80, method=6. EXIF is omitted because the saved image is a new RGB buffer.
def _webp(image: Image.Image, quality: int) -> bytes:
# method=6. EXIF is omitted because the saved image is a new RGB buffer.
buffer = io.BytesIO()
image.save(buffer, format="WEBP", quality=80, method=6)
image.save(buffer, format="WEBP", quality=quality, method=6)
return buffer.getvalue()
def render(data: bytes, content_type: str) -> dict:
"""Return thumbnail, crop and optimized payloads. Does not touch storage."""
def render(data: bytes, content_type: str, pipeline_version: int = 1) -> dict:
"""Return thumbnail, crop and optimized payloads. Does not touch storage.
Version 1 is the contract profile (JPEG 90, WebP 80). A later version lowers
quality so a stale writer cannot be confused with the newer bytes.
"""
jpeg_quality = 90 if pipeline_version <= 1 else 60
webp_quality = 80 if pipeline_version <= 1 else 50
image = _open_rgb(data, content_type)
thumb = _fit_down(image, 256)
crop = _crop_square(image, 128)
optimized = _fit_down(image, 1280)
return {
"thumbnail": ( _jpeg(thumb), "image/jpeg", thumb.size[0], thumb.size[1]),
"crop": (_jpeg(crop), "image/jpeg", crop.size[0], crop.size[1]),
"optimized": (_webp(optimized), "image/webp", optimized.size[0], optimized.size[1]),
"thumbnail": (_jpeg(thumb, jpeg_quality), "image/jpeg", thumb.size[0], thumb.size[1]),
"crop": (_jpeg(crop, jpeg_quality), "image/jpeg", crop.size[0], crop.size[1]),
"optimized": (_webp(optimized, webp_quality), "image/webp", optimized.size[0], optimized.size[1]),
}
+63 -1
View File
@@ -2,6 +2,8 @@ import base64
import binascii
import re
from uuid import UUID
from starlette.requests import Request
from starlette.responses import JSONResponse, Response
@@ -398,9 +400,10 @@ async def download_attachment(request: Request) -> Response:
"""
SELECT content_type, object_key
FROM attachment_variants
WHERE attachment_id = $1 AND pipeline_version = 1 AND name = $2
WHERE attachment_id = $1 AND pipeline_version = $2 AND name = $3
""",
row["id"],
int(row["applied_pipeline_version"]),
variant,
)
if found is None:
@@ -410,6 +413,65 @@ async def download_attachment(request: Request) -> Response:
return Response(payload, status_code=200, media_type=media_type, headers={"X-Request-Id": rid})
async def lab_fault(request: Request) -> Response:
rid = request.state.request_id
if not config.lab_mode():
return error_response(404, "not found", rid)
raw = await request.body()
body, err = parse_json_body(raw)
if err:
return error_response(400, err, rid)
assert body is not None
mode = body.get("mode", "")
remaining = body.get("remaining", 1)
if isinstance(remaining, bool) or not isinstance(remaining, int):
return error_response(400, "invalid fault", rid)
try:
armed = await jobs.arm_fault(mode, remaining)
except AppError as exc:
return error_response(exc.status, exc.message, rid)
return _json(armed, rid)
async def lab_jobs(request: Request) -> Response:
rid = request.state.request_id
if not config.lab_mode():
return error_response(404, "not found", rid)
attachment_id = request.path_params["attachment_id"]
if validate_uuid(attachment_id):
return error_response(400, "invalid attachment id", rid)
listed = await jobs.list_jobs(UUID(attachment_id))
if listed["applied_pipeline_version"] is None:
return error_response(404, "attachment not found", rid)
return _json(listed, rid)
async def lab_bump(request: Request) -> Response:
rid = request.state.request_id
if not config.lab_mode():
return error_response(404, "not found", rid)
attachment_id = request.path_params["attachment_id"]
if validate_uuid(attachment_id):
return error_response(400, "invalid attachment id", rid)
result = await jobs.bump_pipeline(UUID(attachment_id))
if result["result"] == "missing":
return error_response(404, "attachment not found", rid)
return _json(result, rid, 202)
async def lab_redeliver(request: Request) -> Response:
rid = request.state.request_id
if not config.lab_mode():
return error_response(404, "not found", rid)
job_id = request.path_params["job_id"]
if validate_uuid(job_id):
return error_response(400, "invalid job id", rid)
result = await jobs.redeliver(UUID(job_id))
if result["result"] == "missing":
return error_response(404, "attachment not found", rid)
return _json(result, rid, 202)
async def lab_replay(request: Request) -> Response:
rid = request.state.request_id
if not config.lab_mode():