Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/CODEOWNERS
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
66 changes: 66 additions & 0 deletions .github/workflows/chat_app_hf_pr_preview_sweep.yml
Original file line number Diff line number Diff line change
@@ -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
7 changes: 4 additions & 3 deletions doc/ci_selection.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
11 changes: 8 additions & 3 deletions example/chat_app/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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-<number>` 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-<number>` 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.
Expand Down
152 changes: 152 additions & 0 deletions test/ci/test_preview_sweep.py
Original file line number Diff line number Diff line change
@@ -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()
52 changes: 52 additions & 0 deletions test/unit/tooling/ci_workflow_selection_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
16 changes: 16 additions & 0 deletions test/unit/tooling/preview_guard_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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)));
}
5 changes: 4 additions & 1 deletion test/unit/tooling/support/markdown_reader_exemptions.dart
Original file line number Diff line number Diff line change
Expand Up @@ -389,16 +389,19 @@ const Map<String, Exemption> 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,
..._pinTableFiles,
'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/',
Expand Down
16 changes: 10 additions & 6 deletions tool/ci/preview_guard.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 = '<!-- llamadart-chat-app-hf-pr-preview -->'
Expand Down
Loading
Loading