Skip to content

Centralize scheduler option handling #3762

Backlog
Backlog

Description

@pranav-sivaraman

Problem

Every scheduler backend turns the job attributes and the user's options (partition access, job.options, -J) into a preamble or submit command on its own. The rules are repeated across backends, and the Slurm backend re-parses the same strings in several places with different parsers. This makes the behaviour inconsistent and easy to get wrong in a new backend. I realized this when doing a review of #3760.

Evidence

Links are pinned to the current develop commit.

Slurm parses the options three different ways. Job arrays:

# Determine if job refers to a Slurm job array, by looking into the
# job.options and job.cli_options
jobarr_parser = ArgumentParser()
jobarr_parser.add_argument('-a', '--array')
parsed_args, _ = jobarr_parser.parse_known_args(
job.options + job.cli_options
)
if parsed_args.array:
job._is_array = True

Constraint merging (argparse to merge, startswith to skip):

c_parser = ArgumentParser()
c_parser.add_argument('-C', '--constraint')
access, access_other = c_parser.parse_known_args(job.sched_access)
job_opts, other_job_opts = c_parser.parse_known_args(job.options)
cli_opts, other_cli_opts = c_parser.parse_known_args(job.cli_options)
if access.constraint and (job_opts.constraint or cli_opts.constraint):
constraints = [access.constraint]
if job_opts.constraint:
constraints.append(job_opts.constraint)
job.options = other_job_opts
else:
constraints.append(cli_opts.constraint)
job._cli_options = other_cli_opts
arg = '&'.join(f'({c.strip()})' for c in constraints)
job._sched_access = [f'--constraint={arg}'] + access_other
if not self._sched_access_in_submit:
for opt in job.sched_access:
preamble.append(f'{self._prefix} {opt}')
preamble.append(self._format_option(hint, '--hint={0}'))
prefix_patt = re.compile(r'(#\w+)')
for opt in job.options + job.cli_options:
if opt.strip().startswith(('-C', '--constraint')):
if access.constraint:
# Constraints are already combined with the `sched_access`
# and processed
continue

Node filtering (shlex + another argparse):

def filternodes(self, job, nodes):
# Collect options that restrict node selection, but we need to first
# create a mutable list out of the immutable SequenceView that
# sched_access is
options = job.sched_access + job.options + job.cli_options
# Properly split lexically all the arguments in the options list so as
# to treat correctly entries such as '--option foo'.
options = list(itertools.chain.from_iterable(shlex.split(opt)
for opt in options))
option_parser = ArgumentParser()
option_parser.add_argument('--reservation')
option_parser.add_argument('-p', '--partition')
option_parser.add_argument('-w', '--nodelist')
option_parser.add_argument('-C', '--constraint')
option_parser.add_argument('-x', '--exclude')
self.log(f'Filtering by Slurm options: {" ".join(options)}')
parsed_args, _ = option_parser.parse_known_args(options)

The srunalloc launcher re-implements the job attribute → option mapping:

class SrunAllocationLauncher(JobLauncher):
def command(self, job):
ret = ['srun']
if job.name:
ret += ['--job-name=%s' % job.name]
if job.time_limit:
h, m, s = seconds_to_hms(job.time_limit)
ret += ['--time=%d:%d:%d' % (h, m, s)]
if job.num_tasks:
ret += ['--ntasks=%s' % str(job.num_tasks)]
if job.num_tasks_per_node:
ret += ['--ntasks-per-node=%s' % str(job.num_tasks_per_node)]
if job.num_tasks_per_core:
ret += ['--ntasks-per-core=%s' % str(job.num_tasks_per_core)]
if job.num_tasks_per_socket:
ret += ['--ntasks-per-socket=%s' % str(job.num_tasks_per_socket)]
if job.num_cpus_per_task:
ret += ['--cpus-per-task=%s' % str(job.num_cpus_per_task)]
if job.exclusive_access:
ret += ['--exclusive']
if job.use_smt is not None:
hint = 'multithread' if job.use_smt else 'nomultithread'
ret += ['--hint=%s' % hint]
for opt in job.options + job.cli_options:
if opt.startswith('#'):
continue
ret.append(opt)
return ret

