forked from mtusi2026/mtusi2026lab7
- restore a verified row by fact: three variants give ready, otherwise failed with a known code instead of ready without content - check trigger functions are not SECURITY DEFINER and pin search_path - record the working stand comparison, the permanent drill lock file and the remaining SeaweedFS details Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
558 lines
17 KiB
Python
558 lines
17 KiB
Python
"""Сверка и возврат заданий после инцидента (change `track1-worker-compromise`,
|
|
design, решение 8; спек `worker-compromise`, «Сохранность заданий»):
|
|
`infra/incident/*.sql` на временной базе. По испорченной строке каждого класса
|
|
и законные состояния: сверка называет ровно испорченные, возврат исправляет их
|
|
и не трогает законные, второй прогон — ноль."""
|
|
|
|
import subprocess
|
|
import uuid
|
|
from collections.abc import AsyncIterator
|
|
|
|
import asyncpg
|
|
import pytest
|
|
from incident_rows import (
|
|
INSERT_VARIANT_SQL,
|
|
VARIANTS,
|
|
add_attachment,
|
|
add_world,
|
|
connect_as,
|
|
variant_key,
|
|
)
|
|
|
|
from conftest import ROOT, admin, truncate_all
|
|
|
|
pytestmark = pytest.mark.anyio
|
|
|
|
INCIDENT_DIR = ROOT / "infra" / "incident"
|
|
CLASSES = (
|
|
"stuck_time",
|
|
"attempt_number",
|
|
"state_mismatch",
|
|
"false_success",
|
|
"future_updated_at",
|
|
"verified_damaged",
|
|
)
|
|
|
|
|
|
@pytest.fixture
|
|
async def connection() -> AsyncIterator[asyncpg.Connection]:
|
|
await truncate_all()
|
|
opened = await admin()
|
|
yield opened
|
|
await opened.close()
|
|
await truncate_all()
|
|
|
|
|
|
def _script(*names: str, stale_seconds: int = 300) -> str:
|
|
text = "".join(
|
|
(INCIDENT_DIR / name).read_text(encoding="utf-8") for name in names
|
|
)
|
|
# подстановка переменной psql
|
|
return text.replace(":stale_seconds", str(stale_seconds))
|
|
|
|
|
|
async def _found(
|
|
connection: asyncpg.Connection,
|
|
**options: int,
|
|
) -> dict[uuid.UUID, set[str]]:
|
|
"""Вложение → его классы; транзакция откатывается."""
|
|
transaction = connection.transaction()
|
|
await transaction.start()
|
|
try:
|
|
await connection.execute(_script("jobs_classes.sql", **options))
|
|
rows = await connection.fetch("SELECT * FROM incident")
|
|
finally:
|
|
await transaction.rollback()
|
|
return {
|
|
row["attachment_id"]: found
|
|
for row in rows
|
|
if (found := {name for name in CLASSES if row[name]})
|
|
}
|
|
|
|
|
|
async def _repair(connection: asyncpg.Connection) -> None:
|
|
async with connection.transaction():
|
|
await connection.execute(
|
|
_script("jobs_classes.sql", "jobs_repair.sql"),
|
|
)
|
|
|
|
|
|
async def _snapshot(
|
|
connection: asyncpg.Connection,
|
|
) -> list[tuple[object, ...]]:
|
|
rows = [
|
|
*await connection.fetch("SELECT * FROM attachments ORDER BY id"),
|
|
*await connection.fetch("SELECT * FROM attachment_jobs ORDER BY id"),
|
|
*await connection.fetch(
|
|
"SELECT * FROM attachment_variants ORDER BY attachment_id, "
|
|
"variant",
|
|
),
|
|
]
|
|
return [tuple(row) for row in rows]
|
|
|
|
|
|
async def _legal(
|
|
connection: asyncpg.Connection,
|
|
world: tuple[uuid.UUID, ...],
|
|
) -> None:
|
|
"""Законные состояния: каждое, которое пишут процессы."""
|
|
for spec in (
|
|
{"status": "pending"},
|
|
# старая версия: готовое без задания и без исходника
|
|
{"status": "ready", "staging": False},
|
|
{"status": "queued", "state": "queued", "published_at": "NULL"},
|
|
{"status": "queued", "state": "queued"},
|
|
# пауза перед повтором и пустой брокер: сроки истекут сами
|
|
{
|
|
"status": "queued",
|
|
"state": "queued",
|
|
"published_at": "NULL",
|
|
"next_attempt_at": "now() + interval '300 s'",
|
|
"attempt": "4",
|
|
},
|
|
{
|
|
"status": "queued",
|
|
"state": "queued",
|
|
"published_at": "now() - interval '3 days'",
|
|
},
|
|
{"status": "processing", "state": "processing"},
|
|
{
|
|
"status": "processing",
|
|
"state": "processing",
|
|
"lease_expires_at": "now() - interval '1 day'",
|
|
},
|
|
# исходник ждёт уборщика меньше срока
|
|
{
|
|
"status": "ready",
|
|
"state": "succeeded",
|
|
"variants": VARIANTS,
|
|
"age_seconds": 100,
|
|
},
|
|
{
|
|
"status": "ready",
|
|
"state": "succeeded",
|
|
"variants": VARIANTS,
|
|
"staging": False,
|
|
},
|
|
{"status": "failed", "state": "failed"},
|
|
{"status": "failed", "state": "failed", "staging": False},
|
|
# после replay: номер большой, бюджет свой
|
|
{
|
|
"status": "queued",
|
|
"state": "queued",
|
|
"attempt": "104",
|
|
"attempt_base": "100",
|
|
},
|
|
):
|
|
await add_attachment(connection, world, **spec)
|
|
|
|
|
|
# испорченная строка → её классы: одна на строку design, решение 8, и
|
|
# разновидности
|
|
DAMAGED: list[tuple[dict[str, object], set[str]]] = [
|
|
(
|
|
{
|
|
"status": "processing",
|
|
"state": "processing",
|
|
"lease_expires_at": "'2100-01-01'",
|
|
},
|
|
{"stuck_time"},
|
|
),
|
|
(
|
|
{
|
|
"status": "processing",
|
|
"state": "processing",
|
|
"lease_expires_at": "NULL",
|
|
},
|
|
{"stuck_time"},
|
|
),
|
|
(
|
|
{
|
|
"status": "queued",
|
|
"state": "queued",
|
|
"next_attempt_at": "'infinity'",
|
|
},
|
|
{"stuck_time"},
|
|
),
|
|
(
|
|
{
|
|
"status": "queued",
|
|
"state": "queued",
|
|
"published_at": "'2100-01-01'",
|
|
},
|
|
{"stuck_time"},
|
|
),
|
|
(
|
|
{"status": "queued", "state": "queued", "attempt": "2147483647"},
|
|
{"attempt_number"},
|
|
),
|
|
(
|
|
{
|
|
"status": "processing",
|
|
"state": "processing",
|
|
"attempt": "150",
|
|
},
|
|
{"attempt_number"},
|
|
),
|
|
(
|
|
{"status": "failed", "state": "failed", "attempt": "2147483647"},
|
|
{"attempt_number"},
|
|
),
|
|
({"status": "queued", "state": "succeeded"}, {"state_mismatch"}),
|
|
({"status": "queued", "state": "failed"}, {"state_mismatch"}),
|
|
({"status": "ready", "state": "queued"}, {"state_mismatch"}),
|
|
({"status": "failed", "state": "processing"}, {"state_mismatch"}),
|
|
({"status": "processing"}, {"state_mismatch"}),
|
|
({"status": "ready"}, {"state_mismatch"}),
|
|
(
|
|
{
|
|
"status": "ready",
|
|
"state": "succeeded",
|
|
"age_seconds": 10,
|
|
},
|
|
{"false_success"},
|
|
),
|
|
(
|
|
{
|
|
"status": "ready",
|
|
"state": "succeeded",
|
|
"variants": ("thumbnail",),
|
|
"age_seconds": 10,
|
|
},
|
|
{"false_success"},
|
|
),
|
|
(
|
|
{
|
|
"status": "ready",
|
|
"state": "succeeded",
|
|
"variants": VARIANTS,
|
|
"age_seconds": 3600,
|
|
},
|
|
{"false_success"},
|
|
),
|
|
(
|
|
{
|
|
"status": "queued",
|
|
"state": "queued",
|
|
"updated_at": "'2100-01-01'",
|
|
},
|
|
{"future_updated_at"},
|
|
),
|
|
(
|
|
{"status": "queued", "state": "queued", "staging": False},
|
|
{"verified_damaged"},
|
|
),
|
|
(
|
|
{
|
|
"status": "processing",
|
|
"state": "succeeded",
|
|
"staging": False,
|
|
"variants": VARIANTS,
|
|
},
|
|
{"verified_damaged"},
|
|
),
|
|
(
|
|
{
|
|
"status": "failed",
|
|
"state": "failed",
|
|
"staging": False,
|
|
"variants": VARIANTS,
|
|
},
|
|
{"verified_damaged"},
|
|
),
|
|
({"status": "queued", "staging": False}, {"verified_damaged"}),
|
|
]
|
|
|
|
|
|
async def test_legal_states_are_not_named(
|
|
connection: asyncpg.Connection,
|
|
) -> None:
|
|
world = await add_world(connection)
|
|
await _legal(connection, world)
|
|
assert await _found(connection) == {}
|
|
before = await _snapshot(connection)
|
|
await _repair(connection)
|
|
assert await _snapshot(connection) == before
|
|
|
|
|
|
async def test_every_class_named_and_repaired(
|
|
connection: asyncpg.Connection,
|
|
) -> None:
|
|
"""K из K: названо ровно испорченное, после возврата — ничего; законное
|
|
не изменено."""
|
|
world = await add_world(connection)
|
|
await _legal(connection, world)
|
|
legal = await _snapshot(connection)
|
|
expected: dict[uuid.UUID, set[str]] = {}
|
|
for spec, classes in DAMAGED:
|
|
row = await add_attachment(connection, world, **spec)
|
|
expected[row] = classes
|
|
assert set().union(*(item for _, item in DAMAGED)) == set(CLASSES)
|
|
# строка вложения в будущем: своя колонка
|
|
future = await add_attachment(
|
|
connection,
|
|
world,
|
|
status="ready",
|
|
state="succeeded",
|
|
variants=VARIANTS,
|
|
)
|
|
await connection.execute(
|
|
"UPDATE attachments SET updated_at = '2100-01-01' WHERE id = $1",
|
|
future,
|
|
)
|
|
expected[future] = {"future_updated_at", "false_success"}
|
|
|
|
assert await _found(connection) == expected
|
|
await _repair(connection)
|
|
assert await _found(connection) == {}
|
|
after = await _snapshot(connection)
|
|
assert set(map(repr, legal)) <= set(map(repr, after))
|
|
await _repair(connection)
|
|
assert await _snapshot(connection) == after
|
|
|
|
|
|
async def test_requeued_row_is_processable(
|
|
connection: asyncpg.Connection,
|
|
) -> None:
|
|
"""Возвращённое — намерение relay: queued без сроков и отметки, бюджет
|
|
новый, номер не уменьшен, строк вариантов нет; сверенное — готовое."""
|
|
world = await add_world(connection)
|
|
requeued = await add_attachment(
|
|
connection,
|
|
world,
|
|
status="ready",
|
|
state="succeeded",
|
|
variants=VARIANTS,
|
|
attempt="3",
|
|
attempt_base="1",
|
|
)
|
|
restored = await add_attachment(
|
|
connection,
|
|
world,
|
|
status="failed",
|
|
state="failed",
|
|
staging=False,
|
|
variants=VARIANTS,
|
|
)
|
|
await _repair(connection)
|
|
row = await connection.fetchrow(
|
|
"SELECT a.status, a.error_code, j.state, j.attempt, j.attempt_base, "
|
|
"j.published_at, j.next_attempt_at, j.lease_expires_at, "
|
|
"j.finished_at, (SELECT count(*) FROM attachment_variants v WHERE "
|
|
"v.attachment_id = a.id) AS variants FROM attachments a JOIN "
|
|
"attachment_jobs j ON j.attachment_id = a.id WHERE a.id = $1",
|
|
requeued,
|
|
)
|
|
assert tuple(row) == (
|
|
"queued",
|
|
None,
|
|
"queued",
|
|
3,
|
|
3,
|
|
None,
|
|
None,
|
|
None,
|
|
None,
|
|
0,
|
|
)
|
|
row = await connection.fetchrow(
|
|
"SELECT a.status, a.error_code, j.state, (SELECT count(*) FROM "
|
|
"attachment_variants v WHERE v.attachment_id = a.id) FROM "
|
|
"attachments a JOIN attachment_jobs j ON j.attachment_id = a.id "
|
|
"WHERE a.id = $1",
|
|
restored,
|
|
)
|
|
assert tuple(row) == ("ready", None, "succeeded", 3)
|
|
|
|
|
|
async def _result(
|
|
connection: asyncpg.Connection,
|
|
attachment: uuid.UUID,
|
|
) -> tuple[object, ...]:
|
|
row = await connection.fetchrow(
|
|
"SELECT a.status, a.error_code, j.state, (SELECT count(*) FROM "
|
|
"attachment_variants v WHERE v.attachment_id = a.id) FROM "
|
|
"attachments a LEFT JOIN attachment_jobs j ON j.attachment_id = a.id "
|
|
"WHERE a.id = $1",
|
|
attachment,
|
|
)
|
|
return tuple(row)
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("start", "variants", "expected"),
|
|
[
|
|
(
|
|
("failed", "failed", ()),
|
|
(),
|
|
("failed", "processing_failed", "failed", 0),
|
|
),
|
|
# строка варианта своим ключом — право worker, результата нет
|
|
(
|
|
("failed", "failed", ()),
|
|
("thumbnail",),
|
|
("failed", "processing_failed", "failed", 0),
|
|
),
|
|
(
|
|
("ready", "succeeded", VARIANTS),
|
|
(),
|
|
("ready", None, "succeeded", 3),
|
|
),
|
|
],
|
|
)
|
|
async def test_verified_restored_by_fact(
|
|
connection: asyncpg.Connection,
|
|
start: tuple[str, str, tuple[str, ...]],
|
|
variants: tuple[str, ...],
|
|
expected: tuple[object, ...],
|
|
) -> None:
|
|
"""Сверенное уборщиком: законный `failed` после срока хранения (исходник,
|
|
оригинал и варианты убраны) и сверенное готовое. Роль worker возвращает
|
|
его в `queued` — сверка называет порчу сверенного, возврат
|
|
восстанавливает по факту: три варианта — готовое, иначе снова `failed` с
|
|
известным кодом, а не `ready` без содержимого (verify W1)."""
|
|
status, state, legal_variants = start
|
|
world = await add_world(connection)
|
|
row = await add_attachment(
|
|
connection,
|
|
world,
|
|
status=status,
|
|
state=state,
|
|
staging=False,
|
|
variants=legal_variants,
|
|
)
|
|
worker = await connect_as("worker")
|
|
try:
|
|
await worker.execute(
|
|
"UPDATE attachments SET status = 'queued', error_code = NULL "
|
|
"WHERE id = $1",
|
|
row,
|
|
)
|
|
await worker.execute(
|
|
"UPDATE attachment_jobs SET state = 'queued' "
|
|
"WHERE attachment_id = $1",
|
|
row,
|
|
)
|
|
for name in variants:
|
|
await worker.execute(
|
|
INSERT_VARIANT_SQL,
|
|
row,
|
|
name,
|
|
variant_key(row, name),
|
|
)
|
|
finally:
|
|
await worker.close()
|
|
assert await _found(connection) == {row: {"verified_damaged"}}
|
|
await _repair(connection)
|
|
assert await _result(connection, row) == expected
|
|
assert await _found(connection) == {}
|
|
after = await _snapshot(connection)
|
|
await _repair(connection)
|
|
assert await _snapshot(connection) == after
|
|
|
|
|
|
async def test_job_created_for_accepted_without_job(
|
|
connection: asyncpg.Connection,
|
|
) -> None:
|
|
world = await add_world(connection)
|
|
row = await add_attachment(connection, world, status="ready")
|
|
await _repair(connection)
|
|
job = await connection.fetchrow(
|
|
"SELECT state, attempt, pipeline_version FROM attachment_jobs "
|
|
"WHERE attachment_id = $1",
|
|
row,
|
|
)
|
|
assert tuple(job) == ("queued", 0, 1)
|
|
|
|
|
|
async def test_stale_threshold_is_a_parameter(
|
|
connection: asyncpg.Connection,
|
|
) -> None:
|
|
world = await add_world(connection)
|
|
row = await add_attachment(
|
|
connection,
|
|
world,
|
|
status="ready",
|
|
state="succeeded",
|
|
variants=VARIANTS,
|
|
age_seconds=60,
|
|
)
|
|
assert await _found(connection) == {}
|
|
assert await _found(connection, stale_seconds=10) == {
|
|
row: {"false_success"},
|
|
}
|
|
|
|
|
|
async def test_audit_output(connection: asyncpg.Connection) -> None:
|
|
"""Строки, которые разбирает `jobs.sh`: каждый класс — и нулевой."""
|
|
world = await add_world(connection)
|
|
await add_attachment(connection, world, status="failed", state="failed")
|
|
await add_attachment(
|
|
connection,
|
|
world,
|
|
status="queued",
|
|
state="queued",
|
|
attempt="2147483647",
|
|
published_at="'2100-01-01'",
|
|
)
|
|
statements = [
|
|
item.strip()
|
|
for item in _script("jobs_audit.sql").split(";\n")
|
|
if item.strip()
|
|
]
|
|
async with connection.transaction():
|
|
await connection.execute(_script("jobs_classes.sql"))
|
|
lines = [
|
|
row[0]
|
|
for statement in statements
|
|
for row in await connection.fetch(statement)
|
|
]
|
|
assert lines == [
|
|
"class stuck_time 1",
|
|
"class attempt_number 1",
|
|
"class state_mismatch 0",
|
|
"class false_success 0",
|
|
"class future_updated_at 0",
|
|
"class verified_damaged 0",
|
|
"info failed_with_source 1",
|
|
"info ready_without_variants 0",
|
|
"damaged 1",
|
|
]
|
|
|
|
|
|
async def test_audit_changes_nothing(connection: asyncpg.Connection) -> None:
|
|
world = await add_world(connection)
|
|
for spec, _ in DAMAGED:
|
|
await add_attachment(connection, world, **spec)
|
|
before = await _snapshot(connection)
|
|
async with connection.transaction():
|
|
await connection.execute(
|
|
_script("jobs_classes.sql", "jobs_audit.sql"),
|
|
)
|
|
assert await _snapshot(connection) == before
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("args", "env"),
|
|
[
|
|
(("fix",), {}),
|
|
(("audit",), {"STALE_SECONDS": "5; DROP TABLE x"}),
|
|
# пустое — умолчание; стенда нет — тоже 2
|
|
(("audit",), {"STALE_SECONDS": ""}),
|
|
],
|
|
)
|
|
def test_script_refuses_bad_arguments(
|
|
args: tuple[str, ...],
|
|
env: dict[str, str],
|
|
) -> None:
|
|
"""Код 2 до обращения к стенду (docker в PATH нет)."""
|
|
result = subprocess.run(
|
|
["/bin/sh", str(INCIDENT_DIR / "jobs.sh"), *args],
|
|
env={"PATH": "/bin:/usr/bin", **env},
|
|
capture_output=True,
|
|
text=True,
|
|
check=False,
|
|
)
|
|
assert result.returncode == 2
|
|
assert result.stdout == ""
|