Добавить версионированный 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
+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),
)