Files
rustfs/scripts/test_ci_plan.py
T
唐小鸭 fc3a216725 fix(ecstore,sse): close m-compatible interop gaps and rename feature (#9684)
* fix(ecstore,sse): close rio-v2 interop gaps on imported drive sets

A rio-v2 build that takes over a drive set written in the compatible format could not start once a KMS was configured, and several object reads and writes disagreed with what the other server stores or expects.

- Startup: the IAM migration now opens KMS-sealed IAM records. The record path is part of the key context, so the migration callback receives it, and the context text is escaped the way it was sealed.
- GET of a single-part encrypted object: whether an object holds one cipher stream per part is read from the marker the object records, not guessed from the ETag length. A sealed ETag is longer than an MD5 and sent these objects down the per-part path, which failed authentication.
- ETag: a sealed ETag is opened for GET and HEAD responses.
- HEAD: the public SSE headers are derived from the stored sealing metadata, and the KMS key id is answered in ARN form on GET and HEAD.
- Content length: an object sealed under an object key records no plaintext size when it is a single-part upload; the size is derived from the stored size of its parts.
- Compression: the compression and actual-size keys are also written in the casing the other server looks up.
- User metadata is stored under the x-amz-meta- prefix so it comes back as user metadata on both sides. Keys starting with "internal-" keep their bare form, because the prefixed form falls into a namespace reads hide.
- Replication: the metadata comparison skips the prefixed user metadata, which the target's HEAD answers without the prefix and which therefore never compared equal.
- ListObjectVersions and the metadata listing extension report the plaintext size of encrypted and compressed versions. This is the only intended behaviour change in a default build.

Three differences stay as they are: the other server cannot read SSE-S3 objects this build writes, listings do not open sealed ETags, and an SSE-KMS write is refused when only a static master key is configured.

Each fix has a regression test that fails without it.

* build: rename cargo feature rio-v2 to m-compatible

The feature selects the stored layout a build reads and writes, not a version of the stream crate, so it is named after that. The rename covers the feature key in every crate that forwards it, all cfg attributes, the CI job ids, names and artifacts, the CI gate and its tests, the validation scripts, the compat compose build argument, the debug launch configuration and the documentation.

The crate rustfs-rio-v2, its path and module name, the tests named after that reader implementation, and the backend_name() strings are unchanged. There is no alias: a build that passed --features rio-v2 must pass --features m-compatible.

No behaviour change in either build.

* refactor(ecstore,sse): select the build variant at one point per module

The m-compatible feature was tested at about 220 places, most of them inside function bodies. Each area that differs between the two builds now has a pair of modules exporting the same functions, and one place that picks between them, so call sites no longer name the build.

- ecstore: io_support/rio.rs selects rio/{native,m_compatible}.rs for the stream readers and writers, the compression scheme and index encoding, and the write-side encryptors. object_api/readers.rs selects readers/{native,m_compatible}.rs for range plans, the multipart layout, plaintext sizes that are not recorded, empty parts and the decompressed stream.
- sse: the sealed-ETag branch moves out of core/read.rs into core/keying/, where this crate keeps its build-specific code, and decrypt_kms_sealed_config is exported in both builds.
- utils: the four checks in metadata_compat.rs become one predicate.
- Tests that exist in only one build move to tests/native.rs and tests/m_compatible.rs child modules, gated once where they are declared. The set of test names is unchanged apart from one rename.

The attribute now appears 95 times; in ecstore it is left on the two selection points and on tests. crates/ecstore/AGENTS.md records the convention.

scripts/error-other-format-baseline.txt changes because that ratchet counts per file: 11 existing call sites moved from object_api/readers.rs (19 to 8) into the new readers/m_compatible.rs (11). The total stays at 564.

No behaviour change in either build. docs/architecture/minio-file-format-compat.md gains a table of where the variant lives and a corrected statement of what a default build can read.

* fix(s3): compare read preconditions with the answered ETag

A HEAD or GET of an object whose stored ETag is sealed answers with the ETag clients were shown for it, but If-Match and If-None-Match were still compared with the stored form. A client sending back the ETag HEAD answered with got 412 for If-Match and no 304 for If-None-Match.

- HEAD and GET compare the ETag conditions with the ETag the response carries, and a 304 carries that ETag.
- The storage layer ends a conditional read on the stored ETag before a body is opened, and cannot await the answered one. For a stored ETag in sealed form it no longer ends the read on an ETag condition and leaves the decision to the request layer. Without this a matching If-Match ended the read with no body to answer with.
- A default build stores no sealed ETag: the form test is constant false there and its behaviour is unchanged.

Tests: a round trip on a real store takes the ETag from HEAD and sends it back to GET and HEAD as If-Match and If-None-Match, and sends the stored form to show it matches nothing; unit tests cover the precondition helper, the storage-layer decision and the form test in both builds. With either half of the fix switched off the round trip fails.

* fix(s3): compare copy-source conditions with the answered ETag

x-amz-copy-source-if-match and x-amz-copy-source-if-none-match on CopyObject and UploadPartCopy were compared with the stored ETag of the source. For a source whose stored ETag is sealed that is not the ETag a read answers with, so the ETag from HEAD was refused with 412.

Both compare the ETag a read of the source answers with, as GET and HEAD do since the previous commit. It is resolved after the source's key authorization and only when the request names an ETag. A default build stores no sealed ETag and is unchanged.

Tests: on a real store, a customer-key source with a sealed stored ETag is copied with the ETag from HEAD as copy-source-if-match through both operations; the stored form as if-match and the answered ETag as if-none-match are refused. The fixture is shared with the read round trip. With either call site switched back the test fails.

* fix(s3): answer a date-conditioned GET 304 with the answered ETag

A GET that carried only If-Modified-Since resolved no answered ETag, because the lookup was limited to requests naming an ETag, and its 304 fell back to the stored ETag. For an object whose stored ETag is sealed the 304 then carried a different validator than HEAD answers with.

GET resolves the answered ETag for every conditional request, so a 304 carries it whichever condition produced it. HEAD already did. An unconditional GET still skips the lookup, and a default build stores no sealed ETag and is unchanged.

Tests: the sealed-ETag round trip takes Last-Modified from HEAD, sends it back as If-Modified-Since to GET and HEAD, and requires the 304 of both to carry the ETag HEAD answered with. With the lookup limited to ETag conditions again, the GET half fails.

---------

Co-authored-by: overtrue <anzhengchao@gmail.com>
2026-11-29 11:50:24 +08:00

920 lines
62 KiB
Python

#!/usr/bin/env python3
"""Regression cases for trusted planning and fail-closed aggregation."""
import copy
import io
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import tomllib
import unittest
from unittest.mock import patch
import ci_gate as gate
class Repository:
def __init__(self, root):
self.root = root
self.git('init', '-q')
self.write('.gitignore', '/target/\n')
self.write('Cargo.toml', '[workspace]\nmembers = ["rustfs", "core", "leaf", "consumer", "macro", "crates/e2e_test"]\n[workspace.dependencies]\nrenamed = { package="leaf", path="leaf" }\n')
for name, directory in [('rustfs', 'rustfs'), ('core', 'core'), ('leaf', 'leaf'), ('consumer', 'consumer'), ('macro', 'macro'), ('e2e_test', 'crates/e2e_test')]:
self.write(f'{directory}/Cargo.toml', f'[package]\nname = "{name}"\nversion = "0.1.0"\n')
self.write(f'{directory}/src/lib.rs', '// source\n')
self.write('consumer/Cargo.toml', '[package]\nname="consumer"\nversion="0.1.0"\n[target.\'cfg(unix)\'.dev-dependencies]\nrenamed = { workspace=true }\n[build-dependencies]\nmacro={path="../macro"}\n')
self.write('macro/Cargo.toml', '[package]\nname="macro"\nversion="0.1.0"\n[lib]\nproc-macro=true\n')
self.write('rustfs/Cargo.toml', '[package]\nname="rustfs"\nversion="0.1.0"\n[dependencies]\nconsumer={path="../consumer"}\n')
self.policy = {'schema_version': 1, 'rollout': 'shadow', 'core_packages': ['core'], 'connect_packages': ['core'],
'full_paths': ['Cargo.toml', 'Cargo.lock', '*/Cargo.toml', '.config/*', '.github/*', 'scripts/*', 'rust-toolchain*']}
self.write(gate.POLICY_PATH, json.dumps(self.policy))
self.write('.config/ecstore-required-tests.json', json.dumps({'tests': [{'suite': 'core::integration', 'name': 'required'}]}))
self.base = self.commit()
def git(self, *args):
return subprocess.check_output(['git', '-c', 'core.hooksPath=/dev/null', '-c', 'user.name=CI Test', '-c', 'user.email=ci@example.invalid', *args], cwd=self.root, stderr=subprocess.PIPE).decode().strip()
def write(self, path, content):
target = self.root / path
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(content)
def commit(self):
self.git('add', '-A')
self.git('commit', '-qm', 'fixture')
return self.git('rev-parse', 'HEAD')
def plan(self, head=None, event='pull_request', base=None, action='opened', proof=None):
return gate.select_plan(event, base or self.base, head or self.git('rev-parse', 'HEAD'), 'refs/heads/main', self.root, action, proof=proof)
class PlannerTests(unittest.TestCase):
def test_runtime_package_install_uses_ipv4_and_propagates_errors(self):
root = Path(gate.__file__).resolve().parent.parent
action = gate.workflow_document((root / '.github/actions/test-runtime/action.yml').read_text())
body = next(step['run'] for step in action['runs']['steps'] if step.get('name') == 'Install runtime tools')
with tempfile.TemporaryDirectory() as directory:
commands = Path(directory)
sudo = commands / 'sudo'
sudo.write_text('#!/bin/sh\nexec "$@"\n')
sudo.chmod(0o755)
apt = commands / 'apt-get'
apt.write_text('''#!/bin/sh
printf '%s\\n' "$*" >> "$APT_CALLS"
[ "$1" = -o ] && [ "$2" = Acquire::ForceIPv4=true ] || exit 100
shift 2
[ "$1" != "$APT_FAIL_STEP" ] || exit 37
''')
apt.chmod(0o755)
calls = commands / 'calls'
for fail_step, status in (('', 0), ('update', 37), ('install', 37)):
calls.write_text('')
environment = dict(os.environ, PATH=f"{commands}{os.pathsep}{os.environ['PATH']}",
APT_CALLS=str(calls), APT_FAIL_STEP=fail_step)
result = subprocess.run(['bash', '-e', '-o', 'pipefail', '-c', body],
env=environment, capture_output=True, text=True)
with self.subTest(fail_step=fail_step):
self.assertEqual(result.returncode, status, result.stderr)
expected = ['-o Acquire::ForceIPv4=true update']
if fail_step != 'update':
expected.append('-o Acquire::ForceIPv4=true install -y libssl-dev ripgrep')
self.assertEqual(calls.read_text().splitlines(), expected)
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.repo = Repository(Path(self.temp.name))
def test_dependency_graph_includes_renamed_target_dev_build_and_proc_macro_edges(self):
packages, graph = gate.cargo_graph(self.repo.root, self.repo.base)
self.assertEqual(graph['consumer'], {'leaf', 'macro'})
self.assertEqual(gate.closure({'leaf'}, graph, reverse=True), {'leaf', 'consumer', 'rustfs'})
self.assertEqual(gate.closure({'macro'}, graph, reverse=True), {'macro', 'consumer', 'rustfs'})
self.repo.write('leaf/src/lib.rs', '// changed\n')
plan = self.repo.plan(self.repo.commit())
self.assertEqual(plan['proposed']['packages'], ['consumer', 'core', 'leaf', 'rustfs'])
self.assertFalse(plan['proposed']['connect'])
self.assertTrue(plan['connect'])
self.assertEqual(plan['packages'], sorted(set(packages) - {'e2e_test'}))
self.assertEqual(plan['policy']['rollout'], 'shadow')
def test_deleted_or_moved_source_keeps_original_dependents(self):
(self.repo.root / 'leaf/src/lib.rs').rename(self.repo.root / 'core/src/moved.rs')
plan = self.repo.plan(self.repo.commit())
self.assertEqual(plan['proposed']['packages'], ['consumer', 'core', 'leaf', 'rustfs'])
self.assertTrue(plan['proposed']['connect'])
self.assertFalse(plan['proposed']['full_validation'])
def test_shared_unknown_lock_and_policy_changes_are_full(self):
for path in ('Cargo.lock', 'rust-toolchain.toml', 'shared/fixture.json', 'scripts/run.sh', '.config/ci-plan.json', 'crates/new/Cargo.toml'):
with self.subTest(path=path):
if path == gate.POLICY_PATH:
modified = dict(self.repo.policy, rollout='enforced', core_packages=[])
self.repo.write(path, json.dumps(modified))
else:
self.repo.write(path, 'changed\n')
plan = self.repo.plan(self.repo.commit())
self.assertTrue(plan['proposed']['full_validation'])
self.assertTrue(plan['connect'])
self.assertEqual(plan['policy']['rollout'], 'shadow')
def test_core_inventory_is_unioned_and_cannot_be_removed_by_candidate(self):
self.repo.write('leaf/src/lib.rs', '// change\n')
with patch.object(gate, 'read_policy', return_value=dict(self.repo.policy, rollout='enforced', core_packages=[])):
plan = self.repo.plan(self.repo.commit())
self.assertIn('core', plan['packages'])
self.repo.write('.config/ecstore-required-tests.json', json.dumps({'tests': []}))
plan = self.repo.plan(self.repo.commit())
self.assertTrue(plan['full_validation'])
self.assertTrue(plan['connect'])
def test_enforced_selection_keeps_shared_package_inputs_full(self):
self.repo.write(gate.POLICY_PATH, json.dumps(dict(self.repo.policy, rollout='enforced')))
baseline = self.repo.commit()
for path in ('leaf/build.rs', 'leaf/tests/fixtures/data.json', 'leaf/tests/fixtures/shared.rs',
'leaf/src/template.html', 'leaf/native/include.h'):
with self.subTest(path=path):
self.repo.write(path, 'changed\n')
plan = self.repo.plan(self.repo.commit(), base=baseline)
self.assertTrue(plan['full_validation'])
self.assertTrue(plan['connect'])
self.assertEqual(set(plan['packages']), {'rustfs', 'core', 'leaf', 'consumer', 'macro'})
def test_enforced_unrelated_source_omits_connect_but_keeps_its_dependents_and_core(self):
self.repo.write(gate.POLICY_PATH, json.dumps(dict(self.repo.policy, rollout='enforced')))
baseline = self.repo.commit()
self.repo.write('leaf/src/lib.rs', '// changed\n')
plan = self.repo.plan(self.repo.commit(), base=baseline)
self.assertEqual(plan['packages'], ['consumer', 'core', 'leaf', 'rustfs'])
self.assertEqual(plan['jobs']['connect-feature-boundaries'], 'skipped')
for job in ('workspace-lint-and-build', 'workspace-tests', 'core-contract', 'e2e-tests',
's3-implemented-tests', 's3-lifecycle-behavior-tests'):
self.assertEqual(plan['jobs'][job], 'success')
def test_enforced_plan_runs_a_real_failing_reverse_dependency_test(self):
self.repo.write('rust-toolchain.toml', (gate.ROOT / 'rust-toolchain.toml').read_text())
self.repo.write(gate.POLICY_PATH, json.dumps(dict(self.repo.policy, rollout='enforced')))
self.repo.write('leaf/src/lib.rs', 'pub fn answer() -> u8 { 1 }\n')
self.repo.write('core/src/lib.rs', '#[test] fn core_contract() { assert_eq!(1, 1); }\n')
self.repo.write('consumer/src/lib.rs', '#[cfg(test)] mod tests { extern crate renamed; #[test] fn reverse_dependency_contract() { assert_eq!(renamed::answer(), 1); } }\n')
baseline = self.repo.commit()
self.repo.write('leaf/src/lib.rs', 'pub fn answer() -> u8 { 2 }\n')
plan = self.repo.plan(self.repo.commit(), base=baseline)
arguments = ['cargo', 'nextest', 'run', '--offline', '--color', 'never', '--no-fail-fast']
for package in plan['packages']:
arguments.extend(['-p', package])
result = subprocess.run(arguments, cwd=self.repo.root, capture_output=True, text=True)
self.assertNotEqual(result.returncode, 0)
self.assertIn('reverse_dependency_contract', result.stderr)
self.assertIn('1 failed', result.stderr)
self.assertIn('1 passed', result.stderr)
def test_docs_and_e2e_shortcuts_do_not_hide_production_or_fixture_inputs(self):
self.repo.write('README.md', '# docs\n')
docs = self.repo.plan(self.repo.commit())
self.assertEqual(docs['mode'], 'docs')
self.assertEqual(docs['packages'], [])
self.repo.write('crates/e2e_test/src/lib.rs', '// harness change\n')
e2e = self.repo.plan(self.repo.commit())
self.assertEqual(e2e['mode'], 'e2e')
self.assertFalse(e2e['connect'])
self.repo.write('leaf/tests/fixtures/README.md', 'fixture input\n')
code = self.repo.plan(self.repo.commit())
self.assertEqual(code['mode'], 'full')
self.assertIn('leaf', code['proposed']['packages'])
def release_metadata_base(self):
self.repo.write(gate.POLICY_PATH, json.dumps(dict(self.repo.policy, rollout='enforced')))
files = {
'flake.nix': '{ pkgs }: {\n rustfs = pkgs.buildRustPackage {\n pname = "rustfs";\n version = "1.0.4";\n src = ./.;\n };\n clientVersion = "0.1.36";\n}\n',
'helm/rustfs/Chart.yaml': 'apiVersion: v2\nname: rustfs\nversion: "1.0.4"\nappVersion: "1.0.4"\n',
'rustfs.spec': 'Name: rustfs\nVersion: 1.0.4\nRelease: 1\n%build\ncargo build --release\n%changelog\n* Mon Oct 26 2026 Maintainer <maintainer@example.invalid>\n- Update RPM package to RustFS 1.0.4\n',
}
for path, content in files.items():
self.repo.write(path, content)
return self.repo.commit(), files
def test_stable_installation_metadata_keeps_quick_checks_without_rust_rebuild(self):
baseline, files = self.release_metadata_base()
for path, content in files.items():
updated = content.replace('1.0.4', '1.0.5') if path != 'rustfs.spec' else content.replace('Version: 1.0.4', 'Version: 1.0.5')
if path == 'rustfs.spec':
updated = updated.replace('%changelog\n', '%changelog\n* Wed Nov 11 2026 Maintainer <maintainer@example.invalid>\n- Update RPM package to RustFS 1.0.5\n\n')
self.repo.write(path, updated)
self.repo.write('README.md', '# Install 1.0.5\n')
head = self.repo.commit()
plan = self.repo.plan(head, base=baseline)
self.assertEqual(plan['mode'], 'docs')
self.assertEqual(plan['packages'], [])
for job in gate.ALWAYS_JOBS:
self.assertEqual(plan['jobs'][job], 'success')
self.assertTrue(all(plan['jobs'][job] == 'skipped' for job in gate.CODE_JOBS))
self.assertEqual(gate.validate_plan(plan, 'pull_request', 'refs/heads/main', head, plan['tree']), plan['jobs'])
for event in ('push', 'merge_group', 'schedule', 'workflow_dispatch'):
self.assertTrue(self.repo.plan(head, event=event, base=baseline)['full_validation'])
def test_push_skips_validation_only_for_the_tree_a_merge_group_run_proved(self):
head, tree = self.repo.git('rev-parse', 'HEAD'), self.repo.git('rev-parse', 'HEAD^{tree}')
proof = {'run_id': 7, 'url': 'https://github.com/rustfs/rustfs/actions/runs/7', 'tree': tree}
plan = self.repo.plan(head, event='push', proof=proof)
self.assertEqual((plan['mode'], plan['proven_by']), ('proven', proof))
# This run validates nothing itself, so the retained plan must not claim a full or Connect validation.
self.assertEqual((plan['full_validation'], plan['connect']), (False, False))
self.assertEqual({job for job, state in plan['jobs'].items() if state == 'success'}, set(gate.ALWAYS_JOBS))
self.assertTrue(all(proof['url'] in plan['not_applicable'][job] for job in gate.CODE_JOBS))
self.assertEqual(gate.validate_plan(plan, 'push', 'refs/heads/main', head, tree), plan['jobs'])
# A direct push has no proving run; a proof of another tree, or on any other event, proves nothing.
for event, candidate in [('push', None), ('push', dict(proof, tree='0' * 40)), ('merge_group', proof),
('schedule', proof), ('workflow_dispatch', proof), ('pull_request', proof)]:
with self.subTest(event=event, proof=candidate):
other = self.repo.plan(head, event=event, proof=candidate)
self.assertNotEqual(other['mode'], 'proven')
self.assertIsNone(other['proven_by'])
if event != 'pull_request':
self.assertTrue(all(other['jobs'][job] == 'success' for job in (gate.LINT_JOB, gate.ARCHIVE_PRODUCER, 'workspace-tests')))
def test_individual_stable_version_fields_without_new_rpm_history_are_metadata(self):
baseline, files = self.release_metadata_base()
for path, content in files.items():
with self.subTest(path=path):
self.repo.git('reset', '--hard', baseline)
updated = content.replace('1.0.4', '1.0.5') if path != 'rustfs.spec' else content.replace('Version: 1.0.4', 'Version: 1.0.5')
self.repo.write(path, updated)
self.assertEqual(self.repo.plan(self.repo.commit(), base=baseline)['mode'], 'docs')
def test_installation_metadata_does_not_hide_build_or_malformed_changes(self):
baseline, files = self.release_metadata_base()
cases = [
('flake.nix', files['flake.nix'].replace('src = ./.;', 'src = ./other;')),
('flake.nix', files['flake.nix'].replace('0.1.36', '0.1.37')),
('flake.nix', files['flake.nix'].replace('1.0.4', '${builtins.readFile ./version}')),
('helm/rustfs/Chart.yaml', files['helm/rustfs/Chart.yaml'] + 'dependencies: []\n'),
('helm/rustfs/Chart.yaml', files['helm/rustfs/Chart.yaml'].replace('appVersion: "1.0.4"', 'appVersion: "1.0.5"')),
('helm/rustfs/Chart.yaml', files['helm/rustfs/Chart.yaml'] + 'version: "1.0.5"\n'),
('rustfs.spec', files['rustfs.spec'].replace('cargo build --release', 'cargo build')),
('rustfs.spec', files['rustfs.spec'].replace('Release: 1', 'Release: 2')),
('rustfs.spec', files['rustfs.spec'].replace('%changelog\n', '%changelog\n%(echo injected)\n')),
('rustfs.spec', files['rustfs.spec'].replace('Update RPM package', 'Rewrite existing history')),
]
cases.extend((path, content.replace('1.0.4', '1.0.5-rc.1')) for path, content in files.items())
for path, content in cases:
with self.subTest(path=path, content=content):
self.repo.git('reset', '--hard', baseline)
self.repo.write(path, content)
self.assertTrue(self.repo.plan(self.repo.commit(), base=baseline)['full_validation'])
def test_installation_metadata_rejects_normalization_marker_collisions(self):
_, files = self.release_metadata_base()
old = files['flake.nix'].replace(' clientVersion =', ' second = pkgs.buildRustPackage {\n pname = "rustfs";\n version = "<version>";\n src = ./other;\n };\n clientVersion =')
self.repo.write('flake.nix', old)
baseline = self.repo.commit()
new = old.replace('version = "1.0.4"', 'version = "<version>"').replace('version = "<version>";\n src = ./other;', 'version = "1.0.5";\n src = ./other;')
self.repo.write('flake.nix', new)
self.assertTrue(self.repo.plan(self.repo.commit(), base=baseline)['full_validation'])
def test_installation_metadata_rejects_missing_files_symlinks_and_mode_changes(self):
baseline, files = self.release_metadata_base()
for path in files:
for mutation in ('delete', 'symlink', 'executable'):
with self.subTest(path=path, mutation=mutation):
self.repo.git('reset', '--hard', baseline)
target = self.repo.root / path
if mutation == 'executable':
target.chmod(0o755)
else:
target.unlink()
if mutation == 'symlink':
target.symlink_to('/tmp/release-metadata')
self.assertTrue(self.repo.plan(self.repo.commit(), base=baseline)['full_validation'])
self.repo.git('reset', '--hard', baseline)
self.assertTrue(self.repo.plan(baseline, base=self.repo.base)['full_validation'])
def test_installation_metadata_cannot_override_code_or_explicit_full_policy(self):
baseline, files = self.release_metadata_base()
self.repo.write('flake.nix', files['flake.nix'].replace('1.0.4', '1.0.5'))
self.repo.write('leaf/src/lib.rs', '// changed implementation\n')
plan = self.repo.plan(self.repo.commit(), base=baseline)
self.assertEqual(plan['mode'], 'full')
self.assertEqual(plan['packages'], ['consumer', 'core', 'leaf', 'rustfs'])
self.repo.git('reset', '--hard', baseline)
self.repo.write('flake.nix', files['flake.nix'].replace('1.0.4', '1.0.5'))
head = self.repo.commit()
policy = dict(self.repo.policy, rollout='enforced', full_paths=['flake.nix'])
with patch.object(gate, 'read_policy', return_value=policy):
self.assertTrue(self.repo.plan(head, base=baseline)['full_validation'])
with patch.object(gate, 'read_policy', return_value=self.repo.policy):
self.assertTrue(self.repo.plan(head, base=baseline)['full_validation'])
def test_shadow_retains_full_mode_for_harness_build_and_fixture_changes(self):
for path in ('crates/e2e_test/build.rs', 'crates/e2e_test/src/fixture.json'):
self.repo.write(path, 'changed\n')
plan = self.repo.plan(self.repo.commit())
self.assertEqual(plan['mode'], 'full')
self.assertTrue(plan['connect'])
def test_new_harness_dependency_disables_e2e_shortcut(self):
self.repo.write('consumer/Cargo.toml', '[package]\nname="consumer"\nversion="0.1.0"\n[dependencies]\nharness={path="../crates/e2e_test"}\n')
baseline = self.repo.commit()
self.repo.write('crates/e2e_test/src/lib.rs', '// change\n')
plan = self.repo.plan(self.repo.commit(), base=baseline)
self.assertEqual(plan['mode'], 'full')
self.assertIn('consumer', plan['proposed']['packages'])
def test_non_pr_events_validate_complete_combined_candidate_and_closed_cancels(self):
self.repo.write('leaf/src/lib.rs', '// PR one\n')
self.repo.write('macro/src/lib.rs', '// PR two\n')
head = self.repo.commit()
for event in ('push', 'merge_group', 'schedule', 'workflow_dispatch'):
plan = self.repo.plan(head, event=event)
self.assertTrue(plan['full_validation'])
self.assertEqual(plan['mode'], 'full')
self.assertEqual(plan['head'], head)
self.assertEqual(plan['tree'], self.repo.git('rev-parse', head + '^{tree}'))
self.assertEqual(gate.validate_plan(plan, event, 'refs/heads/main', head, plan['tree']), plan['jobs'])
closed = self.repo.plan(head, action='closed')
self.assertEqual(set(closed['jobs'].values()), {'skipped'})
def test_unavailable_diff_policy_or_base_falls_back_and_invalid_head_fails(self):
self.repo.write('leaf/src/lib.rs', '// changed\n')
head = self.repo.commit()
for base in ('0' * 40, '', '--output=bad'):
plan = gate.select_plan('pull_request', base, head, 'refs/heads/main', self.repo.root)
self.assertTrue(plan['full_validation'])
self.assertTrue(plan['connect'])
self.assertTrue(plan['packages'])
with patch.object(gate, 'read_policy', side_effect=ValueError('broken policy')):
self.assertTrue(self.repo.plan(head)['full_validation'])
with self.assertRaises(ValueError):
self.repo.plan('--malicious')
def test_actual_workflow_bootstrap_never_executes_pr_policy_and_upgrades_legacy_output(self):
workflow = gate.workflow_document((Path(gate.__file__).resolve().parent.parent / '.github/workflows/ci.yml').read_text())
body = next(step['run'] for step in workflow['jobs']['classify-changes']['steps'] if step.get('id') == 'scope')
self.repo.write('scripts/ci_gate.py', "import os\nwith open(os.environ['GITHUB_OUTPUT'], 'a') as output: output.write('mode=docs\\npackages=[\"core\"]\\nplan={}\\ngateway_smoke=false\\n')\n")
base = self.repo.commit()
self.repo.write('scripts/ci_gate.py', 'raise SystemExit(71)\n')
head = self.repo.commit()
for revision in (base, '0' * 40, ''):
output = self.repo.root / 'outputs'
output.write_text('')
env = dict(os.environ, GITHUB_EVENT_NAME='pull_request', GITHUB_REF='refs/heads/main', GITHUB_SHA=head,
CI_BASE_SHA=revision, RUNNER_TEMP=str(self.repo.root), GITHUB_OUTPUT=str(output))
result = subprocess.run(['bash', '--noprofile', '--norc', '-e', '-o', 'pipefail', '-c', body],
cwd=self.repo.root, env=env, capture_output=True, text=True)
self.assertEqual(result.returncode, 0, result.stderr)
values = dict(line.split('=', 1) for line in output.read_text().splitlines())
self.assertEqual(values['mode'], 'full')
self.assertEqual(values['connect'], 'true')
self.assertEqual(values['packages'], '')
self.assertEqual(values['plan'], '')
self.repo.write('scripts/ci_gate.py', 'raise SystemExit(29)\n')
broken = self.repo.commit()
env['CI_BASE_SHA'] = broken
result = subprocess.run(['bash', '--noprofile', '--norc', '-e', '-o', 'pipefail', '-c', body],
cwd=self.repo.root, env=env, capture_output=True, text=True)
self.assertEqual(result.returncode, 29)
def test_bootstrap_script_is_standalone_and_reads_policy_from_base_objects(self):
self.repo.write('leaf/src/lib.rs', '// changed\n')
self.repo.write(gate.POLICY_PATH, json.dumps(dict(self.repo.policy, rollout='enforced', core_packages=[])))
head = self.repo.commit()
script = self.repo.root / 'trusted.py'
script.write_text(Path(gate.__file__).read_text())
output = self.repo.root / 'outputs'
env = dict(os.environ, GITHUB_EVENT_NAME='pull_request', GITHUB_REF='refs/heads/main', GITHUB_SHA=head,
CI_BASE_SHA=self.repo.base, GITHUB_OUTPUT=str(output))
result = subprocess.run([sys.executable, '-I', str(script), 'select'], cwd=self.repo.root, env=env, capture_output=True, text=True)
self.assertEqual(result.returncode, 0, result.stderr)
values = dict(line.split('=', 1) for line in output.read_text().splitlines())
self.assertEqual(set(values), {'mode', 'plan', 'connect', 'packages', 'full_validation', 'plan_contract'})
self.assertEqual(values['plan_contract'], gate.PLAN_CONTRACT)
plan = json.loads(values['plan'])
self.assertEqual(plan['policy']['revision'], self.repo.base)
self.assertEqual(plan['policy']['rollout'], 'shadow')
self.assertEqual(values['connect'], 'true')
class GateTests(unittest.TestCase):
def test_fips_provider_is_required_at_nightly_and_skipped_on_pr(self):
self.assertEqual(gate.expected_results('full', 'schedule', 'refs/heads/main')['fips-provider'], 'success')
self.assertEqual(gate.expected_results('full', 'pull_request', 'refs/heads/main')['fips-provider'], 'skipped')
plan = self.plan('schedule')
good = self.needs(plan)
self.assertEqual(gate.verify_results(good, 'schedule', plan['ref'], plan['head'], plan['tree']), [])
good['fips-provider']['result'] = 'skipped'
self.assertTrue(gate.verify_results(good, 'schedule', plan['ref']))
def plan(self, event='pull_request', mode='full', connect=True):
jobs = gate.expected_results(mode, event, 'refs/heads/main', connect)
return {'schema_version': 1, 'event': event, 'ref': 'refs/heads/main', 'head': 'a' * 40, 'tree': 'b' * 40,
'base': 'c' * 40, 'action': '', 'mode': mode, 'connect': connect and mode != 'proven', 'full_validation': mode == 'full', 'packages': ['rustfs'] if mode != 'docs' else [],
'policy': {'revision': 'c' * 40, 'rollout': 'enforced'}, 'jobs': jobs, 'configurations': gate.configurations(jobs),
'reasons': ['fixture'], 'not_applicable': {job: 'fixture' for job, state in jobs.items() if state == 'skipped'},
'proven_by': {'run_id': 7, 'url': 'https://github.com/rustfs/rustfs/actions/runs/7', 'tree': 'b' * 40} if mode == 'proven' else None}
def needs(self, plan):
needs = {job: {'result': state} for job, state in plan['jobs'].items()}
needs['classify-changes']['outputs'] = {'mode': plan['mode'], 'plan': json.dumps(plan)}
return needs
def test_failure_cancel_missing_extra_or_unexpected_skip_is_rejected(self):
for event, mode in [('pull_request', 'docs'), ('pull_request', 'e2e'), ('pull_request', 'full'), ('push', 'full'), ('push', 'proven'), ('merge_group', 'full'), ('schedule', 'full'), ('workflow_dispatch', 'full')]:
plan = self.plan(event, mode)
good = self.needs(plan)
self.assertEqual(gate.verify_results(good, event, plan['ref'], plan['head'], plan['tree']), [])
for job, state in plan['jobs'].items():
for bad in (None, 'failure', 'cancelled', 'skipped', 'success'):
if bad == state:
continue
needs = copy.deepcopy(good)
needs[job]['result'] = bad
self.assertTrue(gate.verify_results(needs, event, plan['ref']), (event, mode, job, bad))
needs = copy.deepcopy(good)
del needs[job]
self.assertTrue(gate.verify_results(needs, event, plan['ref']))
good['new-unwired-job'] = {'result': 'success'}
self.assertTrue(gate.verify_results(good, event, plan['ref']))
def test_invalid_plan_matrix_and_candidate_identity_fail_closed(self):
plan = self.plan('merge_group')
for field, value in [('schema_version', 2), ('event', 'push'), ('ref', 'wrong'), ('base', '../main'), ('packages', []), ('connect', 'false'), ('configurations', []), ('jobs', {}), ('not_applicable', {}), ('policy', {})]:
bad = dict(plan, **{field: value})
needs = self.needs(plan)
needs['classify-changes']['outputs']['plan'] = json.dumps(bad)
self.assertTrue(gate.verify_results(needs, 'merge_group', plan['ref']), field)
good = self.needs(plan)
self.assertTrue(gate.verify_results(good, plan['event'], plan['ref'], 'c' * 40, plan['tree']))
self.assertTrue(gate.verify_results(good, plan['event'], plan['ref'], plan['head'], 'c' * 40))
self.assertTrue(gate.verify_results(good, plan['event'], plan['ref'], base='d' * 40))
self.assertTrue(gate.verify_results(good, plan['event'], plan['ref'], action='closed'))
def test_a_proven_push_needs_its_own_tree_proof_and_nothing_else_may_carry_one(self):
proven, full = self.plan('push', 'proven'), self.plan('push', 'full')
self.assertEqual(gate.verify_results(self.needs(proven), 'push', proven['ref'], proven['head'], proven['tree']), [])
proof = proven['proven_by']
bad = [dict(proven, proven_by=None), dict(proven, proven_by=dict(proof, tree='c' * 40)),
dict(proven, proven_by=dict(proof, run_id='7')), dict(proven, proven_by=dict(proof, run_id=0)),
dict(proven, proven_by=dict(proof, url='https://example.invalid/7')), dict(proven, proven_by={}),
dict(full, proven_by=proof), dict(proven, connect=True), dict(proven, full_validation=True)]
for plan in bad:
with self.subTest(plan=plan['proven_by'], connect=plan['connect'], full=plan['full_validation']), self.assertRaises(ValueError):
gate.validate_plan(plan, 'push', plan['ref'])
for event in ('pull_request', 'merge_group', 'schedule', 'workflow_dispatch'):
with self.subTest(event=event), self.assertRaises(ValueError):
gate.expected_results('proven', event, 'refs/heads/main')
def test_the_aggregate_names_the_proving_run_only_for_a_proven_plan(self):
for mode in ('proven', 'full'):
plan = self.plan('push', mode)
with tempfile.TemporaryDirectory() as directory, self.subTest(mode=mode):
summary = Path(directory) / 'summary.md'
environment = {'GITHUB_EVENT_NAME': 'push', 'GITHUB_REF': plan['ref'], 'GITHUB_STEP_SUMMARY': str(summary),
'CI_NEEDS': json.dumps(self.needs(plan))}
with patch.dict(os.environ, environment, clear=True), patch.object(sys, 'argv', ['ci_gate.py', 'verify']), \
patch('sys.stdout', new_callable=io.StringIO) as output:
self.assertEqual(gate.main(), False)
note = ('Validation jobs were skipped as proven: merge_group run https://github.com/rustfs/rustfs/actions/runs/7 '
f"passed tree {'b' * 40}.")
self.assertEqual(note in output.getvalue(), mode == 'proven')
self.assertEqual(summary.read_text() if summary.exists() else '', note + '\n' if mode == 'proven' else '')
def test_the_queue_run_that_proves_a_push_validates_everything_that_push_would(self):
queued = {job for job, result in gate.expected_results('full', 'merge_group', 'refs/heads/main').items() if result == 'success'}
pushed = {job for job, result in gate.expected_results('full', 'push', 'refs/heads/main').items() if result == 'success'}
self.assertLessEqual(pushed, queued)
def test_legacy_base_cannot_authorize_skipped_new_jobs(self):
expected = gate.expected_results('full', 'pull_request', 'refs/heads/main')
needs = {job: {'result': result} for job, result in expected.items()}
needs['classify-changes']['outputs'] = {'mode': 'full'}
self.assertEqual(gate.verify_results(needs, 'pull_request', 'refs/heads/main'), [])
needs['classify-changes']['outputs']['mode'] = 'docs'
self.assertTrue(gate.verify_results(needs, 'pull_request', 'refs/heads/main'))
needs['classify-changes']['outputs'] = {'mode': 'full', 'plan': '{'}
self.assertTrue(gate.verify_results(needs, 'pull_request', 'refs/heads/main'))
def test_plan_from_a_previous_contract_cannot_authorize_the_new_job_set(self):
# A base planner predating the NIGHTLY_JOBS contract still emits
# connect-feature-boundaries as required success on a pull request, and
# one that predates the rio-v2 lane removal still names
# test-and-lint-rio-v2. The current verifier must reject that plan
# instead of accepting the old responsibility, so the workflow's
# contract-marker fallback is the only path that can widen or narrow
# the required set.
stale = self.plan()
stale['jobs'] = dict(stale['jobs'], **{'connect-feature-boundaries': 'success',
'uring-integration': 'success',
'test-and-lint-m-compatible': 'success',
'test-and-lint-protocols': 'success'})
stale['not_applicable'] = {job: 'fixture' for job, state in stale['jobs'].items() if state == 'skipped'}
expected = gate.expected_results('full', 'pull_request', 'refs/heads/main')
self.assertEqual(expected['connect-feature-boundaries'], 'skipped')
needs = {job: {'result': result} for job, result in expected.items()}
needs['classify-changes']['outputs'] = {'mode': 'full', 'plan': json.dumps(stale, separators=(',', ':')),
'connect': 'true', 'full_validation': 'true'}
self.assertTrue(gate.verify_results(needs, 'pull_request', 'refs/heads/main'))
def test_retired_rio_v2_lanes_stay_out_of_the_aggregate(self):
retired = ("test-and-lint-rio-v2", "build-rustfs-debug-binary-rio-v2", "e2e-tests-rio-v2")
for event in gate.EVENTS:
jobs = gate.expected_results("full", event, "refs/heads/main")
self.assertTrue(set(retired).isdisjoint(jobs), event)
self.assertEqual(jobs["build-rustfs-debug-binary"], "success")
self.assertEqual(jobs["e2e-tests"], "success")
self.assertEqual(jobs["s3-implemented-tests"], "success")
self.assertEqual(jobs["s3-lifecycle-behavior-tests"], "success")
self.assertTrue(all(item["job"] not in retired and "rio-v2" not in item["features"] for item in gate.configurations(jobs)))
root = Path(gate.__file__).resolve().parent.parent
workflow = (root / ".github/workflows/ci.yml").read_text()
warm = (root / ".github/workflows/cache-warm.yml").read_text()
for name in (*retired, "warm-ci-feat-rio", "ci-feat-rio"):
self.assertNotIn(name, workflow)
self.assertNotIn(name, warm)
self.assertIn("\n build-rustfs-debug-binary:\n", workflow)
self.assertIn("\n e2e-tests:\n", workflow)
plan = self.plan("schedule")
needs = self.needs(plan)
needs["test-and-lint-rio-v2"] = {"result": "success"}
self.assertTrue(gate.verify_results(needs, "schedule", plan["ref"], plan["head"], plan["tree"]))
def workflow(self):
jobs = {}
for job in gate.ALWAYS_JOBS + gate.CODE_JOBS + gate.OPTIONAL_JOBS:
# A complete plan lookup is represented by equivalent explicit expressions here.
if job in gate.ALWAYS_JOBS:
expression = "true"
elif job == 'connect-feature-boundaries':
expression = "needs.classify-changes.outputs.mode == 'full' && needs.classify-changes.outputs.connect == 'true' && contains(fromJSON('[\"schedule\",\"workflow_dispatch\"]'), github.event_name)"
elif job in gate.NIGHTLY_JOBS:
expression = "needs.classify-changes.outputs.mode == 'full' && contains(fromJSON('[\"schedule\",\"workflow_dispatch\"]'), github.event_name)"
elif job == 'e2e-full':
expression = "needs.classify-changes.outputs.mode == 'full' && (github.event_name == 'merge_group' || github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref == 'refs/heads/main'))"
elif job in gate.E2E_JOBS:
expression = "contains(fromJSON('[\"full\",\"e2e\"]'), needs.classify-changes.outputs.mode)"
else:
expression = "needs.classify-changes.outputs.mode == 'full'"
expression = f"({expression}) && (github.event_name != 'pull_request' || github.event.action != 'closed')"
jobs[job] = {'name': job, 'if': expression, 'steps': []}
jobs['classify-changes']['outputs'] = {'mode': '${{ steps.scope.outputs.mode }}'}
jobs[gate.LINT_JOB]['steps'] = [{'run': 'cargo clippy --all-targets -- -D warnings'}]
jobs[gate.ADVISORIES_JOB]['runs-on'] = 'ubuntu-latest'
jobs[gate.ADVISORIES_JOB]['steps'] = [{'run': 'python3 scripts/security/check_advisories.py --output artifacts/advisories/advisories-gate.json'}]
jobs[gate.SECURITY_INPUT_JOB] = {
'name': 'Security Input Gate',
'needs': ['classify-changes'],
'if': "github.event_name != 'pull_request' || github.event.action != 'closed'",
'uses': gate.SECURITY_INPUT_WORKFLOW,
'with': {
'mode': 'smoke',
'targets': 'auto',
'max_total_time': '60',
'base_sha': '${{ github.event.pull_request.base.sha }}',
'head_sha': '${{ github.sha }}',
'event_name': '${{ github.event_name }}',
'ref_name': '${{ github.ref }}',
'ci_mode': '${{ needs.classify-changes.outputs.mode }}',
},
}
jobs['workspace-tests']['needs'] = [gate.ARCHIVE_PRODUCER]
jobs['classify-changes']['steps'] = [{'id': 'scope', 'run': f"grep -q '^plan_contract={gate.PLAN_CONTRACT}$' \"$GITHUB_OUTPUT\""}]
jobs['test-and-lint-protocols']['strategy'] = {'matrix': {'features': [
{'name': 'swift', 'flags': '--features swift'}, {'name': 'sftp', 'flags': '--features sftp'}, {'name': 'http3', 'flags': '--features http3,swift'},
{'name': 'internode-transport', 'flags': '--features rustfs/internode-transport'}]}}
jobs['required-checks'] = {'name': 'Test and Lint', 'if': "always() && (github.event_name != 'pull_request' || github.event.action != 'closed')",
'needs': list(gate.ALWAYS_JOBS + gate.CODE_JOBS + gate.OPTIONAL_JOBS),
'steps': [{'shell': 'bash', 'env': {'CI_NEEDS': '${{ toJSON(needs) }}'}, 'run': 'python3 scripts/ci_gate.py verify'}]}
return {'on': {'pull_request': {}}, 'jobs': jobs}
def check(self, workflow):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
path = root / '.github/workflows/ci.yml'
path.parent.mkdir(parents=True)
path.write_text(json.dumps(workflow))
return gate.check_workflow(root)
def test_cache_warm_builds_each_reader_selection_and_skips_exact_hits(self):
root = Path(gate.__file__).resolve().parent.parent
readers, warm = gate.ci_dev_workflows(root)
original = json.dumps({**readers, 'cache-warm.yml': warm})
def errors(documents):
warm = documents.pop('cache-warm.yml')
return gate.cache_warm_errors(documents, warm)
def step(jobs, job, text):
return next(item for item in jobs[job]['steps'] if text in item.get('run', item.get('uses', '')))
def rewrite(item, old, new):
item['run'] = item['run'].replace(old, new)
def key(jobs, job):
return step(jobs, job, './.github/actions/setup')['with']
e2e = 'python3 scripts/ci_test_artifact.py cargo warm --configuration e2e'
self.assertEqual(errors(json.loads(original)), [])
mutations = [
(lambda d: rewrite(step(d['cache-warm.yml'], 'warm-ci-dev', e2e), e2e, e2e.replace('e2e', 'workspace')),
'warm-ci-dev must build the e2e archive selection'),
(lambda d: rewrite(step(d['cache-warm.yml'], 'warm-ci-dev', e2e), e2e, e2e + '-foo'),
'warm-ci-dev must build the e2e archive selection'),
(lambda d: rewrite(step(d['cache-warm.yml'], 'warm-ci-dev', e2e), e2e, e2e + '-foo'),
'warm-ci-dev builds the e2e-foo selection, which no ci.yml job archives'),
(lambda d: rewrite(step(d['cache-warm.yml'], 'warm-ci-dev', e2e), 'python3 scripts/ci_test_artifact.py cargo warm --configuration workspace',
'cargo build --workspace --all-targets'),
'warm-ci-dev must build the workspace archive selection'),
# The --timings step runs only on request, so a selection moved into it is not warmed.
(lambda d: (rewrite(step(d['cache-warm.yml'], 'warm-ci-dev', e2e), e2e, ''),
rewrite(step(d['cache-warm.yml'], 'warm-ci-dev', '--timings'), 'cargo build', e2e + '\ncargo build')),
'warm-ci-dev must build the e2e archive selection'),
(lambda d: d['ci.yml']['build-rustfs-debug-binary']['steps'].remove(
step(d['ci.yml'], 'build-rustfs-debug-binary', 'ci_test_artifact.py build --configuration e2e')),
'warm-ci-dev builds the e2e selection, which no ci.yml job archives'),
(lambda d: d['ci.yml']['build-rustfs-debug-binary']['steps'].append({'run': 'python3 scripts/ci_test_artifact.py build --configuration other --archive x'}),
'warm-ci-dev must build the other archive selection'),
(lambda d: rewrite(step(d['cache-warm.yml'], 'warm-ci-dev', gate.LINT_COMMANDS[1]), gate.LINT_COMMANDS[1], 'cargo clippy --all-targets -- -D warnings'),
'warm-ci-dev must run the workspace lint command'),
(lambda d: step(d['cache-warm.yml'], 'warm-ci-dev', e2e).pop('if'), 'warm-ci-dev builds after an exact cache hit'),
(lambda d: step(d['cache-warm.yml'], 'warm-ci-dev', gate.LINT_COMMANDS[1]).update({'if': 'always()'}), 'warm-ci-dev builds after an exact cache hit'),
(lambda d: step(d['cache-warm.yml'], 'warm-ci-uring', 'cargo build').pop('if'), 'warm-ci-uring builds after an exact cache hit'),
(lambda d: step(d['cache-warm.yml'], 'warm-ci-feat-proto', './.github/actions/setup').pop('id'),
'warm-ci-feat-proto builds after an exact cache hit'),
]
warm_key = key(json.loads(original)['cache-warm.yml'], 'warm-ci-dev')['cache-shared-key']
reader_workflows = [name for name in json.loads(original) if name != 'cache-warm.yml']
readers = [(workflow, job) for workflow in reader_workflows for job, block in json.loads(original)[workflow].items()
if any(item.get('with', {}).get('cache-shared-key') == warm_key for item in block.get('steps', []))]
self.assertEqual(len(readers), 14)
for workflow, job in (('cache-warm.yml', 'warm-ci-dev'), ('ci.yml', 'workspace-clippy'), ('reference-parity.yml', 'build-candidate')):
mutations.append((lambda d, workflow=workflow, job=job: key(d[workflow], job).update({'cache-shared-key': 'ci-dev-0'}),
f'{workflow} {job} uses cache key ci-dev-0; the ci-dev key for these warm commands is {warm_key}'))
# A changed warm command without a new key leaves readers on the old artifacts.
mutations.append((lambda d: rewrite(step(d['cache-warm.yml'], 'warm-ci-dev', e2e), '--features e2e-test-hooks', '--features e2e-test-hooks,x'),
f'cache-warm.yml warm-ci-dev uses cache key {warm_key}; the ci-dev key for these warm commands is '))
# Either spelling of the option names the same selection; only the digest notices the edit.
documents = json.loads(original)
rewrite(step(documents['cache-warm.yml'], 'warm-ci-dev', e2e), '--configuration e2e', '--configuration=e2e')
self.assertEqual([error.split(';')[0] for error in errors(documents)], [f'cache-warm.yml warm-ci-dev uses cache key {warm_key}'] +
[f'{workflow} {job} uses cache key {warm_key}' for workflow, job in readers])
for mutate, message in mutations:
documents = json.loads(original)
mutate(documents)
found = errors(documents)
with self.subTest(message=message):
self.assertTrue(any(error.startswith(message) for error in found), found)
def test_ignored_ilm_archive_execution_preserves_failure_and_core_report(self):
workflow = gate.workflow_document((Path(gate.__file__).resolve().parent.parent / '.github/workflows/ci.yml').read_text())
steps = workflow['jobs']['workspace-tests']['steps']
bodies = [step['run'] for step in steps if '--run-ignored ignored-only' in step.get('run', '')]
self.assertEqual(len(bodies), 1)
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
commands = root / 'bin'
commands.mkdir()
timeout = commands / 'timeout'
timeout.write_text('#!/bin/sh\nshift 4\nexec "$@"\n')
timeout.chmod(0o755)
cargo = commands / 'cargo'
cargo.write_text('#!/bin/sh\nprintf "%s\\n" "$@" > "$ILM_ARGS"\nexit "$ILM_STATUS"\n')
cargo.chmod(0o755)
report = root / 'target/nextest/ci/junit.xml'
report.parent.mkdir(parents=True)
report.write_text('existing core report')
args = root / 'args'
for status in (0, 23, 124):
env = dict(os.environ, PATH=f"{commands}{os.pathsep}{os.environ['PATH']}", ILM_ARGS=str(args),
ILM_STATUS=str(status), RUNNER_TEMP=str(root), GITHUB_WORKSPACE=str(root))
result = subprocess.run(['bash', '-e', '-o', 'pipefail', '-c', bodies[0]], cwd=root, env=env, capture_output=True, text=True)
self.assertEqual(result.returncode, status, result.stderr)
self.assertEqual(report.read_text(), 'existing core report')
arguments = args.read_text().splitlines()
self.assertEqual(arguments[:7], ['nextest', 'run', '--profile', 'default', '-j1', '--run-ignored', 'ignored-only'])
self.assertNotIn('--archive-file', arguments)
self.assertEqual(arguments[arguments.index('--cargo-metadata') + 1], 'target/nextest/cargo-metadata.json')
self.assertEqual(arguments[arguments.index('--binaries-metadata') + 1], 'target/nextest/binaries-metadata.json')
self.assertEqual(arguments[arguments.index('--target-dir-remap') + 1], str(root / 'target'))
self.assertIn(f'exit_status={status}', (root / 'artifacts/ilm-integration/diagnostics.txt').read_text())
def test_full_e2e_gate_pushes_only_on_main(self):
workflow_path = Path(gate.__file__).resolve().parent.parent / ".github/workflows/ci.yml"
triggers = gate.workflow_document(workflow_path.read_text())["on"]
for event in ("push", "pull_request"):
self.assertEqual(triggers[event]["branches"], ["main"])
for event, ref, required in (
("push", "refs/heads/main", "success"),
("push", "refs/heads/gateway/integration", "skipped"),
("push", "refs/heads/release", "skipped"),
("push", "refs/heads/feature", "skipped"),
):
self.assertEqual(gate.expected_results("full", event, ref)["e2e-full"], required, ref)
def test_parallel_clippy_lane_still_gates_the_aggregate(self):
lint = gate.LINT_JOB
# The aggregate requires the lint wherever the archive producer runs.
for event, mode, required in (('pull_request', 'full', 'success'), ('pull_request', 'e2e', 'success'),
('pull_request', 'docs', 'skipped'), ('merge_group', 'full', 'success'),
('push', 'full', 'success'), ('schedule', 'full', 'success'),
('workflow_dispatch', 'full', 'success')):
plan = self.plan(event, mode)
self.assertEqual(plan['jobs'][lint], required, (event, mode))
self.assertEqual(plan['jobs'][lint], plan['jobs'][gate.ARCHIVE_PRODUCER], (event, mode))
self.assertEqual(gate.verify_results(self.needs(plan), event, plan['ref']), [])
for bad in ({'failure', 'cancelled', 'skipped', 'success', None} - {required}):
needs = self.needs(plan)
needs[lint]['result'] = bad
errors = gate.verify_results(needs, event, plan['ref'])
self.assertTrue(any(error.startswith(f'{lint}: expected {required}') for error in errors), (event, mode, bad, errors))
needs = self.needs(plan)
del needs[lint]
self.assertTrue(any(lint in error and 'job set differs' in error for error in gate.verify_results(needs, event, plan['ref'])))
self.assertIn(lint, [item['job'] for item in gate.configurations(self.plan()['jobs']) if item['id'] == 'workspace-lint'])
# A base planner that predates the lint job cannot describe the job set.
stale = self.plan()
del stale['jobs'][lint]
needs = self.needs(stale)
self.assertTrue(gate.verify_results(needs, 'pull_request', stale['ref']))
def test_clippy_lane_is_wired_beside_the_archive_producer(self):
workflow = self.workflow()
self.assertEqual(self.check(workflow), [])
lint, producer = gate.LINT_JOB, gate.ARCHIVE_PRODUCER
step = {'run': 'python3 scripts/ci_test_artifact.py cargo lint --configuration workspace'}
for case, (mutate, message) in enumerate((
# The aggregate must keep depending on the lint, and the lint must keep running.
(lambda w: w['jobs']['required-checks']['needs'].remove(lint), 'required-checks must directly depend on every verification job exactly once'),
(lambda w: w['jobs'].pop(lint), 'CI verification jobs and the required gate contract differ'),
(lambda w: w['jobs'][lint].update({'steps': []}), 'workspace Clippy must run on every code event, pull requests included'),
(lambda w: w['jobs'][lint]['steps'][0].update({'if': "github.event_name != 'merge_group'"}), 'workspace Clippy must run on every code event, pull requests included'),
(lambda w: w['jobs'][lint]['steps'][0].update({'run': 'cargo clippy --all-targets'}), 'workspace Clippy must run on every code event, pull requests included'),
(lambda w: w['jobs'][lint].update({'continue-on-error': 'true'}), f'{lint} cannot convert a validation failure into success'),
(lambda w: w['jobs'][lint]['steps'][0].update({'continue-on-error': 'true'}), f'{lint} cannot convert a validation failure into success'),
# Its scope is the archive producer's scope on every event.
(lambda w: w['jobs'][lint].update({'if': "github.event_name == 'merge_group'"}), f'{lint} must run under the same condition as {producer}'),
(lambda w: w['jobs'][lint].update({'if': 'false'}), f'{lint} must run under the same condition as {producer}'),
# One lint, in one place, off the path the workspace tests wait on.
(lambda w: w['jobs'][producer]['steps'].append(dict(step)), f'workspace Clippy belongs to {lint} alone'),
(lambda w: w['jobs'][producer].update({'needs': [lint]}), f'{producer} must not wait for {lint}'),
(lambda w: w['jobs']['workspace-tests']['needs'].append(lint), f'workspace-tests must not wait for {lint}'),
(lambda w: w['jobs']['workspace-tests'].update({'needs': ['classify-changes']}), f'workspace-tests must consume the archive of {producer}'),
# The workflow fallback must name the contract this planner emits.
(lambda w: w['jobs']['classify-changes']['steps'][0].update({'run': "grep -q '^plan_contract=3$' \"$GITHUB_OUTPUT\""}), f'classify-changes must fall back to the full matrix unless the plan carries contract {gate.PLAN_CONTRACT}'),
(lambda w: w['jobs']['classify-changes'].update({'steps': []}), f'classify-changes must fall back to the full matrix unless the plan carries contract {gate.PLAN_CONTRACT}'),
)):
changed = copy.deepcopy(workflow)
mutate(changed)
self.assertIn(message, self.check(changed), case)
# The checked-in workflow satisfies the same contract.
self.assertEqual(gate.check_workflow(Path(gate.__file__).resolve().parent.parent), [])
def test_security_advisories_lane_gates_every_event_including_docs_and_proven(self):
advisories = gate.ADVISORIES_JOB
self.assertIn(advisories, gate.ALWAYS_JOBS)
for event, mode in (('pull_request', 'docs'), ('pull_request', 'e2e'), ('pull_request', 'full'),
('push', 'full'), ('push', 'proven'), ('merge_group', 'full'),
('schedule', 'full'), ('workflow_dispatch', 'full')):
plan = self.plan(event, mode)
self.assertEqual(plan['jobs'][advisories], 'success', (event, mode))
self.assertEqual(gate.verify_results(self.needs(plan), event, plan['ref']), [])
for bad in ('failure', 'cancelled', 'skipped', None):
needs = self.needs(plan)
needs[advisories]['result'] = bad
errors = gate.verify_results(needs, event, plan['ref'])
self.assertTrue(any(error.startswith(f'{advisories}: expected success') for error in errors), (event, mode, bad, errors))
workflow = self.workflow()
self.assertEqual(self.check(workflow), [])
for case, (mutate, message) in enumerate((
(lambda w: w['jobs']['required-checks']['needs'].remove(advisories), 'required-checks must directly depend on every verification job exactly once'),
(lambda w: w['jobs'][advisories].update({'runs-on': 'sm-standard-4'}), f'{advisories} must run on ubuntu-latest'),
(lambda w: w['jobs'][advisories].update({'steps': []}), f'{advisories} must unconditionally run {gate.ADVISORIES_COMMAND}'),
(lambda w: w['jobs'][advisories]['steps'][0].update({'if': "github.event_name != 'pull_request'"}), f'{advisories} must unconditionally run {gate.ADVISORIES_COMMAND}'),
(lambda w: w['jobs'][advisories]['steps'][0].update({'run': f'{gate.ADVISORIES_COMMAND} || true'}), f'{advisories} must not mask failures or override the CI clock'),
(lambda w: w['jobs'][advisories]['steps'][0].update({'run': f'{gate.ADVISORIES_COMMAND} --now 2026-01-01T00:00:00Z'}), f'{advisories} must not mask failures or override the CI clock'),
(lambda w: w['jobs'][advisories].update({'continue-on-error': 'true'}), f'{advisories} cannot convert a validation failure into success'),
)):
changed = copy.deepcopy(workflow)
mutate(changed)
self.assertIn(message, self.check(changed), case)
def test_security_input_gate_lane_gates_every_event_and_validates_contract(self):
job = gate.SECURITY_INPUT_JOB
self.assertIn(job, gate.ALWAYS_JOBS)
for event, mode in (('pull_request', 'docs'), ('pull_request', 'e2e'), ('pull_request', 'full'),
('push', 'full'), ('push', 'proven'), ('merge_group', 'full'),
('schedule', 'full'), ('workflow_dispatch', 'full')):
plan = self.plan(event, mode)
self.assertEqual(plan['jobs'][job], 'success', (event, mode))
self.assertEqual(gate.verify_results(self.needs(plan), event, plan['ref']), [])
for bad in ('failure', 'cancelled', 'skipped', None):
needs = self.needs(plan)
needs[job]['result'] = bad
errors = gate.verify_results(needs, event, plan['ref'])
self.assertTrue(any(error.startswith(f'{job}: expected success') for error in errors), (event, mode, bad, errors))
workflow = self.workflow()
self.assertEqual(self.check(workflow), [])
for case, (mutate, message) in enumerate((
(lambda w: w['jobs']['required-checks']['needs'].remove(job), 'required-checks must directly depend on every verification job exactly once'),
(lambda w: w['jobs'][job].update({'name': 'Dynamic ${{ github.ref }}'}), f"{job} must keep stable display name 'Security Input Gate'"),
(lambda w: w['jobs'][job].update({'uses': './.github/workflows/other.yml'}), f'{job} must call reusable workflow {gate.SECURITY_INPUT_WORKFLOW}'),
(lambda w: w['jobs'][job].update({'needs': []}), f'{job} must depend on classify-changes for ci_mode'),
(lambda w: w['jobs'][job]['with'].pop('base_sha'), f'{job} missing required with inputs: base_sha'),
(lambda w: w['jobs'][job]['with'].update({'shell_cmd': 'id'}), f'{job} has unexpected with inputs: shell_cmd'),
(lambda w: w['jobs'][job]['with'].update({'mode': 'nightly'}), f'{job} must invoke fuzz.yml in smoke mode'),
(lambda w: w['jobs'][job].update({'continue-on-error': 'true'}), f'{job} cannot convert a validation failure into success'),
)):
changed = copy.deepcopy(workflow)
mutate(changed)
self.assertIn(message, self.check(changed), case)
def test_pull_request_cannot_use_a_changed_scope_selector_to_skip_checks(self):
root = Path(gate.__file__).resolve().parent.parent
workflow = gate.workflow_document((root / '.github/workflows/fuzz.yml').read_text())
step = next(step for step in workflow['jobs']['select-targets']['steps'] if step.get('id') == 'select')
with tempfile.TemporaryDirectory() as directory:
repo = Repository(Path(directory))
selector = 'scripts/fuzz/select_targets.py'
for name in (selector, 'fuzz/Cargo.toml'):
repo.write(name, (root / name).read_text())
base = repo.commit()
repo.write('README.md', 'docs only')
benign_head = repo.commit()
environment = dict(os.environ, CALLER_EVENT='pull_request', CALLER_MODE='smoke', CALLER_TARGETS='auto',
CALLER_BUDGET='60', CALLER_BASE_SHA=base, CALLER_CI_MODE='full',
GITHUB_OUTPUT=str(repo.root / 'outputs'))
def select(head):
subprocess.run(['bash', '-eo', 'pipefail', '-c', step['run']], cwd=repo.root, capture_output=True,
env=dict(environment, CALLER_HEAD_SHA=head), check=True)
return json.loads((repo.root / 'artifacts/security-input-gate/selection-manifest.json').read_text())
self.assertFalse(select(benign_head)['applicable'])
repo.write(selector, 'raise RuntimeError("candidate policy executed")')
selection = select(repo.commit())
self.assertTrue(selection['applicable'])
self.assertTrue(selection['run_mutants'])
self.assertEqual(selection['reason'], 'unverified_scope_policy')
manifest = tomllib.loads((root / 'fuzz/Cargo.toml').read_text())
self.assertEqual(selection['targets'], sorted(item['name'] for item in manifest['bin']))
def test_security_input_jobs_use_the_callers_event(self):
root = Path(gate.__file__).resolve().parent.parent
caller = gate.workflow_document((root / '.github/workflows/ci.yml').read_text())
workflow = gate.workflow_document((root / '.github/workflows/fuzz.yml').read_text())
jobs = workflow['jobs']
caller_job = caller['jobs'][gate.SECURITY_INPUT_JOB]
self.assertNotEqual(caller['concurrency']['group'], workflow['concurrency']['group'])
for scope, access in jobs['alert-on-failure']['permissions'].items():
self.assertEqual(access, 'read')
self.assertEqual(caller_job['permissions'][scope], access)
for event, mode, profile, expected in (
('pull_request', 'smoke', '', (True, False, True)),
('merge_group', 'smoke', '', (True, False, True)),
('push', 'smoke', '', (True, False, True)),
('schedule', 'smoke', '', (True, False, True)),
('workflow_dispatch', 'smoke', '', (True, False, True)),
('schedule', '', '', (False, True, False)),
('workflow_dispatch', '', 'both', (True, True, False)),
('workflow_dispatch', '', 'nightly', (False, True, False)),
('workflow_dispatch', '', 'smoke', (True, False, False)),
):
context = {'github.repository': 'rustfs/rustfs', 'github.event_name': event, 'inputs.mode': mode,
'github.event.inputs.profile': profile, 'needs.select-targets.outputs.applicable': 'true',
'needs.select-targets.outputs.has_targets': 'true'}
with self.subTest(event=event, mode=mode, profile=profile):
actual = tuple(gate.condition(jobs[job]['if'], context)
for job in ('pr-fuzz-smoke', 'nightly-fuzz-corpus', 'security-input-gate-verdict'))
self.assertEqual(actual, expected)
def test_semantic_yaml_equivalence_and_wiring_boundaries(self):
workflow = self.workflow()
self.assertEqual(self.check(workflow), [])
workflow['jobs']['required-checks']['if'] = "${{ (github.event.action != 'closed' || github.event_name != 'pull_request') && always() }}"
workflow['jobs']['required-checks']['needs'].reverse()
for job in ('workspace-tests', 'core-contract', 'e2e-tests', 's3-implemented-tests', 's3-lifecycle-behavior-tests'):
del workflow['jobs'][job]['if']
workflow['jobs'][job]['needs'] = ['workspace-lint-and-build' if job == 'workspace-tests' else 'build-rustfs-debug-binary']
self.assertEqual(self.check(workflow), [])
for mutate in (
lambda w: w['jobs']['required-checks']['needs'].pop(),
lambda w: w['jobs']['required-checks'].update({'if': 'success()'}),
lambda w: w['jobs']['required-checks'].update({'if': "'always()' == 'always()'"}),
lambda w: w['jobs']['required-checks']['steps'][0].update({'run': 'python3 scripts/ci_gate.py verify || true'}),
lambda w: w['jobs']['typos'].update({'continue-on-error': 'true'}),
lambda w: w['jobs'][gate.LINT_JOB]['steps'][0].update({'if': 'false'}),
lambda w: w['jobs']['test-and-lint-protocols']['strategy']['matrix']['features'].pop(),
lambda w: w['jobs'].update({'unaccounted': {'name': 'New'}}),
lambda w: w['on']['pull_request'].update({'paths': ['README.md']}),
lambda w: w['jobs']['core-contract'].update({'if': 'false'}),
):
changed = copy.deepcopy(workflow)
mutate(changed)
self.assertTrue(self.check(changed))
with self.assertRaises(ValueError):
gate.workflow_document('jobs: { test: {}, test: {} }')
if __name__ == '__main__':
unittest.main()