diff --git a/.github/workflows/merge-gate.yml b/.github/workflows/merge-gate.yml index 99421728..a7f131bb 100644 --- a/.github/workflows/merge-gate.yml +++ b/.github/workflows/merge-gate.yml @@ -23,6 +23,7 @@ jobs: python-version: '3.12' - run: python scripts/test-merge-gate.py - run: python scripts/test-changelog.py + - run: python scripts/test-ci-feedback.py advisory: if: github.event_name == 'merge_group' uses: ./.github/workflows/advisory.yml diff --git a/docs/ci-feedback.md b/docs/ci-feedback.md new file mode 100644 index 00000000..db7376b8 --- /dev/null +++ b/docs/ci-feedback.md @@ -0,0 +1,17 @@ +# Measuring CI feedback + +Use `python3 scripts/report-ci-feedback.py --pr 286 --pr 287 --queue-run 44659384965 --save-snapshot /tmp/ci-input.json > /tmp/ci-report.json` with authenticated `gh`. Calls are read-only. Select a consecutive creation-ordered window with `--recent-prs 20` (all states, maximum 1000). Repeat `--pr` or `--queue-run` for an explicitly selected cohort. Replay without GitHub access using `--snapshot /tmp/ci-input.json`; retain snapshots alongside reports to make observations reproducible. + +The JSON separates docs, code and merge-queue batches. PR scope uses the conservative prose classifier, including the previous filename of renamed files. It retrieves current/final PR-head runs and checks that the head did not change while fetching files. Workflow creations within 60 seconds form one observed batch. Later Changelog-only events are excluded because label/body edits do not constitute new technical feedback. Multiple technical batches remain visible; older batches are excluded. Rerun, cancelled, incomplete, unverified PR identity, mixed-head and duplicate-workflow batches carry explicit exclusions. Original-attempt jobs are fetched even when retries exist. + +`eligible` means the observed batch passed these accounting filters, **not** that all expected workflows ran or branch protection passed. API results cannot establish workflows that should have triggered but never did. Inspect workflow revisions and selection before treating a batch as complete. Selected PRs are not a representative random population; nearest-rank p50 is suppressed below five eligible samples and p95 below twenty. Summaries separately count completed first attempts (including real failures), success-only attempts and exclusions. These are descriptive sample statistics, not population estimates. + +Feedback time runs from first workflow creation to last observed job completion. Waiting time runs from each job's creation to start; it includes scheduling delay but does not identify the responsible capacity limit. Summed execution seconds are neither billed minutes nor elapsed feedback time. Skipped jobs do not count as allocations; unfinished jobs with no valid execution interval are reported as exclusions. The last-finishing job is evidence of the tail, not a reconstructed dependency critical path. GitHub timestamps have second resolution. + +Do not pool docs and code, PRs and queues, historical and current workflow revisions, or cancelled pushes with successful first attempts. For capacity decisions, collect a stable period and report cohort sizes, exclusions, runner labels and actual billing separately. A current-head snapshot cannot reconstruct historical PR files or identify every push from timestamps alone. + +Run regression fixtures with `python3 scripts/test-ci-feedback.py`. + +Fixed `Full technical suite` and `Changelog policy` context observations are listed separately, including their conclusions and attempts, for runs created within the technical batch window. This is not a dynamic branch-rules evaluation or proof of required-check satisfaction. Missing contexts remain visible as absent observations; later label/body policy reruns do not extend technical feedback. + +Queue selections fetch only the explicitly named run and its original-attempt jobs. A separate sibling Changelog workflow is not fetched by queue-head SHA; absent Changelog observations must not be interpreted as passing or missing required checks. Batches with no completed allocated jobs are excluded from latency summaries. diff --git a/scripts/report-ci-feedback.py b/scripts/report-ci-feedback.py new file mode 100644 index 00000000..98e1db5a --- /dev/null +++ b/scripts/report-ci-feedback.py @@ -0,0 +1,224 @@ +"""Read-only CI feedback accounting. See docs/ci-feedback.md for scope and limits.""" +import argparse +from datetime import datetime, timezone +import importlib.util +import json +import math +from pathlib import Path +import subprocess +from urllib.parse import quote + +SPEC = importlib.util.spec_from_file_location("scope", Path(__file__).with_name("ci-change-scope.py")) +SCOPE = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(SCOPE) + + +def timestamp(value): + if not isinstance(value, str): + raise ValueError("missing timestamp") + return datetime.fromisoformat(value.replace("Z", "+00:00")) + + +def seconds(start, end): + value = (timestamp(end) - timestamp(start)).total_seconds() + if value < 0: + raise ValueError("negative interval") + return value + + +def api(path): + return json.loads(subprocess.check_output(["gh", "api", path], text=True)) + + +def pages(path, field=None): + values = [] + for page in range(1, 101): + payload = api(f"{path}{'&' if '?' in path else '?'}per_page=100&page={page}") + batch = payload[field] if field else payload + values.extend(batch) + if len(batch) < 100: + if field and payload.get("total_count") != len(values): + raise ValueError("API pagination incomplete or changed during collection") + return values + raise ValueError("API pagination limit exceeded") + + +def collect(repository, prs, queue_runs, recent_prs=0): + prs = list(dict.fromkeys(prs)) + queue_runs = list(dict.fromkeys(queue_runs)) + root = f"repos/{repository}" + snapshot = {"repository": repository, "collected_at": datetime.now(timezone.utc).isoformat(), "subjects": []} + if recent_prs: + recent = [] + for page in range(1, (recent_prs + 99) // 100 + 1): + recent.extend(api(f"{root}/pulls?state=all&sort=created&direction=desc&per_page=100&page={page}")) + prs = list(dict.fromkeys(prs + [p['number'] for p in recent[:recent_prs]])) + snapshot['selection'] = {"recent_prs": recent_prs, "pr_numbers": prs, "queue_run_ids": queue_runs} + for number in prs: + pr = api(f"{root}/pulls/{number}") + files = pages(f"{root}/pulls/{number}/files") + if len(files) != pr['changed_files']: + raise ValueError('PR file listing incomplete or changed during collection') + runs = pages(f"{root}/actions/runs?event=pull_request&head_sha={pr['head']['sha']}", "workflow_runs") + # A head SHA may occur on multiple PRs. Do not silently attribute such + # a run to this PR when GitHub supplies a different association. + associations = pages(f"{root}/pulls?state=all&head={quote(pr['head']['label'], safe='')}") + matching = [p['number'] for p in associations if p['head']['sha'] == pr['head']['sha'] + and p['head']['ref'] == pr['head']['ref'] and p['head']['repo'] and pr['head']['repo'] + and p['head']['repo']['full_name'] == pr['head']['repo']['full_name']] + for run in runs: + run['pr_identity_verified'] = any(p['number'] == number for p in run.get('pull_requests', [])) or ( + not run.get('pull_requests') and matching == [number] + and run['head_branch'] == pr['head']['ref'] + and (run.get('head_repository') or {}).get('full_name') == pr['head']['repo']['full_name']) + current = api(f"{root}/pulls/{number}") + snapshot["subjects"].append({"pr": number, "head_sha": pr['head']['sha'], + "current_head_sha": current['head']['sha'], "files": files, "runs": runs}) + for run_id in queue_runs: + run = api(f"{root}/actions/runs/{run_id}") + if run['event'] != 'merge_group': + raise ValueError(f"{run_id} is not a merge queue run") + snapshot['subjects'].append({"head_sha": run['head_sha'], "runs": [run]}) + for subject in snapshot['subjects']: + for run in subject['runs']: + # Fetch the original attempt even when a later retry now exists. + run['jobs'] = pages(f"{root}/actions/runs/{run['id']}/attempts/1/jobs", "jobs") + if subject.get('pr'): + subject['current_head_sha'] = api(f"{root}/pulls/{subject['pr']}")['head']['sha'] + return snapshot + + +def report(snapshot): + rows = [] + for subject in snapshot['subjects']: + runs = sorted(subject['runs'], key=lambda run: run['created_at']) + # Changelog can rerun on label/body changes without a push; it is policy, + # not technical feedback, and has a separate required context. + policy = [r['id'] for r in runs if r['name'] == 'Changelog'] + runs = [r for r in runs if r['name'] != 'Changelog'] + batches = [] + for run in runs: + if not batches or seconds(batches[-1][0]['created_at'], run['created_at']) > 60: + batches.append([]) + batches[-1].append(run) + if not batches: + rows.append({"pr": subject.get('pr'), "head_sha": subject['head_sha'], "cohort": 'unknown', + "eligible": False, "exclusions": ['no_technical_runs'], "jobs": [], + "observed_feedback_seconds": None, "outcome": 'unobserved'}) + for batch in batches: + reasons = [] + if subject.get('pr') and subject['head_sha'] != subject['current_head_sha']: + reasons.append('stale_head') + if batch is not batches[-1]: + reasons.append('superseded_batch') + if len({r['name'] for r in batch}) != len(batch): + reasons.append('duplicate_workflow') + if any(r['head_sha'] != subject['head_sha'] for r in batch): + reasons.append('mixed_heads') + if any(r['run_attempt'] != 1 for r in batch): + reasons.append('retried_run') + if any(r['status'] != 'completed' for r in batch): + reasons.append('incomplete_run') + if any(r['conclusion'] not in {'success', 'failure'} for r in batch): + reasons.append('cancelled_or_other_run') + if subject.get('pr') and any(not r.get('pr_identity_verified', False) for r in batch): + reasons.append('unverified_pr_identity') + jobs = [] + for run in batch: + if not run['jobs']: + reasons.append('missing_jobs') + for job in run['jobs']: + if job['conclusion'] == 'skipped': + continue + if job['conclusion'] not in {'success', 'failure'}: + reasons.append('cancelled_or_other_job') + if job.get('run_attempt') != 1 or job.get('head_sha') != subject['head_sha']: + reasons.append('mixed_job_identity') + try: + wait = seconds(job['created_at'], job['started_at']) + active = seconds(job['started_at'], job['completed_at']) + if job['status'] != 'completed': + raise ValueError('incomplete job') + except (TypeError, ValueError, KeyError): + reasons.append('incomplete_job_timing') + continue + jobs.append({"id": job['id'], "name": job['name'], "url": job['html_url'], + "wait_seconds": wait, "execution_seconds": active, + "completed_at": job['completed_at'], "conclusion": job['conclusion'], + "runner_labels": job.get('labels', [])}) + if not jobs: + reasons.append('no_completed_allocated_jobs') + cohort = 'queue' + if subject.get('pr'): + files = subject['files'] + cohort = 'docs' if files and all(SCOPE.prose(f['filename'].encode()) and + ('previous_filename' not in f or SCOPE.prose(f['previous_filename'].encode())) for f in files) else 'code' + last = max(jobs, key=lambda j: j['completed_at']) if jobs else None + contexts = [] + for run in subject['runs']: + if abs((timestamp(run['created_at']) - timestamp(batch[0]['created_at'])).total_seconds()) > 60: + continue + if run['head_sha'] != subject['head_sha'] or (subject.get('pr') and not run.get('pr_identity_verified', False)): + continue + for job in run['jobs']: + if job.get('head_sha') != subject['head_sha'] or job.get('run_attempt') != 1: + continue + if job.get('name') in {'Changelog policy', 'Full technical suite'}: + try: + context_seconds = seconds(batch[0]['created_at'], job.get('completed_at')) + except (ValueError, TypeError): + context_seconds = None + contexts.append({"feedback_seconds": context_seconds, "name": job['name'], "conclusion": job['conclusion'], + "completed_at": job.get('completed_at'), "url": job['html_url'], + "run_attempt": job['run_attempt']}) + rows.append({"pr": subject.get('pr'), "head_sha": subject['head_sha'], "cohort": cohort, + "outcome": ('other' if any(r['conclusion'] not in {'success', 'failure'} for r in batch) else + 'failure' if any(r['conclusion'] == 'failure' for r in batch) else 'success'), + "observed_required_contexts": contexts, + "eligible": not reasons, "exclusions": sorted(set(reasons)), + "run_ids": [r['id'] for r in batch], "policy_run_ids_excluded": policy, + "observed_feedback_seconds": seconds(batch[0]['created_at'], last['completed_at']) if last else None, + "allocations_observed": len(jobs), "execution_seconds_sum": sum(j['execution_seconds'] for j in jobs), + "last_finishing_job": last, "jobs": jobs}) + summaries = {} + for cohort in ('docs', 'code', 'queue'): + selected = [r for r in rows if r['cohort'] == cohort] + valid = [r for r in selected if r['eligible']] + def distribution(values): + ordered = sorted(values) + return {"n": len(ordered), "p50_seconds": ordered[math.ceil(len(ordered) * .5) - 1] if len(ordered) >= 5 else None, + "p95_seconds": ordered[math.ceil(len(ordered) * .95) - 1] if len(ordered) >= 20 else None} + summaries[cohort] = {"observed_batches": len(selected), "excluded_batches": len(selected)-len(valid), + "completed_first_attempts": distribution([r['observed_feedback_seconds'] for r in valid]), + "success_only": distribution([r['observed_feedback_seconds'] for r in valid if r['outcome'] == 'success']), + "failed_first_attempts": sum(r['outcome'] == 'failure' for r in valid)} + return {"cohort_summaries": summaries, "selection": snapshot.get('selection'), "repository": snapshot['repository'], "collected_at": snapshot['collected_at'], "batches": rows, + "limitations": ["Observed technical workflows only; does not prove expected workflow completeness or required-check satisfaction.", + "PR batches use a 60-second creation window; inspect multiple batches rather than treating them as independent pushes.", + "Current/final PR heads only; PR files classify scope at collection time, not historical workflow selection.", + "Waiting is job creation to start; runner availability and account concurrency cannot be distinguished.", + "Summed execution is neither billed usage nor wall time; last-finishing job is not a dependency critical-path reconstruction.", + "Percentiles use nearest rank: p50 suppressed below n=5, p95 below n=20. Descriptive selected-cohort statistics, not population estimates; workflow revisions may differ."]} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--repo', default='DataFog/datafog-core') + parser.add_argument('--recent-prs', type=int, default=0, help='Newest N PRs by creation, all states (maximum 1000)') + parser.add_argument('--pr', type=int, action='append', default=[]) + parser.add_argument('--queue-run', type=int, action='append', default=[]) + parser.add_argument('--snapshot', type=Path, help='Replay saved API data without network access') + parser.add_argument('--save-snapshot', type=Path) + args = parser.parse_args() + if not 0 <= args.recent_prs <= 1000: + parser.error("--recent-prs must be between 0 and 1000") + if not (args.snapshot or args.pr or args.queue_run or args.recent_prs): + parser.error('select --pr, --queue-run, or --snapshot') + snapshot = json.loads(args.snapshot.read_text()) if args.snapshot else collect(args.repo, args.pr, args.queue_run, args.recent_prs) + if args.save_snapshot: + args.save_snapshot.write_text(json.dumps(snapshot, indent=2) + '\n') + print(json.dumps(report(snapshot), indent=2)) + + +if __name__ == '__main__': + main() diff --git a/scripts/test-ci-feedback.py b/scripts/test-ci-feedback.py new file mode 100644 index 00000000..d0e65290 --- /dev/null +++ b/scripts/test-ci-feedback.py @@ -0,0 +1,150 @@ +"""Synthetic API fixtures for feedback accounting, including invalid cohorts.""" +import copy +import importlib.util +from pathlib import Path +import unittest +from unittest.mock import patch + +spec = importlib.util.spec_from_file_location('feedback', Path(__file__).with_name('report-ci-feedback.py')) +feedback = importlib.util.module_from_spec(spec) +spec.loader.exec_module(feedback) + + +def fixture(): + return {'repository': 'example/repo', 'collected_at': '2026-11-20T00:00:00Z', 'subjects': [{ + 'pr': 12, 'head_sha': 'current', 'current_head_sha': 'current', 'files': [{'filename': 'README.md'}], + 'runs': [{'id': 1, 'pr_identity_verified': True, 'name': 'Python binding', 'head_sha': 'current', 'run_attempt': 1, + 'status': 'completed', 'conclusion': 'success', 'created_at': '2026-11-20T00:00:00Z', + 'jobs': [{'id': 9, 'name': 'Python', 'html_url': 'https://example/job/9', + 'head_sha': 'current', 'run_attempt': 1, 'status': 'completed', 'conclusion': 'success', + 'created_at': '2026-11-20T00:00:02Z', 'started_at': '2026-11-20T00:02:02Z', + 'completed_at': '2026-11-20T00:02:07Z'}]}]}]} + + +class FeedbackTests(unittest.TestCase): + def row(self, data): + return feedback.report(data)['batches'][0] + + def test_current_docs_wait_and_execution_are_distinct(self): + row = self.row(fixture()) + self.assertTrue(row['eligible']) + self.assertEqual(row['cohort'], 'docs') + self.assertEqual(row['observed_feedback_seconds'], 127) + self.assertEqual(row['execution_seconds_sum'], 5) + self.assertEqual(row['jobs'][0]['wait_seconds'], 120) + + def test_failures_are_included_separately(self): + data = fixture() + data['subjects'][0]['runs'][0]['conclusion'] = 'failure' + result = feedback.report(data) + self.assertTrue(result['batches'][0]['eligible']) + self.assertEqual(result['cohort_summaries']['docs']['failed_first_attempts'], 1) + self.assertEqual(result['cohort_summaries']['docs']['success_only']['n'], 0) + + def test_empty_inventory_and_missing_timestamps(self): + data = fixture() + data['subjects'][0]['runs'][0]['jobs'][0]['started_at'] = None + self.assertIn('incomplete_job_timing', self.row(data)['exclusions']) + data['subjects'][0]['runs'] = [] + self.assertIn('no_technical_runs', self.row(data)['exclusions']) + + def test_ambiguous_pr_identity_excluded(self): + data = fixture() + data['subjects'][0]['runs'][0]['pr_identity_verified'] = False + self.assertIn('unverified_pr_identity', self.row(data)['exclusions']) + + def test_percentiles_have_small_sample_guards(self): + data = fixture() + data['subjects'] = [copy.deepcopy(data['subjects'][0]) for _ in range(20)] + result = feedback.report(data)['cohort_summaries']['docs']['completed_first_attempts'] + self.assertEqual(result, {'n': 20, 'p50_seconds': 127, 'p95_seconds': 127}) + data['subjects'] = data['subjects'][:4] + self.assertIsNone(feedback.report(data)['cohort_summaries']['docs']['completed_first_attempts']['p50_seconds']) + + def test_truncated_file_inventory_fails_collection(self): + pr = {'head': {'sha': 'abc'}, 'changed_files': 3001} + with patch.object(feedback, 'api', return_value=pr), patch.object(feedback, 'pages', return_value=[{}] * 3000): + with self.assertRaisesRegex(ValueError, 'file listing incomplete'): + feedback.collect('example/repo', [1], []) + + def test_pagination_detects_missing_jobs(self): + with patch.object(feedback, 'api', return_value={'total_count': 2, 'jobs': [{'id': 1}]}): + with self.assertRaisesRegex(ValueError, 'pagination incomplete'): + feedback.pages('example/jobs', 'jobs') + + def test_all_skipped_has_no_percentile_sample(self): + data = fixture() + data['subjects'][0]['runs'][0]['jobs'] = [{'conclusion': 'skipped'}] + result = feedback.report(data) + self.assertIn('no_completed_allocated_jobs', result['batches'][0]['exclusions']) + self.assertEqual(result['cohort_summaries']['docs']['completed_first_attempts']['n'], 0) + + def test_context_uses_original_job_identity_and_attempt(self): + data = fixture() + run = data['subjects'][0]['runs'][0] + run['run_attempt'] = 2 + run['jobs'][0]['name'] = 'Full technical suite' + self.assertEqual(self.row(data)['observed_required_contexts'][0]['run_attempt'], 1) + run['jobs'][0]['head_sha'] = 'other' + self.assertEqual(self.row(data)['observed_required_contexts'], []) + + def test_stale_head_excluded(self): + data = fixture() + data['subjects'][0]['current_head_sha'] = 'new' + self.assertIn('stale_head', self.row(data)['exclusions']) + + def test_code_and_renamed_code_are_not_prose(self): + for file in [{'filename': 'docs/contracts/example.md'}, + {'filename': 'README.md', 'previous_filename': 'crates/core/src/lib.rs'}]: + data = fixture() + data['subjects'][0]['files'] = [file] + self.assertEqual(self.row(data)['cohort'], 'code') + + def test_queue_cohort(self): + data = fixture() + del data['subjects'][0]['pr'] + self.assertEqual(self.row(data)['cohort'], 'queue') + + def test_reruns_cancellations_and_incomplete_runs_excluded(self): + for field, value, reason in [('run_attempt', 2, 'retried_run'), + ('conclusion', 'cancelled', 'cancelled_or_other_run'), + ('status', 'in_progress', 'incomplete_run')]: + data = fixture() + data['subjects'][0]['runs'][0][field] = value + self.assertIn(reason, self.row(data)['exclusions']) + + def test_policy_metadata_does_not_extend_batch(self): + data = fixture() + policy = copy.deepcopy(data['subjects'][0]['runs'][0]) + policy.update(id=2, name='Changelog', created_at='2026-11-20T02:00:00Z') + data['subjects'][0]['runs'].append(policy) + self.assertEqual(self.row(data)['observed_feedback_seconds'], 127) + + def test_batches_and_duplicate_workflows_are_not_extra_samples(self): + data = fixture() + run = copy.deepcopy(data['subjects'][0]['runs'][0]) + run['id'] = 2 + data['subjects'][0]['runs'].append(run) + self.assertIn('duplicate_workflow', self.row(data)['exclusions']) + run['created_at'] = '2026-11-20T00:02:00Z' + rows = feedback.report(data)['batches'] + self.assertIn('superseded_batch', rows[0]['exclusions']) + self.assertEqual(len(rows), 2) + + def test_skipped_jobs_do_not_allocate_or_parse_invalid_timestamps(self): + data = fixture() + data['subjects'][0]['runs'][0]['jobs'].append({'conclusion': 'skipped'}) + self.assertEqual(self.row(data)['allocations_observed'], 1) + + def test_invalid_job_identity_or_time_excluded(self): + data = fixture() + job = data['subjects'][0]['runs'][0]['jobs'][0] + job['head_sha'] = 'stale' + job['started_at'] = '2026-11-20T00:03:00Z' + row = self.row(data) + self.assertIn('mixed_job_identity', row['exclusions']) + self.assertIn('incomplete_job_timing', row['exclusions']) + + +if __name__ == '__main__': + unittest.main()