diff --git a/.gitea/BUILD_AND_RELEASE.md b/.gitea/BUILD_AND_RELEASE.md index 2fda136..4117d80 100644 --- a/.gitea/BUILD_AND_RELEASE.md +++ b/.gitea/BUILD_AND_RELEASE.md @@ -77,7 +77,11 @@ Android and Windows independently download their platform artifacts from the selected CI run and immediately upload them to the draft. These jobs run in parallel. The final job accepts only the compact metadata artifact from that same CI run. Complete binary archives cannot substitute for platform packages or -metadata. Missing, expired or duplicate required artifacts block preparation +metadata. Gitea can retain old artifact API rows after a job rerun despite overwrite. +Selection requires the exact CI run and source commit, and exactly one artifact +created within its current successful producer job's execution interval. Jobs +preserved during a partial rerun retain their original intervals and artifacts. +Missing, expired or ambiguous artifacts in that interval block preparation before any draft is created. Platform uploads check attachment presence without reading back their bytes. Before publication, every attachment is read back once and verified against trusted SHA256 checksums; the full update package also @@ -94,6 +98,11 @@ operator attention. Published Releases are never overwritten. The built-in GITEA_TOKEN handles release writes and Actions artifact reads; no separate release-write PAT is required. Do not commit credentials or keystores. +Release tools are checked out at the workflow's exact commit; tagged application +source is checked out separately in `.release-source`. A manual dispatch on main +can therefore apply a reviewed release-tool fix to an existing tag without moving +that tag or substituting another application's version or CI artifacts. + Full-pipeline CI produces Actions artifacts without creating Releases. If a tag is pushed before main CI succeeds, release preparation fails without creating a draft; retry the Release workflow once CI has finished. This design overlaps platform uploads, diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml index 236c7e9..39ca30c 100644 --- a/.gitea/workflows/release.yml +++ b/.gitea/workflows/release.yml @@ -24,6 +24,7 @@ env: GIT_CONFIG_VALUE_0: 'false' GIT_CONFIG_KEY_1: core.eol GIT_CONFIG_VALUE_1: lf + RELEASE_PUBSPEC: .release-source/pubspec.yaml RELEASE_TAG: ${{ gitea.event.inputs.tag || gitea.ref_name }} GITEA_REPOSITORY: ${{ gitea.repository }} jobs: @@ -40,16 +41,23 @@ jobs: env: GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} steps: - - name: Check out release tag + - name: Check out pinned release tools + uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + with: + ref: ${{ gitea.sha }} + persist-credentials: false + github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }} + - name: Check out release source separately uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: ref: ${{ gitea.event.inputs.tag || gitea.ref_name }} + path: .release-source persist-credentials: false github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }} - name: Select successful CI and prepare draft id: draft run: | - $env:GITEA_SHA = git rev-parse HEAD + $env:GITEA_SHA = git -C .release-source rev-parse HEAD if ($LASTEXITCODE -ne 0) { throw 'Release source resolution failed.' } python tool/gitea/stage-release.py prepare-ci if ($LASTEXITCODE -ne 0) { throw 'CI selection or draft preparation failed.' } @@ -65,10 +73,17 @@ jobs: CI_RUN_ID: ${{ needs.prepare.outputs.ci-run-id }} CI_ARTIFACT_ID: ${{ needs.prepare.outputs.android-artifact-id }} steps: - - name: Check out release commit + - name: Check out pinned release tools uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: - ref: ${{ needs.prepare.outputs.sha }} + ref: ${{ gitea.sha }} + persist-credentials: false + github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }} + - name: Check out release source separately + uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + with: + ref: ${{ gitea.event.inputs.tag || gitea.ref_name }} + path: .release-source persist-credentials: false github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }} - name: Download Android CI artifact @@ -91,10 +106,17 @@ jobs: CI_RUN_ID: ${{ needs.prepare.outputs.ci-run-id }} CI_ARTIFACT_ID: ${{ needs.prepare.outputs.windows-artifact-id }} steps: - - name: Check out release commit + - name: Check out pinned release tools uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: - ref: ${{ needs.prepare.outputs.sha }} + ref: ${{ gitea.sha }} + persist-credentials: false + github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }} + - name: Check out release source separately + uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + with: + ref: ${{ gitea.event.inputs.tag || gitea.ref_name }} + path: .release-source persist-credentials: false github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }} - name: Download Windows CI artifact @@ -117,10 +139,17 @@ jobs: CI_RUN_ID: ${{ needs.prepare.outputs.ci-run-id }} CI_ARTIFACT_ID: ${{ needs.prepare.outputs.artifact-id }} steps: - - name: Check out release commit + - name: Check out pinned release tools uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 with: - ref: ${{ needs.prepare.outputs.sha }} + ref: ${{ gitea.sha }} + persist-credentials: false + github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }} + - name: Check out release source separately + uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + with: + ref: ${{ gitea.event.inputs.tag || gitea.ref_name }} + path: .release-source persist-credentials: false github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }} - name: Download release verification metadata diff --git a/.gitignore b/.gitignore index fea3319..4995902 100644 --- a/.gitignore +++ b/.gitignore @@ -108,3 +108,4 @@ pubspec_overrides.yaml # Core and native source checkouts prepared by CI or local development. .dependencies/ +.release-source/ diff --git a/test/generated_code_test.dart b/test/generated_code_test.dart index ad94165..8983e83 100644 --- a/test/generated_code_test.dart +++ b/test/generated_code_test.dart @@ -1,3 +1,4 @@ +import 'dart:async'; import 'dart:convert'; import 'dart:io'; @@ -14,29 +15,83 @@ const _generatedFiles = [ ]; void main() { - test('workspace generated code is up to date', () async { - await _expectNoUntrackedGeneratedFiles(); - final before = await _generatedContents(); - final dart = flutterTestDartExecutable(); - for (final directory in _generatorRoots()) { - final result = await Process.run(dart, [ - 'run', - 'build_runner', - 'build', - ], workingDirectory: directory); + test( + 'workspace generated code is up to date', + () async { + await _expectNoUntrackedGeneratedFiles(); + final before = await _generatedContents(); + final dart = flutterTestDartExecutable(); + final elapsed = Stopwatch()..start(); + for (final directory in _generatorRoots()) { + await _generate( + dart, + directory, + const Duration(minutes: 5) - + const Duration(seconds: 10) - + elapsed.elapsed, + ); + } expect( - result.exitCode, - 0, - reason: '$directory\n${result.stdout}\n${result.stderr}', + await _generatedContents(), + before, + reason: 'Generated files changed. Run dart run build_runner build and review the output.', ); + await _expectNoUntrackedGeneratedFiles(); + }, + timeout: const Timeout(Duration(minutes: 5)), + tags: ['codegen'], + ); +} + +Future _generate( + String dart, + String directory, + Duration remaining, +) async { + if (remaining <= Duration.zero) { + throw TimeoutException('Generated-code verification budget exhausted'); + } + final elapsed = Stopwatch()..start(); + stdout.writeln( + 'Generating $directory; remaining budget: ${remaining.inSeconds}s', + ); + final process = await Process.start(dart, [ + 'run', + 'build_runner', + 'build', + ], workingDirectory: directory); + final output = StringBuffer(); + Future read(Stream> stream) async { + await for (final line + in stream.transform(utf8.decoder).transform(const LineSplitter())) { + output.writeln(line); + stdout.writeln('[$directory] $line'); } - expect( - await _generatedContents(), - before, - reason: 'Generated files changed. Run dart run build_runner build and review the output.', + } + + final streams = Future.wait([read(process.stdout), read(process.stderr)]); + var exited = false; + try { + final exitCode = await process.exitCode.timeout(remaining); + exited = true; + await streams; + expect(exitCode, 0, reason: '$directory\n$output'); + } finally { + if (!exited) { + // Flutter's outer test timeout cannot terminate Process.run children. + // End the generator before leaving the test, including on Windows. + if (Platform.isWindows) { + await Process.run('taskkill', ['/PID', '${process.pid}', '/T', '/F']); + } else { + process.kill(ProcessSignal.sigkill); + } + await process.exitCode; + await streams; + } + stdout.writeln( + 'Generation $directory ended after ${elapsed.elapsed.inMilliseconds}ms', ); - await _expectNoUntrackedGeneratedFiles(); - }, timeout: const Timeout(Duration(minutes: 5))); + } } Future _expectNoUntrackedGeneratedFiles() async { diff --git a/tool/check.py b/tool/check.py index 551a6b5..00e23a4 100644 --- a/tool/check.py +++ b/tool/check.py @@ -45,7 +45,12 @@ def check_analyze(): def check_flutter(): package_tests = sorted(str(path.relative_to(ROOT)) for pattern in ('*/test', '*/example/test') for path in (ROOT / 'packages').glob(pattern)) - run(tool_command('flutter', ['test', '--reporter', 'expanded', 'test', *package_tests])) + run(tool_command('flutter', ['test', '--reporter', 'expanded', '--exclude-tags', 'codegen', + 'test', *package_tests])) + # build_runner compiles generators and performs repository-wide file I/O. + # Keep this gate serial with widget tests to avoid competing with their isolates. + run(tool_command('flutter', ['test', '--reporter', 'expanded', '--tags', 'codegen', + 'test/generated_code_test.dart'])) def main(): diff --git a/tool/gitea/stage-release.py b/tool/gitea/stage-release.py index 7a56abb..f6a3597 100644 --- a/tool/gitea/stage-release.py +++ b/tool/gitea/stage-release.py @@ -1,6 +1,7 @@ """Upload platform builds to a commit-bound draft, then verify and publish it.""" import argparse from concurrent.futures import ThreadPoolExecutor +from datetime import datetime import hashlib import importlib.util import io @@ -22,7 +23,7 @@ fingerprint = transport.fingerprint def context(): base = f"{transport.SERVER}/api/v1/repos/{os.environ['GITEA_REPOSITORY']}" sha, tag = os.environ['GITEA_SHA'], os.environ['RELEASE_TAG'] - version, windows_version = app_versions('pubspec.yaml') + version, windows_version = app_versions(os.environ.get('RELEASE_PUBSPEC', 'pubspec.yaml')) if tag != f'v{version}': raise ValueError('Release tag must match pubspec version') remote_tag = request(f'{base}/tags/{urllib.parse.quote(tag, safe="")}') @@ -65,8 +66,25 @@ def ci_artifacts(base, run_id): if not item.get('expired', False)] -def artifact_named(artifacts, name): - matches = [item for item in artifacts if item['name'] == name] +def artifact_named(artifacts, name, run, jobs): + producer = {'cutdex-android-build': 'Build Android APK', + 'cutdex-windows-build': 'Audit and package Windows x64', + 'cutdex-release-metadata': 'Assemble and validate CI artifacts'}[name] + producers = [job for job in jobs if job['name'] == producer + and job.get('conclusion') == 'success' and job.get('head_sha') == run['head_sha']] + if len(producers) != 1: + raise ValueError('Expected one successful artifact producer: ' + producer) + job = producers[0] + def timestamp(value): + return datetime.fromisoformat(value.replace('Z', '+00:00')) + started, completed = timestamp(job['started_at']), timestamp(job['completed_at']) + # Gitea retains old API rows after overwrite/rerun. Accept only the artifact + # uploaded within the current successful producer's interval; cloned jobs + # retain their original interval and therefore reuse their original bytes. + matches = [item for item in artifacts if item['name'] == name + and item.get('workflow_run', {}).get('id') == run['id'] + and item['workflow_run'].get('head_sha') == run['head_sha'] + and started <= timestamp(item['created_at']) <= completed] if len(matches) != 1: raise ValueError('Expected one unexpired CI artifact: ' + name) return matches[0] @@ -91,8 +109,9 @@ def prepare_ci(base, sha, tag, version, windows_version): run_id = int(matches[0]) run = successful_ci(base, sha, run_id) artifacts = ci_artifacts(base, run['id']) - verification = artifact_named(artifacts, 'cutdex-release-metadata') - selected = {platform: artifact_named(artifacts, f'cutdex-{platform}-build') + jobs = request(f"{base}/actions/runs/{run['id']}/jobs")['jobs'] + verification = artifact_named(artifacts, 'cutdex-release-metadata', run, jobs) + selected = {platform: artifact_named(artifacts, f'cutdex-{platform}-build', run, jobs) for platform in ('android', 'windows')} release = prepare(base, sha, tag, version, windows_version, ci_run=run['id']) if os.environ.get('GITHUB_OUTPUT'): diff --git a/tool/gitea/test_stage_release.py b/tool/gitea/test_stage_release.py index 9ac3626..1ca95b1 100644 --- a/tool/gitea/test_stage_release.py +++ b/tool/gitea/test_stage_release.py @@ -41,6 +41,14 @@ class StagedReleaseTests(unittest.TestCase): {'id': 11, 'name': 'cutdex-android-build'}, {'id': 12, 'name': 'cutdex-windows-build'}, {'id': 13, 'name': 'cutdex-release-metadata'}]} + for artifact in self.run_artifacts[1]: + artifact.update(created_at='2026-10-11T10:01:00Z', + workflow_run={'id': 1, 'head_sha': self.sha}) + self.ci_jobs = {1: [{'name': name, 'head_sha': self.sha, 'conclusion': 'success', + 'started_at': '2026-10-11T10:00:00Z', + 'completed_at': '2026-10-11T10:02:00Z'} for name in + ['Build Android APK', 'Audit and package Windows x64', + 'Assemble and validate CI artifacts']]} self.artifact_contents = {10: self.contents, 11: {'app-production-release.apk': self.contents['cutdex-0.1.0-android.apk']}, 12: {name: body for name, body in self.contents.items() @@ -74,6 +82,8 @@ class StagedReleaseTests(unittest.TestCase): self.calls.append((method, url)) if url.endswith('/actions/runs?limit=100'): return {'workflow_runs': self.ci_runs} + if '/actions/runs/' in url and url.endswith('/jobs'): + return {'jobs': self.ci_jobs[int(url.split('/actions/runs/')[1].split('/')[0])]} if '/actions/runs/' in url and url.endswith('/artifacts'): return {'artifacts': self.run_artifacts[int(url.split('/actions/runs/')[1].split('/')[0])]} if '/actions/artifacts/' in url and url.endswith('/zip'): @@ -262,6 +272,29 @@ class StagedReleaseTests(unittest.TestCase): self.assertIn(stage.ci_marker(1), self.release['body']) self.assert_draft() + def test_independent_packaging_retry_uses_current_producers_and_original_android(self): + for job in self.ci_jobs[1][1:]: + job.update(started_at='2026-10-11T11:00:00Z', completed_at='2026-10-11T11:02:00Z') + for old_id, new_id in [(12, 22), (13, 23)]: + old = next(item for item in self.run_artifacts[1] if item['id'] == old_id) + self.run_artifacts[1].append(dict(old, id=new_id, created_at='2026-10-11T11:01:00Z')) + self.run_cli('prepare-ci') + output = (self.root / 'outputs').read_text() + for value in ['artifact-id=23', 'windows-artifact-id=22', 'android-artifact-id=11']: + self.assertIn(value, output) + + def test_same_producer_duplicate_or_wrong_source_artifact_is_rejected(self): + current = self.run_artifacts[1][3] + self.run_artifacts[1].append(dict(current, id=99)) + with self.assertRaisesRegex(ValueError, 'one unexpired CI artifact'): + self.run_cli('prepare-ci') + self.run_artifacts[1].pop() + for identity in [{'id': 2, 'head_sha': self.sha}, {'id': 1, 'head_sha': 'b' * 40}]: + current['workflow_run'] = identity + with self.assertRaisesRegex(ValueError, 'one unexpired CI artifact'): + self.run_cli('prepare-ci') + self.assertIsNone(self.release) + def test_ci_failure_or_expired_metadata_never_creates_draft(self): self.ci_runs[0]['conclusion'] = 'failure' with self.assertRaisesRegex(ValueError, 'No successful main CI'):