Files
mtusi2026lab4/student-tests/test_reconcile_research.py
T

201 lines
10 KiB
Python

"""Repeatable lab 4 consistency experiment; run inside the maintenance Compose service.
Writes one JSON result to stdout. It creates synthetic objects and metadata, but never
deletes the measured baseline or the fresh/linked objects after the experiment.
"""
import hashlib
import importlib.util
import io
import json
import resource
import statistics
import time
from pathlib import Path
from uuid import UUID, uuid4
import psycopg
from PIL import Image
from psycopg.rows import dict_row
from src.db import database_url
from src.store import store
spec = importlib.util.spec_from_file_location("reconciler", "scripts/reconcile-attachments.py")
reconciler = importlib.util.module_from_spec(spec)
spec.loader.exec_module(reconciler)
def put(client, key: str, data: bytes) -> None:
client.put_object(reconciler.BUCKET, key, io.BytesIO(data), len(data), content_type="image/png")
def rss_kib() -> int:
for line in Path("/proc/self/status").read_text().splitlines():
if line.startswith("VmRSS:"):
return int(line.split()[1])
raise RuntimeError("VmRSS unavailable")
def scan(client, conn, label: str, trial: int) -> dict:
before = resource.getrusage(resource.RUSAGE_SELF)
rss_before = rss_kib()
start = time.perf_counter()
result = reconciler.reconcile(client, conn, False, 3600, None, None)
wall_ms = (time.perf_counter() - start) * 1000
after = resource.getrusage(resource.RUSAGE_SELF)
return {
"label": label, "trial": trial, "objects": result["inventory"]["objects"],
"metadata": result["inventory"]["metadata"],
"reconciler_ms": result["duration_ms"], "wall_ms": round(wall_ms, 3),
"cpu_user_ms": round((after.ru_utime - before.ru_utime) * 1000, 3),
"cpu_system_ms": round((after.ru_stime - before.ru_stime) * 1000, 3),
"rss_before_kib": rss_before, "rss_after_kib": rss_kib(), "rss_hwm_kib": after.ru_maxrss,
}
def main() -> None:
client = reconciler.storage()
fixture = Path("/fixtures/sample.png")
original = fixture.read_bytes()
digest = hashlib.sha256(original).hexdigest()
username = "research_" + uuid4().hex[:16]
owner = store.register(username, "Reconciliation research", "Test-password-123")
chat = store.create_chat(owner["id"], "Reconciliation research", [owner["id"]])
owner_id, chat_id = UUID(owner["id"]), UUID(chat["id"])
active_id, missing_id, old_id, fresh_id = (uuid4() for _ in range(4))
active_key, missing_key, old_key, fresh_key = (f"originals/{item}" for item in (active_id, missing_id, old_id, fresh_id))
put(client, active_key, original)
put(client, missing_key, original)
put(client, old_key, original)
try:
with psycopg.connect(database_url()) as failed:
failed.execute(
"INSERT INTO attachments (id,chat_id,owner_id,filename,object_key,content_type,size_bytes,sha256) "
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s)",
(old_id, uuid4(), owner_id, "orphan.png", old_key, "image/png", len(original), digest),
)
except psycopg.errors.ForeignKeyViolation:
pass
else:
raise AssertionError("PostgreSQL fault injection did not roll back")
with psycopg.connect(database_url(), row_factory=dict_row) as conn:
for attachment_id, key in ((active_id, active_key), (missing_id, missing_key)):
conn.execute(
"INSERT INTO attachments (id,chat_id,owner_id,filename,object_key,content_type,size_bytes,sha256) "
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s)",
(attachment_id, chat_id, owner_id, "sample.png", key, "image/png", len(original), digest),
)
message_id = uuid4()
conn.execute("INSERT INTO messages (id,chat_id,sender_id,text) VALUES (%s,%s,%s,%s)",
(message_id, chat_id, owner_id, ""))
conn.execute("INSERT INTO message_attachments (message_id,chat_id,attachment_id,position) VALUES (%s,%s,%s,0)",
(message_id, chat_id, active_id))
client.remove_object(reconciler.BUCKET, missing_key)
time.sleep(6) # An explicit test-only 5-second grace; routine maintenance uses one hour.
put(client, fresh_key, original)
with psycopg.connect(database_url(), row_factory=dict_row) as conn:
preview = reconciler.reconcile(client, conn, False, 5, None, None)
assert old_key in preview["old_orphans"] and fresh_key in preview["fresh_orphans"]
assert str(missing_id) in preview["manual_incidents"] and active_key not in preview["old_orphans"]
assert not reconciler.absent(client, old_key) # Dry-run did not delete.
wrong = Path("/tmp/research-wrong-source")
wrong.write_bytes(b"wrong fixture")
try:
reconciler.reconcile(client, conn, True, 5, missing_id, wrong)
except ValueError:
pass
else:
raise AssertionError("wrong fixture accepted")
assert not reconciler.absent(client, old_key)
apply_without_source = reconciler.reconcile(client, conn, True, 5, None, None)
assert old_key in apply_without_source["deleted"]
assert str(missing_id) in apply_without_source["manual_incidents"]
assert reconciler.absent(client, old_key) and reconciler.absent(client, missing_key)
assert not reconciler.absent(client, fresh_key) and not reconciler.absent(client, active_key)
assert conn.execute("SELECT 1 FROM message_attachments WHERE attachment_id=%s", (active_id,)).fetchone()
post_delete_preview = reconciler.reconcile(client, conn, False, 5, None, None)
assert old_key not in post_delete_preview["old_orphans"]
assert str(missing_id) in post_delete_preview["manual_incidents"]
assert fresh_key in post_delete_preview["fresh_orphans"]
repeat_delete = reconciler.reconcile(client, conn, True, 5, None, None)
assert old_key not in repeat_delete["deleted"]
restored = reconciler.reconcile(client, conn, True, 3600, missing_id, fixture)
assert restored["restore"] == "restored" and not reconciler.absent(client, missing_key)
repeat = reconciler.reconcile(client, conn, True, 3600, missing_id, fixture)
assert repeat["restore"] == "already_present" and not repeat["deleted"]
assert str(missing_id) not in repeat["manual_incidents"]
assert not reconciler.absent(client, fresh_key) and not reconciler.absent(client, active_key)
post_restore_preview = reconciler.reconcile(client, conn, False, 5, None, None)
assert old_key not in post_restore_preview["old_orphans"]
assert str(missing_id) not in post_restore_preview["manual_incidents"]
conn.commit()
tiny = io.BytesIO()
Image.new("RGB", (4, 4), (5, 30, 80)).save(tiny, format="PNG")
data = tiny.getvalue()
tiny_hash = hashlib.sha256(data).hexdigest()
def add_batch(count: int) -> None:
rows = []
for _ in range(count):
attachment_id = uuid4()
key = f"originals/{attachment_id}"
put(client, key, data)
rows.append((attachment_id, chat_id, owner_id, "inventory.png", key, "image/png", len(data), tiny_hash))
with conn.cursor() as cursor:
cursor.executemany(
"INSERT INTO attachments (id,chat_id,owner_id,filename,object_key,content_type,size_bytes,sha256) "
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s)", rows,
)
conn.commit()
measurements = []
for label, additional in (("plus_50", 50), ("plus_250", 200)):
add_batch(additional)
measurements.extend(scan(client, conn, label, trial) for trial in range(1, 4))
assert measurements[3]["objects"] >= measurements[0]["objects"] + 200
assert measurements[3]["metadata"] >= measurements[0]["metadata"] + 200
response = client.get_object(reconciler.BUCKET, missing_key)
try:
assert hashlib.sha256(response.read()).hexdigest() == digest
finally:
response.close()
response.release_conn()
summary = {label: {
"median_wall_ms": round(statistics.median(item["wall_ms"] for item in measurements if item["label"] == label), 3),
"median_cpu_ms": round(statistics.median(item["cpu_user_ms"] + item["cpu_system_ms"] for item in measurements if item["label"] == label), 3),
"objects": next(item["objects"] for item in measurements if item["label"] == label),
"metadata": next(item["metadata"] for item in measurements if item["label"] == label),
} for label in ("plus_50", "plus_250")}
print(json.dumps({
"faults": {
"preview": {"old_detected": old_key in preview["old_orphans"], "fresh_detected": fresh_key in preview["fresh_orphans"],
"missing_detected": str(missing_id) in preview["missing_attachment_ids"],
"linked_preserved": active_key not in preview["old_orphans"], "inventory": preview["inventory"]},
"wrong_fixture_rejected_without_delete": True,
"apply_without_source": {"old_deleted": old_key in apply_without_source["deleted"],
"missing_incident_retained": str(missing_id) in apply_without_source["manual_incidents"],
"fresh_preserved": True, "linked_preserved": True},
"post_delete_dry_run": {"old_absent": old_key not in post_delete_preview["old_orphans"],
"missing_incident_retained": str(missing_id) in post_delete_preview["manual_incidents"]},
"repeat_delete_no_change": old_key not in repeat_delete["deleted"],
"restore": restored["restore"], "repeat": repeat["restore"],
"post_restore_dry_run": {"old_absent": old_key not in post_restore_preview["old_orphans"],
"missing_absent": str(missing_id) not in post_restore_preview["manual_incidents"]},
}, "measurements": measurements, "summary": summary,
"limits": "Single local host, 3 sequential dry-run scans per size; CPU/RSS are maintenance-process measurements only."
}, sort_keys=True))
if __name__ == "__main__":
main()