From 5b05af742bb21b88baf1f9392dfaaa9f9702f7fd Mon Sep 17 00:00:00 2001 From: leehack Date: Sun, 22 Nov 2026 12:20:22 -0500 Subject: [PATCH 1/2] ci: sweep orphaned chat preview Spaces --- .github/CODEOWNERS | 1 + .../chat_app_hf_pr_preview_sweep.yml | 66 ++++++++ doc/ci_selection.md | 7 +- example/chat_app/README.md | 11 +- test/ci/test_preview_sweep.py | 152 ++++++++++++++++++ .../tooling/ci_workflow_selection_test.dart | 52 ++++++ test/unit/tooling/preview_guard_test.dart | 16 ++ tool/ci/preview_guard.py | 16 +- tool/ci/preview_sweep.py | 107 ++++++++++++ 9 files changed, 416 insertions(+), 12 deletions(-) create mode 100644 .github/workflows/chat_app_hf_pr_preview_sweep.yml create mode 100644 test/ci/test_preview_sweep.py create mode 100644 tool/ci/preview_sweep.py diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 1a98ae4ec..075da85d5 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -89,6 +89,7 @@ packages/*/pubspec_overrides.yaml @leehack tool/ci/web_deployment.py @leehack tool/ci/preview_guard.py @leehack +tool/ci/preview_sweep.py @leehack tool/ci/deploy_guard.py @leehack tool/ci/hf_space_deploy.py @leehack test/ci/test_hf_space_deploy.py @leehack diff --git a/.github/workflows/chat_app_hf_pr_preview_sweep.yml b/.github/workflows/chat_app_hf_pr_preview_sweep.yml new file mode 100644 index 000000000..cf7383df1 --- /dev/null +++ b/.github/workflows/chat_app_hf_pr_preview_sweep.yml @@ -0,0 +1,66 @@ +name: Sweep Chat App HF PR Previews + +on: + schedule: + - cron: '23 6 * * *' + workflow_dispatch: + +permissions: {} + +jobs: + list: + name: Find closed PR previews + if: github.repository == 'leehack/llamadart' && github.ref == 'refs/heads/main' + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: read + pull-requests: read + outputs: + prs: ${{ steps.list.outputs.prs }} + steps: + - uses: actions/checkout@v7 + with: + ref: ${{ github.sha }} + persist-credentials: false + - name: Install Hugging Face Hub client + run: python3 -m pip install "huggingface_hub>=0.36.0,<0.37.0" + - name: List preview Spaces for closed PRs + id: list + env: + GH_TOKEN: ${{ github.token }} + HF_TOKEN: ${{ secrets.HF_TOKEN }} + run: python3 tool/ci/preview_sweep.py list + + delete: + name: Remove preview for PR ${{ matrix.pr }} + needs: list + if: needs.list.outputs.prs != '' && needs.list.outputs.prs != '[]' + runs-on: ubuntu-latest + timeout-minutes: 10 + strategy: + fail-fast: false + max-parallel: 2 + matrix: + pr: ${{ fromJSON(needs.list.outputs.prs) }} + # Share the write queue with preview deploys and close-time cleanup. + concurrency: + group: chat-app-hf-pr-preview-write-${{ matrix.pr }} + cancel-in-progress: false + queue: max + permissions: + contents: read + pull-requests: read + steps: + - uses: actions/checkout@v7 + with: + ref: ${{ github.sha }} + persist-credentials: false + - name: Install Hugging Face Hub client + run: python3 -m pip install "huggingface_hub>=0.36.0,<0.37.0" + - name: Recheck live PR and delete the preview Space + env: + GH_TOKEN: ${{ github.token }} + HF_TOKEN: ${{ secrets.HF_TOKEN }} + PREVIEW_PR_NUMBER: ${{ matrix.pr }} + run: python3 tool/ci/preview_sweep.py delete diff --git a/doc/ci_selection.md b/doc/ci_selection.md index 8d9351c40..99a1bb995 100644 --- a/doc/ci_selection.md +++ b/doc/ci_selection.md @@ -315,15 +315,16 @@ part of this batch. python3 -m unittest discover -s test/ci -p 'test_*.py' dart run tool/testing/run_local_e2e.dart --scenario ci-selection actionlint .github/workflows/ci.yml .github/workflows/validation_bundles.yml -actionlint -ignore '^unexpected key "queue" for "concurrency" section\. expected one of "cancel-in-progress", "group"$' .github/workflows/chat_app_hf_static_deploy.yml +actionlint -ignore '^unexpected key "queue" for "concurrency" section\. expected one of "cancel-in-progress", "group"$' .github/workflows/chat_app_hf_static_deploy.yml .github/workflows/chat_app_hf_pr_preview.yml .github/workflows/chat_app_hf_pr_preview_sweep.yml ``` Actionlint 1.7.12 rejects GitHub's documented `concurrency.queue` key ([upstream issue](https://github.com/rhysd/actionlint/issues/657), [pending fix](https://github.com/rhysd/actionlint/pull/654)). Retain its unfiltered diagnostic as evidence before the second invocation: that invocation excludes -only this known schema diagnostic for the reusable deploy workflow. Its queue -policy is covered by the workflow tests; other lint diagnostics still fail. +only this known schema diagnostic for the listed workflows. Workflow tests +cover queue settings and require the preview sweep to share the preview write +group. Other lint diagnostics still fail. Tests cover docs-only and package changes, shared/runtime/unknown inputs, platform targets, workflow changes, actual Git rename/deletion histories, diff --git a/example/chat_app/README.md b/example/chat_app/README.md index 733d4182e..62c8a49de 100644 --- a/example/chat_app/README.md +++ b/example/chat_app/README.md @@ -767,9 +767,14 @@ await prefs.setInt('preferred_backend', backendIndex); sources, or the web bridge asset script. - Creates or updates a per-PR static Space named `llamadart-chat-pr-` and comments the preview URL on the PR. -- Deletes the preview Space when the PR is closed. -- Required repository secret: `HF_TOKEN` with write/create access to the preview - namespace. +- Deletes the preview Space when the close event runs the workflow. GitHub + can skip that event's workflow when the PR has merge conflicts. +- `chat_app_hf_pr_preview_sweep.yml` runs daily on `main` and sweeps + `leehack/llamadart-chat-pr-` Spaces for closed PRs. Each deletion + waits in the PR's preview write queue and checks that the PR is still closed. + Run it manually with `gh workflow run chat_app_hf_pr_preview_sweep.yml --ref main`. +- Required repository secret: `HF_TOKEN` with create, write, and delete access + to the preview namespace. - Optional repository variable: `HF_CHAT_APP_PREVIEW_NAMESPACE`. If omitted, the workflow uses the owner portion of `HF_CHAT_APP_SPACE_REPO`. - Fork PRs are skipped so repository secrets are not exposed to untrusted code. diff --git a/test/ci/test_preview_sweep.py b/test/ci/test_preview_sweep.py new file mode 100644 index 000000000..e40a2b81d --- /dev/null +++ b/test/ci/test_preview_sweep.py @@ -0,0 +1,152 @@ +"""Offline tests for preview discovery and guarded Space deletion.""" +from contextlib import redirect_stdout +import io +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +from types import SimpleNamespace +import unittest +from unittest.mock import Mock, call, patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / 'tool/ci')) +import preview_sweep as sweep + + +class PreviewSweepTest(unittest.TestCase): + @staticmethod + def response(status, *, number=7, state='closed', merged=False): + body = json.dumps({'number': number, 'state': state, 'merged': merged}).encode() + return subprocess.CompletedProcess( + args=['gh'], returncode=0 if status == 200 else 1, + stdout=f'HTTP/2.0 {status} Reason\r\nHeader: value\r\n\r\n'.encode() + body, + stderr=b'private token and signed URL') + + @staticmethod + def http_error(status): + error = RuntimeError('private token and signed URL') + error.response = SimpleNamespace(status_code=status) + return error + + def test_only_exact_ids_for_closed_prs_are_listed(self): + api = Mock() + api.list_spaces.return_value = iter(SimpleNamespace(id=space) for space in [ + 'leehack/llamadart', 'leehack/llamadart-chat-pr-0', + 'leehack/llamadart-chat-pr-01', 'leehack/llamadart-chat-pr-7-extra', + 'leehack/llamadart-chat-pr-7\n', 'other/llamadart-chat-pr-7', + 'leehack/llamadart-chat-pr-7', 'leehack/llamadart-chat-pr-8', + 'leehack/llamadart-chat-pr-9', 'leehack/llamadart-chat-pr-10', + 'leehack/llamadart-chat-pr-7', + ]) + responses = [ + self.response(200), self.response(200, number=8, state='open'), + self.response(404, number=9), self.response(200, number=10, merged=True), + ] + with patch.object(sweep.subprocess, 'run', side_effect=responses) as run: + self.assertEqual(sweep.list_closed_previews(api), ['7', '10']) + api.list_spaces.assert_called_once_with(author='leehack') + self.assertEqual(run.call_args_list, [ + call(['gh', 'api', '--include', f'repos/leehack/llamadart/pulls/{pr}'], + capture_output=True, timeout=30) + for pr in (7, 8, 9, 10) + ]) + api.delete_repo.assert_not_called() + + def test_empty_matrix_is_written_to_workflow_output(self): + api = Mock() + api.list_spaces.return_value = [] + with tempfile.TemporaryDirectory() as temp: + output = Path(temp) / 'output' + with patch.dict(os.environ, { + 'GITHUB_REPOSITORY': 'leehack/llamadart', + 'GITHUB_REF': 'refs/heads/main', 'GITHUB_EVENT_NAME': 'schedule', + 'GITHUB_OUTPUT': str(output), 'HF_TOKEN': 'secret-token'}), patch.dict( + sys.modules, huggingface_hub=SimpleNamespace(HfApi=Mock(return_value=api))): + sweep.main(['list']) + self.assertEqual(output.read_text(), 'prs=[]\n') + + def test_only_trusted_main_dispatch_or_schedule_can_run(self): + env = {'GITHUB_REPOSITORY': 'leehack/llamadart', 'GITHUB_REF': 'refs/heads/main', + 'GITHUB_EVENT_NAME': 'workflow_dispatch', 'HF_TOKEN': 'secret-token'} + client = Mock() + for key, value in [('GITHUB_REPOSITORY', 'other/llamadart'), + ('GITHUB_REF', 'refs/heads/topic'), + ('GITHUB_EVENT_NAME', 'pull_request')]: + for action in ('list', 'delete'): + with self.subTest(key=key, action=action), patch.dict( + os.environ, {**env, key: value}), patch.dict( + sys.modules, huggingface_hub=SimpleNamespace(HfApi=client)): + with self.assertRaises(SystemExit): + sweep.main([action]) + client.assert_not_called() + + def test_delete_validates_the_pr_number_before_any_api_call(self): + api = Mock() + with patch.object(sweep.subprocess, 'run') as read: + for number in ('0', '01', '7-extra', '7\n', 'leehack/llamadart', ''): + with self.subTest(number=number), self.assertRaises(ValueError): + sweep.delete_closed_preview(api, number) + read.assert_not_called() + api.delete_repo.assert_not_called() + + def test_reopen_after_listing_skips_the_delete(self): + api = Mock() + api.list_spaces.return_value = [SimpleNamespace(id='leehack/llamadart-chat-pr-7')] + responses = [self.response(200), self.response(200, state='open')] + with patch.object(sweep.subprocess, 'run', side_effect=responses) as read: + [number] = sweep.list_closed_previews(api) + sweep.delete_closed_preview(api, number) + api.delete_repo.assert_not_called() + self.assertEqual(read.call_count, 2) + + def test_missing_pr_at_delete_time_skips_the_delete(self): + api = Mock() + with patch.object(sweep.subprocess, 'run', return_value=self.response(404)): + sweep.delete_closed_preview(api, '7') + api.delete_repo.assert_not_called() + + def test_delete_uses_exact_id_and_missing_space_is_success(self): + for error in (None, self.http_error(404)): + with self.subTest(error=type(error).__name__): + api = Mock() + api.delete_repo.side_effect = error + with patch.object(sweep.subprocess, 'run', return_value=self.response(200)): + sweep.delete_closed_preview(api, '7') + api.delete_repo.assert_called_once_with( + repo_id='leehack/llamadart-chat-pr-7', repo_type='space') + + def test_failures_exit_with_only_safe_diagnostics(self): + env = {'GITHUB_REPOSITORY': 'leehack/llamadart', 'GITHUB_REF': 'refs/heads/main', + 'GITHUB_EVENT_NAME': 'workflow_dispatch', 'HF_TOKEN': 'secret-token', + 'PREVIEW_PR_NUMBER': '7'} + + def broken_listing(): + yield SimpleNamespace(id='leehack/llamadart-chat-pr-7') + raise self.http_error(429) + + for action, response, expected in [ + ('list', self.response(200), 'list_spaces leehack HTTP 429 RuntimeError'), + ('delete', self.response(403), + 'read_pr leehack/llamadart-chat-pr-7 HTTP 403 CalledProcessError'), + ('delete', self.response(200), + 'delete_repo leehack/llamadart-chat-pr-7 HTTP 500 RuntimeError'), + ]: + api = Mock() + api.list_spaces.return_value = broken_listing() + api.delete_repo.side_effect = self.http_error(500) + stdout = io.StringIO() + with ( + self.subTest(expected=expected), + patch.dict(os.environ, env), + patch.dict(sys.modules, huggingface_hub=SimpleNamespace(HfApi=Mock(return_value=api))), + patch.object(sweep.subprocess, 'run', return_value=response), + redirect_stdout(stdout), + self.assertRaises(SystemExit) as caught, + ): + sweep.main([action]) + self.assertEqual(str(caught.exception), expected) + self.assertEqual(stdout.getvalue(), '') + if response.returncode: + api.delete_repo.assert_not_called() diff --git a/test/unit/tooling/ci_workflow_selection_test.dart b/test/unit/tooling/ci_workflow_selection_test.dart index 7a8bc86ed..69518150e 100644 --- a/test/unit/tooling/ci_workflow_selection_test.dart +++ b/test/unit/tooling/ci_workflow_selection_test.dart @@ -644,6 +644,58 @@ for event,mode,oldflag,owner,attempt,cancel,good,main in itertools.product(('pus }, ); + test('preview sweep uses the same queued write group on trusted main', () { + final workflow = readWorkflow('chat_app_hf_pr_preview_sweep'); + final triggers = workflow['on'] as Map; + expect(triggers.keys, unorderedEquals(['schedule', 'workflow_dispatch'])); + expect(triggers['schedule'], [ + {'cron': '23 6 * * *'}, + ]); + final jobs = workflow['jobs'] as Map; + final list = jobs['list'] as Map; + final delete = jobs['delete'] as Map; + expect(list['if'], contains("github.ref == 'refs/heads/main'")); + expect(list['if'], contains("github.repository == 'leehack/llamadart'")); + expect(list['outputs'], {'prs': r'${{ steps.list.outputs.prs }}'}); + expect(delete['needs'], 'list'); + expect( + delete['if'], + "needs.list.outputs.prs != '' && needs.list.outputs.prs != '[]'", + ); + expect(delete['strategy'], { + 'fail-fast': false, + 'max-parallel': 2, + 'matrix': {'pr': r'${{ fromJSON(needs.list.outputs.prs) }}'}, + }); + final preview = readWorkflow('chat_app_hf_pr_preview')['jobs']['preview']; + final previewGroup = preview['concurrency']['group'] as String; + expect(delete['concurrency'], { + 'group': previewGroup.replaceFirst( + 'github.event.pull_request.number', + 'matrix.pr', + ), + 'cancel-in-progress': preview['concurrency']['cancel-in-progress'], + 'queue': preview['concurrency']['queue'], + }); + final previewOperation = (preview['steps'] as List).last; + for (final (job, operation) in [(list, 'list'), (delete, 'delete')]) { + expect(job['permissions'], {'contents': 'read', 'pull-requests': 'read'}); + final steps = job['steps'] as List; + expect(steps.first['with'], { + 'ref': r'${{ github.sha }}', + 'persist-credentials': false, + }); + final step = steps.last as Map; + expect(step['run'], 'python3 tool/ci/preview_sweep.py $operation'); + expect(step['env']['HF_TOKEN'], previewOperation['env']['HF_TOKEN']); + expect(step['env']['GH_TOKEN'], previewOperation['env']['GH_TOKEN']); + } + expect( + (delete['steps'] as List).last['env']['PREVIEW_PR_NUMBER'], + r'${{ matrix.pr }}', + ); + }); + test('model-store lane checks the package on its own selection', () async { final plan = await selected([ 'packages/llamadart_model_store/lib/src/model_store_io.dart', diff --git a/test/unit/tooling/preview_guard_test.dart b/test/unit/tooling/preview_guard_test.dart index 2561eb710..4faee511c 100644 --- a/test/unit/tooling/preview_guard_test.dart +++ b/test/unit/tooling/preview_guard_test.dart @@ -45,4 +45,20 @@ void main() { }, timeout: const Timeout(Duration(minutes: 2)), ); + + test('the preview sweep deletes only closed PR Spaces', () async { + final result = + await Process.run(Platform.isWindows ? 'python' : 'python3', [ + '-B', + '-m', + 'unittest', + 'discover', + '-s', + 'test/ci', + '-p', + 'test_preview_sweep.py', + ]); + expect(result.exitCode, 0, reason: '${result.stdout}\n${result.stderr}'); + expect(result.stderr, contains('OK')); + }, timeout: const Timeout(Duration(minutes: 2))); } diff --git a/tool/ci/preview_guard.py b/tool/ci/preview_guard.py index d539bd4ea..e8fd62e46 100644 --- a/tool/ci/preview_guard.py +++ b/tool/ci/preview_guard.py @@ -90,6 +90,15 @@ def attempt(): raise OperationFailed(operation, status if isinstance(status, int) else None) from None +def delete_preview(api, space, *, before): + before() + try: + api.delete_repo(repo_id=space, repo_type='space') + except Exception as error: + if status_of(error) != 404: + raise + + class Preview: def __init__(self, event, read=gh_json): self.event, self.read = event, read @@ -164,12 +173,7 @@ def mutate(self, action, api, space, folder): delete_patterns=['*', '**/*'], commit_message=f'deploy PR #{self.number} {self.sha[:7]}'), budget, before=recheck) else: - self.guard(action) - try: - api.delete_repo(repo_id=space, repo_type='space') - except Exception as error: - if status_of(error) != 404: - raise + delete_preview(api, space, before=lambda: self.guard(action)) def comment(self, action, body): marker = '' diff --git a/tool/ci/preview_sweep.py b/tool/ci/preview_sweep.py new file mode 100644 index 000000000..7dcb1e0f7 --- /dev/null +++ b/tool/ci/preview_sweep.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python3 +"""Find orphaned chat previews and safely remove them on main.""" +import json +import logging +import os +from pathlib import Path +import re +import subprocess +import sys + +from hf_space_deploy import status_of +from preview_guard import Superseded, delete_preview + + +REPOSITORY = 'leehack/llamadart' +NAMESPACE = 'leehack' +SPACE_PREFIX = f'{NAMESPACE}/llamadart-chat-pr-' +PR_NUMBER = r'[1-9][0-9]*' +SPACE_ID = re.compile(rf'{SPACE_PREFIX}({PR_NUMBER})') + + +class SweepFailed(Exception): + def __init__(self, operation, target, error, status=None): + if status is None: + status = status_of(error) + status_text = f'HTTP {status}' if type(status) is int else 'no HTTP status' + super().__init__(f'{operation} {target} {status_text} {type(error).__name__}') + + +def pr_is_closed(number, space): + status = None + try: + result = subprocess.run( + ['gh', 'api', '--include', f'repos/{REPOSITORY}/pulls/{number}'], + capture_output=True, timeout=30) + headers, _, body = result.stdout.replace(b'\r\n', b'\n').partition(b'\n\n') + match = re.match(rb'HTTP/[0-9.]+ ([0-9]{3})(?: |\n|$)', headers) + status = int(match[1]) if match else None + if status == 404: + return False + result.check_returncode() + pr = json.loads(body) + if status != 200 or str(pr['number']) != number or pr['state'] not in ('closed', 'open'): + raise ValueError('Invalid live PR response') + return pr['state'] == 'closed' + except Exception as error: + raise SweepFailed('read_pr', space, error, status) from None + + +def list_closed_previews(api): + try: + candidates = {} + for space in api.list_spaces(author=NAMESPACE): + match = SPACE_ID.fullmatch(space.id) + if match: + candidates[match[1]] = space.id + except Exception as error: + raise SweepFailed('list_spaces', NAMESPACE, error) from None + return [number for number, space in candidates.items() if pr_is_closed(number, space)] + + +def delete_closed_preview(api, number): + if not re.fullmatch(PR_NUMBER, number): + raise ValueError('Invalid preview PR number') + space = f'{SPACE_PREFIX}{number}' + + def recheck(): + if not pr_is_closed(number, space): + raise Superseded() + + try: + delete_preview(api, space, before=recheck) + except Superseded: + return + except SweepFailed: + raise + except Exception as error: + raise SweepFailed('delete_repo', space, error) from None + + +def main(args): + operation = 'preview_sweep' + try: + if (os.environ.get('GITHUB_REPOSITORY') != REPOSITORY + or os.environ.get('GITHUB_REF') != 'refs/heads/main' + or os.environ.get('GITHUB_EVENT_NAME') not in ('schedule', 'workflow_dispatch') + or args not in (['list'], ['delete'])): + raise ValueError('Invalid sweep invocation') + operation = args[0] + from huggingface_hub import HfApi + api = HfApi(token=os.environ['HF_TOKEN']) + if operation == 'list': + numbers = list_closed_previews(api) + with Path(os.environ['GITHUB_OUTPUT']).open('a', encoding='utf-8') as output: + output.write(f'prs={json.dumps(numbers)}\n') + else: + delete_closed_preview(api, os.environ['PREVIEW_PR_NUMBER']) + except SweepFailed as error: + raise SystemExit(str(error)) from None + except Exception as error: + raise SystemExit(str(SweepFailed(operation, NAMESPACE, error))) from None + + +if __name__ == '__main__': + # The CLI reports only sanitized provider failures. + logging.disable(logging.CRITICAL) + main(sys.argv[1:]) From eb328e0c133bb643e34208b3167502534e9fa685 Mon Sep 17 00:00:00 2001 From: leehack Date: Sun, 22 Nov 2026 12:31:58 -0500 Subject: [PATCH 2/2] test: record preview sweep workflow reader reach --- test/unit/tooling/support/markdown_reader_exemptions.dart | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/test/unit/tooling/support/markdown_reader_exemptions.dart b/test/unit/tooling/support/markdown_reader_exemptions.dart index fe4c6b37e..79a976dec 100644 --- a/test/unit/tooling/support/markdown_reader_exemptions.dart +++ b/test/unit/tooling/support/markdown_reader_exemptions.dart @@ -389,7 +389,8 @@ const Map suiteExemptions = { gate: null, ), 'test/unit/tooling/ci_workflow_selection_test.dart': ( - reason: 'Only passes Markdown paths to the selector.', + reason: + 'Passes Markdown paths to the selector and inspects YAML without running preview helpers.', evidence: { ..._studioSourceFiles, ..._validationFiles, @@ -397,8 +398,10 @@ const Map suiteExemptions = { 'test/unit/tooling/ci_workflow_selection_test.dart': '.md | AGENTS | CONTRIBUTING | README | doc/ | git checkout | git clone | listSync | website/', 'tool/ci/deploy_guard.py': '.md | git diff', + 'tool/ci/preview_guard.py': '.md | README | git diff | git show', 'tool/ci/select_jobs.py': '.md | AGENTS | CHANGELOG | CONTRIBUTING | README | doc/ | git diff | website/', + 'tool/ci/web_deployment.py': 'git diff', 'tool/testing/validation/coverage_catalog.dart': '.md', 'tool/testing/validation/remote.dart': 'listSync', 'website/lib/src/site/sidebar.dart': 'doc/',