test(backend): share the integration timeout budget between shards

This commit is contained in:
shira committed 2026-10-10 18:05:44 +03:00
1 parent d8abaae85b
commit d6f960f8ae
4 files changed
+26 -3

No files matched your search

+12 -1
View File
@@ -10,6 +10,17 @@ import subprocess
import sys
from collections import defaultdict
# Time budget of the whole suite. CI runs it in two shards of ten minutes, so a
# shard gets its share of the budget and never less than ten minutes, and an
# unsharded local run gets the whole budget.
SUITE_TIMEOUT_MINUTES = 20
SHARD_TIMEOUT_FLOOR_MINUTES = 10
def go_timeout(total):
share = -(-SUITE_TIMEOUT_MINUTES // total)
return f"{max(SHARD_TIMEOUT_FLOOR_MINUTES, share)}m"
def shard_settings():
index = os.environ.get("TEST_SHARD_INDEX")
@@ -73,7 +84,7 @@ def run():
# Go splits -run at slashes. Anchoring only the parent keeps all its subtests.
pattern = "^(" + "|".join(re.escape(name) for name in names) + ")$"
subprocess.run([
*go, "test", "-tags=integration", "-count=1", "-timeout=10m",
*go, "test", "-tags=integration", "-count=1", "-timeout=" + go_timeout(total),
"-run=" + pattern, package,
], check=True)
+12
View File
@@ -114,6 +114,18 @@ class IntegrationSuiteTests(unittest.TestCase):
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(len(self.selected(calls)), 5)
def test_timeout_shares_the_suite_budget_between_shards(self):
cases = [(None, "20m"), ("1", "20m"), ("2", "10m"), ("3", "10m")]
for total, expected in cases:
with self.subTest(total=total):
settings = None if total is None else {"TEST_SHARD_INDEX": "1", "TEST_SHARD_TOTAL": total}
result, calls = self.run_suite(settings)
self.assertEqual(result.returncode, 0, result.stderr)
runs = [args for args in calls if any(arg.startswith("-run=") for arg in args)]
self.assertTrue(runs)
for args in runs:
self.assertIn("-timeout=" + expected, args)
def test_discovery_order_does_not_change_selection(self):
settings = {"TEST_SHARD_INDEX": "1", "TEST_SHARD_TOTAL": "2"}
result, calls = self.run_suite(settings)
+1 -1
View File
@@ -361,7 +361,7 @@ TEST_SHARD_INDEX=2 TEST_SHARD_TOTAL=2 make -C backend test-int
Indexes start at 1. Set both variables together; invalid settings, an empty suite, excess shards, and discovery failures fail the command. `test-int-list` compiles test packages and lists selected tests without starting containers. `make -C backend test-scripts` verifies for every shard count that each test runs in exactly one shard, that a shard listing matches the tests the shard runs, parent-test selection, and runner failure propagation. It is included in `make -C backend check`.
CI uses a separate matrix of two integration jobs with `GOFLAGS=-race` and `fail-fast: false`. Every shard must pass before aggregate and deployment smoke succeed. Run `GOFLAGS='-race -shuffle=on' make -C backend test-int` locally to check races and order independence. Shards use their own containers; runners do not share a database or a broker, so a Kafka test passes in whichever shard it lands. CI takes `TEST_SHARD_TOTAL` from the matrix size (`strategy.job-total`), so adding a shard index to the matrix is enough when suite duration warrants more runners; an index above the total fails the job.
CI uses a separate matrix of two integration jobs with `GOFLAGS=-race` and `fail-fast: false`. Every shard must pass before aggregate and deployment smoke succeed. Run `GOFLAGS='-race -shuffle=on' make -C backend test-int` locally to check races and order independence. Shards use their own containers; runners do not share a database or a broker, so a Kafka test passes in whichever shard it lands. CI takes `TEST_SHARD_TOTAL` from the matrix size (`strategy.job-total`), so adding a shard index to the matrix is enough when suite duration warrants more runners; an index above the total fails the job. The `go test` timeout shares a 20-minute budget of the whole suite between shards with a floor of 10 minutes: an unsharded local run gets 20 minutes, each of the two CI shards gets 10.
## Consent ledger tests
+1 -1
View File
@@ -361,7 +361,7 @@ TEST_SHARD_INDEX=2 TEST_SHARD_TOTAL=2 make -C backend test-int
Индексы начинаются с 1. Обе переменные задаются вместе; неверные параметры, пустой набор, лишние шарды и ошибки обнаружения завершают команду ошибкой. `test-int-list` компилирует тестовый пакет и выводит выбранные тесты без запуска контейнеров. `make -C backend test-scripts` проверяет для каждого числа шардов, что каждый тест выполняется ровно в одном шарде, что список шарда совпадает с тестами, которые шард запускает, выбор родительских тестов и передачу ошибок runner. Он входит в `make -C backend check`.
CI запускает отдельную matrix из двух integration jobs с `GOFLAGS=-race` и `fail-fast: false`. Результат всех шардов обязателен для aggregate и deployment smoke. `GOFLAGS='-race -shuffle=on' make -C backend test-int` позволяет локально проверить гонки и независимость порядка. Шарды используют свои контейнеры; общие БД и брокер между runner не создаются, поэтому тест Kafka проходит в любом шарде, куда он попал. CI берет `TEST_SHARD_TOTAL` из размера matrix (`strategy.job-total`), поэтому, когда длительность suite оправдывает дополнительные runner, достаточно добавить индекс шарда в matrix; индекс больше общего числа шардов завершает job ошибкой.
CI запускает отдельную matrix из двух integration jobs с `GOFLAGS=-race` и `fail-fast: false`. Результат всех шардов обязателен для aggregate и deployment smoke. `GOFLAGS='-race -shuffle=on' make -C backend test-int` позволяет локально проверить гонки и независимость порядка. Шарды используют свои контейнеры; общие БД и брокер между runner не создаются, поэтому тест Kafka проходит в любом шарде, куда он попал. CI берет `TEST_SHARD_TOTAL` из размера matrix (`strategy.job-total`), поэтому, когда длительность suite оправдывает дополнительные runner, достаточно добавить индекс шарда в matrix; индекс больше общего числа шардов завершает job ошибкой. Таймаут `go test` делит бюджет всего набора в 20 минут между шардами, но не меньше 10 минут на шард: локальный запуск без шардов получает 20 минут, каждый из двух шардов CI - по 10.
## Тесты журнала согласий