LSF, OAR, PBS and SGE repeat the same "append access + options + -J, pass #… lines through" loop, with small differences (SGE never reads access):

if not self._sched_access_in_submit:
for opt in job.sched_access:
preamble.append(f'{self._prefix} {opt}')
# emit the rest of the options
options = job.options + job.cli_options
for opt in options:
if opt.startswith('#'):
preamble.append(opt)
else:
preamble.append(self._prefix + ' ' + opt)

A resulting bug: with access=['-C gpu'], a test constraint written as one string, '--constraint mc', is silently dropped, because the merge and the skip disagree. '--constraint=mc' and '-C mc' work. Reproducer, no Slurm needed:

# config.py: one Slurm partition with access=['-C gpu']
site_configuration = {
    'systems': [{
        'name': 'testsys', 'hostnames': ['.*'],
        'partitions': [{'name': 'gpu', 'scheduler': 'slurm', 'launcher': 'srun',
                        'access': ['-C gpu'], 'environs': ['builtin']}],
    }],
    'environments': [{'name': 'builtin'}],
}
# constraint_bug.py
import os

import reframe as rfm
import reframe.utility.sanity as sn
from reframe.core.builtins import parameter, run_after, run_before, sanity_function
from reframe.core.exceptions import SanityError


@rfm.simple_test
class ConstraintMergeBug(rfm.RunOnlyRegressionTest):
    valid_systems = ['*']
    valid_prog_environs = ['*']
    executable = 'true'
    opt = parameter(['--constraint mc', '--constraint=mc', '-C mc'])

    @run_before('run')
    def set_constraint(self):
        self.job.options = [self.opt]

    @run_after('run')
    def check_preamble(self):
        with open(os.path.join(self.stagedir, self.job.script_filename)) as fp:
            if '#SBATCH --constraint=(gpu)&(mc)' not in fp.read():
                raise SanityError(f'{self.opt!r} was not merged with access')

    @sanity_function
    def validate(self):
        return sn.assert_true(True)
$ reframe -C config.py -c constraint_bug.py --dry-run
[     FAIL ] (1/3) ConstraintMergeBug %opt=--constraint mc /92cb1ea1 @testsys:gpu+builtin
[       OK ] (2/3) ConstraintMergeBug %opt=--constraint=mc /c84de3fc @testsys:gpu+builtin
[       OK ] (3/3) ConstraintMergeBug %opt=-C mc /4420f0d9 @testsys:gpu+builtin

The failing case's script has only #SBATCH -C gpu; the other two have #SBATCH --constraint=(gpu)&(mc).

Proposal

Move the rules into a request object built from the job, with one base class for the shared steps and a subclass per scheduler:

class JobRequest:
    prefix = None
    def generated(self): ...      # job attributes → options (per scheduler)
    def user(self): ...           # access + options + -J, in order
    def directives(self): ...     # preamble lines
    def submit_args(self): ...    # sched_access_in_submit

class SlurmRequest(JobRequest):
    prefix = '#SBATCH'
    # constraint merging, job array detection, node filter options

class Job:
    request_cls = JobRequest

    @property
    def request(self):            # computed on access: tests set attributes after creation
        return self.request_cls(self)
  • Each backend's emit_preamble becomes job.request.directives(); filternodes and srunalloc read from the same SlurmRequest.
  • The request classes are pure (no I/O), so the rules can be tested once, without a scheduler, e.g. "the access constraint is always kept", "each generated option appears once", "equivalent spellings give the same result".
  • New backends pick or subclass a request class instead of re-implementing option handling.

Plan: add JobRequest + SlurmRequest with tests pinning the current behaviour, switch the Slurm backend and srunalloc (fixing the bug above), then port the other backends one at a time.

Open question: srunalloc puts job.options and -J on the srun line but not access. Is that intentional?

I'd like to take this on, if the approach sounds reasonable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions