лаба на 5

This commit is contained in:
2026-11-12 15:32:10 +03:00
parent 910252c277
commit 0edfe46482
13 changed files with 1378 additions and 31 deletions
+160
View File
@@ -0,0 +1,160 @@
import json
import subprocess
import sys
import time
from pathlib import Path
from client import Client, check
from fault_injection_grade5 import job_state
ROOT = Path(__file__).resolve().parents[1]
COMPOSE = ["docker", "compose", "-f", "compose.yaml", "-f", "compose.concurrent.yaml"]
MARKER = "/tmp/lab5_pause_before_commit"
def run(*args, check_result=True):
return subprocess.run(
args,
cwd=ROOT,
capture_output=True,
text=True,
check=check_result,
)
def compose(*args):
return run(*COMPOSE, *args)
def sql(query):
result = run(
"docker", "compose", "exec", "-T", "postgres",
"psql", "-U", "lab2", "-d", "messenger",
"-t", "-A", "-c", query,
)
return result.stdout.strip()
def wait_until(predicate, timeout, message):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
if predicate():
return
time.sleep(0.25)
raise AssertionError(message)
def marker_exists():
result = run(
*COMPOSE,
"exec", "-T", "worker",
"test", "-f", MARKER,
check_result=False,
)
return result.returncode == 0
def release_worker():
compose("exec", "-T", "worker", "rm", "-f", MARKER)
def main():
try:
compose("up", "-d", "--build", "--force-recreate", "worker")
client = Client()
alice, bob, _, chat = client.bootstrap()
attachment, original = client.attachment(alice, chat)
attachment_id = attachment["id"]
wait_until(
marker_exists,
60,
"first worker did not pause",
)
first = job_state(attachment_id)
check(first["job_status"] == "processing", "first execution not processing")
check(first["execution_id"] is not None, "missing execution ID")
sql(f"""
UPDATE attachment_jobs
SET started_at = now() - interval '120 seconds'
WHERE id = '{first["job_id"]}'
AND status = 'processing';
""")
wait_until(
lambda: (
job_state(attachment_id)["execution_id"]
!= first["execution_id"]
),
15,
"dispatcher did not release the old execution",
)
compose("up", "-d", "--build", "worker-second")
deadline = time.monotonic() + 120
while time.monotonic() < deadline:
state = job_state(attachment_id)
if state["job_status"] == "ready":
break
time.sleep(0.25)
else:
raise AssertionError("second worker did not complete the job")
check(state["execution_id"] != first["execution_id"], "execution ID unchanged")
check(state["attachment_status"] == "ready", "attachment not ready")
release_worker()
time.sleep(3)
after = job_state(attachment_id)
check(after == state, "old execution overwrote newer result")
content = client.call(
"GET",
f"/api/v1/attachments/{attachment_id}/content",
actor=bob,
)
check(content["bytes"] == original, "original content changed")
print("PASS: stale execution rejected after newer execution completed")
finally:
try:
release_worker()
except Exception:
pass
try:
compose("stop", "worker-second")
except Exception:
pass
run(
"docker", "compose",
"up", "-d", "--force-recreate", "worker",
)
print("Normal worker configuration restored")
if __name__ == "__main__":
try:
main()
except Exception as exc:
print(f"FAIL: {exc}", file=sys.stderr)
raise SystemExit(1)
+129
View File
@@ -0,0 +1,129 @@
import json
import subprocess
import sys
import time
from pathlib import Path
from client import Client, check
ROOT = Path(__file__).resolve().parents[1]
OVERRIDE = ROOT / "compose.fault.yaml"
POINTS = ("before_side_effect", "after_side_effect", "before_ack")
CONTAINER = "mtusi2026lab5-worker-1"
def command(*args):
return subprocess.run(
args,
cwd=ROOT,
capture_output=True,
text=True,
check=True,
)
def configure(point):
OVERRIDE.write_text(
"services:\n"
" worker:\n"
" environment:\n"
' FAULT_INJECTION_ENABLED: "1"\n'
f" FAULT_INJECTION_POINT: {point}\n",
encoding="utf-8",
)
command(
"docker", "compose",
"-f", "compose.yaml",
"-f", "compose.fault.yaml",
"up", "-d", "--force-recreate", "worker",
)
def restore():
command(
"docker", "compose",
"up", "-d", "--force-recreate", "worker",
)
def restart_count():
result = command(
"docker", "inspect",
"-f", "{{.RestartCount}}",
CONTAINER,
)
return int(result.stdout.strip())
def crash_logged(point):
result = command(
"docker", "logs", CONTAINER,
)
return f"FAULT INJECTION: {point}" in result.stderr + result.stdout
def run_case(point):
print(f"RUN: {point}", flush=True)
configure(point)
client = Client()
alice, bob, _, chat = client.bootstrap()
attachment, original = client.attachment(alice, chat)
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
if restart_count() >= 1 and crash_logged(point):
break
time.sleep(0.5)
else:
raise AssertionError(f"{point}: worker did not crash")
ready = client.wait_ready(bob, attachment, wait_seconds=150)
check(ready["status"] == "ready", f"{point}: not ready")
content = client.call(
"GET",
f"/api/v1/attachments/{attachment['id']}/content",
actor=bob,
)
check(content["bytes"] == original, f"{point}: original changed")
for variant in ("thumbnail", "crop", "optimized"):
response = client.call(
"GET",
f"/api/v1/attachments/{attachment['id']}/content?variant={variant}",
actor=bob,
)
check(bool(response["bytes"]), f"{point}: {variant} is empty")
check(restart_count() == 1, f"{point}: unexpected restart count")
print(
f"PASS: {point}, recovered, original and variants intact",
flush=True,
)
def main():
try:
for point in POINTS:
run_case(point)
finally:
print("Restoring normal worker configuration...", flush=True)
restore()
print("FAULT INJECTION DISABLED", flush=True)
if __name__ == "__main__":
try:
main()
except (AssertionError, subprocess.CalledProcessError, OSError) as exc:
print(f"FAIL: {exc}", file=sys.stderr)
raise SystemExit(1)
+463
View File
@@ -0,0 +1,463 @@
import json
import subprocess
import time
from pathlib import Path
import pika
from client import Client, check
ROOT = Path(__file__).resolve().parents[1]
BASE_URL = "http://localhost:8080"
def sql(query):
result = subprocess.run(
[
"docker", "compose", "exec", "-T", "postgres",
"psql", "-U", "lab2", "-d", "messenger",
"-t", "-A", "-c", query,
],
cwd=ROOT,
capture_output=True,
text=True,
check=True,
)
return result.stdout.strip()
def job_state(attachment_id):
result = sql(f"""
SELECT row_to_json(t)
FROM (
SELECT
j.id AS job_id,
j.attachment_id,
j.status AS job_status,
a.status AS attachment_status,
j.attempt,
j.generation,
j.execution_id,
j.finished_at,
a.s3_key,
a.variants
FROM attachment_jobs j
JOIN attachments a ON a.id = j.attachment_id
WHERE a.id = '{attachment_id}'
) t;
""")
check(bool(result), "job not found")
return json.loads(result)
def publish_duplicate(payload):
result = subprocess.run(
[
"docker", "compose", "exec", "-T", "worker",
"python", "-c",
"""
import json
import sys
import pika
from src.queue import connect, QUEUE
payload = json.loads(sys.stdin.read())
connection, channel = connect()
channel.confirm_delivery()
channel.basic_publish(
exchange="",
routing_key=QUEUE,
body=json.dumps(payload).encode(),
properties=pika.BasicProperties(
delivery_mode=2,
content_type="application/json",
message_id=payload["job_id"],
),
mandatory=True,
)
connection.close()
""",
],
cwd=ROOT,
input=json.dumps(payload),
capture_output=True,
text=True,
check=True,
)
return result
def test_duplicate():
client = Client(BASE_URL)
alice, bob, _, chat = client.bootstrap()
attachment, original = client.attachment(alice, chat)
attachment_id = attachment["id"]
client.wait_ready(bob, attachment, wait_seconds=120)
before = job_state(attachment_id)
check(before["job_status"] == "ready", "job is not ready")
check(before["attachment_status"] == "ready", "attachment is not ready")
payload = {
"schema_version": 1,
"job_id": before["job_id"],
"type": "attachment.process.v1",
"attachment_id": attachment_id,
"pipeline_version": 1,
"attempt": before["attempt"],
"generation": before["generation"],
"created_at": "2026-01-01T00:00:00Z",
}
publish_duplicate(payload)
publish_duplicate(payload)
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
queue = subprocess.run(
[
"docker", "compose", "exec", "-T", "rabbitmq",
"rabbitmqctl", "list_queues",
"name", "messages_ready", "messages_unacknowledged",
"--quiet",
],
cwd=ROOT,
capture_output=True,
text=True,
check=True,
)
lines = queue.stdout.splitlines()
matching = [
line.split()
for line in lines
if line.startswith("attachment.process.v1")
]
if matching and matching[0][1:] == ["0", "0"]:
break
time.sleep(1)
else:
raise AssertionError("duplicate messages were not consumed")
after = job_state(attachment_id)
check(before == after, "duplicate delivery changed committed result")
content = client.call(
"GET",
f"/api/v1/attachments/{attachment_id}/content",
actor=bob,
)
check(content["bytes"] == original, "original content changed")
print("PASS: duplicate delivery, state unchanged, original intact")
def test_reorder():
client = Client(BASE_URL)
alice, bob, _, chat = client.bootstrap()
attachment, original = client.attachment(alice, chat)
attachment_id = attachment["id"]
client.wait_ready(bob, attachment, wait_seconds=120)
before = job_state(attachment_id)
check(before["job_status"] == "ready", "job is not ready")
payload = {
"schema_version": 1,
"job_id": before["job_id"],
"type": "attachment.process.v1",
"attachment_id": attachment_id,
"pipeline_version": 1,
"attempt": before["attempt"],
"generation": before["generation"],
"created_at": "2026-01-01T00:00:00Z",
}
for attempt in (
before["attempt"] + 1,
before["attempt"] - 1,
before["attempt"],
):
message = dict(payload)
message["attempt"] = attempt
publish_duplicate(message)
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
queue = subprocess.run(
[
"docker", "compose", "exec", "-T", "rabbitmq",
"rabbitmqctl", "list_queues",
"name", "messages_ready", "messages_unacknowledged",
"--quiet",
],
cwd=ROOT,
capture_output=True,
text=True,
check=True,
)
matching = [
line.split()
for line in queue.stdout.splitlines()
if line.startswith("attachment.process.v1")
]
if matching and matching[0][1:] == ["0", "0"]:
break
time.sleep(1)
else:
raise AssertionError("reordered messages were not consumed")
after = job_state(attachment_id)
check(before == after, "reordered delivery changed committed result")
content = client.call(
"GET",
f"/api/v1/attachments/{attachment_id}/content",
actor=bob,
)
check(content["bytes"] == original, "original content changed")
print("PASS: reordered attempts, state unchanged, original intact")
def test_stale_generation():
client = Client(BASE_URL)
alice, bob, _, chat = client.bootstrap()
attachment, original = client.attachment(alice, chat)
attachment_id = attachment["id"]
client.wait_ready(bob, attachment, wait_seconds=120)
before = job_state(attachment_id)
check(before["job_status"] == "ready", "job is not ready")
check(before["generation"] == 1, "unexpected initial generation")
payload = {
"schema_version": 1,
"job_id": before["job_id"],
"type": "attachment.process.v1",
"attachment_id": attachment_id,
"pipeline_version": 1,
"attempt": before["attempt"],
"generation": before["generation"],
"created_at": "2026-01-01T00:00:00Z",
}
for generation in (0, 2, 1):
message = dict(payload)
message["generation"] = generation
publish_duplicate(message)
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
queue = subprocess.run(
[
"docker", "compose", "exec", "-T", "rabbitmq",
"rabbitmqctl", "list_queues",
"name", "messages_ready", "messages_unacknowledged",
"--quiet",
],
cwd=ROOT,
capture_output=True,
text=True,
check=True,
)
matching = [
line.split()
for line in queue.stdout.splitlines()
if line.startswith("attachment.process.v1")
]
if matching and matching[0][1:] == ["0", "0"]:
break
time.sleep(1)
else:
raise AssertionError("generation messages were not consumed")
after = job_state(attachment_id)
check(before == after, "generation mismatch changed committed result")
content = client.call(
"GET",
f"/api/v1/attachments/{attachment_id}/content",
actor=bob,
)
check(content["bytes"] == original, "original content changed")
print("PASS: stale and future generations rejected, result unchanged")
def test_replay_generation():
client = Client(BASE_URL)
alice, bob, _, chat = client.bootstrap()
attachment, original = client.attachment(alice, chat)
attachment_id = attachment["id"]
client.wait_ready(bob, attachment, wait_seconds=120)
before = job_state(attachment_id)
check(before["job_status"] == "ready", "initial job is not ready")
check(before["generation"] == 1, "unexpected initial generation")
job_id = before["job_id"]
sql(f"""
BEGIN;
UPDATE attachment_jobs
SET status = 'failed',
last_error_code = 'test_replay',
finished_at = now(),
failed_published_at = now()
WHERE id = '{job_id}'
AND status = 'ready';
UPDATE attachments
SET status = 'failed',
error_code = 'test_replay',
updated_at = now()
WHERE id = '{attachment_id}'
AND status = 'ready';
COMMIT;
""")
result = subprocess.run(
[
"docker", "compose", "exec", "-T", "worker",
"python", "-m", "scripts.replay_job", job_id,
],
cwd=ROOT,
capture_output=True,
text=True,
check=True,
)
check("REPLAY ACCEPTED" in result.stdout, "replay was rejected")
replayed = job_state(attachment_id)
check(replayed["generation"] == 2, "generation did not increase")
stale_payload = {
"schema_version": 1,
"job_id": job_id,
"type": "attachment.process.v1",
"attachment_id": attachment_id,
"pipeline_version": 1,
"attempt": 1,
"generation": 1,
"created_at": "2026-01-01T00:00:00Z",
}
publish_duplicate(stale_payload)
deadline = time.monotonic() + 120
while time.monotonic() < deadline:
current = job_state(attachment_id)
if current["job_status"] == "ready":
break
check(current["job_status"] != "failed", "replay failed")
time.sleep(0.5)
else:
raise AssertionError("replayed job did not become ready")
check(current["generation"] == 2, "generation did not increase")
check(current["attachment_status"] == "ready", "attachment not ready")
check(current["execution_id"] != before["execution_id"], "execution ID unchanged")
payload = {
"schema_version": 1,
"job_id": job_id,
"type": "attachment.process.v1",
"attachment_id": attachment_id,
"pipeline_version": 1,
"attempt": 1,
"generation": 1,
"created_at": "2026-01-01T00:00:00Z",
}
publish_duplicate(payload)
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
queue = subprocess.run(
[
"docker", "compose", "exec", "-T", "rabbitmq",
"rabbitmqctl", "list_queues",
"name", "messages_ready", "messages_unacknowledged",
"--quiet",
],
cwd=ROOT,
capture_output=True,
text=True,
check=True,
)
matching = [
line.split()
for line in queue.stdout.splitlines()
if line.startswith("attachment.process.v1")
]
if matching and matching[0][1:] == ["0", "0"]:
break
time.sleep(1)
else:
raise AssertionError("stale message was not consumed")
after = job_state(attachment_id)
check(current == after, "stale generation overwrote newer result")
content = client.call(
"GET",
f"/api/v1/attachments/{attachment_id}/content",
actor=bob,
)
check(content["bytes"] == original, "original changed after replay")
print("PASS: replay generation 1 -> 2, stale message rejected")
if __name__ == "__main__":
test_duplicate()
test_reorder()
test_stale_generation()
test_replay_generation()