final
This commit is contained in:
@@ -55,3 +55,52 @@ make test-security BASE_URL=https://localhost:8443 CA_FILE=/absolute/path/to/ca.
|
||||
## Что ещё остаётся доказать
|
||||
|
||||
Smoke не доказывает persistence, число реальных контейнеров, durability брокера, outbox, отсутствие утечек/уязвимостей, полноту telemetry или выполнение уровня 4/5. Конкурентные/нагрузочные/негативные проверки своего решения добавляйте отдельно. Список защиты текущей лабы находится в README.md. Проверки рассчитаны на localhost-стенд, не на production.
|
||||
|
||||
## Дополнительные проверки реализации lab5
|
||||
|
||||
Windows: команды из корня, Python launcher `py`. Для дополнительных сценариев нужен Pillow (`py -m pip install Pillow==12.0.0`), для JSON Schema job — jsonschema. Публичные smoke/resilience используют только stdlib и не менялись.
|
||||
|
||||
```powershell
|
||||
pwsh -File scripts/bootstrap.ps1
|
||||
docker compose -f docker-compose.yml -f compose.local.yaml -f compose.test.yaml up -d --build
|
||||
$env:BASE_URL='http://127.0.0.1:18085'
|
||||
py tests/smoke.py
|
||||
py tests/pipeline_core.py
|
||||
py tests/pipeline_faults.py
|
||||
py tests/pipeline_retention.py
|
||||
```
|
||||
|
||||
`compose.local.yaml` меняет только внешний порт на 18085 из-за резервирования 8080 Windows. `compose.test.yaml` включает закрытые операторские fault points, retry budget=3, lease=8s, timeout=25s, pending limit=6. Ранний lease намеренно создаёт ситуацию ещё живого старого worker. Количество API всегда 2.
|
||||
|
||||
- pipeline_core: queued snapshot при остановленных workers, 409 до готовности, сообщение с queued attachment, original/thumbnail/crop/WebP, EXIF/alpha/без увеличения, MIME/corrupt/oversize/filename/ACL, 24 конкурентных повтора через 2 API.
|
||||
- pipeline_faults: crash publisher до/после publish, API и broker restart при остановленном worker, 24 дубля, worker crash до/после effects/COMMIT/ack, expired lease со старым живым worker, hard timeout, новая версия раньше старой доставки, постоянная/временная ошибка, failed registry и операторский replay/noop. В конце 10 параллельных upload → 6 accepted/4 unavailable, затем drain, RSS/CPU samples и ledger всех 202.
|
||||
- pipeline_retention: отдельная операторская инъекция полного PNG 49 млн пикселей в staging с согласованными checksum/size (API штатно такой файл отвергает). Worker должен ограничить декодирование. Затем искусственно состаренный FAILED источник очищается, replay после retention отклоняется, свежий orphan и используемый READY original сохраняются.
|
||||
|
||||
Запускайте эти сценарии последовательно на изолированном стенде. Они останавливают реальные сервисы и добавляют синтетические данные. Fault injection в обычной конфигурации выключен, HTTP управляющих endpoints нет. После проверок: `docker compose -f docker-compose.yml -f compose.local.yaml up -d` возвращает production-настройки. Volumes не удалять.
|
||||
|
||||
Операторские команды (через существующий dispatcher контейнер):
|
||||
|
||||
```powershell
|
||||
docker compose exec -T dispatcher python -m pipeline.operator replay ATTACHMENT_UUID
|
||||
docker compose exec -T dispatcher python -m pipeline.operator upgrade ATTACHMENT_UUID --version 2
|
||||
```
|
||||
|
||||
Сохранность/failover: `py tests/resilience.py --mode persistence --action-script scripts/restart.cmd` и `py tests/resilience.py --mode failover --action-script scripts/stop-one.cmd`. После failover восстановить `docker compose -f docker-compose.yml -f compose.local.yaml up -d api`. Windows restart hook сохраняет StartedAt до/после всех хранилищ/процессов; stop hook записывает остановленную API. Linux `.sh` — эквивалентные действия, перед запуском `chmod +x`.
|
||||
|
||||
`py tests/pipeline_boundaries.py` проверяет межоперационные окна настоящими блокировками: задержка Message INSERT удерживает FOR SHARE на Attachment и запрещает параллельный перевод в FAILED до COMMIT; затем FAILED → POST Message 409. Отдельный holder exclusive cleanup lock блокирует content до освобождения; байты совпадают, shared lock после ответа освобождён. Запускать отдельно, без других инъекций.
|
||||
|
||||
`py tests/pipeline_ack_guard.py` (test profile): после S3 writes worker задерживается, dispatcher останавливается до lease recovery. Проверяется, что истёкший worker не публикует READY и не удаляет pending delivery / publication index. После запуска dispatcher та же job заканчивается на попытке 2 с одним manifest и четырьмя S3 result-объектами.
|
||||
|
||||
`py scripts/capture_evidence.py` сохраняет whitelisted параметры контейнеров, проверку persisted outbox templates по jobs.schema.json, сводку дискретных RSS/CPU samples, JUnit и SHA-256 исходников. `.env`, secrets и сырой docker inspect в доказательства не записываются.
|
||||
|
||||
`py tests/pipeline_filename.py`: границы filename 255 ASCII / 255 emoji / 256 emoji и скачивание через LB с длинным Content-Disposition.
|
||||
|
||||
`py tests/pipeline_upload_crash.py` останавливает обе API через SIGKILL в подтверждённом окне между S3 PUT и INSERT/COMMIT Attachment. Проверяет отсутствие 202 и записи БД, unreferenced staging и успешный upload с прежней сессией после запуска API. SQL trigger удаляется в finally; staged orphan остаётся для штатного cleanup после grace.
|
||||
|
||||
`py tests/pipeline_history_capacity.py`: создаёт отдельный синтетический чат, заполняет историю до limit−1 через SQL, одновременно отправляет десять разных POST. Ожидаются один 201, девять 413 и ровно limit строк в БД. Строка чата блокируется до COMMIT, поэтому проверка COUNT и запись сериализованы между API-репликами. Данные проверки остаются в учебном volume.
|
||||
|
||||
Полный воспроизводимый прогон: `py -m pip install -r requirements-tools.txt`, затем `pwsh -File scripts/run_tests.ps1` при доступном JDK 21. Он последовательно запускает все исполняемые lab5-сценарии в этой папке, оба режима resilience, 30 секунд load, Java-тесты, OpenAPI и проверки стиля. `client.py`, `image_probe.py`, `pipeline_support.py` — вспомогательные модули, используемые сценариями. Общий журнал — `evidence/test-suite.txt`; профиль со сбоями включается только на время экспериментов, обычная конфигурация восстанавливается в finally.
|
||||
|
||||
Стиль собственной реализации: Java AOSP через google-java-format 1.28.0 (JAR проверяется по SHA-256), Python Black 25.9.0. Проверка: `py scripts/style.py`; исправление форматирования: `py scripts/style.py --apply`. Публичные Python-тесты и контракты задания не форматируются. Java API-интерфейсы содержат Javadoc и HTTP-аннотации. Контроллеры используют `@RequiredArgsConstructor`, final-зависимость и один вызов сервиса на операцию; эти правила проверяет style.py. Контроллер скачивания получает от сервиса готовый ResponseEntity с вычисленными заголовками.
|
||||
|
||||
Начальная схема находится только в `src/main/resources/db/migration/V1__init.sql`. `py scripts/check_migration.py` создаёт временную БД, применяет V1 и сравнивает схему с текущим стендом без истории Flyway; временная БД удаляется в finally. Результаты — `evidence/migration-check.txt` и `migration-check.json`. Для уже применённых на этом локальном стенде V1–V4 выполнено отдельное согласование истории через Flyway repair после сравнения схем, с сохранением данных; детали и доказательства в REPORT.md. Обычный запуск на новой БД не требует repair и выполняет одну V1.
|
||||
|
||||
@@ -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)
|
||||
Reference in New Issue
Block a user