Skip to content

fix: standardize handling of resources - #3421

Merged
johanneskoester merged 4 commits into
snakemake:mainfrom
pvandyken:fix/human-friendly-units-groups
Feb 5, 2026
Merged

johanneskoester merged 4 commits into
snakemake:mainfrom
pvandyken:fix/human-friendly-units-groups

Conversation

@pvandyken

@pvandyken pvandyken commented Mar 13, 2025 •

Copy link
Copy Markdown
Contributor

This centralizes the code for resource handling into the resource.py file under a new Resource class. Notably, DefaultResources has been removed, its functionality rolled into the new class. The same class is now used for handling global resource limits, default resources, and rule resource constraints

As a result of this standarization, the following bugs/inconsistencies are fixed:

  1. humanreadable resources can now be specified in a group job in cluster submit without crashing the program (fix: group resources #3367)
  2. mem, mem_mb, and mem_mib can now be used interchangeably across --resources, --set-resource-scopes, --default-resources, --set-resources, and the resource keyword within a Snakefile, as the names are internally standardized.
  3. humanreadable resources can now be used in all resource contexts (e.g. --resources)
  4. Providing the same effective resource twice (e.g. mem, mem_mb and/or mem_mib) in the same rule or in the global resource specification raises an error.
  5. BREAKING mem_mb and mem_mib can no longer be provided a string or a function that returns a string within a rule.
  6. The {resources} object available within a shell command or parameter context now has access to all versions of a sized resource, e.g. mem, mem_mb, mem_mib. mem is now always a string with a unit.

A few additional changes:

  • The old Resource class in snakemake/io.py (that subclasses Namedlist was renamed to ResourceList to prevent confusion. This class is still used within the Job class and is ultimately passed onto the executor. This ensures compatibility with the existing plugin interface.
  • I added the ability to watch for a specific Exception class within the tests to help increase the resolution of some of my "failure" tests. This is completely backwards-compatible
  • Additional typing annotations were added throughout the code I touched.
  • A small rearrangement in the code within snakemake/workflow.py to group the resource-related code together.

Outstanding issues (not to be resolved here)

  1. It was, and remains, possible to sneak a string value as a thread using --set-threads with a python expression
  2. --resources cannot be given an expression, per design. Currently, though, nothing stops one from from providing an expression directly via the api. This problem preexists this PR.
  3. There is currently no testing of the cli parsing functions. This should be written in a new PR.
  4. The check for positive integers is only done for the CLI. Resources requested within rules will not be so validated. This is unchanged from previous

Gotchas

  1. This does represent a breaking change for API use, as the dataclasses will not perform any automatic conversion. Specifically, ResourceSettings.resources, .overwrite_threads, .overwrite_resources, and .default_resources will be broken in dependent apps.

QC

  • The PR contains a test case for the changes or the changes are already covered by an existing test case.
  • The documentation (docs/) is updated to reflect the changes or this is not necessary (e.g. if the change does neither modify the language nor the behavior or functionalities of Snakemake).

Summary by CodeRabbit

Release Notes

  • New Features

    • Support for human-readable resource specifications (e.g., "1 GB", "1 GiB")
    • New resource units: mem_mib, disk_mib alongside existing mem_mb, disk_mb
  • Bug Fixes

    • Improved resource handling and validation with better error messages
    • Enhanced resource constraint detection and reporting
  • Refactor

    • Unified resource management system for simplified configuration
    • Streamlined CLI resource parsing and argument handling

@coderabbitai

coderabbitai Bot commented Mar 13, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This pull request introduces a comprehensive refactoring of Snakemake's resource management system. It replaces legacy DefaultResources and ParsedResource classes with new Resource and Resources classes offering unified API for resource handling across CLI parsing, workflow execution, job scheduling, and rule expansion. New exception types are added for resource-related errors, and existing APIs are updated to use the new resource abstractions.

Changes

Cohort / File(s) Summary
Resource System Core
src/snakemake/resources.py
Complete rewrite introducing Resource class for individual resource management and Resources class as a Mapping-like container with parsing, evaluation, and normalization capabilities. Adds ResourceScopes enhancements for scope predicates (is_local, is_global, is_excluded). Includes extensive public API: from_cli_expression, parse, parser_factory, default, from_mapping and unit conversion helpers.
Exception Hierarchy
src/snakemake/exceptions.py
Adds new resource-related exception classes: NestedCoroutineError, ResourceError, ResourceInsufficiencyError, ResourceValidationError, ResourceConstraintError, ResourceConversionError, ResourceDuplicationError with specialized constructors and classmethods for error formatting.
Public API Updates
src/snakemake/api.py, src/snakemake/script/__init__.py
Updates to use new Resources.default("full") instead of DefaultResources(mode="full"); parameter type changed from io_.Resources to io_.ResourceList in Snakemake constructor.
CLI Parsing
src/snakemake/cli.py, src/snakemake/settings/types.py
Refactored resource and thread parsing to use Resources.parser_factory and Resources.parse. Added parse_set_threads wrapper converting ints to Resource("_cores", n). Updated resource settings with ValidResource type alias and cached property parsing for _parsed_resources, _parsed_overwrite_resources, etc.
IO Type System
src/snakemake/io/__init__.py
Renamed Resources class to ResourceList (Namedlist subclass). Enhanced with generics: Namedlist(Generic[_TNamedKeys, _TNamedList]) with updated items() return type annotation.
Common Utilities
src/snakemake/common/__init__.py, src/snakemake/logging.py
Added mib_to_mb conversion function. Updated mb_to_mib signature with type annotation. Enhanced get_input_function_aux_params to accept Callable and Mapping types. Replaced WorkflowError with NestedCoroutineError in async context. Updated format_dict to accept Mapping type.
Job and Resource Management
src/snakemake/jobs.py, src/snakemake/scheduling/job_scheduler.py, src/snakemake/spawn_jobs.py
Job.resources now returns ResourceList. GroupJob handles resource aggregation with both WorkflowError and ResourceInsufficiencyError. JobScheduler expands workflow.global_resources via expand_items(...) and uses value.raw for CLI formatting. Removed ParsedResource import and _get_resources_to_skip helper.
Workflow and Rules
src/snakemake/workflow.py, src/snakemake/rules.py, src/snakemake/dag.py
Workflow.global_resources sourced from _parsed_resources; resource initialization and merging consolidated via Resources.from_mapping. Rule.expand_resources refactored to use expand_items with refined error handling for ResourceConstraintError and ResourceConversionError. Added type hints for Workflow, Resources attributes. DAG.stats signature updated to use capitalized typing aliases.
Tests
tests/common.py, tests/tests.py, tests/test_*.../Snakefile*
Updated test framework to import and use Resources instead of DefaultResources. Added tests for new exceptions (ResourceConversionError, ResourceDuplicationError). Updated Snakefile tests to use new resource formats (mem="1 GB", mem_mib, disk="1 GB") and assertions validating Resources parsing and expansion.

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120+ minutes

Possibly related PRs

Suggested reviewers

  • johanneskoester
🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 29.45% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title 'fix: standardize handling of resources' accurately reflects the main objective of the PR, which centralizes resource handling through a new Resource class and standardizes how mem, mem_mb, and mem_mib are handled across the codebase.
Description check ✅ Passed The PR description is comprehensive and well-structured. It clearly explains the changes, lists specific fixes and behavioral changes, documents breaking changes, and acknowledges outstanding issues and gotchas. Both QC checkboxes are marked as complete.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@pvandyken pvandyken added the bug Something isn't working label Mar 13, 2025
@pvandyken
pvandyken force-pushed the fix/human-friendly-units-groups branch 2 times, most recently from ab20f60 to f98ac7b Compare March 13, 2025 18:00

@coderabbitai coderabbitai Bot left a comment

Copy link