Skip to content

Hooks to customize test grouping and group order for scope-based schedulers #1394

Open

Description

@RonnyPfannschmidt

🤖 Written by Claude Opus 5.5 via Claude Code for the pytest-xdist maintainers; I prompted it, it did the work, I read it.

Follow-up to #500, rescoped for the current code. That PR is being closed because it can't be rebased: it targeted xdist 1.31 and bundled a rewrite of every load scheduler. Most of that rewrite has landed in other forms since then. Background: #18.

Current state

  • LoadFileScheduling and LoadGroupScheduling subclass LoadScopeScheduling and only override _split_scope(nodeid), so the "one base class, override the grouping" part of Custom test grouping and test group order logic #500 already exists.
  • --dist loadgroup / @pytest.mark.xdist_group (Create new dist option 'loadgroup' #733) covers marker-based grouping, but it smuggles the group to the controller as an @group nodeid suffix. Loadgroup: Don't modify test nodeids any longer. #1119 proposes an explicit side-channel for that.
  • --loadscope-reorder (on by default) sorts groups by size in LoadScopeScheduling.schedule().
  • pytest_xdist_make_scheduler still lets a plugin replace the whole scheduler. That is heavy when all you want is different grouping.

Proposal

  1. Grouping hook, consulted by LoadScopeScheduling._split_scope before the subclass default:
    @pytest.hookspec(firstresult=True)
    def pytest_xdist_get_test_group(config: pytest.Config, nodeid: str) -> str | None:
        """Return the work-unit key for ``nodeid``, or None to use the scheduler default."""
    Call it once per nodeid when the workqueue is built, and cache the result. It must not be re-invoked from mark_test_complete.
  2. Ordering hook, called after the workqueue is built in schedule():
    @pytest.hookspec(firstresult=True)
    def pytest_xdist_order_test_groups(
        config: pytest.Config, groups: dict[str, list[str]]
    ) -> list[str] | None:
        """Return group keys in dispatch order, or None to keep the default."""
    This needs a defined precedence relative to --loadscope-reorder. Suggestion: a non-None result wins, and reorder only applies when no hook answers.
  3. Out of scope: --dist load keeps its per-test batching. Custom test grouping and test group order logic #500 turned load into one test per group, which removes batching and costs more round-trips. Users who want grouping pick loadscope plus the hook.

Known limitation / open question

The controller only has nodeid strings, so the hook can't see marks, fixtures or fixture-scope instances. That was #18's actual goal (phases 2 and 3). A fully useful version needs workers to send per-item metadata with collectionfinish, which is the same channel #1119 needs. Should that land first, so the hook gets (nodeid, metadata) from the start instead of growing a second signature later?

Notes for an implementer

  • Don't port Custom test grouping and test group order logic #500's scheduler bugs: loadscope must keep rsplit("::", 1).
  • _assign_work_unit uses worker_collection.index(nodeid) per test, which is O(N) per lookup. With fine-grained custom groups this becomes quadratic, so a nodeid-to-index map should come with it.
  • Tests: grouping hook returning None vs. a key; ordering hook vs. --loadscope-reorder; crash/replace-worker path with custom groups (see the 2026-04 loadgroup hang fix).

Activity

  1. sahilmathur254 commented on Oct 21, 2026

    @sahilmathur254

    Hi! I’m interested in working on this as a focused contribution.

    Looking at current master, #1388 already transports group names alongside collected node IDs, and #1119 was closed as superseded. This doesn’t yet provide general mark or fixture metadata.

    Would you prefer starting with the node-ID-based grouping hook proposed here, or should its initial API expose worker-provided metadata?

    My proposed scope would be:

    • Add grouping and ordering hooks for the scope-based scheduler family, preserving existing behavior when hooks return None.
    • Cache grouping decisions during queue construction, without invoking the hook again during completion handling.
    • Let an explicit ordering-hook result take precedence over --loadscope-reorder.
    • Cover fallback behavior, ordering precedence, and worker replacement with regression tests, plus documentation and a changelog entry.

    I’d leave --dist load batching unchanged. I also noticed #1383 overlaps the collection-index optimization, so I’d coordinate with that work rather than duplicate it.

    Does that scope and API direction sound appropriate?

  2. RonnyPfannschmidt commented on Nov 27, 2026

    @RonnyPfannschmidt
    MemberAuthor

    @sahilmathur254 im currently swamped nd cant provide good guidance - this is a delciate topic so coordination with the maintainers will be necessary for success

    currently i'd recommend smaller size for the initial attempts simply because pytest-core is very overloaded thanks to the AI-bros running a DOS attack on opensource volunteer maintenance

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions