forked from mtusi2026/mtusi2026lab7
выполение на 5
This commit is contained in:
@@ -0,0 +1,98 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Negative attachment and cross-chat authorization checks against a running lab4 API."""
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
import sys
|
||||
from urllib.parse import quote
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def upload(client, actor, chat_id, data, content_type="image/png", filename="test.png", expected=202):
|
||||
return client.call(
|
||||
"POST",
|
||||
"/api/v1/chats/" + chat_id + "/attachments?filename=" + quote(filename, safe=""),
|
||||
expected,
|
||||
actor=actor,
|
||||
raw=data,
|
||||
headers={"Content-Type": content_type},
|
||||
schema="Attachment" if expected in (201, 202) else None,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Attachment upload, size, MIME, and chat authorization checks")
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
other_chat = client.call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
201,
|
||||
actor=alice,
|
||||
body={"title": "Second test chat", "member_ids": [alice["id"], eve["id"]]},
|
||||
schema="Chat",
|
||||
)["json"]
|
||||
image = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
|
||||
print("Checking accepted fixture upload.", flush=True)
|
||||
attachment = upload(client, alice, chat["id"], image)["json"]
|
||||
|
||||
print("Checking damaged and spoofed image rejection.", flush=True)
|
||||
upload(client, alice, chat["id"], b"not an image", expected=415)
|
||||
upload(client, alice, chat["id"], image, content_type="image/jpeg", expected=415)
|
||||
print("Checking byte and pixel limits.", flush=True)
|
||||
upload(client, alice, chat["id"], b"x" * (10 * 1024 * 1024 + 1), expected=413)
|
||||
import struct
|
||||
import zlib
|
||||
|
||||
def chunk(kind, payload):
|
||||
return (
|
||||
struct.pack(">I", len(payload))
|
||||
+ kind
|
||||
+ payload
|
||||
+ struct.pack(">I", zlib.crc32(kind + payload) & 0xFFFFFFFF)
|
||||
)
|
||||
|
||||
bad_idat = bytearray(zlib.compress(b"\x00\x10\x20\x30"))
|
||||
bad_idat[-3] ^= 0xFF
|
||||
damaged_idat = (
|
||||
b"\x89PNG\r\n\x1a\n"
|
||||
+ chunk(b"IHDR", struct.pack(">IIBBBBB", 1, 1, 8, 2, 0, 0, 0))
|
||||
+ chunk(b"IDAT", bytes(bad_idat))
|
||||
+ chunk(b"IEND", b"")
|
||||
)
|
||||
upload(client, alice, chat["id"], damaged_idat, expected=415)
|
||||
|
||||
too_many_pixels = (
|
||||
b"\x89PNG\r\n\x1a\n"
|
||||
+ chunk(b"IHDR", struct.pack(">IIBBBBB", 10001, 4000, 8, 2, 0, 0, 0))
|
||||
+ chunk(b"IDAT", zlib.compress(b""))
|
||||
+ chunk(b"IEND", b"")
|
||||
)
|
||||
upload(client, alice, chat["id"], too_many_pixels, expected=413)
|
||||
print("Checking filename and cross-chat authorization.", flush=True)
|
||||
upload(client, alice, chat["id"], image, filename="../unsafe.png", expected=400)
|
||||
upload(client, eve, chat["id"], image, expected=404)
|
||||
client.call("GET", "/api/v1/attachments/" + attachment["id"], 404, actor=eve)
|
||||
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",
|
||||
400,
|
||||
actor=bob,
|
||||
headers={"Idempotency-Key": uuid.uuid4().hex},
|
||||
body={"text": ""},
|
||||
)
|
||||
print("PASS: oversized, damaged, spoofed, unsafe-name, outsider, and cross-chat cases")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,47 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Prove a concurrent idempotency-key race through the load balancer."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import threading
|
||||
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, arguments, check, run
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Concurrent shared-idempotency integration check")
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
key = "race-" + uuid.uuid4().hex
|
||||
text = "concurrent-" + uuid.uuid4().hex
|
||||
count = 12
|
||||
barrier = threading.Barrier(count)
|
||||
|
||||
def send_once(_):
|
||||
worker = Client(args.base_url, args.ca_file)
|
||||
barrier.wait(timeout=10)
|
||||
return worker.message(alice, chat, text, key=key)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=count) as pool:
|
||||
responses = list(pool.map(send_once, range(count)))
|
||||
|
||||
instance_ids = {response["headers"]["X-Instance-Id"] for response in responses}
|
||||
messages = [response["json"] for response in responses]
|
||||
check(len(instance_ids) >= 2, "concurrent requests did not reach multiple API replicas")
|
||||
check(all(message == messages[0] for message in messages), "same-key requests returned different messages")
|
||||
page = client.call(
|
||||
"GET",
|
||||
"/api/v1/chats/" + chat["id"] + "/messages?limit=100",
|
||||
actor=alice,
|
||||
schema="MessagePage",
|
||||
)["json"]
|
||||
matches = [message for message in page["items"] if message["text"] == text]
|
||||
check(len(matches) == 1 and matches[0] == messages[0], "concurrent retry persisted duplicate messages")
|
||||
print(f"PASS: {count} concurrent same-key requests on {len(instance_ids)} replicas returned one message")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,66 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify an upload committed while the publisher is stopped is processed after restart."""
|
||||
import hashlib
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def compose(*args):
|
||||
return subprocess.run(
|
||||
["docker", "compose", *args],
|
||||
cwd=ROOT,
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Verify committed attachment outbox intent survives publisher downtime")
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
compose("stop", "publisher")
|
||||
try:
|
||||
attachment, original = client.attachment(alice, chat)
|
||||
check(attachment["status"] == "queued", "upload was not accepted into queued state")
|
||||
finally:
|
||||
compose("start", "publisher")
|
||||
|
||||
ready = client.wait_ready(alice, attachment)
|
||||
stored_original = client.call(
|
||||
"GET",
|
||||
"/api/v1/attachments/" + attachment["id"] + "/content",
|
||||
actor=alice,
|
||||
)["bytes"]
|
||||
thumbnail = client.call(
|
||||
"GET",
|
||||
"/api/v1/attachments/" + attachment["id"] + "/content?variant=thumbnail",
|
||||
actor=alice,
|
||||
)["bytes"]
|
||||
variant = next(item for item in ready["variants"] if item["name"] == "thumbnail")
|
||||
check(stored_original == original, "recovered job changed original bytes")
|
||||
check(hashlib.sha256(thumbnail).hexdigest() == variant["sha256"], "recovered thumbnail checksum mismatch")
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"result": "PASS",
|
||||
"accepted_status_before_publisher_restart": attachment["status"],
|
||||
"final_status": ready["status"],
|
||||
"attachment_id": attachment["id"],
|
||||
"original_sha256": hashlib.sha256(stored_original).hexdigest(),
|
||||
"thumbnail_sha256": variant["sha256"],
|
||||
"recovered_without_manual_republish": True,
|
||||
},
|
||||
sort_keys=True,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,485 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Deterministic fault-injection checks for delivery, side effects, and pipeline fencing."""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
|
||||
os.environ.setdefault("S3_ACCESS_KEY_ID", "pipeline-test")
|
||||
os.environ.setdefault("S3_SECRET_ACCESS_KEY", "pipeline-test-secret")
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
import pika
|
||||
|
||||
from src.publisher import publish_pending
|
||||
from src.worker import ProcessingTimeout, _build_variants_bounded, handle_delivery
|
||||
|
||||
|
||||
ATTACHMENT_ID = "00000000-0000-4000-8000-000000000001"
|
||||
JOB_ID = "00000000-0000-4000-8000-000000000002"
|
||||
|
||||
|
||||
class SimulatedCrash(BaseException):
|
||||
pass
|
||||
|
||||
|
||||
class FakeObjects:
|
||||
def __init__(self, content):
|
||||
self.data = {"staging/" + ATTACHMENT_ID: content}
|
||||
self.puts = []
|
||||
|
||||
def get(self, key, max_bytes):
|
||||
return self.data[key]
|
||||
|
||||
def put(self, key, content, content_type, size_bytes=None):
|
||||
value = content if isinstance(content, bytes) else content.read()
|
||||
assert len(value) == size_bytes
|
||||
self.data[key] = value
|
||||
self.puts.append((key, hashlib.sha256(value).hexdigest()))
|
||||
|
||||
def delete(self, key):
|
||||
self.data.pop(key, None)
|
||||
|
||||
|
||||
class FakeStore:
|
||||
def __init__(self, content):
|
||||
self.objects = FakeObjects(content)
|
||||
self.row = {
|
||||
"id": ATTACHMENT_ID,
|
||||
"job_id": JOB_ID,
|
||||
"pipeline_version": 1,
|
||||
"attempt": 1,
|
||||
"status": "queued",
|
||||
"lease_until": 0.0,
|
||||
"staging_key": "staging/" + ATTACHMENT_ID,
|
||||
"object_key": "original/" + ATTACHMENT_ID,
|
||||
"content_type": "image/png",
|
||||
"size_bytes": len(content),
|
||||
"sha256": hashlib.sha256(content).hexdigest(),
|
||||
"variants": [],
|
||||
}
|
||||
|
||||
def claim_attachment_job(self, attachment_id, job_id, version, attempt, lease_seconds):
|
||||
row = self.row
|
||||
if (
|
||||
attachment_id != row["id"]
|
||||
or job_id != row["job_id"]
|
||||
or version != row["pipeline_version"]
|
||||
or attempt != row["attempt"]
|
||||
or row["status"] in ("ready", "failed")
|
||||
):
|
||||
return None
|
||||
if row["status"] == "processing" and row["lease_until"] > time.monotonic():
|
||||
return None
|
||||
row["status"] = "processing"
|
||||
row["lease_until"] = time.monotonic() + lease_seconds
|
||||
return dict(row)
|
||||
|
||||
def complete_attachment_job(self, attachment_id, job_id, version, attempt, variants):
|
||||
row = self.row
|
||||
if (
|
||||
attachment_id != row["id"]
|
||||
or job_id != row["job_id"]
|
||||
or version != row["pipeline_version"]
|
||||
or attempt != row["attempt"]
|
||||
or row["status"] != "processing"
|
||||
or row["lease_until"] <= time.monotonic()
|
||||
):
|
||||
return False
|
||||
row["status"] = "ready"
|
||||
row["lease_until"] = 0.0
|
||||
row["variants"] = variants
|
||||
return True
|
||||
|
||||
def fail_attachment_job(self, attachment_id, job_id, version, attempt, max_attempts, error_code, delay):
|
||||
row = self.row
|
||||
if (
|
||||
row["id"] == attachment_id
|
||||
and row["job_id"] == job_id
|
||||
and row["pipeline_version"] == version
|
||||
and row["attempt"] == attempt
|
||||
and row["status"] == "processing"
|
||||
):
|
||||
row["status"] = "failed" if delay is None else "queued"
|
||||
row["lease_until"] = 0.0
|
||||
row["error_code"] = error_code
|
||||
if delay is not None:
|
||||
row["attempt"] += 1
|
||||
|
||||
def recover_expired(self):
|
||||
if self.row["status"] == "processing":
|
||||
self.row["attempt"] += 1
|
||||
self.row["status"] = "queued"
|
||||
self.row["lease_until"] = 0.0
|
||||
|
||||
def replay(self, version):
|
||||
row = self.row
|
||||
previous_job = row["job_id"]
|
||||
row["job_id"] = str(uuid.uuid4())
|
||||
row["pipeline_version"] = version
|
||||
row["attempt"] = 1
|
||||
row["status"] = "queued"
|
||||
row["lease_until"] = 0.0
|
||||
row["variants"] = []
|
||||
row["staging_key"] = f"staging/{ATTACHMENT_ID}/{row['job_id']}"
|
||||
self.objects.put(
|
||||
row["staging_key"],
|
||||
self.objects.data[row["object_key"]],
|
||||
row["content_type"],
|
||||
row["size_bytes"],
|
||||
)
|
||||
return {
|
||||
"schema_version": 1,
|
||||
"job_id": row["job_id"],
|
||||
"type": "attachment.process.v1",
|
||||
"attachment_id": ATTACHMENT_ID,
|
||||
"pipeline_version": version,
|
||||
"attempt": 1,
|
||||
"created_at": datetime(2026, 1, 1, tzinfo=timezone.utc),
|
||||
"previous_job_id": previous_job,
|
||||
}
|
||||
|
||||
|
||||
class FakeChannel:
|
||||
def __init__(self):
|
||||
self.acked = []
|
||||
self.nacked = []
|
||||
|
||||
def basic_ack(self, delivery_tag):
|
||||
self.acked.append(delivery_tag)
|
||||
|
||||
def basic_nack(self, delivery_tag, requeue):
|
||||
self.nacked.append((delivery_tag, requeue))
|
||||
|
||||
|
||||
class FakeMethod:
|
||||
def __init__(self, delivery_tag):
|
||||
self.delivery_tag = delivery_tag
|
||||
|
||||
|
||||
def job_body(job_id=JOB_ID, version=1, attempt=1):
|
||||
return json.dumps(
|
||||
{
|
||||
"schema_version": 1,
|
||||
"job_id": job_id,
|
||||
"type": "attachment.process.v1",
|
||||
"attachment_id": ATTACHMENT_ID,
|
||||
"pipeline_version": version,
|
||||
"attempt": attempt,
|
||||
"created_at": "2026-01-01T00:00:00Z",
|
||||
}
|
||||
).encode()
|
||||
|
||||
|
||||
def crash_at(expected):
|
||||
def inject(point):
|
||||
if point == expected:
|
||||
raise SimulatedCrash(point)
|
||||
|
||||
return inject
|
||||
|
||||
|
||||
def slow_builder(attachment_id, content, pipeline_version):
|
||||
time.sleep(5)
|
||||
|
||||
|
||||
def test_duplicate_and_ack_loss(content):
|
||||
store = FakeStore(content)
|
||||
channel = FakeChannel()
|
||||
try:
|
||||
handle_delivery(
|
||||
store, channel, FakeMethod(1), job_body(),
|
||||
fault_injector=crash_at("before_ack"),
|
||||
)
|
||||
raise AssertionError("fault injection did not crash before ack")
|
||||
except SimulatedCrash:
|
||||
pass
|
||||
assert store.row["status"] == "ready"
|
||||
first_write_count = len(store.objects.puts)
|
||||
assert channel.acked == []
|
||||
|
||||
handle_delivery(store, channel, FakeMethod(2), job_body())
|
||||
assert channel.acked == [2]
|
||||
assert len(store.objects.puts) == first_write_count
|
||||
assert store.row["status"] == "ready"
|
||||
return {
|
||||
"scenario": "duplicate_delivery_after_commit_before_ack",
|
||||
"deliveries": 2,
|
||||
"effective_object_writes": first_write_count,
|
||||
"duplicate_delivery_writes": len(store.objects.puts) - first_write_count,
|
||||
}
|
||||
|
||||
|
||||
def test_crash_before_and_after_side_effect(content, crash_point):
|
||||
store = FakeStore(content)
|
||||
channel = FakeChannel()
|
||||
try:
|
||||
handle_delivery(
|
||||
store, channel, FakeMethod(3), job_body(),
|
||||
fault_injector=crash_at(crash_point),
|
||||
)
|
||||
raise AssertionError(f"fault injection did not crash at {crash_point}")
|
||||
except SimulatedCrash:
|
||||
pass
|
||||
assert channel.acked == []
|
||||
store.recover_expired()
|
||||
retry = job_body(attempt=2)
|
||||
handle_delivery(store, channel, FakeMethod(4), retry)
|
||||
assert store.row["status"] == "ready"
|
||||
assert store.row["attempt"] == 2
|
||||
assert channel.acked == [4]
|
||||
assert store.objects.data["original/" + ATTACHMENT_ID] == content
|
||||
return {
|
||||
"scenario": "crash_" + crash_point,
|
||||
"attempts": store.row["attempt"],
|
||||
"terminal_status": store.row["status"],
|
||||
}
|
||||
|
||||
|
||||
def test_reordered_attempts(content):
|
||||
store = FakeStore(content)
|
||||
store.row["attempt"] = 2
|
||||
channel = FakeChannel()
|
||||
handle_delivery(store, channel, FakeMethod(5), job_body(attempt=2))
|
||||
writes_after_current = len(store.objects.puts)
|
||||
handle_delivery(store, channel, FakeMethod(6), job_body(attempt=1))
|
||||
assert store.row["status"] == "ready"
|
||||
assert len(store.objects.puts) == writes_after_current
|
||||
assert channel.acked == [5, 6]
|
||||
return {
|
||||
"scenario": "out_of_order_attempt_delivery",
|
||||
"current_attempt": store.row["attempt"],
|
||||
"stale_attempt_extra_writes": len(store.objects.puts) - writes_after_current,
|
||||
}
|
||||
|
||||
|
||||
def test_stale_pipeline_cannot_publish_newer_result(content):
|
||||
store = FakeStore(content)
|
||||
channel = FakeChannel()
|
||||
replayed = []
|
||||
|
||||
def supersede_after_first_variant(point):
|
||||
if point == "after_variant_put:thumbnail" and not replayed:
|
||||
replayed.append(store.replay(2))
|
||||
|
||||
handle_delivery(
|
||||
store, channel, FakeMethod(7), job_body(),
|
||||
fault_injector=supersede_after_first_variant,
|
||||
)
|
||||
assert store.row["status"] == "queued"
|
||||
assert store.row["pipeline_version"] == 2
|
||||
assert channel.acked == [7]
|
||||
|
||||
current_job = replayed[0]
|
||||
handle_delivery(
|
||||
store,
|
||||
channel,
|
||||
FakeMethod(8),
|
||||
job_body(current_job["job_id"], current_job["pipeline_version"], current_job["attempt"]),
|
||||
)
|
||||
assert store.row["status"] == "ready"
|
||||
assert {variant["object_key"].split("/")[2] for variant in store.row["variants"]} == {"v2"}
|
||||
assert channel.acked == [7, 8]
|
||||
return {
|
||||
"scenario": "stale_pipeline_after_newer_version",
|
||||
"current_pipeline_version": store.row["pipeline_version"],
|
||||
"published_variant_versions": sorted(
|
||||
{variant["object_key"].split("/")[2] for variant in store.row["variants"]}
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
class FakeTransaction:
|
||||
def __init__(self, store):
|
||||
self.store = store
|
||||
|
||||
def __enter__(self):
|
||||
self.published = False
|
||||
self.store.current_transaction = self
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc_value, traceback):
|
||||
if exc_type is None and self.published:
|
||||
self.store.outbox_published = True
|
||||
self.store.current_transaction = None
|
||||
return False
|
||||
|
||||
|
||||
class FakeConnection:
|
||||
def __init__(self, store):
|
||||
self.store = store
|
||||
|
||||
def transaction(self):
|
||||
return FakeTransaction(self.store)
|
||||
|
||||
def execute(self, query, params):
|
||||
assert "UPDATE attachment_outbox" in query
|
||||
assert params == ("outbox-row",)
|
||||
self.store.current_transaction.published = True
|
||||
|
||||
|
||||
class FakePool:
|
||||
def __init__(self, store):
|
||||
self.store = store
|
||||
|
||||
def connection(self):
|
||||
connection = FakeConnection(self.store)
|
||||
|
||||
class ConnectionContext:
|
||||
def __enter__(self_inner):
|
||||
return connection
|
||||
|
||||
def __exit__(self_inner, exc_type, exc_value, traceback):
|
||||
return False
|
||||
|
||||
return ConnectionContext()
|
||||
|
||||
|
||||
class FakeOutboxStore:
|
||||
def __init__(self):
|
||||
self.pool = FakePool(self)
|
||||
self.outbox_published = False
|
||||
self.current_transaction = None
|
||||
|
||||
def claim_outbox(self, connection):
|
||||
if self.outbox_published:
|
||||
return None
|
||||
return {
|
||||
"id": "outbox-row",
|
||||
"job_id": JOB_ID,
|
||||
"attachment_id": ATTACHMENT_ID,
|
||||
"pipeline_version": 1,
|
||||
"attempt": 1,
|
||||
"created_at": datetime(2026, 1, 1, tzinfo=timezone.utc),
|
||||
}
|
||||
|
||||
|
||||
class AmbiguousConfirmChannel:
|
||||
def __init__(self):
|
||||
self.messages = []
|
||||
self.fail_once = True
|
||||
|
||||
def basic_publish(self, **message):
|
||||
self.messages.append(message)
|
||||
if self.fail_once:
|
||||
self.fail_once = False
|
||||
raise pika.exceptions.AMQPConnectionError("simulated lost publisher confirm")
|
||||
|
||||
|
||||
class FailBeforePublishChannel:
|
||||
def __init__(self):
|
||||
self.messages = []
|
||||
self.fail_once = True
|
||||
|
||||
def basic_publish(self, **message):
|
||||
if self.fail_once:
|
||||
self.fail_once = False
|
||||
raise pika.exceptions.AMQPConnectionError("simulated publisher crash before publish")
|
||||
self.messages.append(message)
|
||||
|
||||
|
||||
def test_committed_outbox_survives_publisher_crash():
|
||||
store = FakeOutboxStore()
|
||||
channel = FailBeforePublishChannel()
|
||||
try:
|
||||
publish_pending(store, channel)
|
||||
raise AssertionError("publisher crash was not injected")
|
||||
except pika.exceptions.AMQPConnectionError:
|
||||
pass
|
||||
assert not store.outbox_published
|
||||
assert channel.messages == []
|
||||
assert publish_pending(store, channel)
|
||||
assert store.outbox_published
|
||||
assert len(channel.messages) == 1
|
||||
return {
|
||||
"scenario": "publisher_crash_before_publish",
|
||||
"published_after_restart": len(channel.messages),
|
||||
"outbox_recovered_after_restart": store.outbox_published,
|
||||
}
|
||||
|
||||
|
||||
def test_outbox_confirm_gap_republishes_same_job():
|
||||
store = FakeOutboxStore()
|
||||
channel = AmbiguousConfirmChannel()
|
||||
try:
|
||||
publish_pending(store, channel)
|
||||
raise AssertionError("publisher confirm fault was not injected")
|
||||
except pika.exceptions.AMQPConnectionError:
|
||||
pass
|
||||
assert not store.outbox_published
|
||||
assert publish_pending(store, channel)
|
||||
assert store.outbox_published
|
||||
assert len(channel.messages) == 2
|
||||
first, second = channel.messages
|
||||
assert first["body"] == second["body"]
|
||||
assert first["properties"].message_id == second["properties"].message_id == "outbox-row"
|
||||
return {
|
||||
"scenario": "publish_confirm_lost_after_broker_accept",
|
||||
"deliveries": len(channel.messages),
|
||||
"same_message_id": True,
|
||||
}
|
||||
|
||||
|
||||
def test_image_processing_has_a_hard_timeout():
|
||||
started = time.monotonic()
|
||||
try:
|
||||
_build_variants_bounded(
|
||||
ATTACHMENT_ID,
|
||||
b"bounded timeout test",
|
||||
1,
|
||||
timeout_seconds=1,
|
||||
builder=slow_builder,
|
||||
)
|
||||
raise AssertionError("slow transform exceeded its time budget without termination")
|
||||
except ProcessingTimeout:
|
||||
pass
|
||||
elapsed = time.monotonic() - started
|
||||
assert elapsed < 4
|
||||
return {
|
||||
"scenario": "transform_timeout_terminated",
|
||||
"configured_timeout_seconds": 1,
|
||||
"observed_seconds": round(elapsed, 3),
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
content = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
results = [
|
||||
test_duplicate_and_ack_loss(content),
|
||||
test_crash_before_and_after_side_effect(content, "after_claim"),
|
||||
test_crash_before_and_after_side_effect(content, "after_original_put"),
|
||||
test_reordered_attempts(content),
|
||||
test_stale_pipeline_cannot_publish_newer_result(content),
|
||||
test_committed_outbox_survives_publisher_crash(),
|
||||
test_outbox_confirm_gap_republishes_same_job(),
|
||||
test_image_processing_has_a_hard_timeout(),
|
||||
]
|
||||
report = {
|
||||
"result": "PASS",
|
||||
"track": "2",
|
||||
"fixture": "tests/fixtures/sample.png",
|
||||
"scenarios": results,
|
||||
"invariants": {
|
||||
"confirmed_work_eventually_ready": True,
|
||||
"duplicate_effects_create_no_second_variant_set": True,
|
||||
"stale_attempt_writes_no_effects": True,
|
||||
"stale_pipeline_cannot_publish_current_metadata": True,
|
||||
"ambiguous_confirm_republishes_stable_job": True,
|
||||
"delivery_semantics": "at-least-once; effects are fenced/idempotent",
|
||||
},
|
||||
}
|
||||
evidence = ROOT / "evidence" / "pipeline-faults.json"
|
||||
evidence.parent.mkdir(exist_ok=True)
|
||||
evidence.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8")
|
||||
print(json.dumps(report, sort_keys=True))
|
||||
print(f"Evidence written to {evidence.relative_to(ROOT)}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,167 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify explicit replay changes the deployed pipeline while preserving the original."""
|
||||
import hashlib
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
MARK_FAILED_CODE = """
|
||||
import sys
|
||||
from src.store import Store
|
||||
|
||||
store = Store()
|
||||
store.open()
|
||||
try:
|
||||
with store.pool.connection() as conn:
|
||||
updated = conn.execute(
|
||||
"UPDATE attachments SET status = 'failed', error_code = 'injected_test_failure', "
|
||||
"variants = '[]'::jsonb, lease_until = NULL WHERE id = %s AND status = 'ready'",
|
||||
(sys.argv[1],),
|
||||
)
|
||||
if updated.rowcount != 1:
|
||||
raise RuntimeError("test attachment was not ready for failed replay injection")
|
||||
finally:
|
||||
store.close()
|
||||
"""
|
||||
|
||||
AUDIT_CODE = """
|
||||
import json
|
||||
import sys
|
||||
from src.store import Store
|
||||
|
||||
store = Store()
|
||||
store.open()
|
||||
try:
|
||||
with store.pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT prior_version, pipeline_version, action FROM attachment_pipeline_events "
|
||||
"WHERE attachment_id = %s ORDER BY id",
|
||||
(sys.argv[1],),
|
||||
).fetchall()
|
||||
print(json.dumps(rows, sort_keys=True))
|
||||
finally:
|
||||
store.close()
|
||||
"""
|
||||
|
||||
|
||||
def docker_exec(container_id, *args):
|
||||
return subprocess.run(
|
||||
["docker", "exec", container_id, *args],
|
||||
cwd=ROOT,
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
|
||||
|
||||
def replay(container_id, attachment_id, version):
|
||||
result = docker_exec(
|
||||
container_id,
|
||||
"python3",
|
||||
"-m",
|
||||
"src.replay_attachment",
|
||||
"--attachment-id",
|
||||
attachment_id,
|
||||
"--pipeline-version",
|
||||
str(version),
|
||||
)
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Verify versioned attachment replay against the running Compose stack")
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
attachment, original = client.attachment(alice, chat)
|
||||
ready_v1 = client.wait_ready(alice, attachment)
|
||||
v1_thumbnail = next(item for item in ready_v1["variants"] if item["name"] == "thumbnail")
|
||||
v1_bytes = client.call(
|
||||
"GET",
|
||||
"/api/v1/attachments/" + attachment["id"] + "/content?variant=thumbnail",
|
||||
actor=alice,
|
||||
)["bytes"]
|
||||
check(hashlib.sha256(v1_bytes).hexdigest() == v1_thumbnail["sha256"], "v1 thumbnail checksum mismatch")
|
||||
|
||||
containers = subprocess.run(
|
||||
["docker", "compose", "ps", "--quiet", "--status", "running", "api"],
|
||||
cwd=ROOT,
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
).stdout.split()
|
||||
check(bool(containers), "no running API container found")
|
||||
replay_v2 = replay(containers[0], attachment["id"], 2)
|
||||
check(replay_v2["status"] == "queued", "replay was not queued")
|
||||
check(replay_v2["pipeline_version"] == 2, "replay did not select pipeline v2")
|
||||
check(replay_v2["job_id"] != replay_v2["previous_job_id"], "replay reused the previous logical job id")
|
||||
|
||||
ready_v2 = client.wait_ready(alice, ready_v1)
|
||||
v2_thumbnail = next(item for item in ready_v2["variants"] if item["name"] == "thumbnail")
|
||||
v2_bytes = client.call(
|
||||
"GET",
|
||||
"/api/v1/attachments/" + attachment["id"] + "/content?variant=thumbnail",
|
||||
actor=alice,
|
||||
)["bytes"]
|
||||
original_bytes = client.call(
|
||||
"GET",
|
||||
"/api/v1/attachments/" + attachment["id"] + "/content",
|
||||
actor=alice,
|
||||
)["bytes"]
|
||||
check(v2_thumbnail["sha256"] != v1_thumbnail["sha256"], "pipeline v2 did not change thumbnail encoding")
|
||||
check(hashlib.sha256(v2_bytes).hexdigest() == v2_thumbnail["sha256"], "v2 thumbnail checksum mismatch")
|
||||
check(original_bytes == original, "pipeline replay changed the original file")
|
||||
|
||||
docker_exec(
|
||||
containers[0],
|
||||
"python3",
|
||||
"-c",
|
||||
MARK_FAILED_CODE,
|
||||
attachment["id"],
|
||||
)
|
||||
failed_replay = replay(containers[0], attachment["id"], 2)
|
||||
check(failed_replay["status"] == "queued", "failed attachment replay was not queued")
|
||||
check(failed_replay["pipeline_version"] == 2, "failed replay changed pipeline version")
|
||||
check(failed_replay["job_id"] != failed_replay["previous_job_id"], "failed replay reused a job id")
|
||||
ready_replayed = client.wait_ready(alice, ready_v2)
|
||||
audit = json.loads(
|
||||
docker_exec(
|
||||
containers[0],
|
||||
"python3",
|
||||
"-c",
|
||||
AUDIT_CODE,
|
||||
attachment["id"],
|
||||
).stdout
|
||||
)
|
||||
check(
|
||||
[(row["prior_version"], row["pipeline_version"], row["action"]) for row in audit]
|
||||
== [(1, 2, "replay"), (2, 2, "replay")],
|
||||
"pipeline replay audit trail is incomplete",
|
||||
)
|
||||
check(ready_replayed["status"] == "ready", "failed attachment did not recover")
|
||||
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"result": "PASS",
|
||||
"previous_job_id": replay_v2["previous_job_id"],
|
||||
"job_id": replay_v2["job_id"],
|
||||
"pipeline_version": replay_v2["pipeline_version"],
|
||||
"failed_replay_job_id": failed_replay["job_id"],
|
||||
"audited_replays": len(audit),
|
||||
"v1_thumbnail_sha256": v1_thumbnail["sha256"],
|
||||
"v2_thumbnail_sha256": v2_thumbnail["sha256"],
|
||||
"original_sha256": hashlib.sha256(original_bytes).hexdigest(),
|
||||
},
|
||||
sort_keys=True,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,102 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Deterministic tests of the reconciliation decision rules without deleting real objects."""
|
||||
import os
|
||||
import hashlib
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
os.environ.setdefault("S3_ACCESS_KEY_ID", "test-reconciler")
|
||||
os.environ.setdefault("S3_SECRET_ACCESS_KEY", "test-only-not-a-real-secret")
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from src.reconcile import reconcile
|
||||
|
||||
|
||||
class FakeObjects:
|
||||
def __init__(self, items):
|
||||
self.items = items
|
||||
self.deleted = []
|
||||
|
||||
def objects(self):
|
||||
return iter(self.items)
|
||||
|
||||
def delete(self, key):
|
||||
self.deleted.append(key)
|
||||
self.items = [(name, date) for name, date in self.items if name != key]
|
||||
|
||||
def put(self, key, content, content_type):
|
||||
self.items.append((key, datetime.now(timezone.utc)))
|
||||
|
||||
|
||||
class FakeStore:
|
||||
def __init__(self):
|
||||
now = datetime.now(timezone.utc)
|
||||
self.metadata = {
|
||||
"original/present": {"id": "present-id", "object_key": "original/present"},
|
||||
"original/missing": {
|
||||
"id": "missing-id",
|
||||
"object_key": "original/missing",
|
||||
"size_bytes": 4,
|
||||
"sha256": hashlib.sha256(b"test").hexdigest(),
|
||||
"content_type": "image/png",
|
||||
},
|
||||
}
|
||||
self.objects = FakeObjects(
|
||||
[
|
||||
("original/present", now),
|
||||
("original/stale-orphan", now - timedelta(hours=2)),
|
||||
("original/new-orphan", now - timedelta(minutes=10)),
|
||||
]
|
||||
)
|
||||
self.missing_incidents = set()
|
||||
self.cleared_incidents = set()
|
||||
|
||||
def reconciliation_snapshot(self):
|
||||
return self.metadata
|
||||
|
||||
def record_missing_object(self, attachment_id):
|
||||
self.missing_incidents.add(attachment_id)
|
||||
|
||||
def clear_missing_object(self, attachment_id):
|
||||
self.missing_incidents.discard(attachment_id)
|
||||
self.cleared_incidents.add(attachment_id)
|
||||
|
||||
|
||||
def main():
|
||||
store = FakeStore()
|
||||
dry_run = reconcile(store, grace_seconds=3600, apply_changes=False)
|
||||
assert dry_run["stale_orphan_candidates"] == 1
|
||||
assert dry_run["missing_objects"] == 1
|
||||
assert dry_run["deleted_orphans"] == 0
|
||||
assert store.objects.deleted == [] and store.missing_incidents == set()
|
||||
|
||||
applied = reconcile(store, grace_seconds=3600, apply_changes=True)
|
||||
assert store.objects.deleted == ["original/stale-orphan"]
|
||||
assert "original/new-orphan" not in store.objects.deleted
|
||||
assert store.missing_incidents == {"missing-id"}
|
||||
assert store.cleared_incidents == {"present-id"}
|
||||
assert applied["deleted_orphans"] == 1 and applied["missing_objects"] == 1
|
||||
|
||||
with tempfile.TemporaryDirectory() as backup:
|
||||
restore_dir = Path(backup)
|
||||
(restore_dir / "missing-id").write_bytes(b"test")
|
||||
preview = reconcile(store, 3600, False, restore_dir)
|
||||
assert preview["restorable_missing_objects"] == 1
|
||||
assert store.missing_incidents == {"missing-id"}
|
||||
restored = reconcile(store, 3600, True, restore_dir)
|
||||
assert restored["restored_missing_objects"] == 1
|
||||
assert store.missing_incidents == set()
|
||||
|
||||
repeated = reconcile(store, grace_seconds=3600, apply_changes=True)
|
||||
assert repeated["stale_orphan_candidates"] == 0 and repeated["missing_objects"] == 0
|
||||
assert store.objects.deleted == ["original/stale-orphan"]
|
||||
assert store.missing_incidents == set()
|
||||
print("PASS: dry-run is read-only; stale orphan cleanup is idempotent and respects grace period")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,211 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Exercise real S3/PostgreSQL reconciliation using disposable synthetic objects."""
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
STORE_CODE = """
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from src.store import Store
|
||||
|
||||
store = Store()
|
||||
store.open()
|
||||
try:
|
||||
action = sys.argv[1]
|
||||
if action == "key":
|
||||
attachment_id = sys.argv[2]
|
||||
matches = [
|
||||
key for key, row in store.reconciliation_snapshot().items()
|
||||
if str(row["id"]) == attachment_id and row["reconcile_type"] == "original"
|
||||
]
|
||||
if len(matches) != 1:
|
||||
raise RuntimeError("attachment metadata lookup failed")
|
||||
print(matches[0])
|
||||
elif action == "put":
|
||||
key, file_path = sys.argv[2:4]
|
||||
content = Path(file_path).read_bytes()
|
||||
store.objects.put(key, content, "image/png", len(content))
|
||||
elif action == "delete":
|
||||
store.objects.delete(sys.argv[2])
|
||||
elif action == "exists":
|
||||
print("yes" if any(key == sys.argv[2] for key, _ in store.objects.objects()) else "no")
|
||||
else:
|
||||
raise RuntimeError("unsupported test operation")
|
||||
finally:
|
||||
store.close()
|
||||
"""
|
||||
|
||||
PRIVATE_CHECK_CODE = """
|
||||
import socket
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
try:
|
||||
socket.getaddrinfo("s3-core", 8888)
|
||||
except socket.gaierror:
|
||||
print("PASS: SeaweedFS master/filer network is isolated")
|
||||
else:
|
||||
raise RuntimeError("API network can resolve the SeaweedFS core service")
|
||||
|
||||
for port in (8181, 9101):
|
||||
try:
|
||||
socket.create_connection(("s3", port), timeout=1).close()
|
||||
except OSError:
|
||||
continue
|
||||
raise RuntimeError("unexpected SeaweedFS gateway interface is reachable on port " + str(port))
|
||||
|
||||
try:
|
||||
urllib.request.urlopen("http://s3:8333/messenger-attachments/", timeout=3)
|
||||
except urllib.error.HTTPError as error:
|
||||
if error.code == 403:
|
||||
print("PASS: unauthenticated bucket access denied")
|
||||
else:
|
||||
raise RuntimeError("unexpected anonymous S3 status: " + str(error.code))
|
||||
else:
|
||||
raise RuntimeError("private bucket allowed an unauthenticated GET")
|
||||
"""
|
||||
|
||||
|
||||
def docker_exec(container_id, *args):
|
||||
return subprocess.run(
|
||||
["docker", "exec", container_id, *args],
|
||||
cwd=ROOT,
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
|
||||
|
||||
def reconciliation(container_id, *args):
|
||||
result = docker_exec(container_id, "python3", "src/reconcile.py", "--grace-seconds", "60", *args)
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
def object_exists(container_id, key):
|
||||
return docker_exec(
|
||||
container_id, "python3", "-c", STORE_CODE, "exists", key
|
||||
).stdout.strip() == "yes"
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Real PostgreSQL/SeaweedFS reconciliation and private-bucket experiment")
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
alice, bob, _, chat = client.bootstrap()
|
||||
attachment, content = client.attachment(alice, chat)
|
||||
attachment = client.wait_ready(alice, attachment)
|
||||
message = client.message(alice, chat, "", attachments=[attachment["id"]])["json"]
|
||||
|
||||
result = subprocess.run(
|
||||
["docker", "compose", "ps", "--quiet", "--status", "running", "api"],
|
||||
cwd=ROOT,
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
containers = result.stdout.split()
|
||||
check(len(containers) >= 2, "at least two running API replicas are required")
|
||||
container_id = containers[0]
|
||||
key = docker_exec(
|
||||
container_id, "python3", "-c", STORE_CODE, "key", attachment["id"]
|
||||
).stdout.strip()
|
||||
orphan_key = "original/" + str(uuid.uuid4())
|
||||
|
||||
with tempfile.TemporaryDirectory() as backup:
|
||||
source = Path(backup) / "original.png"
|
||||
source.write_bytes(content)
|
||||
container_file = "/tmp/lab4-orphan-" + uuid.uuid4().hex + ".png"
|
||||
recovery_dir = "/tmp/lab4-recovery-" + uuid.uuid4().hex
|
||||
recovery_file = recovery_dir + "/" + attachment["id"]
|
||||
orphan_created = False
|
||||
orphan_removed = False
|
||||
missing_deleted = False
|
||||
missing_restored = False
|
||||
try:
|
||||
subprocess.run(["docker", "cp", str(source), container_id + ":" + container_file], check=True)
|
||||
docker_exec(container_id, "python3", "-c", STORE_CODE, "put", orphan_key, container_file)
|
||||
orphan_created = True
|
||||
docker_exec(container_id, "python3", "-c", STORE_CODE, "delete", key)
|
||||
missing_deleted = True
|
||||
|
||||
preview = reconciliation(container_id)
|
||||
check(
|
||||
preview["orphan_objects"] >= 1 and preview["missing_objects"] == 1,
|
||||
"dry-run missed injected inconsistencies",
|
||||
)
|
||||
check(preview["deleted_orphans"] == 0, "dry-run modified S3")
|
||||
immediate_apply = reconciliation(container_id, "--apply")
|
||||
check(object_exists(container_id, orphan_key), "fresh orphan was deleted during the grace period")
|
||||
|
||||
docker_exec(container_id, "mkdir", "-p", recovery_dir)
|
||||
subprocess.run(
|
||||
["docker", "cp", str(source), container_id + ":" + recovery_file],
|
||||
check=True,
|
||||
)
|
||||
restore_preview = reconciliation(container_id, "--restore-dir", recovery_dir)
|
||||
check(restore_preview["restorable_missing_objects"] == 1, "exact backup was not identified as restorable")
|
||||
restored = reconciliation(container_id, "--apply", "--restore-dir", recovery_dir)
|
||||
check(restored["restored_missing_objects"] == 1, "missing S3 object was not restored")
|
||||
missing_restored = True
|
||||
|
||||
repeated = reconciliation(container_id, "--apply", "--restore-dir", recovery_dir)
|
||||
check(repeated["missing_objects"] == 0, "repeat reconciliation still reports missing object")
|
||||
check(object_exists(container_id, orphan_key), "recent orphan did not respect grace period")
|
||||
print("Waiting for the 60-second orphan grace period.")
|
||||
time.sleep(61)
|
||||
|
||||
cleanup_preview = reconciliation(container_id)
|
||||
check(cleanup_preview["stale_orphan_candidates"] >= 1, "stale orphan was not identified after grace")
|
||||
cleaned = reconciliation(container_id, "--apply")
|
||||
orphan_removed = not object_exists(container_id, orphan_key)
|
||||
check(orphan_removed, "injected stale orphan was not removed")
|
||||
final_scan = reconciliation(container_id, "--apply")
|
||||
check(
|
||||
final_scan["orphan_objects"] == 0 and final_scan["missing_objects"] == 0,
|
||||
"repeat scan is not clean",
|
||||
)
|
||||
finally:
|
||||
if missing_deleted and not missing_restored:
|
||||
docker_exec(container_id, "python3", "-c", STORE_CODE, "put", key, container_file)
|
||||
if orphan_created and not orphan_removed:
|
||||
docker_exec(container_id, "python3", "-c", STORE_CODE, "delete", orphan_key)
|
||||
|
||||
private = docker_exec(container_id, "python3", "-c", PRIVATE_CHECK_CODE).stdout.strip()
|
||||
check("PASS:" in private, "unauthenticated S3 access check failed")
|
||||
downloaded = client.call(
|
||||
"GET",
|
||||
"/api/v1/attachments/" + attachment["id"] + "/content",
|
||||
actor=bob,
|
||||
)["bytes"]
|
||||
check(downloaded == content, "reconciler changed the original of an attachment used by a message")
|
||||
check(message["attachment_ids"] == [attachment["id"]], "test message did not retain the attachment reference")
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"result": "PASS",
|
||||
"dataset_objects_scanned": final_scan["objects_seen"],
|
||||
"metadata_records_scanned": final_scan["metadata_seen"],
|
||||
"scan_duration_ms": final_scan["duration_ms"],
|
||||
"orphan_detected_and_removed": cleaned["deleted_orphans"],
|
||||
"missing_detected_and_restored": restored["restored_missing_objects"],
|
||||
"fresh_orphan_preserved_until_grace": True,
|
||||
"message_attachment_download_checksum": "unchanged",
|
||||
"private_bucket": "anonymous request denied",
|
||||
},
|
||||
sort_keys=True,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,45 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Local transformation checks for the lab5 image worker."""
|
||||
import hashlib
|
||||
import io
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
os.environ.setdefault("S3_ACCESS_KEY_ID", "worker-test")
|
||||
os.environ.setdefault("S3_SECRET_ACCESS_KEY", "worker-test-secret")
|
||||
|
||||
from PIL import Image
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from src.worker import build_variants
|
||||
|
||||
|
||||
def main():
|
||||
original = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
attachment_id = "00000000-0000-4000-8000-000000000001"
|
||||
variants = build_variants(attachment_id, original, pipeline_version=1)
|
||||
by_name = {item["name"]: item for item in variants}
|
||||
assert set(by_name) == {"thumbnail", "crop", "optimized"}
|
||||
assert (by_name["thumbnail"]["width"], by_name["thumbnail"]["height"]) == (256, 160)
|
||||
assert (by_name["crop"]["width"], by_name["crop"]["height"]) == (128, 128)
|
||||
assert by_name["optimized"]["content_type"] == "image/webp"
|
||||
for item in variants:
|
||||
content = item["content"]
|
||||
assert len(content) == item["size_bytes"]
|
||||
assert hashlib.sha256(content).hexdigest() == item["sha256"]
|
||||
with Image.open(io.BytesIO(content)) as image:
|
||||
assert image.size == (item["width"], item["height"])
|
||||
newer = build_variants(attachment_id, original, pipeline_version=2)
|
||||
assert all(f"/v2/" in item["object_key"] for item in newer)
|
||||
assert all(f"/v1/" in item["object_key"] for item in variants)
|
||||
assert by_name["thumbnail"]["sha256"] != {
|
||||
item["name"]: item for item in newer
|
||||
}["thumbnail"]["sha256"]
|
||||
print("PASS: versioned thumbnail, crop, and optimized variants match dimensions and checksums")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,78 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify queued uploads and message links survive an API/worker restart."""
|
||||
import hashlib
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def compose(*args):
|
||||
return subprocess.run(
|
||||
["docker", "compose", *args],
|
||||
cwd=ROOT,
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Verify queued attachment recovery after API and worker restart")
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
alice, bob, _, chat = client.bootstrap()
|
||||
compose("stop", "worker")
|
||||
worker_stopped = True
|
||||
try:
|
||||
attachment, original = client.attachment(alice, chat)
|
||||
check(attachment["status"] == "queued", "upload was not accepted while worker was stopped")
|
||||
message = client.message(alice, chat, "", attachments=[attachment["id"]])["json"]
|
||||
check(message["attachment_ids"] == [attachment["id"]], "queued attachment was not linked to message")
|
||||
client.call(
|
||||
"GET",
|
||||
"/api/v1/attachments/" + attachment["id"] + "/content",
|
||||
409,
|
||||
actor=bob,
|
||||
)
|
||||
compose("restart", "api")
|
||||
compose("start", "worker")
|
||||
worker_stopped = False
|
||||
client.call("GET", "/health/ready", schema="Health")
|
||||
ready = client.wait_ready(bob, attachment)
|
||||
original_bytes = client.call(
|
||||
"GET",
|
||||
"/api/v1/attachments/" + attachment["id"] + "/content",
|
||||
actor=bob,
|
||||
)["bytes"]
|
||||
check(original_bytes == original, "recovered worker changed original bytes")
|
||||
page = client.call(
|
||||
"GET",
|
||||
"/api/v1/chats/" + chat["id"] + "/messages",
|
||||
actor=bob,
|
||||
schema="MessagePage",
|
||||
)["json"]
|
||||
recovered_message = next(item for item in page["items"] if item["id"] == message["id"])
|
||||
check(recovered_message["attachment_ids"] == [attachment["id"]], "message lost attachment link")
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"result": "PASS",
|
||||
"initial_status": attachment["status"],
|
||||
"final_status": ready["status"],
|
||||
"message_attachment_link_survived": True,
|
||||
"original_sha256": hashlib.sha256(original_bytes).hexdigest(),
|
||||
},
|
||||
sort_keys=True,
|
||||
)
|
||||
)
|
||||
finally:
|
||||
if worker_stopped:
|
||||
compose("start", "worker")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,365 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Repeat a paced synthetic message workload with telemetry off and sampled."""
|
||||
import argparse
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import re
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
|
||||
|
||||
def command(args, capture=True):
|
||||
result = subprocess.run(
|
||||
args,
|
||||
cwd=ROOT,
|
||||
check=True,
|
||||
text=True,
|
||||
stdout=subprocess.PIPE if capture else None,
|
||||
stderr=subprocess.PIPE if capture else None,
|
||||
)
|
||||
return result.stdout.strip() if capture else ""
|
||||
|
||||
|
||||
def set_env_value(text, name, value):
|
||||
lines = text.splitlines()
|
||||
prefix = name + "="
|
||||
for index, line in enumerate(lines):
|
||||
if line.startswith(prefix):
|
||||
lines[index] = prefix + value
|
||||
break
|
||||
else:
|
||||
lines.append(prefix + value)
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def parse_env(text):
|
||||
values = {}
|
||||
for line in text.splitlines():
|
||||
if line and not line.startswith("#") and "=" in line:
|
||||
name, value = line.split("=", 1)
|
||||
values[name] = value
|
||||
return values
|
||||
|
||||
|
||||
def wait_ready(url, ca_file=None, timeout=90):
|
||||
deadline = time.monotonic() + timeout
|
||||
context = ssl.create_default_context(cafile=ca_file)
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
with urllib.request.urlopen(url + "/health/ready", context=context, timeout=2) as response:
|
||||
if response.status == 200:
|
||||
return
|
||||
except (urllib.error.URLError, TimeoutError, OSError):
|
||||
pass
|
||||
time.sleep(2)
|
||||
raise RuntimeError("API did not become ready after the sampling mode change")
|
||||
|
||||
|
||||
def parse_size(value):
|
||||
match = re.fullmatch(r"\s*([\d.]+)\s*(B|kB|MB|GB|KiB|MiB|GiB)\s*", value)
|
||||
if not match:
|
||||
return None
|
||||
factors = {
|
||||
"B": 1,
|
||||
"kB": 1000,
|
||||
"MB": 1000**2,
|
||||
"GB": 1000**3,
|
||||
"KiB": 1024,
|
||||
"MiB": 1024**2,
|
||||
"GiB": 1024**3,
|
||||
}
|
||||
return int(float(match.group(1)) * factors[match.group(2)])
|
||||
|
||||
|
||||
def docker_resources():
|
||||
rows = command(
|
||||
[
|
||||
"docker",
|
||||
"stats",
|
||||
"--no-stream",
|
||||
"--format",
|
||||
"{{.Name}};{{.CPUPerc}};{{.MemUsage}}",
|
||||
]
|
||||
)
|
||||
cpu_total = 0.0
|
||||
memory_total = 0
|
||||
found = False
|
||||
for row in rows.splitlines():
|
||||
fields = row.split(";")
|
||||
if len(fields) != 3 or not any(
|
||||
name in fields[0] for name in ("-api-", "-worker-", "-publisher-", "-otel-collector-")
|
||||
):
|
||||
continue
|
||||
cpu = re.match(r"\s*([\d.]+)%", fields[1])
|
||||
memory = parse_size(fields[2].split("/", 1)[0])
|
||||
if cpu and memory is not None:
|
||||
cpu_total += float(cpu.group(1))
|
||||
memory_total += memory
|
||||
found = True
|
||||
return {"cpu_percent_sum": round(cpu_total, 2), "memory_bytes_sum": memory_total} if found else None
|
||||
|
||||
|
||||
def storage_sizes(compose):
|
||||
paths = {
|
||||
"prometheus": (["exec", "-T", "prometheus", "du", "-sb", "/prometheus"]),
|
||||
"loki": (["exec", "-T", "loki", "du", "-sb", "/loki"]),
|
||||
"tempo": (["exec", "-T", "tempo", "du", "-sb", "/var/tempo"]),
|
||||
}
|
||||
result = {}
|
||||
for name, args in paths.items():
|
||||
output = command(compose + args)
|
||||
result[name] = int(output.split()[0])
|
||||
return result
|
||||
|
||||
|
||||
def tempo_message_traces(compose, start, end):
|
||||
url = (
|
||||
"http://127.0.0.1:3200/api/search?start=%d&end=%d&limit=2000"
|
||||
"&tags=service.name%%3Dmessenger-api" % (start, end)
|
||||
)
|
||||
output = command(compose + ["exec", "-T", "tempo", "wget", "-qO-", url])
|
||||
data = json.loads(output)
|
||||
return [
|
||||
item
|
||||
for item in data.get("traces", [])
|
||||
if item.get("rootTraceName") == "POST /api/v1/chats/{chat_id}/messages"
|
||||
]
|
||||
|
||||
|
||||
def mean_spans(compose, traces, sample_limit=20):
|
||||
counts = []
|
||||
for item in traces[:sample_limit]:
|
||||
output = command(
|
||||
compose
|
||||
+ [
|
||||
"exec",
|
||||
"-T",
|
||||
"tempo",
|
||||
"wget",
|
||||
"-qO-",
|
||||
"http://127.0.0.1:3200/api/traces/" + item["traceID"],
|
||||
]
|
||||
)
|
||||
data = json.loads(output)
|
||||
count = sum(
|
||||
len(scope.get("spans", []))
|
||||
for batch in data.get("batches", [])
|
||||
for scope in batch.get("instrumentationLibrarySpans", batch.get("scopeSpans", []))
|
||||
)
|
||||
counts.append(count)
|
||||
return round(sum(counts) / len(counts), 2) if counts else 0.0
|
||||
|
||||
|
||||
def run_load(base_url, ca_file, duration, concurrency, target_rps, alice, chat):
|
||||
from client import Client, Failure
|
||||
|
||||
barrier = threading.Barrier(concurrency + 1)
|
||||
ticket_lock = threading.Lock()
|
||||
ticket = 0
|
||||
latencies = []
|
||||
failures = 0
|
||||
results_lock = threading.Lock()
|
||||
start_clock = time.monotonic()
|
||||
start_epoch = int(time.time())
|
||||
deadline = start_clock + duration
|
||||
|
||||
def worker(worker_id):
|
||||
nonlocal ticket, failures
|
||||
client = Client(base_url, ca_file, timeout=5)
|
||||
local_latencies = []
|
||||
local_failures = 0
|
||||
barrier.wait()
|
||||
while True:
|
||||
with ticket_lock:
|
||||
current = ticket
|
||||
ticket += 1
|
||||
due = start_clock + current / target_rps
|
||||
if due >= deadline:
|
||||
break
|
||||
delay = due - time.monotonic()
|
||||
if delay > 0:
|
||||
time.sleep(delay)
|
||||
started = time.monotonic()
|
||||
try:
|
||||
client.message(alice, chat, "synthetic-track1-%d-%d" % (worker_id, current))
|
||||
local_latencies.append(time.monotonic() - started)
|
||||
except Failure:
|
||||
local_failures += 1
|
||||
with results_lock:
|
||||
latencies.extend(local_latencies)
|
||||
failures += local_failures
|
||||
|
||||
samples = []
|
||||
with ThreadPoolExecutor(max_workers=concurrency) as pool:
|
||||
futures = [pool.submit(worker, worker_id) for worker_id in range(concurrency)]
|
||||
barrier.wait()
|
||||
while any(not future.done() for future in futures):
|
||||
sample = docker_resources()
|
||||
if sample is not None:
|
||||
samples.append(sample)
|
||||
time.sleep(2)
|
||||
for future in futures:
|
||||
future.result()
|
||||
elapsed = time.monotonic() - start_clock
|
||||
sorted_latencies = sorted(latencies)
|
||||
|
||||
def percentile(value):
|
||||
if not sorted_latencies:
|
||||
return None
|
||||
index = max(0, math.ceil(value * len(sorted_latencies)) - 1)
|
||||
return round(sorted_latencies[index] * 1000, 3)
|
||||
|
||||
total = len(sorted_latencies) + failures
|
||||
report = {
|
||||
"workload": "paced synthetic POST messages; no automatic retries",
|
||||
"requested_duration_seconds": duration,
|
||||
"target_rps": target_rps,
|
||||
"elapsed_seconds": round(elapsed, 3),
|
||||
"concurrency": concurrency,
|
||||
"successful_requests": len(sorted_latencies),
|
||||
"failed_requests": failures,
|
||||
"error_ratio": round(failures / total, 6) if total else None,
|
||||
"successful_rps": round(len(sorted_latencies) / elapsed, 3),
|
||||
"successful_latency_ms": {
|
||||
"p50": percentile(0.50),
|
||||
"p95": percentile(0.95),
|
||||
"p99": percentile(0.99),
|
||||
},
|
||||
"docker_resource_samples": len(samples),
|
||||
}
|
||||
if samples:
|
||||
report["docker_resources"] = {
|
||||
"mean_cpu_percent_sum": round(
|
||||
sum(item["cpu_percent_sum"] for item in samples) / len(samples), 2
|
||||
),
|
||||
"peak_cpu_percent_sum": max(item["cpu_percent_sum"] for item in samples),
|
||||
"peak_memory_bytes_sum": max(item["memory_bytes_sum"] for item in samples),
|
||||
"services": ["api", "worker", "publisher", "otel-collector"],
|
||||
}
|
||||
return report, start_epoch, int(time.time())
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--env-file", default=".env")
|
||||
parser.add_argument("--base-url", default=None)
|
||||
parser.add_argument("--ca-file", default=None)
|
||||
parser.add_argument("--duration", type=int, default=15)
|
||||
parser.add_argument("--concurrency", type=int, default=2)
|
||||
parser.add_argument("--target-rps", type=int, default=20)
|
||||
parser.add_argument("--warmup-seconds", type=int, default=5)
|
||||
parser.add_argument("--output", default="evidence/track1-observability-cost.json")
|
||||
args = parser.parse_args()
|
||||
if not 1 <= args.duration <= 3600 or not 1 <= args.concurrency <= 128 or args.target_rps < 1:
|
||||
parser.error("duration must be 1..3600, concurrency 1..128, and target-rps positive")
|
||||
|
||||
env_path = ROOT / args.env_file
|
||||
if not env_path.is_file():
|
||||
parser.error("create the local .env from .env.example and generate secrets first")
|
||||
original = env_path.read_text(encoding="utf-8")
|
||||
values = parse_env(original)
|
||||
base_url = args.base_url or "https://localhost:" + values.get("APP_PORT", "8443")
|
||||
compose = ["docker", "compose", "--env-file", str(env_path)]
|
||||
output_path = ROOT / args.output
|
||||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
results = []
|
||||
configurations = [
|
||||
("off", "true", "1.0"),
|
||||
("sample-100-percent", "false", "1.0"),
|
||||
("sample-25-percent", "false", "0.25"),
|
||||
("sample-10-percent", "false", "0.1"),
|
||||
]
|
||||
try:
|
||||
for name, disabled, ratio in configurations:
|
||||
changed = set_env_value(original, "OTEL_SDK_DISABLED", disabled)
|
||||
changed = set_env_value(changed, "OTEL_TRACES_SAMPLER", "parentbased_traceidratio")
|
||||
changed = set_env_value(changed, "OTEL_TRACES_SAMPLER_ARG", ratio)
|
||||
env_path.write_text(changed, encoding="utf-8")
|
||||
command(compose + ["up", "-d", "--force-recreate", "api", "publisher", "worker"])
|
||||
wait_ready(base_url, args.ca_file)
|
||||
time.sleep(args.warmup_seconds)
|
||||
from client import Client
|
||||
|
||||
alice, _, _, chat = Client(base_url, args.ca_file, timeout=10).bootstrap()
|
||||
time.sleep(2)
|
||||
before = storage_sizes(compose)
|
||||
load, start, end = run_load(
|
||||
base_url, args.ca_file, args.duration, args.concurrency, args.target_rps, alice, chat
|
||||
)
|
||||
time.sleep(15)
|
||||
after = storage_sizes(compose)
|
||||
traces = tempo_message_traces(compose, start - 5, end + 20)
|
||||
spans_per_trace = mean_spans(compose, traces)
|
||||
results.append(
|
||||
{
|
||||
"configuration": name,
|
||||
"sdk_disabled": disabled == "true",
|
||||
"trace_sampling_ratio": float(ratio),
|
||||
"load": load,
|
||||
"window_unix_seconds": {"start": start, "end": end},
|
||||
"sampled_message_trace_count": len(traces),
|
||||
"estimated_spans_per_message_trace": spans_per_trace,
|
||||
"persistent_storage_bytes_delta": {
|
||||
signal: after[signal] - before[signal] for signal in before
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
baseline = next(
|
||||
item["estimated_spans_per_message_trace"]
|
||||
for item in results
|
||||
if item["configuration"] == "sample-100-percent"
|
||||
)
|
||||
for item in results:
|
||||
expected_spans = item["load"]["successful_requests"] * baseline
|
||||
observed_spans = item["sampled_message_trace_count"] * item["estimated_spans_per_message_trace"]
|
||||
item["estimated_spans_not_recorded"] = round(max(0.0, expected_spans - observed_spans), 2)
|
||||
|
||||
report = {
|
||||
"experiment": "telemetry overhead under fixed-rate synthetic POST load",
|
||||
"hypothesis": "Trace sampling lowers API/worker CPU and Tempo ingest; metrics and logs remain enabled.",
|
||||
"method": {
|
||||
"duration_seconds": args.duration,
|
||||
"concurrency": args.concurrency,
|
||||
"target_rps": args.target_rps,
|
||||
"warmup_seconds": args.warmup_seconds,
|
||||
"telemetry_flush_wait_seconds": 15,
|
||||
"hardware": {
|
||||
"platform": platform.platform(),
|
||||
"processor": platform.processor() or "unspecified",
|
||||
"logical_cpus": os.cpu_count(),
|
||||
},
|
||||
"sampled_span_estimate": "The first 20 matching message traces per mode are opened in Tempo; the resulting mean spans per trace is extrapolated to all sampled messages.",
|
||||
"storage_method": "Filesystem byte deltas in Prometheus, Loki and Tempo named volumes; this includes indexes/WAL and is not network wire size.",
|
||||
},
|
||||
"limitations": [
|
||||
"The generator paces arrivals but has finite concurrency and can catch up after delays; it is not a production open-loop load model.",
|
||||
"Database history grows between modes; all modes use identical duration and concurrency.",
|
||||
"Sampling is head-based and random: errors and rare slow requests can be omitted along with successful requests.",
|
||||
"Span loss is an estimate based on sampled message traces, not Collector exporter delivery counters.",
|
||||
"CPU and memory are sampled Docker container totals for API, worker, publisher and Collector; the monitor adds equal overhead to all modes.",
|
||||
],
|
||||
"results": results,
|
||||
"balanced_configuration": "sample-25-percent",
|
||||
}
|
||||
output_path.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
print(json.dumps(report, ensure_ascii=False, indent=2))
|
||||
finally:
|
||||
env_path.write_text(original, encoding="utf-8")
|
||||
command(compose + ["up", "-d", "--force-recreate", "api", "publisher", "worker"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,151 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run ten simultaneous near-6-MiB uploads and sample API container memory."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from io import BytesIO
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
from PIL import Image
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
UNIT = {"B": 1, "KiB": 1024, "MiB": 1024**2, "GiB": 1024**3}
|
||||
USAGE_RE = re.compile(r"([\d.]+)(B|KiB|MiB|GiB)\s*/")
|
||||
|
||||
|
||||
def usage_bytes(line):
|
||||
match = USAGE_RE.search(line)
|
||||
return int(float(match.group(1)) * UNIT[match.group(2)]) if match else 0
|
||||
|
||||
|
||||
def api_containers():
|
||||
result = subprocess.run(
|
||||
["docker", "compose", "ps", "--quiet", "--status", "running", "api"],
|
||||
cwd=ROOT,
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
ids = result.stdout.split()
|
||||
check(len(ids) >= 2, "at least two running API containers are required")
|
||||
return ids
|
||||
|
||||
|
||||
def sample_once(ids):
|
||||
output = subprocess.run(
|
||||
["docker", "stats", "--no-stream", "--format", "{{.MemUsage}}", *ids],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
).stdout.splitlines()
|
||||
values = [usage_bytes(line) for line in output]
|
||||
check(len(values) == len(ids) and all(values), "could not parse docker stats memory usage")
|
||||
return max(values)
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Bounded-memory ten-client upload experiment")
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
width = height = 1400
|
||||
content = BytesIO()
|
||||
Image.frombytes("RGB", (width, height), os.urandom(width * height * 3)).save(
|
||||
content, format="PNG", compress_level=0
|
||||
)
|
||||
payload = content.getvalue()
|
||||
check(0 < len(payload) <= 10 * 1024 * 1024, "synthetic PNG is outside the upload size limit")
|
||||
ids = api_containers()
|
||||
baseline = sample_once(ids)
|
||||
samples = []
|
||||
stats_process = subprocess.Popen(
|
||||
["docker", "stats", "--format", "{{.MemUsage}}", *ids],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
bufsize=1,
|
||||
)
|
||||
|
||||
def sampler():
|
||||
if stats_process.stdout is None:
|
||||
return
|
||||
for line in stats_process.stdout:
|
||||
value = usage_bytes(line)
|
||||
if value:
|
||||
samples.append(value)
|
||||
|
||||
sampling_thread = threading.Thread(target=sampler, daemon=True)
|
||||
sampling_thread.start()
|
||||
count = 10
|
||||
barrier = threading.Barrier(count)
|
||||
|
||||
def upload(index):
|
||||
worker = Client(args.base_url, args.ca_file)
|
||||
barrier.wait(timeout=15)
|
||||
return worker.call(
|
||||
"POST",
|
||||
"/api/v1/chats/" + chat["id"] + "/attachments?filename=load-" + str(index) + ".png",
|
||||
202,
|
||||
actor=alice,
|
||||
raw=payload,
|
||||
headers={"Content-Type": "image/png"},
|
||||
schema="Attachment",
|
||||
)
|
||||
|
||||
started = time.monotonic()
|
||||
try:
|
||||
with ThreadPoolExecutor(max_workers=count) as pool:
|
||||
responses = list(pool.map(upload, range(count)))
|
||||
finally:
|
||||
stopped_by_test = False
|
||||
if stats_process.poll() is None:
|
||||
stats_process.kill()
|
||||
stopped_by_test = True
|
||||
try:
|
||||
stats_process.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
stats_process.kill()
|
||||
stats_process.wait(timeout=5)
|
||||
sampling_thread.join(timeout=5)
|
||||
stats_error = stats_process.stderr.read() if stats_process.stderr is not None else ""
|
||||
check(
|
||||
stats_process.returncode == 0 or (stopped_by_test and stats_process.returncode == -9),
|
||||
"docker stats sampling process failed (exit "
|
||||
+ str(stats_process.returncode)
|
||||
+ "): "
|
||||
+ stats_error.strip()[:300],
|
||||
)
|
||||
check(bool(samples), "docker stats produced no memory samples")
|
||||
peak = max([baseline] + samples)
|
||||
check(len(responses) == count and all(response["status"] == 202 for response in responses), "an upload failed")
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"uploads": count,
|
||||
"concurrency": count,
|
||||
"bytes_per_upload": len(payload),
|
||||
"duration_seconds": round(time.monotonic() - started, 3),
|
||||
"api_containers": len(ids),
|
||||
"sample_count": len(samples) // len(ids),
|
||||
"baseline_max_container_bytes": baseline,
|
||||
"peak_max_container_bytes": peak,
|
||||
"peak_delta_bytes": max(0, peak - baseline),
|
||||
"sampling_method": "continuous docker stats stream; Docker/CLI sampling cadence",
|
||||
"memory_scope": "Docker-reported API container working set; LB, DB, S3, and host cache excluded",
|
||||
},
|
||||
sort_keys=True,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
Reference in New Issue
Block a user