Skip to content

Add API-based cloud batch scheduler support (BaseAPISchedulerIO, QCloudResources, AWSBatchIO) - #84

Open
hrushikesh-s wants to merge 9 commits into
Matgenix:developfrom
hrushikesh-s:aws-batch-api
Open

hrushikesh-s wants to merge 9 commits into
Matgenix:developfrom
hrushikesh-s:aws-batch-api

Conversation

@hrushikesh-s

@hrushikesh-s hrushikesh-s commented Nov 25, 2026 •

Copy link
Copy Markdown

Stage 1 of the cloud compute plan in Matgenix/jobflow-remote#533.

  • QCloudResources (qtoolkit.core.data_objects): resources for cloud jobs (queue_name, job_name, vcpus, memory, gpus, time_limit, max_retries, environment, and scheduler_kwargs). HPC-only fields stay out of cloud submissions. QResources and QCloudResources share queue_name and job_name through BaseQResources.
  • BaseAPISchedulerIO (qtoolkit.api.base): base class for schedulers controlled through an API (submit, cancel, get_job, get_jobs_list). It returns the usual QJob, QState, SubmissionResult, and CancelResult objects. It shares the job ID and resource helpers with BaseSchedulerIO through BaseScheduler in qtoolkit.core.base.
  • AWSBatchIO (qtoolkit.api.aws_batch): first backend, with boto3 in the optional aws extra. It makes job names valid for AWS Batch and runs commands with /bin/bash -c by default (shell_cmd). It submits single-container jobs only, and rejects the options for array, multi-node, EKS, and ECS task jobs.
  • Offline unit tests with moto. CI installs the aws extra.

Tested live on AWS Batch, first on Fargate (see the comment below) and then on an EC2 Spot CPU queue with two atomate2 phonon flows through jobflow-remote.

@hrushikesh-s

hrushikesh-s commented Nov 25, 2026 •

Copy link
Copy Markdown
Author

Tested AWSBatchIO live on AWS Batch (Fargate, us-east-2), then deleted all temporary resources:

  • Normal job (1 vCPU, 2048 MiB, env vars): QUEUED -> RUNNING -> DONE, exit_status=0, runtime 29 s, expected output in CloudWatch Logs.
  • Failing job (exit 42, 0.25 vCPU, 512 MiB): QUEUED -> RUNNING -> FAILED, exit_status=42.
  • Running job (sleep 180): showed up in get_jobs_list(), reported live runtime (6 s), and cancel() stopped it cleanly (FAILED).
  • Direct command without shell (shell_cmd=None, /bin/echo argv-ok): DONE, exit_status=0.
  • Invalid inputs: unknown job ID returned None, and an invalid Fargate CPU/memory pair returned SubmissionStatus.FAILED.

Two notes for Matgenix/jobflow-remote#533: ListJobs can lag slightly behind DescribeJobs (so _get_jobs_list now filters DescribeJobs results to active states when states=None), and container stdout/stderr lives in CloudWatch Logs.

@hrushikesh-s
hrushikesh-s marked this pull request as ready for review November 25, 2026 06:49
@hrushikesh-s hrushikesh-s changed the title [WIP] Add API scheduler base class and AWS Batch backend Add API-based cloud batch scheduler support (BaseAPISchedulerIO, QCloudResources, AWSBatchIO) Nov 25, 2026
@hrushikesh-s

Copy link
Copy Markdown
Author

