From f526df07f06e20834ab1c65dbdaeabb6f9c66060 Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 8 Nov 2026 18:27:33 +1300 Subject: [PATCH 01/17] ci: aggregate slow-service coverage independently --- .../actions/check-gradle-module/action.yml | 137 ++++++++++ .../assess-required-gate.sh | 8 +- .github/workflows/ci.yml | 242 ++++++++---------- .github/workflows/validation-summary.yml | 18 +- .../architecture/system-architecture-cicd.md | 4 +- .../tests/ci-lightweight-scope-contract.sh | 145 ++++++++++- .../tests/ci-validation-summary-contract.sh | 28 +- .../pr-required-gate-context-contract.sh | 15 +- .../tests/pr-retarget-workflow-contract.sh | 4 +- .../tests/test_slow_service_ci_partition.py | 27 ++ 10 files changed, 466 insertions(+), 162 deletions(-) create mode 100644 .github/actions/check-gradle-module/action.yml diff --git a/.github/actions/check-gradle-module/action.yml b/.github/actions/check-gradle-module/action.yml new file mode 100644 index 0000000000..b053a6c669 --- /dev/null +++ b/.github/actions/check-gradle-module/action.yml @@ -0,0 +1,137 @@ +name: Check Gradle module +description: Run the canonical module checks and retain their coverage and diagnostic proof. +inputs: + module: + description: Exact module selected by change detection. + required: true + partition: + description: Existing full or numbered CI partition. + required: true + java-version: + description: Compiler and test toolchain version. + required: true + bootable-modules: + description: JSON array of selected bootable modules. + required: true +runs: + using: composite + steps: + - name: ⚙️ Set Up Python for Combined Coverage Verification + if: ${{ inputs.module == 'common-saga' }} + uses: ./.github/actions/setup-python + with: + requirements: none + + - name: Set up Python for installation inventory composition + if: ${{ inputs.module == 'game-design-service' }} + uses: ./.github/actions/setup-python + with: + requirements: yaml + + - name: ⚙️ Set Up Java + uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6 + with: + distribution: 'temurin' + java-version: ${{ inputs.java-version }} + + - name: ⚙️ Set Up Gradle + uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6 + with: + build-scan-publish: true + build-scan-terms-of-use-url: 'https://gradle.com/help/legal-terms-of-use' + build-scan-terms-of-use-agree: 'yes' + cache-read-only: false + + # Cached negative Spring Boot 4.1.1 resolution requires metadata revalidation (CI 37847761035). + - name: 🧪 Run Gradle Checks + id: checks + shell: bash + run: | + echo "::group::Run Module Validation" + bash ./.github/scripts/run-gradle-module-checks.sh '${{ inputs.module }}' '${{ inputs.partition }}' + echo "::endgroup::" + + - name: 📦 Build Runtime JAR + if: ${{ contains(fromJSON(inputs.bootable-modules), inputs.module) && (inputs.module != 'account-service' && inputs.module != 'game-session-service' || inputs.partition == '1') }} + shell: bash + run: ./gradlew --max-workers=2 '-Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8' :${{ inputs.module }}:bootJar -PfullCheck + + - name: 📈 Parse Coverage % + id: coverage + env: + MODULE_DIR: ${{ inputs.module == 'load-testing' && 'dev-tools/load-testing' || format('services/{0}', inputs.module) }} + shell: bash + run: | + COVERAGE_FILE="$MODULE_DIR/build/reports/jacoco/test/jacocoTestReport.xml" + if [ -f "$COVERAGE_FILE" ]; then + COVERAGE_LINE=$(grep -A 1 "&2 + PERCENT=0 + fi + echo "percent=$PERCENT" >> "$GITHUB_OUTPUT" + + - name: 🔎 Verify Combined Unit and Integration Coverage + if: ${{ inputs.module == 'common-saga' && inputs.partition == 'full' }} + shell: bash + run: | + python3 dev-tools/validation/validate-jacoco-combined-report.py \ + --report services/common-saga/build/reports/jacoco/test/jacocoTestReport.xml \ + --require-covered-class net/firedevops/firemud/common/saga/SagaRunner \ + --require-covered-class net/firedevops/firemud/common/saga/persistence/SagaInstanceRepository \ + --require-covered-method net/firedevops/firemud/common/saga/persistence/SagaInstanceRepository#findAll + + - name: 📤 Upload Coverage Report + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: jacoco-${{ inputs.module }}-${{ inputs.partition }}-report-${{ github.sha }}-attempt-${{ github.run_attempt }} + path: ${{ inputs.module == 'load-testing' && 'dev-tools/load-testing/build/reports/jacoco/test/' || format('services/{0}/build/reports/jacoco/test/', inputs.module) }} + + - name: 📤 Upload Test Logs if Failed + if: ${{ failure() || cancelled() }} + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: test-logs-${{ inputs.module }}-${{ inputs.partition }}-${{ github.sha }} + path: ${{ inputs.module == 'load-testing' && 'dev-tools/load-testing/build/reports/tests/' || format('services/{0}/build/reports/tests/', inputs.module) }} + + - name: 📤 Upload JUnit Test Results + if: ${{ always() && inputs.module != 'account-service' && inputs.module != 'game-session-service' }} + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: junit-${{ inputs.module }}-${{ inputs.partition }}-results-${{ github.sha }}-attempt-${{ github.run_attempt }} + path: ${{ inputs.module == 'load-testing' && 'dev-tools/load-testing/build/test-results/**/*.xml' || format('services/{0}/build/test-results/**/*.xml', inputs.module) }} + if-no-files-found: warn + retention-days: 14 + + - name: 📤 Upload Slow-Service Partition Reports and Execution Data + if: ${{ always() && (inputs.module == 'account-service' || inputs.module == 'game-session-service') }} + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: slow-service-ci-partition-${{ github.run_id }}-${{ github.sha }}-attempt-${{ github.run_attempt }}-${{ inputs.module }}-partition-${{ inputs.partition }} + path: | + services/${{ inputs.module }}/build/classes/java/main/ + services/${{ inputs.module }}/build/slow-service-ci-partition/${{ inputs.module }}/partition-${{ inputs.partition }}/ + services/${{ inputs.module }}/build/jacoco/*.exec + services/${{ inputs.module }}/build/reports/jacoco/test/ + services/${{ inputs.module }}/build/test-results/**/*.xml + if-no-files-found: warn + retention-days: 14 + + - name: Upload Gradle Task Profile + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: gradle-profile-${{ inputs.module }}-${{ inputs.partition }}-${{ github.sha }}-attempt-${{ github.run_attempt }} + path: | + build/reports/profile/ + build/reports/compile-failure/${{ inputs.module }}/ + if-no-files-found: warn + retention-days: 14 diff --git a/.github/actions/preserve-required-gate/assess-required-gate.sh b/.github/actions/preserve-required-gate/assess-required-gate.sh index 786ea68dc1..ac5be01b50 100644 --- a/.github/actions/preserve-required-gate/assess-required-gate.sh +++ b/.github/actions/preserve-required-gate/assess-required-gate.sh @@ -125,13 +125,15 @@ validation_cancelled_before_checks() { jq -e --argjson run "${workflow_run_id}" --argjson attempt "${attempt}" \ --arg head "${HEAD_SHA}" --arg repo "${GITHUB_REPOSITORY}" --argjson gate "${job_json}" ' ["Detect CI-Relevant Changes", "GitHub Workflow Lint", "Buf Generation", "Dev Tools README Contract", - ("Build and Test ($" + "{{ matrix.module }} / $" + "{{ matrix.partition }})"), "Metrics Cardinality Policy Check", "Flyway Migration Sanity Checks", + ("Build and Test ($" + "{{ matrix.module }} / $" + "{{ matrix.partition }})"), + ("Build and Test (account-service / $" + "{{ matrix.partition }})"), + ("Build and Test (game-session-service / $" + "{{ matrix.partition }})"), "Metrics Cardinality Policy Check", "Flyway Migration Sanity Checks", "gRPC Transport Configuration Sanity Checks", "PostgreSQL Runtime Upgrade Proof", "Validate Documentation", "YAML Lint", "Dockerfile Lint", "Helm Render Validation", "Helm Chart Lint", "Python Script Validation", "ShellCheck", "Frontend Checks", "Dev Tool Contract Checks", "Helm Transaction Proof", "Account Coverage Aggregate", "Game Session Coverage Aggregate", "Validation Gate"] as $names - | type == "array" and length == 1 and .[0].total_count == 22 and (.[0].jobs | type) == "array" and - (.[0].jobs | length) == 22 and ([.[0].jobs[].id] | unique | length) == 22 and + | type == "array" and length == 1 and .[0].total_count == 24 and (.[0].jobs | type) == "array" and + (.[0].jobs | length) == 24 and ([.[0].jobs[].id] | unique | length) == 24 and ([.[0].jobs[].name] | sort) == ($names | sort) and all(.[0].jobs[]; (.id | type) == "number" and .id > 0 and .id == (.id | floor) and .run_id == $run and .run_attempt == $attempt and .head_sha == $head and .status == "completed" and diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ad3a195196..b10d815011 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -35,6 +35,9 @@ jobs: affected_services: ${{ steps.compute.outputs.affected_services }} affected_modules: ${{ steps.compute.outputs.affected_modules }} module_check_matrix: ${{ steps.compute.outputs.module_check_matrix }} + other_module_check_matrix: ${{ steps.compute.outputs.other_module_check_matrix }} + account_module_check_matrix: ${{ steps.compute.outputs.account_module_check_matrix }} + game_session_module_check_matrix: ${{ steps.compute.outputs.game_session_module_check_matrix }} bootable_modules: ${{ steps.compute.outputs.bootable_modules }} docs_changed: ${{ steps.compute.outputs.docs_changed }} frontend_changed: ${{ steps.compute.outputs.frontend_changed }} @@ -153,6 +156,9 @@ jobs: ({ module, partition: String(index + 1), "java-version": 25 })) : [{ module, partition: "full", "java-version": 25 }] ); + outputs.other_module_check_matrix = outputs.module_check_matrix.filter(row => !slowServicePartitionCounts[row.module]); + outputs.account_module_check_matrix = outputs.module_check_matrix.filter(row => row.module === "account-service"); + outputs.game_session_module_check_matrix = outputs.module_check_matrix.filter(row => row.module === "game-session-service"); for (const [name, value] of Object.entries(outputs)) { core.setOutput( name, @@ -1065,116 +1071,41 @@ jobs: build-and-test: name: Build and Test (${{ matrix.module }} / ${{ matrix.partition }}) needs: [changes] - if: ${{ (github.event_name != 'pull_request' || github.event.action != 'edited' || github.event.changes.base.ref != null) && needs.changes.outputs.affected_modules != '[]' }} + if: ${{ (github.event_name != 'pull_request' || github.event.action != 'edited' || github.event.changes.base.ref != null) && needs.changes.outputs.other_module_check_matrix != '[]' }} runs-on: ubuntu-latest permissions: contents: read id-token: write - # Allow 90 minutes for the full Game Session native issuer suites; retain Account 60, allow World 60, and retain Game Design 30. - timeout-minutes: ${{ matrix.module == 'game-session-service' && 90 || matrix.module == 'account-service' && 60 || matrix.module == 'world-management-service' && 60 || matrix.module == 'game-design-service' && 30 || 20 }} + timeout-minutes: ${{ matrix.module == 'world-management-service' && 60 || matrix.module == 'game-design-service' && 30 || 20 }} strategy: fail-fast: false matrix: - include: ${{ fromJSON(needs.changes.outputs.module_check_matrix) }} - + include: ${{ fromJSON(needs.changes.outputs.other_module_check_matrix) }} steps: - name: Harden runner uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 with: egress-policy: audit - - name: 'Declare Game Session CI partition count: 4' - if: ${{ matrix.module == 'game-session-service' }} - run: ':' - - - name: 'Declare Account CI partition count: 4' - if: ${{ matrix.module == 'account-service' }} - run: ':' - - name: ⬇️ Checkout Code uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: fetch-depth: 2 persist-credentials: false - - name: ⚙️ Set Up Python for Combined Coverage Verification - if: ${{ matrix.module == 'common-saga' }} - uses: ./.github/actions/setup-python - with: - requirements: none - - - name: Set up Python for installation inventory composition - if: ${{ matrix.module == 'game-design-service' }} - uses: ./.github/actions/setup-python - with: - requirements: yaml - - - name: ⚙️ Set Up Java - uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6 + - name: Validate module and retain proof + if: ${{ always() }} + uses: ./.github/actions/check-gradle-module with: - distribution: 'temurin' + module: ${{ matrix.module }} + partition: ${{ matrix.partition }} java-version: ${{ matrix.java-version }} + bootable-modules: ${{ needs.changes.outputs.bootable_modules }} - - name: ⚙️ Set Up Gradle - uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6 - with: - build-scan-publish: true - build-scan-terms-of-use-url: 'https://gradle.com/help/legal-terms-of-use' - build-scan-terms-of-use-agree: 'yes' - cache-read-only: false - - # Cached negative Spring Boot 4.1.1 resolution requires metadata revalidation (CI 37847761035). - - name: 🧪 Run Gradle Checks - id: checks - run: | - echo "::group::Run Module Validation" - bash ./.github/scripts/run-gradle-module-checks.sh '${{ matrix.module }}' '${{ matrix.partition }}' - echo "::endgroup::" - - - name: 📦 Build Runtime JAR - if: ${{ contains(fromJSON(needs.changes.outputs.bootable_modules), matrix.module) && (matrix.module != 'account-service' && matrix.module != 'game-session-service' || matrix.partition == '1') }} - run: ./gradlew --max-workers=2 '-Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8' :${{ matrix.module }}:bootJar -PfullCheck - - - name: 📈 Parse Coverage % - id: coverage - env: - MODULE_DIR: ${{ matrix.module == 'load-testing' && 'dev-tools/load-testing' || format('services/{0}', matrix.module) }} - run: | - COVERAGE_FILE="$MODULE_DIR/build/reports/jacoco/test/jacocoTestReport.xml" - if [ -f "$COVERAGE_FILE" ]; then - COVERAGE_LINE=$(grep -A 1 "&2 - PERCENT=0 - fi - echo "percent=$PERCENT" >> "$GITHUB_OUTPUT" - - - name: 🔎 Verify Combined Unit and Integration Coverage - if: ${{ matrix.module == 'common-saga' && matrix.partition == 'full' }} - run: | - python3 dev-tools/validation/validate-jacoco-combined-report.py \ - --report services/common-saga/build/reports/jacoco/test/jacocoTestReport.xml \ - --require-covered-class net/firedevops/firemud/common/saga/SagaRunner \ - --require-covered-class net/firedevops/firemud/common/saga/persistence/SagaInstanceRepository \ - --require-covered-method net/firedevops/firemud/common/saga/persistence/SagaInstanceRepository#findAll - - - name: 📤 Upload Coverage Report - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 - with: - name: jacoco-${{ matrix.module }}-${{ matrix.partition }}-report-${{ github.sha }}-attempt-${{ github.run_attempt }} - path: ${{ matrix.module == 'load-testing' && 'dev-tools/load-testing/build/reports/jacoco/test/' || format('services/{0}/build/reports/jacoco/test/', matrix.module) }} - - - name: ☂️ Upload Coverage to Codecov + - &module-codecov + name: ☂️ Upload Coverage to Codecov continue-on-error: true - # Optional coverage upload must leave time for required proof artifacts. + # Required proof artifacts are already retained before this bounded optional upload. timeout-minutes: 2 uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1 with: @@ -1187,51 +1118,90 @@ jobs: name: ${{ matrix.module }}-${{ matrix.partition }}-jacoco verbose: true - - name: 📤 Upload Test Logs if Failed - if: ${{ failure() || cancelled() }} - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + build-and-test-account: + name: Build and Test (account-service / ${{ matrix.partition }}) + needs: [changes] + if: ${{ (github.event_name != 'pull_request' || github.event.action != 'edited' || github.event.changes.base.ref != null) && needs.changes.outputs.account_module_check_matrix != '[]' }} + runs-on: ubuntu-latest + permissions: + contents: read + id-token: write + timeout-minutes: 60 + strategy: + fail-fast: false + matrix: + include: ${{ fromJSON(needs.changes.outputs.account_module_check_matrix) }} + steps: + - name: Harden runner + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 with: - name: test-logs-${{ matrix.module }}-${{ matrix.partition }}-${{ github.sha }} - path: ${{ matrix.module == 'load-testing' && 'dev-tools/load-testing/build/reports/tests/' || format('services/{0}/build/reports/tests/', matrix.module) }} + egress-policy: audit - - name: 📤 Upload JUnit Test Results - if: ${{ always() && matrix.module != 'account-service' && matrix.module != 'game-session-service' }} - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + - name: 'Declare Account CI partition count: 4' + if: ${{ matrix.module == 'account-service' }} + run: ':' + + - name: ⬇️ Checkout Code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: - name: junit-${{ matrix.module }}-${{ matrix.partition }}-results-${{ github.sha }}-attempt-${{ github.run_attempt }} - path: ${{ matrix.module == 'load-testing' && 'dev-tools/load-testing/build/test-results/**/*.xml' || format('services/{0}/build/test-results/**/*.xml', matrix.module) }} - if-no-files-found: warn - retention-days: 14 + fetch-depth: 2 + persist-credentials: false - - name: 📤 Upload Slow-Service Partition Reports and Execution Data - if: ${{ always() && (matrix.module == 'account-service' || matrix.module == 'game-session-service') }} - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + - name: Validate module and retain proof + if: ${{ always() }} + uses: ./.github/actions/check-gradle-module with: - name: slow-service-ci-partition-${{ github.run_id }}-${{ github.sha }}-attempt-${{ github.run_attempt }}-${{ matrix.module }}-partition-${{ matrix.partition }} - path: | - services/${{ matrix.module }}/build/classes/java/main/ - services/${{ matrix.module }}/build/slow-service-ci-partition/${{ matrix.module }}/partition-${{ matrix.partition }}/ - services/${{ matrix.module }}/build/jacoco/*.exec - services/${{ matrix.module }}/build/reports/jacoco/test/ - services/${{ matrix.module }}/build/test-results/**/*.xml - if-no-files-found: warn - retention-days: 14 + module: ${{ matrix.module }} + partition: ${{ matrix.partition }} + java-version: ${{ matrix.java-version }} + bootable-modules: ${{ needs.changes.outputs.bootable_modules }} - - name: Upload Gradle Task Profile - if: always() - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + - *module-codecov + + build-and-test-game-session: + name: Build and Test (game-session-service / ${{ matrix.partition }}) + needs: [changes] + if: ${{ (github.event_name != 'pull_request' || github.event.action != 'edited' || github.event.changes.base.ref != null) && needs.changes.outputs.game_session_module_check_matrix != '[]' }} + runs-on: ubuntu-latest + permissions: + contents: read + id-token: write + timeout-minutes: 90 + strategy: + fail-fast: false + matrix: + include: ${{ fromJSON(needs.changes.outputs.game_session_module_check_matrix) }} + steps: + - name: Harden runner + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 with: - name: gradle-profile-${{ matrix.module }}-${{ matrix.partition }}-${{ github.sha }}-attempt-${{ github.run_attempt }} - path: | - build/reports/profile/ - build/reports/compile-failure/${{ matrix.module }}/ - if-no-files-found: warn - retention-days: 14 + egress-policy: audit + + - name: 'Declare Game Session CI partition count: 4' + if: ${{ matrix.module == 'game-session-service' }} + run: ':' + + - name: ⬇️ Checkout Code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + fetch-depth: 2 + persist-credentials: false + + - name: Validate module and retain proof + if: ${{ always() }} + uses: ./.github/actions/check-gradle-module + with: + module: ${{ matrix.module }} + partition: ${{ matrix.partition }} + java-version: ${{ matrix.java-version }} + bootable-modules: ${{ needs.changes.outputs.bootable_modules }} + + - *module-codecov account-coverage-aggregate: name: Account Coverage Aggregate - needs: [changes, build-and-test] - if: ${{ (github.event_name != 'pull_request' || github.event.action != 'edited' || github.event.changes.base.ref != null) && contains(fromJSON(needs.changes.outputs.affected_modules || '[]'), 'account-service') && needs.build-and-test.result == 'success' }} + needs: [changes, build-and-test-account] + if: ${{ (github.event_name != 'pull_request' || github.event.action != 'edited' || github.event.changes.base.ref != null) && contains(fromJSON(needs.changes.outputs.affected_modules || '[]'), 'account-service') && needs.build-and-test-account.result == 'success' }} runs-on: ubuntu-latest timeout-minutes: 30 permissions: @@ -1341,8 +1311,8 @@ jobs: game-session-coverage-aggregate: name: Game Session Coverage Aggregate - needs: [changes, build-and-test] - if: ${{ (github.event_name != 'pull_request' || github.event.action != 'edited' || github.event.changes.base.ref != null) && contains(fromJSON(needs.changes.outputs.affected_modules || '[]'), 'game-session-service') && needs.build-and-test.result == 'success' }} + needs: [changes, build-and-test-game-session] + if: ${{ (github.event_name != 'pull_request' || github.event.action != 'edited' || github.event.changes.base.ref != null) && contains(fromJSON(needs.changes.outputs.affected_modules || '[]'), 'game-session-service') && needs.build-and-test-game-session.result == 'success' }} runs-on: ubuntu-latest timeout-minutes: 30 permissions: @@ -1466,7 +1436,7 @@ jobs: ACCOUNT_COVERAGE_AGGREGATE: ${{ needs.account-coverage-aggregate.result }} GAME_SESSION_MODULE_AFFECTED: ${{ contains(fromJSON(needs.changes.outputs.affected_modules || '[]'), 'game-session-service') }} GAME_SESSION_COVERAGE_AGGREGATE: ${{ needs.game-session-coverage-aggregate.result }} - needs: [changes, postgres-runtime-upgrade-proof, buf-check, docker-lint, shellcheck, python-script-validation, dev-tool-contract-checks, dev-tools-readme-contract, yaml-lint, metrics-cardinality-check, flyway-migration-sanity-checks, grpc-transport-config-sanity-checks, workflow-lint, helm-lint, helm-render-validation, helm-transaction-proof, docs-check, frontend-checks, build-and-test, account-coverage-aggregate, game-session-coverage-aggregate] + needs: [changes, postgres-runtime-upgrade-proof, buf-check, docker-lint, shellcheck, python-script-validation, dev-tool-contract-checks, dev-tools-readme-contract, yaml-lint, metrics-cardinality-check, flyway-migration-sanity-checks, grpc-transport-config-sanity-checks, workflow-lint, helm-lint, helm-render-validation, helm-transaction-proof, docs-check, frontend-checks, build-and-test, build-and-test-account, build-and-test-game-session, account-coverage-aggregate, game-session-coverage-aggregate] if: ${{ always() }} steps: - name: Harden runner @@ -1562,6 +1532,9 @@ jobs: DOCS_CHECK: ${{ needs.docs-check.result }} FRONTEND_CHECKS: ${{ needs.frontend-checks.result }} BUILD_AND_TEST: ${{ needs.build-and-test.result }} + BUILD_AND_TEST_ACCOUNT: ${{ needs.build-and-test-account.result }} + BUILD_AND_TEST_GAME_SESSION: ${{ needs.build-and-test-game-session.result }} + OTHER_MODULES_AFFECTED: ${{ needs.changes.outputs.other_module_check_matrix != '[]' }} run: | is_acceptable_optional_result() { local result="$1" @@ -1662,16 +1635,19 @@ jobs: fi fi - echo "Build and Test Matrix => $BUILD_AND_TEST" - if [ "$AFFECTED_MODULES" != "[]" ]; then - if [ "$BUILD_AND_TEST" != "success" ]; then - failed=1 - fi - else - if ! is_acceptable_optional_result "$BUILD_AND_TEST"; then + # A skipped selected group is missing proof, even if its sibling groups succeeded. + require_matrix_group() { + local label="$1" affected="$2" result="$3" + echo "$label => $result (affected=$affected)" + if [ "$affected" = "true" ]; then + if [ "$result" != "success" ]; then failed=1; fi + elif [ "$result" != "skipped" ]; then failed=1 fi - fi + } + require_matrix_group "Other module matrix" "$OTHER_MODULES_AFFECTED" "$BUILD_AND_TEST" + require_matrix_group "Account matrix" "$ACCOUNT_MODULE_AFFECTED" "$BUILD_AND_TEST_ACCOUNT" + require_matrix_group "Game Session matrix" "$GAME_SESSION_MODULE_AFFECTED" "$BUILD_AND_TEST_GAME_SESSION" echo "Account Coverage Aggregate => $ACCOUNT_COVERAGE_AGGREGATE (account-affected=$ACCOUNT_MODULE_AFFECTED)" if [ "$ACCOUNT_MODULE_AFFECTED" = "true" ]; then diff --git a/.github/workflows/validation-summary.yml b/.github/workflows/validation-summary.yml index 2c98f1e635..c3479ddd5b 100644 --- a/.github/workflows/validation-summary.yml +++ b/.github/workflows/validation-summary.yml @@ -157,9 +157,11 @@ jobs: "logging-admin-service", "social-groups-service", "spring-cloud-gateway", "tcp-proxy-service", "world-management-service", "hosted-environment-identity-controller", "load-testing", ]); - const placeholders = new Set([ - "Build and Test ($" + "{{ matrix.module }})", - "Build and Test ($" + "{{ matrix.module }} / $" + "{{ matrix.partition }})", + const placeholders = new Map([ + ["Build and Test ($" + "{{ matrix.module }})", "legacy"], + ["Build and Test ($" + "{{ matrix.module }} / $" + "{{ matrix.partition }})", "other"], + ["Build and Test (account-service / $" + "{{ matrix.partition }})", "account-service"], + ["Build and Test (game-session-service / $" + "{{ matrix.partition }})", "game-session-service"], ]); const aggregateNames = new Map([ ["account-service", "Account Coverage Aggregate"], @@ -185,7 +187,7 @@ jobs: } matrix.push({ job, module, partition: partition || null }); } else if (placeholders.has(job.name) && job.conclusion === "skipped") { - matrix.push({ job, placeholder: true }); + matrix.push({ job, placeholder: placeholders.get(job.name) }); } else { throw new Error("Unknown Validation source job: " + job.name); } @@ -244,8 +246,14 @@ jobs: invalidSlowServiceMatrix = true; } } + const invalidPlaceholder = matrix.some(entry => entry.placeholder && ( + entry.job.steps?.some(step => step.conclusion !== "skipped") || + (entry.placeholder === "legacy" ? matrix.length !== 1 : + matrix.some(candidate => candidate.module && + (entry.placeholder === "other" ? !slowServices.has(candidate.module) : candidate.module === entry.placeholder))) + )); if (!matrix.length || new Set(matrix.map(entry => entry.job.name)).size !== matrix.length || - (matrix.some(entry => entry.placeholder) && matrix.length !== 1) || + invalidPlaceholder || duplicateUnpartitionedModule || invalidSlowServiceMatrix) { throw new Error("Missing or ambiguous module matrix"); } diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index c25cd9bb55..ba530c6ca5 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -34,7 +34,7 @@ The manual [Game Session factory inventory qualification workflow](../../.github ## Required Gate Preservation -The Validation, Security, CodeQL, License, and Smoke gates retain their exact branch-protection names. A metadata-only pull-request edit reuses proof only through the shared preservation action, which validates the owning workflow and repository, pull-request event, canonical PR/base/head run title, check/job identity, and substantive preservation-step state. Fork heads remain supported, including empty GitHub PR associations when the exact canonical title supplies attribution. Completed metadata preservation checks never become original proof. A newer completed substantive failure defeats an older success. A failed Validation aggregate from a cancelled workflow is missing proof only for the narrowly recognized pre-execution cancellation shape: the complete exact-attempt native snapshot contains the known gate and all twenty-one prerequisite jobs, including the exact Build and Test matrix placeholder and both Account Coverage Aggregate and Game Session Coverage Aggregate jobs; every prerequisite is cancelled without executed steps, except that either coverage aggregate may be skipped without steps; and the gate failed only Enforce validation success. The assessor independently binds the attempt, job identities and native Actions checks before excluding that cancellation artifact from authoritative failures. A cancelled workflow alone is insufficient; executed prerequisite steps, failed or timed-out assertions, unknown outcomes, incomplete evidence and conflicting identities retain fail-closed failure. Existing selection then uses other original proof or emits dependency deferral; cancellation never supplies success or broadens automatic rerun eligibility. +The Validation, Security, CodeQL, License, and Smoke gates retain their exact branch-protection names. A metadata-only pull-request edit reuses proof only through the shared preservation action, which validates the owning workflow and repository, pull-request event, canonical PR/base/head run title, check/job identity, and substantive preservation-step state. Fork heads remain supported, including empty GitHub PR associations when the exact canonical title supplies attribution. Completed metadata preservation checks never become original proof. A newer completed substantive failure defeats an older success. A failed Validation aggregate from a cancelled workflow is missing proof only for the narrowly recognized pre-execution cancellation shape: the complete exact-attempt native snapshot contains the known gate and all twenty-three prerequisite jobs, including the three distinct other-module, Account and Game Session Build and Test matrix placeholders and both Account Coverage Aggregate and Game Session Coverage Aggregate jobs; every prerequisite is cancelled without executed steps, except that either coverage aggregate may be skipped without steps; and the gate failed only Enforce validation success. The assessor independently binds the attempt, job identities and native Actions checks before excluding that cancellation artifact from authoritative failures. Historical single-matrix inventories do not qualify for this exception; incomplete current inventories cannot fall back to that older shape. A cancelled workflow alone is insufficient; executed prerequisite steps, failed or timed-out assertions, unknown outcomes, incomplete evidence and conflicting identities retain fail-closed failure. Existing selection then uses other original proof or emits dependency deferral; cancellation never supplies success or broadens automatic rerun eligibility. A supplementary Commit Status with the same required gate name may withhold an otherwise successful native Actions CheckRun. Both must succeed when both exist; the native app-pinned CheckRun remains mandatory, and a status creator, actor name, or URL cannot establish App authority. The controller independently evaluates that native proof and all exact-head same-name status barriers, including foreign barriers. A status success alone never supplies required native proof. @@ -110,7 +110,7 @@ The main [`ci.yml`](../../.github/workflows/ci.yml) workflow: - Runs formatting and lint steps (Spotless, markdownlint, link checks). - On the complete CI path, executes a matrix of Gradle `check` tasks for affected microservices with SpotBugs, Checkstyle, and tests enabled. Account Service and Game Session each use four complete-check partitions; other modules remain one check per affected module. Lightweight documentation-only PR validation does not run these service checks. - Affected-module checks and the source-built Compose boot-jar command first use Gradle's restored dependency metadata without a forced refresh. The shared runner gives a fully recognized repository-resolution failure one retry of the same complete Gradle command with `--refresh-dependencies`; successful commands do not revalidate every dependency. The existing pre-substantive compile/test boundary remains. jOOQ also permits only the exact matching `jooqCodegen` classpath-resolution failure, including Gradle's `generateJooq FAILED` task wrapper when the failure prevents the JavaExec generator from launching. The configuration-cache wrapper remains retryable only before `generateJooq` starts. Genuine JavaExec, code-generation, SQL, compiler, test, mixed, unknown, interrupted, or unrelated configuration failures retain their original failure. -- On the complete CI path, preserves every service test task and JaCoCo execution. Each Account Service and Game Session partition uploads its report to Codecov using GitHub OIDC; a separate read-only aggregate verifies every module partition’s selectors and JUnit results, then merges execution data from unit and every available categorized integration/cross-service task into the complete service report. Other modules retain one report from their module check; modules without categorized tests retain their unit-only report. Production classes remain in reports rather than being excluded to improve percentages. Lightweight documentation-only PR validation does not run these service checks or coverage reports. +- On the complete CI path, preserves every service test task and JaCoCo execution. Each Account Service and Game Session partition uploads its report to Codecov using GitHub OIDC; a separate read-only aggregate verifies every module partition’s selectors and JUnit results, then merges execution data from unit and every available categorized integration/cross-service task into the complete service report. Other modules retain one report from their module check; modules without categorized tests retain their unit-only report. Production classes remain in reports rather than being excluded to improve percentages. Lightweight documentation-only PR validation does not run these service checks or coverage reports. Account and Game Session validation use disjoint four-partition matrix jobs, with remaining modules in a third matrix and one shared module-validation recipe. Each service aggregate waits only for its own successful matrix. The final Validation Gate requires every selected matrix group and its applicable aggregate; an unaffected group may skip, but a selected skipped, cancelled or failed group cannot pass. - Retains Gradle JUnit XML results from each affected-module `check`, including unit and categorized integration/cross-service outcomes, for 14 days. Account and Game Session retain them with their complete partition evidence in `slow-service-ci-partition---attempt---partition-`; other modules use `junit---results--attempt-`. Including the attempt keeps partial workflow reruns from colliding with earlier artifacts. The load-testing matrix entry uses its `dev-tools/load-testing` output; missing XML is reported as a warning so artifact retention does not change the test gate. - Runs the existing module check with Gradle's native `--profile`; Account and Game Session partition jobs also profile their existing test-class preparation invocation before class selection. The workflow retains `build/reports/profile/` from the repository root as `gradle-profile----attempt-` for 14 days, including profiles from both invocations when present. These reports expose startup, configuration, dependency and task durations. Profiling does not change the selected checks or recovery behavior; fork concurrency remains controlled by the task configuration above. Missing reports warn rather than supplying timing evidence; cancelled or early-failed runs may not produce a report. Parallel task durations can overlap and must not be summed as elapsed time; JUnit results remain the separate source for individual test costs. - Failed Java compile tasks additionally retain bounded generated Java, proto, and build/version inputs with hashes and an omissions manifest in the existing per-module profile artifact. The same collector covers the source-built Compose all-eleven-service `bootJar` boundary in `dev-tools/build-compose-service-jars.sh`, using a distinct invocation directory under `build/reports/compile-failure/runtime-bootjar/`. The read-only `pr-local-smoke` job retains only that invocation's evidence on build failure as `runtime-bootjar-compile-failure--attempt-` for three days; missing evidence warns and upload failure cannot replace the build result. Native `--info` compiler identity lines come from the original check or boot-jar build; a separate offline diagnostic records Gradle/JVM identity, compiler selection and ordered compile classpath paths/lengths without copying JARs. Diagnostic selection is explicitly post-failure and cannot establish the original executed compiler or dependency bytes. Diagnostics use the canonical locked Gradle wrapper, retaining local resource admission, verified inherited leases, and its existing CI bypass. Collection is limited to four failed tasks, 512 input files, 2 MiB per input, 16 MiB total inputs, 4096 visited directory entries across source enumeration, a 16 MiB streamed log tail, and 60 seconds per diagnostic; symlink paths are rejected. Source enumeration and diagnostic output limits report possible truncation, including an exactly full diagnostic output. Live output is forwarded while only the bounded log tail is buffered for capture; capture/forwarding failures still drain the original output. Missing facts and diagnostic failure remain explicit. Missing boot-jar capture scratch runs the original build once without evidence. Success, failures without a failed Java compile task, and cancellation/signal exits (128 or above) produce no compile-failure evidence; cancellation/signal exits skip diagnostics. A failed `compileJava` task may retain evidence even when the failure comes from classpath or dependency resolution rather than compiler diagnostics. Collection never retries compilation or tests, changes dependency recovery, or replaces the original exit. No environment dump, credentials, whole cache, or unrelated workspace data is retained. diff --git a/dev-tools/tests/ci-lightweight-scope-contract.sh b/dev-tools/tests/ci-lightweight-scope-contract.sh index 366fb41410..f8afc662ac 100644 --- a/dev-tools/tests/ci-lightweight-scope-contract.sh +++ b/dev-tools/tests/ci-lightweight-scope-contract.sh @@ -166,6 +166,7 @@ PY python3 - "$CI_WORKFLOW" "$SECURITY_WORKFLOW" "$PREVIEW_WORKFLOW" "$ZAP_WORKFLOW" "$CLASSIFIER" "$ROOT_DIR/build.gradle.kts" <<'PY' import copy import json +import os from pathlib import Path import re import subprocess @@ -202,7 +203,7 @@ def require_equal(mapping, path, expected, label): ) -def evaluate_module_check_matrix(step, modules): +def evaluate_module_check_matrix(step, modules, output="module_check_matrix"): script = value_at(step, ("with", "script"), "ci workflow") match = re.search( r"(?ms)^[ \t]*outputs\.module_check_matrix = .*?^[ \t]*\);", @@ -220,7 +221,7 @@ def evaluate_module_check_matrix(step, modules): const fs = require("node:fs"); const input = JSON.parse(fs.readFileSync(0, "utf8")); const outputs = { affected_modules: input.modules }; -const rows = new Function("outputs", `${input.partition_set}\n${input.assignment}\nreturn outputs.module_check_matrix;`)(outputs); +const rows = new Function("outputs", `${input.partition_set}\n${input.assignment}\n${input.groups}\nreturn outputs[${JSON.stringify(input.output)}];`)(outputs); process.stdout.write(JSON.stringify(rows)); """ try: @@ -233,6 +234,8 @@ process.stdout.write(JSON.stringify(rows)); "modules": modules, "assignment": match.group(0).strip(), "partition_set": partition_set.group(0).strip(), + "groups": "\n".join(re.findall(r"(?m)^.*outputs\.(?:other|account|game_session)_module_check_matrix = .*;$", script)), + "output": output, }), ) rows = json.loads(result.stdout) @@ -488,9 +491,56 @@ security = load_workflow(sys.argv[2]) preview = load_workflow(sys.argv[3]) zap = load_workflow(sys.argv[4]) ci_compute_step = find_step(ci, "changes", "Compute affected jobs", "ci workflow") +module_action = load_workflow(str(Path(sys.argv[1]).parents[1] / "actions/check-gradle-module/action.yml")) +require_equal(module_action, ("runs", "using"), "composite", "module action") +if set(module_action["inputs"]) != {"module", "partition", "java-version", "bootable-modules"}: + raise SystemExit("Module recipe must declare its complete explicit input boundary") +recipe_text = json.dumps(module_action["runs"]["steps"]) +if "matrix." in recipe_text or "needs." in recipe_text: + raise SystemExit("Composite must not depend on inaccessible caller context") +for step in module_action["runs"]["steps"]: + if "run" in step and step.get("shell") != "bash": + raise SystemExit("Composite run steps need explicit Bash") +# Compare the extracted recipe with the existing exact command/artifact contracts +# after substituting only its explicit caller-input boundary. +normalized_recipe = recipe_text.replace("inputs.java-version", "matrix.java-version").replace("inputs.module", "matrix.module").replace("inputs.partition", "matrix.partition").replace("inputs.bootable-modules", "needs.changes.outputs.bootable_modules") +module_ci = {"jobs": {"build-and-test": {"steps": json.loads(normalized_recipe)}}} +codec_step = find_step(ci, "build-and-test", "Upload Coverage to Codecov", "ci workflow") +require_equal(codec_step, ("continue-on-error",), "true", "native Codecov") +require_equal(codec_step, ("timeout-minutes",), "2", "native Codecov") +module_ci["jobs"]["build-and-test"]["steps"].append(codec_step) +groups = { + "build-and-test": ("other_module_check_matrix", None), + "build-and-test-account": ("account_module_check_matrix", "account-service"), + "build-and-test-game-session": ("game_session_module_check_matrix", "game-session-service"), +} +for job_id, (output, module) in groups.items(): + job = ci["jobs"][job_id] + name_module = module or "${{ matrix.module }}" + require_equal(job, ("name",), "Build and Test (" + name_module + " / ${{ matrix.partition }})", job_id) + timeout = "60" if module == "account-service" else "90" if module == "game-session-service" else "${{ matrix.module == 'world-management-service' && 60 || matrix.module == 'game-design-service' && 30 || 20 }}" + require_equal(job, ("timeout-minutes",), timeout, job_id) + require_equal(job, ("needs",), ["changes"], job_id) + require_equal(job, ("strategy", "fail-fast"), "false", job_id) + require_equal(job, ("strategy", "matrix"), {"include": "${{ fromJSON(needs.changes.outputs." + output + ") }}"}, job_id) + require_contains(job, ("if",), "needs.changes.outputs." + output + " != '[]'", job_id) + require_equal(job, ("permissions",), {"contents": "read", "id-token": "write"}, job_id) + call = find_step(ci, job_id, "Validate module and retain proof", "ci workflow") + require_equal(call, ("uses",), "./.github/actions/check-gradle-module", job_id) + require_equal(call, ("if",), "${{ always() }}", job_id) + require_equal(call, ("with",), { + "module": "${{ matrix.module }}", "partition": "${{ matrix.partition }}", + "java-version": "${{ matrix.java-version }}", + "bootable-modules": "${{ needs.changes.outputs.bootable_modules }}", + }, job_id) + if find_step(ci, job_id, "Upload Coverage to Codecov", job_id) != codec_step: + raise SystemExit("All callers must share the same bounded optional Codecov upload") + checkout = find_step(ci, job_id, "Checkout Code", job_id) + require_equal(checkout, ("with",), {"fetch-depth": "2", "persist-credentials": "false"}, job_id) + module_checks_step = find_step( - ci, "build-and-test", "Run Gradle Checks", "ci workflow" + module_ci, "build-and-test", "Run Gradle Checks", "ci workflow" ) require_equal( module_checks_step, @@ -509,7 +559,7 @@ require_equal( require_equal( ci, ("jobs", "build-and-test", "strategy", "matrix", "include"), - "${{ fromJSON(needs.changes.outputs.module_check_matrix) }}", + "${{ fromJSON(needs.changes.outputs.other_module_check_matrix) }}", "ci workflow", ) matrix_config = value_at(ci, ("jobs", "build-and-test", "strategy", "matrix"), "ci workflow") @@ -553,7 +603,32 @@ for expected in ( '"java-version": 25', ): require_contains(ci_compute_step, ("with", "script"), expected, "ci workflow") -java_setup_step = find_step(ci, "build-and-test", "Set Up Java", "ci workflow") +all_modules = [ + "common-data-runtime", "common-platform-core", "common-saga", "common-temporal", "common-security", + "common-test-support", "common-web-support", "account-service", "automation-scripting-service", + "entity-management-service", "game-design-service", "game-logic-service", "game-session-service", + "logging-admin-service", "social-groups-service", "spring-cloud-gateway", "tcp-proxy-service", + "world-management-service", "hosted-environment-identity-controller", "load-testing", +] +for selected in ([], ["account-service"], ["game-session-service"], + ["account-service", "game-session-service", "common-security"], all_modules): + complete = evaluate_module_check_matrix(ci_compute_step, selected) + split = [] + for _, (output, module) in groups.items(): + require_equal(ci, ("jobs", "changes", "outputs", output), + "${{ steps.compute.outputs." + output + " }}", "ci workflow") + rows = evaluate_module_check_matrix(ci_compute_step, selected, output) + expected = [row for row in complete if (row["module"] == module if module else row["module"] not in {"account-service", "game-session-service"})] + if rows != expected: + raise SystemExit(f"Matrix group {output} changed existing partition identities") + split.extend(rows) + key = lambda row: (row["module"], row["partition"], row["java-version"]) + if sorted(map(key, split)) != sorted(map(key, complete)) or len(set(map(key, split))) != len(complete): + raise SystemExit("Split matrices must preserve exactly the original disjoint work") + if selected == all_modules and len(split) != 26: + raise SystemExit("Complete selection must retain 4 Account + 4 GS + 18 other jobs") + +java_setup_step = find_step(module_ci, "build-and-test", "Set Up Java", "ci workflow") require_equal( java_setup_step, ("with", "java-version"), @@ -562,7 +637,7 @@ require_equal( ) runtime_jar_step = find_step( - ci, "build-and-test", "Build Runtime JAR", "ci workflow" + module_ci, "build-and-test", "Build Runtime JAR", "ci workflow" ) require_equal( runtime_jar_step, @@ -584,7 +659,7 @@ require_equal( ) test_logs_step = find_step( - ci, "build-and-test", "Upload Test Logs if Failed", "ci workflow" + module_ci, "build-and-test", "Upload Test Logs if Failed", "ci workflow" ) require_equal( test_logs_step, @@ -594,7 +669,7 @@ require_equal( ) junit_results_step = find_step( - ci, "build-and-test", "Upload JUnit Test Results", "ci workflow" + module_ci, "build-and-test", "Upload JUnit Test Results", "ci workflow" ) require_equal( junit_results_step, @@ -622,7 +697,7 @@ require_equal( ) slow_partition_artifact_step = find_step( - ci, "build-and-test", + module_ci, "build-and-test", "Upload Slow-Service Partition Reports and Execution Data", "ci workflow", ) @@ -646,7 +721,7 @@ for artifact_path in ( require_contains(slow_partition_artifact_step, ("with", "path"), artifact_path, "ci workflow") gradle_profile_step = find_step( - ci, "build-and-test", "Upload Gradle Task Profile", "ci workflow" + module_ci, "build-and-test", "Upload Gradle Task Profile", "ci workflow" ) require_equal(gradle_profile_step, ("if",), "always()", "ci workflow") require_equal( @@ -663,8 +738,9 @@ for module, job_id, display, prefix in ( ("game-session-service", "game-session-coverage-aggregate", "Game Session", "GAME_SESSION"), ): aggregate_job = value_at(ci, ("jobs", job_id), "ci workflow") - require_equal(aggregate_job, ("needs",), ["changes", "build-and-test"], "ci workflow") - require_contains(aggregate_job, ("if",), "needs.build-and-test.result == 'success'", "ci workflow") + group_id = "build-and-test-" + ("account" if module == "account-service" else "game-session") + require_equal(aggregate_job, ("needs",), ["changes", group_id], "ci workflow") + require_contains(aggregate_job, ("if",), f"needs.{group_id}.result == 'success'", "ci workflow") require_contains( aggregate_job, ("if",), f"contains(fromJSON(needs.changes.outputs.affected_modules || '[]'), '{module}')", @@ -1035,7 +1111,7 @@ try: except (OSError, subprocess.CalledProcessError) as exc: raise SystemExit(f"ci workflow: shared provenance capture fixture failed: {exc}") from exc -coverage_report_step = find_step(ci, "build-and-test", "Upload Coverage Report", "ci workflow") +coverage_report_step = find_step(module_ci, "build-and-test", "Upload Coverage Report", "ci workflow") require_equal( coverage_report_step, ("with", "name"), "jacoco-${{ matrix.module }}-${{ matrix.partition }}-report-${{ github.sha }}-attempt-${{ github.run_attempt }}", @@ -1246,6 +1322,49 @@ gate_enforcement_steps = [ ] if len(gate_enforcement_steps) != 1: raise SystemExit("ci workflow: expected one Validation Gate enforcement step") +# Execute the real enforcement shell with controlled upstream outcomes, without CI or Gradle. +gate = gate_enforcement_steps[0] +for group_id in groups: + require_list_item(ci, ("jobs", "validation-gate", "needs"), group_id, "ci workflow") +for variable, job_id in (("BUILD_AND_TEST", "build-and-test"), + ("BUILD_AND_TEST_ACCOUNT", "build-and-test-account"), + ("BUILD_AND_TEST_GAME_SESSION", "build-and-test-game-session")): + require_equal(gate, ("env", variable), "${{ needs." + job_id + ".result }}", "ci workflow") +require_equal(gate, ("env", "OTHER_MODULES_AFFECTED"), + "${{ needs.changes.outputs.other_module_check_matrix != '[]' }}", "ci workflow") +base_env = {name: "success" for name in gate["env"]} +for name in ("DOCS_CHANGED", "FRONTEND_CHANGED", "PYTHON_CHANGED", "DESIGN_DOCS_CHANGED", + "VALIDATION_PYTHON_CHANGED", "POSTGRES_RUNTIME_PROOF_CHANGED", + "ACCOUNT_MODULE_AFFECTED", "GAME_SESSION_MODULE_AFFECTED", "OTHER_MODULES_AFFECTED"): + base_env[name] = "true" +base_env["LIGHTWEIGHT_ONLY"] = "false" +base_env["AFFECTED_MODULES"] = '["account-service","game-session-service","common-security"]' +def gate_case(changes, expected): + result = subprocess.run(["bash", "-e", "-c", gate["run"]], env={**os.environ, **base_env, **changes}, capture_output=True, text=True) + if (result.returncode == 0) != expected: + raise SystemExit(f"Validation Gate fixture {changes} unexpectedly returned {result.returncode}: {result.stdout} {result.stderr}") +gate_case({}, True) +for flag, result, aggregate in ( + ("OTHER_MODULES_AFFECTED", "BUILD_AND_TEST", None), + ("ACCOUNT_MODULE_AFFECTED", "BUILD_AND_TEST_ACCOUNT", "ACCOUNT_COVERAGE_AGGREGATE"), + ("GAME_SESSION_MODULE_AFFECTED", "BUILD_AND_TEST_GAME_SESSION", "GAME_SESSION_COVERAGE_AGGREGATE"), +): + for outcome in ("failure", "cancelled", "skipped", "timed_out", ""): + gate_case({result: outcome}, False) + unaffected = {flag: "false", result: "skipped"} + if aggregate: + unaffected[aggregate] = "skipped" + for outcome in ("failure", "cancelled", "skipped"): + gate_case({aggregate: outcome}, False) + gate_case(unaffected, True) + gate_case({**unaffected, result: "failure"}, False) +gate_case({"CHANGES_RESULT": "failure"}, False) +gate_case({"WORKFLOW_LINT": "failure"}, False) +gate_case({"OTHER_MODULES_AFFECTED": "false", "ACCOUNT_MODULE_AFFECTED": "false", + "GAME_SESSION_MODULE_AFFECTED": "false", "AFFECTED_MODULES": "[]", + "BUILD_AND_TEST": "skipped", "BUILD_AND_TEST_ACCOUNT": "skipped", + "BUILD_AND_TEST_GAME_SESSION": "skipped", "ACCOUNT_COVERAGE_AGGREGATE": "skipped", + "GAME_SESSION_COVERAGE_AGGREGATE": "skipped"}, True) require_equal( gate_enforcement_steps[0], ("env", "POSTGRES_RUNTIME_PROOF_CHANGED"), diff --git a/dev-tools/tests/ci-validation-summary-contract.sh b/dev-tools/tests/ci-validation-summary-contract.sh index 8891239ad9..31882f64e5 100644 --- a/dev-tools/tests/ci-validation-summary-contract.sh +++ b/dev-tools/tests/ci-validation-summary-contract.sh @@ -37,7 +37,8 @@ expected_markers = { 'Declare Game Session CI partition count: 4': "${{ matrix.module == 'game-session-service' }}", } marker_steps = [ - step for step in ci['jobs']['build-and-test']['steps'] + step for group in ('build-and-test-account', 'build-and-test-game-session') + for step in ci['jobs'][group]['steps'] if step.get('name', '').startswith('Declare ') and 'CI partition count:' in step.get('name', '') ] @@ -343,7 +344,30 @@ async function noWrites(config, reject = false) { const skipped = clone(jobs).filter(x => !x.name.startsWith('Build and Test (')); skipped.find(x => x.name === 'Account Coverage Aggregate').conclusion = 'skipped'; skipped.find(x => x.name === 'Game Session Coverage Aggregate').conclusion = 'skipped'; - skipped.push({ ...row('Build and Test ($' + '{{ matrix.module }} / $' + '{{ matrix.partition }})', 201), conclusion: 'skipped' }); + skipped.push({ ...row('Build and Test ($' + '{{ matrix.module }} / $' + '{{ matrix.partition }})', 201), conclusion: 'skipped', steps: [] }); + const groupPlaceholder = (module, id) => ({ + ...row(`Build and Test (${module} / $` + '{{ matrix.partition }})', id), + conclusion: 'skipped', steps: [], + }); + const allGroupsSkipped = [...clone(skipped), groupPlaceholder('account-service', 202), groupPlaceholder('game-session-service', 203)]; + const groupedSkippedRun = harness({ jobs: allGroupsSkipped }); await groupedSkippedRun.run(); + assert.equal(groupedSkippedRun.calls.creates.length, 1); + // A selected group's real rows may coexist with skipped sibling groups. + const accountOnly = clone(jobs).filter(job => !job.name.startsWith('Build and Test (game-session-service') && job.name !== 'Build and Test (common-security / full)'); + accountOnly.find(job => job.name === 'Game Session Coverage Aggregate').conclusion = 'skipped'; + accountOnly.push(groupPlaceholder('game-session-service', 202), clone(skipped[skipped.length - 1])); + const accountOnlyRun = harness({ jobs: accountOnly }); await accountOnlyRun.run(); + assert.equal(accountOnlyRun.calls.creates.length, 1); + const otherOnly = clone(jobs).filter(job => !job.name.startsWith('Build and Test (account-service') && !job.name.startsWith('Build and Test (game-session-service')); + for (const job of otherOnly.filter(job => job.name.endsWith('Coverage Aggregate'))) job.conclusion = 'skipped'; + otherOnly.push(groupPlaceholder('account-service', 202), groupPlaceholder('game-session-service', 203)); + const otherOnlyRun = harness({ jobs: otherOnly }); await otherOnlyRun.run(); + assert.equal(otherOnlyRun.calls.creates.length, 1); + await noWrites({ jobs: [...clone(jobs), groupPlaceholder('account-service', 202)] }, true); + await noWrites({ jobs: [...clone(allGroupsSkipped), groupPlaceholder('account-service', 204)] }, true); + const executedPlaceholder = clone(allGroupsSkipped); + executedPlaceholder[executedPlaceholder.length - 1].steps = [{name: 'Run checks', conclusion: 'success'}]; + await noWrites({ jobs: executedPlaceholder }, true); const skippedRun = harness({ jobs: skipped }); await skippedRun.run(); assert.match(skippedRun.calls.creates[0].body, /Service build\/test matrix: `skipped`/); assert.match(skippedRun.calls.creates[0].body, /Account coverage aggregation: `skipped`/); diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 2d14445295..776ecec283 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -992,14 +992,16 @@ head, base = os.environ["HEAD_SHA"], os.environ["BASE_SHA"] repo = os.environ["GITHUB_REPOSITORY"] title = f"CI — Validation pr-{os.environ['PR_NUMBER']} base-{base} head-{head}" names = ["Detect CI-Relevant Changes", "GitHub Workflow Lint", "Buf Generation", "Dev Tools README Contract", - "Build and Test ($" + "{{ matrix.module }} / $" + "{{ matrix.partition }})", "Metrics Cardinality Policy Check", "Flyway Migration Sanity Checks", + "Build and Test ($" + "{{ matrix.module }} / $" + "{{ matrix.partition }})", + "Build and Test (account-service / $" + "{{ matrix.partition }})", + "Build and Test (game-session-service / $" + "{{ matrix.partition }})", "Metrics Cardinality Policy Check", "Flyway Migration Sanity Checks", "gRPC Transport Configuration Sanity Checks", "PostgreSQL Runtime Upgrade Proof", "Validate Documentation", "YAML Lint", "Dockerfile Lint", "Helm Render Validation", "Helm Chart Lint", "Python Script Validation", "ShellCheck", "Frontend Checks", "Dev Tool Contract Checks", "Helm Transaction Proof", "Account Coverage Aggregate", "Game Session Coverage Aggregate", "Validation Gate"] def step(name, conclusion): return {"name": name, "status": "completed", "conclusion": conclusion} -# Captured incident shape: 19 existing prerequisite jobs never reached a step; +# Exact split-matrix cancellation shape: 21 prerequisites never reached a step; # both slow-service aggregation prerequisites were skipped without running, # while the always() gate failed only its enforcement step after cancellation. jobs = [{"id": 500 + index, "run_id": 100, "run_attempt": 1, "head_sha": head, @@ -1021,6 +1023,13 @@ gate["steps"] = [step("Set up job", "success"), step("Pre Harden runner", "succe step("Report dependency-deferred required gate", "skipped"), step("Enforce validation success", "failure"), step("Post Harden runner", "success"), step("Complete job", "success")] +if scenario == "cancellation-old-shape": + jobs = [job for job in jobs if job["name"] not in ( + "Build and Test (account-service / $" + "{{ matrix.partition }})", + "Build and Test (game-session-service / $" + "{{ matrix.partition }})")] +if scenario == "cancellation-partial-new-shape": + jobs = [job for job in jobs if job["name"] != + "Build and Test (game-session-service / $" + "{{ matrix.partition }})"] if scenario == "cancellation-real-failure": jobs[1]["conclusion"] = "failure" jobs[1]["steps"] = [step("Run lint", "failure")] @@ -1872,7 +1881,7 @@ for scenario in cancellation-only cancellation-pending cancellation-metadata can echo "cancellation lost missing-proof behavior: $scenario" >&2; exit 1; } done -for scenario in cancellation-later-attempt-failed-source cancellation-real-failure cancellation-hidden-step-failure cancellation-executed-check cancellation-aggregate-executed cancellation-aggregate-failed cancellation-game-session-aggregate-executed cancellation-game-session-aggregate-failed cancellation-gate-other-failure cancellation-unknown-assertion cancellation-timed-out cancellation-action-required cancellation-partial cancellation-wrong-attempt cancellation-wrong-head cancellation-duplicate cancellation-missing-steps cancellation-wrong-app cancellation-check-conflict cancellation-run-conflict; do +for scenario in cancellation-old-shape cancellation-partial-new-shape cancellation-later-attempt-failed-source cancellation-real-failure cancellation-hidden-step-failure cancellation-executed-check cancellation-aggregate-executed cancellation-aggregate-failed cancellation-game-session-aggregate-executed cancellation-game-session-aggregate-failed cancellation-gate-other-failure cancellation-unknown-assertion cancellation-timed-out cancellation-action-required cancellation-partial cancellation-wrong-attempt cancellation-wrong-head cancellation-duplicate cancellation-missing-steps cancellation-wrong-app cancellation-check-conflict cancellation-run-conflict; do output_file="$tmp_dir/$scenario-output" if run_action "$tmp_dir/$scenario-count" none "$scenario" "" "$output_file" >"$tmp_dir/$scenario-log" 2>&1; then echo "cancellation suppressed failed or incomplete proof: $scenario" >&2; exit 1 diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index 81f0415241..7b75580023 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -581,7 +581,9 @@ for job in \ helm-render-validation \ docs-check \ frontend-checks \ - build-and-test; do + build-and-test \ + build-and-test-account \ + build-and-test-game-session; do assert_job_condition ci.yml "$job" "$required_condition" done diff --git a/dev-tools/tests/test_slow_service_ci_partition.py b/dev-tools/tests/test_slow_service_ci_partition.py index 1cb7e0caac..e033df9f0d 100644 --- a/dev-tools/tests/test_slow_service_ci_partition.py +++ b/dev-tools/tests/test_slow_service_ci_partition.py @@ -1047,6 +1047,33 @@ def test_four_way_retry_requires_every_latest_effective_partition(self): with self.assertRaisesRegex(ValueError, f"partition {partition} physical attempt 1 has missing"): PARTITION.resolve_effective_artifacts(missing, module, RUN_ID, SOURCE_SHA, "2") + def test_own_complete_partitions_can_aggregate_before_unrelated_jobs_finish(self): + for module in ("account-service", "game-session-service"): + with self.subTest(module=module): + provenance = make_provenance(module) + latest = provenance["attempts"][-1] + for index, status in enumerate(("queued", "in_progress")): + unrelated = copy.deepcopy(latest["jobs"][0]) + unrelated.update( + id=9000 + index, name=f"Build and Test (unrelated-{index} / full)", + status=status, conclusion=None, completed_at=None, + ) + latest["jobs"].append(unrelated) + latest["total_count"] += 1 + resolved = PARTITION.resolve_effective_artifacts(provenance, module, RUN_ID, SOURCE_SHA, "2") + self.assertEqual(set(resolved["partitions"]), {"1", "2", "3", "4"}) + failed = copy.deepcopy(provenance) + own = next(item for item in failed["attempts"][-1]["jobs"] if item["name"] == f"Build and Test ({module} / 1)") + own["conclusion"] = "failure" + with self.assertRaisesRegex(ValueError, "latest effective.*failure"): + PARTITION.resolve_effective_artifacts(failed, module, RUN_ID, SOURCE_SHA, "2") + missing = copy.deepcopy(provenance) + for attempt in missing["attempts"]: + attempt["jobs"] = [item for item in attempt["jobs"] if item["name"] != f"Build and Test ({module} / 4)"] + attempt["total_count"] = len(attempt["jobs"]) + with self.assertRaisesRegex(ValueError, "partition 4"): + PARTITION.resolve_effective_artifacts(missing, module, RUN_ID, SOURCE_SHA, "2") + def test_four_way_union_and_measured_classes_include_later_partitions(self): module = "game-session-service" plan = make_plan(module) From f5bb2ef542ecbd258f58f21ff3490cc3fccb1e5a Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 8 Nov 2026 19:18:56 +1300 Subject: [PATCH 02/17] Partition World CI checks with complete coverage provenance --- .../actions/check-gradle-module/action.yml | 6 +- .../assess-required-gate.sh | 9 +- .../capture-slow-service-provenance.cjs | 2 +- .github/scripts/run-gradle-module-checks.sh | 7 +- .github/workflows/ci.yml | 173 ++++- .github/workflows/validation-summary.yml | 28 +- build.gradle.kts | 2 +- .../architecture/system-architecture-cicd.md | 12 +- .../tests/ci-lightweight-scope-contract.sh | 55 +- .../tests/ci-validation-summary-contract.sh | 45 +- .../tests/jacoco-combined-report-contract.sh | 15 + .../pr-required-gate-context-contract.sh | 18 +- .../tests/test_slow_service_ci_partition.py | 89 +++ .../slow_service_ci_test_partition.py | 4 +- .../slow_service_ci_test_partition_plan.json | 668 ++++++++++++++++++ 15 files changed, 1073 insertions(+), 60 deletions(-) diff --git a/.github/actions/check-gradle-module/action.yml b/.github/actions/check-gradle-module/action.yml index b053a6c669..ae18897a0f 100644 --- a/.github/actions/check-gradle-module/action.yml +++ b/.github/actions/check-gradle-module/action.yml @@ -52,7 +52,7 @@ runs: echo "::endgroup::" - name: 📦 Build Runtime JAR - if: ${{ contains(fromJSON(inputs.bootable-modules), inputs.module) && (inputs.module != 'account-service' && inputs.module != 'game-session-service' || inputs.partition == '1') }} + if: ${{ contains(fromJSON(inputs.bootable-modules), inputs.module) && (inputs.module != 'account-service' && inputs.module != 'game-session-service' && inputs.module != 'world-management-service' || inputs.partition == '1') }} shell: bash run: ./gradlew --max-workers=2 '-Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8' :${{ inputs.module }}:bootJar -PfullCheck @@ -103,7 +103,7 @@ runs: path: ${{ inputs.module == 'load-testing' && 'dev-tools/load-testing/build/reports/tests/' || format('services/{0}/build/reports/tests/', inputs.module) }} - name: 📤 Upload JUnit Test Results - if: ${{ always() && inputs.module != 'account-service' && inputs.module != 'game-session-service' }} + if: ${{ always() && inputs.module != 'account-service' && inputs.module != 'game-session-service' && inputs.module != 'world-management-service' }} uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: name: junit-${{ inputs.module }}-${{ inputs.partition }}-results-${{ github.sha }}-attempt-${{ github.run_attempt }} @@ -112,7 +112,7 @@ runs: retention-days: 14 - name: 📤 Upload Slow-Service Partition Reports and Execution Data - if: ${{ always() && (inputs.module == 'account-service' || inputs.module == 'game-session-service') }} + if: ${{ always() && (inputs.module == 'account-service' || inputs.module == 'game-session-service' || inputs.module == 'world-management-service') }} uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: name: slow-service-ci-partition-${{ github.run_id }}-${{ github.sha }}-attempt-${{ github.run_attempt }}-${{ inputs.module }}-partition-${{ inputs.partition }} diff --git a/.github/actions/preserve-required-gate/assess-required-gate.sh b/.github/actions/preserve-required-gate/assess-required-gate.sh index ac5be01b50..8f0ea792b8 100644 --- a/.github/actions/preserve-required-gate/assess-required-gate.sh +++ b/.github/actions/preserve-required-gate/assess-required-gate.sh @@ -127,13 +127,14 @@ validation_cancelled_before_checks() { ["Detect CI-Relevant Changes", "GitHub Workflow Lint", "Buf Generation", "Dev Tools README Contract", ("Build and Test ($" + "{{ matrix.module }} / $" + "{{ matrix.partition }})"), ("Build and Test (account-service / $" + "{{ matrix.partition }})"), + ("Build and Test (world-management-service / $" + "{{ matrix.partition }})"), ("Build and Test (game-session-service / $" + "{{ matrix.partition }})"), "Metrics Cardinality Policy Check", "Flyway Migration Sanity Checks", "gRPC Transport Configuration Sanity Checks", "PostgreSQL Runtime Upgrade Proof", "Validate Documentation", "YAML Lint", "Dockerfile Lint", "Helm Render Validation", "Helm Chart Lint", "Python Script Validation", "ShellCheck", "Frontend Checks", "Dev Tool Contract Checks", "Helm Transaction Proof", "Account Coverage Aggregate", - "Game Session Coverage Aggregate", "Validation Gate"] as $names - | type == "array" and length == 1 and .[0].total_count == 24 and (.[0].jobs | type) == "array" and - (.[0].jobs | length) == 24 and ([.[0].jobs[].id] | unique | length) == 24 and + "Game Session Coverage Aggregate", "World Coverage Aggregate", "Validation Gate"] as $names + | type == "array" and length == 1 and .[0].total_count == 26 and (.[0].jobs | type) == "array" and + (.[0].jobs | length) == 26 and ([.[0].jobs[].id] | unique | length) == 26 and ([.[0].jobs[].name] | sort) == ($names | sort) and all(.[0].jobs[]; (.id | type) == "number" and .id > 0 and .id == (.id | floor) and .run_id == $run and .run_attempt == $attempt and .head_sha == $head and .status == "completed" and @@ -147,7 +148,7 @@ validation_cancelled_before_checks() { all(.steps[]; .status == "completed" and (if .name == "Enforce validation success" then .conclusion == "failure" else (.conclusion == "success" or .conclusion == "skipped") end)) - elif (.name == "Account Coverage Aggregate" or .name == "Game Session Coverage Aggregate") then + elif (.name == "Account Coverage Aggregate" or .name == "Game Session Coverage Aggregate" or .name == "World Coverage Aggregate") then (.conclusion == "cancelled" or .conclusion == "skipped") and .steps == [] else .conclusion == "cancelled" and .steps == [] end) ' <<<"${jobs_snapshot}" >/dev/null || return 1 diff --git a/.github/scripts/capture-slow-service-provenance.cjs b/.github/scripts/capture-slow-service-provenance.cjs index 9261a8b733..94a5ee3243 100644 --- a/.github/scripts/capture-slow-service-provenance.cjs +++ b/.github/scripts/capture-slow-service-provenance.cjs @@ -3,7 +3,7 @@ const fs = require("node:fs"); const path = require("node:path"); -const SUPPORTED_MODULES = new Set(["account-service", "game-session-service"]); +const SUPPORTED_MODULES = new Set(["account-service", "game-session-service", "world-management-service"]); const CANONICAL_RUN_NAME = "CI — Validation"; const SHA_PATTERN = /^[0-9a-f]{40}$/; diff --git a/.github/scripts/run-gradle-module-checks.sh b/.github/scripts/run-gradle-module-checks.sh index 51a4be02ec..db34bc1039 100644 --- a/.github/scripts/run-gradle-module-checks.sh +++ b/.github/scripts/run-gradle-module-checks.sh @@ -8,13 +8,14 @@ readonly PARTITION="${2:-full}" if [[ $# -lt 1 || $# -gt 2 || ! "$MODULE" =~ ^[a-z0-9]+(-[a-z0-9]+)*$ || \ ( "$MODULE" == "account-service" && "$PARTITION" != "full" && ! "$PARTITION" =~ ^[1-4]$ ) || \ ( "$MODULE" == "game-session-service" && "$PARTITION" != "full" && ! "$PARTITION" =~ ^[1-4]$ ) || \ - ( "$MODULE" != "account-service" && "$MODULE" != "game-session-service" && $# -eq 2 && "$PARTITION" != "full" ) ]]; then - echo "usage: run-gradle-module-checks.sh [full|partition] (Account: 1-4; Game Session: 1-4)" >&2 + ( "$MODULE" == "world-management-service" && "$PARTITION" != "full" && ! "$PARTITION" =~ ^[1-2]$ ) || \ + ( "$MODULE" != "account-service" && "$MODULE" != "game-session-service" && "$MODULE" != "world-management-service" && $# -eq 2 && "$PARTITION" != "full" ) ]]; then + echo "usage: run-gradle-module-checks.sh [full|partition] (Account: 1-4; Game Session: 1-4; World: 1-2)" >&2 exit 64 fi declare -a CHECK_ARGS=(-PfullCheck) -if [[ ( "$MODULE" == "account-service" || "$MODULE" == "game-session-service" ) && "$PARTITION" != "full" ]]; then +if [[ ( "$MODULE" == "account-service" || "$MODULE" == "game-session-service" || "$MODULE" == "world-management-service" ) && "$PARTITION" != "full" ]]; then SERVICE_DIR="$ROOT_DIR/services/$MODULE" PARTITION_DIR="$SERVICE_DIR/build/slow-service-ci-partition" declare -a PREPARE_TASKS=(":${MODULE}:testClasses") diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b10d815011..e8c9f6c761 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -38,6 +38,7 @@ jobs: other_module_check_matrix: ${{ steps.compute.outputs.other_module_check_matrix }} account_module_check_matrix: ${{ steps.compute.outputs.account_module_check_matrix }} game_session_module_check_matrix: ${{ steps.compute.outputs.game_session_module_check_matrix }} + world_module_check_matrix: ${{ steps.compute.outputs.world_module_check_matrix }} bootable_modules: ${{ steps.compute.outputs.bootable_modules }} docs_changed: ${{ steps.compute.outputs.docs_changed }} frontend_changed: ${{ steps.compute.outputs.frontend_changed }} @@ -149,7 +150,7 @@ jobs: lightweight_only: false, }; } - const slowServicePartitionCounts = { "account-service": 4, "game-session-service": 4 }; + const slowServicePartitionCounts = { "account-service": 4, "game-session-service": 4, "world-management-service": 2 }; outputs.module_check_matrix = outputs.affected_modules.flatMap((module) => slowServicePartitionCounts[module] ? Array.from({ length: slowServicePartitionCounts[module] }, (_, index) => @@ -159,6 +160,7 @@ jobs: outputs.other_module_check_matrix = outputs.module_check_matrix.filter(row => !slowServicePartitionCounts[row.module]); outputs.account_module_check_matrix = outputs.module_check_matrix.filter(row => row.module === "account-service"); outputs.game_session_module_check_matrix = outputs.module_check_matrix.filter(row => row.module === "game-session-service"); + outputs.world_module_check_matrix = outputs.module_check_matrix.filter(row => row.module === "world-management-service"); for (const [name, value] of Object.entries(outputs)) { core.setOutput( name, @@ -1198,6 +1200,46 @@ jobs: - *module-codecov + build-and-test-world: + name: Build and Test (world-management-service / ${{ matrix.partition }}) + needs: [changes] + if: ${{ (github.event_name != 'pull_request' || github.event.action != 'edited' || github.event.changes.base.ref != null) && needs.changes.outputs.world_module_check_matrix != '[]' }} + runs-on: ubuntu-latest + permissions: + contents: read + id-token: write + timeout-minutes: 60 + strategy: + fail-fast: false + matrix: + include: ${{ fromJSON(needs.changes.outputs.world_module_check_matrix) }} + steps: + - name: Harden runner + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + with: + egress-policy: audit + + - name: 'Declare World CI partition count: 2' + if: ${{ matrix.module == 'world-management-service' }} + run: ':' + + - name: ⬇️ Checkout Code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + fetch-depth: 2 + persist-credentials: false + + - name: Validate module and retain proof + if: ${{ always() }} + uses: ./.github/actions/check-gradle-module + with: + module: ${{ matrix.module }} + partition: ${{ matrix.partition }} + java-version: ${{ matrix.java-version }} + bootable-modules: ${{ needs.changes.outputs.bootable_modules }} + + - *module-codecov + account-coverage-aggregate: name: Account Coverage Aggregate needs: [changes, build-and-test-account] @@ -1420,6 +1462,118 @@ jobs: if-no-files-found: error retention-days: 14 + # Final gating and PR reporting + world-coverage-aggregate: + name: World Coverage Aggregate + needs: [changes, build-and-test-world] + if: ${{ (github.event_name != 'pull_request' || github.event.action != 'edited' || github.event.changes.base.ref != null) && contains(fromJSON(needs.changes.outputs.affected_modules || '[]'), 'world-management-service') && needs.build-and-test-world.result == 'success' }} + runs-on: ubuntu-latest + timeout-minutes: 30 + permissions: + actions: read + contents: read + steps: + - name: Harden runner + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + with: + egress-policy: audit + + - name: Check out World source for complete coverage aggregation + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ github.sha }} + fetch-depth: 2 + persist-credentials: false + + - name: 🐍 Set Up Python + uses: ./.github/actions/setup-python + with: + requirements: none + + - name: Capture World partition job and artifact provenance + id: provenance + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + env: + CI_RUN_ID: ${{ github.run_id }} + CI_RUN_ATTEMPT: ${{ github.run_attempt }} + CI_EVENT_NAME: ${{ github.event_name }} + CI_REF_NAME: ${{ github.ref_name }} + CI_SOURCE_SHA: ${{ github.sha }} + CI_NATIVE_HEAD_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }} + CI_PROVENANCE_PATH: services/world-management-service/build/slow-service-ci-partition-provenance.json + CI_MODULE: world-management-service + with: + script: | + const captureSlowServiceProvenance = require( + require("node:path").join(process.env.GITHUB_WORKSPACE, + ".github/scripts/capture-slow-service-provenance.cjs"), + ); + await captureSlowServiceProvenance({ + github, + context, + env: process.env, + module: process.env.CI_MODULE, + }); + + - name: Select World artifacts from latest effective job outcomes + id: selection + env: + PROVENANCE_PATH: services/world-management-service/build/slow-service-ci-partition-provenance.json + SELECTION_PATH: services/world-management-service/build/slow-service-ci-partition-selection.json + run: | + python3 dev-tools/validation/slow_service_ci_test_partition.py select-artifacts \ + --module world-management-service \ + --run-id "$GITHUB_RUN_ID" \ + --source-revision "$GITHUB_SHA" \ + --run-attempt "$GITHUB_RUN_ATTEMPT" \ + --provenance-json "$PROVENANCE_PATH" \ + --selection-json "$SELECTION_PATH" \ + --github-output "$GITHUB_OUTPUT" + + - name: Download all effective World partition artifacts + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 + continue-on-error: true + with: + artifact-ids: ${{ steps.selection.outputs.artifact_ids }} + path: services/world-management-service/build/slow-service-ci-partition-inputs + merge-multiple: false + + - name: Verify complete World partition and report union + run: | + python3 dev-tools/validation/slow_service_ci_test_partition.py verify-aggregate \ + --module world-management-service \ + --input-dir services/world-management-service/build/slow-service-ci-partition-inputs \ + --verified-classes-dir services/world-management-service/build/slow-service-ci-verified-classes \ + --selection-json services/world-management-service/build/slow-service-ci-partition-selection.json \ + --run-id "$GITHUB_RUN_ID" \ + --source-revision "$GITHUB_SHA" \ + --run-attempt "$GITHUB_RUN_ATTEMPT" + + - name: ⚙️ Set Up Java for World Coverage Aggregation + uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6 + with: + distribution: 'temurin' + java-version: 25 + + - name: ⚙️ Set Up Gradle for World Coverage Aggregation + uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6 + with: + build-scan-publish: true + build-scan-terms-of-use-url: 'https://gradle.com/help/legal-terms-of-use' + build-scan-terms-of-use-agree: 'yes' + cache-read-only: false + + - name: Merge complete World JaCoCo coverage + run: ./gradlew --max-workers=2 '-Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8' :world-management-service:jacocoTestReport -PfullCheck -PslowServiceCiCoverageAggregate=world-management-service -PslowServiceCiCoverageClassesDirectory=build/slow-service-ci-verified-classes + + - name: 📤 Upload Complete World Coverage Report + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: jacoco-world-management-service-complete-report-${{ github.sha }}-attempt-${{ github.run_attempt }} + path: services/world-management-service/build/reports/jacoco/test/ + if-no-files-found: error + retention-days: 14 + # Final gating and PR reporting validation-gate: name: Validation Gate @@ -1435,8 +1589,10 @@ jobs: ACCOUNT_MODULE_AFFECTED: ${{ contains(fromJSON(needs.changes.outputs.affected_modules || '[]'), 'account-service') }} ACCOUNT_COVERAGE_AGGREGATE: ${{ needs.account-coverage-aggregate.result }} GAME_SESSION_MODULE_AFFECTED: ${{ contains(fromJSON(needs.changes.outputs.affected_modules || '[]'), 'game-session-service') }} + WORLD_MODULE_AFFECTED: ${{ contains(fromJSON(needs.changes.outputs.affected_modules || '[]'), 'world-management-service') }} GAME_SESSION_COVERAGE_AGGREGATE: ${{ needs.game-session-coverage-aggregate.result }} - needs: [changes, postgres-runtime-upgrade-proof, buf-check, docker-lint, shellcheck, python-script-validation, dev-tool-contract-checks, dev-tools-readme-contract, yaml-lint, metrics-cardinality-check, flyway-migration-sanity-checks, grpc-transport-config-sanity-checks, workflow-lint, helm-lint, helm-render-validation, helm-transaction-proof, docs-check, frontend-checks, build-and-test, build-and-test-account, build-and-test-game-session, account-coverage-aggregate, game-session-coverage-aggregate] + WORLD_COVERAGE_AGGREGATE: ${{ needs.world-coverage-aggregate.result }} + needs: [changes, postgres-runtime-upgrade-proof, buf-check, docker-lint, shellcheck, python-script-validation, dev-tool-contract-checks, dev-tools-readme-contract, yaml-lint, metrics-cardinality-check, flyway-migration-sanity-checks, grpc-transport-config-sanity-checks, workflow-lint, helm-lint, helm-render-validation, helm-transaction-proof, docs-check, frontend-checks, build-and-test, build-and-test-account, build-and-test-game-session, build-and-test-world, account-coverage-aggregate, game-session-coverage-aggregate, world-coverage-aggregate] if: ${{ always() }} steps: - name: Harden runner @@ -1513,7 +1669,9 @@ jobs: ACCOUNT_MODULE_AFFECTED: ${{ env.ACCOUNT_MODULE_AFFECTED }} ACCOUNT_COVERAGE_AGGREGATE: ${{ needs.account-coverage-aggregate.result }} GAME_SESSION_MODULE_AFFECTED: ${{ env.GAME_SESSION_MODULE_AFFECTED }} + WORLD_MODULE_AFFECTED: ${{ env.WORLD_MODULE_AFFECTED }} GAME_SESSION_COVERAGE_AGGREGATE: ${{ needs.game-session-coverage-aggregate.result }} + WORLD_COVERAGE_AGGREGATE: ${{ needs.world-coverage-aggregate.result }} CHANGES_RESULT: ${{ needs.changes.result }} BUF_CHECK: ${{ needs.buf-check.result }} DOCKER_LINT: ${{ needs.docker-lint.result }} @@ -1534,6 +1692,7 @@ jobs: BUILD_AND_TEST: ${{ needs.build-and-test.result }} BUILD_AND_TEST_ACCOUNT: ${{ needs.build-and-test-account.result }} BUILD_AND_TEST_GAME_SESSION: ${{ needs.build-and-test-game-session.result }} + BUILD_AND_TEST_WORLD: ${{ needs.build-and-test-world.result }} OTHER_MODULES_AFFECTED: ${{ needs.changes.outputs.other_module_check_matrix != '[]' }} run: | is_acceptable_optional_result() { @@ -1648,6 +1807,7 @@ jobs: require_matrix_group "Other module matrix" "$OTHER_MODULES_AFFECTED" "$BUILD_AND_TEST" require_matrix_group "Account matrix" "$ACCOUNT_MODULE_AFFECTED" "$BUILD_AND_TEST_ACCOUNT" require_matrix_group "Game Session matrix" "$GAME_SESSION_MODULE_AFFECTED" "$BUILD_AND_TEST_GAME_SESSION" + require_matrix_group "World matrix" "$WORLD_MODULE_AFFECTED" "$BUILD_AND_TEST_WORLD" echo "Account Coverage Aggregate => $ACCOUNT_COVERAGE_AGGREGATE (account-affected=$ACCOUNT_MODULE_AFFECTED)" if [ "$ACCOUNT_MODULE_AFFECTED" = "true" ]; then @@ -1667,6 +1827,15 @@ jobs: failed=1 fi + echo "World Coverage Aggregate => $WORLD_COVERAGE_AGGREGATE (world-affected=$WORLD_MODULE_AFFECTED)" + if [ "$WORLD_MODULE_AFFECTED" = "true" ]; then + if [ "$WORLD_COVERAGE_AGGREGATE" != "success" ]; then + failed=1 + fi + elif [ "$WORLD_COVERAGE_AGGREGATE" != "skipped" ]; then + failed=1 + fi + if [ "$failed" -ne 0 ]; then echo "Validation Gate failed because one or more required validation jobs did not succeed." >&2 exit 1 diff --git a/.github/workflows/validation-summary.yml b/.github/workflows/validation-summary.yml index c3479ddd5b..fbdf6c04bf 100644 --- a/.github/workflows/validation-summary.yml +++ b/.github/workflows/validation-summary.yml @@ -162,10 +162,12 @@ jobs: ["Build and Test ($" + "{{ matrix.module }} / $" + "{{ matrix.partition }})", "other"], ["Build and Test (account-service / $" + "{{ matrix.partition }})", "account-service"], ["Build and Test (game-session-service / $" + "{{ matrix.partition }})", "game-session-service"], + ["Build and Test (world-management-service / $" + "{{ matrix.partition }})", "world-management-service"], ]); const aggregateNames = new Map([ ["account-service", "Account Coverage Aggregate"], ["game-session-service", "Game Session Coverage Aggregate"], + ["world-management-service", "World Coverage Aggregate"], ]); const aggregates = new Map(); for (const [module, name] of aggregateNames) { @@ -182,7 +184,7 @@ jobs: const match = /^Build and Test \(([a-z0-9-]+)(?: \/ (full|[1-4]))?\)$/.exec(job.name || ""); if (match && modules.has(match[1])) { const [, module, partition] = match; - if (partition && (slowServices.has(module) ? !["1", "2", "3", "4"].includes(partition) : partition !== "full")) { + if (partition && (slowServices.has(module) ? !(module === "world-management-service" ? ["1", "2", "full"] : ["1", "2", "3", "4"]).includes(partition) : partition !== "full")) { throw new Error("Invalid module partition: " + job.name); } matrix.push({ job, module, partition: partition || null }); @@ -210,8 +212,8 @@ jobs: // new jobs must not turn a truncated four-way matrix into an apparent old pair. let expectedPartitions = "1,2"; let invalidPlanMarkers = false; - if (slowServices.has(module) && serviceMatrix.some(entry => entry.partition !== null)) { - const moduleLabel = module === "account-service" ? "Account" : "Game Session"; + if (slowServices.has(module) && serviceMatrix.some(entry => entry.partition !== null && entry.partition !== "full")) { + const moduleLabel = module === "account-service" ? "Account" : module === "world-management-service" ? "World" : "Game Session"; const markerPrefix = `Declare ${moduleLabel} CI partition count:`; const markers = serviceMatrix.map(entry => { const steps = entry.job.steps; @@ -219,20 +221,26 @@ jobs: steps.some(step => typeof step?.name !== "string")) return null; return steps.filter(step => step.name.startsWith(markerPrefix)); }); - const fourWay = markers.some(entries => entries?.length > 0); - if (fourWay) { - expectedPartitions = "1,2,3,4"; + if (module === "world-management-service") { invalidPlanMarkers = markers.some(entries => entries?.length !== 1 || - entries[0].name !== `${markerPrefix} 4`); + entries[0].name !== `${markerPrefix} 2`); } else { - invalidPlanMarkers = markers.some(entries => entries === null); + const fourWay = markers.some(entries => entries?.length > 0); + if (fourWay) { + expectedPartitions = "1,2,3,4"; + invalidPlanMarkers = markers.some(entries => entries?.length !== 1 || + entries[0].name !== `${markerPrefix} 4`); + } else { + invalidPlanMarkers = markers.some(entries => entries === null); + } } } const partitioned = !invalidPlanMarkers && serviceMatrix.length === expectedPartitions.split(",").length && serviceMatrix.every(entry => entry.partition !== null) && serviceMatrix.map(entry => entry.partition).sort().join(",") === expectedPartitions; - const legacy = serviceMatrix.length === 1 && serviceMatrix[0].partition === null; + const legacy = serviceMatrix.length === 1 && (serviceMatrix[0].partition === null || + (module === "world-management-service" && serviceMatrix[0].partition === "full")); if (serviceMatrix.length > 0 && !partitioned && !legacy) invalidSlowServiceMatrix = true; if (partitioned && ( !aggregate || @@ -268,7 +276,7 @@ jobs: for (const [module, aggregate] of aggregates) { const label = module === "account-service" ? "Account coverage aggregation" - : "Game Session coverage aggregation"; + : module === "world-management-service" ? "World coverage aggregation" : "Game Session coverage aggregation"; validationChecks.push([label, aggregate.conclusion]); } if (validationChecks.some(([, result]) => result === "neutral")) throw new Error("Unexpected neutral Validation job"); diff --git a/build.gradle.kts b/build.gradle.kts index 718dc60535..63e88cd1d0 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -91,7 +91,7 @@ tasks.register("compileBufGeneratedJava") { } val fullCheck = project.hasProperty("fullCheck") || System.getenv("CI") != null -val slowServiceCiPartitionCounts = mapOf("account-service" to 4, "game-session-service" to 4) +val slowServiceCiPartitionCounts = mapOf("account-service" to 4, "game-session-service" to 4, "world-management-service" to 2) val slowServiceCiModules = slowServiceCiPartitionCounts.keys val slowServiceCiPartition = providers.gradleProperty("slowServiceCiPartition").orNull val slowServiceCiPartitionModule = providers.gradleProperty("slowServiceCiPartitionModule").orNull diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index ba530c6ca5..b7d1cfdc83 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -34,7 +34,7 @@ The manual [Game Session factory inventory qualification workflow](../../.github ## Required Gate Preservation -The Validation, Security, CodeQL, License, and Smoke gates retain their exact branch-protection names. A metadata-only pull-request edit reuses proof only through the shared preservation action, which validates the owning workflow and repository, pull-request event, canonical PR/base/head run title, check/job identity, and substantive preservation-step state. Fork heads remain supported, including empty GitHub PR associations when the exact canonical title supplies attribution. Completed metadata preservation checks never become original proof. A newer completed substantive failure defeats an older success. A failed Validation aggregate from a cancelled workflow is missing proof only for the narrowly recognized pre-execution cancellation shape: the complete exact-attempt native snapshot contains the known gate and all twenty-three prerequisite jobs, including the three distinct other-module, Account and Game Session Build and Test matrix placeholders and both Account Coverage Aggregate and Game Session Coverage Aggregate jobs; every prerequisite is cancelled without executed steps, except that either coverage aggregate may be skipped without steps; and the gate failed only Enforce validation success. The assessor independently binds the attempt, job identities and native Actions checks before excluding that cancellation artifact from authoritative failures. Historical single-matrix inventories do not qualify for this exception; incomplete current inventories cannot fall back to that older shape. A cancelled workflow alone is insufficient; executed prerequisite steps, failed or timed-out assertions, unknown outcomes, incomplete evidence and conflicting identities retain fail-closed failure. Existing selection then uses other original proof or emits dependency deferral; cancellation never supplies success or broadens automatic rerun eligibility. +The Validation, Security, CodeQL, License, and Smoke gates retain their exact branch-protection names. A metadata-only pull-request edit reuses proof only through the shared preservation action, which validates the owning workflow and repository, pull-request event, canonical PR/base/head run title, check/job identity, and substantive preservation-step state. Fork heads remain supported, including empty GitHub PR associations when the exact canonical title supplies attribution. Completed metadata preservation checks never become original proof. A newer completed substantive failure defeats an older success. A failed Validation aggregate from a cancelled workflow is missing proof only for the narrowly recognized pre-execution cancellation shape: the complete exact-attempt native snapshot contains the known gate and all twenty-five prerequisite jobs, including the four distinct other-module, Account, Game Session, and World Build and Test matrix placeholders and the Account, Game Session, and World Coverage Aggregate jobs; every prerequisite is cancelled without executed steps, except that any coverage aggregate may be skipped without steps; and the gate failed only Enforce validation success. The assessor independently binds the attempt, job identities and native Actions checks before excluding that cancellation artifact from authoritative failures. Historical single-matrix inventories do not qualify for this exception; incomplete current inventories cannot fall back to that older shape. A cancelled workflow alone is insufficient; executed prerequisite steps, failed or timed-out assertions, unknown outcomes, incomplete evidence and conflicting identities retain fail-closed failure. Existing selection then uses other original proof or emits dependency deferral; cancellation never supplies success or broadens automatic rerun eligibility. A supplementary Commit Status with the same required gate name may withhold an otherwise successful native Actions CheckRun. Both must succeed when both exist; the native app-pinned CheckRun remains mandatory, and a status creator, actor name, or URL cannot establish App authority. The controller independently evaluates that native proof and all exact-head same-name status barriers, including foreign barriers. A status success alone never supplies required native proof. @@ -68,7 +68,7 @@ Account Service and Game Session validation each use four independent matrix par Workflows live in the `.github/workflows/` directory. A typical pipeline runs on every pull request and on pushes to the long-lived publication branches (`develop` today, and `main` for release-oriented publication paths). -The optional Validation Summary publishes from a trusted default-branch completion callback, outside the original Validation workflow, so comment scheduling cannot delay required-gate resolution. It reconstructs the existing summary from complete exact-attempt job evidence after checking the source workflow/repository and canonical title’s PR number, base SHA, and head SHA against the current PR. It recognizes source-qualified Build and Test module/partition inventories and requires the complete selected partition set and matching aggregate for each affected Account or Game Session module, while retaining attributable older two-partition and unpartitioned source runs. This optional reporter accepts native empty PR-association arrays; absent, malformed, conflicting, or ambiguous associations cannot publish. With an empty array the historical source base ref remains unknown: the first fresh exact-SHA PR read instead pins the current base ref as a publication fence, rechecked before every write. An available association must agree with the title and current PR; required-gate provenance selectors remain unchanged. It executes no PR code or artifacts and retains only Actions read and PR comment-write permissions. Metadata-only, fork, bot, cancelled, closed, stale, and incomplete sources cannot publish; legacy sources retaining their inline Validation Summary remain solely owned by that inline job until their next normal base carry. The reporter bounds API time and pagination and rechecks the source and PR before each comment write. Native callback execution and timing improvement remain unproved until default-branch deployment and hosted proof. +The optional Validation Summary publishes from a trusted default-branch completion callback, outside the original Validation workflow, so comment scheduling cannot delay required-gate resolution. It reconstructs the existing summary from complete exact-attempt job evidence after checking the source workflow/repository and canonical title’s PR number, base SHA, and head SHA against the current PR. It recognizes source-qualified Build and Test module/partition inventories and requires the complete selected partition set and matching aggregate for each affected Account, Game Session, or World Management module. World requires its native two-partition declaration; historical World full-check jobs remain valid without an aggregate. Account and Game Session retain attributable older two-partition and unpartitioned source runs. This optional reporter accepts native empty PR-association arrays; absent, malformed, conflicting, or ambiguous associations cannot publish. With an empty array the historical source base ref remains unknown: the first fresh exact-SHA PR read instead pins the current base ref as a publication fence, rechecked before every write. An available association must agree with the title and current PR; required-gate provenance selectors remain unchanged. It executes no PR code or artifacts and retains only Actions read and PR comment-write permissions. Metadata-only, fork, bot, cancelled, closed, stale, and incomplete sources cannot publish; legacy sources retaining their inline Validation Summary remain solely owned by that inline job until their next normal base carry. The reporter bounds API time and pagination and rechecks the source and PR before each comment write. Native callback execution and timing improvement remain unproved until default-branch deployment and hosted proof. The optional [Static Analysis Summary](../../.github/workflows/static-analysis-summary.yml) takes one bounded snapshot on each CodeQL or License completion, showing a pending counterpart honestly and updating the same bot comment when its completion arrives. Serialization uses branch and immutable head SHA so superseded heads cannot evict current-head pending callbacks. An older-base callback for the same head is only a wake signal: it validates its source identity and selects exact current-base/head workflow and check proof before publishing. Current-PR fences and duplicate cleanup remain mandatory; callback cancellation, unavailable API evidence, and the non-atomic final read/write do not establish guaranteed delivery. Required gates are independent of this optional comment. @@ -108,11 +108,11 @@ The main [`ci.yml`](../../.github/workflows/ci.yml) workflow: - Generates protobuf outputs to keep generated stubs aligned with the checked-in schemas. - Runs formatting and lint steps (Spotless, markdownlint, link checks). -- On the complete CI path, executes a matrix of Gradle `check` tasks for affected microservices with SpotBugs, Checkstyle, and tests enabled. Account Service and Game Session each use four complete-check partitions; other modules remain one check per affected module. Lightweight documentation-only PR validation does not run these service checks. +- On the complete CI path, executes a matrix of Gradle `check` tasks for affected microservices with SpotBugs, Checkstyle, and tests enabled. Account Service and Game Session each use four complete-check partitions, and World Management uses two; other modules remain one check per affected module. Lightweight documentation-only PR validation does not run these service checks. - Affected-module checks and the source-built Compose boot-jar command first use Gradle's restored dependency metadata without a forced refresh. The shared runner gives a fully recognized repository-resolution failure one retry of the same complete Gradle command with `--refresh-dependencies`; successful commands do not revalidate every dependency. The existing pre-substantive compile/test boundary remains. jOOQ also permits only the exact matching `jooqCodegen` classpath-resolution failure, including Gradle's `generateJooq FAILED` task wrapper when the failure prevents the JavaExec generator from launching. The configuration-cache wrapper remains retryable only before `generateJooq` starts. Genuine JavaExec, code-generation, SQL, compiler, test, mixed, unknown, interrupted, or unrelated configuration failures retain their original failure. -- On the complete CI path, preserves every service test task and JaCoCo execution. Each Account Service and Game Session partition uploads its report to Codecov using GitHub OIDC; a separate read-only aggregate verifies every module partition’s selectors and JUnit results, then merges execution data from unit and every available categorized integration/cross-service task into the complete service report. Other modules retain one report from their module check; modules without categorized tests retain their unit-only report. Production classes remain in reports rather than being excluded to improve percentages. Lightweight documentation-only PR validation does not run these service checks or coverage reports. Account and Game Session validation use disjoint four-partition matrix jobs, with remaining modules in a third matrix and one shared module-validation recipe. Each service aggregate waits only for its own successful matrix. The final Validation Gate requires every selected matrix group and its applicable aggregate; an unaffected group may skip, but a selected skipped, cancelled or failed group cannot pass. -- Retains Gradle JUnit XML results from each affected-module `check`, including unit and categorized integration/cross-service outcomes, for 14 days. Account and Game Session retain them with their complete partition evidence in `slow-service-ci-partition---attempt---partition-`; other modules use `junit---results--attempt-`. Including the attempt keeps partial workflow reruns from colliding with earlier artifacts. The load-testing matrix entry uses its `dev-tools/load-testing` output; missing XML is reported as a warning so artifact retention does not change the test gate. -- Runs the existing module check with Gradle's native `--profile`; Account and Game Session partition jobs also profile their existing test-class preparation invocation before class selection. The workflow retains `build/reports/profile/` from the repository root as `gradle-profile----attempt-` for 14 days, including profiles from both invocations when present. These reports expose startup, configuration, dependency and task durations. Profiling does not change the selected checks or recovery behavior; fork concurrency remains controlled by the task configuration above. Missing reports warn rather than supplying timing evidence; cancelled or early-failed runs may not produce a report. Parallel task durations can overlap and must not be summed as elapsed time; JUnit results remain the separate source for individual test costs. +- On the complete CI path, preserves every service test task and JaCoCo execution. Each Account Service, Game Session, and World Management partition uploads its report to Codecov using GitHub OIDC; a separate read-only aggregate verifies every module partition’s selectors and JUnit results, then merges execution data from unit and every available categorized integration/cross-service task into the complete service report. Other modules retain one report from their module check; modules without categorized tests retain their unit-only report. Production classes remain in reports rather than being excluded to improve percentages. Lightweight documentation-only PR validation does not run these service checks or coverage reports. Account and Game Session validation use disjoint four-partition matrix jobs, World Management uses a two-partition matrix, with remaining modules in a fourth matrix and one shared module-validation recipe. Each service aggregate waits only for its own successful matrix. World partitions balance measured whole-class costs across unit, integration, and cross-service tasks collectively; nested classes stay with their enclosing class, and newly compiled classes receive deterministic assignments. Only partition 1 builds the runtime JAR. Additional runner admission, compilation, and aggregation overhead must be measured before claiming elapsed-time savings. The final Validation Gate requires every selected matrix group and its applicable aggregate; an unaffected group may skip, but a selected skipped, cancelled or failed group cannot pass. +- Retains Gradle JUnit XML results from each affected-module `check`, including unit and categorized integration/cross-service outcomes, for 14 days. Account, Game Session, and World Management retain them with their complete partition evidence in `slow-service-ci-partition---attempt---partition-`; other modules use `junit---results--attempt-`. Including the attempt keeps partial workflow reruns from colliding with earlier artifacts. The load-testing matrix entry uses its `dev-tools/load-testing` output; missing XML is reported as a warning so artifact retention does not change the test gate. +- Runs the existing module check with Gradle's native `--profile`; Account, Game Session, and World Management partition jobs also profile their existing test-class preparation invocation before class selection. The workflow retains `build/reports/profile/` from the repository root as `gradle-profile----attempt-` for 14 days, including profiles from both invocations when present. These reports expose startup, configuration, dependency and task durations. Profiling does not change the selected checks or recovery behavior; fork concurrency remains controlled by the task configuration above. Missing reports warn rather than supplying timing evidence; cancelled or early-failed runs may not produce a report. Parallel task durations can overlap and must not be summed as elapsed time; JUnit results remain the separate source for individual test costs. - Failed Java compile tasks additionally retain bounded generated Java, proto, and build/version inputs with hashes and an omissions manifest in the existing per-module profile artifact. The same collector covers the source-built Compose all-eleven-service `bootJar` boundary in `dev-tools/build-compose-service-jars.sh`, using a distinct invocation directory under `build/reports/compile-failure/runtime-bootjar/`. The read-only `pr-local-smoke` job retains only that invocation's evidence on build failure as `runtime-bootjar-compile-failure--attempt-` for three days; missing evidence warns and upload failure cannot replace the build result. Native `--info` compiler identity lines come from the original check or boot-jar build; a separate offline diagnostic records Gradle/JVM identity, compiler selection and ordered compile classpath paths/lengths without copying JARs. Diagnostic selection is explicitly post-failure and cannot establish the original executed compiler or dependency bytes. Diagnostics use the canonical locked Gradle wrapper, retaining local resource admission, verified inherited leases, and its existing CI bypass. Collection is limited to four failed tasks, 512 input files, 2 MiB per input, 16 MiB total inputs, 4096 visited directory entries across source enumeration, a 16 MiB streamed log tail, and 60 seconds per diagnostic; symlink paths are rejected. Source enumeration and diagnostic output limits report possible truncation, including an exactly full diagnostic output. Live output is forwarded while only the bounded log tail is buffered for capture; capture/forwarding failures still drain the original output. Missing facts and diagnostic failure remain explicit. Missing boot-jar capture scratch runs the original build once without evidence. Success, failures without a failed Java compile task, and cancellation/signal exits (128 or above) produce no compile-failure evidence; cancellation/signal exits skip diagnostics. A failed `compileJava` task may retain evidence even when the failure comes from classpath or dependency resolution rather than compiler diagnostics. Collection never retries compilation or tests, changes dependency recovery, or replaces the original exit. No environment dump, credentials, whole cache, or unrelated workspace data is retained. - Uses Node 24 to lint OpenAPI specs, run React linters, and execute an accessibility audit using headless Chrome. - Validates tracked Bash scripts across the repository with ShellCheck and validates every tracked Python script with `py_compile` plus repository-wide Ruff linting. diff --git a/dev-tools/tests/ci-lightweight-scope-contract.sh b/dev-tools/tests/ci-lightweight-scope-contract.sh index f8afc662ac..9c811d76f6 100644 --- a/dev-tools/tests/ci-lightweight-scope-contract.sh +++ b/dev-tools/tests/ci-lightweight-scope-contract.sh @@ -35,7 +35,7 @@ for expected in \ 'declare -a PREPARE_TASKS=(":${MODULE}:testClasses")' \ 'PREPARE_TASKS+=(":${MODULE}:${task_name}Classes")' \ 'CHECK_ARGS+=("-PslowServiceCiPartitionModule=$MODULE" "-PslowServiceCiPartition=$PARTITION")' \ - 'Account: 1-4; Game Session: 1-4' \ + 'Account: 1-4; Game Session: 1-4; World: 1-2' \ 'bash "$ROOT_DIR/dev-tools/validation/run-gradle-with-dependency-recovery.sh"'; do require_contains "$MODULE_CHECK_WRAPPER" "$expected" done @@ -100,7 +100,7 @@ raise SystemExit(0) ("account-service", str(partition)) for partition in range(1, 5) ] + [ ("game-session-service", str(partition)) for partition in range(1, 5) - ] + ] + [("world-management-service", str(partition)) for partition in range(1, 3)] for module, partition in partitioned_cases: result, entries = invoke(module, partition) if result.returncode != 0: @@ -135,7 +135,7 @@ raise SystemExit(0) if "-PfullCheck" not in check or any(value not in check for value in expected_check_properties): raise SystemExit(f"{module}/{partition} lost its full-check selector arguments") - for module in ("account-service", "game-session-service", "common-security"): + for module in ("account-service", "game-session-service", "world-management-service", "common-security"): result, entries = invoke(module, "full") if result.returncode != 0: raise SystemExit(f"full check entrypoint rejected {module}: {result.stderr}") @@ -153,6 +153,8 @@ raise SystemExit(0) ("account-service", "5"), ("game-session-service", "0"), ("game-session-service", "5"), + ("world-management-service", "0"), + ("world-management-service", "3"), ("common-security", "3"), ("bad_module", "full"), ): @@ -234,7 +236,7 @@ process.stdout.write(JSON.stringify(rows)); "modules": modules, "assignment": match.group(0).strip(), "partition_set": partition_set.group(0).strip(), - "groups": "\n".join(re.findall(r"(?m)^.*outputs\.(?:other|account|game_session)_module_check_matrix = .*;$", script)), + "groups": "\n".join(re.findall(r"(?m)^.*outputs\.(?:other|account|game_session|world)_module_check_matrix = .*;$", script)), "output": output, }), ) @@ -513,12 +515,13 @@ groups = { "build-and-test": ("other_module_check_matrix", None), "build-and-test-account": ("account_module_check_matrix", "account-service"), "build-and-test-game-session": ("game_session_module_check_matrix", "game-session-service"), + "build-and-test-world": ("world_module_check_matrix", "world-management-service"), } for job_id, (output, module) in groups.items(): job = ci["jobs"][job_id] name_module = module or "${{ matrix.module }}" require_equal(job, ("name",), "Build and Test (" + name_module + " / ${{ matrix.partition }})", job_id) - timeout = "60" if module == "account-service" else "90" if module == "game-session-service" else "${{ matrix.module == 'world-management-service' && 60 || matrix.module == 'game-design-service' && 30 || 20 }}" + timeout = "60" if module in ("account-service", "world-management-service") else "90" if module == "game-session-service" else "${{ matrix.module == 'world-management-service' && 60 || matrix.module == 'game-design-service' && 30 || 20 }}" require_equal(job, ("timeout-minutes",), timeout, job_id) require_equal(job, ("needs",), ["changes"], job_id) require_equal(job, ("strategy", "fail-fast"), "false", job_id) @@ -593,7 +596,7 @@ require_contains( require_contains( ci_compute_step, ("with", "script"), - 'const slowServicePartitionCounts = { "account-service": 4, "game-session-service": 4 };', + 'const slowServicePartitionCounts = { "account-service": 4, "game-session-service": 4, "world-management-service": 2 };', "ci workflow", ) for expected in ( @@ -610,7 +613,7 @@ all_modules = [ "logging-admin-service", "social-groups-service", "spring-cloud-gateway", "tcp-proxy-service", "world-management-service", "hosted-environment-identity-controller", "load-testing", ] -for selected in ([], ["account-service"], ["game-session-service"], +for selected in ([], ["account-service"], ["game-session-service"], ["world-management-service"], ["account-service", "game-session-service", "common-security"], all_modules): complete = evaluate_module_check_matrix(ci_compute_step, selected) split = [] @@ -618,15 +621,15 @@ for selected in ([], ["account-service"], ["game-session-service"], require_equal(ci, ("jobs", "changes", "outputs", output), "${{ steps.compute.outputs." + output + " }}", "ci workflow") rows = evaluate_module_check_matrix(ci_compute_step, selected, output) - expected = [row for row in complete if (row["module"] == module if module else row["module"] not in {"account-service", "game-session-service"})] + expected = [row for row in complete if (row["module"] == module if module else row["module"] not in {"account-service", "game-session-service", "world-management-service"})] if rows != expected: raise SystemExit(f"Matrix group {output} changed existing partition identities") split.extend(rows) key = lambda row: (row["module"], row["partition"], row["java-version"]) if sorted(map(key, split)) != sorted(map(key, complete)) or len(set(map(key, split))) != len(complete): raise SystemExit("Split matrices must preserve exactly the original disjoint work") - if selected == all_modules and len(split) != 26: - raise SystemExit("Complete selection must retain 4 Account + 4 GS + 18 other jobs") + if selected == all_modules and len(split) != 27: + raise SystemExit("Complete selection must retain 4 Account + 4 GS + 2 World + 17 other jobs") java_setup_step = find_step(module_ci, "build-and-test", "Set Up Java", "ci workflow") require_equal( @@ -642,7 +645,7 @@ runtime_jar_step = find_step( require_equal( runtime_jar_step, ("if",), - "${{ contains(fromJSON(needs.changes.outputs.bootable_modules), matrix.module) && (matrix.module != 'account-service' && matrix.module != 'game-session-service' || matrix.partition == '1') }}", + "${{ contains(fromJSON(needs.changes.outputs.bootable_modules), matrix.module) && (matrix.module != 'account-service' && matrix.module != 'game-session-service' && matrix.module != 'world-management-service' || matrix.partition == '1') }}", "ci workflow", ) require_equal( @@ -674,7 +677,7 @@ junit_results_step = find_step( require_equal( junit_results_step, ("if",), - "${{ always() && matrix.module != 'account-service' && matrix.module != 'game-session-service' }}", + "${{ always() && matrix.module != 'account-service' && matrix.module != 'game-session-service' && matrix.module != 'world-management-service' }}", "ci workflow", ) require_equal( @@ -703,7 +706,7 @@ slow_partition_artifact_step = find_step( ) require_equal( slow_partition_artifact_step, ("if",), - "${{ always() && (matrix.module == 'account-service' || matrix.module == 'game-session-service') }}", + "${{ always() && (matrix.module == 'account-service' || matrix.module == 'game-session-service' || matrix.module == 'world-management-service') }}", "ci workflow", ) require_equal( @@ -736,9 +739,10 @@ require_equal(gradle_profile_step, ("with", "retention-days"), "14", "ci workflo for module, job_id, display, prefix in ( ("account-service", "account-coverage-aggregate", "Account", "ACCOUNT"), ("game-session-service", "game-session-coverage-aggregate", "Game Session", "GAME_SESSION"), + ("world-management-service", "world-coverage-aggregate", "World", "WORLD"), ): aggregate_job = value_at(ci, ("jobs", job_id), "ci workflow") - group_id = "build-and-test-" + ("account" if module == "account-service" else "game-session") + group_id = "build-and-test-" + ("account" if module == "account-service" else "world" if module == "world-management-service" else "game-session") require_equal(aggregate_job, ("needs",), ["changes", group_id], "ci workflow") require_contains(aggregate_job, ("if",), f"needs.{group_id}.result == 'success'", "ci workflow") require_contains( @@ -824,6 +828,7 @@ capture_scripts = [] for module, job_id, display in ( ("account-service", "account-coverage-aggregate", "Account"), ("game-session-service", "game-session-coverage-aggregate", "Game Session"), + ("world-management-service", "world-coverage-aggregate", "World"), ): capture = find_step( ci, job_id, f"Capture {display} partition job and artifact provenance", "ci workflow" @@ -838,8 +843,8 @@ const owner = "example", repository = "firemud", runId = 70; const testedMerge = "a".repeat(40), nativeHead = "b".repeat(40), baseSha = "c".repeat(40); const wrongSha = "d".repeat(40); const repositoryFullName = `${owner}/${repository}`; -const coreJobRows = ["account-service", "game-session-service"].flatMap((module, index) => - Array.from({ length: 4 }, (_, index) => index + 1).map(partition => ({ +const coreJobRows = ["account-service", "game-session-service", "world-management-service"].flatMap((module, index) => + Array.from({ length: module === "world-management-service" ? 2 : 4 }, (_, index) => index + 1).map(partition => ({ id: 100 + index * 10 + partition, run_id: runId, head_sha: nativeHead, name: `Build and Test (${module} / ${partition})`, status: "completed", conclusion: "success", started_at: "2026-10-30T01:00:00Z", @@ -851,8 +856,8 @@ const jobRows = coreJobRows.concat(Array.from({ length: 97 }, (_, index) => ({ name: `Unrelated completed job ${index}`, status: "completed", conclusion: "success", started_at: "2026-10-30T01:00:00Z", completed_at: "2026-10-30T02:00:00Z", }))); -const coreArtifactRows = ["account-service", "game-session-service"].flatMap((module, index) => - Array.from({ length: 4 }, (_, index) => index + 1).map(partition => ({ +const coreArtifactRows = ["account-service", "game-session-service", "world-management-service"].flatMap((module, index) => + Array.from({ length: module === "world-management-service" ? 2 : 4 }, (_, index) => index + 1).map(partition => ({ id: 700 + index * 10 + partition, name: `slow-service-ci-partition-${runId}-${testedMerge}-attempt-1-${module}-partition-${partition}`, expired: false, size_in_bytes: 1024, created_at: "2026-10-30T02:00:00Z", @@ -984,8 +989,8 @@ async function runFor(embedded, options = {}) { } (async () => { - assert.equal(jobRows.length, 105); - assert.equal(artifactRows.length, 105); + assert.equal(jobRows.length, 107); + assert.equal(artifactRows.length, 107); for (const embedded of input.scripts) { assert.ok(embedded.script.includes("capture-slow-service-provenance.cjs")); assert.ok(embedded.script.includes("module: process.env.CI_MODULE")); @@ -1073,7 +1078,7 @@ async function runFor(embedded, options = {}) { { label: "wrong attempt", options: { eventName: "pull_request", runAttempt: 1, apiRunAttempt: 2 } }, { label: "wrong repository", options: { eventName: "pull_request", runRepository: "other/repository" } }, { label: "wrong dispatch title", options: { eventName: "workflow_dispatch", refName: "release/2026", runName: "CI — Validation develop" } }, - { label: "unsupported module", options: { eventName: "pull_request", module: "world-management-service" } }, + { label: "unsupported module", options: { eventName: "pull_request", module: "unsupported-service" } }, ]; for (const { label, options } of wrongIdentityCases) { const result = await runFor(embedded, options); @@ -1157,7 +1162,7 @@ if re.findall(r"options\.release\.set\((\d+)\)", gradle_build) != ["25", "25"]: buf_java_setup = find_step(ci, "buf-check", "Set up Java for remote generator compatibility proof", "ci workflow") require_equal(buf_java_setup, ("with", "java-version"), "25", "ci workflow") for expected in ( - 'val slowServiceCiPartitionCounts = mapOf("account-service" to 4, "game-session-service" to 4)', + 'val slowServiceCiPartitionCounts = mapOf("account-service" to 4, "game-session-service" to 4, "world-management-service" to 2)', 'providers.gradleProperty("slowServiceCiPartitionModule").orNull', 'if ((slowServiceCiPartition == null) != (slowServiceCiPartitionModule == null))', 'slowServiceCiPartitionCounts[slowServiceCiPartitionModule]', @@ -1328,14 +1333,15 @@ for group_id in groups: require_list_item(ci, ("jobs", "validation-gate", "needs"), group_id, "ci workflow") for variable, job_id in (("BUILD_AND_TEST", "build-and-test"), ("BUILD_AND_TEST_ACCOUNT", "build-and-test-account"), - ("BUILD_AND_TEST_GAME_SESSION", "build-and-test-game-session")): + ("BUILD_AND_TEST_GAME_SESSION", "build-and-test-game-session"), + ("BUILD_AND_TEST_WORLD", "build-and-test-world")): require_equal(gate, ("env", variable), "${{ needs." + job_id + ".result }}", "ci workflow") require_equal(gate, ("env", "OTHER_MODULES_AFFECTED"), "${{ needs.changes.outputs.other_module_check_matrix != '[]' }}", "ci workflow") base_env = {name: "success" for name in gate["env"]} for name in ("DOCS_CHANGED", "FRONTEND_CHANGED", "PYTHON_CHANGED", "DESIGN_DOCS_CHANGED", "VALIDATION_PYTHON_CHANGED", "POSTGRES_RUNTIME_PROOF_CHANGED", - "ACCOUNT_MODULE_AFFECTED", "GAME_SESSION_MODULE_AFFECTED", "OTHER_MODULES_AFFECTED"): + "ACCOUNT_MODULE_AFFECTED", "GAME_SESSION_MODULE_AFFECTED", "WORLD_MODULE_AFFECTED", "OTHER_MODULES_AFFECTED"): base_env[name] = "true" base_env["LIGHTWEIGHT_ONLY"] = "false" base_env["AFFECTED_MODULES"] = '["account-service","game-session-service","common-security"]' @@ -1348,6 +1354,7 @@ for flag, result, aggregate in ( ("OTHER_MODULES_AFFECTED", "BUILD_AND_TEST", None), ("ACCOUNT_MODULE_AFFECTED", "BUILD_AND_TEST_ACCOUNT", "ACCOUNT_COVERAGE_AGGREGATE"), ("GAME_SESSION_MODULE_AFFECTED", "BUILD_AND_TEST_GAME_SESSION", "GAME_SESSION_COVERAGE_AGGREGATE"), + ("WORLD_MODULE_AFFECTED", "BUILD_AND_TEST_WORLD", "WORLD_COVERAGE_AGGREGATE"), ): for outcome in ("failure", "cancelled", "skipped", "timed_out", ""): gate_case({result: outcome}, False) diff --git a/dev-tools/tests/ci-validation-summary-contract.sh b/dev-tools/tests/ci-validation-summary-contract.sh index 31882f64e5..b0f759a37c 100644 --- a/dev-tools/tests/ci-validation-summary-contract.sh +++ b/dev-tools/tests/ci-validation-summary-contract.sh @@ -35,9 +35,10 @@ if '${{ needs.' in script or 'downloadArtifact' in script: expected_markers = { 'Declare Account CI partition count: 4': "${{ matrix.module == 'account-service' }}", 'Declare Game Session CI partition count: 4': "${{ matrix.module == 'game-session-service' }}", + 'Declare World CI partition count: 2': "${{ matrix.module == 'world-management-service' }}", } marker_steps = [ - step for group in ('build-and-test-account', 'build-and-test-game-session') + step for group in ('build-and-test-account', 'build-and-test-game-session', 'build-and-test-world') for step in ci['jobs'][group]['steps'] if step.get('name', '').startswith('Declare ') and 'CI partition count:' in step.get('name', '') @@ -75,7 +76,7 @@ const pr = { base: { ref: 'develop', sha: base, repo: { full_name: repository } }, }; const row = (name, id) => ({ id, name, run_id: 70, run_attempt: 1, head_sha: head, status: 'completed', conclusion: 'success', steps: [{ name: 'Harden runner', status: 'completed', conclusion: 'success' }] }); -const jobs = payload.names.filter(name => !name.includes('${{')).map((name, i) => row(name, i + 1)); +const jobs = payload.names.filter(name => !name.includes('${{') && name !== 'World Coverage Aggregate').map((name, i) => row(name, i + 1)); jobs.push( row('Build and Test (account-service / 1)', 90), row('Build and Test (account-service / 2)', 92), @@ -373,6 +374,46 @@ async function noWrites(config, reject = false) { assert.match(skippedRun.calls.creates[0].body, /Account coverage aggregation: `skipped`/); assert.match(skippedRun.calls.creates[0].body, /Game Session coverage aggregation: `skipped`/); + // Historical World full jobs remain valid without a partition aggregate. + for (const name of ['Build and Test (world-management-service)', 'Build and Test (world-management-service / full)']) { + const historicalWorld = harness({ jobs: [...clone(jobs), row(name, 500)] }); + await historicalWorld.run(); + assert.equal(historicalWorld.calls.creates.length, 1); + } + const worldPair = [1, 2].map(partition => ({ + ...row(`Build and Test (world-management-service / ${partition})`, 500 + partition), + steps: [{ name: 'Declare World CI partition count: 2', status: 'completed', conclusion: 'success' }], + })); + const worldJobs = [...clone(accountFourWay), ...worldPair, row('World Coverage Aggregate', 503)]; + const worldRun = harness({ jobs: worldJobs }); await worldRun.run(); + assert.match(worldRun.calls.creates[0].body, /World coverage aggregation: `success`/); + for (const missing of ['Build and Test (world-management-service / 1)', 'Build and Test (world-management-service / 2)', 'World Coverage Aggregate']) { + await noWrites({ jobs: clone(worldJobs).filter(job => job.name !== missing) }, true); + } + for (const mutate of [ + job => { job.steps = []; }, + job => { job.steps[0].name = 'Declare World CI partition count: 4'; }, + job => { job.steps.push(clone(job.steps[0])); }, + job => { job.steps[0].name = 'Harden runner'; }, + ]) { + const invalid = clone(worldJobs); mutate(invalid.find(job => job.name === 'Build and Test (world-management-service / 2)')); + await noWrites({ jobs: invalid }, true); + } + await noWrites({ jobs: [...clone(worldJobs), row('Build and Test (world-management-service / 3)', 504)] }, true); + await noWrites({ jobs: [...clone(worldJobs), clone(worldPair[0])] }, true); + await noWrites({ jobs: [...clone(worldJobs), row('Build and Test (world-management-service / full)', 504)] }, true); + for (const conclusion of ['failure', 'cancelled', 'timed_out']) { + const failed = clone(worldJobs); + failed.find(job => job.name === 'Build and Test (world-management-service / 2)').conclusion = conclusion; + failed.find(job => job.name === 'World Coverage Aggregate').conclusion = 'skipped'; + const failedRun = harness({ jobs: failed }); await failedRun.run(); + assert.match(failedRun.calls.creates[0].body, /World coverage aggregation: `skipped`/); + } + const worldSkipped = [...clone(allGroupsSkipped), groupPlaceholder('world-management-service', 501), + { ...row('World Coverage Aggregate', 503), conclusion: 'skipped' }]; + const worldSkippedRun = harness({ jobs: worldSkipped }); await worldSkippedRun.run(); + assert.equal(worldSkippedRun.calls.creates.length, 1); + const legacy = clone(jobs).filter(x => x.name !== 'Account Coverage Aggregate' && x.name !== 'Game Session Coverage Aggregate' && diff --git a/dev-tools/tests/jacoco-combined-report-contract.sh b/dev-tools/tests/jacoco-combined-report-contract.sh index 274480427d..b27d0d0f06 100644 --- a/dev-tools/tests/jacoco-combined-report-contract.sh +++ b/dev-tools/tests/jacoco-combined-report-contract.sh @@ -11,12 +11,14 @@ check_graph="$TMP_DIR/check-graph" report_graph="$TMP_DIR/report-graph" account_aggregate_graph="$TMP_DIR/account-aggregate-graph" game_session_aggregate_graph="$TMP_DIR/game-session-aggregate-graph" +world_aggregate_graph="$TMP_DIR/world-aggregate-graph" bash "$LOCKED_GRADLE" :common-saga:test -PfullCheck --dry-run --no-configuration-cache >"$unit_graph" bash "$LOCKED_GRADLE" :common-saga:check -PfullCheck --dry-run --no-configuration-cache >"$check_graph" bash "$LOCKED_GRADLE" :common-saga:jacocoTestReport -PfullCheck --dry-run --no-configuration-cache >"$report_graph" bash "$LOCKED_GRADLE" :account-service:jacocoTestReport -PfullCheck -PslowServiceCiCoverageAggregate=account-service -PslowServiceCiCoverageClassesDirectory=build/slow-service-ci-verified-classes --dry-run --configuration-cache --configuration-cache-problems=fail >"$account_aggregate_graph" bash "$LOCKED_GRADLE" :game-session-service:jacocoTestReport -PfullCheck -PslowServiceCiCoverageAggregate=game-session-service -PslowServiceCiCoverageClassesDirectory=build/slow-service-ci-verified-classes --dry-run --configuration-cache --configuration-cache-problems=fail >"$game_session_aggregate_graph" +bash "$LOCKED_GRADLE" :world-management-service:jacocoTestReport -PfullCheck -PslowServiceCiCoverageAggregate=world-management-service -PslowServiceCiCoverageClassesDirectory=build/slow-service-ci-verified-classes --dry-run --configuration-cache --configuration-cache-problems=fail >"$world_aggregate_graph" if grep -Eq '^:common-saga:(integrationTest|crossServiceTest|jacocoTestReport)([[:space:]]|$)' "$unit_graph"; then echo "Focused :common-saga:test unexpectedly scheduled categorized tests or the combined report." >&2 @@ -66,4 +68,17 @@ grep -Eq '^:game-session-service:jacocoTestReport([[:space:]]|$)' "$game_session exit 1 } +if grep -Eq '^:world-management-service:(test|integrationTest|crossServiceTest)([[:space:]]|$)' "$world_aggregate_graph"; then + echo "World coverage aggregation unexpectedly reran a partitioned test task." >&2 + exit 1 +fi +if grep -Eq '^:[^ ]*:(classes|compile[^ ]*|test|integrationTest|crossServiceTest)([[:space:]]|$)' "$world_aggregate_graph"; then + echo "World coverage aggregation recompiled classes instead of using measured partition classes." >&2 + exit 1 +fi +grep -Eq '^:world-management-service:jacocoTestReport([[:space:]]|$)' "$world_aggregate_graph" || { + echo "World coverage aggregation did not schedule jacocoTestReport." >&2 + exit 1 +} + echo "JaCoCo combined and slow-service partition report task graph contracts passed" diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 776ecec283..ca18bedc37 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -994,11 +994,12 @@ title = f"CI — Validation pr-{os.environ['PR_NUMBER']} base-{base} head-{head} names = ["Detect CI-Relevant Changes", "GitHub Workflow Lint", "Buf Generation", "Dev Tools README Contract", "Build and Test ($" + "{{ matrix.module }} / $" + "{{ matrix.partition }})", "Build and Test (account-service / $" + "{{ matrix.partition }})", + "Build and Test (world-management-service / $" + "{{ matrix.partition }})", "Build and Test (game-session-service / $" + "{{ matrix.partition }})", "Metrics Cardinality Policy Check", "Flyway Migration Sanity Checks", "gRPC Transport Configuration Sanity Checks", "PostgreSQL Runtime Upgrade Proof", "Validate Documentation", "YAML Lint", "Dockerfile Lint", "Helm Render Validation", "Helm Chart Lint", "Python Script Validation", "ShellCheck", "Frontend Checks", "Dev Tool Contract Checks", "Helm Transaction Proof", - "Account Coverage Aggregate", "Game Session Coverage Aggregate", "Validation Gate"] + "Account Coverage Aggregate", "Game Session Coverage Aggregate", "World Coverage Aggregate", "Validation Gate"] def step(name, conclusion): return {"name": name, "status": "completed", "conclusion": conclusion} # Exact split-matrix cancellation shape: 21 prerequisites never reached a step; @@ -1030,6 +1031,19 @@ if scenario == "cancellation-old-shape": if scenario == "cancellation-partial-new-shape": jobs = [job for job in jobs if job["name"] != "Build and Test (game-session-service / $" + "{{ matrix.partition }})"] +if scenario == "cancellation-pre-world-shape": + jobs = [job for job in jobs if job["name"] not in ( + "Build and Test (world-management-service / $" + "{{ matrix.partition }})", + "World Coverage Aggregate")] +if scenario == "cancellation-world-missing-partition": + jobs = [job for job in jobs if job["name"] != + "Build and Test (world-management-service / $" + "{{ matrix.partition }})"] +if scenario == "cancellation-world-aggregate-executed": + world = next(job for job in jobs if job["name"] == "World Coverage Aggregate") + world["steps"] = [step("Verify complete World partition and report union", "success")] +if scenario == "cancellation-world-aggregate-failed": + world = next(job for job in jobs if job["name"] == "World Coverage Aggregate") + world["conclusion"] = "failure" if scenario == "cancellation-real-failure": jobs[1]["conclusion"] = "failure" jobs[1]["steps"] = [step("Run lint", "failure")] @@ -1881,7 +1895,7 @@ for scenario in cancellation-only cancellation-pending cancellation-metadata can echo "cancellation lost missing-proof behavior: $scenario" >&2; exit 1; } done -for scenario in cancellation-old-shape cancellation-partial-new-shape cancellation-later-attempt-failed-source cancellation-real-failure cancellation-hidden-step-failure cancellation-executed-check cancellation-aggregate-executed cancellation-aggregate-failed cancellation-game-session-aggregate-executed cancellation-game-session-aggregate-failed cancellation-gate-other-failure cancellation-unknown-assertion cancellation-timed-out cancellation-action-required cancellation-partial cancellation-wrong-attempt cancellation-wrong-head cancellation-duplicate cancellation-missing-steps cancellation-wrong-app cancellation-check-conflict cancellation-run-conflict; do +for scenario in cancellation-pre-world-shape cancellation-world-missing-partition cancellation-world-aggregate-executed cancellation-world-aggregate-failed cancellation-old-shape cancellation-partial-new-shape cancellation-later-attempt-failed-source cancellation-real-failure cancellation-hidden-step-failure cancellation-executed-check cancellation-aggregate-executed cancellation-aggregate-failed cancellation-game-session-aggregate-executed cancellation-game-session-aggregate-failed cancellation-gate-other-failure cancellation-unknown-assertion cancellation-timed-out cancellation-action-required cancellation-partial cancellation-wrong-attempt cancellation-wrong-head cancellation-duplicate cancellation-missing-steps cancellation-wrong-app cancellation-check-conflict cancellation-run-conflict; do output_file="$tmp_dir/$scenario-output" if run_action "$tmp_dir/$scenario-count" none "$scenario" "" "$output_file" >"$tmp_dir/$scenario-log" 2>&1; then echo "cancellation suppressed failed or incomplete proof: $scenario" >&2; exit 1 diff --git a/dev-tools/tests/test_slow_service_ci_partition.py b/dev-tools/tests/test_slow_service_ci_partition.py index e033df9f0d..4efae374ee 100644 --- a/dev-tools/tests/test_slow_service_ci_partition.py +++ b/dev-tools/tests/test_slow_service_ci_partition.py @@ -300,6 +300,95 @@ def utf8_constant(value): class SlowServiceCiPartitionTests(unittest.TestCase): + def test_world_all_tasks_compiled_nested_groups_and_new_classes_are_complete(self): + module = "world-management-service" + historical = PARTITION.load_historical_plan(module) + self.assertEqual(historical["partition_count"], 2) + document = json.loads(PARTITION.PLAN_PATH.read_text()) + self.assertEqual(document["weight_provenance"][module]["artifact_id"], 13604416967) + self.assertEqual(sum(len(task["classes"]) for task in historical["tasks"].values()), 150) + self.assertEqual(sum(metric["cases"] for task in historical["tasks"].values() + for metric in task["metrics_by_partition"].values()), 1016) + loads = {p: sum(entry["weight_seconds"] for task in historical["tasks"].values() + for entry in task["classes"].values() if entry["partition"] == p) + for p in (1, 2)} + self.assertLess(abs(loads[1] - loads[2]), 0.01) + self.assertEqual(set(historical["tasks"]), {"test", "integrationTest", "crossServiceTest"}) + with tempfile.TemporaryDirectory() as temporary: + discovered, flags = {}, {} + for task in historical["tasks"]: + directory = Path(temporary) / task + known = next(iter(historical["tasks"][task]["classes"])) + for name in (known, known + "$Nested", "net.example.NewWorldTest", "net.example.NewWorldTest$Nested", "net.example.Fixture"): + write_compiled_class(directory, name, 0x0021) + discovered[task] = PARTITION.class_names_from_directories([directory]) + candidates = {name for name in discovered[task] if PARTITION.is_test_class(name)} + flags[task] = PARTITION.test_class_access_flags_from_directories([directory], candidates) + plan = PARTITION.build_plan(discovered, SOURCE_SHA, "1", RUN_ID, module, + class_access_flags_by_task=flags) + repeated = PARTITION.build_plan(dict(reversed(list(discovered.items()))), SOURCE_SHA, "1", RUN_ID, module, + class_access_flags_by_task=flags) + self.assertEqual(plan, repeated) + manifests = [PARTITION.partition_manifest(plan, p) for p in (1, 2)] + PARTITION.validate_partitions(manifests) + for task, names in discovered.items(): + selected = [set(m["tasks"][task]["selected_classes"]) for m in manifests] + self.assertEqual(selected[0] | selected[1], names) + self.assertFalse(selected[0] & selected[1]) + self.assertTrue(all("$" not in name for name in names)) + # Empty selections in an individual task are valid, never a reason to drop that task. + empty = copy.deepcopy(manifests) + task = "crossServiceTest" + for manifest in empty: + manifest["tasks"][task]["assignments"] = dict.fromkeys(discovered[task], 1) + manifest["tasks"][task]["selected_classes"] = sorted(discovered[task]) if manifest["partition"] == 1 else [] + PARTITION.validate_partitions(empty) + + def test_world_two_way_provenance_and_aggregate_fail_closed(self): + module = "world-management-service" + provenance = make_provenance(module) + selection = PARTITION.selection_document(provenance, module, RUN_ID, SOURCE_SHA, "2") + self.assertEqual(set(selection["resolved"]["partitions"]), {"1", "2"}) + self.assertEqual(selection["resolved"]["partitions"]["1"]["attempt"], 1) + self.assertEqual(selection["resolved"]["partitions"]["2"]["attempt"], 2) + for conclusion in ("failure", "cancelled", "timed_out"): + bad = copy.deepcopy(provenance) + bad["attempts"][-1]["jobs"][1]["conclusion"] = conclusion + with self.assertRaises(ValueError): + PARTITION.resolve_effective_artifacts(bad, module, RUN_ID, SOURCE_SHA, "2") + for mutation in ("missing_job", "missing_artifact", "wrong_source", "wrong_attempt"): + bad = copy.deepcopy(provenance) + if mutation == "missing_job": + for attempt in bad["attempts"]: + attempt["jobs"] = attempt["jobs"][:1] + attempt["total_count"] = 1 + elif mutation == "missing_artifact": + bad["artifacts"]["items"].pop() + bad["artifacts"]["total_count"] -= 1 + elif mutation == "wrong_source": + bad["run"]["tested_source_sha"] = "f" * 40 + else: + bad["run"]["run_attempt"] = 3 + with self.subTest(mutation=mutation), self.assertRaises(ValueError): + PARTITION.resolve_effective_artifacts(bad, module, RUN_ID, SOURCE_SHA, "2") + for mutation in (None, "missing_manifest", "missing_junit", "missing_exec", "unequal_bytecode"): + with self.subTest(mutation=mutation), tempfile.TemporaryDirectory() as temporary: + input_dir, selection_path, verified, artifacts = prepare_aggregate(Path(temporary), module, selection) + if mutation == "missing_manifest": + next(artifacts[2].rglob("manifest.json")).unlink() + elif mutation == "missing_junit": + next(artifacts[2].glob("test-results/test/*.xml")).unlink() + elif mutation == "missing_exec": + (artifacts[2] / "jacoco/test.exec").unlink() + elif mutation == "unequal_bytecode": + next(artifacts[2].glob("classes/java/main/**/*.class")).write_bytes(b"mismatched bytes") + args = (input_dir, selection_path, verified, module, RUN_ID, SOURCE_SHA, "2") + if mutation: + with self.assertRaises(ValueError): + PARTITION.verify_aggregate(*args) + else: + self.assertEqual(PARTITION.verify_aggregate(*args), 2) + def test_account_plan_uses_measured_four_way_split_weights(self): historical = PARTITION.load_historical_plan("account-service") integration = historical["tasks"]["integrationTest"] diff --git a/dev-tools/validation/slow_service_ci_test_partition.py b/dev-tools/validation/slow_service_ci_test_partition.py index be974e36c7..504a272f32 100644 --- a/dev-tools/validation/slow_service_ci_test_partition.py +++ b/dev-tools/validation/slow_service_ci_test_partition.py @@ -16,8 +16,8 @@ from typing import Any PLAN_PATH = Path(__file__).with_name("slow_service_ci_test_partition_plan.json") -SERVICES = ("account-service", "game-session-service") -PARTITION_COUNTS = {"account-service": 4, "game-session-service": 4} +SERVICES = ("account-service", "game-session-service", "world-management-service") +PARTITION_COUNTS = {"account-service": 4, "game-session-service": 4, "world-management-service": 2} def partitions_for(module: str) -> range: diff --git a/dev-tools/validation/slow_service_ci_test_partition_plan.json b/dev-tools/validation/slow_service_ci_test_partition_plan.json index 6966395ffb..0841ab7b94 100644 --- a/dev-tools/validation/slow_service_ci_test_partition_plan.json +++ b/dev-tools/validation/slow_service_ci_test_partition_plan.json @@ -2810,6 +2810,662 @@ "unknown_class_estimated_weight_seconds": 1.0 } } + }, + "world-management-service": { + "partition_count": 2, + "tasks": { + "crossServiceTest": { + "classes": { + "net.firedevops.firemud.worldmanagement.client.AccountTenantOperationEntitlementClientMtlsTest": { + "partition": 2, + "weight_seconds": 53.212 + }, + "net.firedevops.firemud.worldmanagement.client.EntityPlayerCreatedActorPlacementReceiptClientMtlsTest": { + "partition": 2, + "weight_seconds": 27.311 + }, + "net.firedevops.firemud.worldmanagement.client.EntityPreseededActorAssignmentReceiptClientMtlsTest": { + "partition": 2, + "weight_seconds": 27.873 + }, + "net.firedevops.firemud.worldmanagement.client.GrpcGameSessionCanonicalInitialAdmissionOwnerClientMtlsTest": { + "partition": 2, + "weight_seconds": 32.766 + }, + "net.firedevops.firemud.worldmanagement.tenant.AccountAdmissionProtectionCurrentOwnerCompositionCrossServiceTest": { + "partition": 2, + "weight_seconds": 40.894 + }, + "net.firedevops.firemud.worldmanagement.tenant.CanonicalInitialPlayerLocationGrpcServiceMtlsTest": { + "partition": 2, + "weight_seconds": 17.751 + }, + "net.firedevops.firemud.worldmanagement.tenant.PrivateWorldPreparationSourceCompositionCrossServiceTest": { + "partition": 2, + "weight_seconds": 118.669 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest": { + "partition": 1, + "weight_seconds": 767.628 + } + }, + "metrics_by_partition": { + "1": { + "cases": 20, + "suites": 1, + "weight_seconds": 767.628 + }, + "2": { + "cases": 26, + "suites": 7, + "weight_seconds": 318.47599999999994 + } + }, + "unknown_class_estimated_weight_seconds": 36.83 + }, + "integrationTest": { + "classes": { + "integration.net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInitialPlayerLocationRepositoryPostgresIntegrationTest": { + "partition": 2, + "weight_seconds": 7.888 + }, + "integration.net.firedevops.firemud.worldmanagement.tenant.WorldDraftTerminalOutcomePostgresIntegrationTest": { + "partition": 2, + "weight_seconds": 19.485 + }, + "net.firedevops.firemud.worldmanagement.InitialAdmissionBindHoldPostgresIntegrationTest": { + "partition": 2, + "weight_seconds": 35.11 + }, + "net.firedevops.firemud.worldmanagement.RoomRepositoryPostgresIntegrationTest": { + "partition": 2, + "weight_seconds": 5.306 + }, + "net.firedevops.firemud.worldmanagement.RunOwnedWorldLaunchEvidencePostgresIntegrationTest": { + "partition": 1, + "weight_seconds": 6.059 + }, + "net.firedevops.firemud.worldmanagement.WorldAuthoredSourceIntakeIntegrationTest": { + "partition": 2, + "weight_seconds": 6.938 + }, + "net.firedevops.firemud.worldmanagement.WorldAuthoredSourceIntakeMtlsIntegrationTest": { + "partition": 2, + "weight_seconds": 5.815 + }, + "net.firedevops.firemud.worldmanagement.WorldAuthoredVersionIdentityIntegrationTest": { + "partition": 2, + "weight_seconds": 7.019 + }, + "net.firedevops.firemud.worldmanagement.WorldCompleteLaunchBindingIntegrationTest": { + "partition": 1, + "weight_seconds": 6.947 + }, + "net.firedevops.firemud.worldmanagement.WorldDesignPublicationFenceIntegrationTest": { + "partition": 2, + "weight_seconds": 5.114 + }, + "net.firedevops.firemud.worldmanagement.WorldManagementServiceApplicationIntegrationTest": { + "partition": 1, + "weight_seconds": 5.114 + }, + "net.firedevops.firemud.worldmanagement.WorldPreparationStartLocationSubtransactionPostgresIntegrationTest": { + "partition": 2, + "weight_seconds": 4.629 + }, + "net.firedevops.firemud.worldmanagement.WorldPublicationOwnerBindingMigrationIntegrationTest": { + "partition": 2, + "weight_seconds": 2.114 + }, + "net.firedevops.firemud.worldmanagement.WorldSameTransactionGuardSubtransactionPostgresIntegrationTest": { + "partition": 1, + "weight_seconds": 4.451 + }, + "net.firedevops.firemud.worldmanagement.data.LegacyDemoSeedingPostgresIntegrationTest": { + "partition": 1, + "weight_seconds": 10.53 + }, + "net.firedevops.firemud.worldmanagement.data.RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest": { + "partition": 2, + "weight_seconds": 15.47 + }, + "net.firedevops.firemud.worldmanagement.service.impl.RunOwnedCanonicalWorldLaunchEvidenceMtlsIntegrationTest": { + "partition": 1, + "weight_seconds": 9.342 + }, + "net.firedevops.firemud.worldmanagement.service.impl.RunOwnedWorldLaunchEvidenceMtlsIntegrationTest": { + "partition": 2, + "weight_seconds": 17.883 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldAppliedGraphHistoryPostgresIntegrationTest": { + "partition": 2, + "weight_seconds": 4.857 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceExecutionTerminalSchemaPostgresIntegrationTest": { + "partition": 1, + "weight_seconds": 2.556 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationPostgresIntegrationTest": { + "partition": 1, + "weight_seconds": 3.332 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldExecutionIntentHistoryPostgresIntegrationTest": { + "partition": 1, + "weight_seconds": 3.606 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldGraphApplicationReceiptDigestPostgresIntegrationTest": { + "partition": 1, + "weight_seconds": 7.123 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldGuardedAuthoredGraphCapturePostgresIntegrationTest": { + "partition": 2, + "weight_seconds": 22.646 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldInitialAdmissionHoldHistoryPostgresIntegrationTest": { + "partition": 2, + "weight_seconds": 4.031 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldOperationalRegionAssignmentPostgresIntegrationTest": { + "partition": 2, + "weight_seconds": 3.407 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldPrivateFreshOperationPostgresIntegrationTest": { + "partition": 2, + "weight_seconds": 34.204 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldRuntimeFamilyCatalogPostgresIntegrationTest": { + "partition": 2, + "weight_seconds": 74.538 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldRuntimeInstallationRegistryPostgresIntegrationTest": { + "partition": 2, + "weight_seconds": 25.14 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldSelectedFullPublicationEvidenceFixtureTest": { + "partition": 1, + "weight_seconds": 2.158 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldSelectedPublicationPostgresIntegrationTest": { + "partition": 2, + "weight_seconds": 9.479 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldTerminalAndLocationOwnerGuardsPostgresIntegrationTest": { + "partition": 1, + "weight_seconds": 5.993 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldV1PreparationHistoryPostgresIntegrationTest": { + "partition": 2, + "weight_seconds": 28.699 + } + }, + "metrics_by_partition": { + "1": { + "cases": 34, + "suites": 12, + "weight_seconds": 67.211 + }, + "2": { + "cases": 121, + "suites": 21, + "weight_seconds": 339.772 + } + }, + "unknown_class_estimated_weight_seconds": 6.938 + }, + "test": { + "classes": { + "net.firedevops.firemud.worldmanagement.WorldManagementTemporalHostingTest": { + "partition": 2, + "weight_seconds": 3.129 + }, + "net.firedevops.firemud.worldmanagement.client.GameDesignClientTest": { + "partition": 1, + "weight_seconds": 0.351 + }, + "net.firedevops.firemud.worldmanagement.client.GrpcGameSessionCanonicalInitialAdmissionOwnerClientTest": { + "partition": 2, + "weight_seconds": 0.492 + }, + "net.firedevops.firemud.worldmanagement.client.GrpcGameSessionInitialAdmissionBindProofClientTest": { + "partition": 1, + "weight_seconds": 0.177 + }, + "net.firedevops.firemud.worldmanagement.controller.GenerationRuleControllerTest": { + "partition": 2, + "weight_seconds": 6.109 + }, + "net.firedevops.firemud.worldmanagement.controller.RegionControllerTest": { + "partition": 1, + "weight_seconds": 2.016 + }, + "net.firedevops.firemud.worldmanagement.data.RunOwnedCanonicalWorldLaunchEvidenceProviderTest": { + "partition": 2, + "weight_seconds": 6.051 + }, + "net.firedevops.firemud.worldmanagement.data.RunOwnedWorldFixedPresetResourcesTest": { + "partition": 2, + "weight_seconds": 0.035 + }, + "net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidenceProviderTest": { + "partition": 2, + "weight_seconds": 0.018 + }, + "net.firedevops.firemud.worldmanagement.data.TestDataSeederTest": { + "partition": 2, + "weight_seconds": 0.818 + }, + "net.firedevops.firemud.worldmanagement.dto.RoomSnapshotDtoTest": { + "partition": 1, + "weight_seconds": 0.002 + }, + "net.firedevops.firemud.worldmanagement.repository.InitialAdmissionBindHoldRepositoryTest": { + "partition": 2, + "weight_seconds": 1.554 + }, + "net.firedevops.firemud.worldmanagement.service.impl.GenerationRuleServiceImplTest": { + "partition": 2, + "weight_seconds": 0.208 + }, + "net.firedevops.firemud.worldmanagement.service.impl.InitialAdmissionBindHoldReconcilerTest": { + "partition": 2, + "weight_seconds": 0.261 + }, + "net.firedevops.firemud.worldmanagement.service.impl.InitialAdmissionBindHoldServiceImplTest": { + "partition": 2, + "weight_seconds": 0.1 + }, + "net.firedevops.firemud.worldmanagement.service.impl.InstanceServiceImplTest": { + "partition": 2, + "weight_seconds": 0.063 + }, + "net.firedevops.firemud.worldmanagement.service.impl.PingServiceImplTest": { + "partition": 2, + "weight_seconds": 0.002 + }, + "net.firedevops.firemud.worldmanagement.service.impl.RegionServiceImplTest": { + "partition": 2, + "weight_seconds": 0.058 + }, + "net.firedevops.firemud.worldmanagement.service.impl.RoomServiceImplTest": { + "partition": 2, + "weight_seconds": 0.431 + }, + "net.firedevops.firemud.worldmanagement.service.impl.TemporalWorldLifecycleOrchestratorTest": { + "partition": 2, + "weight_seconds": 0.153 + }, + "net.firedevops.firemud.worldmanagement.service.impl.TemporalWorldLifecycleWorkflowMetadataResolverTest": { + "partition": 2, + "weight_seconds": 0.388 + }, + "net.firedevops.firemud.worldmanagement.service.impl.WorldDesignMutationServiceImplTest": { + "partition": 1, + "weight_seconds": 0.387 + }, + "net.firedevops.firemud.worldmanagement.service.impl.WorldDraftDesignDigestServiceImplTest": { + "partition": 2, + "weight_seconds": 0.109 + }, + "net.firedevops.firemud.worldmanagement.service.impl.WorldEventServiceImplTest": { + "partition": 1, + "weight_seconds": 0.116 + }, + "net.firedevops.firemud.worldmanagement.service.impl.WorldInstanceActivationServiceImplTemporalDelegationTest": { + "partition": 2, + "weight_seconds": 0.152 + }, + "net.firedevops.firemud.worldmanagement.service.impl.WorldLifecycleCommandServiceImplTest": { + "partition": 1, + "weight_seconds": 0.316 + }, + "net.firedevops.firemud.worldmanagement.service.impl.WorldManagementGrpcServiceTest": { + "partition": 2, + "weight_seconds": 0.723 + }, + "net.firedevops.firemud.worldmanagement.service.impl.WorldUpgradeValidationServiceImplTest": { + "partition": 1, + "weight_seconds": 0.005 + }, + "net.firedevops.firemud.worldmanagement.tenant.CanonicalInitialPlayerLocationGrpcCodecTest": { + "partition": 1, + "weight_seconds": 0.122 + }, + "net.firedevops.firemud.worldmanagement.tenant.CanonicalInitialPlayerLocationServiceTest": { + "partition": 2, + "weight_seconds": 0.95 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphCodecTest": { + "partition": 1, + "weight_seconds": 0.035 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshotCaptureSerializationTest": { + "partition": 2, + "weight_seconds": 0.004 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshotTest": { + "partition": 2, + "weight_seconds": 0.006 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphTest": { + "partition": 2, + "weight_seconds": 0.094 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeDigestTest": { + "partition": 1, + "weight_seconds": 0.012 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeGrpcServiceTest": { + "partition": 2, + "weight_seconds": 0.165 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeMtlsTest": { + "partition": 2, + "weight_seconds": 2.539 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeServiceTest": { + "partition": 2, + "weight_seconds": 0.18 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalAuthoredGraphReaderTest": { + "partition": 2, + "weight_seconds": 0.233 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalFrozenTopologyDeadlineReadTest": { + "partition": 1, + "weight_seconds": 4.632 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalFrozenTopologyServiceTest": { + "partition": 2, + "weight_seconds": 0.304 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalFrozenTopologyTest": { + "partition": 2, + "weight_seconds": 0.005 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInitialAdmissionHoldGrpcServiceTest": { + "partition": 1, + "weight_seconds": 0.085 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInitialAdmissionHoldOwnerTest": { + "partition": 1, + "weight_seconds": 0.007 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociationTest": { + "partition": 1, + "weight_seconds": 0.026 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationAssemblyServiceTest": { + "partition": 2, + "weight_seconds": 0.378 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationPreflightTest": { + "partition": 1, + "weight_seconds": 0.753 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationTest": { + "partition": 2, + "weight_seconds": 0.203 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceStartLocationReadbackTest": { + "partition": 2, + "weight_seconds": 0.349 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceTopologyPlanTest": { + "partition": 1, + "weight_seconds": 0.115 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalStartSessionTerminalReadTest": { + "partition": 1, + "weight_seconds": 0.156 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldCompleteLaunchBindingServiceTest": { + "partition": 2, + "weight_seconds": 0.345 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidenceTest": { + "partition": 1, + "weight_seconds": 0.054 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationServiceTest": { + "partition": 2, + "weight_seconds": 0.31 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldDraftStartLocationReceiptTest": { + "partition": 1, + "weight_seconds": 0.002 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyCommitEvidenceTest": { + "partition": 2, + "weight_seconds": 0.155 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyCommitPlanTest": { + "partition": 1, + "weight_seconds": 0.346 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyCommitRepositoryTest": { + "partition": 2, + "weight_seconds": 0.593 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldGameDesignPublicationTerminalVerifierTest": { + "partition": 1, + "weight_seconds": 1.562 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldGuardedAuthoredTopologyPlanTest": { + "partition": 1, + "weight_seconds": 0.009 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldOwnerBindingSerializationTest": { + "partition": 1, + "weight_seconds": 0.005 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldPrivateFreshOperationRepositoryTest": { + "partition": 1, + "weight_seconds": 0.203 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldPrivatePreparationInputAssemblyTest": { + "partition": 2, + "weight_seconds": 45.025 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldPrivatePreparationProtectionClientMtlsTest": { + "partition": 2, + "weight_seconds": 56.693 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldPrivatePreparationSourceClientMtlsTest": { + "partition": 2, + "weight_seconds": 80.191 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldPublishedSourceSnapshotReadTest": { + "partition": 2, + "weight_seconds": 0.009 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldPublishedSpawnRequirementsReadGrpcServiceTest": { + "partition": 1, + "weight_seconds": 0.084 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldPublishedSpawnRequirementsReadOwnerTest": { + "partition": 1, + "weight_seconds": 0.952 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldRuntimeInstallationArtifactTest": { + "partition": 2, + "weight_seconds": 0.084 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldRuntimeInstallationRegistryTest": { + "partition": 2, + "weight_seconds": 0.002 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldSelectedDraftPublicationFreezeGrpcServiceTest": { + "partition": 1, + "weight_seconds": 0.161 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldSelectedDraftPublicationFreezeRequestTest": { + "partition": 1, + "weight_seconds": 0.351 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldSelectedDraftPublicationFreezeServiceTest": { + "partition": 2, + "weight_seconds": 0.169 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldSelectedOwnerInventoryReadGrpcServiceTest": { + "partition": 1, + "weight_seconds": 0.234 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldSelectedOwnerInventoryReadServiceTest": { + "partition": 2, + "weight_seconds": 0.137 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldSelectedPublicationArtifactInventoryTest": { + "partition": 2, + "weight_seconds": 0.074 + }, + "net.firedevops.firemud.worldmanagement.tenant.WorldSelectedPublicationSelectorCaptureTest": { + "partition": 2, + "weight_seconds": 0.078 + }, + "unit.net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityCanonicalTargetReadTest": { + "partition": 1, + "weight_seconds": 0.828 + }, + "unit.net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityGrpcServiceTest": { + "partition": 2, + "weight_seconds": 0.118 + }, + "unit.net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityServiceTest": { + "partition": 1, + "weight_seconds": 0.139 + }, + "unit.net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceActivationGrpcServiceTest": { + "partition": 1, + "weight_seconds": 0.211 + }, + "unit.net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceActivationRepositoryTest": { + "partition": 1, + "weight_seconds": 1.384 + }, + "unit.net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceActivationServiceTest": { + "partition": 1, + "weight_seconds": 0.469 + }, + "unit.net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceExecutionIdentityTest": { + "partition": 2, + "weight_seconds": 0.042 + }, + "unit.net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceLifecycleReadGrpcServiceTest": { + "partition": 2, + "weight_seconds": 0.03 + }, + "unit.net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceLifecycleReadRepositoryTest": { + "partition": 2, + "weight_seconds": 0.119 + }, + "unit.net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceOriginalOperationRecoveryVerifierTest": { + "partition": 1, + "weight_seconds": 0.83 + }, + "unit.net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationGrpcServiceTest": { + "partition": 1, + "weight_seconds": 0.672 + }, + "unit.net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationServiceTest": { + "partition": 1, + "weight_seconds": 0.013 + }, + "unit.net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceCommittedReadTest": { + "partition": 1, + "weight_seconds": 0.419 + }, + "unit.net.firedevops.firemud.worldmanagement.tenant.WorldDraftCommitOrderVerifierTest": { + "partition": 2, + "weight_seconds": 0.073 + }, + "unit.net.firedevops.firemud.worldmanagement.tenant.WorldDraftTerminalOutcomeTest": { + "partition": 1, + "weight_seconds": 0.049 + }, + "unit.net.firedevops.firemud.worldmanagement.tenant.WorldDraftTerminalReadGrpcServiceTest": { + "partition": 1, + "weight_seconds": 0.148 + }, + "unit.net.firedevops.firemud.worldmanagement.tenant.WorldOriginalDraftGraphApplicationServiceTest": { + "partition": 1, + "weight_seconds": 0.077 + }, + "unit.net.firedevops.firemud.worldmanagement.tenant.WorldOriginalDraftGraphApplyGrpcServiceTest": { + "partition": 1, + "weight_seconds": 0.097 + }, + "unit.net.firedevops.firemud.worldmanagement.tenant.WorldOriginalStartSessionActivationTerminalReadGrpcMtlsTest": { + "partition": 1, + "weight_seconds": 6.411 + }, + "unit.net.firedevops.firemud.worldmanagement.tenant.WorldOriginalStartSessionActivationTerminalReadGrpcServiceTest": { + "partition": 2, + "weight_seconds": 1.956 + }, + "unit.net.firedevops.firemud.worldmanagement.tenant.WorldOriginalStartSessionProtectedActivationGrpcMtlsTest": { + "partition": 1, + "weight_seconds": 5.245 + }, + "unit.net.firedevops.firemud.worldmanagement.tenant.WorldOriginalStartSessionProtectedActivationGrpcServiceTest": { + "partition": 2, + "weight_seconds": 1.295 + }, + "unit.net.firedevops.firemud.worldmanagement.tenant.WorldOriginalStartSessionProtectedActivationServiceTest": { + "partition": 1, + "weight_seconds": 0.274 + }, + "unit.net.firedevops.firemud.worldmanagement.tenant.WorldPublicationTerminalCompletionGrpcMtlsTest": { + "partition": 1, + "weight_seconds": 5.808 + }, + "unit.net.firedevops.firemud.worldmanagement.tenant.WorldPublicationTerminalCompletionGrpcServiceTest": { + "partition": 1, + "weight_seconds": 0.285 + }, + "unit.net.firedevops.firemud.worldmanagement.tenant.WorldPublicationTerminalReadGrpcServiceTest": { + "partition": 1, + "weight_seconds": 0.067 + }, + "unit.net.firedevops.firemud.worldmanagement.tenant.WorldPublicationTerminalReadServiceTest": { + "partition": 1, + "weight_seconds": 0.155 + }, + "unit.net.firedevops.firemud.worldmanagement.tenant.WorldPublicationTerminalServiceTest": { + "partition": 1, + "weight_seconds": 0.001 + }, + "unit.net.firedevops.firemud.worldmanagement.tenant.WorldPublishedStartLocationReadGrpcServiceTest": { + "partition": 2, + "weight_seconds": 0.011 + }, + "unit.net.firedevops.firemud.worldmanagement.tenant.WorldRuntimeFamilyCatalogReadGrpcServiceTest": { + "partition": 1, + "weight_seconds": 0.074 + }, + "unit.net.firedevops.firemud.worldmanagement.tenant.WorldStartSessionAccountParticipationVerifierTest": { + "partition": 1, + "weight_seconds": 0.079 + }, + "unit.net.firedevops.firemud.worldmanagement.tenant.WorldStartSessionExecutionTerminalReadGrpcServiceTest": { + "partition": 1, + "weight_seconds": 0.172 + } + }, + "metrics_by_partition": { + "1": { + "cases": 424, + "suites": 54, + "weight_seconds": 37.18300000000001 + }, + "2": { + "cases": 391, + "suites": 56, + "weight_seconds": 213.77299999999994 + } + }, + "unknown_class_estimated_weight_seconds": 0.165 + } + } } }, "weight_provenance": { @@ -2844,6 +3500,18 @@ "source_assessment": "R1308-independent-runner-partition-assessment", "source_head": "38c0da4fe656c07dad184838d8dcadf370a382c3", "source_option": 2 + }, + "world-management-service": { + "artifact_id": 13604416967, + "artifact_name": "junit-world-management-service-full-results-66e331035e2f09cc82beffdb7726c603f9a5881a-attempt-1", + "attempt": 1, + "job_id": 128618673184, + "native_head_sha": "2dd867b086e72c223bd4761cd18d7a2373c2137e", + "run_id": 42443744681, + "tested_source_sha": "66e331035e2f09cc82beffdb7726c603f9a5881a", + "unknown_class_fallback": "Median observed class weight per task, with deterministic least-loaded assignment for newly compiled tests.", + "weight_method": "JUnit suite wall seconds grouped by task and outer class, including nested suites, assigned longest-first across both partitions collectively. Historical weights guide balance, not the current compiled-class inventory or elapsed runner savings.", + "zip_sha256": "b64eefb045a6a95ea51ed668f4b5a4c11d0b419cb2e1e66864a0c19c93eeafd2" } } } From 693e93e7100bebba2c7d0c98da049c2f798ab224 Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 8 Nov 2026 19:20:54 +1300 Subject: [PATCH 03/17] Receive deferred CI scope optimization after Account cutover --- .github/scripts/classify-change-scope.cjs | 20 +++- .../scripts/classify-change-scope.test.cjs | 113 ++++++++++++++++++ design/project-management/ai-observations.md | 8 ++ 3 files changed, 139 insertions(+), 2 deletions(-) diff --git a/.github/scripts/classify-change-scope.cjs b/.github/scripts/classify-change-scope.cjs index 02d5efe5e6..ef6f8c01b1 100644 --- a/.github/scripts/classify-change-scope.cjs +++ b/.github/scripts/classify-change-scope.cjs @@ -133,6 +133,7 @@ function isPythonDependency(file) { function isLightweightEligible(file) { return ( (isDocumentation(file) || isValidationPython(file)) && + !isServiceSourceMarkdown(file) && file !== "dev-tools/docs/generate-erd.sh" && !isRuntimeAuthority(file) && !SHARED_FILES.has(file) @@ -157,12 +158,27 @@ function moduleForFile(file) { return null; } +function isServiceSourceMarkdown(file) { + return file.startsWith("services/") && + moduleForFile(file) !== null && + /^services\/[^/]+\/src\/.*\.md$/.test(file); +} + function classifyChangeScope(inputFiles, options = {}) { const files = [...new Set(inputFiles)].sort(); const forceAll = options.forceAll === true; + // Known service documentation outside source sets retains docs proof without + // selecting runtime modules, including README files under shared common-* paths. + // Unknown services, source resources and non-lightweight inputs remain fail closed. + const moduleInputFiles = files.filter( + (file) => + !(file.startsWith("services/") && + moduleForFile(file) !== null && + isLightweightEligible(file)), + ); const runAll = forceAll || - files.some( + moduleInputFiles.some( (file) => SHARED_FILES.has(file) || (SHARED_PREFIXES.some((prefix) => file.startsWith(prefix)) && @@ -176,7 +192,7 @@ function classifyChangeScope(inputFiles, options = {}) { ALL_SERVICES.forEach((service) => affectedServices.add(service)); ALL_MODULES.forEach((module) => affectedModules.add(module)); } else { - for (const file of files) { + for (const file of moduleInputFiles) { const module = moduleForFile(file); if (module !== null) { affectedModules.add(module); diff --git a/.github/scripts/classify-change-scope.test.cjs b/.github/scripts/classify-change-scope.test.cjs index 5bd0855abc..320a8eabff 100644 --- a/.github/scripts/classify-change-scope.test.cjs +++ b/.github/scripts/classify-change-scope.test.cjs @@ -41,6 +41,119 @@ test("documentation-only changes use the lightweight path", () => { assert.deepEqual(result.affectedServices, []); }); +test("known service and shared-module documentation selects no heavy module proof", async () => { + for (const module of ALL_MODULES.filter((module) => module !== "load-testing")) { + for (const path of [`services/${module}/README.md`, `services/${module}/design/README.md`]) { + const result = await classifyGithubFiles([path], 1); + + assert.equal(result.runAll, false, path); + assert.equal(result.lightweightOnly, true, path); + assert.equal(result.docsChanged, true, path); + assert.deepEqual(result.affectedModules, [], path); + assert.deepEqual(result.affectedServices, [], path); + assert.deepEqual(result.bootableModules, [], path); + } + } +}); + +test("Markdown packaged under known service source retains module proof", () => { + for (const [path, module, service] of [ + ["services/account-service/src/main/resources/content/README.md", "account-service", "account-service"], + ["services/account-service/src/test/resources/fixtures/README.md", "account-service", "account-service"], + ]) { + const result = classifyChangeScope([path]); + + assert.equal(result.runAll, false, path); + assert.equal(result.lightweightOnly, false, path); + assert.equal(result.docsChanged, true, path); + assert.deepEqual(result.affectedModules, [module], path); + assert.deepEqual(result.affectedServices, service ? [service] : [], path); + assert.deepEqual(result.bootableModules, service ? [service] : [], path); + } + + const sharedPath = "services/common-platform-core/src/main/resources/schema/README.md"; + const sharedResult = classifyChangeScope([sharedPath]); + assert.equal(sharedResult.runAll, true, sharedPath); + assert.equal(sharedResult.lightweightOnly, false, sharedPath); + assert.equal(sharedResult.docsChanged, true, sharedPath); + assert.deepEqual(sharedResult.affectedModules, ALL_MODULES, sharedPath); +}); + +test("service documentation does not add modules to a cumulative runtime diff", async () => { + const result = await classifyGithubFiles([ + "services/common-platform-core/README.md", + "services/world-management-service/README.md", + "services/account-service/src/main/java/example/Account.java", + ], 3); + + assert.equal(result.runAll, false); + assert.equal(result.lightweightOnly, false); + assert.equal(result.docsChanged, true); + assert.deepEqual(result.affectedModules, ["account-service"]); + assert.deepEqual(result.affectedServices, ["account-service"]); + assert.deepEqual(result.bootableModules, ["account-service"]); +}); + +test("service docs never suppress shared runtime, toolchain, or workflow inputs", () => { + for (const path of [ + "services/common-platform-core/src/main/java/example/Shared.java", + "gradle/libs.versions.toml", + "protos/account.proto", + ".github/workflows/ci.yml", + ]) { + const result = classifyChangeScope(["services/account-service/README.md", path]); + + assert.equal(result.runAll, true, path); + assert.equal(result.lightweightOnly, false, path); + assert.deepEqual(result.affectedModules, ALL_MODULES, path); + } +}); + +test("forced and incomplete service-documentation inventories retain complete proof", async () => { + const path = "services/common-platform-core/README.md"; + const forced = classifyChangeScope([path], { forceAll: true }); + assert.equal(forced.runAll, true); + assert.equal(forced.lightweightOnly, false); + assert.deepEqual(forced.affectedModules, ALL_MODULES); + + for (const count of [undefined, 2, "1"]) { + const result = await classifyGithubFiles([path], count); + assert.equal(result.runAll, true); + assert.equal(result.lightweightOnly, false); + assert.deepEqual(result.affectedModules, ALL_MODULES); + } + const malformed = await classifyGithubFiles([{ filename: path, previous_filename: "" }], 1); + assert.equal(malformed.runAll, true); + assert.deepEqual(malformed.affectedModules, ALL_MODULES); +}); + +test("unknown-service documentation still fails closed", async () => { + const result = await classifyGithubFiles(["services/unknown-service/README.md"], 1); + + assert.equal(result.runAll, true); + assert.deepEqual(result.affectedModules, ALL_MODULES); + assert.deepEqual(result.affectedServices, ALL_SERVICES); +}); + +test("renaming runtime inputs to service docs retains their old runtime selection", async () => { + for (const [previous, expectedModules, runAll] of [ + ["services/account-service/src/main/java/Account.java", ["account-service"], false], + ["services/game-session-service/src/main/java/Session.java", + ["game-session-service", "account-service"], false], + ["services/common-platform-core/src/main/java/Shared.java", ALL_MODULES, true], + ["services/unknown-service/src/main/java/Owner.java", ALL_MODULES, true], + ]) { + const result = await classifyGithubFiles([{ + filename: "services/account-service/README.md", + previous_filename: previous, + }], 1); + + assert.equal(result.runAll, runAll, previous); + assert.equal(result.lightweightOnly, false, previous); + assert.deepEqual(result.affectedModules, expectedModules, previous); + } +}); + test("ERD generation remains docs-affecting but never uses the lightweight path", () => { const result = classifyChangeScope(["dev-tools/docs/generate-erd.sh"]); diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 31af3e1766..75cb8eca99 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -33,6 +33,7 @@ A small inbox for unresolved agent, tooling, environment, and workflow issues; s - `2026-11-02` (Pacific/Auckland): SpotBugs crashed during Account authentication extraction. - A distinct local JVM failure occurred at 5:06:16am NZDT on 2 November during the 49-file Account authentication extraction: the Temurin 25.0.5+8 SpotBugs worker `2436948` crashed with `SIGSEGV` in `IndexSetIterator::advance_and_next` while C2 compiled `ValueRangeAnalysisFactory.analyze`. The wrapper returned exit 1 without an observed resource-drain stall. Root preserved the fatal and compiler-replay logs in R1430 and reported the occurrence to Overseer. This differs from the earlier Java 21 G1 daemon failure; a common cause is unproven. Next: retain the unchanged targeted SpotBugs retry outcome and compare exact JVM/frame evidence if it recurs; do not treat passing tests as completion of the failed static gate. + - Recurrence on 3 November: public receiving proof 346 crashed Temurin 25.0.5+8 worker `4180380` during `:common-platform-core:spotbugsTest` with `SIGSEGV` in `PhaseIdealLoop::build_loop_late`. Fatal and replay logs are retained privately in R1430/public-static proof 346 JVM and in the original worktree. That task joins the existing Game Session main SpotBugs proof 198/200 holds pending the Overseer JVM investigation; do not retry it or change JVM options, JDK or host without that investigation’s direction. Other selected enabled checks and documentation pass; the complete static gate remains unqualified. A common cause is unknown. - `2026-11-01` (Pacific/Auckland): Two different repository-network failures interrupted one unchanged CI image build. - #3369 at `208bc8488443` failed runtime-images run `41247930228` resolving Spring Boot mail starter `4.1.2`; independent Maven Central POM and JAR requests subsequently returned HTTP 200. One failed-job retry built all service jars, then failed connecting to `archive.ubuntu.com:443` during base-image APT installation despite its existing retries. These are distinct observed failures, not an application compile failure or a proven common cause. The failed logs remain in R1420 and both events were reported to Overseer. Next: qualify the unchanged image build on its next authorized retry or normal candidate run, retaining the exact failure if network access fails again; do not weaken package verification or mark remote smoke passed from local proof. @@ -55,6 +56,13 @@ A small inbox for unresolved agent, tooling, environment, and workflow issues; s - `2026-11-03` (Pacific/Auckland): Physical issuer retirement lost a fresh Redis connection before mutation. - #3382 substantive Validation run [41474380442](https://github.com/benhook1013/FireMUD/actions/runs/41474380442), Game Session partition 1, passed 85 of 86 physical cases; `retiresOriginalReleasesAndContinuesPastThePhysicalHistoryBound` failed at its release step because a newly opened Lettuce connection disconnected before `ACL WHOAMI`. No Redis mutation was dispatched by that attempt. The unchanged complete case passed locally in proof160 (93.841s); this does not establish the remote cause or completed remote improvement from the separately qualified PostgreSQL fixture pool. Source inspection found no intentional in-test shutdown or ACL change. Next: on a natural recurrence, retain Redis container health/logs and the exact turnover iteration alongside connection events; preserve fail-closed handling and the full history-bound proof. Reported to Overseer; no reconnect, blind mutation retry, assertion reduction or production workaround was added. +- `2026-11-03` (Pacific/Auckland): GitHub job-log connector closes transport during CI failure inspection. + - Repeated per-job connector requests failed with `Transport closed` for #3386 Validation and #3388 World/Python jobs while other metadata reads worked. One later #3388 per-job request succeeded during an active workflow, without explaining the failures; whole-run `gh run view --log` still refused before completion. Both #3389 Account jobs `125829036896` / `125829037055` recurred. Read-only per-job `gh api` log retrieval recovered their bytes into private files; any ANSI-capable retrieval must write directly to the private file rather than a terminal. Cause remains unknown. Next: preserve exact request/transport diagnostics on recurrence and repair the connector; do not rerun CI or replace controller operations to recover logs. + +- `2026-11-04` (Pacific/Auckland): Gameplay controller MCP writes intermittently wait or return transient service errors while the bound CLI remains usable. + - Several native-fix and acknowledgement calls exceeded the initial 30-second tool wait; an unsent `deadline_exceeded` fix attempt and an `overloaded` acknowledgement with unknown outcome were also returned. The acknowledgement request was `request_aca253fec2bd7085257f04174863e644`; retrying its exact key/body/binding through the existing Gameplay CLI recovered it. Doctor verified the same clean `1ef2b58` connection and worker identity. No profile switch, worker replacement or grant reset was used. + - Cause remains unknown. FireController stewardship should compare bound MCP/long-wait concurrency and service traces against CLI round trips, preserving the original requests and idempotency receipts. Continue supported exact-key recovery; a pending response alone does not justify duplicate writes or reviews. + - `2026-11-04` (Pacific/Auckland): FireController automatic Hosted selection can remain stuck without a child operation. - While qualifying #3386, two normal channel-front starts returned `review_busy` although Hosted operation discovery was empty. FireController Worker confirmed an original automatic selection had stayed in `selecting` since 11:36 UTC on 3 November without creating a review operation; childless selections were absent from operation discovery. The original selection and request key are retained, and no duplicate review, queue override or grant was issued. Next: FireController Worker is fixing selector recovery and discovery; verify the installed correction and the original selection’s recovery before treating Hosted progression as restored. From a8458e0b96a01c875b37b46c534668852e5f50ab Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 8 Nov 2026 21:09:51 +1300 Subject: [PATCH 04/17] Consolidate coverage aggregation and complete World gate contracts --- .../action.yml | 103 +++++++ .github/workflows/ci.yml | 274 +----------------- .../tests/ci-lightweight-scope-contract.sh | 48 ++- .../tests/pr-retarget-workflow-contract.sh | 3 +- 4 files changed, 155 insertions(+), 273 deletions(-) create mode 100644 .github/actions/aggregate-slow-service-coverage/action.yml diff --git a/.github/actions/aggregate-slow-service-coverage/action.yml b/.github/actions/aggregate-slow-service-coverage/action.yml new file mode 100644 index 0000000000..0d142d96f9 --- /dev/null +++ b/.github/actions/aggregate-slow-service-coverage/action.yml @@ -0,0 +1,103 @@ +name: Aggregate slow-service coverage +description: Verify partition provenance and merge complete measured service coverage. +inputs: + module: + description: Exact supported slow-service module. + required: true + module-label: + description: Human-readable service label. + required: true +runs: + using: composite + steps: + - name: 🐍 Set Up Python + uses: ./.github/actions/setup-python + with: + requirements: none + + - name: Capture ${{ inputs.module-label }} partition job and artifact provenance + id: provenance + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + env: + CI_RUN_ID: ${{ github.run_id }} + CI_RUN_ATTEMPT: ${{ github.run_attempt }} + CI_EVENT_NAME: ${{ github.event_name }} + CI_REF_NAME: ${{ github.ref_name }} + CI_SOURCE_SHA: ${{ github.sha }} + CI_NATIVE_HEAD_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }} + CI_PROVENANCE_PATH: services/${{ inputs.module }}/build/slow-service-ci-partition-provenance.json + CI_MODULE: ${{ inputs.module }} + with: + script: | + const captureSlowServiceProvenance = require( + require("node:path").join(process.env.GITHUB_WORKSPACE, + ".github/scripts/capture-slow-service-provenance.cjs"), + ); + await captureSlowServiceProvenance({ + github, + context, + env: process.env, + module: process.env.CI_MODULE, + }); + + - name: Select ${{ inputs.module-label }} artifacts from latest effective job outcomes + id: selection + env: + PROVENANCE_PATH: services/${{ inputs.module }}/build/slow-service-ci-partition-provenance.json + SELECTION_PATH: services/${{ inputs.module }}/build/slow-service-ci-partition-selection.json + shell: bash + run: | + python3 dev-tools/validation/slow_service_ci_test_partition.py select-artifacts \ + --module ${{ inputs.module }} \ + --run-id "$GITHUB_RUN_ID" \ + --source-revision "$GITHUB_SHA" \ + --run-attempt "$GITHUB_RUN_ATTEMPT" \ + --provenance-json "$PROVENANCE_PATH" \ + --selection-json "$SELECTION_PATH" \ + --github-output "$GITHUB_OUTPUT" + + - name: Download all effective ${{ inputs.module-label }} partition artifacts + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 + continue-on-error: true + with: + artifact-ids: ${{ steps.selection.outputs.artifact_ids }} + path: services/${{ inputs.module }}/build/slow-service-ci-partition-inputs + merge-multiple: false + + - name: Verify complete ${{ inputs.module-label }} partition and report union + shell: bash + run: | + python3 dev-tools/validation/slow_service_ci_test_partition.py verify-aggregate \ + --module ${{ inputs.module }} \ + --input-dir services/${{ inputs.module }}/build/slow-service-ci-partition-inputs \ + --verified-classes-dir services/${{ inputs.module }}/build/slow-service-ci-verified-classes \ + --selection-json services/${{ inputs.module }}/build/slow-service-ci-partition-selection.json \ + --run-id "$GITHUB_RUN_ID" \ + --source-revision "$GITHUB_SHA" \ + --run-attempt "$GITHUB_RUN_ATTEMPT" + + - name: ⚙️ Set Up Java for ${{ inputs.module-label }} Coverage Aggregation + uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6 + with: + distribution: 'temurin' + java-version: 25 + + - name: ⚙️ Set Up Gradle for ${{ inputs.module-label }} Coverage Aggregation + uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6 + with: + build-scan-publish: true + build-scan-terms-of-use-url: 'https://gradle.com/help/legal-terms-of-use' + build-scan-terms-of-use-agree: 'yes' + cache-read-only: false + + - name: Merge complete ${{ inputs.module-label }} JaCoCo coverage + shell: bash + run: ./gradlew --max-workers=2 '-Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8' :${{ inputs.module }}:jacocoTestReport -PfullCheck -PslowServiceCiCoverageAggregate=${{ inputs.module }} -PslowServiceCiCoverageClassesDirectory=build/slow-service-ci-verified-classes + + - name: 📤 Upload Complete ${{ inputs.module-label }} Coverage Report + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: jacoco-${{ inputs.module }}-complete-report-${{ github.sha }}-attempt-${{ github.run_attempt }} + path: services/${{ inputs.module }}/build/reports/jacoco/test/ + if-no-files-found: error + retention-days: 14 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e8c9f6c761..323c589a7f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1262,94 +1262,11 @@ jobs: fetch-depth: 2 persist-credentials: false - - name: 🐍 Set Up Python - uses: ./.github/actions/setup-python - with: - requirements: none - - - name: Capture Account partition job and artifact provenance - id: provenance - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 - env: - CI_RUN_ID: ${{ github.run_id }} - CI_RUN_ATTEMPT: ${{ github.run_attempt }} - CI_EVENT_NAME: ${{ github.event_name }} - CI_REF_NAME: ${{ github.ref_name }} - CI_SOURCE_SHA: ${{ github.sha }} - CI_NATIVE_HEAD_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }} - CI_PROVENANCE_PATH: services/account-service/build/slow-service-ci-partition-provenance.json - CI_MODULE: account-service - with: - script: | - const captureSlowServiceProvenance = require( - require("node:path").join(process.env.GITHUB_WORKSPACE, - ".github/scripts/capture-slow-service-provenance.cjs"), - ); - await captureSlowServiceProvenance({ - github, - context, - env: process.env, - module: process.env.CI_MODULE, - }); - - - name: Select Account artifacts from latest effective job outcomes - id: selection - env: - PROVENANCE_PATH: services/account-service/build/slow-service-ci-partition-provenance.json - SELECTION_PATH: services/account-service/build/slow-service-ci-partition-selection.json - run: | - python3 dev-tools/validation/slow_service_ci_test_partition.py select-artifacts \ - --module account-service \ - --run-id "$GITHUB_RUN_ID" \ - --source-revision "$GITHUB_SHA" \ - --run-attempt "$GITHUB_RUN_ATTEMPT" \ - --provenance-json "$PROVENANCE_PATH" \ - --selection-json "$SELECTION_PATH" \ - --github-output "$GITHUB_OUTPUT" - - - name: Download all effective Account partition artifacts - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 - continue-on-error: true + - name: Aggregate complete Account coverage + uses: ./.github/actions/aggregate-slow-service-coverage with: - artifact-ids: ${{ steps.selection.outputs.artifact_ids }} - path: services/account-service/build/slow-service-ci-partition-inputs - merge-multiple: false - - - name: Verify complete Account partition and report union - run: | - python3 dev-tools/validation/slow_service_ci_test_partition.py verify-aggregate \ - --module account-service \ - --input-dir services/account-service/build/slow-service-ci-partition-inputs \ - --verified-classes-dir services/account-service/build/slow-service-ci-verified-classes \ - --selection-json services/account-service/build/slow-service-ci-partition-selection.json \ - --run-id "$GITHUB_RUN_ID" \ - --source-revision "$GITHUB_SHA" \ - --run-attempt "$GITHUB_RUN_ATTEMPT" - - - name: ⚙️ Set Up Java for Account Coverage Aggregation - uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6 - with: - distribution: 'temurin' - java-version: 25 - - - name: ⚙️ Set Up Gradle for Account Coverage Aggregation - uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6 - with: - build-scan-publish: true - build-scan-terms-of-use-url: 'https://gradle.com/help/legal-terms-of-use' - build-scan-terms-of-use-agree: 'yes' - cache-read-only: false - - - name: Merge complete Account JaCoCo coverage - run: ./gradlew --max-workers=2 '-Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8' :account-service:jacocoTestReport -PfullCheck -PslowServiceCiCoverageAggregate=account-service -PslowServiceCiCoverageClassesDirectory=build/slow-service-ci-verified-classes - - - name: 📤 Upload Complete Account Coverage Report - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 - with: - name: jacoco-account-service-complete-report-${{ github.sha }}-attempt-${{ github.run_attempt }} - path: services/account-service/build/reports/jacoco/test/ - if-no-files-found: error - retention-days: 14 + module: account-service + module-label: Account game-session-coverage-aggregate: name: Game Session Coverage Aggregate @@ -1373,96 +1290,12 @@ jobs: fetch-depth: 2 persist-credentials: false - - name: 🐍 Set Up Python - uses: ./.github/actions/setup-python + - name: Aggregate complete Game Session coverage + uses: ./.github/actions/aggregate-slow-service-coverage with: - requirements: none + module: game-session-service + module-label: Game Session - - name: Capture Game Session partition job and artifact provenance - id: provenance - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 - env: - CI_RUN_ID: ${{ github.run_id }} - CI_RUN_ATTEMPT: ${{ github.run_attempt }} - CI_EVENT_NAME: ${{ github.event_name }} - CI_REF_NAME: ${{ github.ref_name }} - CI_SOURCE_SHA: ${{ github.sha }} - CI_NATIVE_HEAD_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }} - CI_PROVENANCE_PATH: services/game-session-service/build/slow-service-ci-partition-provenance.json - CI_MODULE: game-session-service - with: - script: | - const captureSlowServiceProvenance = require( - require("node:path").join(process.env.GITHUB_WORKSPACE, - ".github/scripts/capture-slow-service-provenance.cjs"), - ); - await captureSlowServiceProvenance({ - github, - context, - env: process.env, - module: process.env.CI_MODULE, - }); - - - name: Select Game Session artifacts from latest effective job outcomes - id: selection - env: - PROVENANCE_PATH: services/game-session-service/build/slow-service-ci-partition-provenance.json - SELECTION_PATH: services/game-session-service/build/slow-service-ci-partition-selection.json - run: | - python3 dev-tools/validation/slow_service_ci_test_partition.py select-artifacts \ - --module game-session-service \ - --run-id "$GITHUB_RUN_ID" \ - --source-revision "$GITHUB_SHA" \ - --run-attempt "$GITHUB_RUN_ATTEMPT" \ - --provenance-json "$PROVENANCE_PATH" \ - --selection-json "$SELECTION_PATH" \ - --github-output "$GITHUB_OUTPUT" - - - name: Download all effective Game Session partition artifacts - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 - continue-on-error: true - with: - artifact-ids: ${{ steps.selection.outputs.artifact_ids }} - path: services/game-session-service/build/slow-service-ci-partition-inputs - merge-multiple: false - - - name: Verify complete Game Session partition and report union - run: | - python3 dev-tools/validation/slow_service_ci_test_partition.py verify-aggregate \ - --module game-session-service \ - --input-dir services/game-session-service/build/slow-service-ci-partition-inputs \ - --verified-classes-dir services/game-session-service/build/slow-service-ci-verified-classes \ - --selection-json services/game-session-service/build/slow-service-ci-partition-selection.json \ - --run-id "$GITHUB_RUN_ID" \ - --source-revision "$GITHUB_SHA" \ - --run-attempt "$GITHUB_RUN_ATTEMPT" - - - name: ⚙️ Set Up Java for Game Session Coverage Aggregation - uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6 - with: - distribution: 'temurin' - java-version: 25 - - - name: ⚙️ Set Up Gradle for Game Session Coverage Aggregation - uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6 - with: - build-scan-publish: true - build-scan-terms-of-use-url: 'https://gradle.com/help/legal-terms-of-use' - build-scan-terms-of-use-agree: 'yes' - cache-read-only: false - - - name: Merge complete Game Session JaCoCo coverage - run: ./gradlew --max-workers=2 '-Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8' :game-session-service:jacocoTestReport -PfullCheck -PslowServiceCiCoverageAggregate=game-session-service -PslowServiceCiCoverageClassesDirectory=build/slow-service-ci-verified-classes - - - name: 📤 Upload Complete Game Session Coverage Report - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 - with: - name: jacoco-game-session-service-complete-report-${{ github.sha }}-attempt-${{ github.run_attempt }} - path: services/game-session-service/build/reports/jacoco/test/ - if-no-files-found: error - retention-days: 14 - - # Final gating and PR reporting world-coverage-aggregate: name: World Coverage Aggregate needs: [changes, build-and-test-world] @@ -1485,94 +1318,11 @@ jobs: fetch-depth: 2 persist-credentials: false - - name: 🐍 Set Up Python - uses: ./.github/actions/setup-python - with: - requirements: none - - - name: Capture World partition job and artifact provenance - id: provenance - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 - env: - CI_RUN_ID: ${{ github.run_id }} - CI_RUN_ATTEMPT: ${{ github.run_attempt }} - CI_EVENT_NAME: ${{ github.event_name }} - CI_REF_NAME: ${{ github.ref_name }} - CI_SOURCE_SHA: ${{ github.sha }} - CI_NATIVE_HEAD_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }} - CI_PROVENANCE_PATH: services/world-management-service/build/slow-service-ci-partition-provenance.json - CI_MODULE: world-management-service - with: - script: | - const captureSlowServiceProvenance = require( - require("node:path").join(process.env.GITHUB_WORKSPACE, - ".github/scripts/capture-slow-service-provenance.cjs"), - ); - await captureSlowServiceProvenance({ - github, - context, - env: process.env, - module: process.env.CI_MODULE, - }); - - - name: Select World artifacts from latest effective job outcomes - id: selection - env: - PROVENANCE_PATH: services/world-management-service/build/slow-service-ci-partition-provenance.json - SELECTION_PATH: services/world-management-service/build/slow-service-ci-partition-selection.json - run: | - python3 dev-tools/validation/slow_service_ci_test_partition.py select-artifacts \ - --module world-management-service \ - --run-id "$GITHUB_RUN_ID" \ - --source-revision "$GITHUB_SHA" \ - --run-attempt "$GITHUB_RUN_ATTEMPT" \ - --provenance-json "$PROVENANCE_PATH" \ - --selection-json "$SELECTION_PATH" \ - --github-output "$GITHUB_OUTPUT" - - - name: Download all effective World partition artifacts - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 - continue-on-error: true - with: - artifact-ids: ${{ steps.selection.outputs.artifact_ids }} - path: services/world-management-service/build/slow-service-ci-partition-inputs - merge-multiple: false - - - name: Verify complete World partition and report union - run: | - python3 dev-tools/validation/slow_service_ci_test_partition.py verify-aggregate \ - --module world-management-service \ - --input-dir services/world-management-service/build/slow-service-ci-partition-inputs \ - --verified-classes-dir services/world-management-service/build/slow-service-ci-verified-classes \ - --selection-json services/world-management-service/build/slow-service-ci-partition-selection.json \ - --run-id "$GITHUB_RUN_ID" \ - --source-revision "$GITHUB_SHA" \ - --run-attempt "$GITHUB_RUN_ATTEMPT" - - - name: ⚙️ Set Up Java for World Coverage Aggregation - uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6 - with: - distribution: 'temurin' - java-version: 25 - - - name: ⚙️ Set Up Gradle for World Coverage Aggregation - uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6 - with: - build-scan-publish: true - build-scan-terms-of-use-url: 'https://gradle.com/help/legal-terms-of-use' - build-scan-terms-of-use-agree: 'yes' - cache-read-only: false - - - name: Merge complete World JaCoCo coverage - run: ./gradlew --max-workers=2 '-Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8' :world-management-service:jacocoTestReport -PfullCheck -PslowServiceCiCoverageAggregate=world-management-service -PslowServiceCiCoverageClassesDirectory=build/slow-service-ci-verified-classes - - - name: 📤 Upload Complete World Coverage Report - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + - name: Aggregate complete World coverage + uses: ./.github/actions/aggregate-slow-service-coverage with: - name: jacoco-world-management-service-complete-report-${{ github.sha }}-attempt-${{ github.run_attempt }} - path: services/world-management-service/build/reports/jacoco/test/ - if-no-files-found: error - retention-days: 14 + module: world-management-service + module-label: World # Final gating and PR reporting validation-gate: diff --git a/dev-tools/tests/ci-lightweight-scope-contract.sh b/dev-tools/tests/ci-lightweight-scope-contract.sh index 9c811d76f6..ae36b49b3a 100644 --- a/dev-tools/tests/ci-lightweight-scope-contract.sh +++ b/dev-tools/tests/ci-lightweight-scope-contract.sh @@ -736,6 +736,18 @@ require_equal( require_contains(gradle_profile_step, ("with", "path"), "build/reports/profile/", "ci workflow") require_equal(gradle_profile_step, ("with", "retention-days"), "14", "ci workflow") +aggregate_action = load_workflow(str(Path(sys.argv[1]).parents[1] / "actions/aggregate-slow-service-coverage/action.yml")) +require_equal(aggregate_action, ("runs", "using"), "composite", "coverage action") +for key in ("module", "module-label"): + require_equal(aggregate_action, ("inputs", key, "required"), "true", "coverage action") +aggregate_steps = aggregate_action["runs"]["steps"] +for step in aggregate_steps: + if "run" in step: + require_equal(step, ("shell",), "bash", "coverage action") + if "checkout@" in step.get("uses", ""): + raise SystemExit("coverage checkout must remain in the owning job") +aggregate_ci = copy.deepcopy(ci) + for module, job_id, display, prefix in ( ("account-service", "account-coverage-aggregate", "Account", "ACCOUNT"), ("game-session-service", "game-session-coverage-aggregate", "Game Session", "GAME_SESSION"), @@ -751,10 +763,24 @@ for module, job_id, display, prefix in ( "ci workflow", ) require_equal(aggregate_job, ("permissions",), {"actions": "read", "contents": "read"}, "ci workflow") - aggregate_java = find_step(ci, job_id, f"Set Up Java for {display} Coverage Aggregation", "ci workflow") + require_equal(aggregate_job, ("timeout-minutes",), "30", "ci workflow") + steps = aggregate_job["steps"] + if len(steps) != 3 or "harden-runner@" not in steps[0].get("uses", ""): + raise SystemExit("coverage jobs must harden, check out, then aggregate") + checkout = steps[1] + if "actions/checkout@" not in checkout.get("uses", ""): + raise SystemExit("coverage checkout must precede the local composite") + require_equal(checkout, ("with", "ref"), "${{ github.sha }}", "ci workflow") + require_equal(checkout, ("with", "persist-credentials"), "false", "ci workflow") + require_equal(checkout, ("with", "fetch-depth"), "2", "ci workflow") + require_equal(steps[2], ("uses",), "./.github/actions/aggregate-slow-service-coverage", "ci workflow") + require_equal(steps[2], ("with",), {"module": module, "module-label": display}, "ci workflow") + recipe = json.dumps(aggregate_steps).replace("${{ inputs.module }}", module).replace("${{ inputs.module-label }}", display) + aggregate_ci["jobs"][job_id]["steps"] = steps[:2] + json.loads(recipe) + aggregate_java = find_step(aggregate_ci, job_id, f"Set Up Java for {display} Coverage Aggregation", "ci workflow") require_equal(aggregate_java, ("with", "java-version"), "25", "ci workflow") require_equal(aggregate_java, ("with", "distribution"), "temurin", "ci workflow") - capture = find_step(ci, job_id, f"Capture {display} partition job and artifact provenance", "ci workflow") + capture = find_step(aggregate_ci, job_id, f"Capture {display} partition job and artifact provenance", "ci workflow") require_equal(capture, ("env", "CI_MODULE"), module, "ci workflow") require_equal( capture, @@ -781,20 +807,20 @@ for module, job_id, display, prefix in ( "module: process.env.CI_MODULE", "ci workflow", ) - select = find_step(ci, job_id, f"Select {display} artifacts from latest effective job outcomes", "ci workflow") + select = find_step(aggregate_ci, job_id, f"Select {display} artifacts from latest effective job outcomes", "ci workflow") require_contains(select, ("run",), "python3 dev-tools/validation/slow_service_ci_test_partition.py select-artifacts", "ci workflow") require_contains(select, ("run",), f"--module {module}", "ci workflow") - download = find_step(ci, job_id, f"Download all effective {display} partition artifacts", "ci workflow") + download = find_step(aggregate_ci, job_id, f"Download all effective {display} partition artifacts", "ci workflow") require_equal(download, ("continue-on-error",), "true", "ci workflow") require_equal(download, ("with", "artifact-ids"), "${{ steps.selection.outputs.artifact_ids }}", "ci workflow") - verify = find_step(ci, job_id, f"Verify complete {display} partition and report union", "ci workflow") + verify = find_step(aggregate_ci, job_id, f"Verify complete {display} partition and report union", "ci workflow") require_contains(verify, ("run",), "python3 dev-tools/validation/slow_service_ci_test_partition.py verify-aggregate", "ci workflow") require_contains( verify, ("run",), f"--verified-classes-dir services/{module}/build/slow-service-ci-verified-classes", "ci workflow", ) - merge = find_step(ci, job_id, f"Merge complete {display} JaCoCo coverage", "ci workflow") + merge = find_step(aggregate_ci, job_id, f"Merge complete {display} JaCoCo coverage", "ci workflow") require_contains( merge, ("run",), f":{module}:jacocoTestReport -PfullCheck -PslowServiceCiCoverageAggregate={module} -PslowServiceCiCoverageClassesDirectory=build/slow-service-ci-verified-classes", @@ -820,7 +846,7 @@ for module, job_id, display, prefix in ( ) # Execute the shared provenance helper with strict, offline GitHub API mocks. -# This covers both service callers, identity aliases, pagination, and refusal paths. +# This covers all service callers, identity aliases, pagination, and refusal paths. helper_path = Path(sys.argv[1]).resolve().parents[2] / ".github/scripts/capture-slow-service-provenance.cjs" if not helper_path.is_file(): raise SystemExit(f"ci workflow: missing shared provenance helper: {helper_path}") @@ -831,7 +857,7 @@ for module, job_id, display in ( ("world-management-service", "world-coverage-aggregate", "World"), ): capture = find_step( - ci, job_id, f"Capture {display} partition job and artifact provenance", "ci workflow" + aggregate_ci, job_id, f"Capture {display} partition job and artifact provenance", "ci workflow" ) capture_scripts.append({"module": module, "script": capture["with"]["script"]}) capture_node = r""" @@ -1368,10 +1394,12 @@ for flag, result, aggregate in ( gate_case({"CHANGES_RESULT": "failure"}, False) gate_case({"WORKFLOW_LINT": "failure"}, False) gate_case({"OTHER_MODULES_AFFECTED": "false", "ACCOUNT_MODULE_AFFECTED": "false", - "GAME_SESSION_MODULE_AFFECTED": "false", "AFFECTED_MODULES": "[]", + "GAME_SESSION_MODULE_AFFECTED": "false", "WORLD_MODULE_AFFECTED": "false", + "AFFECTED_MODULES": "[]", "BUILD_AND_TEST": "skipped", "BUILD_AND_TEST_ACCOUNT": "skipped", "BUILD_AND_TEST_GAME_SESSION": "skipped", "ACCOUNT_COVERAGE_AGGREGATE": "skipped", - "GAME_SESSION_COVERAGE_AGGREGATE": "skipped"}, True) + "GAME_SESSION_COVERAGE_AGGREGATE": "skipped", "BUILD_AND_TEST_WORLD": "skipped", + "WORLD_COVERAGE_AGGREGATE": "skipped"}, True) require_equal( gate_enforcement_steps[0], ("env", "POSTGRES_RUNTIME_PROOF_CHANGED"), diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index 7b75580023..b47d12f249 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -583,7 +583,8 @@ for job in \ frontend-checks \ build-and-test \ build-and-test-account \ - build-and-test-game-session; do + build-and-test-game-session \ + build-and-test-world; do assert_job_condition ci.yml "$job" "$required_condition" done From ed6342c750c885fa1c142abce766a1629d1ad15d Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 8 Nov 2026 23:12:21 +1300 Subject: [PATCH 05/17] Correct split-matrix prerequisite inventory comment --- dev-tools/tests/pr-required-gate-context-contract.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index ca18bedc37..2db736656a 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -1002,7 +1002,7 @@ names = ["Detect CI-Relevant Changes", "GitHub Workflow Lint", "Buf Generation", "Account Coverage Aggregate", "Game Session Coverage Aggregate", "World Coverage Aggregate", "Validation Gate"] def step(name, conclusion): return {"name": name, "status": "completed", "conclusion": conclusion} -# Exact split-matrix cancellation shape: 21 prerequisites never reached a step; +# Exact split-matrix cancellation shape: 25 prerequisites never reached a step; # both slow-service aggregation prerequisites were skipped without running, # while the always() gate failed only its enforcement step after cancellation. jobs = [{"id": 500 + index, "run_id": 100, "run_attempt": 1, "head_sha": head, From f61712ddb784ecf3501b3a4341e1615f7e60a32a Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 9 Nov 2026 00:20:55 +1300 Subject: [PATCH 06/17] Cache verified GitHub CLI archives and keep routine review proof in Controller --- .github/actions/setup-gh/action.yml | 24 +++- design/developer-workflows/pr-lifecycle.md | 1 + .../workflow_version_authority_contract.py | 124 ++++++++++++++++++ 3 files changed, 143 insertions(+), 6 deletions(-) diff --git a/.github/actions/setup-gh/action.yml b/.github/actions/setup-gh/action.yml index f505808d50..7e3f707948 100644 --- a/.github/actions/setup-gh/action.yml +++ b/.github/actions/setup-gh/action.yml @@ -7,17 +7,28 @@ runs: id: versions uses: ./.github/actions/load-workflow-tool-versions - - name: Install pinned GitHub CLI + - name: Validate supported runner shell: bash - env: - GH_VERSION: ${{ steps.versions.outputs.gh-version }} - GH_SHA256: ${{ steps.versions.outputs.gh-linux-amd64-sha256 }} run: | set -euo pipefail if [[ "${RUNNER_OS:-}" != Linux || "${RUNNER_ARCH:-}" != X64 ]]; then echo "pinned GitHub CLI installer requires a Linux X64 runner" >&2 exit 1 fi + + - name: Restore pinned GitHub CLI archive + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6 + with: + path: ${{ runner.temp }}/firemud-gh/${{ steps.versions.outputs.gh-version }}/gh.tar.gz + key: firemud-gh-${{ runner.os }}-${{ runner.arch }}-v${{ steps.versions.outputs.gh-version }}-${{ steps.versions.outputs.gh-linux-amd64-sha256 }} + + - name: Install pinned GitHub CLI + shell: bash + env: + GH_VERSION: ${{ steps.versions.outputs.gh-version }} + GH_SHA256: ${{ steps.versions.outputs.gh-linux-amd64-sha256 }} + run: | + set -euo pipefail gh_version="${GH_VERSION:?}" gh_sha256="${GH_SHA256:?}" install_root="${RUNNER_TEMP:?}/firemud-gh/${gh_version}" @@ -40,13 +51,14 @@ runs: mv -fT -- "$temporary_archive" "$archive_path" trap - EXIT fi + # Always verify restored or downloaded bytes before extracting the pinned binary. + printf '%s %s\n' "$gh_sha256" "$archive_path" \ + | sha256sum --check --status rm -rf -- "$extraction_dir" mkdir -p -- "$extraction_dir" tar -xzf "$archive_path" -C "$extraction_dir" -- "gh_${gh_version}_linux_amd64/bin/gh" install -m 0755 "$extraction_dir/gh_${gh_version}_linux_amd64/bin/gh" "$install_dir/gh" - printf '%s %s\n' "$gh_sha256" "$archive_path" \ - | sha256sum --check --status reported_version="$("$install_dir/gh" --version | awk 'NR == 1 { print $3 }')" if [[ "$reported_version" != "$gh_version" ]]; then echo "::error title=GitHub CLI version mismatch::Expected ${gh_version}, but the installed binary reported ${reported_version}." >&2 diff --git a/design/developer-workflows/pr-lifecycle.md b/design/developer-workflows/pr-lifecycle.md index 21a0e97a1e..fc04859888 100644 --- a/design/developer-workflows/pr-lifecycle.md +++ b/design/developer-workflows/pr-lifecycle.md @@ -14,6 +14,7 @@ FireMUD owns the project authority and safety requirements below. Follow the act - Preserve actual human stops and allocations independently of candidate preparation and merge readiness. Reaching a configured discovery limit or stopping a channel does not erase findings, grant coverage, or establish readiness. Do not reopen, replace, reset, or approximate controls without the required authority. Deliberate queue removal requires explicit User authorization and an audited reason; merging or closing a PR does not grant it. - Adjudicate findings as accepted, routed, or rejected with a concrete outcome and evidence. Accepted findings remain source-owned correction obligations until verified fixed. Routed observations identify another owner without claiming that owner’s acceptance or fix. Target owners independently disposition incoming routes and verify resolutions; retargeting preserves the open obligation and prior ownership, including honest unassigned work. Open outgoing routes do not hold the source’s merge readiness. Preserve source linkage and original evidence when correcting a disposition; newly accepted findings still require fixes. - Summary-only and outside-diff findings require verification and disposition as well as inline findings. Historical accepted-fixed evidence does not replace current verification. Resolve a thread only after its exact finding is fixed at the current published head; do not conceal unresolved work through thread resolution or record edits. +- Routine bot findings do not need public replies or reflexive `@coderabbit` exchanges. Record the assessment, decision, and any fix and verification proof in FireController; resolve verified-fixed threads without extra chat under the current-published-head rule above. Reply only when genuine clarification or reconsideration is needed, or to provide necessary context for human reviewers, and only within applicable communication authorization. - Keep private captures, review history, findings, and uncertain publication intents intact. Recover only through the installed release’s supported guarded operations within existing authority. Recording, recovery, imports, or publication alone grant no provider credit, fix proof, CI result, or merge authority. Do not blind-repost an uncertain checkpoint, invent attribution, or infer delivery failure from public absence. Unsupported or ambiguous recovery remains a reported hold for FireController Worker. - Follow the configured admission, provider-exclusion, quota, and cooldown controls; do not request against an active or rate-limited target or enable paid capacity. Use included quota only. Supported operations and recorded allowances do not themselves grant authority or clear unrelated holds. - For CI observation using a shared GitHub credential budget, coordinate one observer across relevant workers and runs. Prefer the supported native batched CI wait and existing inbox notices for followed PR merges, closures, and review completions; other workers consume those results and continue independent work. Add review-activity or known-operation waits when a relevant review hold or retained operation needs observation. Do not fan out simultaneous per-run watchers or duplicate an active observer. Use narrow run-list or run-view reads at least 60 seconds apart only when a supported wait cannot supply the required evidence, and check status at meaningful readiness transitions. Honor evidenced reset/retry-after times; report a hold when no time is available. diff --git a/dev-tools/tests/workflow_version_authority_contract.py b/dev-tools/tests/workflow_version_authority_contract.py index b0eb57c2af..f1095cf25d 100644 --- a/dev-tools/tests/workflow_version_authority_contract.py +++ b/dev-tools/tests/workflow_version_authority_contract.py @@ -3,12 +3,15 @@ from __future__ import annotations +import hashlib import importlib.util +import io import json import os import re import shlex import subprocess +import tarfile import tempfile from collections import Counter from pathlib import Path @@ -1198,6 +1201,127 @@ def expect_workflow_failure(steps, expected_message, *, path=workflow_fixture, j if required_setup_gh_fragment not in setup_gh_text: fail(f"setup-gh installer does not consume canonical authority: {required_setup_gh_fragment}") + gh_steps = load(actions / "setup-gh/action.yml")["runs"]["steps"] + if [step.get("name") for step in gh_steps] != [ + "Load workflow tool versions", + "Validate supported runner", + "Restore pinned GitHub CLI archive", + "Install pinned GitHub CLI", + ]: + fail("setup-gh must validate the runner, restore the archive, and always install it") + gh_validation, gh_cache, gh_install = gh_steps[1:] + if not re.fullmatch(r"actions/cache@[0-9a-f]{40}", gh_cache.get("uses", "")): + fail("setup-gh archive cache must use an immutable action revision") + if gh_cache.get("with") != { + "path": "${{ runner.temp }}/firemud-gh/${{ steps.versions.outputs.gh-version }}/gh.tar.gz", + "key": ( + "firemud-gh-${{ runner.os }}-${{ runner.arch }}-v${{ steps.versions.outputs.gh-version }}-" + "${{ steps.versions.outputs.gh-linux-amd64-sha256 }}" + ), + }: + fail("setup-gh must cache only the archive under one exact OS/arch/version/checksum key") + if any("if" in step or "continue-on-error" in step for step in gh_steps): + fail("setup-gh must not skip validation or installation on cache hits or suppress failure") + for runner_os, runner_arch, expected_status in (("Linux", "X64", 0), ("Windows", "X64", 1), ("Linux", "ARM64", 1)): + result = subprocess.run( + ["bash", "-c", gh_validation["run"]], + env={**os.environ, "RUNNER_OS": runner_os, "RUNNER_ARCH": runner_arch}, + capture_output=True, + text=True, + check=False, + ) + if result.returncode != expected_status: + fail(f"setup-gh runner validation failed: {runner_os}/{runner_arch}: {result}") + + # Execute the actual installer with real tar/checksum tools and a download-only fixture. + with tempfile.TemporaryDirectory(prefix="firemud-gh-contract-") as gh_fixture: + fixture = Path(gh_fixture) + fixture_bin = fixture / "bin" + fixture_bin.mkdir() + curl = fixture_bin / "curl" + curl.write_text( + "#!/usr/bin/env bash\nset -euo pipefail\n" + 'printf "download\\n" >> "$GH_DOWNLOAD_LOG"\n' + '[[ " $* " == *" $GH_EXPECTED_URL "* ]]\n' + '[[ "${@: -2:1}" == -o ]]\n' + 'if [[ "$GH_DOWNLOAD_MODE" == fail ]]; then\n' + ' printf partial > "${@: -1}"\n exit 28\nfi\n' + 'cp -- "$GH_FIXTURE_ARCHIVE" "${@: -1}"\n', + encoding="utf-8", + ) + curl.chmod(0o755) + version = a["GH_VERSION"] + payload = ( + '#!/usr/bin/env bash\nprintf "version-check\\n" >> "$GH_EXECUTION_LOG"\n' + f"printf 'gh version {version} (fixture)\\n'\n" + ).encode() + archive = fixture / "fixture.tar.gz" + wrong_version_archive = fixture / "wrong-version.tar.gz" + for archive_file, binary in ( + (archive, payload), + (wrong_version_archive, payload.replace(f"gh version {version}".encode(), b"gh version 0.0.0")), + ): + with tarfile.open(archive_file, "w:gz") as bundle: + member = tarfile.TarInfo(f"gh_{version}_linux_amd64/bin/gh") + member.mode, member.size = 0o755, len(binary) + bundle.addfile(member, io.BytesIO(binary)) + for case, cached, download_mode, expected_status in ( + ("cold", None, "ok", 0), + ("warm", archive.read_bytes(), "fail", 0), + ("corrupt", b"corrupt cache", "ok", 0), + ("outage", None, "fail", 28), + ("mismatch", None, "ok", 1), + ("version", None, "ok", 1), + ): + runner_temp = fixture / case + install_root = runner_temp / "firemud-gh" / version + install_root.mkdir(parents=True) + archive_path = install_root / "gh.tar.gz" + if cached is not None: + archive_path.write_bytes(cached) + stale_binary = install_root / "extracted" / f"gh_{version}_linux_amd64/bin/gh" + stale_binary.parent.mkdir(parents=True) + stale_binary.write_text("stale extraction must be replaced\n", encoding="utf-8") + path_file, download_log, execution_log = (runner_temp / name for name in ("path", "download", "execution")) + path_file.touch() + download_archive = wrong_version_archive if case == "version" else archive + expected_checksum = hashlib.sha256(download_archive.read_bytes()).hexdigest() + result = subprocess.run( + ["bash", "-c", gh_install["run"]], + env={ + **os.environ, + "PATH": f"{fixture_bin}{os.pathsep}{os.environ['PATH']}", + "GH_VERSION": version, + "GH_SHA256": "0" * 64 if case == "mismatch" else expected_checksum, + "RUNNER_TEMP": str(runner_temp), + "GITHUB_PATH": str(path_file), + "GH_FIXTURE_ARCHIVE": str(download_archive), + "GH_EXPECTED_URL": ( + f"https://github.com/cli/cli/releases/download/v{version}/gh_{version}_linux_amd64.tar.gz" + ), + "GH_DOWNLOAD_MODE": download_mode, + "GH_DOWNLOAD_LOG": str(download_log), + "GH_EXECUTION_LOG": str(execution_log), + }, + capture_output=True, + text=True, + check=False, + ) + if result.returncode != expected_status: + fail(f"setup-gh {case} fixture failed: {result}") + if download_log.exists() != (case != "warm") or list(install_root.glob("gh.tar.gz.*")): + fail(f"setup-gh {case} must avoid warm downloads and clean staged downloads") + if expected_status == 0: + if archive_path.read_bytes() != archive.read_bytes() or stale_binary.read_bytes() != payload: + fail(f"setup-gh {case} must replace stale bytes with the verified archive and extraction") + if path_file.read_text() != f"{install_root}/bin\n" or execution_log.read_text() != "version-check\n": + fail(f"setup-gh {case} must check the installed version before publishing its PATH") + elif case == "version": + if path_file.read_text() or "GitHub CLI version mismatch" not in result.stderr: + fail("setup-gh must reject a checksum-valid archive reporting the wrong version") + elif archive_path.exists() or path_file.read_text() or execution_log.exists(): + fail(f"setup-gh {case} must not promote, execute, or expose a failed download") + setup_kubectl_text = (actions / "setup-kubectl/action.yml").read_text() if "azure/setup-kubectl@" in setup_kubectl_text or "actions/cache@" in setup_kubectl_text: fail("setup-kubectl must use a direct, non-cached installer") From f97e858d45fc1456a963be32986e8392527edde2 Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 9 Nov 2026 01:00:03 +1300 Subject: [PATCH 07/17] Expose safe phase timings for pinned CLI downloads --- .github/actions/setup-gh/action.yml | 6 +++ .../workflow_version_authority_contract.py | 40 ++++++++++++++++++- 2 files changed, 44 insertions(+), 2 deletions(-) diff --git a/.github/actions/setup-gh/action.yml b/.github/actions/setup-gh/action.yml index 7e3f707948..70ff0abf18 100644 --- a/.github/actions/setup-gh/action.yml +++ b/.github/actions/setup-gh/action.yml @@ -42,8 +42,14 @@ runs: | sha256sum --check --status; then temporary_archive="$(mktemp -- "${install_root}/gh.tar.gz.XXXXXX")" trap 'rm -f -- "$temporary_archive"' EXIT + # Emit numeric diagnostics once per curl invocation, including failures, without signed redirect URLs. + curl_metrics='setup_gh_download_http_code=%{http_code} setup_gh_download_redirect_count=%{num_redirects}' + curl_metrics+=' setup_gh_download_dns_seconds=%{time_namelookup} setup_gh_download_connect_seconds=%{time_connect}' + curl_metrics+=' setup_gh_download_tls_seconds=%{time_appconnect} setup_gh_download_first_byte_seconds=%{time_starttransfer}' + curl_metrics+=' setup_gh_download_total_seconds=%{time_total}' curl -fsSL --retry 3 --retry-delay 2 --retry-max-time 30 \ --connect-timeout 10 --max-time 60 \ + --write-out "${curl_metrics}\n" \ "https://github.com/cli/cli/releases/download/v${gh_version}/gh_${gh_version}_linux_amd64.tar.gz" \ -o "$temporary_archive" printf '%s %s\n' "$gh_sha256" "$temporary_archive" \ diff --git a/dev-tools/tests/workflow_version_authority_contract.py b/dev-tools/tests/workflow_version_authority_contract.py index f1095cf25d..2c960cec07 100644 --- a/dev-tools/tests/workflow_version_authority_contract.py +++ b/dev-tools/tests/workflow_version_authority_contract.py @@ -1187,6 +1187,7 @@ def expect_workflow_failure(steps, expected_message, *, path=workflow_fixture, j setup_gh_curl_pattern = ( r"(?m)^\s*curl -fsSL --retry 3 --retry-delay 2 --retry-max-time 30 \\\n" r"\s*--connect-timeout 10 --max-time 60 \\\n" + r'\s*--write-out "\$\{curl_metrics\}\\n" \\\n' r'\s*"https://github\.com/cli/cli/releases/download/v\$\{gh_version\}/gh_\$\{gh_version\}_linux_amd64\.tar\.gz" \\\n' r'\s*-o "\$temporary_archive"$' ) @@ -1210,6 +1211,17 @@ def expect_workflow_failure(steps, expected_message, *, path=workflow_fixture, j ]: fail("setup-gh must validate the runner, restore the archive, and always install it") gh_validation, gh_cache, gh_install = gh_steps[1:] + gh_metric_variables = { + "http_code": "200", + "num_redirects": "1", + "time_namelookup": "0.010000", + "time_connect": "0.020000", + "time_appconnect": "0.030000", + "time_starttransfer": "0.040000", + "time_total": "0.050000", + } + if sorted(re.findall(r"%\{([^}]+)\}", gh_install["run"])) != sorted(gh_metric_variables): + fail("setup-gh curl diagnostics must expose only the fixed numeric HTTP/redirect/timing fields") if not re.fullmatch(r"actions/cache@[0-9a-f]{40}", gh_cache.get("uses", "")): fail("setup-gh archive cache must use an immutable action revision") if gh_cache.get("with") != { @@ -1244,9 +1256,19 @@ def expect_workflow_failure(steps, expected_message, *, path=workflow_fixture, j 'printf "download\\n" >> "$GH_DOWNLOAD_LOG"\n' '[[ " $* " == *" $GH_EXPECTED_URL "* ]]\n' '[[ "${@: -2:1}" == -o ]]\n' + 'output="${@: -1}"\nformat=\n' + 'while (($#)); do\n' + ' if [[ "$1" == --write-out ]]; then format="$2"; shift 2; else shift; fi\n' + 'done\n' + + "".join( + f"format=${{format//'%{{{variable}}}'/'{value}'}}\n" + for variable, value in gh_metric_variables.items() + ) + + 'format=${format//\'%{url_effective}\'/"$GH_SIGNED_URL_FIXTURE"}\n' + 'printf "%b" "$format"\n' 'if [[ "$GH_DOWNLOAD_MODE" == fail ]]; then\n' - ' printf partial > "${@: -1}"\n exit 28\nfi\n' - 'cp -- "$GH_FIXTURE_ARCHIVE" "${@: -1}"\n', + ' printf partial > "$output"\n exit 28\nfi\n' + 'cp -- "$GH_FIXTURE_ARCHIVE" "$output"\n', encoding="utf-8", ) curl.chmod(0o755) @@ -1302,6 +1324,8 @@ def expect_workflow_failure(steps, expected_message, *, path=workflow_fixture, j "GH_DOWNLOAD_MODE": download_mode, "GH_DOWNLOAD_LOG": str(download_log), "GH_EXECUTION_LOG": str(execution_log), + "GH_TOKEN": "fixture-credential-must-not-be-logged", + "GH_SIGNED_URL_FIXTURE": "https://release-assets.example/asset?signature=fixture-secret", }, capture_output=True, text=True, @@ -1309,6 +1333,18 @@ def expect_workflow_failure(steps, expected_message, *, path=workflow_fixture, j ) if result.returncode != expected_status: fail(f"setup-gh {case} fixture failed: {result}") + expected_metrics = ( + "setup_gh_download_http_code=200 setup_gh_download_redirect_count=1 " + "setup_gh_download_dns_seconds=0.010000 setup_gh_download_connect_seconds=0.020000 " + "setup_gh_download_tls_seconds=0.030000 setup_gh_download_first_byte_seconds=0.040000 " + "setup_gh_download_total_seconds=0.050000\n" + ) + if result.stdout != ("" if case == "warm" else expected_metrics): + fail(f"setup-gh {case} must emit exactly the fixed metrics once per download invocation") + if any(secret in result.stdout + result.stderr for secret in ( + "https://", "signature=", "fixture-secret", "fixture-credential-must-not-be-logged", + )): + fail(f"setup-gh {case} diagnostics exposed a URL, query string, or credential") if download_log.exists() != (case != "warm") or list(install_root.glob("gh.tar.gz.*")): fail(f"setup-gh {case} must avoid warm downloads and clean staged downloads") if expected_status == 0: From 0e60a7b99c473f81fe5d79a5dedb7cf45b470600 Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 9 Nov 2026 04:40:27 +1300 Subject: [PATCH 08/17] Retain World preparation cache-miss diagnostics --- .github/scripts/run-gradle-module-checks.sh | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.github/scripts/run-gradle-module-checks.sh b/.github/scripts/run-gradle-module-checks.sh index db34bc1039..93349d682c 100644 --- a/.github/scripts/run-gradle-module-checks.sh +++ b/.github/scripts/run-gradle-module-checks.sh @@ -35,12 +35,17 @@ if [[ ( "$MODULE" == "account-service" || "$MODULE" == "game-session-service" || fi done + declare -a PREPARE_LOG_ARGS=() + if [[ "$MODULE" == "world-management-service" ]]; then + PREPARE_LOG_ARGS+=(--info) + fi + # Build every current service test class first, then freeze one source-derived selector. bash "$ROOT_DIR/dev-tools/validation/run-gradle-with-dependency-recovery.sh" \ --runner "$ROOT_DIR/gradlew" -- \ --max-workers=2 \ '-Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8' \ - "${PREPARE_TASKS[@]}" -PfullCheck --profile + "${PREPARE_TASKS[@]}" -PfullCheck --profile "${PREPARE_LOG_ARGS[@]}" python3 "$ROOT_DIR/dev-tools/validation/slow_service_ci_test_partition.py" plan \ --module "$MODULE" \ --partition "$PARTITION" \ From 724a7b4a7bb20a1c4320db7754a47f1a2d3dfed8 Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 9 Nov 2026 05:18:54 +1300 Subject: [PATCH 09/17] Measure World owner composition phase durations --- ...ationOwnerCompositionCrossServiceTest.java | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java index 7f4e0d1c26..e8c044e834 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java @@ -245,6 +245,8 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mockito; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.aop.framework.ProxyFactory; import org.springframework.boot.ssl.SslBundle; import org.springframework.boot.ssl.SslBundles; @@ -291,6 +293,9 @@ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") class WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest { + private static final Logger LOGGER = + LoggerFactory.getLogger( + WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.class); private static final String NAMESPACE = "firemud"; private static final tools.jackson.databind.ObjectMapper JSON = JsonMapper.builder().build(); private static final Network NETWORK = Network.newNetwork(); @@ -589,6 +594,8 @@ private void compose( var sharedAuthoredSource = controlledSource("controlled-upstream", tenant); var sharedCreation = CanonicalHumanPublicationOwnerTestFixtures.creationEvidence(sharedAuthoredSource); + long compositionStartedNanos = System.nanoTime(); + logCompositionTiming(compositionStartedNanos, "fixtures-start"); try (var account = new AccountControlUiOriginalOrderFixture( ACCOUNT.getJdbcUrl(), @@ -601,6 +608,7 @@ private void compose( true); var world = database(WORLD, "world-management-service", true); var gs = database(GS, "game-session-service", true)) { + logCompositionTiming(compositionStartedNanos, "fixture-resources-ready"); var issuer = new AccountOriginalStartSessionAuthorizationProofFixture( account, proofDirectory.resolve("issuer"), NAMESPACE); @@ -721,6 +729,7 @@ public void attachAccountRedemptionProjection( claim.get().ownerMutationId(), input.gameSessionOwnerAttemptId(), claim.get().ownerFence()); + logCompositionTiming(compositionStartedNanos, "owner-preparation-ready"); var pki = new WorldOriginalStartSessionPreparationProofPki(proofDirectory.resolve("pki")); var factory = new GrpcChannelFactory(); var currentAttemptRefusal = new AtomicReference(); @@ -1084,6 +1093,7 @@ public ServerCall.Listener interceptCall( pki.client("game-session-service"), false); try { + logCompositionTiming(compositionStartedNanos, "transport-ready"); Map> worldBefore = rows( world.dsl(), @@ -1903,6 +1913,7 @@ public void close() {} } // Current Game Session association remains STARTING; this is not admission or delivery. } finally { + logCompositionTiming(compositionStartedNanos, "cleanup-start"); channel.shutdownNow(); assertThat(channel.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); } @@ -1912,9 +1923,21 @@ public void close() {} } finally { shutdown(gsServer); } + } finally { + logCompositionTiming(compositionStartedNanos, "composition-exit"); } } + // Subtract adjacent cumulative milestones for phase durations. Exit markers do not imply success. + private static void logCompositionTiming(long startedNanos, String phase) { + long elapsedNanos = System.nanoTime() - startedNanos; + LOGGER.info( + "World owner composition timing: invocation={} phase={} elapsedMillis={}", + startedNanos, + phase, + TimeUnit.NANOSECONDS.toMillis(elapsedNanos)); + } + private static CanonicalInitialAdmissionRequest canonicalAdmissionRequest( WorldCanonicalInitialAdmissionHold.HoldIdentity identity) { var request = identity.request(); From 858a1ae96d9ea02e7a732248834e2f85c3749cd7 Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 9 Nov 2026 05:40:17 +1300 Subject: [PATCH 10/17] Capture bounded Account CI worker stall diagnostics --- .../actions/check-gradle-module/action.yml | 1 + .github/scripts/run-gradle-module-checks.sh | 10 +- .../tests/test_gradle_compile_failure.py | 215 +++++++++++++- .../collect-gradle-compile-failure.py | 275 +++++++++++++++++- 4 files changed, 495 insertions(+), 6 deletions(-) diff --git a/.github/actions/check-gradle-module/action.yml b/.github/actions/check-gradle-module/action.yml index ae18897a0f..2e077b0932 100644 --- a/.github/actions/check-gradle-module/action.yml +++ b/.github/actions/check-gradle-module/action.yml @@ -133,5 +133,6 @@ runs: path: | build/reports/profile/ build/reports/compile-failure/${{ inputs.module }}/ + build/reports/gradle-stall/${{ inputs.module }}/ if-no-files-found: warn retention-days: 14 diff --git a/.github/scripts/run-gradle-module-checks.sh b/.github/scripts/run-gradle-module-checks.sh index 93349d682c..55e6cb0b5e 100644 --- a/.github/scripts/run-gradle-module-checks.sh +++ b/.github/scripts/run-gradle-module-checks.sh @@ -69,6 +69,14 @@ if [[ -z "$CHECK_LOG" ]]; then '-Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8' \ ":${MODULE}:check" "${CHECK_ARGS[@]}" --profile fi +declare -a CAPTURE_ARGS=() +# Observe Account's stalled forks only on an isolated hosted Linux runner. +if [[ "$MODULE" == "account-service" && "$PARTITION" != "full" && + "${GITHUB_ACTIONS:-}" == true && "${RUNNER_ENVIRONMENT:-}" == github-hosted && + "${RUNNER_OS:-}" == Linux ]]; then + CAPTURE_ARGS+=(--root "$ROOT_DIR" --stall-output + "$ROOT_DIR/build/reports/gradle-stall/$MODULE/partition-$PARTITION") +fi set +e bash "$ROOT_DIR/dev-tools/validation/run-gradle-with-dependency-recovery.sh" \ --runner "$ROOT_DIR/gradlew" -- \ @@ -78,7 +86,7 @@ bash "$ROOT_DIR/dev-tools/validation/run-gradle-with-dependency-recovery.sh" \ "${CHECK_ARGS[@]}" \ --profile --info --console=plain 2>&1 | \ ( - python3 "$ROOT_DIR/dev-tools/validation/collect-gradle-compile-failure.py" --capture-log "$CHECK_LOG" + python3 "$ROOT_DIR/dev-tools/validation/collect-gradle-compile-failure.py" --capture-log "$CHECK_LOG" "${CAPTURE_ARGS[@]}" capture_status=$? if (( capture_status != 0 )); then cat >/dev/null diff --git a/dev-tools/tests/test_gradle_compile_failure.py b/dev-tools/tests/test_gradle_compile_failure.py index 2c37ce5d85..523f00aec2 100644 --- a/dev-tools/tests/test_gradle_compile_failure.py +++ b/dev-tools/tests/test_gradle_compile_failure.py @@ -5,13 +5,14 @@ import json import os import shutil +import signal import subprocess import sys import tempfile import time import unittest from pathlib import Path -from unittest.mock import patch +from unittest.mock import Mock, patch ROOT = Path(__file__).resolve().parents[2] SPEC = importlib.util.spec_from_file_location( @@ -41,6 +42,218 @@ def write(self, relative, content='source'): path.write_text(content) return path + def stall_identity(self, pid=123, parent=100, role='daemon'): + return {'pid': pid, 'ppid': parent, 'start': 42, 'role': role, + 'state': 'S', 'cpu_ticks': 1, 'rss_pages': 10, 'jcmd': '/unused/jcmd'} + + def test_stall_timer_activity_attribution_and_one_batch(self): + identity = self.stall_identity() + with patch.object(CAPTURE.time, 'monotonic', return_value=0) as clock, patch.object( + CAPTURE, 'java_identity', return_value=identity), patch.object( + CAPTURE.subprocess, 'Popen') as launch, patch.object(CAPTURE.os, 'killpg') as kill, patch.object( + CAPTURE, 'owns_session', return_value=True): + observer = CAPTURE.StallObserver(self.root, self.output) + observer.observe(b'The client will now receive all logging from the daemon (pi') + observer.observe(b'd: 123). The daemon log file: secret') + self.assertEqual(identity, observer.daemon) + clock.return_value = 299 + observer.tick() + launch.assert_not_called() + observer.observe(b'progress') + clock.return_value = 598 + observer.tick() + launch.assert_not_called() + clock.return_value = 599 + observer.tick() + launch.assert_called_once() + self.assertTrue(launch.call_args.kwargs['start_new_session']) + self.assertEqual(subprocess.DEVNULL, launch.call_args.kwargs['stdin']) + clock.return_value = 690 + observer.tick() + kill.assert_called_once() + observer.observe(b'new progress') + clock.return_value = 1000 + observer.tick() + launch.assert_called_once() + + def test_stall_without_daemon_and_launch_failure_are_nonfatal(self): + with patch.object(CAPTURE.time, 'monotonic', side_effect=[0, 301]), patch.object( + CAPTURE.subprocess, 'Popen') as launch: + observer = CAPTURE.StallObserver(self.root, self.output) + observer.tick() + launch.assert_called_once() + self.assertIn('null', launch.call_args.args[0]) + with patch.object(CAPTURE.time, 'monotonic', side_effect=[0, 301]), patch.object( + CAPTURE.subprocess, 'Popen', side_effect=OSError('unavailable')): + observer = CAPTURE.StallObserver(self.root, self.output) + observer.daemon = self.stall_identity() + observer.tick() + self.assertTrue(observer.attempted) + self.assertIsNone(observer.child) + + def test_stall_processes_include_both_workers_exclude_unrelated_and_reused(self): + proc = self.root / 'proc' + java = self.write('jdk/bin/java') + def process(pid, parent, main, display=b''): + base = proc / str(pid) + base.mkdir(parents=True) + fields = ['0'] * 22 + fields[0], fields[1], fields[19] = 'S', str(parent), '42' + (base / 'stat').write_text(f'{pid} (java) ' + ' '.join(fields)) + (base / 'cmdline').write_bytes(b'java\0' + main + b'\0' + display + b'\0SECRET\0') + (base / 'exe').symlink_to(java) + process(100, 1, b'org.gradle.launcher.daemon.bootstrap.GradleDaemon') + for pid in (101, 102): + process(pid, 100, b'worker.org.gradle.process.internal.worker.GradleWorkerMain', + b'Gradle Test Executor 4') + process(103, 999, b'worker.org.gradle.process.internal.worker.GradleWorkerMain', + b'Gradle Test Executor 5') + process(104, 100, b'other.JavaMain') + with patch.object(CAPTURE, 'PROC_ROOT', proc): + daemon = CAPTURE.java_identity(100) + selected = CAPTURE.stall_processes(daemon) + self.assertEqual({100, 101, 102}, {p['pid'] for p in selected}) + self.assertNotIn('SECRET', json.dumps(selected)) + self.assertEqual([], CAPTURE.stall_processes({**daemon, 'start': 43})) + with patch.object(CAPTURE, 'STALL_MAX_PROCESSES', 2): + self.assertEqual(2, len(CAPTURE.stall_processes(daemon))) + + def test_stall_sanitizer_rejects_names_secrets_and_diagnostic_prose(self): + raw = (b'"SECRET-password" #17 tid=0xabc nid=0xdef waiting\n' + b' java.lang.Thread.State: WAITING (parking)\n' + b' at java.base@25/java.lang.Object.wait0(Native Method)\n' + b' at org.example.Work.run(Work.java:42)\n' + b' - locked <0xabc> (a java.lang.Object)\n' + b'JAVA_TOOL_OPTIONS=SECRET\njdbc:postgresql://SECRET\n' + b'SELECT SECRET FROM private\nVM.command_line SECRET\n') + output = CAPTURE.sanitized_threads(raw) + self.assertNotIn('SECRET', output) + self.assertIn('#17 tid=0xabc nid=0xdef', output) + self.assertIn('WAITING', output) + self.assertIn('Work.run(Work.java:42)', output) + self.assertIn('locked <0xabc>', output) + + def test_stall_identity_change_never_attaches(self): + original = self.stall_identity() + with patch.object(CAPTURE, 'java_identity', return_value={**original, 'start': 43}), patch.object( + CAPTURE.subprocess, 'Popen') as launch: + result = CAPTURE.thread_snapshot(original) + self.assertEqual('exited-or-changed', result['status']) + launch.assert_not_called() + + def test_stall_fake_jcmd_output_limit_and_timeout(self): + fake = self.write('jcmd', '#!/usr/bin/env python3\n' + 'print("at org.example.Work.run(Work.java:42)", flush=True)\n' + 'print("SECRET" * 1000, flush=True)\n' + 'import time; time.sleep(10)\n') + fake.chmod(0o755) + identity = {**self.stall_identity(), 'jcmd': str(fake)} + with patch.object(CAPTURE, 'java_identity', return_value=identity), patch.object( + CAPTURE, 'STALL_DUMP_BYTES', 100): + result = CAPTURE.thread_snapshot(identity) + self.assertEqual('limited', result['status']) + self.assertNotIn('SECRET', json.dumps(result)) + self.assertNotIn('jcmd', result) + fake.write_text('#!/usr/bin/env python3\nimport time; time.sleep(10)\n') + with patch.object(CAPTURE, 'java_identity', return_value=identity), patch.object( + CAPTURE, 'STALL_COMMAND_SECONDS', 0.1): + result = CAPTURE.thread_snapshot(identity) + self.assertEqual('timeout', result['status']) + + def test_stall_missing_jcmd_is_nonfatal(self): + identity = self.stall_identity() + with patch.object(CAPTURE, 'java_identity', return_value=identity): + self.assertEqual('unavailable', CAPTURE.thread_snapshot(identity)['status']) + + def test_stall_snapshots_are_fresh_bounded_and_reject_symlinks(self): + identity = self.stall_identity() + with patch.object(CAPTURE, 'stall_processes', return_value=[identity]), patch.object( + CAPTURE, 'thread_snapshot', return_value={'status': 'complete'}), patch.object( + CAPTURE.time, 'sleep'), patch('sys.stdout', io.StringIO()): + CAPTURE.collect_stall(self.root, self.output, identity) + CAPTURE.collect_stall(self.root, self.output, identity) + self.assertEqual(4, len(list(self.output.glob('observation-*/snapshot-*.json')))) + link = self.root / 'escape' + link.symlink_to(self.output, target_is_directory=True) + with self.assertRaises(ValueError): + CAPTURE.collect_stall(self.root, link, identity) + + def test_stall_session_guard_never_signals_parent_or_unowned_group(self): + with patch.object(CAPTURE.os, 'getpgid', return_value=50), patch.object( + CAPTURE.os, 'getsid', return_value=50): + self.assertFalse(CAPTURE.owns_session(123)) + with patch.object(CAPTURE, 'owns_session', return_value=False), patch.object( + CAPTURE.os, 'killpg') as kill: + with self.assertRaises(SystemExit): + CAPTURE.stop_stall_session(signal.SIGALRM, None) + observer = CAPTURE.StallObserver(self.root, self.output) + child = observer.child = Mock() + observer.close() + kill.assert_not_called() + child.wait.assert_not_called() + with patch.object(CAPTURE, 'owns_session', return_value=True), patch.object( + CAPTURE.os, 'killpg') as kill, self.assertRaises(SystemExit): + CAPTURE.stop_stall_session(signal.SIGALRM, None) + kill.assert_called_once_with(os.getpid(), signal.SIGKILL) + + def test_stall_capture_cancellation_closes_observer(self): + observer = Mock() + observer.tick.side_effect = SystemExit(143) + read_fd, write_fd = os.pipe() + os.close(write_fd) + with os.fdopen(read_fd, 'rb') as source, self.assertRaises(SystemExit): + list(CAPTURE.capture_chunks(source, observer)) + observer.close.assert_called_once() + + def test_stall_missing_attribution_is_explicit_and_never_enumerates_jvms(self): + with patch.object(CAPTURE, 'stall_processes') as enumerate_jvms, patch.object( + CAPTURE.time, 'sleep'), patch('sys.stdout', io.StringIO()) as output: + CAPTURE.collect_stall(self.root, self.output, None) + enumerate_jvms.assert_not_called() + self.assertIn('"daemon_attribution": "unavailable"', output.getvalue()) + + def test_stall_blocked_diagnostic_sink_is_reaped_without_touching_other_processes(self): + child = subprocess.Popen([sys.executable, '-c', + 'import os;\nwhile True: os.write(1, b"x" * 65536)'], + stdout=subprocess.PIPE, start_new_session=True) + unrelated = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(30)']) + self.addCleanup(unrelated.wait) + self.addCleanup(unrelated.kill) + self.addCleanup(child.stdout.close) + self.addCleanup(child.wait) + self.addCleanup(lambda: child.kill() if child.poll() is None else None) + observer = CAPTURE.StallObserver(self.root, self.output) + observer.child, observer.started, observer.attempted = child, time.monotonic(), True + read_fd, write_fd = os.pipe() + os.write(write_fd, b'build output') + os.close(write_fd) + with os.fdopen(read_fd, 'rb') as source: + self.assertEqual([b'build output'], list(CAPTURE.capture_chunks(source, observer))) + self.assertIsNotNone(child.poll()) + self.assertIsNone(unrelated.poll()) + + def test_stall_exited_or_reused_daemon_is_not_labelled_verified(self): + with patch.object(CAPTURE, 'stall_processes', return_value=[]), patch.object( + CAPTURE.time, 'sleep'), patch('sys.stdout', io.StringIO()) as output: + CAPTURE.collect_stall(self.root, self.output, self.stall_identity()) + self.assertIn('"daemon_attribution": "unavailable"', output.getvalue()) + for path in self.output.glob('observation-*/snapshot-*.json'): + self.assertEqual('unavailable', json.loads(path.read_text())['daemon_attribution']) + + def test_stall_capture_keeps_exact_stdout_and_closes_on_eof(self): + read_fd, write_fd = os.pipe() + os.write(write_fd, b'original output\n') + os.close(write_fd) + observer = Mock() + destination = io.BytesIO() + with os.fdopen(read_fd, 'rb') as source: + status = CAPTURE.capture_log(source, destination, self.log, observer) + self.assertEqual(0, status) + self.assertEqual(b'original output\n', destination.getvalue()) + self.assertEqual(destination.getvalue(), self.log.read_bytes()) + observer.observe.assert_called_once_with(b'original output\n') + observer.close.assert_called_once() + def test_compile_failure_bounds_and_symlink_rejection(self): self.write('services/common-saga/build/generated/source/Bad.java', 'bad') self.write('services/common-saga/build/generated/source/Huge.java', 'x' * 100) diff --git a/dev-tools/validation/collect-gradle-compile-failure.py b/dev-tools/validation/collect-gradle-compile-failure.py index 0466db2ea5..2c4f7134e6 100644 --- a/dev-tools/validation/collect-gradle-compile-failure.py +++ b/dev-tools/validation/collect-gradle-compile-failure.py @@ -10,6 +10,7 @@ import signal import subprocess import sys +import tempfile import time from collections import deque from pathlib import Path @@ -38,14 +39,263 @@ def safe_file(root, path): return False -def capture_log(source, destination, path): +# Account CI-only observation. No build process is signalled or restarted. +PROC_ROOT = Path('/proc') +STALL_IDLE_SECONDS = 300 +STALL_BATCH_SECONDS = 90 +STALL_COMMAND_SECONDS = 5 +STALL_MAX_PROCESSES = 8 +STALL_DUMP_BYTES = 128 * 1024 +DAEMON_PID = re.compile(rb'The client will now receive all logging from the daemon \(pid: ([0-9]+)\)') + + +def owns_session(pid): + try: + return os.getpgid(pid) == pid and os.getsid(pid) == pid + except ProcessLookupError: + return False + + +def stop_stall_session(signum, frame): + if owns_session(os.getpid()): + os.killpg(os.getpid(), signal.SIGKILL) + raise SystemExit(128 + signum) + + +def java_identity(pid): + """Classify without retaining argv, environment, or arbitrary process names.""" + try: + path = PROC_ROOT / str(pid) + if path.stat().st_uid != os.getuid(): + return None + fields = (path / 'stat').read_bytes().rsplit(b')', 1)[1].split() + with (path / 'cmdline').open('rb') as stream: + arguments = stream.read(8193) + if len(arguments) > 8192: + return None + arguments = arguments.split(b'\0') + if b'org.gradle.launcher.daemon.bootstrap.GradleDaemon' in arguments: + role = 'daemon' + elif (b'worker.org.gradle.process.internal.worker.GradleWorkerMain' in arguments + and any(arg.startswith(b'Gradle Test Executor ') for arg in arguments)): + role = 'test-worker' + else: + return None + executable = (path / 'exe').resolve(strict=True) + if executable.name != 'java': + return None + return {'pid': pid, 'ppid': int(fields[1]), 'start': int(fields[19]), + 'state': fields[0].decode('ascii'), 'role': role, + 'cpu_ticks': int(fields[11]) + int(fields[12]), 'rss_pages': int(fields[21]), + 'jcmd': str(executable.with_name('jcmd'))} + except (OSError, ValueError, IndexError, UnicodeError): + return None + + +def stall_processes(daemon): + current = java_identity(daemon['pid']) + if not current or (current['start'], current['role']) != (daemon['start'], 'daemon'): + return [] + result = [current] + # Workers are direct daemon children. Do not inspect unrelated JVMs or their arguments. + with os.scandir(PROC_ROOT) as entries: + paths = [Path(entry.path) for _, entry in zip(range(MAX_VISITED_ENTRIES), entries) + if entry.name.isdigit()] + for path in paths: + if not path.name.isdigit(): + continue + try: + fields = (path / 'stat').read_bytes().rsplit(b')', 1)[1].split() + if int(fields[1]) != daemon['pid']: + continue + except (OSError, ValueError, IndexError): + continue + worker = java_identity(int(path.name)) + if worker and worker['role'] == 'test-worker': + result.append(worker) + if len(result) >= STALL_MAX_PROCESSES: + break + return result + + +def sanitized_threads(raw): + """Allow only stack/state/monitor syntax; thread names and diagnostic prose are private.""" + lines = [] + for line in raw.decode('utf-8', errors='replace').splitlines(): + if line.startswith('"'): + identifiers = re.findall(r'(?:#\d+|(?:tid|nid)=0x[0-9a-f]+)(?=\s|$)', line[line.rfind(chr(34)) + 1:]) + lines.append('thread (name omitted) ' + ' '.join(identifiers)) + elif re.fullmatch(r'\s*java.lang.Thread.State: [A-Z_]+(?: \([a-z ]+\))?', line): + lines.append(line.strip()) + elif re.fullmatch(r'\s*at [A-Za-z0-9_.$/@+\-]+\([A-Za-z0-9_.$: /\-]+\)', line): + lines.append(line.strip()) + elif re.fullmatch(r'\s*- (?:locked|waiting on|waiting to lock|parking to wait for)\s+<0x[0-9a-f]+> \(a [A-Za-z0-9_.$]+\)', line): + lines.append(line.strip()) + return '\n'.join(lines) + + +def thread_snapshot(identity): + facts = {key: value for key, value in identity.items() if key != 'jcmd'} + current = java_identity(identity['pid']) + # Counters may change; only identity and lineage must remain fixed. + keys = ('pid', 'ppid', 'start', 'role', 'jcmd') + if not current or any(current[key] != identity[key] for key in keys): + return {**facts, 'status': 'exited-or-changed'} + process = None + selector = selectors.DefaultSelector() + raw = bytearray() + status = 'complete' + try: + process = subprocess.Popen([identity['jcmd'], str(identity['pid']), 'Thread.print', '-l'], + stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL) + selector.register(process.stdout, selectors.EVENT_READ) + deadline = time.monotonic() + STALL_COMMAND_SECONDS + while True: + remaining = deadline - time.monotonic() + if remaining <= 0 or not selector.select(remaining): + status = 'timeout' + break + chunk = os.read(process.stdout.fileno(), min(8192, STALL_DUMP_BYTES - len(raw))) + if not chunk: + break + raw.extend(chunk) + if len(raw) >= STALL_DUMP_BYTES: + status = 'limited' + break + if status == 'complete': + process.wait(timeout=max(0.01, deadline - time.monotonic())) + if process.returncode: + status = 'failed' + except subprocess.TimeoutExpired: + status = 'timeout' + except OSError: + status = 'unavailable' + finally: + selector.close() + if process is not None: + if process.poll() is None: + process.kill() # Only our jcmd helper, never the target JVM. + process.wait() + process.stdout.close() + current = java_identity(identity['pid']) + if not current or any(current[key] != identity[key] for key in keys): + return {**facts, 'status': 'exited-or-changed'} + return {**facts, 'status': status, 'threads': sanitized_threads(raw)} + + +def collect_stall(root, output, daemon): + root = root.resolve() + relative = output.absolute().relative_to(root) + cursor = root + for part in relative.parts: + cursor /= part + if cursor.is_symlink(): + raise ValueError('Stall evidence must not traverse symlinks') + output.mkdir(parents=True, exist_ok=True) + # Each invocation owns a fresh directory; never overwrite prior evidence. + target = Path(tempfile.mkdtemp(prefix='observation-', dir=output)) + started = time.monotonic() + for number in range(2): + if number: + time.sleep(max(0, 30 - (time.monotonic() - started))) + processes = stall_processes(daemon) if daemon else [] + report = {'snapshot': number + 1, 'reason': '300 seconds without Gradle output', + 'daemon_attribution': 'verified' if processes else 'unavailable', + 'process_limit': STALL_MAX_PROCESSES, 'process_limit_reached': len(processes) >= STALL_MAX_PROCESSES, + 'processes': [thread_snapshot(process) for process in processes]} + payload = json.dumps(report, indent=2) + '\n' + (target / f'snapshot-{number + 1}.json').write_text(payload) + # Independent child output: a blocked log sink cannot stall Gradle capture. + print('FIREMUD_STALL_SNAPSHOT ' + json.dumps( + {key: value for key, value in report.items() if key != 'processes'}), flush=True) + for process in report['processes']: + print(json.dumps({key: value for key, value in process.items() if key != 'threads'}), flush=True) + print(process.get('threads', ''), flush=True) + + +class StallObserver: + """One independent, bounded diagnostic batch; capture remains the sole build-output reader.""" + def __init__(self, root, output): + self.root, self.output = root, output + self.last_activity = time.monotonic() + self.prefix = b'' + self.daemon = None + self.child = None + self.started = None + self.attempted = False + + def observe(self, chunk): + self.last_activity = time.monotonic() + data = self.prefix + chunk + for match in DAEMON_PID.finditer(data): + candidate = java_identity(int(match[1])) + if candidate and candidate['role'] == 'daemon': + self.daemon = candidate + self.prefix = data[-256:] + + def tick(self): + now = time.monotonic() + if self.child and now - self.started >= STALL_BATCH_SECONDS: + self.close() + if self.attempted or now - self.last_activity < STALL_IDLE_SECONDS: + return + self.attempted = True + try: + self.child = subprocess.Popen( + [sys.executable, str(Path(__file__).resolve()), '--stall-daemon', + json.dumps(self.daemon), '--root', str(self.root), '--output', str(self.output)], + stdin=subprocess.DEVNULL, stdout=sys.stderr, stderr=subprocess.DEVNULL, + start_new_session=True) + self.started = now + except OSError: + pass # Diagnostics never change the original check result. + + def close(self): + if self.child: + # The session contains only this observer and its jcmd helpers. + # Always reap its group, including a helper surviving an observer error. + try: + if owns_session(self.child.pid): + os.killpg(self.child.pid, signal.SIGKILL) + self.child.wait() + else: + self.child.poll() # Reap if exited; never wait on an unowned process. + except ProcessLookupError: + self.child.wait() + self.child = None + + +def capture_chunks(source, observer): + if observer is None: + reader = getattr(source, 'read1', source.read) + while chunk := reader(64 * 1024): + yield chunk + return + selector = selectors.DefaultSelector() + selector.register(source, selectors.EVENT_READ) + try: + while True: + observer.tick() + if not selector.select(1): + continue + chunk = os.read(source.fileno(), 64 * 1024) + if not chunk: + break + observer.observe(chunk) + yield chunk + finally: + selector.close() + observer.close() + + +def capture_log(source, destination, path, observer=None): """Forward immediately; retain only a bounded tail, even if capture fails.""" tail = deque() length = 0 forwarding = True failed = False - reader = getattr(source, 'read1', source.read) - while chunk := reader(64 * 1024): + for chunk in capture_chunks(source, observer): if forwarding: try: destination.write(chunk) @@ -317,9 +567,26 @@ def main(): parser.add_argument('--log', type=Path) parser.add_argument('--output', type=Path) parser.add_argument('--check-exit', type=int) + parser.add_argument('--stall-output', type=Path) + parser.add_argument('--stall-daemon') args = parser.parse_args() + if args.stall_daemon is not None: + # Independent ceiling also applies if the capture parent is abruptly killed. + if not owns_session(os.getpid()): + return 2 # Private mode must be started by our observer, in its own session. + signal.signal(signal.SIGALRM, stop_stall_session) + signal.alarm(STALL_BATCH_SECONDS) + collect_stall(args.root, args.output, json.loads(args.stall_daemon)) + return 0 if args.capture_log is not None: - return capture_log(sys.stdin.buffer, sys.stdout.buffer, args.capture_log) + observer = StallObserver(args.root, args.stall_output) if args.stall_output else None + if observer: + def stop(signum, frame): + observer.close() + raise SystemExit(128 + signum) + for signum in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP): + signal.signal(signum, stop) + return capture_log(sys.stdin.buffer, sys.stdout.buffer, args.capture_log, observer) if any(value is None for value in (args.root, args.log, args.output, args.check_exit)): parser.error('collection requires --root, --log, --output and --check-exit') if 0 < args.check_exit < 128: From 96bf864d2b04baab1972be37dcbc9c0836192f8e Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 9 Nov 2026 06:41:36 +1300 Subject: [PATCH 11/17] Skip cancelled module validation and remove dead timeout branch --- .github/workflows/ci.yml | 10 +++++----- dev-tools/tests/ci-lightweight-scope-contract.sh | 6 ++++-- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 323c589a7f..1c31b0379f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1078,7 +1078,7 @@ jobs: permissions: contents: read id-token: write - timeout-minutes: ${{ matrix.module == 'world-management-service' && 60 || matrix.module == 'game-design-service' && 30 || 20 }} + timeout-minutes: ${{ matrix.module == 'game-design-service' && 30 || 20 }} strategy: fail-fast: false matrix: @@ -1096,7 +1096,7 @@ jobs: persist-credentials: false - name: Validate module and retain proof - if: ${{ always() }} + if: ${{ !cancelled() }} uses: ./.github/actions/check-gradle-module with: module: ${{ matrix.module }} @@ -1150,7 +1150,7 @@ jobs: persist-credentials: false - name: Validate module and retain proof - if: ${{ always() }} + if: ${{ !cancelled() }} uses: ./.github/actions/check-gradle-module with: module: ${{ matrix.module }} @@ -1190,7 +1190,7 @@ jobs: persist-credentials: false - name: Validate module and retain proof - if: ${{ always() }} + if: ${{ !cancelled() }} uses: ./.github/actions/check-gradle-module with: module: ${{ matrix.module }} @@ -1230,7 +1230,7 @@ jobs: persist-credentials: false - name: Validate module and retain proof - if: ${{ always() }} + if: ${{ !cancelled() }} uses: ./.github/actions/check-gradle-module with: module: ${{ matrix.module }} diff --git a/dev-tools/tests/ci-lightweight-scope-contract.sh b/dev-tools/tests/ci-lightweight-scope-contract.sh index ae36b49b3a..ab3d159987 100644 --- a/dev-tools/tests/ci-lightweight-scope-contract.sh +++ b/dev-tools/tests/ci-lightweight-scope-contract.sh @@ -521,7 +521,7 @@ for job_id, (output, module) in groups.items(): job = ci["jobs"][job_id] name_module = module or "${{ matrix.module }}" require_equal(job, ("name",), "Build and Test (" + name_module + " / ${{ matrix.partition }})", job_id) - timeout = "60" if module in ("account-service", "world-management-service") else "90" if module == "game-session-service" else "${{ matrix.module == 'world-management-service' && 60 || matrix.module == 'game-design-service' && 30 || 20 }}" + timeout = "60" if module in ("account-service", "world-management-service") else "90" if module == "game-session-service" else "${{ matrix.module == 'game-design-service' && 30 || 20 }}" require_equal(job, ("timeout-minutes",), timeout, job_id) require_equal(job, ("needs",), ["changes"], job_id) require_equal(job, ("strategy", "fail-fast"), "false", job_id) @@ -530,7 +530,9 @@ for job_id, (output, module) in groups.items(): require_equal(job, ("permissions",), {"contents": "read", "id-token": "write"}, job_id) call = find_step(ci, job_id, "Validate module and retain proof", "ci workflow") require_equal(call, ("uses",), "./.github/actions/check-gradle-module", job_id) - require_equal(call, ("if",), "${{ always() }}", job_id) + # Enter after failures for proof retention, but never start Gradle after cancellation. + # The composite's upload guards below retain their independent failure/cancellation policy. + require_equal(call, ("if",), "${{ !cancelled() }}", job_id) require_equal(call, ("with",), { "module": "${{ matrix.module }}", "partition": "${{ matrix.partition }}", "java-version": "${{ matrix.java-version }}", From 6b791c2840d8bfe7aec834ac2c6dded557536bd3 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Mon, 9 Nov 2026 13:16:41 +1300 Subject: [PATCH 12/17] Stabilize artifact pagination during concurrent service aggregation --- .../capture-slow-service-provenance.cjs | 98 ++++++++++-- .../architecture/system-architecture-cicd.md | 2 +- .../tests/ci-lightweight-scope-contract.sh | 139 +++++++++++++++++- 3 files changed, 219 insertions(+), 20 deletions(-) diff --git a/.github/scripts/capture-slow-service-provenance.cjs b/.github/scripts/capture-slow-service-provenance.cjs index 94a5ee3243..21580f7d90 100644 --- a/.github/scripts/capture-slow-service-provenance.cjs +++ b/.github/scripts/capture-slow-service-provenance.cjs @@ -6,6 +6,7 @@ const path = require("node:path"); const SUPPORTED_MODULES = new Set(["account-service", "game-session-service", "world-management-service"]); const CANONICAL_RUN_NAME = "CI — Validation"; const SHA_PATTERN = /^[0-9a-f]{40}$/; +const ARTIFACT_SNAPSHOT_ATTEMPTS = 4; async function captureSlowServiceProvenance({ github, @@ -129,6 +130,87 @@ async function captureSlowServiceProvenance({ throw new Error(`Exceeded the ${description} pagination bound.`); } + function artifactMetadata(artifact) { + return { + id: artifact.id, + name: artifact.name, + expired: artifact.expired, + size_in_bytes: artifact.size_in_bytes, + created_at: artifact.created_at, + workflow_run: artifact.workflow_run, + }; + } + + function canonicalJson(value) { + if (Array.isArray(value)) { + return `[${value.map(canonicalJson).join(",")}]`; + } + if (value !== null && typeof value === "object") { + return `{${Object.keys(value).sort().map(key => + `${JSON.stringify(key)}:${canonicalJson(value[key])}`, + ).join(",")}}`; + } + return JSON.stringify(value); + } + + async function listArtifactSnapshot() { + const items = []; + const artifactIds = new Set(); + let totalCount; + for (let page = 1; page <= 100; page += 1) { + const { data } = await github.rest.actions.listWorkflowRunArtifacts({ + ...context.repo, + run_id: runId, + page, + per_page: 100, + }); + const count = data?.total_count; + const rows = data?.artifacts; + if ( + !Number.isSafeInteger(count) || + count < 0 || + !Array.isArray(rows) + ) { + throw new Error("Invalid workflow artifact pagination metadata."); + } + if (totalCount !== undefined && totalCount !== count) return null; + if (items.length > count) return null; + totalCount = count; + const expected = Math.min(100, count - items.length); + if (rows.length !== expected) return null; + for (const artifact of rows) { + if (!Number.isSafeInteger(artifact?.id) || artifact.id <= 0) { + throw new Error("Invalid workflow artifact identity."); + } + if (artifactIds.has(artifact.id)) return null; + artifactIds.add(artifact.id); + } + items.push(...rows); + if (items.length === totalCount) return { total_count: totalCount, items }; + } + throw new Error("Exceeded the workflow artifact pagination bound."); + } + + async function listStableArtifactSnapshot() { + let previousFingerprint; + for (let attempt = 1; attempt <= ARTIFACT_SNAPSHOT_ATTEMPTS; attempt += 1) { + const snapshot = await listArtifactSnapshot(); + if (snapshot === null) { + previousFingerprint = undefined; + continue; + } + const fingerprint = canonicalJson({ + total_count: snapshot.total_count, + items: snapshot.items.map(artifactMetadata), + }); + if (previousFingerprint === fingerprint) return snapshot; + previousFingerprint = fingerprint; + } + throw new Error( + `Could not obtain two consecutive identical complete workflow artifact snapshots within ${ARTIFACT_SNAPSHOT_ATTEMPTS} listings.`, + ); + } + const attempts = []; for (let attempt = 1; attempt <= runAttempt; attempt += 1) { const params = { run_id: runId, attempt_number: attempt }; @@ -155,12 +237,7 @@ async function captureSlowServiceProvenance({ }); } - const artifactSnapshot = await listCompletePages( - request => github.rest.actions.listWorkflowRunArtifacts(request), - { run_id: runId }, - "artifacts", - "workflow artifact", - ); + const artifactSnapshot = await listStableArtifactSnapshot(); const artifacts = artifactSnapshot.items; const provenancePath = env.CI_PROVENANCE_PATH; fileSystem.mkdirSync(path.dirname(provenancePath), { recursive: true }); @@ -185,14 +262,7 @@ async function captureSlowServiceProvenance({ attempts, artifacts: { total_count: artifactSnapshot.total_count, - items: artifacts.map(artifact => ({ - id: artifact.id, - name: artifact.name, - expired: artifact.expired, - size_in_bytes: artifact.size_in_bytes, - created_at: artifact.created_at, - workflow_run: artifact.workflow_run, - })), + items: artifacts.map(artifactMetadata), }, }), ); diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index 5f1397278d..f75426cd64 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -110,7 +110,7 @@ The main [`ci.yml`](../../.github/workflows/ci.yml) workflow: - Runs formatting and lint steps (Spotless, markdownlint, link checks). - On the complete CI path, executes a matrix of Gradle `check` tasks for affected microservices with SpotBugs, Checkstyle, and tests enabled. Account Service and Game Session each use four complete-check partitions, and World Management uses two; other modules remain one check per affected module. Lightweight documentation-only PR validation does not run these service checks. - Affected-module checks and the source-built Compose boot-jar command first use Gradle's restored dependency metadata without a forced refresh. The shared runner gives a fully recognized repository-resolution failure one retry of the same complete Gradle command with `--refresh-dependencies`; successful commands do not revalidate every dependency. The existing pre-substantive compile/test boundary remains. jOOQ also permits only the exact matching `jooqCodegen` classpath-resolution failure, including Gradle's `generateJooq FAILED` task wrapper when the failure prevents the JavaExec generator from launching. The configuration-cache wrapper remains retryable only before `generateJooq` starts. Genuine JavaExec, code-generation, SQL, compiler, test, mixed, unknown, interrupted, or unrelated configuration failures retain their original failure. -- On the complete CI path, preserves every service test task and JaCoCo execution. Each Account Service, Game Session, and World Management partition uploads its report to Codecov using GitHub OIDC; a separate read-only aggregate verifies every module partition’s selectors and JUnit results, then merges execution data from unit and every available categorized integration/cross-service task into the complete service report. Other modules retain one report from their module check; modules without categorized tests retain their unit-only report. Production classes remain in reports rather than being excluded to improve percentages. Lightweight documentation-only PR validation does not run these service checks or coverage reports. Account and Game Session validation use disjoint four-partition matrix jobs, World Management uses a two-partition matrix, with remaining modules in a fourth matrix and one shared module-validation recipe. Each service aggregate waits only for its own successful matrix. World partitions balance measured whole-class costs across unit, integration, and cross-service tasks collectively; nested classes stay with their enclosing class, and newly compiled classes receive deterministic assignments. Only partition 1 builds the runtime JAR. Additional runner admission, compilation, and aggregation overhead must be measured before claiming elapsed-time savings. The final Validation Gate requires every selected matrix group and its applicable aggregate; an unaffected group may skip, but a selected skipped, cancelled or failed group cannot pass. +- On the complete CI path, preserves every service test task and JaCoCo execution. Each Account Service, Game Session, and World Management partition uploads its report to Codecov using GitHub OIDC; a separate read-only aggregate verifies every module partition’s selectors and JUnit results, then merges execution data from unit and every available categorized integration/cross-service task into the complete service report. Other modules retain one report from their module check; modules without categorized tests retain their unit-only report. Production classes remain in reports rather than being excluded to improve percentages. Lightweight documentation-only PR validation does not run these service checks or coverage reports. Account and Game Session validation use disjoint four-partition matrix jobs, World Management uses a two-partition matrix, with remaining modules in a fourth matrix and one shared module-validation recipe. Each service aggregate waits only for its own successful matrix. While unrelated matrix jobs continue uploading artifacts, provenance capture retries whole artifact listings within a fixed bound and accepts only two consecutive identical complete snapshots. Incomplete or shifting pages are discarded; persistent instability or invalid provenance fails closed without publishing a partial snapshot. World partitions balance measured whole-class costs across unit, integration, and cross-service tasks collectively; nested classes stay with their enclosing class, and newly compiled classes receive deterministic assignments. Only partition 1 builds the runtime JAR. Additional runner admission, compilation, and aggregation overhead must be measured before claiming elapsed-time savings. The final Validation Gate requires every selected matrix group and its applicable aggregate; an unaffected group may skip, but a selected skipped, cancelled or failed group cannot pass. - Retains Gradle JUnit XML results from each affected-module `check`, including unit and categorized integration/cross-service outcomes, for 14 days. Account, Game Session, and World Management retain them with their complete partition evidence in `slow-service-ci-partition---attempt---partition-`; other modules use `junit---results--attempt-`. Including the attempt keeps partial workflow reruns from colliding with earlier artifacts. The load-testing matrix entry uses its `dev-tools/load-testing` output; missing XML is reported as a warning so artifact retention does not change the test gate. - Runs the existing module check with Gradle's native `--profile`; Account, Game Session, and World Management partition jobs also profile their existing test-class preparation invocation before class selection. The workflow retains `build/reports/profile/` from the repository root as `gradle-profile----attempt-` for 14 days, including profiles from both invocations when present. These reports expose startup, configuration, dependency and task durations. Profiling does not change the selected checks or recovery behavior; fork concurrency remains controlled by the task configuration above. Missing reports warn rather than supplying timing evidence; cancelled or early-failed runs may not produce a report. Parallel task durations can overlap and must not be summed as elapsed time; JUnit results remain the separate source for individual test costs. - Failed Java compile tasks additionally retain bounded generated Java, proto, and build/version inputs with hashes and an omissions manifest in the existing per-module profile artifact. The same collector covers the source-built Compose all-eleven-service `bootJar` boundary in `dev-tools/build-compose-service-jars.sh`, using a distinct invocation directory under `build/reports/compile-failure/runtime-bootjar/`. The read-only `pr-local-smoke` job retains only that invocation's evidence on build failure as `runtime-bootjar-compile-failure--attempt-` for three days; missing evidence warns and upload failure cannot replace the build result. Native `--info` compiler identity lines come from the original check or boot-jar build; a separate offline diagnostic records Gradle/JVM identity, compiler selection and ordered compile classpath paths/lengths without copying JARs. Diagnostic selection is explicitly post-failure and cannot establish the original executed compiler or dependency bytes. Diagnostics use the canonical locked Gradle wrapper, retaining local resource admission, verified inherited leases, and its existing CI bypass. Collection is limited to four failed tasks, 512 input files, 2 MiB per input, 16 MiB total inputs, 4096 visited directory entries across source enumeration, a 16 MiB streamed log tail, and 60 seconds per diagnostic; symlink paths are rejected. Source enumeration and diagnostic output limits report possible truncation, including an exactly full diagnostic output. Live output is forwarded while only the bounded log tail is buffered for capture; capture/forwarding failures still drain the original output. Missing facts and diagnostic failure remain explicit. Missing boot-jar capture scratch runs the original build once without evidence. Success, failures without a failed Java compile task, and cancellation/signal exits (128 or above) produce no compile-failure evidence; cancellation/signal exits skip diagnostics. A failed `compileJava` task may retain evidence even when the failure comes from classpath or dependency resolution rather than compiler diagnostics. Collection never retries compilation or tests, changes dependency recovery, or replaces the original exit. No environment dump, credentials, whole cache, or unrelated workspace data is retained. diff --git a/dev-tools/tests/ci-lightweight-scope-contract.sh b/dev-tools/tests/ci-lightweight-scope-contract.sh index ab3d159987..61ae97dad7 100644 --- a/dev-tools/tests/ci-lightweight-scope-contract.sh +++ b/dev-tools/tests/ci-lightweight-scope-contract.sh @@ -939,6 +939,7 @@ async function runFor(embedded, options = {}) { pull_requests: apiAssociations, }; const calls = []; + let artifactRequestCount = 0; const assertRepo = request => { assert.equal(request.owner, owner, "every Actions request must bind the owner"); assert.equal(request.repo, repository, "every Actions request must bind the repository"); @@ -977,6 +978,14 @@ async function runFor(embedded, options = {}) { assert.equal(request.run_id, runId); assert.equal(request.per_page, 100); calls.push(["artifacts", request]); + const round = Math.floor(artifactRequestCount / 2); + artifactRequestCount += 1; + if (options.artifactProviderError && request.page === 2) { + throw new Error(options.artifactProviderError); + } + if (options.artifactResponse) { + return { data: options.artifactResponse(round, request, artifactRows) }; + } return { data: { total_count: artifactRows.length, @@ -1010,9 +1019,9 @@ async function runFor(embedded, options = {}) { }); assert.equal(writes.length, 1); assert.equal(writes[0][0], env.CI_PROVENANCE_PATH); - return { ok: true, calls, provenance: JSON.parse(writes[0][1]) }; + return { ok: true, calls, writes, provenance: JSON.parse(writes[0][1]) }; } catch (error) { - return { ok: false, calls, error: error.message }; + return { ok: false, calls, writes, error: error.message }; } } @@ -1034,7 +1043,10 @@ async function runFor(embedded, options = {}) { const result = await runFor(embedded, options); assert.equal(result.ok, true, `${embedded.module}/${options.eventName}: ${result.error}`); const attempts = options.runAttempt || 1; - const expectedKinds = ["run", ...Array(attempts * 2).fill("jobs"), "artifacts", "artifacts"]; + const expectedKinds = [ + "run", ...Array(attempts * 2).fill("jobs"), + "artifacts", "artifacts", "artifacts", "artifacts", + ]; assert.deepEqual(result.calls.map(([kind]) => kind), expectedKinds); assert.deepEqual( result.calls.filter(([kind]) => kind === "jobs").map(([, request]) => request.page), @@ -1046,7 +1058,7 @@ async function runFor(embedded, options = {}) { ); assert.deepEqual( result.calls.filter(([kind]) => kind === "artifacts").map(([, request]) => request.page), - [1, 2], + [1, 2, 1, 2], ); assert.equal(result.provenance.run.head_sha, nativeHead); assert.equal(result.provenance.run.tested_source_sha, @@ -1125,11 +1137,128 @@ async function runFor(embedded, options = {}) { eventName: "pull_request", incompleteArtifactsPage: 2, }); assert.equal(incompleteArtifacts.ok, false, `${embedded.module} accepted incomplete artifact pagination`); - assert.match(incompleteArtifacts.error, /Incomplete workflow artifact page 2/); + assert.match(incompleteArtifacts.error, /two consecutive identical complete workflow artifact snapshots/); assert.deepEqual( incompleteArtifacts.calls.map(([kind]) => kind), + ["run", "jobs", "jobs", ...Array(8).fill("artifacts")], + ); + assert.equal(incompleteArtifacts.writes.length, 0); + + const uploadedArtifact = { + id: 3000, name: "unrelated-artifact-uploaded-between-pages", expired: false, + size_in_bytes: 512, created_at: "2026-10-30T02:01:00Z", + workflow_run: { id: runId, head_sha: nativeHead }, + }; + const uploadedRows = [uploadedArtifact, ...artifactRows]; + const uploadBetweenPages = await runFor(embedded, { + eventName: "pull_request", + artifactResponse(round, request) { + const rows = round === 0 && request.page === 1 ? artifactRows : uploadedRows; + return { + total_count: rows.length, + artifacts: rowsForPage(rows, request), + }; + }, + }); + assert.equal(uploadBetweenPages.ok, true, `${embedded.module} did not recover after an upload between pages`); + assert.deepEqual( + uploadBetweenPages.calls.filter(([kind]) => kind === "artifacts").map(([, request]) => request.page), + [1, 2, 1, 2, 1, 2], + ); + assert.equal(uploadBetweenPages.provenance.artifacts.total_count, artifactRows.length + 1); + assert.equal(uploadBetweenPages.provenance.artifacts.items[0].id, uploadedArtifact.id); + + const shiftedDuplicatePage = await runFor(embedded, { + eventName: "pull_request", + artifactResponse(round, request, rows) { + if (round < 2 && request.page === 2) { + return { + total_count: rows.length, + artifacts: rows.slice(99, 106), + }; + } + const start = (request.page - 1) * request.per_page; + return { + total_count: rows.length, + artifacts: rows.slice(start, start + request.per_page), + }; + }, + }); + assert.equal(shiftedDuplicatePage.ok, true, `${embedded.module} did not retry a shifted duplicate page`); + assert.deepEqual( + shiftedDuplicatePage.calls.filter(([kind]) => kind === "artifacts").map(([, request]) => request.page), + [1, 2, 1, 2, 1, 2, 1, 2], + ); + assert.equal(shiftedDuplicatePage.provenance.artifacts.items.length, artifactRows.length); + assert.equal( + new Set(shiftedDuplicatePage.provenance.artifacts.items.map(artifact => artifact.id)).size, + artifactRows.length, + ); + + const changedMetadataRows = artifactRows.map(artifact => ({ ...artifact })); + changedMetadataRows[0] = { ...changedMetadataRows[0], size_in_bytes: 2048 }; + const changesBetweenSnapshots = await runFor(embedded, { + eventName: "pull_request", + artifactResponse(round, request) { + const rows = round === 0 ? artifactRows : changedMetadataRows; + return { + total_count: rows.length, + artifacts: rowsForPage(rows, request), + }; + }, + }); + assert.equal(changesBetweenSnapshots.ok, true, `${embedded.module} did not converge after complete snapshots changed`); + assert.deepEqual( + changesBetweenSnapshots.calls.filter(([kind]) => kind === "artifacts").map(([, request]) => request.page), + [1, 2, 1, 2, 1, 2], + ); + assert.equal(changesBetweenSnapshots.provenance.artifacts.items[0].size_in_bytes, 2048); + + const changedIdentityRows = artifactRows.map(artifact => ({ ...artifact })); + changedIdentityRows[0] = { ...changedIdentityRows[0], id: 9000 }; + const changedIdsBetweenSnapshots = await runFor(embedded, { + eventName: "pull_request", + artifactResponse(round, request) { + const rows = round === 0 ? artifactRows : changedIdentityRows; + return { + total_count: rows.length, + artifacts: rowsForPage(rows, request), + }; + }, + }); + assert.equal(changedIdsBetweenSnapshots.ok, true, `${embedded.module} did not converge after complete snapshots changed IDs`); + assert.deepEqual( + changedIdsBetweenSnapshots.calls.filter(([kind]) => kind === "artifacts").map(([, request]) => request.page), + [1, 2, 1, 2, 1, 2], + ); + assert.equal(changedIdsBetweenSnapshots.provenance.artifacts.total_count, artifactRows.length); + assert.equal(changedIdsBetweenSnapshots.provenance.artifacts.items[0].id, 9000); + + const neverStable = await runFor(embedded, { + eventName: "pull_request", + artifactResponse(round, request) { + const rows = round % 2 === 0 ? artifactRows : changedMetadataRows; + return { + total_count: rows.length, + artifacts: rowsForPage(rows, request), + }; + }, + }); + assert.equal(neverStable.ok, false, `${embedded.module} accepted snapshots that never stabilized`); + assert.match(neverStable.error, /two consecutive identical complete workflow artifact snapshots/); + assert.equal(neverStable.calls.filter(([kind]) => kind === "artifacts").length, 8); + assert.equal(neverStable.writes.length, 0); + + const providerError = await runFor(embedded, { + eventName: "pull_request", artifactProviderError: "provider unavailable", + }); + assert.equal(providerError.ok, false, `${embedded.module} accepted an artifact provider error`); + assert.equal(providerError.error, "provider unavailable"); + assert.deepEqual( + providerError.calls.map(([kind]) => kind), ["run", "jobs", "jobs", "artifacts", "artifacts"], ); + assert.equal(providerError.writes.length, 0); } })().catch(error => { console.error(error); process.exitCode = 1; }); """ From 8d8af8389a5b9316d84591ef8c34880a9a2c4f59 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Mon, 9 Nov 2026 16:27:38 +1300 Subject: [PATCH 13/17] Preserve failed module diagnostics across workflow attempts --- .github/actions/check-gradle-module/action.yml | 2 +- dev-tools/tests/ci-lightweight-scope-contract.sh | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/.github/actions/check-gradle-module/action.yml b/.github/actions/check-gradle-module/action.yml index 2e077b0932..21cb32adca 100644 --- a/.github/actions/check-gradle-module/action.yml +++ b/.github/actions/check-gradle-module/action.yml @@ -99,7 +99,7 @@ runs: if: ${{ failure() || cancelled() }} uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: - name: test-logs-${{ inputs.module }}-${{ inputs.partition }}-${{ github.sha }} + name: test-logs-${{ inputs.module }}-${{ inputs.partition }}-${{ github.sha }}-attempt-${{ github.run_attempt }} path: ${{ inputs.module == 'load-testing' && 'dev-tools/load-testing/build/reports/tests/' || format('services/{0}/build/reports/tests/', inputs.module) }} - name: 📤 Upload JUnit Test Results diff --git a/dev-tools/tests/ci-lightweight-scope-contract.sh b/dev-tools/tests/ci-lightweight-scope-contract.sh index 61ae97dad7..59612cac24 100644 --- a/dev-tools/tests/ci-lightweight-scope-contract.sh +++ b/dev-tools/tests/ci-lightweight-scope-contract.sh @@ -672,6 +672,12 @@ require_equal( "${{ failure() || cancelled() }}", "ci workflow", ) +require_equal( + test_logs_step, + ("with", "name"), + "test-logs-${{ matrix.module }}-${{ matrix.partition }}-${{ github.sha }}-attempt-${{ github.run_attempt }}", + "ci workflow", +) junit_results_step = find_step( module_ci, "build-and-test", "Upload JUnit Test Results", "ci workflow" From 9e68dbedb097f30fb6ebd023454688e8c2731d3e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 9 Nov 2026 20:44:13 +1300 Subject: [PATCH 14/17] Unify service recognition and document World CI partitions --- .github/scripts/classify-change-scope.cjs | 12 ++++++------ design/architecture/system-architecture-cicd.md | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.github/scripts/classify-change-scope.cjs b/.github/scripts/classify-change-scope.cjs index ef6f8c01b1..eb3a9c7bdd 100644 --- a/.github/scripts/classify-change-scope.cjs +++ b/.github/scripts/classify-change-scope.cjs @@ -158,9 +158,12 @@ function moduleForFile(file) { return null; } +function isRecognizedServiceFile(file) { + return file.startsWith("services/") && moduleForFile(file) !== null; +} + function isServiceSourceMarkdown(file) { - return file.startsWith("services/") && - moduleForFile(file) !== null && + return isRecognizedServiceFile(file) && /^services\/[^/]+\/src\/.*\.md$/.test(file); } @@ -171,10 +174,7 @@ function classifyChangeScope(inputFiles, options = {}) { // selecting runtime modules, including README files under shared common-* paths. // Unknown services, source resources and non-lightweight inputs remain fail closed. const moduleInputFiles = files.filter( - (file) => - !(file.startsWith("services/") && - moduleForFile(file) !== null && - isLightweightEligible(file)), + (file) => !(isRecognizedServiceFile(file) && isLightweightEligible(file)), ); const runAll = forceAll || diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index dda372ff0f..ce78ebbcf5 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -62,7 +62,7 @@ The fresh disposable [PR #3081](https://github.com/benhook1013/FireMUD/pull/3081 The shipped [preservation contract](../../dev-tools/tests/pr-required-gate-context-contract.sh) asserts canonical assessment, ordinary listener scope, and the retained fail-closed identity, evidence, chronology, history, admission, and confirmation boundaries. -Account Service and Game Session validation each use four independent matrix partitions. Account retains two test forks per partition. On Linux, Game Session caps `integrationTest` at two JVM forks, bounded by Gradle’s worker count; JUnit methods within each suite remain serial, and other platforms retain their existing single-fork behavior. Each runner compiles every current test source set, selects whole discovered classes with nested classes kept together, and runs the complete service check task graph with fullCheck and existing fork settings. Checked-in historical assignments seed the selectors; newly discovered classes are assigned deterministically so the module’s partitions are disjoint and cover the current compiled class inventory. Each runner publishes run-, tested-source-, attempt-, service-, and partition-qualified JUnit, JaCoCo execution-data, measured production class files, selector, and partial-report artifacts. For pull requests, the tested source SHA is the merge checkout while Actions API head identities refer to the PR head; the aggregate verifies both against the trusted event and canonical run title. Push and manual runs use one SHA for both identities. The read-only service aggregate queries the workflow run and every attempt’s job and artifact metadata with complete pagination, then binds each artifact to the latest effective successful job outcome for that exact run, tested source, native head, service, and partition. GitHub may clone carried jobs into a later attempt with new job IDs and a later raw `run_attempt` while retaining their original execution timestamps. The aggregate therefore keeps the latest effective outcome authoritative and correlates its exact run, native head, job name and execution window with the earliest matching successful attempt before selecting that attempt’s artifact and manifest. A retained earlier successful partition may support a partial retry only when its artifact remains available and its latest effective job outcome is successful; absent or ambiguous provenance, missing artifacts, and failed newer job outcomes hold aggregation, and a newer failure never falls back to an older success. The aggregate verifies both selector and JUnit report unions and requires identical complete production-class inventories and bytes from every measured partition. Missing, extra, symlinked or unequal class files refuse aggregation. The exact Spring annotation-processor sidecar `META-INF/spring-configuration-metadata.json` may accompany the measured class tree but is not bytecode and is not copied into the verified JaCoCo handoff; other non-class payloads remain rejected. It copies one verified measured tree into its fixed build handoff and generates the complete service JaCoCo report from those class bytes and every current test task’s execution data, without recompiling aggregate classes. The existing Validation Gate requires every module matrix entry and the corresponding coverage aggregate when either slow service is affected. Ordinary local checks for both services remain unpartitioned. The historical profiles and saved reports supply candidate grouping only; they do not establish a whole-run saving or available runner capacity. +Account Service and Game Session validation each use four independent matrix partitions. Account retains two test forks per partition. On Linux, Game Session caps `integrationTest` at two JVM forks, bounded by Gradle’s worker count; JUnit methods within each suite remain serial, and other platforms retain their existing single-fork behavior. Each runner compiles every current test source set, selects whole discovered classes with nested classes kept together, and runs the complete service check task graph with fullCheck and existing fork settings. Checked-in historical assignments seed the selectors; newly discovered classes are assigned deterministically so the module’s partitions are disjoint and cover the current compiled class inventory. Each runner publishes run-, tested-source-, attempt-, service-, and partition-qualified JUnit, JaCoCo execution-data, measured production class files, selector, and partial-report artifacts. For pull requests, the tested source SHA is the merge checkout while Actions API head identities refer to the PR head; the aggregate verifies both against the trusted event and canonical run title. Push and manual runs use one SHA for both identities. The read-only service aggregate queries the workflow run and every attempt’s job and artifact metadata with complete pagination, then binds each artifact to the latest effective successful job outcome for that exact run, tested source, native head, service, and partition. GitHub may clone carried jobs into a later attempt with new job IDs and a later raw `run_attempt` while retaining their original execution timestamps. The aggregate therefore keeps the latest effective outcome authoritative and correlates its exact run, native head, job name and execution window with the earliest matching successful attempt before selecting that attempt’s artifact and manifest. A retained earlier successful partition may support a partial retry only when its artifact remains available and its latest effective job outcome is successful; absent or ambiguous provenance, missing artifacts, and failed newer job outcomes hold aggregation, and a newer failure never falls back to an older success. The aggregate verifies both selector and JUnit report unions and requires identical complete production-class inventories and bytes from every measured partition. Missing, extra, symlinked or unequal class files refuse aggregation. The exact Spring annotation-processor sidecar `META-INF/spring-configuration-metadata.json` may accompany the measured class tree but is not bytecode and is not copied into the verified JaCoCo handoff; other non-class payloads remain rejected. It copies one verified measured tree into its fixed build handoff and generates the complete service JaCoCo report from those class bytes and every current test task’s execution data, without recompiling aggregate classes. World Management uses the same provenance and aggregation contract with two whole-class partitions balanced collectively across its unit, integration, and cross-service tasks. The existing Validation Gate requires every selected module matrix group and the corresponding coverage aggregate when any of the three slow services is affected. Ordinary local checks for all three services remain unpartitioned. The historical profiles and saved reports supply candidate grouping only; they do not establish a whole-run saving or available runner capacity. ## Workflow Structure From 3f19ad85ad2fa867b978ec009b078eb950ae1b97 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 10 Nov 2026 04:35:40 +1300 Subject: [PATCH 15/17] Provision pinned Python for Gradle recovery in CI --- .github/actions/check-gradle-module/action.yml | 4 ++-- .github/workflows/ci.yml | 15 +++++++++++++++ .github/workflows/runtime-images.yml | 15 +++++++++++++++ .github/workflows/smoke.yml | 2 +- 4 files changed, 33 insertions(+), 3 deletions(-) diff --git a/.github/actions/check-gradle-module/action.yml b/.github/actions/check-gradle-module/action.yml index 941f068bc2..c74002b107 100644 --- a/.github/actions/check-gradle-module/action.yml +++ b/.github/actions/check-gradle-module/action.yml @@ -16,8 +16,8 @@ inputs: runs: using: composite steps: - - name: ⚙️ Set Up Python for Combined Coverage Verification - if: ${{ inputs.module == 'common-saga' }} + - name: Set up Python for Gradle recovery and coverage verification + if: ${{ inputs.module != 'game-design-service' }} uses: ./.github/actions/setup-python with: requirements: none diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 48b1192841..c90e3b83a9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -255,6 +255,11 @@ jobs: - name: Set up Gradle for remote generator compatibility proof uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6 + - name: Set up Python for Gradle recovery + uses: ./.github/actions/setup-python + with: + requirements: none + - name: Compile the actual Buf-generated Java sources run: | test -n "$(find protos/gen/java -name '*.java' -print -quit)" @@ -686,6 +691,11 @@ jobs: build-scan-terms-of-use-agree: 'yes' cache-read-only: false + - name: Set up Python for Gradle recovery + uses: ./.github/actions/setup-python + with: + requirements: none + - name: 🧪 Check Flyway Migration Versions env: FIREMUD_FLYWAY_BASE_REF: ${{ github.event_name == 'workflow_dispatch' && inputs.flyway_base_sha || github.event_name == 'pull_request' && github.event.pull_request.base.sha || github.event.before }} @@ -724,6 +734,11 @@ jobs: build-scan-terms-of-use-agree: 'yes' cache-read-only: false + - name: Set up Python for Gradle recovery + uses: ./.github/actions/setup-python + with: + requirements: none + - name: 🧪 Check gRPC Transport Configuration run: bash ./dev-tools/validation/run-gradle-with-dependency-recovery.sh --runner ./gradlew -- checkGrpcTransportConfig checkGrpcPublicMethods diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index 29a2214208..7e61a9fe8c 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -1171,6 +1171,11 @@ jobs: build-scan-terms-of-use-agree: 'yes' cache-read-only: false + - name: Set up Python for Gradle recovery + uses: ./.github/actions/setup-python + with: + requirements: none + - name: Build service JAR run: bash ./dev-tools/validation/run-gradle-with-dependency-recovery.sh --runner ./gradlew -- :${{ matrix.service }}:bootJar @@ -1411,6 +1416,11 @@ jobs: username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} + - name: Set up Python for Gradle recovery + uses: ./.github/actions/setup-python + with: + requirements: none + - name: Build controller JAR and image locally run: | set -euo pipefail @@ -1895,6 +1905,11 @@ jobs: cache-from: type=gha,scope=pr-controller-smoke cache-to: type=gha,mode=max,scope=pr-controller-smoke + - name: Set up Python for Gradle recovery + uses: ./.github/actions/setup-python + with: + requirements: none + - name: Build controller image for credential-free local validation run: | set -euo pipefail diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index f4232fbdeb..73d639c532 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -608,7 +608,7 @@ jobs: } // One canonical producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "b89a1fb4bb324220c842b2250ca82f8db0d5d17b7ef86e70ad56e107ed4bce34"; + const canonicalRuntimeWorkflowSha256 = "ea6ade0f69718573aeac4e4b5a1e9050e53e1e3cef3426b8791f182d8d49e112"; // Retain the exact fail-red producer still executed by trusted base refreshes. const canonicalLegacyRuntimeWorkflowSha256 = "db0acb4e51630b729eb92362ea3e748f3f96b06d8ef5ca466a718ded67725804"; // Include held-admission proof, authenticated cleanup, and their executed inputs. From 78f3d3ef3c79a8af0841d55ffda99e902b83dc75 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 10 Nov 2026 05:52:14 +1300 Subject: [PATCH 16/17] fix(ci): preserve trusted smoke refresh proof Recognize the reviewed prior producer only for trusted refreshes and retain exact exception and cleanup proof. Catch direct Gradle wrapper bypasses in list steps and bare invocations. --- .github/workflows/smoke.yml | 27 ++++++++++------ .../architecture/system-architecture-cicd.md | 2 +- .../gradle-dependency-recovery-contract.sh | 7 ++++- .../pr-required-gate-context-contract.sh | 31 +++++++++++++++---- 4 files changed, 50 insertions(+), 17 deletions(-) diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 73d639c532..b53216b527 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -607,8 +607,10 @@ jobs: throw new Error(`${label} retry loop exited unexpectedly`); } - // One canonical producer definition; the contract test reports fingerprint upkeep. + // Current producer definition; the contract test reports fingerprint upkeep. const canonicalRuntimeWorkflowSha256 = "ea6ade0f69718573aeac4e4b5a1e9050e53e1e3cef3426b8791f182d8d49e112"; + // Trusted refreshes can still execute the previous successful default-branch definition. + const canonicalPreviousTrustedRefreshRuntimeWorkflowSha256 = "520407ce97e1ffbe1db824264f0a64e95887f36df2dc07d5738bed4448759ae2"; // Retain the exact fail-red producer still executed by trusted base refreshes. const canonicalLegacyRuntimeWorkflowSha256 = "db0acb4e51630b729eb92362ea3e748f3f96b06d8ef5ca466a718ded67725804"; // Include held-admission proof, authenticated cleanup, and their executed inputs. @@ -724,6 +726,12 @@ jobs: } } + function isSuccessfulRuntimeWorkflowDefinition(definitionHash, sourceEvent) { + return definitionHash === canonicalRuntimeWorkflowSha256 || + (sourceEvent === "repository_dispatch" && + definitionHash === canonicalPreviousTrustedRefreshRuntimeWorkflowSha256); + } + async function verifyCanonicalSmokeProducer(run, candidate, identity) { if (!positiveInteger(run.id) || !positiveInteger(run.run_attempt)) return false; const { data: source } = await withTransientGitHubRetry( @@ -788,7 +796,7 @@ jobs: const bytes = Buffer.from(definition.content, "base64"); if (definition.size !== bytes.length) return false; const definitionHash = require("node:crypto").createHash("sha256").update(bytes).digest("hex"); - if (definitionHash === canonicalRuntimeWorkflowSha256) { + if (isSuccessfulRuntimeWorkflowDefinition(definitionHash, source.event)) { if (markers.length !== 1 || markers[0].status !== "completed" || markers[0].conclusion !== "skipped") return false; } else if (definitionHash !== canonicalLegacyRuntimeWorkflowSha256) return false; @@ -872,11 +880,7 @@ jobs: // Typed refresh workflow authority is its native default-branch revision; // the executed classifier source still belongs to the verified PR merge. const workflowSha = source.event === "pull_request" ? identity.mergeSha : source.head_sha; - for (const [path, expectedSha256] of Object.entries({ - [workflowPath]: source.conclusion === "failure" - ? canonicalLegacyRuntimeWorkflowSha256 : canonicalRuntimeWorkflowSha256, - ...canonicalPlayClassifierSha256, - })) { + for (const path of [workflowPath, ...Object.keys(canonicalPlayClassifierSha256)]) { const { data: definition } = await withTransientGitHubRetry( `immutable PLAY classifier definition lookup: ${path}`, () => github.rest.repos.getContent({ @@ -887,8 +891,13 @@ jobs: definition.encoding !== "base64" || typeof definition.content !== "string") return false; const bytes = Buffer.from(definition.content, "base64"); if (definition.size !== bytes.length) return false; - if (require("node:crypto").createHash("sha256").update(bytes).digest("hex") !== - expectedSha256) return false; + const definitionHash = require("node:crypto").createHash("sha256").update(bytes).digest("hex"); + const expectedSha256 = path === workflowPath + ? canonicalLegacyRuntimeWorkflowSha256 : canonicalPlayClassifierSha256[path]; + const matches = path === workflowPath && source.conclusion === "success" + ? isSuccessfulRuntimeWorkflowDefinition(definitionHash, source.event) + : definitionHash === expectedSha256; + if (!matches) return false; } const { data: latest } = await withTransientGitHubRetry( "current runtime attempt lookup", diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index bedfc0fc8a..6bf3ae1299 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -90,7 +90,7 @@ The publisher's no-checkout, Actions-read-only resolver reads only the supplied Smoke Gate retains affirmative successful smoke-step evidence for earlier producers. When GitHub omits or delays step metadata, the canonical producer additionally qualifies through its native `PR Full-Stack Smoke (runtime-required=true)` job identity and successful terminal job outcome. This producer has stable smoke and cleanup step IDs and an unconditional terminal guard. Ordinary runtime qualification requires both Actions-native outcomes to be `success` and the transition-exception marker to be explicitly skipped. Missing marker metadata cannot use the native-job fallback: a successful job alone may instead represent the bounded exception described below. Skipped, missing, cancelled, or failed execution or authenticated cleanup cannot qualify as real runtime proof. Non-required image builds use a different evaluated job name. The gate verifies the exact successful run attempt, owning repository/workflow/event, native job ID/attempt/head/check URL, canonical PR/base/head/merge title, ordered merge parents, and current PR head/base branch before accepting this path. It also rechecks that no newer attempt superseded that source. Job success, logs, command-written outputs, and image artifacts alone are not smoke proof. The existing native job name does not widen the held-admission proof scope defined above. A separate, temporary diagnostic exception lets the required Smoke Gate succeed for a same-repository `benhook1013/FireMUD` pull request whose current live PR carries the `canonical-play-transition` label. A `pull_request` producer also requires the source event label and exact verified PR-event base/head/merge tuple. A typed `pr-runtime-base-refresh` producer instead derives label authority from its verified live same-repository PR, never dispatch payload labels, and requires the exact current base/head/merge tuple again at consumption. Both paths require the latest successful CI attempt with its explicit exception marker while the PR head and base branch remain current. During the default-branch workflow rollout, the exact previous fail-red producer fingerprint remains accepted only with its original failed smoke and terminal guard plus successful marker and cleanup; it supplies the same diagnostic exception and no runtime qualification. The smoke invocation retains its failed Actions-native outcome through step-level continuation; only the exact label, classifier and successful authenticated cleanup can make the mandatory final guard accept that failed probe. Every other probe failure still fails CI. GitHub reports the continued step conclusion as success, so the consumer verifies the immutable marker rather than treating that conclusion as runtime proof. The fingerprinted producer must attest the classified direct-backend `PLAY` `ERROR ENTITLEMENT_UNAVAILABLE` after successful held-admission qualification and backend `LOGIN`, with successful authenticated cleanup. The executing workflow is fingerprinted at the PR merge revision or typed refresh's native default-branch revision, respectively; classifiers, held-admission qualification, authenticated cleanup, certificate setup, and their checked-in environment and Compose inputs are always fingerprinted at the tested PR merge. Its original smoke failure remains visible in the probe logs, summary and Actions-native outcome; unrelated failures still block, and image export and upload must be skipped. The typed publication handoff also requires a real successful image upload. A trusted workflow-run publisher detects the exception marker before exposing a publication source and skips its privileged job; a successful CI conclusion under exception does not authorize registry access or preview images. This is gate acceptance for the nonproduction canonical cutover, not successful smoke, runtime qualification, branch-image promotion, hosted preview eligibility, or production activation. Trusted `main`/`develop` branch publication still requires real passing `LOGIN` → `PLAY` → `LOOK` smoke and cannot use this exception; after the cutover merges, branch images remain on hold until the Account entitlement path is repaired. Remove the label-based marker and consumer exception when fresh-image backend `LOGIN` → `PLAY` → `LOOK` passes, then remove this transitional contract. The [player access tracker](../project-management/implementation-tracking/player-access-and-session.md#temporary-canonical-play-transition-exception) records the current cutover proof gap. -The producer guarantee, independent of smoke-step metadata but requiring an explicit skipped exception marker, is bound to a SHA-256 fingerprint of the entire immutable source workflow definition, including its surrounding YAML execution context. Pull-request attempts use the verified event test-merge revision; typed refresh attempts use their native default-branch `head_sha`. Missing, unavailable, altered, or unattributable definitions cannot use this guarantee, and older producers with missing step metadata remain closed. Every change to [runtime-images.yml](../../.github/workflows/runtime-images.yml) requires review of the producer guarantee and an update of `canonicalRuntimeWorkflowSha256` in [smoke.yml](../../.github/workflows/smoke.yml). The existing [required-gate contract](../../dev-tools/tests/pr-required-gate-context-contract.sh) computes the expected fingerprint and reports the exact update when it is stale; it also exercises native outcome rejection, immutable revision/attempt attribution, and the retained older step-proof path. Every change to a fingerprinted classifier, qualification or cleanup script, certificate setup, environment defaults, or Compose input also requires review and an update of `canonicalPlayClassifierSha256` in `smoke.yml`; the required-gate contract reports each stale value. These fingerprints remain part of the owning workflows, not a separate proof registry. +The producer guarantee, independent of smoke-step metadata but requiring an explicit skipped exception marker, is bound to a SHA-256 fingerprint of the entire immutable source workflow definition, including its surrounding YAML execution context. Pull-request attempts use the verified event test-merge revision, and typed refresh attempts use their native default-branch `head_sha`. During producer rollout, only verified typed refreshes can also use the reviewed previous successful workflow definition. Both paths keep the existing marker, attempt, and execution proof requirements. Missing, unavailable, altered, or unattributable definitions cannot use this guarantee. Every change to [runtime-images.yml](../../.github/workflows/runtime-images.yml) requires review of the producer guarantee and an update of `canonicalRuntimeWorkflowSha256` in [smoke.yml](../../.github/workflows/smoke.yml). The existing [required-gate contract](../../dev-tools/tests/pr-required-gate-context-contract.sh) computes the expected fingerprint and reports the exact update when it is stale; it also exercises native outcome rejection, immutable revision/attempt attribution, and the retained older step-proof path. Every change to a fingerprinted classifier, qualification or cleanup script, certificate setup, environment defaults, or Compose input also requires review and an update of `canonicalPlayClassifierSha256` in `smoke.yml`; the required-gate contract reports each stale value. These fingerprints remain part of the owning workflows, not a separate proof registry. Branch-to-environment promotion contract: diff --git a/dev-tools/tests/gradle-dependency-recovery-contract.sh b/dev-tools/tests/gradle-dependency-recovery-contract.sh index 29617392a1..c1465c051e 100644 --- a/dev-tools/tests/gradle-dependency-recovery-contract.sh +++ b/dev-tools/tests/gradle-dependency-recovery-contract.sh @@ -1202,11 +1202,16 @@ class DistributionRecovery(unittest.TestCase): unittest.main(argv=["distribution-recovery"], exit=True) PY_DISTRIBUTION_TEST +GRADLE_COMMAND_PATTERN='^[[:space:]]*(-[[:space:]]+)?(run:[[:space:]]+)?\./gradlew([[:space:]]|$)' +for command_form in '- run: ./gradlew :check' './gradlew'; do + printf '%s\n' "$command_form" | grep -Eq "$GRADLE_COMMAND_PATTERN" || fail "Gradle wrapper command form was not detected: $command_form" +done + for workflow in "$ROOT_DIR/.github/workflows/ci.yml" "$ROOT_DIR/.github/workflows/runtime-images.yml" \ "$ROOT_DIR/.github/actions/check-gradle-module/action.yml" \ "$ROOT_DIR/.github/actions/aggregate-slow-service-coverage/action.yml"; do [[ -f "$workflow" ]] || fail "Missing Gradle bootstrap owner: $workflow" - if grep -Eq '^[[:space:]]*(run: )?\./gradlew[[:space:]]' "$workflow"; then + if grep -Eq "$GRADLE_COMMAND_PATTERN" "$workflow"; then fail "Gradle bootstrap bypasses bounded distribution recovery in $workflow" fi done diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 25e534f41d..8cad9606b3 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -3472,13 +3472,16 @@ for (const [declaration] of icons) { assert.equal(statusIcon("skipped"), "⏭️"); } const bytes = fs.readFileSync(process.argv[2] + ".producer"); -const start = script.indexOf("async function verifyKnownPlayFailure("); +const start = script.indexOf("function isSuccessfulRuntimeWorkflowDefinition("); const end = script.indexOf("// Commit objects", start); const fn = script.slice(start, end); const workflowPath = ".github/workflows/runtime-images.yml"; const repositoryName = "benhook1013/FireMUD"; const canonicalSmokeJobName = "PR Full-Stack Smoke (runtime-required=true)"; const canonicalRuntimeWorkflowSha256 = require("node:crypto").createHash("sha256").update(bytes).digest("hex"); +const previousRefreshBytes = Buffer.concat([bytes, Buffer.from("\n# Previous trusted refresh definition\n")]); +const canonicalPreviousTrustedRefreshRuntimeWorkflowSha256 = require("node:crypto").createHash("sha256") + .update(previousRefreshBytes).digest("hex"); // Separate test authority lets the same verifier exercise both immutable modes. const canonicalLegacyRuntimeWorkflowSha256 = "0".repeat(64); const canonicalPlayClassifierSha256 = JSON.parse(script.match(/const canonicalPlayClassifierSha256 = (\{[\s\S]*?\});/)[1]); @@ -3497,7 +3500,7 @@ const candidate = {id: 123, run_id: 99, run_attempt: 2, head_sha: headSha, name: steps: [...failures.map(name => step(name, "success")), step("Stop smoke stack", "success"), step("Known canonical transition PLAY failure with successful authenticated cleanup", "success"), step("Export fixed-tag preview image artifact", "skipped"), step("Upload preview image artifact", "skipped")]}; -async function verify(mutate = () => {}, event = "pull_request") { +async function verify(mutate = () => {}, event = "pull_request", knownPlay = true) { const data = structuredClone({pr: "3390", consumerRepository: repositoryName, run, identity, source, candidate, jobs: [candidate], latest: {...source}, eventHeadRepository: repositoryName, currentPullRequest: {state: "open", head: {sha: headSha, repo: {full_name: repositoryName}}, @@ -3512,6 +3515,10 @@ async function verify(mutate = () => {}, event = "pull_request") { data.source.head_sha = data.latest.head_sha = workflowSha; data.candidate.head_sha = data.jobs[0].head_sha = workflowSha; } + if (!knownPlay) { + data.candidate.steps.find(step => step.name === + "Known canonical transition PLAY failure with successful authenticated cleanup").conclusion = "skipped"; + } mutate(data); const contentRequests = []; const github = {request: async () => ({data: data.source}), paginate: async () => data.jobs, @@ -3526,14 +3533,17 @@ async function verify(mutate = () => {}, event = "pull_request") { if (!data.definitions[path]) throw Object.assign(new Error("definition unavailable"), {status: 404}); return {data: data.definitions[path]}; }}}}; + const verifier = knownPlay ? "verifyKnownPlayFailure" : "verifyCanonicalSmokeProducer"; const accepted = await new Function("github", "prNumber", "repositoryName", "canonicalSmokeJobName", "workflowPath", - "canonicalRuntimeWorkflowSha256", "canonicalLegacyRuntimeWorkflowSha256", "canonicalPlayClassifierSha256", "positiveInteger", "withTransientGitHubRetry", "context", "owner", "repo", "require", "data", - `${fn}; return verifyKnownPlayFailure(data.run, data.candidate, data.identity);`)( - github, data.pr, data.consumerRepository, canonicalSmokeJobName, workflowPath, canonicalRuntimeWorkflowSha256, data.legacyDefinition ? canonicalRuntimeWorkflowSha256 : canonicalLegacyRuntimeWorkflowSha256, canonicalPlayClassifierSha256, + "canonicalRuntimeWorkflowSha256", "canonicalPreviousTrustedRefreshRuntimeWorkflowSha256", "canonicalLegacyRuntimeWorkflowSha256", "canonicalPlayClassifierSha256", "positiveInteger", "withTransientGitHubRetry", "context", "owner", "repo", "require", "data", + `${fn}; return ${verifier}(data.run, data.candidate, data.identity);`)( + github, data.pr, data.consumerRepository, canonicalSmokeJobName, workflowPath, canonicalRuntimeWorkflowSha256, + canonicalPreviousTrustedRefreshRuntimeWorkflowSha256, + data.legacyDefinition ? canonicalRuntimeWorkflowSha256 : canonicalLegacyRuntimeWorkflowSha256, canonicalPlayClassifierSha256, value => Number.isSafeInteger(value) && value > 0, (_label, call) => call(), {payload: {repository: {default_branch: "develop"}, pull_request: {head: {repo: {full_name: data.eventHeadRepository}}}}}, "benhook1013", "FireMUD", require, data); - if (accepted) assert.deepEqual(contentRequests, [workflowPath, ...Object.keys(classifierDefinitions)]); + if (accepted) assert.deepEqual(contentRequests, knownPlay ? [workflowPath, ...Object.keys(classifierDefinitions)] : [workflowPath]); return accepted; } // Proof errors in a successful exception attempt must fail closed. @@ -3644,6 +3654,15 @@ function markerAccepted(overrides = {}) { }, event), true, "exact old fail-red default-branch producer remains a diagnostic exception only"); } assert.equal(await verify(() => {}, "repository_dispatch"), true); + const usePreviousRefresh = data => Object.assign(data.definitions[workflowPath], { + content: previousRefreshBytes.toString("base64"), size: previousRefreshBytes.length, + }); + for (const knownPlay of [true, false]) { + assert.equal(await verify(usePreviousRefresh, "repository_dispatch", knownPlay), true, + "trusted refresh may retain the previous successful producer proof"); + assert.equal(await verify(usePreviousRefresh, "pull_request", knownPlay), false, + "the previous successful definition cannot attest a PR producer"); + } for (const path of Object.keys(classifierDefinitions)) { assert.equal(await verify(d => { const altered = Buffer.concat([Buffer.from(d.definitions[path].content, "base64"), Buffer.from("\n# altered classifier\n")]); From 616866a1c522b6f6ab6a36dcf12c1c0d4ddc3368 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 10 Nov 2026 06:45:51 +1300 Subject: [PATCH 17/17] fix(ci): pace coverage artifact snapshots --- .github/scripts/capture-slow-service-provenance.cjs | 4 ++++ dev-tools/tests/ci-lightweight-scope-contract.sh | 9 +++++++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/.github/scripts/capture-slow-service-provenance.cjs b/.github/scripts/capture-slow-service-provenance.cjs index 21580f7d90..414169ab89 100644 --- a/.github/scripts/capture-slow-service-provenance.cjs +++ b/.github/scripts/capture-slow-service-provenance.cjs @@ -2,11 +2,13 @@ const fs = require("node:fs"); const path = require("node:path"); +const { setTimeout: sleep } = require("node:timers/promises"); const SUPPORTED_MODULES = new Set(["account-service", "game-session-service", "world-management-service"]); const CANONICAL_RUN_NAME = "CI — Validation"; const SHA_PATTERN = /^[0-9a-f]{40}$/; const ARTIFACT_SNAPSHOT_ATTEMPTS = 4; +const ARTIFACT_SNAPSHOT_DELAY_MS = 1000; async function captureSlowServiceProvenance({ github, @@ -14,6 +16,7 @@ async function captureSlowServiceProvenance({ env = process.env, module, fileSystem = fs, + wait = sleep, }) { if (!SUPPORTED_MODULES.has(module)) { throw new Error(`Unsupported slow-service provenance module: ${module}`); @@ -194,6 +197,7 @@ async function captureSlowServiceProvenance({ async function listStableArtifactSnapshot() { let previousFingerprint; for (let attempt = 1; attempt <= ARTIFACT_SNAPSHOT_ATTEMPTS; attempt += 1) { + if (attempt > 1) await wait(ARTIFACT_SNAPSHOT_DELAY_MS); const snapshot = await listArtifactSnapshot(); if (snapshot === null) { previousFingerprint = undefined; diff --git a/dev-tools/tests/ci-lightweight-scope-contract.sh b/dev-tools/tests/ci-lightweight-scope-contract.sh index 4897a5c508..b5f0621ab4 100644 --- a/dev-tools/tests/ci-lightweight-scope-contract.sh +++ b/dev-tools/tests/ci-lightweight-scope-contract.sh @@ -1001,6 +1001,7 @@ async function runFor(embedded, options = {}) { }, }; const writes = []; + const snapshotWaits = []; const env = { CI_RUN_ID: String(runId), CI_RUN_ATTEMPT: String(runAttempt), @@ -1022,12 +1023,13 @@ async function runFor(embedded, options = {}) { env, module: options.module || embedded.module, fileSystem, + wait: async milliseconds => { snapshotWaits.push([milliseconds, artifactRequestCount]); }, }); assert.equal(writes.length, 1); assert.equal(writes[0][0], env.CI_PROVENANCE_PATH); - return { ok: true, calls, writes, provenance: JSON.parse(writes[0][1]) }; + return { ok: true, calls, writes, snapshotWaits, provenance: JSON.parse(writes[0][1]) }; } catch (error) { - return { ok: false, calls, writes, error: error.message }; + return { ok: false, calls, writes, snapshotWaits, error: error.message }; } } @@ -1054,6 +1056,7 @@ async function runFor(embedded, options = {}) { "artifacts", "artifacts", "artifacts", "artifacts", ]; assert.deepEqual(result.calls.map(([kind]) => kind), expectedKinds); + assert.deepEqual(result.snapshotWaits, [[1000, 2]]); assert.deepEqual( result.calls.filter(([kind]) => kind === "jobs").map(([, request]) => request.page), Array.from({ length: attempts }, () => [1, 2]).flat(), @@ -1148,6 +1151,7 @@ async function runFor(embedded, options = {}) { incompleteArtifacts.calls.map(([kind]) => kind), ["run", "jobs", "jobs", ...Array(8).fill("artifacts")], ); + assert.deepEqual(incompleteArtifacts.snapshotWaits, [[1000, 2], [1000, 4], [1000, 6]]); assert.equal(incompleteArtifacts.writes.length, 0); const uploadedArtifact = { @@ -1219,6 +1223,7 @@ async function runFor(embedded, options = {}) { [1, 2, 1, 2, 1, 2], ); assert.equal(changesBetweenSnapshots.provenance.artifacts.items[0].size_in_bytes, 2048); + assert.deepEqual(changesBetweenSnapshots.snapshotWaits, [[1000, 2], [1000, 4]]); const changedIdentityRows = artifactRows.map(artifact => ({ ...artifact })); changedIdentityRows[0] = { ...changedIdentityRows[0], id: 9000 };