Files
mtusi2026lab4/student-tests/consistency_test.py
T
IlyaandClaude Opus 5.5 57105dd010 выполнение ЛР4 на 4
- S3: SeaweedFS 4.51 (MinIO-образы недоступны), приватный bucket,
  отдельные ограниченные ключи API, служебные порты закрыты;
  идемпотентный s3-init с проверкой приватности и прогревом записи
- вложения: потоковая загрузка PNG/JPEG, лимиты 10 MiB / 40 Мпикс,
  тип по содержимому, проверка filename, скачивание только участникам
- согласованность PG/S3: pending -> PUT -> ready, компенсация, sweeper
  с grace и dry-run; attachment_ids в сообщениях, FK по чату
- back-pressure на S3 PUT после найденного OOM SeaweedFS
- тесты student-tests, evidence, REPORT.md, DEMO.md

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 18:00:45 +03:00

153 lines
7.7 KiB
Python

#!/usr/bin/env python3
"""Failures between S3 and PostgreSQL: S3 outage, aborted upload, and the sweeper with injected faults.
Modifies the compose stack: stops/starts the s3 service and writes synthetic rows/objects. Takes ~1.5 min
(the sweeper refuses grace < 60 s, so injected "old" objects must really age).
"""
import json
import socket
import time
import uuid
from urllib.parse import urlparse
from stack import SAMPLE_PNG, api_python, count_objects, dc, psql
from client import Client, Failure, arguments, check, run
GRACE = 60
def pending_count():
return int(psql("SELECT count(*) FROM attachments WHERE status = 'pending'"))
def put_object(key):
api_python("import io; from app.objects import ObjectStore; s=ObjectStore(); "
"s._s3.put_object(Bucket=s.bucket, Key=%r, Body=io.BytesIO(b'injected'))" % key)
def object_exists(key):
return api_python("from app.objects import ObjectStore; s=ObjectStore(); "
"print(any(k == %r for k, _ in s.list_originals()))" % key) == "True"
def insert_pending(chat_id, owner_id, key, age_seconds):
psql("INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, width, height, "
"object_key, status, created_at, updated_at) VALUES ('%s','%s','%s','injected.png','image/png',8,'%s',1,1,'%s',"
"'pending', now() - make_interval(secs => %d), now() - make_interval(secs => %d))"
% (uuid.uuid4(), chat_id, owner_id, "0" * 64, key, age_seconds, age_seconds))
def row_exists(key):
return psql("SELECT count(*) FROM attachments WHERE object_key = '%s'" % key) == "1"
def sweep(*flags):
out = dc("run", "--rm", "--no-deps", "-T", "sweeper", "python", "-m", "app.sweeper", "--once", "--grace", str(GRACE), *flags).stdout
report = json.loads(out.strip().splitlines()[-1])
check("skipped" not in report, "sweeper lock is held")
return report
def main():
args = arguments("S3/PostgreSQL consistency under failures")
c = Client(args.base_url, timeout=15)
alice, bob, eve, chat = c.bootstrap()
path = "/api/v1/chats/" + chat["id"] + "/attachments?filename=x.png"
ready = c.call("POST", path, 201, actor=alice, raw=SAMPLE_PNG, headers={"Content-Type": "image/png"}, schema="Attachment")["json"]
ready_key = psql("SELECT object_key FROM attachments WHERE id = '%s'" % ready["id"])
# 1. S3 outage -------------------------------------------------------------------------------
pend0 = pending_count()
dc("stop", "s3")
try:
t = time.monotonic()
c.call("POST", path, 503, actor=alice, raw=SAMPLE_PNG, headers={"Content-Type": "image/png"})
upload_s = time.monotonic() - t
c.call("GET", "/api/v1/attachments/" + ready["id"] + "/content", 503, actor=bob)
meta = c.call("GET", "/api/v1/attachments/" + ready["id"], actor=bob, schema="Attachment")["json"]
c.message(alice, chat, "S3 лежит, а сообщения работают")
c.call("GET", "/health/ready", schema="Health")
check(pending_count() == pend0, "failed upload left a pending row")
print("PASS S3 down: upload 503 in %.2fs, content 503, metadata 200 (%s), messages 201, ready 200, no pending row left"
% (upload_s, meta["status"]))
finally:
dc("start", "s3")
dc("up", "-d", "--no-build", "--wait", "s3")
t = time.monotonic()
while True:
try:
r = c.call("GET", "/api/v1/attachments/" + ready["id"] + "/content", [200, 503], actor=bob)
except Failure:
r = {"status": None}
if r["status"] == 200:
check(r["bytes"] == SAMPLE_PNG, "bytes changed after S3 restart")
break
check(time.monotonic() - t < 30, "S3 did not recover")
time.sleep(1)
print("PASS S3 back (healthy per compose): first download byte-identical after %.1fs" % (time.monotonic() - t))
# 2. Client aborts in the middle of the body ----------------------------------------------------
objects0, pend0 = count_objects(), pending_count()
u = urlparse(c.base)
s = socket.create_connection((u.hostname, u.port or 80), timeout=5)
s.sendall(("POST /api/v1/chats/%s/attachments?filename=abort.png HTTP/1.1\r\nHost: %s\r\nAuthorization: Bearer %s\r\n"
"Content-Type: image/png\r\nContent-Length: %d\r\n\r\n" % (chat["id"], u.hostname, alice["token"], 5 * 1024 * 1024)).encode())
s.sendall(SAMPLE_PNG + bytes(1024 * 1024))
s.close()
time.sleep(2)
check(count_objects() == objects0 and pending_count() == pend0, "aborted upload left an object or a row")
print("PASS aborted upload (1.1 of 5 MiB sent): no S3 object, no metadata row")
# 3. Sweeper: inject inconsistencies on both sides -----------------------------------------------
# The background sweeper (grace 900 s) would clean the injected 1-hour-old rows during the wait; pause it
# and run single passes with grace 60 s instead.
dc("stop", "sweeper")
try:
sweeper_scenario(c, alice, bob, chat, ready, ready_key)
finally:
dc("start", "sweeper")
def sweeper_scenario(c, alice, bob, chat, ready, ready_key):
old_orphan = "originals/" + uuid.uuid4().hex # object without row (failed compensation)
old_pending_obj = "originals/" + uuid.uuid4().hex # crash after PUT, before COMMIT ready
old_pending_noobj = "originals/" + uuid.uuid4().hex # crash before PUT
put_object(old_orphan)
put_object(old_pending_obj)
insert_pending(chat["id"], alice["id"], old_pending_obj, 3600)
insert_pending(chat["id"], alice["id"], old_pending_noobj, 3600)
print("injected: orphan object, stale pending row + object, stale pending row without object; waiting %ds" % (GRACE + 3))
time.sleep(GRACE + 3)
fresh_orphan = "originals/" + uuid.uuid4().hex # look like uploads still in progress
fresh_pending = "originals/" + uuid.uuid4().hex
put_object(fresh_orphan)
put_object(fresh_pending)
insert_pending(chat["id"], alice["id"], fresh_pending, 0)
dry = sweep("--dry-run")
print("dry-run:", json.dumps({k: dry[k] for k in ("pending_found", "orphans_found", "objects_scanned", "duration_ms")}))
check(dry["pending_found"] >= 2 and dry["orphans_found"] >= 1, "dry-run did not detect injected faults")
check(old_orphan in dry["orphan_keys_sample"] or dry["orphans_found"] > 5, "orphan key not reported")
check(object_exists(old_orphan) and row_exists(old_pending_obj), "dry-run changed something")
real = sweep()
print("real:", json.dumps({k: real[k] for k in ("pending_deleted", "orphans_deleted", "objects_scanned", "duration_ms")}))
check(not object_exists(old_orphan), "orphan object survived")
check(not object_exists(old_pending_obj) and not row_exists(old_pending_obj), "stale pending row/object survived")
check(not row_exists(old_pending_noobj), "stale pending row without object survived")
check(object_exists(fresh_orphan) and object_exists(fresh_pending) and row_exists(fresh_pending), "fresh upload was deleted")
check(object_exists(ready_key), "ready object was deleted")
d = c.call("GET", "/api/v1/attachments/" + ready["id"] + "/content", actor=bob)
check(d["bytes"] == SAMPLE_PNG, "ready attachment damaged")
again = sweep()
print("repeat:", json.dumps({k: again[k] for k in ("pending_found", "orphans_found")}))
check(again["pending_found"] == 0 and again["orphans_found"] == 0, "second pass is not a no-op")
print("PASS sweeper: dry-run reports only; real pass removes stale pending rows/objects and orphans; "
"fresh and ready kept; repeat is a no-op")
# fresh_* are left on purpose: the background sweeper removes them after ORPHAN_GRACE_SECONDS.
if __name__ == "__main__":
run(main)