From 87fad69990a4cb0a5de7769e3d3465d2378bee38 Mon Sep 17 00:00:00 2001 From: "cw-instinct[bot]" Date: Sat, 21 Nov 2026 23:21:50 +0200 Subject: [PATCH 1/4] Atlas refresh: count failed weeks at >=168 h, keep state of failed runs, say recorded checks Code, tests and protocol only; no Atlas data. --- .github/workflows/refresh.yml | 17 ++- atlas/PROTOCOL.md | 2 +- atlas/refresh.py | 74 +++++++++-- atlas/site/build.py | 2 +- atlas/tools/carry_failed_state.py | 90 +++++++++++++ tests/test_carry_failed_state.py | 148 +++++++++++++++++++++ tests/test_refresh_state_wording.py | 198 ++++++++++++++++++++++++++++ 7 files changed, 515 insertions(+), 16 deletions(-) create mode 100644 atlas/tools/carry_failed_state.py create mode 100644 tests/test_carry_failed_state.py create mode 100644 tests/test_refresh_state_wording.py diff --git a/.github/workflows/refresh.yml b/.github/workflows/refresh.yml index e37321ae..2f3edb60 100644 --- a/.github/workflows/refresh.yml +++ b/.github/workflows/refresh.yml @@ -49,9 +49,16 @@ jobs: git show "origin/$newest:atlas/data/refresh-state.json" > "$RUNNER_TEMP/prev-state.json" || true echo "Carrying state from open PR branch $newest" fi + - name: Carry state kept by a failed run + # A run that fails after Refresh (Check, Smoke) never opens a PR, so its weekly counters would be lost. That run uploads only + # refresh-state.json as an artifact (no generated pages or data). Here the newest such artifact of this workflow is offered as a + # second candidate (atlas/tools/carry_failed_state.py picks the newest valid one among recent failed runs on main); refresh.py ignores it unless its updated_at is newer than main's and the PR branch's state, and ignores + # a file that is not a valid state. Nothing from it is published without a PR and its CI. + run: python atlas/tools/carry_failed_state.py --out "$RUNNER_TEMP/failed-state/refresh-state.json" - name: Refresh + id: refresh run: | - python atlas/refresh.py --state-from "$RUNNER_TEMP/prev-state.json" \ + python atlas/refresh.py --state-from "$RUNNER_TEMP/prev-state.json" --state-from "$RUNNER_TEMP/failed-state/refresh-state.json" \ --summary "$RUNNER_TEMP/summary.md" --report "$RUNNER_TEMP/report.json" cat "$RUNNER_TEMP/summary.md" >> "$GITHUB_STEP_SUMMARY" - name: Stats from Pulse @@ -73,6 +80,14 @@ jobs: python atlas/site/check.py - name: Smoke (browser) run: python atlas/site/tools/smoke_test.py + - name: Keep state if a later step failed + if: failure() && steps.refresh.outcome == 'success' + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: atlas-refresh-state + path: atlas/data/refresh-state.json + retention-days: 21 + if-no-files-found: error - name: Open PR if: steps.diff.outputs.changed == 'true' run: | diff --git a/atlas/PROTOCOL.md b/atlas/PROTOCOL.md index 60fdade6..098750ab 100644 --- a/atlas/PROTOCOL.md +++ b/atlas/PROTOCOL.md @@ -21,7 +21,7 @@ Input row fields: legacy data from a scout census on 2026-10-15 (NOT evidence A published card is marked closed in one of two ways, and the card says which. A single failed page load is never proof of closure, and a blocked or JavaScript-only page (401/403/429/503, Cloudflare challenge) counts as reachable. 1. **Human review** (this protocol, step 6): an official shutdown/sunset statement, or at least two independent signals (e.g. the domain fails by two methods AND no activity anywhere for 90+ days). Cards closed this way are never reopened automatically: a re-registered or parked domain can answer HTTP 200 too. Reopening needs a new check. -2. **Automated weekly check** (`atlas/refresh.py`): each week the primary URL is fetched with several attempts plus alternate URLs (http/https, www). The first failed week only marks the entry as suspected in `atlas/data/refresh-state.json`; nothing is published. A second consecutive failed week marks the card closed (`include_closed_history`) with a `site_reachable` claim (`direct_observation`, outcome `contradicted`) and a `status_history` record `by: atlas/refresh.py`. The card then shows "Closed by automated check since ". If the site answers again in a later weekly check, the card reopens automatically (back to live, with a new claim and history record). The checker validates every redirect and connects to the exact DNS addresses it validated, without using system proxies; private, local, cloud-internal and special platform addresses are refused and count as failed attempts. JSON reads are capped at 1 MB per response and 25 MB per aggregate source read; aggregate processing is capped at 100,000 rows and 50 pages. Pagination offsets must be decimal values of at most 12 digits. +2. **Automated weekly check** (`atlas/refresh.py`): each week the primary URL is fetched with several attempts plus alternate URLs (http/https, www). A failed check counts as a new week only when at least 7 days have passed since the previous counted failed check (`last_counted_at` in `refresh-state.json`), so a manual run, a retry or a second run in the same week never adds a week; an older entry without that field uses its `first_failed_at` when it has exactly one failed week; when the previous count time is unknown the check does not count and `interval_baseline_at` marks where the 7 days start. The first failed week only marks the entry as suspected in `atlas/data/refresh-state.json`; nothing is published. A second consecutive failed week marks the card closed (`include_closed_history`) with a `site_reachable` claim (`direct_observation`, outcome `contradicted`) and a `status_history` record `by: atlas/refresh.py`. The card then shows "Closed by automated check since ". If the site answers again in a later weekly check, the card reopens automatically (back to live, with a new claim and history record). The checker validates every redirect and connects to the exact DNS addresses it validated, without using system proxies; private, local, cloud-internal and special platform addresses are refused and count as failed attempts. JSON reads are capped at 1 MB per response and 25 MB per aggregate source read; aggregate processing is capped at 100,000 rows and 50 pages. Pagination offsets must be decimal values of at most 12 digits. ### Between live and closed: reachability notes diff --git a/atlas/refresh.py b/atlas/refresh.py index 668d407c..82b1194e 100644 --- a/atlas/refresh.py +++ b/atlas/refresh.py @@ -40,7 +40,7 @@ Exit code 0 always unless the script itself breaks; findings go to the summary. """ import argparse, concurrent.futures as cf, copy, glob, http.client, ipaddress, json, math, os, re, socket, ssl, string, sys, tempfile, threading, time, urllib.error, urllib.parse, urllib.request -from datetime import datetime, timezone +from datetime import datetime, timedelta, timezone HERE = os.path.dirname(os.path.abspath(__file__)) DATA = os.path.join(HERE, 'data') @@ -59,6 +59,37 @@ 'medium.com', 'blogspot.com', 'wordpress.com', 'framer.website', 'framer.app', 'webflow.io', 'carrd.co'} +MIN_WEEK_GAP = timedelta(days=7) + + +def _parse_ts(ts): + return datetime.strptime(ts, '%Y-%m-%dT%H:%M:%SZ').replace(tzinfo=timezone.utc) + + +def counts_as_new_week(st, ts): + """True when this failed check adds a week: >= 7 days (MIN_WEEK_GAP) since the previous counted failed check. + The previous count time is `last_counted_at`; for an entry recorded before that field existed with exactly 1 failed week it is + `first_failed_at`, which this script sets only when it creates the entry, in the same run as the first count. + When the previous count time is unknown or unreadable (older entry with more weeks, bad value) nothing is assumed: the check + does not count, and `interval_baseline_at` is set to this check's time (not a counted failure, only the start of the 7-day + interval). The entry keeps its failed_weeks and first_failed_at. A later check counts once 7 days have passed since the baseline. + Mutates only st['interval_baseline_at'] (set when missing or unreadable).""" + def parsed(v): + try: + return _parse_ts(v) if isinstance(v, str) else None + except ValueError: + return None + last = parsed(st.get('last_counted_at')) + if last is None and st.get('last_counted_at') is None and st.get('failed_weeks') == 1: + last = parsed(st.get('first_failed_at')) + if last is None: + last = parsed(st.get('interval_baseline_at')) + if last is None: + st['interval_baseline_at'] = ts + return False + return _parse_ts(ts) - last >= MIN_WEEK_GAP + + def now_iso(): return datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ') @@ -980,13 +1011,21 @@ def write_atomic(path, text): raise +def valid_state(d): + """Shape check for a state file that comes from outside the repo checkout (PR branch, failed-run artifact).""" + return (isinstance(d, dict) and d.get('version') == 1 and isinstance(d.get('entries'), dict) + and isinstance(d.get('updated_at', ''), str) + and all(isinstance(v, dict) and isinstance(v.get('failed_weeks'), int) and isinstance(v.get('first_failed_at'), str) + for v in d['entries'].values())) + + def main(): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument('--dry-run', action='store_true', help='check everything, write nothing') ap.add_argument('--snapshot', default=None) ap.add_argument('--sources', default=os.path.join(HERE, 'refresh-sources.json')) ap.add_argument('--state', default=os.path.join(DATA, 'refresh-state.json')) - ap.add_argument('--state-from', default=None, help='start from this state (e.g. the open refresh PR) if it is newer than --state') + ap.add_argument('--state-from', action='append', default=None, help='start from this state (repeatable; e.g. the open refresh PR, the state kept by a failed run) if it is newer than --state; the newest updated_at wins') ap.add_argument('--summary', default=None, help='write the markdown PR summary here') ap.add_argument('--report', default=None, help='write the full JSON report here') ap.add_argument('--only', default=None, help='comma-separated slugs (testing)') @@ -1002,10 +1041,15 @@ def main(): sources = load_json(a.sources, {}).get('sources', {}) state_raw = open(a.state, encoding='utf-8').read() if os.path.exists(a.state) else None state = json.loads(state_raw) if state_raw else {'version': 1, 'entries': {}, 'moved': {}} - if a.state_from and os.path.exists(a.state_from): - alt = load_json(a.state_from, None) - if alt and (alt.get('updated_at') or '') > (state.get('updated_at') or ''): - print(f'starting from newer state {a.state_from} ({alt.get("updated_at")})') + for path in (a.state_from or []): + if not os.path.exists(path): + continue + alt = load_json(path, None) + if not valid_state(alt): + print(f'ignoring {path}: not a valid refresh state') + continue + if (alt.get('updated_at') or '') > (state.get('updated_at') or ''): + print(f'starting from newer state {path} ({alt.get("updated_at")})') state = alt state.setdefault('entries', {}); state.setdefault('moved', {}) state_before = copy.deepcopy(state) @@ -1059,20 +1103,24 @@ def job(e): if e['status'] == 'live': if r['cls'] == 'fail': st = st or {'failed_weeks': 0, 'first_failed_at': ts} - st['failed_weeks'] += 1 + new_week = counts_as_new_week(st, ts) if st['failed_weeks'] else True + if new_week: + st['failed_weeks'] += 1 + st['last_counted_at'] = ts + st.pop('interval_baseline_at', None) st['last_error'] = r['error'] state['entries'][slug] = st - if st['failed_weeks'] >= 2: - rep['died'].append({'slug': slug, 'url': r['via'], 'error': r['error'], 'first_failed_at': st['first_failed_at']}) + if new_week and st['failed_weeks'] >= 2: + rep['died'].append({'slug': slug, 'url': r['via'], 'error': r['error'], 'first_failed_at': st['first_failed_at'], 'failed_weeks': st['failed_weeks']}) claim = {'kind': 'site_reachable', - 'statement': f'Automated weekly check could not reach the site in {st["failed_weeks"]} consecutive weeks ' + 'statement': f'Automated weekly check could not reach the site in {st["failed_weeks"]} recorded weekly checks since {st["first_failed_at"][:10]} ' f'({ATTEMPTS} attempts each week plus alternate URLs); last error: {r["error"]}.', 'value': None, 'unit': None, 'window': None, 'basis': 'direct_observation', 'source_url': r['via'], 'quote': (r['error'] or '')[:200], 'observed_at': ts, 'methods': r['methods'], 'outcome': 'contradicted', - 'refresh': {'by': TOOL, 'rule': 'closed after 2 consecutive failed weekly checks', 'first_failed_at': st['first_failed_at']}} + 'refresh': {'by': TOOL, 'rule': 'closed after 2 consecutive failed weekly checks', 'failed_weeks_recorded': st['failed_weeks'], 'first_failed_at': st['first_failed_at']}} e['claims'].insert(0, claim) e.setdefault('status_history', []).append({'at': ts, 'from': 'live', 'to': 'closed', 'by': TOOL, - 'reason': f'unreachable in {st["failed_weeks"]} consecutive weekly checks since {st["first_failed_at"][:10]}'}) + 'reason': f'unreachable in {st["failed_weeks"]} recorded weekly checks since {st["first_failed_at"][:10]}'}) e['status'], e['verdict'] = 'closed', 'include_closed_history' st['closed_at'] = ts changed_slugs.add(slug) @@ -1179,7 +1227,7 @@ def job(e): https = lambda u: u if str(u).startswith('https://') else 'https://' + str(u).split('://', 1)[-1] for d in rep['died']: atlas_events.append(ev_file, today, d['slug'], 'closed', - 'Automated weekly check: site unreachable in 2 consecutive weekly checks', https(d['url'])) + f'Automated weekly check: site unreachable in {d["failed_weeks"]} recorded weekly checks since {d["first_failed_at"][:10]}', https(d['url'])) for d in rep['revived']: atlas_events.append(ev_file, today, d['slug'], 'reopened', 'Automated weekly check: site answers again after an automated closure', https(d['url'])) diff --git a/atlas/site/build.py b/atlas/site/build.py index bea82465..cc76a60e 100644 --- a/atlas/site/build.py +++ b/atlas/site/build.py @@ -868,7 +868,7 @@ def build_platform(site, c): if how == 'auto': ev = next((x.get('statement') for x in claims if x.get('kind') == 'site_reachable' and x.get('outcome') == 'contradicted'), None) or ev closed_box = (f'
Closed by automated check since {time_tag(since)}. ' - f'The site could not be reached in 2 consecutive weekly checks (several attempts plus alternate URLs each week). ' + f'Rule: closed after the site could not be reached in 2 consecutive weekly checks (several attempts plus alternate URLs each week); the evidence below gives the checks recorded for this card. ' f'This card is kept as a history record and reopens automatically if the site answers again. {e(ev) if ev else ""}
') else: closed_box = (f'
Closed. This card is kept as a history record. ' diff --git a/atlas/tools/carry_failed_state.py b/atlas/tools/carry_failed_state.py new file mode 100644 index 00000000..45510d12 --- /dev/null +++ b/atlas/tools/carry_failed_state.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 +"""Pick the newest usable refresh state kept by a failed run of this workflow (.github/workflows/refresh.yml). + +A run that fails after the Refresh step opens no PR, so it uploads only atlas/data/refresh-state.json as the artifact +`atlas-refresh-state`. This script looks through the recent failed runs of the workflow on the default branch, downloads each +candidate artifact, keeps those that are valid refresh states and writes the one with the newest `updated_at` to --out. +Nothing here decides whether that state is used: atlas/refresh.py --state-from takes it only if it is newer than the other states. + +Fail-safe: every problem (gh error, no run, expired or missing artifact, bad download, malformed state) skips that candidate; +if nothing usable is left --out is not written and the exit code is 0, so the refresh starts from the state it would have had anyway. +Needs the gh CLI and GH_TOKEN, GITHUB_REPOSITORY. Only reads.""" +import argparse +import json +import os +import shutil +import subprocess +import sys +import tempfile + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +import refresh # noqa: E402 (valid_state) + +ARTIFACT = 'atlas-refresh-state' + + +def gh(*args): + p = subprocess.run(['gh', *args], capture_output=True, text=True, timeout=120) + if p.returncode != 0: + raise RuntimeError(f'gh {args[0]} failed: {p.stderr.strip()[:200]}') + return p.stdout + + +def candidates(repo, workflow, branch, limit): + runs = json.loads(gh('run', 'list', '--workflow', workflow, '--branch', branch, '--limit', str(limit), + '--json', 'databaseId,headBranch,event,conclusion')) + for r in runs: + # Provenance: runs of this workflow on the default branch, started by the schedule or by hand. + # gh --status takes one value, so filter the conclusion here: failure and timed_out both leave state behind (the upload step runs on failure()). + if r.get('conclusion') in ('failure', 'timed_out') and r.get('headBranch') == branch and r.get('event') in ('schedule', 'workflow_dispatch') and isinstance(r.get('databaseId'), int): + yield r['databaseId'] + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument('--out', required=True) + ap.add_argument('--repo', default=os.environ.get('GITHUB_REPOSITORY', '')) + ap.add_argument('--workflow', default='refresh.yml') + ap.add_argument('--branch', default='main') + ap.add_argument('--limit', type=int, default=100) + a = ap.parse_args() + best, best_id = None, None + tmp = tempfile.mkdtemp() + try: + try: + ids = list(candidates(a.repo, a.workflow, a.branch, a.limit)) + except Exception as ex: # noqa: BLE001 + print(f'no failed-run state: {ex}') + return 0 + for rid in ids: + try: + arts = json.loads(gh('api', f'repos/{a.repo}/actions/runs/{rid}/artifacts'))['artifacts'] + ok = [x for x in arts if x.get('name') == ARTIFACT and x.get('expired') is False + and (x.get('workflow_run') or {}).get('head_branch') == a.branch] + if not ok: + continue + d = os.path.join(tmp, str(rid)) + gh('run', 'download', str(rid), '--name', ARTIFACT, '--dir', d) + st = json.load(open(os.path.join(d, 'refresh-state.json'), encoding='utf-8')) + except Exception as ex: # noqa: BLE001 + print(f'skipping run {rid}: {type(ex).__name__}: {str(ex)[:120]}') + continue + if not refresh.valid_state(st) or not st.get('updated_at'): + print(f'skipping run {rid}: not a valid refresh state') + continue + if best is None or st['updated_at'] > best['updated_at']: + best, best_id = st, rid + if best is None: + print('no usable state kept by a failed run') + return 0 + os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True) + with open(a.out, 'w', encoding='utf-8') as f: + json.dump(best, f, ensure_ascii=False, indent=1) + print(f'using state of failed run {best_id} (updated_at {best["updated_at"]})') + return 0 + finally: + shutil.rmtree(tmp, ignore_errors=True) + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/test_carry_failed_state.py b/tests/test_carry_failed_state.py new file mode 100644 index 00000000..d1d9285c --- /dev/null +++ b/tests/test_carry_failed_state.py @@ -0,0 +1,148 @@ +"""atlas/tools/carry_failed_state.py with a fake `gh` (offline, read-only): which failed-run state is carried into the next refresh, +and that every failure of the carry path leaves the refresh starting from the state it would have had anyway.""" +import json +import os +import stat +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / 'tests')) +from test_refresh_state_wording import run_refresh, st # noqa: E402 + +SCRIPT = ROOT / 'atlas/tools/carry_failed_state.py' +FAKE_GH = '''#!/usr/bin/env python3 +import json, os, shutil, sys +fx = json.load(open(os.environ["FAKE_GH"])) +a = sys.argv[1:] +if a[:2] == ["run", "list"]: + if fx.get("list_error"): sys.stderr.write("boom"); sys.exit(1) + print(json.dumps(fx["runs"])) +elif a[0] == "api": + rid = a[1].split("/runs/")[1].split("/")[0] + if rid in fx.get("api_error", []): sys.stderr.write("boom"); sys.exit(1) + print(json.dumps({"artifacts": fx["artifacts"].get(rid, [])})) +elif a[:2] == ["run", "download"]: + rid = a[2]; d = a[a.index("--dir") + 1] + if rid in fx.get("download_error", []): sys.stderr.write("gone"); sys.exit(1) + os.makedirs(d, exist_ok=True) + body = fx["files"][rid] + open(os.path.join(d, "refresh-state.json"), "w").write(body if isinstance(body, str) else json.dumps(body)) +else: + sys.exit(2) +''' + + +def art(branch='main', expired=False): + return [{'name': 'atlas-refresh-state', 'expired': expired, 'workflow_run': {'head_branch': branch}}] + + +def run_of(i, branch='main', event='schedule', conclusion='failure'): + return {'databaseId': i, 'headBranch': branch, 'event': event, 'conclusion': conclusion} + + +class Carry(unittest.TestCase): + def pick(self, fx): + with tempfile.TemporaryDirectory() as d: + d = Path(d) + gh = d / 'bin' / 'gh' + gh.parent.mkdir() + gh.write_text(FAKE_GH) + gh.chmod(gh.stat().st_mode | stat.S_IEXEC) + (d / 'fx.json').write_text(json.dumps(fx)) + out = d / 'sub' / 'refresh-state.json' + env = dict(os.environ, PATH=f'{gh.parent}:{os.environ["PATH"]}', FAKE_GH=str(d / 'fx.json'), GITHUB_REPOSITORY='o/r') + p = subprocess.run([sys.executable, str(SCRIPT), '--out', str(out)], env=env, capture_output=True, text=True) + self.assertEqual(p.returncode, 0, p.stderr) + return (json.loads(out.read_text()) if out.exists() else None), p.stdout + + def test_newest_by_state_timestamp_not_by_run_order(self): + # run 3 is the newest run but its state is older than run 2's (e.g. restarted from older state) + fx = {'runs': [run_of(3), run_of(2), run_of(1)], 'artifacts': {'1': art(), '2': art(), '3': art()}, + 'files': {'1': st(1, at='2026-11-01T00:00:00Z'), '2': st(2, at='2026-11-15T00:00:00Z'), '3': st(1, at='2026-11-08T00:00:00Z')}} + got, _ = self.pick(fx) + self.assertEqual(got['updated_at'], '2026-11-15T00:00:00Z') + + def test_run_that_failed_before_refresh_has_no_artifact_and_is_skipped(self): + fx = {'runs': [run_of(3), run_of(2)], 'artifacts': {'3': [], '2': art()}, 'files': {'2': st(2, at='2026-11-15T00:00:00Z')}} + got, _ = self.pick(fx) + self.assertEqual(got['entries']['opentask']['failed_weeks'], 2) + + def test_expired_missing_or_unreadable_newest_falls_back_to_older_usable(self): + fx = {'runs': [run_of(5), run_of(4), run_of(3), run_of(2)], + 'artifacts': {'5': art(expired=True), '4': art(), '3': art(), '2': art()}, + 'download_error': ['4'], 'api_error': [], + 'files': {'3': 'not json {', '2': st(2, at='2026-11-08T00:00:00Z')}} + got, out = self.pick(fx) + self.assertEqual(got['updated_at'], '2026-11-08T00:00:00Z') + self.assertIn('skipping run 4', out) + self.assertIn('skipping run 3', out) + + def test_old_usable_state_beyond_five_runs_is_still_found(self): + runs = [run_of(i) for i in range(40, 10, -1)] # 30 runs of 100 scanned, newest first + fx = {'runs': runs, 'artifacts': {'12': art()}, 'files': {'12': st(2, at='2026-10-01T00:00:00Z')}} + got, _ = self.pick(fx) + self.assertEqual(got['updated_at'], '2026-10-01T00:00:00Z') + + def test_provenance_branch_and_event(self): + fx = {'runs': [run_of(3, branch='feature'), run_of(2, event='pull_request'), run_of(1)], + 'artifacts': {'3': art('feature'), '2': art(), '1': art('feature')}, # run 1 lists main but its artifact says another branch + 'files': {'3': st(9, at='2026-11-20T00:00:00Z'), '2': st(9, at='2026-11-19T00:00:00Z'), '1': st(9, at='2026-11-18T00:00:00Z')}} + got, _ = self.pick(fx) + self.assertIsNone(got) + + def test_conclusion_failure_or_timed_out_only(self): + fx = {'runs': [run_of(4, conclusion='success'), run_of(3, conclusion='cancelled'), run_of(2, conclusion='timed_out'), run_of(1, conclusion='failure')], + 'artifacts': {'4': art(), '3': art(), '2': art(), '1': art()}, + 'files': {'4': st(9, at='2026-11-20T00:00:00Z'), '3': st(9, at='2026-11-19T00:00:00Z'), + '2': st(2, at='2026-11-15T00:00:00Z'), '1': st(1, at='2026-11-08T00:00:00Z')}} + got, _ = self.pick(fx) + self.assertEqual(got['updated_at'], '2026-11-15T00:00:00Z') + + def test_partly_malformed_state_is_ignored_entirely(self): + bad = st(2, at='2026-11-20T00:00:00Z') + bad['entries']['broken'] = {'failed_weeks': 'x'} + fx = {'runs': [run_of(2), run_of(1)], 'artifacts': {'2': art(), '1': art()}, 'files': {'2': bad, '1': st(1, at='2026-11-01T00:00:00Z')}} + got, _ = self.pick(fx) + self.assertEqual(got['updated_at'], '2026-11-01T00:00:00Z') + self.assertNotIn('broken', got['entries']) + + def test_gh_failures_never_fail_the_step_and_write_nothing(self): + for fx in ({'list_error': True}, {'runs': []}, {'runs': [run_of(1)], 'artifacts': {'1': art()}, 'download_error': ['1']}, + {'runs': [run_of(1)], 'artifacts': {}, 'api_error': ['1']}): + got, _ = self.pick(fx) + self.assertIsNone(got) + + +class Chain(unittest.TestCase): + """Consecutive runs through the real refresh.main: a state is counted once and a stale artifact never overrides newer state.""" + def write(self, d, name, obj): + p = Path(d) / name + p.write_text(json.dumps(obj), encoding='utf-8') + return p + + def test_no_double_count_and_stale_artifact_loses(self): + with tempfile.TemporaryDirectory() as d: + # run A (Nov 15, failed after Refresh) kept 'opentask' at 1 failed week + art_a = self.write(d, 'a.json', dict(st(1, at='2026-11-15T09:00:00Z'), entries={'opentask': { + 'failed_weeks': 1, 'first_failed_at': '2026-11-15T09:00:00Z', 'last_counted_at': '2026-11-15T09:00:00Z', 'last_error': 'x'}})) + # run B (Nov 22, 7 days later) starts from A's artifact: 2nd counted week, closes, writes a newer state + snap, state_b, _ = run_refresh({'version': 1, 'moved': {}, 'entries': {}}, [art_a], now='2026-11-22T09:00:00Z') + self.assertEqual(snap['platforms'][0]['status'], 'closed') + self.assertEqual(state_b['entries']['opentask']['failed_weeks'], 2) + # run C, same week as B, with A's artifact still listed and B's state as main/PR state: B's state is newer, A is not used + # again, and the same-week rerun adds nothing + _, state_c, _ = run_refresh(state_b, [art_a], now='2026-11-22T12:00:00Z') + self.assertEqual(state_c['entries']['opentask']['failed_weeks'], 2) + # an artifact left by a failed run of the SAME week as the state it started from is not counted again either + art_b2 = self.write(d, 'b2.json', state_b) + snap_d, state_d, _ = run_refresh({'version': 1, 'moved': {}, 'entries': {}}, [art_b2], now='2026-11-22T15:00:00Z') + # nothing new this week: no data change, so no state is written and nothing is counted a third time + self.assertEqual(state_d, {'version': 1, 'moved': {}, 'entries': {}}) + self.assertEqual(snap_d['platforms'][0]['status'], 'live') # the harness snapshot is not touched + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_refresh_state_wording.py b/tests/test_refresh_state_wording.py new file mode 100644 index 00000000..c236e907 --- /dev/null +++ b/tests/test_refresh_state_wording.py @@ -0,0 +1,198 @@ +"""Failed-week counters: wording says what was recorded, a gap in the records never closes an extra entry, and a state that +comes from outside the checkout (open refresh PR, state kept by a failed run) only wins when it is valid and newer. Offline.""" +import copy +import json +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / 'atlas')) +import refresh + +SNAP = json.loads((ROOT / 'atlas/data/snapshot-verified-2026-10-15.json').read_text(encoding='utf-8')) + + +def run_refresh(state, state_from=(), slugs=('opentask',), now=None, boom=False, keep=None): + """One real refresh.py main() on a one-site-per-slug copy of the snapshot pointing at a refused (non-public) address.""" + with tempfile.TemporaryDirectory() as d: + d = Path(d) + snap = copy.deepcopy(SNAP) + snap['platforms'] = [p for p in snap['platforms'] if p['slug'] in slugs] + for p in snap['platforms']: + p['canonical_url'] = 'http://127.0.0.1:9/' + p['status'] = 'live' + (d / 'snap.json').write_text(json.dumps(snap), encoding='utf-8') + (d / 'events.jsonl').write_text('', encoding='utf-8') + (d / 'state.json').write_text(json.dumps(state), encoding='utf-8') + (d / 'sources.json').write_text('{"sources": {}}', encoding='utf-8') + argv = ['refresh.py', '--snapshot', str(d / 'snap.json'), '--state', str(d / 'state.json'), '--sources', str(d / 'sources.json'), + '--replications', str(d / 'none.json'), '--report', str(d / 'report.json'), '--summary', str(d / 'summary.md')] + for p in state_from: + argv += ['--state-from', str(p)] + patches = [mock.patch.object(sys, 'argv', argv), + mock.patch.object(refresh, 'BACKOFF', (0,)), + mock.patch.object(refresh, 'run_replications', side_effect=RuntimeError('boom') if boom else None, return_value=False)] + if now: + patches.append(mock.patch.object(refresh, 'now_iso', return_value=now)) + for pt in patches: + pt.start() + try: + refresh.main() + except RuntimeError: + if not boom: + raise + finally: + mock.patch.stopall() + if keep is not None: + keep.update({'state': (d / 'state.json').read_text(encoding='utf-8'), 'snap': (d / 'snap.json').read_text(encoding='utf-8')}) + return (json.loads((d / 'snap.json').read_text(encoding='utf-8')), json.loads((d / 'state.json').read_text(encoding='utf-8')), + (d / 'events.jsonl').read_text(encoding='utf-8')) + + +def st(weeks, at='2026-11-14T00:00:00Z', first='2026-11-14T00:00:00Z'): + return {'version': 1, 'moved': {}, 'updated_at': at, 'entries': {'opentask': {'failed_weeks': weeks, 'first_failed_at': first, 'last_error': 'x'}}} + + +class Wording(unittest.TestCase): + def test_closure_says_recorded_checks_with_the_recorded_count(self): + snap, state, events = run_refresh(st(1)) + e = snap['platforms'][0] + self.assertEqual(e['status'], 'closed') + claim = e['claims'][0] + self.assertIn('2 recorded weekly checks since 2026-11-14', claim['statement']) + self.assertNotIn('consecutive weeks', claim['statement']) + self.assertIn('2 recorded weekly checks since 2026-11-14', e['status_history'][-1]['reason']) + self.assertEqual(claim['refresh']['failed_weeks_recorded'], 2) + self.assertIn('2 recorded weekly checks since 2026-11-14', events) + + def test_first_failure_only_suspects(self): + snap, state, _ = run_refresh({'version': 1, 'moved': {}, 'entries': {}}) + self.assertEqual(snap['platforms'][0]['status'], 'live') + self.assertEqual(state['entries']['opentask']['failed_weeks'], 1) + + def test_a_week_missing_from_the_records_is_not_made_up(self): + # counters are never inferred from calendar gaps: one recorded failure stays one, closure needs a second recorded failure + snap, state, _ = run_refresh(st(1, at='2026-10-01T00:00:00Z', first='2026-10-01T00:00:00Z'), slugs=('opentask', 'clawbench')) + by = {p['slug']: p for p in snap['platforms']} + self.assertEqual(by['clawbench']['status'], 'live') + self.assertEqual(state['entries']['clawbench']['failed_weeks'], 1) + + +def fresh(weeks, counted, first='2026-11-15T09:00:00Z'): + d = st(weeks, at=first, first=first) + if counted: + d['entries']['opentask']['last_counted_at'] = counted + return d + + +class SevenDayGap(unittest.TestCase): + """A failed check adds a week only when >= 7 days passed since the previous counted failed check.""" + def test_same_week_reruns_do_not_count(self): + for now in ('2026-11-21T19:10:54Z', '2026-11-22T08:30:00Z', '2026-11-28T08:00:00Z'): # manual, scheduled next day, just under 7 days + snap, state, _ = run_refresh(fresh(1, '2026-11-21T10:00:00Z', '2026-11-21T10:00:00Z'), now=now) + self.assertEqual(snap['platforms'][0]['status'], 'live') + self.assertEqual(state['entries']['opentask']['failed_weeks'], 1) + self.assertEqual(state['entries']['opentask']['first_failed_at'], '2026-11-21T10:00:00Z') + self.assertEqual(state['entries']['opentask']['last_counted_at'], '2026-11-21T10:00:00Z') + + def test_exactly_seven_days_counts_and_closes(self): + s, state, _ = run_refresh(fresh(1, '2026-11-15T09:00:00Z'), now='2026-11-22T09:00:00Z') + self.assertEqual(s['platforms'][0]['status'], 'closed') + self.assertEqual((state['entries']['opentask']['failed_weeks'], state['entries']['opentask']['last_counted_at']), (2, '2026-11-22T09:00:00Z')) + + def test_manual_run_then_scheduled_then_a_week_later(self): + _, a, _ = run_refresh({'version': 1, 'moved': {}, 'entries': {}}, now='2026-11-17T09:00:00Z') # first failure, manual + _, b, _ = run_refresh(a, now='2026-11-22T09:00:00Z') # scheduled, 5 days later: no + self.assertEqual(b['entries']['opentask']['failed_weeks'], 1) + s, c, _ = run_refresh(b, now='2026-11-24T09:00:00Z') # 7 days after the counted one + self.assertEqual((s['platforms'][0]['status'], c['entries']['opentask']['failed_weeks']), ('closed', 2)) + + def test_migration_one_week_entry_uses_first_failed_at_as_last_count(self): + # current state shape: failed_weeks 1, no last_counted_at; counted once, at first_failed_at (grounded), so a run 13 h later is not a new week + s, state, _ = run_refresh(fresh(1, None, '2026-11-21T19:10:54Z'), now='2026-11-22T08:30:00Z') + self.assertEqual(s['platforms'][0]['status'], 'live') + self.assertEqual(state['entries']['opentask']['failed_weeks'], 1) + s, state, _ = run_refresh(fresh(1, None, '2026-11-21T19:10:54Z'), now='2026-11-28T19:10:54Z') + self.assertEqual(s['platforms'][0]['status'], 'closed') + + def test_unknown_last_count_time_sets_a_baseline_and_does_not_count(self): + # 3 recorded weeks, no last_counted_at: nothing is assumed. First run: no count, no close, baseline = this check. + s, state, _ = run_refresh(fresh(3, None, '2026-11-01T09:00:00Z'), now='2026-11-22T09:00:00Z') + e = state['entries']['opentask'] + self.assertEqual((e['failed_weeks'], e['first_failed_at'], e['interval_baseline_at']), (3, '2026-11-01T09:00:00Z', '2026-11-22T09:00:00Z')) + self.assertNotIn('last_counted_at', e) + self.assertEqual(s['platforms'][0]['status'], 'live') + # early runs keep the baseline and still do not count (just under 168 h) + _, early, _ = run_refresh(state, now='2026-11-29T08:59:59Z') + self.assertEqual((early['entries']['opentask']['failed_weeks'], early['entries']['opentask']['interval_baseline_at']), (3, '2026-11-22T09:00:00Z')) + # exactly 168 h after the baseline it counts, records last_counted_at and drops the baseline + _, later, _ = run_refresh(early, now='2026-11-29T09:00:00Z') + e = later['entries']['opentask'] + self.assertEqual((e['failed_weeks'], e['last_counted_at']), (4, '2026-11-29T09:00:00Z')) + self.assertNotIn('interval_baseline_at', e) + + def test_one_failed_week_with_unknown_count_time_cannot_close_early(self): + # failed_weeks 1 whose last_counted_at is present but malformed: unknown, so baseline, no close on the first or an early run + bad = fresh(1, 'garbage', '2026-11-01T09:00:00Z') + s, state, _ = run_refresh(bad, now='2026-11-22T09:00:00Z') + self.assertEqual((s['platforms'][0]['status'], state['entries']['opentask']['failed_weeks']), ('live', 1)) + self.assertEqual(state['entries']['opentask']['interval_baseline_at'], '2026-11-22T09:00:00Z') + _, early, _ = run_refresh(state, now='2026-11-25T09:00:00Z') + self.assertEqual(early['entries']['opentask']['failed_weeks'], 1) + s, closed, _ = run_refresh(early, now='2026-11-29T09:00:00Z') + self.assertEqual((s['platforms'][0]['status'], closed['entries']['opentask']['failed_weeks']), ('closed', 2)) + + def test_malformed_baseline_is_reset_not_counted(self): + st_ = fresh(3, None, '2026-11-01T09:00:00Z') + st_['entries']['opentask']['interval_baseline_at'] = 'garbage' + _, state, _ = run_refresh(st_, now='2026-11-22T09:00:00Z') + e = state['entries']['opentask'] + self.assertEqual((e['failed_weeks'], e['interval_baseline_at']), (3, '2026-11-22T09:00:00Z')) + + def test_bad_timestamp_does_not_count(self): + st_ = {'failed_weeks': 2, 'last_counted_at': 'garbage', 'first_failed_at': '2026-11-01T09:00:00Z'} + self.assertFalse(refresh.counts_as_new_week(st_, '2026-11-22T09:00:00Z')) + self.assertEqual(st_['interval_baseline_at'], '2026-11-22T09:00:00Z') + + def test_failed_refresh_leaves_no_partial_state_and_the_retry_counts_once(self): + start = {'version': 1, 'moved': {}, 'entries': {}} + kept = {} + run_refresh(start, now='2026-11-17T09:00:00Z', boom=True, keep=kept) + self.assertEqual(json.loads(kept['state']), start) # state file untouched by a run that died + self.assertEqual(json.loads(kept['snap'])['platforms'][0]['status'], 'live') + _, retry, _ = run_refresh(start, now='2026-11-17T12:00:00Z') + self.assertEqual(retry['entries']['opentask']['failed_weeks'], 1) + _, again, _ = run_refresh(retry, now='2026-11-18T12:00:00Z') + self.assertEqual(again['entries']['opentask']['failed_weeks'], 1) + + +class StateFrom(unittest.TestCase): + def write(self, d, name, obj): + p = Path(d) / name + p.write_text(json.dumps(obj), encoding='utf-8') + return p + + def test_newer_valid_state_wins_older_and_invalid_are_ignored(self): + with tempfile.TemporaryDirectory() as d: + older = self.write(d, 'older.json', st(5, at='2026-11-01T00:00:00Z')) + newer = self.write(d, 'newer.json', st(1, at='2026-11-20T00:00:00Z')) + bad = self.write(d, 'bad.json', {'version': 1, 'updated_at': '2099-01-01T00:00:00Z', 'entries': {'opentask': {'failed_weeks': 'lots'}}}) + main_state = st(0, at='2026-11-10T00:00:00Z') + _, state, _ = run_refresh(main_state, [older, bad, newer]) + # started from `newer` (1 failed week), so this run records the 2nd and closes; neither `older` nor `bad` was used + self.assertEqual(state['entries']['opentask']['failed_weeks'], 2) + _, state, _ = run_refresh(main_state, [older, bad]) + self.assertEqual(state['entries']['opentask']['failed_weeks'], 1) + + def test_valid_state_shape(self): + self.assertTrue(refresh.valid_state(st(1))) + for bad in (None, [], {'version': 2, 'entries': {}}, {'version': 1, 'entries': []}, + {'version': 1, 'entries': {'a': {'failed_weeks': True}}}): + self.assertFalse(refresh.valid_state(bad)) + + +if __name__ == '__main__': + unittest.main() From 5f585e03e1bf46ecaf23dc1e90522a8ce26c0e96 Mon Sep 17 00:00:00 2001 From: "cw-instinct[bot]" Date: Sat, 21 Nov 2026 23:41:40 +0200 Subject: [PATCH 2/4] Atlas refresh: apply an already-earned closure without counting another week Codex P1 on 87fad69: a retry after a run that counted the 2nd week but lost the closure stayed live. A valid last_counted_at with failed_weeks >= 2 and a still-failing check now closes the card without adding a week; legacy history without a valid count time is never treated as earned. --- atlas/refresh.py | 13 ++++++++++++- tests/test_carry_failed_state.py | 18 +++++++++--------- tests/test_refresh_state_wording.py | 24 ++++++++++++++++++++++++ 3 files changed, 45 insertions(+), 10 deletions(-) diff --git a/atlas/refresh.py b/atlas/refresh.py index 82b1194e..8b4b20e9 100644 --- a/atlas/refresh.py +++ b/atlas/refresh.py @@ -66,6 +66,17 @@ def _parse_ts(ts): return datetime.strptime(ts, '%Y-%m-%dT%H:%M:%SZ').replace(tzinfo=timezone.utc) +def earned_closure(st): + """True when this entry already reached the closure threshold in a counting run (a valid `last_counted_at` is written only when a + week is counted, and a counted 2nd week closes the card) but the closure itself was lost, e.g. the run failed after Refresh and + only the state was carried. The still-failing check of this run then applies the closure without adding a week. An entry without a + valid `last_counted_at` (legacy state, unknown history) is never treated as earned.""" + try: + return st.get('failed_weeks', 0) >= 2 and isinstance(st.get('last_counted_at'), str) and bool(_parse_ts(st['last_counted_at'])) + except ValueError: + return False + + def counts_as_new_week(st, ts): """True when this failed check adds a week: >= 7 days (MIN_WEEK_GAP) since the previous counted failed check. The previous count time is `last_counted_at`; for an entry recorded before that field existed with exactly 1 failed week it is @@ -1110,7 +1121,7 @@ def job(e): st.pop('interval_baseline_at', None) st['last_error'] = r['error'] state['entries'][slug] = st - if new_week and st['failed_weeks'] >= 2: + if st['failed_weeks'] >= 2 and (new_week or earned_closure(st)): rep['died'].append({'slug': slug, 'url': r['via'], 'error': r['error'], 'first_failed_at': st['first_failed_at'], 'failed_weeks': st['failed_weeks']}) claim = {'kind': 'site_reachable', 'statement': f'Automated weekly check could not reach the site in {st["failed_weeks"]} recorded weekly checks since {st["first_failed_at"][:10]} ' diff --git a/tests/test_carry_failed_state.py b/tests/test_carry_failed_state.py index d1d9285c..c1e5bd8d 100644 --- a/tests/test_carry_failed_state.py +++ b/tests/test_carry_failed_state.py @@ -133,16 +133,16 @@ def test_no_double_count_and_stale_artifact_loses(self): snap, state_b, _ = run_refresh({'version': 1, 'moved': {}, 'entries': {}}, [art_a], now='2026-11-22T09:00:00Z') self.assertEqual(snap['platforms'][0]['status'], 'closed') self.assertEqual(state_b['entries']['opentask']['failed_weeks'], 2) - # run C, same week as B, with A's artifact still listed and B's state as main/PR state: B's state is newer, A is not used - # again, and the same-week rerun adds nothing - _, state_c, _ = run_refresh(state_b, [art_a], now='2026-11-22T12:00:00Z') + # run C within 7 days of B's count, with B's state carried but B's closure lost (snapshot live again): the still-failing check + # applies the already-earned closure and does NOT add a week + snap_c, state_c, _ = run_refresh(state_b, [art_a], now='2026-11-22T12:00:00Z') self.assertEqual(state_c['entries']['opentask']['failed_weeks'], 2) - # an artifact left by a failed run of the SAME week as the state it started from is not counted again either - art_b2 = self.write(d, 'b2.json', state_b) - snap_d, state_d, _ = run_refresh({'version': 1, 'moved': {}, 'entries': {}}, [art_b2], now='2026-11-22T15:00:00Z') - # nothing new this week: no data change, so no state is written and nothing is counted a third time - self.assertEqual(state_d, {'version': 1, 'moved': {}, 'entries': {}}) - self.assertEqual(snap_d['platforms'][0]['status'], 'live') # the harness snapshot is not touched + self.assertEqual(snap_c['platforms'][0]['status'], 'closed') + self.assertEqual(state_c['entries']['opentask']['last_counted_at'], '2026-11-22T09:00:00Z') + # the same artifact offered again (older main state) still only applies the earned closure, never a third count + snap_d, state_d, _ = run_refresh({'version': 1, 'moved': {}, 'entries': {}}, [art_b2 := self.write(d, 'b2.json', state_b)], now='2026-11-22T15:00:00Z') + self.assertEqual(state_d['entries']['opentask']['failed_weeks'], 2) + self.assertEqual(snap_d['platforms'][0]['status'], 'closed') if __name__ == '__main__': unittest.main() diff --git a/tests/test_refresh_state_wording.py b/tests/test_refresh_state_wording.py index c236e907..848070b3 100644 --- a/tests/test_refresh_state_wording.py +++ b/tests/test_refresh_state_wording.py @@ -152,6 +152,30 @@ def test_malformed_baseline_is_reset_not_counted(self): e = state['entries']['opentask'] self.assertEqual((e['failed_weeks'], e['interval_baseline_at']), (3, '2026-11-22T09:00:00Z')) + def test_earned_closure_is_applied_without_counting_again(self): + # state kept by a run that counted the 2nd week then failed before publishing: the retry (live card, 2 weeks, valid count time) closes + s, state, _ = run_refresh(fresh(2, '2026-11-22T09:00:00Z'), now='2026-11-23T09:00:00Z') + e = state['entries']['opentask'] + self.assertEqual(s['platforms'][0]['status'], 'closed') + self.assertEqual((e['failed_weeks'], e['last_counted_at']), (2, '2026-11-22T09:00:00Z')) + self.assertIn('2 recorded weekly checks', s['platforms'][0]['claims'][0]['statement']) + + def test_earned_closure_unit(self): + self.assertTrue(refresh.earned_closure({'failed_weeks': 2, 'last_counted_at': '2026-11-22T09:00:00Z'})) + + def test_legacy_history_without_a_valid_count_time_is_never_an_earned_closure(self): + for entry in ({'failed_weeks': 3, 'first_failed_at': '2026-11-01T09:00:00Z'}, + {'failed_weeks': 2, 'first_failed_at': '2026-11-01T09:00:00Z', 'last_counted_at': 'garbage'}, + {'failed_weeks': 2, 'first_failed_at': '2026-11-01T09:00:00Z', 'last_counted_at': None}, + {'failed_weeks': 1, 'first_failed_at': '2026-11-01T09:00:00Z', 'last_counted_at': '2026-11-22T09:00:00Z'}): + self.assertFalse(refresh.earned_closure(entry)) + st_ = fresh(3, None, '2026-11-01T09:00:00Z') + s, state, _ = run_refresh(st_, now='2026-11-22T09:00:00Z') + self.assertEqual((s['platforms'][0]['status'], state['entries']['opentask']['failed_weeks']), ('live', 3)) + bad = fresh(2, 'garbage', '2026-11-01T09:00:00Z') + s, state, _ = run_refresh(bad, now='2026-11-22T09:00:00Z') + self.assertEqual((s['platforms'][0]['status'], state['entries']['opentask']['failed_weeks']), ('live', 2)) + def test_bad_timestamp_does_not_count(self): st_ = {'failed_weeks': 2, 'last_counted_at': 'garbage', 'first_failed_at': '2026-11-01T09:00:00Z'} self.assertFalse(refresh.counts_as_new_week(st_, '2026-11-22T09:00:00Z')) From c31e3aa93aaf22ad4dcc511c2e462eab0ea9d3a2 Mon Sep 17 00:00:00 2001 From: "cw-instinct[bot]" Date: Sun, 22 Nov 2026 00:05:02 +0200 Subject: [PATCH 3/4] Atlas refresh: persist an adopted state even when this run counts nothing Codex P1 on 5f585e03: state_before was taken after adopting a --state-from candidate, so a same-week rerun carrying a PR's state wrote nothing and the superseded PR branch was deleted with its counters. The run now compares with the state on disk. --- atlas/refresh.py | 6 +++++- tests/test_refresh_state_wording.py | 21 +++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/atlas/refresh.py b/atlas/refresh.py index 8b4b20e9..3a68a067 100644 --- a/atlas/refresh.py +++ b/atlas/refresh.py @@ -1052,6 +1052,8 @@ def main(): sources = load_json(a.sources, {}).get('sources', {}) state_raw = open(a.state, encoding='utf-8').read() if os.path.exists(a.state) else None state = json.loads(state_raw) if state_raw else {'version': 1, 'entries': {}, 'moved': {}} + state_on_disk = copy.deepcopy(state) + state_on_disk.setdefault('entries', {}); state_on_disk.setdefault('moved', {}) for path in (a.state_from or []): if not os.path.exists(path): continue @@ -1063,7 +1065,9 @@ def main(): print(f'starting from newer state {path} ({alt.get("updated_at")})') state = alt state.setdefault('entries', {}); state.setdefault('moved', {}) - state_before = copy.deepcopy(state) + # Compared with what --state holds on disk, not with the adopted state: an adopted state (open refresh PR, state kept by a failed + # run) must be written even when this run adds nothing, because the workflow deletes the superseded PR branch afterwards. + state_before = state_on_disk ts = now_iso() today = ts[:10] diff --git a/tests/test_refresh_state_wording.py b/tests/test_refresh_state_wording.py index 848070b3..69cdffe6 100644 --- a/tests/test_refresh_state_wording.py +++ b/tests/test_refresh_state_wording.py @@ -211,6 +211,27 @@ def test_newer_valid_state_wins_older_and_invalid_are_ignored(self): _, state, _ = run_refresh(main_state, [older, bad]) self.assertEqual(state['entries']['opentask']['failed_weeks'], 1) + def test_adopted_state_is_persisted_even_when_this_run_counts_nothing(self): + # Codex P1 on 5f585e03: carried PR state with 1 counted week, same-week rerun, nothing new. It must be written to --state. + with tempfile.TemporaryDirectory() as d: + carried = self.write(d, 'pr.json', fresh(1, '2026-11-22T09:00:00Z', '2026-11-22T09:00:00Z')) + snap, state, _ = run_refresh({'version': 1, 'moved': {}, 'entries': {}}, [carried], now='2026-11-23T09:00:00Z') + e = state['entries']['opentask'] + self.assertEqual((e['failed_weeks'], e['last_counted_at'], e['first_failed_at']), (1, '2026-11-22T09:00:00Z', '2026-11-22T09:00:00Z')) + self.assertEqual(snap['platforms'][0]['status'], 'live') + # and the next counted check still waits for 168 h from that count + _, early, _ = run_refresh(state, now='2026-11-29T08:00:00Z') + self.assertEqual(early['entries']['opentask']['failed_weeks'], 1) + s2, late, _ = run_refresh(early, now='2026-11-29T09:00:00Z') + self.assertEqual((s2['platforms'][0]['status'], late['entries']['opentask']['failed_weeks']), ('closed', 2)) + + def test_older_or_invalid_adopted_candidates_leave_the_disk_state_alone(self): + with tempfile.TemporaryDirectory() as d: + older = self.write(d, 'old.json', st(1, at='2026-10-01T00:00:00Z')) + _, state, _ = run_refresh({'version': 1, 'moved': {}, 'updated_at': '2026-11-10T00:00:00Z', 'entries': {}}, [older], now='2026-11-23T09:00:00Z') + self.assertEqual(state['entries']['opentask']['failed_weeks'], 1) # counted from the disk state (empty), not from the older candidate + self.assertNotEqual(state['entries']['opentask'].get('last_counted_at'), None) + def test_valid_state_shape(self): self.assertTrue(refresh.valid_state(st(1))) for bad in (None, [], {'version': 2, 'entries': {}}, {'version': 1, 'entries': []}, From fc6f09704ce11dd86739c51e961a57e9f0dc3683 Mon Sep 17 00:00:00 2001 From: "cw-instinct[bot]" Date: Sun, 22 Nov 2026 00:26:16 +0200 Subject: [PATCH 4/4] Atlas refresh: keep the failed-run state in the last step of the job Codex P2 on c31e3aa: failure() is evaluated when a step's turn comes, so the upload placed before Open PR could not see a failure of Open PR or of the cleanup. It is now the last step; a structural test pins the order and the condition. --- .github/workflows/refresh.yml | 18 +++++++------ tests/test_refresh_workflow_order.py | 40 ++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 8 deletions(-) create mode 100644 tests/test_refresh_workflow_order.py diff --git a/.github/workflows/refresh.yml b/.github/workflows/refresh.yml index 2f3edb60..2ce080df 100644 --- a/.github/workflows/refresh.yml +++ b/.github/workflows/refresh.yml @@ -80,14 +80,6 @@ jobs: python atlas/site/check.py - name: Smoke (browser) run: python atlas/site/tools/smoke_test.py - - name: Keep state if a later step failed - if: failure() && steps.refresh.outcome == 'success' - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 - with: - name: atlas-refresh-state - path: atlas/data/refresh-state.json - retention-days: 21 - if-no-files-found: error - name: Open PR if: steps.diff.outputs.changed == 'true' run: | @@ -116,3 +108,13 @@ jobs: else msg="Closed: the newest weekly refresh found no difference from main, so this PR is obsolete."; fi gh pr close "$n" --comment "$msg" --delete-branch || true done + - name: Keep state if any later step failed + # Last step on purpose: failure() is evaluated when the step's turn comes, so only a step placed after Open PR and the cleanup + # can see a failure of those. + if: failure() && steps.refresh.outcome == 'success' + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: atlas-refresh-state + path: atlas/data/refresh-state.json + retention-days: 21 + if-no-files-found: error diff --git a/tests/test_refresh_workflow_order.py b/tests/test_refresh_workflow_order.py new file mode 100644 index 00000000..2931fbfc --- /dev/null +++ b/tests/test_refresh_workflow_order.py @@ -0,0 +1,40 @@ +"""Structure of .github/workflows/refresh.yml (text only, no YAML library): the step that keeps refresh-state.json after a failure must run +after every publishing and cleanup step, otherwise failure() cannot see a failure of those steps (Codex P2 on PR 313).""" +import re +import unittest +from pathlib import Path + +WF = (Path(__file__).resolve().parents[1] / '.github/workflows/refresh.yml').read_text(encoding='utf-8') + + +def steps(): + out = [] + for p in re.split(r'(?m)^(?= - name: )', WF[WF.index(' steps:'):])[1:]: + out.append((re.match(r' - name: (.*)', p).group(1).strip(), p)) + return out + + +class Order(unittest.TestCase): + def test_keep_state_step_is_last_and_keeps_its_condition(self): + names = [n for n, _ in steps()] + keep = [i for i, n in enumerate(names) if n.startswith('Keep state')] + self.assertEqual(len(keep), 1) + self.assertEqual(keep[0], len(names) - 1, names) + body = steps()[keep[0]][1] + self.assertIn("if: failure() && steps.refresh.outcome == 'success'", body) + self.assertIn('name: atlas-refresh-state', body) + self.assertIn('path: atlas/data/refresh-state.json', body) + + def test_it_comes_after_refresh_and_every_publishing_or_cleanup_step(self): + names = [n for n, _ in steps()] + keep = next(i for i, n in enumerate(names) if n.startswith('Keep state')) + for must_precede in ('Refresh', 'Build', 'Check', 'Smoke (browser)', 'Open PR', 'Close superseded refresh PRs'): + self.assertLess(names.index(must_precede), keep, must_precede) + + def test_refresh_step_has_the_id_the_condition_reads(self): + refresh = next(b for n, b in steps() if n == 'Refresh') + self.assertIn('id: refresh', refresh) + + +if __name__ == '__main__': + unittest.main()