@gpetretto This is ready for review (Stage 1 for Matgenix/jobflow-remote#533, paired with draft PR Matgenix/jobflow-remote#553). Could you please approve the CI workflow run and let me know if the BaseAPISchedulerIO, QCloudResources, and AWSBatchIO design looks good?

@gpetretto gpetretto left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @hrushikesh-s, thanks a lot for the PR!
I went through the changes and left some comments. Some are up for discussion.
I did not try explicitly the aws implement and I am a user of the boto3 packages, so I relied on the comments from Claude concerning some details of the package and some general review.
As a general comment, once this is finalized, it would be good to have another PR with some documentation, like the one from jobflow-remote.



@dataclass
class QCloudResources(BaseQResources):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Several elements seem in common between QResources and QCloudResources. If the risk of misinterpreting them is high it is fine to keep them separated, but for example job_name seems unlikely to be particularly different. The question is why those that are in common were left out of the BaseQResources? Having the base class for just a single attribute when there is a larger overlap seemed a bit weird.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point. BaseQResources is now a dataclass with queue_name and job_name, the first two fields of both classes. time_limit and scheduler_kwargs are also shared, but they stay declared in each subclass. Dataclass fields of a base class come first, so moving them to the base would change the positional arguments of QResources. Eg: the third positional argument of QResources would then be time_limit instead of memory_per_thread. The other similar fields differ in meaning or units (memory_per_thread in MB vs total memory in MiB, gpus_per_job vs gpus), so I kept them separate. A test checks that the positional order of QResources is unchanged.

Comment thread src/qtoolkit/io/api/__init__.py Outdated
@@ -0,0 +1,4 @@
from qtoolkit.io.api.aws_batch import AWSBatchIO, AWSBatchState

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As a general comment for the module, I would propose that this goes one level up (i.e. qtoolkit.api instead of qtoolkit.io.api), and moving _BaseScheduler to BaseScheduler in core. What do you think?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, done. The package is now qtoolkit.api (qtoolkit.api.base and qtoolkit.api.aws_batch), the tests are in tests/api, and _BaseScheduler is now BaseScheduler in qtoolkit/core/base.py. qtoolkit.io no longer imports the API classes. I'll update the imports in Matgenix/jobflow-remote#553.

Comment thread src/qtoolkit/core/data_objects.py Outdated
priority: int | None = None
"""Scheduling priority of the job."""

image: str | None = None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

just asking due to my limited experience, is this general enough for other cloud services?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The field itself is general. GCP Batch, Azure Batch, and Kubernetes all take an image per job. AWS Batch is the exception for the container jobs that AWSBatchIO submits, because their image is set in the job definition and cannot be overridden at submission, so AWSBatchIO rejected it. Since no backend uses it yet, I removed image from QCloudResources, as I did for priority. It can come back with the first backend that supports it.

Comment thread src/qtoolkit/io/api/aws_batch.py Outdated
session = boto3.Session(
region_name=self.region_name, profile_name=self.profile_name
)
self._client = session.client("batch", endpoint_url=self.endpoint_url)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looking at the client API, there are many additional arguments that can be set, are there any that would be worth passing to this client? Or is a client_kwargs attribute worth having? In case, how to handle a Config object?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added client_kwargs, which is passed to session.client("batch", ...). To keep AWSBatchIO serializable, config is given as a dict and converted to botocore.config.Config when the client is created, for example client_kwargs={"config": {"retries": {"max_attempts": 10, "mode": "adaptive"}, "read_timeout": 120}}. The most useful ones are config (retries, timeouts, and proxies) and verify. endpoint_url stays a direct argument since it is the most common one, and setting it in both places raises an error. client_kwargs rejects region_name, service_name, and credentials.



class AWSBatchIO(BaseAPISchedulerIO):
"""Scheduler IO for single AWS Batch container jobs.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not familiar with the boto3 interface. How are the credentials set? It doesn't seem there is a way to set them in the object. Should there be such a way? Or what is the standard approach? Can it be documented here?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

boto3 finds the credentials through its standard chain, which includes environment variables, the shared ~/.aws/credentials and ~/.aws/config files (selected with profile_name or AWS_PROFILE, including SSO profiles), and the IAM role of the EC2 instance or ECS task. I think this is the right approach, because the arguments of AWSBatchIO get serialized (eg: in the jobflow-remote project file), and keys passed as arguments would end up there in plain text. I documented this in the class docstring with a link to the boto3 guide...

Comment thread src/qtoolkit/core/data_objects.py Outdated

max_retries: int | None = None
"""Maximum number of retries of a failed job (0 means no retries).
Which failures are retried depends on the backend."""

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What does None mean if 0 is no retries? Should it be only typed int with 0 as a default then? Or should None mean to not set the value?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

None means not set, so the retry strategy of the job definition applies. 0 disables retries and overrides the job definition. I kept int | None for this reason and updated the docstring.

EVENLY_DISTRIBUTED = "EVENLY_DISTRIBUTED"


class BaseQResources(QTKObject):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this be a dataclass? (with kw_only=True?)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it is now a dataclass. I did not use kw_only=True, because it needs Python 3.10 and requires-python is still >=3.9, even though CI now tests only 3.11 and later. It would also make queue_name and job_name keyword-only in QResources, so existing code that passes them as positional arguments would break. If you prefer to also move time_limit and scheduler_kwargs to the base with kw_only=True, I can do it together with requires-python = ">=3.10".

return results

@staticmethod
def _parse_job(raw: dict[str, Any]) -> QJob:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AWS only reports why a job failed in statusReason (e.g. a spot reclaim, an image pull error or a timeout), and with no shared filesystem there may be nothing in the logs either. Would it be worth keeping that message in the returned QJob (or making it available somehow), so that a user can see why a job failed without going to the AWS console?

Elaborated with Claude.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good idea. I added a generic state_reason field to QJob. It could also hold the Slurm REASON, for example. AWSBatchIO fills it from statusReason and container.reason. Both are needed, because for an out-of-memory kill statusReason only says "Essential container in task exited", while container.reason says "OutOfMemoryError: Container killed due to memory usage". jobflow-remote can add it to the error message of failed jobs in a separate PR.

Comment thread src/qtoolkit/io/api/aws_batch.py Outdated
self.endpoint_url = endpoint_url
self.default_job_name = default_job_name
self.shell_cmd = shell_cmd
self._client: Any = None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Once _get_client() has been called, the object can no longer be pickled or deep-copied, because the boto3 client can't be. This would break, for example, passing the IO to a process started with spawn or forkserver (the default on macOS and Windows, and on Linux from Python 3.14). Since likely every API backend will hold a client, maybe the lazy client could be handled in BaseAPISchedulerIO: an abstract _create_client(), with the base caching the client in _client and resetting it in getstate.

Suggested by Claude

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, done as suggested. BaseAPISchedulerIO has an abstract _create_client(), _get_client() caches the client in _client, and getstate drops it. So pickling and deepcopy work after the client was created, and the copy creates its own client on first use. Both are tested, including against moto.

Comment thread src/qtoolkit/io/api/aws_batch.py Outdated
container_overrides = dict(container_overrides)
else:
raise TypeError("containerOverrides must be a dict.")
container_overrides["command"] = self.format_command(commands)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is it fine to override command, even if it is passed? in options? warn/raise/allow?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It now raises a ValueError when commands is given and the options also contain containerOverrides["command"], since it is not clear which one should win. A command in the options is used only with commands=None.

…d and client handling in BaseAPISchedulerIO, rejected vs transient errors, client_kwargs, and QJob.state_reason
@hrushikesh-s

Copy link
Copy Markdown
Author

Thanks a lot for the detailed review, @gpetretto! I addressed all the comments in c473911, with replies in each thread. The API schedulers now live in qtoolkit.api, shell_cmd and the client handling moved to BaseAPISchedulerIO, only rejected requests return FAILED, and QJob has a new state_reason. Agreed on the documentation, I'll open a separate PR for it once this one is merged.

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants