You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
os.process_cpu_count() should take cgroups CPU limitations into account (on Linux) #149452
os.process_cpu_count() currently takes CPU core scheduler affinity into account. However, there are other ways to restrict CPU usage on Linux, most significantly cgroups as used by Docker and Kubernetes.
For example, if I ask for 2 cpus for a container, process_cpu_count() does not respect that:
This can lead to surprising behavior for users, where too many threads are started in a container given the available resources.
An existing implementation in Python
In contrast, the loky.cpu_count() function does know about these restrictions:
$ docker run -it --cpus=2 python:3.14-slim bash
root@557b43351822:/# pip install --quiet loky
root@557b43351822:/# python
Python 3.14.2 (main, Jan 13 2026, 03:08:39) [GCC 14.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import loky
>>> loky.cpu_count()
2
This is a minor feature, which does not need previous discussion elsewhere
Links to previous discussion of this feature:
There was some discussion in #77167. Given cpu_count() is now distinct from process_cpu_count(), it seems useful to make the latter accurate, and cgroups as the basis for Linux containerization has a massive scale of deployment.
This looks like a nontrivial implementation. Should we really make it part of the stdlib as this may vary across platforms and we would need to maintain this? Iam tagging it as a mp issue event though it is not mp-really (but it is related to mt/mp)
If the final decision is that it's not worth doing, the minimalist option is to document the limitations of process_cpu_count() and point readers at better alternatives.
As a reference point, the (fairly minimal) Rust standard library decided to add cgroups support in 1.61 to the equivalent API. The detailed changelog explained that "Since available_parallelism is often used to create a thread pool for parallel computation, which may be CPU-bound for performance, available_parallelism will return a value consistent with the ability to use that many threads continuously, if possible. For instance, in a container with 8 virtual CPUs but quotas only allowing for 50% usage, available_parallelism will return 4."
I guess if Rust ever becomes a CPython dependency that would allow for an easy fix...
I am perfectly ok for a doc update for now as it is largerly non-controversial. I would be interested in having something in the stdlib though, but the question is:
can all Tier 1 platforms be properly supported?
can Tier 2/3 platforms be supported at minimal cost?
how maintainable will it be?
UUID is another beast where there are lots of checks since we want to support many platforms and I would honestly want to avoid this kind of code if possible.. if every Linux distribution needs its own check it will be hard to maintain properly =/ but we can make it as an iterative approach (start with common checks). We however do not want to end up with frozen dev as for ctypes.util.find_library() (I think we soft-deprecated that function)
At first glance at the Rust std implementation as a potential baseline, I think it's mostly just adding cgroups support for Linux, none of the other OSes have much custom code beyond what Python already does (https://github.com/rust-lang/rust/tree/main/library/std/src/sys/thread).
I'm not sure I fully agree with the decisions there, but, it does look like an “available_parallelism” API serves a slightly different purpose than process_cpu_count -- though arguably a more niche one: AFAIK @vstinner added process_cpu_count in the context of CPU isolation, for reliable beachmark timing.
Given that multiprocessing pools need a default, perhaps “available_parallelism” logic should live somewhre in stdlib.
I guess if Rust ever becomes a CPython dependency that would allow for an easy fix...
Or just shell out to nproc if that's available, right? That has cgroups v2 support, in the latest versions.
can all Tier 1 platforms be properly supported?
can Tier 2/3 platforms be supported at minimal cost?
how maintainable will it be?
Those are questions for a different feature request, though one that's implied here: “Make os.process_cpu_count() reliably take platform CPU quota into account.” That is an unreachable state.
It would turn os.process_cpu_count is a pit of unbounded complexity, similar to shutil.copyfile/os.sendfile implementing 3+ different “best” ways to move bytes around on specific systems.
But alas, in this case, the stdlib os module is probably the right layer for this complexity. We already started on this path with the affinity support.
On its own, the cgroups feature will not vary across platforms -- it's platform-specific. And it should be rather stable once implemented. Other platforms, and Linux, might add other limiting mechanisms; that's where maintainability cost is. But IMO we should take patches for those on all “major” platforms (even unsupported ones, under the PEP 11 policy).
Those are questions for a different feature request, though one that's implied here: “Make os.process_cpu_count() reliably take platform CPU quota into account.” That is an unreachable state.
Actually that was my question but I phrased it poorly :) Now, as I said, I'm ok with this addition, just that we should be careful with how precise we'll be. Relying on cgroup only first should be ok since it's kinda standardized and we'll see in the future about other limiting mechanisms.
I should however apologize concerning the loky statement: the complexity mainly comes from the physical core counting. If we are only interested in logical available cores, the features looks not that complex to do.
I mean that in general, Linux cgroups CPU limits are not directly related to a whole number of CPU and so it's hard to use such limit to update os.cpu_count() or os.process_cpu_count().
IMO, rounding up is the correct thing to do. If your quota is “2.5 CPUs”, 2 threads will not saturate that and 4+ is definitely wasteful (if they're CPU-bound).
It's also what nproc does (at least the version in Fedora currently):
AFAIK cgroups v1 (that is, what pylint is using) is kinda obsolete already; perhaps we can do just v2 if we're adding this to 3.16?
IMO iterating the mounts is hypercorrect, a holdover from v1 maybe. /sys/fs/cgroup should work fine. (For example, we also open /dev/urandom even though a sysadmin could theoretically put that device elsewhere.)
cpu.weight
This is relative weight (like nice). For “available_parallelism” we should ignore it; we don't know what the system load will be when worker threads are running.
Activity
picnixz commentedon May 6, 2026
This looks like a nontrivial implementation. Should we really make it part of the stdlib as this may vary across platforms and we would need to maintain this? Iam tagging it as a mp issue event though it is not mp-really (but it is related to mt/mp)
itamarst commentedon May 6, 2026
If the final decision is that it's not worth doing, the minimalist option is to document the limitations of
process_cpu_count()and point readers at better alternatives.As a reference point, the (fairly minimal) Rust standard library decided to add cgroups support in 1.61 to the equivalent API. The detailed changelog explained that "Since available_parallelism is often used to create a thread pool for parallel computation, which may be CPU-bound for performance, available_parallelism will return a value consistent with the ability to use that many threads continuously, if possible. For instance, in a container with 8 virtual CPUs but quotas only allowing for 50% usage, available_parallelism will return 4."
I guess if Rust ever becomes a CPython dependency that would allow for an easy fix...
picnixz commentedon May 6, 2026
I am perfectly ok for a doc update for now as it is largerly non-controversial. I would be interested in having something in the stdlib though, but the question is:
UUID is another beast where there are lots of checks since we want to support many platforms and I would honestly want to avoid this kind of code if possible.. if every Linux distribution needs its own check it will be hard to maintain properly =/ but we can make it as an iterative approach (start with common checks). We however do not want to end up with frozen dev as for ctypes.util.find_library() (I think we soft-deprecated that function)
itamarst commentedon May 7, 2026
At first glance at the Rust std implementation as a potential baseline, I think it's mostly just adding cgroups support for Linux, none of the other OSes have much custom code beyond what Python already does (https://github.com/rust-lang/rust/tree/main/library/std/src/sys/thread).
encukou commentedon May 7, 2026
Turns out this is a duplicate of #77167 & #80235.
I'm not sure I fully agree with the decisions there, but, it does look like an “
available_parallelism” API serves a slightly different purpose thanprocess_cpu_count-- though arguably a more niche one: AFAIK @vstinner addedprocess_cpu_countin the context of CPU isolation, for reliable beachmark timing.Given that
multiprocessingpools need a default, perhaps “available_parallelism” logic should live somewhre in stdlib.Or just shell out to
nprocif that's available, right? That has cgroups v2 support, in the latest versions.Those are questions for a different feature request, though one that's implied here: “Make
os.process_cpu_count()reliably take platform CPU quota into account.” That is an unreachable state.It would turn
os.process_cpu_countis a pit of unbounded complexity, similar toshutil.copyfile/os.sendfileimplementing 3+ different “best” ways to move bytes around on specific systems.But alas, in this case, the stdlib
osmodule is probably the right layer for this complexity. We already started on this path with the affinity support.On its own, the cgroups feature will not vary across platforms -- it's platform-specific. And it should be rather stable once implemented. Other platforms, and Linux, might add other limiting mechanisms; that's where maintainability cost is. But IMO we should take patches for those on all “major” platforms (even unsupported ones, under the PEP 11 policy).
picnixz commentedon May 7, 2026
Actually that was my question but I phrased it poorly :) Now, as I said, I'm ok with this addition, just that we should be careful with how precise we'll be. Relying on cgroup only first should be ok since it's kinda standardized and we'll see in the future about other limiting mechanisms.
I should however apologize concerning the loky statement: the complexity mainly comes from the physical core counting. If we are only interested in logical available cores, the features looks not that complex to do.
encukou commentedon May 7, 2026
This goes directly against an earlier decision; we need to address @vstinner's point:
IMO, rounding up is the correct thing to do. If your quota is “2.5 CPUs”, 2 threads will not saturate that and 4+ is definitely wasteful (if they're CPU-bound).
It's also what
nprocdoes (at least the version in Fedora currently):vstinner commentedon May 7, 2026
Copy of my comment (2023).
pylint parses different cgroup files:
/sys/fs/cgroup/cpu/cpu.cfs_quota_us/sys/fs/cgroup/cpu/cpu.cfs_period_us/sys/fs/cgroup/cpu/cpu.sharesCode: https://github.com/d1gl3/pylint/blob/2625c341e07f60276dcd2c23a8b47f49f80688a0/pylint/lint/run.py#L34-L80
On a recent container (ex: Fedora 44), none of these files exist, but I have
/sys/fs/cgroup/cpu.max(cgroup version 2).coreutils
nprocprogram callsnum_processors()function which is implemented in gnulib:lib/nproc.c. This function gets the CPU quota:/proc/self/cgroup/proc/mounts<cgroup2 mount point> / <cgroup> / "cpu.max"(ignore line starting with "max"), remove the last part of cgroup at each iterationThe CPU quota is not used if the process scheduler is SCHED_FIFO, SCHED_RR or SCHED_DEADLINE.
I reimplemented the code in Python:
vstinner commentedon May 7, 2026
cgroup v2 has other files related to the CPU:
cpu.weightcpuset.cpus.effectivecpuset.cpus.isolatedcpuset.mems.effectiveThese files are not used by gnulib
num_processors()function. Should we parse these files as well?encukou commentedon May 8, 2026
AFAIK cgroups v1 (that is, what
pylintis using) is kinda obsolete already; perhaps we can do just v2 if we're adding this to 3.16?IMO iterating the mounts is hypercorrect, a holdover from v1 maybe.
/sys/fs/cgroupshould work fine. (For example, we also open/dev/urandomeven though a sysadmin could theoretically put that device elsewhere.)This is relative weight (like
nice). For “available_parallelism” we should ignore it; we don't know what the system load will be when worker threads are running.sched_getaffinityreflects this already:itamarst commentedon Nov 23, 2026
I'm going to try to turn @vstinner's sketch into a real PR.