на оценку 5

This commit is contained in:
2026-11-10 16:21:46 +03:00
parent 276dbdad8a
commit 7110afc598
170 changed files with 21149 additions and 30 deletions
+105
View File
@@ -0,0 +1,105 @@
#!/usr/bin/env python3
"""Grade-3 asynchronous durability scenario against the local Compose stack."""
import hashlib
import subprocess
import time
from pathlib import Path
from client import Client, arguments, check, run
from image_probe import jpeg_size
ROOT = Path(__file__).resolve().parents[1]
def compose(*args):
command = ["docker", "compose"]
if (ROOT / ".env").exists():
command += ["--env-file", ".env"]
command += list(args)
subprocess.run(command, cwd=ROOT, check=True,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
def sql(statement):
command = ["docker", "compose"]
if (ROOT / ".env").exists():
command += ["--env-file", ".env"]
command += ["exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-Atc", statement]
return subprocess.run(command, cwd=ROOT, check=True, text=True,
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL).stdout.strip()
def main():
args = arguments("Lab5 worker-stop and broker-restart durability scenario")
client = Client(args.base_url, args.ca_file)
compose("stop", "worker")
try:
alice, bob, _, chat = client.bootstrap()
attachment, original = client.attachment(alice, chat)
linked = client.message(alice, chat, "", attachments=[attachment["id"]])["json"]
check(linked["attachment_ids"] == [attachment["id"]], "queued attachment was not linkable")
client.call("GET", "/api/v1/attachments/" + attachment["id"] + "/content", 409, actor=bob)
# Accepted staging, DB intent and durable queue must survive both API and
# broker restart while no worker is available.
compose("restart", "api", "broker")
compose("up", "-d", "--wait", "api", "broker")
compose("restart", "dispatcher")
snapshot = client.call("GET", "/api/v1/attachments/" + attachment["id"], actor=bob, schema="Attachment")["json"]
check(snapshot["status"] in ("queued", "processing"), "accepted job disappeared or failed during restart")
compose("start", "worker")
ready = client.wait_ready(bob, snapshot)
downloaded = client.call("GET", "/api/v1/attachments/" + attachment["id"] + "/content", actor=bob)
check(downloaded["bytes"] == original, "original changed after asynchronous recovery")
variants = [item for item in ready["variants"] if item["name"] == "thumbnail"]
check(len(variants) == 1, "recovery did not produce exactly one thumbnail")
variant = variants[0]
thumbnail = client.call("GET", "/api/v1/attachments/" + attachment["id"] + "/content?variant=thumbnail", actor=bob)
check(hashlib.sha256(thumbnail["bytes"]).hexdigest() == variant["sha256"], "thumbnail checksum mismatch")
check(jpeg_size(thumbnail["bytes"]) == (256, 160), "thumbnail dimensions mismatch")
# Force a redelivery of the same logical job. Deterministic keys and the
# variant primary key must turn it into the same effect, not a duplicate.
attachment_id = attachment["id"]
sql("UPDATE attachment_jobs SET status='queued', published_at=NULL, error_code=NULL WHERE attachment_id='" + attachment_id + "'")
deadline = time.monotonic() + 15
while time.monotonic() < deadline:
if sql("SELECT status FROM attachment_jobs WHERE attachment_id='" + attachment_id + "'") == "succeeded":
break
time.sleep(0.2)
else:
raise AssertionError("redelivered job did not finish")
count = sql("SELECT count(*) FROM attachment_variants WHERE attachment_id='" + attachment_id + "' AND name='thumbnail'")
check(count == "1", "redelivery created duplicate variants")
after_duplicate = client.call("GET", "/api/v1/attachments/" + attachment_id, actor=bob, schema="Attachment")["json"]
repeated = [item for item in after_duplicate["variants"] if item["name"] == "thumbnail"]
check(len(repeated) == 1 and repeated[0]["sha256"] == variant["sha256"], "redelivery changed the logical result")
# A transient storage failure is retried a bounded number of times and
# ends with a stable, non-sensitive API error code.
compose("stop", "worker")
failed_attachment, _ = client.attachment(alice, chat)
failed_id = failed_attachment["id"]
client.message(alice, chat, "", attachments=[failed_id])
sql("UPDATE attachments SET staging_key='staging/" + failed_id + "/missing' WHERE id='" + failed_id + "'")
compose("start", "worker")
deadline = time.monotonic() + 20
while time.monotonic() < deadline:
failed_snapshot = client.call("GET", "/api/v1/attachments/" + failed_id, actor=bob, schema="Attachment")["json"]
if failed_snapshot["status"] == "failed":
break
time.sleep(0.2)
else:
raise AssertionError("job did not reach failed after bounded retries")
check(failed_snapshot["error_code"] == "retry_exhausted", "unsafe or unexpected final error code")
retry_state = sql("SELECT attempt || ':' || status FROM attachment_jobs WHERE attachment_id='" + failed_id + "'")
check(retry_state == "5:failed", "job did not stop at configured retry limit")
client.call("GET", "/api/v1/attachments/" + failed_id + "/content", 409, actor=bob)
print("PASS: durable recovery, idempotent redelivery and bounded final failure verified.")
finally:
compose("up", "-d", "api", "broker", "dispatcher", "worker")
if __name__ == "__main__":
run(main)
+100
View File
@@ -0,0 +1,100 @@
#!/usr/bin/env python3
"""Black-box attachment validation and exact contract-boundary checks."""
import os
import struct
import zlib
from attachment_memory import cleanup, noisy_png, png_chunk
from client import Client, check, run
MAX_BYTES = 10 * 1024 * 1024
def exact_size_png(sample, target_size=MAX_BYTES):
check(sample.endswith(png_chunk(b"IEND", b"")), "sample PNG has no final IEND")
prefix, iend = sample[:-12], sample[-12:]
filler_size = target_size - len(prefix) - len(iend) - 12
check(filler_size >= 0, "sample PNG is larger than boundary")
result = prefix + png_chunk(b"ruSt", bytes(filler_size)) + iend
check(len(result) == target_size, "exact-size PNG construction failed")
return result
def exact_pixel_png(width=10_000, height=4_000):
compressor = zlib.compressobj(level=9)
row = bytes(1 + width * 3)
parts = []
for _ in range(height):
chunk = compressor.compress(row)
if chunk:
parts.append(chunk)
parts.append(compressor.flush())
return (
b"\x89PNG\r\n\x1a\n"
+ png_chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0))
+ png_chunk(b"IDAT", b"".join(parts))
+ png_chunk(b"IEND", b"")
)
def config_only_png(width, height):
return (
b"\x89PNG\r\n\x1a\n"
+ png_chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0))
)
def upload(client, actor, chat, filename, payload, expected, schema=None):
return client.call(
"POST",
"/api/v1/chats/%s/attachments?filename=%s" % (chat["id"], filename),
expected,
actor=actor,
raw=payload,
headers={"Content-Type": "image/png"},
schema=schema,
)
def main():
client = Client(os.environ.get("BASE_URL"), None, timeout=30)
alice, bob, eve, chat = client.bootstrap()
users = [alice["id"], bob["id"], eve["id"]]
sample = open(os.path.join(os.path.dirname(__file__), "fixtures", "sample.png"), "rb").read()
try:
boundary = exact_size_png(sample)
response = upload(client, alice, chat, "exact-10mib.png", boundary, 202, "Attachment")
attachment = client.wait_ready(alice, response["json"], wait_seconds=90)
check(attachment["size_bytes"] == MAX_BYTES, "10 MiB boundary size changed")
downloaded = client.call(
"GET", "/api/v1/attachments/%s/content" % attachment["id"],
200, actor=alice,
)["bytes"]
check(downloaded == boundary, "10 MiB original changed after round trip")
pixels = exact_pixel_png()
pixel_response = upload(client, alice, chat, "exact-40m-pixels.png", pixels, 202, "Attachment")
client.wait_ready(alice, pixel_response["json"], wait_seconds=90)
upload(client, alice, chat, "over-pixels.png", config_only_png(20_000, 10_000), 413)
upload(client, alice, chat, "truncated.png", sample[:33], 415)
corrupted = noisy_png()
check(len(corrupted) > 70_000, "corruption fixture is too small")
corrupted = bytearray(corrupted)
corrupted[70_000] ^= 0xff
upload(client, alice, chat, "corrupt-after-prefix.png", bytes(corrupted), 415)
upload(client, alice, chat, "%20%20%20", sample, 400)
upload(client, alice, chat, "c1%C2%85.png", sample, 400)
upload(client, alice, chat, "invalid-%FF.png", sample, 400)
print("PASS: exact byte/pixel boundaries, complete decode, and filename validation are correct.")
finally:
cleanup(chat["id"], users)
if __name__ == "__main__":
run(main)
+149
View File
@@ -0,0 +1,149 @@
#!/usr/bin/env python3
"""Concurrent real PNG uploads with Docker API-container memory sampling."""
import concurrent.futures
import json
import os
import struct
import subprocess
import threading
import time
import uuid
import zlib
from client import Client, check, run
def png_chunk(kind, payload):
return struct.pack(">I", len(payload)) + kind + payload + struct.pack(">I", zlib.crc32(kind + payload))
def noisy_png(width=2048, height=1024):
rows = bytearray()
for _ in range(height):
rows.append(0)
rows.extend(os.urandom(width * 3))
return (
b"\x89PNG\r\n\x1a\n"
+ png_chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0))
+ png_chunk(b"IDAT", zlib.compress(bytes(rows), level=0))
+ png_chunk(b"IEND", b"")
)
def bytes_from_docker(value):
number, unit = value.split()[0], value.split()[0][-3:]
if unit in {"KiB", "MiB", "GiB"}:
number = value.split()[0][:-3]
else:
unit = "B"
factor = {"B": 1, "KiB": 1024, "MiB": 1024**2, "GiB": 1024**3}[unit]
return int(float(number) * factor)
def api_container_ids():
result = subprocess.run(
["docker", "compose", "ps", "-q", "api"],
check=True, text=True, capture_output=True,
)
return [line for line in result.stdout.splitlines() if line]
def sample_memory(container_ids, stop_event, peaks):
while not stop_event.is_set():
result = subprocess.run(
["docker", "stats", "--no-stream", "--format", "{{.Name}}\t{{.MemUsage}}", *container_ids],
check=False, text=True, capture_output=True,
)
if result.returncode == 0:
for line in result.stdout.splitlines():
name, usage = line.split("\t", 1)
current = bytes_from_docker(usage.split(" / ", 1)[0])
peaks[name] = max(peaks.get(name, 0), current)
stop_event.wait(0.05)
def cleanup(chat_id, user_ids):
object_script = (
'root_user="$(cat /run/secrets/minio_root_user)"\n'
'root_password="$(cat /run/secrets/minio_root_password)"\n'
'mc alias set local http://minio:9000 "$root_user" "$root_password" --api S3v4 >/dev/null\n'
'mc rm --recursive --force "local/${S3_BUCKET}/attachments/' + chat_id + '/" >/dev/null 2>&1 || true\n'
)
subprocess.run(
["docker", "compose", "run", "--rm", "--entrypoint", "/bin/sh", "minio-bootstrap", "-ec", object_script],
check=True,
)
quoted_users = ",".join("'%s'" % value for value in user_ids)
sql = f"""
BEGIN;
DELETE FROM messages WHERE chat_id = '{chat_id}';
DELETE FROM attachments WHERE chat_id = '{chat_id}';
DELETE FROM sessions WHERE user_id IN ({quoted_users});
DELETE FROM chat_members WHERE chat_id = '{chat_id}';
DELETE FROM chats WHERE id = '{chat_id}';
DELETE FROM users WHERE id IN ({quoted_users});
COMMIT;
"""
subprocess.run(
["docker", "compose", "exec", "-T", "postgres", "psql", "-v", "ON_ERROR_STOP=1", "-U", "messenger", "-d", "messenger"],
input=sql, text=True, check=True,
)
def main():
concurrency = 12
base_url = os.environ.get("BASE_URL", "http://127.0.0.1:8080")
client = Client(base_url, None, timeout=30)
alice, bob, eve, chat = client.bootstrap()
users = [alice["id"], bob["id"], eve["id"]]
payload = noisy_png()
stop_event = threading.Event()
peaks = {}
sampler = threading.Thread(
target=sample_memory,
args=(api_container_ids(), stop_event, peaks),
daemon=True,
)
sampler.start()
started = time.monotonic()
def upload(index):
response = client.call(
"POST",
"/api/v1/chats/%s/attachments?filename=memory-%02d.png" % (chat["id"], index),
202,
actor=alice,
raw=payload,
headers={"Content-Type": "image/png", "X-Load-Id": uuid.uuid4().hex},
schema="Attachment",
)
return response["headers"]["X-Instance-Id"]
try:
with concurrent.futures.ThreadPoolExecutor(max_workers=concurrency) as pool:
instances = list(pool.map(upload, range(concurrency)))
elapsed = time.monotonic() - started
stop_event.set()
sampler.join(timeout=10)
check(len(set(instances)) >= 2, "uploads did not exercise both API replicas")
check(len(peaks) >= 2, "memory was not sampled for both API replicas")
summary = {
"concurrency": concurrency,
"payload_bytes": len(payload),
"total_uploaded_bytes": len(payload) * concurrency,
"elapsed_seconds": round(elapsed, 3),
"successful_uploads": len(instances),
"api_instances_observed": len(set(instances)),
"peak_memory_bytes_by_container": peaks,
}
print(json.dumps(summary, ensure_ascii=False, sort_keys=True))
print("PASS: concurrent attachment uploads remained within configured API memory limits.")
finally:
stop_event.set()
sampler.join(timeout=10)
cleanup(chat["id"], users)
if __name__ == "__main__":
run(main)
+314
View File
@@ -0,0 +1,314 @@
#!/usr/bin/env python3
"""Grade-4 fault injection and media pipeline verification."""
import hashlib
import json
import struct
import subprocess
import time
from pathlib import Path
from client import Client, arguments, check, run
from image_probe import jpeg_size
ROOT = Path(__file__).resolve().parents[1]
def compose(*args, capture=False, check_result=True):
command = ["docker", "compose"]
if (ROOT / ".env").exists():
command += ["--env-file", ".env"]
command += list(args)
return subprocess.run(
command,
cwd=ROOT,
check=check_result,
text=capture,
stdout=subprocess.PIPE if capture else subprocess.DEVNULL,
stderr=subprocess.PIPE if capture else subprocess.DEVNULL,
)
def sql(statement):
result = compose(
"exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger",
"-v", "ON_ERROR_STOP=1", "-Atc", statement,
capture=True,
)
return result.stdout.strip()
def restart_count(service):
container_id = compose("ps", "-q", service, capture=True).stdout.strip()
check(bool(container_id), service + " container is not running")
result = subprocess.run(
["docker", "inspect", "--format", "{{.RestartCount}}", container_id],
check=True,
text=True,
stdout=subprocess.PIPE,
)
return int(result.stdout.strip())
def wait_until(predicate, timeout, description):
deadline = time.monotonic() + timeout
last = None
while time.monotonic() < deadline:
last = predicate()
if last:
return last
time.sleep(0.2)
raise AssertionError(description + "; last=" + repr(last))
def wait_failed(client, actor, attachment, timeout=30):
current = attachment
def poll():
nonlocal current
current = client.call(
"GET",
"/api/v1/attachments/" + attachment["id"],
actor=actor,
schema="Attachment",
)["json"]
return current if current["status"] == "failed" else None
return wait_until(poll, timeout, "attachment did not become failed")
def webp_size(data):
check(
len(data) >= 30 and data[:4] == b"RIFF" and data[8:12] == b"WEBP",
"optimized output is not a WebP RIFF container",
)
chunk = data[12:16]
payload = data[20:]
if chunk == b"VP8 ":
marker = payload.find(b"\x9d\x01\x2a")
check(marker >= 0 and len(payload) >= marker + 7, "invalid VP8 frame")
width, height = struct.unpack_from("<HH", payload, marker + 3)
return width & 0x3FFF, height & 0x3FFF
if chunk == b"VP8L":
check(len(payload) >= 5 and payload[0] == 0x2F, "invalid VP8L frame")
bits = int.from_bytes(payload[1:5], "little")
return (bits & 0x3FFF) + 1, ((bits >> 14) & 0x3FFF) + 1
if chunk == b"VP8X":
check(len(payload) >= 10, "invalid VP8X frame")
width = int.from_bytes(payload[4:7], "little") + 1
height = int.from_bytes(payload[7:10], "little") + 1
return width, height
raise AssertionError("unsupported WebP primary chunk " + repr(chunk))
def verify_variants(client, actor, ready, original):
check(ready["status"] == "ready", "attachment is not ready")
by_name = {item["name"]: item for item in ready["variants"]}
check(
set(by_name) == {"thumbnail", "crop", "optimized"},
"ready attachment must contain exactly three level-4 variants",
)
expected = {
"thumbnail": ("image/jpeg", (256, 160)),
"crop": ("image/jpeg", (128, 128)),
"optimized": ("image/webp", (320, 200)),
}
for name, (content_type, dimensions) in expected.items():
metadata = by_name[name]
check(
(metadata["width"], metadata["height"]) == dimensions,
name + " metadata dimensions mismatch",
)
downloaded = client.call(
"GET",
"/api/v1/attachments/" + ready["id"] + "/content?variant=" + name,
actor=actor,
)
check(
downloaded["headers"].get_content_type() == content_type,
name + " content type mismatch",
)
check(
len(downloaded["bytes"]) == metadata["size_bytes"] and
hashlib.sha256(downloaded["bytes"]).hexdigest() == metadata["sha256"],
name + " checksum/size mismatch",
)
actual = (
webp_size(downloaded["bytes"])
if name == "optimized"
else jpeg_size(downloaded["bytes"])
)
check(actual == dimensions, name + " actual dimensions mismatch")
downloaded_original = client.call(
"GET",
"/api/v1/attachments/" + ready["id"] + "/content",
actor=actor,
)["bytes"]
check(downloaded_original == original, "original bytes changed")
check(
sql("SELECT staging_key IS NULL FROM attachments WHERE id='" + ready["id"] + "'") == "t",
"successful processing did not safely clear staging",
)
def jobctl(*args, expect_success=True):
result = compose(
"run", "--rm", "--no-deps", "--entrypoint", "/app/jobctl",
"dispatcher", *args,
capture=True,
check_result=False,
)
if expect_success:
check(result.returncode == 0, "jobctl failed: " + result.stderr)
else:
check(result.returncode != 0, "unsafe jobctl command unexpectedly succeeded")
return result
def main():
args = arguments("Lab5 grade-4 fault injection scenario")
client = Client(args.base_url, args.ca_file)
alice, bob, _, chat = client.bootstrap()
# Media pipeline: crop and optimized are real files with deterministic
# metadata; optimized is not enlarged beyond the 320x200 fixture.
baseline, original = client.attachment(alice, chat)
ready = client.wait_ready(bob, baseline)
verify_variants(client, bob, ready, original)
# Crash after DB commit but before publish. The outbox row has no marker,
# dispatcher restarts, publishes it, and no operator creates a second job.
compose("stop", "worker")
wait_until(
lambda: sql("SELECT count(*) FROM attachment_jobs WHERE status='queued' AND published_at IS NULL") == "0",
10,
"outbox was not initially drained",
)
dispatcher_restarts = restart_count("dispatcher")
compose("exec", "-T", "dispatcher", "touch", "/tmp/mtusi-fault-before-publish")
outbox_attachment, outbox_original = client.attachment(alice, chat)
wait_until(
lambda: restart_count("dispatcher") > dispatcher_restarts,
15,
"dispatcher fault marker did not crash the process",
)
check(
sql("SELECT count(*) FROM attachment_jobs WHERE attachment_id='" + outbox_attachment["id"] + "'") == "1",
"outbox recovery created another logical job",
)
wait_until(
lambda: sql("SELECT published_at IS NOT NULL FROM attachment_jobs WHERE attachment_id='" + outbox_attachment["id"] + "'") == "t",
15,
"outbox row was not published after dispatcher restart",
)
compose("start", "worker")
outbox_ready = client.wait_ready(bob, outbox_attachment)
verify_variants(client, bob, outbox_ready, outbox_original)
# Crash after all object writes and before the result transaction/ack.
# Expire the lease explicitly to make the deterministic test fast.
worker_restarts = restart_count("worker")
compose("exec", "-T", "worker", "touch", "/tmp/mtusi-fault-after-objects")
crashed_attachment, crashed_original = client.attachment(alice, chat)
wait_until(
lambda: restart_count("worker") > worker_restarts,
20,
"worker fault marker did not crash the process",
)
sql(
"UPDATE attachment_jobs SET lease_until=CURRENT_TIMESTAMP-INTERVAL '1 second' "
"WHERE attachment_id='" + crashed_attachment["id"] + "' AND status='processing'"
)
crashed_ready = client.wait_ready(bob, crashed_attachment)
verify_variants(client, bob, crashed_ready, crashed_original)
check(
int(sql(
"SELECT count(*) FROM attachment_job_events e JOIN attachment_jobs j USING(job_id) "
"WHERE j.attachment_id='" + crashed_attachment["id"] + "' AND e.event_type='lease_recovered'"
)) >= 1,
"expired processing lease was not audited as recovered",
)
check(
sql(
"SELECT count(*) FROM attachment_variants WHERE attachment_id='" +
crashed_attachment["id"] + "'"
) == "3",
"crash/redelivery multiplied variants",
)
# A trusted metadata integrity mismatch is permanent and fails on attempt 1.
compose("stop", "worker")
permanent, _ = client.attachment(alice, chat)
sql(
"UPDATE attachments SET sha256=decode(repeat('00',32),'hex') WHERE id='" +
permanent["id"] + "'"
)
compose("start", "worker")
permanent_failed = wait_failed(client, bob, permanent)
check(permanent_failed["error_code"] == "invalid_image", "permanent error code mismatch")
check(
sql(
"SELECT attempt || ':' || status FROM attachment_jobs WHERE attachment_id='" +
permanent["id"] + "'"
) == "1:failed",
"permanent failure was retried",
)
# A transient missing staging object consumes the bounded retry budget,
# appears in the failed registry, and can be replayed only after staging is
# restored. Replaying the resulting succeeded job must be rejected.
compose("stop", "worker")
transient, transient_original = client.attachment(alice, chat)
transient_id = transient["id"]
job_id = sql(
"SELECT job_id::text FROM attachment_jobs WHERE attachment_id='" + transient_id + "'"
)
original_staging = sql(
"SELECT staging_key FROM attachments WHERE id='" + transient_id + "'"
)
sql(
"UPDATE attachments SET staging_key='staging/" + transient_id +
"/missing' WHERE id='" + transient_id + "'"
)
compose("start", "worker")
transient_failed = wait_failed(client, bob, transient, timeout=40)
check(transient_failed["error_code"] == "retry_exhausted", "transient final code mismatch")
check(
sql("SELECT attempt || ':' || status FROM attachment_jobs WHERE job_id='" + job_id + "'") ==
"5:failed",
"transient failure did not stop at max attempts",
)
check(
sql(
"SELECT count(*) FROM attachment_job_events WHERE job_id='" + job_id +
"' AND event_type='retry_scheduled'"
) == "4",
"transient retry audit count mismatch",
)
failed_registry = json.loads(jobctl("list-failed").stdout)
check(any(item["job_id"] == job_id for item in failed_registry), "failed registry omitted job")
sql(
"UPDATE attachments SET staging_key='" + original_staging +
"' WHERE id='" + transient_id + "'"
)
replay = json.loads(jobctl("replay", job_id).stdout)
check(replay["status"] == "queued" and replay["replay_count"] == 1, "replay was not audited")
replay_ready = client.wait_ready(bob, transient_failed)
verify_variants(client, bob, replay_ready, transient_original)
jobctl("replay", job_id, expect_success=False)
check(
sql(
"SELECT replay_count || ':' || status FROM attachment_jobs WHERE job_id='" + job_id + "'"
) == "1:succeeded",
"rejected replay changed a successful job",
)
print(
"PASS: level-4 variants, outbox crash recovery, lease recovery, "
"backoff/failed registry and safe replay verified."
)
if __name__ == "__main__":
run(main)
+234
View File
@@ -0,0 +1,234 @@
#!/usr/bin/env python3
"""Grade-5 track 2: repeatable versioned-pipeline idempotency experiment."""
import hashlib
import json
import time
from client import Client, arguments, check, run
from level4_resilience import compose, restart_count, sql, verify_variants, wait_until
def jobctl(service, *args, expect_success=True):
result = compose(
"run", "--rm", "--no-deps", "--entrypoint", "/app/jobctl",
service, *args,
capture=True,
check_result=False,
)
if expect_success:
check(result.returncode == 0, "jobctl failed: " + result.stderr)
else:
check(result.returncode != 0, "fault-injection command unexpectedly succeeded")
return result
def job_id(attachment_id, version):
return sql(
"SELECT job_id::text FROM attachment_jobs WHERE attachment_id='" +
attachment_id + "' AND pipeline_version=" + str(version)
)
def variant_hashes(attachment_id, version):
rows = sql(
"SELECT name || ':' || encode(sha256,'hex') FROM attachment_variants "
"WHERE attachment_id='" + attachment_id + "' AND pipeline_version=" +
str(version) + " ORDER BY name"
)
return tuple(rows.splitlines()) if rows else ()
def wait_pipeline(client, actor, attachment, version, timeout=45):
current = attachment
def poll():
nonlocal current
current = client.call(
"GET",
"/api/v1/attachments/" + attachment["id"],
actor=actor,
schema="Attachment",
)["json"]
state = sql(
"SELECT status || ':' || pipeline_version FROM attachments WHERE id='" +
attachment["id"] + "'"
)
return current if current["status"] == "ready" and len(current["variants"]) == 3 and state == "ready:" + str(version) else None
return wait_until(poll, timeout, "pipeline v" + str(version) + " did not become ready")
def expire_processing_lease(attachment_id, version):
sql(
"UPDATE attachment_jobs SET lease_until=CURRENT_TIMESTAMP-INTERVAL '1 second' "
"WHERE attachment_id='" + attachment_id + "' AND pipeline_version=" +
str(version) + " AND status='processing'"
)
def wait_queue_drained():
return wait_until(
lambda: sql(
"SELECT count(*) FROM attachment_jobs WHERE status IN ('queued','processing')"
) == "0",
20,
"logical job queue did not drain",
)
def main():
args = arguments("Lab5 grade-5 versioned pipeline idempotency")
client = Client(args.base_url, args.ca_file)
alice, bob, _, chat = client.bootstrap()
# H1: a crash before the first object-store side effect loses neither the
# confirmed upload nor its logical job. The final original must not exist
# yet, demonstrated by the rejected v2 upgrade source read.
before_restarts = restart_count("worker")
compose("exec", "-T", "worker", "touch", "/tmp/mtusi-fault-before-objects")
before, before_original = client.attachment(alice, chat)
wait_until(
lambda: restart_count("worker") > before_restarts,
20,
"worker did not crash before object writes",
)
check(
sql(
"SELECT status FROM attachment_jobs WHERE attachment_id='" +
before["id"] + "'"
) == "processing",
"before-side-effect crash did not leave a leased job",
)
rejected = jobctl("worker", "upgrade", before["id"], "2", expect_success=False)
check(
"upgrade source original is unavailable" in rejected.stderr,
"before-side-effect crash unexpectedly published the final original",
)
expire_processing_lease(before["id"], 1)
before_ready = wait_pipeline(client, bob, before, 1)
verify_variants(client, bob, before_ready, before_original)
# H2: after an object side effect but before result COMMIT/ack, a new
# pipeline can supersede the in-flight v1 job. The copied original is the
# durable handoff for v2; v1 cannot publish metadata after the upgrade.
after_restarts = restart_count("worker")
compose("exec", "-T", "worker", "touch", "/tmp/mtusi-fault-after-objects")
raced, raced_original = client.attachment(alice, chat)
wait_until(
lambda: restart_count("worker") > after_restarts,
20,
"worker did not crash after object writes",
)
v1_raced_job = job_id(raced["id"], 1)
check(
sql(
"SELECT status FROM attachment_jobs WHERE job_id='" + v1_raced_job + "'"
) == "processing",
"after-side-effect crash did not preserve the leased v1 job",
)
upgraded = json.loads(jobctl("worker", "upgrade", raced["id"], "2").stdout)
check(
upgraded["pipeline_version"] == 2 and upgraded["status"] == "queued",
"v2 upgrade did not create a queued versioned job",
)
raced_ready = wait_pipeline(client, bob, raced, 2)
verify_variants(client, bob, raced_ready, raced_original)
check(
sql(
"SELECT status FROM attachment_jobs WHERE job_id='" + v1_raced_job + "'"
) == "superseded",
"in-flight v1 job was not superseded",
)
check(
sql(
"SELECT count(*) FROM attachment_variants WHERE attachment_id='" +
raced["id"] + "' AND pipeline_version=1"
) == "0",
"stale v1 metadata committed after v2 became active",
)
check(
sql(
"SELECT count(*) FROM attachment_job_events WHERE job_id='" +
v1_raced_job + "' AND event_type='superseded'"
) == "1",
"superseded in-flight pipeline was not audited",
)
# H3: a completed v1 can be reprocessed by the distinct v2 profile. Both
# version histories remain, while API reads only active v2.
versioned, versioned_original = client.attachment(alice, chat)
v1_ready = wait_pipeline(client, bob, versioned, 1)
verify_variants(client, bob, v1_ready, versioned_original)
v1_job = job_id(versioned["id"], 1)
v1_hashes = variant_hashes(versioned["id"], 1)
check(len(v1_hashes) == 3, "v1 variant history is incomplete")
upgraded = json.loads(jobctl("worker", "upgrade", versioned["id"], "2").stdout)
v2_job = upgraded["job_id"]
v2_ready = wait_pipeline(client, bob, versioned, 2)
verify_variants(client, bob, v2_ready, versioned_original)
v2_hashes = variant_hashes(versioned["id"], 2)
check(len(v2_hashes) == 3, "v2 variant history is incomplete")
check(v1_hashes != v2_hashes, "v1 and v2 profiles produced identical variant hashes")
check(
sql(
"SELECT count(*) FROM attachment_variants WHERE attachment_id='" +
versioned["id"] + "'"
) == "6",
"version upgrade did not preserve both variant histories",
)
# Duplicate v2 deliveries followed by a reordered stale v1 delivery are
# all no-ops. Record the active result before injection and prove the old
# job cannot overwrite it.
active_before = variant_hashes(versioned["id"], 2)
original_sha_before = hashlib.sha256(
client.call(
"GET",
"/api/v1/attachments/" + versioned["id"] + "/content",
actor=bob,
)["bytes"]
).hexdigest()
jobctl("dispatcher", "inject", v2_job)
jobctl("dispatcher", "inject", v2_job)
jobctl("dispatcher", "inject", v1_job)
time.sleep(2)
wait_queue_drained()
active_after = variant_hashes(versioned["id"], 2)
original_sha_after = hashlib.sha256(
client.call(
"GET",
"/api/v1/attachments/" + versioned["id"] + "/content",
actor=bob,
)["bytes"]
).hexdigest()
check(active_after == active_before, "duplicate/reordered delivery changed active v2 hashes")
check(original_sha_after == original_sha_before, "duplicate/reordered delivery changed original")
check(
sql(
"SELECT status || ':' || pipeline_version FROM attachments WHERE id='" +
versioned["id"] + "'"
) == "ready:2",
"stale v1 delivery rolled back the active pipeline",
)
check(
sql(
"SELECT count(*) FROM attachment_variants WHERE attachment_id='" +
versioned["id"] + "'"
) == "6",
"duplicate/reordered messages multiplied variant rows",
)
check(
sql("SELECT status FROM attachment_jobs WHERE job_id='" + v2_job + "'") == "succeeded",
"duplicate v2 delivery changed successful job state",
)
print(
"PASS: pipeline v1/v2 history, crash before/after side effect, "
"superseded in-flight work, duplicate and reordered stale deliveries verified."
)
if __name__ == "__main__":
run(main)
+52
View File
@@ -0,0 +1,52 @@
#!/bin/sh
set -eu
project_root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
cd "$project_root"
api_containers=$(docker compose ps -q api)
if [ -z "$api_containers" ]; then
printf "%s\n" "no running API containers found" >&2
exit 1
fi
for container_id in $api_containers; do
docker exec "$container_id" sh -ec '
test ! -e /run/secrets/minio_root_user
test ! -e /run/secrets/minio_root_password
! env | grep -Eq "^MINIO_ROOT_(USER|PASSWORD)="
'
done
docker compose run --rm --entrypoint /bin/sh minio-bootstrap -ec '
root_user="$(cat /run/secrets/minio_root_user)"
root_password="$(cat /run/secrets/minio_root_password)"
api_user="$(cat /run/secrets/s3_access_key_id)"
api_password="$(cat /run/secrets/s3_secret_access_key)"
probe_key="policy-probe/object.txt"
mc alias set admin http://minio:9000 "$root_user" "$root_password" --api S3v4 >/dev/null
mc alias set limited http://minio:9000 "$api_user" "$api_password" --api S3v4 >/dev/null
cleanup() {
mc rm --force "admin/${S3_BUCKET}/${probe_key}" >/dev/null 2>&1 || true
mc rb --force "admin/forbidden-policy-probe" >/dev/null 2>&1 || true
}
trap cleanup EXIT INT TERM
printf private-probe | mc pipe "limited/${S3_BUCKET}/${probe_key}" >/dev/null
mc stat "limited/${S3_BUCKET}/${probe_key}" >/dev/null
mc cat "limited/${S3_BUCKET}/${probe_key}" >/dev/null
if mc mb "limited/forbidden-policy-probe" >/dev/null 2>&1; then
printf "%s\n" "limited API credentials unexpectedly created another bucket" >&2
exit 1
fi
if wget -qO- "http://minio:9000/${S3_BUCKET}/${probe_key}" >/dev/null 2>&1; then
printf "%s\n" "anonymous HTTP GET unexpectedly read a private object" >&2
exit 1
fi
mc rm --force "limited/${S3_BUCKET}/${probe_key}" >/dev/null
trap - EXIT INT TERM
printf "%s\n" "PASS: API has no MinIO root credentials; limited policy permits object IO only in the private bucket; anonymous GET is denied."
'
+192
View File
@@ -0,0 +1,192 @@
#!/usr/bin/env python3
"""Inject isolated DB/S3 inconsistencies and prove reconciler dry-run/apply/repeat."""
import json
import os
import subprocess
import time
USER_ID = "90000000-0000-4000-8000-000000000001"
CHAT_ID = "90000000-0000-4000-8000-000000000002"
MISSING_ID = "90000000-0000-4000-8000-000000000011"
PROTECTED_ID = "90000000-0000-4000-8000-000000000012"
FAILED_ID = "90000000-0000-4000-8000-000000000013"
MESSAGE_ID = "90000000-0000-4000-8000-000000000021"
PREFIX = "attachments/reconcile-integration"
ORPHAN_KEY = PREFIX + "/orphan"
FAILED_KEY = PREFIX + "/failed"
def run(command, *, input_text=None, capture=False):
result = subprocess.run(
command,
input=input_text,
text=True,
check=False,
capture_output=capture,
env=os.environ.copy(),
)
if result.returncode != 0:
details = result.stderr.strip() if capture else "see command output"
raise RuntimeError("command failed: %s: %s" % (command[0], details))
return result.stdout if capture else ""
def compose(*arguments, capture=False, input_text=None):
return run(
["docker", "compose", *arguments],
input_text=input_text,
capture=capture,
)
def database(sql):
compose(
"exec", "-T", "postgres",
"psql", "-v", "ON_ERROR_STOP=1", "-U", "messenger", "-d", "messenger",
input_text=sql,
)
def object_command(script):
compose(
"run", "--rm", "--entrypoint", "/bin/sh", "minio-bootstrap",
"-ec", script,
)
def clean_objects():
object_command(
'root_user="$(cat /run/secrets/minio_root_user)"\n'
'root_password="$(cat /run/secrets/minio_root_password)"\n'
'mc alias set local http://minio:9000 "$root_user" "$root_password" --api S3v4 >/dev/null\n'
'mc rm --force "local/${S3_BUCKET}/' + ORPHAN_KEY + '" >/dev/null 2>&1 || true\n'
'mc rm --force "local/${S3_BUCKET}/' + FAILED_KEY + '" >/dev/null 2>&1 || true\n'
)
def clean_database():
database(f"""
BEGIN;
DELETE FROM messages WHERE id = '{MESSAGE_ID}';
DELETE FROM attachments WHERE id IN ('{MISSING_ID}', '{PROTECTED_ID}', '{FAILED_ID}');
DELETE FROM chat_members WHERE chat_id = '{CHAT_ID}';
DELETE FROM chats WHERE id = '{CHAT_ID}';
DELETE FROM users WHERE id = '{USER_ID}';
COMMIT;
""")
def inject_database():
database(f"""
BEGIN;
INSERT INTO users (id, username, display_name, password_hash)
VALUES ('{USER_ID}', 'reconcile_fixture', 'Reconcile Fixture', 'not-used');
INSERT INTO chats (id, title) VALUES ('{CHAT_ID}', 'Reconcile Integration');
INSERT INTO chat_members (chat_id, user_id, position) VALUES ('{CHAT_ID}', '{USER_ID}', 0);
INSERT INTO attachments (
id, chat_id, owner_id, object_key, filename, content_type,
size_bytes, sha256, width, height, status, error_code, created_at, updated_at
) VALUES
('{MISSING_ID}', '{CHAT_ID}', '{USER_ID}', '{PREFIX}/missing', 'missing.png', 'image/png',
7, decode(repeat('00', 32), 'hex'), 1, 1, 'ready', NULL, now() - interval '2 hours', now() - interval '2 hours'),
('{PROTECTED_ID}', '{CHAT_ID}', '{USER_ID}', '{PREFIX}/protected-missing', 'protected.png', 'image/png',
7, decode(repeat('00', 32), 'hex'), 1, 1, 'ready', NULL, now() - interval '2 hours', now() - interval '2 hours'),
('{FAILED_ID}', '{CHAT_ID}', '{USER_ID}', '{FAILED_KEY}', 'failed.png', 'image/png',
7, decode(repeat('00', 32), 'hex'), 1, 1, 'failed', 'fixture_failed', now() - interval '2 hours', now() - interval '2 hours');
INSERT INTO messages (id, chat_id, sender_id, text)
VALUES ('{MESSAGE_ID}', '{CHAT_ID}', '{USER_ID}', 'protected attachment reference');
INSERT INTO message_attachments (message_id, chat_id, attachment_id, position)
VALUES ('{MESSAGE_ID}', '{CHAT_ID}', '{PROTECTED_ID}', 0);
COMMIT;
""")
def inject_objects():
object_command(
'root_user="$(cat /run/secrets/minio_root_user)"\n'
'root_password="$(cat /run/secrets/minio_root_password)"\n'
'mc alias set local http://minio:9000 "$root_user" "$root_password" --api S3v4 >/dev/null\n'
'printf orphan | mc pipe "local/${S3_BUCKET}/' + ORPHAN_KEY + '" >/dev/null\n'
'printf failed | mc pipe "local/${S3_BUCKET}/' + FAILED_KEY + '" >/dev/null\n'
)
def reconcile(apply=False):
command = [
"run", "--rm", "--entrypoint", "/app/reconciler", "api",
"--grace-period", "1s",
]
if apply:
command.append("--apply")
output = compose(*command, capture=True)
return json.loads(output)
def kinds(result):
return {issue["kind"] for issue in result["issues"]}
def fixture_issues(result):
return [issue for issue in result["issues"] if issue["object_key"].startswith(PREFIX)]
def main():
clean_objects()
clean_database()
try:
inject_database()
inject_objects()
time.sleep(2)
dry_run = reconcile(False)
expected = {
"orphan_object", "missing_object", "referenced_missing_object", "failed_object",
}
if kinds({"issues": fixture_issues(dry_run)}) != expected:
raise RuntimeError("dry-run did not detect all injected inconsistencies")
if dry_run["deleted_objects"] or dry_run["failed_attachments"]:
raise RuntimeError("dry-run performed mutations")
applied = reconcile(True)
applied_fixture = fixture_issues(applied)
applied_actions = {issue["kind"]: issue["action"] for issue in applied_fixture}
expected_actions = {
"orphan_object": "deleted",
"failed_object": "deleted",
"missing_object": "marked_failed",
"referenced_missing_object": "manual_repair_required",
}
if applied_actions != expected_actions:
raise RuntimeError("fixture apply actions differ: %s" % applied_actions)
repeated = reconcile(True)
if repeated["deleted_objects"] or repeated["failed_attachments"]:
raise RuntimeError("repeated apply was not mutation-idempotent")
protected = [issue for issue in fixture_issues(repeated) if issue.get("protected")]
if len(protected) != 1 or protected[0]["action"] != "manual_repair_required":
raise RuntimeError("referenced missing attachment was not protected")
print(json.dumps({
"dry_run_issues": len(dry_run["issues"]),
"apply_fixture_deleted_objects": sum(
issue["action"] == "deleted" for issue in applied_fixture
),
"apply_fixture_failed_attachments": sum(
issue["action"] == "marked_failed" for issue in applied_fixture
),
"repeat_mutations": repeated["deleted_objects"] + repeated["failed_attachments"],
"protected_manual_issues": len(protected),
"scanned_attachments": applied["scanned_attachments"],
"scanned_objects": applied["scanned_objects"],
"duration_ms": applied["duration_ms"],
}, ensure_ascii=False))
print("PASS: real PostgreSQL/MinIO reconciliation is dry-run safe, idempotent and reference-aware.")
finally:
clean_objects()
clean_database()
if __name__ == "__main__":
main()
+90
View File
@@ -0,0 +1,90 @@
#!/usr/bin/env python3
"""Measure real PostgreSQL/MinIO reconciler traversal at two inventory sizes."""
import json
import subprocess
import time
PREFIX = "attachments/reconcile-scale"
def compose(*arguments, capture=False):
result = subprocess.run(
["docker", "compose", *arguments],
check=False,
text=True,
capture_output=capture,
)
if result.returncode != 0:
raise RuntimeError(result.stderr.strip() if capture else "docker compose command failed")
return result.stdout if capture else ""
def object_command(script):
compose("run", "--rm", "--entrypoint", "/bin/sh", "minio-bootstrap", "-ec", script)
def clean():
object_command(
'root_user="$(cat /run/secrets/minio_root_user)"\n'
'root_password="$(cat /run/secrets/minio_root_password)"\n'
'mc alias set local http://minio:9000 "$root_user" "$root_password" --api S3v4 >/dev/null\n'
'mc rm --recursive --force "local/${S3_BUCKET}/' + PREFIX + '/" >/dev/null 2>&1 || true\n'
)
def create(count):
object_command(
'root_user="$(cat /run/secrets/minio_root_user)"\n'
'root_password="$(cat /run/secrets/minio_root_password)"\n'
'mc alias set local http://minio:9000 "$root_user" "$root_password" --api S3v4 >/dev/null\n'
'mkdir -p /tmp/reconcile-scale\n'
'index=0\n'
'while [ "$index" -lt ' + str(count) + ' ]; do\n'
' printf x > "/tmp/reconcile-scale/object-${index}"\n'
' index=$((index + 1))\n'
'done\n'
'mc cp --recursive /tmp/reconcile-scale/ "local/${S3_BUCKET}/' + PREFIX + '/" >/dev/null\n'
)
def dry_run():
started = time.monotonic()
output = compose(
"run", "--rm", "--entrypoint", "/app/reconciler", "api",
"--grace-period", "1s",
capture=True,
)
elapsed = time.monotonic() - started
result = json.loads(output)
return {
"scanned_attachments": result["scanned_attachments"],
"scanned_objects": result["scanned_objects"],
"issues": len(result["issues"]),
"reconciler_duration_ms": result["duration_ms"],
"container_start_and_run_ms": round(elapsed * 1000),
}
def main():
measurements = []
clean()
try:
for count in (100, 1000):
clean()
create(count)
time.sleep(2)
measurement = dry_run()
measurement["injected_orphan_objects"] = count
if measurement["issues"] < count:
raise RuntimeError("reconciler did not observe all scale fixtures")
measurements.append(measurement)
print(json.dumps({"measurements": measurements}, ensure_ascii=False))
print("PASS: reconciler traversal cost measured on real PostgreSQL/MinIO inventories.")
finally:
clean()
if __name__ == "__main__":
main()
+82
View File
@@ -0,0 +1,82 @@
#!/usr/bin/env python3
"""Verify contract responses and original durability during a real MinIO outage."""
import json
import os
import subprocess
import time
from attachment_memory import cleanup
from client import Client, Failure, check, run
def compose(*arguments, **kwargs):
return subprocess.run(["docker", "compose", *arguments], check=True, **kwargs)
def wait_for_status(client, path, expected, timeout=20):
deadline = time.monotonic() + timeout
last_error = None
while time.monotonic() < deadline:
try:
return client.call("GET", path, expected=expected)
except Failure as error:
last_error = error
time.sleep(0.25)
raise Failure("%s did not reach %d: %s" % (path, expected, last_error))
def restore_storage(client):
compose("up", "-d", "--wait", "minio")
compose("run", "--rm", "minio-bootstrap")
wait_for_status(client, "/health/ready", 200, timeout=30)
def main():
client = Client(os.environ.get("BASE_URL"), None, timeout=15)
alice, bob, eve, chat = client.bootstrap()
users = [alice["id"], bob["id"], eve["id"]]
attachment, original = client.attachment(alice, chat)
storage_stopped = False
try:
compose("stop", "minio")
storage_stopped = True
readiness = wait_for_status(client, "/health/ready", 503)
check(readiness["elapsed"] < 5, "readiness exceeded its bounded timeout")
started = time.monotonic()
failure = client.call(
"POST",
"/api/v1/chats/%s/attachments?filename=outage.png" % chat["id"],
503,
actor=alice,
raw=original,
headers={"Content-Type": "image/png"},
)
elapsed = time.monotonic() - started
check(failure["json"]["error"]["code"] == "unavailable", "wrong S3 outage error code")
check(elapsed < 15, "upload outage response exceeded API/client timeout")
restore_storage(client)
storage_stopped = False
attachment = client.wait_ready(alice, attachment)
downloaded = client.call(
"GET", "/api/v1/attachments/%s/content" % attachment["id"],
200, actor=alice,
)["bytes"]
check(downloaded == original, "existing original changed across MinIO outage")
print(json.dumps({
"readiness_503_seconds": round(readiness["elapsed"], 3),
"upload_503_seconds": round(elapsed, 3),
"original_bytes_verified": len(original),
}, sort_keys=True))
print("PASS: MinIO outage returns bounded JSON 503 and preserves existing originals.")
finally:
if storage_stopped:
restore_storage(client)
cleanup(chat["id"], users)
if __name__ == "__main__":
run(main)