ЛР6: наблюдаемость, SLO и диагностика отказов
This commit is contained in:
@@ -0,0 +1,317 @@
|
||||
import os
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from contextlib import contextmanager
|
||||
from urllib.error import HTTPError, URLError
|
||||
|
||||
from client import Client, check, run
|
||||
from observe import trace_for, upload
|
||||
from pipeline_support import COMPOSE, compose, ready_api, sql, wait_ready
|
||||
from telemetry_support import logs, save, spans, states, value, wait_until
|
||||
|
||||
|
||||
API_ALERTS = ["ApiHighErrorRate", "ApiBurnFast", "ApiBurnSlow"]
|
||||
READY_ALERTS = ["ReadyBurnFast", "ReadyBurnSlow"]
|
||||
|
||||
|
||||
class Traffic:
|
||||
def __init__(self, actor):
|
||||
self.actor = actor
|
||||
self.stop = threading.Event()
|
||||
self.lock = threading.Lock()
|
||||
self.counts = {}
|
||||
self.error = None
|
||||
self.slowest_ok = 0
|
||||
|
||||
def run(self):
|
||||
client = Client(timeout=12)
|
||||
while not self.stop.is_set():
|
||||
started = time.monotonic()
|
||||
try:
|
||||
response = client.call(
|
||||
"GET", "/api/v1/users/me", actor=self.actor, expected=[200, 503]
|
||||
)
|
||||
status = response["status"]
|
||||
elapsed = time.monotonic() - started
|
||||
with self.lock:
|
||||
self.counts[status] = self.counts.get(status, 0) + 1
|
||||
if status == 200:
|
||||
self.slowest_ok = max(self.slowest_ok, elapsed)
|
||||
else:
|
||||
self.error = response["headers"]["X-Request-Id"]
|
||||
except Exception as error:
|
||||
with self.lock:
|
||||
name = type(error).__name__
|
||||
self.counts[name] = self.counts.get(name, 0) + 1
|
||||
self.stop.wait(0.2)
|
||||
|
||||
@contextmanager
|
||||
def start(self, clients=6):
|
||||
with ThreadPoolExecutor(max_workers=clients) as pool:
|
||||
workers = [pool.submit(self.run) for _ in range(clients)]
|
||||
try:
|
||||
yield self
|
||||
finally:
|
||||
self.stop.set()
|
||||
for worker in workers:
|
||||
worker.result()
|
||||
|
||||
def snapshot(self):
|
||||
with self.lock:
|
||||
return dict(self.counts)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def session_lock(seconds):
|
||||
command = (
|
||||
'psql -v ON_ERROR_STOP=1 -U "$(cat /run/secrets/postgres_user)"'
|
||||
' -d "$(cat /run/secrets/postgres_db)" -At'
|
||||
)
|
||||
with subprocess.Popen(
|
||||
COMPOSE + ["exec", "-T", "db", "sh", "-c", command],
|
||||
stdin=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE,
|
||||
text=True,
|
||||
) as process:
|
||||
process.stdin.write(
|
||||
f"SET application_name='lab6-incident'; BEGIN; LOCK TABLE sessions IN ACCESS EXCLUSIVE MODE; "
|
||||
f"SELECT pg_sleep({seconds}); ROLLBACK;\n"
|
||||
)
|
||||
process.stdin.close()
|
||||
try:
|
||||
wait_until(
|
||||
lambda: sql(
|
||||
"SELECT count(*) FROM pg_stat_activity WHERE application_name='lab6-incident'"
|
||||
" AND wait_event='PgSleep';"
|
||||
)
|
||||
== "1",
|
||||
15,
|
||||
"database lock not acquired",
|
||||
)
|
||||
yield time.monotonic()
|
||||
finally:
|
||||
sql(
|
||||
"SELECT pg_cancel_backend(pid) FROM pg_stat_activity"
|
||||
" WHERE application_name='lab6-incident' AND state='active';"
|
||||
)
|
||||
process.wait(timeout=15)
|
||||
|
||||
|
||||
def monitor(names, firing, timeout, started):
|
||||
samples = []
|
||||
|
||||
reached = set()
|
||||
target = "firing" if firing else "inactive"
|
||||
|
||||
def check_state():
|
||||
snapshot = states()
|
||||
samples.append(
|
||||
{
|
||||
"seconds": round(time.monotonic() - started, 2),
|
||||
"states": {name: snapshot[name] for name in names},
|
||||
}
|
||||
)
|
||||
reached.update(name for name in names if snapshot[name] == target)
|
||||
return (
|
||||
len(reached) == len(names)
|
||||
if firing
|
||||
else all(snapshot[name] == target for name in names)
|
||||
)
|
||||
|
||||
wait_until(check_state, timeout, "unexpected alert states: " + str(names))
|
||||
return samples
|
||||
|
||||
|
||||
def find_failed_dependency(request_id, since):
|
||||
trace_id = wait_until(lambda: trace_for(request_id, since), 35, "DB incident log missing")
|
||||
|
||||
def dependency():
|
||||
try:
|
||||
rows = spans(trace_id)
|
||||
except HTTPError as error:
|
||||
if error.code == 404:
|
||||
return None
|
||||
raise
|
||||
for row in rows:
|
||||
if row["name"] == "postgres.session.lookup":
|
||||
duration = (int(row["endTimeUnixNano"]) - int(row["startTimeUnixNano"])) / 1e9
|
||||
if duration >= 3:
|
||||
return {
|
||||
"trace_id": trace_id,
|
||||
"request_id": request_id,
|
||||
"dependency": row["name"],
|
||||
"duration_seconds": duration,
|
||||
"status": row.get("status"),
|
||||
}
|
||||
return None
|
||||
|
||||
return wait_until(dependency, 35, "slow PostgreSQL span missing")
|
||||
|
||||
|
||||
def database_incidents(actor):
|
||||
with Traffic(actor).start() as traffic:
|
||||
time.sleep(15)
|
||||
wait_until(lambda: traffic.snapshot().get(200, 0) >= 35, 15, "no warm traffic")
|
||||
before = traffic.snapshot().get(503, 0)
|
||||
with session_lock(3) as started:
|
||||
canceled = sql(
|
||||
"SELECT pg_cancel_backend(pid) FROM (SELECT pid FROM pg_stat_activity"
|
||||
" WHERE wait_event_type='Lock' AND query LIKE '%sessions%' LIMIT 1) AS blocked;"
|
||||
)
|
||||
check(canceled == "t", "short incident did not cancel a DB read")
|
||||
brief = []
|
||||
for _ in range(17):
|
||||
brief.append({"seconds": round(time.monotonic() - started, 2), "states": states()})
|
||||
time.sleep(1)
|
||||
short_errors = traffic.snapshot().get(503, 0) - before
|
||||
check(short_errors > 0, "short fault produced no observed errors")
|
||||
check(
|
||||
not any(sample["states"][name] == "firing" for sample in brief for name in API_ALERTS),
|
||||
"short burst fired an API alert",
|
||||
)
|
||||
since = time.time() - 2
|
||||
with session_lock(85) as started:
|
||||
detection = monitor(API_ALERTS, True, 75, started)
|
||||
request_id = traffic.error
|
||||
released = time.monotonic()
|
||||
recovery = monitor(API_ALERTS, False, 95, released)
|
||||
check(
|
||||
traffic.snapshot().get(200, 0) > 30 and traffic.snapshot().get(503, 0) > short_errors,
|
||||
"sustained incident did not affect HTTP",
|
||||
)
|
||||
sample = find_failed_dependency(request_id, since)
|
||||
return {
|
||||
"traffic_clients": 6,
|
||||
"short": {"503_count": short_errors, "samples": brief, "alert_firings": 0},
|
||||
"sustained": {
|
||||
"firing": detection,
|
||||
"resolved": recovery,
|
||||
"bounded_lock_seconds": 85,
|
||||
"traffic_statuses": traffic.snapshot(),
|
||||
"cause": sample,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def queue_incident(client, actor, chat):
|
||||
compose("stop", "worker")
|
||||
started = time.monotonic()
|
||||
attachments = []
|
||||
try:
|
||||
for index in range(16):
|
||||
attachments.append(upload(client, actor, chat, "lag-" + str(index))["json"])
|
||||
provisional = monitor(["AttachmentQueueLag"], True, 45, started)
|
||||
peak = {
|
||||
"age_seconds": value("max(lab_queue_oldest_seconds)"),
|
||||
"backlog": value("max(lab_queue_depth)"),
|
||||
"reported_capacity": value("sum(lab_worker_capacity)"),
|
||||
}
|
||||
check(peak["backlog"] >= 16, "observability reported no backlog")
|
||||
finally:
|
||||
compose("start", "worker")
|
||||
released = time.monotonic()
|
||||
for attachment in attachments:
|
||||
wait_ready(client, actor, attachment)
|
||||
drain = round(time.monotonic() - released, 2)
|
||||
ready_firing = monitor(READY_ALERTS, True, 45, released)
|
||||
resolved = monitor(["AttachmentQueueLag"], False, 30, released)
|
||||
ready_resolved = monitor(READY_ALERTS, False, 90, released)
|
||||
return {
|
||||
"accepted": len(attachments),
|
||||
"queue_firing": provisional,
|
||||
"peak": peak,
|
||||
"drained_seconds": drain,
|
||||
"ready_burn_firing": ready_firing,
|
||||
"queue_resolved": resolved,
|
||||
"ready_burn_resolved": ready_resolved,
|
||||
"all_ready": True,
|
||||
}
|
||||
|
||||
|
||||
def collector_snapshot():
|
||||
metric = "otelcol_exporter_send_failed_log_records_total"
|
||||
return {
|
||||
"send_failed_logs": value("sum(" + metric + '{exporter="otlphttp/loki"})'),
|
||||
"queue_size": value('max(otelcol_exporter_queue_size{exporter="otlphttp/loki"})'),
|
||||
"queue_capacity": value('max(otelcol_exporter_queue_capacity{exporter="otlphttp/loki"})'),
|
||||
"rss_bytes": value("otelcol_process_memory_rss_bytes"),
|
||||
}
|
||||
|
||||
|
||||
def backend_incident(client, actor, chat):
|
||||
before = collector_snapshot()
|
||||
acknowledged = []
|
||||
samples = []
|
||||
compose("stop", "loki")
|
||||
started = time.monotonic()
|
||||
try:
|
||||
for index in range(30):
|
||||
acknowledged.append(
|
||||
client.message(actor, chat, "backend proof " + str(index))["json"]["id"]
|
||||
)
|
||||
if index % 3 == 0:
|
||||
samples.append(collector_snapshot())
|
||||
time.sleep(0.7)
|
||||
samples.append(collector_snapshot())
|
||||
finally:
|
||||
compose("start", "loki")
|
||||
page = client.call(
|
||||
"GET", f"/api/v1/chats/{chat['id']}/messages?limit=100", actor=actor, schema="MessagePage"
|
||||
)["json"]
|
||||
check(
|
||||
set(acknowledged) <= {item["id"] for item in page["items"]},
|
||||
"message loss during telemetry outage",
|
||||
)
|
||||
after = collector_snapshot()
|
||||
failed = (
|
||||
max([after["send_failed_logs"], *[s["send_failed_logs"] for s in samples]])
|
||||
- before["send_failed_logs"]
|
||||
)
|
||||
check(failed > 0, "Collector exporter drops were not observed")
|
||||
wait_until(loki_ready, 75, "Loki failed to recover")
|
||||
since = time.time() - 2
|
||||
response = client.message(actor, chat, "telemetry restored")
|
||||
restored_trace = wait_until(
|
||||
lambda: trace_for(response["headers"]["X-Request-Id"], since),
|
||||
45,
|
||||
"new business log not exported after Loki recovery",
|
||||
)
|
||||
return {
|
||||
"confirmed_and_read": len(acknowledged),
|
||||
"seconds": round(time.monotonic() - started, 2),
|
||||
"collector_before": before,
|
||||
"collector_samples": samples,
|
||||
"collector_after": after,
|
||||
"failed_export_log_records_delta": failed,
|
||||
"restored_trace_id": restored_trace,
|
||||
}
|
||||
|
||||
|
||||
def loki_ready():
|
||||
try:
|
||||
logs('{service_name="messenger-api"}', limit=1)
|
||||
return True
|
||||
except (HTTPError, URLError, TimeoutError):
|
||||
return False
|
||||
|
||||
|
||||
def main():
|
||||
ready_api()
|
||||
client = Client(timeout=12)
|
||||
actor, _, _, chat = client.bootstrap()
|
||||
mode = os.getenv("INCIDENT", "all")
|
||||
if mode in ("all", "db"):
|
||||
save("database-incident.json", database_incidents(actor))
|
||||
print("PASS short DB burst and sustained slowdown: real alerts and DB trace", flush=True)
|
||||
if mode in ("all", "queue"):
|
||||
save("queue-incident.json", queue_incident(client, actor, chat))
|
||||
print("PASS stopped worker: backlog, firing/resolved and slow READY burn", flush=True)
|
||||
if mode in ("all", "backend"):
|
||||
save("backend-incident.json", backend_incident(client, actor, chat))
|
||||
print("PASS stopped Loki: bounded telemetry failure and saved business writes", flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,185 @@
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from urllib.error import HTTPError
|
||||
|
||||
from client import Client, check, run
|
||||
from pipeline_support import compose, fault, job, ready_api, wait_ready
|
||||
from telemetry_support import fetch, logs, prom, save, spans, wait_until
|
||||
|
||||
|
||||
def upload(client, actor, chat, name):
|
||||
return client.call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/attachments?filename={name}.png",
|
||||
actor=actor,
|
||||
raw=Path("tests/fixtures/sample.png").read_bytes(),
|
||||
headers={"Content-Type": "image/png"},
|
||||
expected=202,
|
||||
schema="Attachment",
|
||||
)
|
||||
|
||||
|
||||
def trace_for(request_id, since):
|
||||
rows = logs('{service_name="messenger-api"} | request_id="' + request_id + '"', since)
|
||||
for row in rows:
|
||||
trace_id = row["stream"].get("trace_id")
|
||||
for entry in row["values"]:
|
||||
metadata = entry[2] if len(entry) > 2 else {}
|
||||
trace_id = trace_id or metadata.get("trace_id")
|
||||
if trace_id:
|
||||
return trace_id
|
||||
return None
|
||||
|
||||
|
||||
def complete_trace(trace_id):
|
||||
try:
|
||||
rows = spans(trace_id)
|
||||
except HTTPError as error:
|
||||
if error.code == 404:
|
||||
return None
|
||||
raise
|
||||
required = {
|
||||
"POST /api/v1/chats/{chat_id}/attachments",
|
||||
"attachments publish",
|
||||
"attachments consume",
|
||||
"s3.staging.read",
|
||||
"postgres.publish_result",
|
||||
}
|
||||
return (
|
||||
rows
|
||||
if required <= {row["name"] for row in rows}
|
||||
and sum(row["name"] == "attachments consume" for row in rows) >= 2
|
||||
else None
|
||||
)
|
||||
|
||||
|
||||
def verify_trace(rows):
|
||||
indexed = {s["spanId"]: s for s in rows}
|
||||
consumers = [s for s in rows if s["name"] == "attachments consume"]
|
||||
assert len(consumers) >= 2, "retry absent from trace"
|
||||
for consumer in consumers:
|
||||
producer = indexed[consumer["parentSpanId"]]
|
||||
assert producer["name"] == "attachments publish", "consumer parent is not producer"
|
||||
assert (
|
||||
indexed[producer["parentSpanId"]]["kind"] == "SPAN_KIND_SERVER"
|
||||
or str(indexed[producer["parentSpanId"]]["kind"]) == "2"
|
||||
)
|
||||
return [
|
||||
{
|
||||
key: row.get(key)
|
||||
for key in ("name", "service", "spanId", "parentSpanId", "kind", "status")
|
||||
}
|
||||
for row in rows
|
||||
]
|
||||
|
||||
|
||||
def verify_metrics():
|
||||
names = [
|
||||
"lab_http_requests_total",
|
||||
"lab_http_duration_seconds_bucket",
|
||||
"lab_jobs_total",
|
||||
"lab_job_duration_seconds_bucket",
|
||||
"lab_ready_duration_seconds_bucket",
|
||||
"lab_queue_depth",
|
||||
"lab_queue_oldest_seconds",
|
||||
"lab_db_pool_connections",
|
||||
"lab_worker_busy",
|
||||
"lab_worker_capacity",
|
||||
"lab_process_cpu_seconds_total",
|
||||
"lab_process_rss_bytes",
|
||||
]
|
||||
return wait_until(
|
||||
lambda: collect_metrics(names),
|
||||
50,
|
||||
"required metric series missing",
|
||||
)
|
||||
|
||||
|
||||
def collect_metrics(names):
|
||||
result = prom('{__name__=~"' + "|".join(names) + '"}')
|
||||
present = {row["metric"]["__name__"] for row in result}
|
||||
if present != set(names):
|
||||
return None
|
||||
forbidden = {
|
||||
"user_id",
|
||||
"chat_id",
|
||||
"message_id",
|
||||
"attachment_id",
|
||||
"request_id",
|
||||
"filename",
|
||||
"url",
|
||||
}
|
||||
for row in result:
|
||||
assert not forbidden & set(row["metric"]), "forbidden metric attributes"
|
||||
return {
|
||||
name: {
|
||||
"series": sum(row["metric"]["__name__"] == name for row in result),
|
||||
"label_keys": sorted(
|
||||
{
|
||||
key
|
||||
for row in result
|
||||
if row["metric"]["__name__"] == name
|
||||
for key in row["metric"]
|
||||
}
|
||||
),
|
||||
}
|
||||
for name in names
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
ready_api()
|
||||
client = Client(timeout=12)
|
||||
actor, _, _, chat = client.bootstrap()
|
||||
marker = "proof" + uuid.uuid4().hex
|
||||
client.message(actor, chat, marker)
|
||||
since = time.time() - 2
|
||||
compose("stop", "worker")
|
||||
try:
|
||||
response = upload(client, actor, chat, marker)
|
||||
attachment = response["json"]
|
||||
fault(attachment, "before_effects", "transient")
|
||||
finally:
|
||||
compose("start", "worker")
|
||||
wait_ready(client, actor, attachment)
|
||||
check(job(attachment)["attempt"] == 2, "proof job did not retry")
|
||||
request_id = response["headers"]["X-Request-Id"]
|
||||
trace_id = wait_until(
|
||||
lambda: trace_for(request_id, since), 45, "API request ID missing from Loki"
|
||||
)
|
||||
rows = wait_until(lambda: complete_trace(trace_id), 60, "correlated trace missing from Tempo")
|
||||
worker_logs = wait_until(
|
||||
lambda: logs('{service_name="messenger-worker"} | trace_id="' + trace_id + '"', since),
|
||||
30,
|
||||
"worker logs missing for trace",
|
||||
)
|
||||
events = sorted({entry[1] for row in worker_logs for entry in row["values"]})
|
||||
check("worker.retry" in events and "worker.ready" in events, "retry/ready logs missing")
|
||||
check(
|
||||
not logs('{service_name=~"messenger-.+"} |= "' + marker + '"', since - 10),
|
||||
"sensitive marker in logs",
|
||||
)
|
||||
check(marker not in str(rows), "sensitive marker in trace")
|
||||
check(
|
||||
fetch("/api/dashboards/uid/messenger-lab6")["dashboard"]["title"] == "Messenger Lab 6",
|
||||
"dashboard not provisioned",
|
||||
)
|
||||
save(
|
||||
"signal-link.json",
|
||||
{
|
||||
"trace_id": trace_id,
|
||||
"request_id": request_id,
|
||||
"spans": verify_trace(rows),
|
||||
"worker_events": events,
|
||||
"marker_absent": True,
|
||||
},
|
||||
)
|
||||
save("metric-inventory.json", verify_metrics())
|
||||
print(
|
||||
"PASS real upload -> publish -> consumer retry -> S3/DB; Loki/Tempo/Prometheus via Grafana"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,15 @@
|
||||
from client import run
|
||||
from pipeline_faults import Experiment
|
||||
|
||||
|
||||
def main():
|
||||
experiment = Experiment()
|
||||
experiment.fenced_without_dispatcher()
|
||||
print(
|
||||
"PASS expired worker without dispatcher: no premature ACK; pending/index retained; recovery publishes exactly one result on attempt 2",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,133 @@
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from client import Client, check, run
|
||||
from pipeline_support import compose, sql, ready_api, wait_ready, wait_for, operator, COMPOSE
|
||||
import subprocess
|
||||
import uuid
|
||||
|
||||
|
||||
def eligibility(c, a, chat, attachment):
|
||||
sql(
|
||||
"create function proof_message_guard() returns trigger language plpgsql as $$ begin if NEW.chat_id='"
|
||||
+ chat["id"]
|
||||
+ "'::uuid then perform pg_sleep(4); end if; return NEW; end; $$; create trigger proof_message_guard before insert on messages for each row execute function proof_message_guard();"
|
||||
)
|
||||
try:
|
||||
with ThreadPoolExecutor(max_workers=1) as pool:
|
||||
request = pool.submit(c.message, a, chat, "guard", None, [attachment["id"]])
|
||||
wait_for(
|
||||
lambda: sql("select count(*) from pg_stat_activity where wait_event='PgSleep';")
|
||||
!= "0",
|
||||
10,
|
||||
)
|
||||
code = """import psycopg
|
||||
from pipeline.repository import Repository
|
||||
from pipeline.config import Settings
|
||||
try:
|
||||
with Repository(Settings()).connection() as db:
|
||||
db.execute("SET lock_timeout='250ms'")
|
||||
db.execute("UPDATE attachments SET status='FAILED',error_code='injected_failure' WHERE id=%s",('ATTACHMENT',))
|
||||
except psycopg.errors.LockNotAvailable:
|
||||
print('blocked_by_message_transaction',flush=True)
|
||||
else:
|
||||
raise AssertionError('status changed between validation and commit')
|
||||
""".replace(
|
||||
"ATTACHMENT", attachment["id"]
|
||||
)
|
||||
output = compose("exec", "-T", "dispatcher", "python", "-c", code)
|
||||
check(output == "blocked_by_message_transaction", "status guard missing")
|
||||
check(
|
||||
request.result()["json"]["attachment_ids"] == [attachment["id"]],
|
||||
"message not created",
|
||||
)
|
||||
finally:
|
||||
sql("drop trigger proof_message_guard on messages; drop function proof_message_guard();")
|
||||
sql(
|
||||
"begin;update attachments set status='FAILED',error_code='injected_failure' where id='"
|
||||
+ attachment["id"]
|
||||
+ "';update processing_jobs set status='FAILED',error_code='injected_failure' where attachment_id='"
|
||||
+ attachment["id"]
|
||||
+ "';commit;"
|
||||
)
|
||||
c.call(
|
||||
"POST",
|
||||
"/api/v1/chats/" + chat["id"] + "/messages",
|
||||
409,
|
||||
actor=a,
|
||||
body={"text": "", "attachment_ids": [attachment["id"]]},
|
||||
headers={"Idempotency-Key": uuid.uuid4().hex},
|
||||
)
|
||||
operator("replay", attachment)
|
||||
print(
|
||||
"PASS message eligibility: status UPDATE blocked until Message COMMIT; subsequent FAILED attachment rejected with 409",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
|
||||
def download_guard(c, actor, attachment, body):
|
||||
code = """import time
|
||||
from pipeline.repository import Repository
|
||||
from pipeline.config import Settings
|
||||
with Repository(Settings()).connection() as db:
|
||||
db.execute('SELECT pg_advisory_xact_lock(741204)')
|
||||
print('cleanup_locked',flush=True)
|
||||
time.sleep(4)
|
||||
"""
|
||||
holder = subprocess.Popen(
|
||||
COMPOSE + ["exec", "-T", "dispatcher", "python", "-c", code],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
)
|
||||
try:
|
||||
check(holder.stdout.readline().strip() == "cleanup_locked", "cleanup fence not acquired")
|
||||
with ThreadPoolExecutor(max_workers=1) as pool:
|
||||
request = pool.submit(
|
||||
c.call,
|
||||
"GET",
|
||||
"/api/v1/attachments/" + attachment["id"] + "/content",
|
||||
200,
|
||||
None,
|
||||
actor,
|
||||
)
|
||||
wait_for(
|
||||
lambda: sql(
|
||||
"select count(*) from pg_stat_activity where wait_event='advisory' and query ilike '%pg_advisory_xact_lock_shared(741204)%';"
|
||||
)
|
||||
!= "0",
|
||||
3,
|
||||
"download did not wait on cleanup fence",
|
||||
)
|
||||
check(not request.done(), "download bypassed cleanup fence")
|
||||
_, errors = holder.communicate(timeout=10)
|
||||
check(holder.returncode == 0, "cleanup holder failed")
|
||||
check(request.result(timeout=10)["bytes"] == body, "download changed bytes")
|
||||
check(
|
||||
sql("select pg_try_advisory_xact_lock(741204);") == "t",
|
||||
"download leaked transaction fence",
|
||||
)
|
||||
finally:
|
||||
if holder.poll() is None:
|
||||
holder.kill()
|
||||
holder.wait()
|
||||
print(
|
||||
"PASS download/cleanup barrier: content waits for exclusive cleanup, returns identical bytes, releases shared fence",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
ready_api()
|
||||
c = Client(base_url="http://127.0.0.1:18085", timeout=30)
|
||||
a, b, e, chat = c.bootstrap()
|
||||
compose("stop", "worker")
|
||||
try:
|
||||
attachment, body = c.attachment(a, chat)
|
||||
eligibility(c, a, chat, attachment)
|
||||
finally:
|
||||
compose("start", "worker")
|
||||
wait_ready(c, a, attachment)
|
||||
download_guard(c, b, attachment, body)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,142 @@
|
||||
from client import Client, check, run
|
||||
from pipeline_support import ready_api, wait_ready, metadata, compose, broker, sql
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
from PIL import Image
|
||||
import hashlib
|
||||
import io
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
|
||||
|
||||
def main():
|
||||
ready_api()
|
||||
c = Client(base_url="http://127.0.0.1:18085", timeout=30)
|
||||
a, b, e, chat = c.bootstrap()
|
||||
png = Path("tests/fixtures/sample.png").read_bytes()
|
||||
path = "/api/v1/chats/" + chat["id"] + "/attachments?filename=proof.png"
|
||||
|
||||
def upload(data=png, mime="image/png", expected=202):
|
||||
return c.call(
|
||||
"POST",
|
||||
path,
|
||||
expected,
|
||||
actor=a,
|
||||
raw=data,
|
||||
headers={"Content-Type": mime},
|
||||
schema="Attachment" if expected == 202 else None,
|
||||
)
|
||||
|
||||
compose("stop", "worker")
|
||||
attachment = upload()["json"]
|
||||
check(attachment["status"] == "queued", "upload response not queued snapshot")
|
||||
c.call("GET", "/api/v1/attachments/" + attachment["id"] + "/content", 409, actor=b)
|
||||
c.message(a, chat, "", attachments=[attachment["id"]])
|
||||
compose("start", "worker")
|
||||
result = wait_ready(c, b, attachment)
|
||||
verify(c, b, attachment, png, result)
|
||||
print(
|
||||
"PASS queued snapshot, link before ready, 409 before worker; original + 3 variants",
|
||||
flush=True,
|
||||
)
|
||||
negative(c, a, e, chat, attachment, upload, png)
|
||||
fixtures(c, a, b, upload)
|
||||
concurrent(c, a, chat, attachment)
|
||||
print("PASS core pipeline contract", flush=True)
|
||||
|
||||
|
||||
def verify(c, actor, attachment, original, result):
|
||||
base = "/api/v1/attachments/" + attachment["id"] + "/content"
|
||||
check(c.call("GET", base, actor=actor)["bytes"] == original, "original changed")
|
||||
check(
|
||||
{v["name"] for v in result["variants"]} == {"thumbnail", "crop", "optimized"},
|
||||
"variant set differs",
|
||||
)
|
||||
for variant in result["variants"]:
|
||||
response = c.call("GET", base + "?variant=" + variant["name"], actor=actor)
|
||||
check(
|
||||
hashlib.sha256(response["bytes"]).hexdigest() == variant["sha256"], "variant checksum"
|
||||
)
|
||||
check(len(response["bytes"]) == variant["size_bytes"], "variant size")
|
||||
check(response["headers"].get_content_type() == variant["content_type"], "variant MIME")
|
||||
with Image.open(io.BytesIO(response["bytes"])) as image:
|
||||
check(image.size == (variant["width"], variant["height"]), "variant dimensions")
|
||||
check(not image.getexif(), "EXIF retained")
|
||||
|
||||
|
||||
def negative(c, a, e, chat, attachment, upload, png):
|
||||
upload(png[:33], expected=415)
|
||||
upload(png, "image/jpeg", 415)
|
||||
upload(b"x" * 10485761, expected=413)
|
||||
c.call(
|
||||
"POST",
|
||||
"/api/v1/chats/" + chat["id"] + "/attachments?filename=..%2Fx.png",
|
||||
400,
|
||||
actor=a,
|
||||
raw=png,
|
||||
headers={"Content-Type": "image/png"},
|
||||
)
|
||||
for suffix in ("", "/content"):
|
||||
c.call("GET", "/api/v1/attachments/" + attachment["id"] + suffix, 404, actor=e)
|
||||
other = c.call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
201,
|
||||
actor=a,
|
||||
body={"title": "other", "member_ids": [a["id"]]},
|
||||
schema="Chat",
|
||||
)["json"]
|
||||
c.call(
|
||||
"POST",
|
||||
"/api/v1/chats/" + other["id"] + "/messages",
|
||||
404,
|
||||
actor=a,
|
||||
body={"text": "x", "attachment_ids": [attachment["id"]]},
|
||||
headers={"Idempotency-Key": uuid.uuid4().hex},
|
||||
)
|
||||
print("PASS bytes/corruption/MIME/filename/ACL/cross-chat negatives", flush=True)
|
||||
|
||||
|
||||
def fixtures(c, a, b, upload):
|
||||
output = io.BytesIO()
|
||||
Image.new("RGBA", (8, 4), (255, 0, 0, 0)).save(output, format="PNG")
|
||||
attachment = upload(output.getvalue())["json"]
|
||||
result = wait_ready(c, b, attachment)
|
||||
data = c.call(
|
||||
"GET", "/api/v1/attachments/" + attachment["id"] + "/content?variant=thumbnail", actor=b
|
||||
)["bytes"]
|
||||
with Image.open(io.BytesIO(data)) as image:
|
||||
check(
|
||||
image.size == (8, 4) and min(image.getpixel((0, 0))) >= 250, "alpha/upscale incorrect"
|
||||
)
|
||||
output = io.BytesIO()
|
||||
image = Image.new("RGB", (80, 40), (20, 80, 160))
|
||||
exif = image.getexif()
|
||||
exif[274] = 6
|
||||
image.save(output, format="JPEG", exif=exif)
|
||||
attachment = upload(output.getvalue(), "image/jpeg")["json"]
|
||||
result = wait_ready(c, b, attachment)
|
||||
thumb = next(v for v in result["variants"] if v["name"] == "thumbnail")
|
||||
check((thumb["width"], thumb["height"]) == (40, 80), "EXIF orientation ignored")
|
||||
verify(c, b, attachment, output.getvalue(), result)
|
||||
print("PASS alpha white, no small-image enlargement, EXIF rotation, crop and WebP", flush=True)
|
||||
|
||||
|
||||
def concurrent(c, a, chat, attachment):
|
||||
key = uuid.uuid4().hex
|
||||
|
||||
def send(_):
|
||||
return c.message(a, chat, "concurrent", key=key, attachments=[attachment["id"]])
|
||||
|
||||
with ThreadPoolExecutor(max_workers=12) as pool:
|
||||
replies = list(pool.map(send, range(24)))
|
||||
check(len({r["json"]["id"] for r in replies}) == 1, "duplicate message effects")
|
||||
check(
|
||||
len({r["headers"]["X-Instance-Id"] for r in replies}) == 2, "two API replicas not observed"
|
||||
)
|
||||
print("PASS 24 concurrent requests across 2 API replicas; single message effect", flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,373 @@
|
||||
from client import Client, check, run
|
||||
from pipeline_support import (
|
||||
compose,
|
||||
sql,
|
||||
broker,
|
||||
wait_for,
|
||||
ready_api,
|
||||
metadata,
|
||||
wait_ready,
|
||||
job,
|
||||
payload,
|
||||
inject_duplicate,
|
||||
fault,
|
||||
fault_hit,
|
||||
operator,
|
||||
manifest,
|
||||
events,
|
||||
)
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
from PIL import Image
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
|
||||
|
||||
class Experiment:
|
||||
def __init__(self):
|
||||
ready_api()
|
||||
self.client = Client(base_url="http://127.0.0.1:18085", timeout=30)
|
||||
self.actor, self.member, self.outsider, self.chat = self.client.bootstrap()
|
||||
self.body = Path("tests/fixtures/sample.png").read_bytes()
|
||||
self.rows = []
|
||||
self.accepted = []
|
||||
|
||||
def upload(self, body=None, expected=202):
|
||||
response = self.client.call(
|
||||
"POST",
|
||||
"/api/v1/chats/" + self.chat["id"] + "/attachments?filename=fault.png",
|
||||
expected,
|
||||
actor=self.actor,
|
||||
raw=self.body if body is None else body,
|
||||
headers={"Content-Type": "image/png"},
|
||||
schema="Attachment" if expected == 202 or isinstance(expected, list) else None,
|
||||
)
|
||||
if response["status"] == 202:
|
||||
self.accepted.append(response["json"]["id"])
|
||||
return response["json"]
|
||||
return response
|
||||
|
||||
def run_case(self, name, action):
|
||||
started = time.monotonic()
|
||||
action()
|
||||
row = {"scenario": name, "result": "PASS", "seconds": round(time.monotonic() - started, 3)}
|
||||
self.rows.append(row)
|
||||
print(json.dumps(row), flush=True)
|
||||
Path("evidence/pipeline-faults.json").write_text(json.dumps(self.rows, indent=2))
|
||||
|
||||
def settled(self, attachment):
|
||||
wait_ready(self.client, self.actor, attachment, 120)
|
||||
check(events(attachment, "ready") == 1, "multiple published effects")
|
||||
check(
|
||||
int(
|
||||
sql(
|
||||
"select count(*) from attachment_variants where attachment_id='"
|
||||
+ attachment["id"]
|
||||
+ "';"
|
||||
)
|
||||
)
|
||||
== 3,
|
||||
"duplicate variants",
|
||||
)
|
||||
data = self.client.call(
|
||||
"GET", "/api/v1/attachments/" + attachment["id"] + "/content", actor=self.member
|
||||
)["bytes"]
|
||||
check(data == self.body, "original changed")
|
||||
|
||||
def prepare(self, point, action, count=1):
|
||||
compose("stop", "worker")
|
||||
attachment = self.upload()
|
||||
fault(attachment, point, action, count)
|
||||
compose("start", "worker")
|
||||
return attachment
|
||||
|
||||
def durability(self):
|
||||
compose("stop", "worker", "dispatcher")
|
||||
accepted = [self.upload() for _ in range(2)]
|
||||
for attachment in accepted:
|
||||
self.client.message(self.actor, self.chat, "", attachments=[attachment["id"]])
|
||||
check(job(attachment)["status"] == "QUEUED", "worker ran while stopped")
|
||||
check(
|
||||
sql(
|
||||
"select published_at IS NULL from processing_outbox where job_id='"
|
||||
+ job(attachment)["job_id"]
|
||||
+ "';"
|
||||
)
|
||||
== "t",
|
||||
"unexpected publish",
|
||||
)
|
||||
compose("restart", "api")
|
||||
ready_api()
|
||||
fault(accepted[0], "before_publish", "crash")
|
||||
compose("start", "dispatcher")
|
||||
wait_for(lambda: fault_hit(accepted[0], "before_publish"))
|
||||
wait_for(
|
||||
lambda: all(
|
||||
job(a)["job_id"] in broker("XRANGE", "attachment-jobs", "-", "+") for a in accepted
|
||||
)
|
||||
)
|
||||
before = broker("XLEN", "attachment-jobs")
|
||||
time.sleep(12)
|
||||
check(
|
||||
broker("XLEN", "attachment-jobs") == before,
|
||||
"watchdog multiplied queued broker messages",
|
||||
)
|
||||
compose("restart", "broker")
|
||||
wait_for(lambda: broker("PING") == "PONG")
|
||||
history = broker("XRANGE", "attachment-jobs", "-", "+")
|
||||
check(all(job(a)["job_id"] in history for a in accepted), "broker restart lost messages")
|
||||
compose("start", "worker")
|
||||
for attachment in accepted:
|
||||
self.settled(attachment)
|
||||
print(
|
||||
"durability: 202 -> outbox COMMIT without publisher; API restart; publish; broker restart while worker stopped; same jobs ready",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
def publisher_confirm_window(self):
|
||||
compose("stop", "worker", "dispatcher")
|
||||
attachment = self.upload()
|
||||
fault(attachment, "after_publish", "crash")
|
||||
compose("start", "dispatcher")
|
||||
wait_for(lambda: fault_hit(attachment, "after_publish"))
|
||||
compose("start", "worker")
|
||||
self.settled(attachment)
|
||||
wait_for(lambda: broker("XLEN", "attachment-jobs") == "0", 60)
|
||||
check(self.object_count(attachment) == 4, "publisher crash duplicated effect")
|
||||
|
||||
def duplicates(self):
|
||||
attachment = self.upload()
|
||||
self.settled(attachment)
|
||||
value = payload(attachment)
|
||||
before = manifest(attachment)
|
||||
attempt = job(attachment)["attempt"]
|
||||
with ThreadPoolExecutor(max_workers=8) as pool:
|
||||
list(pool.map(lambda _: inject_duplicate(value), range(24)))
|
||||
wait_for(lambda: broker("XLEN", "attachment-jobs") == "0")
|
||||
check(
|
||||
manifest(attachment) == before and job(attachment)["attempt"] == attempt,
|
||||
"ready duplicate executed",
|
||||
)
|
||||
check(self.object_count(attachment) == 4, "duplicate S3 object set")
|
||||
|
||||
def object_count(self, attachment):
|
||||
code = (
|
||||
"from pipeline.storage import Storage;from pipeline.config import Settings;s=Storage(Settings());print(len(s.client.list_objects_v2(Bucket=s.settings.bucket,Prefix='results/"
|
||||
+ attachment["id"]
|
||||
+ "/').get('Contents',[])))"
|
||||
)
|
||||
return int(compose("exec", "-T", "dispatcher", "python", "-c", code))
|
||||
|
||||
def crash(self, point):
|
||||
attachment = self.prepare(point, "crash")
|
||||
wait_for(lambda: fault_hit(attachment, point), 60)
|
||||
self.settled(attachment)
|
||||
wait_for(lambda: broker("XLEN", "attachment-jobs") == "0", 60)
|
||||
check(self.object_count(attachment) == 4, "crash redelivery multiplied S3 objects")
|
||||
expected = 2 if point in ("before_effects", "after_effects") else 1
|
||||
check(job(attachment)["attempt"] == expected, "unexpected managed attempt count")
|
||||
|
||||
def lease_fencing(self):
|
||||
attachment = self.prepare("after_effects", "pause")
|
||||
wait_for(lambda: fault_hit(attachment, "after_effects"), 60)
|
||||
self.settled(attachment)
|
||||
wait_for(lambda: events(attachment, "fenced_stale_result") >= 1, 30)
|
||||
check(job(attachment)["attempt"] == 2, "lease did not recover work")
|
||||
check(self.object_count(attachment) == 4, "lease recovery multiplied objects")
|
||||
|
||||
def timeout_recovery(self):
|
||||
attachment = self.prepare("before_effects", "timeout")
|
||||
wait_for(lambda: fault_hit(attachment, "before_effects"), 60)
|
||||
self.settled(attachment)
|
||||
wait_for(lambda: events(attachment, "worker_timeout") >= 1, 40)
|
||||
check(self.object_count(attachment) == 4, "timeout recovery multiplied effects")
|
||||
|
||||
def fenced_without_dispatcher(self):
|
||||
attachment = self.prepare("after_effects", "pause")
|
||||
wait_for(lambda: fault_hit(attachment, "after_effects"), 60)
|
||||
compose("stop", "dispatcher")
|
||||
try:
|
||||
time.sleep(13)
|
||||
check(job(attachment)["status"] == "PROCESSING", "test did not hold recovery window")
|
||||
check(events(attachment, "ready") == 0, "expired worker published result")
|
||||
check(
|
||||
int(broker("XLEN", "attachment-jobs")) >= 1,
|
||||
"unfinished current delivery acknowledged",
|
||||
)
|
||||
check(
|
||||
int(broker("HLEN", "job-publications")) >= 1, "unfinished publication index removed"
|
||||
)
|
||||
finally:
|
||||
compose("start", "dispatcher")
|
||||
self.settled(attachment)
|
||||
wait_for(lambda: broker("XLEN", "attachment-jobs") == "0", 60)
|
||||
check(
|
||||
job(attachment)["attempt"] == 2, "lease recovery did not schedule next managed attempt"
|
||||
)
|
||||
check(self.object_count(attachment) == 4, "recovery multiplied S3 effects")
|
||||
Path("evidence/fenced-pending.json").write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"attachment_id": attachment["id"],
|
||||
"unfinished_delivery_retained": True,
|
||||
"recovered_attempt": 2,
|
||||
"one_manifest": True,
|
||||
"s3_objects": 4,
|
||||
},
|
||||
indent=2,
|
||||
)
|
||||
)
|
||||
|
||||
def version_fencing(self):
|
||||
attachment = self.prepare("after_effects", "pause")
|
||||
wait_for(lambda: fault_hit(attachment, "after_effects"), 60)
|
||||
old = payload(attachment)
|
||||
operator("upgrade", attachment, 2)
|
||||
wait_ready(self.client, self.actor, attachment, 90)
|
||||
check(job(attachment)["pipeline_version"] == 2, "new version missing")
|
||||
before = manifest(attachment)
|
||||
wait_for(lambda: events(attachment, "fenced_stale_result") >= 1, 30)
|
||||
new = payload(attachment)
|
||||
for value in [new, old, new, old, old]:
|
||||
inject_duplicate(value)
|
||||
wait_for(lambda: broker("XLEN", "attachment-jobs") == "0", 60)
|
||||
check(manifest(attachment) == before, "old result overwrote new version")
|
||||
check("/v2/" in before and "/v1/" not in before, "wrong manifest version")
|
||||
check(events(attachment, "ready") == 1, "old in-flight version published")
|
||||
|
||||
def failure_replay(self, action):
|
||||
attachment = self.prepare("before_effects", action, 3 if action == "transient" else 1)
|
||||
wait_for(lambda: metadata(self.client, self.actor, attachment)["status"] == "failed", 90)
|
||||
result = metadata(self.client, self.actor, attachment)
|
||||
check(
|
||||
result["error_code"]
|
||||
== ("retry_exhausted" if action == "transient" else "invalid_image"),
|
||||
"unsafe failure code",
|
||||
)
|
||||
original = job(attachment)
|
||||
check(
|
||||
original["attempt"] == (3 if action == "transient" else 1), "retry budget not enforced"
|
||||
)
|
||||
self.client.call(
|
||||
"GET", "/api/v1/attachments/" + attachment["id"] + "/content", 409, actor=self.actor
|
||||
)
|
||||
response = operator("replay", attachment)
|
||||
check(response["replayed"], "replay rejected")
|
||||
self.settled(attachment)
|
||||
check(job(attachment)["job_id"] == original["job_id"], "replay replaced logical job")
|
||||
check(job(attachment)["attempt"] == original["attempt"] + 1, "attempt counter reset")
|
||||
before = manifest(attachment)
|
||||
check(not operator("replay", attachment)["replayed"], "successful job replayed")
|
||||
check(manifest(attachment) == before, "noop replay changed effect")
|
||||
|
||||
def backpressure(self):
|
||||
compose("stop", "worker", "dispatcher")
|
||||
output = io.BytesIO()
|
||||
Image.frombytes("RGB", (800, 600), os.urandom(800 * 600 * 3)).save(output, format="PNG")
|
||||
body = output.getvalue()
|
||||
samples = []
|
||||
sample_errors = []
|
||||
done = threading.Event()
|
||||
|
||||
def sample():
|
||||
while not done.is_set():
|
||||
try:
|
||||
value = compose(
|
||||
"stats", "--no-stream", "--format", "{{.Name}} {{.MemUsage}} {{.CPUPerc}}"
|
||||
)
|
||||
check(bool(value), "empty stats sample")
|
||||
samples.append(value)
|
||||
except Exception as error:
|
||||
sample_errors.append(type(error).__name__)
|
||||
return
|
||||
|
||||
sampler = threading.Thread(target=sample)
|
||||
sampler.start()
|
||||
try:
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
responses = list(
|
||||
pool.map(lambda _: self.upload(body, expected=[202, 503]), range(10))
|
||||
)
|
||||
accepted = [r for r in responses if "id" in r]
|
||||
check(len(accepted) == 6, "admission capacity not atomic across replicas")
|
||||
started = time.monotonic()
|
||||
compose("start", "dispatcher", "worker")
|
||||
latencies = []
|
||||
for attachment in accepted:
|
||||
wait_ready(self.client, self.actor, attachment, 90)
|
||||
latencies.append(time.monotonic() - started)
|
||||
finally:
|
||||
done.set()
|
||||
sampler.join()
|
||||
check(not sample_errors and samples, "memory sampling failed")
|
||||
check(any("worker" in value for value in samples), "worker RSS not sampled")
|
||||
summary = {
|
||||
"accepted": len(accepted),
|
||||
"rejected": 10 - len(accepted),
|
||||
"concurrency": 10,
|
||||
"image_bytes": len(body),
|
||||
"seconds_to_observed_ready": latencies,
|
||||
"stats_samples": samples,
|
||||
"method": "closed loop; sequential polls overestimate early completions",
|
||||
}
|
||||
Path("evidence/backpressure.json").write_text(json.dumps(summary, indent=2))
|
||||
print(
|
||||
"backpressure: 6 accepted, 4 rejected with 503, accepted jobs drained after recovery",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
experiment = Experiment()
|
||||
experiment.run_case("commit_publish_api_broker_restart", experiment.durability)
|
||||
experiment.run_case("publish_confirm_db_mark_crash", experiment.publisher_confirm_window)
|
||||
experiment.run_case("24_concurrent_duplicate_deliveries", experiment.duplicates)
|
||||
for point in ["before_effects", "after_effects", "after_commit", "before_ack"]:
|
||||
experiment.run_case("crash_" + point, lambda point=point: experiment.crash(point))
|
||||
experiment.run_case("expired_lease_fences_old_worker", experiment.lease_fencing)
|
||||
experiment.run_case("hard_process_timeout_recovery", experiment.timeout_recovery)
|
||||
experiment.run_case("new_version_then_stale_reordered_jobs", experiment.version_fencing)
|
||||
experiment.run_case(
|
||||
"permanent_failure_explicit_replay", lambda: experiment.failure_replay("permanent")
|
||||
)
|
||||
experiment.run_case(
|
||||
"bounded_retry_explicit_replay", lambda: experiment.failure_replay("transient")
|
||||
)
|
||||
experiment.run_case("two_replica_atomic_backpressure_recovery", experiment.backpressure)
|
||||
wait_for(
|
||||
lambda: sql(
|
||||
"select count(*) from attachments where status='READY' and staging_key IS NOT NULL;"
|
||||
)
|
||||
== "0",
|
||||
90,
|
||||
"ready staging not cleaned",
|
||||
)
|
||||
ids = ",".join("'" + value + "'" for value in experiment.accepted)
|
||||
missing = sql(
|
||||
"select count(*) from attachments a left join processing_jobs j on j.attachment_id=a.id and j.pipeline_version=a.pipeline_version left join processing_outbox o using(job_id) where a.id in ("
|
||||
+ ids
|
||||
+ ") and (j.job_id is null or o.job_id is null or a.status not in ('READY','FAILED') or j.status<>a.status);"
|
||||
)
|
||||
check(missing == "0", "confirmed task lost or not terminal")
|
||||
Path("evidence/accepted-jobs.json").write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"accepted_ids": experiment.accepted,
|
||||
"count": len(experiment.accepted),
|
||||
"missing_or_nonterminal": int(missing),
|
||||
},
|
||||
indent=2,
|
||||
)
|
||||
)
|
||||
print(
|
||||
"PASS staging cleaned after safe result publication; no confirmed job lost; all pipeline fault invariants",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,39 @@
|
||||
from client import Client, check, run
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
|
||||
def main():
|
||||
c = Client(base_url="http://127.0.0.1:18085", timeout=30)
|
||||
a, b, e, chat = c.bootstrap()
|
||||
body = Path("tests/fixtures/sample.png").read_bytes()
|
||||
path = "/api/v1/chats/" + chat["id"] + "/attachments?filename="
|
||||
for name in ["a" * 255, "\U0001f600" * 255]:
|
||||
attachment = c.call(
|
||||
"POST",
|
||||
path + quote(name),
|
||||
202,
|
||||
actor=a,
|
||||
raw=body,
|
||||
headers={"Content-Type": "image/png"},
|
||||
schema="Attachment",
|
||||
)["json"]
|
||||
check(attachment["filename"] == name, "filename changed")
|
||||
c.wait_ready(a, attachment)
|
||||
result = c.call("GET", "/api/v1/attachments/" + attachment["id"] + "/content", actor=b)
|
||||
check(result["bytes"] == body, "Unicode filename download failed")
|
||||
c.call(
|
||||
"POST",
|
||||
path + quote("\U0001f600" * 256),
|
||||
400,
|
||||
actor=a,
|
||||
raw=body,
|
||||
headers={"Content-Type": "image/png"},
|
||||
)
|
||||
print(
|
||||
"PASS filename code-point limits: 255 ASCII and 255 emoji -> 202 and download 200; 256 emoji -> 400; long Content-Disposition accepted by LB"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,53 @@
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import threading
|
||||
import uuid
|
||||
|
||||
from client import Client, check, run
|
||||
from pipeline_support import compose, ready_api, sql
|
||||
|
||||
|
||||
def main():
|
||||
ready_api()
|
||||
client = Client(base_url="http://127.0.0.1:18085", timeout=30)
|
||||
actor, _, _, chat = client.bootstrap()
|
||||
limit = int(compose("exec", "-T", "api", "printenv", "MAX_MESSAGES_PER_CHAT"))
|
||||
check(1 <= limit <= 10000, "unexpected test history capacity")
|
||||
sql(
|
||||
"insert into messages(id,chat_id,sender_id,text,created_at) "
|
||||
"select gen_random_uuid(),'" + chat["id"] + "','" + actor["id"] + "','seed',now() "
|
||||
"from generate_series(1," + str(limit - 1) + ");"
|
||||
)
|
||||
barrier = threading.Barrier(10)
|
||||
|
||||
def send(_):
|
||||
barrier.wait()
|
||||
return client.call(
|
||||
"POST",
|
||||
"/api/v1/chats/" + chat["id"] + "/messages",
|
||||
[201, 413],
|
||||
actor=actor,
|
||||
body={"text": "last slot", "attachment_ids": []},
|
||||
headers={"Idempotency-Key": uuid.uuid4().hex},
|
||||
)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
responses = list(pool.map(send, range(10)))
|
||||
instances = {item["headers"].get("X-Instance-Id") for item in responses}
|
||||
check(
|
||||
len(instances) == 2 and None not in instances,
|
||||
"last-slot race did not reach both API replicas",
|
||||
)
|
||||
confirmed = [item for item in responses if item["status"] == 201]
|
||||
rejected = [item for item in responses if item["status"] == 413]
|
||||
check(len(confirmed) == 1 and len(rejected) == 9, "history capacity raced across API replicas")
|
||||
check(
|
||||
int(sql("select count(*) from messages where chat_id='" + chat["id"] + "';")) == limit,
|
||||
"history capacity exceeded in DB",
|
||||
)
|
||||
print(
|
||||
"PASS history last-slot race: 10 simultaneous unique POSTs, exactly 1 committed and 9 rejected with 413; DB count equals configured limit"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,140 @@
|
||||
from client import Client, check, run
|
||||
from pipeline_support import compose, sql, broker, ready_api, wait_ready, wait_for, metadata, job
|
||||
import hashlib
|
||||
import json
|
||||
import uuid
|
||||
|
||||
|
||||
def execute(code, data=None):
|
||||
return compose("exec", "-T", "dispatcher", "python", "-c", code, data=data)
|
||||
|
||||
|
||||
def main():
|
||||
ready_api()
|
||||
c = Client(base_url="http://127.0.0.1:18085", timeout=30)
|
||||
a, b, e, chat = c.bootstrap()
|
||||
protected, original = c.attachment(a, chat)
|
||||
wait_ready(c, a, protected)
|
||||
key = sql("select object_key from attachments where id='" + protected["id"] + "';")
|
||||
status = compose(
|
||||
"exec",
|
||||
"-T",
|
||||
"minio",
|
||||
"curl",
|
||||
"-s",
|
||||
"-o",
|
||||
"/dev/null",
|
||||
"-w",
|
||||
"%{http_code}",
|
||||
"http://localhost:9000/messenger-attachments/" + key,
|
||||
)
|
||||
check(status == "403", "bucket permits anonymous access")
|
||||
print("PASS anonymous direct S3 GET of existing original returns 403", flush=True)
|
||||
compose("stop", "worker")
|
||||
attachment, _ = c.attachment(a, chat)
|
||||
code = r"""import hashlib,struct,zlib
|
||||
from pipeline.storage import Storage
|
||||
from pipeline.config import Settings
|
||||
from pipeline.repository import Repository
|
||||
s=Settings();storage=Storage(s);repo=Repository(s)
|
||||
def chunk(kind,data):return struct.pack('>I',len(data))+kind+data+struct.pack('>I',zlib.crc32(kind+data)&0xffffffff)
|
||||
compressor=zlib.compressobj();parts=[];row=b'\0'+b'\0'*(7000*3)
|
||||
for _ in range(7000):parts.append(compressor.compress(row))
|
||||
parts.append(compressor.flush())
|
||||
data=b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('>IIBBBBB',7000,7000,8,2,0,0,0))+chunk(b'IDAT',b''.join(parts))+chunk(b'IEND',b'')
|
||||
with repo.connection() as db:
|
||||
item=db.execute('select staging_key from attachments where id=%s',('ATTACHMENT',)).fetchone()
|
||||
storage.client.put_object(Bucket=s.bucket,Key=item['staging_key'],Body=data,ContentType='image/png')
|
||||
db.execute('update attachments set size_bytes=%s,checksum=%s where id=%s',(len(data),hashlib.sha256(data).hexdigest(),'ATTACHMENT'))
|
||||
print('injected 49-million-pixel complete PNG into trusted staging with matching metadata')
|
||||
""".replace(
|
||||
"ATTACHMENT", attachment["id"]
|
||||
)
|
||||
print(execute(code), flush=True)
|
||||
compose("start", "worker")
|
||||
wait_for(lambda: metadata(c, a, attachment)["status"] == "failed", 60)
|
||||
check(
|
||||
metadata(c, a, attachment)["error_code"] == "invalid_image",
|
||||
"worker pixel guard did not reject",
|
||||
)
|
||||
check(job(attachment)["attempt"] == 1, "permanent pixel error retried")
|
||||
check(
|
||||
sql(
|
||||
"select count(*) from attachment_variants where attachment_id='"
|
||||
+ attachment["id"]
|
||||
+ "';"
|
||||
)
|
||||
== "0",
|
||||
"invalid image published variants",
|
||||
)
|
||||
print(
|
||||
"PASS worker independently rejects >40 million pixels before full decode; FAILED on first attempt",
|
||||
flush=True,
|
||||
)
|
||||
sql(
|
||||
"update attachments set updated_at=now()-interval '2 days' where id='"
|
||||
+ attachment["id"]
|
||||
+ "';"
|
||||
)
|
||||
fresh = "staging/fresh-proof-" + uuid.uuid4().hex
|
||||
code = r"""from pipeline.storage import Storage
|
||||
from pipeline.repository import Repository
|
||||
from pipeline.cleanup import Cleanup
|
||||
from pipeline.config import Settings
|
||||
s=Settings();storage=Storage(s);repo=Repository(s)
|
||||
storage.client.put_object(Bucket=s.bucket,Key='FRESH',Body=b'fresh-proof')
|
||||
Cleanup(repo,storage).run()
|
||||
storage.client.head_object(Bucket=s.bucket,Key='FRESH')
|
||||
print('fresh orphan retained by grace')
|
||||
storage.client.delete_object(Bucket=s.bucket,Key='FRESH')
|
||||
""".replace(
|
||||
"FRESH", fresh
|
||||
)
|
||||
print(execute(code), flush=True)
|
||||
check(
|
||||
metadata(c, a, attachment)["error_code"] == "staging_expired",
|
||||
"expired failed staging retained",
|
||||
)
|
||||
check(
|
||||
sql("select staging_key IS NULL from attachments where id='" + attachment["id"] + "';")
|
||||
== "t",
|
||||
"staging reference retained",
|
||||
)
|
||||
command = [
|
||||
"docker",
|
||||
"compose",
|
||||
"-f",
|
||||
"docker-compose.yml",
|
||||
"-f",
|
||||
"compose.local.yaml",
|
||||
"-f",
|
||||
"compose.test.yaml",
|
||||
"exec",
|
||||
"-T",
|
||||
"dispatcher",
|
||||
"python",
|
||||
"-m",
|
||||
"pipeline.operator",
|
||||
"replay",
|
||||
attachment["id"],
|
||||
]
|
||||
import subprocess
|
||||
|
||||
response = subprocess.run(command, capture_output=True, text=True, timeout=30)
|
||||
check(
|
||||
response.returncode != 0 and "staging_expired" in response.stderr, "expired replay accepted"
|
||||
)
|
||||
check(metadata(c, a, attachment)["status"] == "failed", "unsafe replay changed status")
|
||||
check(
|
||||
c.call("GET", "/api/v1/attachments/" + protected["id"] + "/content", actor=b)["bytes"]
|
||||
== original,
|
||||
"cleanup deleted referenced original",
|
||||
)
|
||||
print(
|
||||
"PASS expired failed staging cleaned; unsafe replay refused; referenced ready bytes retained",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,171 @@
|
||||
import json
|
||||
import subprocess
|
||||
import time
|
||||
from client import Client, check
|
||||
|
||||
COMPOSE = [
|
||||
"docker",
|
||||
"compose",
|
||||
"-f",
|
||||
"docker-compose.yml",
|
||||
"-f",
|
||||
"compose.local.yaml",
|
||||
"-f",
|
||||
"compose.test.yaml",
|
||||
]
|
||||
|
||||
|
||||
def compose(*args, data=None):
|
||||
result = subprocess.run(
|
||||
COMPOSE + list(args), input=data, text=True, capture_output=True, timeout=120
|
||||
)
|
||||
check(result.returncode == 0, "Compose operator action failed: " + args[0])
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def sql(statement):
|
||||
return compose(
|
||||
"exec",
|
||||
"-T",
|
||||
"db",
|
||||
"sh",
|
||||
"-c",
|
||||
'psql -v ON_ERROR_STOP=1 -U "$(cat /run/secrets/postgres_user)" -d "$(cat /run/secrets/postgres_db)" -At',
|
||||
data=statement,
|
||||
)
|
||||
|
||||
|
||||
def broker(*args):
|
||||
return compose("exec", "-T", "broker", "redis-cli", *args)
|
||||
|
||||
|
||||
def wait_for(predicate, timeout=90, message="condition timed out"):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
if predicate():
|
||||
return
|
||||
time.sleep(0.25)
|
||||
raise AssertionError(message)
|
||||
|
||||
|
||||
def ready_api():
|
||||
observed = set()
|
||||
|
||||
def probe():
|
||||
try:
|
||||
states = compose("ps", "--format", "{{.Health}}", "api").splitlines()
|
||||
if len(states) != 2 or any(state != "healthy" for state in states):
|
||||
return False
|
||||
response = Client(base_url="http://127.0.0.1:18085").call(
|
||||
"GET", "/health/ready", schema="Health"
|
||||
)
|
||||
observed.add(response["headers"].get("X-Instance-Id"))
|
||||
return len(observed - {None}) == 2
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
wait_for(probe, 120, "API not ready")
|
||||
|
||||
|
||||
def metadata(client, actor, attachment):
|
||||
return client.call(
|
||||
"GET", "/api/v1/attachments/" + attachment["id"], actor=actor, schema="Attachment"
|
||||
)["json"]
|
||||
|
||||
|
||||
def wait_ready(client, actor, attachment, timeout=90):
|
||||
def probe():
|
||||
value = metadata(client, actor, attachment)
|
||||
check(value["status"] != "failed", "attachment failed")
|
||||
return value["status"] == "ready"
|
||||
|
||||
wait_for(probe, timeout, "attachment not ready")
|
||||
return metadata(client, actor, attachment)
|
||||
|
||||
|
||||
def job(attachment):
|
||||
text = sql(
|
||||
"select row_to_json(j) from processing_jobs j where attachment_id='"
|
||||
+ attachment["id"]
|
||||
+ "' order by pipeline_version desc limit 1;"
|
||||
)
|
||||
return json.loads(text)
|
||||
|
||||
|
||||
def payload(attachment, version=None):
|
||||
row = job(attachment)
|
||||
text = sql("select payload from processing_outbox where job_id='" + row["job_id"] + "';")
|
||||
value = json.loads(text)
|
||||
if version is not None:
|
||||
value["pipeline_version"] = version
|
||||
return value
|
||||
|
||||
|
||||
def inject_duplicate(value):
|
||||
return broker("XADD", "attachment-jobs", "*", "job", json.dumps(value))
|
||||
|
||||
|
||||
def fault(attachment, point, action, count=1):
|
||||
version = job(attachment)["pipeline_version"]
|
||||
sql(
|
||||
"INSERT INTO pipeline_faults(attachment_id,pipeline_version,point,action,remaining) VALUES ('"
|
||||
+ attachment["id"]
|
||||
+ "',"
|
||||
+ str(version)
|
||||
+ ",'"
|
||||
+ point
|
||||
+ "','"
|
||||
+ action
|
||||
+ "',"
|
||||
+ str(count)
|
||||
+ ");"
|
||||
)
|
||||
|
||||
|
||||
def fault_hit(attachment, point):
|
||||
return (
|
||||
sql(
|
||||
"select coalesce(sum(hits),0) from pipeline_faults where attachment_id='"
|
||||
+ attachment["id"]
|
||||
+ "' and point='"
|
||||
+ point
|
||||
+ "';"
|
||||
)
|
||||
!= "0"
|
||||
)
|
||||
|
||||
|
||||
def operator(action, attachment, version=2):
|
||||
text = compose(
|
||||
"exec",
|
||||
"-T",
|
||||
"dispatcher",
|
||||
"python",
|
||||
"-m",
|
||||
"pipeline.operator",
|
||||
action,
|
||||
attachment["id"],
|
||||
"--version",
|
||||
str(version),
|
||||
)
|
||||
return json.loads(text)
|
||||
|
||||
|
||||
def manifest(attachment):
|
||||
return sql(
|
||||
"select name,object_key,sha256 from attachment_variants where attachment_id='"
|
||||
+ attachment["id"]
|
||||
+ "' order by pipeline_version,name;"
|
||||
)
|
||||
|
||||
|
||||
def events(attachment, event):
|
||||
return int(
|
||||
sql(
|
||||
"select count(*) from pipeline_events e join processing_jobs j using(job_id) where j.attachment_id='"
|
||||
+ attachment["id"]
|
||||
+ "' and e.event='"
|
||||
+ event
|
||||
+ "';"
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,86 @@
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
from client import Client, check, run
|
||||
from pipeline_support import compose, ready_api, sql, wait_for, wait_ready
|
||||
|
||||
|
||||
def staging_keys():
|
||||
code = """import json
|
||||
from pipeline.config import Settings
|
||||
from pipeline.storage import Storage
|
||||
s=Storage(Settings())
|
||||
print(json.dumps([o['Key'] for p in s.client.get_paginator('list_objects_v2').paginate(Bucket=s.settings.bucket,Prefix='staging/') for o in p.get('Contents',[])]))
|
||||
"""
|
||||
return set(json.loads(compose("exec", "-T", "dispatcher", "python", "-c", code)))
|
||||
|
||||
|
||||
def main():
|
||||
ready_api()
|
||||
client = Client(base_url="http://127.0.0.1:18085", timeout=45)
|
||||
actor, _, _, chat = client.bootstrap()
|
||||
filename = "crash-" + uuid.uuid4().hex + ".png"
|
||||
before = staging_keys()
|
||||
sql(
|
||||
"create function proof_upload_crash() returns trigger language plpgsql as $$ begin "
|
||||
"if NEW.filename='"
|
||||
+ filename
|
||||
+ "' then perform pg_sleep(45); end if; return NEW; end; $$; "
|
||||
"create trigger proof_upload_crash before insert on attachments "
|
||||
"for each row execute function proof_upload_crash();"
|
||||
)
|
||||
try:
|
||||
with ThreadPoolExecutor(max_workers=1) as pool:
|
||||
request = pool.submit(
|
||||
client.call,
|
||||
"POST",
|
||||
"/api/v1/chats/" + chat["id"] + "/attachments?filename=" + filename,
|
||||
202,
|
||||
actor=actor,
|
||||
raw=Path("tests/fixtures/sample.png").read_bytes(),
|
||||
headers={"Content-Type": "image/png"},
|
||||
schema="Attachment",
|
||||
)
|
||||
wait_for(
|
||||
lambda: sql("select count(*) from pg_stat_activity where wait_event='PgSleep';")
|
||||
!= "0",
|
||||
15,
|
||||
"upload did not reach S3-before-COMMIT window",
|
||||
)
|
||||
orphan = staging_keys() - before
|
||||
check(len(orphan) == 1, "no staged source before attachment COMMIT")
|
||||
compose("kill", "-s", "SIGKILL", "api")
|
||||
try:
|
||||
request.result(timeout=20)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError("killed upload returned a confirmed attachment")
|
||||
check(
|
||||
sql("select count(*) from attachments where filename='" + filename + "';") == "0",
|
||||
"uncommitted attachment survived process death",
|
||||
)
|
||||
for key in orphan:
|
||||
check(
|
||||
sql("select count(*) from attachments where staging_key='" + key + "';") == "0",
|
||||
"orphan unexpectedly referenced",
|
||||
)
|
||||
finally:
|
||||
sql("drop trigger proof_upload_crash on attachments; drop function proof_upload_crash();")
|
||||
compose("start", "api")
|
||||
ready_api()
|
||||
attachment, body = client.attachment(actor, chat)
|
||||
wait_ready(client, actor, attachment)
|
||||
downloaded = client.call(
|
||||
"GET", "/api/v1/attachments/" + attachment["id"] + "/content", 200, actor=actor
|
||||
)
|
||||
check(downloaded["bytes"] == body, "upload after API recovery corrupted")
|
||||
print(
|
||||
"PASS SIGKILL after S3 PUT before DB COMMIT: no confirmed response, DB rolled back, staged orphan unreferenced; same session uploads after recovery"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,84 @@
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlencode
|
||||
from urllib.request import urlopen
|
||||
|
||||
from client import check
|
||||
|
||||
|
||||
GRAFANA = os.getenv("GRAFANA_URL", "http://127.0.0.1:13006")
|
||||
EVIDENCE = Path("evidence")
|
||||
|
||||
|
||||
def fetch(path, **params):
|
||||
suffix = "?" + urlencode(params) if params else ""
|
||||
with urlopen(GRAFANA + path + suffix, timeout=8) as response:
|
||||
return json.load(response)
|
||||
|
||||
|
||||
def datasource(name, path, **params):
|
||||
return fetch(f"/api/datasources/proxy/uid/{name}{path}", **params)
|
||||
|
||||
|
||||
def prom(expression):
|
||||
response = datasource("prometheus", "/api/v1/query", query=expression)
|
||||
check(response["status"] == "success", "PromQL query failed")
|
||||
return response["data"]["result"]
|
||||
|
||||
|
||||
def value(expression, default=0.0):
|
||||
values = prom(expression)
|
||||
return float(values[0]["value"][1]) if values else default
|
||||
|
||||
|
||||
def states():
|
||||
return {
|
||||
row["name"]: row["state"]
|
||||
for row in datasource("prometheus", "/api/v1/rules")["data"]["groups"][0]["rules"]
|
||||
}
|
||||
|
||||
|
||||
def logs(query, since=None, limit=100):
|
||||
result = datasource(
|
||||
"loki",
|
||||
"/loki/api/v1/query_range",
|
||||
query=query,
|
||||
start=int((since or time.time() - 180) * 1e9),
|
||||
limit=limit,
|
||||
)
|
||||
return result["data"]["result"]
|
||||
|
||||
|
||||
def spans(trace_id):
|
||||
trace = datasource("tempo", "/api/traces/" + trace_id)
|
||||
return [
|
||||
dict(
|
||||
span,
|
||||
service=next(
|
||||
a["value"]["stringValue"]
|
||||
for a in batch["resource"]["attributes"]
|
||||
if a["key"] == "service.name"
|
||||
),
|
||||
)
|
||||
for batch in trace.get("batches", trace.get("resourceSpans", []))
|
||||
for scope in batch["scopeSpans"]
|
||||
for span in scope["spans"]
|
||||
]
|
||||
|
||||
|
||||
def save(name, data):
|
||||
(EVIDENCE / name).write_text(
|
||||
json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
|
||||
)
|
||||
|
||||
|
||||
def wait_until(probe, timeout, description):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
result = probe()
|
||||
if result:
|
||||
return result
|
||||
time.sleep(1)
|
||||
raise AssertionError(description)
|
||||
Reference in New Issue
Block a user