Files
mtusi2026lab5/student_tests/lab5_pipeline_idempotency.py
T
2026-11-19 10:57:39 +03:00

315 lines
12 KiB
Python

#!/usr/bin/env python3
"""Prove version fencing and idempotent convergence under duplicate/crash faults."""
import json
import os
from pathlib import Path
import subprocess
import sys
import time
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check, run # noqa: E402
COMPOSE = ["docker", "compose", "--env-file", ".env.example"]
FAULTS = (
"FAULT_CRASH_AFTER_OUTBOX_COMMIT",
"FAULT_CRASH_BEFORE_SIDE_EFFECT",
"FAULT_CRASH_AFTER_SIDE_EFFECT",
"FAULT_CRASH_AFTER_RESULT_COMMIT",
)
def command(*args, capture=False, environment=None, check_result=True):
result = subprocess.run(
[*COMPOSE, *args], cwd=ROOT, text=True, capture_output=capture,
env=environment, check=check_result)
return result.stdout.strip() if capture else ""
def database_scalar(sql):
return command(
"exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger",
"-At", "-c", sql, capture=True)
def env_value(name):
for line in (ROOT / ".env.example").read_text(encoding="utf-8").splitlines():
if line.startswith(name + "="):
return line.split("=", 1)[1]
raise Failure("missing " + name + " in .env.example")
def compose_environment(**overrides):
environment = os.environ.copy()
for name in FAULTS:
environment[name] = "false"
environment.update({name: str(value) for name, value in overrides.items()})
return environment
def recreate(service, **overrides):
command(
"up", "-d", "--no-deps", "--force-recreate", service,
environment=compose_environment(**overrides))
def wait_http(client, seconds=120):
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
try:
client.call("GET", "/health/ready", schema="Health")
return
except Failure:
time.sleep(1)
raise Failure("API did not become ready")
def wait_database(sql, expected, seconds=120):
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
if database_scalar(sql) == expected:
return
time.sleep(0.5)
raise Failure("database condition did not become " + expected + ": " + sql)
def job_row(attachment_id, version):
row = database_scalar(
"SELECT id || '|' || attempt || '|' || "
"to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') "
"FROM attachment_jobs WHERE attachment_id='" + attachment_id
+ "' AND pipeline_version=" + str(version) + ";")
check(bool(row), "pipeline job is missing")
return row.split("|")
def publish(attachment_id, version):
job_id, attempt, created_at = job_row(attachment_id, version)
payload = json.dumps({
"schema_version": 1,
"job_id": job_id,
"type": "attachment.process.v1",
"attachment_id": attachment_id,
"pipeline_version": version,
"attempt": int(attempt),
"created_at": created_at,
}, separators=(",", ":"))
command(
"exec", "-T", "rabbitmq", "rabbitmqadmin",
"-u", env_value("RABBITMQ_USER"), "-p", env_value("RABBITMQ_PASSWORD"),
"publish", "exchange=" + env_value("ATTACHMENT_JOB_EXCHANGE"),
"routing_key=" + env_value("ATTACHMENT_JOB_ROUTING_KEY"),
"payload=" + payload,
'properties={"delivery_mode":2,"content_type":"application/json"}')
def promote(attachment_id, version):
subprocess.run(
["powershell", "-NoProfile", "-File", str(ROOT / "scripts" / "promote-pipeline.ps1"),
"-AttachmentId", attachment_id, "-PipelineVersion", str(version),
"-RequestedBy", "idempotency-test", "-EnvFile", ".env.example"],
cwd=ROOT, check=True, text=True)
def variant_snapshot(attachment_id, version):
return database_scalar(
"SELECT string_agg(name || ':' || sha256 || ':' || object_key, ',' ORDER BY name) "
"FROM attachment_variants WHERE attachment_id='" + attachment_id
+ "' AND pipeline_version=" + str(version) + ";")
def job_status(attachment_id, version):
return database_scalar(
"SELECT status || '|' || published || '|' || coalesce(last_error_code, '') "
"FROM attachment_jobs WHERE attachment_id='" + attachment_id
+ "' AND pipeline_version=" + str(version) + ";")
def variant_count(attachment_id, version):
return database_scalar(
"SELECT count(*) FROM attachment_variants WHERE attachment_id='"
+ attachment_id + "' AND pipeline_version=" + str(version) + ";")
def object_count(attachment_id):
script = (
'mc alias set local http://minio:9000 "$MINIO_ROOT_USER" '
'"$MINIO_ROOT_PASSWORD" >/dev/null && '
'mc ls --recursive "local/$S3_BUCKET/attachments/' + attachment_id
+ '/" 2>/dev/null | wc -l')
output = command(
"run", "--rm", "--no-deps", "--entrypoint", "/bin/sh",
"minio-init", "-c", script, capture=True)
return int(output.splitlines()[-1])
def wait_marker(attachment_id, column, seconds=60):
wait_database(
"SELECT " + column + "::text FROM attachment_jobs WHERE attachment_id='"
+ attachment_id + "' ORDER BY pipeline_version DESC LIMIT 1;", "true", seconds)
def wait_queue_empty(seconds=150):
deadline = time.monotonic() + seconds
marker = env_value("ATTACHMENT_JOB_QUEUE") + "\t0\t0"
while time.monotonic() < deadline:
listing = command(
"exec", "-T", "rabbitmq", "rabbitmqctl", "list_queues",
"name", "messages_ready", "messages_unacknowledged", capture=True)
if marker in listing:
return
time.sleep(0.5)
raise Failure("main queue did not drain")
def wait_worker_consumer(seconds=150):
deadline = time.monotonic() + seconds
queue = env_value("ATTACHMENT_JOB_QUEUE")
while time.monotonic() < deadline:
listing = command(
"exec", "-T", "rabbitmq", "rabbitmqctl", "list_queues",
"name", "consumers", capture=True)
for line in listing.splitlines():
columns = line.split("\t")
if len(columns) == 2 and columns[0] == queue and int(columns[1]) > 0:
return
time.sleep(1)
raise Failure("worker did not register a RabbitMQ consumer")
def assert_ready_invariants(attachment_id, expected_version):
row = database_scalar(
"SELECT pipeline_version || '|' || status FROM attachments WHERE id='"
+ attachment_id + "';")
check(row == str(expected_version) + "|ready", "active pipeline is not ready")
check(database_scalar(
"SELECT count(*) FROM attachment_variants WHERE attachment_id='" + attachment_id
+ "' AND pipeline_version=" + str(expected_version) + ";") == "3",
"active pipeline does not have exactly three variants")
check(database_scalar(
"SELECT count(*) FROM attachment_jobs WHERE attachment_id='" + attachment_id
+ "' AND status IN ('queued','processing');") == "0",
"acknowledged attachment still has non-terminal work")
def fault_case(client, alice, bob, chat, flag, marker, expected_objects_before_commit):
recreate(
"worker", **{flag: "true", "JOB_TIMEOUT": "5s", "JOB_LEASE_DURATION": "8s"})
wait_worker_consumer()
attachment, _ = client.attachment(alice, chat)
wait_marker(attachment["id"], marker, seconds=150)
check(database_scalar(
"SELECT count(*) FROM attachment_variants WHERE attachment_id='"
+ attachment["id"] + "';") == "0",
"result metadata committed before the injected pre-commit crash")
check(object_count(attachment["id"]) == expected_objects_before_commit,
"unexpected object count at injected fault point")
ready = client.wait_ready(bob, attachment, wait_seconds=150)
check(ready["status"] == "ready", "faulted job was lost")
assert_ready_invariants(attachment["id"], 2)
check(int(database_scalar(
"SELECT attempt FROM attachment_jobs WHERE attachment_id='"
+ attachment["id"] + "' AND pipeline_version=2;")) >= 2,
"crashed job was not recovered through a later managed attempt")
check(object_count(attachment["id"]) == 4,
"idempotent retry did not converge to one deterministic object set")
recreate("worker")
return attachment["id"]
def main():
client = Client("http://localhost:8080")
recreate("api", ATTACHMENT_PIPELINE_VERSION="1")
wait_http(client)
alice, bob, _, chat = client.bootstrap()
# Complete v1, promote to v2, then deliver newer work before stale v1 and
# duplicate v2 messages. Arrival order intentionally differs from creation order.
versioned, _ = client.attachment(alice, chat)
client.wait_ready(bob, versioned, wait_seconds=120)
version1 = variant_snapshot(versioned["id"], 1)
check(bool(version1), "v1 result is missing")
command("stop", "worker")
promote(versioned["id"], 2)
publish(versioned["id"], 2)
publish(versioned["id"], 2)
publish(versioned["id"], 1)
command("up", "-d", "--no-deps", "worker")
client.wait_ready(bob, versioned, wait_seconds=120)
wait_queue_empty()
version2 = variant_snapshot(versioned["id"], 2)
check(bool(version2) and version2 != version1,
"v2 did not produce a distinct immutable versioned result")
check(database_scalar(
"SELECT count(*) FROM attachment_variants WHERE attachment_id='"
+ versioned["id"] + "';") == "6", "versioned rows were lost or duplicated")
stable = version2
publish(versioned["id"], 1)
publish(versioned["id"], 2)
wait_queue_empty()
check(variant_snapshot(versioned["id"], 2) == stable,
"stale or duplicate delivery overwrote the active v2 result")
assert_ready_invariants(versioned["id"], 2)
# Promote a still-queued v1 intent to v2. The old job must become
# superseded, and its already-durable message must be a harmless no-op.
command("stop", "worker")
superseded, _ = client.attachment(alice, chat)
check(job_status(superseded["id"], 1).startswith("queued|"),
"new upload did not start as a queued v1 job")
promote(superseded["id"], 2)
check(job_status(superseded["id"], 1) == "superseded|true|superseded_by_v2",
"queued v1 job was not fenced as superseded by v2")
check(variant_count(superseded["id"], 1) == "0",
"superseded job already has v1 result rows")
publish(superseded["id"], 1)
command("up", "-d", "--no-deps", "worker")
client.wait_ready(bob, superseded, wait_seconds=120)
wait_queue_empty()
check(variant_count(superseded["id"], 1) == "0",
"stale superseded v1 delivery created v1 result rows")
check(variant_count(superseded["id"], 2) == "3",
"promoted v2 job did not produce exactly three variants")
assert_ready_invariants(superseded["id"], 2)
recreate("api", ATTACHMENT_PIPELINE_VERSION="2")
wait_http(client)
before_id = fault_case(
client, alice, bob, chat, "FAULT_CRASH_BEFORE_SIDE_EFFECT",
"before_effect_fault_injected", 0)
after_id = fault_case(
client, alice, bob, chat, "FAULT_CRASH_AFTER_SIDE_EFFECT",
"after_effect_fault_injected", 4)
# Existing level-4 fault point proves redelivery after result COMMIT but before ack.
recreate("worker", FAULT_CRASH_AFTER_RESULT_COMMIT="true")
wait_worker_consumer()
committed, _ = client.attachment(alice, chat)
wait_marker(committed["id"], "result_fault_injected")
client.wait_ready(bob, committed, wait_seconds=120)
wait_queue_empty()
assert_ready_invariants(committed["id"], 2)
recreate("worker")
confirmed = database_scalar(
"SELECT count(*) FROM attachments WHERE id IN ('" + versioned["id"] + "','"
+ superseded["id"] + "','" + before_id + "','" + after_id + "','"
+ committed["id"] + "') AND status='ready';")
check(confirmed == "5", "a confirmed task was lost")
print("PASS: version fencing, superseded, duplicate/reorder and "
"pre/post-side-effect crashes")
if __name__ == "__main__":
try:
run(main)
finally:
try:
recreate("api", ATTACHMENT_PIPELINE_VERSION="2")
recreate("worker")
except Exception:
pass