#!/usr/bin/env python3 """Partition integration compilation as well as Nextest execution.""" import json from pathlib import Path import re import subprocess import sys def plan(metadata, package, number, total): if total < 4 or total % 2: return None package = next(p for p in metadata['packages'] if p['name'] == package) features = package['features'] enabled, pending = set(), ['default'] while pending: feature = pending.pop() if feature in enabled: continue enabled.add(feature) pending.extend(f for f in features.get(feature, []) if f in features) units, integrations = [], [] eligible = False integration_index = 0 library = {'lib', 'rlib', 'staticlib', 'cdylib', 'dylib', 'proc-macro'} for target in sorted(package['targets'], key=lambda t: t['name']): kinds = set(target['kind']) if not kinds <= library and kinds not in [ {'bin'}, {'test'}, {'example'}, {'custom-build'}]: return None if not target['test']: continue if not set(target.get('required-features', [])) <= enabled: # Dev-dependency feature unification can enable more than the # default closure. Keep Cargo's original selection consistently # across the whole matrix rather than guessing which are active. return None eligible = True if kinds <= library: units.append('--lib') elif kinds == {'bin'}: units.extend(['--bin', target['name']]) elif kinds == {'test'}: # Each sorted target belongs to a pair of jobs, which split its # cases. This bounds compilation while keeping a large integration # binary from loading one job with all of its cases. owner = integration_index % (total // 2) integration_index += 1 if owner == (number - 1) // 2: integrations.extend(['--test', target['name']]) else: # A new Cargo target kind must retain the original selection. return None if integration_index < total // 2: return None phases = [] if integrations: phases.append(integrations + ['--partition', f'hash:{(number - 1) % 2 + 1}/2']) # Cargo builds the real package executables for integration tests. Keep # that ahead of unit execution: a unit may launch a real binary too, and # must never consume the previous checkout's executable from a warm target. if units: phases.append(units + ['--partition', f'hash:{number}/{total}']) return phases if eligible else None def main(arguments): wrapper = Path(__file__).with_name('cargo-test-with-one-retry.sh') def original(): return subprocess.run(['bash', str(wrapper), *arguments]).returncode # Feature suites and arbitrary caller filters keep their original Cargo # semantics. Only the package-only fast matrix opts into target selection. if (len(arguments) != 9 or arguments[:6] != [ 'nextest', 'run', '--profile', 'fast', '--no-fail-fast', '--partition'] or arguments[7] != '-p'): return original() partition = re.fullmatch(r'hash:([1-9][0-9]*)/([1-9][0-9]*)', arguments[6]) if not partition: return original() number, total = map(int, partition.groups()) if number > total: return original() try: metadata = json.loads(subprocess.check_output( ['cargo', 'metadata', '--no-deps', '--format-version', '1'])) phases = plan(metadata, arguments[8], number, total) except (OSError, ValueError, KeyError, StopIteration, subprocess.CalledProcessError): # One shard falling back after a transient metadata error would mix # case and binary partition schemes and could omit integration cases. print('[cargo-target-shard] cannot establish complete target coverage', file=sys.stderr) return 1 if phases is None: print('[cargo-target-shard] retaining the original Cargo target selection', flush=True) return original() if not phases: print('[cargo-target-shard] no integration target is assigned to this partition', flush=True) package = next(p for p in metadata['packages'] if p['name'] == arguments[8]) if any('example' in target['kind'] for target in package['targets']): # Default Cargo test selection compiles non-test examples too. Explicit # --test/--lib selections omit them, so retain their normal compilation # and linking without turning their #[test] functions into new cases. command = ['build', '--profile', 'test', '--examples', '-p', arguments[8]] print('[cargo-target-shard] ' + ' '.join(command), flush=True) result = subprocess.run(['bash', str(wrapper), *command]).returncode if result: return result status = 0 passed_phase = False empty_phase = False for targets in phases: command = ['nextest', 'run', '--profile', 'fast', '--no-fail-fast', '-p', arguments[8], *targets] print('[cargo-target-shard] ' + ' '.join(command), flush=True) result = subprocess.run(['bash', str(wrapper), *command]).returncode # Finish the other assigned phase after a test failure, just as the # original --no-fail-fast suite did. Never retry a failed test. if result == 4: # Nextest's documented no-tests result: one assigned phase may # consist entirely of nightly cases. Preserve the original # empty-suite failure if neither phase has fast cases. empty_phase = True elif result and not status: status = result elif result == 0: passed_phase = True return status or (4 if empty_phase and not passed_phase else 0) if __name__ == '__main__': sys.exit(main(sys.argv[1:]))