From 5fbb24dda6bbd5203c9aba8ca6a14210160537f9 Mon Sep 17 00:00:00 2001 From: scuttletoby <123843277+scuttletoby@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:09:38 +0000 Subject: [PATCH 1/4] gardener: review-tiers check, judgment as a model draft (#1064) - New general check review-tiers: merged pull requests that had less review than their tier asks for. Tiers and waiver words come from options (or the merge gate's own review block); lens comments are read by the gate's own code (fork-ci/actions/pr-queue, installed as gate/). One rate_limit read and one paged GraphQL search per run, cached in the check's cacheDir, so the next run searches only pull requests updated since the day before. - Contract v1 gains cacheDir and dryRun (additive; read with .get()). - Report: a "#N" where is shown (OWNER/REPO#N when the report goes to another repository); well-known token shapes are masked. - Judgment: shown as "Judgment (model draft)", timeoutSeconds bounds the whole answer (a trickling server is cut off), no paid fallback (documented). - Tests: verdicts, override/waiver/exempt, gate review block, budget and partial searches, the cache (runs again, stops half-way, old/empty/newer state, dry run), slow and silent model endpoints; RedCheck mutations. Co-Authored-By: Claude Opus 5.5 --- fork-kit/common/machine.example.json | 1 + fork-kit/gardener/README.md | 65 ++- fork-kit/gardener/checks/review-tiers | 557 ++++++++++++++++++++ fork-kit/gardener/lib/gardener/cli.py | 8 +- fork-kit/gardener/lib/gardener/config.py | 2 +- fork-kit/gardener/lib/gardener/contract.py | 7 +- fork-kit/gardener/lib/gardener/judge.py | 40 +- fork-kit/gardener/lib/gardener/report.py | 34 +- fork-kit/gardener/lib/gardener/runner.py | 11 +- fork-kit/gardener/sbin/gardener-install | 23 +- fork-kit/gardener/tests/checks.test.py | 381 ++++++++++++- fork-kit/gardener/tests/gardener_fixture.py | 7 + fork-kit/gardener/tests/install.test.py | 14 +- fork-kit/gardener/tests/report.test.py | 95 +++- fork-kit/gardener/tests/run.test.py | 10 +- 15 files changed, 1195 insertions(+), 60 deletions(-) create mode 100755 fork-kit/gardener/checks/review-tiers diff --git a/fork-kit/common/machine.example.json b/fork-kit/common/machine.example.json index 067fa9a0b437d..81add56b91fcb 100644 --- a/fork-kit/common/machine.example.json +++ b/fork-kit/common/machine.example.json @@ -47,6 +47,7 @@ { "name": "worktrees", "options": { "staleDays": 14 } }, { "name": "workflows-off", "options": { "ignore": ["old-deploy.yml"] } }, { "name": "install-drift" }, + { "name": "review-tiers", "options": { "days": 7, "waivers": ["no review needed:"] } }, { "path": "/srv/example/bin/doc-check", "id": "docs", "timeoutSeconds": 120 } ] } diff --git a/fork-kit/gardener/README.md b/fork-kit/gardener/README.md index e6c4300843ce4..4f7d63c002af1 100644 --- a/fork-kit/gardener/README.md +++ b/fork-kit/gardener/README.md @@ -19,8 +19,8 @@ For each project in the config (or the one `--project` names): 2. **Window** (only with `--timer`, which the timer passes): see [Window](#window). 3. **Checks**, one after another, each with its own timeout. A check that fails in any way becomes exactly one finding and the next check still runs (see [Checks](#checks)). -4. **Judgment** (optional): with a `model` configured, the findings go to a local model; see - [Judgment](#judgment). +4. **Judgment** (optional): with a `model` configured, the findings go to a model (a local one, by design) for a + draft opinion; see [Judgment](#judgment). 5. **Report**: the full report is saved as `report.md` and the issue's part as `issue.md` in the state folder. Then the done marker. Then the report issue is written (see [Report issue](#report-issue)); if that fails, only the issue is tried again on later ticks, at most 3 times a day; the checks and the model do not run again. @@ -102,10 +102,16 @@ A check is any executable. It gets one JSON object on stdin: "options": {}, "fix": false, "today": "2026-11-23", - "gh": "gh" + "gh": "gh", + "cacheDir": "/srv/example/state/example/cache/docs", + "dryRun": false } ``` +`cacheDir` is this check's own folder in the project's private state folder, kept between runs (the check makes it +when it needs it); in a dry run (`dryRun` true) a check writes nothing there. Both came later in version 1: read +them with `.get()`. + It runs in the project root, in a process group of its own. It prints one finding per line on stdout and nothing else (notes go to stderr), and exits 0: @@ -114,7 +120,7 @@ else (notes go to stderr), and exits 0: ``` `id`, `severity` (`error`, `warn` or `info`) and `text` are required; `where` (a path relative to the root, or -`OWNER/REPO: path`, ...) and `fix` (what a person does about it) are optional. Nothing else. An `id` is a letter or +`OWNER/REPO: path`, `#N` for a pull request or issue of the project's repository, ...) and `fix` (what a person does about it) are optional. Nothing else. An `id` is a letter or digit, then up to 99 letters, digits, `.`, `_` or `-`. Python checks can use `gardener.contract.read_context()` and `emit()`. @@ -151,6 +157,23 @@ All report only, and none needs root. Options as in each script's header. - **install-drift**: each fork kit's install record (`/etc//installed.tsv`) against the files and links on the machine, as the user that runs it (paths it cannot read are one note, not drift). With `release` (a commit), kits on another release. +- **review-tiers**: merged pull requests (last `days`, 7) that had less review than their tier asks for. Without + options it judges by the merge gate's own `review` block in the queue config (`queueConfig`, default + `.github/pr-queue.json`, read from git at `base`); with `tiers` by the project's tiers: `rules` (globs to a + tier), a `registry` file in the repository (rows of paths with a tier, for example a list of modules), + `unmatched`, and per tier `requires` {`minLenses`, `lenses`: [{`name`, `match` (a regex on lens names), `count`}]}. + Lens comments are read by the gate's own code (`fork-ci/actions/pr-queue`, copied into the install as `gate/`), + so a comment counts exactly when the gate would take it as a lens, and only those posted before the merge by + the queue config's lens authors; a valid override comment before the merge settles a pull request, and so does a + comment of a counted author whose first line starts with one of `waivers` (a person decided, at any time). + `exemptLabels`, `exemptAuthors`. Inline review comments are not read; a pull request with more than 100 files is + judged at the top tier. GitHub: `gh api rate_limit` (free) and one paged GraphQL search per run; below + `minRemaining` (1000) points left this hour it does not search and judges from its cache. The cache (in + `cacheDir`) keeps per pull request only what the verdict needs (paths, lens names, no comment text), so the next + run searches only pull requests updated since the day before: a page or two. A search stopped half-way (a GitHub + error, `maxPages`, the budget) keeps the old search day, so the next run searches those days again; an old, broken + or other-repository cache is read as empty and a newer one is never overwritten. Its findings name the pull + request (`#N`). Never fixes: a review is done by people. ## Report issue @@ -159,9 +182,11 @@ issue is built from an allow-list and the full report stays on the machine (`rep issue says so): - Per finding: its severity, check, id, and its `where` only when that is a path inside the project's repository - (relative) or `OWNER/REPO: path`; its text and fix with what still looks like a local name (a path, also a - Windows drive or `\\server` path, URL, IPv4 or IPv6 address, e-mail or `user@host`, a home folder encoded in a - folder name) masked. The project root and home folder are replaced only as whole folders (`/srv/app` is not + (relative), `OWNER/REPO: path`, or a pull request or issue of the project's repository (`#N`, written + `OWNER/REPO#N` when the report goes to another repository); its text and fix with what still looks like a local + name (a path, also a Windows drive or `\\server` path, URL, IPv4 or IPv6 address, e-mail or `user@host`, a home + folder encoded in a folder name) or a well-known token shape (`ghp_`, `github_pat_`, `sk-`, `xoxb-`, `AKIA`, a + private key block) masked. The project root and home folder are replaced only as whole folders (`/srv/app` is not part of `/srv/app2`). - The text and fix of a project's own check (`path`) are shown only with `"publicText": true`; otherwise the issue shows its id, count and `where`, and the text stays in the local report. General checks are shown. @@ -173,7 +198,7 @@ issue says so): - A failed check shows its id and why in fixed words (`exited with code 1`); what it printed on stderr goes to the local report only. - Notes are the gardener's own words; the model's endpoint is never shown (`model reachable` or `unreachable`). -- The judgment is masked like the rest. +- The judgment (a model draft) is masked like the rest. A check must still not print secrets. Check authors: with `publicText`, everything your check prints in `text` and `fix` (host names, user names, paths not masked above) may be published in the issue. @@ -201,13 +226,19 @@ run. There are no retries inside a run. ## Judgment -Optional, and phase 1 is the interface only. With `model` set, the findings as the issue shows them (nothing from +Optional. With `model` set, the findings as the issue shows them (nothing from outside the repository) and a few of the files they name (`maxFiles`, each cut to `maxFileBytes`, only files git tracks in the root: never an ignored or untracked file such as a local `.env`) go to the endpoint's OpenAI-style -`/chat/completions` in one request. The answer goes into the report under "Judgment", masked like the rest of the -issue. An endpoint that is not reachable, or answers with an error, nonsense or not HTTP at all, is a note -(`model unreachable`) and the run goes on. The endpoint is never shown. There is no fallback to a paid model, and -the model never sees the whole repository. +`/chat/completions` in one request. The answer goes into the report under "Judgment (model draft)" with a line +that nobody checked it; it passes the same filter as check text (masked; left out when the issue shows counts +only). An endpoint that is not reachable, takes longer than `timeoutSeconds` in all (connecting and reading the +whole answer, so a server that trickles bytes is cut off too), or answers with an error, nonsense or not HTTP at +all, is a note (`model unreachable`) and the run goes on. The endpoint is never shown, and the model never sees +the whole repository. + +There is **no fallback to a paid model**, on purpose: the projects this was made for allow only their chosen large +paid models for agent work, and a cheap paid model is the wrong trade, while a local model costs nothing. A project +that does want a paid model can point `endpoint` at an OpenAI-compatible gateway itself. ## State: runs again, stops half-way, old or empty state @@ -267,6 +298,8 @@ copy of the code and shows its test then fails. ## General vs project -General (this kit): the runner, the check contract, the report issue, the state, the general checks and the timer. -Project (the machine file only): which projects, their repositories and folders, their schedule, their budgets and -their own checks, given by path. The kit never names a project or a project's check. +General (this kit): the runner, the check contract, the report issue, the state, the general checks (review-tiers +too: tiers and how a review is shown come from options, the lens rules from the merge gate) and the timer. +Project (the machine file only): which projects, their repositories and folders, their schedule, their budgets, +their review tiers and waiver words, and their own checks, given by path. The kit never names a project or a +project's check. diff --git a/fork-kit/gardener/checks/review-tiers b/fork-kit/gardener/checks/review-tiers new file mode 100755 index 0000000000000..3b0d24dc929c5 --- /dev/null +++ b/fork-kit/gardener/checks/review-tiers @@ -0,0 +1,557 @@ +#!/usr/bin/python3 -IB +"""review-tiers: merged pull requests that had less review than their tier asks for. Report only, even with "fix": +a review is done by people, never by a tool. + +A pull request's tier comes from the paths it changed, and the review it had from its lens comments, read by the +merge gate's own code (fork-ci/actions/pr-queue: lens.py, config.py, review_config.py, review_judge.py), imported, +never copied: a lens comment counts here exactly when the gate would read it as one. The check only adds what the gate +does not judge: it looks back at pull requests that are already merged (merged past the gate, by an admin or before +the rules existed), and at tiers that the project keeps outside the gate config. + +Options: + repo OWNER/REPO (default: the project's repo) + branch the base branch of the merged pull requests (default: the root's origin/HEAD branch, else main) + days how far back, in days (default 7, at most 90) + base the git ref the project files below are read from (default origin/HEAD, else origin/main, else main) + queueConfig the gate's queue config, a path in the repository (default .github/pr-queue.json): its bot_logins, + lens_author_associations and override decide whose comments count; without the file: OWNER, MEMBER and + COLLABORATOR, no bots, no override + tiers the project's tiers (below); without it, the queue config's "review" block (the gate's own rules) + exemptLabels [label]: pull requests with one of these labels are not judged + exemptAuthors [login]: pull requests of these authors are not judged + waivers [text]: a comment whose first line starts with one of these (any case), by an author the queue config + counts for lenses and posted at any time, even after the merge, settles the pull request: a person + decided it needed no (more) review + maxPages search pages of 20 pull requests (default 8, at most 25) + minRemaining the GraphQL budget left this hour below which the check does not search (default 1000) + + "tiers": { + "rules": [{"paths": ["**/*.md"], "tier": 0}], first rule whose glob (the gate's dialect) matches a path + "registry": {"file": "path/rows.json", "rows": "items", "paths": "paths", "tier": "tier", "default": 2}, + else every row whose "paths" equal or are a folder of the path + (the highest tier of them; a row without a tier: default) + "unmatched": 0, else this tier + "approvalsCount": false, an approving review counts as one more lens + "requires": {"2": {"minLenses": 1}, + "3": {"minLenses": 3, "lenses": [{"name": "data integrity", "match": "data.?integrity", "count": 2}]}} + } + +A pull request's tier is the highest tier of its changed paths. It passes when it has at least minLenses different lens +names (the gate's lens_key) and, per "lenses" entry, at least "count" names that match "match" (a regex, any case), +or when a valid override comment of the queue config (its prefix, by its author association, unedited) was posted +before it merged. With the review block instead: the gate's review_judge gives its weight and the lens names its +rules require, and min_lenses its count. Only comments and reviews posted before the merge count; a lens report +that the gate would not take as a read (edited, hidden, a short sha) still counts here, since it shows the review +was done. Inline review comments are not read. A tier no "requires" entry names asks for nothing. + +GitHub: one `gh api rate_limit` (free) and one GraphQL search per run (paged), cached in the check's cache folder +(the context's "cacheDir"): a run searches only pull requests updated since the day before the last search, so the +next day's run costs a page or two. The facts of each merged pull request are cached, and the verdicts are worked out +again each run with the current tiers. A run that stops half-way (a GitHub error, a page past minRemaining) writes +no new search day, so the next run searches the same days again. Old, broken or other-version cache files are read +as empty; a newer one is never overwritten. A dry run reads the cache but writes nothing. +""" +import datetime, hashlib, json, os, re, subprocess, sys + +KIT = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) +sys.path.insert(0, os.path.join(KIT, 'lib')) +from gardener.contract import emit, read_context # noqa: E402 + +_GATE = os.path.join(KIT, 'gate') # the installed copy; in a fork checkout, the gate itself +GATE = _GATE if os.path.isdir(_GATE) else os.path.join(os.path.dirname(os.path.dirname(KIT)), 'fork-ci', 'actions', + 'pr-queue') +sys.path.insert(0, GATE) +import config as gate_config # noqa: E402 +import lens # noqa: E402 +import review_config # noqa: E402 +import review_glob # noqa: E402 +import review_judge # noqa: E402 + +CACHE_VERSION = 1 +PAGE = 20 +MAX_FILES = 100 +MAX_COMMENTS = 100 +MAX_REVIEWS = 50 +DEFAULT_ASSOCIATIONS = ('OWNER', 'MEMBER', 'COLLABORATOR') +NEVER = '\x00' # an override prefix no comment can start with: the project has no override +SHOW = 5 # lens names shown in a finding + +QUERY = '''query($q: String!, $first: Int!, $after: String) { + rateLimit { cost remaining } + search(query: $q, type: ISSUE, first: $first, after: $after) { + pageInfo { hasNextPage endCursor } + nodes { ... on PullRequest { + number mergedAt + author { login __typename } + labels(first: 50) { nodes { name } } + files(first: %d) { totalCount nodes { path } } + comments(last: %d) { totalCount nodes { body createdAt authorAssociation includesCreatedEdit isMinimized url + author { login __typename } } } + reviews(last: %d) { totalCount nodes { id body submittedAt state authorAssociation includesCreatedEdit + isMinimized url author { login __typename } } } + } } + } +}''' % (MAX_FILES, MAX_COMMENTS, MAX_REVIEWS) + + +def fail(msg): + sys.exit(f'review-tiers: {msg}') + + +def note(msg): + print(f'review-tiers: {msg}', file=sys.stderr, flush=True) + + +def git(root, *args): + try: + p = subprocess.run(['git', '-C', root, *args], capture_output=True, timeout=60, stdin=subprocess.DEVNULL, + env=dict(os.environ, GIT_TERMINAL_PROMPT='0')) + except (OSError, subprocess.TimeoutExpired): + return None + return p.stdout if p.returncode == 0 else None + + +def base_ref(root, wanted): + if not root: + return None + for ref in ([wanted] if wanted else ['origin/HEAD', 'origin/main', 'main']): + if git(root, 'rev-parse', '--verify', '-q', f'{ref}^{{commit}}') is not None: + return ref + if wanted: + fail(f'"base" {wanted!r} is not a commit in the project root') + return None + + +def default_branch(root): + out = git(root, 'symbolic-ref', '-q', '--short', 'refs/remotes/origin/HEAD') if root else None + name = out.decode('utf-8', 'replace').strip() if out else '' + return name.split('/', 1)[1] if name.startswith('origin/') else 'main' + + +def read_file(root, ref, rel): + """The bytes of rel at ref, or None when it is not there.""" + if not ref: + return None + return git(root, 'show', f'{ref}:{rel}') + + +# --- options ------------------------------------------------------------------------------------------------------- + +def _int(v, lo, hi, what): + if not isinstance(v, int) or isinstance(v, bool) or not lo <= v <= hi: + fail(f'{what} must be a whole number {lo}-{hi}') + return v + + +def _strings(v, what): + if not isinstance(v, list) or not all(isinstance(s, str) and s for s in v): + fail(f'{what} must be a list of non-empty strings') + return v + + +def _known(obj, keys, what): + if not isinstance(obj, dict): + fail(f'{what} must be an object') + unknown = sorted(set(obj) - set(keys)) + if unknown: + fail(f'{what}: unknown key {unknown[0]!r} (known: {", ".join(keys)})') + + +def parse_tiers(t): + _known(t, ('rules', 'registry', 'unmatched', 'approvalsCount', 'requires'), 'tiers') + rules = [] + for i, r in enumerate(t.get('rules') or []): + _known(r, ('paths', 'tier'), f'tiers.rules[{i}]') + globs = _strings(r.get('paths'), f'tiers.rules[{i}].paths') + for g in globs: + why = review_config.glob_problem(g) + if why: + fail(f'tiers.rules[{i}].paths: {g!r}: {why}') + rules.append((tuple(globs), _int(r.get('tier'), 0, 9, f'tiers.rules[{i}].tier'))) + reg = t.get('registry') + if reg is not None: + _known(reg, ('file', 'rows', 'paths', 'tier', 'default'), 'tiers.registry') + if not isinstance(reg.get('file'), str) or not reg['file']: + fail('tiers.registry.file must be a path in the repository') + for k in ('rows', 'paths', 'tier'): + if not isinstance(reg.get(k, ''), str): + fail(f'tiers.registry.{k} must be a key name') + reg = {'file': reg['file'], 'rows': reg.get('rows', ''), 'paths': reg.get('paths') or 'paths', + 'tier': reg.get('tier') or 'tier', 'default': _int(reg.get('default', 0), 0, 9, + 'tiers.registry.default')} + requires = {} + raw = t.get('requires') + if not isinstance(raw, dict) or not raw: + fail('tiers.requires must name at least one tier: {"2": {"minLenses": 1}}') + for key, req in raw.items(): + if not re.fullmatch(r'[0-9]', key): + fail(f'tiers.requires: {key!r} is not a tier 0-9') + where = f'tiers.requires.{key}' + _known(req, ('minLenses', 'lenses'), where) + named = [] + for i, n in enumerate(req.get('lenses') or []): + _known(n, ('name', 'match', 'count'), f'{where}.lenses[{i}]') + if not isinstance(n.get('match'), str) or not n['match']: + fail(f'{where}.lenses[{i}].match must be a regex') + try: + rx = re.compile(n['match'], re.I) + except re.error as e: + fail(f'{where}.lenses[{i}].match: {e}') + name = n.get('name') or n['match'] + if not isinstance(name, str): + fail(f'{where}.lenses[{i}].name must be text') + named.append((name, rx, _int(n.get('count', 1), 1, 9, f'{where}.lenses[{i}].count'))) + requires[int(key)] = (_int(req.get('minLenses', 0), 0, 20, f'{where}.minLenses'), tuple(named)) + if not isinstance(t.get('approvalsCount', False), bool): + fail('tiers.approvalsCount must be true or false') + return {'rules': tuple(rules), 'registry': reg, 'unmatched': _int(t.get('unmatched', 0), 0, 9, 'tiers.unmatched'), + 'approvals': t.get('approvalsCount', False), 'requires': requires, 'top': max(requires)} + + +def load_registry(root, ref, reg): + data = read_file(root, ref, reg['file']) + if data is None: + fail(f'tiers.registry.file {reg["file"]!r} is not in the project root at {ref or "(no git ref)"}') + try: + obj = json.loads(data) + rows = obj[reg['rows']] if reg['rows'] else obj + if not isinstance(rows, list): + raise ValueError('not a list') + except (ValueError, KeyError, TypeError) as e: + fail(f'tiers.registry.file {reg["file"]!r}: no list of rows ({type(e).__name__})') + out = [] + for row in rows: + if not isinstance(row, dict): + continue + paths = row.get(reg['paths']) + paths = [paths] if isinstance(paths, str) else paths if isinstance(paths, list) else [] + tier = row.get(reg['tier'], reg['default']) + tier = tier if isinstance(tier, int) and not isinstance(tier, bool) and 0 <= tier <= 9 else reg['default'] + out.append(([p.strip('/') for p in paths if isinstance(p, str) and p.strip('/')], tier)) + return out + + +def path_tier(tiers, registry, path): + for globs, tier in tiers['rules']: + if review_glob.matches_any(globs, path): + return tier + hits = [tier for paths, tier in registry if any(path == p or path.startswith(p + '/') for p in paths)] + return max(hits) if hits else tiers['unmatched'] + + +# --- cache --------------------------------------------------------------------------------------------------------- + +def read_cache(path, key): + """(cache dict or None, newer). Missing, broken, of another key or an older version: None.""" + if not path: + return None, False + try: + with open(path, encoding='utf-8') as f: + data = json.load(f) + except FileNotFoundError: + return None, False + except (OSError, ValueError) as e: + note(f'the cache could not be read ({type(e).__name__}): searching the whole window') + return None, False + v = data.get('version') if isinstance(data, dict) else None + if isinstance(v, int) and not isinstance(v, bool) and v > CACHE_VERSION: + note(f'the cache is of a newer gardener (version {v}): not used, and not overwritten') + return None, True + if v != CACHE_VERSION or data.get('key') != key or not isinstance(data.get('prs'), dict) \ + or not all(re.fullmatch(r'[1-9][0-9]{0,8}', k) and good_fact(f) for k, f in data['prs'].items()): + note('the cache is of an older version or another repository or queue config: searching the whole window') + return None, False + return data, False + + +FACT_KEYS = {'mergedAt': str, 'author': str, 'bot': bool, 'labels': list, 'paths': list, 'pathsComplete': bool, + 'commentsComplete': bool} +READ_KEYS = {'lenses': list, 'lensesAfter': list, 'override': bool, 'waived': bool, 'approvals': int} + + +def good_fact(f): + """A cached pull request entry this version wrote: every key, of its type.""" + if not isinstance(f, dict) or not all(isinstance(f.get(k), t) for k, t in FACT_KEYS.items()): + return False + if 'unread' in f: + return isinstance(f['unread'], str) + return all(isinstance(f.get(k), t) for k, t in READ_KEYS.items()) and \ + all(isinstance(x, str) for k in ('labels', 'paths', 'lenses', 'lensesAfter') for x in f[k]) + + +def good_day(day, upto): + """day is a date (YYYY-MM-DD) no later than upto.""" + try: + return isinstance(day, str) and datetime.date.fromisoformat(day).isoformat() == day and day <= upto + except ValueError: + return False + + +def write_cache(path, data): + os.makedirs(os.path.dirname(path), mode=0o700, exist_ok=True) + tmp = f'{path}.tmp-{os.getpid()}' + try: + with open(tmp, 'w', encoding='utf-8') as f: + json.dump(data, f, sort_keys=True) + f.flush() + os.fsync(f.fileno()) + os.replace(tmp, path) + except BaseException: + try: + os.unlink(tmp) + except OSError: + pass + raise + + +# --- GitHub -------------------------------------------------------------------------------------------------------- + +def gh_json(gh, args): + try: + p = subprocess.run([gh, 'api', *args], capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL) + except (OSError, subprocess.TimeoutExpired) as e: + fail(f'gh api {args[0]}: {type(e).__name__}') + if p.returncode != 0: + fail(f'gh api {args[0]}: {(p.stderr or p.stdout).strip()[-200:]}') + try: + return json.loads(p.stdout) + except ValueError: + fail(f'gh api {args[0]}: the answer is not JSON') + + +def graphql_left(gh): + got = gh_json(gh, ['rate_limit']) + try: + n = got['resources']['graphql']['remaining'] + except (KeyError, TypeError): + fail('gh api rate_limit: no GraphQL budget in the answer') + if not isinstance(n, int): + fail('gh api rate_limit: no GraphQL budget in the answer') + return n + + +def waived(post, review, waivers): + first = ((post.get('body') or '').lstrip().splitlines() or [''])[0].strip().lower() + return review.counts(post) and not review.is_bot(post) and not review.hidden(post) \ + and any(first.startswith(w) for w in waivers) + + +def facts(pr, review, override, waivers): + """What the cache keeps of one merged pull request: no comment text, only what the verdict needs.""" + merged = pr.get('mergedAt') or '' + author = pr.get('author') or {} + comments = [c for c in (pr.get('comments') or {}).get('nodes') or [] if c] + reviews = [r for r in (pr.get('reviews') or {}).get('nodes') or [] if r] + + def view(before): + keep = [c for c in comments if ((c.get('createdAt') or '') <= merged) == before] + rs = [r for r in reviews if ((r.get('submittedAt') or '') <= merged) == before] + flags = {r['id']: {'includesCreatedEdit': r.get('includesCreatedEdit'), 'isMinimized': r.get('isMinimized'), + 'url': r.get('url'), 'author': {'__typename': (r.get('author') or {}).get('__typename')}} + for r in rs if isinstance(r.get('id'), str)} + return {'comments': keep, 'reviews': rs, lens.REVIEW_FLAGS: flags} + + out = {'mergedAt': merged, 'author': author.get('login') or '', + 'bot': author.get('__typename') == 'Bot', + 'labels': sorted({(n or {}).get('name') or '' for n in (pr.get('labels') or {}).get('nodes') or []} - {''}), + 'paths': [n['path'] for n in (pr.get('files') or {}).get('nodes') or [] if (n or {}).get('path')], + 'pathsComplete': ((pr.get('files') or {}).get('totalCount') or 0) + <= len((pr.get('files') or {}).get('nodes') or []), + 'commentsComplete': ((pr.get('comments') or {}).get('totalCount') or 0) <= len(comments) + and ((pr.get('reviews') or {}).get('totalCount') or 0) <= len(reviews)} + try: + before, after = view(True), view(False) + out['lenses'] = sorted(k for k in review.lens_scan(before)[0] if not k.startswith(lens.NO_HEADER)) + out['lensesAfter'] = sorted(k for k in review.lens_scan(after)[0] if not k.startswith(lens.NO_HEADER)) + posts = [p for _, _, p in review.lens_posts(before)] + out['override'] = override and any(review.override_sha(p) for p in posts) + out['waived'] = any(waived(p, review, waivers) for p in comments + reviews) + out['approvals'] = sum(1 for r in before['reviews'] if r.get('state') == 'APPROVED' and review.counts(r) + and not review.is_bot(r)) + except Exception as e: # a comment this Python reads otherwise (lens.UnicodeDrift) or any other surprise + out['unread'] = type(e).__name__ + return out + + +def search(gh, query, max_pages, min_left): + """([pull request nodes], complete, why not complete). complete is False when the pages ran out or the budget fell + too low.""" + nodes, after = [], None + for _ in range(max_pages): + args = ['graphql', '-f', f'query={QUERY}', '-f', f'q={query}', '-F', f'first={PAGE}'] + if after: + args += ['-f', f'after={after}'] + got = gh_json(gh, args) + if not isinstance(got, dict) or got.get('errors') or not isinstance(got.get('data'), dict): + msgs = [e.get('message', '') for e in got.get('errors') or [] if isinstance(e, dict)] \ + if isinstance(got, dict) else [] + fail(f'gh api graphql: {"; ".join(msgs)[:200] or "no data in the answer"}') + s = got['data'].get('search') or {} + nodes += [n for n in s.get('nodes') or [] if isinstance(n, dict) and isinstance(n.get('number'), int)] + page = s.get('pageInfo') or {} + if not page.get('hasNextPage'): + return nodes, True, None + after = page.get('endCursor') + left = (got['data'].get('rateLimit') or {}).get('remaining') + if isinstance(left, int) and left < min_left: + return nodes, False, f'the GraphQL budget fell to {left} (under minRemaining {min_left}) while searching' + return nodes, False, f'more than {max_pages} pages of pull requests (maxPages)' + + +# --- verdicts ------------------------------------------------------------------------------------------------------ + +def some(names): + names = list(names) + return ', '.join(names[:SHOW]) + (f' and {len(names) - SHOW} more' if len(names) > SHOW else '') if names \ + else 'none' + + +def verdict_tiers(f, tiers, registry): + """None when it had enough review, else (what it needed, what was missing).""" + paths = f['paths'] + tier = max([path_tier(tiers, registry, p) for p in paths] or [tiers['unmatched']]) + if not f['pathsComplete']: + tier = max(tier, tiers['top']) + need = tiers['requires'].get(tier) + if not need: + return None + min_lenses, named = need + have = len(f['lenses']) + (f['approvals'] if tiers['approvals'] else 0) + missing = [] + if have < min_lenses: + missing.append(f'{min_lenses} lens(es), found {have}') + for name, rx, count in named: + n = sum(1 for k in f['lenses'] if rx.search(k)) + if n < count: + missing.append(f'{count} {name} lens(es), found {n}') + return (f'tier {tier}', missing) if missing else None + + +def verdict_rules(f, rules, config_path): + try: + j = review_judge.judge(rules, [('M', (p,)) for p in f['paths']], config_path) + except review_judge.JudgeError as e: + return 'the review rules', [f'its paths cannot be judged ({e})'[:300]] + have = set(f['lenses']) + missing = [name for name in j.lenses if lens.lens_key(name) not in have] + need = getattr(rules.min_lenses, j.weight) + out = [f'lens {some(missing)}'] if missing else [] + if len(have) < need: + out.append(f'{need} lens(es), found {len(have)}') + return (j.weight, out) if out else None + + +def main(): + ctx = read_context() + opt = ctx['options'] + _known(opt, ('repo', 'branch', 'days', 'base', 'queueConfig', 'tiers', 'exemptLabels', 'exemptAuthors', + 'waivers', 'maxPages', 'minRemaining'), 'options') + repo = opt.get('repo') or ctx['project']['repo'] + if not repo: + emit('review-tiers.no-repo', 'info', 'no repository to read: the project has no "repo" and the check no ' + '"repo"') + return + if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9-]*/[A-Za-z0-9._-]+', repo): + fail('repo must be OWNER/REPO') + root = ctx['project']['root'] + days = _int(opt.get('days', 7), 1, 90, 'days') + max_pages = _int(opt.get('maxPages', 8), 1, 25, 'maxPages') + min_left = _int(opt.get('minRemaining', 1000), 0, 5000, 'minRemaining') + exempt_labels = set(_strings(opt.get('exemptLabels', []), 'exemptLabels')) + exempt_authors = {a.lower() for a in _strings(opt.get('exemptAuthors', []), 'exemptAuthors')} + waivers = tuple(w.strip().lower() for w in _strings(opt.get('waivers', []), 'waivers')) + if not all(waivers): + fail('waivers must not be blank') + ref = base_ref(root, opt.get('base')) + branch = opt.get('branch') or default_branch(root) + if not re.fullmatch(r'[A-Za-z0-9._/-]+', branch): + fail('branch must be a branch name') + qpath = opt.get('queueConfig') or '.github/pr-queue.json' + qtext = read_file(root, ref, qpath) + if qtext is None and opt.get('queueConfig'): + fail(f'queueConfig {qpath!r} is not in the project root at {ref or "(no git ref)"}') + cfg = None + if qtext is not None: + try: + cfg = gate_config.parse(qtext, qpath) + except gate_config.ConfigError as e: + fail(f'the gate refuses the queue config: {e}'[:500]) + tiers = parse_tiers(opt['tiers']) if 'tiers' in opt else None + if tiers is None and (cfg is None or cfg.review is None): + emit('review-tiers.no-rules', 'info', 'no review tiers to judge by: give the check a "tiers" option, or the ' + 'queue config a "review" block', '', 'see the review-tiers check in the gardener README') + return + registry = load_registry(root, ref, tiers['registry']) if tiers and tiers['registry'] else [] + review = lens.Review(cfg.bot_logins if cfg else (), (cfg.override_prefix if cfg else '') or NEVER, + cfg.override_association if cfg else '', + cfg.lens_author_associations if cfg else DEFAULT_ASSOCIATIONS, log=note) + has_override = bool(cfg and cfg.override_prefix) + + today = datetime.date.fromisoformat(ctx['today']) + start = (today - datetime.timedelta(days=days - 1)).isoformat() + # what decides the cached facts: whose comments count, the waivers (the verdicts are worked out again each run) + key = hashlib.sha256(json.dumps([repo.lower(), branch, list(review.bots), list(review.lens_associations), + review.override_re.pattern, review.override_association, list(waivers)]) + .encode()).hexdigest() + cache_dir = ctx.get('cacheDir') or '' + dry = ctx.get('dryRun') is True + path = os.path.join(cache_dir, 'cache.json') if cache_dir else '' + cache, newer = read_cache(path, key) + usable = bool(cache) and good_day(cache.get('searchedDay'), ctx['today']) \ + and good_day(cache.get('from'), start) # a wider window than the cache's: search all of it + prs = dict(cache['prs']) if usable else {} + since, searched = start, None + if usable: + last = (datetime.date.fromisoformat(cache['searchedDay']) - datetime.timedelta(days=1)).isoformat() + since, searched = max(start, last), cache['searchedDay'] + + left = graphql_left(ctx['gh']) + if left < min_left: + emit('review-tiers.budget', 'info', f'not searched today: the GraphQL budget left this hour is {left}, under ' + f'minRemaining {min_left}; judged from the cache only', '', 'nothing to do: the next run searches') + else: + q = f'repo:{repo} is:pr is:merged base:{branch} merged:>={start} sort:updated-desc' + if since > start: + q += f' updated:>={since}' + nodes, complete, why = search(ctx['gh'], q, max_pages, min_left) + for n in nodes: + prs[str(n['number'])] = facts(n, review, has_override, waivers) + if complete: + searched = ctx['today'] + else: + emit('review-tiers.partial', 'info', f'the search stopped early: {why}; the next run searches the same ' + 'days again', '', 'raise maxPages or lower days if this repeats') + prs = {k: v for k, v in prs.items() if isinstance(v, dict) and (v.get('mergedAt') or '')[:10] >= start} + if path and not dry and not newer: + write_cache(path, {'version': CACHE_VERSION, 'key': key, 'prs': prs, 'from': start, + 'searchedDay': searched or '1970-01-01'}) + + for number in sorted(prs, key=int): + f = prs[number] + if exempt_labels & set(f.get('labels') or []) or (f.get('author') or '').lower() in exempt_authors: + continue + if f.get('unread'): + emit('review-tiers.unread', 'warn', f'its comments could not be read by the lens rules ({f["unread"]})', + f'#{number}', 'look at its review by hand') + continue + if f.get('override') or f.get('waived'): + continue + got = verdict_tiers(f, tiers, registry) if tiers else verdict_rules(f, cfg.review, qpath) + if not got: + continue + level, missing = got + extra = [] + if not f.get('pathsComplete', True): + extra.append(f'it changed more than {MAX_FILES} files') + if not f.get('commentsComplete', True): + extra.append(f'only its last {MAX_COMMENTS} comments and {MAX_REVIEWS} reviews were read') + if f.get('lensesAfter'): + extra.append(f'lens after the merge: {some(f["lensesAfter"])}') + emit('review-tiers.skipped', 'warn', + f'merged with less review than {level} asks: needs {"; ".join(missing)} (lenses before the merge: ' + f'{some(f.get("lenses") or [])})' + (f'; {"; ".join(extra)}' if extra else ''), + f'#{number}', 'review it now (a lens comment on the pull request), or note on it why it needed none') + + +if __name__ == '__main__': + main() diff --git a/fork-kit/gardener/lib/gardener/cli.py b/fork-kit/gardener/lib/gardener/cli.py index 45692c58a3685..0c591f49055d7 100644 --- a/fork-kit/gardener/lib/gardener/cli.py +++ b/fork-kit/gardener/lib/gardener/cli.py @@ -185,7 +185,8 @@ def run_project(cfg, project, args, t, gh_factory): for check in project['checks']: c = dict(check, fix=check['fix'] and not args.dry_run) try: - got, ok = runner.run(project, c, today, cfg['gh']) + got, ok = runner.run(project, c, today, cfg['gh'], os.path.join(folder, 'cache', check['id']), + args.dry_run) except Exception as e: # a MemoryError too: one check never stops the run got, ok = [runner.failed(check, 'the gardener could not run it', type(e).__name__)], False findings += got @@ -195,12 +196,13 @@ def run_project(cfg, project, args, t, gh_factory): home = report.home_dir() text_checks = {c['id'] for c in project['checks'] if c['name'] or c['publicText']} counts = counts_only(cfg, project, gh_factory) - public = report.public_findings(findings, root, home, project['reportRepo'], text_checks, counts) + public = report.public_findings(findings, root, home, project['reportRepo'], text_checks, counts, + project['repo']) answer, note = judge.judge(project['model'], public, root) if note: notes.append(note) part = report.render_issue(name, today, findings, notes, answer, root, home, project['reportRepo'], - text_checks, counts) + text_checks, counts, project['repo']) full = report.render_local(name, today, findings, notes, answer) if args.dry_run: say(f'{name}: dry run: the report issue would get:') diff --git a/fork-kit/gardener/lib/gardener/config.py b/fork-kit/gardener/lib/gardener/config.py index 1fa71a9e45f45..6713ffd3b6b00 100644 --- a/fork-kit/gardener/lib/gardener/config.py +++ b/fork-kit/gardener/lib/gardener/config.py @@ -31,7 +31,7 @@ MachineFileError = machine_file.MachineFileError CHECKS_DIR = os.path.join(_kit, 'checks') -GENERAL_CHECKS = ('context-budget', 'facts', 'install-drift', 'workflows-off', 'worktrees') +GENERAL_CHECKS = ('context-budget', 'facts', 'install-drift', 'review-tiers', 'workflows-off', 'worktrees') NAME_RE = re.compile(r'^[a-z0-9][a-z0-9._-]{0,63}$') REPO_RE = re.compile(r'^[A-Za-z0-9][A-Za-z0-9-]{0,38}/[A-Za-z0-9._-]{1,100}$') TIME_RE = re.compile(r'^([01][0-9]|2[0-3]):([0-5][0-9])$') diff --git a/fork-kit/gardener/lib/gardener/contract.py b/fork-kit/gardener/lib/gardener/contract.py index ae7d7c866ea88..5cd7eb368f1d8 100644 --- a/fork-kit/gardener/lib/gardener/contract.py +++ b/fork-kit/gardener/lib/gardener/contract.py @@ -4,7 +4,12 @@ process group of its own, and writes one JSON object to its stdin: {"version": 1, "project": {"name": "...", "repo": "OWNER/REPO" or "", "root": "/path" or ""}, - "check": "", "options": {...}, "fix": false, "today": "YYYY-MM-DD", "gh": "gh"} + "check": "", "options": {...}, "fix": false, "today": "YYYY-MM-DD", "gh": "gh", + "cacheDir": "/state//cache/", "dryRun": false} + +cacheDir (added in version 1, so a check reads it with .get()) is a folder only this check of this project uses, +kept between runs, in the private state folder; the check makes it when it needs it. dryRun: the run is a dry run, +and the check writes nothing there. It prints its findings to stdout, one JSON object per line, and exits 0 (with or without findings): diff --git a/fork-kit/gardener/lib/gardener/judge.py b/fork-kit/gardener/lib/gardener/judge.py index 4f37c823ef757..4b5ef9d5792b3 100644 --- a/fork-kit/gardener/lib/gardener/judge.py +++ b/fork-kit/gardener/lib/gardener/judge.py @@ -1,18 +1,40 @@ -"""gardener.judge: the optional judgment step (phase 1: the interface only). +"""gardener.judge: the optional judgment step: a model drafts a short opinion on the findings. When the project's config has "model" {endpoint, model}, the findings as the issue shows them (report. public_findings: nothing from outside the repository) and a few of the files they name (at most maxFiles, each cut to maxFileBytes, only files git tracks in the project root: never an ignored or untracked file such as a local .env) go to that endpoint's OpenAI-style /chat/completions in one request. The answer is added to the report under -"Judgment", masked like the rest of the issue. An endpoint that is not reachable, or answers with an error, -nonsense or not HTTP at all, is a note ("model unreachable") and the run goes on; there is no fallback to a paid -model. The note never names the endpoint. It never sees the whole repository. +"Judgment (model draft)": nobody checked it, and it is masked like the rest of the issue (report.public_text) and +left out when the issue shows counts only. An endpoint that is not reachable, is slower than timeoutSeconds in +all (connecting and reading the whole answer), or answers with an error, nonsense or not HTTP at all, is a note +("model unreachable") and the run goes on. The note never names the endpoint. It never sees the whole repository. + +There is no fallback to a paid model, on purpose: the projects this was made for allow only their chosen (large) +paid models for agent work, and a cheap paid model would be the wrong trade; a local model costs nothing. A +project that wants a paid model can point `endpoint` at any OpenAI-compatible gateway itself. """ -import json, os, subprocess, urllib.request +import json, os, subprocess, time, urllib.request SYSTEM = ('You review a daily maintenance report of a software project. For each finding, say in one short line ' 'whether it looks real and what to do first. Use only the findings and files given. Plain English.') MAX_ANSWER = 8000 +MAX_RESPONSE = 1 << 20 # bytes of the HTTP answer read at most + + +def read_all(resp, deadline): + """The response body (at most MAX_RESPONSE bytes), or TimeoutError once the monotonic deadline passes: the + socket timeout alone bounds each read, not a server that trickles bytes.""" + body = b'' + while len(body) < MAX_RESPONSE: + if time.monotonic() > deadline: + raise TimeoutError('the answer took too long') + chunk = resp.read1(min(65536, MAX_RESPONSE - len(body))) + if not chunk: + break + body += chunk + if time.monotonic() > deadline: + raise TimeoutError('the answer took too long') + return body def tracked(root, rel): @@ -62,6 +84,7 @@ def judge(model, findings, root): return None, None if not findings: return None, 'judgment: nothing to judge (no findings)' + deadline = time.monotonic() + model['timeoutSeconds'] try: files = files_for(findings, root, model['maxFiles'], model['maxFileBytes']) listed = [{k: f[k] for k in ('check', 'id', 'severity', 'where', 'text')} for f in findings] @@ -74,8 +97,11 @@ def judge(model, findings, root): 'messages': [{'role': 'system', 'content': SYSTEM}, {'role': 'user', 'content': user}]}).encode(), headers={'Content-Type': 'application/json'}, method='POST') - with urllib.request.urlopen(req, timeout=model['timeoutSeconds']) as resp: - data = json.loads(resp.read(1 << 20)) + left = deadline - time.monotonic() + if left <= 0: + raise TimeoutError('no time left') + with urllib.request.urlopen(req, timeout=left) as resp: + data = json.loads(read_all(resp, deadline)) answer = data['choices'][0]['message']['content'] if not isinstance(answer, str) or not answer.strip(): raise ValueError('an empty answer') diff --git a/fork-kit/gardener/lib/gardener/report.py b/fork-kit/gardener/lib/gardener/report.py index 143532eca16d1..18bf294546916 100644 --- a/fork-kit/gardener/lib/gardener/report.py +++ b/fork-kit/gardener/lib/gardener/report.py @@ -2,9 +2,10 @@ Two reports are written from the same findings: - The issue part (render_issue) is built from an allow-list, because the report repository may be public: per - finding only its severity, check, id, a `where` that is a path inside the project's repository (relative), and + finding only its severity, check, id, a `where` that is a path inside the project's repository (relative) or a + pull request or issue of it (`#N`, written `OWNER/REPO#N` when the report goes to another repository), and its text and fix with what still looks like a local name (a path, URL, address, user@host, e-mail, a Windows or - share path) masked. Free text only of the general checks (their words are known), the gardener's own findings + share path) or a well-known token shape masked. Free text only of the general checks (their words are known), the gardener's own findings and project checks set to "publicText": true; another project check's findings show id, where and a count. A finding whose `where` is outside the repository, or that has none, is only counted per check, without its id (the gardener's own findings excepted: their words are fixed). With counts_only (a private project repository @@ -32,7 +33,11 @@ _SAFE_REL = re.compile(r'[A-Za-z0-9._+-]+(?:/[A-Za-z0-9._+-]+)*') _REPO_WHERE = re.compile(r'([A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+): (.+)') +_NUMBER = re.compile(r'#[1-9][0-9]{0,8}') _MASKS = ( + (re.compile(r'-----BEGIN [A-Z ]*PRIVATE KEY-----.*?(?:-----END [A-Z ]*PRIVATE KEY-----|\Z)', re.S), ''), + (re.compile(r'\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_\w{20,}|glpat-[\w-]{20,}|xox[abposr]-[\w-]{10,}' + r'|sk-[\w-]{20,}|AKIA[0-9A-Z]{16})\b'), ''), # well-known token shapes (re.compile(r'[A-Za-z][A-Za-z0-9+.-]*://\S+'), ''), (re.compile(r'[\w.+-]+@[\w-]+(?:\.[\w-]+)*'), ''), # e-mail, ssh user@host (re.compile(r'\b\d{1,3}(?:\.\d{1,3}){3}\b'), ''), @@ -78,12 +83,18 @@ def public_text(text, root, home): return text -def public_where(where, root, report_repo=''): +def public_where(where, root, report_repo='', repo=''): """Where to show in the issue: a path inside the repository, relative (":LINE" kept), "OWNER/REPO: path" of the - report repository, or '' for none. None: outside the repository, or not a plain path.""" + report repository, a pull request or issue of the project's repository ("#N"; "OWNER/REPO#N" when the report + repository is another one, so the link is not to its own #N), or '' for none. None: outside the repository, or + not a plain path.""" w = (where or '').strip() if not w: return '' + if _NUMBER.fullmatch(w): + if not repo or (report_repo and repo.lower() != report_repo.lower()): + return f'{repo}{w}' if repo else None + return w m = _REPO_WHERE.fullmatch(w) if m: if report_repo and m.group(1).lower() == report_repo.lower(): @@ -125,7 +136,9 @@ def _document(name, title, today, counts, rows, notes, judgment, cap, more_hint, if notes: tail += ['### Notes', ''] + [f'- {_cell(n)}' for n in notes] if judgment: - tail += ['', '### Judgment (local model)', '', judgment.strip()] + tail += ['', '### Judgment (model draft)', '', + 'A model wrote this; nobody checked it. Use it as a hint, not as a finding.', '', + judgment.strip()] tail += ['', f'Written by the gardener (fork-kit/gardener) on {today}; it rewrites everything below the ' 'marker on each run.'] if rows: @@ -146,15 +159,16 @@ def _document(name, title, today, counts, rows, notes, judgment, cap, more_hint, return '\n'.join(lines + tail) + '\n' -def public_findings(findings, root, home, report_repo='', text_checks=(), counts_only=False): +def public_findings(findings, root, home, report_repo='', text_checks=(), counts_only=False, repo=''): """The allow-listed view of the findings (module doc): [{severity, check, id, text, where, fix}]. text_checks: the ids of the checks whose text may be shown (general checks and "publicText" project checks); the gardener's own findings always. Folded into one counted entry: a finding outside the repository or with no where (per severity, check and where; no id: a project check's id may name a local thing), and one whose text may not be - shown (per severity, check, id and where). counts_only: every finding, per severity and check.""" + shown (per severity, check, id and where). counts_only: every finding, per severity and check. repo: the + project's repository (a "#N" where is one of its pull requests or issues).""" out, hidden = [], {} for f in findings: - w = public_where(f.get('where'), root, report_repo) + w = public_where(f.get('where'), root, report_repo, repo) if counts_only: key = (f['severity'], f['check'], '', '', 'in the local report only') elif w is None or (w == '' and not f.get('own')): @@ -179,10 +193,10 @@ def public_findings(findings, root, home, report_repo='', text_checks=(), counts def render_issue(name, today, findings, notes, judgment=None, root='', home='', report_repo='', text_checks=(), - counts_only=False): + counts_only=False, repo=''): """The issue part, from the marker down (markdown), from the allow-list (module doc).""" rows = [(f['severity'], f['check'], f'{f["id"]}: {f["text"]}' if f['id'] else f['text'], f['where'], f['fix']) - for f in public_findings(findings, root, home, report_repo, text_checks, counts_only)] + for f in public_findings(findings, root, home, report_repo, text_checks, counts_only, repo)] return _document(name, 'Gardener report', today, _counts(findings), rows, [public_text(n, root, home) for n in notes], public_text(judgment, root, home) if judgment and not counts_only else None, MAX_PART, diff --git a/fork-kit/gardener/lib/gardener/runner.py b/fork-kit/gardener/lib/gardener/runner.py index a2981cf036639..9a76c5977dd79 100644 --- a/fork-kit/gardener/lib/gardener/runner.py +++ b/fork-kit/gardener/lib/gardener/runner.py @@ -24,11 +24,14 @@ def command(check): return [config.expand(check['path'])] -def context(project, check, today, gh): +def context(project, check, today, gh, cache_dir='', dry_run=False): + """The contract's context. cacheDir: a folder the check may keep files in between runs (it makes it; empty when + there is none); dryRun: true in `gardener run --dry-run`, when a check writes nothing, its cache neither.""" return {'version': contract.VERSION, 'project': {'name': project['name'], 'repo': project['repo'], 'root': config.expand(project['root']) if project['root'] else ''}, - 'check': check['id'], 'options': check['options'], 'fix': check['fix'], 'today': today, 'gh': gh} + 'check': check['id'], 'options': check['options'], 'fix': check['fix'], 'today': today, 'gh': gh, + 'cacheDir': cache_dir, 'dryRun': dry_run} def failed(check, text, detail='', fix=''): @@ -104,9 +107,9 @@ def _talk(proc, data, deadline): sel.close() -def run(project, check, today, gh): +def run(project, check, today, gh, cache_dir='', dry_run=False): """(findings, ok): the check's findings with "check" set to its id; ok is False when it failed.""" - ctx = json.dumps(context(project, check, today, gh)).encode() + ctx = json.dumps(context(project, check, today, gh, cache_dir, dry_run)).encode() root = config.expand(project['root']) if project['root'] else None if root and not os.path.isdir(root): return [failed(check, 'the project root is not a folder', f'root {project["root"]}', diff --git a/fork-kit/gardener/sbin/gardener-install b/fork-kit/gardener/sbin/gardener-install index aef21353afb22..880d3936b0359 100755 --- a/fork-kit/gardener/sbin/gardener-install +++ b/fork-kit/gardener/sbin/gardener-install @@ -5,8 +5,9 @@ gardener-install uninstall gardener-install self-check -install copies bin/gardener, sbin/gardener-install, lib/gardener/, checks/, systemd/, README.md and -fork-kit/common/{machine_file,kit_install}.py of one release into /usr/local/libexec/gardener/versions// (with +install copies bin/gardener, sbin/gardener-install, lib/gardener/, checks/, systemd/, README.md, +fork-kit/common/{machine_file,kit_install}.py and the merge gate's lens and review rules (fork-ci/actions/pr-queue: +the review-tiers check imports them, into gate/) of one release into /usr/local/libexec/gardener/versions// (with MANIFEST.sha256), checks the copy, switches the link `current` to it and links /usr/local/bin/gardener and /usr/local/sbin/gardener-install to it. With --timer it also writes the kit's one timer: the user units gardener.service and gardener.timer in /etc/systemd/user/, which run `gardener run --timer` every hour for each @@ -40,10 +41,13 @@ class GardenerInstaller(kit_install.Installer): LIBEXEC = '/usr/local/libexec/gardener' LINKS = {'/usr/local/bin/gardener': 'bin/gardener', '/usr/local/sbin/gardener-install': 'sbin/gardener-install'} - CHECKS = ('checks/context-budget', 'checks/facts', 'checks/install-drift', 'checks/workflows-off', - 'checks/worktrees') + CHECKS = ('checks/context-budget', 'checks/facts', 'checks/install-drift', 'checks/review-tiers', + 'checks/workflows-off', 'checks/worktrees') + # the gate's own code, imported by review-tiers, never copied into the kit's source (GATE_SOURCE) + GATE = ('gate/config.py', 'gate/lens.py', 'gate/review_config.py', 'gate/review_glob.py', 'gate/review_judge.py', + 'gate/review.vectors.json') SOURCE_FILES = ('bin/gardener', 'sbin/gardener-install', 'README.md', 'common/machine_file.py', - 'common/kit_install.py', 'systemd/gardener.service', 'systemd/gardener.timer') + CHECKS + 'common/kit_install.py', 'systemd/gardener.service', 'systemd/gardener.timer') + CHECKS + GATE EXECUTABLE = frozenset({'bin/gardener', 'sbin/gardener-install'} | set(CHECKS)) PACKAGE = 'gardener' MODULES = ('__init__', 'cli', 'config', 'contract', 'judge', 'report', 'runner') @@ -51,6 +55,15 @@ class GardenerInstaller(kit_install.Installer): HAS_CONFIG = True KIT_STEPS = ('timer-units',) + def read_source(self, source, rel): + """gate/... comes from the fork's fork-ci/actions/pr-queue (next to fork-kit), unless the source folder has its + own gate/ (an installed copy).""" + if rel.startswith('gate/') and not os.path.lexists(os.path.join(source, 'gate')): + gate = os.path.join(os.path.dirname(os.path.dirname(os.path.normpath(source))), 'fork-ci', 'actions', + 'pr-queue') + return super().read_source(gate, rel[len('gate/'):]) + return super().read_source(source, rel) + def add_install_options(self, parser): parser.add_argument('--timer', dest='timer', action='store_true', default=None) parser.add_argument('--no-timer', dest='timer', action='store_false') diff --git a/fork-kit/gardener/tests/checks.test.py b/fork-kit/gardener/tests/checks.test.py index b319f313b81df..4469b6d415d0b 100644 --- a/fork-kit/gardener/tests/checks.test.py +++ b/fork-kit/gardener/tests/checks.test.py @@ -1,5 +1,5 @@ """The general checks shipped with the kit, each run the way the runner runs it (the contract context on stdin) on -fixture files, temporary git repositories, a fake `gh` and a fake `facts`. Every line they print must be a finding. +fixture files, temporary git repositories, a fake `gh` (the GitHub API, GraphQL search too) and a fake `facts`. Every line they print must be a finding. No network, no root. python3 -I -B fork-kit/gardener/tests/checks.test.py @@ -19,9 +19,9 @@ class Check(gf.Temp): env = {} - def run_check(self, name, options=None, fix=False, repo='example-owner/app', gh='gh', code=0): + def run_check(self, name, options=None, fix=False, repo='example-owner/app', gh='gh', code=0, **more): ctx = {'version': contract.VERSION, 'project': {'name': 'example', 'repo': repo, 'root': self.root}, - 'check': name, 'options': options or {}, 'fix': fix, 'today': '2026-11-23', 'gh': gh} + 'check': name, 'options': options or {}, 'fix': fix, 'today': '2026-11-23', 'gh': gh, **more} r = subprocess.run([sys.executable, '-I', '-B', os.path.join(gf.CHECKS, name)], input=json.dumps(ctx), capture_output=True, text=True, cwd=self.root, timeout=120, env=dict(os.environ, **self.env)) @@ -362,6 +362,350 @@ def test_unreadable_paths_are_a_note_not_drift(self): found = self.run_check('install-drift', self.opts()) self.assertEqual(self.ids(found), ['install-drift.unreadable']) +SHA = 'a' * 40 +QUEUE = {'required_checks': ['ci', 'head_check'], 'merge_method': 'squash', 'bot_logins': ['helper-bot'], + 'lens_author_associations': ['OWNER', 'MEMBER'], + 'override': {'prefix': 'override for head', 'author_association': 'OWNER'}, + 'ready_command': 'gh pr merge {pr} --auto --squash', 'push_command': 'git push', + 'lens_format_doc': 'README.md', 'head_check': 'head_check'} +REVIEW = {'version': 1, 'mode': 'enforce', + 'rules': [{'name': 'gate', 'weight': 'critical', 'paths': ['ci/**'], 'lenses': ['merge-path', 'state']}, + {'name': 'code', 'weight': 'normal', 'paths': ['**'], 'lenses': ['code']}], + 'lenses': {'merge-path': {'prompt': 'l/merge-path.md'}, 'state': {'prompt': 'l/state.md'}, + 'code': {'prompt': 'l/code.md'}}, + 'min_lenses': {'critical': 2, 'normal': 1, 'light': 0}, 'findings': True, 'state_line': False, + 'rounds': {'approach_at': 3, 'max': 4, 'approach_lens': 'code'}} +TIERS = {'rules': [{'paths': ['**/*.md'], 'tier': 0}], + 'registry': {'file': 'modules.json', 'rows': 'modules', 'paths': 'paths', 'tier': 'tier', 'default': 2}, + 'unmatched': 0, + 'requires': {'2': {'minLenses': 2, 'lenses': [{'name': 'correctness', 'match': 'correct'}]}, + '3': {'minLenses': 3, 'lenses': [{'name': 'data integrity', 'match': 'data.?integrity', + 'count': 2}]}}} +MODULES = {'modules': [{'id': 'shop', 'paths': ['mods/shop'], 'tier': 3}, {'id': 'chat', 'paths': ['mods/chat']}, + {'id': 'web', 'paths': 'mods/web', 'tier': 1}]} +MERGED = '2026-11-20T12:00:00Z' + + +def post(body, when='2026-11-20T11:00:00Z', assoc='OWNER', login='owner-one', kind='User', edited=False, + hidden=False): + return {'body': body, 'createdAt': when, 'authorAssociation': assoc, 'includesCreatedEdit': edited, + 'isMinimized': hidden, 'url': 'https://example.invalid/c', 'author': {'login': login, '__typename': kind}} + + +def lens_post(name, **kw): + return post(f'Lens: {name} ยท read at {SHA}\n\nNo findings.', **kw) + + +def approval(when='2026-11-20T11:00:00Z', assoc='OWNER', rid='r1'): + return {'id': rid, 'body': '', 'submittedAt': when, 'state': 'APPROVED', 'authorAssociation': assoc, + 'includesCreatedEdit': False, 'isMinimized': False, 'url': 'https://example.invalid/r', + 'author': {'login': 'owner-one', '__typename': 'User'}} + + +def pr(number, paths, comments=(), reviews=(), merged=MERGED, labels=(), author='dev-one', files_total=None, + comments_total=None): + return {'number': number, 'mergedAt': merged, 'author': {'login': author, '__typename': 'User'}, + 'labels': {'nodes': [{'name': n} for n in labels]}, + 'files': {'totalCount': len(paths) if files_total is None else files_total, + 'nodes': [{'path': p} for p in paths]}, + 'comments': {'totalCount': len(comments) if comments_total is None else comments_total, + 'nodes': list(comments)}, + 'reviews': {'totalCount': len(reviews), 'nodes': list(reviews)}} + + +class ReviewTiers(Check): + """review-tiers against a fake gh: `api rate_limit` and paged `api graphql` searches, every call logged.""" + + def setUp(self): + super().setUp() + self.cache = os.path.join(self.tmp, 'cache', 'review-tiers') + self.log = os.path.join(self.tmp, 'gh-calls.jsonl') + self.repo(queue=dict(QUEUE), modules=MODULES) + + def repo(self, queue=None, modules=None): + os.makedirs(self.root, exist_ok=True) + if not os.path.isdir(os.path.join(self.root, '.git')): + self.git(self.root, 'init', '-q', '-b', 'main') + if queue is not None: + self.write('.github/pr-queue.json', json.dumps(queue)) + if modules is not None: + self.write('modules.json', json.dumps(modules)) + self.git(self.root, 'add', '-A') + self.git(self.root, 'commit', '-q', '--allow-empty', '-m', 'files') + + def fake_gh(self, pages, remaining=4000, fail_page=None): + """pages: lists of pull request nodes, one per search page. fail_page: that page fails (1 = the first).""" + data = os.path.join(self.tmp, 'gh-pages.json') + with open(data, 'w') as f: + json.dump(pages, f) + return self.script('gh', f""" + import json, sys + a = sys.argv[1:] + with open({self.log!r}, 'a') as log: + log.write(json.dumps(a) + '\\n') + if a == ['api', 'rate_limit']: + print(json.dumps({{'resources': {{'graphql': {{'remaining': {remaining}}}}}}})) + sys.exit(0) + assert a[:2] == ['api', 'graphql'], a + opts = dict(x.split('=', 1) for x in a[2:] if '=' in x) + page = int(opts.get('after', 'c0')[1:]) + if page + 1 == {fail_page!r}: + sys.stderr.write('HTTP 502: Bad Gateway\\n') + sys.exit(1) + pages = json.load(open({data!r})) + more = page + 1 < len(pages) + print(json.dumps({{'data': {{'rateLimit': {{'cost': 1, 'remaining': {remaining} - page}}, + 'search': {{'pageInfo': {{'hasNextPage': more, 'endCursor': 'c%d' % (page + 1)}}, + 'nodes': pages[page] if pages else []}}}}}})) + """) + + def calls(self): + if not os.path.exists(self.log): + return [] + with open(self.log) as f: + return [json.loads(ln) for ln in f] + + def queries(self): + return [dict(x.split('=', 1) for x in c[2:] if '=' in x and x.startswith('q='))['q'] + for c in self.calls() if c[:2] == ['api', 'graphql']] + + def check(self, gh, options=None, code=0, **more): + opts = {'tiers': TIERS} if options is None else options + more.setdefault('cacheDir', self.cache) + return self.run_check('review-tiers', opts, gh=gh, code=code, **more) + + def by_pr(self, found): + return {f['where']: f for f in found if f['id'] == 'review-tiers.skipped'} + + # --- verdicts -------------------------------------------------------------------------------------------------- + + def test_each_tier_asks_for_its_lenses(self): + gh = self.fake_gh([[ + pr(1, ['docs/a.md', 'mods/chat/README.md']), # tier 0: nothing needed + pr(2, ['mods/chat/Chat.java'], [lens_post('correctness')]), # tier 2, one lens + pr(3, ['mods/chat/Chat.java'], [lens_post('correctness-ops'), lens_post('design-tests')]), # enough + pr(4, ['mods/shop/Shop.java'], [lens_post(n) for n in ('correctness', 'design', 'tests', + 'data-integrity-1')]), # tier 3: one DI + pr(5, ['mods/shop/Shop.java'], [lens_post(n) for n in ('correctness', 'data-integrity-1', + 'data integrity 2')]), # tier 3: enough + pr(6, ['tools/x.sh']), # unmatched: tier 0 + pr(7, ['mods/web/a.js']), # tier 1: asks nothing + pr(8, ['mods/chat/Chat.java'], [lens_post('design'), lens_post('tests')]), # no correctness + pr(9, ['mods/chatter/x.java', 'mods/chat'], [lens_post('correctness'), lens_post('design')]), + ]]) + found = self.check(gh) + got = self.by_pr(found) + self.assertEqual(sorted(got), ['#2', '#4', '#8']) + self.assertIn('tier 2 asks: needs 2 lens(es), found 1 (lenses before the merge: correctness)', got['#2']['text']) + self.assertIn('tier 3 asks: needs 2 data integrity lens(es), found 1', got['#4']['text']) + self.assertIn('needs 1 correctness lens(es), found 0', got['#8']['text']) + self.assertTrue(all(f['severity'] == 'warn' for f in got.values())) + + def test_only_counted_authors_and_comments_before_the_merge_count(self): + gh = self.fake_gh([[ + pr(1, ['mods/chat/C.java'], [lens_post('correctness'), lens_post('design', assoc='NONE')]), + pr(2, ['mods/chat/C.java'], [lens_post('correctness'), lens_post('design', login='helper-bot')]), + pr(3, ['mods/chat/C.java'], [lens_post('correctness'), lens_post('design', when='2026-11-21T09:00:00Z')]), + pr(4, ['mods/chat/C.java'], [lens_post('correctness'), lens_post('design', assoc='MEMBER')]), + ]]) + got = self.by_pr(self.check(gh)) + self.assertEqual(sorted(got), ['#1', '#2', '#3']) + self.assertIn('lens after the merge: design', got['#3']['text']) + + def test_approvals_count_only_when_asked(self): + node = pr(1, ['mods/chat/C.java'], [lens_post('correctness')], [approval()]) + self.assertEqual(sorted(self.by_pr(self.check(self.fake_gh([[node]])))), ['#1']) + tiers = dict(TIERS, approvalsCount=True) + os.remove(self.log) + self.assertEqual(self.by_pr(self.check(self.fake_gh([[node]]), {'tiers': tiers}, cacheDir='')), {}) + + def test_too_many_files_is_judged_at_the_top_tier(self): + gh = self.fake_gh([[pr(1, ['docs/a.md'], [lens_post('correctness'), lens_post('design')], files_total=300, + comments_total=150)]]) + got = self.by_pr(self.check(gh)) + self.assertIn('tier 3 asks', got['#1']['text']) + self.assertIn('it changed more than 100 files', got['#1']['text']) + self.assertIn('only its last 100 comments and 50 reviews were read', got['#1']['text']) + + def test_override_waiver_and_exemptions_settle_a_pull_request(self): + gh = self.fake_gh([[ + pr(1, ['mods/chat/C.java'], [post(f'override for head {SHA}: urgent fix')]), + pr(2, ['mods/chat/C.java'], [post(f'override for head {SHA}: urgent fix', edited=True)]), + pr(3, ['mods/chat/C.java'], [post(f'override for head {SHA}: urgent fix', assoc='MEMBER')]), + pr(4, ['mods/chat/C.java'], [post('Retro waiver: a version bump only\nmore', + when='2026-11-22T08:00:00Z')]), + pr(5, ['mods/chat/C.java'], [post('Retro waiver: a version bump only', assoc='NONE')]), + pr(6, ['mods/chat/C.java'], [post('see the retro waiver: below')]), # not the first words + pr(7, ['mods/chat/C.java'], labels=['no-review']), + pr(8, ['mods/chat/C.java'], author='Release-Bot'), + pr(9, ['mods/chat/C.java'], [post(f'override for head {SHA}: late', when='2026-11-21T09:00:00Z')]), + ]]) + got = self.by_pr(self.check(gh, {'tiers': TIERS, 'waivers': ['retro waiver'], 'exemptLabels': ['no-review'], + 'exemptAuthors': ['release-bot']})) + self.assertEqual(sorted(got), ['#2', '#3', '#5', '#6', '#9']) + + def test_the_gate_review_block_judges_without_tiers(self): + self.repo(queue=dict(QUEUE, review=REVIEW)) + gh = self.fake_gh([[ + pr(1, ['ci/run.sh'], [lens_post('merge-path')]), + pr(2, ['ci/run.sh'], [lens_post('merge-path'), lens_post('state')]), + pr(3, ['src/a.ts'], [lens_post('code')]), + pr(4, ['src/a.ts']), + ]]) + got = self.by_pr(self.check(gh, {})) + self.assertEqual(sorted(got), ['#1', '#4']) + self.assertIn('less review than critical asks: needs lens state; 2 lens(es), found 1', got['#1']['text']) + self.assertIn('less review than normal asks: needs lens code', got['#4']['text']) + + def test_the_registry_and_queue_config_come_from_git_not_the_working_tree(self): + self.write('modules.json', json.dumps({'modules': [{'id': 'chat', 'paths': ['mods/chat'], 'tier': 0}]})) + self.write('.github/pr-queue.json', json.dumps(dict(QUEUE, lens_author_associations=['NONE']))) + gh = self.fake_gh([[pr(1, ['mods/chat/C.java'], [lens_post('correctness')])]]) + got = self.by_pr(self.check(gh)) + self.assertIn('found 1', got['#1']['text']) # tier 2 from git; OWNER counted, as in git + + def test_no_rules_no_repo_and_bad_options(self): + gh = self.fake_gh([[]]) + self.assertEqual(self.ids(self.check(gh, {})), ['review-tiers.no-rules']) + self.assertEqual(self.ids(self.check(gh, repo='')), ['review-tiers.no-repo']) + self.assertEqual(self.calls(), []) # neither asked GitHub anything + for opts, why in (({'tiers': dict(TIERS, colour=1)}, "unknown key 'colour'"), + ({'tiers': dict(TIERS, requires={})}, 'must name at least one tier'), + ({'tiers': TIERS, 'days': 0}, 'days must be'), + ({'tiers': TIERS, 'queueConfig': 'gone.json'}, 'not in the project root'), + ({'tiers': dict(TIERS, registry=dict(TIERS['registry'], file='gone.json'))}, + 'not in the project root')): + with self.subTest(why=why): + self.check(gh, opts, code=1) + self.assertIn(why, self.last_stderr) + + def test_a_comment_the_lens_rules_cannot_read_is_a_warning(self): + bad = post('x') + bad['body'] = 5 # not text: the lens rules raise + got = self.check(self.fake_gh([[pr(1, ['mods/chat/C.java'], [bad])]])) + self.assertEqual(self.ids(got), ['review-tiers.unread']) + self.assertEqual(got[0]['where'], '#1') + + # --- the GitHub budget ------------------------------------------------------------------------------------------- + + def test_one_search_and_the_query(self): + self.check(self.fake_gh([[pr(1, ['docs/a.md'])], [pr(2, ['docs/b.md'])]])) + self.assertEqual([c[:2] for c in self.calls()], [['api', 'rate_limit'], ['api', 'graphql'], ['api', 'graphql']]) + self.assertEqual(self.queries()[0], + 'repo:example-owner/app is:pr is:merged base:main merged:>=2026-11-17 sort:updated-desc') + + def test_a_low_budget_searches_nothing_and_judges_the_cache(self): + self.check(self.fake_gh([[pr(1, ['mods/chat/C.java'])]])) + os.remove(self.log) + found = self.check(self.fake_gh([[]], remaining=500)) + self.assertEqual(self.ids(found), ['review-tiers.budget', 'review-tiers.skipped']) + self.assertEqual(self.queries(), []) + + def test_too_many_pages_is_partial_and_the_next_run_searches_the_days_again(self): + pages = [[pr(i, ['mods/chat/C.java'])] for i in range(1, 4)] + found = self.check(self.fake_gh(pages), {'tiers': TIERS, 'maxPages': 2}) + self.assertIn('review-tiers.partial', self.ids(found)) + self.assertEqual(sorted(self.by_pr(found)), ['#1', '#2']) + with open(os.path.join(self.cache, 'cache.json')) as f: + self.assertEqual(json.load(f)['searchedDay'], '1970-01-01') + os.remove(self.log) + self.check(self.fake_gh(pages), {'tiers': TIERS, 'maxPages': 5}) + self.assertNotIn('updated:', self.queries()[0]) # the whole window again + + def test_the_budget_falling_while_searching_stops_the_search(self): + pages = [[pr(i, ['docs/a.md'])] for i in range(1, 4)] + found = self.check(self.fake_gh(pages, remaining=1000)) # 999 left after page 1 + self.assertIn('review-tiers.partial', self.ids(found)) + self.assertEqual(len(self.queries()), 2) + + # --- state: runs again, stops half-way, old or empty state ------------------------------------------------------ + + def cache_file(self): + return os.path.join(self.cache, 'cache.json') + + def test_runs_again_the_same_day_and_the_next_day_search_only_what_changed(self): + self.check(self.fake_gh([[pr(1, ['mods/chat/C.java']), pr(2, ['docs/a.md'])]])) + os.remove(self.log) + found = self.check(self.fake_gh([[pr(2, ['mods/chat/C.java'])]])) # #2 updated; #1 from the cache + self.assertIn('updated:>=2026-11-22', self.queries()[0]) + self.assertEqual(sorted(self.by_pr(found)), ['#1', '#2']) + os.remove(self.log) + found = self.check(self.fake_gh([[]]), today='2026-11-24') + self.assertIn('merged:>=2026-11-18 sort:updated-desc updated:>=2026-11-22', self.queries()[0]) + self.assertEqual(sorted(self.by_pr(found)), ['#1', '#2']) + os.remove(self.log) + found = self.check(self.fake_gh([[]]), today='2026-11-28') # #1 and #2 fell out of the window + self.assertEqual(self.by_pr(found), {}) + with open(self.cache_file()) as f: + self.assertEqual(json.load(f)['prs'], {}) + + def test_a_wider_window_searches_all_of_it(self): + self.check(self.fake_gh([[]])) + os.remove(self.log) + self.check(self.fake_gh([[]]), {'tiers': TIERS, 'days': 30}) + self.assertEqual(self.queries()[0], 'repo:example-owner/app is:pr is:merged base:main merged:>=2026-10-25 ' + 'sort:updated-desc') + + def test_stopped_half_way_leaves_the_cache_as_it_was(self): + self.check(self.fake_gh([[pr(1, ['mods/chat/C.java'])]])) + with open(self.cache_file(), 'rb') as f: + before = f.read() + self.check(self.fake_gh([[pr(2, ['docs/a.md'])], [pr(3, ['docs/a.md'])]], fail_page=2), code=1) + self.assertIn('HTTP 502', self.last_stderr) + with open(self.cache_file(), 'rb') as f: + self.assertEqual(f.read(), before) + self.assertEqual([n for n in os.listdir(self.cache) if n != 'cache.json'], []) # no temporary file left + + def test_old_broken_empty_or_other_caches_are_read_as_empty(self): + good = {'mergedAt': MERGED, 'author': 'a', 'bot': False, 'labels': [], 'paths': ['mods/chat/C.java'], + 'pathsComplete': True, 'commentsComplete': True} + self.check(self.fake_gh([[]])) + with open(self.cache_file()) as f: + key = json.load(f)['key'] + cases = {'empty file': '', 'not JSON': '{', 'a list': '[]', 'no version': {'prs': {}}, + 'an older version': {'version': 0, 'key': key, 'prs': {}, 'from': '2026-11-17', + 'searchedDay': '2026-11-23'}, + 'an entry without the new keys': {'version': 1, 'key': key, 'prs': {'1': good}, 'from': '2026-11-17', + 'searchedDay': '2026-11-23'}, + 'another key': {'version': 1, 'key': 'x', 'prs': {}, 'from': '2026-11-17', + 'searchedDay': '2026-11-23'}, + 'no search day': {'version': 1, 'key': key, 'prs': {}, 'from': '2026-11-17'}, + 'a day in the future': {'version': 1, 'key': key, 'prs': {}, 'from': '2026-11-17', + 'searchedDay': '2026-12-01'}} + for why, data in cases.items(): + with self.subTest(why=why): + with open(self.cache_file(), 'w') as f: + f.write(data if isinstance(data, str) else json.dumps(data)) + os.remove(self.log) + found = self.check(self.fake_gh([[pr(5, ['mods/chat/C.java'])]])) + self.assertNotIn('updated:', self.queries()[0]) # the whole window + self.assertEqual(sorted(self.by_pr(found)), ['#5']) # nothing from the bad cache + with open(self.cache_file()) as f: + fresh = json.load(f) + self.assertEqual((fresh['version'], fresh['key'], fresh['searchedDay'], sorted(fresh['prs'])), + (1, key, '2026-11-23', ['5'])) + + def test_a_newer_cache_is_not_used_and_not_overwritten(self): + os.makedirs(self.cache) + with open(self.cache_file(), 'w') as f: + f.write('{"version": 9, "prs": {"1": {}}}') + found = self.check(self.fake_gh([[pr(5, ['mods/chat/C.java'])]])) + self.assertEqual(sorted(self.by_pr(found)), ['#5']) + self.assertNotIn('updated:', self.queries()[0]) + with open(self.cache_file()) as f: + self.assertEqual(f.read(), '{"version": 9, "prs": {"1": {}}}') + + def test_a_dry_run_and_no_cache_folder_write_nothing(self): + self.check(self.fake_gh([[pr(1, ['mods/chat/C.java'])]]), dryRun=True) + self.assertFalse(os.path.exists(self.cache)) + self.check(self.fake_gh([[pr(1, ['mods/chat/C.java'])]]), cacheDir='') + self.assertFalse(os.path.exists(self.cache)) + + def test_the_cache_keeps_no_comment_text(self): + self.check(self.fake_gh([[pr(1, ['mods/chat/C.java'], [post('Lens: correctness\nsecret words here')])]])) + with open(self.cache_file()) as f: + self.assertNotIn('secret words', f.read()) + class Contract(unittest.TestCase): @@ -384,6 +728,37 @@ def test_a_check_without_a_context_exits_with_a_message(self): MUTATIONS = { + 'review-tiers: only lens comments from before the merge count': ( + 'checks/review-tiers', " keep = [c for c in comments if ((c.get('createdAt') or '') <= merged) == before]", + " keep = comments if before else []", + 'ReviewTiers.test_only_counted_authors_and_comments_before_the_merge_count'), + 'review-tiers: an override counts only before the merge': ( + 'checks/review-tiers', " posts = [p for _, _, p in review.lens_posts(before)]", " posts = comments", + 'ReviewTiers.test_override_waiver_and_exemptions_settle_a_pull_request'), + 'review-tiers: a waiver counts only from a counted author': ( + 'checks/review-tiers', " return review.counts(post) and not review.is_bot(post)", + " return not review.is_bot(post)", 'ReviewTiers.test_override_waiver_and_exemptions_settle_a_pull_request'), + 'review-tiers: too many files is the top tier': ( + 'checks/review-tiers', " tier = max(tier, tiers['top'])\n", " pass\n", + 'ReviewTiers.test_too_many_files_is_judged_at_the_top_tier'), + 'review-tiers: a partial search does not move the search day': ( + 'checks/review-tiers', " if complete:\n searched = ctx['today']", " searched = ctx['today']", + 'ReviewTiers.test_too_many_pages_is_partial_and_the_next_run_searches_the_days_again'), + 'review-tiers: a wider window searches all of it': ( + 'checks/review-tiers', "and good_day(cache.get('from'), start)", 'and True', + 'ReviewTiers.test_a_wider_window_searches_all_of_it'), + 'review-tiers: a dry run writes no cache': ( + 'checks/review-tiers', 'if path and not dry and not newer:', 'if path and not newer:', + 'ReviewTiers.test_a_dry_run_and_no_cache_folder_write_nothing'), + 'review-tiers: a newer cache is not overwritten': ( + 'checks/review-tiers', 'if path and not dry and not newer:', 'if path and not dry:', + 'ReviewTiers.test_a_newer_cache_is_not_used_and_not_overwritten'), + 'review-tiers: a cache entry of another shape is not used': ( + 'checks/review-tiers', "and good_fact(f) for k, f in data['prs'].items()", "for k, f in data['prs'].items()", + 'ReviewTiers.test_old_broken_empty_or_other_caches_are_read_as_empty'), + 'review-tiers: a low budget does not search': ( + 'checks/review-tiers', ' if left < min_left:\n emit(', ' if False:\n emit(', + 'ReviewTiers.test_a_low_budget_searches_nothing_and_judges_the_cache'), 'a finding id is a dotted name': ( 'contract', " if not ID.fullmatch(obj['id']):", " if False:", 'Contract.test_parse_finding'), 'a branch with no work of its own is not merged': ( diff --git a/fork-kit/gardener/tests/gardener_fixture.py b/fork-kit/gardener/tests/gardener_fixture.py index e707b9cfddb86..d0f84711b5a49 100644 --- a/fork-kit/gardener/tests/gardener_fixture.py +++ b/fork-kit/gardener/tests/gardener_fixture.py @@ -132,6 +132,9 @@ def state(self, name='example'): return json.load(f) +GATE_FILES = ('config.py', 'lens.py', 'review_config.py', 'review_glob.py', 'review_judge.py', 'review.vectors.json') + + def red_check(case, test_file, mutations): """mutations: {rule: (module, text, broken text, 'Class.test_name')}.""" for rule, (module, text, broken, test) in mutations.items(): @@ -146,6 +149,10 @@ def red_check(case, test_file, mutations): env = {LIB_ENV: lib} if module.startswith('checks/'): shutil.copytree(os.path.join(KIT, 'checks'), os.path.join(tmp, 'checks'), symlinks=True) + gate = os.path.join(os.path.dirname(os.path.dirname(KIT)), 'fork-ci', 'actions', 'pr-queue') + os.makedirs(os.path.join(tmp, 'gate')) # where review-tiers finds it in an installed copy + for name in GATE_FILES: + shutil.copy(os.path.join(gate, name), os.path.join(tmp, 'gate')) path = env[CHECKS_ENV] = os.path.join(tmp, module) else: path = os.path.join(lib, 'gardener', f'{module}.py') diff --git a/fork-kit/gardener/tests/install.test.py b/fork-kit/gardener/tests/install.test.py index 03cff4684f05f..33f5eaf6cdf3c 100644 --- a/fork-kit/gardener/tests/install.test.py +++ b/fork-kit/gardener/tests/install.test.py @@ -12,6 +12,8 @@ KIT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, os.path.join(os.path.dirname(KIT), 'common', 'tests')) import install_fixture as fx # noqa: E402 +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import gardener_fixture as gf # noqa: E402 SHA1, SHA2 = fx.SHA1, fx.SHA2 UNITS = ('/etc/systemd/user/gardener.service', '/etc/systemd/user/gardener.timer') @@ -92,18 +94,22 @@ def test_the_timer_unit_ticks_every_hour_from_the_release_in_use(self): self.assertEqual(self.run_main('self-check')[0], 0) def test_the_installed_checks_run_from_the_release(self): - """Each general check in the installed copy finds the kit's lib beside it (no source tree needed).""" + """Each general check in the installed copy finds the kit's lib beside it, and review-tiers the merge gate's + code in gate/ (no source tree needed).""" import subprocess self.assertEqual(self.install()[0], 0) release = self.path(os.readlink(self.path('/usr/local/libexec/gardener/current'))) - ctx = json.dumps({'version': 1, 'project': {'name': 'x', 'repo': '', 'root': self.root}, 'check': 'c', - 'options': {'files': {}}, 'fix': False, 'today': '2026-11-23', 'gh': 'gh'}) - for name in ('context-budget', 'worktrees'): + self.assertEqual(sorted(os.listdir(os.path.join(release, 'gate'))), sorted(gf.GATE_FILES)) + for name, options in (('context-budget', {'files': {}}), ('worktrees', {}), ('review-tiers', {})): + ctx = json.dumps({'version': 1, 'project': {'name': 'x', 'repo': '', 'root': self.root}, 'check': 'c', + 'options': options, 'fix': False, 'today': '2026-11-23', 'gh': 'gh'}) path = os.path.join(release, 'checks', name) self.assertTrue(os.access(path, os.X_OK), name) r = subprocess.run([sys.executable, '-I', '-B', path], input=ctx, capture_output=True, text=True, cwd=self.root, timeout=60) self.assertEqual(r.returncode, 0, r.stderr) + if name == 'review-tiers': + self.assertIn('review-tiers.no-repo', r.stdout) def assert_disable_said_first(self, out): """Users are told to disable the timer before the units go, not after (no dangling wants link).""" diff --git a/fork-kit/gardener/tests/report.test.py b/fork-kit/gardener/tests/report.test.py index 60e8d2e3592de..15b679cfc09f4 100644 --- a/fork-kit/gardener/tests/report.test.py +++ b/fork-kit/gardener/tests/report.test.py @@ -1,11 +1,11 @@ """The report issue (missing, closed, edited by hand, its marker removed, a GitHub error), what goes into it (the allow-list: nothing local reaches the issue; the size cap) and the judgment step (a fake local model over HTTP, one -that is not there and one that does not speak HTTP). +that is not there, one that does not speak HTTP and one that trickles its answer). GitHub is a fake (gardener_fixture.FakeGitHub); the `gh api` wrapper is run against a fake gh script. python3 -I -B fork-kit/gardener/tests/report.test.py """ -import http.server, json, os, socket, subprocess, sys, threading, unittest +import http.server, json, os, socket, subprocess, sys, threading, time, unittest sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import gardener_fixture as gf # noqa: E402 @@ -193,6 +193,22 @@ def test_only_paths_inside_the_repository_are_shown(self): with self.subTest(where=where): self.assertEqual(report.public_where(where, root, 'example-owner/app'), want) + def test_a_pull_request_number_is_shown_and_linked_to_the_right_repository(self): + root = '/srv/u/repo' + cases = [('#12', 'example-owner/app', 'example-owner/app', '#12'), + ('#12', 'example-owner/app', 'Example-Owner/App', '#12'), + ('#12', 'example-owner/app', 'example-owner/reports', 'example-owner/app#12'), + ('#12', 'example-owner/app', '', '#12'), + ('#12', '', 'example-owner/reports', None), # whose #12? not shown + ('#0', 'example-owner/app', 'example-owner/app', None), ('#1x', 'example-owner/app', '', None), + ('#12 and more', 'example-owner/app', '', None)] + for where, repo, report_repo, want in cases: + with self.subTest(where=where, repo=repo, report_repo=report_repo): + self.assertEqual(report.public_where(where, root, report_repo, repo), want) + body = report.render_issue('example', '2026-11-23', [self.finding(where='#7')], [], root=root, + report_repo='example-owner/reports', text_checks={'c'}, repo='example-owner/app') + self.assertIn('| example-owner/app#7 |', body) + def test_a_finding_outside_the_repository_is_only_counted(self): fs = [self.finding(where='/srv/u/.claude/projects/-srv-u--repo/memory/plans.md', text='orphan plans.md'), self.finding(where='/srv/u/.claude/projects/-srv-u--repo/memory/b.md', text='orphan b.md'), @@ -253,7 +269,12 @@ def test_masks(self): ('ssh admin@build-box failed', 'build-box'), ('ip 2001:db8:a1e0::1 up', '2001'), ('ip 2001:db8:a1e0::1 up', 'a1e0'), ('bind :: now', '::'), ('lo ::1', '::1'), (r'C:\Users\alice\secret\plan.txt', 'alice'), ('C:/Users/alice/x', 'alice'), - (r'share \\nas\private\x', 'nas'), ('a/srv/u/x y', '/srv'), ('a~/secret/x', 'secret')): + (r'share \\nas\private\x', 'nas'), ('a/srv/u/x y', '/srv'), ('a~/secret/x', 'secret'), + *((f'token {t} here', t[6:]) for t in ('ghp_' + 'Ab1' * 12, 'github_pat_' + 'x1' * 20, + 'sk-' + 'q' * 30, 'xoxb-' + '12-ab' * 4, + 'AKIA' + 'B7' * 8)), + ('-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXk\n-----END OPENSSH PRIVATE KEY-----', + 'b3BlbnNz')): with self.subTest(text=text): self.assertNotIn(gone, report.public_text(text, '/srv/u/repo', '/srv/u')) for kept in ('origin/main is ahead', 'docs/a.md', 'at 12:30:45', 'std::vector', 'a.b c'): @@ -364,6 +385,53 @@ def test_an_endpoint_that_does_not_speak_http_is_a_note(self): self.assertIsNone(got) self.assertIn('model unreachable', note) + def trickle_server(self, gap): + """An HTTP server that sends its headers at once and then one byte of the body every gap seconds: each read + is quick, the whole answer is not.""" + srv = socket.socket() + srv.bind(('127.0.0.1', 0)) + srv.listen(4) + self.addCleanup(srv.close) + body = json.dumps({'choices': [{'message': {'content': 'late'}}]}).encode() + + def serve(): + try: + conn, _ = srv.accept() + except OSError: + return + with conn: + try: + conn.recv(65536) + conn.sendall(b'HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n' + b'Content-Length: %d\r\n\r\n' % len(body)) + for i in range(len(body)): + conn.sendall(body[i:i + 1]) + time.sleep(gap) + except OSError: + return + threading.Thread(target=serve, daemon=True).start() + return f'http://127.0.0.1:{srv.getsockname()[1]}/v1' + + def test_a_slow_model_is_cut_off_at_the_timeout_in_all(self): + started = time.monotonic() + got, note = judge.judge(self.model(self.trickle_server(0.2), timeoutSeconds=1), [dict(GOOD, check='c')], + self.root) + self.assertLess(time.monotonic() - started, 4) # not len(body) * 0.2 seconds + self.assertIsNone(got) + self.assertIn('model unreachable or no usable answer (TimeoutError)', note) + + def test_a_model_that_never_answers_is_cut_off(self): + srv = socket.socket() + srv.bind(('127.0.0.1', 0)) + srv.listen(4) # accepts, reads nothing, says nothing + self.addCleanup(srv.close) + started = time.monotonic() + got, note = judge.judge(self.model(f'http://127.0.0.1:{srv.getsockname()[1]}/v1', timeoutSeconds=1), + [dict(GOOD, check='c')], self.root) + self.assertLess(time.monotonic() - started, 4) + self.assertIsNone(got) + self.assertIn('model unreachable', note) + def test_an_unreachable_model_is_a_note_and_the_run_goes_on(self): s = socket.socket() s.bind(('127.0.0.1', 0)) @@ -384,7 +452,20 @@ def test_the_judgment_goes_into_the_report(self): self.write_machine(self.project([{'path': self.finding_script('demo', GOOD)}], model={'endpoint': endpoint, 'model': 'm'})) self.assertEqual(self.run_cli('run')[0], 0) - self.assertIn('### Judgment (local model)\n\ndemo.thing: real; fix the doc first', self.gh.issues[1]['body']) + body = self.gh.issues[1]['body'] + self.assertIn('### Judgment (model draft)\n\nA model wrote this; nobody checked it.', body) + self.assertIn('\n\ndemo.thing: real; fix the doc first', body) + + def test_the_judgment_is_masked_like_check_text(self): + answer = f'see {self.root}/docs/a.md and token ghp_' + 'a' * 36 + endpoint, _ = self.serve({'choices': [{'message': {'content': answer}}]}) + self.write_machine(self.project([{'path': self.finding_script('demo', GOOD)}], + model={'endpoint': endpoint, 'model': 'm'})) + self.assertEqual(self.run_cli('run')[0], 0) + body = self.gh.issues[1]['body'] + self.assertIn('### Judgment (model draft)', body) + self.assertNotIn(self.root, body) + self.assertNotIn('ghp_' + 'a' * 36, body) MUTATIONS = { @@ -431,6 +512,12 @@ def test_the_judgment_goes_into_the_report(self): 'judge reads only tracked files': ( 'judge', ' if not tracked(real_root, rel):\n continue\n', '', 'Judge.test_the_model_gets_findings_and_only_tracked_files_inside_the_root'), + 'judge: the timeout bounds the whole answer': ( + 'judge', " if time.monotonic() > deadline:\n raise TimeoutError('the answer took too long')\n" + " chunk", ' chunk', 'Judge.test_a_slow_model_is_cut_off_at_the_timeout_in_all'), + 'a #N where is linked to the project repository': ( + 'report', " return f'{repo}{w}' if repo else None", " return w", + 'Render.test_a_pull_request_number_is_shown_and_linked_to_the_right_repository'), 'judge: any failure is a note': ( 'judge', ' except Exception as e:', ' except (OSError, ValueError, KeyError, IndexError, TypeError) as e:', 'Judge.test_an_endpoint_that_does_not_speak_http_is_a_note'), diff --git a/fork-kit/gardener/tests/run.test.py b/fork-kit/gardener/tests/run.test.py index 53e6ecd2b2be4..1021df6344b46 100644 --- a/fork-kit/gardener/tests/run.test.py +++ b/fork-kit/gardener/tests/run.test.py @@ -393,9 +393,15 @@ def test_the_check_gets_the_contract_context_in_its_root(self): self.assertEqual(self.run_cli('run')[0], 0) with open(os.path.join(self.tmp, 'ctx.json')) as f: ctx = json.load(f) + cache = os.path.join(self.state_dir, 'example', 'cache', 'spy') self.assertEqual(ctx, {'version': contract.VERSION, 'check': 'spy', 'options': {'a': 1}, 'fix': False, - 'today': '2026-11-23', 'gh': 'gh', 'cwd': self.root, + 'today': '2026-11-23', 'gh': 'gh', 'cwd': self.root, 'cacheDir': cache, + 'dryRun': False, 'project': {'name': 'example', 'repo': 'example-owner/app', 'root': self.root}}) + self.assertFalse(os.path.exists(cache)) # the check makes it when it needs it + self.assertEqual(self.run_cli('run', '--dry-run')[0], 0) + with open(os.path.join(self.tmp, 'ctx.json')) as f: + self.assertIs(json.load(f)['dryRun'], True) class Privacy(gf.Temp): @@ -740,7 +746,7 @@ def test_the_example_machine_file_section_parses(self): 'Config.test_an_error_of_any_kind_in_one_project_does_not_stop_the_next'), 'the issue is built from the allow-list': ( 'cli', " part = report.render_issue(name, today, findings, notes, answer, root, home, project['reportRepo'],\n" - " text_checks, counts)", + " text_checks, counts, project['repo'])", " part = report.render_local(name, today, findings, notes, answer)", 'Privacy.test_nothing_local_reaches_the_issue'), 'a project check\'s text is public only with publicText': ( From a0e325c6b4416f7281677b7724b2d47fb45f255c Mon Sep 17 00:00:00 2001 From: scuttletoby <123843277+scuttletoby@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:24:26 +0000 Subject: [PATCH 2/4] gardener: kit tests copy the kit in the fork's layout, gate folder included The installer reads the gardener's gate/ from fork-ci/actions/pr-queue two folders up from the kit; the shared install fixture copied the kit to a folder with nothing beside it, so 7 gardener install tests failed in CI. Co-Authored-By: Claude Opus 5.5 --- fork-kit/common/tests/install_fixture.py | 12 ++++++++---- fork-kit/common/tests/kit_install.test.py | 2 +- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/fork-kit/common/tests/install_fixture.py b/fork-kit/common/tests/install_fixture.py index 683e9037c67f0..e465182bee896 100644 --- a/fork-kit/common/tests/install_fixture.py +++ b/fork-kit/common/tests/install_fixture.py @@ -8,6 +8,7 @@ FORK_KIT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) COMMON = os.path.join(FORK_KIT, 'common') +GATE = os.path.join(os.path.dirname(FORK_KIT), 'fork-ci', 'actions', 'pr-queue') ENGINE = os.path.join(COMMON, 'kit_install.py') BOOTSTRAP = os.path.join(COMMON, 'bootstrap.sh') SHA1, SHA2 = 'a' * 40, 'b' * 40 @@ -179,10 +180,13 @@ def install(self, *extra, sha=SHA1, stop_after=None, source=None): stop_after=stop_after) def copy_kit(self): - """A source folder of the kit (and its common/ beside it) the test may change.""" - src = os.path.join(self.root, 'src') - shutil.copytree(self.KIT_DIR, src, ignore=shutil.ignore_patterns('__pycache__')) - shutil.copytree(COMMON, os.path.join(self.root, 'common'), ignore=shutil.ignore_patterns('__pycache__')) + """A source folder of the kit the test may change, laid out as in the fork: its common/ beside it, and the + fork's other folders a kit reads from at install (fork-ci/actions/pr-queue: the gardener's gate/) two up.""" + src = os.path.join(self.root, 'fork-kit', 'src') + ignore = shutil.ignore_patterns('__pycache__') + shutil.copytree(self.KIT_DIR, src, ignore=ignore) + shutil.copytree(COMMON, os.path.join(self.root, 'fork-kit', 'common'), ignore=ignore) + shutil.copytree(GATE, os.path.join(self.root, 'fork-ci', 'actions', 'pr-queue'), ignore=ignore) return src @staticmethod diff --git a/fork-kit/common/tests/kit_install.test.py b/fork-kit/common/tests/kit_install.test.py index bd31692ee7366..39c91f6faacd1 100644 --- a/fork-kit/common/tests/kit_install.test.py +++ b/fork-kit/common/tests/kit_install.test.py @@ -349,7 +349,7 @@ def test_a_release_whose_installer_differs_is_refused(self): shutil.rmtree(self.root) os.makedirs(self.root) src = self.copy_kit() - with open(os.path.join(src if rel.startswith('sbin/') else self.root, rel), 'a') as f: + with open(os.path.join(src if rel.startswith('sbin/') else os.path.dirname(src), rel), 'a') as f: f.write('# as a newer release has it\n') code, _, err = self.install(source=src) self.assertEqual(code, 1) From c6c56b7dd8c52fff12b6d3e04f32b180d4442fa0 Mon Sep 17 00:00:00 2001 From: scuttletoby <123843277+scuttletoby@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:30:13 +0000 Subject: [PATCH 3/4] gardener: worktrees reads branches by their full name (refname:short is ambiguous) A branch named like a tag or remote printed as heads/ and crashed the check. Co-Authored-By: Claude Opus 5.5 --- fork-kit/gardener/checks/worktrees | 4 ++-- fork-kit/gardener/tests/checks.test.py | 9 +++++++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/fork-kit/gardener/checks/worktrees b/fork-kit/gardener/checks/worktrees index 00b5ee37f9a20..6f8c5cdda20cb 100755 --- a/fork-kit/gardener/checks/worktrees +++ b/fork-kit/gardener/checks/worktrees @@ -100,7 +100,7 @@ for r in opt.get('repos') or [root]: base = base_of(repo) base_branch = base.split('/', 1)[1] if base and base.startswith('origin/') else base gone = set() - for line in git(repo, 'for-each-ref', '--format=%(refname:short)\t%(upstream:track)', 'refs/heads').stdout \ + for line in git(repo, 'for-each-ref', '--format=%(refname:lstrip=2)\t%(upstream:track)', 'refs/heads').stdout \ .splitlines(): name, _, track = line.partition('\t') if track.strip() == '[gone]': @@ -150,7 +150,7 @@ for r in opt.get('repos') or [root]: for t in prunable: emit('worktrees.prunable', 'info', 'worktree record whose folder is gone', t['worktree'], f'git -C {qp(r)} worktree prune') - for line in git(repo, 'for-each-ref', '--format=%(refname:short)', 'refs/heads').stdout.splitlines(): + for line in git(repo, 'for-each-ref', '--format=%(refname:lstrip=2)', 'refs/heads').stdout.splitlines(): branch = line.strip() if not branch or branch in in_trees or branch == base_branch: continue diff --git a/fork-kit/gardener/tests/checks.test.py b/fork-kit/gardener/tests/checks.test.py index 4469b6d415d0b..6ba937eaf2d48 100644 --- a/fork-kit/gardener/tests/checks.test.py +++ b/fork-kit/gardener/tests/checks.test.py @@ -159,6 +159,15 @@ def test_merged_stale_prunable_and_branches(self): ('worktrees.stale', 'worktree of branch old-work')]) self.assertTrue(os.path.isdir(os.path.join(trees, 'merged-branch'))) # report only + def test_a_branch_named_like_another_ref_is_read_by_its_full_name(self): + """refname:short writes `heads/x` when a tag or remote has the short name x too; git then reads + refs/heads/heads/x, and the whole check failed on a real repository.""" + self.merged('pr7') + self.git(self.root, 'update-ref', 'refs/remotes/pr7', 'HEAD') + self.git(self.root, 'tag', 'pr7') + found = self.run_check('worktrees') + self.assertEqual([(f['id'], f['text'].split(':')[0]) for f in found], [('branches.merged', 'branch pr7')]) + def test_fix_prunes_only_records_of_gone_folders(self): trees = os.path.join(self.tmp, 'trees') self.git(self.root, 'branch', 'gone-tree') From 73066be62892ea4c6226e970fc69dd780ccf3381 Mon Sep 17 00:00:00 2001 From: scuttletoby <123843277+scuttletoby@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:56:59 +0000 Subject: [PATCH 4/4] gardener review-tiers: resumable search, late reviews clear, no repo option Fix round 1 from the lens: - A search cut off by maxPages or the budget now remembers where it stopped (resume point in the cache) and goes on there next run, older pull requests first, until the whole window is read; "partial" is a warning. A page of one second is stepped past; a broken resume point is dropped. - Lenses after the merge that, with those before it, meet the tier clear the warning and leave a "late" note; the fix hint says so. - "No lens at all" (skipped, warn) is counted apart from "a lens kind missing" (short, warn at the top tier, else info). - The "repo" option is refused: the check reads the project's own repo. - The gate's code is part of the cache key; the unused "bot" fact is gone. - With the gate's review block, a pull request with more than 100 files is judged as critical. - A GraphQL page GitHub cannot answer is asked again once with 5 pull requests a page. - The judge's model call is bounded by timeoutSeconds in total: each read waits at most until the deadline. Co-Authored-By: Claude Opus 5.5 --- fork-kit/gardener/README.md | 42 ++-- fork-kit/gardener/checks/review-tiers | 251 +++++++++++++++++------- fork-kit/gardener/lib/gardener/judge.py | 15 +- fork-kit/gardener/tests/checks.test.py | 217 +++++++++++++++++--- fork-kit/gardener/tests/report.test.py | 45 ++++- 5 files changed, 448 insertions(+), 122 deletions(-) diff --git a/fork-kit/gardener/README.md b/fork-kit/gardener/README.md index 4f7d63c002af1..2073bbf142acf 100644 --- a/fork-kit/gardener/README.md +++ b/fork-kit/gardener/README.md @@ -157,23 +157,33 @@ All report only, and none needs root. Options as in each script's header. - **install-drift**: each fork kit's install record (`/etc//installed.tsv`) against the files and links on the machine, as the user that runs it (paths it cannot read are one note, not drift). With `release` (a commit), kits on another release. -- **review-tiers**: merged pull requests (last `days`, 7) that had less review than their tier asks for. Without - options it judges by the merge gate's own `review` block in the queue config (`queueConfig`, default - `.github/pr-queue.json`, read from git at `base`); with `tiers` by the project's tiers: `rules` (globs to a - tier), a `registry` file in the repository (rows of paths with a tier, for example a list of modules), - `unmatched`, and per tier `requires` {`minLenses`, `lenses`: [{`name`, `match` (a regex on lens names), `count`}]}. +- **review-tiers**: merged pull requests (last `days`, 7) of the project's own repository (`repo`; there is no + option for another one) that had less review than their tier asks for. Without options it judges by the merge + gate's own `review` block in the queue config (`queueConfig`, default `.github/pr-queue.json`, read from git at + `base`); with `tiers` by the project's tiers: `rules` (globs to a tier), a `registry` file in the repository (rows + of paths with a tier, for example a list of modules), `unmatched`, and per tier `requires` {`minLenses`, + `lenses`: [{`name`, `match` (a regex on lens names), `count`}]}. Lens comments are read by the gate's own code (`fork-ci/actions/pr-queue`, copied into the install as `gate/`), - so a comment counts exactly when the gate would take it as a lens, and only those posted before the merge by - the queue config's lens authors; a valid override comment before the merge settles a pull request, and so does a - comment of a counted author whose first line starts with one of `waivers` (a person decided, at any time). - `exemptLabels`, `exemptAuthors`. Inline review comments are not read; a pull request with more than 100 files is - judged at the top tier. GitHub: `gh api rate_limit` (free) and one paged GraphQL search per run; below - `minRemaining` (1000) points left this hour it does not search and judges from its cache. The cache (in - `cacheDir`) keeps per pull request only what the verdict needs (paths, lens names, no comment text), so the next - run searches only pull requests updated since the day before: a page or two. A search stopped half-way (a GitHub - error, `maxPages`, the budget) keeps the old search day, so the next run searches those days again; an old, broken - or other-repository cache is read as empty and a newer one is never overwritten. Its findings name the pull - request (`#N`). Never fixes: a review is done by people. + so a comment counts exactly when the gate would take it as a lens, and only those posted by the queue config's + lens authors; a valid override comment before the merge settles a pull request, and so does a comment of a + counted author whose first line starts with one of `waivers` (a person decided, at any time; anyone the queue + counts for lenses can waive, the pull request's own author too). `exemptLabels`, `exemptAuthors`. Inline review + comments are not read; a pull request with more than 100 files is judged at the top tier (with the gate's + `review` block: as critical). + Findings: `review-tiers.skipped` (warn) no lens at all before the merge; `review-tiers.short` lenses before the + merge, but not the ones its tier asks for (warn at the top tier or critical, else info); `review-tiers.late` + (info) the lenses before and after the merge together are enough: reviewing a pull request after its merge + clears the warning and leaves this note. + GitHub: `gh api rate_limit` (free) and one paged GraphQL search per run (`maxPages`, 8; give the check about 10 + seconds a page in its `timeoutSeconds`); below `minRemaining` (1000) points left this hour it does not search and + judges from its cache. The cache (in `cacheDir`) keeps per pull request only what the verdict needs (paths, lens + names, no comment text), so the next run searches only pull requests updated since the day before: a page or two. + A search cut off half-way (`maxPages`, the budget) is a `review-tiers.partial` warning; the cache keeps where it + stopped, and the next runs go on from there (older pull requests first) until every pull request in the window was + read, then search from the new day. A GitHub error fails the check and writes nothing; a page GitHub cannot answer + is asked again once with fewer pull requests. An old, broken or other-repository cache, or one written by other + gate code (a kit upgrade), is read as empty, a broken resume point is dropped, and a newer cache is never + overwritten. Its findings name the pull request (`#N`). Never fixes: a review is done by people. ## Report issue diff --git a/fork-kit/gardener/checks/review-tiers b/fork-kit/gardener/checks/review-tiers index 3b0d24dc929c5..e5bbe083c5321 100755 --- a/fork-kit/gardener/checks/review-tiers +++ b/fork-kit/gardener/checks/review-tiers @@ -8,8 +8,7 @@ never copied: a lens comment counts here exactly when the gate would read it as does not judge: it looks back at pull requests that are already merged (merged past the gate, by an admin or before the rules existed), and at tiers that the project keeps outside the gate config. -Options: - repo OWNER/REPO (default: the project's repo) +Options (the repository is always the project's own "repo": the report masks and links `#N` against it): branch the base branch of the merged pull requests (default: the root's origin/HEAD branch, else main) days how far back, in days (default 7, at most 90) base the git ref the project files below are read from (default origin/HEAD, else origin/main, else main) @@ -21,8 +20,10 @@ Options: exemptAuthors [login]: pull requests of these authors are not judged waivers [text]: a comment whose first line starts with one of these (any case), by an author the queue config counts for lenses and posted at any time, even after the merge, settles the pull request: a person - decided it needed no (more) review - maxPages search pages of 20 pull requests (default 8, at most 25) + decided it needed no (more) review. Anyone the queue config counts for lenses can waive, the pull + request's own author included (an agent that posts as such an account too) + maxPages search pages of 20 pull requests per run (default 8, at most 25); a page takes up to about 10 s, so + the check's timeoutSeconds must cover maxPages x 10 s minRemaining the GraphQL budget left this hour below which the check does not search (default 1000) "tiers": { @@ -40,16 +41,28 @@ A pull request's tier is the highest tier of its changed paths. It passes when i names (the gate's lens_key) and, per "lenses" entry, at least "count" names that match "match" (a regex, any case), or when a valid override comment of the queue config (its prefix, by its author association, unedited) was posted before it merged. With the review block instead: the gate's review_judge gives its weight and the lens names its -rules require, and min_lenses its count. Only comments and reviews posted before the merge count; a lens report -that the gate would not take as a read (edited, hidden, a short sha) still counts here, since it shows the review -was done. Inline review comments are not read. A tier no "requires" entry names asks for nothing. +rules require, and min_lenses its count. A pull request with more paths than one page shows (100) is judged at the +top tier (critical) for the lens count. A lens report that the gate would not take as a read (edited, hidden, a +short sha) still counts here, since it shows the review was done. Inline review comments are not read. A tier no +"requires" entry names asks for nothing. + +Findings: `review-tiers.skipped` (warn): no lens at all before the merge; `review-tiers.short` (warn at the top tier +or critical, else info): lenses before the merge, but not the ones its tier asks for; `review-tiers.late` (info): +the lenses it asks for came only after the merge (the review was done, late). A review after the merge settles the +warning, as the fix hint says. GitHub: one `gh api rate_limit` (free) and one GraphQL search per run (paged), cached in the check's cache folder (the context's "cacheDir"): a run searches only pull requests updated since the day before the last search, so the next day's run costs a page or two. The facts of each merged pull request are cached, and the verdicts are worked out -again each run with the current tiers. A run that stops half-way (a GitHub error, a page past minRemaining) writes -no new search day, so the next run searches the same days again. Old, broken or other-version cache files are read -as empty; a newer one is never overwritten. A dry run reads the cache but writes nothing. +again each run with the current tiers. A search cut off by maxPages or minRemaining remembers where it stopped (the +oldest "updated" time it read: the search is newest first) and the next run goes on from there (that second +included, so the pull requests updated in it are read again) before it searches anything newer, so a busy window is +read in full over a few runs (`review-tiers.partial`, warn, until then); only when a whole page shares one second does +it step one second past it. A run +that fails (a GitHub error) writes nothing, so the next run repeats it. Old, broken or other-version cache files are +read as empty, a broken resume point is dropped (the whole window is searched again); a newer cache is never +overwritten. The cache is keyed by the gate's code too, so a kit upgrade that reads lenses otherwise starts afresh. +A dry run reads the cache but writes nothing. """ import datetime, hashlib, json, os, re, subprocess, sys @@ -68,6 +81,7 @@ import review_glob # noqa: E402 import review_judge # noqa: E402 CACHE_VERSION = 1 +GATE_FILES = ('config.py', 'lens.py', 'review_config.py', 'review_glob.py', 'review_judge.py') PAGE = 20 MAX_FILES = 100 MAX_COMMENTS = 100 @@ -81,7 +95,7 @@ QUERY = '''query($q: String!, $first: Int!, $after: String) { search(query: $q, type: ISSUE, first: $first, after: $after) { pageInfo { hasNextPage endCursor } nodes { ... on PullRequest { - number mergedAt + number mergedAt updatedAt author { login __typename } labels(first: 50) { nodes { name } } files(first: %d) { totalCount nodes { path } } @@ -264,7 +278,7 @@ def read_cache(path, key): return data, False -FACT_KEYS = {'mergedAt': str, 'author': str, 'bot': bool, 'labels': list, 'paths': list, 'pathsComplete': bool, +FACT_KEYS = {'mergedAt': str, 'author': str, 'labels': list, 'paths': list, 'pathsComplete': bool, 'commentsComplete': bool} READ_KEYS = {'lenses': list, 'lensesAfter': list, 'override': bool, 'waived': bool, 'approvals': int} @@ -287,6 +301,33 @@ def good_day(day, upto): return False +STAMP = re.compile(r'[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z') + + +def good_resume(r, upto): + """Where a cut-off search stopped: {"day": the day it began, "since": its lower "updated" day or "", "before": + the oldest "updated" time it read}.""" + return isinstance(r, dict) and set(r) == {'day', 'since', 'before'} and good_day(r['day'], upto) \ + and (r['since'] == '' or good_day(r['since'], r['day'])) and isinstance(r['before'], str) \ + and bool(STAMP.fullmatch(r['before'])) and r['before'][:10] <= upto + + +def second_before(stamp): + t = datetime.datetime.strptime(stamp, '%Y-%m-%dT%H:%M:%SZ') - datetime.timedelta(seconds=1) + return t.strftime('%Y-%m-%dT%H:%M:%SZ') + + +def gate_hash(): + h = hashlib.sha256() + for name in GATE_FILES: + try: + with open(os.path.join(GATE, name), 'rb') as f: + h.update(name.encode() + b'\0' + f.read() + b'\0') + except OSError: + h.update(name.encode() + b'\0missing\0') + return h.hexdigest() + + def write_cache(path, data): os.makedirs(os.path.dirname(path), mode=0o700, exist_ok=True) tmp = f'{path}.tmp-{os.getpid()}' @@ -352,7 +393,6 @@ def facts(pr, review, override, waivers): return {'comments': keep, 'reviews': rs, lens.REVIEW_FLAGS: flags} out = {'mergedAt': merged, 'author': author.get('login') or '', - 'bot': author.get('__typename') == 'Bot', 'labels': sorted({(n or {}).get('name') or '' for n in (pr.get('labels') or {}).get('nodes') or []} - {''}), 'paths': [n['path'] for n in (pr.get('files') or {}).get('nodes') or [] if (n or {}).get('path')], 'pathsComplete': ((pr.get('files') or {}).get('totalCount') or 0) @@ -373,29 +413,50 @@ def facts(pr, review, override, waivers): return out -def search(gh, query, max_pages, min_left): - """([pull request nodes], complete, why not complete). complete is False when the pages ran out or the budget fell - too low.""" - nodes, after = [], None - for _ in range(max_pages): - args = ['graphql', '-f', f'query={QUERY}', '-f', f'q={query}', '-F', f'first={PAGE}'] - if after: - args += ['-f', f'after={after}'] - got = gh_json(gh, args) - if not isinstance(got, dict) or got.get('errors') or not isinstance(got.get('data'), dict): - msgs = [e.get('message', '') for e in got.get('errors') or [] if isinstance(e, dict)] \ - if isinstance(got, dict) else [] - fail(f'gh api graphql: {"; ".join(msgs)[:200] or "no data in the answer"}') - s = got['data'].get('search') or {} - nodes += [n for n in s.get('nodes') or [] if isinstance(n, dict) and isinstance(n.get('number'), int)] +def graphql_page(gh, query, first, after): + args = ['graphql', '-f', f'query={QUERY}', '-f', f'q={query}', '-F', f'first={first}'] + if after: + args += ['-f', f'after={after}'] + got = gh_json(gh, args) + if not isinstance(got, dict) or got.get('errors') or not isinstance(got.get('data'), dict): + msgs = [e.get('message', '') for e in got.get('errors') or [] if isinstance(e, dict)] \ + if isinstance(got, dict) else [] + return None, '; '.join(msgs)[:200] or 'no data in the answer' + return got['data'], None + + +def search(gh, query, pages, min_left): + """A dict: nodes, complete, why (not complete), used (pages), oldest (the oldest "updated" time read, or None). + complete is False when the pages ran out or the budget fell too low. A page GitHub cannot answer (too much + comment text for one query: "timeout", "something went wrong") is asked again once with fewer pull requests.""" + out = {'nodes': [], 'complete': False, 'why': None, 'used': 0, 'oldest': None} + after, first = None, PAGE + while out['used'] < pages: + data, err = graphql_page(gh, query, first, after) + if err is not None and first == PAGE: + note(f'gh api graphql: {err}: asking again for {PAGE // 4} pull requests a page') + first = PAGE // 4 + data, err = graphql_page(gh, query, first, after) + if err is not None: + fail(f'gh api graphql: {err}') + out['used'] += 1 + s = data.get('search') or {} + got = [n for n in s.get('nodes') or [] if isinstance(n, dict) and isinstance(n.get('number'), int)] + out['nodes'] += got + stamps = [n['updatedAt'] for n in got if isinstance(n.get('updatedAt'), str) and STAMP.fullmatch(n['updatedAt'])] + if stamps: + out['oldest'] = min(stamps + ([out['oldest']] if out['oldest'] else [])) page = s.get('pageInfo') or {} if not page.get('hasNextPage'): - return nodes, True, None + out['complete'] = True + return out after = page.get('endCursor') - left = (got['data'].get('rateLimit') or {}).get('remaining') + left = (data.get('rateLimit') or {}).get('remaining') if isinstance(left, int) and left < min_left: - return nodes, False, f'the GraphQL budget fell to {left} (under minRemaining {min_left}) while searching' - return nodes, False, f'more than {max_pages} pages of pull requests (maxPages)' + out['why'] = f'the GraphQL budget fell to {left} (under minRemaining {min_left}) while searching' + return out + out['why'] = f'more than {pages} page(s) of pull requests left for this run (maxPages)' + return out # --- verdicts ------------------------------------------------------------------------------------------------------ @@ -406,8 +467,9 @@ def some(names): else 'none' -def verdict_tiers(f, tiers, registry): - """None when it had enough review, else (what it needed, what was missing).""" +def verdict_tiers(f, lenses, tiers, registry): + """None when lenses (names) and its approvals are enough review, else (what it needed, what was missing, top: + the highest level).""" paths = f['paths'] tier = max([path_tier(tiers, registry, p) for p in paths] or [tiers['unmatched']]) if not f['pathsComplete']: @@ -416,40 +478,43 @@ def verdict_tiers(f, tiers, registry): if not need: return None min_lenses, named = need - have = len(f['lenses']) + (f['approvals'] if tiers['approvals'] else 0) + have = len(lenses) + (f['approvals'] if tiers['approvals'] else 0) missing = [] if have < min_lenses: missing.append(f'{min_lenses} lens(es), found {have}') for name, rx, count in named: - n = sum(1 for k in f['lenses'] if rx.search(k)) + n = sum(1 for k in lenses if rx.search(k)) if n < count: missing.append(f'{count} {name} lens(es), found {n}') - return (f'tier {tier}', missing) if missing else None + return (f'tier {tier}', missing, tier == tiers['top']) if missing else None -def verdict_rules(f, rules, config_path): +def verdict_rules(f, lenses, rules, config_path): try: j = review_judge.judge(rules, [('M', (p,)) for p in f['paths']], config_path) except review_judge.JudgeError as e: - return 'the review rules', [f'its paths cannot be judged ({e})'[:300]] - have = set(f['lenses']) + return 'the review rules', [f'its paths cannot be judged ({e})'[:300]], True + weight, need = j.weight, getattr(rules.min_lenses, j.weight) + if not f['pathsComplete']: # the paths past the first page may ask for more: the heaviest count + weight, need = 'critical', max(need, rules.min_lenses.critical) + have = set(lenses) missing = [name for name in j.lenses if lens.lens_key(name) not in have] - need = getattr(rules.min_lenses, j.weight) out = [f'lens {some(missing)}'] if missing else [] if len(have) < need: out.append(f'{need} lens(es), found {len(have)}') - return (j.weight, out) if out else None + return (weight, out, weight == 'critical') if out else None def main(): ctx = read_context() opt = ctx['options'] - _known(opt, ('repo', 'branch', 'days', 'base', 'queueConfig', 'tiers', 'exemptLabels', 'exemptAuthors', + if 'repo' in opt: # the report masks and links `#N` against the project's repo: another one would leak + fail('there is no "repo" option: the check reads the project\'s own repository (its "repo")') + _known(opt, ('branch', 'days', 'base', 'queueConfig', 'tiers', 'exemptLabels', 'exemptAuthors', 'waivers', 'maxPages', 'minRemaining'), 'options') - repo = opt.get('repo') or ctx['project']['repo'] + repo = ctx['project']['repo'] if not repo: - emit('review-tiers.no-repo', 'info', 'no repository to read: the project has no "repo" and the check no ' - '"repo"') + emit('review-tiers.no-repo', 'info', 'no repository to read: the project has no "repo"') return if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9-]*/[A-Za-z0-9._-]+', repo): fail('repo must be OWNER/REPO') @@ -490,9 +555,10 @@ def main(): today = datetime.date.fromisoformat(ctx['today']) start = (today - datetime.timedelta(days=days - 1)).isoformat() # what decides the cached facts: whose comments count, the waivers (the verdicts are worked out again each run) + # and the gate's code that read them (a kit upgrade that reads lens comments otherwise starts afresh) key = hashlib.sha256(json.dumps([repo.lower(), branch, list(review.bots), list(review.lens_associations), - review.override_re.pattern, review.override_association, list(waivers)]) - .encode()).hexdigest() + review.override_re.pattern, review.override_association, list(waivers), + gate_hash()]).encode()).hexdigest() cache_dir = ctx.get('cacheDir') or '' dry = ctx.get('dryRun') is True path = os.path.join(cache_dir, 'cache.json') if cache_dir else '' @@ -500,31 +566,60 @@ def main(): usable = bool(cache) and good_day(cache.get('searchedDay'), ctx['today']) \ and good_day(cache.get('from'), start) # a wider window than the cache's: search all of it prs = dict(cache['prs']) if usable else {} - since, searched = start, None - if usable: - last = (datetime.date.fromisoformat(cache['searchedDay']) - datetime.timedelta(days=1)).isoformat() - since, searched = max(start, last), cache['searchedDay'] - + searched = cache['searchedDay'] if usable else None + resume = cache.get('resume') if usable else None + if resume is not None and not good_resume(resume, ctx['today']): + note('the resume point in the cache is broken: dropped') + resume = None + + def since_day(): + if not searched: + return start + return max(start, (datetime.date.fromisoformat(searched) - datetime.timedelta(days=1)).isoformat()) + + base_q = f'repo:{repo} is:pr is:merged base:{branch} merged:>={start} sort:updated-desc' left = graphql_left(ctx['gh']) if left < min_left: emit('review-tiers.budget', 'info', f'not searched today: the GraphQL budget left this hour is {left}, under ' f'minRemaining {min_left}; judged from the cache only', '', 'nothing to do: the next run searches') else: - q = f'repo:{repo} is:pr is:merged base:{branch} merged:>={start} sort:updated-desc' - if since > start: - q += f' updated:>={since}' - nodes, complete, why = search(ctx['gh'], q, max_pages, min_left) - for n in nodes: - prs[str(n['number'])] = facts(n, review, has_override, waivers) - if complete: - searched = ctx['today'] - else: - emit('review-tiers.partial', 'info', f'the search stopped early: {why}; the next run searches the same ' - 'days again', '', 'raise maxPages or lower days if this repeats') + pages, why = max_pages, None + if resume: # first go on where a cut-off search stopped: the older pull requests it did not reach + before = resume['before'][:-1] + '+00:00' + lower = resume['since'] if resume['since'] > start else '' + q = base_q + (f' updated:{lower}T00:00:00+00:00..{before}' if lower else f' updated:<={before}') + got = search(ctx['gh'], q, pages, min_left) + for n in got['nodes']: + prs[str(n['number'])] = facts(n, review, has_override, waivers) + pages -= got['used'] + if got['complete']: + searched, resume = resume['day'], None + else: + why = got['why'] + resume = dict(resume, before=got['oldest'] if got['oldest'] and got['oldest'] < resume['before'] + else second_before(resume['before'])) # a whole page in one second: step past it + if resume is None and pages > 0: + since = since_day() + got = search(ctx['gh'], base_q + (f' updated:>={since}' if since > start else ''), pages, min_left) + for n in got['nodes']: + prs[str(n['number'])] = facts(n, review, has_override, waivers) + if got['complete']: + searched = ctx['today'] + else: + why = got['why'] + if got['oldest']: + resume = {'day': ctx['today'], 'since': since if since > start else '', 'before': got['oldest']} + if why: + emit('review-tiers.partial', 'warn', f'the search stopped early: {why}; pull requests it did not reach ' + 'are not judged yet, the next run goes on where this one stopped', '', + 'nothing to do if it clears in a run or two; else raise maxPages (and the timeout) or lower days') prs = {k: v for k, v in prs.items() if isinstance(v, dict) and (v.get('mergedAt') or '')[:10] >= start} if path and not dry and not newer: - write_cache(path, {'version': CACHE_VERSION, 'key': key, 'prs': prs, 'from': start, - 'searchedDay': searched or '1970-01-01'}) + data = {'version': CACHE_VERSION, 'key': key, 'prs': prs, 'from': start, + 'searchedDay': searched or '1970-01-01'} + if resume: + data['resume'] = resume + write_cache(path, data) for number in sorted(prs, key=int): f = prs[number] @@ -536,10 +631,18 @@ def main(): continue if f.get('override') or f.get('waived'): continue - got = verdict_tiers(f, tiers, registry) if tiers else verdict_rules(f, cfg.review, qpath) + + def verdict(names): + return verdict_tiers(f, names, tiers, registry) if tiers else verdict_rules(f, names, cfg.review, qpath) + got = verdict(f['lenses']) if not got: continue - level, missing = got + level, missing, top = got + if f['lensesAfter'] and not verdict(sorted(set(f['lenses']) | set(f['lensesAfter']))): + emit('review-tiers.late', 'info', f'reviewed only after the merge: {level} asked for {"; ".join(missing)} ' + f'before it (lenses after the merge: {some(f["lensesAfter"])})', f'#{number}', + 'nothing to do for it: the review is done') + continue extra = [] if not f.get('pathsComplete', True): extra.append(f'it changed more than {MAX_FILES} files') @@ -547,10 +650,14 @@ def main(): extra.append(f'only its last {MAX_COMMENTS} comments and {MAX_REVIEWS} reviews were read') if f.get('lensesAfter'): extra.append(f'lens after the merge: {some(f["lensesAfter"])}') - emit('review-tiers.skipped', 'warn', - f'merged with less review than {level} asks: needs {"; ".join(missing)} (lenses before the merge: ' - f'{some(f.get("lenses") or [])})' + (f'; {"; ".join(extra)}' if extra else ''), - f'#{number}', 'review it now (a lens comment on the pull request), or note on it why it needed none') + none = not f['lenses'] and not (tiers and tiers['approvals'] and f['approvals']) + hint = 'review it now: lens comments on the pull request settle this, even after the merge' + if waivers: + hint += f'; if it needed no (more) review, a comment starting "{opt["waivers"][0].strip()}: why"' + emit('review-tiers.skipped' if none else 'review-tiers.short', 'warn' if none or top else 'info', + f'merged with {"no review" if none else "less review than " + level + " asks"}: needs ' + f'{"; ".join(missing)}' + ('' if none else f' (lenses before the merge: {some(f["lenses"])})') + + (f' ({level})' if none else '') + (f'; {"; ".join(extra)}' if extra else ''), f'#{number}', hint) if __name__ == '__main__': diff --git a/fork-kit/gardener/lib/gardener/judge.py b/fork-kit/gardener/lib/gardener/judge.py index 4b5ef9d5792b3..eabebbb24e9ce 100644 --- a/fork-kit/gardener/lib/gardener/judge.py +++ b/fork-kit/gardener/lib/gardener/judge.py @@ -21,13 +21,26 @@ MAX_RESPONSE = 1 << 20 # bytes of the HTTP answer read at most +def cut_read_at(resp, left): + """Let the next read of resp wait at most left seconds: the socket timeout set when the call started would let + one stalled read run on that long again after the deadline.""" + sock = getattr(getattr(getattr(resp, 'fp', None), 'raw', None), '_sock', None) + if sock is not None: + try: + sock.settimeout(max(0.05, left)) + except OSError: + pass + + def read_all(resp, deadline): """The response body (at most MAX_RESPONSE bytes), or TimeoutError once the monotonic deadline passes: the socket timeout alone bounds each read, not a server that trickles bytes.""" body = b'' while len(body) < MAX_RESPONSE: - if time.monotonic() > deadline: + left = deadline - time.monotonic() + if left <= 0: raise TimeoutError('the answer took too long') + cut_read_at(resp, left) chunk = resp.read1(min(65536, MAX_RESPONSE - len(body))) if not chunk: break diff --git a/fork-kit/gardener/tests/checks.test.py b/fork-kit/gardener/tests/checks.test.py index 6ba937eaf2d48..4ccfcac2929c9 100644 --- a/fork-kit/gardener/tests/checks.test.py +++ b/fork-kit/gardener/tests/checks.test.py @@ -4,7 +4,7 @@ python3 -I -B fork-kit/gardener/tests/checks.test.py """ -import hashlib, json, os, subprocess, sys, unittest +import hashlib, json, os, shutil, subprocess, sys, unittest from unittest import mock sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) @@ -19,10 +19,11 @@ class Check(gf.Temp): env = {} - def run_check(self, name, options=None, fix=False, repo='example-owner/app', gh='gh', code=0, **more): + def run_check(self, name, options=None, fix=False, repo='example-owner/app', gh='gh', code=0, script=None, + **more): ctx = {'version': contract.VERSION, 'project': {'name': 'example', 'repo': repo, 'root': self.root}, 'check': name, 'options': options or {}, 'fix': fix, 'today': '2026-11-23', 'gh': gh, **more} - r = subprocess.run([sys.executable, '-I', '-B', os.path.join(gf.CHECKS, name)], input=json.dumps(ctx), + r = subprocess.run([sys.executable, '-I', '-B', script or os.path.join(gf.CHECKS, name)], input=json.dumps(ctx), capture_output=True, text=True, cwd=self.root, timeout=120, env=dict(os.environ, **self.env)) self.assertEqual(r.returncode, code, r.stderr) @@ -412,8 +413,8 @@ def approval(when='2026-11-20T11:00:00Z', assoc='OWNER', rid='r1'): def pr(number, paths, comments=(), reviews=(), merged=MERGED, labels=(), author='dev-one', files_total=None, - comments_total=None): - return {'number': number, 'mergedAt': merged, 'author': {'login': author, '__typename': 'User'}, + comments_total=None, updated='2026-11-20T12:30:00Z'): + return {'number': number, 'mergedAt': merged, 'updatedAt': updated, 'author': {'login': author, '__typename': 'User'}, 'labels': {'nodes': [{'name': n} for n in labels]}, 'files': {'totalCount': len(paths) if files_total is None else files_total, 'nodes': [{'path': p} for p in paths]}, @@ -442,13 +443,15 @@ def repo(self, queue=None, modules=None): self.git(self.root, 'add', '-A') self.git(self.root, 'commit', '-q', '--allow-empty', '-m', 'files') - def fake_gh(self, pages, remaining=4000, fail_page=None): - """pages: lists of pull request nodes, one per search page. fail_page: that page fails (1 = the first).""" + def fake_gh(self, pages, remaining=4000, fail_page=None, fail_first=()): + """pages: lists of pull request nodes, one per search page. fail_page: that page fails (1 = the first). + fail_first: pages of these sizes get a GraphQL error. A query with an "updated" range (a resumed search) gets + only the nodes in it, paged again at the same size (the search is newest first, like GitHub's).""" data = os.path.join(self.tmp, 'gh-pages.json') with open(data, 'w') as f: json.dump(pages, f) return self.script('gh', f""" - import json, sys + import json, re, sys a = sys.argv[1:] with open({self.log!r}, 'a') as log: log.write(json.dumps(a) + '\\n') @@ -461,7 +464,16 @@ def fake_gh(self, pages, remaining=4000, fail_page=None): if page + 1 == {fail_page!r}: sys.stderr.write('HTTP 502: Bad Gateway\\n') sys.exit(1) + if int(opts['first']) in {tuple(fail_first)!r}: + print(json.dumps({{'errors': [{{'message': 'Something went wrong while executing your query.'}}]}})) + sys.exit(0) pages = json.load(open({data!r})) + m = re.search(r'updated:(?:<=|(\\S+)\\.\\.)(\\S+)', opts['q']) + if m: + lo, hi = [x and x.replace('+00:00', 'Z') for x in m.groups()] + size = max([len(p) for p in pages] + [1]) + keep = [n for p in pages for n in p if n['updatedAt'] <= hi and (not lo or n['updatedAt'] >= lo)] + pages = [keep[i:i + size] for i in range(0, len(keep), size)] or [[]] more = page + 1 < len(pages) print(json.dumps({{'data': {{'rateLimit': {{'cost': 1, 'remaining': {remaining} - page}}, 'search': {{'pageInfo': {{'hasNextPage': more, 'endCursor': 'c%d' % (page + 1)}}, @@ -484,7 +496,7 @@ def check(self, gh, options=None, code=0, **more): return self.run_check('review-tiers', opts, gh=gh, code=code, **more) def by_pr(self, found): - return {f['where']: f for f in found if f['id'] == 'review-tiers.skipped'} + return {f['where']: f for f in found if f['id'] in ('review-tiers.skipped', 'review-tiers.short')} # --- verdicts -------------------------------------------------------------------------------------------------- @@ -508,7 +520,9 @@ def test_each_tier_asks_for_its_lenses(self): self.assertIn('tier 2 asks: needs 2 lens(es), found 1 (lenses before the merge: correctness)', got['#2']['text']) self.assertIn('tier 3 asks: needs 2 data integrity lens(es), found 1', got['#4']['text']) self.assertIn('needs 1 correctness lens(es), found 0', got['#8']['text']) - self.assertTrue(all(f['severity'] == 'warn' for f in got.values())) + self.assertEqual({w: (f['id'], f['severity']) for w, f in got.items()}, # a kind missing: warn at the top + {'#2': ('review-tiers.short', 'info'), '#4': ('review-tiers.short', 'warn'), + '#8': ('review-tiers.short', 'info')}) def test_only_counted_authors_and_comments_before_the_merge_count(self): gh = self.fake_gh([[ @@ -517,9 +531,42 @@ def test_only_counted_authors_and_comments_before_the_merge_count(self): pr(3, ['mods/chat/C.java'], [lens_post('correctness'), lens_post('design', when='2026-11-21T09:00:00Z')]), pr(4, ['mods/chat/C.java'], [lens_post('correctness'), lens_post('design', assoc='MEMBER')]), ]]) - got = self.by_pr(self.check(gh)) - self.assertEqual(sorted(got), ['#1', '#2', '#3']) - self.assertIn('lens after the merge: design', got['#3']['text']) + found = self.check(gh) + self.assertEqual(sorted(self.by_pr(found)), ['#1', '#2']) + late = [f for f in found if f['id'] == 'review-tiers.late'] # #3: enough only with the late lens + self.assertEqual([(f['where'], f['severity']) for f in late], [('#3', 'info')]) + self.assertIn('lenses after the merge: design', late[0]['text']) + + def test_a_review_after_the_merge_settles_the_warning_as_the_hint_says(self): + late = dict(when='2026-11-21T09:00:00Z') + gh = self.fake_gh([[ + pr(1, ['mods/chat/C.java'], [lens_post('correctness', **late), lens_post('design', **late)]), # enough + pr(2, ['mods/chat/C.java'], [lens_post('design', **late)]), # still not enough + pr(3, ['mods/shop/S.java'], [lens_post(n, **late) for n in ('correctness', 'data integrity 1', + 'data-integrity-2')]), + ]]) + found = self.check(gh, {'tiers': TIERS, 'waivers': ['Retro waiver']}) + self.assertEqual([(f['id'], f['where'], f['severity']) for f in found], + [('review-tiers.late', '#1', 'info'), ('review-tiers.skipped', '#2', 'warn'), + ('review-tiers.late', '#3', 'info')]) + self.assertIn('lens after the merge: design', found[1]['text']) + self.assertEqual(found[1]['fix'], 'review it now: lens comments on the pull request settle this, even after ' + 'the merge; if it needed no (more) review, a comment starting "Retro ' + 'waiver: why"') + + def test_no_lens_at_all_is_told_apart_from_a_kind_missing(self): + gh = self.fake_gh([[ + pr(1, ['mods/chat/C.java']), + pr(2, ['mods/chat/C.java'], [lens_post('design')]), + pr(3, ['mods/shop/S.java']), + pr(4, ['mods/chat/C.java'], reviews=[approval()]), + ]]) + got = {f['where']: (f['id'], f['severity']) for f in self.check(gh)} + self.assertEqual(got, {'#1': ('review-tiers.skipped', 'warn'), '#2': ('review-tiers.short', 'info'), + '#3': ('review-tiers.skipped', 'warn'), '#4': ('review-tiers.skipped', 'warn')}) + os.remove(self.log) + got = {f['where']: f['id'] for f in self.check(gh, {'tiers': dict(TIERS, approvalsCount=True)}, cacheDir='')} + self.assertEqual(got['#4'], 'review-tiers.short') # a counted approval is some review def test_approvals_count_only_when_asked(self): node = pr(1, ['mods/chat/C.java'], [lens_post('correctness')], [approval()]) @@ -564,7 +611,13 @@ def test_the_gate_review_block_judges_without_tiers(self): got = self.by_pr(self.check(gh, {})) self.assertEqual(sorted(got), ['#1', '#4']) self.assertIn('less review than critical asks: needs lens state; 2 lens(es), found 1', got['#1']['text']) - self.assertIn('less review than normal asks: needs lens code', got['#4']['text']) + self.assertEqual(got['#4']['text'], 'merged with no review: needs lens code; 1 lens(es), found 0 (normal)') + + def test_too_many_files_is_judged_critical_by_the_review_block_too(self): + self.repo(queue=dict(QUEUE, review=REVIEW)) + got = self.by_pr(self.check(self.fake_gh([[pr(1, ['src/a.ts'], [lens_post('code')], files_total=300)]]), {})) + self.assertIn('less review than critical asks: needs 2 lens(es), found 1', got['#1']['text']) + self.assertEqual(got['#1']['severity'], 'warn') def test_the_registry_and_queue_config_come_from_git_not_the_working_tree(self): self.write('modules.json', json.dumps({'modules': [{'id': 'chat', 'paths': ['mods/chat'], 'tier': 0}]})) @@ -581,6 +634,8 @@ def test_no_rules_no_repo_and_bad_options(self): for opts, why in (({'tiers': dict(TIERS, colour=1)}, "unknown key 'colour'"), ({'tiers': dict(TIERS, requires={})}, 'must name at least one tier'), ({'tiers': TIERS, 'days': 0}, 'days must be'), + ({'tiers': TIERS, 'repo': 'other-owner/secret'}, 'there is no "repo" option'), + ({'tiers': TIERS, 'repo': 'example-owner/app'}, 'there is no "repo" option'), ({'tiers': TIERS, 'queueConfig': 'gone.json'}, 'not in the project root'), ({'tiers': dict(TIERS, registry=dict(TIERS['registry'], file='gone.json'))}, 'not in the project root')): @@ -610,16 +665,78 @@ def test_a_low_budget_searches_nothing_and_judges_the_cache(self): self.assertEqual(self.ids(found), ['review-tiers.budget', 'review-tiers.skipped']) self.assertEqual(self.queries(), []) - def test_too_many_pages_is_partial_and_the_next_run_searches_the_days_again(self): - pages = [[pr(i, ['mods/chat/C.java'])] for i in range(1, 4)] - found = self.check(self.fake_gh(pages), {'tiers': TIERS, 'maxPages': 2}) - self.assertIn('review-tiers.partial', self.ids(found)) - self.assertEqual(sorted(self.by_pr(found)), ['#1', '#2']) - with open(os.path.join(self.cache, 'cache.json')) as f: - self.assertEqual(json.load(f)['searchedDay'], '1970-01-01') + def test_a_cut_off_search_goes_on_where_it_stopped_until_every_pull_request_is_judged(self): + """Newest first, one page a run: three runs read three pages (each run reads its cut-off second again), then the + next day searches only what changed.""" + nodes = [pr(i, ['mods/chat/C.java'], updated=f'2026-11-22T{20 - i}:00:00Z') for i in range(1, 8)] + pages = [nodes[:3], nodes[3:6], nodes[6:]] + opts = {'tiers': TIERS, 'maxPages': 1} + seen = [] + for run in range(3): + if os.path.exists(self.log): + os.remove(self.log) + found = self.check(self.fake_gh(pages), opts) + seen.append((sorted(self.by_pr(found)), [f['severity'] for f in found if f['id'] == 'review-tiers.partial'], + self.queries())) + base = 'repo:example-owner/app is:pr is:merged base:main merged:>=2026-11-17 sort:updated-desc' + self.assertEqual(seen, [ + (['#1', '#2', '#3'], ['warn'], [base]), + (['#1', '#2', '#3', '#4', '#5'], ['warn'], [base + ' updated:<=2026-11-22T17:00:00+00:00']), + ([f'#{i}' for i in range(1, 8)], [], [base + ' updated:<=2026-11-22T15:00:00+00:00'])]) + with open(self.cache_file()) as f: + data = json.load(f) + self.assertEqual((data['searchedDay'], 'resume' in data), ('2026-11-23', False)) + os.remove(self.log) + self.check(self.fake_gh([[]]), opts, today='2026-11-24') + self.assertEqual(self.queries(), [base.replace('11-17', '11-18') + ' updated:>=2026-11-22']) + + def test_a_resumed_search_keeps_its_lower_day_and_a_finished_one_searches_on_in_the_same_run(self): + self.check(self.fake_gh([[pr(1, ['docs/a.md'])]]), today='2026-11-20') # search day 11-20 + os.remove(self.log) + pages = [[pr(i, ['docs/a.md'], updated=f'2026-11-2{3 - i}T10:00:00Z')] for i in range(1, 3)] + self.check(self.fake_gh(pages), {'tiers': TIERS, 'maxPages': 1}) + with open(self.cache_file()) as f: + self.assertEqual(json.load(f)['resume'], {'day': '2026-11-23', 'since': '2026-11-19', + 'before': '2026-11-22T10:00:00Z'}) os.remove(self.log) - self.check(self.fake_gh(pages), {'tiers': TIERS, 'maxPages': 5}) - self.assertNotIn('updated:', self.queries()[0]) # the whole window again + self.check(self.fake_gh(pages), {'tiers': TIERS, 'maxPages': 3}) + self.assertEqual([q.split('sort:updated-desc ')[1] for q in self.queries()], + ['updated:2026-11-19T00:00:00+00:00..2026-11-22T10:00:00+00:00'] * 2 + + ['updated:>=2026-11-22']) + + def test_a_page_of_one_second_does_not_stop_the_search_for_ever(self): + same = '2026-11-22T10:00:00Z' + pages = [[pr(1, ['docs/a.md'], updated=same), pr(2, ['docs/a.md'], updated=same)], + [pr(3, ['docs/a.md'], updated='2026-11-21T10:00:00Z')]] + for run in range(2): + self.check(self.fake_gh(pages), {'tiers': TIERS, 'maxPages': 1}) + with open(self.cache_file()) as f: + self.assertEqual(json.load(f)['resume']['before'], '2026-11-22T09:59:59Z') + self.check(self.fake_gh(pages), {'tiers': TIERS, 'maxPages': 1}) + with open(self.cache_file()) as f: + self.assertEqual(sorted(json.load(f)['prs']), ['1', '2', '3']) + + def test_a_broken_resume_point_is_dropped(self): + self.check(self.fake_gh([[]])) + with open(self.cache_file()) as f: + data = json.load(f) + for bad in ({'day': '2026-11-23', 'since': '', 'before': 'yesterday'}, {'day': '2026-11-23'}, [], + {'day': '2026-12-30', 'since': '', 'before': '2026-11-22T10:00:00Z'}): + with self.subTest(bad=bad): + with open(self.cache_file(), 'w') as f: + json.dump(dict(data, resume=bad), f) + os.remove(self.log) + self.check(self.fake_gh([[]])) + self.assertIn('resume point in the cache is broken', self.last_stderr) + self.assertEqual([q.split('sort:updated-desc')[1] for q in self.queries()], [' updated:>=2026-11-22']) + + def test_a_page_github_cannot_answer_is_asked_again_smaller(self): + found = self.check(self.fake_gh([[pr(1, ['mods/chat/C.java'])]], fail_first=[20])) + self.assertEqual(sorted(self.by_pr(found)), ['#1']) + firsts = [dict(x.split('=', 1) for x in c[2:] if '=' in x)['first'] for c in self.calls() if c[1] == 'graphql'] + self.assertEqual(firsts, ['20', '5']) + self.check(self.fake_gh([[]], fail_first=[20, 5]), code=1) + self.assertIn('Something went wrong', self.last_stderr) def test_the_budget_falling_while_searching_stops_the_search(self): pages = [[pr(i, ['docs/a.md'])] for i in range(1, 4)] @@ -666,7 +783,7 @@ def test_stopped_half_way_leaves_the_cache_as_it_was(self): self.assertEqual([n for n in os.listdir(self.cache) if n != 'cache.json'], []) # no temporary file left def test_old_broken_empty_or_other_caches_are_read_as_empty(self): - good = {'mergedAt': MERGED, 'author': 'a', 'bot': False, 'labels': [], 'paths': ['mods/chat/C.java'], + good = {'mergedAt': MERGED, 'author': 'a', 'labels': [], 'paths': ['mods/chat/C.java'], 'pathsComplete': True, 'commentsComplete': True} self.check(self.fake_gh([[]])) with open(self.cache_file()) as f: @@ -704,6 +821,24 @@ def test_a_newer_cache_is_not_used_and_not_overwritten(self): with open(self.cache_file()) as f: self.assertEqual(f.read(), '{"version": 9, "prs": {"1": {}}}') + def test_a_change_to_the_gate_code_starts_the_cache_afresh(self): + """The cache keeps lens names the gate's code read: other code may read other names.""" + kit = os.path.join(self.tmp, 'kit') + shutil.copytree(gf.CHECKS, os.path.join(kit, 'checks')) + shutil.copytree(gf.LIB, os.path.join(kit, 'lib'), ignore=shutil.ignore_patterns('__pycache__')) + shutil.copytree(os.path.join(os.path.dirname(os.path.dirname(gf.KIT)), 'fork-ci', 'actions', 'pr-queue'), + os.path.join(kit, 'gate'), ignore=shutil.ignore_patterns('__pycache__')) + script = os.path.join(kit, 'checks', 'review-tiers') + self.check(self.fake_gh([[]]), script=script) + os.remove(self.log) + self.check(self.fake_gh([[]]), script=script) + self.assertIn('updated:>=', self.queries()[0]) # same code: the cache is used + with open(os.path.join(kit, 'gate', 'lens.py'), 'a') as f: + f.write('\n# a new release\n') + os.remove(self.log) + self.check(self.fake_gh([[]]), script=script) + self.assertNotIn('updated:', self.queries()[0]) # the whole window + def test_a_dry_run_and_no_cache_folder_write_nothing(self): self.check(self.fake_gh([[pr(1, ['mods/chat/C.java'])]]), dryRun=True) self.assertFalse(os.path.exists(self.cache)) @@ -750,9 +885,37 @@ def test_a_check_without_a_context_exits_with_a_message(self): 'review-tiers: too many files is the top tier': ( 'checks/review-tiers', " tier = max(tier, tiers['top'])\n", " pass\n", 'ReviewTiers.test_too_many_files_is_judged_at_the_top_tier'), - 'review-tiers: a partial search does not move the search day': ( - 'checks/review-tiers', " if complete:\n searched = ctx['today']", " searched = ctx['today']", - 'ReviewTiers.test_too_many_pages_is_partial_and_the_next_run_searches_the_days_again'), + 'review-tiers: a cut-off search does not move the search day': ( + 'checks/review-tiers', " if got['complete']:\n searched = ctx['today']", + " if True:\n searched = ctx['today']", 'ReviewTiers.test_a_cut_off_search_goes_on_where_it_stopped_until_every_pull_request_is_judged'), + 'review-tiers: a cut-off search goes on where it stopped': ( + 'checks/review-tiers', ' if resume: # first go on', ' if False: # first go on', 'ReviewTiers.test_a_cut_off_search_goes_on_where_it_stopped_until_every_pull_request_is_judged'), + 'review-tiers: a cut-off search is a warning': ( + 'checks/review-tiers', "emit('review-tiers.partial', 'warn'", "emit('review-tiers.partial', 'info'", 'ReviewTiers.test_a_cut_off_search_goes_on_where_it_stopped_until_every_pull_request_is_judged'), + 'review-tiers: a page of one second is stepped past': ( + 'checks/review-tiers', "else second_before(resume['before']))", "else resume['before'])", + 'ReviewTiers.test_a_page_of_one_second_does_not_stop_the_search_for_ever'), + 'review-tiers: a broken resume point is dropped': ( + 'checks/review-tiers', " if resume is not None and not good_resume(resume, ctx['today']):", + ' if False:', 'ReviewTiers.test_a_broken_resume_point_is_dropped'), + 'review-tiers: a page GitHub cannot answer is asked again smaller': ( + 'checks/review-tiers', ' if err is not None and first == PAGE:', ' if False:', + 'ReviewTiers.test_a_page_github_cannot_answer_is_asked_again_smaller'), + 'review-tiers: a review after the merge settles it': ( + 'checks/review-tiers', " if f['lensesAfter'] and not verdict(", " if False and not verdict(", + 'ReviewTiers.test_a_review_after_the_merge_settles_the_warning_as_the_hint_says'), + 'review-tiers: no lens at all is told apart': ( + 'checks/review-tiers', "emit('review-tiers.skipped' if none else 'review-tiers.short',", + "emit('review-tiers.short',", 'ReviewTiers.test_no_lens_at_all_is_told_apart_from_a_kind_missing'), + 'review-tiers: there is no repo option': ( + 'checks/review-tiers', " if 'repo' in opt: #", ' if False: #', + 'ReviewTiers.test_no_rules_no_repo_and_bad_options'), + 'review-tiers: the gate code is part of the cache key': ( + 'checks/review-tiers', ' gate_hash()]).encode()', + ' ]).encode()', 'ReviewTiers.test_a_change_to_the_gate_code_starts_the_cache_afresh'), + 'review-tiers: too many files is critical by the review block too': ( + 'checks/review-tiers', " if not f['pathsComplete']: # the paths past", ' if False: # the paths past', + 'ReviewTiers.test_too_many_files_is_judged_critical_by_the_review_block_too'), 'review-tiers: a wider window searches all of it': ( 'checks/review-tiers', "and good_day(cache.get('from'), start)", 'and True', 'ReviewTiers.test_a_wider_window_searches_all_of_it'), diff --git a/fork-kit/gardener/tests/report.test.py b/fork-kit/gardener/tests/report.test.py index 15b679cfc09f4..5fac6224047e5 100644 --- a/fork-kit/gardener/tests/report.test.py +++ b/fork-kit/gardener/tests/report.test.py @@ -387,12 +387,12 @@ def test_an_endpoint_that_does_not_speak_http_is_a_note(self): def trickle_server(self, gap): """An HTTP server that sends its headers at once and then one byte of the body every gap seconds: each read - is quick, the whole answer is not.""" + is quick (gap is under the 0.05 s the last reads may wait), the whole answer is not.""" srv = socket.socket() srv.bind(('127.0.0.1', 0)) srv.listen(4) self.addCleanup(srv.close) - body = json.dumps({'choices': [{'message': {'content': 'late'}}]}).encode() + body = json.dumps({'choices': [{'message': {'content': 'late' + ' ' * 300}}]}).encode() def serve(): try: @@ -414,12 +414,42 @@ def serve(): def test_a_slow_model_is_cut_off_at_the_timeout_in_all(self): started = time.monotonic() - got, note = judge.judge(self.model(self.trickle_server(0.2), timeoutSeconds=1), [dict(GOOD, check='c')], + got, note = judge.judge(self.model(self.trickle_server(0.02), timeoutSeconds=1), [dict(GOOD, check='c')], self.root) - self.assertLess(time.monotonic() - started, 4) # not len(body) * 0.2 seconds + self.assertLess(time.monotonic() - started, 4) # not len(body) * 0.02 = 7 seconds self.assertIsNone(got) self.assertIn('model unreachable or no usable answer (TimeoutError)', note) + def test_a_model_that_stalls_near_the_deadline_is_cut_off_at_the_deadline(self): + srv = socket.socket() + srv.bind(('127.0.0.1', 0)) + srv.listen(4) + self.addCleanup(srv.close) + stop = threading.Event() + self.addCleanup(stop.set) + + def serve(): + try: + conn, _ = srv.accept() + except OSError: + return + with conn: + try: + conn.recv(65536) + conn.sendall(b'HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 50\r\n\r\n') + time.sleep(0.8) + conn.sendall(b'{') # one byte, then nothing + stop.wait(10) + except OSError: + return + threading.Thread(target=serve, daemon=True).start() + started = time.monotonic() + got, note = judge.judge(self.model(f'http://127.0.0.1:{srv.getsockname()[1]}/v1', timeoutSeconds=1), + [dict(GOOD, check='c')], self.root) + self.assertLess(time.monotonic() - started, 1.5) # not 0.8 + another whole second + self.assertIsNone(got) + self.assertIn('model unreachable', note) + def test_a_model_that_never_answers_is_cut_off(self): srv = socket.socket() srv.bind(('127.0.0.1', 0)) @@ -513,8 +543,11 @@ def test_the_judgment_is_masked_like_check_text(self): 'judge', ' if not tracked(real_root, rel):\n continue\n', '', 'Judge.test_the_model_gets_findings_and_only_tracked_files_inside_the_root'), 'judge: the timeout bounds the whole answer': ( - 'judge', " if time.monotonic() > deadline:\n raise TimeoutError('the answer took too long')\n" - " chunk", ' chunk', 'Judge.test_a_slow_model_is_cut_off_at_the_timeout_in_all'), + 'judge', " if left <= 0:\n raise TimeoutError('the answer took too long')\n", '', + 'Judge.test_a_slow_model_is_cut_off_at_the_timeout_in_all'), + 'judge: a stalled read ends at the deadline': ( + 'judge', ' cut_read_at(resp, left)\n', '', + 'Judge.test_a_model_that_stalls_near_the_deadline_is_cut_off_at_the_deadline'), 'a #N where is linked to the project repository': ( 'report', " return f'{repo}{w}' if repo else None", " return w", 'Render.test_a_pull_request_number_is_shown_and_linked_to_the_right_repository'),