feat: Carry audited pipeline replay and fault probes into lab6 (U4)

This commit is contained in:
Самохвалов Андрей Ремович
2026-10-02 15:12:27 +03:00
parent 8eab283f6f
commit e5d8796dc6
9 changed files with 547 additions and 1 deletions
+59
View File
@@ -0,0 +1,59 @@
"""Run in a one-shot publisher container to inject publish-before-confirm gap."""
import json
import os
from pathlib import Path
from uuid import UUID, uuid4
import pika
from src.db import pool
from src.publisher import QUEUE, job_payload, publish_batch
attachment_id = UUID(os.environ["FAULT_ATTACHMENT_ID"])
url = Path(os.environ["BROKER_URL_FILE"]).read_text(encoding="utf-8").strip()
broker = pika.BlockingConnection(pika.URLParameters(url))
try:
channel = broker.channel()
channel.queue_declare(queue=QUEUE, passive=True)
channel.confirm_delivery()
token = uuid4()
with pool().connection() as conn:
row = conn.execute(
"SELECT o.id,o.job_id,o.attempt,j.attachment_id,j.pipeline_version,j.created_at "
"FROM attachment_outbox o JOIN attachment_jobs j ON j.id=o.job_id "
"WHERE j.attachment_id=%s AND j.pipeline_version=1 AND o.attempt=1",
(attachment_id,),
).fetchone()
assert row is not None
claimed = conn.execute(
"UPDATE attachment_outbox SET claim_token=%s,"
"claim_expires_at=clock_timestamp()+interval '30 seconds' "
"WHERE id=%s AND claim_token IS NULL AND published_at IS NULL RETURNING id",
(token, row["id"]),
).fetchone()
assert claimed is not None
body = json.dumps(job_payload(row), separators=(",", ":")).encode()
channel.basic_publish(
exchange="", routing_key=QUEUE, mandatory=True, body=body,
properties=pika.BasicProperties(content_type="application/json", delivery_mode=2),
)
# Simulate process death after broker confirm, before PostgreSQL confirm.
with pool().connection() as conn:
conn.execute(
"UPDATE attachment_outbox SET claim_expires_at=clock_timestamp()-interval '1 second' "
"WHERE id=%s AND claim_token=%s AND published_at IS NULL",
(row["id"], token),
)
published = publish_batch(channel)
with pool().connection() as conn:
outbox = conn.execute(
"SELECT published_at IS NOT NULL AS confirmed FROM attachment_outbox "
"WHERE id=%s", (row["id"],),
).fetchone()
count = channel.queue_declare(queue=QUEUE, passive=True).method.message_count
assert published >= 1 and outbox["confirmed"] and count >= 2
print(json.dumps({"confirmed_after_republish": True, "queued_copies_before_worker": count}))
finally:
broker.close()
+188
View File
@@ -0,0 +1,188 @@
#!/usr/bin/env python3
"""Deterministic fault windows for the versioned attachment pipeline.
Run in a one-shot worker image while the normal worker and publisher are stopped.
All rows and objects are synthetic and stay in the educational volumes.
"""
import hashlib
import json
import os
import subprocess
import sys
import time
from io import BytesIO
from uuid import uuid4
from PIL import Image
from src.attachments import BUCKET, storage
from src.db import pool
from src.pipeline_jobs import (
claim_job, finish_attempt, queue_attachment, recover_expired, reserve_upload,
)
from src.replay import replay_failed
from src.reprocess import start_new_version
from src.worker import process_message
image = BytesIO()
Image.new("RGB", (320, 200), "#2765a8").save(image, format="PNG")
DATA = image.getvalue()
SHA = hashlib.sha256(DATA).hexdigest()
def create_case():
user_id, chat_id, attachment_id = uuid4(), uuid4(), uuid4()
staging_key = f"staging/{attachment_id}"
with pool().connection() as conn:
with conn.transaction():
conn.execute(
"INSERT INTO users (id,username,display_name,password_hash) VALUES (%s,%s,%s,%s)",
(user_id, f"fault_{user_id.hex[:20]}", "Pipeline fault fixture", "synthetic"),
)
conn.execute("INSERT INTO chats (id,title) VALUES (%s,%s)", (chat_id, "Pipeline fault fixture"))
conn.execute(
"INSERT INTO memberships (chat_id,user_id,position) VALUES (%s,%s,0)",
(chat_id, user_id),
)
reserve_upload(conn, attachment_id, staging_key)
storage().put_object(BUCKET, staging_key, BytesIO(DATA), len(DATA), content_type="image/png")
with pool().connection() as conn:
_, job_id = queue_attachment(
conn, attachment_id=attachment_id, chat_id=chat_id, owner_id=user_id,
filename="fixture.png", staging_key=staging_key,
object_key=f"originals/{attachment_id}", content_type="image/png",
size_bytes=len(DATA), sha256=SHA,
)
return attachment_id, job_id
def item(job_id, attempt=1):
return {"job_id": str(job_id), "attempt": attempt}
def state(attachment_id, version):
with pool().connection() as conn:
attachment = conn.execute(
"SELECT status,pipeline_version,sha256 FROM attachments WHERE id=%s", (attachment_id,)
).fetchone()
rows = conn.execute(
"SELECT name,sha256 FROM attachment_variants "
"WHERE attachment_id=%s AND pipeline_version=%s ORDER BY name",
(attachment_id, version),
).fetchall()
return attachment, {row["name"]: row["sha256"] for row in rows}
def assert_ready(attachment_id, version):
attachment, variants = state(attachment_id, version)
assert attachment["status"] == "ready" and attachment["pipeline_version"] == version
assert attachment["sha256"] == SHA
assert set(variants) == {"original", "thumbnail", "crop", "optimized"}
assert variants["original"] == SHA
return variants
def expire_and_recover(job_id):
with pool().connection() as conn:
conn.execute(
"UPDATE attachment_jobs SET lease_expires_at=clock_timestamp()-interval '1 second' "
"WHERE id=%s AND status='processing'",
(job_id,),
)
recovered = recover_expired(conn, max_attempts=5)
assert (job_id, "queued") in recovered
def crash(job_id, point):
child = subprocess.run(
[sys.executable, "-c", "from src.worker import process_message; "
f"process_message({{'job_id': '{job_id}', 'attempt': 1}})"],
env={**os.environ, "LAB5_FAULT_POINT": point, "LAB5_FAULT_JOB_ID": str(job_id)},
capture_output=True, text=True,
)
assert child.returncode == 72, (point, child.returncode, child.stderr)
def main():
results = {}
attachment, job = create_case()
crash(job, "after_result_commit_before_ack")
first = assert_ready(attachment, 1)
assert process_message(item(job)) == "duplicate_or_stale"
assert assert_ready(attachment, 1) == first
results["after_result_commit_before_ack_duplicate"] = "pass"
attachment, job = create_case()
crash(job, "after_claim_before_s3")
expire_and_recover(job)
assert process_message(item(job, 2)) == "ready"
assert_ready(attachment, 1)
results["before_side_effect_lease_recovery"] = "pass"
attachment, job = create_case()
crash(job, "after_s3_before_result_commit")
expire_and_recover(job)
assert process_message(item(job, 2)) == "ready"
assert_ready(attachment, 1)
results["after_s3_before_result_commit"] = "pass"
attachment, old_job = create_case()
assert process_message(item(old_job)) == "ready"
with pool().connection() as conn:
version, new_job = start_new_version(conn, attachment)
assert version == 2
assert process_message(item(old_job)) == "duplicate_or_stale"
assert process_message(item(new_job)) == "ready"
newer = assert_ready(attachment, 2)
assert process_message(item(old_job)) == "duplicate_or_stale"
assert assert_ready(attachment, 2) == newer
assert len(state(attachment, 1)[1]) == 4
results["duplicate_reorder_new_version"] = "pass"
attachment, job = create_case()
with pool().connection() as conn:
claimed = claim_job(conn, job, 1)
assert finish_attempt(
conn, job, claimed["lease_token"], max_attempts=5,
error_code="invalid_image", permanent=True,
) == "failed"
attempt = replay_failed(conn, job, "lab5-test", "verified synthetic replay")
assert attempt == 2
assert process_message(item(job, attempt)) == "ready"
assert_ready(attachment, 1)
with pool().connection() as conn:
count = conn.execute(
"SELECT count(*) AS n FROM attachment_job_replays WHERE job_id=%s", (job,)
).fetchone()["n"]
assert count == 1
results["failed_registry_operator_replay"] = "pass"
attachment, job = create_case()
with pool().connection() as conn:
claimed = claim_job(conn, job, 1)
assert finish_attempt(
conn, job, claimed["lease_token"], max_attempts=2,
delay_seconds=0.01, error_code="storage_unavailable",
) == "queued"
time.sleep(0.03)
with pool().connection() as conn:
claimed = claim_job(conn, job, 2)
assert claimed is not None
assert finish_attempt(
conn, job, claimed["lease_token"], max_attempts=2,
error_code="storage_unavailable",
) == "failed"
attempt = replay_failed(conn, job, "lab5-test", "retry budget reset after repair")
assert attempt == 3
assert process_message(item(job, attempt)) == "ready"
assert_ready(attachment, 1)
results["bounded_transient_retry_then_replay"] = "pass"
print(json.dumps(results, sort_keys=True))
if __name__ == "__main__":
main()
+45
View File
@@ -0,0 +1,45 @@
#!/usr/bin/env python3
"""Show that broker confirm without outbox confirmation safely republishes."""
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, arguments, check, run # noqa: E402
def compose(*args, input_data=None):
return subprocess.run(
["docker", "compose", *args], cwd=ROOT,
input=input_data, check=True,
)
def main():
args = arguments("Lab6 publish/confirm gap")
client = Client(args.base_url, args.ca_file)
compose("stop", "worker", "publisher")
attachment = None
try:
alice, bob, _eve, chat = client.bootstrap()
attachment, _original = client.attachment(alice, chat)
check(attachment["status"] == "queued", "upload was not queued")
source = (ROOT / "student-tests/publish_gap_inner.py").read_bytes()
compose(
"run", "--rm", "--no-deps", "-T",
"-e", f"FAULT_ATTACHMENT_ID={attachment['id']}", "publisher", "python", "-",
input_data=source,
)
finally:
compose("up", "-d", "publisher", "worker")
ready = client.wait_ready(bob, attachment)
check(ready["status"] == "ready", "republished job did not finish")
check(len(ready["variants"]) == 3, "duplicate delivery changed variant set")
print("PASS: confirmed broker copy republished after lost DB confirm; worker reached ready once")
if __name__ == "__main__":
run(main)