fix(lab4): preserve error contract and verify storage consistency

This commit is contained in:
kolya5544
2026-11-11 18:25:57 +03:00
parent f875e2977f
commit 0150b91ec0
18 changed files with 1051 additions and 35 deletions
+39 -2
View File
@@ -32,7 +32,7 @@ BASE = "http://127.0.0.1:8080"
def sh(*args):
return subprocess.run(args, cwd=ROOT, capture_output=True, text=True, encoding="utf-8")
return subprocess.run(args, cwd=ROOT, capture_output=True, text=True, encoding="utf-8", check=True)
def compose(*args):
@@ -106,9 +106,32 @@ def keys_for(ids):
return out
async def bind_to_messages(s, token, chat, ids):
"""Create real message references, not just ready attachment metadata."""
headers = {"Authorization": "Bearer " + token}
for start in range(0, len(ids), 10):
batch = ids[start:start + 10]
async with s.post("%s/api/v1/chats/%s/messages" % (BASE, chat),
json={"text": "reconciler keeper", "attachment_ids": batch},
headers={**headers, "Idempotency-Key": str(uuid.uuid4())}) as r:
body = await r.json()
assert r.status == 201 and body["attachment_ids"] == batch, (r.status, body)
async def message_bindings(s, token, chat):
async with s.get("%s/api/v1/chats/%s/messages?limit=100" % (BASE, chat),
headers={"Authorization": "Bearer " + token}) as r:
r.raise_for_status()
body = await r.json()
return {m["id"]: m["attachment_ids"] for m in body["items"]}
async def main(args):
report = {"date": time.strftime("%Y-%m-%d %H:%M:%S"), "cost_of_scan": [], "args": vars(args)}
async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=60), connector=aiohttp.TCPConnector(limit=32)) as s:
# Docker commands block the event loop longer than the server's keep-alive.
# Do not reuse idle HTTP sockets after a scan or fault-injection command.
async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=60),
connector=aiohttp.TCPConnector(limit=32, force_close=True)) as s:
token, chat = await register(s)
base = reconcile("--grace", "0", "--apply") # нормализация: убираем следы прошлых прогонов
base = reconcile("--grace", "0")
@@ -127,6 +150,9 @@ async def main(args):
missing_ids = [a for a, _ in sample[:20]]
mismatch_ids = [a for a, _ in sample[20:25]]
used_ids = [a for a, _ in random.sample([u for u in uploaded if u[0] not in set(missing_ids + mismatch_ids)], 200)]
await bind_to_messages(s, token, chat, used_ids)
bindings_before = await message_bindings(s, token, chat)
assert {a for ids in bindings_before.values() for a in ids} == set(used_ids)
orphans = ["att/%s/original" % uuid.uuid4() for _ in range(20)]
mkeys, xkeys = keys_for(missing_ids), keys_for(mismatch_ids)
code = ("import asyncio\nfrom app import config\nfrom app.s3 import S3\nasync def m():\n s=S3(); await s.start()\n"
@@ -152,6 +178,9 @@ async def main(args):
report["apply"] = {k: applied[k] for k in ("fixed", "orphans_skipped_fresh", "timing_ms", "orphan_objects_count", "missing_objects_count", "size_mismatch_count")}
report["fresh_uploads_during_apply"] = {"uploaded": len(fresh), "intact": await check_intact(s, token, fresh)}
report["in_use_attachments_intact"] = "%d/%d" % (await check_intact(s, token, used_pairs), len(used_pairs))
bindings_after = await message_bindings(s, token, chat)
report["message_bindings"] = {"messages": len(bindings_before), "attachments": len(used_ids),
"unchanged": bindings_after == bindings_before}
again = reconcile("--grace", "5", "--apply")
report["second_apply_idempotent"] = {"fixed": again["fixed"], "orphan_objects_count": again["orphan_objects_count"],
"missing_objects_count": again["missing_objects_count"]}
@@ -161,6 +190,14 @@ async def main(args):
with open(os.path.join(args.out, "track2_reconcile.json"), "w", encoding="utf-8") as fh:
json.dump(report, fh, ensure_ascii=False, indent=2)
print(json.dumps({k: v for k, v in report.items() if k != "args"}, ensure_ascii=False, indent=2))
assert len(uploaded) == 3 * (args.total // 3), "not all requested uploads succeeded"
assert report["dry_run_repeatable"] and report["dry_run_found_exactly_injected"], report["dry_run"]
assert dry1["fixed"] == dry2["fixed"] == {"deleted_orphans": 0, "marked_failed": 0}
assert applied["fixed"] == {"deleted_orphans": 20, "marked_failed": 25}, applied
assert report["fresh_uploads_during_apply"] == {"uploaded": 200, "intact": 200}
assert report["in_use_attachments_intact"] == "200/200" and report["message_bindings"]["unchanged"]
assert again["fixed"] == {"deleted_orphans": 0, "marked_failed": 0}, again
assert (again["orphan_objects_count"], again["missing_objects_count"], again["size_mismatch_count"]) == (0, 0, 0)
if __name__ == "__main__":
+2
View File
@@ -0,0 +1,2 @@
aiohttp==3.14.3
Pillow==12.3.0
+12 -1
View File
@@ -28,7 +28,8 @@ PROJECT = "mtusi-lab4"
def sh(*args, env=None):
return subprocess.run(args, cwd=ROOT, capture_output=True, text=True, env=dict(os.environ, **(env or {}))).stdout.strip()
return subprocess.run(args, cwd=ROOT, capture_output=True, text=True, check=True,
env=dict(os.environ, **(env or {}))).stdout.strip()
def noisy_png(side, seed):
@@ -54,6 +55,8 @@ def set_api(concurrency, replicas):
if len(ids) == replicas and all(sh("docker", "inspect", "-f", "{{.State.Health.Status}}", i) == "healthy" for i in ids):
break
time.sleep(1)
else:
raise RuntimeError("API replicas did not become healthy within 90 seconds")
time.sleep(6)
@@ -99,6 +102,9 @@ async def main(args):
for conc in args.concurrency:
set_api(conc, 1)
cid = api_containers()[0]
limits = json.loads(sh("docker", "inspect", "-f",
'{"memory_bytes":{{.HostConfig.Memory}},"nano_cpus":{{.HostConfig.NanoCpus}}}', cid))
assert limits == {"memory_bytes": 256 * 1024 * 1024, "nano_cpus": 1000000000}, limits
async with aiohttp.ClientSession() as s:
uid, token = await register(s)
async with s.post(BASE + "/api/v1/chats", json={"title": "mem", "member_ids": [uid]}, headers={"Authorization": "Bearer " + token}) as r:
@@ -120,6 +126,7 @@ async def main(args):
intact += 1
oom = sh("docker", "inspect", "-f", "{{.State.OOMKilled}}", cid)
entry = {"UPLOAD_CONCURRENCY": conc, "statuses": statuses, "wall_seconds": round(wall, 2), "peak_rss_mib": peak,
"resource_limits": limits,
"rss_before_mib": baseline_hwm, "rss_after_mib": rss, "oom_killed": oom,
"accepted_files_intact": "%d/%d" % (intact, statuses.get("201", 0)),
"p50_s": round(ok_lat[len(ok_lat) // 2], 2) if ok_lat else None, "max_s": round(ok_lat[-1], 2) if ok_lat else None}
@@ -128,6 +135,10 @@ async def main(args):
set_api(4, 2)
with open(os.path.join(args.out, "upload_memory.json"), "w", encoding="utf-8") as fh:
json.dump(report, fh, ensure_ascii=False, indent=2)
for entry in report["runs"]:
assert entry["statuses"] == {"201": args.clients}, entry
assert entry["accepted_files_intact"] == "%d/%d" % (args.clients, args.clients), entry
assert entry["oom_killed"] == "false" and 0 < entry["peak_rss_mib"] < 256, entry
if __name__ == "__main__":