Skip to content

Cooperative Parallelism #10443

Open

Description

@kastiglione

Description of the problem / feature request:

This is an umbrella issue of problems that arise from using build tools that have their own internal parallelism.

In this Google Groups thread, @jmmv asked to file an issue about this:

https://groups.google.com/d/msg/bazel-discuss/_oHaU50P5Rg/imx5Y49MAwAJ

A little context: swiftc is the swift compiler driver. It's a non-traditional compiler, it doesn't build one source file at time, it builds one module of N source files at time. swiftc spawns "swift frontend" invocations, and the number of spawned processes is very often >1.

There are two related problems:

  1. Tools that perform parallel sub-actions cannot express this use of parallelism to bazel
  2. Actions have no API through which they can specify maximum parallelism

In the first case, it would be good if the action API could express to Bazel how much parallelism is used by an action. This avoids the problem of N bazel actions each running some M sub-actions each.

In the second case, it would be good if the action API could express a range of parallelism an action is capable of using. This would really help the performance of bottleneck actions in the critical path. For example, Bazel could see that it's not using its full amount of jobs, and donate the extra parallelism to the bottleneck action. We see this as particularly useful at the tail end of builds, where there are fewer targets left to build. This problem shows up even more in incremental builds, where the action graph is often much more flat, even linear.

As @allevato pointed out in the google groups thread, this would require some way for actions to pass args that are known not to affect output, such as a -j<N> flag. This would also need to preserve the cache keys.

Feature requests: what underlying problem are you trying to solve with this feature?

This feature allows us to avoid two current problems:

  1. prevent oversubscribing cpu during the build
  2. prevent slower-than-necessary builds that are caused by wasted parallelism

The first issue can happen with any swift module over 25 files. The default batching logic creates one swift frontend for each group of 25 files. A swift module with 100 files will spawn 4 sub-actions, unbeknownst to Bazel.

As mentioned, the second case is something that causes slowdowns for incremental development builds.

Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.

If needed, I can make a rules_swift project that demonstrates the issue.

We see the problem in our build by looking at --experimental_generate_json_trace_profile and by comparing to Xcode's builds, which can sometimes be faster due to its seemingly hard code use of -j8.

What operating system are you running Bazel on?

macOS

What's the output of bazel info release?

release 1.2.0

Have you found anything relevant by searching the web?

As mentioned above, a small amount of discussion happened on Google Groups:

https://groups.google.com/d/msg/bazel-discuss/_oHaU50P5Rg/imx5Y49MAwAJ

I've also posted a general (non-bazel) question to the Swift Forums.

https://forums.swift.org/t/globally-optimized-build-parallelism/31802/2

