feat: limit accepted attachment work and add queue overload bench
Reject uploads with 429 at [uploads] max_unfinished_jobs, counted by the existing partial indexes in the membership block. Add the bench_queue profile, hypotheses H1-H9 and the fifth failure-stand API. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -6155,3 +6155,319 @@ def test_defense_faults(
|
||||
crash_relay_after_confirm(api, stand, alice, chat)
|
||||
replay_returns_work(api, stand, alice, chat)
|
||||
replay_ready_refused(api, stand, alice, chat)
|
||||
|
||||
|
||||
# Предел незавершённых заданий (design change `track1-queue-overload`, решение
|
||||
# 13). Работает пятый API стенда: у прочих предел выключен, и они копят задания,
|
||||
# пока worker стоит у чужих проверок.
|
||||
BACKLOG_ENV = dict(
|
||||
item.split("=", 1)
|
||||
for item in os.environ.get("FAULT_BACKLOG_ENV", "").split()
|
||||
)
|
||||
BACKLOG_LIMIT = int(BACKLOG_ENV.get("UPLOADS__MAX_UNFINISHED_JOBS", "3"))
|
||||
EXPECTED_BACKLOG_ENV = {"UPLOADS__MAX_UNFINISHED_JOBS": "3"}
|
||||
BACKLOG_RETRY_AFTER_S = "5"
|
||||
# обе остальные проверки загрузки на пределе — без тела и без места: быстрее
|
||||
BACKLOG_REJECT_MAX_S = 1
|
||||
# прежние проверки могли оставить задание на следующую попытку или аренду
|
||||
UNFINISHED_WAIT_S = 120
|
||||
# загрузки в полёте реплики: настройки по умолчанию `[uploads]` пятого API
|
||||
BACKLOG_IN_FLIGHT = 4 + 16
|
||||
BACKLOG_CLIENTS = 40
|
||||
|
||||
|
||||
def assert_backlog_stand() -> None:
|
||||
"""Без малого предела пятого API тесты предела ничего не доказывают."""
|
||||
assert BACKLOG_ENV == EXPECTED_BACKLOG_ENV, (
|
||||
f"backlog stand started with {BACKLOG_ENV}, "
|
||||
f"expected {EXPECTED_BACKLOG_ENV}"
|
||||
)
|
||||
|
||||
|
||||
def unfinished_jobs(stand: Stand) -> int:
|
||||
return int(stand("unfinished-jobs"))
|
||||
|
||||
|
||||
def wait_no_unfinished(
|
||||
stand: Stand,
|
||||
*,
|
||||
timeout: float = UNFINISHED_WAIT_S,
|
||||
) -> None:
|
||||
"""Незавершённых заданий нет: worker и relay работают."""
|
||||
deadline = time.monotonic() + timeout
|
||||
while True:
|
||||
count = unfinished_jobs(stand)
|
||||
if count == 0:
|
||||
return
|
||||
assert time.monotonic() < deadline, f"{count} unfinished jobs left"
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def assert_backlog_rejected(resp: httpx.Response, elapsed: float) -> None:
|
||||
assert_error(resp, 429)
|
||||
assert resp.headers["Retry-After"] == BACKLOG_RETRY_AFTER_S
|
||||
assert elapsed < BACKLOG_REJECT_MAX_S, f"429 after {elapsed:.2f}s"
|
||||
|
||||
|
||||
def backlog_records(stand: Stand) -> list[dict[str, Any]]:
|
||||
return [
|
||||
json.loads(line)
|
||||
for line in stand("backlog-api-log").splitlines()
|
||||
if line.startswith("{")
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.spec("queue-overload", "Предел достигнут")
|
||||
@pytest.mark.spec("queue-overload", "Порядок проверок у предела")
|
||||
@pytest.mark.spec("queue-overload", "Остальной API у предела")
|
||||
@pytest.mark.spec("queue-overload", "Загрузки снова принимаются")
|
||||
def test_backlog_limit(
|
||||
backlog_api: Api,
|
||||
stand: Stand,
|
||||
alice: Actor,
|
||||
eve: Actor,
|
||||
chat: dict[str, Any],
|
||||
) -> None:
|
||||
assert_backlog_stand()
|
||||
data = images.sample_png()
|
||||
finished = backlog_api.upload_ready(alice, chat["id"], data)
|
||||
wait_no_unfinished(stand)
|
||||
# 30 MiB, которые начинаются как PNG: Content-Length 31 457 280
|
||||
big = images.PNG_SIGNATURE + bytes(
|
||||
3 * images.MAX_BYTES - len(images.PNG_SIGNATURE),
|
||||
)
|
||||
with worker_stopped(stand):
|
||||
accepted = [
|
||||
backlog_api.upload(alice, chat["id"], data)
|
||||
for _ in range(BACKLOG_LIMIT)
|
||||
]
|
||||
assert unfinished_jobs(stand) == BACKLOG_LIMIT
|
||||
rows, objects = objects_and_rows(stand)
|
||||
resp, elapsed = timed(
|
||||
lambda: upload_raw(backlog_api, alice, chat, data),
|
||||
)
|
||||
assert_backlog_rejected(resp, elapsed)
|
||||
assert resp.headers["X-Request-Id"]
|
||||
assert resp.headers["X-Instance-Id"]
|
||||
after_rows, after_objects = objects_and_rows(stand)
|
||||
assert not new_ids(rows, after_rows)
|
||||
assert not after_objects - objects
|
||||
assert unfinished_jobs(stand) == BACKLOG_LIMIT
|
||||
|
||||
# порядок проверок: сначала дешёвые, и они раньше предела
|
||||
assert_error(upload_raw(backlog_api, eve, chat, data), 404)
|
||||
too_big = upload_raw(backlog_api, alice, chat, big)
|
||||
assert_error(too_big, 413)
|
||||
assert too_big.request.headers["Content-Length"] == "31457280"
|
||||
assert_error(
|
||||
upload_raw(
|
||||
backlog_api,
|
||||
alice,
|
||||
chat,
|
||||
data,
|
||||
content_type="text/plain",
|
||||
),
|
||||
415,
|
||||
)
|
||||
|
||||
# остальной API у предела
|
||||
backlog_api.send_message(alice, chat["id"], "text at the limit")
|
||||
assert_ok(
|
||||
backlog_api.messages_page(alice, chat["id"]),
|
||||
200,
|
||||
"MessagePage",
|
||||
)
|
||||
assert (
|
||||
backlog_api.attachment_meta(alice, finished["id"]).status_code
|
||||
== 200
|
||||
)
|
||||
assert_content(
|
||||
backlog_api.attachment_content(alice, finished["id"]),
|
||||
data,
|
||||
"image/png",
|
||||
)
|
||||
backlog_api.send_message(
|
||||
alice,
|
||||
chat["id"],
|
||||
"",
|
||||
attachment_ids=[accepted[0]["id"]],
|
||||
)
|
||||
ready = backlog_api.request("GET", "/health/ready")
|
||||
assert ready.status_code == 200, describe(ready)
|
||||
|
||||
wait_no_unfinished(stand)
|
||||
more = backlog_api.upload(alice, chat["id"], data)
|
||||
for attachment in (*accepted, more):
|
||||
backlog_api.wait_attachment(
|
||||
alice,
|
||||
attachment["id"],
|
||||
timeout=JOB_WAIT_S,
|
||||
)
|
||||
|
||||
records = backlog_records(stand)
|
||||
started = next(r for r in records if r.get("event") == "Started API")
|
||||
assert started["uploads_max_unfinished_jobs"] == BACKLOG_LIMIT
|
||||
rejected = [
|
||||
record
|
||||
for record in records
|
||||
if record.get("event") == "Rejected attachment"
|
||||
and record.get("reason") == "backlog"
|
||||
]
|
||||
assert rejected, "no backlog rejection in the replica log"
|
||||
assert rejected[-1]["limit"] == BACKLOG_LIMIT
|
||||
assert rejected[-1]["unfinished"] >= BACKLOG_LIMIT
|
||||
|
||||
|
||||
@pytest.mark.spec("queue-overload", "Завершённые задания не считаются")
|
||||
def test_backlog_ignores_finished(
|
||||
backlog_api: Api,
|
||||
stand: Stand,
|
||||
alice: Actor,
|
||||
chat: dict[str, Any],
|
||||
) -> None:
|
||||
assert_backlog_stand()
|
||||
wait_no_unfinished(stand)
|
||||
data = images.sample_png()
|
||||
undecodable = images.jpeg_precision_12()
|
||||
for _ in range(BACKLOG_LIMIT):
|
||||
backlog_api.upload_ready(alice, chat["id"], data)
|
||||
for _ in range(BACKLOG_LIMIT):
|
||||
failed = backlog_api.upload(
|
||||
alice,
|
||||
chat["id"],
|
||||
undecodable,
|
||||
content_type="image/jpeg",
|
||||
)
|
||||
backlog_api.wait_attachment(
|
||||
alice,
|
||||
failed["id"],
|
||||
status="failed",
|
||||
timeout=JOB_WAIT_S,
|
||||
)
|
||||
wait_no_unfinished(stand)
|
||||
accepted = backlog_api.upload(alice, chat["id"], data)
|
||||
backlog_api.wait_attachment(alice, accepted["id"], timeout=JOB_WAIT_S)
|
||||
|
||||
|
||||
@pytest.mark.spec("queue-overload", "Ожидание следующей попытки считается")
|
||||
def test_backlog_counts_waiting_retry(
|
||||
backlog_api: Api,
|
||||
stand: Stand,
|
||||
alice: Actor,
|
||||
chat: dict[str, Any],
|
||||
) -> None:
|
||||
assert_backlog_stand()
|
||||
wait_no_unfinished(stand)
|
||||
data = images.sample_png()
|
||||
with worker_stopped(stand), relay_stopped(stand):
|
||||
accepted = [
|
||||
backlog_api.upload(alice, chat["id"], data)
|
||||
for _ in range(BACKLOG_LIMIT)
|
||||
]
|
||||
# срок следующей попытки далеко: задание ждёт, а не работает
|
||||
stand("set-next-attempt", accepted[0]["id"], "600")
|
||||
job = job_row(stand, accepted[0]["id"])
|
||||
assert job is not None and job["state"] == "queued", job
|
||||
assert job["next_attempt_at"] is not None, job
|
||||
resp, elapsed = timed(
|
||||
lambda: upload_raw(backlog_api, alice, chat, data),
|
||||
)
|
||||
assert_backlog_rejected(resp, elapsed)
|
||||
stand("set-next-attempt", accepted[0]["id"], "0")
|
||||
for attachment in accepted:
|
||||
backlog_api.wait_attachment(
|
||||
alice,
|
||||
attachment["id"],
|
||||
timeout=JOB_WAIT_S,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.spec("queue-overload", "Предел при остановленных брокере и relay")
|
||||
def test_backlog_without_broker(
|
||||
backlog_api: Api,
|
||||
stand: Stand,
|
||||
alice: Actor,
|
||||
chat: dict[str, Any],
|
||||
) -> None:
|
||||
assert_backlog_stand()
|
||||
wait_no_unfinished(stand)
|
||||
data = images.sample_png()
|
||||
accepted = []
|
||||
with (
|
||||
worker_stopped(stand),
|
||||
relay_stopped(stand),
|
||||
outage(stand, "stop", "rabbitmq"),
|
||||
):
|
||||
for _ in range(BACKLOG_LIMIT):
|
||||
resp, elapsed = timed(
|
||||
lambda: upload_raw(backlog_api, alice, chat, data),
|
||||
)
|
||||
accepted.append(assert_accepted(resp))
|
||||
assert elapsed < BACKLOG_REJECT_MAX_S, f"202 after {elapsed:.2f}s"
|
||||
resp, elapsed = timed(
|
||||
lambda: upload_raw(backlog_api, alice, chat, data),
|
||||
)
|
||||
assert_backlog_rejected(resp, elapsed)
|
||||
for attachment in accepted:
|
||||
backlog_api.wait_attachment(
|
||||
alice,
|
||||
attachment["id"],
|
||||
timeout=JOB_WAIT_S,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.spec("queue-overload", "Превышение ограничено")
|
||||
def test_backlog_overshoot_bounded(
|
||||
backlog_api: Api,
|
||||
stand: Stand,
|
||||
alice: Actor,
|
||||
chat: dict[str, Any],
|
||||
) -> None:
|
||||
assert_backlog_stand()
|
||||
wait_no_unfinished(stand)
|
||||
base_url = str(backlog_api.client.base_url)
|
||||
data = images.sample_png()
|
||||
barrier = threading.Barrier(BACKLOG_CLIENTS)
|
||||
|
||||
def upload_at_once(_: int) -> httpx.Response:
|
||||
with Api(base_url, timeout=THREAD_CLIENT_TIMEOUT_S) as client:
|
||||
barrier.wait(timeout=30)
|
||||
return upload_raw(client, alice, chat, data)
|
||||
|
||||
with worker_stopped(stand), ThreadPoolExecutor(BACKLOG_CLIENTS) as pool:
|
||||
answers = list(pool.map(upload_at_once, range(BACKLOG_CLIENTS)))
|
||||
accepted = [resp.json() for resp in answers if resp.status_code == 202]
|
||||
statuses = sorted({resp.status_code for resp in answers})
|
||||
assert set(statuses) <= {202, 429}, statuses
|
||||
assert (
|
||||
BACKLOG_LIMIT <= len(accepted) <= BACKLOG_LIMIT + BACKLOG_IN_FLIGHT
|
||||
), f"accepted {len(accepted)}, statuses {statuses}"
|
||||
for resp in answers:
|
||||
if resp.status_code == 429:
|
||||
assert_error(resp, 429)
|
||||
for attachment in accepted:
|
||||
backlog_api.wait_attachment(
|
||||
alice,
|
||||
attachment["id"],
|
||||
timeout=JOB_WAIT_S,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.spec("queue-overload", "Предел выключен")
|
||||
def test_backlog_off(
|
||||
api: Api,
|
||||
stand: Stand,
|
||||
alice: Actor,
|
||||
chat: dict[str, Any],
|
||||
) -> None:
|
||||
assert_backlog_stand()
|
||||
wait_no_unfinished(stand)
|
||||
data = images.sample_png()
|
||||
with worker_stopped(stand):
|
||||
accepted = [
|
||||
api.upload(alice, chat["id"], data)
|
||||
for _ in range(BACKLOG_LIMIT + 2)
|
||||
]
|
||||
assert unfinished_jobs(stand) == BACKLOG_LIMIT + 2
|
||||
for attachment in accepted:
|
||||
api.wait_attachment(alice, attachment["id"], timeout=JOB_WAIT_S)
|
||||
|
||||
Reference in New Issue
Block a user