From 9cc699320222512df8ab62e33b3607d3bf8df190 Mon Sep 17 00:00:00 2001 From: Itamar Turner-Trauring Date: Mon, 23 Nov 2026 13:20:03 -0500 Subject: [PATCH 01/17] Preliminary test for respecting cgroups in process_cpu_count() --- Lib/test/test_os/test_os.py | 39 +++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/Lib/test/test_os/test_os.py b/Lib/test/test_os/test_os.py index 8b6b7deb65b88b..ca953964bbbbb7 100644 --- a/Lib/test/test_os/test_os.py +++ b/Lib/test/test_os/test_os.py @@ -4682,6 +4682,45 @@ def test_process_cpu_count_affinity(self): affinity2 = os.process_cpu_count() self.assertEqual(affinity2, affinity1 - 1) + @unittest.skipUnless( + sys.platform == "linux" and shutil.which("systemd-run") is not None, + "testing cgroups requires Linux with systemd-run", + ) + def test_process_cpu_count_cgroups(self): + base_count = os.process_cpu_count() + if base_count is None: + self.skipTest("Could not determine the number of CPUs") + elif base_count < 2: + self.skipTest("require at least 2 CPU cores to test") + + # TODO test setting the period too + # TODO test nested cgroups + for setting, expected in [ + (0.01, 1), + (0.5, 1), + (1, 1), + (1.5, 2), + (base_count - 1, base_count - 1), + ]: + result = int( + subprocess.check_output( + [ + "systemd-run", + "--user", + "--scope", + "--quiet", + "--property", + f"CPUQuota={int(100 * setting)}%", + "--", + sys.executable, + "-c", + "import os; print(os.process_cpu_count())", + ], + encoding="utf-8", + ).strip() + ) + self.assertEqual(result, expected) + # FD inheritance check is only useful for systems with process support. @support.requires_subprocess() From b32eb6119233c5255153323b0f885aa14ac2884f Mon Sep 17 00:00:00 2001 From: Itamar Turner-Trauring Date: Mon, 23 Nov 2026 14:37:08 -0500 Subject: [PATCH 02/17] Sketch of cgroups implementation for process_cpu_count() --- Lib/os.py | 122 +++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 121 insertions(+), 1 deletion(-) diff --git a/Lib/os.py b/Lib/os.py index f999150150ccba..cc6c1ee1ef8dd4 100644 --- a/Lib/os.py +++ b/Lib/os.py @@ -1225,6 +1225,123 @@ def add_dll_directory(path): ) +if sys.platform == "linux": + def _get_cgroup2_mount_point(): + from builtins import open + + if path.exists("/sys/fs/cgroup/cgroup.controllers"): + return "/sys/fs/cgroup" + + try: + with open("/proc/mounts") as fp: + for line in fp: + parts = line.split() + _, mount_dir, mount_type, *_ = parts + if mount_type == "cgroup2": + for quoted, value in [ + (r"\040", " "), + (r"\011", "\t"), + (r"\012", "\n"), + (r"\134", "\\"), + ]: + mount_dir = mount_dir.replace(quoted, value) + return mount_dir + except OSError: + return + + + def _parse_cgroup2_cpu_max(filename): + """ + Returns None if file not found or a parsing error, or a number of cores + if successful. + """ + from builtins import open + + try: + with open(filename) as fp: + line = fp.readline() + except OSError: + return + + parts = line.split() + if len(parts) != 2: + return + + if parts[0] == "max": + return cpu_count() + + try: + quota = int(parts[0]) + period = int(parts[1]) + except ValueError: + return + + # Rounds up in order to saturate CPUs if the quota is fractional: + import math + + return max(math.ceil(quota / period), 1) + + + def _cpu_count_cgroups(): + from builtins import open + + sched = sched_getscheduler(0) + if sched in (SCHED_FIFO, SCHED_RR, SCHED_DEADLINE): + return + + cgroup_subpath = None + try: + fp = open("/proc/self/cgroup") + except OSError: + return + with fp: + for line in fp: + # Cgroups v2 format; see cgroups(7) man page, section on + # /proc/pid/cgroups + if line.startswith("0::/"): + cgroup_subpath = line[3:].rstrip("\n") + + if cgroup_subpath is None: + return + + cgroup2_mount_point = _get_cgroup2_mount_point() + if cgroup2_mount_point is None: + return + + # Traverse nested controllers, from child to parent, looking for a CPU + # limit: + cpu_quota = cpu_count() + while True: + cpu_max_filename = path.join( + cgroup2_mount_point, + cgroup_subpath[1:], + "cpu.max" + ) + num_cpus = _parse_cgroup2_cpu_max(cpu_max_filename) + if num_cpus is not None: + # Per the docs + # (https://docs.kernel.org/admin-guide/cgroup-v2.html): "When a + # controller is enabled on a nested cgroup, it always restricts + # the resource distribution further. The restrictions set + # closer to the root in the hierarchy can not be overridden + # from further away." So we have to pick the minimum. + cpu_quota = min(num_cpus, cpu_quota) + if cpu_quota == 1: + # Can't get any lower than 1: + return 1 + + # Move on to the parent cgroup, if any: + if cgroup_subpath == "/": + break + + cgroup_subpath = path.dirname(cgroup_subpath) + + return cpu_quota +else: + def _cpu_count_cgroups(): + return + + if _exists('sched_getaffinity') and sys._get_cpu_count_config() < 0: def process_cpu_count(): """ @@ -1233,7 +1350,10 @@ def process_cpu_count(): Return the number of logical CPUs usable by the calling thread of the current process. Return None if indeterminable. """ - return len(sched_getaffinity(0)) + cpu_count_cgroups = _cpu_count_cgroups() + if cpu_count_cgroups is None: + cpu_count_cgroups = cpu_count() + return min(len(sched_getaffinity(0)), cpu_count_cgroups) else: # Just an alias to cpu_count() (same docstring) process_cpu_count = cpu_count From 5e5e3f3b26276aa17a233416d93af4aab0017696 Mon Sep 17 00:00:00 2001 From: Itamar Turner-Trauring Date: Mon, 23 Nov 2026 16:32:53 -0500 Subject: [PATCH 03/17] Extend testing --- Lib/test/test_os/test_os.py | 75 +++++++++++++++++++++++++++---------- 1 file changed, 56 insertions(+), 19 deletions(-) diff --git a/Lib/test/test_os/test_os.py b/Lib/test/test_os/test_os.py index ca953964bbbbb7..5e32c3aafe1fe4 100644 --- a/Lib/test/test_os/test_os.py +++ b/Lib/test/test_os/test_os.py @@ -4693,31 +4693,68 @@ def test_process_cpu_count_cgroups(self): elif base_count < 2: self.skipTest("require at least 2 CPU cores to test") - # TODO test setting the period too - # TODO test nested cgroups - for setting, expected in [ + def get_systemd_args( + num_cpus, + cpu_period_ms=None, + python_code="import os; print(os.process_cpu_count())" + ): + result = [ + "systemd-run", + "--user", + # Technically only necessary for nested systemd-run, where we + # get the same auto-generat()ed unit name: + f"--unit=python-tests-{os.urandom(16).hex()}", + "--scope", + "--quiet", + "--property", + f"CPUQuota={int(100 * num_cpus)}%", + ] + if cpu_period_ms is not None: + result.extend([ + "--property", + f"CPUQuotaPeriodSec={cpu_period_ms}ms" + ]) + result.extend([ + "--", + sys.executable, + "-c", + python_code, + ]) + return result + + def run_and_get_int(command_args): + return int( + subprocess.check_output(command_args, encoding="utf-8").strip() + ) + + for set_num_cpus, expected in [ (0.01, 1), (0.5, 1), (1, 1), (1.5, 2), (base_count - 1, base_count - 1), ]: - result = int( - subprocess.check_output( - [ - "systemd-run", - "--user", - "--scope", - "--quiet", - "--property", - f"CPUQuota={int(100 * setting)}%", - "--", - sys.executable, - "-c", - "import os; print(os.process_cpu_count())", - ], - encoding="utf-8", - ).strip() + result = run_and_get_int(get_systemd_args(set_num_cpus)) + self.assertEqual(result, expected) + + # Changes to the quota's period are taken into account: + result = run_and_get_int(get_systemd_args(1, 30)) + self.assertEqual(result, 1) + + # Result is minimum of sched affinity and quota: + for affinity_cores, cgroups_cores, expected in [ + (1, 2, 1), + (2, 1, 1), + (2, 2, 2), + ]: + code = f"""\ +import os +mask = os.sched_getaffinity(0) +os.sched_setaffinity(0, list(mask)[:{affinity_cores}]) +print(os.process_cpu_count()) +""" + result = run_and_get_int( + get_systemd_args(cgroups_cores, python_code=code) ) self.assertEqual(result, expected) From 4b4fef767d7dbd0a150809812fc48a013473bbb7 Mon Sep 17 00:00:00 2001 From: Itamar Turner-Trauring Date: Mon, 23 Nov 2026 16:54:53 -0500 Subject: [PATCH 04/17] Documentation --- Doc/library/os.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Doc/library/os.rst b/Doc/library/os.rst index fff27b48ae989c..fdc50196391e67 100644 --- a/Doc/library/os.rst +++ b/Doc/library/os.rst @@ -6281,7 +6281,7 @@ Miscellaneous System Information Get the number of logical CPUs usable by the calling thread of the **current process**. Returns ``None`` if undetermined. It can be less than - :func:`cpu_count` depending on the CPU affinity. + :func:`cpu_count` depending on the CPU affinity and cgroups settings. The :func:`cpu_count` function can be used to get the number of logical CPUs in the **system**. From d87dc8f2c45c0de406fb6605f12b3bf73d64a2ba Mon Sep 17 00:00:00 2001 From: Itamar Turner-Trauring Date: Mon, 23 Nov 2026 17:03:36 -0500 Subject: [PATCH 05/17] Add changelog entry --- .../Library/2026-11-23-17-03-23.gh-issue-149452.zKhaUP.rst | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Misc/NEWS.d/next/Library/2026-11-23-17-03-23.gh-issue-149452.zKhaUP.rst diff --git a/Misc/NEWS.d/next/Library/2026-11-23-17-03-23.gh-issue-149452.zKhaUP.rst b/Misc/NEWS.d/next/Library/2026-11-23-17-03-23.gh-issue-149452.zKhaUP.rst new file mode 100644 index 00000000000000..a75a9bd5889a24 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-23-17-03-23.gh-issue-149452.zKhaUP.rst @@ -0,0 +1,3 @@ +:func:`os.process_cpu_count` will now respect cgroups-v2 CPU quotas on on +Linux. This includes CPU limits set by Docker, Kubernetes, and other tools +that rely on cgroups. From c087aaa0c530824e5c510494ce336aed0b19690f Mon Sep 17 00:00:00 2001 From: Itamar Turner-Trauring Date: Mon, 23 Nov 2026 17:18:35 -0500 Subject: [PATCH 06/17] Edits --- .../next/Library/2026-11-23-17-03-23.gh-issue-149452.zKhaUP.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Misc/NEWS.d/next/Library/2026-11-23-17-03-23.gh-issue-149452.zKhaUP.rst b/Misc/NEWS.d/next/Library/2026-11-23-17-03-23.gh-issue-149452.zKhaUP.rst index a75a9bd5889a24..4d6116c02b34f5 100644 --- a/Misc/NEWS.d/next/Library/2026-11-23-17-03-23.gh-issue-149452.zKhaUP.rst +++ b/Misc/NEWS.d/next/Library/2026-11-23-17-03-23.gh-issue-149452.zKhaUP.rst @@ -1,3 +1,3 @@ -:func:`os.process_cpu_count` will now respect cgroups-v2 CPU quotas on on +Fix :func:`os.process_cpu_count` to respect cgroups-v2 CPU quotas on Linux. This includes CPU limits set by Docker, Kubernetes, and other tools that rely on cgroups. From aed27cde4cb986e4db95dda5e65cc27d54d8ef03 Mon Sep 17 00:00:00 2001 From: Itamar Turner-Trauring Date: Mon, 23 Nov 2026 17:18:55 -0500 Subject: [PATCH 07/17] Wrap --- .../Library/2026-11-23-17-03-23.gh-issue-149452.zKhaUP.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Misc/NEWS.d/next/Library/2026-11-23-17-03-23.gh-issue-149452.zKhaUP.rst b/Misc/NEWS.d/next/Library/2026-11-23-17-03-23.gh-issue-149452.zKhaUP.rst index 4d6116c02b34f5..6a452324bc8c09 100644 --- a/Misc/NEWS.d/next/Library/2026-11-23-17-03-23.gh-issue-149452.zKhaUP.rst +++ b/Misc/NEWS.d/next/Library/2026-11-23-17-03-23.gh-issue-149452.zKhaUP.rst @@ -1,3 +1,3 @@ -Fix :func:`os.process_cpu_count` to respect cgroups-v2 CPU quotas on -Linux. This includes CPU limits set by Docker, Kubernetes, and other tools -that rely on cgroups. +Fix :func:`os.process_cpu_count` to respect cgroups-v2 CPU quotas on Linux. This +includes CPU limits set by Docker, Kubernetes, and other tools that rely on +cgroups. From ca83a22fb1027d9dcfd9f9714b5217684bba82ed Mon Sep 17 00:00:00 2001 From: Itamar Turner-Trauring Date: Tue, 24 Nov 2026 10:30:05 -0500 Subject: [PATCH 08/17] Apply batched suggestions from code review Co-authored-by: Victor Stinner --- Lib/os.py | 11 ++++++----- Lib/test/test_os/test_os.py | 4 ++-- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/Lib/os.py b/Lib/os.py index cc6c1ee1ef8dd4..ca457e4ad807e1 100644 --- a/Lib/os.py +++ b/Lib/os.py @@ -1327,7 +1327,7 @@ def _cpu_count_cgroups(): # from further away." So we have to pick the minimum. cpu_quota = min(num_cpus, cpu_quota) if cpu_quota == 1: - # Can't get any lower than 1: + # Can't get any lower than 1 return 1 # Move on to the parent cgroup, if any: @@ -1350,10 +1350,11 @@ def process_cpu_count(): Return the number of logical CPUs usable by the calling thread of the current process. Return None if indeterminable. """ - cpu_count_cgroups = _cpu_count_cgroups() - if cpu_count_cgroups is None: - cpu_count_cgroups = cpu_count() - return min(len(sched_getaffinity(0)), cpu_count_cgroups) + count = _cpu_count_cgroups() + if count is None: + count = cpu_count() + affinity_count = len(sched_getaffinity(0)) + return min(affinity_count, count) else: # Just an alias to cpu_count() (same docstring) process_cpu_count = cpu_count diff --git a/Lib/test/test_os/test_os.py b/Lib/test/test_os/test_os.py index 5e32c3aafe1fe4..391165245c00db 100644 --- a/Lib/test/test_os/test_os.py +++ b/Lib/test/test_os/test_os.py @@ -4690,7 +4690,7 @@ def test_process_cpu_count_cgroups(self): base_count = os.process_cpu_count() if base_count is None: self.skipTest("Could not determine the number of CPUs") - elif base_count < 2: + if base_count < 2: self.skipTest("require at least 2 CPU cores to test") def get_systemd_args( @@ -4738,7 +4738,7 @@ def run_and_get_int(command_args): self.assertEqual(result, expected) # Changes to the quota's period are taken into account: - result = run_and_get_int(get_systemd_args(1, 30)) + result = run_and_get_int(get_systemd_args(1, cpu_period_ms=30)) self.assertEqual(result, 1) # Result is minimum of sched affinity and quota: From e1245352e7349edb1034e62d8e6cc1acc1cdf2e9 Mon Sep 17 00:00:00 2001 From: Itamar Turner-Trauring Date: Tue, 24 Nov 2026 10:37:14 -0500 Subject: [PATCH 09/17] Explicitly return None --- Lib/os.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/Lib/os.py b/Lib/os.py index ca457e4ad807e1..91a5c613a9190b 100644 --- a/Lib/os.py +++ b/Lib/os.py @@ -1247,7 +1247,7 @@ def _get_cgroup2_mount_point(): mount_dir = mount_dir.replace(quoted, value) return mount_dir except OSError: - return + return None def _parse_cgroup2_cpu_max(filename): @@ -1261,11 +1261,11 @@ def _parse_cgroup2_cpu_max(filename): with open(filename) as fp: line = fp.readline() except OSError: - return + return None parts = line.split() if len(parts) != 2: - return + return None if parts[0] == "max": return cpu_count() @@ -1274,7 +1274,7 @@ def _parse_cgroup2_cpu_max(filename): quota = int(parts[0]) period = int(parts[1]) except ValueError: - return + return None # Rounds up in order to saturate CPUs if the quota is fractional: import math @@ -1287,13 +1287,13 @@ def _cpu_count_cgroups(): sched = sched_getscheduler(0) if sched in (SCHED_FIFO, SCHED_RR, SCHED_DEADLINE): - return + return None cgroup_subpath = None try: fp = open("/proc/self/cgroup") except OSError: - return + return None with fp: for line in fp: # Cgroups v2 format; see cgroups(7) man page, section on @@ -1302,11 +1302,11 @@ def _cpu_count_cgroups(): cgroup_subpath = line[3:].rstrip("\n") if cgroup_subpath is None: - return + return None cgroup2_mount_point = _get_cgroup2_mount_point() if cgroup2_mount_point is None: - return + return None # Traverse nested controllers, from child to parent, looking for a CPU # limit: @@ -1339,7 +1339,7 @@ def _cpu_count_cgroups(): return cpu_quota else: def _cpu_count_cgroups(): - return + return None if _exists('sched_getaffinity') and sys._get_cpu_count_config() < 0: From 9f63b4d6ec569d1690a70a38d5c7e547bb705b35 Mon Sep 17 00:00:00 2001 From: Itamar Turner-Trauring Date: Tue, 24 Nov 2026 10:44:31 -0500 Subject: [PATCH 10/17] Lazy imports --- Lib/os.py | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/Lib/os.py b/Lib/os.py index 91a5c613a9190b..5a919571336293 100644 --- a/Lib/os.py +++ b/Lib/os.py @@ -28,6 +28,9 @@ from _collections_abc import _check_methods +lazy from builtins import open as _builtins_open +lazy import math + GenericAlias = type(list[int]) _names = sys.builtin_module_names @@ -1227,13 +1230,11 @@ def add_dll_directory(path): if sys.platform == "linux": def _get_cgroup2_mount_point(): - from builtins import open - if path.exists("/sys/fs/cgroup/cgroup.controllers"): return "/sys/fs/cgroup" try: - with open("/proc/mounts") as fp: + with _builtins_open("/proc/mounts") as fp: for line in fp: parts = line.split() _, mount_dir, mount_type, *_ = parts @@ -1255,10 +1256,8 @@ def _parse_cgroup2_cpu_max(filename): Returns None if file not found or a parsing error, or a number of cores if successful. """ - from builtins import open - try: - with open(filename) as fp: + with _builtins_open(filename) as fp: line = fp.readline() except OSError: return None @@ -1277,21 +1276,17 @@ def _parse_cgroup2_cpu_max(filename): return None # Rounds up in order to saturate CPUs if the quota is fractional: - import math - return max(math.ceil(quota / period), 1) def _cpu_count_cgroups(): - from builtins import open - sched = sched_getscheduler(0) if sched in (SCHED_FIFO, SCHED_RR, SCHED_DEADLINE): return None cgroup_subpath = None try: - fp = open("/proc/self/cgroup") + fp = _builtins_open("/proc/self/cgroup") except OSError: return None with fp: From f07acca2df7f42e29d5c731f0a4d1dfa3b295d40 Mon Sep 17 00:00:00 2001 From: Itamar Turner-Trauring Date: Tue, 24 Nov 2026 10:48:33 -0500 Subject: [PATCH 11/17] Handle return of None from cpu_count(), theoretically possible --- Lib/os.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Lib/os.py b/Lib/os.py index 5a919571336293..cc7d76683bae7e 100644 --- a/Lib/os.py +++ b/Lib/os.py @@ -1345,10 +1345,12 @@ def process_cpu_count(): Return the number of logical CPUs usable by the calling thread of the current process. Return None if indeterminable. """ + affinity_count = len(sched_getaffinity(0)) count = _cpu_count_cgroups() if count is None: count = cpu_count() - affinity_count = len(sched_getaffinity(0)) + if count is None: + count = affinity_count return min(affinity_count, count) else: # Just an alias to cpu_count() (same docstring) From 8f1bb3c66d9775a8e0eb2ca5aceefe2d1533b996 Mon Sep 17 00:00:00 2001 From: Itamar Turner-Trauring Date: Tue, 24 Nov 2026 10:50:07 -0500 Subject: [PATCH 12/17] Add update of change --- Doc/library/os.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Doc/library/os.rst b/Doc/library/os.rst index fdc50196391e67..f09d6ef31e3d1f 100644 --- a/Doc/library/os.rst +++ b/Doc/library/os.rst @@ -6293,6 +6293,9 @@ Miscellaneous System Information .. versionadded:: 3.13 + .. versionchanged:: 3.16 + Previously cgroups CPU limits were not used. + .. function:: sysconf(name, /) From 833fcaf0b3de095ae9e403ebb9710cb3e244afe9 Mon Sep 17 00:00:00 2001 From: Itamar Turner-Trauring Date: Tue, 24 Nov 2026 10:51:34 -0500 Subject: [PATCH 13/17] Feature, not fix --- .../Library/2026-11-23-17-03-23.gh-issue-149452.zKhaUP.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Misc/NEWS.d/next/Library/2026-11-23-17-03-23.gh-issue-149452.zKhaUP.rst b/Misc/NEWS.d/next/Library/2026-11-23-17-03-23.gh-issue-149452.zKhaUP.rst index 6a452324bc8c09..0c9d10ff2b3790 100644 --- a/Misc/NEWS.d/next/Library/2026-11-23-17-03-23.gh-issue-149452.zKhaUP.rst +++ b/Misc/NEWS.d/next/Library/2026-11-23-17-03-23.gh-issue-149452.zKhaUP.rst @@ -1,3 +1,3 @@ -Fix :func:`os.process_cpu_count` to respect cgroups-v2 CPU quotas on Linux. This -includes CPU limits set by Docker, Kubernetes, and other tools that rely on +Add support for cgroups v2 CPU quotas on Linux to :func:`os.process_cpu_count`. +This includes CPU limits set by Docker, Kubernetes, and other tools that rely on cgroups. From 5bdfa8ae77c7b5f3cbfb50ffdc30c648ca73312c Mon Sep 17 00:00:00 2001 From: Itamar Turner-Trauring Date: Tue, 24 Nov 2026 12:50:29 -0500 Subject: [PATCH 14/17] Split into its own function, unit test --- Lib/os.py | 23 +++++++++++++++-------- Lib/test/test_os/test_os.py | 10 ++++++++++ 2 files changed, 25 insertions(+), 8 deletions(-) diff --git a/Lib/os.py b/Lib/os.py index cc7d76683bae7e..29db6beab5dbb6 100644 --- a/Lib/os.py +++ b/Lib/os.py @@ -1229,6 +1229,20 @@ def add_dll_directory(path): if sys.platform == "linux": + def _unquote_mount_path(path): + """Decode quoted characters in /etc/fstab, /proc/mounts, and the like. + + See https://man7.org/linux/man-pages/man5/fstab.5.html + """ + for quoted, value in [ + (r"\040", " "), + (r"\011", "\t"), + (r"\012", "\n"), + (r"\134", "\\"), + ]: + path = path.replace(quoted, value) + return path + def _get_cgroup2_mount_point(): if path.exists("/sys/fs/cgroup/cgroup.controllers"): return "/sys/fs/cgroup" @@ -1239,14 +1253,7 @@ def _get_cgroup2_mount_point(): parts = line.split() _, mount_dir, mount_type, *_ = parts if mount_type == "cgroup2": - for quoted, value in [ - (r"\040", " "), - (r"\011", "\t"), - (r"\012", "\n"), - (r"\134", "\\"), - ]: - mount_dir = mount_dir.replace(quoted, value) - return mount_dir + return _unquote_mount_path(mount_dir) except OSError: return None diff --git a/Lib/test/test_os/test_os.py b/Lib/test/test_os/test_os.py index 391165245c00db..68a278dd9b84d6 100644 --- a/Lib/test/test_os/test_os.py +++ b/Lib/test/test_os/test_os.py @@ -4687,6 +4687,7 @@ def test_process_cpu_count_affinity(self): "testing cgroups requires Linux with systemd-run", ) def test_process_cpu_count_cgroups(self): + """``os.process_cpu_count()`` respects cgroups v2 limits.""" base_count = os.process_cpu_count() if base_count is None: self.skipTest("Could not determine the number of CPUs") @@ -4758,6 +4759,15 @@ def run_and_get_int(command_args): ) self.assertEqual(result, expected) + @unittest.skipUnless( + sys.platform == "linux", "Linux-specific functionality", + ) + def test_unquote_mount_path(self): + """``os._unquote_mount_path()`` decodes correctly.""" + original_path = "/foo/bar\\\n \t" + encoded_path = r"/foo/bar\134\012\040\011" + self.assertEqual(os._unquote_mount_path(encoded_path), original_path) + # FD inheritance check is only useful for systems with process support. @support.requires_subprocess() From 87dd48f6bfcd7be6c057f5f3980edf2f6881802c Mon Sep 17 00:00:00 2001 From: Itamar Turner-Trauring Date: Tue, 24 Nov 2026 12:51:27 -0500 Subject: [PATCH 15/17] Don't call cpu_count() in this function --- Lib/os.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Lib/os.py b/Lib/os.py index 29db6beab5dbb6..df4e44f30e764f 100644 --- a/Lib/os.py +++ b/Lib/os.py @@ -1312,7 +1312,7 @@ def _cpu_count_cgroups(): # Traverse nested controllers, from child to parent, looking for a CPU # limit: - cpu_quota = cpu_count() + cpu_quota = None while True: cpu_max_filename = path.join( cgroup2_mount_point, @@ -1327,6 +1327,8 @@ def _cpu_count_cgroups(): # the resource distribution further. The restrictions set # closer to the root in the hierarchy can not be overridden # from further away." So we have to pick the minimum. + if cpu_quota is None: + cpu_quota = num_cpus cpu_quota = min(num_cpus, cpu_quota) if cpu_quota == 1: # Can't get any lower than 1 From 5b97143169d8ddd7c94469d0f54d73da3dbf940c Mon Sep 17 00:00:00 2001 From: Itamar Turner-Trauring Date: Tue, 24 Nov 2026 13:42:19 -0500 Subject: [PATCH 16/17] Add tests for missing files, and for parsing /proc/mounts --- Lib/os.py | 8 +++---- Lib/test/test_os/test_os.py | 45 ++++++++++++++++++++++++++++++++++++- 2 files changed, 48 insertions(+), 5 deletions(-) diff --git a/Lib/os.py b/Lib/os.py index df4e44f30e764f..cad7fdd9985c3c 100644 --- a/Lib/os.py +++ b/Lib/os.py @@ -28,7 +28,7 @@ from _collections_abc import _check_methods -lazy from builtins import open as _builtins_open +lazy import builtins lazy import math GenericAlias = type(list[int]) @@ -1248,7 +1248,7 @@ def _get_cgroup2_mount_point(): return "/sys/fs/cgroup" try: - with _builtins_open("/proc/mounts") as fp: + with builtins.open("/proc/mounts") as fp: for line in fp: parts = line.split() _, mount_dir, mount_type, *_ = parts @@ -1264,7 +1264,7 @@ def _parse_cgroup2_cpu_max(filename): if successful. """ try: - with _builtins_open(filename) as fp: + with builtins.open(filename) as fp: line = fp.readline() except OSError: return None @@ -1293,7 +1293,7 @@ def _cpu_count_cgroups(): cgroup_subpath = None try: - fp = _builtins_open("/proc/self/cgroup") + fp = builtins.open("/proc/self/cgroup") except OSError: return None with fp: diff --git a/Lib/test/test_os/test_os.py b/Lib/test/test_os/test_os.py index 68a278dd9b84d6..790eb31d150793 100644 --- a/Lib/test/test_os/test_os.py +++ b/Lib/test/test_os/test_os.py @@ -3,6 +3,7 @@ # portable than they had been thought to be. import asyncio +import builtins import codecs import contextlib import decimal @@ -28,6 +29,7 @@ import time import types import unittest +import unittest.mock import uuid import warnings from test import support @@ -4682,11 +4684,52 @@ def test_process_cpu_count_affinity(self): affinity2 = os.process_cpu_count() self.assertEqual(affinity2, affinity1 - 1) + @unittest.skipUnless(sys.platform == "linux", "Requires Linux") + def test_missing_cgroups_files(self): + original_open = builtins.open + original_exists = os.path.exists + + def force_proc_mounts_parsing_exists(path): + if path == "/sys/fs/cgroup/cgroup.controllers": + return False + return original_exists(path) + + with unittest.mock.patch( + "os.path.exists", + force_proc_mounts_parsing_exists + ): + # /proc/mounts parsing correctly identifies where cgroup sysfs is + # mounted + sysfs_cgroup_path = os._get_cgroup2_mount_point() + if sysfs_cgroup_path is None: + # 99% of the time will be /sys/fs/cgroup, so if we failed to + # find it, that better not exist! + self.assertFalse(original_exists("/sys/fs/cgroup")) + else: + self.assertTrue( + original_exists( + os.path.join(sysfs_cgroup_path, "cgroup.controllers") + ) + ) + + for path_to_fail in [ + "/proc/self/cgroup", + "/proc/mounts", + os._get_cgroup2_mount_point() + ]: + def might_fail_to_open(path, *args, **kwargs): + if path.startswith(path_to_fail): + raise OSError("disabled for test") + else: + return original_open(path, *args, **kwargs) + with unittest.mock.patch("builtins.open", might_fail_to_open): + self.assertIsNone(os._cpu_count_cgroups()) + @unittest.skipUnless( sys.platform == "linux" and shutil.which("systemd-run") is not None, "testing cgroups requires Linux with systemd-run", ) - def test_process_cpu_count_cgroups(self): + def test_process_cpu_count_cgroups_end_to_end(self): """``os.process_cpu_count()`` respects cgroups v2 limits.""" base_count = os.process_cpu_count() if base_count is None: From d47c4dcf17dc5f9b63be9b0b7262dc2861860445 Mon Sep 17 00:00:00 2001 From: Itamar Turner-Trauring Date: Tue, 24 Nov 2026 13:52:26 -0500 Subject: [PATCH 17/17] Move some testing out of end-to-end and into direct testing --- Lib/test/test_os/test_os.py | 38 ++++++++++++++++++++++++++++--------- 1 file changed, 29 insertions(+), 9 deletions(-) diff --git a/Lib/test/test_os/test_os.py b/Lib/test/test_os/test_os.py index 790eb31d150793..85b3fd6ddc65ae 100644 --- a/Lib/test/test_os/test_os.py +++ b/Lib/test/test_os/test_os.py @@ -4725,6 +4725,30 @@ def might_fail_to_open(path, *args, **kwargs): with unittest.mock.patch("builtins.open", might_fail_to_open): self.assertIsNone(os._cpu_count_cgroups()) + @unittest.skipUnless(sys.platform == "linux", "Requires Linux") + def test_cpu_count_parse_cpu_max(self): + for cpu_max_contents, expected_n_cpus in [ + # max means all cores + ("max 100000", os.cpu_count()), + # garbage + ("garbage garbage", None), + # too many numbers + ("123 123 123", None), + # less than one core means one core + ("1000 100000", 1), + # One or more cores, rounding up: + ("100000 100000", 1), + ("200000 100000", 2), + ("230000 100000", 3), + # Divide by quota: + ("100000 50000", 2), + ]: + with tempfile.NamedTemporaryFile("w") as f: + f.write(cpu_max_contents) + f.flush() + result = os._parse_cgroup2_cpu_max(f.name) + self.assertEqual(result, expected_n_cpus) + @unittest.skipUnless( sys.platform == "linux" and shutil.which("systemd-run") is not None, "testing cgroups requires Linux with systemd-run", @@ -4771,15 +4795,11 @@ def run_and_get_int(command_args): subprocess.check_output(command_args, encoding="utf-8").strip() ) - for set_num_cpus, expected in [ - (0.01, 1), - (0.5, 1), - (1, 1), - (1.5, 2), - (base_count - 1, base_count - 1), - ]: - result = run_and_get_int(get_systemd_args(set_num_cpus)) - self.assertEqual(result, expected) + # Base setting of number of cores: + result = run_and_get_int(get_systemd_args(1)) + self.assertEqual(result, 1) + result = run_and_get_int(get_systemd_args(2)) + self.assertEqual(result, 2) # Changes to the quota's period are taken into account: result = run_and_get_int(get_systemd_args(1, cpu_period_ms=30))