Activity

  1. added
    team-Local-Exec
    untriaged
    on Dec 20, 2019
  2. rupertks commented on Dec 20, 2019

    @rupertks
    Contributor

    Thanks for creating this issue!

    Since @jmmv specifically asked for it to be created I am removing it from the untriaged label and giving it an initial P2 priority

  3. added
    P2
    and removed
    untriaged
    on Dec 20, 2019
  4. jmmv commented on May 14, 2020

    @jmmv
    Contributor

    Just one more addition since I just closed #11275: if we do this and explicitly tell an action that we should use X threads, we also have to go the other way and ensuring the action doesn't use more than X threads (1 in the general case!) when told so.

  5. mzeren-vmw commented on Oct 8, 2020

    @mzeren-vmw
    Contributor

    we also have to go the other way and ensuring the action doesn't use more than X threads (1 in the general case!) when told so.

    I don't see this as a requirement, at least not until someone provides a use case. We have a local patch that lets us set concurrency and we have cases where an action may peek briefly at 4 threads but empirically has a steady state of 2 threads, for example. A multi-threaded process does not usually consume cores in 100% core increments.

  6. motiejus commented on Dec 28, 2020

    @motiejus

    Consider xz -T0, which uses all available cores. Assume:

    genrule(
        name = name+"-xz",
        srcs = [name],
        outs = [name + ".xz"],
        cmd = "xz -T0 -f $< > $@",
    )
    

    I would like to tell Bazel that "this rule uses N-1 workers, where N is the number of available cores"; I would still like to leave 1-2 slots, in case they are IO bound.

  7. pauldraper commented on Nov 11, 2021

    @pauldraper
    Contributor
  8. brentleyjones commented on Nov 16, 2021

    @brentleyjones
    Contributor
  9. matts1 commented on Dec 6, 2022

    @matts1
    Contributor

    GNU make recently added support for jobservers via named pipes (previously they had to be passed around via file descriptors).

    Could we have bazel create named pipes for its own jobserver, and provide some kind of mechanism to provide those pipes to actions (variable substitition?)? Someone made a workaround which literally just has a jobserver service running in the background for rules_foreign_cc's make, but it'd be nice if we could have this run with fully self-contained builds.

  10. larsrc-google commented on Dec 7, 2022

    @larsrc-google
    Contributor

    One thing you can do now is provide better estimates of the #CPUs your jobs will use. @wilwell submitted d7f0724, which allows specifying the expected amount of CPU/RAM depending on the number of inputs. And I have work in progress to use cgroups for sandboxes, which would allow more flexible limits. Neither of those are as powerful as negotiating with the processes, but I want to see a strong need for that power before complicating matters even more.

  11. lukokr-aarch64 commented on Dec 12, 2023

    @lukokr-aarch64

    We have a very heavy compute build action that would like to use the most cores it can.

    We have no option to break it down into smaller chunks.

    Having the cooperative parallelism would go a long way for us as right now there is no obvious way to obtain the number of jobs that Bazel has access to within a rule context such that we can return it via resource_set.

    We could use a workaround with a repository rule calling out to nproc but that would not account for Bazel --jobs=N flag.

    In the short term it would be useful if the resource_set callable recieved the upper limits on the resources. Something like:

    # This breaks the current API but it demonstrates what we would like to be able to do. 
    def _resources(default, limit, platform):
        default["cpu"] = _jobs(max = limit["cpu"], min = 1, diff = -2)
        return default

    The idea for us is on a machine with 56 cores we could reserve some cores for other smaller actions to trickle through.

    Alternatively a tag to mark all actions of a certain type to be exclusive similiar to how tests can be marked with the exclusive tag.

  12. fmeum commented on Dec 12, 2023

    @fmeum
    Collaborator

    With resource_set, you can approximate having an action run on min(N, $(nproc)) cores for a constant N due to how scheduling works in Bazel: If a resource isn't in use (i.e., all remaining actions are waiting for the big one), an action is executed even if it requests resources in excess of the available total.

    This doesn't allow any kind of $(nproc) - 2 logic though, which would be quite convenient. But I think that this would require special support in ctx.actions.args so that the action's command line can indicate the available level of parallelism. Just making the resource API more flexible wouldn't be sufficient.

  13. blackliner commented on Dec 14, 2024

    @blackliner

    rules_rust having a similar challenge: bazelbuild/rules_rust#3101

  14. fmeum commented on Dec 14, 2024

    @fmeum
    Collaborator

    Bazel gained a --experimental_cpu_load_scheduling flag that schedules actions based on continuously measured actual (not modeled) CPU load. That could be interesting for rulesets to try out.

  15. nvkjw commented on Feb 20, 2026

    @nvkjw

    Use case 0: I happened to be compiling llvm (cmake in docker) and when it got to fortran, I had to crank its parallelism down to 2 to get it to run on a server vm (i.e. no x11 or browser) with 16 GB of RAM. So... it would be great to also
    1- coordinate memory reservations and
    2- automatically gather/track memory use, such that the build system can monitor and just do it for the user automatically. (read: maintaining test size markup in bazel is a PITA. but in practice, it would be best to create a feedback loop through clean CI builds, thus ignoring users who experimentally add sleep(3600) to their code.)
    Related use case: sort --buffer_size= could benefit from more memory.

    Use case 1: multiple users - shared access would be beneficial to not overloading a shared system with local builds.

    Use case 2: recursive make. ok, not exactly useful if you're 100% bazel, but if you have a hybrid bazel calling make, like for an external dep, that would be useful to coordinate across fork/exec's.

    Use case 3a: existing tools that have a -j# flag (like pigz) should be able to "use available cores" i.e. today by default it auto detects and uses all cores. therefore running anything alongside it is oversubscribing your cpu cores. so something more intelligent here would be nice, like query the jobserver, find 2 cores available, then turns that into a -j2 flag.

    Use case 3b: smart tool dynamically communicating with jobserver. pigz could potentially be dynamic and expand as cores become available. that of course means it needs to talk directly to the job server and reserve more (or release) cores as its workload increases or decreases.

    In general, I feel like jobserver needs to be more than just core reservation, it should instead actively monitor the system (cpu idle%, for example) and swapping, and dynamically adjust as something in the background (i.e. not a local build) starts using cores. sort --buffer-size= could benefit from knowing how much RAM was available for use.

    For a first implementation, none of the tools need to be smart. in fact bazel could do the reservation on behalf of each tool (i.e. block launching a process until the resource is available) defaulting to 1 (i.e. what we do today). This largely is needed for local builds. To some extent, that makes things easier, since RBE has some solutions already in place (schedulers, pools, automatic failover to "bigger" machines).

  16. nvkjw commented on Feb 24, 2026

    @nvkjw

    Today I discovered  https://docs.kernel.org/accounting/psi.html which is exactly what I want. and """Meta's Buck2: Developed at Meta (the creators of PSI), Buck2 is designed to use PSI for proactive load shedding. It can pause or slow down local task execution when memory or CPU pressure reaches critical thresholds."""
    On swap enabled systems, I'd be ok with bazel using kill -STOP to PAUSE a process (note, forking may cause issues) so that you can resume "soon". It will require a PSI plus placeholders to lower the parallelism ceiling temporarily.

  17. sluongng commented on Mar 18, 2026

    @sluongng
    Contributor

    I described how we did this for BuildBuddy RBE in Bazelcon 2025 https://www.youtube.com/watch?v=iQqLtuBzkKE

    Essentially, it comes down to a few bullet points:

    1. You need to profile your actions. Knowing how much CPU, memory, and potentially disk I/O each action consumes will help you estimate future behavior. PSI and other metrics from cgroupv2 are great at this. For example, if swiftc were to spawn child processes, the cgroupv2 metrics can capture the total consumption in aggregate for that process tree. There are similar concepts on MacOS and Windows that can be tapped into separately iiuc.

    2. You need to store the profiling data somewhere so that future invocations can use it as references

    3. For cases such as newly added actions in the graph, a heuristic can be applied. In our case, we use a linear regression model, but there can be simpler approach out there.

    With that said, I believe a short and sweet way to go about this is for Bazel to create a "fat" profile.json file using the --profile flag and store all the relevant action profiling data in there. As a startup flag, Bazel could unpack this profile.json file and use it for a "Profile-guided scheduling" strategy for local execution.

    The current Bazel profile already contains quite rich information: target label, primary output, and configuration hash. This should help match the recorded action profiling data with future action executions.

    I vibecoded a hack here sluongng@d344a17 (with a lot of assumptions and baked-in heuristic) just to explore the idea. I won't be pursuing this right now, though, as I do believe the best scheduling experience is by adopting an RBE solution instead of trying to bin-pack things on the local machine.


    Use case 1: multiple users

    I think this is one of the use cases that should be left unsolved for local-exec and is well solved by RBE.

    Keep in mind that Bazel itself is a JVM exclusive to the specific output base + workspace. So multiple users are already requiring multiple JVMs, duplicating the output base (and workspace) already. That typically screams for some higher-level resource isolation (Docker container, cgroups isolation, etc, ...) to manage things well. Local action scheduling alone is insufficient to provide a good user experience.

    Thus, I would call multi-users an out-of-scope item for this issue.

    Job server

    I don't think this solution is adequate to implement for a larger setup.
    In a sufficiently large build graph, actions come in many shapes and sizes.
    Some take up more disk, some more CPU, some even take in exotic resources like GPU and FPGA.

    The job server simply assumes each "job" consumes a fixed amount of resources and thus misses a lot of opportunity for maximizing the parallelism on a single machine. I think most of the problems with actions that create a process tree (i.e., running Make or Ninja inside a build action) can be well encapsulated by cgroupv2 resource consumption profiling (and limiting).

  18. nvkjw commented on Mar 30, 2026

    @nvkjw

    I do believe the best scheduling experience is by adopting an RBE solution instead of trying to bin-pack things on the local machine.

    There are still a lot of use cases where local runs are faster than RBE (e.g. big outputs & working-from-home), and even with just one user, if pigz decides to use all 20 cores (and you have 20 other compiles running) you're in for a bad time.

  19. nvkjw commented on Oct 13, 2026

    @nvkjw

    I experimented in my existing work environment (gnumake and jobserver; I know, I know) and added linux kernel PSI feedback to the jobserver (stop launching new processes when ram/cpu/i/o pressure increases) and also making it possible to have one jobserver on the machine shared by all independent make processes, and now I can run dozens of independent make processes (i.e. not recursive cd;make that the existing gnumake+jobserver combo supports (only), with no crashing; the machine doesn't even feel slow.

    Yes, there's a potential race condition if you don't know the size of each action, but in general it's proof that it's a good start, and will solve many of the problems with very little work (no need to instrument every build).

    Personally, I think that instrumenting every action for resource usage is a good idea for the scheduler, but not everything need be perfect on the first try.

  20. nvkjw commented on Oct 29, 2026

    @nvkjw

    ok, now lacking coordination of local builds is crashing my machine. trying to do make to bazel migrations (in parallel) is impossible without even a simple dumb jobserver. memory pressure is the biggest issue, not cores. So I'm going to have to hack a local version of bazel. Hopefully those of you using agents will chime in with a +1 because parallel work is blocked by this. Doing this serially is painfully under-utilizing my machine (48T/24C, 64G). but very specifically, I need make and bazel to share a jobserver, because I'm doing both at the same time.
    "local RBE" doesn't help when my actions range from tiny to ginormous (10G ea) on 48T/24C, 64GB ram. I even run headless so no browsers eating up any ram.

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

    P2team-Local-Exectype: feature request

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions