"""Остановка именно своего стенда; запуск: make test-pipeline-failures""" import hashlib import json import os import time import uuid from subprocess import CalledProcessError import pytest from helpers import ( auth, compose, message_headers, png_bytes, psql, upload_raw, wait_attachment, ) pytestmark = pytest.mark.skipif( os.getenv("RUN_PIPELINE_FAILURE_TESTS") != "1", reason="явные остановки/инъекции: make test-pipeline-failures", ) def wait_for(check, timeout=60): deadline = time.monotonic() + timeout while time.monotonic() < deadline: try: value = check() except CalledProcessError: value = False if value: return value time.sleep(0.2) raise AssertionError("Состояние не достигнуто вовремя") def wait_queue_empty(): wait_for( lambda: "attachments.process.v1\t0" in compose( "exec", "-T", "broker", "rabbitmqctl", "list_queues", "name", "messages" ) ) def job_row(attachment_id): return json.loads( psql(f"""SELECT row_to_json(r) FROM ( SELECT j.id, j.attempt, j.failures, j.lease_until, a.status, a.staging_key, (SELECT count(*) FROM attachment_variants WHERE attachment_id = a.id) AS variants FROM attachment_jobs j JOIN attachments a ON a.id = j.attachment_id WHERE a.id = '{attachment_id}') r;""") ) def accept(api, alice, chat, content=None): response = upload_raw( api, alice, chat["id"], content if content is not None else png_bytes(320, 200) ) assert response.status_code == 202, response.text assert response.json()["status"] == "queued" return response.json() def test_commit_publish_gap_worker_down_and_broker_volume(api, make_user, make_chat): alice = make_user("handoff") chat = make_chat(alice, [alice]) compose("stop", "dispatcher", "worker") try: content = png_bytes(320, 200) attachment = accept(api, alice, chat, content) row = job_row(attachment["id"]) assert row["status"] == "queued" and row["staging_key"] assert ( psql( f"SELECT count(*) FROM attachment_outbox WHERE job_id = '{row['id']}' AND published_at IS NULL;" ) == "1" ) linked = api.post( f"/api/v1/chats/{chat['id']}/messages", json={"text": "", "attachment_ids": [attachment["id"]]}, headers=message_headers(alice), ) assert linked.status_code == 201 assert ( api.get( f"/api/v1/attachments/{attachment['id']}/content", headers=auth(alice) ).status_code == 409 ) compose("restart", "api") # COMMIT уже был; publish ещё не было. wait_for(lambda: api.get("/health/ready").status_code == 200) compose("start", "dispatcher") wait_for( lambda: psql( f"SELECT count(*) FROM attachment_outbox WHERE job_id = '{row['id']}' AND published_at IS NOT NULL;" ) == "1" ) compose("restart", "broker") wait_for( lambda: "attachments.process.v1\t1" in compose( "exec", "-T", "broker", "rabbitmqctl", "list_queues", "name", "messages_ready", ) ) compose("start", "worker") ready = wait_attachment(api, alice, attachment["id"]) assert len(ready["variants"]) == 3 assert ( api.get( f"/api/v1/attachments/{attachment['id']}/content", headers=auth(alice) ).content == content ) print( "HANDOFF: COMMIT -> API restart -> publish -> broker restart with volume -> ready", attachment["id"], ) finally: compose("start", "dispatcher", "worker") @pytest.mark.parametrize("point", ["after-objects", "after-result"]) def test_crash_before_ack_does_not_duplicate_effect(api, make_user, make_chat, point): alice = make_user("crash") chat = make_chat(alice, [alice]) compose("exec", "-T", "worker", "touch", f"/tmp/lab5-crash-{point}") try: attachment = accept(api, alice, chat) if point == "after-objects": wait_for(lambda: job_row(attachment["id"])["status"] == "processing") # Реальный SIG-exit без COMMIT; ждём штатный lease (90 с), не меняя его. ready = wait_attachment(api, alice, attachment["id"], timeout=120) row = job_row(attachment["id"]) assert row["attempt"] == 2 and row["failures"] == 1 else: ready = wait_attachment(api, alice, attachment["id"]) row = job_row(attachment["id"]) assert row["attempt"] == 1 assert row["variants"] == 3 before = ready # Явный дубль уже завершённой job: публикация через тот же adapter с confirm. compose( "exec", "-T", "dispatcher", "python", "-c", f''' import asyncio, sys sys.path.insert(0, 'src') from infrastructure import database_pool_manager as db from infrastructure.broker import RabbitBrokerManager from config.settings import BROKER_URL_FILE from domain.jobs import JobMessageSchema async def main(): await db.create_pool(30) async with db.acquire() as conn: r = await conn.fetchrow("SELECT id AS job_id, attachment_id, pipeline_version, attempt, created_at FROM attachment_jobs WHERE id = $1::uuid", "{row["id"]}") b = RabbitBrokerManager(BROKER_URL_FILE, 2) await b.publish(JobMessageSchema(**dict(r))) await b.close() await db.close() asyncio.run(main()) ''', ) wait_queue_empty() # Проверяем фактический ack, а не только статус в БД. for variant in ready["variants"]: response = api.get( f"/api/v1/attachments/{attachment['id']}/content", params={"variant": variant["name"]}, headers=auth(alice), ) assert response.status_code == 200 assert hashlib.sha256(response.content).hexdigest() == variant["sha256"] assert wait_attachment(api, alice, attachment["id"]) == before assert job_row(attachment["id"])["variants"] == 3 print( "CRASH/REDELIVERY:", point, "attempt", row["attempt"], "variants=3", attachment["id"], ) finally: compose("exec", "-T", "worker", "rm", "-f", f"/tmp/lab5-crash-{point}") compose("start", "worker") def test_retry_exhaustion_and_safe_operator_replay(api, make_user, make_chat): alice = make_user("retry") chat = make_chat(alice, [alice]) compose("stop", "worker") name = "lab5_fault_" + uuid.uuid4().hex attachment = accept(api, alice, chat) row = job_row(attachment["id"]) psql(f"""CREATE FUNCTION {name}() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.id = '{attachment["id"]}' AND NEW.status = 'ready' THEN RAISE EXCEPTION 'injected commit failure'; END IF; RETURN NEW; END; $$; CREATE TRIGGER {name} BEFORE UPDATE ON attachments FOR EACH ROW EXECUTE FUNCTION {name}();""") try: compose("start", "worker") failed = wait_attachment( api, alice, attachment["id"], terminal="failed", timeout=90 ) assert failed["error_code"] == "retry_exhausted" row = job_row(attachment["id"]) assert row["attempt"] == row["failures"] == 5 and row["variants"] == 0 times = json.loads( psql( f"SELECT json_agg(available_at ORDER BY attempt) FROM attachment_outbox WHERE job_id = '{row['id']}';" ) ) from datetime import datetime deltas = [ (datetime.fromisoformat(b) - datetime.fromisoformat(a)).total_seconds() for a, b in zip(times, times[1:]) ] assert len(deltas) == 4 assert all(delay >= 2**index for index, delay in enumerate(deltas)) psql(f"DROP TRIGGER {name} ON attachments; DROP FUNCTION {name}();") result = compose( "exec", "-T", "dispatcher", "python", "src/jobs.py", "replay", "--job-id", row["id"], "--operator", "lab-test", "--reason", "fault removed", ) assert "queued:" in result ready = wait_attachment(api, alice, attachment["id"]) assert len(ready["variants"]) == 3 again = compose( "exec", "-T", "dispatcher", "python", "src/jobs.py", "replay", "--job-id", row["id"], "--operator", "lab-test", "--reason", "duplicate replay", ) assert "no-op:" in again assert ( psql( f"SELECT count(*) FROM attachment_replays WHERE job_id = '{row['id']}';" ) == "1" ) print( "RETRY: attempts=5, backoff seconds", deltas, "failed -> audited replay -> ready; ready replay no-op", ) finally: psql( f"DROP TRIGGER IF EXISTS {name} ON attachments; DROP FUNCTION IF EXISTS {name}();" ) compose("start", "worker") def test_publisher_crash_after_confirm_recovers_outbox(api, make_user, make_chat): alice = make_user("confirm") chat = make_chat(alice, [alice]) compose("exec", "-T", "dispatcher", "touch", "/tmp/lab5-crash-after-publish") try: attachment = accept(api, alice, chat) ready = wait_attachment(api, alice, attachment["id"]) row = job_row(attachment["id"]) wait_for( lambda: psql( f"SELECT count(*) FROM attachment_outbox WHERE job_id = '{row['id']}' AND published_at IS NOT NULL;" ) == "1", timeout=30, ) wait_queue_empty() assert len(ready["variants"]) == 3 and row["attempt"] == 1 print( "CONFIRM GAP: confirmed publish -> crash -> outbox lease -> duplicate no-op", attachment["id"], ) finally: compose("exec", "-T", "dispatcher", "rm", "-f", "/tmp/lab5-crash-after-publish") compose("start", "dispatcher") def test_staging_cleanup_retention_and_replay_guard(api, make_user, make_chat, upload): from subprocess import CalledProcessError from test_pipeline import broken_idat alice = make_user("retention") chat = make_chat(alice, [alice]) ready = upload(alice, chat) failed = accept(api, alice, chat, broken_idat()) wait_attachment(api, alice, failed["id"], terminal="failed") failed_job = job_row(failed["id"]) compose("stop", "worker") try: active = accept(api, alice, chat) psql( f"UPDATE attachments SET created_at = clock_timestamp() - interval '2 days' WHERE id = '{active['id']}';" ) psql( f"UPDATE attachments SET updated_at = clock_timestamp() - interval '2 days' WHERE id = '{failed['id']}';" ) compose("exec", "-T", "janitor", "python", "src/janitor.py", "--once") assert job_row(ready["id"])["staging_key"] is None assert job_row(failed["id"])["staging_key"] is None assert job_row(active["id"])["staging_key"] is not None assert job_row(active["id"])["status"] == "queued" with pytest.raises(CalledProcessError): compose( "exec", "-T", "dispatcher", "python", "src/jobs.py", "replay", "--job-id", failed_job["id"], "--operator", "lab-test", "--reason", "expired source", ) assert ( api.get( f"/api/v1/attachments/{ready['id']}/content", headers=auth(alice) ).status_code == 200 ) compose("start", "worker") wait_attachment(api, alice, active["id"]) print( "CLEANUP: ready staging removed; expired failed retired; active queued preserved; expired replay rejected" ) finally: compose("start", "worker") def test_worker_process_has_effective_memory_limit(): result = compose( "exec", "-T", "worker", "python", "-c", """ import subprocess, sys, tempfile from pathlib import Path from PIL import Image with tempfile.TemporaryDirectory() as directory: root = Path(directory) source = root / 'source.png' with Image.new('1', (8000, 5000)) as image: image.save(source) result = subprocess.run([sys.executable, 'src/infrastructure/media/image_transform.py', str(source), str(root), '40000000', '128', '30'], capture_output=True, text=True) assert result.returncode == 2, (result.returncode, result.stderr) assert result.stdout.strip() == 'image_resource_limit', result.stdout print('Linux RLIMIT_AS=128MiB: decoder refused 40Mpx without killing worker') """, ) assert "decoder refused" in result print(result.strip())