From 59200ea9494dc9d05b57679fa6ba6ca7cbc48887 Mon Sep 17 00:00:00 2001 From: "Christoph Engelbert (noctarius)" Date: Fri, 20 Nov 2026 07:32:47 +0100 Subject: [PATCH 1/2] fix(snode): size a Kubernetes worker's huge pages from the pods' requests apply_config treated every huge page a worker carried before simplyblock as the host's own and added simplyblock's pages on top. On Kubernetes that pool is accounted for: a pod can use only the hugepages-2Mi it requests, so pages no pod requests are unused. apply_config now lists the pods on the node, leaves simplyblock's storage pods out, and keeps the host's share at no more than what the others request. A pool that already holds both is left as it is; one that does not grows by the shortfall. When the pods cannot be listed, the previous behavior stays. The e2e lblk run 44678939560 reserved 7958 pages that no pod requested; apply_config raised the pool to 12028 (23.5 GiB of 31 GiB), the kubelet took all of it out of the node's memory, and the SPDK pod stayed Pending on "Insufficient memory" until the run timed out. Co-Authored-By: Claude Opus 5.5 --- simplyblock_core/utils/__init__.py | 23 ++- .../api/internal/storage_node/kubernetes.py | 51 +++++- tests/unit/test_hugepages_kube_accounting.py | 156 ++++++++++++++++++ tests/unit/test_talos_hugepages.py | 1 + 4 files changed, 225 insertions(+), 6 deletions(-) create mode 100644 tests/unit/test_hugepages_kube_accounting.py diff --git a/simplyblock_core/utils/__init__.py b/simplyblock_core/utils/__init__.py index a403c78c59..b8635324aa 100644 --- a/simplyblock_core/utils/__init__.py +++ b/simplyblock_core/utils/__init__.py @@ -3456,8 +3456,16 @@ def user_hugepages_baseline(node, current_hugepages, state_dir: str | None = Non return max(current_user, 0) -def set_hugepages_if_needed(node, hugepages_needed, page_size_kb=2048): - """Set hugepages for a specific NUMA node, adjusting up or down based on previous allocation.""" +def set_hugepages_if_needed(node, hugepages_needed, page_size_kb=2048, claimed_by_others=None): + """Set hugepages for a specific NUMA node, adjusting up or down based on previous allocation. + + ``claimed_by_others`` is the 2 MiB pages other workloads are known to use, + where something accounts for them: on Kubernetes, the hugepages-2Mi the + node's pods request (a pod can use no more). The host's own share is then + at most that many pages, and a pool that already holds them beside + simplyblock's is left as it is -- grown only by the shortfall, never + shrunk. Without it the whole pool the host carried before simplyblock is + the host's, and simplyblock's pages go on top.""" hugepage_path = _nr_hugepages_path(node, page_size_kb) try: @@ -3465,10 +3473,15 @@ def set_hugepages_if_needed(node, hugepages_needed, page_size_kb=2048): current_hugepages = int(f.read().strip()) current_user = user_hugepages_baseline(node, current_hugepages) + if claimed_by_others is not None: + current_user = min(current_user, claimed_by_others) - # The final total can never drop below what simplyblock itself needs. - required = adjust_hugepages(current_user + hugepages_needed) - required = max(required, hugepages_needed) + if claimed_by_others is not None and current_hugepages >= current_user + hugepages_needed: + required = current_hugepages + else: + # The final total can never drop below what simplyblock itself needs. + required = adjust_hugepages(current_user + hugepages_needed) + required = max(required, hugepages_needed) logger.debug(f"Node {node}: setting to {required} (user={current_user} + simplyblock={hugepages_needed})") if current_hugepages != required: diff --git a/simplyblock_web/api/internal/storage_node/kubernetes.py b/simplyblock_web/api/internal/storage_node/kubernetes.py index e8d58b5536..6f4376c923 100644 --- a/simplyblock_web/api/internal/storage_node/kubernetes.py +++ b/simplyblock_web/api/internal/storage_node/kubernetes.py @@ -749,6 +749,54 @@ def _hugepages_per_numa(nodes): return {numa: mem // 2000000 for numa, mem in per_numa_bytes.items()} +_STORAGE_POD_LABEL = ("role", "simplyblock-storage-node") + + +def _pod_hugepages_mib(pod): + """The hugepages-2Mi a pod requests, in MiB, the way the scheduler counts + it: the larger of its containers' sum and its largest init container.""" + def requested(container): + resources = container.resources + if resources is None: + return 0 + # Kubernetes requires a huge-page request to equal its limit, and + # defaults the request to the limit when only the limit is given. + quantity = (resources.requests or {}).get('hugepages-2Mi') or (resources.limits or {}).get('hugepages-2Mi') + return _quantity_to_mib(quantity) + + spec = pod.spec + containers = sum(requested(c) for c in spec.containers or []) + init = max((requested(c) for c in spec.init_containers or []), default=0) + return max(containers, init) + + +def _hugepages_claimed_by_other_pods(node_name): + """The 2 MiB pages the pods on ``node_name`` request, simplyblock's own + storage pods left out, or None when Kubernetes cannot say. + + The kubelet sets every container's hugetlb limit to its request, so no pod + uses more than this: whatever else the host's pool holds is unused, and + simplyblock may count on it. The storage pods are left out because their + pages are the ones apply_config is sizing. A pod that has finished holds + nothing.""" + if not node_name: + return None + try: + pods = core_utils.get_k8s_core_client().list_pod_for_all_namespaces( + field_selector=f"spec.nodeName={node_name}").items + except Exception as e: + logger.warning("Cannot list the pods on '%s' (%s): the huge pages the host carries are kept as its own", + node_name, e) + return None + key, value = _STORAGE_POD_LABEL + mib = sum(_pod_hugepages_mib(pod) for pod in pods + if (pod.status is None or pod.status.phase not in ("Succeeded", "Failed")) + and (pod.metadata.labels or {}).get(key) != value) + pages = -(-mib // 2) # ceil + logger.info("Pods on '%s' other than simplyblock's request %d huge pages", node_name, pages) + return pages + + def _talos_sysfs_patch(pages_per_numa): """The strategic-merge machine-config patch that reserves the pages. @@ -1703,8 +1751,9 @@ def apply_config(): return utils.get_response(False, "Config validation is incorrect") # Set Huge page memory + claimed = _hugepages_claimed_by_other_pods(os.environ.get("HOSTNAME", "")) for numa, num_pages in _hugepages_per_numa(nodes).items(): - core_utils.set_hugepages_if_needed(numa, num_pages) + core_utils.set_hugepages_if_needed(numa, num_pages, claimed_by_others=claimed) return utils.get_response(True) diff --git a/tests/unit/test_hugepages_kube_accounting.py b/tests/unit/test_hugepages_kube_accounting.py new file mode 100644 index 0000000000..6cd22786ef --- /dev/null +++ b/tests/unit/test_hugepages_kube_accounting.py @@ -0,0 +1,156 @@ +"""apply_config on a Kubernetes worker sizes the huge-page pool from what +Kubernetes says the pool's pages are claimed by, not from what the host carried +the first time simplyblock saw it. + +Regression: e2e run 44678939560 (lblk, 2026-11-20). The test bootstrap reserved +half of a 31 GiB worker as huge pages, 7958 pages that no pod requested. The init +Job recorded them as the host's own and apply_config added simplyblock's 3990 on +top: 12028 pages, 23.5 GiB. The kubelet takes the whole pool out of the node's +memory, used or not, so 7.6 GiB was left for pods, and the SPDK pod's 2188 MiB did +not fit beside the 5.9 GiB the control-plane pods on that worker requested. It +stayed Pending on 'Insufficient memory' until the run timed out. + +A pod can use only the huge pages it requests (the kubelet sets every container's +hugetlb limit to its request), so the requests of the pods on the node are what +the pool is claimed by. simplyblock's own storage pods are left out of that sum: +their pages are the ones being sized. +""" +import os +from unittest.mock import MagicMock, patch + +import pytest +from kubernetes.client import ( + ApiException, + V1Container, + V1ObjectMeta, + V1Pod, + V1PodSpec, + V1PodStatus, + V1ResourceRequirements, +) + +from simplyblock_core import utils +from simplyblock_web.api.internal.storage_node import kubernetes as k8s_node + +WORKER = "githubactions-lblk-storage-node-1" + +#: The node config the e2e run's worker carried: 6.5 GiB of huge pages for SPDK, +#: which apply_config turns into 3990 pages on NUMA node 0. +NODE_CONFIG = {"huge_page_memory": 6980607384, "max_size": 0, "socket": 0} + +#: What the bootstrap reserved on that worker before simplyblock arrived. +HOST_RESERVED = 7958 + + +class _Host: + """One NUMA node's huge-page count and simplyblock's records, under a directory.""" + + def __init__(self, root): + self.records = os.path.join(root, "run") + self.count_file = os.path.join(root, "nr_hugepages") + os.makedirs(self.records) + + def _count_path(self, node, page_size_kb=2048): + return self.count_file + + def count(self): + with open(self.count_file) as f: + return int(f.read()) + + def set_count(self, pages): + with open(self.count_file, "w") as f: + f.write(f"{pages}\n") + + def _kernel_write(self, node, pages, page_size_kb=2048): + self.set_count(int(pages)) + + def record_baseline(self, pages): + """What the init Job writes before it calls apply_config.""" + with open(os.path.join(self.records, "hugepages_baseline_node0"), "w") as f: + f.write(str(pages)) + + +def _pod(name, hugepages=None, phase="Running", labels=None): + requests = {"memory": "256Mi"} + if hugepages: + requests["hugepages-2Mi"] = hugepages + return V1Pod( + metadata=V1ObjectMeta(name=name, namespace="simplyblock", labels=labels or {}), + spec=V1PodSpec(node_name=WORKER, containers=[ + V1Container(name="c", resources=V1ResourceRequirements(requests=requests, limits=dict(requests)))]), + status=V1PodStatus(phase=phase)) + + +@pytest.fixture +def host(tmp_path): + h = _Host(str(tmp_path)) + h.set_count(HOST_RESERVED) + h.record_baseline(HOST_RESERVED) + with patch.object(utils, "_HUGEPAGES_BASELINE_DIR", h.records), \ + patch.object(utils, "_nr_hugepages_path", h._count_path), \ + patch.object(utils, "_write_nr_hugepages", h._kernel_write): + yield h + + +def _apply_config(pods=None, error=None): + core = MagicMock() + if error is not None: + core.list_pod_for_all_namespaces.side_effect = error + else: + core.list_pod_for_all_namespaces.return_value = MagicMock(items=pods or []) + with patch.dict(os.environ, {"HOSTNAME": WORKER}), \ + patch.object(k8s_node.core_utils, "get_k8s_core_client", return_value=core), \ + patch.object(k8s_node.core_utils, "load_config", return_value={"nodes": [NODE_CONFIG]}), \ + patch.object(k8s_node.core_utils, "validate_config", return_value=True), \ + patch.object(k8s_node.utils, "get_response", side_effect=lambda d, error=None, http_code=None: (d, error)): + k8s_node.apply_config() + return core + + +def test_unclaimed_host_pages_cover_simplyblock_and_the_pool_is_left_alone(host): + """The e2e run: 7958 pages, none requested by a pod, 3990 needed.""" + core = _apply_config(pods=[_pod("prometheus-0"), _pod("webappapi")]) + + assert host.count() == HOST_RESERVED + core.list_pod_for_all_namespaces.assert_called_once_with(field_selector=f"spec.nodeName={WORKER}") + + +def test_pages_other_pods_request_are_kept_beside_simplyblocks(host): + """2000 pages claimed by another workload plus 3990 for simplyblock still + fit in the 7958 the host carries.""" + _apply_config(pods=[_pod("dpdk-app", hugepages="4000Mi")]) + + assert host.count() == HOST_RESERVED + + +def test_the_pool_grows_when_other_pods_and_simplyblock_do_not_fit(host): + """6000 pages claimed by another workload plus 3990 for simplyblock is more + than the 7958 the host carries: the pool grows to cover both.""" + _apply_config(pods=[_pod("dpdk-app", hugepages="12000Mi")]) + + assert host.count() == utils.adjust_hugepages(6000 + 3990) + + +def test_simplyblocks_own_storage_pods_are_not_counted_as_claims(host): + """A storage pod of this host, left over from the previous attempt, holds + pages that are the ones being sized: counting it would grow the pool by + simplyblock's need twice.""" + spdk = _pod("snode-spdk-pod-4420-9290ee", hugepages="7170Mi", labels={"role": "simplyblock-storage-node"}) + _apply_config(pods=[spdk]) + + assert host.count() == HOST_RESERVED + + +def test_finished_pods_claim_nothing(host): + _apply_config(pods=[_pod("old-job", hugepages="12000Mi", phase="Succeeded"), + _pod("failed-job", hugepages="12000Mi", phase="Failed")]) + + assert host.count() == HOST_RESERVED + + +def test_without_the_kubernetes_accounting_the_host_reservation_is_kept(host): + """When the pods cannot be listed, nothing says who uses the host's pages: + they stay the host's, and simplyblock's go on top as before.""" + _apply_config(error=ApiException(status=403, reason="Forbidden")) + + assert host.count() == utils.adjust_hugepages(HOST_RESERVED + 3990) diff --git a/tests/unit/test_talos_hugepages.py b/tests/unit/test_talos_hugepages.py index 993b011f1d..a311f2d061 100644 --- a/tests/unit/test_talos_hugepages.py +++ b/tests/unit/test_talos_hugepages.py @@ -763,6 +763,7 @@ def test_apply_config_writes_the_shared_sizing(self): with patch.object(k8s_node.core_utils, 'load_config', return_value={"nodes": nodes}), \ patch.object(k8s_node.core_utils, 'validate_config', return_value=True), \ patch.object(k8s_node.core_utils, 'set_hugepages_if_needed') as set_hp, \ + patch.object(k8s_node, '_hugepages_claimed_by_other_pods', return_value=None), \ patch.object(k8s_node.utils, 'get_response', side_effect=lambda d, error=None, http_code=None: (d, error)): k8s_node.apply_config() self.assertEqual([c.args for c in set_hp.call_args_list], From 70e7cfd20eec758ba5c7d7e6da661a3b0d2c524f Mon Sep 17 00:00:00 2001 From: "Christoph Engelbert (noctarius)" Date: Fri, 20 Nov 2026 07:44:22 +0100 Subject: [PATCH 2/2] fix(snode): count every pod claim and keep it across a release Three gaps in the pod accounting, from the review of #1698: - The pods' claim was capped at the recorded baseline. On a host that reserved nothing itself, a pool simplyblock had grown to 4096 and a pod claiming 2000 of it was left at 4096, short of the 2000 beside simplyblock's 3990. The claim is now the host's share as it stands, and a claim above the baseline raises the baseline, so release_hugepages leaves those pages to the host. - Requests were read with the MiB-only converter, which raised on valid quantities such as 4194304k outside the error handling and failed apply_config. They are now parsed with kubernetes.utils.parse_quantity, inside the handler. - Native sidecars (init containers with restartPolicy Always) were counted like init containers that finish. They now add to the app containers and to every init container started after them, as the scheduler counts them. Co-Authored-By: Claude Opus 5.5 --- simplyblock_core/utils/__init__.py | 16 +++-- .../api/internal/storage_node/kubernetes.py | 38 +++++++----- tests/unit/test_hugepages_kube_accounting.py | 58 +++++++++++++++++-- 3 files changed, 89 insertions(+), 23 deletions(-) diff --git a/simplyblock_core/utils/__init__.py b/simplyblock_core/utils/__init__.py index b8635324aa..6d80aacca3 100644 --- a/simplyblock_core/utils/__init__.py +++ b/simplyblock_core/utils/__init__.py @@ -3461,11 +3461,13 @@ def set_hugepages_if_needed(node, hugepages_needed, page_size_kb=2048, claimed_b ``claimed_by_others`` is the 2 MiB pages other workloads are known to use, where something accounts for them: on Kubernetes, the hugepages-2Mi the - node's pods request (a pod can use no more). The host's own share is then - at most that many pages, and a pool that already holds them beside + node's pods request (a pod can use no more). The host's share is then + exactly that many pages, and a pool that already holds them beside simplyblock's is left as it is -- grown only by the shortfall, never - shrunk. Without it the whole pool the host carried before simplyblock is - the host's, and simplyblock's pages go on top.""" + shrunk. A claim above the recorded baseline raises the baseline, so + release_hugepages leaves those pages to the host. Without it the whole + pool the host carried before simplyblock is the host's, and simplyblock's + pages go on top.""" hugepage_path = _nr_hugepages_path(node, page_size_kb) try: @@ -3474,7 +3476,11 @@ def set_hugepages_if_needed(node, hugepages_needed, page_size_kb=2048, claimed_b current_user = user_hugepages_baseline(node, current_hugepages) if claimed_by_others is not None: - current_user = min(current_user, claimed_by_others) + if claimed_by_others > current_user: + _save_user_hugepages_baseline(node, claimed_by_others) + logger.info(f"Node {node}: user hugepage baseline raised {current_user} -> {claimed_by_others} " + f"to the pages other pods request") + current_user = claimed_by_others if claimed_by_others is not None and current_hugepages >= current_user + hugepages_needed: required = current_hugepages diff --git a/simplyblock_web/api/internal/storage_node/kubernetes.py b/simplyblock_web/api/internal/storage_node/kubernetes.py index 6f4376c923..a89603e2b3 100644 --- a/simplyblock_web/api/internal/storage_node/kubernetes.py +++ b/simplyblock_web/api/internal/storage_node/kubernetes.py @@ -9,6 +9,7 @@ from flask_openapi3 import APIBlueprint from jinja2 import Environment, PackageLoader from kubernetes.client import ApiException, V1DeleteOptions +from kubernetes.utils import parse_quantity from pydantic import BaseModel, Field from tenacity import ( RetryError, @@ -752,9 +753,12 @@ def _hugepages_per_numa(nodes): _STORAGE_POD_LABEL = ("role", "simplyblock-storage-node") -def _pod_hugepages_mib(pod): - """The hugepages-2Mi a pod requests, in MiB, the way the scheduler counts - it: the larger of its containers' sum and its largest init container.""" +def _pod_hugepages_bytes(pod): + """The hugepages-2Mi a pod requests, in bytes, the way the scheduler counts + it. Native sidecars (init containers with restartPolicy Always) run from + their start to the pod's end, so they add to the app containers and to + every init container after them; any other init container claims only + while it runs, before the app containers start.""" def requested(container): resources = container.resources if resources is None: @@ -762,12 +766,18 @@ def requested(container): # Kubernetes requires a huge-page request to equal its limit, and # defaults the request to the limit when only the limit is given. quantity = (resources.requests or {}).get('hugepages-2Mi') or (resources.limits or {}).get('hugepages-2Mi') - return _quantity_to_mib(quantity) + return parse_quantity(quantity) if quantity else 0 spec = pod.spec - containers = sum(requested(c) for c in spec.containers or []) - init = max((requested(c) for c in spec.init_containers or []), default=0) - return max(containers, init) + sidecars = 0 + init_peak = 0 + for container in spec.init_containers or []: + if container.restart_policy == "Always": + sidecars += requested(container) + init_peak = max(init_peak, sidecars) + else: + init_peak = max(init_peak, sidecars + requested(container)) + return max(sum(requested(c) for c in spec.containers or []) + sidecars, init_peak) def _hugepages_claimed_by_other_pods(node_name): @@ -781,18 +791,18 @@ def _hugepages_claimed_by_other_pods(node_name): nothing.""" if not node_name: return None + key, value = _STORAGE_POD_LABEL try: pods = core_utils.get_k8s_core_client().list_pod_for_all_namespaces( field_selector=f"spec.nodeName={node_name}").items + claimed = sum(_pod_hugepages_bytes(pod) for pod in pods + if (pod.status is None or pod.status.phase not in ("Succeeded", "Failed")) + and (pod.metadata.labels or {}).get(key) != value) except Exception as e: - logger.warning("Cannot list the pods on '%s' (%s): the huge pages the host carries are kept as its own", - node_name, e) + logger.warning("Cannot count the huge pages the pods on '%s' request (%s): the huge pages the host " + "carries are kept as its own", node_name, e) return None - key, value = _STORAGE_POD_LABEL - mib = sum(_pod_hugepages_mib(pod) for pod in pods - if (pod.status is None or pod.status.phase not in ("Succeeded", "Failed")) - and (pod.metadata.labels or {}).get(key) != value) - pages = -(-mib // 2) # ceil + pages = int(-(-claimed // (2 * 1024 * 1024))) # ceil logger.info("Pods on '%s' other than simplyblock's request %d huge pages", node_name, pages) return pages diff --git a/tests/unit/test_hugepages_kube_accounting.py b/tests/unit/test_hugepages_kube_accounting.py index 6cd22786ef..7993bf2f5a 100644 --- a/tests/unit/test_hugepages_kube_accounting.py +++ b/tests/unit/test_hugepages_kube_accounting.py @@ -66,18 +66,25 @@ def _kernel_write(self, node, pages, page_size_kb=2048): def record_baseline(self, pages): """What the init Job writes before it calls apply_config.""" - with open(os.path.join(self.records, "hugepages_baseline_node0"), "w") as f: + self.record("baseline", pages) + + def record(self, kind, pages): + with open(os.path.join(self.records, f"hugepages_{kind}_node0"), "w") as f: f.write(str(pages)) -def _pod(name, hugepages=None, phase="Running", labels=None): +def _container(name, hugepages=None, restart_policy=None): requests = {"memory": "256Mi"} if hugepages: requests["hugepages-2Mi"] = hugepages + return V1Container(name=name, restart_policy=restart_policy, + resources=V1ResourceRequirements(requests=requests, limits=dict(requests))) + + +def _pod(name, hugepages=None, phase="Running", labels=None, init_containers=None): return V1Pod( metadata=V1ObjectMeta(name=name, namespace="simplyblock", labels=labels or {}), - spec=V1PodSpec(node_name=WORKER, containers=[ - V1Container(name="c", resources=V1ResourceRequirements(requests=requests, limits=dict(requests)))]), + spec=V1PodSpec(node_name=WORKER, containers=[_container("c", hugepages)], init_containers=init_containers), status=V1PodStatus(phase=phase)) @@ -154,3 +161,46 @@ def test_without_the_kubernetes_accounting_the_host_reservation_is_kept(host): _apply_config(error=ApiException(status=403, reason="Forbidden")) assert host.count() == utils.adjust_hugepages(HOST_RESERVED + 3990) + + +def test_a_claim_above_the_hosts_own_share_is_kept_and_survives_the_release(host): + """The host reserved nothing itself, simplyblock grew the pool to 4096 + earlier, and a pod has since claimed 2000 of it: 4096 does not hold the + claim beside simplyblock's 3990, so the pool grows. The claim also becomes + the host's share, so giving simplyblock's pages back later leaves it.""" + host.set_count(4096) + host.record_baseline(0) + host.record("sb", 4096) + + _apply_config(pods=[_pod("dpdk-app", hugepages="4000Mi")]) + + assert host.count() == utils.adjust_hugepages(2000 + 3990) + assert utils.release_hugepages() == {0: 2000} + assert host.count() == 2000 + + +def test_a_decimal_quantity_is_read_like_a_binary_one(host): + """4194304k is 4194304000 bytes, exactly 2000 pages of 2 MiB: a valid + hugepages-2Mi request, counted like 4000Mi.""" + _apply_config(pods=[_pod("dpdk-app", hugepages="4194304k")]) + + assert host.count() == HOST_RESERVED + + +def test_a_native_sidecar_claims_beside_the_containers_it_runs_with(host): + """An init container with restartPolicy Always runs for the pod's whole + life: 6000Mi beside the app's 6000Mi is 6000 pages, which with + simplyblock's 3990 no longer fit in 7958.""" + sidecar = _container("proxy", hugepages="6000Mi", restart_policy="Always") + _apply_config(pods=[_pod("dpdk-app", hugepages="6000Mi", init_containers=[sidecar])]) + + assert host.count() == utils.adjust_hugepages(6000 + 3990) + + +def test_an_init_container_that_ends_claims_only_while_it_runs(host): + """A plain init container finishes before the app starts: the pod claims + the larger of the two, 3000 pages, which fit beside simplyblock's 3990.""" + init = _container("setup", hugepages="6000Mi") + _apply_config(pods=[_pod("dpdk-app", hugepages="6000Mi", init_containers=[init])]) + + assert host.count() == HOST_RESERVED