Аудит F10, F14, F15, F16: rolling update, тесты lab4, CI приложения, тест памяти

- F10: rolling-update.sh собирает migrate (единственный сервис с build),
  проверяет APP_VERSION в образе, в новой реплике и в ответах через LB;
  реально выполнено обновление 1 -> 2 (evidence/rolling-update.txt)
- F14: s3_outage.py переписан под lab5 (503 в API, retry в worker, принятое
  задание доходит до ready); устаревший consistency_faults.py удалён
- F15: .github/workflows/app.yml — сборка, готовность, smoke и регрессии на
  изолированном стенде, логи при ошибке, очистка
- F16: upload_memory.py с явными критериями и ненулевым кодом выхода, размер
  в каждой записи, progressive JPEG в смеси
- run_all.sh: все регрессии аудита, make validate, регрессия lab3, rolling update
This commit is contained in:
2026-11-13 21:02:54 +03:00
parent a71b445019
commit 5d60a85cc1
10 changed files with 822 additions and 280 deletions
+76 -79
View File
@@ -1,63 +1,48 @@
#!/usr/bin/env python3
"""Недоступность S3: stop (порт закрыт) и pause (S3 «завис», TCP не отвечает).
"""Недоступность S3 в lab5 (переписано из lab4 по аудиту F14: там ожидался синхронный 201).
python3 student-tests/s3_outage.py [--output evidence/s3-outage.json]
python3 student-tests/s3_outage.py --output evidence/s3-outage.json
Ожидания: upload и download — быстрый 503 unavailable c Retry-After (не 500 и не
таймаут LB), текстовые сообщения и /health/ready продолжают работать (S3 не входит в
readiness), после восстановления S3 загрузка снова 201 без перезапуска API.
API (как в lab4): при остановленном (`stop`) и зависшем (`pause`) S3 upload и download — быстрый
503 unavailable с Retry-After, текстовые сообщения 201, /health/ready 200, GET метаданных 200.
Worker (новое): задание, принятое ДО отказа S3, при обработке получает storage_unavailable и
уходит в retry с backoff; после восстановления S3 оно доходит до ready. Если отказ длился
дольше всех попыток — failed(retry_exhausted), и оператор делает replay (это тоже проверяется).
"""
import argparse
import json
import subprocess
import sys
import time
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client # noqa: E402
PNG = (ROOT / "tests/fixtures/sample.png").read_bytes()
log = []
from lab5lib import (Client, Log, SAMPLE_PNG, check, compose, events, ops, upload, wait_status, wait_until)
def probe(c, alice, chat, att):
def probe(c, alice, chat, att_ready, att_queued):
out = {}
for name, args in (
("upload", ("POST", "/api/v1/chats/%s/attachments?filename=o.png" % chat["id"])),
("download", ("GET", "/api/v1/attachments/%s/content" % att["id"])),
("text_message", ("POST", "/api/v1/chats/%s/messages" % chat["id"])),
("ready", ("GET", "/health/ready"))):
kw = {}
if name == "upload":
kw = {"raw": PNG, "headers": {"Content-Type": "image/png"}}
if name == "text_message":
kw = {"body": {"text": "без S3"}, "headers": {"Idempotency-Key": uuid.uuid4().hex}}
calls = {
"upload": ("POST", "/api/v1/chats/%s/attachments?filename=o.png" % chat["id"],
{"raw": SAMPLE_PNG, "headers": {"Content-Type": "image/png"}}),
"download_ready": ("GET", "/api/v1/attachments/%s/content" % att_ready["id"], {}),
"metadata_queued": ("GET", "/api/v1/attachments/%s" % att_queued["id"], {}),
"text_message": ("POST", "/api/v1/chats/%s/messages" % chat["id"],
{"body": {"text": "без S3"}, "headers": {"Idempotency-Key": uuid.uuid4().hex}}),
"ready": ("GET", "/health/ready", {}),
}
for name, (method, path, kw) in calls.items():
t = time.monotonic()
r = c.call(*args, [200, 201, 503, 502, 504], actor=alice if name != "ready" else None, **kw)
r = c.call(method, path, [200, 201, 202, 503], actor=None if name == "ready" else alice, **kw)
out[name] = {"status": r["status"], "ms": round((time.monotonic() - t) * 1000),
"code": (r["json"] or {}).get("error", {}).get("code"),
"retry_after": r["headers"].get("Retry-After")}
return out
def phase(name, c, alice, chat, att):
entry = {"phase": name, "probe": probe(c, alice, chat, att)}
log.append(entry)
print(json.dumps(entry, ensure_ascii=False), flush=True)
return entry
def recover(c, alice, chat, started):
while time.monotonic() - started < 120:
r = c.call("POST", "/api/v1/chats/%s/attachments?filename=r.png" % chat["id"], [201, 503], actor=alice,
raw=PNG, headers={"Content-Type": "image/png"})
if r["status"] == 201:
return round(time.monotonic() - started, 1)
time.sleep(0.5)
return None
def s3_healthy():
cid = compose("ps", "-q", "s3").stdout.strip()
import subprocess
st = subprocess.run(["docker", "inspect", "-f", "{{.State.Health.Status}}", cid], capture_output=True,
text=True).stdout.strip()
return st == "healthy"
def main():
@@ -65,45 +50,57 @@ def main():
ap.add_argument("--base-url", default="http://localhost:8080")
ap.add_argument("--output")
args = ap.parse_args()
log = Log("S3 outage: API answers 503 fast, accepted jobs retry and complete")
c = Client(args.base_url, timeout=30)
alice, _bob, _eve, chat = c.bootstrap()
att = c.call("POST", "/api/v1/chats/%s/attachments?filename=a.png" % chat["id"], 201, actor=alice, raw=PNG,
headers={"Content-Type": "image/png"}, schema="Attachment")["json"]
phase("baseline", c, alice, chat, att)
for action, undo in ((["stop", "s3"], ["start", "s3"]), (["pause", "s3"], ["unpause", "s3"])):
subprocess.run(["docker", "compose"] + action, cwd=ROOT, check=True, capture_output=True)
time.sleep(1)
phase("immediately after `%s` (S3Health not yet stale)" % " ".join(action), c, alice, chat, att)
time.sleep(4)
phase("S3 down for 5 s (`%s`)" % " ".join(action), c, alice, chat, att)
subprocess.run(["docker", "compose"] + undo, cwd=ROOT, check=True, capture_output=True)
t0 = time.monotonic()
rec = recover(c, alice, chat, t0)
log.append({"phase": "recovery after `%s`" % " ".join(undo), "upload_201_after_s": rec})
print(json.dumps(log[-1]), flush=True)
# Оставляем стенд рабочим: ждём, пока healthcheck S3 снова станет healthy (после pause
# он несколько проверок подряд был unhealthy, а `docker compose up api` при нездоровой
# зависимости не запускает реплики).
cid = subprocess.run(["docker", "compose", "ps", "-q", "s3"], cwd=ROOT, capture_output=True, text=True).stdout.strip()
t0 = time.monotonic()
while time.monotonic() - t0 < 120:
st = subprocess.run(["docker", "inspect", "-f", "{{.State.Health.Status}}", cid], capture_output=True, text=True).stdout.strip()
if st == "healthy":
break
time.sleep(1)
log.append({"phase": "s3 healthcheck healthy again", "after_s": round(time.monotonic() - t0, 1), "status": st})
print(json.dumps(log[-1]), flush=True)
down = [e for e in log if e.get("phase", "").startswith("S3 down")]
ok = all(e["probe"]["upload"]["status"] == 503 and e["probe"]["download"]["status"] == 503
and e["probe"]["text_message"]["status"] == 201 and e["probe"]["ready"]["status"] == 200
for e in down) and all(e.get("upload_201_after_s") is not None for e in log if "upload_201_after_s" in e)
no5xx = all(p["status"] in (200, 201, 503) for e in log if "probe" in e for p in e["probe"].values())
ok = ok and st == "healthy"
print(json.dumps({"pass": ok and no5xx, "only_200_201_503": no5xx}))
if args.output:
Path(args.output).write_text(json.dumps({"pass": ok and no5xx, "phases": log}, ensure_ascii=False, indent=1))
return 0 if ok and no5xx else 1
alice, bob, _eve, chat = c.bootstrap()
att_ready = c.wait_ready(alice, upload(c, alice, chat, SAMPLE_PNG, "before.png"))
res = {}
try:
compose("stop", "worker")
queued = upload(c, alice, chat, SAMPLE_PNG, "accepted-before-outage.png")
log.step("worker stopped, job accepted before outage", attachment_id=queued["id"])
for action, undo in (("stop", "start"), ("pause", "unpause")):
compose(action, "s3")
time.sleep(5) # S3Health (1 с) заметил отказ, данные устарели (3 с)
pr = probe(c, alice, chat, att_ready, queued)
res["s3_" + action] = pr
log.step("S3 `%s` for 5 s" % action, **pr)
check(pr["upload"]["status"] == 503 and pr["download_ready"]["status"] == 503
and pr["text_message"]["status"] == 201 and pr["ready"]["status"] == 200
and pr["metadata_queued"]["status"] == 200, "API during S3 %s: %s" % (action, pr))
if action == "stop":
compose("up", "-d", "--no-deps", "--no-recreate", "worker")
info = wait_until(lambda: (lambda i: i if "retry_scheduled" in events(i) else None)(
ops("inspect", queued["id"])), 60, 1, "worker retry on storage error")
retries = [e["detail"] for e in info["events"] if e["event"] == "retry_scheduled"]
res["worker_during_outage"] = {"events": events(info), "retries": retries}
log.step("worker meets S3 outage -> retry with backoff", **res["worker_during_outage"])
check(all(r["error_code"] == "storage_unavailable" for r in retries), "retry reason")
compose(undo, "s3")
t0 = time.monotonic()
wait_until(s3_healthy, 120, 1, "s3 healthy")
log.step("S3 `%s` -> healthy" % undo, seconds=round(time.monotonic() - t0, 1))
final = wait_status(c, bob, queued["id"], {"ready", "failed"}, 120)
replayed = None
if final["status"] == "failed":
check(final["error_code"] == "retry_exhausted", "unexpected failure " + str(final["error_code"]))
replayed = ops("replay", queued["id"], "--reason", "S3 restored")["replay"][0]["result"]
final = wait_status(c, bob, queued["id"], {"ready", "failed"}, 60)
info = ops("inspect", queued["id"])
res["accepted_job"] = {"final": final["status"], "replay": replayed, "attempts": info["jobs"][0]["attempt"],
"events": events(info)}
check(final["status"] == "ready", "accepted job not completed")
log.step("job accepted before outage completed", **res["accepted_job"])
after = c.wait_ready(alice, upload(c, alice, chat, SAMPLE_PNG, "after.png"))
res["upload_after_recovery"] = after["status"]
log.step("upload after recovery", status=after["status"])
finally:
compose("unpause", "s3", ok=False)
compose("start", "s3", ok=False)
compose("up", "-d", "--no-deps", "--no-recreate", "--wait", "worker", ok=False)
log.save(args.output, results=res)
print("PASS: S3 outage handled by API (503) and worker (retry), accepted work completed")
if __name__ == "__main__":
sys.exit(main())
main()