Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

ci: scope ci-gate with the crate and package graph (CUA-3134) (#6369)

cua-agents[bot]1c13fb7d468e
diff --git a/.github/ci-areas.json b/.github/ci-areas.json
index a7e6740141..e12436af4e 100644
--- a/.github/ci-areas.json
+++ b/.github/ci-areas.json
@@ -2,26 +2,16 @@
"shared": [
".github/**",
"*",
- "**/Cargo.lock",
- "**/rust-toolchain.toml",
- "**/pnpm-lock.yaml",
- "**/pnpm-workspace.yaml",
- "**/package-lock.json",
"**/uv.lock",
- "libs/cua/Cargo.toml",
- "libs/cua-driver/rust/Cargo.toml",
- "libs/cua-spacesd/Cargo.toml",
- "libs/cua-driver/rust/.cargo/**",
- "libs/cua/.cargo/**",
- "libs/cua/proto/**",
- "libs/cua/crates/cua-proto/**",
- "libs/cua-driver/rust/crates/cua-driver-core/**",
- "libs/cua-driver/rust/crates/cua-driver-contract/**",
- "libs/cua/crates/cua-sandbox-core/**",
"scripts/ci/**",
"flake.nix",
"nix/**"
],
+ "inputs": {
+ "libs/cua/proto/**": [
+ "libs/cua/crates/cua-proto"
+ ]
+ },
"areas": {
"relay": {
"paths": [
@@ -254,9 +244,12 @@
},
"spaces-macos": {
"paths": [
- "apps/cua-spaces-macos/**"
+ "apps/cua-spaces-macos/**",
+ "libs/spaces-app-swift/**",
+ "libs/spaces-notch-swift/**"
],
"workflows": [
+ "ci-check-docs-image-refs.yml",
"ci-check-docs-links.yml",
"ci-cua-spaces-macos.yml",
"ci-cua-spaces-web.yml",
@@ -361,7 +354,8 @@
"docs": {
"paths": [
"docs/**",
- "skills/**"
+ "skills/**",
+ "scripts/docs-generators/**"
],
"workflows": [
"ci-check-docs-image-refs.yml",
diff --git a/.github/scripts/ci_gate_scope.py b/.github/scripts/ci_gate_scope.py
index 25c0863173..297795a98d 100644
--- a/.github/scripts/ci_gate_scope.py
+++ b/.github/scripts/ci_gate_scope.py
@@ -2,15 +2,28 @@
"""Decide which workflows `ci-gate` must wait for, from the paths a PR changes.
The area map lives in `.github/ci-areas.json` and is documented in
-`docs/contributing/CI.md`. The rules, in order:
-
-1. A changed file that matches `shared`, or matches no area, widens the gate to
- every workflow (the behaviour before path scoping).
-2. Otherwise each changed file belongs to the first area whose globs match it.
-3. A workflow listed under some area is required only when one of its areas
+`docs/contributing/CI.md`. The package graph comes from the manifests
+(`ci_graph.py`). The rules, in order:
+
+1. A changed file that matches `shared` widens the gate to every workflow.
+2. A workspace file (a Cargo or pnpm workspace's root manifest, lockfile,
+ toolchain pin or `.cargo/`) affects every member of that workspace.
+3. A file inside a package (the deepest `Cargo.toml` or `package.json`
+ directory above it) affects that package; a file listed under `inputs`
+ affects the packages named there.
+4. Every affected package also affects every package that depends on it,
+ transitively. Each affected package adds the area its directory is in.
+5. Any other file adds the first area whose globs match it. A file, or an
+ affected package, that matches no area widens the gate to every workflow.
+6. A workflow listed under some area is required only when one of its areas
changed. A workflow listed under no area is always required, so a new or
unmapped workflow can never be skipped by accident.
+The gate runs this script, the map and the graph from the base branch, so a
+pull request cannot narrow its own gate by editing them. It also reads the
+pull request's manifests and adds their edges, so a dependency the pull request
+adds counts too.
+
The gate itself never decides what a workflow's own `paths:` filter runs; it
only decides which of the runs that exist it waits for.
"""
@@ -23,6 +36,9 @@ import re
import sys
from pathlib import Path
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+import ci_graph # noqa: E402
+
ROOT = Path(__file__).resolve().parents[2]
MAP_PATH = ROOT / '.github/ci-areas.json'
WORKFLOWS = ROOT / '.github/workflows'
@@ -90,16 +106,54 @@ def area_of(path: str, cfg: dict) -> str | None:
return None
-def scope(files: list[str], cfg: dict) -> tuple[list[str], set[str] | None]:
- """Return (changed areas, workflows to ignore). Ignore is None when nothing is."""
- areas: set[str] = set()
+def load_graph(roots: list[Path] | None = None) -> ci_graph.Graph:
+ """The package graph of the base tree, plus the pull request's edges (CI_GATE_HEAD_ROOT)."""
+ if roots is None:
+ roots = [ROOT]
+ head = os.environ.get('CI_GATE_HEAD_ROOT')
+ if head:
+ roots.append(Path(head))
+ return ci_graph.union([ci_graph.load(r) for r in roots])
+
+
+def affected_packages(files: list[str], cfg: dict, graph: ci_graph.Graph) -> tuple[set[str], set[str], bool]:
+ """Return (packages the files touch directly, non-package files, everything)."""
+ seeds: set[str] = set()
+ loose: set[str] = set()
for f in files:
- a = area_of(f, cfg)
+ if matches(f, cfg['shared']):
+ return set(), set(), True
+ ws = graph.workspace_file(f)
+ if ws is not None:
+ seeds |= graph.members(ws)
+ continue
+ inputs = [pkg for glob, pkgs in cfg.get('inputs', {}).items() if matches(f, [glob]) for pkg in pkgs]
+ if inputs:
+ seeds.update(p for p in inputs if p in graph.packages)
+ loose.add(f) # an input still counts for its own area
+ continue
+ owner = graph.owner(f)
+ if owner is not None:
+ seeds.add(owner)
+ else:
+ loose.add(f)
+ return seeds, loose, False
+
+
+def scope(files: list[str], cfg: dict, graph: ci_graph.Graph | None = None) -> tuple[list[str], set[str] | None]:
+ """Return (changed areas, workflows to ignore). Ignore is empty when nothing is."""
+ if not files:
+ return ['all'], set()
+ graph = graph if graph is not None else load_graph()
+ seeds, loose, everything = affected_packages(files, cfg, graph)
+ if everything:
+ return ['all'], set()
+ areas: set[str] = set()
+ for path in sorted(loose) + [d + '/' for d in sorted(graph.dependents(seeds))]:
+ a = area_of(path, cfg)
if a is None:
return ['all'], set()
areas.add(a)
- if not files:
- return ['all'], set()
mapped = {w for a in cfg['areas'].values() for w in a['workflows']}
needed = {w for name in areas for w in cfg['areas'][name]['workflows']}
return sorted(areas), mapped - needed
@@ -146,11 +200,16 @@ def main() -> int:
args = ap.parse_args()
cfg = load_map(args.map)
files = [l.strip() for l in sys.stdin if l.strip()]
- areas, ignored = scope(files, cfg)
+ graph = load_graph()
+ seeds, _, _ = affected_packages(files, cfg, graph)
+ affected = graph.dependents(seeds)
+ areas, ignored = scope(files, cfg, graph)
regex = ignore_regex(ignored)
urgent = 'urgent' in [l.strip() for l in args.labels.split(',')]
lines = [
f'changed files: {len(files)}',
+ f'packages affected (changed, plus their dependents): {len(affected)}'
+ + (f' ({", ".join(sorted(graph.packages[d].name for d in affected))})' if 0 < len(affected) <= 40 else ''),
f'areas: {", ".join(areas)}',
f'workflows the gate ignores: {", ".join(sorted(ignored)) or "none (waits for every run)"}',
]
diff --git a/.github/scripts/ci_graph.py b/.github/scripts/ci_graph.py
new file mode 100644
index 0000000000..179a996809
--- /dev/null
+++ b/.github/scripts/ci_graph.py
@@ -0,0 +1,257 @@
+#!/usr/bin/env python3
+"""The repo's package dependency graph, read from the manifests.
+
+`ci_gate_scope.py` uses it so a change to a shared crate or package waits for the
+workflows of everything that depends on it, and nothing else. It reads only
+manifests (every `Cargo.toml`, `package.json` and `pnpm-workspace.yaml`), so the
+gate needs no toolchain and no network. `.github/scripts/tests/test_ci_graph.py`
+checks the Cargo edges against `cargo metadata`.
+
+Nodes are package directories (repo-relative, no trailing slash):
+
+* Cargo: every manifest with a `[package]`. An edge is a `path` dependency in
+ `[dependencies]`, `[dev-dependencies]`, `[build-dependencies]` or any
+ `[target.*.*dependencies]`, including `workspace = true` entries resolved
+ through the workspace root's `[workspace.dependencies]`.
+* JavaScript: every `package.json` with a `name`. An edge is a `workspace:`,
+ `link:` or `file:` dependency on another package in the repo.
+
+A workspace is the directory of a `[workspace]` manifest or a
+`pnpm-workspace.yaml`. Its lockfile, toolchain pin and root manifest are
+workspace files: changing one affects every member.
+"""
+from __future__ import annotations
+
+import json
+import os
+import posixpath
+import sys
+from dataclasses import dataclass, field
+from pathlib import Path
+
+try:
+ import tomllib
+except ModuleNotFoundError: # Python < 3.11
+ import tomli as tomllib # type: ignore[no-redef]
+
+ROOT = Path(__file__).resolve().parents[2]
+SKIP_DIRS = {'.git', 'node_modules', 'target', '.build', 'dist', '.next', '.venv', 'vendor'}
+DEP_TABLES = ('dependencies', 'dev-dependencies', 'build-dependencies')
+JS_DEP_TABLES = ('dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies')
+# Files at a workspace root that every member builds with.
+CARGO_WORKSPACE_FILES = ('Cargo.toml', 'Cargo.lock', 'rust-toolchain.toml', 'rust-toolchain', '.cargo/')
+PNPM_WORKSPACE_FILES = ('pnpm-workspace.yaml', 'pnpm-lock.yaml', 'package.json', '.npmrc')
+
+
+@dataclass
+class Package:
+ dir: str
+ name: str
+ kind: str # 'cargo' or 'js'
+ workspace: str
+ deps: set[str] = field(default_factory=set) # dirs of packages this one depends on
+
+
+@dataclass
+class Graph:
+ packages: dict[str, Package]
+ workspaces: dict[str, str] # workspace dir -> 'cargo' or 'js'
+
+ # --- queries -------------------------------------------------------------
+
+ def owner(self, path: str) -> str | None:
+ """The deepest package directory that contains `path`."""
+ d = posixpath.dirname(path)
+ while True:
+ if d in self.packages:
+ return d
+ if not d:
+ return None
+ d = posixpath.dirname(d)
+
+ def workspace_file(self, path: str) -> str | None:
+ """The workspace whose root lockfile, manifest or toolchain pin `path` is."""
+ for ws, kind in self.workspaces.items():
+ rel = path[len(ws) + 1:] if ws and path.startswith(ws + '/') else (path if not ws else None)
+ if rel is None:
+ continue
+ names = CARGO_WORKSPACE_FILES if kind == 'cargo' else PNPM_WORKSPACE_FILES
+ if any(rel == n or (n.endswith('/') and rel.startswith(n)) for n in names):
+ return ws
+ return None
+
+ def members(self, ws: str) -> set[str]:
+ return {d for d, p in self.packages.items() if p.workspace == ws}
+
+ def dependents(self, dirs: set[str]) -> set[str]:
+ """`dirs` plus every package that depends on one of them, transitively."""
+ rev: dict[str, set[str]] = {}
+ for d, p in self.packages.items():
+ for dep in p.deps:
+ rev.setdefault(dep, set()).add(d)
+ out, todo = set(dirs), list(dirs)
+ while todo:
+ for d in rev.get(todo.pop(), ()):
+ if d not in out:
+ out.add(d)
+ todo.append(d)
+ return out
+
+ def closure(self, dirs: set[str]) -> set[str]:
+ """`dirs` plus everything they depend on, transitively."""
+ out, todo = set(dirs), list(dirs)
+ while todo:
+ p = self.packages.get(todo.pop())
+ for dep in (p.deps if p else ()):
+ if dep not in out:
+ out.add(dep)
+ todo.append(dep)
+ return out
+
+ def by_name(self, name: str) -> list[str]:
+ return sorted(d for d, p in self.packages.items() if p.name == name)
+
+
+# --- loading -----------------------------------------------------------------
+
+
+def _walk(root: Path, names: set[str]) -> list[str]:
+ found = []
+ for dirpath, dirnames, filenames in os.walk(root):
+ dirnames[:] = [d for d in dirnames if d not in SKIP_DIRS]
+ for f in filenames:
+ if f in names:
+ found.append(Path(dirpath, f).relative_to(root).as_posix())
+ return sorted(found)
+
+
+def _norm(base: str, rel: str) -> str:
+ out = posixpath.normpath(posixpath.join(base, rel))
+ return '' if out == '.' else out
+
+
+def _cargo_dep_specs(manifest: dict):
+ for table in DEP_TABLES:
+ yield from (manifest.get(table) or {}).items()
+ for target in (manifest.get('target') or {}).values():
+ for table in DEP_TABLES:
+ yield from (target.get(table) or {}).items()
+
+
+def load(root: Path = ROOT) -> Graph:
+ files = _walk(root, {'Cargo.toml', 'package.json', 'pnpm-workspace.yaml'})
+ packages: dict[str, Package] = {}
+ workspaces: dict[str, str] = {}
+ ws_deps: dict[str, dict] = {}
+ cargo: dict[str, dict] = {}
+
+ for f in files:
+ d = posixpath.dirname(f)
+ name = posixpath.basename(f)
+ if name == 'Cargo.toml':
+ try:
+ data = tomllib.loads((root / f).read_text())
+ except (OSError, tomllib.TOMLDecodeError):
+ continue # templates and fixtures that are not real manifests
+ cargo[d] = data
+ if 'workspace' in data:
+ workspaces[d] = 'cargo'
+ ws_deps[d] = (data['workspace'].get('dependencies') or {})
+ elif name == 'pnpm-workspace.yaml':
+ workspaces[d] = 'js'
+
+ def nearest_ws(d: str, kind: str) -> str:
+ cur = d
+ while True:
+ if workspaces.get(cur) == kind:
+ return cur
+ if not cur:
+ return d
+ cur = posixpath.dirname(cur)
+
+ for d, data in cargo.items():
+ pkg = data.get('package')
+ if not isinstance(pkg, dict) or 'name' not in pkg:
+ continue
+ ws = nearest_ws(d, 'cargo')
+ p = Package(d, pkg['name'], 'cargo', ws)
+ for key, spec in _cargo_dep_specs(data):
+ if not isinstance(spec, dict):
+ continue
+ if spec.get('workspace') is True:
+ spec = ws_deps.get(ws, {}).get(key)
+ if isinstance(spec, dict) and 'path' in spec:
+ p.deps.add(_norm(ws, spec['path']))
+ elif 'path' in spec:
+ p.deps.add(_norm(d, spec['path']))
+ packages[d] = p
+
+ js: dict[str, dict] = {}
+ for f in files:
+ if posixpath.basename(f) != 'package.json':
+ continue
+ try:
+ data = json.loads((root / f).read_text())
+ except (OSError, ValueError):
+ continue
+ if isinstance(data, dict) and isinstance(data.get('name'), str):
+ js[posixpath.dirname(f)] = data
+ names: dict[tuple[str, str], str] = {}
+ for d, data in js.items():
+ ws = nearest_ws(d, 'js')
+ if d in packages: # a crate and a JS package in one directory: keep the crate
+ continue
+ packages[d] = Package(d, data['name'], 'js', ws)
+ names[(ws, data['name'])] = d
+ for d, data in js.items():
+ p = packages.get(d)
+ if not p or p.kind != 'js':
+ continue
+ for table in JS_DEP_TABLES:
+ for dep, spec in (data.get(table) or {}).items():
+ if not isinstance(spec, str):
+ continue
+ if spec.startswith('workspace:'):
+ target = names.get((p.workspace, dep))
+ if target:
+ p.deps.add(target)
+ elif spec.startswith(('link:', 'file:')):
+ target = _norm(d, spec.split(':', 1)[1])
+ if target in js:
+ p.deps.add(target)
+
+ for p in packages.values():
+ p.deps = {dep for dep in p.deps if dep in packages and dep != p.dir}
+ return Graph(packages, workspaces)
+
+
+def union(graphs: list[Graph]) -> Graph:
+ """One graph with every package, workspace and edge of `graphs` (base and head trees)."""
+ packages: dict[str, Package] = {}
+ workspaces: dict[str, str] = {}
+ for g in graphs:
+ workspaces.update(g.workspaces)
+ for d, p in g.packages.items():
+ if d in packages:
+ packages[d].deps |= p.deps
+ else:
+ packages[d] = Package(p.dir, p.name, p.kind, p.workspace, set(p.deps))
+ return Graph(packages, workspaces)
+
+
+def main() -> int:
+ g = load()
+ if len(sys.argv) > 1:
+ for name in sys.argv[1:]:
+ for d in g.by_name(name) or [name]:
+ deps = sorted(g.dependents({d}) - {d})
+ print(f'{d} ({len(deps)} dependents)')
+ for dep in deps:
+ print(f' {dep}')
+ return 0
+ print(json.dumps({d: sorted(p.deps) for d, p in sorted(g.packages.items())}, indent=1))
+ return 0
+
+
+if __name__ == '__main__':
+ sys.exit(main())
diff --git a/.github/scripts/tests/test_ci_gate_scope.py b/.github/scripts/tests/test_ci_gate_scope.py
index b27adf6b0f..6e17cf8141 100644
--- a/.github/scripts/tests/test_ci_gate_scope.py
+++ b/.github/scripts/tests/test_ci_gate_scope.py
@@ -1,5 +1,6 @@
import json
import os
+import shutil
import subprocess
import sys
from pathlib import Path
@@ -10,23 +11,29 @@ import yaml
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import ci_gate_scope as scope # noqa: E402
+import ci_graph # noqa: E402
CFG = scope.load_map()
+GRAPH = ci_graph.load()
WORKFLOWS = sorted(scope.WORKFLOWS.glob('*.yml'))
MAPPED = {w for a in CFG['areas'].values() for w in a['workflows']}
def ignored(*files):
- return scope.scope(list(files), CFG)[1]
+ return scope.scope(list(files), CFG, GRAPH)[1]
-def test_relay_only_change_waits_on_relay_and_rust_jobs_only():
- areas, skip = scope.scope(['libs/cua-spacesd/crates/cua-relay/src/mesh.rs'], CFG)
- assert areas == ['relay']
- assert not skip & {'ci-cua-relay-image.yml', 'ci-cua-spacesd.yml'}
- # The slow image, SDK and doctor jobs belong to other areas and do not gate a relay change.
- assert skip >= {'cd-image-linux.yml', 'e2e-cua-sdk.yml', 'ci-cua-sandbox-doctor.yml',
- 'ci-cua-oci-spacesd.yml', 'ci-cua-spaces-web.yml', 'ci-cua-spaces-macos.yml'}
+def areas_of(*files):
+ return scope.scope(list(files), CFG, GRAPH)[0]
+
+
+def test_relay_change_also_waits_on_the_spacesd_crates_that_link_the_relay():
+ # cua-spacesd and cua-spacesd-server depend on cua-relay, so a relay change
+ # waits on the spacesd area too (the hand-narrowed relay area alone missed it).
+ areas, skip = scope.scope(['libs/cua-spacesd/crates/cua-relay/src/mesh.rs'], CFG, GRAPH)
+ assert areas == ['relay', 'spacesd']
+ assert not skip & {'ci-cua-relay-image.yml', 'ci-cua-spacesd.yml', 'e2e-cua-sdk.yml'}
+ assert skip >= {'ci-cua-spaces-web.yml', 'ci-cua-spaces-macos.yml', 'ci-swift-lume.yml'}
def test_other_spacesd_change_still_waits_on_the_integration_jobs():
@@ -43,20 +50,124 @@ def test_a_change_in_two_areas_needs_both_areas_jobs():
@pytest.mark.parametrize('path', [
- 'Cargo.lock', 'libs/cua-driver/rust/Cargo.lock', 'README.md', 'package.json',
- '.github/workflows/ci-gate.yml', '.github/ci-areas.json', 'libs/cua/proto/a.proto',
- 'libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs',
- 'libs/cua/crates/cua-proto/src/lib.rs', 'rust-toolchain.toml',
+ 'Cargo.lock', 'README.md', 'package.json', 'rust-toolchain.toml',
+ '.github/workflows/ci-gate.yml', '.github/ci-areas.json', '.github/scripts/ci_graph.py',
+ 'scripts/ci/prepush.sh', 'nix/cua-driver/default.nix', 'libs/python/agent/uv.lock',
'some/unmapped/dir/file.txt',
])
def test_shared_and_unknown_files_wait_on_everything(path):
- areas, skip = scope.scope(['libs/cua-spacesd/crates/cua-relay/a.rs', path], CFG)
+ areas, skip = scope.scope(['libs/cua-spacesd/crates/cua-relay/a.rs', path], CFG, GRAPH)
assert areas == ['all']
assert skip == set()
def test_empty_change_list_waits_on_everything():
- assert scope.scope([], CFG) == (['all'], set())
+ assert scope.scope([], CFG, GRAPH) == (['all'], set())
+
+
+# --- the package graph -----------------------------------------------------
+
+
+def dependent_areas(pkg):
+ return {scope.area_of(d + '/', CFG) for d in GRAPH.dependents({pkg})}
+
+
[email protected](('path', 'pkg'), [
+ ('libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs', 'libs/cua-driver/rust/crates/cua-driver-core'),
+ ('libs/cua-driver/rust/crates/cua-driver-contract/src/lib.rs', 'libs/cua-driver/rust/crates/cua-driver-contract'),
+ ('libs/cua/crates/cua-proto/src/lib.rs', 'libs/cua/crates/cua-proto'),
+ ('libs/cua/crates/cua-sandbox-core/src/lib.rs', 'libs/cua/crates/cua-sandbox-core'),
+ ('libs/cua/proto/cua/v1/a.proto', 'libs/cua/crates/cua-proto'),
+])
+def test_a_shared_crate_waits_on_every_dependent_area_and_no_other(path, pkg):
+ areas = set(areas_of(path))
+ assert 'all' not in areas
+ assert areas >= dependent_areas(pkg)
+ assert areas == dependent_areas(pkg) | {scope.area_of(path, CFG)}
+
+
+def test_driver_core_change_waits_on_its_spacesd_dependents_but_not_on_docs_only_jobs():
+ skip = ignored('libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs')
+ assert 'ci-cua-spacesd.yml' not in skip # cua-spacesd depends on the driver core
+ assert 'ci-rust-linux.yml' not in skip
+ assert {'ci-cua-spaces-web.yml', 'ci-swift-lume.yml'} <= skip
+
+
[email protected](('path', 'workspace'), [
+ ('libs/cua-driver/rust/Cargo.lock', 'libs/cua-driver/rust'),
+ ('libs/cua-driver/rust/Cargo.toml', 'libs/cua-driver/rust'),
+ ('libs/cua-driver/rust/.cargo/config.toml', 'libs/cua-driver/rust'),
+ ('libs/cua-spacesd/Cargo.lock', 'libs/cua-spacesd'),
+ ('libs/cua/Cargo.toml', 'libs/cua'),
+ ('docs/pnpm-lock.yaml', 'docs'),
+ ('libs/typescript/pnpm-workspace.yaml', 'libs/typescript'),
+])
+def test_a_workspace_file_affects_every_member_and_its_dependents(path, workspace):
+ members = GRAPH.members(workspace)
+ assert members
+ expected = {scope.area_of(d + '/', CFG) for d in GRAPH.dependents(members)}
+ assert set(areas_of(path)) == expected
+
+
+def test_a_lockfile_in_one_workspace_does_not_wait_on_unrelated_lanes():
+ assert areas_of('docs/pnpm-lock.yaml') == ['docs']
+ skip = ignored('libs/cua-spacesd/Cargo.lock')
+ assert {'ci-cua-spaces-web.yml', 'ci-swift-lume.yml', 'ci-check-docs.yml'} <= skip
+
+
+def test_a_new_dependency_in_the_pull_request_counts(tmp_path):
+ """The gate unions the base graph with the PR's manifests, so a PR that adds an edge waits on it."""
+ def crate(root, rel, deps=''):
+ (root / rel).mkdir(parents=True)
+ (root / rel / 'Cargo.toml').write_text(f'[package]\nname = "{rel.rsplit("/", 1)[1]}"\n{deps}')
+ base, head = tmp_path / 'base', tmp_path / 'head'
+ crate(base, 'libs/cua/crates/a')
+ crate(base, 'docs/b')
+ crate(head, 'libs/cua/crates/a')
+ crate(head, 'docs/b', '[dependencies]\na = { path = "../../libs/cua/crates/a" }\n')
+ only_base = scope.load_graph([base])
+ both = scope.load_graph([base, head])
+ assert scope.scope(['libs/cua/crates/a/src/lib.rs'], CFG, only_base)[0] == ['cua']
+ assert scope.scope(['libs/cua/crates/a/src/lib.rs'], CFG, both)[0] == ['cua', 'docs']
+
+
+def test_a_dependent_package_outside_every_area_waits_on_everything(tmp_path):
+ root = tmp_path / 'r'
+ (root / 'libs/cua/crates/a').mkdir(parents=True)
+ (root / 'libs/cua/crates/a/Cargo.toml').write_text('[package]\nname = "a"\n')
+ (root / 'nowhere/c').mkdir(parents=True)
+ (root / 'nowhere/c/Cargo.toml').write_text('[package]\nname = "c"\n[dependencies]\na = { path = "../../libs/cua/crates/a" }\n')
+ assert scope.scope(['libs/cua/crates/a/x.rs'], CFG, scope.load_graph([root])) == (['all'], set())
+
+
+def test_workspace_inherited_path_dependencies_are_edges(tmp_path):
+ root = tmp_path / 'r'
+ (root / 'ws/crates/a').mkdir(parents=True)
+ (root / 'ws/crates/b').mkdir(parents=True)
+ (root / 'ws/Cargo.toml').write_text(
+ '[workspace]\nmembers = ["crates/*"]\n[workspace.dependencies]\na = { path = "crates/a" }\n')
+ (root / 'ws/crates/a/Cargo.toml').write_text('[package]\nname = "a"\n')
+ (root / 'ws/crates/b/Cargo.toml').write_text(
+ '[package]\nname = "b"\n[target.\'cfg(unix)\'.dev-dependencies]\na = { workspace = true }\n')
+ g = ci_graph.load(root)
+ assert g.packages['ws/crates/b'].deps == {'ws/crates/a'}
+ assert g.dependents({'ws/crates/a'}) == {'ws/crates/a', 'ws/crates/b'}
+ assert g.workspace_file('ws/Cargo.lock') == 'ws'
+ assert g.owner('ws/crates/b/src/lib.rs') == 'ws/crates/b'
+
+
[email protected](shutil.which('cargo') is None, reason='needs cargo')
[email protected]('workspace', ['libs/cua', 'libs/cua-driver/rust', 'libs/cua-spacesd'])
+def test_cargo_edges_match_cargo_metadata(workspace):
+ done = subprocess.run(['cargo', 'metadata', '--no-deps', '--format-version', '1', '--offline'],
+ cwd=scope.ROOT / workspace, capture_output=True, text=True)
+ if done.returncode != 0:
+ pytest.skip(f'cargo metadata failed: {done.stderr[-300:]}')
+ for pkg in json.loads(done.stdout)['packages']:
+ d = Path(pkg['manifest_path']).parent.relative_to(scope.ROOT).as_posix()
+ want = {Path(dep['path']).relative_to(scope.ROOT).as_posix()
+ for dep in pkg['dependencies'] if dep.get('path')} - {d}
+ assert GRAPH.packages[d].deps == want, d
def test_unmapped_workflow_is_never_ignored():
@@ -101,7 +212,7 @@ def test_map_covers_every_area_a_workflow_can_trigger_on(workflow):
def test_the_gate_and_its_scope_files_are_shared():
for f in ('.github/workflows/ci-gate.yml', '.github/ci-areas.json',
- '.github/scripts/ci_gate_scope.py'):
+ '.github/scripts/ci_gate_scope.py', '.github/scripts/ci_graph.py'):
assert scope.area_of(f, CFG) is None
@@ -152,15 +263,15 @@ def test_urgent_label_with_reference_uses_the_same_path_scope(tmp_path):
def test_gate_runs_the_scope_step_first_and_passes_its_output_to_the_wait_step():
gate = yaml.safe_load((scope.WORKFLOWS / 'ci-gate.yml').read_text())
steps = gate['jobs']['ci-gate']['steps']
- assert steps[1]['id'] == 'scope'
- assert steps[2]['env']['IGNORE_RE'] == '${{ steps.scope.outputs.ignore_re }}'
+ assert steps[2]['id'] == 'scope'
+ assert steps[3]['env']['IGNORE_RE'] == '${{ steps.scope.outputs.ignore_re }}'
assert 'labeled' in gate[True]['pull_request']['types']
assert 'edited' in gate[True]['pull_request']['types']
assert 'merge_group' in gate[True]
def test_gate_run_filter_drops_only_ignored_workflows():
- script = yaml.safe_load((scope.WORKFLOWS / 'ci-gate.yml').read_text())['jobs']['ci-gate']['steps'][2]['run']
+ script = yaml.safe_load((scope.WORKFLOWS / 'ci-gate.yml').read_text())['jobs']['ci-gate']['steps'][3]['run']
jq_filter = next(line.split("='", 1)[1].rsplit("'", 1)[0]
for line in script.splitlines() if line.strip().startswith('scope_jq='))
runs = [{'path': '.github/workflows/cd-image-linux.yml@refs/pull/1/merge'},
@@ -172,3 +283,17 @@ def test_gate_run_filter_drops_only_ignored_workflows():
env={**os.environ, 'IGNORE_RE': ignore}).stdout)
assert count('') == 2
assert count('^(cd-image-linux\\.yml)$') == 1
+
+
+def test_gate_runs_the_selector_from_the_base_commit_not_the_pull_request():
+ """A PR that edits the map, the scripts or its manifests cannot narrow its own gate."""
+ steps = yaml.safe_load((scope.WORKFLOWS / 'ci-gate.yml').read_text())['jobs']['ci-gate']['steps']
+ base, head, run = steps[0]['with'], steps[1]['with'], steps[2]['run']
+ assert base['ref'] == '${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha }}'
+ assert base['path'] == 'base'
+ for f in ('/.github/ci-areas.json', '/.github/scripts/ci_gate_scope.py', '/.github/scripts/ci_graph.py'):
+ assert f in base['sparse-checkout'].split()
+ assert f not in head['sparse-checkout'].split()
+ assert 'ref' not in head and head['path'] == 'head'
+ assert 'python3 base/.github/scripts/ci_gate_scope.py' in run
+ assert steps[2]['env']['CI_GATE_HEAD_ROOT'].endswith('/head')
diff --git a/.github/workflows/ci-gate.yml b/.github/workflows/ci-gate.yml
index 9d43f6df5e..938a7248be 100644
--- a/.github/workflows/ci-gate.yml
+++ b/.github/workflows/ci-gate.yml
@@ -16,16 +16,39 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 360
steps:
- # Which workflows this gate may ignore, from the paths the PR changes (area map:
- # .github/ci-areas.json, docs/contributing/CI.md). The merge queue entry resolves the
- # same pull request and reads the same file list, so both events compute one set.
+ # Which workflows this gate may ignore, from the paths the PR changes, the area map
+ # (.github/ci-areas.json) and the package graph (.github/scripts/ci_graph.py); see
+ # docs/contributing/CI.md. The map and both scripts come from the base commit, never
+ # from the pull request, so a PR cannot narrow its own gate by editing them (and any
+ # .github/** change waits for every workflow). The PR's manifests are read too, only
+ # to add the dependency edges it introduces. The merge queue entry resolves the same
+ # pull request and reads the same file list, so both events compute one set.
# Any failure here fails the gate: nothing is skipped on error.
- - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
+ - name: Check out the selector from the base commit
+ uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with:
+ ref: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha }}
+ path: base
persist-credentials: false
+ filter: blob:none
sparse-checkout: |
- .github/ci-areas.json
- .github/scripts/ci_gate_scope.py
+ /.github/ci-areas.json
+ /.github/scripts/ci_gate_scope.py
+ /.github/scripts/ci_graph.py
+ Cargo.toml
+ package.json
+ pnpm-workspace.yaml
+ sparse-checkout-cone-mode: false
+ - name: Check out the pull request's manifests
+ uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
+ with:
+ path: head
+ persist-credentials: false
+ filter: blob:none
+ sparse-checkout: |
+ Cargo.toml
+ package.json
+ pnpm-workspace.yaml
sparse-checkout-cone-mode: false
- name: Scope the gate to the changed areas
id: scope
@@ -33,6 +56,7 @@ jobs:
GH_TOKEN: ${{ github.token }}
PR_NUMBER: ${{ github.event.pull_request.number }}
QUEUE_REF: ${{ github.event.merge_group.head_ref }}
+ CI_GATE_HEAD_ROOT: ${{ github.workspace }}/head
run: |
set -euo pipefail
api() { local out; for _ in 1 2 3 4 5 6; do out=$(gh api "$@") && { printf '%s\n' "$out"; return; }; sleep 20; done; return 1; }
@@ -47,7 +71,7 @@ jobs:
--jq '.[] | .filename, (.previous_filename // empty)' > "$RUNNER_TEMP/files.txt"
# The files API stops at 3000 entries; a PR that large waits on everything.
if (( $(wc -l < "$RUNNER_TEMP/files.txt") >= 3000 )); then echo ".github/too-many-files" > "$RUNNER_TEMP/files.txt"; fi
- python3 .github/scripts/ci_gate_scope.py --labels "$labels" --body-file "$RUNNER_TEMP/pr-body.txt" < "$RUNNER_TEMP/files.txt"
+ python3 base/.github/scripts/ci_gate_scope.py --labels "$labels" --body-file "$RUNNER_TEMP/pr-body.txt" < "$RUNNER_TEMP/files.txt"
- name: Wait for every other workflow on the pull request head
env:
GH_TOKEN: ${{ github.token }}
diff --git a/docs/contributing/CI.md b/docs/contributing/CI.md
index c9522ab297..9f5b31865d 100644
--- a/docs/contributing/CI.md
+++ b/docs/contributing/CI.md
@@ -6,27 +6,54 @@ pull request workflows and passes when they pass. This page explains which of th
## Path-scoped gate
A workflow still starts on its own `paths:` filter. The gate then waits only for the workflows that belong
-to the areas the pull request changed. Slow jobs for other areas (for example the Linux image build on a
-relay-only change) still run, but they no longer hold up the merge.
+to the areas the pull request affects. Slow jobs for other areas (for example the Linux image build on a
+docs-only change) still run, but they no longer hold up the merge.
-The area map is [`.github/ci-areas.json`](../../.github/ci-areas.json). The scope step in
-`.github/workflows/ci-gate.yml` runs [`.github/scripts/ci_gate_scope.py`](../../.github/scripts/ci_gate_scope.py)
-on the pull request's file list.
+Two inputs decide the areas:
+
+- The area map, [`.github/ci-areas.json`](../../.github/ci-areas.json): path globs to areas, and areas to workflows.
+- The package graph, [`.github/scripts/ci_graph.py`](../../.github/scripts/ci_graph.py): every crate and
+ JavaScript package in the repo and their `path` / `workspace:` dependencies, read from the manifests
+ (`Cargo.toml`, `package.json`, `pnpm-workspace.yaml`). A test checks it against `cargo metadata`.
+
+The scope step in `.github/workflows/ci-gate.yml` runs
+[`.github/scripts/ci_gate_scope.py`](../../.github/scripts/ci_gate_scope.py) on the pull request's file list.
Rules, in order:
-1. A changed file that matches a **shared** glob, or matches no area at all, makes the gate wait for every run, as it did before scoping.
-2. Any other changed file belongs to the first area (top to bottom in the table) whose globs match it.
-3. A workflow listed under an area is required only when one of its areas changed.
-4. A workflow listed under no area (for example the eMudhra and release-metadata checks) is always required. A new workflow is therefore required until someone maps it. The gate never waits for **CI: CLA**, because the required `contributor-attribution` check enforces the CLA.
+1. A changed file that matches a **shared** glob makes the gate wait for every run.
+2. A **workspace file** (a Cargo or pnpm workspace's root manifest, `Cargo.lock`, `pnpm-lock.yaml`,
+ `rust-toolchain.toml` or `.cargo/`) affects every member of that workspace.
+3. A file inside a package (the nearest `Cargo.toml` or `package.json` above it) affects that package.
+ A file listed under `inputs` in the map (for example `libs/cua/proto/**` for `cua-proto`) affects the
+ packages named there, and its own area.
+4. Every affected package also affects **every package that depends on it**, transitively. So a change to a
+ shared crate such as `cua-proto` or `cua-driver-core` waits for the areas of all its dependents, and no others.
+5. Any other file belongs to the first area (top to bottom in the table) whose globs match it. A file, or an
+ affected package, outside every area makes the gate wait for every run.
+6. A workflow listed under an area is required only when one of its areas is affected.
+7. A workflow listed under no area (for example the eMudhra and release-metadata checks) is always required. A new workflow is therefore required until someone maps it. The gate never waits for **CI: CLA**, because the required `contributor-attribution` check enforces the CLA.
+
+Unaffected workflows still run if their own `paths:` match; the gate just doesn't wait for them. `ci-gate`
+is the only required check, so nothing else needs a placeholder status. Main pushes, nightly and manual runs
+are not scoped: each workflow runs in full on its own `push` and `schedule` triggers.
+
+**A pull request cannot narrow its own gate.** The gate checks out the map and both scripts from the base
+commit, not from the pull request. It reads the pull request's manifests only to add the dependency edges the
+pull request introduces. Any `.github/**` change (workflows, the map, the scripts) waits for every workflow,
+and `.github/` changes need a code owner's review.
Merge-queue runs (`merge_group`) read the file list of the same pull request through the same API call, so
the queue and the pull request wait on the same set. If the scope step fails for any reason, the gate fails.
It never skips on error.
+To see what a change affects locally: `printf '%s\n' <files> | python3 .github/scripts/ci_gate_scope.py`.
+To list a package's dependents: `python3 .github/scripts/ci_graph.py cua-proto`.
+
### Shared files (wait for everything)
-`.github/**`, `*`, `**/Cargo.lock`, `**/rust-toolchain.toml`, `**/pnpm-lock.yaml`, `**/pnpm-workspace.yaml`, `**/package-lock.json`, `**/uv.lock`, `libs/cua/Cargo.toml`, `libs/cua-driver/rust/Cargo.toml`, `libs/cua-spacesd/Cargo.toml`, `libs/cua-driver/rust/.cargo/**`, `libs/cua/.cargo/**`, `libs/cua/proto/**`, `libs/cua/crates/cua-proto/**`, `libs/cua-driver/rust/crates/cua-driver-core/**`, `libs/cua-driver/rust/crates/cua-driver-contract/**`, `libs/cua/crates/cua-sandbox-core/**`, `scripts/ci/**`, `flake.nix`, `nix/**`
+`.github/**`, `*` (any file at the repo root), `**/uv.lock` (the Python graph is not modelled yet),
+`scripts/ci/**`, `flake.nix`, `nix/**`
Any file outside every area below also counts as shared.
@@ -42,27 +69,26 @@ Any file outside every area below also counts as shared.
| `images` | `libs/images/**`, `scripts/images/**` | 19 | `cd-image-linux`, `ci-check-docs`, `ci-cua-spaces-macos`, `ci-cua-spacesd`, `e2e-cua-sdk` |
| `spaces-web` | `apps/cua-spaces-web/**`, `apps/cua-spaces-desktop/**` | 7 | `ci-cua-spaces-macos`, `ci-cua-spaces-web` |
| `spaces-app` | `apps/cua-spaces/**` | 7 | `ci-cua-spaces-web`, `ci-cua-spaces` |
-| `spaces-macos` | `apps/cua-spaces-macos/**` | 7 | `ci-cua-spaces-macos`, `ci-cua-spaces-web` |
+| `spaces-macos` | `apps/cua-spaces-macos/**`, `libs/spaces-app-swift/**`, `libs/spaces-notch-swift/**` | 8 | `ci-cua-spaces-macos`, `ci-cua-spaces-web` |
| `python` | `libs/python/**`, `libs/cua-bench/**`, `libs/cua-bench-rl/**`, `libs/cua-s1/**` | 24 | `ci-check-docs`, `ci-cua-sdk`, `ci-test-python`, `e2e-cua-sdk` |
| `typescript` | `libs/typescript/**`, `libs/cuabot/**` | 9 | none of the slow jobs |
| `lume` | `libs/lume/**`, `libs/lumier/**`, `libs/spaces-sdk-swift/**` | 11 | `ci-check-docs`, `ci-cua-sdk`, `ci-cua-spaces-macos`, `ci-swift-lume` |
| `containers` | `libs/kasm/**`, `libs/qemu-docker/**`, `libs/xfce/**`, `libs/xfce-cua/**` | 11 | none of the slow jobs |
-| `docs` | `docs/**`, `skills/**` | 17 | `ci-check-docs`, `e2e-cua-sdk` |
+| `docs` | `docs/**`, `skills/**`, `scripts/docs-generators/**` | 17 | `ci-check-docs`, `e2e-cua-sdk` |
| `compat` | `tests/compat/**` | 11 | none of the slow jobs |
| `installers` | `scripts/install/**` | 6 | none of the slow jobs |
| `examples` | `examples/**` | 5 | `ci-openkoalabot-example-tauri` |
-The `relay` area is narrowed by hand: the relay is a standalone server, so a change under
-`libs/cua-spacesd/crates/cua-relay/` waits for `ci-cua-relay-image`, `ci-cua-spacesd` (the Rust workspace
-build, lint and tests) and the cheap repo checks, and not for the Linux image, SDK end-to-end, image doctor or OCI jobs.
-Every other area lists every workflow whose own `paths:` reach it.
+The `relay` area is narrowed by hand to `ci-cua-relay-image`, `ci-cua-spacesd` and the cheap repo checks.
+`cua-spacesd` and `cua-spacesd-server` link `cua-relay`, so the package graph also adds the `spacesd` area
+to a relay change. Every other area lists every workflow whose own `paths:` reach it.
### Keeping the map correct
`.github/scripts/tests/test_ci_gate_scope.py` (run by `CI: Test Scripts`) fails when a workflow's
`pull_request` paths reach an area that does not list it. When you add a workflow with a `paths:` filter,
or add a path to one, add it to the matching areas in `.github/ci-areas.json`. Changing the map or the gate
-is a `.github/**` change, so it waits for every workflow.
+is a `.github/**` change, so it waits for every workflow, and it takes effect only once it is on `main`.
## Urgent-fix lane