Files
mtusi2026lab5/tests/pipeline_boundaries.py
2026-11-06 21:15:31 +03:00

134 lines
4.9 KiB
Python

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)