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..afa66d050d --- /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: bash ./dev-tools/validation/run-gradle-with-dependency-recovery.sh --runner ./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/actions/check-gradle-module/action.yml b/.github/actions/check-gradle-module/action.yml new file mode 100644 index 0000000000..c74002b107 --- /dev/null +++ b/.github/actions/check-gradle-module/action.yml @@ -0,0 +1,138 @@ +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 Gradle recovery and coverage verification + if: ${{ inputs.module != 'game-design-service' }} + 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.module != 'world-management-service' || inputs.partition == '1') }} + shell: bash + run: bash ./dev-tools/validation/run-gradle-with-dependency-recovery.sh --runner ./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 }}-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 + 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 }} + 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' || 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 }} + 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 }}/ + build/reports/gradle-stall/${{ 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..8f0ea792b8 100644 --- a/.github/actions/preserve-required-gate/assess-required-gate.sh +++ b/.github/actions/preserve-required-gate/assess-required-gate.sh @@ -125,13 +125,16 @@ 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 (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 == 22 and (.[0].jobs | type) == "array" and - (.[0].jobs | length) == 22 and ([.[0].jobs[].id] | unique | length) == 22 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 @@ -145,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/actions/setup-gh/action.yml b/.github/actions/setup-gh/action.yml index f505808d50..70ff0abf18 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}" @@ -31,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" \ @@ -40,13 +57,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/.github/scripts/capture-slow-service-provenance.cjs b/.github/scripts/capture-slow-service-provenance.cjs index 9261a8b733..414169ab89 100644 --- a/.github/scripts/capture-slow-service-provenance.cjs +++ b/.github/scripts/capture-slow-service-provenance.cjs @@ -2,10 +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"]); +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, @@ -13,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}`); @@ -129,6 +133,88 @@ 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) { + if (attempt > 1) await wait(ARTIFACT_SNAPSHOT_DELAY_MS); + 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 +241,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 +266,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/.github/scripts/classify-change-scope.cjs b/.github/scripts/classify-change-scope.cjs index 02d5efe5e6..eb3a9c7bdd 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 isRecognizedServiceFile(file) { + return file.startsWith("services/") && moduleForFile(file) !== null; +} + +function isServiceSourceMarkdown(file) { + return isRecognizedServiceFile(file) && + /^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) => !(isRecognizedServiceFile(file) && 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/.github/scripts/run-gradle-module-checks.sh b/.github/scripts/run-gradle-module-checks.sh index 4523c4344f..a9b7aef77d 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") @@ -34,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" \ diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0389908fe9..c90e3b83a9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -35,6 +35,10 @@ 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 }} + 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 }} @@ -146,13 +150,17 @@ 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) => ({ 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"); + 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, @@ -247,10 +255,15 @@ 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)" - ./gradlew compileBufGeneratedJava + bash ./dev-tools/validation/run-gradle-with-dependency-recovery.sh --runner ./gradlew -- compileBufGeneratedJava docker-lint: name: Dockerfile Lint @@ -678,10 +691,15 @@ 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 }} - run: ./gradlew checkFlywayVersions + run: bash ./dev-tools/validation/run-gradle-with-dependency-recovery.sh --runner ./gradlew -- checkFlywayVersions grpc-transport-config-sanity-checks: name: gRPC Transport Configuration Sanity Checks @@ -716,8 +734,13 @@ 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: ./gradlew checkGrpcTransportConfig checkGrpcPublicMethods + run: bash ./dev-tools/validation/run-gradle-with-dependency-recovery.sh --runner ./gradlew -- checkGrpcTransportConfig checkGrpcPublicMethods workflow-lint: name: GitHub Workflow Lint @@ -1065,116 +1088,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 == '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 + - name: Validate module and retain proof + if: ${{ !cancelled() }} + uses: ./.github/actions/check-gradle-module with: - requirements: yaml - - - name: โš™๏ธ Set Up Java - uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6 - 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,163 +1135,130 @@ jobs: name: ${{ matrix.module }}-${{ matrix.partition }}-jacoco verbose: true - - name: ๐Ÿ“ค Upload Test Logs if Failed - if: ${{ failure() || cancelled() }} - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 - 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) }} - - - name: ๐Ÿ“ค Upload JUnit Test Results - if: ${{ always() && matrix.module != 'account-service' && matrix.module != 'game-session-service' }} - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # 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 - - - 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 - 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 - - - name: Upload Gradle Task Profile - if: always() - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 - with: - name: gradle-profile-${{ matrix.module }}-${{ matrix.partition }}-${{ github.sha }}-attempt-${{ github.run_attempt }} - path: | - build/reports/profile/ - build/reports/compile-failure/${{ matrix.module }}/ - build/reports/gradle-stall/${{ matrix.module }}/ - if-no-files-found: warn - retention-days: 14 - - 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' }} + 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 - timeout-minutes: 30 permissions: - actions: read 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: egress-policy: audit - - name: Check out Account source for complete coverage aggregation + - name: 'Declare Account CI partition count: 4' + if: ${{ matrix.module == 'account-service' }} + run: ':' + + - name: โฌ‡๏ธ Checkout Code uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: - ref: ${{ github.sha }} fetch-depth: 2 persist-credentials: false - - name: ๐Ÿ Set Up Python - uses: ./.github/actions/setup-python + - name: Validate module and retain proof + if: ${{ !cancelled() }} + uses: ./.github/actions/check-gradle-module with: - requirements: none + module: ${{ matrix.module }} + partition: ${{ matrix.partition }} + java-version: ${{ matrix.java-version }} + bootable-modules: ${{ needs.changes.outputs.bootable_modules }} - - 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 + - *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: - 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 + 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: - artifact-ids: ${{ steps.selection.outputs.artifact_ids }} - path: services/account-service/build/slow-service-ci-partition-inputs - merge-multiple: false + fetch-depth: 2 + persist-credentials: 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 + - name: Validate module and retain proof + if: ${{ !cancelled() }} + uses: ./.github/actions/check-gradle-module with: - distribution: 'temurin' - java-version: 25 + module: ${{ matrix.module }} + partition: ${{ matrix.partition }} + java-version: ${{ matrix.java-version }} + bootable-modules: ${{ needs.changes.outputs.bootable_modules }} - - name: โš™๏ธ Set Up Gradle for Account Coverage Aggregation - uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6 + - *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: - 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 + egress-policy: audit - - 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: 'Declare World CI partition count: 2' + if: ${{ matrix.module == 'world-management-service' }} + run: ':' - - name: ๐Ÿ“ค Upload Complete Account Coverage Report - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + - name: โฌ‡๏ธ Checkout Code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # 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 + fetch-depth: 2 + persist-credentials: false - 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' }} + - name: Validate module and retain proof + if: ${{ !cancelled() }} + 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] + 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: @@ -1355,101 +1270,74 @@ jobs: with: egress-policy: audit - - name: Check out Game Session source for complete coverage aggregation + - name: Check out Account 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 + - name: Aggregate complete Account coverage + uses: ./.github/actions/aggregate-slow-service-coverage with: - requirements: none + module: account-service + module-label: Account - - 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 + game-session-coverage-aggregate: + name: Game Session Coverage Aggregate + 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: + actions: read + contents: read + steps: + - name: Harden runner + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 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 + egress-policy: audit + + - name: Check out Game Session source for complete coverage aggregation + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: - artifact-ids: ${{ steps.selection.outputs.artifact_ids }} - path: services/game-session-service/build/slow-service-ci-partition-inputs - merge-multiple: false + ref: ${{ github.sha }} + fetch-depth: 2 + persist-credentials: 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 + - name: Aggregate complete Game Session coverage + uses: ./.github/actions/aggregate-slow-service-coverage with: - distribution: 'temurin' - java-version: 25 + module: game-session-service + module-label: Game Session - - name: โš™๏ธ Set Up Gradle for Game Session Coverage Aggregation - uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6 + 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: - 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 + egress-policy: audit - - 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: Check out World source for complete coverage aggregation + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ github.sha }} + fetch-depth: 2 + persist-credentials: false - - name: ๐Ÿ“ค Upload Complete Game Session Coverage Report - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + - name: Aggregate complete World coverage + uses: ./.github/actions/aggregate-slow-service-coverage 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 + module: world-management-service + module-label: World # Final gating and PR reporting validation-gate: @@ -1466,8 +1354,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, 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 @@ -1544,7 +1434,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 }} @@ -1563,6 +1455,10 @@ 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 }} + 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() { local result="$1" @@ -1663,16 +1559,20 @@ 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" + 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 @@ -1692,6 +1592,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/runtime-images.yml b/.github/workflows/runtime-images.yml index ea2804fecd..7e61a9fe8c 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -1171,8 +1171,13 @@ 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: ./gradlew :${{ matrix.service }}:bootJar + run: bash ./dev-tools/validation/run-gradle-with-dependency-recovery.sh --runner ./gradlew -- :${{ matrix.service }}:bootJar - name: Set up Docker Buildx uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 @@ -1411,10 +1416,15 @@ 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 - ./gradlew :hosted-environment-identity-controller:bootJar + bash ./dev-tools/validation/run-gradle-with-dependency-recovery.sh --runner ./gradlew -- :hosted-environment-identity-controller:bootJar docker build \ --file services/hosted-environment-identity-controller/Dockerfile \ --build-arg BASE_IMAGE="ghcr.io/benhook1013/firemud-base@${{ needs.build-base-image.outputs.digest }}" \ @@ -1895,10 +1905,16 @@ 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 - ./gradlew :hosted-environment-identity-controller:bootJar + bash ./dev-tools/validation/run-gradle-with-dependency-recovery.sh \ + --runner ./gradlew -- :hosted-environment-identity-controller:bootJar docker build \ --file services/hosted-environment-identity-controller/Dockerfile \ --build-arg BASE_IMAGE="$BASE_IMAGE" \ diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index a4bc626f22..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. - const canonicalRuntimeWorkflowSha256 = "520407ce97e1ffbe1db824264f0a64e95887f36df2dc07d5738bed4448759ae2"; + // 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/.github/workflows/validation-summary.yml b/.github/workflows/validation-summary.yml index 2c98f1e635..fbdf6c04bf 100644 --- a/.github/workflows/validation-summary.yml +++ b/.github/workflows/validation-summary.yml @@ -157,13 +157,17 @@ 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"], + ["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) { @@ -180,12 +184,12 @@ 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 }); } 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); } @@ -208,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; @@ -217,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 || @@ -244,8 +254,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"); } @@ -260,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 e92de2b824..6bf3ae1299 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-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. @@ -62,13 +62,13 @@ 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 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. @@ -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: @@ -108,11 +108,12 @@ 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. +- Gradle-based Validation and runtime builds, including affected-module checks, controller builds and the source-built Compose boot-jar command, can recover one exact pinned Gradle-wrapper distribution HTTP 429, 500, 502, 503 or 504 failure before any Gradle task starts. The recovery uses only the official Gradle GitHub release-asset API for the same stable version, requires the release asset digest and downloaded bytes to match the repository's SHA-256 pin, checks the exact asset size, and atomically seeds the ordinary wrapper cache without replacing existing bytes. Metadata and asset requests have bounded time/size limits. The unchanged wrapper command then retries once and still verifies/extracts its own archive. No alternate Gradle version, mirror, compiler/test retry or successful runtime claim is introduced; missing, inconsistent, custom-layout, mixed, interrupted or unrecognized evidence retains the original failure. - 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. -- 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. 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. - 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/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/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. diff --git a/dev-tools/tests/ci-lightweight-scope-contract.sh b/dev-tools/tests/ci-lightweight-scope-contract.sh index 366fb41410..b5f0621ab4 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"), ): @@ -166,6 +168,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 +205,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 +223,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 +236,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|world)_module_check_matrix = .*;$", script)), + "output": output, }), ) rows = json.loads(result.stdout) @@ -488,9 +493,59 @@ 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"), + "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 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) + 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) + # 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 }}", + "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 +564,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") @@ -543,7 +598,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 ( @@ -553,7 +608,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"], ["world-management-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", "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) != 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( java_setup_step, ("with", "java-version"), @@ -562,12 +642,12 @@ 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, ("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( @@ -579,12 +659,12 @@ require_equal( require_equal( runtime_jar_step, ("run",), - "./gradlew --max-workers=2 '-Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8' :${{ matrix.module }}:bootJar -PfullCheck", + "bash ./dev-tools/validation/run-gradle-with-dependency-recovery.sh --runner ./gradlew -- --max-workers=2 '-Dorg.gradle.jvmargs=-Xmx2500m -Dfile.encoding=UTF-8' :${{ matrix.module }}:bootJar -PfullCheck", "ci workflow", ) 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, @@ -592,14 +672,20 @@ 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( - 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, ("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( @@ -622,13 +708,13 @@ 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", ) 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( @@ -646,7 +732,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( @@ -658,23 +744,51 @@ 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"), + ("world-management-service", "world-coverage-aggregate", "World", "WORLD"), ): 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 "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( aggregate_job, ("if",), f"contains(fromJSON(needs.changes.outputs.affected_modules || '[]'), '{module}')", "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, @@ -701,20 +815,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", @@ -740,7 +854,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}") @@ -748,9 +862,10 @@ 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" + 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""" @@ -762,8 +877,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", @@ -775,8 +890,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", @@ -830,6 +945,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"); @@ -868,6 +984,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, @@ -877,6 +1001,7 @@ async function runFor(embedded, options = {}) { }, }; const writes = []; + const snapshotWaits = []; const env = { CI_RUN_ID: String(runId), CI_RUN_ATTEMPT: String(runAttempt), @@ -898,18 +1023,19 @@ 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, provenance: JSON.parse(writes[0][1]) }; + return { ok: true, calls, writes, snapshotWaits, provenance: JSON.parse(writes[0][1]) }; } catch (error) { - return { ok: false, calls, error: error.message }; + return { ok: false, calls, writes, snapshotWaits, error: error.message }; } } (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")); @@ -925,8 +1051,12 @@ 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.snapshotWaits, [[1000, 2]]); assert.deepEqual( result.calls.filter(([kind]) => kind === "jobs").map(([, request]) => request.page), Array.from({ length: attempts }, () => [1, 2]).flat(), @@ -937,7 +1067,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, @@ -997,7 +1127,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); @@ -1016,11 +1146,130 @@ 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.deepEqual(incompleteArtifacts.snapshotWaits, [[1000, 2], [1000, 4], [1000, 6]]); + 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); + assert.deepEqual(changesBetweenSnapshots.snapshotWaits, [[1000, 2], [1000, 4]]); + + 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; }); """ @@ -1035,7 +1284,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 }}", @@ -1081,7 +1330,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]', @@ -1246,6 +1495,53 @@ 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"), + ("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", "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"]' +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"), + ("WORLD_MODULE_AFFECTED", "BUILD_AND_TEST_WORLD", "WORLD_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", "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", "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/ci-validation-summary-contract.sh b/dev-tools/tests/ci-validation-summary-contract.sh index 8891239ad9..b0f759a37c 100644 --- a/dev-tools/tests/ci-validation-summary-contract.sh +++ b/dev-tools/tests/ci-validation-summary-contract.sh @@ -35,9 +35,11 @@ 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 step in ci['jobs']['build-and-test']['steps'] + 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', '') ] @@ -74,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), @@ -343,12 +345,75 @@ 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`/); 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/gradle-dependency-recovery-contract.sh b/dev-tools/tests/gradle-dependency-recovery-contract.sh index 4819030968..c1465c051e 100644 --- a/dev-tools/tests/gradle-dependency-recovery-contract.sh +++ b/dev-tools/tests/gradle-dependency-recovery-contract.sh @@ -1044,3 +1044,175 @@ run_case common-web-support 125 assert_no_retry echo "Gradle dependency-recovery contract passed." + + +# The normal module path retries the unchanged invocation once after a verified +# archive recovery. A second wrapper failure remains failed and is not retried. +for retry_result in success failure; do + new_case "distribution-$retry_result" + mkdir -p "$CASE_DIR/gradle/wrapper" + fixture_sha="$(printf '%s' 'controlled pinned distribution archive' | sha256sum | cut -d ' ' -f 1)" + printf '%s\n' 'distributionBase=GRADLE_USER_HOME' 'distributionPath=wrapper/dists' \ + 'zipStoreBase=GRADLE_USER_HOME' 'zipStorePath=wrapper/dists' \ + 'distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.0-bin.zip' \ + "distributionSha256Sum=$fixture_sha" > "$CASE_DIR/gradle/wrapper/gradle-wrapper.properties" + cat > "$CASE_DIR/bin/curl" <<'CURL_DISTRIBUTION' +#!/usr/bin/env python3 +import hashlib +import json +from pathlib import Path +import sys +payload = b"controlled pinned distribution archive" +output = Path(sys.argv[sys.argv.index("-o") + 1]) +if sys.argv[-1].endswith("/releases/tags/v9.9.0"): + output.write_text(json.dumps({"tag_name": "v9.9.0", "assets": [{"id": 7, "name": "gradle-9.9.0-bin.zip", "size": len(payload), "digest": "sha256:" + hashlib.sha256(payload).hexdigest()}]})) +else: + assert sys.argv[-1] == "https://api.github.com/repos/gradle/gradle-distributions/releases/assets/7" + output.write_bytes(payload) +CURL_DISTRIBUTION + chmod +x "$CASE_DIR/bin/curl" + # shellcheck disable=SC2016 + write_wrapper 'if [[ "$call_count" -eq 1 || "${FAKE_DISTRIBUTION_RETRY_RESULT:-}" == failure ]]; then + echo "Downloading https://services.gradle.org/distributions/gradle-9.9.0-bin.zip" + echo "java.io.IOException: Server returned HTTP response code: 504 for URL: https://services.gradle.org/distributions/gradle-9.9.0-bin.zip" + exit 1 + fi + exit 0' + expected=0 + [[ "$retry_result" == success ]] || expected=1 + GRADLE_USER_HOME="$CASE_DIR/gradle-cache" FAKE_DISTRIBUTION_RETRY_RESULT="$retry_result" run_case common-web-support "$expected" + assert_call_count 2 + [[ "$(sed -n '1p' "$CASE_DIR/calls")" == "$(sed -n '2p' "$CASE_DIR/calls")" ]] || fail "distribution recovery changed the Gradle invocation" + ! grep -Fq -- '--refresh-dependencies' "$CASE_DIR/calls" || fail "distribution transport must not force dependency refresh" + assert_output_contains "Recovered the pinned wrapper distribution before task execution" +done + +# Exercise the wrapper transport recovery separately from Maven metadata refresh. +python3 - "$RECOVERY_RUNNER" <<'PY_DISTRIBUTION_TEST' +import contextlib +import hashlib +import io +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest +from unittest.mock import patch + +runner = Path(sys.argv[1]).read_text() +code = runner.split("<<'PY_DISTRIBUTION'\n", 1)[1].split("\nPY_DISTRIBUTION\n", 1)[0] +url = "https://services.gradle.org/distributions/gradle-9.9.0-bin.zip" +payload = b"controlled pinned distribution archive" +checksum = hashlib.sha256(payload).hexdigest() + +class DistributionRecovery(unittest.TestCase): + def attempt(self, *, log=None, changes=None, metadata=None, body=payload, args=(), error=None, existing=None): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + props = { + "distributionBase": "GRADLE_USER_HOME", "distributionPath": "wrapper/dists", + "zipStoreBase": "GRADLE_USER_HOME", "zipStorePath": "wrapper/dists", + "distributionUrl": url.replace(":", "\\:"), "distributionSha256Sum": checksum, + } + props.update(changes or {}) + properties = root / "gradle/wrapper/gradle-wrapper.properties" + properties.parent.mkdir(parents=True) + properties.write_text("".join(f"{key}={value}\n" for key, value in props.items() if value is not None)) + log_path = root / "normal.log" + log_path.write_text(log if log is not None else f'Downloading {url}\nException in thread "main" java.io.IOException: Server returned HTTP response code: 504 for URL: {url}\n') + release = metadata if metadata is not None else {"tag_name": "v9.9.0", "assets": [{"id": 7, "name": "gradle-9.9.0-bin.zip", "size": len(payload), "digest": f"sha256:{checksum}"}]} + cache = root / "cache" + number = int.from_bytes(hashlib.md5(url.encode()).digest(), "big") + key = "" + while number: + number, remainder = divmod(number, 36) + key = "0123456789abcdefghijklmnopqrstuvwxyz"[remainder] + key + target = cache / "wrapper/dists/gradle-9.9.0-bin" / key / "gradle-9.9.0-bin.zip" + if existing is not None: + target.parent.mkdir(parents=True) + target.write_bytes(existing) + calls = [] + def fetch(command, **options): + calls.append(command) + self.assertEqual(command[0], "curl") + self.assertTrue(options["check"]) + self.assertLessEqual(options["timeout"], 80) + if error is not None: + raise error + output = Path(command[command.index("-o") + 1]) + if command[-1].endswith("/releases/tags/v9.9.0"): + self.assertIn("Accept: application/vnd.github+json", command) + output.write_text(json.dumps(release)) + else: + self.assertEqual(command[-1], "https://api.github.com/repos/gradle/gradle-distributions/releases/assets/7") + self.assertIn("Accept: application/octet-stream", command) + output.write_bytes(body) + return subprocess.CompletedProcess(command, 0) + with patch.object(sys, "argv", ["recovery", str(root), str(log_path), *args]), patch.dict(os.environ, {"GRADLE_USER_HOME": str(cache)}), patch("subprocess.run", side_effect=fetch), contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): + with self.assertRaises(SystemExit) as outcome: + exec(compile(code, "distribution-recovery", "exec"), {}) + return outcome.exception.code, calls, target.read_bytes() if target.exists() else None + + def test_exact_pinned_distribution_uses_official_api_and_keeps_bytes(self): + status, calls, stored = self.attempt() + self.assertEqual(status, 0) + self.assertEqual(len(calls), 2) + self.assertEqual(stored, payload) + + def test_existing_verified_archive_is_not_replaced(self): + status, calls, stored = self.attempt(existing=payload) + self.assertEqual((status, calls, stored), (0, [], payload)) + status, calls, stored = self.attempt(existing=b"unexpected existing archive") + self.assertEqual((status, calls, stored), (1, [], b"unexpected existing archive")) + + def test_task_test_compile_and_unrecognized_failures_never_fetch(self): + base = f'Downloading {url}\nException in thread "main" java.io.IOException: Server returned HTTP response code: 504 for URL: {url}\n' + for log in ["unrelated failure", base.replace("504", "404"), base.replace(url, url.replace("9.9.0", "9.8.2")), "> Task :account-service:test\n" + base, "\x1b[31m> Task :account-service:test\x1b[0m\n" + base, "Compilation failed\n" + base, "There were failing tests\n" + base, "BUILD FAILED\n" + base, "java.lang.IllegalStateException: unrelated failure\n" + base, base + "Downloading https://untrusted.example/other.zip\n"]: + with self.subTest(log=log): + status, calls, stored = self.attempt(log=log) + self.assertEqual((status, calls, stored), (1, [], None)) + + def test_bad_pin_layout_and_different_cache_args_never_fetch(self): + for changes in [{"distributionSha256Sum": None}, {"distributionSha256Sum": "bad"}, {"distributionUrl": "https://untrusted.example/gradle-9.9.0-bin.zip"}, {"zipStorePath": "other"}, {"distributionBase": "PROJECT"}]: + with self.subTest(changes=changes): + self.assertEqual(self.attempt(changes=changes)[:2], (1, [])) + for args in [("-g", "/other"), ("--gradle-user-home=/other",)]: + self.assertEqual(self.attempt(args=args)[:2], (1, [])) + + def test_malformed_or_mismatched_release_metadata_does_not_download_asset(self): + base = {"tag_name": "v9.9.0", "assets": [{"id": 7, "name": "gradle-9.9.0-bin.zip", "size": len(payload), "digest": f"sha256:{checksum}"}]} + variants = [{}, [], {**base, "assets": None}, {**base, "assets": ["malformed"]}, {**base, "tag_name": "v9.8.2"}, {**base, "draft": True}, {**base, "prerelease": True}, {**base, "assets": []}, {**base, "assets": base["assets"] * 2}] + for change in [{"id": True}, {"id": 0}, {"size": 0}, {"size": 536870913}, {"digest": "sha256:" + "0" * 64}]: + variants.append({**base, "assets": [{**base["assets"][0], **change}]}) + for metadata in variants: + with self.subTest(metadata=metadata): + status, calls, stored = self.attempt(metadata=metadata) + self.assertEqual(status, 1) + self.assertEqual(len(calls), 1) + self.assertIsNone(stored) + + def test_download_error_and_checksum_or_size_mismatch_publish_nothing(self): + for body in [payload + b"extra", b"x" * len(payload)]: + status, calls, stored = self.attempt(body=body) + self.assertEqual((status, len(calls), stored), (1, 2, None)) + status, calls, stored = self.attempt(error=subprocess.CalledProcessError(22, "curl")) + self.assertEqual((status, len(calls), stored), (1, 1, None)) + +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 "$GRADLE_COMMAND_PATTERN" "$workflow"; then + fail "Gradle bootstrap bypasses bounded distribution recovery in $workflow" + fi +done +echo "Official Gradle distribution transport contracts passed" 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 4a6bad2355..8cad9606b3 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -1056,14 +1056,17 @@ 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 (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} -# Captured incident shape: 19 existing prerequisite jobs 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, @@ -1085,6 +1088,26 @@ 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-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")] @@ -1936,7 +1959,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-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 @@ -3449,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]); @@ -3474,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}}, @@ -3489,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, @@ -3503,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. @@ -3621,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")]); diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index 81f0415241..b47d12f249 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -581,7 +581,10 @@ 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 \ + build-and-test-world; 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..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"] @@ -1047,6 +1136,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) diff --git a/dev-tools/tests/workflow_version_authority_contract.py b/dev-tools/tests/workflow_version_authority_contract.py index b0eb57c2af..2c960cec07 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 @@ -1184,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"$' ) @@ -1198,6 +1202,162 @@ 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:] + 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") != { + "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' + '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 > "$output"\n exit 28\nfi\n' + 'cp -- "$GH_FIXTURE_ARCHIVE" "$output"\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), + "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, + check=False, + ) + 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: + 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") diff --git a/dev-tools/validation/run-gradle-with-dependency-recovery.sh b/dev-tools/validation/run-gradle-with-dependency-recovery.sh index 459f3b528e..0ec3c9611c 100644 --- a/dev-tools/validation/run-gradle-with-dependency-recovery.sh +++ b/dev-tools/validation/run-gradle-with-dependency-recovery.sh @@ -464,6 +464,143 @@ retry_delay_seconds() { printf '%s\n' "$delay" } +# Recover only a wrapper download failure before any Gradle task starts. The +# official API is another transport for the same pinned release bytes, never a +# version fallback or permission to retry compilation/tests. +recover_wrapper_distribution() { + local root_dir + root_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" + grep -Eq '^Downloading https://services[.]gradle[.]org/distributions/gradle-[0-9]+[.][0-9]+[.][0-9]+-bin[.]zip$' "$NORMAL_LOG" || return 1 + python3 - "$root_dir" "$NORMAL_LOG" "${GRADLE_ARGS[@]}" <<'PY_DISTRIBUTION' +import hashlib +import json +import os +from pathlib import Path +import re +import subprocess +import sys +import tempfile + +root, log = Path(sys.argv[1]), Path(sys.argv[2]) + +def digest(path): + value = hashlib.sha256() + with path.open("rb") as source: + for chunk in iter(lambda: source.read(1024 * 1024), b""): + value.update(chunk) + return value.hexdigest() + +def recover(): + # A different CLI cache selection or custom layout is not this recovery path. + if any(arg == "-g" or arg.startswith("-g") or arg.startswith("--gradle-user-home") for arg in sys.argv[3:]): + return False + if log.stat().st_size > 1048576: + return False + text = log.read_text(errors="replace") + text = re.sub(r"\x1b\[[0-?]*[ -/]*[@-~]", "", text) + if re.search(r"^> Task |BUILD FAILED|Compilation failed|There were failing tests|\berror:", text, re.MULTILINE): + return False + props = {} + properties = root / "gradle/wrapper/gradle-wrapper.properties" + if properties.stat().st_size > 65536: + return False + for line in properties.read_text().splitlines(): + if not line.strip() or line.lstrip().startswith("#"): + continue + key, value = line.split("=", 1) + if key in props: + return False + props[key] = value.replace("\\:", ":") + url = props.get("distributionUrl", "") + match = re.fullmatch(r"https://services\.gradle\.org/distributions/gradle-([0-9]+\.[0-9]+\.[0-9]+)-bin\.zip", url) + checksum = props.get("distributionSha256Sum", "") + if not match or not re.fullmatch(r"[0-9a-f]{64}", checksum): + return False + if any(props.get(key) != value for key, value in { + "distributionBase": "GRADLE_USER_HOME", "distributionPath": "wrapper/dists", + "zipStoreBase": "GRADLE_USER_HOME", "zipStorePath": "wrapper/dists", + }.items()): + return False + failure = re.compile(r'(?:Exception in thread "main" )?java\.io\.IOException: Server returned HTTP response code: (?:429|500|502|503|504) for URL: ' + re.escape(url)) + if not any(failure.fullmatch(line) for line in text.splitlines()): + return False + # Refuse mixed top-level failures and downloads for a different distribution. + for line in text.splitlines(): + if line.startswith("Downloading ") and line != f"Downloading {url}": + return False + if re.match(r'(?:Exception in thread "[^"]+" )?(?:[A-Za-z_$][\w$]*\.)+[A-Za-z_$][\w$]*(?:Exception|Error):', line) and not failure.fullmatch(line): + return False + version = match[1] + name = f"gradle-{version}-bin.zip" + cache_root = Path(os.environ.get("GRADLE_USER_HOME") or Path.home() / ".gradle") + # Match Gradle PathAssembler's URL-derived cache key; SHA-256 verifies bytes. + number = int.from_bytes(hashlib.md5(url.encode()).digest(), "big") + cache_key = "" + while number: + number, remainder = divmod(number, 36) + cache_key = "0123456789abcdefghijklmnopqrstuvwxyz"[remainder] + cache_key + target = cache_root / "wrapper/dists" / name.removesuffix(".zip") / cache_key / name + if target.is_symlink(): + return False + if target.exists(): + return digest(target) == checksum + with tempfile.TemporaryDirectory(prefix="distribution-", dir=log.parent) as temporary: + metadata, archive = Path(temporary) / "release.json", Path(temporary) / name + common = ["curl", "-fsSL", "--retry", "2", "--retry-delay", "2", "--connect-timeout", "10"] + subprocess.run(common + ["--max-time", "20", "--retry-max-time", "25", "--max-filesize", "2097152", + "-H", "Accept: application/vnd.github+json", "-o", str(metadata), + f"https://api.github.com/repos/gradle/gradle-distributions/releases/tags/v{version}"], + check=True, timeout=30) + release = json.loads(metadata.read_text()) + if not isinstance(release, dict) or not isinstance(release.get("assets"), list): + return False + if any(not isinstance(asset, dict) for asset in release["assets"]): + return False + assets = [asset for asset in release["assets"] if asset.get("name") == name] + if release.get("tag_name") != f"v{version}" or release.get("draft") or release.get("prerelease") or len(assets) != 1: + return False + asset = assets[0] + asset_id, size = asset.get("id"), asset.get("size") + if type(asset_id) is not int or asset_id <= 0 or type(size) is not int or not 0 < size <= 536870912: + return False + if asset.get("digest") != f"sha256:{checksum}": + return False + subprocess.run(common + ["--max-time", "60", "--retry-max-time", "70", "--max-filesize", str(size), + "-H", "Accept: application/octet-stream", "-o", str(archive), + f"https://api.github.com/repos/gradle/gradle-distributions/releases/assets/{asset_id}"], + check=True, timeout=80) + if archive.stat().st_size != size or digest(archive) != checksum: + return False + target.parent.mkdir(parents=True, exist_ok=True) + # Publish a complete verified archive atomically without replacing an + # existing archive. The ordinary wrapper still verifies and extracts it. + with tempfile.NamedTemporaryFile(prefix="verified-", dir=target.parent, delete=False) as output: + candidate = Path(output.name) + try: + with archive.open("rb") as source: + for chunk in iter(lambda: source.read(1024 * 1024), b""): + output.write(chunk) + output.flush() + os.fsync(output.fileno()) + try: + os.link(candidate, target) + except FileExistsError: + if target.is_symlink() or digest(target) != checksum: + return False + finally: + candidate.unlink(missing_ok=True) + print(f"Verified pinned Gradle {version} distribution via official release asset API; SHA256={checksum}.") + return True + +try: + recovered = recover() +except (OSError, ValueError, KeyError, TypeError, subprocess.SubprocessError) as failure: + print(f"Pinned Gradle distribution transport recovery unavailable ({type(failure).__name__}); preserving original build failure.", file=sys.stderr) + recovered = False +sys.exit(0 if recovered else 1) +PY_DISTRIBUTION +} + run_gradle_check false "$NORMAL_LOG" if [[ "$GRADLE_EXIT" -eq 0 ]]; then exit 0 @@ -473,6 +610,12 @@ if [[ "$GRADLE_EXIT" -ne 1 ]]; then exit "$GRADLE_EXIT" fi +if recover_wrapper_distribution; then + echo "Recovered the pinned wrapper distribution before task execution; retrying the original Gradle command once." + run_gradle_check false "$REFRESH_LOG" + exit "$GRADLE_EXIT" +fi + if ! is_dependency_resolution_failure "$NORMAL_LOG"; then exit "$GRADLE_EXIT" fi 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" } } } diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 0bb71f3468..910c6f79b7 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -2,8 +2,8 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists distributionSha256Sum=0b00b0ffe07c4d4789c12d4935a44a7057d55774b7540bd4a3f76f336deb177a distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.0-bin.zip -networkTimeout=10000 -retries=0 +networkTimeout=60000 +retries=3 retryBackOffMs=500 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME 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();