Реализовать наблюдаемость и доказательства уровня 4

This commit is contained in:
EgorAnti
2026-11-19 20:08:50 +03:00
parent 470d9d6f1e
commit 935de06050
195 changed files with 19333 additions and 53 deletions
+29
View File
@@ -0,0 +1,29 @@
# Student-owned tests
This directory contains additional experiments written for this implementation.
The course-provided black-box suite remains in `tests/`; Spring tests remain in
`src/test/java`.
- `idempotency_concurrent.py` — one key through multiple API replicas.
- `readiness_gate.py` — both replicas become unhealthy after the required
schema table disappears; readiness and business traffic must return 503,
then recover after the table is restored.
- `failover_each.py` — sequential process failover of both Compose replicas.
- `rolling_update.py` — sequential replacement under write load.
- `node_failover.py` — hard loss of one worker in the disposable three-node
Swarm lab, task relocation and confirmed-data verification.
- `lab4_negative.py` — oversized/corrupt/MIME-spoofed uploads, unsafe filename,
unknown attachment, foreign user and cross-chat binding; every user error is 4xx.
- `concurrent_upload_memory.py` — 12 simultaneous ~6.5 MiB valid PNG uploads and
aggregate API container memory sampling through `docker stats` (lab5 `202`
upload contract).
- `lab5_worker_recovery.py` — durable worker stop/restart, all three variants and
idempotent duplicate delivery.
- `lab5_fault_injection.py` — crashes after outbox commit and after result commit
but before consumer acknowledgement.
- `lab5_dlq_replay_lease.py` — permanent failure DLQ routing, guarded audited
replay, and expired processing-lease recovery.
- `lab5_pipeline_idempotency.py` — versioned pipeline v1/v2, audited promotion,
`superseded` fencing, duplicate/reordered/stale deliveries, and crashes before
and after the S3 side effect. The script prints invariant checks and a final
`PASS` line; it uses `.env.example` for the disposable test stand by default.
+145
View File
@@ -0,0 +1,145 @@
#!/usr/bin/env python3
"""Run 10+ simultaneous valid PNG uploads and sample aggregate API container RAM."""
import argparse
import binascii
import concurrent.futures
import json
import random
import re
import struct
import subprocess
import sys
import threading
import time
import zlib
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, Failure, check, run # noqa: E402
def png_chunk(kind, payload):
return (struct.pack('>I', len(payload)) + kind + payload
+ struct.pack('>I', binascii.crc32(kind + payload) & 0xffffffff))
def make_png(width=1800, height=1200):
rng = random.Random(20261111)
rows = bytearray()
for _ in range(height):
rows.append(0)
rows.extend(rng.randbytes(width * 3))
return (b'\x89PNG\r\n\x1a\n'
+ png_chunk(b'IHDR', struct.pack('>IIBBBBB', width, height, 8, 2, 0, 0, 0))
+ png_chunk(b'IDAT', zlib.compress(bytes(rows), 1))
+ png_chunk(b'IEND', b''))
def memory_bytes(value):
match = re.fullmatch(r'([0-9]+(?:\.[0-9]+)?)\s*([A-Za-z]+)', value.strip())
if not match:
raise ValueError('unrecognized Docker memory value: ' + value)
number, unit = match.groups()
factors = {'B': 1, 'kB': 1000, 'KiB': 1024, 'MB': 1000**2,
'MiB': 1024**2, 'GB': 1000**3, 'GiB': 1024**3}
return int(float(number) * factors[unit])
def api_containers(env_file):
result = subprocess.run(
['docker', 'compose', '--env-file', env_file, 'ps', '-q', 'api'],
cwd=ROOT, check=True, capture_output=True, text=True)
ids = [line for line in result.stdout.splitlines() if line]
check(len(ids) >= 2, 'memory experiment requires at least two API containers')
return ids
def sample_total_memory(container_ids):
result = subprocess.run(
['docker', 'stats', '--no-stream', '--format', '{{.MemUsage}}', *container_ids],
check=True, capture_output=True, text=True)
usages = []
for line in result.stdout.splitlines():
if line.strip():
usages.append(memory_bytes(line.split('/', 1)[0].strip()))
check(len(usages) == len(container_ids), 'docker stats did not return every API container')
return sum(usages)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--base-url', default='http://localhost:8080')
parser.add_argument('--compose-env-file', default='.env')
parser.add_argument('--concurrency', type=int, default=12)
parser.add_argument('--output', default='evidence/upload-memory.json')
args = parser.parse_args()
check(args.concurrency >= 10, 'experiment requires concurrency >= 10')
bootstrap = Client(args.base_url, timeout=30)
alice, bob, _, chat = bootstrap.bootstrap()
payload = make_png()
check(len(payload) <= 10_485_760, 'generated PNG exceeds upload limit')
containers = api_containers(args.compose_env_file)
baseline = sample_total_memory(containers)
peak = baseline
samples = []
stop = threading.Event()
def monitor():
nonlocal peak
while not stop.is_set():
try:
current = sample_total_memory(containers)
samples.append(current)
peak = max(peak, current)
except (subprocess.SubprocessError, Failure, ValueError):
pass
stop.wait(0.1)
barrier = threading.Barrier(args.concurrency)
def upload(index):
client = Client(args.base_url, timeout=30)
barrier.wait(timeout=30)
path = (f"/api/v1/chats/{chat['id']}/attachments"
f"?filename=memory-{index}.png")
return client.call('POST', path, 202, actor=alice, raw=payload,
headers={'Content-Type': 'image/png'}, schema='Attachment')['json']['id']
monitor_thread = threading.Thread(target=monitor, daemon=True)
monitor_thread.start()
started = time.monotonic()
try:
with concurrent.futures.ThreadPoolExecutor(max_workers=args.concurrency) as pool:
ids = list(pool.map(upload, range(args.concurrency)))
finally:
stop.set()
monitor_thread.join(timeout=5)
duration = time.monotonic() - started
check(len(ids) == args.concurrency and len(set(ids)) == len(ids),
'not every concurrent upload completed exactly once')
result = {
'concurrency': args.concurrency,
'successful_uploads': len(ids),
'payload_bytes_each': len(payload),
'duration_seconds': round(duration, 3),
'api_replicas': len(containers),
'memory_samples': len(samples),
'baseline_api_memory_bytes': baseline,
'peak_api_memory_bytes': peak,
'peak_increase_bytes': max(0, peak - baseline),
'configured_max_concurrent_uploads_per_replica': 3,
'configured_max_upload_bytes': 10_485_760,
'configured_max_image_pixels': 40_000_000,
}
output = ROOT / args.output
output.parent.mkdir(parents=True, exist_ok=True)
output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
print(json.dumps(result, ensure_ascii=False))
print('PASS: concurrent upload memory experiment')
if __name__ == '__main__':
run(main)
+135
View File
@@ -0,0 +1,135 @@
#!/usr/bin/env python3
"""Stop every observed API replica in turn and record recovery metrics."""
import json
import os
from pathlib import Path
import subprocess
import sys
import time
import uuid
from urllib.parse import quote
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, Failure, arguments, check, run
def executable(path, label):
value = Path(path).expanduser().resolve()
check(value.is_file() and os.access(value, os.X_OK), label + ' must be executable')
return value
def observe_instances(client, actor, attempts=60):
result = set()
for _ in range(attempts):
result.add(client.call(
'GET', '/api/v1/users/me', actor=actor, schema='User'
)['headers']['X-Instance-Id'])
return result
def message_history(client, actor, chat_id):
path = '/api/v1/chats/' + chat_id + '/messages?limit=100'
result = []
for _ in range(1000):
page = client.call(
'GET', path, actor=actor, schema='MessagePage')['json']
result.extend(page['items'])
if page['next_cursor'] is None:
return result
path = ('/api/v1/chats/' + chat_id + '/messages?limit=100&cursor='
+ quote(page['next_cursor'], safe=''))
raise Failure('history pagination exceeded safety bound')
def main():
def configure(parser):
parser.add_argument('--action-script', required=True)
parser.add_argument('--restore-script', required=True)
parser.add_argument('--window', type=float, default=15)
parser.add_argument('--output', default=None)
args = arguments('Sequential failover of every API replica', configure)
check(5 <= args.window <= 60, 'window must be 5..60 seconds')
action = executable(args.action_script, 'action script')
restore = executable(args.restore_script, 'restore script')
client = Client(args.base_url, args.ca_file, timeout=2)
alice, bob, _, chat = client.bootstrap()
targets = sorted(observe_instances(client, alice))
check(len(targets) >= 2, 'expected at least two API replicas')
targets = targets[:2]
summaries = []
for target in targets:
check(target in observe_instances(client, alice),
'target replica is not observable before stop')
env = dict(os.environ)
env['TARGET_INSTANCE_ID'] = target
process = subprocess.Popen(
[str(action)], env=env,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
started = time.monotonic()
first_recovery = None
reads = writes = failures = 0
confirmed = []
key = uuid.uuid4().hex
text = 'failover-each-' + target + '-' + key
while time.monotonic() - started < args.window:
try:
if (reads + writes) % 2 == 0:
response = client.message(alice, chat, text, key=key)
confirmed.append(response['json'])
writes += 1
key = uuid.uuid4().hex
text = 'failover-each-' + target + '-' + key
else:
client.call('GET', '/api/v1/users/me', actor=bob, schema='User')
reads += 1
if process.poll() == 0 and first_recovery is None:
first_recovery = time.monotonic() - started
except Failure:
failures += 1
time.sleep(0.05)
check(process.wait(timeout=5) == 0, 'stop-one action failed')
elapsed = time.monotonic() - started
check(first_recovery is not None and first_recovery <= 10,
'recovery exceeded 10 seconds')
history = message_history(client, bob, chat['id'])
history_ids = {message['id'] for message in history}
check(all(message['id'] in history_ids for message in confirmed),
'confirmed message disappeared after failover')
summaries.append({
'target_instance_id': target,
'window_seconds': round(elapsed, 3),
'successful_reads': reads,
'successful_writes': writes,
'failed_attempts': failures,
'successful_rps': round((reads + writes) / elapsed, 3),
'first_recovery_seconds': round(first_recovery, 3),
})
check(subprocess.run(
[str(restore)], stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, timeout=100).returncode == 0,
'restore action failed')
check(target in observe_instances(client, alice),
'stopped replica did not return after restore')
report = {
'scenario': 'sequential failover of each API replica',
'replicas': len(targets),
'results': summaries,
}
output = json.dumps(report, ensure_ascii=False, indent=2)
if args.output:
destination = Path(args.output)
destination.parent.mkdir(parents=True, exist_ok=True)
destination.write_text(output + '\n', encoding='utf-8')
print(output)
if __name__ == '__main__':
run(main)
+53
View File
@@ -0,0 +1,53 @@
#!/usr/bin/env python3
"""Prove that one idempotency scope is shared across API replicas."""
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import sys
import uuid
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, arguments, check, run
def main():
args = arguments('Concurrent cross-replica idempotency check')
bootstrap = Client(args.base_url, args.ca_file, timeout=5)
alice, _, _, chat = bootstrap.bootstrap()
key = uuid.uuid4().hex
text = 'Один результат для всех реплик ' + key
path = '/api/v1/chats/' + chat['id'] + '/messages'
def send(_):
client = Client(args.base_url, args.ca_file, timeout=10)
return client.call(
'POST',
path,
201,
actor=alice,
body={'text': text},
headers={'Idempotency-Key': key},
schema='Message')
with ThreadPoolExecutor(max_workers=16) as pool:
responses = list(pool.map(send, range(32)))
messages = [response['json'] for response in responses]
instances = {
response['headers']['X-Instance-Id'] for response in responses
}
check(all(message == messages[0] for message in messages),
'same key returned different messages')
check(len(instances) >= 2,
'requests did not exercise at least two API replicas')
page = bootstrap.call(
'GET', path + '?limit=100', actor=alice, schema='MessagePage')['json']
matches = [item for item in page['items'] if item['id'] == messages[0]['id']]
check(len(matches) == 1, 'idempotent message is missing or duplicated')
print('PASS: 32 concurrent requests used ' + str(len(instances))
+ ' replicas and created one message')
if __name__ == '__main__':
run(main)
+65
View File
@@ -0,0 +1,65 @@
#!/usr/bin/env python3
"""Negative black-box checks for lab4; uses only synthetic users and files."""
import argparse
import sys
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, Failure, check, run # noqa: E402
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--base-url', default='http://localhost:8080')
parser.add_argument('--expect-s3-unavailable', action='store_true')
args = parser.parse_args()
client = Client(args.base_url, timeout=20)
alice, bob, eve, chat = client.bootstrap()
png = (ROOT / 'tests' / 'fixtures' / 'sample.png').read_bytes()
upload_path = '/api/v1/chats/' + chat['id'] + '/attachments?filename=sample.png'
if args.expect_s3_unavailable:
response = client.call('POST', upload_path, 503, actor=alice, raw=png,
headers={'Content-Type': 'image/png'})
check(response['json']['error']['code'] == 'unavailable', 'S3 outage must return unavailable')
print('PASS: unavailable S3 returns contract JSON 503')
return
attachment, original = client.attachment(alice, chat)
client.call('GET', '/api/v1/attachments/' + attachment['id'], 404, actor=eve)
client.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content', 404, actor=eve)
other_chat = client.call('POST', '/api/v1/chats', 201, actor=alice,
body={'title': 'Другой чат', 'member_ids': [alice['id'], eve['id']]},
schema='Chat')['json']
client.call('POST', '/api/v1/chats/' + other_chat['id'] + '/messages', 404,
actor=alice, headers={'Idempotency-Key': uuid.uuid4().hex},
body={'text': '', 'attachment_ids': [attachment['id']]})
client.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 404,
actor=alice, headers={'Idempotency-Key': uuid.uuid4().hex},
body={'text': '', 'attachment_ids': [str(uuid.uuid4())]})
client.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 400,
actor=alice, headers={'Idempotency-Key': uuid.uuid4().hex},
body={'text': '', 'attachment_ids': [attachment['id'], attachment['id']]})
client.call('POST', upload_path, 415, actor=alice, raw=png,
headers={'Content-Type': 'image/jpeg'})
client.call('POST', upload_path, 415, actor=alice, raw=b'\x89PNG\r\n\x1a\ntruncated',
headers={'Content-Type': 'image/png'})
client.call('POST', upload_path, 413, actor=alice, raw=b'x' * (10_485_760 + 1),
headers={'Content-Type': 'image/png'})
client.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=../escape.png',
400, actor=alice, raw=png, headers={'Content-Type': 'image/png'})
downloaded = client.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content',
actor=bob)
check(downloaded['bytes'] == original, 'authorized download changed bytes')
print('PASS: unknown/foreign attachment, foreign chat/user, MIME spoof, corruption, byte limit and filename checks')
if __name__ == '__main__':
run(main)
+126
View File
@@ -0,0 +1,126 @@
#!/usr/bin/env python3
"""Exercise DLQ routing, guarded replay and expired processing leases."""
from pathlib import Path
import subprocess
import sys
import time
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check, run # noqa: E402
COMPOSE = ["docker", "compose", "--env-file", ".env.example"]
def command(*args, capture=False):
result = subprocess.run(
[*COMPOSE, *args], cwd=ROOT, check=True, text=True,
capture_output=capture)
return result.stdout.strip() if capture else ""
def database_scalar(sql):
return command(
"exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger",
"-At", "-c", sql, capture=True)
def env_value(name):
for line in (ROOT / ".env.example").read_text(encoding="utf-8").splitlines():
if line.startswith(name + "="):
return line.split("=", 1)[1]
raise Failure("missing " + name + " in .env.example")
def queue_ready(queue):
listing = command(
"exec", "-T", "rabbitmq", "rabbitmqctl", "list_queues",
"name", "messages_ready", capture=True)
for line in listing.splitlines():
columns = line.split("\t")
if len(columns) == 2 and columns[0] == queue:
return int(columns[1])
raise Failure("queue not found: " + queue)
def wait_ready(client, actor, attachment, seconds=120):
return client.wait_ready(actor, attachment, wait_seconds=seconds)
def replay(job_id):
subprocess.run(
["powershell", "-NoProfile", "-File", str(ROOT / "scripts" / "replay-failed.ps1"),
"-JobId", job_id, "-RequestedBy", "integration-test",
"-EnvFile", ".env.example"],
cwd=ROOT, check=True, text=True)
def main():
client = Client("http://localhost:8080")
alice, bob, _, chat = client.bootstrap()
# A permanently malformed delivery is rejected and dead-lettered.
before_dlq = queue_ready(env_value("ATTACHMENT_DLQ_QUEUE"))
command(
"exec", "-T", "rabbitmq", "rabbitmqadmin",
"-u", env_value("RABBITMQ_USER"), "-p", env_value("RABBITMQ_PASSWORD"),
"publish", "exchange=" + env_value("ATTACHMENT_JOB_EXCHANGE"),
"routing_key=" + env_value("ATTACHMENT_JOB_ROUTING_KEY"),
"payload={}",
'properties={"delivery_mode":2,"content_type":"application/json"}')
deadline = time.monotonic() + 30
while time.monotonic() < deadline and queue_ready(env_value("ATTACHMENT_DLQ_QUEUE")) <= before_dlq:
time.sleep(0.5)
check(queue_ready(env_value("ATTACHMENT_DLQ_QUEUE")) == before_dlq + 1,
"malformed permanent failure was not dead-lettered exactly once")
# Replay is allowed only from failed and creates one audit record.
command("stop", "worker")
failed, _ = client.attachment(alice, chat)
job_id = database_scalar(
"SELECT id FROM attachment_jobs WHERE attachment_id = '" + failed["id"] + "';")
database_scalar(
"UPDATE attachment_jobs SET status='failed', published=true, "
"last_error_code='retry_exhausted', lease_token=NULL, lease_until=NULL "
"WHERE id='" + job_id + "'; "
"UPDATE attachments SET status='failed', error_code='retry_exhausted' "
"WHERE id='" + failed["id"] + "'; SELECT 1;")
replay(job_id)
replay(job_id)
audit_count = database_scalar(
"SELECT count(*) FROM attachment_job_replays WHERE job_id='" + job_id + "';")
check(audit_count == "1", "replay was not guarded or was audited more than once")
command("start", "worker")
ready = wait_ready(client, bob, failed)
check(ready["status"] == "ready", "replayed failed job did not become ready")
replay(job_id)
check(database_scalar(
"SELECT count(*) FROM attachment_job_replays WHERE job_id='" + job_id + "';") == "1",
"replay changed an already successful job")
check(database_scalar(
"SELECT count(*) FROM attachment_variants WHERE attachment_id='" + failed["id"] + "';") == "3",
"replay did not preserve exactly one variant set")
# The API reaper returns an expired processing lease to the durable outbox.
command("stop", "worker")
leased, _ = client.attachment(alice, chat)
lease_job = database_scalar(
"SELECT id FROM attachment_jobs WHERE attachment_id='" + leased["id"] + "';")
database_scalar(
"UPDATE attachment_jobs SET status='processing', attempt=1, published=true, "
"lease_token=gen_random_uuid(), lease_until=clock_timestamp()-interval '1 second' "
"WHERE id='" + lease_job + "'; "
"UPDATE attachments SET status='processing' WHERE id='" + leased["id"] + "'; SELECT 1;")
command("start", "worker")
lease_ready = wait_ready(client, bob, leased)
check(lease_ready["status"] == "ready", "expired processing lease was not recovered")
check(int(database_scalar(
"SELECT attempt FROM attachment_jobs WHERE id='" + lease_job + "';")) >= 2,
"expired lease did not consume a bounded retry attempt")
print("PASS: DLQ, guarded replay and expired lease recovery")
if __name__ == "__main__":
run(main)
+135
View File
@@ -0,0 +1,135 @@
#!/usr/bin/env python3
"""Prove recovery across DB-commit/publish and result-commit/ack crashes."""
import os
from pathlib import Path
import subprocess
import sys
import time
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check, run # noqa: E402
COMPOSE = ["docker", "compose", "--env-file", ".env.example"]
def command(*args, capture=False, environment=None):
result = subprocess.run(
[*COMPOSE, *args], cwd=ROOT, check=True, text=True,
capture_output=capture, env=environment)
return result.stdout.strip() if capture else ""
def database_scalar(sql):
return command(
"exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger",
"-At", "-c", sql, capture=True)
def recreate(service, fault_name=None):
environment = os.environ.copy()
environment["FAULT_CRASH_AFTER_OUTBOX_COMMIT"] = "false"
environment["FAULT_CRASH_AFTER_RESULT_COMMIT"] = "false"
if fault_name:
environment[fault_name] = "true"
command("up", "-d", "--no-deps", "--force-recreate", service,
environment=environment)
def wait_http(client, seconds=120):
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
try:
client.call("GET", "/health/ready", schema="Health")
return
except Failure:
time.sleep(1)
raise Failure("API did not become ready")
def wait_job(attachment_id, expected="ready", seconds=120):
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
status = database_scalar(
"SELECT status FROM attachment_jobs WHERE attachment_id = '"
+ attachment_id + "';")
if status == expected:
return
if status == "failed":
raise Failure("fault-injected job reached failed")
time.sleep(1)
raise Failure("fault-injected job did not reach " + expected)
def latest_attachment(chat_id, fault_column):
row = database_scalar(
"SELECT a.id FROM attachments a JOIN attachment_jobs j ON j.attachment_id = a.id "
"WHERE a.chat_id = '" + chat_id + "' AND j." + fault_column
+ " = true ORDER BY a.created_at DESC LIMIT 1;")
check(bool(row), "fault marker was not persisted")
return row
def main():
client = Client("http://localhost:8080")
wait_http(client)
alice, bob, _, chat = client.bootstrap()
original = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
# Crash exactly after attachment + outbox COMMIT, before the request thread publishes.
recreate("api", "FAULT_CRASH_AFTER_OUTBOX_COMMIT")
wait_http(client)
try:
client.call(
"POST", "/api/v1/chats/" + chat["id"] + "/attachments?filename=outbox.png",
202, actor=alice, raw=original, headers={"Content-Type": "image/png"},
schema="Attachment")
raise Failure("outbox fault did not terminate the API request")
except Failure as error:
if "outbox fault did not" in str(error):
raise
outbox_attachment = latest_attachment(chat["id"], "publish_fault_injected")
wait_job(outbox_attachment)
recreate("api")
wait_http(client)
recovered = client.call(
"GET", "/api/v1/attachments/" + outbox_attachment,
actor=bob, schema="Attachment")["json"]
check(recovered["status"] == "ready", "outbox recovery did not publish the job")
check(len(recovered["variants"]) == 3, "outbox recovery did not finish all variants")
# Crash after S3 effects + result COMMIT, before RabbitMQ consumer ack.
recreate("worker", "FAULT_CRASH_AFTER_RESULT_COMMIT")
queued = client.call(
"POST", "/api/v1/chats/" + chat["id"] + "/attachments?filename=ack-window.png",
202, actor=alice, raw=original, headers={"Content-Type": "image/png"},
schema="Attachment")["json"]
wait_job(queued["id"])
ready = client.wait_ready(bob, queued, wait_seconds=120)
check(len(ready["variants"]) == 3, "result crash lost variants")
result_marker = database_scalar(
"SELECT result_fault_injected FROM attachment_jobs WHERE attachment_id = '"
+ queued["id"] + "';")
check(result_marker == "t", "result commit fault marker was not persisted")
recreate("worker")
deadline = time.monotonic() + 60
while time.monotonic() < deadline:
queues = command(
"exec", "-T", "rabbitmq", "rabbitmqctl", "list_queues",
"name", "messages_ready", "messages_unacknowledged", capture=True)
if "attachments.process.level4.v1\t0\t0" in queues:
break
time.sleep(1)
variant_count = database_scalar(
"SELECT count(*) FROM attachment_variants WHERE attachment_id = '"
+ queued["id"] + "';")
check(variant_count == "3", "redelivery duplicated committed variants")
print("PASS: outbox commit/publish crash and result commit/ack crash recovered")
if __name__ == "__main__":
run(main)
+314
View File
@@ -0,0 +1,314 @@
#!/usr/bin/env python3
"""Prove version fencing and idempotent convergence under duplicate/crash faults."""
import json
import os
from pathlib import Path
import subprocess
import sys
import time
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check, run # noqa: E402
COMPOSE = ["docker", "compose", "--env-file", ".env.example"]
FAULTS = (
"FAULT_CRASH_AFTER_OUTBOX_COMMIT",
"FAULT_CRASH_BEFORE_SIDE_EFFECT",
"FAULT_CRASH_AFTER_SIDE_EFFECT",
"FAULT_CRASH_AFTER_RESULT_COMMIT",
)
def command(*args, capture=False, environment=None, check_result=True):
result = subprocess.run(
[*COMPOSE, *args], cwd=ROOT, text=True, capture_output=capture,
env=environment, check=check_result)
return result.stdout.strip() if capture else ""
def database_scalar(sql):
return command(
"exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger",
"-At", "-c", sql, capture=True)
def env_value(name):
for line in (ROOT / ".env.example").read_text(encoding="utf-8").splitlines():
if line.startswith(name + "="):
return line.split("=", 1)[1]
raise Failure("missing " + name + " in .env.example")
def compose_environment(**overrides):
environment = os.environ.copy()
for name in FAULTS:
environment[name] = "false"
environment.update({name: str(value) for name, value in overrides.items()})
return environment
def recreate(service, **overrides):
command(
"up", "-d", "--no-deps", "--force-recreate", service,
environment=compose_environment(**overrides))
def wait_http(client, seconds=120):
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
try:
client.call("GET", "/health/ready", schema="Health")
return
except Failure:
time.sleep(1)
raise Failure("API did not become ready")
def wait_database(sql, expected, seconds=120):
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
if database_scalar(sql) == expected:
return
time.sleep(0.5)
raise Failure("database condition did not become " + expected + ": " + sql)
def job_row(attachment_id, version):
row = database_scalar(
"SELECT id || '|' || attempt || '|' || "
"to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') "
"FROM attachment_jobs WHERE attachment_id='" + attachment_id
+ "' AND pipeline_version=" + str(version) + ";")
check(bool(row), "pipeline job is missing")
return row.split("|")
def publish(attachment_id, version):
job_id, attempt, created_at = job_row(attachment_id, version)
payload = json.dumps({
"schema_version": 1,
"job_id": job_id,
"type": "attachment.process.v1",
"attachment_id": attachment_id,
"pipeline_version": version,
"attempt": int(attempt),
"created_at": created_at,
}, separators=(",", ":"))
command(
"exec", "-T", "rabbitmq", "rabbitmqadmin",
"-u", env_value("RABBITMQ_USER"), "-p", env_value("RABBITMQ_PASSWORD"),
"publish", "exchange=" + env_value("ATTACHMENT_JOB_EXCHANGE"),
"routing_key=" + env_value("ATTACHMENT_JOB_ROUTING_KEY"),
"payload=" + payload,
'properties={"delivery_mode":2,"content_type":"application/json"}')
def promote(attachment_id, version):
subprocess.run(
["powershell", "-NoProfile", "-File", str(ROOT / "scripts" / "promote-pipeline.ps1"),
"-AttachmentId", attachment_id, "-PipelineVersion", str(version),
"-RequestedBy", "idempotency-test", "-EnvFile", ".env.example"],
cwd=ROOT, check=True, text=True)
def variant_snapshot(attachment_id, version):
return database_scalar(
"SELECT string_agg(name || ':' || sha256 || ':' || object_key, ',' ORDER BY name) "
"FROM attachment_variants WHERE attachment_id='" + attachment_id
+ "' AND pipeline_version=" + str(version) + ";")
def job_status(attachment_id, version):
return database_scalar(
"SELECT status || '|' || published || '|' || coalesce(last_error_code, '') "
"FROM attachment_jobs WHERE attachment_id='" + attachment_id
+ "' AND pipeline_version=" + str(version) + ";")
def variant_count(attachment_id, version):
return database_scalar(
"SELECT count(*) FROM attachment_variants WHERE attachment_id='"
+ attachment_id + "' AND pipeline_version=" + str(version) + ";")
def object_count(attachment_id):
script = (
'mc alias set local http://minio:9000 "$MINIO_ROOT_USER" '
'"$MINIO_ROOT_PASSWORD" >/dev/null && '
'mc ls --recursive "local/$S3_BUCKET/attachments/' + attachment_id
+ '/" 2>/dev/null | wc -l')
output = command(
"run", "--rm", "--no-deps", "--entrypoint", "/bin/sh",
"minio-init", "-c", script, capture=True)
return int(output.splitlines()[-1])
def wait_marker(attachment_id, column, seconds=60):
wait_database(
"SELECT " + column + "::text FROM attachment_jobs WHERE attachment_id='"
+ attachment_id + "' ORDER BY pipeline_version DESC LIMIT 1;", "true", seconds)
def wait_queue_empty(seconds=150):
deadline = time.monotonic() + seconds
marker = env_value("ATTACHMENT_JOB_QUEUE") + "\t0\t0"
while time.monotonic() < deadline:
listing = command(
"exec", "-T", "rabbitmq", "rabbitmqctl", "list_queues",
"name", "messages_ready", "messages_unacknowledged", capture=True)
if marker in listing:
return
time.sleep(0.5)
raise Failure("main queue did not drain")
def wait_worker_consumer(seconds=150):
deadline = time.monotonic() + seconds
queue = env_value("ATTACHMENT_JOB_QUEUE")
while time.monotonic() < deadline:
listing = command(
"exec", "-T", "rabbitmq", "rabbitmqctl", "list_queues",
"name", "consumers", capture=True)
for line in listing.splitlines():
columns = line.split("\t")
if len(columns) == 2 and columns[0] == queue and int(columns[1]) > 0:
return
time.sleep(1)
raise Failure("worker did not register a RabbitMQ consumer")
def assert_ready_invariants(attachment_id, expected_version):
row = database_scalar(
"SELECT pipeline_version || '|' || status FROM attachments WHERE id='"
+ attachment_id + "';")
check(row == str(expected_version) + "|ready", "active pipeline is not ready")
check(database_scalar(
"SELECT count(*) FROM attachment_variants WHERE attachment_id='" + attachment_id
+ "' AND pipeline_version=" + str(expected_version) + ";") == "3",
"active pipeline does not have exactly three variants")
check(database_scalar(
"SELECT count(*) FROM attachment_jobs WHERE attachment_id='" + attachment_id
+ "' AND status IN ('queued','processing');") == "0",
"acknowledged attachment still has non-terminal work")
def fault_case(client, alice, bob, chat, flag, marker, expected_objects_before_commit):
recreate(
"worker", **{flag: "true", "JOB_TIMEOUT": "5s", "JOB_LEASE_DURATION": "8s"})
wait_worker_consumer()
attachment, _ = client.attachment(alice, chat)
wait_marker(attachment["id"], marker, seconds=150)
check(database_scalar(
"SELECT count(*) FROM attachment_variants WHERE attachment_id='"
+ attachment["id"] + "';") == "0",
"result metadata committed before the injected pre-commit crash")
check(object_count(attachment["id"]) == expected_objects_before_commit,
"unexpected object count at injected fault point")
ready = client.wait_ready(bob, attachment, wait_seconds=150)
check(ready["status"] == "ready", "faulted job was lost")
assert_ready_invariants(attachment["id"], 2)
check(int(database_scalar(
"SELECT attempt FROM attachment_jobs WHERE attachment_id='"
+ attachment["id"] + "' AND pipeline_version=2;")) >= 2,
"crashed job was not recovered through a later managed attempt")
check(object_count(attachment["id"]) == 4,
"idempotent retry did not converge to one deterministic object set")
recreate("worker")
return attachment["id"]
def main():
client = Client("http://localhost:8080")
recreate("api", ATTACHMENT_PIPELINE_VERSION="1")
wait_http(client)
alice, bob, _, chat = client.bootstrap()
# Complete v1, promote to v2, then deliver newer work before stale v1 and
# duplicate v2 messages. Arrival order intentionally differs from creation order.
versioned, _ = client.attachment(alice, chat)
client.wait_ready(bob, versioned, wait_seconds=120)
version1 = variant_snapshot(versioned["id"], 1)
check(bool(version1), "v1 result is missing")
command("stop", "worker")
promote(versioned["id"], 2)
publish(versioned["id"], 2)
publish(versioned["id"], 2)
publish(versioned["id"], 1)
command("up", "-d", "--no-deps", "worker")
client.wait_ready(bob, versioned, wait_seconds=120)
wait_queue_empty()
version2 = variant_snapshot(versioned["id"], 2)
check(bool(version2) and version2 != version1,
"v2 did not produce a distinct immutable versioned result")
check(database_scalar(
"SELECT count(*) FROM attachment_variants WHERE attachment_id='"
+ versioned["id"] + "';") == "6", "versioned rows were lost or duplicated")
stable = version2
publish(versioned["id"], 1)
publish(versioned["id"], 2)
wait_queue_empty()
check(variant_snapshot(versioned["id"], 2) == stable,
"stale or duplicate delivery overwrote the active v2 result")
assert_ready_invariants(versioned["id"], 2)
# Promote a still-queued v1 intent to v2. The old job must become
# superseded, and its already-durable message must be a harmless no-op.
command("stop", "worker")
superseded, _ = client.attachment(alice, chat)
check(job_status(superseded["id"], 1).startswith("queued|"),
"new upload did not start as a queued v1 job")
promote(superseded["id"], 2)
check(job_status(superseded["id"], 1) == "superseded|true|superseded_by_v2",
"queued v1 job was not fenced as superseded by v2")
check(variant_count(superseded["id"], 1) == "0",
"superseded job already has v1 result rows")
publish(superseded["id"], 1)
command("up", "-d", "--no-deps", "worker")
client.wait_ready(bob, superseded, wait_seconds=120)
wait_queue_empty()
check(variant_count(superseded["id"], 1) == "0",
"stale superseded v1 delivery created v1 result rows")
check(variant_count(superseded["id"], 2) == "3",
"promoted v2 job did not produce exactly three variants")
assert_ready_invariants(superseded["id"], 2)
recreate("api", ATTACHMENT_PIPELINE_VERSION="2")
wait_http(client)
before_id = fault_case(
client, alice, bob, chat, "FAULT_CRASH_BEFORE_SIDE_EFFECT",
"before_effect_fault_injected", 0)
after_id = fault_case(
client, alice, bob, chat, "FAULT_CRASH_AFTER_SIDE_EFFECT",
"after_effect_fault_injected", 4)
# Existing level-4 fault point proves redelivery after result COMMIT but before ack.
recreate("worker", FAULT_CRASH_AFTER_RESULT_COMMIT="true")
wait_worker_consumer()
committed, _ = client.attachment(alice, chat)
wait_marker(committed["id"], "result_fault_injected")
client.wait_ready(bob, committed, wait_seconds=120)
wait_queue_empty()
assert_ready_invariants(committed["id"], 2)
recreate("worker")
confirmed = database_scalar(
"SELECT count(*) FROM attachments WHERE id IN ('" + versioned["id"] + "','"
+ superseded["id"] + "','" + before_id + "','" + after_id + "','"
+ committed["id"] + "') AND status='ready';")
check(confirmed == "5", "a confirmed task was lost")
print("PASS: version fencing, superseded, duplicate/reorder and "
"pre/post-side-effect crashes")
if __name__ == "__main__":
try:
run(main)
finally:
try:
recreate("api", ATTACHMENT_PIPELINE_VERSION="2")
recreate("worker")
except Exception:
pass
+158
View File
@@ -0,0 +1,158 @@
#!/usr/bin/env python3
"""Exercise durable queued upload, component restarts and duplicate delivery.
Run from the repository root against the local compose.yaml:
python student_tests/lab5_worker_recovery.py
The script preserves volumes and leaves the complete stack running.
"""
import hashlib
import json
from pathlib import Path
import subprocess
import sys
import time
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check, run # noqa: E402
from image_probe import jpeg_size # noqa: E402
COMPOSE = ["docker", "compose", "--env-file", ".env.example"]
def command(*args, capture=False):
result = subprocess.run(
[*COMPOSE, *args], cwd=ROOT, check=True,
text=True, capture_output=capture)
return result.stdout.strip() if capture else ""
def database_scalar(sql):
return command(
"exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger",
"-At", "-c", sql, capture=True)
def env_value(name):
for line in (ROOT / ".env.example").read_text(encoding="utf-8").splitlines():
if line.startswith(name + "="):
return line.split("=", 1)[1]
raise Failure("missing " + name + " in .env.example")
def wait_http_ready(client, seconds=120):
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
try:
client.call("GET", "/health/ready", schema="Health")
return
except Failure:
time.sleep(1)
raise Failure("API did not become ready after restart")
def wait_rabbit(seconds=120):
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
result = subprocess.run(
[*COMPOSE, "exec", "-T", "rabbitmq", "rabbitmq-diagnostics", "-q", "ping"],
cwd=ROOT, text=True, capture_output=True)
if result.returncode == 0:
return
time.sleep(2)
raise Failure("RabbitMQ did not become ready after restart")
def main():
client = Client("http://localhost:8080")
command("stop", "worker")
try:
alice, bob, _, chat = client.bootstrap()
attachment, original = client.attachment(alice, chat)
check(attachment["status"] == "queued", "upload did not remain queued")
client.call(
"GET", "/api/v1/attachments/" + attachment["id"] + "/content",
409, actor=bob)
linked = client.message(alice, chat, "", attachments=[attachment["id"]])["json"]
check(linked["attachment_ids"] == [attachment["id"]],
"queued attachment could not be linked")
command("restart", "api")
command("restart", "rabbitmq")
wait_rabbit()
wait_http_ready(client)
command("start", "worker")
ready = client.wait_ready(bob, attachment, wait_seconds=120)
check(ready["status"] == "ready", "attachment did not become ready")
downloaded = client.call(
"GET", "/api/v1/attachments/" + attachment["id"] + "/content", actor=bob)
check(downloaded["bytes"] == original, "original bytes changed")
variants = {item["name"]: item for item in ready["variants"]}
check(set(variants) == {"thumbnail", "crop", "optimized"},
"expected thumbnail, crop and optimized variants")
check((variants["thumbnail"]["width"], variants["thumbnail"]["height"]) == (256, 160),
"thumbnail dimensions differ from contract")
check((variants["crop"]["width"], variants["crop"]["height"]) == (128, 128),
"crop dimensions differ from contract")
crop = client.call(
"GET", "/api/v1/attachments/" + attachment["id"] + "/content?variant=crop",
actor=bob)
check(crop["headers"].get_content_type() == "image/jpeg", "crop is not JPEG")
check(jpeg_size(crop["bytes"]) == (128, 128), "crop JPEG has wrong dimensions")
optimized = client.call(
"GET", "/api/v1/attachments/" + attachment["id"] + "/content?variant=optimized",
actor=bob)
check(optimized["headers"].get_content_type() == "image/webp", "optimized is not WebP")
check(optimized["bytes"][:4] == b"RIFF" and optimized["bytes"][8:12] == b"WEBP",
"optimized payload has no WebP signature")
job_row = database_scalar(
"SELECT id || '|' || pipeline_version || '|' || attempt || '|' || "
"to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') "
"FROM attachment_jobs WHERE attachment_id = '" + attachment["id"] + "';")
job_id, pipeline_version, attempt, created_at = job_row.split("|")
payload = json.dumps({
"schema_version": 1,
"job_id": job_id,
"type": "attachment.process.v1",
"attachment_id": attachment["id"],
"pipeline_version": int(pipeline_version),
"attempt": int(attempt),
"created_at": created_at,
}, separators=(",", ":"))
command(
"exec", "-T", "rabbitmq", "rabbitmqadmin",
"-u", env_value("RABBITMQ_USER"),
"-p", env_value("RABBITMQ_PASSWORD"),
"publish", "exchange=" + env_value("ATTACHMENT_JOB_EXCHANGE"),
"routing_key=" + env_value("ATTACHMENT_JOB_ROUTING_KEY"),
"payload=" + payload,
'properties={"delivery_mode":2,"content_type":"application/json"}')
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
queued = command(
"exec", "-T", "rabbitmq", "rabbitmqctl", "list_queues",
"name", "messages_ready", "messages_unacknowledged", capture=True)
if env_value("ATTACHMENT_JOB_QUEUE") + "\t0\t0" in queued:
break
time.sleep(0.5)
variant_count = database_scalar(
"SELECT count(*) FROM attachment_variants WHERE attachment_id = '"
+ attachment["id"] + "';")
status = database_scalar(
"SELECT status FROM attachments WHERE id = '" + attachment["id"] + "';")
check(variant_count == "3", "duplicate delivery changed the three variant rows")
check(status == "ready", "duplicate delivery changed terminal ready state")
check(hashlib.sha256(downloaded["bytes"]).hexdigest() == attachment["sha256"],
"original checksum changed")
print("PASS: stopped worker, durable restart recovery and duplicate delivery")
finally:
command("start", "worker")
if __name__ == "__main__":
run(main)
+182
View File
@@ -0,0 +1,182 @@
#!/usr/bin/env python3
"""Hard-stop one Swarm worker and prove API task relocation and data safety."""
import json
import atexit
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import subprocess
import sys
import time
import uuid
from urllib.parse import quote
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, Failure, arguments, check, run
def command(*parts, timeout=30):
result = subprocess.run(
parts, capture_output=True, text=True, timeout=timeout)
check(result.returncode == 0, 'command failed: ' + ' '.join(parts[:3]))
return result.stdout.strip()
def api_tasks(manager):
output = command(
'docker', 'exec', manager, 'docker', 'service', 'ps', 'hla-app_api',
'--filter', 'desired-state=running',
'--format', '{{.ID}}\t{{.Node}}\t{{.CurrentState}}')
result = []
for line in output.splitlines():
fields = line.split('\t')
if len(fields) == 3 and fields[2].startswith('Running'):
result.append({'task_id': fields[0], 'node': fields[1]})
return result
def history(client, actor, chat_id):
path = '/api/v1/chats/' + chat_id + '/messages?limit=100'
result = []
for _ in range(1000):
page = client.call('GET', path, actor=actor, schema='MessagePage')['json']
result.extend(page['items'])
if page['next_cursor'] is None:
return result
path = ('/api/v1/chats/' + chat_id + '/messages?limit=100&cursor='
+ quote(page['next_cursor'], safe=''))
raise Failure('history pagination exceeded safety bound')
def observe(client, actor, attempts=40):
def request(_):
local = Client(client.base, timeout=2)
return local.call(
'GET', '/api/v1/users/me', actor=actor, schema='User')
with ThreadPoolExecutor(max_workers=16) as pool:
responses = list(pool.map(request, range(attempts)))
return {response['headers']['X-Instance-Id'] for response in responses}
def restore_worker(manager, node):
subprocess.run(
['docker', 'start', node], stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, timeout=30)
deadline = time.monotonic() + 90
status = ''
while time.monotonic() < deadline:
result = subprocess.run(
['docker', 'exec', manager, 'docker', 'node', 'ls',
'--filter', 'name=' + node, '--format', '{{.Status}}'],
capture_output=True, text=True, timeout=30)
status = result.stdout.strip()
if result.returncode == 0 and status == 'Ready':
return True
time.sleep(2)
return False
def main():
def configure(parser):
parser.add_argument('--manager-container', default='hla-swarm-manager')
parser.add_argument('--window', type=float, default=30)
parser.add_argument('--output', default=None)
args = arguments('Swarm worker loss and API relocation', configure)
check(15 <= args.window <= 120, 'window must be 15..120 seconds')
client = Client(args.base_url, args.ca_file, timeout=2)
alice, bob, _, chat = client.bootstrap()
before_instances = observe(client, alice)
check(len(before_instances) >= 2, 'expected two API instances before node loss')
before_tasks = api_tasks(args.manager_container)
check(len(before_tasks) == 2, 'expected two running API tasks')
candidates = [task for task in before_tasks
if task['node'].startswith('hla-swarm-worker')]
check(bool(candidates), 'no API task is running on a worker node')
victim = candidates[0]
confirmed_before = client.message(
alice, chat, 'confirmed-before-node-loss-' + uuid.uuid4().hex)['json']
started = time.monotonic()
command('docker', 'stop', '--time', '1', victim['node'], timeout=15)
restore_at_exit = lambda: restore_worker(args.manager_container, victim['node'])
atexit.register(restore_at_exit)
first_recovery = None
reads = writes = failures = 0
confirmed_during = []
key = uuid.uuid4().hex
text = 'during-node-loss-' + key
while time.monotonic() - started < args.window:
try:
if (reads + writes) % 2 == 0:
response = client.message(alice, chat, text, key=key)
confirmed_during.append(response['json'])
writes += 1
key = uuid.uuid4().hex
text = 'during-node-loss-' + key
else:
client.call('GET', '/api/v1/users/me', actor=bob, schema='User')
reads += 1
if first_recovery is None:
first_recovery = time.monotonic() - started
except Failure:
failures += 1
time.sleep(0.05)
deadline = time.monotonic() + 90
after_tasks = []
while time.monotonic() < deadline:
after_tasks = api_tasks(args.manager_container)
if (len(after_tasks) == 2
and all(task['node'] != victim['node'] for task in after_tasks)
and any(task['task_id'] != victim['task_id'] for task in after_tasks)):
break
time.sleep(2)
check(len(after_tasks) == 2, 'API service did not return to two tasks')
check(all(task['node'] != victim['node'] for task in after_tasks),
'API task was not relocated away from failed node')
check(first_recovery is not None and first_recovery <= 10,
'API did not recover within 10 seconds')
stored = history(client, bob, chat['id'])
stored_ids = {message['id'] for message in stored}
check(confirmed_before['id'] in stored_ids,
'pre-failure confirmed message was lost')
check(all(message['id'] in stored_ids for message in confirmed_during),
'message confirmed during node loss was lost')
check(restore_worker(args.manager_container, victim['node']),
'failed worker did not rejoin the Swarm')
atexit.unregister(restore_at_exit)
after_instances = observe(client, alice, attempts=96)
check(len(after_instances - before_instances) >= 1,
'replacement API process was not visible through X-Instance-Id')
elapsed = time.monotonic() - started
report = {
'scenario': 'hard loss of one Swarm worker',
'failed_node': victim['node'],
'old_task_id': victim['task_id'],
'tasks_before': before_tasks,
'tasks_after_relocation': after_tasks,
'instance_ids_before': sorted(before_instances),
'instance_ids_after': sorted(after_instances),
'successful_reads': reads,
'successful_writes': writes,
'failed_attempts': failures,
'first_recovery_seconds': round(first_recovery, 3),
'successful_rps': round((reads + writes) / args.window, 3),
'experiment_seconds_including_rejoin': round(elapsed, 3),
'confirmed_data_preserved': True,
'database_node_failed': False,
'note': ('PostgreSQL, Nginx, manager quorum and local volumes are not '
'protected by this experiment.'),
}
output = json.dumps(report, ensure_ascii=False, indent=2)
if args.output:
destination = Path(args.output)
destination.parent.mkdir(parents=True, exist_ok=True)
destination.write_text(output + '\n', encoding='utf-8')
print(output)
if __name__ == '__main__':
run(main)
+104
View File
@@ -0,0 +1,104 @@
#!/usr/bin/env python3
"""Reproduce and guard against serving business traffic from unready APIs."""
from pathlib import Path
import subprocess
import sys
import time
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, Failure, arguments, check, run
ORIGINAL_TABLE = 'message_idempotency'
TEMPORARY_TABLE = 'message_idempotency_readiness_test'
def command(*args):
result = subprocess.run(
args,
cwd=ROOT,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
check=False)
if result.returncode != 0:
output = result.stdout.strip()
raise Failure('command failed: ' + ' '.join(args[:3])
+ (': ' + output if output else ''))
return result.stdout.strip()
def rename_table(source, target):
sql = 'ALTER TABLE ' + source + ' RENAME TO ' + target + ';'
command(
'docker', 'compose', 'exec', '-T', 'postgres', 'sh', '-ec',
'psql -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" '
'-d "$POSTGRES_DB" -c \'' + sql + '\'')
def api_container_ids():
output = command('docker', 'compose', 'ps', '-q', 'api')
return [line.strip() for line in output.splitlines() if line.strip()]
def health_status(container_id):
return command(
'docker', 'inspect',
'--format={{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}',
container_id)
def wait_for_all_health(expected, timeout):
deadline = time.monotonic() + timeout
last = []
while time.monotonic() < deadline:
containers = api_container_ids()
last = [health_status(container) for container in containers]
if len(containers) >= 2 and all(value == expected for value in last):
return containers
time.sleep(1)
raise Failure('API health did not become ' + expected
+ '; last statuses: ' + repr(last))
def configure(parser):
parser.add_argument(
'--health-timeout', type=float, default=45.0,
help='seconds to wait for both Docker health states')
def main():
args = arguments('Readiness must gate business traffic through the LB', configure)
client = Client(args.base_url, args.ca_file, timeout=8)
client.call('GET', '/health/ready', 200, schema='Health')
actor = client.user('readiness_gate')
renamed = False
try:
rename_table(ORIGINAL_TABLE, TEMPORARY_TABLE)
renamed = True
containers = wait_for_all_health('unhealthy', args.health_timeout)
client.call('GET', '/health/ready', 503)
instances = set()
for _ in range(8):
response = client.call(
'GET', '/api/v1/users/me', 503, actor=actor)
instances.add(response['headers']['X-Instance-Id'])
check(instances, 'no refusing API instance was observed')
finally:
if renamed:
rename_table(TEMPORARY_TABLE, ORIGINAL_TABLE)
wait_for_all_health('healthy', args.health_timeout)
# Nginx may retain a passive failure for fail_timeout=2s.
time.sleep(3)
client.call('GET', '/health/ready', 200, schema='Health')
client.call('GET', '/api/v1/users/me', 200, actor=actor, schema='User')
print('PASS: ' + str(len(containers))
+ ' unhealthy API containers refused business traffic with 503 '
+ 'and recovered after schema restoration')
if __name__ == '__main__':
run(main)
+110
View File
@@ -0,0 +1,110 @@
#!/usr/bin/env python3
"""Run closed-loop writes while API replicas are replaced one at a time."""
from concurrent.futures import ThreadPoolExecutor
import json
import math
import os
from pathlib import Path
import subprocess
import sys
import threading
import time
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, Failure, arguments, check, run
def main():
def configure(parser):
parser.add_argument('--action-script', required=True)
parser.add_argument('--duration', type=float, default=180)
parser.add_argument('--concurrency', type=int, default=4)
parser.add_argument('--output', default=None)
args = arguments('Rolling replacement under write load', configure)
check(30 <= args.duration <= 300, 'duration must be 30..300 seconds')
check(1 <= args.concurrency <= 32, 'concurrency must be 1..32')
action = Path(args.action_script).expanduser().resolve()
check(action.is_file() and os.access(action, os.X_OK),
'action script must be executable')
bootstrap = Client(args.base_url, args.ca_file, timeout=5)
alice, _, _, chat = bootstrap.bootstrap()
barrier = threading.Barrier(args.concurrency + 1)
def worker(worker_id):
client = Client(args.base_url, args.ca_file, timeout=5)
barrier.wait()
deadline = time.monotonic() + args.duration
latencies = []
errors = 0
instances = set()
index = 0
while time.monotonic() < deadline:
started = time.monotonic()
try:
response = client.message(
alice, chat, 'rolling-%s-%s' % (worker_id, index))
latencies.append(time.monotonic() - started)
instances.add(response['headers']['X-Instance-Id'])
except Failure:
errors += 1
index += 1
return latencies, errors, instances
started = time.monotonic()
with ThreadPoolExecutor(max_workers=args.concurrency) as pool:
futures = [pool.submit(worker, number)
for number in range(args.concurrency)]
barrier.wait()
time.sleep(3)
action_started = time.monotonic()
process = subprocess.run(
[str(action)], stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, timeout=args.duration - 5)
action_seconds = time.monotonic() - action_started
check(process.returncode == 0, 'rolling action failed')
results = [future.result() for future in futures]
elapsed = time.monotonic() - started
latencies = sorted(value for values, _, _ in results for value in values)
errors = sum(value for _, value, _ in results)
instances = set().union(*(value for _, _, value in results))
total = len(latencies) + errors
def percentile(fraction):
if not latencies:
return None
index = max(0, math.ceil(fraction * len(latencies)) - 1)
return round(1000 * latencies[index], 3)
report = {
'scenario': 'sequential API replacement under closed-loop writes',
'requested_duration_seconds': args.duration,
'elapsed_seconds': round(elapsed, 3),
'rolling_action_seconds': round(action_seconds, 3),
'concurrency': args.concurrency,
'observed_instance_ids': sorted(instances),
'successful_requests': len(latencies),
'failed_requests': errors,
'error_ratio': round(errors / total, 6) if total else None,
'successful_rps': round(len(latencies) / elapsed, 3),
'successful_latency_ms': {
'p50': percentile(.50),
'p95': percentile(.95),
'p99': percentile(.99),
},
'note': 'Closed-loop result on one host; success latency excludes failures.',
}
output = json.dumps(report, ensure_ascii=False, indent=2)
if args.output:
destination = Path(args.output)
destination.parent.mkdir(parents=True, exist_ok=True)
destination.write_text(output + '\n', encoding='utf-8')
print(output)
check(bool(latencies), 'no successful writes')
check(len(instances) >= 3,
'rolling replacement did not expose replacement instance IDs')
if __name__ == '__main__':
run(main)