diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 0ee24abf61..7011e79864 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -1,34 +1,26 @@ name: CodeQL -# SOC 2: SAST (OA-C-24). Static analysis on push/PR to main + weekly. +# SOC 2: SAST (OA-C-24). Static analysis on push to main, a weekly schedule and +# manual dispatch. Not on pull requests: findings surface after merge. The merge +# queue is disabled, so merge_group does not run today. on: push: branches: [main] - # Every pull request, whatever its base, plus each merge queue group. - pull_request: - # Drafts run nothing (each job checks `draft`); marking one ready runs CI. - types: [opened, synchronize, reopened, ready_for_review] merge_group: schedule: - cron: "23 5 * * 1" + workflow_dispatch: permissions: contents: read -# Cancel a pull request's earlier run when it gets a new commit; a run on -# main that has started always finishes. concurrency: - # A pull request's newer push cancels its older run. Pushes to main share - # one group: one analysis runs at a time, and the newest waiting push - # replaces an older waiting one, since its tree contains the older one's - # code. Nothing is cancelled once it runs. In 20.7 hours on 2026-11-20, - # 35 merges each analyzed all three languages, for 563 runner-minutes; - # replayed under this rule, 29 runs would have used about 458. No - # release reads this workflow. After a burst of merges, a cancelled - # CodeQL run on main means it was replaced, not that main is red. The merge queue, schedules and dispatches each get a - # group of their own. - group: ${{ github.workflow }}-${{ github.event.pull_request.number || (github.event_name == 'push' && github.ref) || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + # Pushes to main share one group: one analysis runs at a time, and the newest + # waiting push replaces an older waiting one, since its tree contains the + # older one's code. Nothing is cancelled once it runs. Merge queue groups, + # schedules and manual dispatches each get a group of their own. + group: ${{ github.workflow }}-${{ (github.event_name == 'push' && github.ref) || github.run_id }} + cancel-in-progress: false jobs: analyze: diff --git a/.github/workflows/packages.yml b/.github/workflows/packages.yml index 54e485ac43..afa54b0169 100644 --- a/.github/workflows/packages.yml +++ b/.github/workflows/packages.yml @@ -114,6 +114,9 @@ jobs: timeout-minutes: 5 outputs: flow: ${{ steps.classify.outputs.flow }} + flow_at_rest: ${{ steps.classify.outputs.flow_at_rest }} + flow_onprem: ${{ steps.classify.outputs.flow_onprem }} + flow_agent_frameworks: ${{ steps.classify.outputs.flow_agent_frameworks }} flow_unit_shards: ${{ steps.classify.outputs.flow_unit_shards }} types: ${{ steps.classify.outputs.types }} agent: ${{ steps.classify.outputs.agent }} @@ -145,7 +148,7 @@ jobs: if [ "$EVENT_NAME" = pull_request ]; then unit_shards=4; else unit_shards=2; fi echo "flow_unit_shards=$unit_shards" >> "$GITHUB_OUTPUT" all() { - for pkg in flow types agent eligibility verify capture privacy desktop tray program_graph weight; do echo "$pkg=true" >> "$GITHUB_OUTPUT"; done + for pkg in flow flow_at_rest flow_onprem flow_agent_frameworks types agent eligibility verify capture privacy desktop tray program_graph seal_view weight; do echo "$pkg=true" >> "$GITHUB_OUTPUT"; done exit 0 } case "$EVENT_NAME" in @@ -177,6 +180,22 @@ jobs: # Flow depends on the in-tree types, and its `capture` extra is tested # against the in-tree capture. flow="$(hit "^packages/(flow|capture|types)/|$browser_support|$wf")" + # Sub-package gates on pull requests and queue groups; pushes to main, + # schedules and dispatches follow `flow`. Encryption at rest is the + # default for every store, so any Flow, Types or Capture code change can + # regress it; only prose (docs/ and top-level *.md) skips these jobs. + if [ "$EVENT_NAME" != pull_request ] && [ "$EVENT_NAME" != merge_group ]; then + flow_at_rest="$flow" + flow_onprem="$flow" + flow_agent_frameworks="$flow" + else + code_changed="$(grep -Ev '^packages/(flow|capture|types)/(docs/|[^/]*\.md$)' <<<"$changed" || true)" + hit_code() { if grep -Eq "$1" <<<"$code_changed"; then echo true; else echo false; fi; } + flow_code="$(hit_code "^packages/(flow|capture|types)/|$browser_support|$wf")" + flow_at_rest="$flow_code" + flow_onprem="$flow_code" + flow_agent_frameworks="$flow_code" + fi # The types package is the leaf: only its own files re-run it. types="$(hit "^packages/types/|$wf")" # The agent shim is tested against the in-tree core. @@ -198,6 +217,9 @@ jobs: weight="$(hit "^packages/|^pyproject\.toml$|^openadapt/|^hatch_build\.py$|^scripts/install_weight/|$wf")" { echo "flow=$flow" + echo "flow_at_rest=$flow_at_rest" + echo "flow_onprem=$flow_onprem" + echo "flow_agent_frameworks=$flow_agent_frameworks" echo "types=$types" echo "agent=$agent" echo "eligibility=$eligibility" @@ -674,16 +696,14 @@ jobs: flow-default-at-rest: # The whole flow suite under the product default: encryption at rest on - # (no plaintext opt-out). Required on pull requests. Tests that read or - # plant plaintext files directly, and known open limitations, are skipped - # in this mode with their reason (tests/default_at_rest_skips.txt, #2423). + # (no plaintext opt-out). Required on code-changing pull requests (prose-only + # Flow PRs skip it via flow_at_rest). Tests that read or plant plaintext files + # directly, and known open limitations, are skipped in this mode with their + # reason (tests/default_at_rest_skips.txt, #2423). name: flow default at rest (shard ${{ matrix.shard }}/${{ matrix.of }}) needs: scope - # PR and post-merge tiers. The merge queue skips it: a pull request can - # enter the queue only after packages-gate passed with these shards green - # on its merge with main, and flow-critical re-checks the golden path on - # the group. - if: github.event_name == 'pull_request' && github.event.pull_request.draft != true && needs.scope.outputs.flow == 'true' + # PR tier only (as on main): avoids untriaged nightly e2e under encrypted mode. + if: github.event_name == 'pull_request' && github.event.pull_request.draft != true && needs.scope.outputs.flow_at_rest == 'true' runs-on: ubuntu-latest # The nightly tier (a schedule or a dispatch) also measures coverage, # which slows the suite by about a third; it gets 60 minutes. @@ -694,10 +714,7 @@ jobs: # Each shard runs one pytest-xdist worker per vCPU (four on # ubuntu-latest) and pays about 35 s of setup. Files are packed by # measured time (scripts/ci/flow_shards.py), so the shards finish - # together. A pull request's fast lane takes four shards: with three, - # the identity, wire and verifier tests it must keep held each shard - # near 12 minutes of tests (run 44684203094). The full suite on main - # and nightly takes two. + # together. include: [{"shard":1,"of":4},{"shard":2,"of":4},{"shard":3,"of":4},{"shard":4,"of":4}] defaults: run: @@ -836,7 +853,7 @@ jobs: mapfile -t files < "$RUNNER_TEMP/shard.txt" # The wall-clock bound needs an uncontended worker; flow core unit # runs it alone, so it is not repeated here. - pytest -n logical --dist loadfile -q -rfE --timeout 300 \ + pytest -n logical --dist loadscope -q -rfE --timeout 300 \ --deselect=tests/test_tx_acid_servers.py::test_50k_seed_speed_and_8_worker_background_concurrency \ --basetemp=runs/ci-default \ --junitxml=runs/flow-default-at-rest-${{ matrix.shard }}.xml "${files[@]}" @@ -1029,7 +1046,7 @@ jobs: done unit_rc=0 # shellcheck disable=SC2086 # COVERAGE_ARGS is empty or two flags. - pytest -n logical --dist loadfile -v --durations=20 --basetemp=runs/ci \ + pytest -n logical --dist loadscope -v --durations=20 --basetemp=runs/ci \ --deselect="$serial_case" $COVERAGE_ARGS \ --junitxml=runs/flow-unit-shard-${{ matrix.shard }}-of-${{ matrix.of }}.xml "${files[@]}" || unit_rc=$? if "$run_serial"; then @@ -1070,7 +1087,7 @@ jobs: # The durable and authority files whose tests read files directly # as plaintext are not listed yet (#2423 lists them). run: >- - pytest -n logical --dist loadfile -q --basetemp=runs/ci-default-at-rest + pytest -n logical --dist loadscope -q --basetemp=runs/ci-default-at-rest tests/test_rollback.py tests/test_rollback_qualify.py tests/test_checkpoint_key_derivations.py tests/test_key_hierarchy.py tests/test_at_rest_review_round3.py @@ -1305,7 +1322,7 @@ jobs: flow-onprem-offline: name: flow on-prem offline install, update and rollback (egress blocked) needs: scope - if: github.event.pull_request.draft != true && (needs.scope.outputs.flow == 'true') + if: github.event.pull_request.draft != true && (needs.scope.outputs.flow_onprem == 'true') runs-on: ubuntu-latest timeout-minutes: 30 defaults: @@ -1320,7 +1337,9 @@ jobs: python-version: "3.12" - uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0 with: - enable-cache: false + enable-cache: true + cache-dependency-glob: "packages/flow/uv.lock" + cache-suffix: flow-onprem-offline - name: Signed update and rollback state machine (hermetic, fake build) run: bash deploy/on-prem/bin/test-update.sh - name: Build two signed offline releases from the lock (connected) @@ -1344,7 +1363,7 @@ jobs: flow-agent-frameworks: name: flow agent frameworks (scripted models) needs: scope - if: github.event.pull_request.draft != true && (needs.scope.outputs.flow == 'true') + if: github.event.pull_request.draft != true && (needs.scope.outputs.flow_agent_frameworks == 'true') runs-on: ubuntu-latest timeout-minutes: 25 defaults: @@ -1369,6 +1388,15 @@ jobs: # need mcp<2 and openai<3. The adapter is tested against this one # version, in this job only. run: uv pip install --no-config --require-hashes -r ci/crewai-1.6.1.txt + - name: Resolve Playwright version + id: pw + run: | + uv run --no-sync python -c "import importlib.metadata as m; print('version=' + m.version('playwright'))" >> "$GITHUB_OUTPUT" + - name: Cache Playwright browsers + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ~/.cache/ms-playwright + key: ${{ runner.os }}-playwright-${{ steps.pw.outputs.version }} - name: Install and launch Playwright browser timeout-minutes: 12 run: >- @@ -1380,7 +1408,7 @@ jobs: OTEL_SDK_DISABLED: "true" run: | mkdir -p runs - uv run --no-sync pytest -v --timeout=120 -k "not real_model" \ + uv run --no-sync pytest -n logical --dist loadscope -v --timeout=120 -k "not real_model" \ tests/test_agent_write_guard.py tests/test_agent_framework_*.py \ tests/e2e/test_skill_cache_e2e.py \ --junitxml=runs/frameworks-junit.xml @@ -2160,10 +2188,10 @@ jobs: "verify-clean-install": "verify", "flow-lint": "flow", "flow-unit": "flow", - "flow-default-at-rest": "flow", + "flow-default-at-rest": "flow_at_rest", "flow-critical": "flow", - "flow-onprem-offline": "flow", - "flow-agent-frameworks": "flow", + "flow-onprem-offline": "flow_onprem", + "flow-agent-frameworks": "flow_agent_frameworks", "flow-native-census": "flow", "flow-linux-atspi": "flow", "capture-linux": "capture", diff --git a/tests/test_ci_efficiency_gating.py b/tests/test_ci_efficiency_gating.py new file mode 100644 index 0000000000..c04e0f627b --- /dev/null +++ b/tests/test_ci_efficiency_gating.py @@ -0,0 +1,297 @@ +"""Contract tests for PR CI path-gating, xdist loadscope, caches, and CodeQL triggers.""" + +from __future__ import annotations + +import json +import os +import re +import subprocess +import sys +from pathlib import Path + +import pytest +import yaml + +ROOT = Path(__file__).resolve().parents[1] +WORKFLOWS = ROOT / ".github" / "workflows" + + +def _load(name: str) -> dict: + return yaml.safe_load((WORKFLOWS / name).read_text(encoding="utf-8")) + + +def _triggers(workflow: dict) -> dict: + return workflow.get("on", workflow.get(True)) + + +def _run_classifier( + changed_files: list[str], event_name: str = "pull_request", tmp_path: Path | None = None +) -> dict[str, str]: + """Run the actual `Classify the change` bash step with `git diff` stubbed.""" + classify_step = next( + s + for s in _load("packages.yml")["jobs"]["scope"]["steps"] + if s.get("name") == "Classify the change" + ) + script = classify_step["run"] + assert 'changed="$(git diff --name-only "$base" HEAD)"' in script + stubbed = script.replace( + 'changed="$(git diff --name-only "$base" HEAD)"', + 'changed="$STUB_CHANGED"', + ) + out_file = (tmp_path / "github_output.txt") if tmp_path else None + assert out_file is not None + out_file.write_text("", encoding="utf-8") + env = { + **os.environ, + "EVENT_NAME": event_name, + "BEFORE_SHA": "", + "GROUP_BASE_SHA": "", + "STUB_CHANGED": "\n".join(changed_files), + "GITHUB_OUTPUT": str(out_file), + } + res = subprocess.run( + ["bash", "-c", stubbed], + env=env, + capture_output=True, + text=True, + check=False, + ) + assert res.returncode == 0, res.stdout + res.stderr + outputs: dict[str, str] = {} + for line in out_file.read_text(encoding="utf-8").splitlines(): + if "=" in line: + k, v = line.split("=", 1) + outputs[k.strip()] = v.strip() + return outputs + + +def test_codeql_runs_post_merge_and_scheduled_not_on_pull_request() -> None: + wf = _load("codeql.yml") + triggers = set(_triggers(wf)) + assert "pull_request" not in triggers + assert {"push", "schedule", "workflow_dispatch"}.issubset(triggers) + assert wf["concurrency"]["cancel-in-progress"] is False + + +def test_packages_workflow_pins_every_action_to_40_char_sha() -> None: + for name in ("packages.yml", "codeql.yml"): + text = (WORKFLOWS / name).read_text(encoding="utf-8") + uses = re.findall(r"uses:\s*(\S+)", text) + assert uses, name + for ref in uses: + if ref.startswith("./"): + continue + assert re.search(r"@[0-9a-f]{40}$", ref), f"unpinned action in {name}: {ref}" + + +def test_packages_workflow_enables_loadscope_and_caches() -> None: + wf = _load("packages.yml") + jobs = wf["jobs"] + + unit_test = next(s for s in jobs["flow-unit"]["steps"] if s.get("name") == "Test") + assert "pytest -n logical --dist loadscope" in unit_test["run"] + + unit_enc = next( + s + for s in jobs["flow-unit"]["steps"] + if s.get("name") == "Rollback, checkpoint and key tests under the default (encrypted) mode" + ) + assert "pytest -n logical --dist loadscope" in unit_enc["run"] + + at_rest_test = next( + s + for s in jobs["flow-default-at-rest"]["steps"] + if s.get("name") == "Test under the default (encrypted) mode" + ) + assert "pytest -n logical --dist loadscope" in at_rest_test["run"] + + onprem_uv = next( + s for s in jobs["flow-onprem-offline"]["steps"] if "setup-uv@" in s.get("uses", "") + ) + assert onprem_uv["with"]["enable-cache"] is True + + fw_steps = jobs["flow-agent-frameworks"]["steps"] + pw_cache = next(s for s in fw_steps if s.get("name") == "Cache Playwright browsers") + assert pw_cache["with"]["path"] == "~/.cache/ms-playwright" + assert "55cc8345863c7cc4c66a329aec7e433d2d1c52a9" in pw_cache["uses"] + + +@pytest.mark.parametrize( + ("changed_files", "expect_flow", "expect_code"), + [ + # #2423-style encryption/storage/runtime/compiler/test/lock paths MUST select + (["packages/flow/openadapt_flow/crypto.py"], "true", "true"), + (["packages/flow/openadapt_flow/stream_aead.py"], "true", "true"), + (["packages/flow/openadapt_flow/key_rotation.py"], "true", "true"), + (["packages/flow/openadapt_flow/retention.py"], "true", "true"), + (["packages/flow/openadapt_flow/compiler/distill.py"], "true", "true"), + (["packages/flow/tests/conftest.py"], "true", "true"), + (["packages/flow/uv.lock"], "true", "true"), + (["packages/types/openadapt_types/models.py"], "true", "true"), + (["packages/capture/openadapt_capture/recorder.py"], "true", "true"), + ([".github/workflows/packages.yml"], "true", "true"), + # Prose-only Flow PRs skip the heavy encrypted/on-prem/framework jobs + (["packages/flow/docs/LIMITS.md"], "true", "false"), + (["packages/flow/README.md", "packages/flow/CHANGELOG.md"], "true", "false"), + (["packages/flow/docs/commands/run.md"], "true", "false"), + # Mixed prose + code MUST select + ( + ["packages/flow/docs/LIMITS.md", "packages/flow/openadapt_flow/api.py"], + "true", + "true", + ), + # Unrelated package PR selects neither + (["packages/tray/README.md"], "false", "false"), + ], +) +def test_classifier_selects_all_flow_code_and_skips_prose_only_prs( + tmp_path: Path, + changed_files: list[str], + expect_flow: str, + expect_code: str, +) -> None: + out = _run_classifier(changed_files, event_name="pull_request", tmp_path=tmp_path) + assert out["flow"] == expect_flow + assert out["flow_at_rest"] == expect_code + assert out["flow_onprem"] == expect_code + assert out["flow_agent_frameworks"] == expect_code + + +@pytest.mark.parametrize( + ("event", "outputs", "job_results", "expected"), + [ + # Prose-only Flow PR: at-rest, onprem, and agent-frameworks skipped -> gate passes + ( + "pull_request", + { + "flow": "true", + "flow_at_rest": "false", + "flow_onprem": "false", + "flow_agent_frameworks": "false", + }, + { + "flow-unit": "success", + "flow-critical": "success", + "flow-default-at-rest": "skipped", + "flow-onprem-offline": "skipped", + "flow-agent-frameworks": "skipped", + }, + 0, + ), + # Code-changing PR: flow_at_rest=true but skipped -> gate FAILS + ( + "pull_request", + { + "flow": "true", + "flow_at_rest": "true", + "flow_onprem": "false", + "flow_agent_frameworks": "false", + }, + { + "flow-unit": "success", + "flow-critical": "success", + "flow-default-at-rest": "skipped", + "flow-onprem-offline": "skipped", + "flow-agent-frameworks": "skipped", + }, + 1, + ), + # On-prem selected but skipped -> gate FAILS + ( + "pull_request", + { + "flow": "true", + "flow_at_rest": "false", + "flow_onprem": "true", + "flow_agent_frameworks": "false", + }, + { + "flow-unit": "success", + "flow-critical": "success", + "flow-default-at-rest": "skipped", + "flow-onprem-offline": "skipped", + "flow-agent-frameworks": "skipped", + }, + 1, + ), + # Cancelled job on an unselected PR STILL fails the gate + ( + "pull_request", + { + "flow": "true", + "flow_at_rest": "false", + "flow_onprem": "false", + "flow_agent_frameworks": "false", + }, + { + "flow-unit": "success", + "flow-critical": "success", + "flow-default-at-rest": "cancelled", + "flow-onprem-offline": "skipped", + "flow-agent-frameworks": "skipped", + }, + 1, + ), + # Merge queue skips flow-default-at-rest cleanly (pr_only) + ( + "merge_group", + { + "flow": "true", + "flow_at_rest": "true", + "flow_onprem": "false", + "flow_agent_frameworks": "false", + }, + { + "flow-unit": "skipped", + "flow-critical": "success", + "flow-default-at-rest": "skipped", + "flow-onprem-offline": "skipped", + "flow-agent-frameworks": "skipped", + }, + 0, + ), + # Push to main skips flow-default-at-rest cleanly (pr_only, as on main) + ( + "push", + { + "flow": "true", + "flow_at_rest": "true", + "flow_onprem": "true", + "flow_agent_frameworks": "true", + }, + { + "flow-unit": "success", + "flow-critical": "success", + "flow-default-at-rest": "skipped", + "flow-onprem-offline": "success", + "flow-agent-frameworks": "success", + }, + 0, + ), + ], +) +def test_packages_gate_enforces_sub_package_flow_selection( + event: str, + outputs: dict[str, str], + job_results: dict[str, str], + expected: int, +) -> None: + gate_step = next( + s + for s in _load("packages.yml")["jobs"]["packages-gate"]["steps"] + if s.get("name") == "Require every selected package job to pass" + ) + gate = gate_step["run"] + script = "\n".join(gate.splitlines()[1:-1]) + needs: dict[str, dict] = {"scope": {"result": "success", "outputs": outputs}} + for name, status in job_results.items(): + needs[name] = {"result": status} + result = subprocess.run( + [sys.executable, "-c", script], + env={**os.environ, "RESULTS": json.dumps(needs), "EVENT_NAME": event}, + capture_output=True, + text=True, + check=False, + ) + assert result.returncode == expected, result.stdout + result.stderr