Prove versioned pipeline recovery and audited replay (U4)

This commit is contained in:
Самохвалов Андрей Ремович
2026-10-02 14:44:24 +03:00
parent 03899d790b
commit ab88c5ba1b
7 changed files with 372 additions and 1 deletions
+1 -1
View File
@@ -149,7 +149,7 @@ def claim_job(conn, job_id, delivery_attempt, lease_seconds=60):
def _reschedule_locked(conn, job, *, max_attempts, delay_seconds, error_code, permanent):
if max_attempts < 1 or delay_seconds < 0:
raise ValueError("invalid retry configuration")
failed = permanent or job["attempt"] >= max_attempts
failed = permanent or job["attempt"] - job["replay_start_attempt"] + 1 >= max_attempts
if failed:
code = error_code if permanent else "retry_exhausted"
conn.execute(
+64
View File
@@ -0,0 +1,64 @@
"""Explicit, audited replay of one failed current-version job."""
import argparse
from uuid import UUID
from .db import pool
def replay_failed(conn, job_id: UUID, operator: str, reason: str) -> int:
if not 1 <= len(operator) <= 80 or not 1 <= len(reason) <= 200:
raise ValueError("operator and reason are required")
with conn.transaction():
job = conn.execute(
"SELECT j.*,a.status AS attachment_status,"
"a.pipeline_version AS current_pipeline_version "
"FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id "
"WHERE j.id=%s FOR UPDATE OF j,a",
(job_id,),
).fetchone()
if (job is None or job["status"] != "failed" or
job["pipeline_version"] != job["current_pipeline_version"] or
job["attachment_status"] != "failed"):
raise ValueError("only a failed current-version job can be replayed")
attempt = job["attempt"] + 1
conn.execute(
"UPDATE attachment_jobs SET status='queued',attempt=%s,replay_start_attempt=%s,"
"next_attempt_at=clock_timestamp(),error_code=NULL,updated_at=clock_timestamp() "
"WHERE id=%s",
(attempt, attempt, job_id),
)
conn.execute(
"UPDATE attachments SET status='queued',error_code=NULL,updated_at=clock_timestamp() "
"WHERE id=%s AND pipeline_version=%s",
(job["attachment_id"], job["pipeline_version"]),
)
conn.execute(
"INSERT INTO attachment_outbox (job_id,attempt) VALUES (%s,%s)",
(job_id, attempt),
)
conn.execute(
"INSERT INTO attachment_job_replays "
"(job_id,previous_attempt,new_attempt,previous_error_code,operator_name,reason) "
"VALUES (%s,%s,%s,%s,%s,%s)",
(job_id, job["attempt"], attempt, job["error_code"], operator, reason),
)
return attempt
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("job_id", type=UUID)
parser.add_argument("--operator", required=True)
parser.add_argument("--reason", required=True)
args = parser.parse_args()
try:
with pool().connection() as conn:
attempt = replay_failed(conn, args.job_id, args.operator, args.reason)
except ValueError as exc:
parser.error(str(exc))
print(f"Queued job {args.job_id} attempt {attempt}")
if __name__ == "__main__":
main()
+57
View File
@@ -0,0 +1,57 @@
"""Start a new pipeline version from a verified, already ready original."""
import argparse
from uuid import UUID, uuid4
from .db import pool
def start_new_version(conn, attachment_id: UUID) -> tuple[int, UUID]:
with conn.transaction():
row = conn.execute(
"SELECT * FROM attachments WHERE id=%s FOR UPDATE", (attachment_id,)
).fetchone()
if row is None or row["status"] != "ready":
raise ValueError("only a ready attachment can start a new version")
original = conn.execute(
"SELECT object_key,size_bytes,sha256 FROM attachment_variants "
"WHERE attachment_id=%s AND pipeline_version=%s AND name='original'",
(attachment_id, row["pipeline_version"]),
).fetchone()
if (original is None or original["object_key"] != row["object_key"] or
original["size_bytes"] != row["size_bytes"] or
original["sha256"] != row["sha256"]):
raise ValueError("verified original is missing")
version = row["pipeline_version"] + 1
job_id = uuid4()
conn.execute(
"UPDATE attachments SET pipeline_version=%s,status='queued',error_code=NULL,"
"updated_at=clock_timestamp() WHERE id=%s",
(version, attachment_id),
)
conn.execute(
"INSERT INTO attachment_jobs (id,attachment_id,pipeline_version) "
"VALUES (%s,%s,%s)",
(job_id, attachment_id, version),
)
conn.execute(
"INSERT INTO attachment_outbox (job_id,attempt) VALUES (%s,1)",
(job_id,),
)
return version, job_id
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("attachment_id", type=UUID)
args = parser.parse_args()
try:
with pool().connection() as conn:
version, job_id = start_new_version(conn, args.attachment_id)
except ValueError as exc:
parser.error(str(exc))
print(f"Queued attachment {args.attachment_id} version {version} job {job_id}")
if __name__ == "__main__":
main()
+10
View File
@@ -104,6 +104,13 @@ def _delay(attempt: int) -> float:
return base + random.uniform(0, base / 2)
def _fault(point: str, job_id) -> None:
"""Test-only process death at a named durable boundary for one job."""
if (os.environ.get("LAB5_FAULT_POINT") == point and
os.environ.get("LAB5_FAULT_JOB_ID") == str(job_id)):
os._exit(72)
@contextmanager
def _deadline(seconds: int):
def expired(_signal, _frame):
@@ -124,13 +131,16 @@ def process_message(item: dict) -> str:
if job is None:
return "duplicate_or_stale"
token = job["lease_token"]
_fault("after_claim_before_s3", job["id"])
try:
with _deadline(LEASE_SECONDS):
data = _source_bytes(job)
variants = render(data, job["content_type"])
stored = _write_variants(job, variants)
_fault("after_s3_before_result_commit", job["id"])
with pool().connection() as conn:
current = complete_job(conn, job["id"], token, stored)
_fault("after_result_commit_before_ack", job["id"])
if current and job["staging_key"]:
try:
storage().remove_object(BUCKET, job["staging_key"])