File size: 13,364 Bytes
4eef289
 
 
 
 
 
 
 
 
 
 
 
 
 
cad04d1
 
c10a376
4eef289
 
 
 
 
 
 
 
 
 
 
 
 
2c1b7e7
4eef289
 
 
2c1b7e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4eef289
 
 
 
 
 
 
 
 
2c1b7e7
 
 
4eef289
 
 
 
2c1b7e7
 
 
4eef289
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c10a376
4eef289
 
 
c10a376
 
 
 
 
 
 
 
4eef289
 
 
 
 
 
 
 
 
 
 
c10a376
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4eef289
 
 
 
 
 
cad04d1
 
 
 
 
 
 
 
 
 
 
 
4eef289
 
 
cad04d1
 
 
 
 
4eef289
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cad04d1
4eef289
 
 
 
 
cad04d1
4eef289
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cad04d1
4eef289
cad04d1
c10a376
4eef289
 
 
 
 
 
 
 
 
 
c10a376
 
 
 
 
 
 
 
 
 
 
 
 
 
4eef289
 
 
 
 
c10a376
 
 
 
 
4eef289
 
 
 
 
cad04d1
c10a376
 
4eef289
 
c10a376
4eef289
 
 
c10a376
4eef289
 
cad04d1
 
 
 
 
 
 
4eef289
 
 
c10a376
4eef289
 
 
 
 
 
 
 
 
 
 
c10a376
 
 
 
 
 
 
 
cad04d1
 
 
 
 
 
 
 
 
 
 
 
 
c10a376
 
cad04d1
 
 
 
 
 
 
 
 
 
c10a376
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4eef289
 
 
 
 
 
 
 
 
 
 
cad04d1
4eef289
 
 
 
 
2c1b7e7
4eef289
 
c10a376
 
 
4eef289
 
 
 
 
 
 
 
 
 
 
cad04d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4eef289
cad04d1
4eef289
 
 
 
c10a376
 
 
 
 
4eef289
 
 
 
 
 
cad04d1
 
 
 
 
 
 
 
 
c10a376
cad04d1
 
 
 
 
 
 
 
 
 
 
 
c10a376
4eef289
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
"""Run PR preflight checks in isolated parallel local lanes.

The regular CI preflight stays the serial source of truth. This runner is a
fast local front door: it selects the same checks, groups independent work into
lanes, and runs each lane in a temporary git worktree so caches, graph hydration,
and package builds do not contend with each other.
"""

from __future__ import annotations

import argparse
from concurrent.futures import ThreadPoolExecutor
from concurrent.futures import as_completed
from dataclasses import dataclass
from datetime import UTC
from datetime import datetime
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import time

REPO_ROOT = Path(__file__).resolve().parents[1]
if str(REPO_ROOT) not in sys.path:
    sys.path.insert(0, str(REPO_ROOT))

from scripts.ci_preflight import Check  # noqa: E402
from scripts.ci_preflight import PROFILE_CHOICES  # noqa: E402
from scripts.ci_preflight import changed_files  # noqa: E402
from scripts.ci_preflight import select_checks  # noqa: E402

LANE_ORDER = (
    "cheap",
    "static",
    "unit",
    "canary",
    "contract",
    "clean-host",
    "docs",
    "graph",
    "telemetry",
    "similarity",
    "browser",
    "package",
    "misc",
)
CHECK_LANES = {
    "whitespace": "cheap",
    "repo stats": "cheap",
    "no-test policy": "cheap",
    "ruff format": "static",
    "ruff": "static",
    "mypy": "static",
    "pip check": "static",
    "unit-linux equivalent": "unit",
    "A-Z canary": "canary",
    "contract compatibility local": "contract",
    "clean host contract": "clean-host",
    "public docs tracker": "docs",
    "docs strict build": "docs",
    "hydrate graph LFS": "graph",
    "graph artifact validation": "graph",
    "telemetry enterprise": "telemetry",
    "similarity precision/recall": "similarity",
    "browser monitor security": "browser",
    "clean preflight dist": "package",
    "build wheel": "package",
    "twine check": "package",
}


@dataclass(frozen=True)
class Lane:
    name: str
    checks: tuple[Check, ...]


@dataclass(frozen=True)
class LaneResult:
    name: str
    returncode: int
    elapsed: float
    check_count: int
    worktree: Path | None = None


@dataclass(frozen=True)
class GateResult:
    returncode: int
    elapsed: float
    worker_count: int
    lanes: tuple[LaneResult, ...]


def _lane_name(check: Check) -> str:
    return CHECK_LANES.get(check.name, "misc")


def group_checks(checks: list[Check]) -> list[Lane]:
    grouped: dict[str, list[Check]] = {lane: [] for lane in LANE_ORDER}
    for check in checks:
        grouped[_lane_name(check)].append(_worktree_safe_check(check))
    return [Lane(name, tuple(grouped[name])) for name in LANE_ORDER if grouped[name]]


