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)