235 lines
11 KiB
Python
235 lines
11 KiB
Python
#!/usr/bin/env python3
|
|
"""Grade 5 Track 2: Two-Store (PostgreSQL <-> S3) Reconciler experiment for Lab 4.
|
|
1. Seeds >=25 healthy active attachments (some referenced by messages).
|
|
2. Injects faults on BOTH sides:
|
|
- 3 aged orphan S3 objects (> grace) without DB rows
|
|
- 1 aged missing-S3 'ready' attachment (referenced in message; S3 object deleted out-of-band)
|
|
- 1 aged missing-S3 'pending' attachment in DB (never committed to S3)
|
|
- 1 fresh orphan S3 object INSIDE grace period (simulating in-flight upload)
|
|
3. Runs Reconciler in --dry-run (proves 0 mutations, detects exact anomalies, skips fresh grace).
|
|
4. Runs Reconciler in --apply (deletes aged orphans & stale pending row, marks missing ready attachment as failed, preserves fresh grace & all >=25 healthy objects).
|
|
5. Runs Reconciler a second time (proves strict idempotency: 0 mutations, 0 anomalies).
|
|
6. Verifies all >=25 healthy attachments remain downloadable with exact SHA-256 and captures traversal cost.
|
|
"""
|
|
import base64
|
|
import datetime as dt
|
|
import hashlib
|
|
import json
|
|
from pathlib import Path
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
import urllib.error
|
|
import urllib.request
|
|
import uuid
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
FIXTURE_PNG = ROOT / "tests" / "fixtures" / "sample.png"
|
|
EVIDENCE_PATH = ROOT / "evidence" / "track2_reconciler.json"
|
|
BASE_URL = sys.argv[1] if len(sys.argv) > 1 else "http://localhost:8080"
|
|
|
|
|
|
def run_cmd(cmd, input_text=None):
|
|
return subprocess.run(cmd, cwd=str(ROOT), input=input_text, text=True, capture_output=True, check=True)
|
|
|
|
|
|
def http_call(method, path, body=None, raw_bytes=None, headers=None, timeout=15):
|
|
h = {"Accept": "application/json"}
|
|
data = raw_bytes
|
|
if body is not None:
|
|
data = json.dumps(body).encode("utf-8")
|
|
h["Content-Type"] = "application/json"
|
|
if headers:
|
|
h.update(headers)
|
|
req = urllib.request.Request(BASE_URL + path, data=data, headers=h, method=method)
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
raw = resp.read()
|
|
ct = resp.headers.get("Content-Type", "")
|
|
parsed = json.loads(raw.decode("utf-8")) if (raw and "application/json" in ct) else None
|
|
return resp.code, parsed, raw
|
|
except urllib.error.HTTPError as err:
|
|
raw = err.read()
|
|
ct = err.headers.get("Content-Type", "")
|
|
parsed = json.loads(raw.decode("utf-8")) if (raw and "application/json" in ct) else None
|
|
return err.code, parsed, raw
|
|
|
|
|
|
def register_and_login():
|
|
uname = f"rec_{uuid.uuid4().hex[:8]}"
|
|
pw = f"Track2Pass-{uuid.uuid4().hex}"
|
|
st, u, _ = http_call("POST", "/api/v1/users", {"username": uname, "display_name": "Reconciler", "password": pw})
|
|
assert st == 201
|
|
basic = base64.b64encode(f"{uname}:{pw}".encode("utf-8")).decode("ascii")
|
|
st, sess, _ = http_call("POST", "/api/v1/auth/sessions", headers={"Authorization": f"Basic {basic}"})
|
|
assert st == 201
|
|
return {"id": u["id"], "headers": {"Authorization": f"Bearer {sess['token']}"}}
|
|
|
|
|
|
def mc_exec(s3_cid, script_body):
|
|
cmd = ["docker", "exec", "-i", s3_cid, "/bin/sh", "-e"]
|
|
return run_cmd(cmd, input_text=script_body).stdout
|
|
|
|
|
|
def s3_object_exists(s3_cid, obj_key):
|
|
res = subprocess.run(
|
|
["docker", "exec", s3_cid, "/bin/sh", "-c",
|
|
f"mc alias set local http://127.0.0.1:9000 minio_admin_local minio_admin_secret_lab4 >/dev/null && mc stat local/messenger-attachments/{obj_key} >/dev/null 2>&1"],
|
|
cwd=str(ROOT), text=True, capture_output=True,
|
|
)
|
|
return res.returncode == 0
|
|
|
|
|
|
def main():
|
|
api_cid = run_cmd(["docker", "compose", "--env-file", ".env", "ps", "-q", "api"]).stdout.strip().splitlines()[0].strip()
|
|
pg_cid = run_cmd(["docker", "compose", "--env-file", ".env", "ps", "-q", "postgres"]).stdout.strip()
|
|
s3_cid = run_cmd(["docker", "compose", "--env-file", ".env", "ps", "-q", "s3"]).stdout.strip()
|
|
|
|
sample = FIXTURE_PNG.read_bytes()
|
|
expected_sha = hashlib.sha256(sample).hexdigest()
|
|
|
|
actor = register_and_login()
|
|
st, chat, _ = http_call("POST", "/api/v1/chats", {
|
|
"title": "Track 2 Reconciler Chat",
|
|
"member_ids": [actor["id"]],
|
|
}, headers=actor["headers"])
|
|
assert st == 201
|
|
|
|
# 1. Upload 25 healthy active attachments (and link first 10 to messages)
|
|
healthy = []
|
|
for i in range(25):
|
|
st, att, _ = http_call(
|
|
"POST",
|
|
f"/api/v1/chats/{chat['id']}/attachments?filename=healthy_{i}.png",
|
|
raw_bytes=sample,
|
|
headers={**actor["headers"], "Content-Type": "image/png"},
|
|
)
|
|
assert st == 201
|
|
healthy.append(att)
|
|
if i < 10:
|
|
st_m, _, _ = http_call("POST", f"/api/v1/chats/{chat['id']}/messages", {
|
|
"text": f"Attached #{i}",
|
|
"attachment_ids": [att["id"]],
|
|
}, headers={**actor["headers"], "Idempotency-Key": f"rec-msg-{i}-{uuid.uuid4().hex[:8]}"})
|
|
assert st_m == 201
|
|
|
|
# 2. Upload 1 legitimate attachment that will suffer out-of-band S3 object loss (Fault C)
|
|
st, victim_att, _ = http_call(
|
|
"POST",
|
|
f"/api/v1/chats/{chat['id']}/attachments?filename=victim.png",
|
|
raw_bytes=sample,
|
|
headers={**actor["headers"], "Content-Type": "image/png"},
|
|
)
|
|
assert st == 201
|
|
st_m, _, _ = http_call("POST", f"/api/v1/chats/{chat['id']}/messages", {
|
|
"text": "Message referencing S3-lost attachment",
|
|
"attachment_ids": [victim_att["id"]],
|
|
}, headers={**actor["headers"], "Idempotency-Key": f"rec-victim-{uuid.uuid4().hex[:8]}"})
|
|
assert st_m == 201
|
|
|
|
victim_key = f"attachments/{chat['id']}/{victim_att['id']}"
|
|
|
|
# Inject Fault A (3 orphan S3 objects) & remove victim_key out-of-band (Fault C)
|
|
orphan_keys = [f"attachments/{chat['id']}/orphan_{uuid.uuid4()}" for _ in range(3)]
|
|
mc_script = "mc alias set local http://127.0.0.1:9000 minio_admin_local minio_admin_secret_lab4 >/dev/null\n"
|
|
for k in orphan_keys:
|
|
mc_script += f"printf 'orphan-bytes-%s' '{k}' | mc pipe local/messenger-attachments/{k} >/dev/null\n"
|
|
mc_script += f"mc rm local/messenger-attachments/{victim_key} >/dev/null\n"
|
|
mc_exec(s3_cid, mc_script)
|
|
|
|
# Inject Fault D: aged 'pending' DB row without S3 object
|
|
stale_pending_id = str(uuid.uuid4())
|
|
run_cmd([
|
|
"docker", "exec", "-i", pg_cid, "psql", "-v", "ON_ERROR_STOP=1", "-U", "messenger", "-d", "messenger",
|
|
], input_text=f"""
|
|
INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key, status, error_code, created_at, updated_at)
|
|
VALUES ('{stale_pending_id}'::uuid, '{chat['id']}'::uuid, '{actor['id']}'::uuid, 'stale_pending.png', 'image/png', 100, '{expected_sha}', 'attachments/{chat['id']}/{stale_pending_id}', 'pending', NULL, NOW() - INTERVAL '20 seconds', NOW() - INTERVAL '20 seconds');
|
|
""")
|
|
|
|
# Wait 7 seconds so Faults A/C/D cross the 5s grace threshold
|
|
time.sleep(7.0)
|
|
|
|
# Inject Fault B: FRESH orphan S3 object INSIDE grace period (age ~0s < 5s)
|
|
fresh_key = f"attachments/{chat['id']}/fresh_{uuid.uuid4()}"
|
|
mc_exec(s3_cid, f"""
|
|
mc alias set local http://127.0.0.1:9000 minio_admin_local minio_admin_secret_lab4 >/dev/null
|
|
printf 'inflight-upload' | mc pipe local/messenger-attachments/{fresh_key} >/dev/null
|
|
""")
|
|
|
|
# 3. Run Reconciler in --dry-run (grace=5s)
|
|
dry_raw = run_cmd([
|
|
"docker", "exec", api_cid, "/app/messenger", "-reconcile-once", "-dry-run", "-grace-seconds=5",
|
|
]).stdout
|
|
dry_report = json.loads(dry_raw)
|
|
assert dry_report["lock_acquired"] is True
|
|
for k in orphan_keys:
|
|
assert k in dry_report["orphan_s3_found"], f"Dry-run missed orphan {k}"
|
|
assert fresh_key in dry_report["orphan_s3_skipped_grace"], "Dry-run must skip fresh in-flight S3 object inside grace"
|
|
assert victim_att["id"] in dry_report["missing_s3_found"]
|
|
assert stale_pending_id in dry_report["missing_s3_found"]
|
|
assert dry_report["orphan_s3_deleted"] == []
|
|
assert dry_report["missing_s3_marked_failed"] == []
|
|
assert dry_report["missing_s3_deleted"] == []
|
|
assert dry_report["healthy_preserved"] >= 25
|
|
print(f"PASS: dry-run scanned {dry_report['s3_objects_scanned']} S3 objs, {dry_report['db_rows_scanned']} DB rows in {dry_report['duration_ms']}ms")
|
|
|
|
# 4. Run Reconciler in --apply (grace=5s)
|
|
apply_raw = run_cmd([
|
|
"docker", "exec", api_cid, "/app/messenger", "-reconcile-once", "-grace-seconds=5",
|
|
]).stdout
|
|
apply_report = json.loads(apply_raw)
|
|
assert set(orphan_keys).issubset(set(apply_report["orphan_s3_deleted"]))
|
|
assert fresh_key in apply_report["orphan_s3_skipped_grace"], "Apply must NOT delete fresh object inside grace!"
|
|
assert victim_att["id"] in apply_report["missing_s3_marked_failed"]
|
|
assert stale_pending_id in apply_report["missing_s3_deleted"]
|
|
assert apply_report["healthy_preserved"] >= 25
|
|
|
|
# Verify S3 state: aged orphans gone, fresh orphan STILL present!
|
|
for k in orphan_keys:
|
|
assert not s3_object_exists(s3_cid, k), f"Aged orphan {k} was not removed"
|
|
assert s3_object_exists(s3_cid, fresh_key), "Fresh object inside grace was wrongly deleted!"
|
|
|
|
# Verify DB/API state: victim attachment marked failed & download returns 409; stale pending deleted!
|
|
st_v, _, _ = http_call("GET", f"/api/v1/attachments/{victim_att['id']}/content", headers=actor["headers"])
|
|
assert st_v == 409, f"Expected 409 on missing_s3_object download, got {st_v}"
|
|
|
|
# 5. Re-run Reconciler immediately (repeatability / idempotency check!)
|
|
rerun_raw = run_cmd([
|
|
"docker", "exec", api_cid, "/app/messenger", "-reconcile-once", "-grace-seconds=5",
|
|
]).stdout
|
|
rerun_report = json.loads(rerun_raw)
|
|
assert rerun_report["orphan_s3_deleted"] == []
|
|
assert rerun_report["missing_s3_marked_failed"] == []
|
|
assert rerun_report["missing_s3_deleted"] == []
|
|
assert rerun_report["healthy_preserved"] >= 25
|
|
|
|
# 6. Verify ALL 25 healthy active attachments remain downloadable with exact SHA-256
|
|
for att in healthy:
|
|
st_h, _, raw_h = http_call("GET", f"/api/v1/attachments/{att['id']}/content", headers=actor["headers"])
|
|
assert st_h == 200 and hashlib.sha256(raw_h).hexdigest() == expected_sha
|
|
|
|
# Cleanup our synthetic fresh_key test artifact in S3 so bucket stays tidy
|
|
mc_exec(s3_cid, f"mc alias set local http://127.0.0.1:9000 minio_admin_local minio_admin_secret_lab4 >/dev/null && mc rm local/messenger-attachments/{fresh_key} >/dev/null")
|
|
|
|
out = {
|
|
"timestamp_utc": dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
|
"healthy_attachments_verified": len(healthy),
|
|
"injected_faults": {
|
|
"aged_orphan_s3_objects": len(orphan_keys),
|
|
"fresh_orphan_s3_inside_grace": 1,
|
|
"missing_s3_ready_referenced": 1,
|
|
"missing_s3_pending_stale": 1,
|
|
},
|
|
"dry_run_report": dry_report,
|
|
"apply_report": apply_report,
|
|
"idempotent_rerun_report": rerun_report,
|
|
"status": "PASS",
|
|
}
|
|
EVIDENCE_PATH.parent.mkdir(parents=True, exist_ok=True)
|
|
EVIDENCE_PATH.write_text(json.dumps(out, indent=2) + "\n", encoding="utf-8")
|
|
print(f"PASS: Track 2 two-store reconciler experiment verified; evidence saved to {EVIDENCE_PATH}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|