diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 81be609..07de5e0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -101,7 +101,7 @@ jobs: run: make -C backend test-race integration: - name: Integration tests (${{ matrix.shard }}/2) + name: Integration tests (${{ matrix.shard }}/${{ strategy.job-total }}) runs-on: ubuntu-24.04 timeout-minutes: 30 strategy: @@ -121,10 +121,12 @@ jobs: cache-dependency-path: backend/go.sum - name: Install Go dependencies run: make -C backend deps + # The shard total comes from the matrix size, so adding a shard cannot + # leave TEST_SHARD_TOTAL stale; an index outside the total fails the run. - name: Run PostgreSQL, Redis, SeaweedFS, and Kafka integration shard env: TEST_SHARD_INDEX: ${{ matrix.shard }} - TEST_SHARD_TOTAL: "2" + TEST_SHARD_TOTAL: ${{ strategy.job-total }} GOFLAGS: -race run: make -C backend test-int @@ -316,6 +318,55 @@ jobs: - name: Build and check technical health routes run: make -C deploy smoke + e2e: + name: Browser E2E + needs: + - backend + - frontend + - infrastructure + runs-on: ubuntu-24.04 + timeout-minutes: 45 + steps: + - name: Check out source + uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0 + with: + persist-credentials: false + - name: Set up Node.js + uses: actions/setup-node@2028fbc5c25fe9cf00d9f06a71cc4710d4507903 # v6.0.0 + with: + node-version-file: frontend/.node-version + - name: Install declared pnpm + run: npm install --global "$(node -p "require('./frontend/package.json').packageManager")" + - name: Cache pnpm store + uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 + with: + path: ~/.local/share/pnpm/store + key: ${{ runner.os }}-pnpm-${{ hashFiles('frontend/pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-pnpm- + # The runner mounts the installed @playwright/test into the browser image. + - name: Install frontend dependencies + run: make -C frontend install + # deploy/scripts/e2e.sh generates its own throwaway env file with random + # secrets outside the workspace and starts a fresh, uniquely named stand, + # so the job needs no repository secrets and no root .env. + - name: Run the Playwright suite on an isolated stand + run: make -C deploy test-e2e + # Only the Playwright report, failed-test traces and screenshots, and the + # stand logs are uploaded; the generated env file never enters this tree. + - name: Upload E2E diagnostics + if: ${{ failure() }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: e2e-diagnostics-attempt-${{ github.run_attempt }} + path: | + frontend/test-results/e2e/report/ + frontend/test-results/e2e/results/ + frontend/test-results/e2e/stand.log + if-no-files-found: warn + include-hidden-files: false + retention-days: 14 + aggregate: name: Required CI result if: always() @@ -328,35 +379,24 @@ jobs: - codegen - infrastructure - smoke + - e2e - security - security-images runs-on: ubuntu-24.04 + timeout-minutes: 5 steps: + # Every job in needs must report success. failure, cancelled, and + # skipped (for example after a failed dependency) all fail this result, + # and a job added to needs is checked without a separate line here. - name: Require every CI job to pass env: - API_RESULT: ${{ needs.api.result }} - BACKEND_RESULT: ${{ needs.backend.result }} - INTEGRATION_RESULT: ${{ needs.integration.result }} - FRONTEND_RESULT: ${{ needs.frontend.result }} - ML_RESULT: ${{ needs.ml.result }} - CODEGEN_RESULT: ${{ needs.codegen.result }} - INFRASTRUCTURE_RESULT: ${{ needs.infrastructure.result }} - SMOKE_RESULT: ${{ needs.smoke.result }} - SECURITY_RESULT: ${{ needs.security.result }} - SECURITY_IMAGES_RESULT: ${{ needs.security-images.result }} + NEEDS_JSON: ${{ toJSON(needs) }} run: | - printf 'api=%s backend=%s frontend=%s ml=%s codegen=%s infrastructure=%s smoke=%s\n' \ - "$API_RESULT" "$BACKEND_RESULT" "$FRONTEND_RESULT" "$ML_RESULT" \ - "$CODEGEN_RESULT" "$INFRASTRUCTURE_RESULT" "$SMOKE_RESULT" - test "$API_RESULT" = success - test "$BACKEND_RESULT" = success - printf 'integration=%s\n' "$INTEGRATION_RESULT" - test "$INTEGRATION_RESULT" = success - test "$FRONTEND_RESULT" = success - test "$ML_RESULT" = success - test "$CODEGEN_RESULT" = success - test "$INFRASTRUCTURE_RESULT" = success - test "$SMOKE_RESULT" = success - printf 'security=%s security-images=%s\n' "$SECURITY_RESULT" "$SECURITY_IMAGES_RESULT" - test "$SECURITY_RESULT" = success - test "$SECURITY_IMAGES_RESULT" = success + set -euo pipefail + jq -r 'to_entries[] | "\(.key)=\(.value.result)"' <<<"$NEEDS_JSON" + test "$(jq 'length' <<<"$NEEDS_JSON")" -gt 0 + failed=$(jq -r '[to_entries[] | select(.value.result != "success") | .key] | join(" ")' <<<"$NEEDS_JSON") + if [ -n "$failed" ]; then + printf 'Required jobs did not succeed: %s\n' "$failed" >&2 + exit 1 + fi diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index cb25b9b..5dfa36c 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -40,6 +40,7 @@ jobs: needs: - docs runs-on: ubuntu-24.04 + timeout-minutes: 5 steps: - name: Require documentation checks to pass env: diff --git a/deploy/Makefile b/deploy/Makefile index eb15b7f..1bb8f1c 100644 --- a/deploy/Makefile +++ b/deploy/Makefile @@ -14,7 +14,7 @@ MONITORING_FILE := $(ROOT)/deploy/docker/docker-compose.monitoring.yml E2E_FILE := $(ROOT)/deploy/docker/docker-compose.e2e.yml PLAYWRIGHT_VERSION := $(shell sed -n 's/^ *"@playwright\/test": "\([^"]*\)",\{0,1\}$$/\1/p' "$(ROOT)/frontend/package.json") -.PHONY: help config build up down logs monitoring-config monitoring-up monitoring-down monitoring-logs ml-config ml-build ml-up ml-down ml-logs check smoke test-e2e +.PHONY: help config build up down logs monitoring-config monitoring-up monitoring-down monitoring-logs ml-config ml-build ml-up ml-down ml-logs check check-workflows smoke test-e2e help: ## Show deployment commands @awk 'BEGIN {FS = ":.*## "} /^[a-zA-Z0-9_-]+:.*## / {printf "%-18s %s\n", $$1, $$2}' $(MAKEFILE_LIST) @@ -76,7 +76,10 @@ ml-logs: ## Follow ML service logs @test -f "$(ENV_FILE)" || { printf 'Missing %s.\n' "$(ENV_FILE)" >&2; exit 2; } APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" $(DOCKER) compose --env-file "$(ENV_FILE)" -p "$(ML_PROJECT)" -f "$(ML_FILE)" logs -f -check: config ## Validate all Compose files without starting services +check: config check-workflows ## Validate Compose files and CI workflow aggregates without starting services + +check-workflows: ## Check that each workflow aggregate job requires every other job + PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s "$(ROOT)/scripts" -p 'test_workflow_aggregate.py' smoke: ## Start an isolated stack and check infrastructure health routes @bash scripts/smoke.sh diff --git a/docs/en/DEPLOY.md b/docs/en/DEPLOY.md index 7c082bb..0f90ad2 100644 --- a/docs/en/DEPLOY.md +++ b/docs/en/DEPLOY.md @@ -196,4 +196,4 @@ The five checked-in dashboard JSON files are maintained as project dashboards: G The local monitoring stack is a single-node development/demo setup and provides no HA. Compose validation does not establish production retention, off-host backups, public access control, alert delivery, or core application behavior. -Workflow files exist in .github/workflows/. Their presence does not mean they have run on GitHub. See the testing guide for the difference between configuration validation, an infrastructure smoke, and product-flow tests. +Workflow files exist in .github/workflows/. Their presence does not mean they have run on GitHub. Branch protection should require two checks: `Required CI result` from ci.yml and `Required documentation result` from docs.yml. See the testing guide for the difference between configuration validation, an infrastructure smoke, and product-flow tests. diff --git a/docs/en/DEVELOPMENT.md b/docs/en/DEVELOPMENT.md index eb34637..444d3cd 100644 --- a/docs/en/DEVELOPMENT.md +++ b/docs/en/DEVELOPMENT.md @@ -54,7 +54,7 @@ What exists now: - OpenAPI contracts api/core/ and api/ml/ with schema merge, bundles, lint, and generation for Go (ogen), TypeScript (Orval), and Python (datamodel-code-generator). The SPA has an interface scaffold with placeholder screens, a generated API client, and MSW handlers. - Compose projects: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`), and monitoring (`docker-compose.monitoring.yml`). - Kafka: one KRaft node in the core Compose project with an internal-only listener, a named volume, a health check, and a memory limit. The backend runs the outbox relay, which creates the `lincodex.domain.events` topic and publishes committed outbox events to it through a franz-go producer; see [Outbox relay](#outbox-relay). Readiness does not check Kafka, and nothing consumes the events yet. -- CI jobs in .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix of two shards), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke`, and the required `aggregate` result. See [TESTING.md](TESTING.md) for sharding. +- CI jobs in .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix of two shards), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke`, `e2e` (Playwright suite on an isolated stand), and the required `aggregate` result, which fails when any of them fails, is cancelled, or is skipped. See [TESTING.md](TESTING.md) for sharding and the browser suite. - Observability: Prometheus, Loki, Alloy, Grafana with provisioned datasources and dashboards, and PostgreSQL, Redis, and node exporters. The React app does not send telemetry yet. Not implemented yet: registration and login (their contract is declared; the operations answer 501 or 401), consents, profiles, the questionnaire and assessment, the company cabinet, needs and matching, invitations and contacts, the Resend and SMTP transports and mail delivery, event consumers, notifications, support, and an end-to-end business suite. backend/db/migrations/ contains the outbox table with its relay index, the identity storage tables (`users`, `email_tokens`, `sessions`), and the `policy_versions` table and no other business schema; no product rule reads the policy yet; registration, verification, and session behavior on top of that storage comes in later tasks, product usecase and adapter directories other than the password hashing and policy pieces contain only placeholders, and `make -C deploy test-e2e` runs only a technical Playwright smoke of the SPA, API health, and error routes on a throwaway stack, not a business flow (see [TESTING.md](TESTING.md#browser-e2e-suite)). The target design is in [ARCHITECTURE.md](ARCHITECTURE.md). diff --git a/docs/en/TESTING.md b/docs/en/TESTING.md index e25ce2e..c14aff4 100644 --- a/docs/en/TESTING.md +++ b/docs/en/TESTING.md @@ -25,6 +25,7 @@ Useful focused commands: | make -C ml check | Ruff, mypy, pytest, and wheel build | | make -C ml check-generated | Pydantic models match the ML bundle without rewriting files | | make -C deploy config | Render Compose configurations without starting them | +| make -C deploy check | Render Compose configurations and run `check-workflows`, which fails when a workflow `aggregate` job does not need every other job or lacks `if: always()` | | make -C deploy smoke | Isolated technical smoke of service health routes | | make -C deploy test-e2e | Playwright browser suite against an isolated throwaway stack | | make -C observability check | Validate Prometheus, Loki, Alloy, and dashboard JSON | @@ -57,7 +58,7 @@ Artifacts of the last run are in `frontend/test-results/e2e/`, which Git ignores The current suite (`frontend/e2e/smoke.spec.ts`) checks that the SPA serves `/` with `lang="ru"` and its heading, that `/status` shows the technical page with a live API, that `/api/v1/healthz` returns 200 `{"status":"ok"}` through the frontend proxy, that an unknown SPA route shows the not-found page, and that `/api/v1/missing` returns 404 `application/problem+json` with code `not_found`. It needs no data. Later business tests create their own synthetic users and records through the public API in the fresh stack of each run; they do not use shared fixtures or real data. -The suite does not cover candidate or employer workflows, sign-in, mail delivery, dependency failures (deployment smoke covers those), browsers other than desktop Chromium, layout, or accessibility. CI does not run it yet. +The suite does not cover candidate or employer workflows, sign-in, mail delivery, dependency failures (deployment smoke covers those), browsers other than desktop Chromium, layout, or accessibility. CI runs the suite in the `e2e` job after `backend`, `frontend`, and `infrastructure` pass: `make -C frontend install`, then `make -C deploy test-e2e`. The job needs no repository secrets or root `.env`; each run uses its own generated env file and fresh stand. On failure CI uploads the `e2e-diagnostics-attempt-` artifact with `report/`, `results/` (traces and screenshots), and `stand.log` for 14 days. Hidden files and the env file are not uploaded. The `e2e` result is part of the required aggregate. ## Integration test bootstrap @@ -101,7 +102,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. Increase the matrix size together with `TEST_SHARD_TOTAL` when suite duration warrants more runners. +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. ## Future software validation diff --git a/docs/ru/DEPLOY.md b/docs/ru/DEPLOY.md index da70163..55f99d7 100644 --- a/docs/ru/DEPLOY.md +++ b/docs/ru/DEPLOY.md @@ -198,4 +198,4 @@ Prometheus опрашивает backend /metrics на порту 9090, PostgreSQ Локальный стек мониторинга рассчитан на разработку и демонстрацию на одном узле и не обеспечивает HA. Проверка Compose валидирует конфигурацию, но не подтверждает production retention, backup вне узла, контроль публичного доступа, доставку alerts или поведение core приложения. -Файлы CI workflow находятся в .github/workflows/. Их наличие не подтверждает запуск на GitHub. В руководстве по проверкам описана разница между проверкой конфигурации, infrastructure smoke и проверкой продуктового сценария. +Файлы CI workflow находятся в .github/workflows/. Их наличие не подтверждает запуск на GitHub. Защита ветки должна требовать две проверки: `Required CI result` из ci.yml и `Required documentation result` из docs.yml. В руководстве по проверкам описана разница между проверкой конфигурации, infrastructure smoke и проверкой продуктового сценария. diff --git a/docs/ru/DEVELOPMENT.md b/docs/ru/DEVELOPMENT.md index 79225e5..17b716a 100644 --- a/docs/ru/DEVELOPMENT.md +++ b/docs/ru/DEVELOPMENT.md @@ -54,7 +54,7 @@ Frontend зависимости выбираются из актуальных s - OpenAPI контракты api/core/ и api/ml/ с объединением схем, bundles, lint и генерацией для Go (ogen), TypeScript (Orval) и Python (datamodel-code-generator). В SPA есть каркас интерфейса с экранами-заготовками, generated API client и MSW handlers. - Compose проекты: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`) и monitoring (`docker-compose.monitoring.yml`). - Kafka: один узел KRaft в core Compose проекте с listener только во внутренней сети, именованным volume, healthcheck и лимитом памяти. Backend запускает relay outbox, который создает топик `lincodex.domain.events` и публикует в него зафиксированные события outbox через producer на franz-go; см. [Relay outbox](#relay-outbox). Readiness не проверяет Kafka, и события пока никто не читает. -- CI jobs в .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix из двух шардов), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke` и обязательный итог `aggregate`. Шардирование описано в [TESTING.md](TESTING.md). +- CI jobs в .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix из двух шардов), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke`, `e2e` (набор Playwright на изолированном стенде) и обязательный итог `aggregate`, который падает, если любой из них упал, отменен или пропущен. Шардирование и браузерный набор описаны в [TESTING.md](TESTING.md). - Observability: Prometheus, Loki, Alloy, Grafana с provisioned datasources и dashboards, exporters для PostgreSQL, Redis и node. React-приложение пока не отправляет телеметрию. Еще не реализованы: регистрация и вход (их контракт объявлен; операции отвечают 501 или 401), согласия, профили, анкета и тестирование, кабинет компании, потребности и подбор, приглашения и контакты, транспорты Resend и SMTP и отправка почты, потребители событий, уведомления, поддержка и бизнес-E2E suite. В backend/db/migrations/ есть таблица outbox с индексом для relay, таблицы хранения identity (`users`, `email_tokens`, `sessions`) и таблица `policy_versions`, другой бизнес-схемы нет; ни одно продуктовое правило пока не читает политику; регистрация, подтверждение и сессии поверх этого хранения появятся в следующих задачах, каталоги продуктовых usecase и адаптеров, кроме частей для хеширования паролей и политики, содержат только заглушки, а `make -C deploy test-e2e` запускает только технический smoke на Playwright для SPA, health API и маршрутов ошибок на одноразовом стеке, а не бизнес-сценарий (см. [TESTING.md](TESTING.md#браузерный-e2e-набор)). Целевая архитектура описана в [ARCHITECTURE.md](ARCHITECTURE.md). diff --git a/docs/ru/TESTING.md b/docs/ru/TESTING.md index e447396..d4b30c3 100644 --- a/docs/ru/TESTING.md +++ b/docs/ru/TESTING.md @@ -25,6 +25,7 @@ make test запускает backend, frontend и ML тесты. make check та | make -C ml check | Ruff, mypy, pytest и сборку wheel | | make -C ml check-generated | Соответствие Pydantic-моделей ML bundle без перезаписи файлов | | make -C deploy config | Рендер Compose конфигураций без запуска | +| make -C deploy check | Рендер Compose конфигураций и `check-workflows`, который падает, если job `aggregate` в workflow не зависит от всех остальных jobs или не имеет `if: always()` | | make -C deploy smoke | Изолированный технический smoke по service health routes | | make -C deploy test-e2e | Браузерный набор Playwright на изолированном одноразовом стеке | | make -C observability check | Проверку Prometheus, Loki, Alloy и dashboard JSON | @@ -57,7 +58,7 @@ Deployment smoke проверяет инфраструктурные маршр Текущий набор (`frontend/e2e/smoke.spec.ts`) проверяет, что SPA отдает `/` с `lang="ru"` и заголовком, что `/status` показывает техническую страницу с живым API, что `/api/v1/healthz` через прокси frontend возвращает 200 `{"status":"ok"}`, что неизвестный маршрут SPA показывает страницу "не найдено" и что `/api/v1/missing` возвращает 404 `application/problem+json` с кодом `not_found`. Данные ему не нужны. Будущие бизнес-тесты создают своих синтетических пользователей и записи через публичный API в свежем стеке каждого прогона; общие фикстуры и реальные данные не используются. -Набор не проверяет сценарии кандидата и работодателя, вход, доставку почты, отказы зависимостей (их проверяет deployment smoke), браузеры кроме desktop Chromium, верстку и доступность. В CI он пока не запускается. +Набор не проверяет сценарии кандидата и работодателя, вход, доставку почты, отказы зависимостей (их проверяет deployment smoke), браузеры кроме desktop Chromium, верстку и доступность. CI запускает набор в job `e2e` после успешных `backend`, `frontend` и `infrastructure`: `make -C frontend install`, затем `make -C deploy test-e2e`. Секреты репозитория и корневой `.env` не нужны; каждый прогон использует свой сгенерированный env-файл и свежий стенд. При ошибке CI загружает артефакт `e2e-diagnostics-attempt-` с `report/`, `results/` (трассы и снимки экрана) и `stand.log` на 14 дней. Скрытые файлы и env-файл не загружаются. Результат `e2e` входит в обязательный aggregate. ## Bootstrap интеграционных тестов @@ -101,7 +102,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 проходит в любом шарде, куда он попал. Число шардов увеличивается в matrix вместе с `TEST_SHARD_TOTAL`, когда длительность suite оправдывает дополнительные runner. +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 ошибкой. ## Будущая программная валидация diff --git a/scripts/README.en.md b/scripts/README.en.md index 23968f3..1e61e34 100644 --- a/scripts/README.en.md +++ b/scripts/README.en.md @@ -9,7 +9,8 @@ Helper tools that work across multiple parts of the repository. - `check-generated.py` detects generated files that differ from Git. - `docs-check.py` checks documentation, README language pairs, and local links. - `test_docs_check.py` and `test_merge_schemas.py` test documentation validation and schema merging; `test_contract_copies.py` checks that the OpenAPI 3.2 fixture and the ML contract keep identical copies of the api/core conventions. +- `test_workflow_aggregate.py` checks every workflow in `.github/workflows` that has an `aggregate` job: the aggregate needs every other job and runs with `if: always()`, and every `needs` entry names an existing job. The test uses only the Python standard library and fails when it does not recognize the workflow structure. -Run them through Make from the repository root: `make -C api check`, `make -C api check-compat API_BASE_REF=`, `make check-generated`, and `make docs-check`. Service-specific scripts live in their service directories. +Run them through Make from the repository root: `make -C api check`, `make -C api check-compat API_BASE_REF=`, `make check-generated`, `make docs-check`, and `make -C deploy check-workflows` (part of `make -C deploy check`). Service-specific scripts live in their service directories. See the [development guide](../docs/en/DEVELOPMENT.md). diff --git a/scripts/README.md b/scripts/README.md index fab9e63..289e49a 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -9,7 +9,8 @@ - `check-generated.py` обнаруживает расхождения сгенерированных файлов с Git. - `docs-check.py` проверяет документацию, языковые пары README и локальные ссылки. - `test_docs_check.py` и `test_merge_schemas.py` проверяют валидацию документации и объединение схем; `test_contract_copies.py` проверяет, что фикстура OpenAPI 3.2 и ML-контракт хранят идентичные копии соглашений api/core. +- `test_workflow_aggregate.py` проверяет каждый workflow в `.github/workflows` с job `aggregate`: aggregate зависит от всех остальных jobs и запускается с `if: always()`, а все `needs` ссылаются на существующие jobs. Тест использует только стандартную библиотеку Python и падает, если не распознал структуру workflow. -Запускайте их через Make из корня: `make -C api check`, `make -C api check-compat API_BASE_REF=`, `make check-generated` и `make docs-check`. Скрипты конкретного сервиса находятся в его каталоге. +Запускайте их через Make из корня: `make -C api check`, `make -C api check-compat API_BASE_REF=`, `make check-generated`, `make docs-check` и `make -C deploy check-workflows` (входит в `make -C deploy check`). Скрипты конкретного сервиса находятся в его каталоге. Подробнее: [разработка](../docs/ru/DEVELOPMENT.md). diff --git a/scripts/test_workflow_aggregate.py b/scripts/test_workflow_aggregate.py new file mode 100644 index 0000000..f8174c5 --- /dev/null +++ b/scripts/test_workflow_aggregate.py @@ -0,0 +1,244 @@ +"""Check that each required aggregate job in .github/workflows covers every job. + +Branch protection requires only the aggregate result of each workflow, so a +job missing from the aggregate's needs would stop blocking merges without any +visible failure. The parser is line-based and uses only the standard library: +it accepts the plain block style the workflows use and raises on anything it +does not recognize instead of passing silently. +""" + +from __future__ import annotations + +import re +import unittest +from dataclasses import dataclass, field +from pathlib import Path + +WORKFLOWS_DIR = Path(__file__).resolve().parents[1] / ".github" / "workflows" +AGGREGATE = "aggregate" +# Workflows that must keep a required aggregate job. +REQUIRED_AGGREGATES = ("ci.yml", "docs.yml") + +NAME = r"[A-Za-z_][A-Za-z0-9_-]*" +JOB_LINE = re.compile(rf"^ ({NAME}):$") +JOB_KEY_LINE = re.compile(r"^ ([A-Za-z_][A-Za-z0-9_-]*):(?: (.*))?$") +NEEDS_ITEM = re.compile(rf"^ - ({NAME})$") +FLOW_LIST = re.compile(rf"^\[\s*({NAME}(?:\s*,\s*{NAME})*)?\s*\]$") + + +class WorkflowFormatError(ValueError): + """The workflow uses a structure this checker does not recognize.""" + + +@dataclass +class Job: + needs: list[str] = field(default_factory=list) + condition: str | None = None + + +def strip_comment(line: str) -> str: + # Workflow values here never contain " #", so a comment starts there. + index = line.find(" #") + return (line[:index] if index >= 0 else line).rstrip() + + +def unquote(value: str) -> str: + if len(value) >= 2 and value[0] == value[-1] and value[0] in "'\"": + return value[1:-1] + return value + + +def parse_jobs(text: str, source: str = "") -> dict[str, Job]: + """Return job ids with their needs and job-level if from a workflow file.""" + + def fail(number: int, message: str) -> WorkflowFormatError: + return WorkflowFormatError(f"{source}:{number}: {message}") + + lines = text.splitlines() + jobs_lines = [number for number, line in enumerate(lines) if line.rstrip() == "jobs:"] + if len(jobs_lines) != 1: + raise WorkflowFormatError(f"{source}: expected one top-level 'jobs:' line, found {len(jobs_lines)}") + + jobs: dict[str, Job] = {} + current: str | None = None + in_needs = False + for number in range(jobs_lines[0] + 1, len(lines)): + raw = lines[number] + if "\t" in raw: + raise fail(number + 1, "tabs are not supported") + line = strip_comment(raw) + if not line.strip() or line.lstrip().startswith("#"): + continue + indent = len(line) - len(line.lstrip(" ")) + if indent == 0: + break # Next top-level key: the jobs mapping ended. + if indent == 2: + match = JOB_LINE.match(line) + if not match: + raise fail(number + 1, f"unrecognized job line {raw!r}") + current = match.group(1) + if current in jobs: + raise fail(number + 1, f"duplicate job {current!r}") + jobs[current] = Job() + in_needs = False + continue + if current is None or indent < 4: + raise fail(number + 1, f"unexpected indentation in {raw!r}") + job = jobs[current] + if indent == 4: + match = JOB_KEY_LINE.match(line) + if not match: + raise fail(number + 1, f"unrecognized job key line {raw!r}") + key, value = match.group(1), (match.group(2) or "").strip() + in_needs = False + if key == "needs": + if not value: + in_needs = True + elif re.fullmatch(NAME, value): + job.needs.append(value) + elif flow := FLOW_LIST.match(value): + job.needs.extend(re.split(r"\s*,\s*", flow.group(1)) if flow.group(1) else []) + else: + raise fail(number + 1, f"unrecognized needs value {value!r}") + elif key == "if": + if not value: + raise fail(number + 1, "multi-line job if is not supported") + job.condition = unquote(value) + continue + if in_needs: + match = NEEDS_ITEM.match(line) + if not match: + raise fail(number + 1, f"unrecognized needs item {raw!r}") + job.needs.append(match.group(1)) + if not jobs: + raise WorkflowFormatError(f"{source}: no jobs found") + return jobs + + +def aggregate_problems(jobs: dict[str, Job]) -> list[str]: + """Describe every way the jobs break the aggregate contract.""" + problems = [] + for job_id, job in jobs.items(): + for need in job.needs: + if need not in jobs: + problems.append(f"job {job_id!r} needs unknown job {need!r}") + if len(set(job.needs)) != len(job.needs): + problems.append(f"job {job_id!r} lists a need more than once") + aggregate = jobs.get(AGGREGATE) + if aggregate is None: + return problems + [f"no {AGGREGATE!r} job"] + missing = sorted(set(jobs) - {AGGREGATE} - set(aggregate.needs)) + if missing: + problems.append(f"{AGGREGATE!r} does not need {missing}") + if AGGREGATE in aggregate.needs: + problems.append(f"{AGGREGATE!r} needs itself") + if aggregate.condition not in ("always()", "${{ always() }}"): + problems.append(f"{AGGREGATE!r} must run with 'if: always()', found {aggregate.condition!r}") + return problems + + +class WorkflowAggregateTests(unittest.TestCase): + def test_repository_aggregates_cover_every_job(self): + workflows = sorted(WORKFLOWS_DIR.glob("*.yml")) + sorted(WORKFLOWS_DIR.glob("*.yaml")) + self.assertTrue(workflows, f"no workflows found in {WORKFLOWS_DIR}") + checked = [] + for path in workflows: + with self.subTest(workflow=path.name): + jobs = parse_jobs(path.read_text(encoding="utf-8"), path.name) + if AGGREGATE not in jobs: + self.assertNotIn(path.name, REQUIRED_AGGREGATES, f"{path.name} lost its {AGGREGATE!r} job") + continue + self.assertGreater(len(jobs), 1, f"{path.name} has no jobs besides {AGGREGATE!r}") + self.assertEqual(aggregate_problems(jobs), [], path.name) + checked.append(path.name) + for name in REQUIRED_AGGREGATES: + self.assertIn(name, checked) + + +VALID = """\ +name: Example +on: + push: +jobs: + build: + name: Build + runs-on: ubuntu-24.04 + steps: + - name: Run + run: | + printf 'needs: nothing\\n' + test: + needs: build # trailing comment + strategy: + matrix: + shard: [1, 2] + steps: + - run: make test + aggregate: + name: Required result + if: always() + needs: + - build + # comment inside the list + - test + steps: + - run: true +""" + + +class ParserTests(unittest.TestCase): + def test_valid_workflow_is_parsed(self): + jobs = parse_jobs(VALID) + self.assertEqual(list(jobs), ["build", "test", "aggregate"]) + self.assertEqual(jobs["test"].needs, ["build"]) + self.assertEqual(jobs["aggregate"].needs, ["build", "test"]) + self.assertEqual(jobs["aggregate"].condition, "always()") + self.assertEqual(aggregate_problems(jobs), []) + + def test_flow_needs_and_quoted_condition_are_parsed(self): + jobs = parse_jobs(VALID.replace(" needs:\n - build\n # comment inside the list\n - test\n", + " needs: [build, test]\n").replace("if: always()", "if: '${{ always() }}'")) + self.assertEqual(jobs["aggregate"].needs, ["build", "test"]) + self.assertEqual(aggregate_problems(jobs), []) + + def test_missing_need_is_reported(self): + jobs = parse_jobs(VALID.replace(" - test\n", "")) + self.assertEqual(aggregate_problems(jobs), ["'aggregate' does not need ['test']"]) + + def test_missing_or_other_condition_is_reported(self): + cases = { + "missing": VALID.replace(" if: always()\n", ""), + "success()": VALID.replace("if: always()", "if: success()"), + } + for title, text in cases.items(): + with self.subTest(case=title): + problems = aggregate_problems(parse_jobs(text)) + self.assertEqual(len(problems), 1) + self.assertIn("if: always()", problems[0]) + + def test_unknown_need_is_reported(self): + jobs = parse_jobs(VALID.replace(" needs: build #", " needs: biuld #")) + self.assertIn("job 'test' needs unknown job 'biuld'", aggregate_problems(jobs)) + + def test_missing_aggregate_is_reported(self): + jobs = parse_jobs(VALID.split(" aggregate:\n")[0]) + self.assertEqual(aggregate_problems(jobs), ["no 'aggregate' job"]) + + def test_unrecognized_structure_fails_loudly(self): + broken = { + "no jobs key": VALID.replace("jobs:\n", "workflows:\n"), + "flow jobs": VALID.split("jobs:\n")[0] + "jobs: {build: {}}\n", + "inline job": VALID.replace(" build:\n", " build: {}\n"), + "odd indentation": VALID.replace(" name: Build\n", " name: Build\n"), + "tab": VALID.replace(" name: Build\n", "\tname: Build\n"), + "needs mapping": VALID.replace(" - test\n", " test: true\n"), + "needs expression": VALID.replace(" needs: build #", " needs: ${{ x }} #"), + "empty jobs": VALID.split("jobs:\n")[0] + "jobs:\n", + } + for title, text in broken.items(): + with self.subTest(case=title), self.assertRaises(WorkflowFormatError): + parse_jobs(text, title) + + +if __name__ == "__main__": + unittest.main()