Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/part.yml
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ jobs:
queue-timeout-minutes: ${{ fromJSON(inputs.part).queue }}
results: ${{ fromJSON(inputs.part).results }}
target: ${{ fromJSON(inputs.part).target }}
cores: ${{ fromJSON(inputs.part).cores }}
# the part step fails on red and on a failed upload: upload once more (the same file)
# where its own upload did not succeed; a red part's is done (issue #242)
- id: again
Expand Down Expand Up @@ -260,6 +261,7 @@ jobs:
queue-timeout-minutes: ${{ fromJSON(inputs.part).queue }}
results: ${{ fromJSON(inputs.part).results }}
target: ${{ fromJSON(env.RETRY).target }}
cores: ${{ fromJSON(inputs.part).cores }}
resume: ${{ fromJSON(env.RETRY).resume }}
attempt-of: ${{ fromJSON(env.RETRY).attempt_of }}
# as the first attempt's: once more only where the part action's own upload did not succeed
Expand Down
5 changes: 5 additions & 0 deletions actions/part/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ inputs:
command:
description: run with bash -c in the job's checkout, inside the project's env
required: true
cores:
description: optional logical CPU count within a fixed slot on a dynamic CPU runner
default: ''
workers:
description: optional CI_WORKERS override, bounded by the slot and its actual CPU affinity
default: ''
Expand Down Expand Up @@ -100,6 +103,7 @@ runs:
env:
IN_PROJECT: ${{ inputs.project }}
IN_ID: ${{ inputs.id }}
IN_CORES: ${{ inputs.cores }}
IN_WORKERS: ${{ inputs.workers }}
IN_COMMAND: ${{ inputs.command }}
IN_TIMEOUT: ${{ inputs.timeout-minutes }}
Expand All @@ -117,6 +121,7 @@ runs:
run: >-
set --;
if [ -n "$IN_WORKERS" ]; then set -- --workers "$IN_WORKERS"; fi;
if [ -n "$IN_CORES" ]; then set -- "$@" --cores "$IN_CORES"; fi;
exec "$GITHUB_ACTION_PATH/../lib/ci-run.sh" part --project "$IN_PROJECT" --id "$IN_ID" --command "$IN_COMMAND"
--timeout-minutes "$IN_TIMEOUT" --gpus "$IN_GPUS" --gpu-mem-mib "$IN_GPU_MEM" --memory "$IN_MEMORY"
--queue-timeout-minutes "$IN_QUEUE" --results "$IN_RESULTS"
Expand Down
4 changes: 4 additions & 0 deletions ci_runners/flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -665,6 +665,8 @@ def entry(p: Mapping, files: bool = False) -> dict:
if 'workers' in p:
# Actions converts JSON numbers through double precision. Keep the exact decimal text.
out['workers'] = str(p['workers'])
if 'cores' in p:
out['cores'] = str(p['cores'])
out['gpus'] = GPUS.get(p['needs'], 0)
out['memory'] = f'{math.ceil(p["memory_gib"] * 1024)}M' if p.get('memory_gib') is not None else ''
out['results'] = p.get('results', '')
Expand Down Expand Up @@ -828,6 +830,8 @@ def decide(part: Mapping, doc: Mapping | None, role: str, rows: Sequence | None,
if isinstance(bare.get('workers'), str):
# A private fallback routes the part again through the schema's integer validation.
bare['workers'] = int(bare['workers'])
if isinstance(bare.get('cores'), str):
bare['cores'] = int(bare['cores'])
r = retry_public(bare, first) if is_public(env) else rt.retry(bare, first, rows, unread)
if not r['retry']:
return None
Expand Down
10 changes: 8 additions & 2 deletions ci_runners/inventory.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,8 @@ def _num(v: object) -> bool:
#: the classes whose runners take one host CI slot (design §4.3, §7)
CI_SLOT_CLASSES = ('part', 'compile')

DYNAMIC_CPU = "ci-cpu-dynamic"
CORE_REFUSAL = "cores: "
_CPU_WIDTH_CANDIDATE = re.compile(r'ci-cpu-[0-9]+\Z')
CPU_WIDTH_LABEL = re.compile(r'ci-cpu-[1-9][0-9]*\Z')

Expand Down Expand Up @@ -335,6 +337,10 @@ def load(text: str) -> Inventory:
if not pub and cls in CI_SLOT_CLASSES:
slot_pools.append(pool)
sized = [label for label in labels if _CPU_WIDTH_CANDIDATE.fullmatch(label)]
dynamic = DYNAMIC_CPU in labels
if dynamic and (cls != 'part' or pub or 'ci-cpu' not in labels or sized or not v.get('slot')
or len(pools_of(h, 'part')) != 1):
raise InventoryError(f'{where}: ci-cpu-dynamic requires one private slotted ci-cpu pool')
if sized:
cap = sized[0]
if len(sized) != 1 or not CPU_WIDTH_LABEL.fullmatch(cap) or cls != 'part' or pub:
Expand All @@ -356,11 +362,11 @@ def load(text: str) -> Inventory:
if len(v['slot']['cpus']) != n:
raise InventoryError(f'hosts.{role}.pools.{pool}: slot.cpus has {len(v["slot"]["cpus"])} '
f'cpusets for {n} runners')
slot_ranges.extend((lo, hi, pool, bool(sized))
slot_ranges.extend((lo, hi, pool, bool(sized) or dynamic)
for c in v['slot']['cpus'] for lo, hi in cpu_ranges(c))
if not sized:
seen[cls, pub] = pool
if widths:
if widths or any(flag for _, _, _, flag in slot_ranges):
if h['slots'] < len(slot_pools):
raise InventoryError(f'hosts.{role}.slots: {h["slots"]} shared CI slots for {len(slot_pools)} pools '
f'({", ".join(slot_pools)}); sized CPU pools need at least one slot per pool')
Expand Down
64 changes: 54 additions & 10 deletions ci_runners/part.py
Original file line number Diff line number Diff line change
Expand Up @@ -481,8 +481,17 @@ def worker_exit(record: str, requested: int, why: str, *, final: bool = False) -
return ex


def core_exit(record: str, requested: int, why: str, *, final: bool = False) -> dict:
ex = {'unavailable': inventory.CORE_REFUSAL + why,
'cores': {'requested': requested, 'command_started': False},
'workers_final': final, 'end_epoch': time.time(), 'boot_end': boot_id()}
_write_json(os.path.join(record, 'exit.json'), ex)
return ex


def supervise(record: str, timeout: float, argv: Sequence[str], cap: int = 0, p2p: Sequence[str] = (),
worker_spec: tuple[int, int, Sequence[int]] | None = None) -> int:
worker_spec: tuple[int, int, Sequence[int]] | None = None,
core_spec: tuple[int, int, Sequence[int], int | None] | None = None) -> int:
"""Run ``argv`` in its own session with OOM score +500, end it at ``timeout``, and
write ``exit.json``. Runs inside the part's scope, in a session of its own, so the
job's signals (a cancel, a stopped runner) do not reach it: only a stop of the scope
Expand Down Expand Up @@ -522,6 +531,31 @@ def adj():
timed_out = False
worker_info = {}
child_env = None
if core_spec is not None:
width, maximum, pin, requested = core_spec
try:
chosen = set(sorted(set(pin) & os.sched_getaffinity(0))[:width])
if len(chosen) != width:
core_exit(record, width, f'requested {width}; only {len(chosen)} slot CPUs available in the part scope')
return 0
os.sched_setaffinity(0, chosen)
actual = os.sched_getaffinity(0)
except OSError:
core_exit(record, width, 'could not pin CPUs or read affinity inside the part scope')
return 0
if actual != chosen:
core_exit(record, width, 'measured affinity does not match the selected CPUs')
return 0
if requested is not None and requested > min(maximum, len(actual)):
worker_exit(record, requested, f'requested {requested}; limit is {min(maximum, len(actual))} '
f'(slot worker limit {maximum}, allocated CPUs {len(actual)})')
return 0
effective = min(maximum, len(actual)) if requested is None else requested
cpus = cpu_list(actual)
child_env = {**os.environ, 'CI_CPUS': cpus, 'CI_WORKERS': str(effective)}
worker_info = {'cores': {'requested': width, 'effective': len(actual), 'command_started': True, 'cpus': cpus}}
if requested is not None:
worker_info['workers'] = {'requested': requested, 'effective': effective, 'command_started': True, 'cpus': cpus}
if worker_spec is not None:
requested, maximum, pin = worker_spec
if requested > maximum:
Expand Down Expand Up @@ -949,7 +983,7 @@ def finish(record: str, rec: Mapping[str, object], ex: Mapping[str, object] | No
retry_on = []
peak = rec.get('peak_c') or {}
run_seconds = int(max(0.0, end - float(rec['run_epoch']))) if rec.get('run_epoch') else 0
worker_info = {'workers': ex['workers']} if ex and 'workers' in ex else {}
worker_info = {k: ex[k] for k in ('cores', 'workers') if ex and k in ex}
return {**worker_info, 'outcome': o.kind, 'reason': o.reason, 'next': h.next, 'retry-on': retry_on, 'host': role,
'gpus': ','.join(str(c) for c in rec.get('cards', [])), 'queue-seconds': int(rec.get('queue_seconds', 0)),
'run-seconds': run_seconds,
Expand Down Expand Up @@ -994,6 +1028,7 @@ class Inputs:
lock: str = '' # empty: the class's default, ``x`` on ``compile``, else ``none`` (design §4.3)
target: str = '' # a slurm part's targets, in the order to try (decision 14.2)
workers: int | None = None
cores: int | None = None


def parse_args(argv: Sequence[str]) -> Inputs:
Expand All @@ -1012,9 +1047,10 @@ def parse_args(argv: Sequence[str]) -> Inputs:
p.add_argument('--lock', choices=('', *LOCKS), default='')
p.add_argument('--target', default='')
p.add_argument('--workers', type=workers.cli_count)
p.add_argument('--cores', type=lambda value: workers.cli_count(value, 'cores'))
a = p.parse_args(list(argv))
return Inputs(a.project, a.command, a.id, a.timeout_minutes, a.gpus, a.gpu_mem_mib, a.memory,
a.queue_timeout_minutes, a.results, a.resume == 'true', a.attempt_of, a.lock, a.target, a.workers)
a.queue_timeout_minutes, a.results, a.resume == 'true', a.attempt_of, a.lock, a.target, a.workers, a.cores)


def queue_capped(inv: inventory.Inventory, runner: str) -> bool:
Expand Down Expand Up @@ -1145,7 +1181,7 @@ def gate(self, a: Inputs, cls: str, lock: str) -> str:
self.slot, why = runner_slot(h, cls, self.env)
if why:
return f'slot: {why}'
if a.workers is None and self.slot is not None and not slot_cpus(self.slot) <= os.sched_getaffinity(0):
if a.cores is None and a.workers is None and self.slot is not None and not slot_cpus(self.slot) <= os.sched_getaffinity(0):
return f'slot: slot {self.slot.index}\'s cpus {self.slot.cpus} are not all CPUs this runner may use'
return ''

Expand Down Expand Up @@ -1322,6 +1358,9 @@ def execute(self, a: Inputs) -> tuple[int, dict[str, object]]:
hold: locks.HostLock | None = None # the host lock, held for the whole command (design §5.5 item 3)
rec['lock'] = lock
try:
if a.cores is not None and cls != 'part':
ex = core_exit(record, a.cores, 'dynamic cores require a private CPU runner', final=True)
return self._end(record, rec, a, ex=ex)
if a.workers is not None:
public_gpu = cls == 'gpu' and self.env.get('RUNNER_NAME', '').startswith(
f'{self.inv.this}{inventory.PUBLIC_HOST_SUFFIX}')
Expand All @@ -1335,10 +1374,15 @@ def execute(self, a: Inputs) -> tuple[int, dict[str, object]]:
if cls == slurmpart.CLASS: # one batch job on a Slurm cluster (decision 14.3)
return self._slurm(a, proj, memory, record, rec, work, lock)
why = self.gate(a, cls, lock)
if why and not (a.workers is not None and why.startswith('slot: ')):
if why and not ((a.workers is not None or a.cores is not None) and why.startswith('slot: ')):
return self._end(record, rec, a, unavailable=why)
worker_spec = None
if a.workers is not None:
worker_spec = core_spec = None
if a.cores is not None:
if self.slot is None or inventory.DYNAMIC_CPU not in (labels or ()):
ex = core_exit(record, a.cores, 'no verifiable slot on a dynamic CPU pool')
return self._end(record, rec, a, ex=ex)
core_spec = (a.cores, self.slot.workers, sorted(slot_cpus(self.slot)), a.workers)
elif a.workers is not None:
if self.slot is None:
detail = f' ({why})' if why else ''
ex = worker_exit(record, a.workers, f'this runner has no verifiable slot worker limit{detail}')
Expand Down Expand Up @@ -1480,15 +1524,15 @@ def execute(self, a: Inputs) -> tuple[int, dict[str, object]]:
cpus=cpus, files=h['files'], slot=slot_path, resume=a.resume,
held=hold.mode if hold else '', runner=self.slot)
# With an override, the in-scope supervisor pins itself and the command inherits its mask.
inner = command_argv(a.command, cpus=pin if worker_spec is None else '', nice=0 if cls == 'compile' else 10)
inner = command_argv(a.command, cpus=pin if worker_spec is None and core_spec is None else '', nice=0 if cls == 'compile' else 10)
cap = registry.memory_bytes(memory) if self.caps_memory() else 0
p2p = self.p2p if cls in P2P_CLASSES else []
# the inner timeout: the plan's minutes, times the slot's speed on a runner with one (16.2)
timeout = a.timeout_minutes * 60 if self.slot is None else a.timeout_minutes * 60 * self.slot.speed
supervisor_args = json.dumps(p2p)
supervisor_call = 'json.loads(sys.argv[4])))'
if worker_spec is not None:
supervisor_args = json.dumps([p2p, worker_spec])
if worker_spec is not None or core_spec is not None:
supervisor_args = json.dumps([p2p, worker_spec, core_spec])
supervisor_call = '*json.loads(sys.argv[4])))'
sup = [sys.executable, '-I', '-c', 'import json, sys; sys.path.insert(0, sys.argv.pop(1)); '
'from ci_runners.part import supervise; '
Expand Down
5 changes: 5 additions & 0 deletions ci_runners/pool.py
Original file line number Diff line number Diff line change
Expand Up @@ -1010,6 +1010,9 @@ def pool_table(inv, p: Mapping, yielded: set[str] | None = None) -> list[dict]:
if isinstance(slot, dict):
e.update(memory_gib=round(registry.memory_bytes(slot['memory']) / (1 << 30), 3), speed=float(slot['speed']),
workers=int(slot['workers']))
if inventory.DYNAMIC_CPU in common:
e['max_cores'] = min(sum(hi - lo + 1 for lo, hi in inventory.cpu_ranges(c))
for c in slot['cpus'])
out.append(e)
return out

Expand Down Expand Up @@ -1251,6 +1254,8 @@ def _pool_entry(v: object) -> bool:
return False
if not all(type(v[k]) is int and v[k] >= 0 for k in ('listening', 'yielded') if k in v):
return False
if 'max_cores' in v and (type(v['max_cores']) is not int or v['max_cores'] <= 0):
return False
return all(type(v[k]) in (int, float) and math.isfinite(v[k]) and v[k] > 0
for k in ('memory_gib', 'speed', 'workers') if k in v)

Expand Down
2 changes: 1 addition & 1 deletion ci_runners/presence.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@
#: also a wait that ran out (the host was busy: no slot, no card, no host lock) and a request
#: the class's row refuses (the caller's ``gpus``, ``lock`` or class, not the host)
NOT_INFRA = ('busy', 'drained', 'project queue full', drain_mod.UNREADABLE, 'queue timeout', 'gpus ', 'lock ',
'this host has no compile_cpus', workers.REASON)
'this host has no compile_cpus', workers.REASON, inventory.CORE_REFUSAL)
HOOK_INFRA = ('stale', 'runner', 'policy', 'inventory', 'timeout', 'error') # the hook's refusals that are infrastructure ends
CLUSTER = 'slurm' # a cluster part's unavailable is the cluster's, not the host's
YIELD_CLASSES = ('part', 'gpu', 'multi') # the classes whose runners yield to an earlier tier (19.2)
Expand Down
Loading
Loading