"""Конкурентные границы retirement/replay на настоящем PostgreSQL""" from subprocess import CalledProcessError from helpers import compose, psql, upload_raw, wait_attachment from test_pipeline import broken_idat def checked_compose(*args): try: return compose(*args) except CalledProcessError as error: raise AssertionError(error.stderr) from None def test_replay_waiting_for_cleanup_rechecks_retired_source(api, make_user, make_chat): alice = make_user("replay_race") chat = make_chat(alice, [alice]) response = upload_raw(api, alice, chat["id"], broken_idat()) assert response.status_code == 202 attachment = wait_attachment(api, alice, response.json()["id"], terminal="failed") job_id = psql( f"SELECT id FROM attachment_jobs WHERE attachment_id = '{attachment['id']}';" ) # Удерживаем lock job, запускаем replay и дожидаемся его реального ожидания # в pg_stat_activity. Затем retirement меняет только attachment и коммитит. result = checked_compose( "exec", "-T", "dispatcher", "python", "-c", f""" import asyncio, sys from uuid import UUID sys.path.insert(0, 'src') from infrastructure import database_pool_manager as db from infrastructure.dependencies.jobs import create_job_repository from domain.errors import ConflictError async def main(): await db.create_pool(30) job_id = UUID('{job_id}') task = None try: async with db.acquire() as conn: async with conn.transaction(): await conn.fetchval('SELECT id FROM attachment_jobs WHERE id = $1 FOR UPDATE', job_id) pid = await conn.fetchval('SELECT pg_backend_pid()') task = asyncio.create_task(create_job_repository().replay(job_id, 'race-test', 'concurrent retirement')) for _ in range(200): blocked = await conn.fetchval('SELECT EXISTS(SELECT 1 FROM pg_stat_activity WHERE $1 = ANY(pg_blocking_pids(pid)))', pid) if blocked: break await asyncio.sleep(0.01) else: raise AssertionError('replay did not wait for the job lock') await conn.execute('UPDATE attachments SET staging_key = NULL WHERE id = $1', UUID('{attachment["id"]}')) try: changed = await task except ConflictError: pass else: raise AssertionError(f'replay accepted retired source: changed={{changed}}') print('PASS: replay rechecks attachment after waiting; retired source rejected') finally: if task is not None and not task.done(): task.cancel() await asyncio.gather(task, return_exceptions=True) # Оставляем только эту синтетическую запись в терминальном состоянии # и при обнаружении регрессии, не допуская processing без исходника. async with db.acquire() as conn, conn.transaction(): await conn.fetchval('SELECT id FROM attachment_jobs WHERE id = $1 FOR UPDATE', job_id) await conn.execute('UPDATE attachment_jobs SET lease_token = NULL, lease_until = NULL WHERE id = $1', job_id) await conn.execute("UPDATE attachments SET status = 'failed', staging_key = NULL, error_code = 'invalid_image' WHERE id = $1", UUID('{attachment["id"]}')) await db.close() asyncio.run(main()) """, ) assert "retired source rejected" in result