ЛР5: устойчивый versioned pipeline изображений, outbox и доказательства отказов
This commit is contained in:
@@ -0,0 +1,263 @@
|
||||
"""Explicit reordered deliveries, retry backoff, and synchronized cleanup/replay races."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from fault_suite import (
|
||||
COMPOSE,
|
||||
command,
|
||||
compose,
|
||||
fault,
|
||||
job,
|
||||
operation,
|
||||
reached,
|
||||
runtime,
|
||||
sql,
|
||||
wait_until,
|
||||
)
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client
|
||||
|
||||
|
||||
def main():
|
||||
result = {"scenarios": []}
|
||||
compose("up", "-d", "--no-build", "--wait", "api", "worker", "dispatcher", "lb")
|
||||
c = Client("http://127.0.0.1:8085")
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
|
||||
def upload():
|
||||
return c.attachment(alice, chat)[0]["id"]
|
||||
|
||||
def ready(aid):
|
||||
return c.wait_ready(bob, {"id": aid})
|
||||
|
||||
def replay_command(aid):
|
||||
return command(
|
||||
COMPOSE
|
||||
+ [
|
||||
"exec",
|
||||
"-T",
|
||||
"--index",
|
||||
"2",
|
||||
"api",
|
||||
"python",
|
||||
"-m",
|
||||
"messenger.jobctl",
|
||||
"replay",
|
||||
aid,
|
||||
],
|
||||
check=False,
|
||||
)
|
||||
|
||||
def make_failed():
|
||||
compose("stop", "worker")
|
||||
aid = upload()
|
||||
sql(f"UPDATE attachment_jobs SET attempt_limit=1 WHERE attachment_id='{aid}'")
|
||||
fault("before_effect", aid, "error")
|
||||
compose("start", "worker")
|
||||
wait_until(lambda: job(aid)["state"] == "failed")
|
||||
return aid
|
||||
|
||||
try:
|
||||
# Two real transient failures before eventual successful processing.
|
||||
compose("stop", "worker")
|
||||
aid = upload()
|
||||
fault("before_effect", aid, "error")
|
||||
fault("before_effect", aid, "error")
|
||||
compose("start", "worker")
|
||||
ready(aid)
|
||||
assert job(aid)["attempt"] == 3
|
||||
audits = sql(
|
||||
f"SELECT event,attempt,created_at FROM job_audit WHERE job_id='{job(aid)['id']}' ORDER BY id",
|
||||
rows=True,
|
||||
)
|
||||
retries = [a for a in audits if a["event"] == "retry_scheduled"]
|
||||
claims = [a for a in audits if a["event"] == "claimed"]
|
||||
delays = [
|
||||
(
|
||||
datetime.fromisoformat(claims[i + 1]["created_at"])
|
||||
- datetime.fromisoformat(retries[i]["created_at"])
|
||||
).total_seconds()
|
||||
for i in range(2)
|
||||
]
|
||||
assert delays[0] >= 1 and delays[1] >= 2
|
||||
result["scenarios"].append(
|
||||
{
|
||||
"name": "transient_retry_backoff_and_jitter",
|
||||
"attachment_id": aid,
|
||||
"attempts": 3,
|
||||
"observed_delays_seconds": delays,
|
||||
"audit": audits,
|
||||
"passed": True,
|
||||
}
|
||||
)
|
||||
|
||||
# Reorder actual broker messages AFTER v2 is already public.
|
||||
operation(f"print(j.reprocess('{aid}',2,o))")
|
||||
before = ready(aid)
|
||||
ids = sql(
|
||||
f"SELECT id,pipeline_version FROM attachment_jobs WHERE attachment_id='{aid}' ORDER BY pipeline_version",
|
||||
rows=True,
|
||||
)
|
||||
v1, v2 = ids
|
||||
snippet = (
|
||||
"import json; from messenger.jobs import broker_client,STREAM; b=broker_client(); "
|
||||
f"versions=[('{v2['id']}',2),('{v1['id']}',1),('{v2['id']}',2)]; "
|
||||
f"[b.xadd(STREAM,{{'body':json.dumps({{'schema_version':1,'job_id':jid,'type':'attachment.process.v1','attachment_id':'{aid}','pipeline_version':version,'attempt':1,'created_at':'2026-11-06T00:00:00Z'}})}}) for jid,version in versions]; print('reordered v2,v1,v2')"
|
||||
)
|
||||
operation(snippet)
|
||||
time.sleep(2)
|
||||
assert ready(aid) == before
|
||||
hashes = {}
|
||||
for variant in ["original", "thumbnail", "crop", "optimized"]:
|
||||
data = c.call("GET", f"/api/v1/attachments/{aid}/content?variant={variant}", actor=bob)[
|
||||
"bytes"
|
||||
]
|
||||
hashes[variant] = hashlib.sha256(data).hexdigest()
|
||||
publications = sql(
|
||||
f"SELECT pipeline_version,count(*) AS n FROM attachment_jobs j JOIN job_audit a ON a.job_id=j.id WHERE j.attachment_id='{aid}' AND a.event='published' GROUP BY pipeline_version ORDER BY pipeline_version",
|
||||
rows=True,
|
||||
)
|
||||
assert publications == [{"pipeline_version": 1, "n": 1}, {"pipeline_version": 2, "n": 1}]
|
||||
result["scenarios"].append(
|
||||
{
|
||||
"name": "broker_reorder_v2_v1_v2_no_regression",
|
||||
"attachment_id": aid,
|
||||
"hashes": hashes,
|
||||
"publications": publications,
|
||||
"passed": True,
|
||||
}
|
||||
)
|
||||
|
||||
# Malformed jobs are rejected and acknowledged, including non-UTF8 bytes.
|
||||
worker_before = next(item for item in runtime() if item["service"] == "worker")
|
||||
snippet = (
|
||||
"import json; from messenger.jobs import broker_client,STREAM; b=broker_client(); "
|
||||
f"base={{'schema_version':1,'job_id':'{v2['id']}','type':'attachment.process.v1','attachment_id':'{aid}','pipeline_version':2,'attempt':1,'created_at':'2026-11-06T00:00:00Z'}}; "
|
||||
"bad=[json.dumps({**base,'job_id':123}),json.dumps({**base,'attachment_id':[]}),json.dumps({**base,'schema_version':True}),json.dumps({**base,'created_at':123}),bytes([255]),bytes([110,111,116,45,106,115,111,110])]; "
|
||||
"[b.xadd(STREAM,{'body':payload}) for payload in bad]; print('6 malformed deliveries')"
|
||||
)
|
||||
operation(snippet)
|
||||
normal = upload()
|
||||
ready(normal)
|
||||
worker_after = next(item for item in runtime() if item["service"] == "worker")
|
||||
assert worker_after["container_id"] == worker_before["container_id"]
|
||||
assert worker_after["restart_count"] == worker_before["restart_count"]
|
||||
logs = compose("logs", "--tail", "100", "worker").stdout
|
||||
assert logs.count('"event": "invalid_delivery"') >= 6
|
||||
result["scenarios"].append(
|
||||
{
|
||||
"name": "six_poison_deliveries_rejected_without_worker_crash",
|
||||
"attachment_id": normal,
|
||||
"worker_before": worker_before,
|
||||
"worker_after": worker_after,
|
||||
"safe_log_events": 6,
|
||||
"passed": True,
|
||||
}
|
||||
)
|
||||
|
||||
# Simulated old metadata must not make accepted queued staging eligible for cleanup.
|
||||
compose("stop", "worker")
|
||||
aid = upload()
|
||||
sql(
|
||||
f"UPDATE attachments SET created_at=now()-interval '8 days',updated_at=now()-interval '8 days' WHERE id='{aid}'"
|
||||
)
|
||||
operation("from messenger.jobctl import cleanup; print(cleanup(s,o,0,0))")
|
||||
assert job(aid)["state"] == "queued"
|
||||
source_present = operation(
|
||||
f"\nwith s.connection() as conn:\n a=conn.execute(\"SELECT stage_key FROM attachments WHERE id=%s\",('{aid}',)).fetchone()\n print(o.exists(a['stage_key']))"
|
||||
)
|
||||
assert source_present == "True"
|
||||
compose("start", "worker")
|
||||
ready(aid)
|
||||
result["scenarios"].append(
|
||||
{
|
||||
"name": "eight_day_old_queued_metadata_never_expires_staging",
|
||||
"attachment_id": aid,
|
||||
"age_simulated_in_database": True,
|
||||
"passed": True,
|
||||
}
|
||||
)
|
||||
|
||||
# Cleanup stops AFTER its final state check, BEFORE actual S3 DELETE, holding row lock.
|
||||
aid = make_failed()
|
||||
fid = fault("cleanup_before_delete", aid, "pause")
|
||||
with ThreadPoolExecutor(2) as executor:
|
||||
cleaner = executor.submit(
|
||||
operation, "from messenger.jobctl import cleanup; print(cleanup(s,o,0,3600))"
|
||||
)
|
||||
wait_until(lambda: reached(fid))
|
||||
replay = executor.submit(replay_command, aid).result(timeout=15)
|
||||
assert replay.returncode == 1
|
||||
assert json.loads(replay.stdout)["status"] == 503
|
||||
sql(f"UPDATE test_faults SET released=true WHERE id={fid}")
|
||||
cleaner.result(timeout=15)
|
||||
refused = replay_command(aid)
|
||||
assert refused.returncode == 1 and json.loads(refused.stdout)["status"] == 409
|
||||
assert job(aid)["state"] == "failed"
|
||||
result["scenarios"].append(
|
||||
{
|
||||
"name": "cleanup_paused_before_delete_blocks_concurrent_replay",
|
||||
"attachment_id": aid,
|
||||
"while_locked_status": 503,
|
||||
"after_source_expiry_status": 409,
|
||||
"passed": True,
|
||||
}
|
||||
)
|
||||
|
||||
# Reverse ordering: replay holds the lock before its queued COMMIT.
|
||||
aid = make_failed()
|
||||
fid = fault("replay_before_commit", aid, "pause")
|
||||
with ThreadPoolExecutor(2) as executor:
|
||||
replayer = executor.submit(replay_command, aid)
|
||||
wait_until(lambda: reached(fid))
|
||||
cleaning = executor.submit(
|
||||
command,
|
||||
COMPOSE
|
||||
+ [
|
||||
"exec",
|
||||
"-T",
|
||||
"--index",
|
||||
"2",
|
||||
"api",
|
||||
"python",
|
||||
"-m",
|
||||
"messenger.jobctl",
|
||||
"cleanup",
|
||||
"--failed-hours",
|
||||
"0",
|
||||
],
|
||||
False,
|
||||
).result(timeout=15)
|
||||
assert cleaning.returncode == 1 and json.loads(cleaning.stdout)["status"] == 503
|
||||
sql(f"UPDATE test_faults SET released=true WHERE id={fid}")
|
||||
assert replayer.result(timeout=15).returncode == 0
|
||||
ready(aid)
|
||||
operation("from messenger.jobctl import cleanup; print(cleanup(s,o,0,3600))")
|
||||
ready(aid)
|
||||
result["scenarios"].append(
|
||||
{
|
||||
"name": "replay_holds_lock_cleanup_cannot_delete_then_ready",
|
||||
"attachment_id": aid,
|
||||
"cleanup_while_locked_status": 503,
|
||||
"passed": True,
|
||||
}
|
||||
)
|
||||
result["passed"] = True
|
||||
finally:
|
||||
sql("UPDATE test_faults SET released=true WHERE reached_at IS NOT NULL")
|
||||
command(
|
||||
["docker", "compose", "up", "-d", "--no-build", "--wait", "api", "worker", "dispatcher"]
|
||||
)
|
||||
Path("evidence/extra-invariants.json").write_text(json.dumps(result, indent=2))
|
||||
print("PASS: backoff, reordered deliveries and both real cleanup/replay interleavings")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user