def filter_lanes(
    lanes: list[Lane],
    *,
    include: tuple[str, ...] = (),
    skip: tuple[str, ...] = (),
) -> list[Lane]:
    include_set = set(include)
    skip_set = set(skip)
    return [
        lane
        for lane in lanes
        if (not include_set or lane.name in include_set) and lane.name not in skip_set
    ]


def _worktree_safe_check(check: Check) -> Check:
    ci_preflight = (REPO_ROOT / "scripts" / "ci_preflight.py").resolve()
    argv = tuple(
        "scripts/ci_preflight.py" if _same_path_arg(arg, ci_preflight) else arg
        for arg in check.argv
    )
    if check.name == "unit-linux equivalent":
        try:
            workers_index = argv.index("-n") + 1
        except ValueError:
            pass
        else:
            if workers_index < len(argv) and argv[workers_index] == "auto":
                argv = (
                    *argv[:workers_index],
                    str(_local_xdist_workers()),
                    *argv[workers_index + 1 :],
                )
    return Check(check.name, argv, check.env)


def _local_xdist_workers() -> int:
    cpu_count = os.cpu_count() or 2
    return max(1, min(4, cpu_count // 4))


def _same_path_arg(arg: str, expected: Path) -> bool:
    try:
        return Path(arg).resolve() == expected
    except OSError:
        return False


def _git_stdout(args: list[str]) -> str:
    return subprocess.check_output(["git", *args], cwd=REPO_ROOT, text=True)


def _is_worktree_dirty() -> bool:
    return bool(_git_stdout(["status", "--porcelain"]).strip())


def _create_worktree(lane: str, *, revision: str) -> Path:
    parent = Path(tempfile.mkdtemp(prefix="ctx-local-fast-"))
    worktree = parent / lane
    env = os.environ.copy()
    env.setdefault("GIT_LFS_SKIP_SMUDGE", "1")
    subprocess.check_call(
        ["git", "worktree", "add", "--detach", str(worktree), revision],
        cwd=REPO_ROOT,
        env=env,
        stdout=subprocess.DEVNULL,
    )
    return worktree


def _remove_worktree(worktree: Path) -> None:
    subprocess.run(
        ["git", "worktree", "remove", "--force", str(worktree)],
        cwd=REPO_ROOT,
        check=False,
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL,
    )
    shutil.rmtree(worktree.parent, ignore_errors=True)


def _run_check(check: Check, *, cwd: Path, index: int, total: int, lane: str) -> int:
    print(
        f"[{lane} {index}/{total}] {check.name}: {' '.join(check.argv)}",
        flush=True,
    )
    env = os.environ.copy()
    env.setdefault("PYTHONDONTWRITEBYTECODE", "1")
    env.setdefault("PIP_DISABLE_PIP_VERSION_CHECK", "1")
    env.setdefault("GIT_LFS_SKIP_SMUDGE", "1")
    if check.env:
        env.update(check.env)
    proc = subprocess.run(check.argv, cwd=cwd, check=False, env=env)
    if proc.returncode != 0:
        print(f"[{lane} fail] {check.name} exited {proc.returncode}", file=sys.stderr)
    return proc.returncode


def run_lane(lane: Lane, *, keep_worktrees: bool, revision: str = "HEAD") -> LaneResult:
    start = time.monotonic()
    worktree = _create_worktree(lane.name, revision=revision)
    summary_worktree = worktree if keep_worktrees else None
    try:
        for index, check in enumerate(lane.checks, start=1):
            returncode = _run_check(
                check,
                cwd=worktree,
                index=index,
                total=len(lane.checks),
                lane=lane.name,
            )
            if returncode != 0:
                return LaneResult(
                    lane.name,
                    returncode,
                    time.monotonic() - start,
                    len(lane.checks),
                    summary_worktree,
                )
        return LaneResult(
            lane.name,
            0,
            time.monotonic() - start,
            len(lane.checks),
            summary_worktree,
        )
    finally:
        if not keep_worktrees:
            _remove_worktree(worktree)


def _sort_lane_results(results: list[LaneResult]) -> tuple[LaneResult, ...]:
    order = {name: index for index, name in enumerate(LANE_ORDER)}
    return tuple(sorted(results, key=lambda result: order.get(result.name, len(order))))


def run_lanes(
    lanes: list[Lane],
    *,
    jobs: int,
    keep_worktrees: bool = False,
    revision: str = "HEAD",
) -> GateResult:
    start = time.monotonic()
    if not lanes:
        print("No local-fast lanes selected.")
        return GateResult(0, 0.0, 0, ())
    worker_count = max(1, min(jobs, len(lanes)))
    print(f"Running {len(lanes)} local-fast lanes with {worker_count} workers.")
    failures: list[LaneResult] = []
    results: list[LaneResult] = []
    with ThreadPoolExecutor(max_workers=worker_count) as executor:
        futures = {
            executor.submit(
                run_lane,
                lane,
                keep_worktrees=keep_worktrees,
                revision=revision,
            ): lane
            for lane in lanes
        }
        for future in as_completed(futures):
            result = future.result()
            results.append(result)
            status = "pass" if result.returncode == 0 else "fail"
            print(f"[{status}] {result.name} lane in {result.elapsed:.1f}s")
            if result.returncode != 0:
                failures.append(result)

    if failures:
        for failure in failures:
            print(
                f"[fail] {failure.name} lane exited {failure.returncode}",
                file=sys.stderr,
            )
    return GateResult(
        1 if failures else 0,
        time.monotonic() - start,
        worker_count,
        _sort_lane_results(results),
    )


def write_summary_json(
    path: Path,
    result: GateResult,
    *,
    head_sha: str,
    base_ref: str,
    base_sha: str,
    profile: str,
    source_worktree_dirty_at_selection: bool,
    changed_file_paths: list[str],
    started_at: str,
    finished_at: str,
) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    payload = {
        "schema_version": 2,
        "head_sha": head_sha,
        "base_ref": base_ref,
        "base_sha": base_sha,
        "profile": profile,
        "committed_head_only": True,
        "source_worktree_dirty_at_selection": source_worktree_dirty_at_selection,
        "changed_file_paths": changed_file_paths,
        "started_at": started_at,
        "finished_at": finished_at,
        "returncode": result.returncode,
        "elapsed_seconds": round(result.elapsed, 3),
        "worker_count": result.worker_count,
        "lanes": [
            {
                "name": lane.name,
                "returncode": lane.returncode,
                "elapsed_seconds": round(lane.elapsed, 3),
                "check_count": lane.check_count,
                "worktree": str(lane.worktree) if lane.worktree else None,
            }
            for lane in result.lanes
        ],
    }
    path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")


def print_dry_run(lanes: list[Lane]) -> None:
    for lane in lanes:
        print(f"[lane] {lane.name}")
        for check in lane.checks:
            print(f"  - {check.name}: {' '.join(check.argv)}")


def _default_jobs() -> int:
    cpu_count = os.cpu_count() or 2
    return max(1, min((cpu_count + 1) // 2, len(LANE_ORDER)))


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--base", default="origin/main")
    parser.add_argument("--profile", choices=PROFILE_CHOICES, default="pr")
    parser.add_argument("--python", default=sys.executable)
    parser.add_argument("--jobs", type=int, default=_default_jobs())
    parser.add_argument("--lane", action="append", choices=LANE_ORDER)
    parser.add_argument("--skip-lane", action="append", choices=LANE_ORDER)
    parser.add_argument("--summary-json", type=Path)
    parser.add_argument("--dry-run", action="store_true")
    parser.add_argument("--keep-worktrees", action="store_true")
    parser.add_argument(
        "--allow-dirty",
        action="store_true",
        help="allow a dirty worktree; uncommitted changes still are not run in temp worktrees",
    )
    args = parser.parse_args(argv)

    if not shutil.which("git"):
        raise SystemExit("git is required for local_fast_gate")
    if args.dry_run:
        files = changed_files(args.base)
        selection_base = args.base
    else:
        started_at = datetime.now(UTC).isoformat()
        source_worktree_dirty_at_selection = _is_worktree_dirty()
        if not args.allow_dirty and source_worktree_dirty_at_selection:
            raise SystemExit(
                "local-fast runs committed HEAD in temp worktrees; commit or stash changes first "
                "(or pass --allow-dirty if you only need a committed-HEAD gate)."
            )
        head_sha = _git_stdout(["rev-parse", "HEAD"]).strip()
        base_sha = _git_stdout(["merge-base", args.base, head_sha]).strip()
        if not head_sha or not base_sha:
            raise SystemExit("could not resolve committed HEAD and comparison base")
        files = changed_files(base_sha, head_ref=head_sha)
        selection_base = base_sha
    checks, notes = select_checks(
        base_ref=selection_base,
        files=files,
        profile=args.profile,
        python=args.python,
    )
    lanes = filter_lanes(
        group_checks(checks),
        include=tuple(args.lane or ()),
        skip=tuple(args.skip_lane or ()),
    )
    for note in notes:
        print(f"[note] {note}")
    print("[note] local-fast runs selected committed-HEAD checks in isolated temp worktrees.")
    if args.dry_run:
        print_dry_run(lanes)
        return 0
    if _git_stdout(["rev-parse", "HEAD"]).strip() != head_sha:
        raise SystemExit("HEAD changed while local-fast selected checks")
    result = run_lanes(
        lanes,
        jobs=args.jobs,
        keep_worktrees=args.keep_worktrees,
        revision=head_sha,
    )
    finished_at = datetime.now(UTC).isoformat()
    if args.summary_json:
        write_summary_json(
            args.summary_json,
            result,
            head_sha=head_sha,
            base_ref=args.base,
            base_sha=base_sha,
            profile=args.profile,
            source_worktree_dirty_at_selection=source_worktree_dirty_at_selection,
            changed_file_paths=files,
            started_at=started_at,
            finished_at=finished_at,
        )
    return result.returncode


if __name__ == "__main__":
    raise SystemExit(main())