forked from mtusi2026/mtusi2026lab6
189 lines
11 KiB
Python
189 lines
11 KiB
Python
#!/usr/bin/env python3
|
||
"""Трек 2: доказанная идемпотентность versioned pipeline — автоматическая инъекция отказов.
|
||
|
||
Каждый сценарий внедряет отказ, ждёт завершения и проверяет инварианты (python -m messenger jobs
|
||
invariants: I1 нет потерь, I2 один набор вариантов на ключ эффекта, I3 один COMMIT на работу,
|
||
I4 монотонный указатель версии, I5 ready не откатывается, I6 fencing, I7 нет осиротевших объектов).
|
||
D дубли: 8 копий сообщения одной работы одновременно (worker'ы стартуют на полной очереди)
|
||
R reorder: устаревшие попытки (attempt 1, 2) приходят после attempt 3; попытка «из будущего»
|
||
C crash до побочного эффекта / после записи S3 до COMMIT / после COMMIT до ack / зависание (fencing)
|
||
V1 устаревшая работа после новой версии: v2 опубликована, затем исполняется v1 → superseded без эффектов
|
||
V2 гонка версий: v1 медленно пишет результат, v2 фиксируется раньше → v1 не двигает указатель назад
|
||
V3 повторная доставка v1 после перехода на v2 и повтор reprocess — no-op
|
||
ВНИМАНИЕ: останавливает/пересоздаёт worker (в т. ч. с WORKER_PIPELINES=2), volumes не трогает.
|
||
"""
|
||
import os
|
||
import shlex
|
||
import subprocess
|
||
import time
|
||
import uuid
|
||
|
||
from common import (BASE_URL, DC, ROOT, Client, Suite, check, events, jobs_cli, login, make_png, new_user, s3_admin,
|
||
sh, sql, upload, wait_status, wait_until)
|
||
|
||
LEASE = float(os.environ.get("JOB_LEASE_SECONDS", "20"))
|
||
c = Client(BASE_URL, timeout=30)
|
||
s = Suite("track 2: pipeline idempotency (" + BASE_URL + ")")
|
||
alice = new_user(c, "ia"); login(c, alice)
|
||
chat = c.call("POST", "/api/v1/chats", 201, actor=alice, schema="Chat",
|
||
body={"title": "idempotency", "member_ids": [alice["id"]]})["json"]
|
||
START = sql("SELECT to_char(clock_timestamp() AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"')")[0]
|
||
|
||
|
||
def workers(pipelines=None):
|
||
"""Пересоздать worker'ы с заданным WORKER_PIPELINES (None — по умолчанию 1,2) и дождаться healthy."""
|
||
env = dict(os.environ)
|
||
if pipelines:
|
||
env["WORKER_PIPELINES"] = pipelines
|
||
else:
|
||
env.pop("WORKER_PIPELINES", None)
|
||
subprocess.run(shlex.split(DC) + ["up", "-d", "--no-deps", "--force-recreate", "--wait", "worker"], cwd=ROOT,
|
||
check=True, timeout=180, env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||
|
||
|
||
def names(aid):
|
||
return [e["event"] for e in events(aid)]
|
||
|
||
|
||
def jobs_of(aid):
|
||
return {j["pipeline_version"]: j for j in jobs_cli("status", aid)["jobs"]}
|
||
|
||
|
||
def invariants(scope_since=START):
|
||
r = jobs_cli("invariants", "--settled", "--verify-bytes", "--since", scope_since, expect=(0, 1))
|
||
check(r["ok"], "invariants violated: %s" % r["violations"])
|
||
return r["stats"]
|
||
|
||
|
||
def served(aid):
|
||
return {v["name"]: v["sha256"] for v in
|
||
c.call("GET", "/api/v1/attachments/" + aid, actor=alice, schema="Attachment")["json"]["variants"]}
|
||
|
||
|
||
def v_rows(aid):
|
||
return sql("SELECT pipeline_version || ':' || name || ':' || sha256 FROM attachment_variants"
|
||
" WHERE attachment_id = '%s' ORDER BY 1" % aid)
|
||
|
||
|
||
@s.case("D: 8 duplicate copies of one job delivered concurrently → one claim, one commit")
|
||
def _():
|
||
sh("stop_worker", timeout=120)
|
||
try:
|
||
att, _ = upload(c, alice, chat, make_png(70, 50), filename="dup.png")
|
||
wait_until(lambda: "published" in names(att["id"]), timeout=30)
|
||
job = jobs_of(att["id"])[1]
|
||
jobs_cli("publish-raw", "--job", job["job_id"], "--count", "8")
|
||
finally:
|
||
sh("start_worker", timeout=120)
|
||
wait_status(c, alice, att["id"], ("ready", "failed"), timeout=60)
|
||
wait_until(lambda: names(att["id"]).count("duplicate_ignored") == 8, timeout=LEASE * 3, interval=1)
|
||
seq = names(att["id"])
|
||
check(seq.count("claimed") == 1 and seq.count("committed") == 1 and "lease_takeover" not in seq, "%s" % seq)
|
||
check(len(v_rows(att["id"])) == 3, "variant rows")
|
||
return "9 deliveries: claimed 1, committed 1, duplicate_ignored 8"
|
||
|
||
|
||
@s.case("R: reorder — stale attempts (1, 2) and a future one arrive DURING attempt 3 → ignored")
|
||
def _():
|
||
# попытки 1–2 падают «временно», попытка 3 медленная (15 с) — в это окно приходят старые сообщения
|
||
att, _ = upload(c, alice, chat, make_png(44, 44), filename="fault-transient-2-fault-slow-15.png")
|
||
wait_until(lambda: names(att["id"]).count("claimed") == 3, timeout=60, interval=0.5)
|
||
job = jobs_of(att["id"])[1]
|
||
check(job["attempt"] == 3 and job["status"] == "processing", "job %s/%s" % (job["status"], job["attempt"]))
|
||
for a in (2, 1, 9):
|
||
jobs_cli("publish-raw", "--job", job["job_id"], "--attempt", a)
|
||
wait_until(lambda: names(att["id"]).count("stale_ignored") == 3, timeout=30, interval=1)
|
||
check(jobs_of(att["id"])[1]["status"] == "processing", "stale message interrupted the live attempt")
|
||
wait_status(c, alice, att["id"], "ready", timeout=60)
|
||
seq = names(att["id"])
|
||
check(seq.count("committed") == 1 and seq.count("claimed") == 3 and "lease_takeover" not in seq, "%s" % seq)
|
||
future = [e for e in events(att["id"]) if e["event"] == "stale_ignored" and (e["detail"] or {}).get("future")]
|
||
check(len(future) == 1 and len(v_rows(att["id"])) == 3, "future attempt / variants")
|
||
return "during attempt 3: attempts 2, 1 → stale_ignored; 9 → stale_ignored(future) + term; one commit"
|
||
|
||
|
||
@s.case("C: crash before/after side effect, after COMMIT, hung worker — all reach one result")
|
||
def _():
|
||
kinds = ["crash-before-s3", "crash-after-s3", "crash-after-commit", "hang-40"]
|
||
ids = {k: upload(c, alice, chat, make_png(60, 61), filename="fault-%s-m.png" % k)[0]["id"] for k in kinds}
|
||
for k, aid in ids.items():
|
||
check(wait_status(c, alice, aid, ("ready", "failed"), timeout=LEASE * 6)["status"] == "ready", k)
|
||
wait_until(lambda: "lease_lost" in names(ids["hang-40"]), timeout=60, interval=1)
|
||
out = {}
|
||
for k, aid in ids.items():
|
||
seq = names(aid)
|
||
check(seq.count("committed") == 1, "%s: %s" % (k, seq))
|
||
out[k] = "takeover" if "lease_takeover" in seq else ("dup_ignored" if "duplicate_ignored" in seq else "-")
|
||
return "%s" % out
|
||
|
||
|
||
@s.case("V1: stale v1 job after v2 is published → superseded, no v1 side effects")
|
||
def _():
|
||
sh("stop_worker", timeout=120)
|
||
att, data = upload(c, alice, chat, make_png(150, 100), filename="v1-after-v2.png")
|
||
r = jobs_cli("reprocess", "--attachment", att["id"], "--pipeline-version", 2)
|
||
check(r["result"] == "enqueued", "%s" % r)
|
||
wait_until(lambda: names(att["id"]).count("published") == 2, timeout=30)
|
||
workers("2") # только v2-worker'ы: v1 откладывается (nak), v2 исполняется
|
||
try:
|
||
wait_until(lambda: jobs_of(att["id"])[2]["status"] == "ready", timeout=60)
|
||
finally:
|
||
workers() # снова 1,2 — теперь доходит устаревшая v1
|
||
wait_until(lambda: jobs_of(att["id"])[1]["status"] == "superseded", timeout=LEASE * 2, interval=1)
|
||
rows = v_rows(att["id"])
|
||
check(all(r.startswith("2:") for r in rows) and len(rows) == 3, "v1 wrote variants: %s" % rows)
|
||
check(s3_admin("ls", "variants/%s/v1/" % att["id"].replace("-", "")) == "", "v1 objects exist")
|
||
meta = c.call("GET", "/api/v1/attachments/" + att["id"], actor=alice, schema="Attachment")["json"]
|
||
check(meta["status"] == "ready", "status")
|
||
check(sql("SELECT published_version FROM attachments WHERE id = '%s'" % att["id"]) == ["2"], "pointer")
|
||
return "v2 ready first; v1 → superseded at claim; variants only v2, pointer 2"
|
||
|
||
|
||
@s.case("V2: version race — slow v1 commits after v2 → pointer stays on v2 (no overwrite by older)")
|
||
def _():
|
||
att, _ = upload(c, alice, chat, make_png(140, 90), filename="race-fault-slow-12-v1.png")
|
||
wait_until(lambda: "claimed" in names(att["id"]), timeout=30, interval=0.5)
|
||
jobs_cli("reprocess", "--attachment", att["id"], "--pipeline-version", 2)
|
||
wait_until(lambda: jobs_of(att["id"]).get(2, {}).get("status") == "ready", timeout=60)
|
||
check(sql("SELECT published_version FROM attachments WHERE id = '%s'" % att["id"]) == ["2"], "v2 not published")
|
||
v2_served = served(att["id"])
|
||
wait_until(lambda: jobs_of(att["id"])[1]["status"] in ("superseded", "ready"), timeout=60, interval=1)
|
||
j1 = jobs_of(att["id"])[1]
|
||
check(j1["status"] == "superseded", "v1 status %s" % j1["status"])
|
||
check(sql("SELECT published_version FROM attachments WHERE id = '%s'" % att["id"]) == ["2"], "pointer moved back")
|
||
check(served(att["id"]) == v2_served, "served variants changed")
|
||
ev = [e for e in events(att["id"]) if e["event"] == "published_version_changed"]
|
||
check([e["detail"]["to"] for e in ev] == [2], "pointer history %s" % [e["detail"] for e in ev])
|
||
return "v1 finished after v2 → superseded at commit; pointer history %s" % [(e["detail"]["from"], e["detail"]["to"]) for e in ev]
|
||
|
||
|
||
@s.case("V3: redelivered v1 after v2 rollout and repeated reprocess are no-ops")
|
||
def _():
|
||
att, _ = upload(c, alice, chat, make_png(64, 48), filename="rollout.png")
|
||
wait_status(c, alice, att["id"], "ready")
|
||
v1_served = served(att["id"])
|
||
jobs_cli("reprocess", "--attachment", att["id"], "--pipeline-version", 2)
|
||
wait_until(lambda: sql("SELECT published_version FROM attachments WHERE id = '%s'" % att["id"]) == ["2"], timeout=60)
|
||
v2_served = served(att["id"])
|
||
check(v2_served != v1_served and set(v2_served) == set(v1_served), "v2 variants not served")
|
||
j = jobs_of(att["id"])
|
||
jobs_cli("publish-raw", "--job", j[1]["job_id"], "--count", "3")
|
||
r1 = jobs_cli("reprocess", "--attachment", att["id"], "--pipeline-version", 2)
|
||
r2 = jobs_cli("reprocess", "--attachment", att["id"], "--pipeline-version", 1)
|
||
check(r1["result"] == r2["result"] == "noop", "%s %s" % (r1, r2))
|
||
wait_until(lambda: names(att["id"]).count("duplicate_ignored") >= 3, timeout=30, interval=1)
|
||
check(served(att["id"]) == v2_served, "v1 duplicate changed result")
|
||
check(sql("SELECT published_version FROM attachments WHERE id = '%s'" % att["id"]) == ["2"], "pointer")
|
||
return "v1 ready → v2 ready (pointer 1→2); 3 v1 duplicates ignored; reprocess v1/v2 again → noop"
|
||
|
||
|
||
@s.case("invariants I1–I7 hold for everything this suite produced (settled, bytes verified)")
|
||
def _():
|
||
wait_until(lambda: jobs_cli("invariants", "--settled", "--since", START, expect=(0, 1))["ok"], timeout=60, interval=2)
|
||
st = invariants()
|
||
return "attachments %s, jobs %s %s, variants %s, events %s" % (
|
||
st["attachments"], st["jobs"], st["job_status"], st["variants"], st["events"])
|
||
|
||
|
||
s.run()
|