diff --git a/.github/codeowners/areas.yaml b/.github/codeowners/areas.yaml index b4763efd40a1..f8caffaa5a65 100644 --- a/.github/codeowners/areas.yaml +++ b/.github/codeowners/areas.yaml @@ -215,6 +215,7 @@ areas: - examples/global_planner/ - aisimulate/ - examples/aisimulate/ + - examples/power-aware-budget/ - label: runtime github_team: '@ai-dynamo/dynamo-runtime-codeowners' path_globs: diff --git a/.lycheeignore b/.lycheeignore index 21c81b9f17a2..e922ef312fc2 100644 --- a/.lycheeignore +++ b/.lycheeignore @@ -43,3 +43,6 @@ # tree/main link in templates/dgdr.mdx 404s from CI until the PR is merged. ^https://github\.com/ai-dynamo/dynamo/tree/main/examples/deployments/dgdr$ +# This example is introduced by the same PR as its docs link, so the main-branch +# URL returns 404 until merge. +^https://github\.com/ai-dynamo/dynamo/tree/main/examples/power-aware-budget$ diff --git a/CODEOWNERS b/CODEOWNERS index 04422d622462..942ce6485c73 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -164,6 +164,7 @@ /aisimulate/ @ai-dynamo/dynamo-planner-codeowners /examples/aisimulate/ @ai-dynamo/dynamo-planner-codeowners /examples/global_planner/ @ai-dynamo/dynamo-planner-codeowners +/examples/power-aware-budget/ @ai-dynamo/dynamo-planner-codeowners /components/src/dynamo/planner/ @ai-dynamo/dynamo-planner-codeowners /components/src/dynamo/profiler/ @ai-dynamo/dynamo-planner-codeowners /components/src/dynamo/planner/core/ @ai-dynamo/dynamo-planner-codeowners diff --git a/components/src/dynamo/planner/config/defaults.py b/components/src/dynamo/planner/config/defaults.py index 1e2a85d1701d..c915d78e5380 100644 --- a/components/src/dynamo/planner/config/defaults.py +++ b/components/src/dynamo/planner/config/defaults.py @@ -102,6 +102,23 @@ class SLAPlannerDefaults(BasePlannerDefaults): # Advisory mode: compute and log decisions without executing scaling advisory = False + # Power-aware scaling (disabled by default for backward compat). + # + # Per-GPU caps are DGD-owned: authored on each worker component's + # ``podTemplate.metadata.annotations`` (``dynamo.nvidia.com/gpu-power-limit``), + # stamped onto Pods by the operator, and enforced by the Power Agent. The + # planner only reads them. It does NOT own or write per-GPU caps, so no + # per-GPU / safe-default / sweep-interval fields live here — the planner + # config carries only the deployment-wide budget. Power inputs are + # process-static: DGD admission protects the per-component tuple, and a + # total-budget change requires a Planner restart. + # + # ``total_gpu_power_limit`` is required when ``enable_power_awareness=True`` + # (validator enforces). Default None — not a placeholder integer — so the + # type itself signals "operator must set". + enable_power_awareness: bool = False + total_gpu_power_limit: Optional[int] = None + class SubComponentType(str, Enum): PREFILL = "prefill" diff --git a/components/src/dynamo/planner/config/planner_config.py b/components/src/dynamo/planner/config/planner_config.py index cdb1552bcc1f..a73300cbc912 100644 --- a/components/src/dynamo/planner/config/planner_config.py +++ b/components/src/dynamo/planner/config/planner_config.py @@ -614,6 +614,42 @@ def _validate_ca_bundle_path(cls, v: Optional[str]) -> Optional[str]: # Advisory mode: compute and log decisions without executing scaling advisory: bool = SLAPlannerDefaults.advisory + # --- Power-aware budget (read-only caps; DGD-owned) --- + # + # Per-GPU caps are NOT configured here. They are authored on each worker + # component's ``podTemplate.metadata.annotations`` + # (``dynamo.nvidia.com/gpu-power-limit``), applied to Pods by the operator, + # and enforced by the Power Agent. The planner reads those caps from the DGD + # and combines them with ``total_gpu_power_limit`` to project and clamp a + # power budget. It never writes per-GPU caps. These inputs are + # process-static; changing the total budget requires a Planner restart. + enable_power_awareness: bool = Field( + default=False, + description=( + "Enable power-aware budget projection and budget-gated replica " + "scaling. Per-GPU caps are read from DGD worker podTemplate " + "annotations; this planner combines them with total_gpu_power_limit " + "to publish power-budget gauges and clamp scale-up. Requires " + "total_gpu_power_limit, environment='kubernetes', and " + "mode in ('disagg', 'prefill', 'decode'). Not supported for " + "mode='agg'." + ), + ) + total_gpu_power_limit: Optional[int] = Field( + default=None, + ge=1, + description=( + "Total GPU power budget in watts for this DGD. Required when " + "enable_power_awareness=True; changing it requires a Planner " + "restart. Recommended formula: " + "(rack_capacity_W × headroom_factor) − non_gpu_overhead with " + "headroom_factor ≈ 0.85–0.9. Used for the power-budget gauges and " + "as the projected ceiling the final budget clamp holds scaling to — " + "a bound on projected draw from the requested caps, not a proven " + "hardware limit (see the Power Agent for effective enforcement)." + ), + ) + # Diagnostics report settings report_interval_hours: Optional[float] = Field( default=24.0, @@ -645,15 +681,16 @@ def _validate_ca_bundle_path(cls, v: Optional[str]) -> Optional[str]: default=8080, description=( "Port for the live diagnostics dashboard HTTP server. " - "Set to 0 to disable. When enabled, visit http://host:port/ " - "to view a real-time Plotly report of accumulated snapshots." + "Set to 0 to disable. When enabled, visit " + "http://:/ to view a real-time Plotly report of " + "accumulated snapshots." ), ) scheduling: SchedulingConfig = Field( default_factory=SchedulingConfig, description=( - "Plugin-pipeline scheduling config — see ``SchedulingConfig`` " "docstring." + "Plugin-pipeline scheduling config — see ``SchedulingConfig`` docstring." ), ) @@ -752,6 +789,33 @@ def _validate_config(self) -> "PlannerConfig": f"got {self.fpm_sample_bucket_size}" ) + # Power-awareness validation. Per-GPU caps come from DGD worker + # podTemplate annotations, not this config, so the only required knob + # is the total budget — and a Kubernetes connector to read the DGD. + if self.enable_power_awareness: + if self.total_gpu_power_limit is None: + raise ValueError( + "total_gpu_power_limit is required when enable_power_awareness=True. " + "Recommended: (rack_capacity_W × headroom_factor) − non_gpu_overhead " + "with headroom_factor ≈ 0.85–0.9. Setting this incorrectly " + "could silently cap your cluster — there is no safe default." + ) + if self.environment != "kubernetes": + raise ValueError( + "enable_power_awareness=True requires environment='kubernetes'. " + "Per-GPU caps are read from DGD worker podTemplate annotations, " + "which only the Kubernetes connector resolves; virtual/replay and " + "global-planner modes have no DGD with authoritative caps." + ) + if self.mode == "agg": + raise ValueError( + "enable_power_awareness=True is not supported with mode='agg'. " + "The Kubernetes deployment-validation and GPU-count paths use the " + "typed decode role resolver, which does not follow the generic " + "type:worker fallback used by the power parser. Power awareness " + "is supported for mode='disagg', 'prefill', and 'decode'." + ) + if self.environment == "global-planner" and not self.global_planner_namespace: raise ValueError( "global_planner_namespace is required when environment='global-planner'. " diff --git a/components/src/dynamo/planner/connectors/base.py b/components/src/dynamo/planner/connectors/base.py index b84937569b3b..1a0269e445f2 100644 --- a/components/src/dynamo/planner/connectors/base.py +++ b/components/src/dynamo/planner/connectors/base.py @@ -10,11 +10,15 @@ from __future__ import annotations -from typing import Optional, Protocol +import inspect +from typing import TYPE_CHECKING, Optional, Protocol, TypeGuard, runtime_checkable from dynamo.planner.config.defaults import SubComponentType, TargetReplica from dynamo.planner.monitoring.worker_info import WorkerInfo +if TYPE_CHECKING: + from dynamo.planner.monitoring.dgd_services import ComponentPowerConfig + class WorkerInfoProvider(Protocol): def get_worker_info( @@ -68,4 +72,74 @@ async def set_component_replicas( pass -__all__ = ["PlannerConnector", "WorkerInfoProvider"] +@runtime_checkable +class PowerAwareConnector(Protocol): + """Narrow read-only power capability — Kubernetes-specific, not part of PlannerConnector. + + The environment calls ``is_power_aware_connector(controller)`` at each + power-aware boundary when ``enable_power_awareness=True``. All four methods + must be present and callable; a typo or absent method is caught at that check + rather than silently falling back to a no-op. + """ + + def get_graph_deployment(self) -> dict: + ... + + def get_component_power_configs( + self, + require_prefill: bool = True, + require_decode: bool = True, + prefill_component_name: Optional[str] = None, + decode_component_name: Optional[str] = None, + deployment: Optional[dict] = None, + ) -> tuple[Optional[ComponentPowerConfig], Optional[ComponentPowerConfig]]: + ... + + async def wait_for_settled_graph_deployment( + self, + include_planner: bool = False, + *, + require_prefill: bool = True, + require_decode: bool = True, + prefill_component_name: Optional[str] = None, + decode_component_name: Optional[str] = None, + ) -> dict: + ... + + async def get_power_aware_worker_counts( + self, + prefill_component_name: Optional[str] = None, + decode_component_name: Optional[str] = None, + ) -> tuple[int, int, bool]: + ... + + +_POWER_AWARE_REQUIRED: tuple[str, ...] = ( + "get_graph_deployment", + "get_component_power_configs", + "wait_for_settled_graph_deployment", + "get_power_aware_worker_counts", +) + + +def is_power_aware_connector(obj: object) -> TypeGuard[PowerAwareConnector]: + """Return True if ``obj`` is a ``PowerAwareConnector``. + + Uses ``inspect.getattr_static`` (so the check is correct on Python < 3.12, + where ``isinstance(..., Protocol)`` may return True for objects such as an + unrestricted ``MagicMock`` that satisfy the protocol only via + ``__getattr__``). Each attribute must also be callable to exclude + non-callable class-level sentinels. + """ + return all( + callable(inspect.getattr_static(obj, name, None)) + for name in _POWER_AWARE_REQUIRED + ) + + +__all__ = [ + "PlannerConnector", + "PowerAwareConnector", + "WorkerInfoProvider", + "is_power_aware_connector", +] diff --git a/components/src/dynamo/planner/connectors/clients/kubernetes_api.py b/components/src/dynamo/planner/connectors/clients/kubernetes_api.py index 07ae061a7fb4..e94c51342399 100644 --- a/components/src/dynamo/planner/connectors/clients/kubernetes_api.py +++ b/components/src/dynamo/planner/connectors/clients/kubernetes_api.py @@ -15,16 +15,19 @@ import asyncio import logging +from collections.abc import Mapping from typing import Optional from kubernetes import client, config from kubernetes.config.config_exception import ConfigException -from dynamo.planner.errors import DynamoGraphDeploymentNotFoundError +from dynamo.planner.errors import DynamoGraphDeploymentNotFoundError, RolloutFailedError from dynamo.planner.monitoring.dgd_services import ( + POWER_ANNOTATION_KEY, Service, get_component_type, get_components_by_name, + resolve_power_component_names, ) from dynamo.runtime.logging import configure_dynamo_logging @@ -36,7 +39,19 @@ DYNAMO_WORKER_METADATA_API_VERSION = "v1alpha1" DGD_PLURAL = "dynamographdeployments" DGDSA_PLURAL = "dynamographdeploymentscalingadapters" +# During a rollout old Pods are still active and carry the previous cap, so +# progressing phases must block pod-annotation settlement. +# Failed is terminal (the operator sets endTime) and must NOT be treated as a +# retryable blocking phase — wait_for_graph_deployment_ready raises +# RolloutFailedError immediately when require_backing_settled=True (the power +# settlement path) so callers get an actionable error rather than timing out. +# The legacy replica-stability path (require_backing_settled=False) does not +# raise on Failed because it predates the rolling-update contract. +ROLLING_UPDATE_BLOCKING_PHASES = frozenset({"Pending", "InProgress"}) JSON_PATCH_CONTENT_TYPE = "application/json-patch+json" +# Stable labels the operator stamps on every worker Pod. +DYNAMO_DGD_NAME_LABEL = "nvidia.com/dynamo-graph-deployment-name" +DYNAMO_COMPONENT_LABEL = "nvidia.com/dynamo-component" def get_current_k8s_namespace() -> str: @@ -58,6 +73,7 @@ def __init__(self, k8s_namespace: Optional[str] = None): config.load_kube_config() # for out-of-cluster deployment self.custom_api = client.CustomObjectsApi() + self.core_api = client.CoreV1Api() self.current_namespace = k8s_namespace or get_current_k8s_namespace() def _get_graph_deployment_from_name(self, graph_deployment_name: str) -> dict: @@ -251,6 +267,27 @@ def is_deployment_ready(self, deployment: dict) -> bool: return ready_condition is not None and ready_condition.get("status") == "True" + @staticmethod + def is_spec_generation_observed(deployment: dict) -> bool: + """True when status has caught up to ``metadata.generation``. + + Annotation-only DGD edits bump generation without changing desired + replica counts. Replica-count stability alone can look "ready" while + ``observedGeneration`` still describes the previous generation, so + callers that cache startup-static fields (power caps) must require + this catch-up on the same snapshot they read. + """ + generation = deployment.get("metadata", {}).get("generation") + if generation is None: + return False + observed = deployment.get("status", {}).get("observedGeneration") + if observed is None: + return False + try: + return int(observed) >= int(generation) + except (TypeError, ValueError): + return False + def get_service_replica_status( self, deployment: dict, service_name: str ) -> tuple[int, bool]: @@ -288,14 +325,142 @@ def get_service_replica_status( return traffic_serving_replicas, is_stable + def non_planner_components_stable(self, deployment: dict) -> tuple[bool, list[str]]: + """Return ``(all_stable, unstable_names)`` for non-planner components.""" + components = get_components_by_name(deployment) + not_ready: list[str] = [] + for component_name, component_spec in components.items(): + if get_component_type(component_spec) == "planner": + continue + _, is_stable = self.get_service_replica_status(deployment, component_name) + if not is_stable: + not_ready.append(component_name) + return not not_ready, not_ready + + @staticmethod + def is_rolling_update_blocking_settlement(deployment: dict) -> tuple[bool, str]: + """True while an operator-managed worker rollout is not yet cut over.""" + rolling = deployment.get("status", {}).get("rollingUpdate") or {} + phase = rolling.get("phase") or "" + if phase in ROLLING_UPDATE_BLOCKING_PHASES: + return True, f"rollingUpdate.phase={phase}" + return False, "" + + @staticmethod + def has_terminating_pods(pods: list) -> bool: + """True if any non-terminal pod in ``pods`` has a deletionTimestamp.""" + return any( + p.metadata.deletion_timestamp is not None + and (p.status is None or p.status.phase not in ("Succeeded", "Failed")) + for p in pods + ) + + def list_pods_for_graph(self, dgd_name: str) -> list: + """List all Pods for a DGD using its stable graph label.""" + return ( + self.core_api.list_namespaced_pod( + namespace=self.current_namespace, + label_selector=f"{DYNAMO_DGD_NAME_LABEL}={dgd_name}", + ).items + or [] + ) + + @staticmethod + def partition_pods_by_component(pods: list) -> dict[str, list]: + """Partition Pods by the stable Dynamo component label.""" + by_component: dict[str, list] = {} + for pod in pods: + component_name = (pod.metadata.labels or {}).get(DYNAMO_COMPONENT_LABEL) + if component_name: + by_component.setdefault(component_name, []).append(pod) + return by_component + + def worker_pods_settled( + self, + deployment: dict, + expected_power_by_component: Mapping[str, str], + ) -> tuple[bool, list[str]]: + """True when all non-terminal pods carry the expected per-GPU annotation. + + ``expected_power_by_component`` maps each power-relevant component name + to the raw ``dynamo.nvidia.com/gpu-power-limit`` string from the DGD + snapshot (verbatim, for exact propagation verification). + + Terminal means phase Succeeded or Failed. Terminating pods + (DeletionTimestamp set) in Running/Pending/Unknown are non-terminal: + they still consume GPU power and block annotation convergence. + + A component with zero desired replicas and no pods is settled; there is + nothing currently enforcing a stale cap, and future pods will be created + from the current DGD intent. + """ + blocking, reason = self.is_rolling_update_blocking_settlement(deployment) + if blocking: + return False, [reason] + + dgd_name = deployment.get("metadata", {}).get("name", "") + components_by_name = get_components_by_name(deployment) + pending: list[str] = [] + pods_by_component = self.partition_pods_by_component( + self.list_pods_for_graph(dgd_name) + ) + + for component_name, expected_raw in expected_power_by_component.items(): + all_pods = pods_by_component.get(component_name, []) + non_terminal = [ + p + for p in all_pods + if p.status is None or p.status.phase not in ("Succeeded", "Failed") + ] + if not non_terminal: + desired = Service( + name=component_name, + service=components_by_name.get(component_name, {}), + ).number_replicas() + if desired > 0: + pending.append( + f"{component_name}: no non-terminal pods (desired={desired})" + ) + continue + + for pod in non_terminal: + # Terminating pods still consume GPU power and will soon be + # replaced. Even when they carry the expected annotation they + # must block settlement so that the planner never counts them + # as "done" and admits new pods that could push total power + # past the ceiling before the old ones fully disappear. + if pod.metadata.deletion_timestamp is not None: + phase = (pod.status.phase if pod.status else None) or "?" + pending.append( + f"{component_name}/{pod.metadata.name}" + f" (phase={phase}, terminating): waiting for pod to disappear" + ) + continue + actual = (pod.metadata.annotations or {}).get(POWER_ANNOTATION_KEY) + if actual != expected_raw: + phase = (pod.status.phase if pod.status else None) or "?" + pending.append( + f"{component_name}/{pod.metadata.name}" + f" (phase={phase}):" + f" annotation {actual!r} != {expected_raw!r}" + ) + + return not pending, pending + async def wait_for_graph_deployment_ready( self, graph_deployment_name: str, include_planner: bool = True, max_attempts: int = 180, # default: 30 minutes total delay_seconds: int = 10, # default: check every 10 seconds - ) -> None: - """Wait for a graph deployment to be ready. + *, + require_backing_settled: bool = False, + require_prefill: bool = True, + require_decode: bool = True, + prefill_component_name: Optional[str] = None, + decode_component_name: Optional[str] = None, + ) -> dict: + """Wait for a graph deployment to be ready; return the ready snapshot. Args: graph_deployment_name: Name of the DGD to wait for. @@ -305,45 +470,131 @@ async def wait_for_graph_deployment_ready( is one of the services in the DGD. max_attempts: Maximum polling iterations. delay_seconds: Seconds between polls. + require_backing_settled: Power-only gate. When True, raises + immediately on ``status.rollingUpdate.phase == "Failed"`` + regardless of ``include_planner`` (the check runs before the + ``include_planner`` branch so ``include_planner=True`` callers + are not exempt; after fix-4 no production caller combines + ``require_backing_settled=True`` with ``include_planner=True``). + When True and ``include_planner`` is False, additionally + requires ``status.observedGeneration >= metadata.generation`` + and every non-terminal worker Pod carrying the expected per-GPU + annotation from the current DGD snapshot, and blocks while + ``status.rollingUpdate.phase`` is Pending or InProgress. + Must stay False for the legacy ``wait_for_deployment_ready`` + path so power-disabled planners keep working with older + operators or custom SAs that lack pods/list permission. + require_prefill / require_decode / ``*_component_name``: + Forwarded to :func:`resolve_power_component_names` when + ``require_backing_settled`` is True so settlement covers the + same workers the power resolver will read (including untyped + named workers). + + Returns: + The DGD dict that satisfied the readiness criteria (same object + callers should use for startup-static reads such as power caps). """ for attempt in range(max_attempts): await asyncio.sleep(delay_seconds) graph_deployment = self.get_graph_deployment(graph_deployment_name) + # Failed is a terminal rollout state; retrying until timeout (up to + # 30 min) serves no purpose. Raise immediately so the operator can + # investigate. Checked before include_planner so this fires on both + # code paths when require_backing_settled is True. + if require_backing_settled: + _rolling = graph_deployment.get("status", {}).get("rollingUpdate") or {} + if _rolling.get("phase") == "Failed": + raise RolloutFailedError( + deployment_name=graph_deployment_name, + reason=_rolling.get("message", ""), + ) + if include_planner: conditions = graph_deployment.get("status", {}).get("conditions", []) ready_condition = next( (c for c in conditions if c.get("type") == "Ready"), None ) if ready_condition and ready_condition.get("status") == "True": - return + return graph_deployment logger.info( f"[Attempt {attempt + 1}/{max_attempts}] " f"(status: {ready_condition.get('status') if ready_condition else 'N/A'}, " f"message: {ready_condition.get('message') if ready_condition else 'no condition found'})" ) - else: - components = get_components_by_name(graph_deployment) - not_ready: list[str] = [] - for component_name, component_spec in components.items(): - if get_component_type(component_spec) == "planner": - continue - _, is_stable = self.get_service_replica_status( - graph_deployment, component_name - ) - if not is_stable: - not_ready.append(component_name) - - if not not_ready: - return + continue + # Legacy exclude-planner path: replica-count stability only. + all_stable, not_ready = self.non_planner_components_stable(graph_deployment) + if not all_stable: logger.info( f"[Attempt {attempt + 1}/{max_attempts}] " f"Waiting for components (excluding planner): " f"not ready: {not_ready}" ) + continue + + if not require_backing_settled: + return graph_deployment + + # Power settlement: generation catch-up + resolved workers' backing. + # The legacy path above does not gate on rollingUpdate because it + # predates the rolling-update contract and may run without pods/list + # RBAC. Failed was caught before the include_planner branch above. + if not self.is_spec_generation_observed(graph_deployment): + generation = graph_deployment.get("metadata", {}).get("generation") + observed = graph_deployment.get("status", {}).get("observedGeneration") + logger.info( + "[Attempt %d/%d] Waiting for DGD generation to be observed: " + "generation=%s, observedGeneration=%s", + attempt + 1, + max_attempts, + generation, + observed, + ) + continue + + # Role resolution runs after is_spec_generation_observed has + # confirmed the DGD spec is stable. Missing or duplicate roles at + # this point are configuration errors, not operator rollout lag. + power_names = resolve_power_component_names( + graph_deployment, + require_prefill=require_prefill, + require_decode=require_decode, + prefill_name=prefill_component_name, + decode_name=decode_component_name, + ) + + # Build per-component expected annotation strings from the same + # DGD snapshot. A missing or malformed annotation is invalid + # configuration — raise immediately rather than retrying. + # Use the raw DGD annotation string: the operator copies it verbatim + # onto Pod annotations, so the settlement comparison must use the + # same raw value to get an exact match. + components_map = get_components_by_name(graph_deployment) + expected_power: dict[str, str] = {} + for name in power_names: + svc = Service(name=name, service=components_map.get(name, {})) + # Raises PowerAnnotationMissingError / PowerAnnotationInvalidError + # on bad config; let those propagate as a fail-fast startup error. + expected_power[name] = svc.get_gpu_power_limit_annotation() + + pods_ok, pods_pending = self.worker_pods_settled( + graph_deployment, expected_power + ) + if not pods_ok: + logger.info( + "[Attempt %d/%d] Waiting for pods to reflect current power" + " annotation: %s", + attempt + 1, + max_attempts, + pods_pending, + ) + continue + + return graph_deployment raise TimeoutError( f"Graph deployment '{graph_deployment_name}' " diff --git a/components/src/dynamo/planner/connectors/kubernetes.py b/components/src/dynamo/planner/connectors/kubernetes.py index f42f836d3804..9a5e7f9ce1cc 100644 --- a/components/src/dynamo/planner/connectors/kubernetes.py +++ b/components/src/dynamo/planner/connectors/kubernetes.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +import asyncio import json import logging import os @@ -41,9 +42,11 @@ UserProvidedModelNameMismatchError, ) from dynamo.planner.monitoring.dgd_services import ( + ComponentPowerConfig, get_component_from_type_or_name, get_component_type, get_components_by_name, + resolve_component_power_configs, ) from dynamo.planner.monitoring.worker_info import ( WorkerInfo, @@ -343,13 +346,29 @@ def _get_model_name_from_deployment( return model_name + def get_graph_deployment(self) -> dict: + """Fetch the DGD once for callers that share it across GPU/power reads. + + Not on the base ``PlannerConnector`` protocol — power awareness is + Kubernetes-local and must not expand that ABC. The environment checks + ``is_power_aware_connector(controller)`` (all three methods present) + rather than duck-typing via ``getattr``. + """ + return self.kube_api.get_graph_deployment(self.graph_deployment_name) + def get_gpu_counts( self, require_prefill: bool = True, require_decode: bool = True, + deployment: Optional[dict] = None, ) -> tuple[int, int]: - """Get the GPU counts for prefill and decode components.""" - deployment = self.kube_api.get_graph_deployment(self.graph_deployment_name) + """Get the GPU counts for prefill and decode components. + + Pass ``deployment`` to reuse an already-fetched DGD (avoids a second + GET when the environment also resolves power configs on the same tick). + """ + if deployment is None: + deployment = self.get_graph_deployment() return self._get_gpu_counts_from_deployment( deployment, require_prefill=require_prefill, @@ -404,6 +423,38 @@ def _get_gpu_counts_from_deployment( return prefill_gpu_count, decode_gpu_count + def get_component_power_configs( + self, + require_prefill: bool = True, + require_decode: bool = True, + prefill_component_name: Optional[str] = None, + decode_component_name: Optional[str] = None, + deployment: Optional[dict] = None, + ) -> tuple[Optional[ComponentPowerConfig], Optional[ComponentPowerConfig]]: + """Resolve DGD-owned per-role power configs from worker podTemplate annotations. + + One DGD GET unless ``deployment`` is provided (shared with + ``get_gpu_counts`` on the same tick). ``watts_per_replica`` on each + config uses the replica-wide GPU total (nodeCount × per-pod) via + ``Service.get_total_gpu_count()``, independent of the per-pod + ``num_gpus`` the GPU-budget math consumes. + + The typed parser errors (``PowerAnnotationMissingError`` / + ``PowerAnnotationInvalidError`` / ``SubComponentNotFoundError`` / + ``DuplicateSubComponentError`` / ``ValueError`` for a bad GPU count) + propagate so the environment can apply the startup-fail vs + runtime-conservative policy rather than the planner guessing a cap. + """ + if deployment is None: + deployment = self.get_graph_deployment() + return resolve_component_power_configs( + deployment, + require_prefill=require_prefill, + require_decode=require_decode, + prefill_name=prefill_component_name, + decode_name=decode_component_name, + ) + def get_frontend_metrics_url(self, port: int = 8000) -> Optional[str]: """Auto-discover the frontend component's metrics URL from the DGD. @@ -427,7 +478,12 @@ def get_frontend_metrics_url(self, port: int = 8000) -> Optional[str]: return None async def wait_for_deployment_ready(self, include_planner: bool = True): - """Wait for the deployment to be ready. + """Wait for the deployment to be ready (legacy replica-stability path). + + Does **not** check pod annotation convergence or require + ``observedGeneration`` catch-up. Power-aware callers that permanently + cache DGD fields must use :meth:`wait_for_settled_graph_deployment` + instead. Args: include_planner: If False, skip the planner component when checking @@ -437,6 +493,48 @@ async def wait_for_deployment_ready(self, include_planner: bool = True): await self.kube_api.wait_for_graph_deployment_ready( self.graph_deployment_name, include_planner=include_planner, + require_backing_settled=False, + ) + + async def wait_for_settled_graph_deployment( + self, + include_planner: bool = False, + *, + require_prefill: bool = True, + require_decode: bool = True, + prefill_component_name: Optional[str] = None, + decode_component_name: Optional[str] = None, + ) -> dict: + """Wait for a settled DGD snapshot and return that same object. + + When ``include_planner`` is False, the snapshot has: + - non-planner worker replica counts stable (desired == updated == ready) + - ``status.observedGeneration >= metadata.generation`` + - every non-terminal worker Pod carries the expected + ``dynamo.nvidia.com/gpu-power-limit`` annotation from the current + DGD snapshot, confirming the operator has propagated the DGD intent + to running Pods (hardware enforcement by the Power Agent/NVML is + separate and not verified here) + + Power-relevant workers are selected with the same role/name resolution + as :meth:`get_component_power_configs` (typed roles, explicit-name + fallback for untyped workers, unique generic ``type: worker`` for agg). + + Callers that permanently cache fields from the DGD (power caps) must + use this snapshot rather than issuing a later GET, so an + annotation-only generation bump cannot be adopted before workers + have rolled onto that generation. Active rolling updates + (``status.rollingUpdate.phase`` Pending/InProgress/Failed) also + block settlement because old Pods still carry the previous cap. + """ + return await self.kube_api.wait_for_graph_deployment_ready( + self.graph_deployment_name, + include_planner=include_planner, + require_backing_settled=True, + require_prefill=require_prefill, + require_decode=require_decode, + prefill_component_name=prefill_component_name, + decode_component_name=decode_component_name, ) def _list_worker_metadata_crs(self) -> list[dict]: @@ -630,15 +728,57 @@ async def get_actual_worker_counts( prefill_component_name: Optional[str] = None, decode_component_name: Optional[str] = None, ) -> tuple[int, int, bool]: - """ - Get actual ready worker counts for prefill and decode from DGD status. + """Get ready worker counts from DGD status without listing Pods.""" + deployment = self.kube_api.get_graph_deployment(self.graph_deployment_name) + return self._worker_counts_from_snapshot( + deployment, + prefill_component_name=prefill_component_name, + decode_component_name=decode_component_name, + ) - Returns: - tuple[int, int, bool]: (prefill_count, decode_count, is_stable) - - is_stable: False if any component is in a rollout (scaling should be skipped) + async def get_power_aware_worker_counts( + self, + prefill_component_name: Optional[str] = None, + decode_component_name: Optional[str] = None, + ) -> tuple[int, int, bool]: + """Get power-safe worker counts without blocking the Planner event loop. + + One thread dispatch contains the synchronous DGD GET and the single + DGD-scoped Pod LIST. The returned Pod snapshot is partitioned locally by + component before terminating-Pod checks run. """ + return await asyncio.to_thread( + self._get_power_aware_worker_counts_sync, + prefill_component_name, + decode_component_name, + ) + + def _get_power_aware_worker_counts_sync( + self, + prefill_component_name: Optional[str], + decode_component_name: Optional[str], + ) -> tuple[int, int, bool]: deployment = self.kube_api.get_graph_deployment(self.graph_deployment_name) + dgd_name = deployment.get("metadata", {}).get("name", "") + pods = self.kube_api.list_pods_for_graph(dgd_name) if dgd_name else [] + pods_by_component = self.kube_api.partition_pods_by_component(pods) + return self._worker_counts_from_snapshot( + deployment, + prefill_component_name=prefill_component_name, + decode_component_name=decode_component_name, + pods_by_component=pods_by_component, + power_aware=True, + ) + def _worker_counts_from_snapshot( + self, + deployment: dict, + *, + prefill_component_name: Optional[str], + decode_component_name: Optional[str], + pods_by_component: Optional[dict[str, list]] = None, + power_aware: bool = False, + ) -> tuple[int, int, bool]: prefill_count = 0 decode_count = 0 all_stable = True @@ -652,6 +792,14 @@ async def get_actual_worker_counts( ready_replicas, is_stable = self.kube_api.get_service_replica_status( deployment, service.name ) + if ( + is_stable + and power_aware + and self.kube_api.has_terminating_pods( + (pods_by_component or {}).get(service.name, []) + ) + ): + is_stable = False if not is_stable: all_stable = False prefill_count = ready_replicas @@ -665,10 +813,39 @@ async def get_actual_worker_counts( ready_replicas, is_stable = self.kube_api.get_service_replica_status( deployment, service.name ) + if ( + is_stable + and power_aware + and self.kube_api.has_terminating_pods( + (pods_by_component or {}).get(service.name, []) + ) + ): + is_stable = False if not is_stable: all_stable = False decode_count = ready_replicas + if power_aware: + is_blocking, reason = self.kube_api.is_rolling_update_blocking_settlement( + deployment + ) + if not is_blocking: + # Failed is not in ROLLING_UPDATE_BLOCKING_PHASES because at + # startup it raises immediately rather than blocking. At runtime + # there is no raise, so the dedicated power path treats Failed as + # fail-closed (unstable) and does not admit scale-ups. + rolling = deployment.get("status", {}).get("rollingUpdate") or {} + if rolling.get("phase") == "Failed": + is_blocking = True + reason = "rollingUpdate.phase=Failed" + if is_blocking: + logger.info( + "%s: treating runtime counts as unstable: %s", + self.graph_deployment_name, + reason, + ) + all_stable = False + return prefill_count, decode_count, all_stable async def set_component_replicas( diff --git a/components/src/dynamo/planner/core/base.py b/components/src/dynamo/planner/core/base.py index 5f2387713025..7e9d80fb80fd 100644 --- a/components/src/dynamo/planner/core/base.py +++ b/components/src/dynamo/planner/core/base.py @@ -48,8 +48,12 @@ logger = logging.getLogger(__name__) -def _engine_caps(worker_info, num_gpu: Optional[int]) -> Optional[EngineCapabilities]: - if worker_info is None and num_gpu is None: +def _engine_caps( + worker_info, + num_gpu: Optional[int], + power_watts_per_replica: Optional[int] = None, +) -> Optional[EngineCapabilities]: + if worker_info is None and num_gpu is None and power_watts_per_replica is None: return None return EngineCapabilities( num_gpu=num_gpu, @@ -61,13 +65,22 @@ def _engine_caps(worker_info, num_gpu: Optional[int]) -> Optional[EngineCapabili max_kv_tokens=worker_info.max_kv_tokens if worker_info else None, kv_cache_block_size=worker_info.kv_cache_block_size if worker_info else None, speculative_nextn=worker_info.speculative_nextn if worker_info else None, + power_watts_per_replica=power_watts_per_replica, ) def build_worker_capabilities(state: DeploymentState) -> WorkerCapabilities: return WorkerCapabilities( - prefill=_engine_caps(state.prefill.info, state.prefill.num_gpus), - decode=_engine_caps(state.decode.info, state.decode.num_gpus), + prefill=_engine_caps( + state.prefill.info, + state.prefill.num_gpus, + state.prefill.power_watts_per_replica, + ), + decode=_engine_caps( + state.decode.info, + state.decode.num_gpus, + state.decode.power_watts_per_replica, + ), ) @@ -104,6 +117,12 @@ def __init__( self._cumulative_gpu_hours: float = 0.0 self._last_gpu_hours_update_ts: Optional[float] = None + + # One-shot guard so the "power budget projected zero" warning (emitted + # when a required role has not yet resolved a per-replica watt value) + # logs once rather than every tick. + self._power_projected_zero_warned: bool = False + self._recorder = DiagnosticsRecorder(config=config) self._dashboard_runner: Optional[aiohttp.web.AppRunner] = None self._engine: Optional[EngineProtocol] = None @@ -359,6 +378,71 @@ def _publish_observation_metrics(self, tick_input: TickInput) -> None: async def _apply_effects(self, effects: PlannerEffects) -> None: pass + def _current_worker_counts(self) -> tuple[int, int]: + """Best-known current (prefill, decode) ready worker counts. + + Reads ``self._last_worker_counts``, cached each tick in ``run()`` from + the tick input — the count source the orchestrator engine exposes. + Returns ``(0, 0)`` before the first worker-state tick populates it. + Consumed by ``_log_decision_summary``. + """ + if self._last_worker_counts is not None: + return ( + self._last_worker_counts.ready_num_prefill or 0, + self._last_worker_counts.ready_num_decode or 0, + ) + return 0, 0 + + def _publish_power_budget_metrics(self, num_p: int, num_d: int) -> None: + """Emit power-budget gauges from DGD-resolved caps (read-only observe path). + + Per-replica watts come from the cached deployment state + (``power_watts_per_replica``, resolved once from the DGD worker + podTemplate annotation during Planner startup), so this performs no + apiserver I/O and never blocks the tick loop. DGD admission rejects + changes to the cached power tuple; changing it requires replacing the + DGD and starting a new Planner. These gauges are advisory + observability; the projected power budget (over the requested caps, + not the effective hardware draw) is applied separately by the final + budget clamp. + + The projection gauges are published only once every required role has + a resolved per-replica watt value and the total budget is a positive + integer; the typed parser and Pydantic keep these integral, so there + is no NaN to clamp. + """ + if self.prometheus_port == 0 or not self.config.enable_power_awareness: + return + pm = self.prometheus_metrics + state = self.environment.deployment_state() + + budget = self.config.total_gpu_power_limit + if budget is None or budget <= 0: + # Startup validation already requires budget > 0; guard here so a + # degenerate value can never publish a divide-by-zero utilization. + return + + p_watts = state.prefill.power_watts_per_replica + d_watts = state.decode.power_watts_per_replica + if (self.require_prefill and p_watts is None) or ( + self.require_decode and d_watts is None + ): + if not self._power_projected_zero_warned: + logger.warning( + "power_projected_watts not published: per-replica watts " + "unresolved (prefill=%s, decode=%s). Caps are authored on " + "the DGD worker podTemplate annotation.", + p_watts, + d_watts, + ) + self._power_projected_zero_warned = True + return + + projected = num_p * (p_watts or 0) + num_d * (d_watts or 0) + pm.power_budget_total_watts.set(budget) + pm.power_projected_watts.set(projected) + pm.power_budget_utilization.set(projected / budget) + async def _apply_scaling_targets( self, targets: list[TargetReplica], blocking: bool = False ) -> None: @@ -367,15 +451,15 @@ async def _apply_scaling_targets( await self.environment.apply_scaling(targets, blocking=blocking) def _log_decision_summary(self, effects: PlannerEffects) -> None: + """Log a one-line summary of the scaling decision after each tick. + + Current worker counts come from ``_current_worker_counts`` — the + cached ``self._last_worker_counts`` set in ``run()``. + """ decision = effects.scale_to diag = effects.diagnostics - if self._last_worker_counts is not None: - current_p = self._last_worker_counts.ready_num_prefill or 0 - current_d = self._last_worker_counts.ready_num_decode or 0 - else: - current_p = 0 - current_d = 0 + current_p, current_d = self._current_worker_counts() rec_p = decision.num_prefill if decision else None rec_d = decision.num_decode if decision else None @@ -432,6 +516,7 @@ def _publish_inventory_and_gpu_hours(self, tick_input: TickInput) -> None: self.prometheus_metrics.num_prefill_replicas.set(num_p) self.prometheus_metrics.num_decode_replicas.set(num_d) self.prometheus_metrics.gpu_hours.set(self._cumulative_gpu_hours) + self._publish_power_budget_metrics(num_p, num_d) @staticmethod def _set_if_observed(gauge, value: Optional[float]) -> None: @@ -463,9 +548,11 @@ def _report_diagnostics(self, tick: ScheduledTick, diag: TickDiagnostics) -> Non # independently-scheduled PREDICT plugin). self._set_if_observed( pm.predicted_requests_per_second, - diag.predicted_num_req / interval - if diag.predicted_num_req is not None and interval > 0 - else None, + ( + diag.predicted_num_req / interval + if diag.predicted_num_req is not None and interval > 0 + else None + ), ) self._set_if_observed(pm.predicted_input_sequence_tokens, diag.predicted_isl) self._set_if_observed(pm.predicted_output_sequence_tokens, diag.predicted_osl) diff --git a/components/src/dynamo/planner/core/budget.py b/components/src/dynamo/planner/core/budget.py index 3fd1b7942b85..b59c6b7395d1 100644 --- a/components/src/dynamo/planner/core/budget.py +++ b/components/src/dynamo/planner/core/budget.py @@ -6,31 +6,26 @@ Two layers: * **Pure math** (``compute_tolerance``, ``bounds_for_total``, - ``proportional_clamp_pair``, ``proportional_clamp_single``): no I/O, no - state, no logging. Shared by the builtin local planner state (where the - budget is enforced intra-DGD by clamping the joint - ``(num_prefill, num_decode)`` desired counts) and the centralized - GlobalPlanner (where it is enforced across DGDs by accepting/rejecting - incoming ScaleRequests). Both layers compute the same ``tolerance`` and - the same in-band check; only the action taken on a breach differs (the - local planner transforms counts, the GlobalPlanner decides). - -* **Config-aware wrappers** (``_apply_global_gpu_budget``, - ``_apply_component_gpu_budget``): pull ``min_gpu_budget``, - ``max_gpu_budget``, ``min_endpoint``, and per-engine GPU counts off a - ``PlannerConfig`` and delegate to the pure primitives. These are what - ``state_machine.py`` and friends call. + ``proportional_clamp_pair``, ``proportional_clamp_single``, plus the + power-budget helpers below): no I/O, no state, no logging. Shared by + the builtin local planner state (where the budget is enforced + intra-DGD by clamping the joint ``(num_prefill, num_decode)`` desired + counts), the orchestrator engine adapter's final budget clamp, and the + centralized GlobalPlanner (where it is enforced across DGDs by + accepting/rejecting incoming ScaleRequests). Callers share the same + ``tolerance`` / in-band check; only the action taken on a breach + differs (local transforms counts, GlobalPlanner decides). * ``_initialize_gpu_counts`` remains a deployment-bootstrap helper: it populates per-engine GPU counts from the DGD spec or CLI flags, with - a virtual-mode fallback. Untouched by this refactor. + a virtual-mode fallback. """ from __future__ import annotations import logging import math -from typing import Iterable +from typing import Iterable, Optional from dynamo.planner.config.planner_config import PlannerConfig from dynamo.planner.errors import DeploymentValidationError @@ -215,78 +210,280 @@ def proportional_clamp_single( # ---------------------------------------------------------------------------- # -# Config-aware wrappers — what state_machine.py and friends call. # +# Power budget — pure ceiling clamp on PROJECTED watts (no floor). # +# # +# The per-GPU caps are DGD-owned; the planner reads ``watts_per_replica`` per # +# role (from the *requested* annotation) and a ``total_gpu_power_limit`` and # +# clamps proposed replica counts so projected watts fit the budget. This is a # +# ceiling on the projected draw of the requested caps — not a proven hardware # +# limit (the Power Agent may clamp a cap up to the GPU minimum or fail to # +# apply it, and does not feed the effective cap back here). Within that model # +# it is treated as a hard constraint: it only ever *lowers* counts and, # +# applied after the GPU-budget clamp, wins over the GPU floor when the two # +# conflict (the floor violation is reported, not enforced). # # ---------------------------------------------------------------------------- # -def _apply_global_gpu_budget( - next_num_p: int, next_num_d: int, config: PlannerConfig -) -> tuple[int, int]: - """Apply GPU budget band to disagg ``(num_p, num_d)``. +def project_watts( + num_p: Optional[int], + num_d: Optional[int], + p_watts: Optional[int], + d_watts: Optional[int], +) -> int: + """Projected watts = Σ count × per-replica watts. Missing count/watts = 0.""" + total = 0 + if num_p is not None and p_watts is not None: + total += num_p * p_watts + if num_d is not None and d_watts is not None: + total += num_d * d_watts + return total + + +def peak_parallel_watts( + current_p: Optional[int], + current_d: Optional[int], + proposed_p: Optional[int], + proposed_d: Optional[int], + p_watts: Optional[int], + d_watts: Optional[int], +) -> int: + """Worst-case draw if both roles move toward their targets in parallel.""" + p_ready = current_p or 0 + d_ready = current_d or 0 + p_peak = max(p_ready, proposed_p if proposed_p is not None else p_ready) + d_peak = max(d_ready, proposed_d if proposed_d is not None else d_ready) + return project_watts(p_peak, d_peak, p_watts, d_watts) + + +def _is_opposing_rebalance( + proposed_p: Optional[int], + proposed_d: Optional[int], + current_p: Optional[int], + current_d: Optional[int], +) -> bool: + """True when one role scales up and the other scales down. + + ``None`` current means no replicas are seated yet, treated as 0 — matching + ``_hold_at_current`` and ``peak_parallel_watts``. ``None`` proposed means + the role is not part of this tick's proposal; direction is indeterminate so + the function returns False and the caller must handle it. + """ + if proposed_p is None or proposed_d is None: + return False + cp = 0 if current_p is None else current_p + cd = 0 if current_d is None else current_d + p_up = proposed_p > cp + p_down = proposed_p < cp + d_up = proposed_d > cd + d_down = proposed_d < cd + return (p_up and d_down) or (p_down and d_up) + + +def minimum_power_footprint_fits( + total_budget: int, + min_endpoint: int, + p_watts: Optional[int], + d_watts: Optional[int], +) -> bool: + """True when ``min_endpoint`` replicas of every present role fit the budget. + + Startup feasibility gate: if even the minimum footprint overshoots the + total power budget the deployment can never satisfy the ceiling, so the + planner must fail closed rather than clamp to an impossible target. + """ + required = 0 + if p_watts is not None: + required += min_endpoint * p_watts + if d_watts is not None: + required += min_endpoint * d_watts + return required <= total_budget + + +def _hold_at_current( + proposed: Optional[int], current: Optional[int] +) -> tuple[Optional[int], bool]: + """Cap a proposal at the current count (block scale-up, allow scale-down). + + ``current is None`` means no replicas are seated yet — treated as 0 so a + create-from-nothing proposal is a scale-up and can be refused when the + fixed peer already exhausts the budget. + """ + if proposed is None: + return None, False + baseline = 0 if current is None else current + held = min(proposed, baseline) + return held, held < proposed + + +def apply_power_budget( + proposed_p: Optional[int], + proposed_d: Optional[int], + current_p: Optional[int], + current_d: Optional[int], + p_watts: Optional[int], + d_watts: Optional[int], + total_budget: int, + min_endpoint: int, +) -> tuple[Optional[int], Optional[int], Optional[str]]: + """Clamp proposed replica counts so projected power fits ``total_budget``. - Honors ``config.max_gpu_budget`` (hard ceiling) and ``config.min_gpu_budget`` - (floor; ``-1`` disables). When both are active, allows the result to - land in ``[min - tolerance, max]`` where ``tolerance = - max(prefill_engine_num_gpu, decode_engine_num_gpu)`` — see - ``proportional_clamp_pair``. ``max_gpu_budget`` is never relaxed. + ``None`` proposals preserve the proposal mask — an unproposed component is + never mutated; its *current* count is charged against the budget when + sizing the proposed component(s). Returns ``(new_p, new_d, reason)`` where + ``reason`` is a short diagnostic when the clamp changed a proposal (or + suppressed a scale-up), else ``None``. - Returns ``(0, 0)`` if the ceiling is below the per-pool minima - (configuration error). + Power is ceiling-only and never raises a count above what was proposed. """ - if config.max_gpu_budget < 0 and config.min_gpu_budget < 0: - return next_num_p, next_num_d - assert config.prefill_engine_num_gpu is not None - assert config.decode_engine_num_gpu is not None - - p_gpu = config.prefill_engine_num_gpu - d_gpu = config.decode_engine_num_gpu - - new_p, new_d = proportional_clamp_pair( - next_num_p, - next_num_d, - p_gpu, - d_gpu, - config.min_gpu_budget, - config.max_gpu_budget, - config.min_endpoint, - ) - - if (new_p, new_d) != (next_num_p, next_num_d): - old_total = next_num_p * p_gpu + next_num_d * d_gpu - new_total = new_p * p_gpu + new_d * d_gpu - logger.warning( - f"GPU budget band [min={config.min_gpu_budget}, max={config.max_gpu_budget}] " - f"clamped ({next_num_p}P + {next_num_d}D = {old_total} GPUs) -> " - f"({new_p}P + {new_d}D = {new_total} GPUs)" + p_adjustable = proposed_p is not None and p_watts is not None and p_watts > 0 + d_adjustable = proposed_d is not None and d_watts is not None and d_watts > 0 + + if ( + p_adjustable + and d_adjustable + and _is_opposing_rebalance(proposed_p, proposed_d, current_p, current_d) + and peak_parallel_watts( + current_p, current_d, proposed_p, proposed_d, p_watts, d_watts + ) + > total_budget + ): + # Settled target may fit, but parallel rollouts can transiently exceed + # the ceiling (e.g. (1,4)->(4,1) peaks at (4,4)). Stage scale-downs + # first by deferring scale-up legs to a later stable tick. + new_p, capped_p = _hold_at_current(proposed_p, current_p) + new_d, capped_d = _hold_at_current(proposed_d, current_d) + if capped_p or capped_d: + return new_p, new_d, "power_rebalance_staged" + + eff_p = proposed_p if proposed_p is not None else current_p + eff_d = proposed_d if proposed_d is not None else current_d + if project_watts(eff_p, eff_d, p_watts, d_watts) <= total_budget: + return proposed_p, proposed_d, None + + if p_adjustable and d_adjustable: + assert proposed_p is not None and proposed_d is not None + assert p_watts is not None and d_watts is not None + new_p, new_d = _shrink_pair( + proposed_p, proposed_d, p_watts, d_watts, total_budget, min_endpoint + ) + # Ceiling never raises a proposed count (decode-no-upscale invariant). + new_p = min(new_p, proposed_p) + new_d = min(new_d, proposed_d) + # The clamp itself can synthesize an opposing rebalance vs current even + # when the proposal was not one (e.g. current (4,1), proposal (5,5) -> + # clamped (2,3)): the settled target fits, but parallel actuation peaks + # at (4,3). Stage that peak the same way as a proposed rebalance by + # holding the scale-up leg(s) at current so the transient stays under + # the ceiling; the scale-up is admitted on a later stable tick. + if ( + _is_opposing_rebalance(new_p, new_d, current_p, current_d) + and peak_parallel_watts( + current_p, current_d, new_p, new_d, p_watts, d_watts + ) + > total_budget + ): + staged_p, capped_p = _hold_at_current(new_p, current_p) + staged_d, capped_d = _hold_at_current(new_d, current_d) + if capped_p or capped_d: + return staged_p, staged_d, "power_rebalance_staged" + return new_p, new_d, "power_budget_clamped" + + if p_adjustable != d_adjustable: + # Exactly one proposed adjustable component; charge the other at its + # current count and never mutate it. + if p_adjustable: + assert proposed_p is not None and p_watts is not None + fixed = eff_d * d_watts if (eff_d is not None and d_watts) else 0 + new_p, suppressed = _shrink_single( + proposed_p, current_p, p_watts, total_budget - fixed, min_endpoint + ) + if new_p == proposed_p: + return new_p, proposed_d, None + reason = ( + "power_budget_scale_up_suppressed" + if suppressed + else "power_budget_clamped" + ) + return new_p, proposed_d, reason + assert proposed_d is not None and d_watts is not None + fixed = eff_p * p_watts if (eff_p is not None and p_watts) else 0 + new_d, suppressed = _shrink_single( + proposed_d, current_d, d_watts, total_budget - fixed, min_endpoint + ) + if new_d == proposed_d: + return proposed_p, new_d, None + reason = ( + "power_budget_scale_up_suppressed" if suppressed else "power_budget_clamped" ) + return proposed_p, new_d, reason + # Over budget but nothing adjustable is proposed (baseline over budget with + # no lever this tick). Do not mutate unproposed components. + return proposed_p, proposed_d, None + + +def _shrink_pair( + num_p: int, + num_d: int, + p_watts: int, + d_watts: int, + budget: int, + min_endpoint: int, +) -> tuple[int, int]: + """Proportionally shrink a disagg pair so watts fit the budget ceiling.""" + projected = num_p * p_watts + num_d * d_watts + if projected <= budget: + return num_p, num_d + # minimum_power_footprint_fits() at startup guarantees this is unreachable + # in a correctly configured deployment. Use RuntimeError (not assert) so + # the guard is never stripped by -O optimized-mode Python. + if budget < min_endpoint * (p_watts + d_watts): + raise RuntimeError( + f"Power budget infeasible: {budget=} < {min_endpoint=} " + f"* ({p_watts=} + {d_watts=}); startup validation missed this" + ) + scale = budget / projected + max_p = math.floor((budget - min_endpoint * d_watts) / p_watts) + new_p = max(min_endpoint, min(max_p, math.floor(num_p * scale))) + remaining = budget - new_p * p_watts + # Cap new_d at num_d: when p_watts >> d_watts the proportional shrink lands + # new_p near min_endpoint, leaving a large remaining budget that would push + # floor(remaining / d_watts) above num_d. Callers guarantee num_d >= + # min_endpoint, so min(num_d, max(min_endpoint, ...)) returns <= num_d + # while still respecting the floor for valid inputs. + new_d = min(num_d, max(min_endpoint, math.floor(remaining / d_watts))) return new_p, new_d -def _apply_component_gpu_budget( - desired_replicas: int, engine_num_gpu: int, config: PlannerConfig -) -> int: - """Apply GPU budget band to a single component (agg, or - prefill-only / decode-only mode).""" - if config.max_gpu_budget < 0 and config.min_gpu_budget < 0: - return desired_replicas - - new_replicas = proportional_clamp_single( - desired_replicas, - engine_num_gpu, - config.min_gpu_budget, - config.max_gpu_budget, - config.min_endpoint, - ) +def _shrink_single( + proposed: int, + current: Optional[int], + watts: int, + avail: int, + min_endpoint: int, +) -> tuple[int, bool]: + """Fit a single adjustable pool into ``avail`` watts. + + Returns ``(new_count, suppressed)``. ``suppressed`` is True when the fixed + (unproposed) component alone leaves no room to even seat ``min_endpoint``, + so the proposed scale-up is refused (held at ``min(proposed, current)``) + rather than the unproposed component being silently mutated. + """ + if avail < min_endpoint * watts: + held, capped = _hold_at_current(proposed, current) + # ``proposed`` is non-optional, so ``_hold_at_current`` never returns + # ``None`` here. ``current is None`` is treated as baseline 0, so a + # create-from-nothing proposal is suppressed when the fixed peer + # alone leaves no room for ``min_endpoint``. + assert held is not None + return held, capped + max_fit = math.floor(avail / watts) + return max(min_endpoint, min(proposed, max_fit)), False - if new_replicas != desired_replicas: - logger.warning( - f"GPU budget band [min={config.min_gpu_budget}, max={config.max_gpu_budget}] " - f"clamped {desired_replicas} replicas (= {desired_replicas * engine_num_gpu} GPUs) " - f"-> {new_replicas} replicas (= {new_replicas * engine_num_gpu} GPUs)" - ) - return new_replicas +# ---------------------------------------------------------------------------- # +# Deployment bootstrap — GPU counts from DGD / CLI. # +# ---------------------------------------------------------------------------- # def _initialize_gpu_counts( diff --git a/components/src/dynamo/planner/core/types.py b/components/src/dynamo/planner/core/types.py index b54bf6626f06..f092c32a312a 100644 --- a/components/src/dynamo/planner/core/types.py +++ b/components/src/dynamo/planner/core/types.py @@ -205,6 +205,10 @@ class EngineCapabilities: max_kv_tokens: Optional[int] = None kv_cache_block_size: Optional[int] = None speculative_nextn: Optional[int] = None + # DGD-resolved per-replica power draw (watts) for this stage: the per-GPU + # cap × the replica-wide GPU total. None when power awareness is off or the + # cap has not been resolved. The final budget clamp reads this. + power_watts_per_replica: Optional[int] = None @dataclass diff --git a/components/src/dynamo/planner/environment/base.py b/components/src/dynamo/planner/environment/base.py index 8c5c55a721b0..05f13efba12e 100644 --- a/components/src/dynamo/planner/environment/base.py +++ b/components/src/dynamo/planner/environment/base.py @@ -3,13 +3,15 @@ from __future__ import annotations +import inspect import logging from typing import Optional from dynamo.planner.config.backend_components import WORKER_COMPONENT_NAMES from dynamo.planner.config.defaults import SubComponentType, TargetReplica from dynamo.planner.config.planner_config import PlannerConfig -from dynamo.planner.connectors.base import PlannerConnector +from dynamo.planner.connectors.base import PlannerConnector, is_power_aware_connector +from dynamo.planner.core.budget import minimum_power_footprint_fits from dynamo.planner.core.types import FpmObservations, TrafficObservation from dynamo.planner.environment.interface import ( PlannerEnvironment, @@ -19,8 +21,9 @@ FpmMetricsProvider, TrafficMetricsProvider, ) -from dynamo.planner.environment.state import DeploymentState +from dynamo.planner.environment.state import ComponentState, DeploymentState from dynamo.planner.errors import DeploymentValidationError +from dynamo.planner.monitoring.dgd_services import ComponentPowerConfig from dynamo.planner.monitoring.traffic_metrics import Metrics logger = logging.getLogger(__name__) @@ -105,10 +108,23 @@ async def initialize(self) -> None: require_prefill=self.require_prefill, require_decode=self.require_decode, ) - await self.controller.wait_for_deployment_ready(include_planner=False) + # Block until one DGD snapshot is generation-caught-up and worker-stable, + # then permanently cache power caps from that same snapshot. Replica-count + # stability alone is not enough: an annotation-only edit bumps + # metadata.generation without changing desired replicas, so a Planner + # restart in the controller-status lag could otherwise cache a newer, + # lower cap while Pods still enforce the previous higher one. + deployment = await self._wait_for_startup_dgd_snapshot() if self.runtime_namespace_source is not None: await self.runtime_namespace_source.refresh_runtime_namespace() - await self._refresh_deployment_state() + await self._refresh_deployment_state(deployment=deployment) + self._load_static_power_caps_at_startup(deployment=deployment) + # FPM init can change the effective runtime namespace / discovery view; + # re-refresh replica/GPU/model state afterward so the first tick sees + # post-init truth. This second call intentionally omits the shared + # deployment snapshot (power caps stay startup-static) and may issue + # a separate DGD GET for GPU counts — that is expected, not a merge + # of the shared-GET path above. await self.fpm_provider.async_init(self._runtime_namespace_or_none()) await self._refresh_deployment_state() @@ -157,12 +173,80 @@ async def apply_scaling( async def shutdown(self) -> None: await self.fpm_provider.shutdown() - async def _refresh_deployment_state(self) -> None: + async def _refresh_deployment_state( + self, deployment: Optional[dict] = None + ) -> None: self._refresh_worker_info() - self._refresh_gpu_counts() + self._refresh_gpu_counts(deployment=deployment) await self._refresh_replica_counts() self._refresh_model_name() + def _shared_dgd_deployment(self) -> Optional[dict]: + """One DGD GET for GPU + power reads when power awareness is on. + + Only connectors that implement ``PowerAwareConnector`` expose + ``get_graph_deployment``; others return ``None`` (no-op). Prefer + ``_wait_for_startup_dgd_snapshot`` at init so caps come from a + generation-observed, worker-stable snapshot. + """ + if not self.config.enable_power_awareness: + return None + if not is_power_aware_connector(self.controller): + return None + return self.controller.get_graph_deployment() + + async def _wait_for_startup_dgd_snapshot(self) -> Optional[dict]: + """Wait for readiness; when power is on, return a settled DGD snapshot. + + The settled wait (observedGeneration + pod annotation convergence) is + only required to permanently cache DGD-owned power caps. Power-disabled + planners keep the standard ``wait_for_deployment_ready`` path. + """ + if self.config.enable_power_awareness: + if not is_power_aware_connector(self.controller): + raise DeploymentValidationError( + [ + "Power awareness requires a connector that implements " + "PowerAwareConnector (get_graph_deployment, " + "get_component_power_configs, " + "wait_for_settled_graph_deployment, " + "get_power_aware_worker_counts); " + "this connector does not." + ] + ) + prefill_name, decode_name = self._power_component_names() + return await self.controller.wait_for_settled_graph_deployment( + include_planner=False, + require_prefill=self.require_prefill, + require_decode=self.require_decode, + prefill_component_name=prefill_name, + decode_component_name=decode_name, + ) + await self.controller.wait_for_deployment_ready(include_planner=False) + return self._shared_dgd_deployment() + + @staticmethod + def _call_with_optional_deployment(method, *, deployment=None, **kwargs): + """Invoke a connector method, forwarding ``deployment`` when accepted. + + Inspects the callable signature so a real ``TypeError`` raised inside + the connector (wrong arg types, ``None`` arithmetic, etc.) is not + swallowed by a retry without ``deployment``. Connectors that support + the shared-snapshot optimization must name the optional keyword exactly + ``deployment``; otherwise this deliberately falls back to the ordinary + connector call (and its own DGD GET). + """ + if deployment is not None: + try: + params = inspect.signature(method).parameters + except (TypeError, ValueError): + # Builtins / C extensions without an inspectable signature — + # fall through to the no-deployment call rather than guess. + return method(**kwargs) + if "deployment" in params: + return method(**kwargs, deployment=deployment) + return method(**kwargs) + def _refresh_worker_info(self) -> None: get_worker_info = getattr(self.controller, "get_worker_info", None) if not callable(get_worker_info): @@ -211,10 +295,12 @@ def _refresh_component_worker_info( ): setattr(component_state.info, field_name, fresh_val) - def _refresh_gpu_counts(self) -> None: + def _refresh_gpu_counts(self, deployment: Optional[dict] = None) -> None: state = self.deployment_state() try: - prefill_gpus, decode_gpus = self.controller.get_gpu_counts( + prefill_gpus, decode_gpus = self._call_with_optional_deployment( + self.controller.get_gpu_counts, + deployment=deployment, require_prefill=self.require_prefill, require_decode=self.require_decode, ) @@ -249,6 +335,132 @@ def _refresh_gpu_counts(self) -> None: if self.require_decode: state.decode.num_gpus = decode_gpus + def _load_static_power_caps_at_startup( + self, deployment: Optional[dict] = None + ) -> None: + """Read DGD-owned per-GPU caps once at startup; fail closed if bad. + + Caps are startup-static for the Planner lifetime. DGD CRD transition + validation rejects changes to a power-annotated component's cap, + effective NVIDIA GPU count, or node count. Changing that tuple requires + deleting and recreating the DGD, then starting Planner against the new + settled deployment. + """ + if not self.config.enable_power_awareness: + return + + try: + prefill_cfg, decode_cfg = self._resolve_power_configs(deployment=deployment) + except Exception as exc: + raise DeploymentValidationError( + [f"Failed to resolve DGD-owned power caps at startup: {exc}"] + ) from exc + + errors: list[str] = [] + if self.require_prefill and prefill_cfg is None: + errors.append( + "Power awareness is on and prefill is required, but the connector " + "returned no prefill power config; cannot cache startup caps." + ) + if self.require_decode and decode_cfg is None: + errors.append( + "Power awareness is on and decode is required, but the connector " + "returned no decode power config; cannot cache startup caps." + ) + if errors: + raise DeploymentValidationError(errors) + + state = self.deployment_state() + if self.require_prefill and prefill_cfg is not None: + self._adopt_power_config(state.prefill, prefill_cfg) + if self.require_decode and decode_cfg is not None: + self._adopt_power_config(state.decode, decode_cfg) + self._validate_minimum_power_footprint(prefill_cfg, decode_cfg) + + def _resolve_power_configs( + self, + deployment: Optional[dict] = None, + ) -> tuple[Optional[ComponentPowerConfig], Optional[ComponentPowerConfig]]: + """Resolve DGD power configs with the same name/generic semantics as startup. + + Uses ``get_component_power_configs`` (explicit backend names + unique + generic ``type: worker`` fallback). Called at startup only to adopt + static caps. Never called at runtime — caps are startup-static. + """ + if not is_power_aware_connector(self.controller): + raise DeploymentValidationError( + [ + "Power awareness requires a connector that implements " + "PowerAwareConnector; this connector does not implement " + "get_component_power_configs." + ] + ) + + prefill_name, decode_name = self._power_component_names() + return self.controller.get_component_power_configs( + deployment=deployment, + require_prefill=self.require_prefill, + require_decode=self.require_decode, + prefill_component_name=prefill_name, + decode_component_name=decode_name, + ) + + def _power_component_names(self) -> tuple[Optional[str], Optional[str]]: + """Backend-default component names used as explicit-name fallbacks. + + Role resolution matches by ``type`` first (disagg) and by the unique + generic ``type: worker`` component (agg), so these names only matter + when the DGD renames a component; mirrors ``initialize()``. + """ + defaults = WORKER_COMPONENT_NAMES.get(self.config.backend) + prefill_name = ( + defaults.prefill_worker_k8s_name + if self.require_prefill and defaults + else None + ) + decode_name = ( + defaults.decode_worker_k8s_name + if self.require_decode and defaults + else None + ) + return prefill_name, decode_name + + @staticmethod + def _adopt_power_config( + component_state: ComponentState, cfg: ComponentPowerConfig + ) -> None: + component_state.power_gpu_limit_watts = cfg.gpu_power_limit_watts + component_state.power_watts_per_replica = cfg.watts_per_replica + + def _validate_minimum_power_footprint( + self, + prefill_cfg: Optional[ComponentPowerConfig], + decode_cfg: Optional[ComponentPowerConfig], + ) -> None: + """Fail closed at startup if the minimum footprint can't fit the budget. + + ``min_endpoint`` replicas of every required role must fit + ``total_gpu_power_limit``; otherwise the ceiling is unsatisfiable and + the planner must not start rather than clamp to an impossible target. + """ + budget = self.config.total_gpu_power_limit + if budget is None: + return + p_watts = prefill_cfg.watts_per_replica if prefill_cfg else None + d_watts = decode_cfg.watts_per_replica if decode_cfg else None + if not minimum_power_footprint_fits( + budget, self.config.min_endpoint, p_watts, d_watts + ): + raise DeploymentValidationError( + [ + "Infeasible power budget: minimum footprint " + f"(min_endpoint={self.config.min_endpoint} of " + f"prefill={p_watts}W, decode={d_watts}W per replica) exceeds " + f"total_gpu_power_limit={budget}W. Raise the budget or lower " + "the per-GPU caps on the worker podTemplate annotations." + ] + ) + async def _refresh_replica_counts(self) -> None: prefill_name = ( self._state.prefill.info.k8s_name @@ -260,14 +472,28 @@ async def _refresh_replica_counts(self) -> None: if self.require_decode and self._state.decode.info is not None else None ) - ( - prefill_count, - decode_count, - stable, - ) = await self.controller.get_actual_worker_counts( - prefill_component_name=prefill_name, - decode_component_name=decode_name, - ) + if self.config.enable_power_awareness: + if not is_power_aware_connector(self.controller): + raise DeploymentValidationError( + [ + "Power awareness requires a connector that implements " + "PowerAwareConnector (get_graph_deployment, " + "get_component_power_configs, " + "wait_for_settled_graph_deployment, " + "get_power_aware_worker_counts); " + "this connector does not." + ] + ) + counts = await self.controller.get_power_aware_worker_counts( + prefill_component_name=prefill_name, + decode_component_name=decode_name, + ) + else: + counts = await self.controller.get_actual_worker_counts( + prefill_component_name=prefill_name, + decode_component_name=decode_name, + ) + prefill_count, decode_count, stable = counts if self.require_prefill: self._state.prefill.replicas.active = prefill_count self._state.prefill.replicas.expected = prefill_count if stable else None diff --git a/components/src/dynamo/planner/environment/state.py b/components/src/dynamo/planner/environment/state.py index 4f0d16446cf0..7cbdd200aa22 100644 --- a/components/src/dynamo/planner/environment/state.py +++ b/components/src/dynamo/planner/environment/state.py @@ -22,6 +22,16 @@ class ComponentState: info: Optional[WorkerInfo] = None replicas: ReplicaState = field(default_factory=ReplicaState) num_gpus: Optional[int] = None + # DGD-owned per-GPU power cap (watts) parsed from this component's worker + # podTemplate annotation, and the already-multiplied per-replica draw + # (cap × get_total_gpu_count()). Both are startup-static for the Planner + # lifetime; DGD admission rejects tuple changes, which require DGD + # replacement and a new Planner. They stay None when power awareness is off. + # ``num_gpus`` deliberately stays on the per-pod ``get_gpu_count()`` — power + # awareness must not change GPU-budget math — while ``power_watts_per_replica`` + # uses the replica-wide (nodeCount × per-pod) GPU total. + power_gpu_limit_watts: Optional[int] = None + power_watts_per_replica: Optional[int] = None @dataclass diff --git a/components/src/dynamo/planner/errors.py b/components/src/dynamo/planner/errors.py index ae1ef5d31660..28eed45f5926 100644 --- a/components/src/dynamo/planner/errors.py +++ b/components/src/dynamo/planner/errors.py @@ -36,6 +36,9 @@ "DuplicateSubComponentError", "DeploymentValidationError", "EmptyTargetReplicasError", + "PowerAnnotationMissingError", + "PowerAnnotationInvalidError", + "RolloutFailedError", ] @@ -233,3 +236,80 @@ def __init__( ): message = "target_replicas cannot be empty" super().__init__(message) + + +class PowerAnnotationMissingError(ComponentError): + """Raised when a worker component has no per-GPU power-limit annotation. + + The per-GPU cap is authored on the worker component's + ``podTemplate.metadata.annotations`` (key + ``dynamo.nvidia.com/gpu-power-limit``); a missing key means the DGD did not + declare a cap for this role. When power awareness is enabled every managed + worker role must carry one, so the planner fails closed rather than + guessing a cap. + """ + + def __init__(self, component_name: str): + self.component_name = component_name + message = ( + f"Component '{component_name}' has no " + "'dynamo.nvidia.com/gpu-power-limit' annotation on its worker " + "podTemplate. Author the per-GPU cap on the DGD worker " + "podTemplate.metadata.annotations." + ) + super().__init__(message) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(component_name={self.component_name!r})" + + +class PowerAnnotationInvalidError(ComponentError): + """Raised when a per-GPU power-limit annotation is not a positive integer. + + The annotation value is watts and must parse to an integer ``> 0``. Empty, + non-numeric, zero, or negative values are configuration errors — the + planner cannot compute a power budget from them and refuses to silently + substitute a default. + """ + + def __init__(self, component_name: str, value: str): + self.component_name = component_name + self.value = value + message = ( + f"Component '{component_name}' has an invalid " + f"'dynamo.nvidia.com/gpu-power-limit' annotation {value!r}; " + "expected a positive integer number of watts." + ) + super().__init__(message) + + def __repr__(self) -> str: + return ( + f"{self.__class__.__name__}(" + f"component_name={self.component_name!r}, value={self.value!r})" + ) + + +class RolloutFailedError(PlannerError): + """Raised when the operator marks a DGD rolling update as Failed. + + Failed is a terminal rollout state (the operator sets ``endTime``). + Retrying until a generic timeout would leave the planner stuck for up to + 30 minutes; instead we surface this as an immediate actionable error so + the operator or user can investigate and recover. + """ + + def __init__(self, deployment_name: str, reason: str = ""): + self.deployment_name = deployment_name + self.reason = reason + detail = f": {reason}" if reason else "" + message = ( + f"DGD '{deployment_name}' rollingUpdate.phase is Failed{detail}. " + "Investigate the operator status and recover before restarting the planner." + ) + super().__init__(message) + + def __repr__(self) -> str: + return ( + f"{self.__class__.__name__}(" + f"deployment_name={self.deployment_name!r}, reason={self.reason!r})" + ) diff --git a/components/src/dynamo/planner/monitoring/dgd_services.py b/components/src/dynamo/planner/monitoring/dgd_services.py index 7b599755e75d..ed4454fc9da3 100644 --- a/components/src/dynamo/planner/monitoring/dgd_services.py +++ b/components/src/dynamo/planner/monitoring/dgd_services.py @@ -15,13 +15,19 @@ import logging import shlex +from dataclasses import dataclass from typing import Optional from pydantic import BaseModel from dynamo.common.utils.runtime import parse_endpoint from dynamo.planner.config.defaults import SubComponentType -from dynamo.planner.errors import DuplicateSubComponentError, SubComponentNotFoundError +from dynamo.planner.errors import ( + DuplicateSubComponentError, + PowerAnnotationInvalidError, + PowerAnnotationMissingError, + SubComponentNotFoundError, +) from dynamo.runtime.logging import configure_dynamo_logging configure_dynamo_logging() @@ -32,6 +38,19 @@ V1BETA1_GENERIC_WORKER_COMPONENT_TYPE = "worker" GPU_RESOURCE_KEY = "nvidia.com/gpu" +# Per-GPU power-limit annotation key (watts, positive integer). +# +# Ownership: this value is *authored* on the DGD worker component +# ``podTemplate.metadata.annotations`` by a human or the profiler. The operator +# renders it onto every worker Pod at create time; the Power Agent DaemonSet +# reads the *live Pod* annotation and applies the NVML/DCGM cap. The Planner +# only *reads* this value from the DGD to project a power budget — it never +# writes it onto Pods. The Power Agent +# keeps its own copy of this literal (deploy/power-agent/power_agent.py); the +# two are asserted identical by a contract test rather than shared as a package +# import, because the agent image does not install the ``dynamo`` package. +POWER_ANNOTATION_KEY = "dynamo.nvidia.com/gpu-power-limit" + def break_arguments(args: list[str] | None) -> list[str]: ans: list[str] = [] @@ -174,12 +193,104 @@ def get_gpu_count(self) -> int: ) try: - return int(gpu_str) + gpu_count = int(gpu_str) except (ValueError, TypeError) as err: raise ValueError( f"Invalid GPU count '{gpu_str}' for component '{self.name}'. " - f"GPU count must be an integer." + f"GPU count must be a positive integer." + ) from err + # A zero/negative GPU count is nonsensical and, for power projection, + # would make watts_per_replica zero — silently disabling enforcement for + # this role. Reject it so the deployment fails loudly instead. + if gpu_count <= 0: + raise ValueError( + f"Invalid GPU count '{gpu_str}' for component '{self.name}'. " + f"GPU count must be a positive integer." + ) + return gpu_count + + def get_node_count(self) -> int: + """Return multinode.nodeCount from the component spec, defaulting to 1. + + The operator CRD defines total GPUs as nodeCount × per-pod GPU request. + Single-node components either omit the field or set it to 1. + + Raises: + ValueError: nodeCount is present but not a positive integer (a + zero/negative value would zero out watts_per_replica and + silently disable power enforcement for the role). + """ + raw = self.service.get("multinode", {}).get("nodeCount", 1) + try: + node_count = int(raw) + except (ValueError, TypeError) as err: + raise ValueError( + f"Invalid multinode.nodeCount '{raw}' for component " + f"'{self.name}'. nodeCount must be a positive integer." ) from err + if node_count <= 0: + raise ValueError( + f"Invalid multinode.nodeCount '{raw}' for component " + f"'{self.name}'. nodeCount must be a positive integer." + ) + return node_count + + def get_total_gpu_count(self) -> int: + """Return total GPUs consumed by one replica: get_gpu_count() × get_node_count(). + + For single-node components this equals get_gpu_count(). For multinode + components the operator allocates nodeCount pods per replica each + carrying the same per-pod GPU request, so power projection must + multiply both factors. + """ + return self.get_gpu_count() * self.get_node_count() + + def get_gpu_power_limit_annotation(self) -> str: + """Return the raw ``dynamo.nvidia.com/gpu-power-limit`` annotation string. + + Validates the annotation (same rules as ``get_gpu_power_limit_watts``) + but returns the original string rather than the parsed integer. The + operator propagates the raw DGD podTemplate annotation verbatim onto + each Pod, so callers that build settlement expected-values must use + this raw string — not the canonical ``str(int)`` — to get an exact + match against what the Pod actually carries. + + Raises: + PowerAnnotationMissingError: annotation key is absent. + PowerAnnotationInvalidError: value is empty, non-integer, or <= 0. + """ + annotations = ( + self.service.get("podTemplate", {}).get("metadata", {}).get("annotations") + or {} + ) + raw = annotations.get(POWER_ANNOTATION_KEY) + if raw is None: + raise PowerAnnotationMissingError(self.name) + raw_str = str(raw) + try: + watts = int(raw_str.strip()) + except (ValueError, TypeError) as err: + raise PowerAnnotationInvalidError(self.name, raw_str) from err + if watts <= 0: + raise PowerAnnotationInvalidError(self.name, raw_str) + return raw_str + + def get_gpu_power_limit_watts(self) -> int: + """Return ``dynamo.nvidia.com/gpu-power-limit`` as a validated integer. + + The per-GPU cap is read from the worker component's + ``podTemplate.metadata.annotations``. This is the *desired* static cap + the operator stamps onto Pods and the Power Agent enforces; the Planner + only reads it for power projection. + + For verbatim annotation comparison (settlement), use + ``get_gpu_power_limit_annotation()`` instead. + + Raises: + PowerAnnotationMissingError: annotation key is absent. + PowerAnnotationInvalidError: value is empty, non-integer, or <= 0. + """ + return int(self.get_gpu_power_limit_annotation().strip()) def get_component_from_type_or_name( @@ -220,3 +331,146 @@ def get_component_from_type_or_name( name, component = matching_components[0] return Service(name=name, service=component) + + +@dataclass(frozen=True) +class ComponentPowerConfig: + """Resolved per-role power facts for one worker component. + + Built by :func:`resolve_component_power_configs` from the DGD-owned per-GPU + annotation and the component's per-replica GPU total. ``watts_per_replica`` + is the value the power-budget projection and clamp consume. + """ + + component_name: str + role: str # prefill | decode | worker + gpu_power_limit_watts: int + gpus_per_replica: int # Service.get_total_gpu_count() (nodeCount × per-pod GPUs) + + @property + def watts_per_replica(self) -> int: + return self.gpu_power_limit_watts * self.gpus_per_replica + + +def _resolve_one_power_service( + deployment: dict, + sub_component_type: SubComponentType, + component_name: Optional[str], +) -> Service: + """Resolve a single role's worker Service without reading the power annotation. + + Role/name resolution reuses ``get_component_from_type_or_name`` for disagg + typed roles (including untyped components matched by explicit name). For agg + (single generic ``type: worker``), the fallback is scoped to this power + parser only — not the shared component resolver. + """ + try: + return get_component_from_type_or_name( + deployment, sub_component_type, component_name=component_name + ) + except SubComponentNotFoundError: + if sub_component_type != SubComponentType.DECODE: + raise + components = get_components_by_name(deployment) + generic_workers = [ + (curr_name, curr_component) + for curr_name, curr_component in components.items() + if get_component_type(curr_component) + == V1BETA1_GENERIC_WORKER_COMPONENT_TYPE + ] + if len(generic_workers) == 1: + name, component = generic_workers[0] + return Service(name=name, service=component) + if len(generic_workers) > 1: + component_names = [name for name, _ in generic_workers] + raise DuplicateSubComponentError(sub_component_type.value, component_names) + raise + + +def _resolve_one_power_config( + deployment: dict, + sub_component_type: SubComponentType, + component_name: Optional[str], +) -> ComponentPowerConfig: + """Resolve a single role's power config, or raise a typed error.""" + service = _resolve_one_power_service(deployment, sub_component_type, component_name) + watts = service.get_gpu_power_limit_watts() + gpus_per_replica = service.get_total_gpu_count() + role = get_component_type(service.service) or sub_component_type.value + return ComponentPowerConfig( + component_name=service.name, + role=role, + gpu_power_limit_watts=watts, + gpus_per_replica=gpus_per_replica, + ) + + +def resolve_power_component_names( + deployment: dict, + *, + require_prefill: bool, + require_decode: bool, + prefill_name: Optional[str] = None, + decode_name: Optional[str] = None, +) -> list[str]: + """Return DGD component names whose Pods must carry the current power annotation. + + Uses the same role/name resolution as :func:`resolve_component_power_configs` + (typed roles, explicit-name fallback for untyped workers, unique generic + ``type: worker`` for agg) but does not read the power annotation — so the + pod-annotation settlement gate can run before cap validation. + """ + names: list[str] = [] + if require_prefill: + names.append( + _resolve_one_power_service( + deployment, SubComponentType.PREFILL, prefill_name + ).name + ) + if require_decode: + names.append( + _resolve_one_power_service( + deployment, SubComponentType.DECODE, decode_name + ).name + ) + # Preserve order but drop duplicates (agg decode-only should be unique). + seen: set[str] = set() + ordered: list[str] = [] + for name in names: + if name not in seen: + seen.add(name) + ordered.append(name) + return ordered + + +def resolve_component_power_configs( + deployment: dict, + *, + require_prefill: bool, + require_decode: bool, + prefill_name: Optional[str] = None, + decode_name: Optional[str] = None, +) -> tuple[Optional[ComponentPowerConfig], Optional[ComponentPowerConfig]]: + """Resolve (prefill, decode) power configs from a DGD dict. + + Returns ``None`` for a role that is not required. Aggregate mode follows + existing Planner semantics — ``require_prefill=False, require_decode=True`` + — and resolves the unique generic ``type: worker`` component as the decode + slot; it does not manufacture a prefill config for that single worker. + + Raises the typed parser errors (``SubComponentNotFoundError``, + ``DuplicateSubComponentError``, ``PowerAnnotationMissingError``, + ``PowerAnnotationInvalidError``, or ``ValueError`` for a bad GPU count) so + the caller can decide startup-fail vs runtime-conservative handling. + """ + prefill_config = None + decode_config = None + if require_prefill: + prefill_config = _resolve_one_power_config( + deployment, SubComponentType.PREFILL, prefill_name + ) + if require_decode: + decode_config = _resolve_one_power_config( + deployment, SubComponentType.DECODE, decode_name + ) + return prefill_config, decode_config diff --git a/components/src/dynamo/planner/monitoring/planner_metrics.py b/components/src/dynamo/planner/monitoring/planner_metrics.py index 5cfb8788b051..e4a21fe61bf6 100644 --- a/components/src/dynamo/planner/monitoring/planner_metrics.py +++ b/components/src/dynamo/planner/monitoring/planner_metrics.py @@ -179,6 +179,21 @@ def __init__(self) -> None: labelnames=_engine_labels, ) + # -- Power-aware budget (DGD-owned caps; read-only) --------------- + self.power_budget_total_watts = Gauge( + f"{PREFIX}_power_budget_total_watts", + "Configured total GPU power budget for this DGD (watts).", + ) + self.power_projected_watts = Gauge( + f"{PREFIX}_power_projected_watts", + "Projected GPU power draw at current replica counts and " + "DGD-resolved per-GPU caps (watts).", + ) + self.power_budget_utilization = Gauge( + f"{PREFIX}_power_budget_utilization", + "Ratio of projected power to total budget (0.0–1.0+).", + ) + # --------------------------------------------------------------------------- # Plugin-framework metrics diff --git a/components/src/dynamo/planner/plugins/orchestrator/engine_adapter.py b/components/src/dynamo/planner/plugins/orchestrator/engine_adapter.py index 4572031064bc..8613b5451feb 100644 --- a/components/src/dynamo/planner/plugins/orchestrator/engine_adapter.py +++ b/components/src/dynamo/planner/plugins/orchestrator/engine_adapter.py @@ -68,6 +68,7 @@ import grpc.aio from dynamo.planner.core.budget import ( + apply_power_budget, proportional_clamp_pair, proportional_clamp_single, ) @@ -77,7 +78,6 @@ PlannerEffects, ScalingDecision, ScheduledTick, - TickDiagnostics, TickInput, TrafficObservation, WorkerCapabilities, @@ -174,6 +174,9 @@ def __init__( self._last_tick_monotonic: float = 0.0 self._last_load_loop_monotonic: float = 0.0 self._last_throughput_loop_monotonic: float = 0.0 + # Emit one rollout-hold warning per continuous mid-rollout stretch; + # reset when the deployment is stable again so the next rollout warns. + self._power_rollout_hold_warned: bool = False # Plugin-framework metrics live alongside the adapter so they # share the orchestrator's lifecycle. Use the default global @@ -644,130 +647,6 @@ async def observe(self, scheduled_tick: ScheduledTick, now_s: float) -> TickInpu ) return response.tick_input - def _project_load_diagnostics(self, diagnostics: TickDiagnostics) -> None: - """Read ``BuiltinLoadPropose._last_load_diagnostics`` and write - to ``diagnostics.load_decision_reason*`` + ``estimated_*_ms``. - - Mirrors the builtin planner diagnostic surface: - - mode=agg → aggregate ``load_decision_reason`` - - mode=disagg → per-component ``load_decision_reason_prefill`` / - ``_decode`` (and also the aggregate, set to whichever side - has a stronger signal; see ``_aggregate_disagg_load_reason``) - - mode=prefill/decode → aggregate reason from the single side - """ - propose = self._builtins.get("load_propose") - if propose is None: - return - d = getattr(propose, "_last_load_diagnostics", None) - if d is None: - return - - mode = self._config.mode - if mode == "agg": - diagnostics.load_decision_reason = d.get("agg") - elif mode == "disagg": - diagnostics.load_decision_reason_prefill = d.get("prefill") - diagnostics.load_decision_reason_decode = d.get("decode") - # Aggregate: prefer scale_up > scale_down > no_change > - # . Lets a single dashboard widget show "what - # did the load path do" without dropping into the per- - # component detail. - diagnostics.load_decision_reason = self._aggregate_disagg_load_reason( - d.get("prefill"), d.get("decode") - ) - elif mode in ("prefill", "decode"): - diagnostics.load_decision_reason = d.get(mode) - - diagnostics.estimated_ttft_ms = d.get("estimated_ttft_ms") - diagnostics.estimated_itl_ms = d.get("estimated_itl_ms") - - def _project_throughput_diagnostics(self, diagnostics: TickDiagnostics) -> None: - """Read ``BuiltinThroughputPropose._last_throughput_diagnostics`` - and write to ``diagnostics.throughput_decision_reason*``. - - Symmetric with ``_project_load_diagnostics``: throughput proposal - records per-component reasons and this helper projects them onto - the public ``TickDiagnostics`` fields. - - Mode mapping: - - mode=agg → aggregate ``throughput_decision_reason`` - - mode=disagg → per-component - ``throughput_decision_reason_prefill``/``_decode`` plus the - aggregate (precedence via ``_aggregate_disagg_throughput_reason``) - - mode=prefill/decode → aggregate from the single side - """ - propose = self._builtins.get("throughput_propose") - if propose is None: - return - d = getattr(propose, "_last_throughput_diagnostics", None) - if d is None: - return - - mode = self._config.mode - if mode == "agg": - diagnostics.throughput_decision_reason = d.get("agg") - elif mode == "disagg": - diagnostics.throughput_decision_reason_prefill = d.get("prefill") - diagnostics.throughput_decision_reason_decode = d.get("decode") - diagnostics.throughput_decision_reason = ( - self._aggregate_disagg_throughput_reason( - d.get("prefill"), d.get("decode") - ) - ) - elif mode in ("prefill", "decode"): - diagnostics.throughput_decision_reason = d.get(mode) - - @staticmethod - def _aggregate_disagg_load_reason( - prefill_reason: Optional[str], decode_reason: Optional[str] - ) -> Optional[str]: - """Collapse two per-component reasons to a single aggregate - string. Precedence keeps "a side scaled" - wins over "both stable", "stable with data" wins over "no - data".""" - priority = [ - "scale_up", - "scale_down_capped_by_throughput", - "scale_down", - "no_change", - "insufficient_data", - "worker_count_mismatch", - "scaling_in_progress", - "no_fpm_data", - "disabled", - ] - pairs = [r for r in (prefill_reason, decode_reason) if r is not None] - if not pairs: - return None - for p in priority: - if p in pairs: - return p - return pairs[0] - - @staticmethod - def _aggregate_disagg_throughput_reason( - prefill_reason: Optional[str], decode_reason: Optional[str] - ) -> Optional[str]: - """Collapse two per-component throughput reasons. Vocabulary - differs from load reasons (no scale_up/down enums on this - side); ranking keeps "stronger action wins": - ``scale`` > ``set_lower_bound`` > skip reasons.""" - priority = [ - "scale", - "set_lower_bound", - "model_not_ready", - "no_traffic_data", - "predict_failed", - "disabled", - ] - pairs = [r for r in (prefill_reason, decode_reason) if r is not None] - if not pairs: - return None - for p in priority: - if p in pairs: - return p - return pairs[0] - async def shutdown(self) -> None: # Stop the gateway BEFORE unregistering plugins so no new # external Register / Heartbeat call can race the teardown. @@ -1031,7 +910,13 @@ def _baseline_from_worker_counts( def _project_scale_to(self, outcome, worker_counts: WorkerCounts): """Project the pipeline outcome onto ``PlannerEffects.scale_to`` - with planner "no change -> None" detection.""" + with planner "no change -> None" detection. + + ``type_aware_merge`` fills omitted roles from the ready-count baseline. + ``PipelineOutcome.proposed_components`` preserves which roles PROPOSE + actually targeted before that merge, so the power path can charge + baseline peers without treating them as adjustable targets. + """ if outcome.execute_action != "apply" or outcome.final_proposal is None: return None @@ -1044,17 +929,45 @@ def _project_scale_to(self, outcome, worker_counts: WorkerCounts): current_p = worker_counts.ready_num_prefill current_d = worker_counts.ready_num_decode - p_unchanged = (num_p is None) or (num_p == current_p) - d_unchanged = (num_d is None) or (num_d == current_d) - if p_unchanged and d_unchanged: - return None + if self._config.enable_power_awareness: + # Restore the explicit PROPOSE-stage mask before the final budget + # boundary. Omitted roles are still charged via ``current_*`` inside + # the clamps, but can never become emitted targets. + if ComponentKey(sub_component_type="prefill") not in ( + outcome.proposed_components + ): + num_p = None + if ComponentKey(sub_component_type="decode") not in ( + outcome.proposed_components + ): + num_d = None + if num_p is None and num_d is None: + return None + else: + p_unchanged = (num_p is None) or (num_p == current_p) + d_unchanged = (num_d is None) or (num_d == current_d) + if p_unchanged and d_unchanged: + return None num_p, num_d = self._apply_final_budget(num_p, num_d, worker_counts) - p_unchanged = (num_p is None) or (num_p == current_p) - d_unchanged = (num_d is None) or (num_d == current_d) - if p_unchanged and d_unchanged: - return None + if self._config.enable_power_awareness: + # Suppress only a proven stable no-op. During a rollout ``expected`` + # is unknown, so an explicit target equal to transient ready may be + # intentional cancellation of the in-flight desired count. + expected_p = worker_counts.expected_num_prefill + expected_d = worker_counts.expected_num_decode + if num_p is not None and expected_p is not None and num_p == expected_p: + num_p = None + if num_d is not None and expected_d is not None and num_d == expected_d: + num_d = None + if num_p is None and num_d is None: + return None + else: + p_unchanged = (num_p is None) or (num_p == current_p) + d_unchanged = (num_d is None) or (num_d == current_d) + if p_unchanged and d_unchanged: + return None return ScalingDecision(num_prefill=num_p, num_decode=num_d) @@ -1064,6 +977,171 @@ def _apply_final_budget( num_d: Optional[int], worker_counts: WorkerCounts, ) -> tuple[Optional[int], Optional[int]]: + """Final invariant boundary: GPU budget then power budget. + + Order is deliberate and non-commutative — the GPU clamp fits replica + counts to the GPU band first, then the power clamp holds the result to + the projected ``total_gpu_power_limit`` (a bound on projected draw from + the requested caps, not a proven hardware limit). Applied here once, it + covers builtin and external-plugin proposals alike. + """ + proposed_p, proposed_d = num_p, num_d + num_p, num_d = self._apply_gpu_final_budget(num_p, num_d, worker_counts) + return self._apply_power_final_budget( + num_p, + num_d, + worker_counts, + proposed_before_gpu=(proposed_p, proposed_d), + ) + + def _hold_scale_up_during_rollout( + self, + num_p: Optional[int], + num_d: Optional[int], + ready_p: Optional[int], + ready_d: Optional[int], + p_watts: Optional[int], + d_watts: Optional[int], + worker_counts: WorkerCounts, + ) -> tuple[Optional[int], Optional[int]]: + """Hold every scale-up at its ready count while ANY power-relevant role + is mid-rollout (conservative, fail-closed). + + The Kubernetes environment tracks a single deployment-wide stability + flag, so a rollout of *either* role marks *both* roles' ``expected`` + (settled) count unknown (None) — there is no per-role desired target to + reason about. A rolling role's settled power can only be charged at its + transient ready count, which undercounts it, so while any role rolls no + role may scale up above its ready count; otherwise the settled total (the + rolling role at its unknown-but-larger desired plus another role grown) + can exceed the budget. Scale-downs stay allowed. A held scale-up becomes + ``None`` immediately, so the already-issued rollout's DGD desired is left + untouched even when the other role legitimately scales down this tick. + + Rollout *state*, not None targets, is the signal — ``type_aware_merge`` + fills a role a plugin omitted from the baseline, so the proposal usually + carries a target for every role. (A future per-role desired/stability + connector contract could relax this to only the roles actually rolling.) + """ + + def _rolling(ready, expected, watts): + return ready is not None and expected is None and bool(watts) + + any_rolling = _rolling( + ready_p, worker_counts.expected_num_prefill, p_watts + ) or _rolling(ready_d, worker_counts.expected_num_decode, d_watts) + if not any_rolling: + self._power_rollout_hold_warned = False + return num_p, num_d + + held_roles: list[str] = [] + if num_p is not None and ready_p is not None and num_p > ready_p: + held_roles.append(f"prefill at {ready_p} (proposed {num_p})") + num_p = None + if num_d is not None and ready_d is not None and num_d > ready_d: + held_roles.append(f"decode at {ready_d} (proposed {num_d})") + num_d = None + if held_roles and not self._power_rollout_hold_warned: + log.warning( + "power budget: holding %s — a power-relevant role is " + "mid-rollout with an unknown settled target, so a scale-up " + "cannot be safely budgeted this tick (further holds this " + "rollout are silent)", + "; ".join(held_roles), + ) + self._power_rollout_hold_warned = True + return num_p, num_d + + def _apply_power_final_budget( + self, + num_p: Optional[int], + num_d: Optional[int], + worker_counts: WorkerCounts, + proposed_before_gpu: Optional[tuple[Optional[int], Optional[int]]] = None, + ) -> tuple[Optional[int], Optional[int]]: + """Clamp the GPU-clamped proposal to the DGD-owned power budget. + + Reads startup-cached per-replica watts from ``WorkerCapabilities`` (no + DGD I/O). No-op unless power awareness is on and a total budget is + configured. Power wins over the GPU floor when they conflict — this + runs after the GPU clamp and only lowers counts. + + Fails closed during a rollout: while any power-relevant role is + mid-rollout (its settled target unknown), every role's scale-up is held + at its ready count — see ``_hold_scale_up_during_rollout`` — so a + proposal cannot admit an over-budget settled state. + """ + if not self._config.enable_power_awareness: + return num_p, num_d + budget = self._config.total_gpu_power_limit + if budget is None: + return num_p, num_d + + p_caps = self._capabilities.prefill + d_caps = self._capabilities.decode + p_watts = p_caps.power_watts_per_replica if p_caps else None + d_watts = d_caps.power_watts_per_replica if d_caps else None + + ready_p = worker_counts.ready_num_prefill + ready_d = worker_counts.ready_num_decode + + num_p, num_d = self._hold_scale_up_during_rollout( + num_p, num_d, ready_p, ready_d, p_watts, d_watts, worker_counts + ) + + new_p, new_d, reason = apply_power_budget( + num_p, + num_d, + ready_p, + ready_d, + p_watts, + d_watts, + budget, + self._config.min_endpoint, + ) + if reason is not None and (new_p, new_d) != (num_p, num_d): + gpu_then_power = "" + if proposed_before_gpu is not None and proposed_before_gpu != ( + num_p, + num_d, + ): + gpu_then_power = ( + f" [GPU clamp first adjusted proposed " + f"prefill {proposed_before_gpu[0]}->{num_p} " + f"decode {proposed_before_gpu[1]}->{num_d}; " + f"power wins over GPU floor]" + ) + log.warning( + "power budget clamp (%s): prefill %s->%s decode %s->%s " + "(budget=%sW, prefill=%sW/replica, decode=%sW/replica)%s", + reason, + num_p, + new_p, + num_d, + new_d, + budget, + p_watts, + d_watts, + gpu_then_power, + ) + return new_p, new_d + + def _apply_gpu_final_budget( + self, + num_p: Optional[int], + num_d: Optional[int], + worker_counts: WorkerCounts, + ) -> tuple[Optional[int], Optional[int]]: + """Clamp proposed counts to the GPU budget band. + + Disagg proposals that name both roles use a joint proportional clamp. + When power awareness is on and exactly one role is proposed (the + power-induced proposal-mask path), the peer is charged at its ready + count and the adjustable role is sized against the residual GPU + ceiling/floor — joint-then-discard would leave the applied state over + ``max_gpu_budget``. Power-off disagg keeps the historical joint clamp + and discards the unproposed role's result. + """ min_endpoint = self._config.min_endpoint min_gpus = self._config.min_gpu_budget max_gpus = self._config.max_gpu_budget @@ -1097,8 +1175,10 @@ def clamp_single(component: str, replicas: Optional[int]) -> Optional[int]: proposed_p = num_p is not None proposed_d = num_d is not None - base_p = num_p if proposed_p else worker_counts.ready_num_prefill - base_d = num_d if proposed_d else worker_counts.ready_num_decode + ready_p = worker_counts.ready_num_prefill + ready_d = worker_counts.ready_num_decode + base_p = num_p if proposed_p else ready_p + base_d = num_d if proposed_d else ready_d if base_p is None or base_d is None: return clamp_single("prefill", num_p), clamp_single("decode", num_d) @@ -1112,6 +1192,82 @@ def clamp_single(component: str, replicas: Optional[int]) -> Optional[int]: max(base_d, min_endpoint) if proposed_d else None, ) + # Both roles proposed: joint proportional clamp (unchanged). + if proposed_p and proposed_d: + clamped_p, clamped_d = proportional_clamp_pair( + max(base_p, min_endpoint), + max(base_d, min_endpoint), + p_gpu, + d_gpu, + min_gpus, + max_gpus, + min_endpoint, + ) + return clamped_p, clamped_d + + if not proposed_p and not proposed_d: + return None, None + + # Power-awareness collapses ready-equal peers to None before this + # clamp, which makes the latent joint-then-discard over-ceiling bug + # reachable on ordinary one-role proposals. Residual sizing is gated + # to that power path so power-off disagg keeps historical joint-clamp + # behavior (see Ted P2 on #12012). A general residual GPU-budget + # correction belongs in a focused follow-up. + if self._config.enable_power_awareness: + # base_* already proved ready_peer is non-None above. + if proposed_p: + assert ready_d is not None + fixed_gpus = ready_d * d_gpu + residual_max = max(0, max_gpus - fixed_gpus) if max_gpus >= 0 else -1 + residual_min = ( + -1 + if min_gpus < 0 or (min_gpus - fixed_gpus) <= 0 + else (min_gpus - fixed_gpus) + ) + desired_p = max(base_p, min_endpoint) + # When the fixed peer alone meets/exceeds the ceiling, + # proportional_clamp_single would return 0 (infeasible). Hold + # at ready instead — never emit a spurious scale-to-zero. + if residual_max >= 0 and residual_max < min_endpoint * p_gpu: + if ready_p is None: + return None, None + return min(desired_p, ready_p), None + return ( + proportional_clamp_single( + desired_p, + p_gpu, + residual_min, + residual_max, + min_endpoint, + ), + None, + ) + assert ready_p is not None + fixed_gpus = ready_p * p_gpu + residual_max = max(0, max_gpus - fixed_gpus) if max_gpus >= 0 else -1 + residual_min = ( + -1 + if min_gpus < 0 or (min_gpus - fixed_gpus) <= 0 + else (min_gpus - fixed_gpus) + ) + desired_d = max(base_d, min_endpoint) + if residual_max >= 0 and residual_max < min_endpoint * d_gpu: + if ready_d is None: + return None, None + return None, min(desired_d, ready_d) + return ( + None, + proportional_clamp_single( + desired_d, + d_gpu, + residual_min, + residual_max, + min_endpoint, + ), + ) + + # Power off: historical joint clamp, then discard the unproposed role. clamped_p, clamped_d = proportional_clamp_pair( max(base_p, min_endpoint), max(base_d, min_endpoint), @@ -1122,6 +1278,3 @@ def clamp_single(component: str, replicas: Optional[int]) -> Optional[int]: min_endpoint, ) return clamped_p if proposed_p else None, clamped_d if proposed_d else None - - -__all__ = ["OrchestratorEngineAdapter"] diff --git a/components/src/dynamo/planner/plugins/orchestrator/pipeline.py b/components/src/dynamo/planner/plugins/orchestrator/pipeline.py index 65475b1e7572..b71cb05c7a51 100644 --- a/components/src/dynamo/planner/plugins/orchestrator/pipeline.py +++ b/components/src/dynamo/planner/plugins/orchestrator/pipeline.py @@ -103,6 +103,7 @@ class PipelineOutcome: propose_outcome: Optional[MergeOutcome] = None reconcile_outcome: Optional[MergeOutcome] = None constrain_outcome: Optional[MergeOutcome] = None + proposed_components: frozenset[ComponentKey] = field(default_factory=frozenset) audit_events: list[str] = field(default_factory=list) @@ -243,6 +244,24 @@ def _proposal_to_baseline( return out +def _proposed_component_mask( + plugin_results: list[PluginResult], +) -> frozenset[ComponentKey]: + """Return components explicitly targeted by PROPOSE-stage overrides. + + Merge baselines deliberately fill omitted components with current replica + counts. Preserve the original target set before that happens so downstream + projection never has to infer provenance from target values. + """ + return frozenset( + ComponentKey(sub_component_type=target.sub_component_type) + for plugin_result in plugin_results + if isinstance(plugin_result.result, OverrideResult) + for target in plugin_result.result.targets + if target.replicas is not None + ) + + def _stage_request( stage: str, ctx: PipelineContext, @@ -783,6 +802,7 @@ async def _body() -> PipelineOutcome: clock=clock, metrics=metrics, ) + proposed_components = _proposed_component_mask(propose_plugin_results) if propose.short_circuited: return PipelineOutcome( execute_action="skip_short_circuit", @@ -790,6 +810,7 @@ async def _body() -> PipelineOutcome: short_circuit_reason=propose.short_circuit_reason, predict_outcome=ca, propose_outcome=propose, + proposed_components=proposed_components, audit_events=audit, ) if propose.proposal is not None: @@ -822,6 +843,7 @@ async def _body() -> PipelineOutcome: predict_outcome=ca, propose_outcome=propose, reconcile_outcome=reconcile, + proposed_components=proposed_components, audit_events=audit, ) if reconcile.proposal is not None: @@ -852,6 +874,7 @@ async def _body() -> PipelineOutcome: propose_outcome=propose, reconcile_outcome=reconcile, constrain_outcome=constrain, + proposed_components=proposed_components, audit_events=audit, ) @@ -868,6 +891,7 @@ async def _body() -> PipelineOutcome: propose_outcome=propose, reconcile_outcome=reconcile, constrain_outcome=constrain, + proposed_components=proposed_components, audit_events=audit, ) @@ -878,6 +902,7 @@ async def _body() -> PipelineOutcome: propose_outcome=propose, reconcile_outcome=reconcile, constrain_outcome=constrain, + proposed_components=proposed_components, audit_events=audit, ) diff --git a/components/src/dynamo/planner/tests/integration/test_power_no_mutation.py b/components/src/dynamo/planner/tests/integration/test_power_no_mutation.py new file mode 100644 index 000000000000..91c8b493f720 --- /dev/null +++ b/components/src/dynamo/planner/tests/integration/test_power_no_mutation.py @@ -0,0 +1,162 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Integration gate: DGD → resolve → project → clamp, with ZERO Pod mutation. + +This is the control-plane half of the power e2e ladder (``gpu_0``; hardware NVML +enforcement is a separate GPU-gated test). It wires a real ``KubernetesConnector`` +over a mocked Kubernetes API, resolves DGD-owned caps, projects the power +budget, clamps an over-budget proposal through the real engine-adapter final +boundary, and asserts the mocked CoreV1 saw **no** ``patch_namespaced_pod`` +call — the hard no-mutation gate. No live cluster, no GPU. +""" + +import os +from types import SimpleNamespace +from unittest.mock import patch + +import pytest + +from dynamo.planner.connectors.kubernetes import KubernetesConnector +from dynamo.planner.core.budget import project_watts +from dynamo.planner.core.types import ( + EngineCapabilities, + WorkerCapabilities, + WorkerCounts, +) +from dynamo.planner.plugins.orchestrator.engine_adapter import OrchestratorEngineAdapter + +pytestmark = [ + pytest.mark.gpu_0, + pytest.mark.pre_merge, + pytest.mark.integration, + pytest.mark.planner, +] + +_DGD = { + "metadata": {"name": "power-aware-example"}, + "spec": { + "components": [ + { + "name": "VllmPrefillWorker", + "type": "prefill", + "replicas": 2, + "podTemplate": { + "metadata": { + "annotations": {"dynamo.nvidia.com/gpu-power-limit": "350"} + }, + "spec": { + "containers": [ + { + "name": "main", + "resources": {"limits": {"nvidia.com/gpu": "2"}}, + } + ] + }, + }, + }, + { + "name": "VllmDecodeWorker", + "type": "decode", + "replicas": 2, + "podTemplate": { + "metadata": { + "annotations": {"dynamo.nvidia.com/gpu-power-limit": "300"} + }, + "spec": { + "containers": [ + { + "name": "main", + "resources": {"limits": {"nvidia.com/gpu": "4"}}, + } + ] + }, + }, + }, + ] + }, +} + + +@pytest.fixture +def k8s(): + """A KubernetesConnector whose apiserver client is fully mocked.""" + with ( + patch("dynamo.planner.connectors.clients.kubernetes_api.config"), + patch( + "dynamo.planner.connectors.clients.kubernetes_api.client.CoreV1Api" + ) as core, + patch( + "dynamo.planner.connectors.clients.kubernetes_api.client.CustomObjectsApi" + ) as custom, + patch.dict(os.environ, {"DYN_PARENT_DGD_K8S_NAME": "power-aware-example"}), + ): + custom_api = custom.return_value + custom_api.get_namespaced_custom_object.return_value = _DGD + connector = KubernetesConnector("test-ns") + yield connector, core + + +def _bare_adapter(capabilities): + adapter = object.__new__(OrchestratorEngineAdapter) + adapter._config = SimpleNamespace( + enable_power_awareness=True, + total_gpu_power_limit=5000, + min_endpoint=1, + min_gpu_budget=-1, + max_gpu_budget=-1, + mode="disagg", + ) + adapter._capabilities = capabilities + adapter._power_rollout_hold_warned = False + return adapter + + +def test_resolve_project_clamp_never_patches_pods(k8s): + connector, core_v1_cls = k8s + + # 1. Resolve DGD-owned caps (read-only GET, no Pod write). + prefill_cfg, decode_cfg = connector.get_component_power_configs() + assert prefill_cfg.watts_per_replica == 700 # 2 GPU × 350 W + assert decode_cfg.watts_per_replica == 1200 # 4 GPU × 300 W + + # 2. Project the budget at the initial replica counts (2 prefill, 2 decode). + projected = project_watts( + 2, 2, prefill_cfg.watts_per_replica, decode_cfg.watts_per_replica + ) + assert projected == 2 * 700 + 2 * 1200 # 3800 W of a 5000 W budget + + # 3. Clamp an over-budget scale-up proposal through the real final boundary. + caps = WorkerCapabilities( + prefill=EngineCapabilities( + num_gpu=2, power_watts_per_replica=prefill_cfg.watts_per_replica + ), + decode=EngineCapabilities( + num_gpu=4, power_watts_per_replica=decode_cfg.watts_per_replica + ), + ) + adapter = _bare_adapter(caps) + # Stable deployment: pin expected == ready so this exercises the power + # proportional clamp, not the rollout hold (which keys off expected=None). + wc = WorkerCounts( + ready_num_prefill=2, + ready_num_decode=2, + expected_num_prefill=2, + expected_num_decode=2, + ) + new_p, new_d = adapter._apply_final_budget(4, 4, wc) # 4*700 + 4*1200 = 7600 > 5000 + assert new_p is not None and new_d is not None + assert (new_p, new_d) != (4, 4) # proportional clamp actually ran + assert new_p * 700 + new_d * 1200 <= 5000 # clamped to fit + + # 4. HARD GATE: the write surface does not exist and was not called. + # CoreV1Api is instantiated (it is present in the implementation for + # pod-annotation startup settlement), but this flow does not exercise + # settlement, so list is not asserted here. The gate proves only that + # the forbidden patch surface is absent and was never invoked. + core_v1_cls.assert_called_once() + core_v1_instance = core_v1_cls.return_value + core_v1_instance.patch_namespaced_pod.assert_not_called() + core_v1_instance.patch_namespaced_pod_status.assert_not_called() + assert not hasattr(connector.kube_api, "patch_pod_annotation") + assert not hasattr(connector.kube_api, "remove_pod_annotation") diff --git a/components/src/dynamo/planner/tests/plugins/orchestrator/test_engine_adapter.py b/components/src/dynamo/planner/tests/plugins/orchestrator/test_engine_adapter.py index 0f5d581f58b0..eda324b2b3ae 100644 --- a/components/src/dynamo/planner/tests/plugins/orchestrator/test_engine_adapter.py +++ b/components/src/dynamo/planner/tests/plugins/orchestrator/test_engine_adapter.py @@ -35,7 +35,7 @@ WorkerCounts, ) from dynamo.planner.plugins.clock import Clock, VirtualClock -from dynamo.planner.plugins.merge.types import ChainAugmentOutcome +from dynamo.planner.plugins.merge.types import ChainAugmentOutcome, ComponentKey from dynamo.planner.plugins.orchestrator.engine_adapter import OrchestratorEngineAdapter from dynamo.planner.plugins.orchestrator.pipeline import PipelineOutcome from dynamo.planner.plugins.types import ComponentTarget, ScalingProposal @@ -282,10 +282,19 @@ def test_observe_fpm_feeds_installed_regression_without_crashing_disagg(): ) -def _apply_outcome(targets): +def _apply_outcome(targets, *, proposed=None): + if proposed is None: + proposed = { + target.sub_component_type + for target in targets + if target.replicas is not None + } return PipelineOutcome( execute_action="apply", final_proposal=ScalingProposal(targets=targets), + proposed_components=frozenset( + ComponentKey(sub_component_type=component) for component in proposed + ), ) @@ -364,6 +373,12 @@ def test_project_scale_to_applies_final_gpu_budget_to_external_proposal(): def test_project_scale_to_budget_preserves_single_component_target_mask(): + """Decode-only proposal: residual GPU clamp must not invent a prefill target. + + Prefill is charged at its ready count against the residual ceiling, and + the proposal-mask invariant must keep ``num_prefill`` None so a + decode-only decision cannot rewrite prefill desired. + """ cfg = PlannerConfig( mode="disagg", enable_load_scaling=True, @@ -372,16 +387,128 @@ def test_project_scale_to_budget_preserves_single_component_target_mask(): served_model_name="test", max_gpu_budget=4, min_gpu_budget=-1, + enable_power_awareness=True, + total_gpu_power_limit=100000, ) adapter = OrchestratorEngineAdapter(cfg, _disagg_caps()) - wc = WorkerCounts(ready_num_prefill=6, ready_num_decode=1) - outcome = _apply_outcome([ComponentTarget(sub_component_type="decode", replicas=4)]) + wc = WorkerCounts(ready_num_prefill=1, ready_num_decode=1) + outcome = _apply_outcome( + [ComponentTarget(sub_component_type="decode", replicas=10)] + ) dec = adapter._project_scale_to(outcome, wc) assert dec is not None assert dec.num_prefill is None - assert dec.num_decode == 2 + # Prefill ready=1 charged against residual ceiling 3 → decode capped at 3. + assert dec.num_decode == 3 + + +def test_partial_decode_proposal_respects_residual_gpu_ceiling(): + """Power-aware path: decode-only proposal must not assume prefill shrinks. + + Current (7, 1), one GPU each, ceiling 8. With power awareness on, the + ready-equal prefill echo is masked to None before the GPU clamp, so the + residual path sizes decode against the residual 1 GPU — never emit decode + 4 from a joint clamp that assumed prefill also dropped to 4. + """ + cfg = PlannerConfig( + mode="disagg", + enable_load_scaling=True, + enable_throughput_scaling=True, + optimization_target="sla", + served_model_name="test", + max_gpu_budget=8, + min_gpu_budget=-1, + enable_power_awareness=True, + # High enough that power does not mask the GPU-ceiling bug. + total_gpu_power_limit=100000, + ) + adapter = OrchestratorEngineAdapter(cfg, _disagg_caps()) + wc = WorkerCounts( + ready_num_prefill=7, + ready_num_decode=1, + expected_num_prefill=7, + expected_num_decode=1, + ) + + assert adapter._apply_gpu_final_budget(None, 7, wc) == (None, 1) + + # Power-awareness masks the ready-equal prefill echo before the GPU clamp. + outcome = _apply_outcome( + [ + ComponentTarget(sub_component_type="prefill", replicas=7), + ComponentTarget(sub_component_type="decode", replicas=7), + ], + proposed={"decode"}, + ) + dec = adapter._project_scale_to(outcome, wc) + assert dec is None or dec.num_prefill is None + applied_d = 1 if (dec is None or dec.num_decode is None) else dec.num_decode + assert applied_d <= 1 + assert 7 + applied_d <= 8 + + +def test_residual_gpu_clamp_holds_when_fixed_peer_already_over_ceiling(): + """Fixed peer alone over the GPU ceiling must not zero the proposed role. + + ready prefill=9, ceiling=8, decode-only propose 4: residual_max is 0, so + proportional_clamp_single would return 0. Hold decode at its ready count + instead of emitting a spurious scale-to-zero. + """ + cfg = PlannerConfig( + mode="disagg", + enable_load_scaling=True, + enable_throughput_scaling=True, + optimization_target="sla", + served_model_name="test", + max_gpu_budget=8, + min_gpu_budget=-1, + enable_power_awareness=True, + total_gpu_power_limit=100000, + ) + adapter = OrchestratorEngineAdapter(cfg, _disagg_caps()) + wc = WorkerCounts( + ready_num_prefill=9, + ready_num_decode=1, + expected_num_prefill=9, + expected_num_decode=1, + ) + + assert adapter._apply_gpu_final_budget(None, 4, wc) == (None, 1) + + outcome = _apply_outcome([ComponentTarget(sub_component_type="decode", replicas=4)]) + dec = adapter._project_scale_to(outcome, wc) + # Held at settled decode=1, then suppressed as a proven stable no-op. + assert dec is None or dec.num_decode is None + assert dec is None or dec.num_prefill is None + + +def test_power_off_partial_proposal_keeps_joint_gpu_clamp(): + """Power-off disagg keeps the historical joint-then-discard GPU clamp. + + Same (7,1)/decode-7/ceiling-8 inputs as the power-aware residual test, but + without power awareness the joint clamp emits decode 4 (Ted P2 scope + guard: residual sizing must not change power-off behavior). + """ + cfg = PlannerConfig( + mode="disagg", + enable_load_scaling=True, + enable_throughput_scaling=True, + optimization_target="sla", + served_model_name="test", + max_gpu_budget=8, + min_gpu_budget=-1, + enable_power_awareness=False, + ) + adapter = OrchestratorEngineAdapter(cfg, _disagg_caps()) + wc = WorkerCounts( + ready_num_prefill=7, + ready_num_decode=1, + expected_num_prefill=7, + expected_num_decode=1, + ) + assert adapter._apply_gpu_final_budget(None, 7, wc) == (None, 4) def test_project_scale_to_does_not_apply_budget_on_baseline_only_noop(): diff --git a/components/src/dynamo/planner/tests/plugins/orchestrator/test_pipeline.py b/components/src/dynamo/planner/tests/plugins/orchestrator/test_pipeline.py index c744e863a982..6f1d2db06b38 100644 --- a/components/src/dynamo/planner/tests/plugins/orchestrator/test_pipeline.py +++ b/components/src/dynamo/planner/tests/plugins/orchestrator/test_pipeline.py @@ -155,6 +155,35 @@ async def test_propose_output_flows_as_reconcile_baseline(ctx_factory): outcome = await orchestrator.tick(PipelineContext(), {PREFILL: 3}) assert outcome.execute_action == "apply" assert outcome.final_proposal.targets[0].replicas == 7 + assert outcome.proposed_components == frozenset({PREFILL}) + + +@pytest.mark.asyncio +async def test_proposed_component_mask_is_captured_before_later_stage_merges( + ctx_factory, +): + ctx = ctx_factory() + orchestrator = ctx["orchestrator"] + orchestrator.register_internal( + plugin_id="propose_prefill", + plugin_type="propose", + priority=10, + instance=StubPlugin(propose=_propose_override(7, "prefill")), + ) + orchestrator.register_internal( + plugin_id="reconcile_decode", + plugin_type="reconcile", + priority=10, + instance=StubPlugin(reconcile=_reconcile_override(5, "decode")), + ) + + outcome = await orchestrator.tick( + PipelineContext(), + {PREFILL: 3, ComponentKey(sub_component_type="decode"): 2}, + ) + + assert outcome.execute_action == "apply" + assert outcome.proposed_components == frozenset({PREFILL}) @pytest.mark.asyncio diff --git a/components/src/dynamo/planner/tests/unit/test_actuation_knobs.py b/components/src/dynamo/planner/tests/unit/test_actuation_knobs.py new file mode 100644 index 000000000000..10f18462e5d5 --- /dev/null +++ b/components/src/dynamo/planner/tests/unit/test_actuation_knobs.py @@ -0,0 +1,149 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Power actuation is DGD-owned: read/resolve, never mutate. + +The planner reads per-GPU caps from the DGD worker podTemplate annotations and +projects a power budget. It does NOT patch Pods. These tests pin the +read/resolve path — ``KubernetesConnector.get_component_power_configs`` +resolves per-role ``ComponentPowerConfig`` from a DGD dict (disagg + agg) and +propagates the typed parser errors. The no-mutation guarantee is enforced by +the mocked Kubernetes behavioral gate in +``tests/integration/test_power_no_mutation.py`` (CoreV1 is instantiated for +read-only pod listing but no patch method exists or is called), not by +brittle ``hasattr`` blacklists. +""" + +import os +from unittest.mock import AsyncMock, Mock, patch + +import pytest + +from dynamo.planner.connectors.kubernetes import KubernetesConnector +from dynamo.planner.errors import ( + PowerAnnotationInvalidError, + PowerAnnotationMissingError, + SubComponentNotFoundError, +) +from dynamo.planner.monitoring.dgd_services import POWER_ANNOTATION_KEY + +pytestmark = [ + pytest.mark.gpu_0, + pytest.mark.pre_merge, + pytest.mark.unit, + pytest.mark.planner, +] + + +@pytest.fixture +def mock_kube_api(): + api = Mock() + api.get_graph_deployment = Mock() + api.wait_for_graph_deployment_ready = AsyncMock() + return api + + +@pytest.fixture +def connector(mock_kube_api, monkeypatch): + """A KubernetesConnector with all K8s calls mocked out.""" + monkeypatch.setattr( + "dynamo.planner.connectors.kubernetes.KubernetesAPI", + Mock(return_value=mock_kube_api), + ) + with patch.dict(os.environ, {"DYN_PARENT_DGD_K8S_NAME": "test-dgd"}): + return KubernetesConnector("test-ns") + + +def _worker(name, comp_type, watts, gpus): + component = { + "name": name, + "type": comp_type, + "podTemplate": { + "spec": { + "containers": [ + {"name": "main", "resources": {"limits": {"nvidia.com/gpu": gpus}}} + ] + } + }, + } + if watts is not None: + component["podTemplate"]["metadata"] = { + "annotations": {POWER_ANNOTATION_KEY: watts} + } + return component + + +def _dgd(*components): + return {"spec": {"components": list(components)}} + + +# --------------------------------------------------------------------------- +# Read / resolve path +# --------------------------------------------------------------------------- + + +class TestGetComponentPowerConfigs: + def test_resolves_disagg_from_annotations(self, connector, mock_kube_api): + mock_kube_api.get_graph_deployment.return_value = _dgd( + _worker("VllmPrefillWorker", "prefill", "350", "2"), + _worker("VllmDecodeWorker", "decode", "300", "4"), + ) + + prefill, decode = connector.get_component_power_configs( + require_prefill=True, require_decode=True + ) + + assert prefill.watts_per_replica == 700 # 2 GPU × 350 W + assert decode.watts_per_replica == 1200 # 4 GPU × 300 W + + def test_resolves_agg_decode_only(self, connector, mock_kube_api): + # Parser-level coverage only: verifies the generic type:worker fallback + # in _resolve_one_power_service(). mode="agg" + enable_power_awareness + # is rejected by PlannerConfig validation because the shared deployment- + # validation and GPU-count paths do not follow this fallback. + mock_kube_api.get_graph_deployment.return_value = _dgd( + _worker("VllmWorker", "worker", "300", "4"), + ) + + prefill, decode = connector.get_component_power_configs( + require_prefill=False, require_decode=True + ) + + assert prefill is None + assert decode.watts_per_replica == 1200 + + def test_missing_annotation_propagates(self, connector, mock_kube_api): + mock_kube_api.get_graph_deployment.return_value = _dgd( + _worker("VllmDecodeWorker", "decode", None, "4"), + ) + with pytest.raises(PowerAnnotationMissingError): + connector.get_component_power_configs( + require_prefill=False, require_decode=True + ) + + def test_malformed_annotation_propagates(self, connector, mock_kube_api): + mock_kube_api.get_graph_deployment.return_value = _dgd( + _worker("VllmDecodeWorker", "decode", "0", "4"), + ) + with pytest.raises(PowerAnnotationInvalidError): + connector.get_component_power_configs( + require_prefill=False, require_decode=True + ) + + def test_missing_role_propagates(self, connector, mock_kube_api): + mock_kube_api.get_graph_deployment.return_value = _dgd( + _worker("VllmDecodeWorker", "decode", "300", "4"), + ) + with pytest.raises(SubComponentNotFoundError): + connector.get_component_power_configs( + require_prefill=True, require_decode=True + ) + + +# --------------------------------------------------------------------------- +# Read surface still exists (write-surface behavioral gate is integration). +# --------------------------------------------------------------------------- + + +def test_connector_exposes_read_only_power_configs(connector): + assert callable(connector.get_component_power_configs) diff --git a/components/src/dynamo/planner/tests/unit/test_dgd_power_annotation.py b/components/src/dynamo/planner/tests/unit/test_dgd_power_annotation.py new file mode 100644 index 000000000000..5ee352013235 --- /dev/null +++ b/components/src/dynamo/planner/tests/unit/test_dgd_power_annotation.py @@ -0,0 +1,305 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Unit tests for DGD-owned per-GPU power-limit parsing (Phase 1). + +Covers ``Service.get_gpu_power_limit_watts`` and +``resolve_component_power_configs`` — the single authoritative way to read a +component's per-GPU cap and per-replica watts from a DGD dict. No planner loop, +no Kubernetes, no Pod mutation. +""" + +import pytest + +from dynamo.planner.errors import ( + DuplicateSubComponentError, + PowerAnnotationInvalidError, + PowerAnnotationMissingError, + SubComponentNotFoundError, +) +from dynamo.planner.monitoring.dgd_services import ( + POWER_ANNOTATION_KEY, + ComponentPowerConfig, + Service, + resolve_component_power_configs, + resolve_power_component_names, +) + +pytestmark = [ + pytest.mark.gpu_0, + pytest.mark.pre_merge, + pytest.mark.unit, + pytest.mark.planner, +] + + +def _worker( + name, + *, + comp_type=None, + watts="350", + gpus="2", + node_count=None, +): + """Build one v1beta1 DGD worker component dict. + + ``watts=None`` omits the annotation entirely; a string value (including + "" / "abc" / "0" / "-1") is written verbatim so malformed cases can be + exercised. + """ + component: dict = { + "name": name, + "podTemplate": { + "spec": { + "containers": [ + {"name": "main", "resources": {"limits": {"nvidia.com/gpu": gpus}}} + ] + } + }, + } + if comp_type is not None: + component["type"] = comp_type + if watts is not None: + component["podTemplate"]["metadata"] = { + "annotations": {POWER_ANNOTATION_KEY: watts} + } + if node_count is not None: + component["multinode"] = {"nodeCount": node_count} + return component + + +def _dgd(*components): + return {"spec": {"components": list(components)}} + + +# --------------------------------------------------------------------------- # +# Service.get_gpu_power_limit_watts +# --------------------------------------------------------------------------- # + + +def test_reads_positive_integer_watts(): + svc = Service(name="P", service=_worker("P", comp_type="prefill", watts="350")) + assert svc.get_gpu_power_limit_watts() == 350 + + +def test_missing_annotation_raises_missing(): + svc = Service(name="P", service=_worker("P", comp_type="prefill", watts=None)) + with pytest.raises(PowerAnnotationMissingError): + svc.get_gpu_power_limit_watts() + + +@pytest.mark.parametrize("bad", ["", " ", "abc", "3.5", "0", "-1", "-300"]) +def test_malformed_or_nonpositive_raises_invalid(bad): + svc = Service(name="P", service=_worker("P", comp_type="prefill", watts=bad)) + with pytest.raises(PowerAnnotationInvalidError): + svc.get_gpu_power_limit_watts() + + +def test_surrounding_whitespace_is_tolerated(): + svc = Service(name="P", service=_worker("P", comp_type="prefill", watts=" 300 ")) + assert svc.get_gpu_power_limit_watts() == 300 + + +# --------------------------------------------------------------------------- # +# ComponentPowerConfig.watts_per_replica +# --------------------------------------------------------------------------- # + + +def test_watts_per_replica_multiplies_gpus(): + cfg = ComponentPowerConfig( + component_name="P", + role="prefill", + gpu_power_limit_watts=350, + gpus_per_replica=2, + ) + assert cfg.watts_per_replica == 700 + + +# --------------------------------------------------------------------------- # +# resolve_component_power_configs — disagg +# --------------------------------------------------------------------------- # + + +def test_resolves_disagg_prefill_and_decode(): + dgd = _dgd( + _worker("VllmPrefillWorker", comp_type="prefill", watts="350", gpus="2"), + _worker("VllmDecodeWorker", comp_type="decode", watts="300", gpus="4"), + ) + prefill, decode = resolve_component_power_configs( + dgd, require_prefill=True, require_decode=True + ) + assert prefill == ComponentPowerConfig( + component_name="VllmPrefillWorker", + role="prefill", + gpu_power_limit_watts=350, + gpus_per_replica=2, + ) + assert decode == ComponentPowerConfig( + component_name="VllmDecodeWorker", + role="decode", + gpu_power_limit_watts=300, + gpus_per_replica=4, + ) + assert prefill.watts_per_replica == 700 + assert decode.watts_per_replica == 1200 + + +def test_asymmetric_caps_are_independent(): + dgd = _dgd( + _worker("P", comp_type="prefill", watts="350", gpus="1"), + _worker("D", comp_type="decode", watts="250", gpus="1"), + ) + prefill, decode = resolve_component_power_configs( + dgd, require_prefill=True, require_decode=True + ) + assert prefill.watts_per_replica == 350 + assert decode.watts_per_replica == 250 + + +# --------------------------------------------------------------------------- # +# resolve_component_power_configs — aggregate (parser-level coverage only) +# +# These tests verify that the power parser's _resolve_one_power_service() +# fallback can read a generic type:worker component. They do NOT imply that +# mode="agg" + enable_power_awareness=True is supported end-to-end: the +# Kubernetes validate_deployment and GPU-count paths use the typed decode +# resolver, which does not follow the generic type:worker fallback. Power +# awareness is explicitly rejected for mode="agg" in PlannerConfig validation. +# --------------------------------------------------------------------------- # + + +def test_agg_generic_worker_resolves_decode_only(): + dgd = _dgd(_worker("VllmWorker", comp_type="worker", watts="300", gpus="4")) + prefill, decode = resolve_component_power_configs( + dgd, require_prefill=False, require_decode=True + ) + assert prefill is None + assert decode is not None + assert decode.component_name == "VllmWorker" + # role reflects the DGD component's actual generic type. + assert decode.role == "worker" + assert decode.watts_per_replica == 1200 + + +def test_agg_does_not_manufacture_prefill_config(): + dgd = _dgd(_worker("VllmWorker", comp_type="worker", watts="300", gpus="4")) + prefill, decode = resolve_component_power_configs( + dgd, require_prefill=False, require_decode=True + ) + assert prefill is None + + +# --------------------------------------------------------------------------- # +# multinode +# --------------------------------------------------------------------------- # + + +def test_multinode_watts_per_replica_multiplies_node_count(): + # 2 GPUs/pod × nodeCount 3 × 350 W = 2100 W per replica. + dgd = _dgd( + _worker("P", comp_type="prefill", watts="350", gpus="2", node_count=3), + _worker("D", comp_type="decode", watts="300", gpus="1"), + ) + prefill, _ = resolve_component_power_configs( + dgd, require_prefill=True, require_decode=True + ) + assert prefill.gpus_per_replica == 6 + assert prefill.watts_per_replica == 2100 + + +# --------------------------------------------------------------------------- # +# explicit-name vs type resolution +# --------------------------------------------------------------------------- # + + +def test_explicit_name_resolution_when_type_absent(): + # Component carries no type; the explicit fallback name resolves it. + dgd = _dgd(_worker("CustomDecode", comp_type=None, watts="300", gpus="2")) + _, decode = resolve_component_power_configs( + dgd, + require_prefill=False, + require_decode=True, + decode_name="CustomDecode", + ) + assert decode is not None + assert decode.component_name == "CustomDecode" + assert decode.watts_per_replica == 600 + + +def test_resolve_power_component_names_includes_untyped_named_worker(): + dgd = _dgd(_worker("CustomDecode", comp_type=None, watts="300", gpus="2")) + names = resolve_power_component_names( + dgd, + require_prefill=False, + require_decode=True, + decode_name="CustomDecode", + ) + assert names == ["CustomDecode"] + + +# --------------------------------------------------------------------------- # +# errors surface from the shared resolver +# --------------------------------------------------------------------------- # + + +def test_missing_role_raises_not_found(): + dgd = _dgd(_worker("D", comp_type="decode", watts="300", gpus="1")) + with pytest.raises(SubComponentNotFoundError): + resolve_component_power_configs(dgd, require_prefill=True, require_decode=True) + + +def test_duplicate_role_raises_duplicate(): + dgd = _dgd( + _worker("P1", comp_type="prefill", watts="350", gpus="1"), + _worker("P2", comp_type="prefill", watts="350", gpus="1"), + _worker("D", comp_type="decode", watts="300", gpus="1"), + ) + with pytest.raises(DuplicateSubComponentError): + resolve_component_power_configs(dgd, require_prefill=True, require_decode=True) + + +def test_missing_annotation_on_required_role_raises(): + dgd = _dgd( + _worker("P", comp_type="prefill", watts=None, gpus="1"), + _worker("D", comp_type="decode", watts="300", gpus="1"), + ) + with pytest.raises(PowerAnnotationMissingError): + resolve_component_power_configs(dgd, require_prefill=True, require_decode=True) + + +def test_invalid_gpu_count_raises_value_error(): + dgd = _dgd(_worker("D", comp_type="decode", watts="300", gpus="notanint")) + with pytest.raises(ValueError): + resolve_component_power_configs(dgd, require_prefill=False, require_decode=True) + + +# --------------------------------------------------------------------------- # +# zero / negative GPU topology — must fail loudly, not zero out enforcement +# --------------------------------------------------------------------------- # + + +@pytest.mark.parametrize("bad_gpus", ["0", "-1", "-4"]) +def test_zero_or_negative_gpu_count_rejected(bad_gpus): + svc = Service(name="D", service=_worker("D", comp_type="decode", gpus=bad_gpus)) + with pytest.raises(ValueError): + svc.get_gpu_count() + + +@pytest.mark.parametrize("bad_nodes", [0, -1, -3]) +def test_zero_or_negative_node_count_rejected(bad_nodes): + svc = Service( + name="D", service=_worker("D", comp_type="decode", node_count=bad_nodes) + ) + with pytest.raises(ValueError): + svc.get_node_count() + with pytest.raises(ValueError): + svc.get_total_gpu_count() + + +@pytest.mark.parametrize("bad_gpus", ["0", "-2"]) +def test_zero_or_negative_gpu_count_fails_resolution(bad_gpus): + # A zero/negative topology must not silently pass through the resolver and + # produce a watts_per_replica of 0 that disables enforcement for the role. + dgd = _dgd(_worker("D", comp_type="decode", watts="300", gpus=bad_gpus)) + with pytest.raises(ValueError): + resolve_component_power_configs(dgd, require_prefill=False, require_decode=True) diff --git a/components/src/dynamo/planner/tests/unit/test_environment.py b/components/src/dynamo/planner/tests/unit/test_environment.py index 4145203b0aa6..9d2caac7a90e 100644 --- a/components/src/dynamo/planner/tests/unit/test_environment.py +++ b/components/src/dynamo/planner/tests/unit/test_environment.py @@ -174,6 +174,88 @@ def test_gpu_discovery_failure_retains_last_observed_state(): assert environment.deployment_state().decode.num_gpus == 4 +@pytest.mark.asyncio +async def test_refresh_replica_counts_legacy_connector_power_disabled(): + """Power-disabled mode keeps the ordinary connector protocol unchanged.""" + + class _LegacyConnector: + async def get_actual_worker_counts( + self, + prefill_component_name=None, + decode_component_name=None, + ): + return 1, 2, True + + controller = _controller() + legacy = _LegacyConnector() + controller.get_actual_worker_counts = legacy.get_actual_worker_counts + environment = PlannerEnvironmentImpl( + config=_config(enable_power_awareness=False), + controller=controller, + require_prefill=True, + require_decode=True, + ) + environment.deployment_state().prefill.info = WorkerInfo(k8s_name="prefill") + environment.deployment_state().decode.info = WorkerInfo(k8s_name="decode") + + await environment._refresh_replica_counts() + + assert environment.deployment_state().prefill.replicas.active == 1 + assert environment.deployment_state().decode.replicas.active == 2 + + +@pytest.mark.asyncio +async def test_refresh_replica_counts_uses_dedicated_power_aware_snapshot(): + """Power-aware mode uses the capability-specific snapshot method.""" + controller = _controller() + controller.get_graph_deployment = MagicMock(return_value={}) + controller.get_component_power_configs = MagicMock(return_value=(None, None)) + controller.wait_for_settled_graph_deployment = AsyncMock(return_value={}) + controller.get_actual_worker_counts = AsyncMock(return_value=(9, 9, True)) + controller.get_power_aware_worker_counts = AsyncMock(return_value=(2, 3, True)) + environment = PlannerEnvironmentImpl( + config=_config(enable_power_awareness=True), + controller=controller, + require_prefill=True, + require_decode=True, + ) + environment.deployment_state().prefill.info = WorkerInfo(k8s_name="prefill") + environment.deployment_state().decode.info = WorkerInfo(k8s_name="decode") + + await environment._refresh_replica_counts() + + controller.get_power_aware_worker_counts.assert_awaited_once_with( + prefill_component_name="prefill", + decode_component_name="decode", + ) + controller.get_actual_worker_counts.assert_not_awaited() + + +@pytest.mark.asyncio +async def test_refresh_replica_counts_power_enabled_non_power_aware_raises(): + """When enable_power_awareness=True but the connector is not a + PowerAwareConnector, _refresh_replica_counts must raise + DeploymentValidationError rather than using its ordinary count method. + """ + controller = _controller() + controller.get_graph_deployment = MagicMock(return_value={}) + controller.get_component_power_configs = MagicMock(return_value=(None, None)) + controller.wait_for_settled_graph_deployment = AsyncMock(return_value={}) + # Deliberately omit get_power_aware_worker_counts: the three older + # capabilities are insufficient for the dedicated runtime snapshot. + environment = PlannerEnvironmentImpl( + config=_config(enable_power_awareness=True), + controller=controller, + require_prefill=True, + require_decode=True, + ) + environment.deployment_state().prefill.info = WorkerInfo(k8s_name="prefill") + environment.deployment_state().decode.info = WorkerInfo(k8s_name="decode") + + with pytest.raises(DeploymentValidationError): + await environment._refresh_replica_counts() + + @pytest.mark.parametrize( ("require_prefill", "require_decode", "missing_field"), [ diff --git a/components/src/dynamo/planner/tests/unit/test_kube.py b/components/src/dynamo/planner/tests/unit/test_kube.py index 0f076e948152..fccde02eddb8 100644 --- a/components/src/dynamo/planner/tests/unit/test_kube.py +++ b/components/src/dynamo/planner/tests/unit/test_kube.py @@ -14,13 +14,19 @@ # limitations under the License. from typing import Any, Dict -from unittest.mock import MagicMock, patch +from unittest.mock import MagicMock, patch, sentinel import pytest from kubernetes import client from dynamo.planner.connectors.clients.kubernetes_api import KubernetesAPI -from dynamo.planner.errors import DynamoGraphDeploymentNotFoundError +from dynamo.planner.errors import ( + DuplicateSubComponentError, + DynamoGraphDeploymentNotFoundError, + PowerAnnotationMissingError, + RolloutFailedError, + SubComponentNotFoundError, +) pytestmark = [ pytest.mark.gpu_0, @@ -55,7 +61,15 @@ def mock_namespace(): @pytest.fixture -def k8s_api(mock_custom_api, mock_config, mock_namespace): +def mock_core_api(): + with patch( + "dynamo.planner.connectors.clients.kubernetes_api.client.CoreV1Api" + ) as mock: + yield mock.return_value + + +@pytest.fixture +def k8s_api(mock_custom_api, mock_core_api, mock_config, mock_namespace): return KubernetesAPI() @@ -402,9 +416,549 @@ async def test_wait_for_graph_deployment_ready_on_second_attempt( side_effect=[mock_deployment_not_ready, mock_deployment_ready], ): # Test with minimal attempts and delay for faster testing - await k8s_api.wait_for_graph_deployment_ready( + settled = await k8s_api.wait_for_graph_deployment_ready( "test-deployment", max_attempts=2, delay_seconds=0.1 ) + assert settled is mock_deployment_ready + + +def _stable_worker_dgd( + *, + generation: int, + observed_generation: int, + decode_watts: str = "400", + dgd_name: str = "test-deployment", +) -> Dict[str, Any]: + """Production-shaped DGD: stable replica counts, explicit generation lag.""" + return { + "metadata": {"name": dgd_name, "generation": generation}, + "spec": { + "components": [ + { + "name": "VllmDecodeWorker", + "type": "decode", + "replicas": 2, + "podTemplate": { + "metadata": { + "annotations": { + "dynamo.nvidia.com/gpu-power-limit": decode_watts + } + }, + "spec": { + "containers": [ + { + "name": "main", + "resources": {"limits": {"nvidia.com/gpu": "1"}}, + } + ] + }, + }, + }, + {"name": "Planner", "type": "planner", "replicas": 1}, + ] + }, + "status": { + "observedGeneration": observed_generation, + "components": { + "VllmDecodeWorker": { + "readyReplicas": 2, + "updatedReplicas": 2, + "availableReplicas": 2, + }, + "Planner": { + "readyReplicas": 0, + "updatedReplicas": 0, + "availableReplicas": 0, + }, + }, + }, + } + + +def _make_pod( + name: str, + *, + phase: str = "Running", + annotation: "str | None" = "300", + deletion_timestamp=None, + component: str = "VllmDecodeWorker", +) -> MagicMock: + """Build a mock Pod object for pod-annotation settlement tests.""" + pod = MagicMock() + pod.metadata.name = name + pod.metadata.annotations = ( + {"dynamo.nvidia.com/gpu-power-limit": annotation} + if annotation is not None + else {} + ) + pod.metadata.labels = {"nvidia.com/dynamo-component": component} + pod.metadata.deletion_timestamp = deletion_timestamp + pod.status.phase = phase + return pod + + +def _mock_pod_list(mock_core_api, pods: list, *, component: str = "VllmDecodeWorker"): + """Wire the single DGD-scoped Pod LIST and label its mock Pods.""" + for pod in pods: + pod.metadata.labels = {"nvidia.com/dynamo-component": component} + result = MagicMock() + result.items = pods + mock_core_api.list_namespaced_pod.return_value = result + + +def test_is_spec_generation_observed_requires_catch_up(k8s_api): + assert ( + k8s_api.is_spec_generation_observed( + _stable_worker_dgd(generation=2, observed_generation=1) + ) + is False + ) + assert ( + k8s_api.is_spec_generation_observed( + _stable_worker_dgd(generation=2, observed_generation=2) + ) + is True + ) + assert k8s_api.is_spec_generation_observed({"status": {}}) is False + + +@pytest.mark.asyncio +async def test_wait_exclude_planner_rejects_unobserved_generation( + k8s_api, mock_custom_api +): + """Annotation-only gen bump: counts look stable, but observedGeneration lags. + + Planner must not treat this snapshot as settled — otherwise a restart can + cache the gen-2 lower cap while Pods still enforce gen-1. + """ + lagging = _stable_worker_dgd( + generation=2, observed_generation=1, decode_watts="300" + ) + with patch.object(k8s_api, "get_graph_deployment", return_value=lagging): + with pytest.raises(TimeoutError): + await k8s_api.wait_for_graph_deployment_ready( + "test-deployment", + include_planner=False, + require_backing_settled=True, + require_prefill=False, + require_decode=True, + max_attempts=2, + delay_seconds=0.01, + ) + + +@pytest.mark.asyncio +async def test_wait_exclude_planner_returns_observed_stable_snapshot( + k8s_api, mock_core_api +): + """Gen-2 lower cap is adopted only after observedGeneration catches up.""" + lagging = _stable_worker_dgd( + generation=2, observed_generation=1, decode_watts="300" + ) + settled = _stable_worker_dgd( + generation=2, observed_generation=2, decode_watts="300" + ) + _mock_pod_list(mock_core_api, [_make_pod("pod-0", annotation="300")]) + with patch.object(k8s_api, "get_graph_deployment", side_effect=[lagging, settled]): + got = await k8s_api.wait_for_graph_deployment_ready( + "test-deployment", + include_planner=False, + require_backing_settled=True, + require_prefill=False, + require_decode=True, + max_attempts=3, + delay_seconds=0.01, + ) + assert got is settled + assert got["status"]["observedGeneration"] == 2 + assert ( + got["spec"]["components"][0]["podTemplate"]["metadata"]["annotations"][ + "dynamo.nvidia.com/gpu-power-limit" + ] + == "300" + ) + + +# --------------------------------------------------------------------------- +# worker_pods_settled unit tests +# --------------------------------------------------------------------------- + + +def test_worker_pods_settled_all_match(k8s_api, mock_core_api): + """All running pods carry the expected annotation → settled.""" + dgd = _stable_worker_dgd(generation=2, observed_generation=2, decode_watts="300") + _mock_pod_list( + mock_core_api, + [_make_pod("pod-0", annotation="300"), _make_pod("pod-1", annotation="300")], + ) + settled, pending = k8s_api.worker_pods_settled(dgd, {"VllmDecodeWorker": "300"}) + assert settled is True + assert pending == [] + + +def test_worker_pods_settled_differing_prefill_decode_caps(k8s_api, mock_core_api): + """Prefill 350 W/GPU and decode 300 W/GPU are independent — both must match.""" + dgd = { + "metadata": {"name": "test-deployment"}, + "spec": { + "components": [ + { + "name": "VllmPrefillWorker", + "type": "prefill", + "replicas": 2, + "podTemplate": { + "metadata": { + "annotations": {"dynamo.nvidia.com/gpu-power-limit": "350"} + }, + "spec": { + "containers": [ + { + "name": "main", + "resources": {"limits": {"nvidia.com/gpu": "2"}}, + } + ] + }, + }, + }, + { + "name": "VllmDecodeWorker", + "type": "decode", + "replicas": 2, + "podTemplate": { + "metadata": { + "annotations": {"dynamo.nvidia.com/gpu-power-limit": "300"} + }, + "spec": { + "containers": [ + { + "name": "main", + "resources": {"limits": {"nvidia.com/gpu": "4"}}, + } + ] + }, + }, + }, + ] + }, + "status": { + "observedGeneration": 2, + "components": { + "VllmPrefillWorker": { + "readyReplicas": 2, + "updatedReplicas": 2, + "availableReplicas": 2, + }, + "VllmDecodeWorker": { + "readyReplicas": 2, + "updatedReplicas": 2, + "availableReplicas": 2, + }, + }, + }, + } + + result = MagicMock() + result.items = [ + _make_pod("p-0", annotation="350", component="VllmPrefillWorker"), + _make_pod("p-1", annotation="350", component="VllmPrefillWorker"), + _make_pod("d-0", annotation="300", component="VllmDecodeWorker"), + _make_pod("d-1", annotation="300", component="VllmDecodeWorker"), + ] + mock_core_api.list_namespaced_pod.return_value = result + settled, pending = k8s_api.worker_pods_settled( + dgd, {"VllmPrefillWorker": "350", "VllmDecodeWorker": "300"} + ) + assert settled is True + assert pending == [] + mock_core_api.list_namespaced_pod.assert_called_once() + + +def test_worker_pods_settled_multi_gpu_replica_compares_per_gpu_annotation( + k8s_api, mock_core_api +): + """4-GPU replica at 300 W/GPU: pod annotation is "300", not "1200".""" + dgd = _stable_worker_dgd(generation=2, observed_generation=2, decode_watts="300") + _mock_pod_list(mock_core_api, [_make_pod("pod-0", annotation="300")]) + settled, pending = k8s_api.worker_pods_settled(dgd, {"VllmDecodeWorker": "300"}) + assert settled is True + assert pending == [] + + +def test_worker_pods_settled_terminating_pod_stale_annotation_blocks( + k8s_api, mock_core_api +): + """A terminating (DeletionTimestamp set) pod still in Running phase is non-terminal. + + It still consumes GPU power and must block pod-annotation settlement until + it disappears. + """ + dgd = _stable_worker_dgd(generation=2, observed_generation=2, decode_watts="300") + terminating = _make_pod( + "pod-old", + phase="Running", + annotation="200", # stale old cap + deletion_timestamp=sentinel.some_timestamp, + ) + _mock_pod_list(mock_core_api, [terminating]) + settled, pending = k8s_api.worker_pods_settled(dgd, {"VllmDecodeWorker": "300"}) + assert settled is False + assert any("pod-old" in msg and "terminating" in msg for msg in pending) + + +def test_worker_pods_settled_succeeded_pod_ignored(k8s_api, mock_core_api): + """A Succeeded pod is terminal and must not block settlement.""" + dgd = _stable_worker_dgd(generation=2, observed_generation=2, decode_watts="300") + _mock_pod_list( + mock_core_api, + [ + _make_pod("pod-ok", phase="Running", annotation="300"), + _make_pod( + "pod-done", phase="Succeeded", annotation="200" + ), # stale but terminal + ], + ) + settled, pending = k8s_api.worker_pods_settled(dgd, {"VllmDecodeWorker": "300"}) + assert settled is True + assert pending == [] + + +def test_worker_pods_settled_zero_replicas_no_pods_is_settled(k8s_api, mock_core_api): + """Scale-to-zero with no pods: nothing enforcing a stale cap → settled.""" + dgd = _stable_worker_dgd(generation=2, observed_generation=2, decode_watts="300") + dgd["spec"]["components"][0]["replicas"] = 0 + _mock_pod_list(mock_core_api, []) + settled, pending = k8s_api.worker_pods_settled(dgd, {"VllmDecodeWorker": "300"}) + assert settled is True + assert pending == [] + + +def test_worker_pods_settled_nonzero_replicas_no_pods_is_pending( + k8s_api, mock_core_api +): + """Nonzero desired replicas but no pods yet: settlement must wait.""" + dgd = _stable_worker_dgd(generation=2, observed_generation=2, decode_watts="300") + _mock_pod_list(mock_core_api, []) + settled, pending = k8s_api.worker_pods_settled(dgd, {"VllmDecodeWorker": "300"}) + assert settled is False + assert any("no non-terminal pods" in msg for msg in pending) + + +def test_worker_pods_settled_missing_annotation_on_running_pod_blocks( + k8s_api, mock_core_api +): + """A running pod with no annotation must block settlement.""" + dgd = _stable_worker_dgd(generation=2, observed_generation=2, decode_watts="300") + _mock_pod_list(mock_core_api, [_make_pod("pod-0", annotation=None)]) + settled, pending = k8s_api.worker_pods_settled(dgd, {"VllmDecodeWorker": "300"}) + assert settled is False + assert any("pod-0" in msg for msg in pending) + + +def test_worker_pods_settled_inprogress_rollout_blocks_without_listing_pods( + k8s_api, mock_core_api +): + """InProgress DGD rollingUpdate phase blocks settlement before listing pods.""" + dgd = _stable_worker_dgd(generation=2, observed_generation=2, decode_watts="300") + dgd["status"]["rollingUpdate"] = {"phase": "InProgress"} + settled, pending = k8s_api.worker_pods_settled(dgd, {"VllmDecodeWorker": "300"}) + assert settled is False + assert pending == ["rollingUpdate.phase=InProgress"] + mock_core_api.list_namespaced_pod.assert_not_called() + + +def test_worker_pods_settled_exact_string_comparison_whitespace(k8s_api, mock_core_api): + """Exact string comparison: DGD '300' must match pod '300' but not ' 300 '.""" + dgd = _stable_worker_dgd(generation=2, observed_generation=2, decode_watts="300") + + # Matching: both "300" + _mock_pod_list(mock_core_api, [_make_pod("pod-0", annotation="300")]) + settled, _ = k8s_api.worker_pods_settled(dgd, {"VllmDecodeWorker": "300"}) + assert settled is True + + # Mismatch: DGD "300", pod " 300 " (unexpected whitespace on pod side) + _mock_pod_list(mock_core_api, [_make_pod("pod-0", annotation=" 300 ")]) + settled, pending = k8s_api.worker_pods_settled(dgd, {"VllmDecodeWorker": "300"}) + assert settled is False + assert any("300" in msg for msg in pending) + + +@pytest.mark.asyncio +async def test_wait_exclude_planner_rejects_pods_with_stale_annotation( + k8s_api, mock_core_api +): + """DGD observed but pods still carry the old cap → settlement must block.""" + dgd = _stable_worker_dgd(generation=2, observed_generation=2, decode_watts="300") + _mock_pod_list( + mock_core_api, + [_make_pod("pod-0", annotation="400")], # old cap + ) + with patch.object(k8s_api, "get_graph_deployment", return_value=dgd): + with pytest.raises(TimeoutError): + await k8s_api.wait_for_graph_deployment_ready( + "test-deployment", + include_planner=False, + require_backing_settled=True, + require_prefill=False, + require_decode=True, + max_attempts=2, + delay_seconds=0.01, + ) + + +@pytest.mark.asyncio +async def test_wait_exclude_planner_rejects_inprogress_rollout(k8s_api, mock_core_api): + """End-to-end: InProgress DGD rollingUpdate phase blocks settlement.""" + dgd = _stable_worker_dgd(generation=2, observed_generation=2, decode_watts="300") + dgd["status"]["rollingUpdate"] = {"phase": "InProgress"} + _mock_pod_list(mock_core_api, [_make_pod("pod-0", annotation="300")]) + with patch.object(k8s_api, "get_graph_deployment", return_value=dgd): + with pytest.raises(TimeoutError): + await k8s_api.wait_for_graph_deployment_ready( + "test-deployment", + include_planner=False, + require_backing_settled=True, + require_prefill=False, + require_decode=True, + max_attempts=2, + delay_seconds=0.01, + ) + + +@pytest.mark.asyncio +async def test_wait_missing_dgd_annotation_raises_immediately(k8s_api, mock_core_api): + """A missing DGD power annotation is a config error, not rollout lag. + + It must raise PowerAnnotationMissingError immediately rather than timing + out after 30 minutes — the pod list must not even be consulted. + """ + dgd = _stable_worker_dgd(generation=2, observed_generation=2, decode_watts="300") + # Remove the annotation to simulate a misconfigured DGD. + del dgd["spec"]["components"][0]["podTemplate"]["metadata"]["annotations"][ + "dynamo.nvidia.com/gpu-power-limit" + ] + with patch.object(k8s_api, "get_graph_deployment", return_value=dgd): + with pytest.raises(PowerAnnotationMissingError): + await k8s_api.wait_for_graph_deployment_ready( + "test-deployment", + include_planner=False, + require_backing_settled=True, + require_prefill=False, + require_decode=True, + max_attempts=5, + delay_seconds=0.01, + ) + mock_core_api.list_namespaced_pod.assert_not_called() + + +@pytest.mark.asyncio +async def test_wait_settlement_propagates_missing_role_immediately( + k8s_api, mock_core_api +): + """SubComponentNotFoundError after generation is observed must propagate, not retry. + + Once observedGeneration >= generation the DGD spec is stable; a missing + power-relevant role is a configuration error, not a rollout race. The + component is stable in status so non_planner_components_stable passes; + only role resolution fails. + """ + dgd = _stable_worker_dgd(generation=2, observed_generation=2, decode_watts="300") + # Change type to something the power resolver cannot match as a decode role. + # The component name and status entry are preserved so stability check passes. + dgd["spec"]["components"][0]["type"] = "frontend" + + with patch.object(k8s_api, "get_graph_deployment", return_value=dgd): + with pytest.raises(SubComponentNotFoundError): + await k8s_api.wait_for_graph_deployment_ready( + "test-deployment", + include_planner=False, + require_backing_settled=True, + require_prefill=False, + require_decode=True, + max_attempts=5, + delay_seconds=0.01, + ) + + +@pytest.mark.asyncio +async def test_wait_settlement_propagates_duplicate_role_immediately( + k8s_api, mock_core_api +): + """DuplicateSubComponentError is always a config error and must not be retried.""" + dgd = _stable_worker_dgd(generation=2, observed_generation=2, decode_watts="300") + # Add a second stable decode component to trigger DuplicateSubComponentError. + dgd["spec"]["components"].append( + {"name": "VllmDecodeWorker2", "type": "decode", "replicas": 2} + ) + dgd["status"]["components"]["VllmDecodeWorker2"] = { + "readyReplicas": 2, + "updatedReplicas": 2, + "availableReplicas": 2, + } + + with patch.object(k8s_api, "get_graph_deployment", return_value=dgd): + with pytest.raises(DuplicateSubComponentError): + await k8s_api.wait_for_graph_deployment_ready( + "test-deployment", + include_planner=False, + require_backing_settled=True, + require_prefill=False, + require_decode=True, + max_attempts=5, + delay_seconds=0.01, + ) + + +@pytest.mark.asyncio +async def test_wait_exclude_planner_settles_untyped_named_worker( + k8s_api, mock_core_api +): + """Explicit-name power worker without ``type`` must still be settlement-gated. + + The power resolver matches untyped components by name + (``_can_use_explicit_component_name``). An old cap on pods must block + settlement regardless of how the component was resolved. + """ + dgd = _stable_worker_dgd(generation=2, observed_generation=2, decode_watts="300") + dgd["spec"]["components"][0].pop("type", None) + + # Old cap on pods → must block. + _mock_pod_list(mock_core_api, [_make_pod("pod-0", annotation="200")]) + with patch.object(k8s_api, "get_graph_deployment", return_value=dgd): + with pytest.raises(TimeoutError): + await k8s_api.wait_for_graph_deployment_ready( + "test-deployment", + include_planner=False, + require_backing_settled=True, + require_prefill=False, + require_decode=True, + decode_component_name="VllmDecodeWorker", + max_attempts=2, + delay_seconds=0.01, + ) + + +@pytest.mark.asyncio +async def test_wait_legacy_exclude_planner_does_not_list_pods(k8s_api, mock_core_api): + """Power-off / legacy wait must not touch Pods. + + ``include_planner=False`` without ``require_backing_settled`` restores the + pre-power readiness contract: replica-count stability only. Generation lag + and pod-annotation settlement are power-settlement concerns. + """ + # Replica-stable, but observedGeneration lags — legacy wait must succeed. + lagging = _stable_worker_dgd( + generation=2, observed_generation=1, decode_watts="300" + ) + with patch.object(k8s_api, "get_graph_deployment", return_value=lagging): + got = await k8s_api.wait_for_graph_deployment_ready( + "test-deployment", + include_planner=False, + require_backing_settled=False, + max_attempts=2, + delay_seconds=0.01, + ) + assert got is lagging + mock_core_api.list_namespaced_pod.assert_not_called() def test_get_graph_deployment(k8s_api, mock_custom_api): @@ -619,3 +1173,203 @@ def test_get_service_replica_status_available_replicas_zero(k8s_api, mock_custom # availableReplicas=0 should be used (not readyReplicas) assert count == 0 assert is_stable is True + + +def test_has_terminating_pods_true_when_running_pod_has_deletion_timestamp( + k8s_api, mock_core_api +): + """has_terminating_pods returns True when a Running pod has a deletionTimestamp. + + Deployment status excludes terminating pods. During a decode scale-down + (4→1) the Deployment can report desired=updated=available=1 while 3 old + decode pods linger with a deletionTimestamp. get_actual_worker_counts calls + has_terminating_pods to detect this blind spot and return is_stable=False, + preventing the planner from admitting the opposing scale-up before old pods + are fully gone. get_service_replica_status stays pod-free intentionally so + non-power paths do not acquire the pods/list RBAC surface. + """ + terminating = _make_pod( + "pod-old", + phase="Running", + deletion_timestamp=sentinel.ts, + ) + + assert k8s_api.has_terminating_pods([terminating]) is True + mock_core_api.list_namespaced_pod.assert_not_called() + + +def test_has_terminating_pods_false_when_no_deletion_timestamp(k8s_api, mock_core_api): + """has_terminating_pods returns False when all pods are cleanly Running.""" + running = _make_pod("pod-0", phase="Running") + + assert k8s_api.has_terminating_pods([running]) is False + mock_core_api.list_namespaced_pod.assert_not_called() + + +def test_list_and_partition_pods_uses_one_dgd_scoped_request(k8s_api, mock_core_api): + prefill = _make_pod("prefill-0", component="VllmPrefillWorker") + decode = _make_pod("decode-0", component="VllmDecodeWorker") + result = MagicMock() + result.items = [prefill, decode] + mock_core_api.list_namespaced_pod.return_value = result + + pods = k8s_api.list_pods_for_graph("my-dgd") + by_component = k8s_api.partition_pods_by_component(pods) + + mock_core_api.list_namespaced_pod.assert_called_once_with( + namespace="default", + label_selector="nvidia.com/dynamo-graph-deployment-name=my-dgd", + ) + assert by_component == { + "VllmPrefillWorker": [prefill], + "VllmDecodeWorker": [decode], + } + + +def test_worker_pods_settled_terminating_pod_correct_annotation_blocks( + k8s_api, mock_core_api +): + """A terminating pod carrying the *expected* annotation must still block settlement. + + P1 regression: before the fix, a terminating pod whose annotation matched + the DGD snapshot was silently accepted, letting the planner admit a scale-up + while the old pod was still Running and consuming power. + """ + dgd = _stable_worker_dgd(generation=2, observed_generation=2, decode_watts="300") + terminating = _make_pod( + "pod-old", + phase="Running", + annotation="300", # matches expected — was incorrectly accepted before fix + deletion_timestamp=sentinel.ts, + ) + _mock_pod_list(mock_core_api, [terminating]) + settled, pending = k8s_api.worker_pods_settled(dgd, {"VllmDecodeWorker": "300"}) + assert settled is False + assert any("pod-old" in msg and "terminating" in msg for msg in pending) + + +@pytest.mark.asyncio +async def test_wait_failed_rollout_raises_immediately(k8s_api, mock_core_api): + """A Failed rollingUpdate phase must raise RolloutFailedError immediately. + + Failed is a terminal operator state (endTime is set). Retrying until the + generic 30-minute timeout wastes time and hides the root cause. + """ + dgd = _stable_worker_dgd(generation=2, observed_generation=2, decode_watts="300") + dgd["status"]["rollingUpdate"] = { + "phase": "Failed", + "message": "pod CrashLoopBackOff", + } + with patch.object(k8s_api, "get_graph_deployment", return_value=dgd): + with pytest.raises(RolloutFailedError) as exc_info: + await k8s_api.wait_for_graph_deployment_ready( + "test-deployment", + include_planner=False, + require_backing_settled=True, + require_prefill=False, + require_decode=True, + max_attempts=10, + delay_seconds=0.01, + ) + assert "test-deployment" in str(exc_info.value) + assert "Failed" in str(exc_info.value) + + +@pytest.mark.asyncio +async def test_wait_failed_rollout_raises_immediately_while_replicas_unstable( + k8s_api, mock_core_api +): + """Failed + unstable replicas must raise RolloutFailedError on attempt 1. + + The stability gate (non_planner_components_stable) must not run before the + Failed check on the require_backing_settled path. If it does, the loop + continues indefinitely and the caller gets a generic TimeoutError instead. + """ + dgd = _stable_worker_dgd(generation=2, observed_generation=2, decode_watts="300") + # Make replicas unstable (desired=2, ready=1) so the old ordering would + # skip the Failed check via the stability-gate continue. + dgd["status"]["components"]["VllmDecodeWorker"]["readyReplicas"] = 1 + dgd["status"]["rollingUpdate"] = { + "phase": "Failed", + "message": "pod CrashLoopBackOff", + } + with patch.object(k8s_api, "get_graph_deployment", return_value=dgd): + with pytest.raises(RolloutFailedError) as exc_info: + await k8s_api.wait_for_graph_deployment_ready( + "test-deployment", + include_planner=False, + require_backing_settled=True, + require_prefill=False, + require_decode=True, + max_attempts=3, + delay_seconds=0.01, + ) + assert "test-deployment" in str(exc_info.value) + assert "CrashLoopBackOff" in str(exc_info.value) + + +@pytest.mark.asyncio +async def test_wait_legacy_failed_rollout_does_not_raise(k8s_api, mock_core_api): + """Power-disabled (require_backing_settled=False) must not raise on a Failed rollout. + + The legacy replica-stability contract predates the rolling-update field; a + power-disabled planner whose replica counts are stable must start + successfully even when rollingUpdate.phase is Failed. + """ + dgd = _stable_worker_dgd(generation=2, observed_generation=2, decode_watts="300") + dgd["status"]["rollingUpdate"] = { + "phase": "Failed", + "message": "pod CrashLoopBackOff", + } + with patch.object(k8s_api, "get_graph_deployment", return_value=dgd): + got = await k8s_api.wait_for_graph_deployment_ready( + "test-deployment", + include_planner=False, + require_backing_settled=False, + max_attempts=2, + delay_seconds=0.01, + ) + assert got is dgd + mock_core_api.list_namespaced_pod.assert_not_called() + + +@pytest.mark.asyncio +async def test_wait_settlement_verbatim_annotation_propagation(k8s_api, mock_core_api): + """DGD annotation ' 350 ' propagates verbatim to Pods; settlement uses raw string. + + The operator copies the raw DGD podTemplate annotation onto each Pod without + normalization, so expected_power stores the raw string ' 350 ' and the + settlement comparison succeeds only when the Pod carries that same raw value. + + ' 350 ' (DGD) + ' 350 ' (Pod) → settles (operator verbatim copy). + ' 350 ' (DGD) + '350' (Pod) → does NOT settle (canonical form differs). + """ + dgd = _stable_worker_dgd(generation=2, observed_generation=2, decode_watts=" 350 ") + + # Verbatim match: pod carries the raw DGD annotation string. + _mock_pod_list(mock_core_api, [_make_pod("pod-0", annotation=" 350 ")]) + with patch.object(k8s_api, "get_graph_deployment", return_value=dgd): + got = await k8s_api.wait_for_graph_deployment_ready( + "test-deployment", + include_planner=False, + require_backing_settled=True, + require_prefill=False, + require_decode=True, + max_attempts=3, + delay_seconds=0.01, + ) + assert got is dgd + + # Canonical form "350" does not match the raw DGD annotation " 350 ". + _mock_pod_list(mock_core_api, [_make_pod("pod-0", annotation="350")]) + with patch.object(k8s_api, "get_graph_deployment", return_value=dgd): + with pytest.raises(TimeoutError): + await k8s_api.wait_for_graph_deployment_ready( + "test-deployment", + include_planner=False, + require_backing_settled=True, + require_prefill=False, + require_decode=True, + max_attempts=3, + delay_seconds=0.01, + ) diff --git a/components/src/dynamo/planner/tests/unit/test_kubernetes_connector.py b/components/src/dynamo/planner/tests/unit/test_kubernetes_connector.py index 2f8bbe4611b1..f11f15a200e1 100644 --- a/components/src/dynamo/planner/tests/unit/test_kubernetes_connector.py +++ b/components/src/dynamo/planner/tests/unit/test_kubernetes_connector.py @@ -52,6 +52,13 @@ def mock_kube_api(): mock_api.update_graph_replicas = AsyncMock() mock_api.wait_for_graph_deployment_ready = AsyncMock() mock_api.is_deployment_ready = Mock() + # Default: no terminating pods; tests that want to simulate terminating pods + # override this per-test. + mock_api.has_terminating_pods = Mock(return_value=False) + mock_api.list_pods_for_graph = Mock(return_value=[]) + mock_api.partition_pods_by_component = Mock(return_value={}) + # Default: no blocking rollout; tests that want InProgress/Pending override. + mock_api.is_rolling_update_blocking_settlement = Mock(return_value=(False, "")) return mock_api @@ -1261,6 +1268,165 @@ async def test_get_actual_worker_counts_no_components( assert is_stable is True +@pytest.mark.asyncio +async def test_get_actual_worker_counts_no_pod_list_when_power_disabled( + kubernetes_connector, mock_kube_api +): + """The ordinary connector path remains Pod-list free.""" + mock_deployment = _deployment( + _component("prefill-component"), + _component("decode-component"), + ) + mock_kube_api.get_graph_deployment.return_value = mock_deployment + mock_kube_api.get_service_replica_status.side_effect = [(2, True), (4, True)] + + await kubernetes_connector.get_actual_worker_counts( + prefill_component_name="prefill-component", + decode_component_name="decode-component", + ) + + mock_kube_api.list_pods_for_graph.assert_not_called() + mock_kube_api.has_terminating_pods.assert_not_called() + + +@pytest.mark.asyncio +async def test_get_power_aware_worker_counts_uses_one_partitioned_pod_snapshot( + kubernetes_connector, mock_kube_api +): + """The power-aware path lists once and checks locally partitioned Pods.""" + mock_deployment = _deployment( + _component("prefill-component"), + _component("decode-component"), + ) + mock_kube_api.get_graph_deployment.return_value = mock_deployment + mock_kube_api.get_service_replica_status.side_effect = [(2, True), (4, True)] + prefill_pods = [object()] + decode_pods = [object()] + all_pods = [*prefill_pods, *decode_pods] + mock_kube_api.list_pods_for_graph.return_value = all_pods + mock_kube_api.partition_pods_by_component.return_value = { + "prefill-component": prefill_pods, + "decode-component": decode_pods, + } + mock_kube_api.has_terminating_pods.return_value = False + + ( + prefill_count, + decode_count, + is_stable, + ) = await kubernetes_connector.get_power_aware_worker_counts( + prefill_component_name="prefill-component", + decode_component_name="decode-component", + ) + + mock_kube_api.list_pods_for_graph.assert_called_once_with("test-graph") + mock_kube_api.partition_pods_by_component.assert_called_once_with(all_pods) + assert mock_kube_api.has_terminating_pods.call_args_list == [ + call(prefill_pods), + call(decode_pods), + ] + assert mock_kube_api.has_terminating_pods.call_count == 2 + assert is_stable is True + assert prefill_count == 2 + assert decode_count == 4 + + +@pytest.mark.asyncio +async def test_get_power_aware_worker_counts_inprogress_rollout_is_unstable( + kubernetes_connector, mock_kube_api +): + """InProgress rollout with replica-stable counts must be unstable when power is on. + + Startup settlement already blocks on Pending/InProgress via + is_rolling_update_blocking_settlement. The runtime power snapshot + must apply the same gate so + a scale-up is not admitted while old and new pod generations overlap. + """ + mock_deployment = _deployment( + _component("prefill-component"), + _component("decode-component"), + ) + mock_kube_api.get_graph_deployment.return_value = mock_deployment + # Replica counts look stable to per-service checks. + mock_kube_api.get_service_replica_status.side_effect = [(2, True), (4, True)] + mock_kube_api.has_terminating_pods.return_value = False + # Deployment-level rollingUpdate is InProgress. + mock_kube_api.is_rolling_update_blocking_settlement.return_value = ( + True, + "rollingUpdate.phase=InProgress", + ) + + _, _, is_stable = await kubernetes_connector.get_power_aware_worker_counts( + prefill_component_name="prefill-component", + decode_component_name="decode-component", + ) + + assert is_stable is False + + +@pytest.mark.asyncio +async def test_get_power_aware_worker_counts_failed_rollout_is_unstable( + kubernetes_connector, mock_kube_api +): + """Failed rollout must be treated as unstable by the power snapshot. + + is_rolling_update_blocking_settlement only covers Pending/InProgress; Failed + was intentionally excluded there because startup raises immediately. At + runtime there is no raise, so the power-aware method must be fail-closed + and return is_stable=False so power-aware ticks do not admit scale-ups + during a terminal (Failed) rollout state. + """ + mock_deployment = { + "metadata": {"name": "test-graph"}, + "spec": { + "components": [ + _component("prefill-component"), + _component("decode-component"), + ] + }, + "status": { + "rollingUpdate": {"phase": "Failed", "message": "pod CrashLoopBackOff"} + }, + } + mock_kube_api.get_graph_deployment.return_value = mock_deployment + mock_kube_api.get_service_replica_status.side_effect = [(2, True), (4, True)] + mock_kube_api.has_terminating_pods.return_value = False + # is_rolling_update_blocking_settlement does not cover Failed; simulate that. + mock_kube_api.is_rolling_update_blocking_settlement.return_value = (False, "") + + _, _, is_stable = await kubernetes_connector.get_power_aware_worker_counts( + prefill_component_name="prefill-component", + decode_component_name="decode-component", + ) + + assert is_stable is False + + +@pytest.mark.asyncio +async def test_get_actual_worker_counts_inprogress_rollout_is_stable_when_power_off( + kubernetes_connector, mock_kube_api +): + """InProgress rollout does not affect the ordinary count path. + + Power-disabled planners do not have pods/list RBAC and must not call the + rolling-update helper. The legacy replica-count path stays unchanged. + """ + mock_deployment = _deployment( + _component("prefill-component"), + _component("decode-component"), + ) + mock_kube_api.get_graph_deployment.return_value = mock_deployment + mock_kube_api.get_service_replica_status.side_effect = [(2, True), (4, True)] + + _, _, is_stable = await kubernetes_connector.get_actual_worker_counts( + prefill_component_name="prefill-component", + decode_component_name="decode-component", + ) + + assert is_stable is True + mock_kube_api.is_rolling_update_blocking_settlement.assert_not_called() + + # Tests for _resolve_dgd_service / get_worker_info component-filter. # # Regression: the filter that compares an MDC entry's ``component`` field @@ -1539,3 +1705,46 @@ def test_service_get_component_name_from_endpoint_arg_missing_value(): service=_component("VllmPrefillWorker", args=["--endpoint"]), ) assert service.get_component_name_from_endpoint_arg() is None + + +@pytest.mark.asyncio +async def test_wait_for_deployment_ready_does_not_require_backing(kubernetes_connector): + """Production power-off path must keep the legacy readiness contract.""" + with patch.object( + kubernetes_connector.kube_api, + "wait_for_graph_deployment_ready", + new_callable=AsyncMock, + ) as wait: + await kubernetes_connector.wait_for_deployment_ready(include_planner=False) + wait.assert_awaited_once_with( + kubernetes_connector.graph_deployment_name, + include_planner=False, + require_backing_settled=False, + ) + + +@pytest.mark.asyncio +async def test_wait_for_settled_graph_deployment_requires_backing(kubernetes_connector): + """Power settlement path must opt into generation + backing gates.""" + with patch.object( + kubernetes_connector.kube_api, + "wait_for_graph_deployment_ready", + new_callable=AsyncMock, + return_value={"metadata": {"name": "dgd"}}, + ) as wait: + got = await kubernetes_connector.wait_for_settled_graph_deployment( + include_planner=False, + require_prefill=False, + require_decode=True, + decode_component_name="CustomDecode", + ) + assert got == {"metadata": {"name": "dgd"}} + wait.assert_awaited_once_with( + kubernetes_connector.graph_deployment_name, + include_planner=False, + require_backing_settled=True, + require_prefill=False, + require_decode=True, + prefill_component_name=None, + decode_component_name="CustomDecode", + ) diff --git a/components/src/dynamo/planner/tests/unit/test_metric_publication.py b/components/src/dynamo/planner/tests/unit/test_metric_publication.py index e524479782a9..1badf2c30459 100644 --- a/components/src/dynamo/planner/tests/unit/test_metric_publication.py +++ b/components/src/dynamo/planner/tests/unit/test_metric_publication.py @@ -61,12 +61,11 @@ def _make_planner(prometheus_enabled: bool = True) -> NativePlannerBase: is toggled post-init as an enabled/disabled gate for the methods under test; the actual port value is never used for I/O. """ - with patch( - "dynamo.planner.core.base.PlannerPrometheusMetrics" - ) as mock_metrics, patch("dynamo.planner.core.base.start_http_server"), patch( - "dynamo.planner.connectors.kubernetes.KubernetesAPI" - ), patch.dict( - os.environ, {"DYN_PARENT_DGD_K8S_NAME": "test-graph"} + with ( + patch("dynamo.planner.core.base.PlannerPrometheusMetrics") as mock_metrics, + patch("dynamo.planner.core.base.start_http_server"), + patch("dynamo.planner.connectors.kubernetes.KubernetesAPI"), + patch.dict(os.environ, {"DYN_PARENT_DGD_K8S_NAME": "test-graph"}), ): mock_metrics.return_value = Mock() config = PlannerConfig.model_construct( @@ -340,12 +339,11 @@ def _make_planner_with_port( ``start_http_server`` is still patched to avoid binding a real port. """ port = 9091 if prometheus_enabled else 0 - with patch( - "dynamo.planner.core.base.PlannerPrometheusMetrics" - ) as mock_metrics, patch("dynamo.planner.core.base.start_http_server"), patch( - "dynamo.planner.connectors.kubernetes.KubernetesAPI" - ), patch.dict( - os.environ, {"DYN_PARENT_DGD_K8S_NAME": "test-graph"} + with ( + patch("dynamo.planner.core.base.PlannerPrometheusMetrics") as mock_metrics, + patch("dynamo.planner.core.base.start_http_server"), + patch("dynamo.planner.connectors.kubernetes.KubernetesAPI"), + patch.dict(os.environ, {"DYN_PARENT_DGD_K8S_NAME": "test-graph"}), ): mock_metrics.return_value = Mock() config = PlannerConfig.model_construct( @@ -412,9 +410,10 @@ class TestPlannerPrometheusMetricsHasSlaTargetGauges: def test_metrics_object_has_sla_target_gauge_attributes(self): """Instance attributes sla_target_ttft_ms and sla_target_itl_ms must exist.""" - with patch( - "dynamo.planner.monitoring.planner_metrics.Gauge" - ) as mock_gauge, patch("dynamo.planner.monitoring.planner_metrics.Enum"): + with ( + patch("dynamo.planner.monitoring.planner_metrics.Gauge") as mock_gauge, + patch("dynamo.planner.monitoring.planner_metrics.Enum"), + ): mock_gauge.return_value = MagicMock() metrics = PlannerPrometheusMetrics() @@ -432,3 +431,122 @@ def test_metrics_object_has_sla_target_gauge_attributes(self): assert ( f"{PREFIX}_sla_target_itl_ms" in registered_names ), f"Expected Gauge name '{PREFIX}_sla_target_itl_ms' not registered" + + +def _power_planner( + *, + prefill_watts_per_replica=700, + decode_watts_per_replica=1200, + total_gpu_power_limit=10000, +): + """A power-aware planner whose deployment state carries DGD-resolved caps. + + Per-replica watts live on the cached ``DeploymentState`` (resolved once + from the DGD worker podTemplate annotation during Planner startup), so the + projection reads them directly — no config caps, no apiserver I/O. + """ + planner = _make_planner(prometheus_enabled=True) + planner.config.enable_power_awareness = True + planner.config.total_gpu_power_limit = total_gpu_power_limit + # NativePlannerBase defaults these to False; disagg exercises both roles. + planner.require_prefill = True + planner.require_decode = True + state = planner.environment.deployment_state() + state.prefill.power_watts_per_replica = prefill_watts_per_replica + state.decode.power_watts_per_replica = decode_watts_per_replica + return planner + + +class TestPublishPowerBudgetMetrics: + """_publish_power_budget_metrics reads DGD-resolved per-replica watts from + the cached deployment state and performs NO apiserver I/O on the tick loop.""" + + def test_projection_from_resolved_state(self): + """projected = Σ replicas × DGD-resolved watts_per_replica.""" + planner = _power_planner( + prefill_watts_per_replica=700, + decode_watts_per_replica=1200, + total_gpu_power_limit=10000, + ) + pm = planner.prometheus_metrics + + planner._publish_power_budget_metrics(num_p=2, num_d=3) + + # projected = 2*700 + 3*1200 = 1400 + 3600 = 5000 + pm.power_projected_watts.set.assert_called_once_with(5000) + pm.power_budget_total_watts.set.assert_called_once_with(10000) + pm.power_budget_utilization.set.assert_called_once_with(0.5) + + def test_asymmetric_caps(self): + """Prefill and decode watts are independent.""" + planner = _power_planner( + prefill_watts_per_replica=350, + decode_watts_per_replica=250, + total_gpu_power_limit=2000, + ) + pm = planner.prometheus_metrics + + planner._publish_power_budget_metrics(num_p=1, num_d=1) + + pm.power_projected_watts.set.assert_called_once_with(600) + + def test_multinode_watts_already_multiplied(self): + """State watts are per-replica (nodeCount × per-pod × cap), used as-is.""" + planner = _power_planner( + prefill_watts_per_replica=2100, # 2 GPU × 3 nodes × 350 W + decode_watts_per_replica=300, + total_gpu_power_limit=10000, + ) + pm = planner.prometheus_metrics + + planner._publish_power_budget_metrics(num_p=2, num_d=1) + + # 2*2100 + 1*300 = 4500 + pm.power_projected_watts.set.assert_called_once_with(4500) + + def test_skipped_when_power_awareness_disabled(self): + """Disabled power awareness publishes nothing at all.""" + planner = _power_planner() + planner.config.enable_power_awareness = False + pm = planner.prometheus_metrics + + planner._publish_power_budget_metrics(num_p=1, num_d=1) + + pm.power_projected_watts.set.assert_not_called() + + def test_skipped_when_prometheus_disabled(self): + """No Prometheus port means no gauge publication.""" + planner = _power_planner() + planner.prometheus_port = 0 + pm = planner.prometheus_metrics + + planner._publish_power_budget_metrics(num_p=1, num_d=1) + + pm.power_projected_watts.set.assert_not_called() + + @pytest.mark.parametrize("budget", [None, 0, -5]) + def test_no_projection_without_positive_budget(self, budget): + """A missing / zero / negative budget skips projection gauges.""" + planner = _power_planner(total_gpu_power_limit=budget) + pm = planner.prometheus_metrics + + planner._publish_power_budget_metrics(num_p=1, num_d=1) + + pm.power_projected_watts.set.assert_not_called() + pm.power_budget_utilization.set.assert_not_called() + + def test_unresolved_watts_warns_once_and_skips_projection(self): + """A required role with no resolved watts skips projection and warns once + rather than publishing a misleading partial value.""" + planner = _power_planner() + state = planner.environment.deployment_state() + state.prefill.power_watts_per_replica = None + + pm = planner.prometheus_metrics + with patch("dynamo.planner.core.base.logger") as mock_logger: + planner._publish_power_budget_metrics(num_p=1, num_d=1) + planner._publish_power_budget_metrics(num_p=1, num_d=1) + + pm.power_projected_watts.set.assert_not_called() + assert mock_logger.warning.call_count == 1 + assert planner._power_projected_zero_warned is True diff --git a/components/src/dynamo/planner/tests/unit/test_planner_config.py b/components/src/dynamo/planner/tests/unit/test_planner_config.py index eb9b9dcc00b6..80c3b6221a03 100644 --- a/components/src/dynamo/planner/tests/unit/test_planner_config.py +++ b/components/src/dynamo/planner/tests/unit/test_planner_config.py @@ -46,6 +46,73 @@ def test_invalid_environment(): ) +# --------------------------------------------------------------------------- +# Power-awareness validator (DGD-owned caps; read-only) +# --------------------------------------------------------------------------- + + +def test_power_awareness_disabled_by_default_needs_no_budget(): + """The feature is off by default, so an otherwise-minimal config is valid + with the power fields left unset.""" + config = PlannerConfig(namespace="test-ns") + assert config.enable_power_awareness is False + assert config.total_gpu_power_limit is None + + +def test_power_awareness_requires_total_gpu_power_limit(): + """enable_power_awareness=True without total_gpu_power_limit must fail — + there is no safe default for the deployment-wide budget.""" + with pytest.raises(ValidationError, match="total_gpu_power_limit is required"): + PlannerConfig( + namespace="test-ns", + enable_power_awareness=True, + ) + + +def test_power_awareness_requires_kubernetes_environment(): + """Per-GPU caps are read from the DGD, so power awareness is only valid on + the Kubernetes connector.""" + with pytest.raises(ValidationError, match="requires environment='kubernetes'"): + PlannerConfig( + namespace="test-ns", + environment="virtual", + enable_power_awareness=True, + total_gpu_power_limit=5000, + ) + + +def test_power_awareness_rejects_agg_mode(): + """Power awareness is not supported with mode='agg': the Kubernetes + validate_deployment and GPU-count paths use the typed decode resolver, which + does not follow the generic type:worker fallback used by the power parser.""" + with pytest.raises(ValidationError, match="not supported with mode='agg'"): + PlannerConfig( + namespace="test-ns", + mode="agg", + enable_power_awareness=True, + total_gpu_power_limit=5000, + ) + + +def test_power_awareness_enabled_with_required_fields_ok(): + """Budget present and environment=kubernetes (default): config validates.""" + config = PlannerConfig( + namespace="test-ns", + enable_power_awareness=True, + total_gpu_power_limit=5000, + ) + assert config.enable_power_awareness is True + assert config.total_gpu_power_limit == 5000 + assert config.environment == "kubernetes" + + +def test_total_gpu_power_limit_rejects_non_positive(): + """total_gpu_power_limit carries a ge=1 constraint (fires regardless of the + awareness flag).""" + with pytest.raises(ValidationError): + PlannerConfig(namespace="test-ns", total_gpu_power_limit=0) + + def test_all_fields_work(): """Test that PlannerConfig accepts all fields.""" config = PlannerConfig( diff --git a/components/src/dynamo/planner/tests/unit/test_power_annotation_contract.py b/components/src/dynamo/planner/tests/unit/test_power_annotation_contract.py new file mode 100644 index 000000000000..e9618e11907d --- /dev/null +++ b/components/src/dynamo/planner/tests/unit/test_power_annotation_contract.py @@ -0,0 +1,60 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Contract test: the planner and Power Agent per-GPU power-limit annotation +keys must be byte-identical. + +The two constants are intentionally duplicated rather than shared as a package +import: the Power Agent image copies three standalone files and does not install +the ``dynamo`` Python package, so a runtime dependency only to share one string +is not justified. This test is +the safety net that keeps them in sync. +""" + +import re +from pathlib import Path + +import pytest + +from dynamo.planner.monitoring.dgd_services import POWER_ANNOTATION_KEY + +pytestmark = [ + pytest.mark.gpu_0, + pytest.mark.pre_merge, + pytest.mark.unit, + pytest.mark.planner, +] + +_LITERAL = re.compile(r'^POWER_ANNOTATION_KEY\s*=\s*"([^"]+)"', re.MULTILINE) + + +def _find_power_agent_source() -> Path: + """Walk up from this test file to locate deploy/power-agent/power_agent.py.""" + for parent in Path(__file__).resolve().parents: + candidate = parent / "deploy" / "power-agent" / "power_agent.py" + if candidate.is_file(): + return candidate + raise AssertionError( + "Could not locate deploy/power-agent/power_agent.py from " + f"{Path(__file__).resolve()}" + ) + + +def test_planner_and_power_agent_annotation_keys_match(): + source = _find_power_agent_source().read_text(encoding="utf-8") + match = _LITERAL.search(source) + assert match is not None, ( + "POWER_ANNOTATION_KEY literal not found in power_agent.py; the contract " + "test can no longer verify the duplicated constants agree." + ) + agent_key = match.group(1) + assert agent_key == POWER_ANNOTATION_KEY, ( + "Power Agent and planner per-GPU power-limit annotation keys diverged: " + f"power_agent.py={agent_key!r} planner={POWER_ANNOTATION_KEY!r}. Keep the " + "two literals identical." + ) + + +def test_annotation_key_value_is_the_expected_literal(): + # Pin the literal so a rename is a deliberate, reviewed change on both sides. + assert POWER_ANNOTATION_KEY == "dynamo.nvidia.com/gpu-power-limit" diff --git a/components/src/dynamo/planner/tests/unit/test_power_budget.py b/components/src/dynamo/planner/tests/unit/test_power_budget.py new file mode 100644 index 000000000000..459bea87f743 --- /dev/null +++ b/components/src/dynamo/planner/tests/unit/test_power_budget.py @@ -0,0 +1,704 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Power-budget clamp (Phase 4): pure ceiling math + engine_adapter wiring. + +Covers the ceiling-only clamp on projected watts (fit → no-op, proportional +shrink, decode-no-upscale, partial proposals, mid-rollout scale-up hold) and the +final-boundary ordering guarantee in ``OrchestratorEngineAdapter``: GPU budget +first, then power budget (non-commutative; power wins over the GPU floor). +""" + +import logging +from types import SimpleNamespace + +import pytest + +from dynamo.planner.core.budget import ( + _shrink_pair, + apply_power_budget, + minimum_power_footprint_fits, + peak_parallel_watts, + project_watts, +) +from dynamo.planner.core.types import ( + EngineCapabilities, + WorkerCapabilities, + WorkerCounts, +) +from dynamo.planner.plugins.merge.types import ComponentKey +from dynamo.planner.plugins.orchestrator.engine_adapter import OrchestratorEngineAdapter + +pytestmark = [ + pytest.mark.gpu_0, + pytest.mark.pre_merge, + pytest.mark.unit, + pytest.mark.planner, +] + + +# --------------------------------------------------------------------------- +# project_watts / minimum_power_footprint_fits +# --------------------------------------------------------------------------- + + +def test_project_watts_sums_present_roles(): + assert project_watts(2, 3, 700, 1200) == 2 * 700 + 3 * 1200 + assert project_watts(2, None, 700, 1200) == 1400 + assert project_watts(None, 3, 700, 1200) == 3600 + assert project_watts(2, 3, None, None) == 0 + + +@pytest.mark.parametrize( + "budget,min_endpoint,p,d,fits", + [ + (5000, 1, 700, 1200, True), # 1900 <= 5000 + (1900, 1, 700, 1200, True), # exactly fits + (1899, 1, 700, 1200, False), # 1900 > 1899 + (1000, 2, 700, 1200, False), # 2*(700+1200) = 3800 > 1000 + (2000, 1, None, 1200, True), # only decode present + ], +) +def test_minimum_power_footprint_fits(budget, min_endpoint, p, d, fits): + assert minimum_power_footprint_fits(budget, min_endpoint, p, d) is fits + + +# --------------------------------------------------------------------------- +# apply_power_budget — ceiling clamp +# --------------------------------------------------------------------------- + + +def test_fit_is_a_no_op(): + assert apply_power_budget(2, 2, 2, 2, 700, 1200, 100000, 1) == (2, 2, None) + + +def test_disagg_over_budget_shrinks_proportionally_to_fit(): + # 3*700 + 3*1200 = 5700 > 5000 + new_p, new_d, reason = apply_power_budget(3, 3, 2, 2, 700, 1200, 5000, 1) + assert reason == "power_budget_clamped" + assert new_p <= 3 and new_d <= 3 # decode-no-upscale: never raised + assert new_p * 700 + new_d * 1200 <= 5000 + + +def test_ceiling_never_raises_a_proposed_count(): + # Even with a huge budget, a proposal that already fits is untouched. + assert apply_power_budget(1, 1, 5, 5, 700, 1200, 100000, 1) == (1, 1, None) + + +def test_partial_proposal_does_not_mutate_unproposed_component(): + # Only prefill proposed; decode fixed at current=2 (2*1200=2400). + # 4*700 + 2400 = 5200 > 5000, so prefill must shrink; decode stays None. + new_p, new_d, reason = apply_power_budget(4, None, 2, 2, 700, 1200, 5000, 1) + assert new_d is None # unproposed decode untouched + assert new_p * 700 + 2 * 1200 <= 5000 + assert reason is not None + + +def test_partial_proposal_suppressed_when_unproposed_alone_over_budget(): + # decode current=5 → 5*1200 = 6000 already over the 5500 budget; prefill + # cannot fit even min_endpoint without changing decode → scale-up refused. + new_p, new_d, reason = apply_power_budget(4, None, 1, 5, 700, 1200, 5500, 1) + assert new_d is None + assert new_p == 1 # held at current (no scale-up) + assert reason == "power_budget_scale_up_suppressed" + + +def test_partial_proposal_suppressed_when_current_missing_and_peer_over_budget(): + # Prefill has no ready count yet (current_p=None) while decode alone is + # already over budget. Creating prefill would worsen the draw — refuse + # rather than letting the full proposal pass through. + new_p, new_d, reason = apply_power_budget(4, None, None, 5, 700, 1200, 5500, 1) + assert new_d is None + assert new_p == 0 + assert reason == "power_budget_scale_up_suppressed" + + +def test_peak_parallel_watts_rebalance_example(): + assert peak_parallel_watts(1, 4, 4, 1, 1000, 1000) == 8000 + assert project_watts(4, 1, 1000, 1000) == 5000 + + +def test_apply_power_budget_rebalance_stages_scale_down_first(): + # Ted P1: settled (4,1)=5000W fits, but parallel peak (4,4)=8000W does not. + assert apply_power_budget(4, 1, 1, 4, 1000, 1000, 5000, 1) == ( + 1, + 1, + "power_rebalance_staged", + ) + + +def test_apply_power_budget_clamp_synthesized_rebalance_is_staged(): + """Clamp can create an opposing rebalance even when the proposal was not one. + + Current (4,1), proposal (5,5), 1000 W/replica, 5000 W budget: the + proportional clamp yields settled (2,3)=5000 W, but parallel actuation + peaks at (4,3)=7000 W. Stage by holding the decode scale-up at current + so this tick emits (2,1) under the ceiling instead of (2,3). + """ + assert apply_power_budget(5, 5, 4, 1, 1000, 1000, 5000, 1) == ( + 2, + 1, + "power_rebalance_staged", + ) + assert peak_parallel_watts(4, 1, 2, 1, 1000, 1000) <= 5000 + + +def test_apply_power_budget_rebalance_staged_with_none_current_p(): + """None current_p (unobserved prefill) must not bypass peak staging. + + Prefill unobserved (current_p=None, treated as 0), decode at 4. + Proposal (4,1) settles at 5000 W, but parallel peak is + max(0,4)*1000 + max(4,1)*1000 = 8000 W > 5000 W budget. + The scale-up leg (prefill) must be held at 0 to stage the decode + scale-down first. + """ + result = apply_power_budget(4, 1, None, 4, 1000, 1000, 5000, 1) + assert result == (0, 1, "power_rebalance_staged"), result + assert peak_parallel_watts(None, 4, 0, 1, 1000, 1000) <= 5000 + + +def test_shrink_pair_infeasible_raises_runtime_error(): + """_shrink_pair must raise RuntimeError for an infeasible budget. + + minimum_power_footprint_fits() at startup prevents this in production. + The explicit RuntimeError (not assert) is safe under -O optimized Python. + """ + with pytest.raises(RuntimeError, match="infeasible"): + _shrink_pair(5, 5, 2000, 2000, 1000, 1) + + +def test_shrink_pair_asymmetric_wattage_never_raises_decode_above_proposed(): + """p_watts >> d_watts must not push new_d above num_d. + + num_p=3, num_d=10, p_watts=100, d_watts=1, budget=200: + projected=310>200. Proportional shrink lands new_p=1 (p_watts is expensive). + remaining=200-100=100; floor(100/1)=100 >> num_d=10 without the cap. + """ + new_p, new_d = _shrink_pair(3, 10, 100, 1, 200, 1) + assert new_d <= 10, f"new_d={new_d} raised above proposed num_d=10" + assert new_p * 100 + new_d * 1 <= 200, "result exceeds budget" + assert new_p >= 1 and new_d >= 1, "must keep at least min_endpoint of each" + + +def test_already_over_budget_baseline_with_no_proposal_is_left_alone(): + # Nothing proposed (both None); baseline over budget but no lever this tick. + assert apply_power_budget(None, None, 10, 10, 700, 1200, 100, 1) == ( + None, + None, + None, + ) + + +# --------------------------------------------------------------------------- +# engine_adapter final-boundary ordering (GPU budget then power budget) +# --------------------------------------------------------------------------- + + +def _bare_adapter(config, capabilities) -> OrchestratorEngineAdapter: + """An adapter with only the fields the budget path reads (skips heavy init).""" + adapter = object.__new__(OrchestratorEngineAdapter) + adapter._config = config + adapter._capabilities = capabilities + adapter._power_rollout_hold_warned = False + return adapter + + +def _agg_config(**overrides): + base = dict( + enable_power_awareness=True, + total_gpu_power_limit=1200, + min_endpoint=1, + min_gpu_budget=8, # GPU floor: 8 GPUs + max_gpu_budget=-1, # no GPU ceiling + mode="agg", + ) + base.update(overrides) + return SimpleNamespace(**base) + + +def test_gpu_budget_then_power_budget_order_is_not_commutative(caplog): + """The GPU floor raises decode to 8, then the power ceiling lowers it to fit + 1200 W — power wins. Applying power first would fit the proposal, then the + GPU floor would raise it back above budget: the two orders disagree.""" + caps = WorkerCapabilities( + prefill=None, + decode=EngineCapabilities(num_gpu=1, power_watts_per_replica=400), + ) + adapter = _bare_adapter(_agg_config(), caps) + wc = WorkerCounts(ready_num_decode=2, expected_num_decode=2) # stable + + # Pipeline order (GPU floor first, then power ceiling): power wins → 3 + # (3 × 400 W = 1200 W fits). The GPU floor of 8 is violated by design — + # power wins over the GPU floor; the clamp warning records both stages. + with caplog.at_level(logging.WARNING): + assert adapter._apply_final_budget(None, 2, wc) == (None, 3) + assert any( + "GPU clamp first adjusted proposed" in r.message + and "power wins over GPU floor" in r.message + for r in caplog.records + ) + + # Reverse order: power fit leaves 2, then the GPU floor raises to 8 — which + # is 3200 W, over the 1200 W budget. Different result → non-commutative. + power_first = adapter._apply_power_final_budget(None, 2, wc) + reversed_result = adapter._apply_gpu_final_budget( + power_first[0], power_first[1], wc + ) + assert reversed_result == (None, 8) + assert reversed_result != adapter._apply_final_budget(None, 2, wc) + + +def test_power_clamp_noop_when_awareness_disabled(): + caps = WorkerCapabilities( + prefill=None, + decode=EngineCapabilities(num_gpu=1, power_watts_per_replica=400), + ) + adapter = _bare_adapter( + _agg_config(enable_power_awareness=False, min_gpu_budget=-1), caps + ) + wc = WorkerCounts(ready_num_decode=2) + # No GPU floor, awareness off → proposal passes through untouched. + assert adapter._apply_final_budget(None, 5, wc) == (None, 5) + + +def _mode_config(mode, **overrides): + base = dict( + enable_power_awareness=True, + total_gpu_power_limit=1200, + min_endpoint=1, + min_gpu_budget=-1, + max_gpu_budget=-1, + mode=mode, + ) + base.update(overrides) + return SimpleNamespace(**base) + + +def _apply_outcome(*targets, proposed=None): + if proposed is None: + proposed = { + target.sub_component_type + for target in targets + if target.replicas is not None + } + return SimpleNamespace( + execute_action="apply", + final_proposal=SimpleNamespace(targets=list(targets)), + proposed_components=frozenset( + ComponentKey(sub_component_type=component) for component in proposed + ), + ) + + +def test_final_boundary_clamps_prefill_mode(): + caps = WorkerCapabilities( + prefill=EngineCapabilities(num_gpu=1, power_watts_per_replica=400), + decode=None, + ) + adapter = _bare_adapter(_mode_config("prefill", total_gpu_power_limit=1200), caps) + wc = WorkerCounts(ready_num_prefill=2, expected_num_prefill=2) # stable + # 6 × 400 W = 2400 W > 1200 W → clamp prefill to floor(1200/400)=3; decode + # is None (not managed in prefill mode) and stays None. + assert adapter._apply_final_budget(6, None, wc) == (3, None) + + +def test_final_boundary_clamps_decode_mode(): + caps = WorkerCapabilities( + prefill=None, + decode=EngineCapabilities(num_gpu=1, power_watts_per_replica=300), + ) + adapter = _bare_adapter(_mode_config("decode", total_gpu_power_limit=900), caps) + wc = WorkerCounts(ready_num_decode=2, expected_num_decode=2) # stable + # 6 × 300 W = 1800 W > 900 W → clamp decode to floor(900/300)=3. + assert adapter._apply_final_budget(None, 6, wc) == (None, 3) + + +def test_final_boundary_clamps_disagg_mode(): + caps = WorkerCapabilities( + prefill=EngineCapabilities(num_gpu=2, power_watts_per_replica=700), + decode=EngineCapabilities(num_gpu=4, power_watts_per_replica=1200), + ) + adapter = _bare_adapter(_mode_config("disagg", total_gpu_power_limit=5000), caps) + wc = WorkerCounts( + ready_num_prefill=2, + ready_num_decode=2, + expected_num_prefill=2, + expected_num_decode=2, + ) # stable + # 4*700 + 4*1200 = 7600 W > 5000 W → proportionally shrunk to fit. + new_p, new_d = adapter._apply_final_budget(4, 4, wc) + assert new_p <= 4 and new_d <= 4 + assert new_p * 700 + new_d * 1200 <= 5000 + + +def test_final_boundary_clamps_merged_proposal_regardless_of_source(): + """``_project_scale_to`` applies the power clamp to the merged + ``final_proposal`` — the single point where builtin and external plugin + proposals converge — so the budget is enforced no matter which plugin + produced the counts.""" + caps = WorkerCapabilities( + prefill=None, + decode=EngineCapabilities(num_gpu=1, power_watts_per_replica=400), + ) + adapter = _bare_adapter(_mode_config("agg", total_gpu_power_limit=1200), caps) + outcome = _apply_outcome(SimpleNamespace(sub_component_type="decode", replicas=6)) + wc = WorkerCounts(ready_num_decode=2, expected_num_decode=2) # stable + decision = adapter._project_scale_to(outcome, wc) + # 6 × 400 W = 2400 W over the 1200 W budget → clamped to 3 in the decision. + assert decision is not None + assert decision.num_decode == 3 + + +def test_project_scale_to_keeps_budget_hold_when_settled_target_is_unknown(): + """Unknown settled state is not enough evidence to suppress a target.""" + caps = WorkerCapabilities( + prefill=EngineCapabilities(num_gpu=1, power_watts_per_replica=700), + decode=EngineCapabilities(num_gpu=1, power_watts_per_replica=1200), + ) + adapter = _bare_adapter(_mode_config("disagg", total_gpu_power_limit=5500), caps) + outcome = _apply_outcome(SimpleNamespace(sub_component_type="prefill", replicas=4)) + # Decode alone already exceeds the ceiling. Prefill has never been + # observed, so the budget layer holds it at the empty baseline (0); + # Projection preserves that explicit result because expected prefill is + # unknown; only equality with a known settled target proves a no-op. + wc = WorkerCounts( + ready_num_prefill=None, + ready_num_decode=5, + expected_num_prefill=None, + expected_num_decode=5, + ) + + decision = adapter._project_scale_to(outcome, wc) + assert decision is not None + assert decision.num_prefill == 0 + assert decision.num_decode is None + + +# The Kubernetes environment uses a single deployment-wide stability flag, so a +# rollout of EITHER role marks BOTH roles' ``expected`` (settled) count None. +# These tests use that reachable state (both None during any rollout). + + +def test_scale_up_held_while_deployment_is_rolling(caplog): + """Fail closed: while any power-relevant role is mid-rollout (deployment + unstable → both expected None), a proposed scale-up emits no target, since + a rolling role can only be charged at its transient ready count. + + The hold warning fires once per continuous mid-rollout stretch, not every + tick, so long rollouts do not flood logs. + """ + caps = WorkerCapabilities( + prefill=EngineCapabilities(num_gpu=2, power_watts_per_replica=700), + decode=EngineCapabilities(num_gpu=4, power_watts_per_replica=1200), + ) + adapter = _bare_adapter(_mode_config("disagg", total_gpu_power_limit=5000), caps) + wc = WorkerCounts( + ready_num_prefill=2, + ready_num_decode=2, + expected_num_prefill=None, # deployment mid-rollout -> + expected_num_decode=None, # both settled targets unknown + ) + with caplog.at_level(logging.WARNING): + # Prefill proposed 2 -> 4 emits no target while the deployment rolls. + assert adapter._apply_final_budget(4, None, wc) == (None, None) + assert adapter._apply_final_budget(4, None, wc) == (None, None) + hold_warnings = [ + r + for r in caplog.records + if "holding" in r.message and "mid-rollout" in r.message + ] + assert len(hold_warnings) == 1 + + # After the deployment stabilizes, a later rollout may warn again. + stable = WorkerCounts( + ready_num_prefill=2, + ready_num_decode=2, + expected_num_prefill=2, + expected_num_decode=2, + ) + assert adapter._apply_final_budget(2, None, stable) == (2, None) + assert adapter._power_rollout_hold_warned is False + rolling_again = WorkerCounts( + ready_num_prefill=2, + ready_num_decode=2, + expected_num_prefill=None, + expected_num_decode=None, + ) + with caplog.at_level(logging.WARNING): + caplog.clear() + assert adapter._apply_final_budget(4, None, rolling_again) == (None, None) + assert ( + sum( + 1 + for r in caplog.records + if "holding" in r.message and "mid-rollout" in r.message + ) + == 1 + ) + + +def test_scale_up_allowed_when_deployment_stable(): + """When the deployment is stable (both expected known == ready), a proposal + is budgeted normally against the known footprint.""" + caps = WorkerCapabilities( + prefill=EngineCapabilities(num_gpu=2, power_watts_per_replica=700), + decode=EngineCapabilities(num_gpu=4, power_watts_per_replica=1200), + ) + adapter = _bare_adapter(_mode_config("disagg", total_gpu_power_limit=6000), caps) + wc = WorkerCounts( + ready_num_prefill=2, + ready_num_decode=2, + expected_num_prefill=2, + expected_num_decode=2, # deployment stable + ) + # decode at 2 (2400 W); prefill 2->4 (2800 W); total 5200 <= 6000 → allowed. + assert adapter._apply_final_budget(4, None, wc) == (4, None) + + +def test_scale_down_allowed_while_deployment_is_rolling(): + """A scale-down is always safe (reduces power), even mid-rollout.""" + caps = WorkerCapabilities( + prefill=EngineCapabilities(num_gpu=2, power_watts_per_replica=700), + decode=EngineCapabilities(num_gpu=4, power_watts_per_replica=1200), + ) + adapter = _bare_adapter(_mode_config("disagg", total_gpu_power_limit=5000), caps) + wc = WorkerCounts( + ready_num_prefill=4, + ready_num_decode=2, + expected_num_prefill=None, # deployment mid-rollout + expected_num_decode=None, + ) + # Prefill scale-down 4 -> 2 is honored despite the rollout. + assert adapter._apply_final_budget(2, None, wc) == (2, None) + + +def test_project_scale_to_holds_scale_up_during_rollout_full_merge(): + """Production-shaped reproduction of the Kubernetes runtime path. + + ``type_aware_merge`` fills a role a plugin omitted from the baseline, so the + final proposal carries a target for BOTH roles (neither is None). The K8s + environment marks BOTH ``expected`` counts None during any rollout, so the + guard must key off that deployment-wide rollout state — not per-role or + None-target detection — and hold the decode scale-up. Without the fix this + returned ``ScalingDecision(num_prefill=2, num_decode=2)``.""" + caps = WorkerCapabilities( + prefill=EngineCapabilities(num_gpu=2, power_watts_per_replica=700), + decode=EngineCapabilities(num_gpu=4, power_watts_per_replica=1200), + ) + # Huge budget so only the rollout guard (not the budget clamp) can act. + adapter = _bare_adapter(_mode_config("disagg", total_gpu_power_limit=100000), caps) + # Deployment mid-rollout: BOTH expected counts unknown (the reachable state). + # Merged proposal carries prefill=2 (baseline) and decode=2 (a scale-up). + wc = WorkerCounts( + ready_num_prefill=2, + ready_num_decode=1, + expected_num_prefill=None, + expected_num_decode=None, + ) + outcome = _apply_outcome( + SimpleNamespace(sub_component_type="prefill", replicas=2), + SimpleNamespace(sub_component_type="decode", replicas=2), + proposed={"decode"}, + ) + decision = adapter._project_scale_to(outcome, wc) + # Decode must not emit a scale-up target while the deployment rolls. + assert decision is None or (decision.num_decode or 0) <= 1 + + +def test_project_scale_to_masks_unproposed_echo_during_rollout_scale_down(): + """A scale-down must not drag the other role's merged baseline echo. + + Production-shaped: prefill is rolling from ready=2 toward a larger desired + (deployment unstable → both ``expected`` None), while decode legitimately + scales down 3 -> 2. ``type_aware_merge`` echoes prefill's baseline == ready 2 + into the merged proposal, so before masking ``_project_scale_to`` returned + ``ScalingDecision(num_prefill=2, num_decode=2)``; DisaggPlanner applies every + non-None target, writing prefill's DGD desired back to 2 and cancelling its + in-flight rollout. The explicit proposal mask drops prefill to None while + preserving the decode scale-down.""" + caps = WorkerCapabilities( + prefill=EngineCapabilities(num_gpu=2, power_watts_per_replica=700), + decode=EngineCapabilities(num_gpu=4, power_watts_per_replica=1200), + ) + # Budget large enough that the decode scale-down is never the constraint. + adapter = _bare_adapter(_mode_config("disagg", total_gpu_power_limit=100000), caps) + wc = WorkerCounts( + ready_num_prefill=2, + ready_num_decode=3, + expected_num_prefill=None, # deployment mid-rollout (prefill 2 -> desired) + expected_num_decode=None, + ) + outcome = _apply_outcome( + # prefill baseline echo == ready 2 (not an intended change) + SimpleNamespace(sub_component_type="prefill", replicas=2), + # decode scale-down 3 -> 2 + SimpleNamespace(sub_component_type="decode", replicas=2), + proposed={"decode"}, + ) + decision = adapter._project_scale_to(outcome, wc) + # prefill's ready echo is masked to None (its rollout desired is left + # untouched); the decode scale-down survives. + assert decision is not None + assert decision.num_prefill is None + assert decision.num_decode == 2 + + +def test_project_scale_to_preserves_explicit_transient_ready_target(): + """An explicit target may intentionally cancel an in-flight rollout. + + During a rollout the settled target is unknown, so value equality with the + transient ready count is not proof of a no-op. + """ + caps = WorkerCapabilities( + prefill=EngineCapabilities(num_gpu=1, power_watts_per_replica=500), + decode=EngineCapabilities(num_gpu=1, power_watts_per_replica=500), + ) + adapter = _bare_adapter(_mode_config("disagg", total_gpu_power_limit=100000), caps) + wc = WorkerCounts( + ready_num_prefill=2, + ready_num_decode=3, + expected_num_prefill=None, + expected_num_decode=None, + ) + outcome = _apply_outcome( + SimpleNamespace(sub_component_type="prefill", replicas=2), + proposed={"prefill"}, + ) + + decision = adapter._project_scale_to(outcome, wc) + + assert decision is not None + assert decision.num_prefill == 2 + assert decision.num_decode is None + + +def test_project_scale_to_partial_prefill_proposal_does_not_scale_decode(): + """Stable merged ``(prefill=5, decode=2)`` at ready ``(2, 2)`` under the + 5000 W example budget must clamp only prefill and leave decode unemitted. + + ``type_aware_merge`` fills the omitted decode role with its ready baseline, + so without restoring the proposal mask before the power clamp both roles + look adjustable and ``_shrink_pair`` can return decode=1 — a cross-role + scale-down ``DisaggPlanner`` would apply. + """ + caps = WorkerCapabilities( + prefill=EngineCapabilities(num_gpu=2, power_watts_per_replica=700), + decode=EngineCapabilities(num_gpu=4, power_watts_per_replica=1200), + ) + adapter = _bare_adapter(_mode_config("disagg", total_gpu_power_limit=5000), caps) + wc = WorkerCounts( + ready_num_prefill=2, + ready_num_decode=2, + expected_num_prefill=2, + expected_num_decode=2, + ) + outcome = _apply_outcome( + SimpleNamespace(sub_component_type="prefill", replicas=5), + # Baseline echo of ready decode — not a genuine proposal. + SimpleNamespace(sub_component_type="decode", replicas=2), + proposed={"prefill"}, + ) + decision = adapter._project_scale_to(outcome, wc) + assert decision is not None + # 3*700 + 2*1200 = 4500 <= 5000; decode stays None (charged, not adjusted). + assert decision.num_prefill == 3 + assert decision.num_decode is None + + +def test_project_scale_to_partial_decode_proposal_does_not_scale_prefill(): + """Mirror of the prefill-only case: merged ``(prefill=2, decode=5)`` must + not emit a prefill target.""" + caps = WorkerCapabilities( + prefill=EngineCapabilities(num_gpu=2, power_watts_per_replica=700), + decode=EngineCapabilities(num_gpu=4, power_watts_per_replica=1200), + ) + adapter = _bare_adapter(_mode_config("disagg", total_gpu_power_limit=5000), caps) + wc = WorkerCounts( + ready_num_prefill=2, + ready_num_decode=2, + expected_num_prefill=2, + expected_num_decode=2, + ) + outcome = _apply_outcome( + SimpleNamespace(sub_component_type="prefill", replicas=2), + SimpleNamespace(sub_component_type="decode", replicas=5), + proposed={"decode"}, + ) + decision = adapter._project_scale_to(outcome, wc) + assert decision is not None + # 2*700 + 3*1200 = 5000; prefill stays None. + assert decision.num_prefill is None + assert decision.num_decode == 3 + + +def test_project_scale_to_rebalance_emits_decode_only_tick1(): + """Stable (1P,4D) -> (4P,1D) must stage decode scale-down before prefill up.""" + caps = WorkerCapabilities( + prefill=EngineCapabilities(num_gpu=1, power_watts_per_replica=1000), + decode=EngineCapabilities(num_gpu=1, power_watts_per_replica=1000), + ) + adapter = _bare_adapter(_mode_config("disagg", total_gpu_power_limit=5000), caps) + wc = WorkerCounts( + ready_num_prefill=1, + ready_num_decode=4, + expected_num_prefill=1, + expected_num_decode=4, + ) + outcome = _apply_outcome( + SimpleNamespace(sub_component_type="prefill", replicas=4), + SimpleNamespace(sub_component_type="decode", replicas=1), + ) + decision = adapter._project_scale_to(outcome, wc) + assert decision is not None + assert decision.num_prefill is None + assert decision.num_decode == 1 + + +def test_project_scale_to_rebalance_prefill_up_after_decode_stable(): + """Tick 2: once decode is at 1, prefill scale-up to 4 is safe.""" + caps = WorkerCapabilities( + prefill=EngineCapabilities(num_gpu=1, power_watts_per_replica=1000), + decode=EngineCapabilities(num_gpu=1, power_watts_per_replica=1000), + ) + adapter = _bare_adapter(_mode_config("disagg", total_gpu_power_limit=5000), caps) + wc = WorkerCounts( + ready_num_prefill=1, + ready_num_decode=1, + expected_num_prefill=1, + expected_num_decode=1, + ) + outcome = _apply_outcome( + SimpleNamespace(sub_component_type="prefill", replicas=4), + SimpleNamespace(sub_component_type="decode", replicas=1), + ) + decision = adapter._project_scale_to(outcome, wc) + assert decision is not None + assert decision.num_prefill == 4 + assert decision.num_decode is None + + +def test_project_scale_to_partial_scale_down_does_not_mutate_unproposed_role(): + """An over-budget one-role scale-down must not drag the baseline-echoed + role through ``_shrink_pair``.""" + caps = WorkerCapabilities( + prefill=EngineCapabilities(num_gpu=2, power_watts_per_replica=700), + decode=EngineCapabilities(num_gpu=4, power_watts_per_replica=1200), + ) + adapter = _bare_adapter(_mode_config("disagg", total_gpu_power_limit=5000), caps) + # Current 4P+4D = 7600 W already over the 5000 W budget. + wc = WorkerCounts( + ready_num_prefill=4, + ready_num_decode=4, + expected_num_prefill=4, + expected_num_decode=4, + ) + outcome = _apply_outcome( + SimpleNamespace(sub_component_type="prefill", replicas=2), + SimpleNamespace(sub_component_type="decode", replicas=4), + proposed={"prefill"}, + ) + decision = adapter._project_scale_to(outcome, wc) + assert decision is not None + assert decision.num_prefill == 2 + # Decode was only a ready echo — must not be emitted / scaled down. + assert decision.num_decode is None diff --git a/components/src/dynamo/planner/tests/unit/test_power_environment.py b/components/src/dynamo/planner/tests/unit/test_power_environment.py new file mode 100644 index 000000000000..42995a8befa3 --- /dev/null +++ b/components/src/dynamo/planner/tests/unit/test_power_environment.py @@ -0,0 +1,440 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Environment power-config load policy (init-only static caps). + +``PlannerEnvironmentImpl._load_static_power_caps_at_startup`` reads DGD-owned +caps once after worker readiness and fails closed on malformed or infeasible +values. Caps are startup-static for the Planner lifetime: ``refresh()`` never +re-reads or re-adopts them. DGD admission rejects annotation or topology tuple +changes; adopting new values requires a replacement DGD and Planner process. +""" + +from unittest.mock import AsyncMock, MagicMock, Mock + +import pytest +from kubernetes.client import ApiException + +from dynamo.planner.config.planner_config import PlannerConfig +from dynamo.planner.connectors.base import is_power_aware_connector +from dynamo.planner.environment.base import PlannerEnvironmentImpl +from dynamo.planner.errors import DeploymentValidationError, PowerAnnotationInvalidError +from dynamo.planner.monitoring.dgd_services import ( + POWER_ANNOTATION_KEY, + ComponentPowerConfig, +) + +pytestmark = [ + pytest.mark.gpu_0, + pytest.mark.pre_merge, + pytest.mark.unit, + pytest.mark.planner, +] + + +def _cfg(role, gpu_power_limit_watts, gpus_per_replica=1): + return ComponentPowerConfig( + component_name=role, + role=role, + gpu_power_limit_watts=gpu_power_limit_watts, + gpus_per_replica=gpus_per_replica, + ) + + +def _env( + controller, + *, + enable_power=True, + budget=10000, + min_endpoint=1, + require_prefill=True, + require_decode=True, +): + config = PlannerConfig.model_construct( + backend="vllm", + namespace="ns", + environment="kubernetes", + enable_power_awareness=enable_power, + total_gpu_power_limit=budget, + min_endpoint=min_endpoint, + ) + return PlannerEnvironmentImpl( + config=config, + controller=controller, + require_prefill=require_prefill, + require_decode=require_decode, + ) + + +def _power_controller(**kwargs): + """Minimal mock accepted by is_power_aware_connector(). + + All three protocol methods must be set explicitly on the instance so + inspect.getattr_static can find them and callable() returns True. + """ + controller = Mock(**kwargs) + controller.get_graph_deployment = Mock() + controller.wait_for_settled_graph_deployment = AsyncMock() + return controller + + +def _controller(prefill_watts=700, decode_watts=1200, *, gpus_per_replica=1): + controller = _power_controller() + controller.get_component_power_configs = Mock( + return_value=( + _cfg("prefill", prefill_watts, gpus_per_replica), + _cfg("decode", decode_watts, gpus_per_replica), + ) + ) + return controller + + +def _refresh_controller(prefill_cfg, decode_cfg): + controller = _power_controller() + controller.get_gpu_counts = Mock(return_value=(1, 1)) + controller.get_component_power_configs = Mock( + return_value=(prefill_cfg, decode_cfg) + ) + controller.get_actual_worker_counts = AsyncMock(return_value=(1, 1, True)) + controller.get_model_name = Mock(return_value="test-model") + return controller + + +def _worker(name, *, comp_type, watts="300", gpus="1", node_count=None): + component = { + "name": name, + "type": comp_type, + "podTemplate": { + "metadata": {"annotations": {POWER_ANNOTATION_KEY: watts}}, + "spec": { + "containers": [ + { + "name": "main", + "resources": {"limits": {"nvidia.com/gpu": gpus}}, + } + ] + }, + }, + } + if node_count is not None: + component["multinode"] = {"nodeCount": node_count} + return component + + +def _dgd(*components): + return {"spec": {"components": list(components)}} + + +def test_is_power_aware_connector_rejects_bare_magic_mock(): + assert is_power_aware_connector(MagicMock()) is False + + +def test_is_power_aware_connector_accepts_valid_connector(): + connector = Mock() + connector.get_graph_deployment = Mock() + connector.get_component_power_configs = Mock() + connector.wait_for_settled_graph_deployment = AsyncMock() + assert is_power_aware_connector(connector) is True + + +def test_is_power_aware_connector_rejects_missing_method(): + connector = Mock() + connector.get_graph_deployment = Mock() + connector.get_component_power_configs = Mock() + # wait_for_settled_graph_deployment absent from __dict__ + assert is_power_aware_connector(connector) is False + + +def test_is_power_aware_connector_rejects_non_callable_attribute(): + connector = Mock() + connector.get_graph_deployment = Mock() + connector.get_component_power_configs = Mock() + connector.wait_for_settled_graph_deployment = "not_a_function" + assert is_power_aware_connector(connector) is False + + +def test_init_populates_power_watts(): + env = _env(_controller(700, 1200)) + env._load_static_power_caps_at_startup() + state = env.deployment_state() + assert state.prefill.power_watts_per_replica == 700 + assert state.decode.power_watts_per_replica == 1200 + + +def test_init_failure_raises_deployment_validation_error(): + controller = _controller() + controller.get_component_power_configs.side_effect = PowerAnnotationInvalidError( + "VllmDecodeWorker", "0" + ) + env = _env(controller) + with pytest.raises(DeploymentValidationError): + env._load_static_power_caps_at_startup() + + +def test_init_infeasible_minimum_footprint_raises(): + env = _env(_controller(700, 1200), budget=1000) + with pytest.raises(DeploymentValidationError, match="Infeasible power budget"): + env._load_static_power_caps_at_startup() + + +def test_awareness_off_is_a_noop(): + controller = _controller() + env = _env(controller, enable_power=False) + env._load_static_power_caps_at_startup() + controller.get_component_power_configs.assert_not_called() + assert env.deployment_state().prefill.power_watts_per_replica is None + + +def test_init_transient_apiexception_fails_closed(): + controller = _controller() + controller.get_component_power_configs.side_effect = ApiException( + status=503, reason="Service Unavailable" + ) + env = _env(controller) + with pytest.raises(DeploymentValidationError): + env._load_static_power_caps_at_startup() + + +def test_init_requires_power_capable_connector(): + controller = Mock(spec=[]) + env = _env(controller) + with pytest.raises(DeploymentValidationError, match="get_component_power_configs"): + env._load_static_power_caps_at_startup() + + +def test_init_required_prefill_config_none_raises(): + """A connector returning None prefill config when prefill is required must fail closed.""" + controller = _power_controller() + controller.get_component_power_configs = Mock( + return_value=(None, _cfg("decode", 300)) + ) + env = _env(controller, require_prefill=True, require_decode=True) + with pytest.raises(DeploymentValidationError, match="prefill"): + env._load_static_power_caps_at_startup() + + +def test_init_required_decode_config_none_raises(): + """A connector returning None decode config when decode is required must fail closed.""" + controller = _power_controller() + controller.get_component_power_configs = Mock( + return_value=(_cfg("prefill", 700), None) + ) + env = _env(controller, require_prefill=True, require_decode=True) + with pytest.raises(DeploymentValidationError, match="decode"): + env._load_static_power_caps_at_startup() + + +@pytest.mark.asyncio +async def test_initialize_power_on_requires_power_aware_connector(): + """Power on + connector missing a PowerAwareConnector method must raise immediately. + + is_power_aware_connector() uses inspect.getattr_static, which bypasses + Mock's __getattr__. A method not explicitly set on the mock instance is + invisible to the check, so omitting wait_for_settled_graph_deployment + triggers DeploymentValidationError rather than silently falling through + to replica-count readiness and skipping observedGeneration / pod-annotation + convergence. + """ + controller = Mock() + controller.async_init = AsyncMock() + controller.validate_deployment = AsyncMock() + controller.get_graph_deployment = Mock() + controller.get_component_power_configs = Mock( + return_value=(_cfg("prefill", 700), _cfg("decode", 300)) + ) + # wait_for_settled_graph_deployment intentionally absent from __dict__: + # is_power_aware_connector(controller) → False. + + env = _env(controller) + fpm = Mock() + fpm.async_init = AsyncMock() + env.fpm_provider = fpm + + with pytest.raises(DeploymentValidationError, match="PowerAwareConnector"): + await env.initialize() + + +def test_restart_adopts_current_cap_not_stale_max(): + fresh_env = _env(_controller(500, 1200)) + fresh_env._load_static_power_caps_at_startup() + state = fresh_env.deployment_state() + assert state.prefill.power_watts_per_replica == 500 + + +@pytest.mark.asyncio +async def test_refresh_does_not_reread_power_annotation(): + """refresh() must not call get_component_power_configs after startup. + + Caps are startup-static. Per Ted's review contract, the runtime tick loop + must not issue a DGD GET to re-resolve or drift-check the annotation — + annotation changes take effect only after a worker rollout plus Planner + restart. + """ + controller = _refresh_controller(_cfg("prefill", 700), _cfg("decode", 1200)) + env = _env(controller) + env._load_static_power_caps_at_startup() + assert env.deployment_state().decode.power_watts_per_replica == 1200 + controller.get_component_power_configs.reset_mock() + + await env.refresh() + + controller.get_component_power_configs.assert_not_called() + assert env.deployment_state().decode.power_watts_per_replica == 1200 + + +def test_call_with_optional_deployment_forwards_when_accepted(): + seen = {} + + def accepts(*, require_prefill=True, deployment=None): + seen["deployment"] = deployment + seen["require_prefill"] = require_prefill + return (1, 1) + + out = PlannerEnvironmentImpl._call_with_optional_deployment( + accepts, deployment={"dgd": True}, require_prefill=False + ) + assert out == (1, 1) + assert seen == {"deployment": {"dgd": True}, "require_prefill": False} + + +def test_call_with_optional_deployment_skips_when_unsupported(): + seen = {} + + def legacy(*, require_prefill=True): + seen["require_prefill"] = require_prefill + return (2, 2) + + out = PlannerEnvironmentImpl._call_with_optional_deployment( + legacy, deployment={"dgd": True}, require_prefill=True + ) + assert out == (2, 2) + assert seen == {"require_prefill": True} + + +def test_call_with_optional_deployment_propagates_inner_typeerror(): + """A TypeError raised inside the connector must not be swallowed/retried.""" + + def broken(*, require_prefill=True, deployment=None): + del require_prefill, deployment + raise TypeError("NoneType is not subscriptable") + + with pytest.raises(TypeError, match="NoneType is not subscriptable"): + PlannerEnvironmentImpl._call_with_optional_deployment( + broken, deployment={"dgd": True}, require_prefill=True + ) + + +@pytest.mark.asyncio +async def test_initialize_caches_caps_from_settled_snapshot_not_lagging_get(): + """Gen-2 lower cap must come from the settled wait snapshot. + + Production race: annotation-only update bumps metadata.generation while + observedGeneration and worker status still describe gen 1. Counts look + stable, so a post-wait DGD GET could return the lower annotation before + Pods roll. initialize() must cache watts from the same snapshot the + settled wait returned — never a later GET of a lagging generation. + """ + lagging = { + "metadata": {"generation": 2}, + "status": {"observedGeneration": 1}, + "spec": {"components": []}, + } + settled = { + "metadata": {"generation": 2}, + "status": {"observedGeneration": 2}, + "spec": {"components": []}, + } + seen = {"power_deployments": [], "gpu_deployments": []} + + def get_power_configs( + *, + require_prefill=True, + require_decode=True, + deployment=None, + prefill_component_name=None, + decode_component_name=None, + ): + del ( + require_prefill, + require_decode, + prefill_component_name, + decode_component_name, + ) + seen["power_deployments"].append(deployment) + return (_cfg("prefill", 300), _cfg("decode", 300)) + + def get_gpu_counts(*, require_prefill=True, require_decode=True, deployment=None): + del require_prefill, require_decode + seen["gpu_deployments"].append(deployment) + return (1, 1) + + controller = Mock() + controller.async_init = AsyncMock() + controller.validate_deployment = AsyncMock() + controller.wait_for_settled_graph_deployment = AsyncMock(return_value=settled) + controller.get_graph_deployment = Mock(return_value=lagging) + controller.get_gpu_counts = get_gpu_counts + controller.get_actual_worker_counts = AsyncMock(return_value=(1, 1, True)) + controller.get_model_name = Mock(return_value="test-model") + controller.get_component_power_configs = get_power_configs + + env = _env(controller, budget=10000) + fpm = Mock() + fpm.async_init = AsyncMock() + env.fpm_provider = fpm + + await env.initialize() + + controller.wait_for_settled_graph_deployment.assert_awaited_once_with( + include_planner=False, + require_prefill=True, + require_decode=True, + prefill_component_name="VllmPrefillWorker", + decode_component_name="VllmDecodeWorker", + ) + assert seen["power_deployments"][0] is settled + assert seen["gpu_deployments"][0] is settled + assert env.deployment_state().decode.power_watts_per_replica == 300 + + +@pytest.mark.asyncio +async def test_initialize_power_disabled_skips_settled_backing_wait(): + """Power-off init must not take the pod-annotation settled path. + + Every real Kubernetes connector exposes wait_for_settled_graph_deployment; + using it when enable_power_awareness=False would list Pods for annotation + verification and can 403 or time out for custom service accounts that only + had the pre-power RBAC surface. + """ + backing_lookups = [] + + async def wait_settled(*, include_planner=True): + del include_planner + backing_lookups.append("settled") + raise AssertionError("settled/backing wait must not run when power is off") + + controller = Mock() + controller.async_init = AsyncMock() + controller.validate_deployment = AsyncMock() + controller.wait_for_settled_graph_deployment = wait_settled + controller.wait_for_deployment_ready = AsyncMock() + controller.get_gpu_counts = Mock(return_value=(1, 1)) + controller.get_actual_worker_counts = AsyncMock(return_value=(1, 1, True)) + controller.get_model_name = Mock(return_value="test-model") + controller.get_component_power_configs = Mock( + side_effect=AssertionError("power configs must not be resolved when off") + ) + controller.get_graph_deployment = Mock( + side_effect=AssertionError("shared DGD GET is power-gated") + ) + + env = _env(controller, enable_power=False) + fpm = Mock() + fpm.async_init = AsyncMock() + env.fpm_provider = fpm + + await env.initialize() + + controller.wait_for_deployment_ready.assert_awaited_once_with(include_planner=False) + assert backing_lookups == [] + assert env.deployment_state().prefill.power_watts_per_replica is None diff --git a/deploy/helm/charts/platform/components/operator/templates/planner.yaml b/deploy/helm/charts/platform/components/operator/templates/planner.yaml index 72848c9be69d..d2c123462ded 100644 --- a/deploy/helm/charts/platform/components/operator/templates/planner.yaml +++ b/deploy/helm/charts/platform/components/operator/templates/planner.yaml @@ -37,7 +37,7 @@ metadata: {{- include "dynamo-operator.labels" . | nindent 4 }} rules: - apiGroups: ["nvidia.com"] - resources: ["dynamocomponentdeployments", "dynamographdeployments"] + resources: ["dynamographdeployments"] verbs: ["get", "list", "create", "update", "patch"] - apiGroups: ["nvidia.com"] resources: ["dynamographdeploymentscalingadapters/scale"] @@ -48,6 +48,16 @@ rules: - apiGroups: ["nvidia.com"] resources: ["dynamoworkermetadatas"] verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] +{{- if .Values.planner.powerAwareness.enabled }} +# Pods (list only): startup settlement reads non-terminal pod annotations to +# verify the DGD-owned power cap has propagated before caching it. No write +# surface: caps are authored on the DGD podTemplate and enforced by the Power +# Agent; the Planner never patches Pods. +# Requires planner.powerAwareness.enabled=true in Helm values. +- apiGroups: [""] + resources: ["pods"] + verbs: ["list"] +{{- end }} --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding @@ -65,7 +75,10 @@ roleRef: name: planner-role apiGroup: rbac.authorization.k8s.io {{- else }} -# Cluster-wide mode: ClusterRole for planner +# Cluster-wide mode: ClusterRole for planner. +# Even though this is a ClusterRole, the operator binds it via a namespace-scoped +# RoleBinding (internal/rbac/manager.go EnsureServiceAccountWithRBAC), so all +# permissions — including pods/list — are effective only in the DGD's namespace. --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole @@ -75,7 +88,7 @@ metadata: {{- include "dynamo-operator.labels" . | nindent 4 }} rules: - apiGroups: ["nvidia.com"] - resources: ["dynamocomponentdeployments", "dynamographdeployments"] + resources: ["dynamographdeployments"] verbs: ["get", "list", "create", "update", "patch"] - apiGroups: ["nvidia.com"] resources: ["dynamographdeploymentscalingadapters/scale"] @@ -86,4 +99,14 @@ rules: - apiGroups: ["nvidia.com"] resources: ["dynamoworkermetadatas"] verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] +{{- if .Values.planner.powerAwareness.enabled }} +# Pods (list only): startup settlement reads non-terminal pod annotations to +# verify the DGD-owned power cap has propagated before caching it. No write +# surface: caps are authored on the DGD podTemplate and enforced by the Power +# Agent; the Planner never patches Pods. +# Requires planner.powerAwareness.enabled=true in Helm values. +- apiGroups: [""] + resources: ["pods"] + verbs: ["list"] +{{- end }} {{- end }} diff --git a/deploy/helm/charts/platform/components/operator/values.yaml b/deploy/helm/charts/platform/components/operator/values.yaml index d782b5c0064f..271332526d44 100644 --- a/deploy/helm/charts/platform/components/operator/values.yaml +++ b/deploy/helm/charts/platform/components/operator/values.yaml @@ -96,6 +96,20 @@ controllerManager: serviceAccount: annotations: {} +planner: + powerAwareness: + # -- Grant the Planner's ServiceAccount pods/list in the DGD namespace. + # Required for power-annotation settlement checks during startup when + # enable_power_awareness=true. Leaving this false avoids granting an + # unnecessary namespace-level permission to power-disabled Planners. + # Note: this is an installation-wide capability flag; per-instance + # power awareness is still controlled by enable_power_awareness in the + # Planner config. In clusters where multiple Planner instances share + # the standard ServiceAccount, enabling this flag grants pods/list to + # all of them. A separate ServiceAccount per Planner is needed for + # truly per-instance least privilege. + enabled: false + dynamo: components: serviceAccount: diff --git a/deploy/helm/charts/platform/tests/planner_rbac_test.yaml b/deploy/helm/charts/platform/tests/planner_rbac_test.yaml new file mode 100644 index 000000000000..44be0f01e464 --- /dev/null +++ b/deploy/helm/charts/platform/tests/planner_rbac_test.yaml @@ -0,0 +1,72 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +suite: planner RBAC — powerAwareness.enabled gate +templates: + - charts/dynamo-operator/templates/planner.yaml + +tests: + # ── cluster-wide mode (default) ────────────────────────────────────────────── + + - it: omits pods/list from ClusterRole when powerAwareness is disabled (default) + asserts: + - notContains: + path: rules + content: + apiGroups: + - "" + resources: + - pods + verbs: + - list + documentIndex: 0 + + - it: includes pods/list in ClusterRole when powerAwareness is enabled + set: + dynamo-operator.planner.powerAwareness.enabled: true + asserts: + - contains: + path: rules + content: + apiGroups: + - "" + resources: + - pods + verbs: + - list + documentIndex: 0 + + # ── namespace-restricted mode ───────────────────────────────────────────────── + + - it: omits pods/list from Role when powerAwareness is disabled in namespace-restricted mode + set: + dynamo-operator.namespaceRestriction.enabled: true + dynamo-operator.upgradeCRD: false + asserts: + - notContains: + path: rules + content: + apiGroups: + - "" + resources: + - pods + verbs: + - list + documentIndex: 1 + + - it: includes pods/list in Role when powerAwareness is enabled in namespace-restricted mode + set: + dynamo-operator.namespaceRestriction.enabled: true + dynamo-operator.upgradeCRD: false + dynamo-operator.planner.powerAwareness.enabled: true + asserts: + - contains: + path: rules + content: + apiGroups: + - "" + resources: + - pods + verbs: + - list + documentIndex: 1 diff --git a/deploy/helm/charts/power-agent/values.yaml b/deploy/helm/charts/power-agent/values.yaml index c75661feef63..2db960ead426 100644 --- a/deploy/helm/charts/power-agent/values.yaml +++ b/deploy/helm/charts/power-agent/values.yaml @@ -204,17 +204,17 @@ daemonset: enabled: true # Conservative default by design: when a Power Agent restarts, the GPUs - # on its node have no power-cap enforcement until it comes back. If the - # planner just emitted new annotations expecting them to apply, that - # propagation stalls. `maxUnavailable: 1` ensures only one node's worth - # of GPUs ever loses enforcement at a time. + # on its node have no power-cap enforcement until it comes back. If worker + # pods on that node carry DGD-owned per-GPU cap annotations (applied by the + # operator), those caps are not enforced during the gap. `maxUnavailable: 1` + # ensures only one node's worth of GPUs ever loses enforcement at a time. # # Override for large fleets: on clusters with hundreds of GPU nodes, # a 1-at-a-time rollout (~30s/pod × N nodes) gets slow. Operators can # opt into faster rollouts with: # --set daemonset.updateStrategy.rollingUpdate.maxUnavailable=10% # (or any percentage / integer). The trade-off is more concurrent - # enforcement gaps during a rollout; safe when the planner's reconcile + # enforcement gaps during a rollout; safe when the agent's reconcile # interval (15s) is much shorter than the rollout duration anyway. updateStrategy: type: RollingUpdate diff --git a/deploy/operator/internal/consts/consts.go b/deploy/operator/internal/consts/consts.go index 39b8f6ee8c0c..22e2bf814606 100644 --- a/deploy/operator/internal/consts/consts.go +++ b/deploy/operator/internal/consts/consts.go @@ -56,6 +56,7 @@ const ( KubeAnnotationDisableImagePullSecretDiscovery = "nvidia.com/disable-image-pull-secret-discovery" KubeAnnotationDynamoDiscoveryBackend = "nvidia.com/dynamo-discovery-backend" KubeAnnotationDynamoKubeDiscoveryMode = "nvidia.com/dynamo-kube-discovery-mode" + KubeAnnotationGPUPowerLimit = "dynamo.nvidia.com/gpu-power-limit" KubeLabelDynamoGraphDeploymentName = "nvidia.com/dynamo-graph-deployment-name" KubeLabelDynamoComponent = "nvidia.com/dynamo-component" diff --git a/deploy/operator/internal/webhook/validation/dynamographdeployment.go b/deploy/operator/internal/webhook/validation/dynamographdeployment.go index eaa05efcde62..ff04ede0d7fd 100644 --- a/deploy/operator/internal/webhook/validation/dynamographdeployment.go +++ b/deploy/operator/internal/webhook/validation/dynamographdeployment.go @@ -32,6 +32,7 @@ import ( grovev1alpha1 "github.com/ai-dynamo/grove/operator/api/core/v1alpha1" authenticationv1 "k8s.io/api/authentication/v1" k8serrors "k8s.io/apimachinery/pkg/api/errors" + apivalidation "k8s.io/apimachinery/pkg/api/validation" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" k8svalidation "k8s.io/apimachinery/pkg/util/validation" "k8s.io/apimachinery/pkg/util/validation/field" @@ -266,6 +267,19 @@ func (v *dynamoGraphDeploymentValidation) validateDynamoGraphDeploymentSpec( } } + // Phase-1 power accounting reads scalar GPU resources and cannot account for DRA devices. + if _, hasPowerLimit := dgdPowerLimit(component); hasPowerLimit { + if draPath := dgdDRAPath(component, componentPath); draPath != nil { + allErrs = append(allErrs, field.Forbidden( + draPath, + fmt.Sprintf( + "cannot be combined with annotation %q: power-aware planning does not support DRA-backed device allocation", + consts.KubeAnnotationGPUPowerLimit, + ), + )) + } + } + allErrs = append(allErrs, v.validateDynamoComponentDeploymentSharedSpec( component, componentPath, @@ -561,6 +575,11 @@ func (v *dynamoGraphDeploymentValidation) validateDynamoGraphDeploymentSpecUpdat canModifyReplicas, nvidiacomv1beta1.DynamoGraphDeploymentGVK.GroupKind(), )...) + allErrs = append(allErrs, v.validateDynamoGraphDeploymentSharedSpecUpdate( + newComponent, + oldComponent, + componentsPath.Index(i), + )...) } if newSpec.BackendFramework != oldSpec.BackendFramework { @@ -604,6 +623,53 @@ func (v *dynamoGraphDeploymentValidation) validateDynamoGraphDeploymentSpecUpdat return allErrs } +// validateDynamoGraphDeploymentSharedSpecUpdate validates DGD-specific component fields on update. +// newComponent, oldComponent, and fldPath must not be nil. +func (v *dynamoGraphDeploymentValidation) validateDynamoGraphDeploymentSharedSpecUpdate( + newComponent *nvidiacomv1beta1.DynamoComponentDeploymentSharedSpec, + oldComponent *nvidiacomv1beta1.DynamoComponentDeploymentSharedSpec, + fldPath *field.Path, +) field.ErrorList { + allErrs := field.ErrorList{} + newPowerLimit, newHasPowerLimit := dgdPowerLimit(newComponent) + oldPowerLimit, oldHasPowerLimit := dgdPowerLimit(oldComponent) + + // Reject transitions into, out of, or within the power-annotation contract. + if newHasPowerLimit != oldHasPowerLimit || + (newHasPowerLimit && newPowerLimit != oldPowerLimit) { + var invalidValue any + if newHasPowerLimit { + invalidValue = newPowerLimit + } + allErrs = append(allErrs, field.Invalid( + fldPath.Child("podTemplate", "metadata", "annotations").Key(consts.KubeAnnotationGPUPowerLimit), + invalidValue, + apivalidation.FieldImmutableErrorMsg, + )) + } + + if oldHasPowerLimit { + // Keep the Planner's remaining cached per-replica power inputs stable. + newNumberOfGPUs := effectiveNumberOfGPUsV1Beta1(newComponent, fldPath) + oldNumberOfGPUs := effectiveNumberOfGPUsV1Beta1(oldComponent, fldPath) + if !newNumberOfGPUs.equal(oldNumberOfGPUs) { + allErrs = append(allErrs, field.Invalid( + newNumberOfGPUs.path, + newNumberOfGPUs.invalidValue(), + apivalidation.FieldImmutableErrorMsg, + )) + } + if newComponent.GetNumberOfNodes() != oldComponent.GetNumberOfNodes() { + allErrs = append(allErrs, field.Invalid( + fldPath.Child("multinode", "nodeCount"), + newComponent.GetNumberOfNodes(), + apivalidation.FieldImmutableErrorMsg, + )) + } + } + return allErrs +} + // validateSpecTopologyConstraintUpdate validates a topology constraint update. // newConstraint and fldPath must not be nil; oldConstraint may be nil for an addition. func (v *dynamoGraphDeploymentValidation) validateSpecTopologyConstraintUpdate( diff --git a/deploy/operator/internal/webhook/validation/dynamographdeployment_helpers.go b/deploy/operator/internal/webhook/validation/dynamographdeployment_helpers.go index bcdf39d195fd..0e9111a190fe 100644 --- a/deploy/operator/internal/webhook/validation/dynamographdeployment_helpers.go +++ b/deploy/operator/internal/webhook/validation/dynamographdeployment_helpers.go @@ -28,6 +28,7 @@ import ( "github.com/ai-dynamo/dynamo/deploy/operator/internal/consts" "github.com/ai-dynamo/dynamo/deploy/operator/internal/dynamo" grovev1alpha1 "github.com/ai-dynamo/grove/operator/api/core/v1alpha1" + corev1 "k8s.io/api/core/v1" k8serrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/validation/field" @@ -187,6 +188,94 @@ func componentsByName( return byName } +func dgdPowerLimit( + component *nvidiacomv1beta1.DynamoComponentDeploymentSharedSpec, +) (string, bool) { + if component.PodTemplate == nil { + return "", false + } + value, exists := component.PodTemplate.Annotations[consts.KubeAnnotationGPUPowerLimit] + return value, exists +} + +func dgdDRAPath( + component *nvidiacomv1beta1.DynamoComponentDeploymentSharedSpec, + fldPath *field.Path, +) *field.Path { + if gpuMemoryServiceFor(component) != nil { + return fldPath.Child("experimental", "gpuMemoryService") + } + if component.PodTemplate == nil { + return nil + } + + // The claim's DeviceClass is external to the DGD, so fail closed for every consumed claim. + containersPath := fldPath.Child("podTemplate", "spec", "containers") + for i := range component.PodTemplate.Spec.Containers { + if len(component.PodTemplate.Spec.Containers[i].Resources.Claims) != 0 { + return containersPath.Index(i).Child("resources", "claims") + } + } + return nil +} + +// effectiveNumberOfGPUs captures the effective scalar GPU count and its source field. +type effectiveNumberOfGPUs struct { + value string + present bool + path *field.Path +} + +func (input effectiveNumberOfGPUs) equal(other effectiveNumberOfGPUs) bool { + return input.present == other.present && (!input.present || input.value == other.value) +} + +func (input effectiveNumberOfGPUs) invalidValue() any { + if !input.present { + return nil + } + return input.value +} + +// effectiveNumberOfGPUsV1Beta1 returns the main container's scalar GPU count, preferring limits to requests. +func effectiveNumberOfGPUsV1Beta1( + component *nvidiacomv1beta1.DynamoComponentDeploymentSharedSpec, + fldPath *field.Path, +) effectiveNumberOfGPUs { + containersPath := fldPath.Child("podTemplate", "spec", "containers") + if component.PodTemplate == nil { + return effectiveNumberOfGPUs{path: containersPath} + } + + // Phase-1 power admission rejects DRA-backed components, matching the Planner's scalar-only + // GPU count. Read the limit before the request, as the Planner does. + resourceName := corev1.ResourceName(consts.KubeResourceGPUNvidia) + for i := range component.PodTemplate.Spec.Containers { + container := &component.PodTemplate.Spec.Containers[i] + if container.Name != consts.MainContainerName { + continue + } + + resourcesPath := containersPath.Index(i).Child("resources") + if quantity, exists := container.Resources.Limits[resourceName]; exists { + return effectiveNumberOfGPUs{ + value: quantity.String(), + present: true, + path: resourcesPath.Child("limits").Key(consts.KubeResourceGPUNvidia), + } + } + if quantity, exists := container.Resources.Requests[resourceName]; exists { + return effectiveNumberOfGPUs{ + value: quantity.String(), + present: true, + path: resourcesPath.Child("requests").Key(consts.KubeResourceGPUNvidia), + } + } + return effectiveNumberOfGPUs{path: resourcesPath} + } + return effectiveNumberOfGPUs{path: containersPath} +} + func sortedComponentNames( components map[string]*nvidiacomv1beta1.DynamoComponentDeploymentSharedSpec, ) []string { diff --git a/deploy/operator/internal/webhook/validation/dynamographdeployment_validation_envtest_test.go b/deploy/operator/internal/webhook/validation/dynamographdeployment_validation_envtest_test.go index 60706ea233b9..d2835ebe1e48 100644 --- a/deploy/operator/internal/webhook/validation/dynamographdeployment_validation_envtest_test.go +++ b/deploy/operator/internal/webhook/validation/dynamographdeployment_validation_envtest_test.go @@ -29,6 +29,7 @@ import ( "github.com/ai-dynamo/dynamo/deploy/operator/internal/features" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" + apivalidation "k8s.io/apimachinery/pkg/api/validation" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" k8sptr "k8s.io/utils/ptr" @@ -507,6 +508,242 @@ func TestDynamoGraphDeploymentValidator_Validate(t *testing.T) { }), deployment: betaDGDForAdmission(nil), }, + { + name: "v1beta1 power tuple is accepted on create", + deployment: betaDGDForAdmission(func(dgd *nvidiacomv1beta1.DynamoGraphDeployment) { + setBetaWorkerPowerInputs(dgd, "300", "1", 2) + }), + }, + { + name: "v1beta1 power annotation with intra-pod GMS DRA is rejected", + deployment: betaDGDForAdmission(func(dgd *nvidiacomv1beta1.DynamoGraphDeployment) { + enableBetaIntraPodGMS(betaWorkerComponent(dgd)) + setBetaWorkerPowerInputs(dgd, "300", "1", 2) + }), + wantWebhookErrs: []string{ + `spec.components[1].experimental.gpuMemoryService: Forbidden: cannot be combined with annotation "dynamo.nvidia.com/gpu-power-limit": power-aware planning does not support DRA-backed device allocation`, + }, + }, + { + name: "v1beta1 power annotation with inter-pod GMS DRA is rejected", + deployment: betaDGDForAdmission(func(dgd *nvidiacomv1beta1.DynamoGraphDeployment) { + enableBetaInterPodGMS(betaWorkerComponent(dgd)) + setBetaWorkerPowerInputs(dgd, "300", "1", 2) + }), + wantWebhookErrs: []string{ + `spec.components[1].experimental.gpuMemoryService: Forbidden: cannot be combined with annotation "dynamo.nvidia.com/gpu-power-limit": power-aware planning does not support DRA-backed device allocation`, + }, + }, + { + name: "v1beta1 power annotation with DRA claim template is rejected", + deployment: betaDGDForAdmission(func(dgd *nvidiacomv1beta1.DynamoGraphDeployment) { + setBetaWorkerPowerInputs(dgd, "300", "1", 2) + setBetaWorkerResourceClaim(dgd, corev1.PodResourceClaim{ + Name: "gpu", + ResourceClaimTemplateName: k8sptr.To("gpu-template"), + }) + }), + wantWebhookErrs: []string{ + `spec.components[1].podTemplate.spec.containers[0].resources.claims: Forbidden: cannot be combined with annotation "dynamo.nvidia.com/gpu-power-limit": power-aware planning does not support DRA-backed device allocation`, + }, + }, + { + name: "v1beta1 power annotation with direct DRA claim is rejected", + deployment: betaDGDForAdmission(func(dgd *nvidiacomv1beta1.DynamoGraphDeployment) { + setBetaWorkerPowerInputs(dgd, "300", "1", 2) + setBetaWorkerResourceClaim(dgd, corev1.PodResourceClaim{ + Name: "gpu", + ResourceClaimName: k8sptr.To("gpu-claim"), + }) + }), + wantWebhookErrs: []string{ + `spec.components[1].podTemplate.spec.containers[0].resources.claims: Forbidden: cannot be combined with annotation "dynamo.nvidia.com/gpu-power-limit": power-aware planning does not support DRA-backed device allocation`, + }, + }, + { + name: "v1beta1 DRA claim without power annotation remains accepted", + deployment: betaDGDForAdmission(func(dgd *nvidiacomv1beta1.DynamoGraphDeployment) { + setBetaWorkerResourceClaim(dgd, corev1.PodResourceClaim{ + Name: "device", + ResourceClaimTemplateName: k8sptr.To("device-template"), + }) + }), + }, + { + name: "v1beta1 power annotation cannot be added to a DRA component", + oldDeployment: betaDGDForAdmission(func(dgd *nvidiacomv1beta1.DynamoGraphDeployment) { + setBetaWorkerResourceClaim(dgd, corev1.PodResourceClaim{ + Name: "device", + ResourceClaimTemplateName: k8sptr.To("device-template"), + }) + }), + deployment: betaDGDForAdmission(func(dgd *nvidiacomv1beta1.DynamoGraphDeployment) { + setBetaWorkerPowerInputs(dgd, "300", "1", 2) + setBetaWorkerResourceClaim(dgd, corev1.PodResourceClaim{ + Name: "device", + ResourceClaimTemplateName: k8sptr.To("device-template"), + }) + }), + wantWebhookErrs: []string{ + `spec.components[1].podTemplate.spec.containers[0].resources.claims: Forbidden: cannot be combined with annotation "dynamo.nvidia.com/gpu-power-limit": power-aware planning does not support DRA-backed device allocation`, + }, + }, + { + name: "v1beta1 power annotation change is rejected by the webhook", + oldDeployment: betaDGDForAdmission(func(dgd *nvidiacomv1beta1.DynamoGraphDeployment) { + setBetaWorkerPowerInputs(dgd, "300", "1", 2) + }), + deployment: betaDGDForAdmission(func(dgd *nvidiacomv1beta1.DynamoGraphDeployment) { + setBetaWorkerPowerInputs(dgd, "350", "1", 2) + }), + wantWebhookErrs: []string{ + `spec.components[1].podTemplate.metadata.annotations[dynamo.nvidia.com/gpu-power-limit]: Invalid value: "350": ` + apivalidation.FieldImmutableErrorMsg, + }, + }, + { + name: "v1beta1 power annotation addition is rejected by the webhook", + oldDeployment: betaDGDForAdmission(func(dgd *nvidiacomv1beta1.DynamoGraphDeployment) { + setBetaWorkerPowerInputs(dgd, "300", "1", 2) + delete(betaWorkerComponent(dgd).PodTemplate.Annotations, consts.KubeAnnotationGPUPowerLimit) + }), + deployment: betaDGDForAdmission(func(dgd *nvidiacomv1beta1.DynamoGraphDeployment) { + setBetaWorkerPowerInputs(dgd, "300", "1", 2) + }), + wantWebhookErrs: []string{ + `spec.components[1].podTemplate.metadata.annotations[dynamo.nvidia.com/gpu-power-limit]: Invalid value: "300": ` + apivalidation.FieldImmutableErrorMsg, + }, + }, + { + name: "v1beta1 power annotation removal is rejected by the webhook", + oldDeployment: betaDGDForAdmission(func(dgd *nvidiacomv1beta1.DynamoGraphDeployment) { + setBetaWorkerPowerInputs(dgd, "300", "1", 2) + }), + deployment: betaDGDForAdmission(func(dgd *nvidiacomv1beta1.DynamoGraphDeployment) { + setBetaWorkerPowerInputs(dgd, "300", "1", 2) + delete(betaWorkerComponent(dgd).PodTemplate.Annotations, consts.KubeAnnotationGPUPowerLimit) + }), + wantWebhookErrs: []string{ + "spec.components[1].podTemplate.metadata.annotations[dynamo.nvidia.com/gpu-power-limit]: Invalid value: null: " + apivalidation.FieldImmutableErrorMsg, + }, + }, + { + name: "v1beta1 effective GPU change is rejected by the webhook", + oldDeployment: betaDGDForAdmission(func(dgd *nvidiacomv1beta1.DynamoGraphDeployment) { + setBetaWorkerPowerInputs(dgd, "300", "1", 2) + }), + deployment: betaDGDForAdmission(func(dgd *nvidiacomv1beta1.DynamoGraphDeployment) { + setBetaWorkerPowerInputs(dgd, "300", "2", 2) + }), + wantWebhookErrs: []string{ + `spec.components[1].podTemplate.spec.containers[0].resources.limits[nvidia.com/gpu]: Invalid value: "2": ` + apivalidation.FieldImmutableErrorMsg, + }, + }, + { + name: "v1beta1 shadow request change is allowed when GPU limit is unchanged", + oldDeployment: betaDGDForAdmission(func(dgd *nvidiacomv1beta1.DynamoGraphDeployment) { + setBetaWorkerPowerInputs(dgd, "300", "1", 2) + }), + deployment: betaDGDForAdmission(func(dgd *nvidiacomv1beta1.DynamoGraphDeployment) { + setBetaWorkerPowerInputs(dgd, "300", "1", 2) + betaWorkerComponent(dgd).PodTemplate.Spec.Containers[0].Resources.Requests = corev1.ResourceList{ + corev1.ResourceName(consts.KubeResourceGPUNvidia): resource.MustParse("8"), + } + }), + }, + { + name: "v1beta1 power node count change is rejected by the webhook", + oldDeployment: betaDGDForAdmission(func(dgd *nvidiacomv1beta1.DynamoGraphDeployment) { + setBetaWorkerPowerInputs(dgd, "300", "1", 2) + }), + deployment: betaDGDForAdmission(func(dgd *nvidiacomv1beta1.DynamoGraphDeployment) { + setBetaWorkerPowerInputs(dgd, "300", "1", 3) + }), + wantWebhookErrs: []string{ + "spec.components[1].multinode.nodeCount: Invalid value: 3: " + apivalidation.FieldImmutableErrorMsg, + }, + }, + { + name: "v1beta1 unrelated power component update reaches webhook", + oldDeployment: betaDGDForAdmission(func(dgd *nvidiacomv1beta1.DynamoGraphDeployment) { + setBetaWorkerPowerInputs(dgd, "300", "1", 2) + }), + deployment: betaDGDForAdmission(func(dgd *nvidiacomv1beta1.DynamoGraphDeployment) { + setBetaWorkerPowerInputs(dgd, "300", "1", 2) + worker := betaWorkerComponent(dgd) + worker.Replicas = k8sptr.To(int32(2)) + worker.PodTemplate.Spec.Containers[0].Image = "registry.example/runtime:1.2.0" + }), + }, + { + name: "v1beta1 unannotated component GPU change remains allowed", + oldDeployment: betaDGDForAdmission(nil), + deployment: betaDGDForAdmission(func(dgd *nvidiacomv1beta1.DynamoGraphDeployment) { + betaWorkerComponent(dgd).PodTemplate.Spec.Containers[0].Resources.Limits = corev1.ResourceList{ + corev1.ResourceName(consts.KubeResourceGPUNvidia): resource.MustParse("2"), + } + }), + }, + { + name: "v1alpha1 power annotation change is rejected after conversion by the webhook", + oldDeployment: alphaDGDForAdmission(func(dgd *nvidiacomv1alpha1.DynamoGraphDeployment) { + setAlphaWorkerPowerInputs(dgd, "300", "1", 2) + }), + deployment: alphaDGDForAdmission(func(dgd *nvidiacomv1alpha1.DynamoGraphDeployment) { + setAlphaWorkerPowerInputs(dgd, "350", "1", 2) + }), + wantWebhookErrs: []string{ + `spec.components[0].podTemplate.metadata.annotations[dynamo.nvidia.com/gpu-power-limit]: Invalid value: "350": ` + apivalidation.FieldImmutableErrorMsg, + }, + }, + { + name: "v1alpha1 power annotation with GMS DRA is rejected after conversion", + deployment: alphaDGDForAdmission(func(dgd *nvidiacomv1alpha1.DynamoGraphDeployment) { + setAlphaWorkerPowerInputs(dgd, "300", "1", 2) + dgd.Spec.Services[dgdAdmissionWorkerName].GPUMemoryService = &nvidiacomv1alpha1.GPUMemoryServiceSpec{ + Enabled: true, + Mode: nvidiacomv1alpha1.GMSModeIntraPod, + } + }), + wantWebhookErrs: []string{ + `spec.components[0].experimental.gpuMemoryService: Forbidden: cannot be combined with annotation "dynamo.nvidia.com/gpu-power-limit": power-aware planning does not support DRA-backed device allocation`, + }, + }, + { + name: "v1alpha1 effective GPU change is rejected after conversion by the webhook", + oldDeployment: alphaDGDForAdmission(func(dgd *nvidiacomv1alpha1.DynamoGraphDeployment) { + setAlphaWorkerPowerInputs(dgd, "300", "1", 2) + }), + deployment: alphaDGDForAdmission(func(dgd *nvidiacomv1alpha1.DynamoGraphDeployment) { + setAlphaWorkerPowerInputs(dgd, "300", "2", 2) + }), + wantWebhookErrs: []string{ + `spec.components[0].podTemplate.spec.containers[0].resources.limits[nvidia.com/gpu]: Invalid value: "2": ` + apivalidation.FieldImmutableErrorMsg, + }, + }, + { + name: "v1alpha1 power node count change is rejected after conversion by the webhook", + oldDeployment: alphaDGDForAdmission(func(dgd *nvidiacomv1alpha1.DynamoGraphDeployment) { + setAlphaWorkerPowerInputs(dgd, "300", "1", 2) + }), + deployment: alphaDGDForAdmission(func(dgd *nvidiacomv1alpha1.DynamoGraphDeployment) { + setAlphaWorkerPowerInputs(dgd, "300", "1", 3) + }), + wantWebhookErrs: []string{ + "spec.components[0].multinode.nodeCount: Invalid value: 3: " + apivalidation.FieldImmutableErrorMsg, + }, + }, + { + name: "v1alpha1 unrelated power service update reaches webhook", + oldDeployment: alphaDGDForAdmission(func(dgd *nvidiacomv1alpha1.DynamoGraphDeployment) { + setAlphaWorkerPowerInputs(dgd, "300", "1", 2) + }), + deployment: alphaDGDForAdmission(func(dgd *nvidiacomv1alpha1.DynamoGraphDeployment) { + setAlphaWorkerPowerInputs(dgd, "300", "1", 2) + worker := dgd.Spec.Services[dgdAdmissionWorkerName] + worker.Replicas = k8sptr.To(int32(2)) + worker.ExtraPodSpec.MainContainer.Image = "registry.example/runtime:1.2.0" + }), + }, // Checkpoint rules. { @@ -2012,6 +2249,47 @@ func betaWorkerComponent( return dgd.GetComponentByName("worker") } +func setBetaWorkerPowerInputs( + dgd *nvidiacomv1beta1.DynamoGraphDeployment, + watts string, + gpus string, + nodeCount int32, +) { + worker := betaWorkerComponent(dgd) + worker.PodTemplate.Annotations = map[string]string{ + consts.KubeAnnotationGPUPowerLimit: watts, + } + worker.PodTemplate.Spec.Containers[0].Resources.Limits = corev1.ResourceList{ + corev1.ResourceName(consts.KubeResourceGPUNvidia): resource.MustParse(gpus), + } + worker.Multinode = &nvidiacomv1beta1.MultinodeSpec{NodeCount: nodeCount} +} + +func setBetaWorkerResourceClaim( + dgd *nvidiacomv1beta1.DynamoGraphDeployment, + podClaim corev1.PodResourceClaim, +) { + worker := betaWorkerComponent(dgd) + worker.PodTemplate.Spec.Containers[0].Resources.Claims = []corev1.ResourceClaim{{Name: podClaim.Name}} + worker.PodTemplate.Spec.ResourceClaims = []corev1.PodResourceClaim{podClaim} +} + +func setAlphaWorkerPowerInputs( + dgd *nvidiacomv1alpha1.DynamoGraphDeployment, + watts string, + gpus string, + nodeCount int32, +) { + worker := dgd.Spec.Services[dgdAdmissionWorkerName] + worker.ExtraPodMetadata = &nvidiacomv1alpha1.ExtraPodMetadata{ + Annotations: map[string]string{consts.KubeAnnotationGPUPowerLimit: watts}, + } + worker.Resources = &nvidiacomv1alpha1.Resources{ + Limits: &nvidiacomv1alpha1.ResourceItem{GPU: gpus}, + } + worker.Multinode = &nvidiacomv1alpha1.MultinodeSpec{NodeCount: nodeCount} +} + func enableBetaContainerDiscovery(dgd *nvidiacomv1beta1.DynamoGraphDeployment) { dgd.Annotations = map[string]string{consts.KubeAnnotationDynamoKubeDiscoveryMode: "container"} } diff --git a/deploy/power-agent/power_agent.py b/deploy/power-agent/power_agent.py index 8cd9fe10321b..d2b6341f201e 100755 --- a/deploy/power-agent/power_agent.py +++ b/deploy/power-agent/power_agent.py @@ -14,12 +14,14 @@ (nvmlDeviceSetPowerManagementLimit) or DCGM (dcgmConfigSet). Scope is opt-in: the agent only ever caps a GPU whose pod carries the -dynamo.nvidia.com/gpu-power-limit annotation (set by the planner on -prefill/decode worker pods). A GPU running only unannotated pods — a -non-Dynamo workload, or a Dynamo worker not yet annotated — that the agent -never capped is left at its hardware default and untouched. If the agent had -previously capped that GPU and the opted-in pod is now gone (a non-managed -workload reuses it, or the planner removed the annotation), the cap is +dynamo.nvidia.com/gpu-power-limit annotation. That annotation is DGD-owned — +authored on the worker component's podTemplate (by a human or the profiler) +and stamped onto each worker pod by the operator at create time; the agent +reads the live pod annotation and never depends on who wrote it. A GPU running +only unannotated pods — a non-Dynamo workload, or a Dynamo worker not yet +annotated — that the agent never capped is left at its hardware default and +untouched. If the agent had previously capped that GPU and the opted-in pod is +now gone (a non-managed workload reuses it, or the pod was deleted), the cap is released back to default so it does not strand on the new tenant. See ``_build_uid_to_annotation`` and ``_release_managed_gpu``. @@ -613,12 +615,12 @@ def _release_managed_gpu( Runtime counterpart to ``_shutdown_cleanup`` / ``_restore_orphaned_gpus_on_startup``. Invoked from steady-state reconcile when a GPU we previously capped is now running only unannotated / non-K8s processes — i.e. the opted-in pod is gone - and a non-managed workload owns the GPU (or the planner removed the - annotation to release it). Without this, the agent's last cap would strand - on the reused GPU until the next agent shutdown (startup orphan recovery - skips busy GPUs), silently throttling the new tenant. This implements the - "planner owns cap lifecycle via annotation removal/update" contract at - runtime. + and a non-managed workload owns the GPU (or the annotated pod was deleted, + releasing the cap). Without this, the agent's last cap would strand on the + reused GPU until the next agent shutdown (startup orphan recovery skips busy + GPUs), silently throttling the new tenant. This implements the "cap + lifecycle follows the live pod annotation" contract at runtime — that + annotation is DGD-owned and applied by the operator. Routed through the active ``Actuator`` (not raw ``pynvml``) so the release write flows through the same library that applied the cap. On @@ -1402,11 +1404,11 @@ def _build_uid_to_annotation(self, pods: list) -> dict[str, Optional[str]]: non-empty ``pod_annotations`` and fall through to the "no parseable annotation → safe default" branch in ``_resolve_cap_for_gpu`` — i.e. the agent would silently power-cap a co-located non-Dynamo workload (or - a Dynamo worker the planner has not yet annotated). Gating on key - presence is what keeps the agent from touching GPUs it was never asked - to manage. The planner is the sole writer of this key and stamps it - only on prefill/decode worker pods. Do NOT reintroduce unannotated pods - with a ``None`` value. + a Dynamo worker not yet annotated). Gating on key presence is what keeps + the agent from touching GPUs it was never asked to manage. This key is + DGD-owned: authored on the worker component podTemplate and applied to + worker pods by the operator. Do NOT reintroduce unannotated pods with a + ``None`` value. A pod that carries the key but with a malformed/empty value IS kept (value as-is) so the safe-default fail-safe still applies to a @@ -1531,15 +1533,15 @@ def _reconcile_gpu( Caps are persistent by design: when a managed GPU is merely idle this cycle (no processes at all) we deliberately DO NOT restore default TGP here. A managed worker may exit briefly (OOM, reschedule) and return to - the same GPU; restoring during that gap would violate the planner's - power budget, and the planner owns cap lifecycle via annotation - removal/update. + the same GPU; restoring during that gap would violate the deployment's + power budget. Cap lifecycle is driven by the live pod annotation, which + is DGD-owned and applied by the operator. A cap IS restored to default in three places: - ``_release_managed_gpu`` during ordinary reconcile, when a GPU we previously capped now runs only unannotated / non-K8s processes (the opted-in pod is gone and a non-managed tenant owns the GPU, - or the planner removed the annotation); + or the pod carrying the annotation was deleted); - ``_shutdown_cleanup`` at agent shutdown (invoked from ``run()`` after SIGTERM); and - ``_restore_orphaned_gpus_on_startup`` (previously-managed + diff --git a/deploy/power-agent/tests/test_annotation_scope.py b/deploy/power-agent/tests/test_annotation_scope.py index a3a5667e9e8b..5ae648b2803d 100644 --- a/deploy/power-agent/tests/test_annotation_scope.py +++ b/deploy/power-agent/tests/test_annotation_scope.py @@ -5,8 +5,8 @@ `_build_uid_to_annotation` is scope-by-annotation-key: a pod is in scope only if it carries ``dynamo.nvidia.com/gpu-power-limit``. A GPU running only -unannotated pods — a co-located non-Dynamo workload, or a Dynamo worker the -planner has not yet annotated — must be left at its hardware default and never +unannotated pods — a co-located non-Dynamo workload, or a Dynamo worker not yet +annotated by the operator — must be left at its hardware default and never written, instead of being silently capped to the safe default. A pod that *does* carry the key but with a malformed value stays in scope so diff --git a/deploy/power-agent/tests/test_multi_dgd_topology.py b/deploy/power-agent/tests/test_multi_dgd_topology.py index 149acf1cfa74..a33b81acbca0 100644 --- a/deploy/power-agent/tests/test_multi_dgd_topology.py +++ b/deploy/power-agent/tests/test_multi_dgd_topology.py @@ -56,8 +56,9 @@ UID_T_DECODE = "uid-trtllm-decode" UID_S_AGG = "uid-sglang-agg" -# Per-pod NVML cap (watts). The planner's `_apply_power_annotations` would -# have stamped these as `dynamo.nvidia.com/gpu-power-limit` annotations. +# Per-pod NVML cap (watts). The operator stamps these as +# `dynamo.nvidia.com/gpu-power-limit` annotations on worker pods from the +# DGD-owned podTemplate. ANNOTATIONS = { UID_V_PREFILL: "450", UID_V_DECODE: "425", diff --git a/docs/fern/components/planner/planner-examples.md b/docs/fern/components/planner/planner-examples.md index 8a3efa70cf38..6fdc0035dcf4 100644 --- a/docs/fern/components/planner/planner-examples.md +++ b/docs/fern/components/planner/planner-examples.md @@ -63,6 +63,50 @@ prophet_window_size: 100 # Larger window for seasonal detection load_predictor_log1p: true ``` +## Power-Aware Budget Scaling + +Keep the Planner's projected GPU power draw within a configured rack/DGD budget. +Per-GPU caps are DGD-owned: authored on each worker component's `podTemplate` +annotation (`dynamo.nvidia.com/gpu-power-limit`), applied to Pods by the +operator, and enforced by the Power Agent. The Planner only reads them and +combines them with `total_gpu_power_limit` (in its config) to project a budget +and clamp scale-up — it never patches Pods. + +The mounted PlannerConfig enables it: + +```json +{ + "enable_power_awareness": true, + "total_gpu_power_limit": 5200 +} +``` + +`enable_power_awareness` requires `environment: "kubernetes"` and +`mode` set to `disagg`, `prefill`, or `decode` (`agg` is not supported). +The Planner caches each annotated component's cap, effective main-container GPU +count, and node count at startup. DGD admission rejects changes to those fields; +delete and recreate the DGD to change them. Restart the Planner after changing +`total_gpu_power_limit`. + +You must also enable `pods/list` RBAC for the Planner's ServiceAccount at +install time. The Planner reads Pod annotations during startup to verify that +power caps have propagated before caching them. Without the permission the +startup settlement check fails. Pass this flag when installing or upgrading the +platform chart: + +```bash +helm dependency build deploy/helm/charts/platform +helm upgrade --install dynamo deploy/helm/charts/platform \ + --set dynamo-operator.planner.powerAwareness.enabled=true +``` + +See the `power-aware-budget/` directory in +[Dynamo examples](https://github.com/ai-dynamo/dynamo/tree/main/examples) for +the full annotation + config contract and its limitations (the budget is a +projected ceiling over requested caps, not a proven hardware limit). Mixed GPU +generations, dynamic cap retargeting, and DRA-backed GPU allocation are not +supported. + ## Virtual Connector For non-Kubernetes environments, use the VirtualConnector to communicate scaling diff --git a/examples/power-aware-budget/README.md b/examples/power-aware-budget/README.md new file mode 100644 index 000000000000..fc2066f44881 --- /dev/null +++ b/examples/power-aware-budget/README.md @@ -0,0 +1,106 @@ + + +# DGD-owned power caps and budget-aware scaling + +This example shows how to author per-GPU power caps and a deployment-wide power +budget so the Planner keeps its **projected** power draw within a configured +rack/DGD budget when it scales replicas. + +> [!NOTE] +> These manifests are a **contract fragment**, not a fully deployable DGD: they +> show only the power-relevant fields (annotations, GPU limits, Planner config). +> A runnable deployment also needs container images, model args, env/secrets, +> and a Frontend — see [examples/backends/vllm/deploy/](../backends/vllm/deploy/) +> for a complete DGD to merge these fields into. + +> [!IMPORTANT] +> The budget is a **projected** ceiling over the *requested* per-GPU caps, not a +> proven hardware limit. The Power Agent applies each requested cap but may +> clamp it up to the GPU's hardware minimum, and a cap write can fail; neither +> is fed back to the Planner today. So the Planner prevents an admitted +> scale-up from pushing `projected_watts` over `total_gpu_power_limit` for the +> requested caps — it does **not** automatically remediate a deployment that is +> already over budget (it holds scale-ups and allows scale-downs), and it does +> not guarantee the *effective* hardware draw stays under the budget. +> Effective-cap and enforcement-health feedback are deferred to the +> dynamic-control design. + +## Ownership model + +| Value | Source of truth | Consumer | +| --- | --- | --- | +| Per-GPU cap (watts, static) | Worker component `podTemplate` annotation `dynamo.nvidia.com/gpu-power-limit` | Operator → Pods; Power Agent (applies NVML/DCGM cap); Planner (reads) | +| Total DGD power budget (watts) | PlannerConfig `total_gpu_power_limit` | Planner | +| Replica targets | Planner (after the budget clamp) | Existing scaling adapter | +| Applied GPU hardware cap | Power Agent | NVML / DCGM | + +The Planner **reads** the caps from the DGD; it does **not** patch Pods. New +replicas created by a scale-up are born with the annotation because the operator +renders it into the Deployment / LeaderWorkerSet template. + +The Planner caches each component's power tuple at startup: the cap, the +effective main-container `nvidia.com/gpu` count (limit first, request fallback), +and `multinode.nodeCount` (default `1`). DGD admission rejects updates to that +tuple for an annotated component. Delete and recreate the DGD to change it. +Changing `total_gpu_power_limit` also requires restarting the Planner process. + +## Author the caps + +1. Put the per-GPU cap on each worker component's `podTemplate.metadata.annotations` + (see [dgd.yaml](dgd.yaml)). Prefill and decode may differ. +2. Set the total budget on the Planner's mounted config (see + [planner_config.json](planner_config.json)): + + ```json + { + "enable_power_awareness": true, + "total_gpu_power_limit": 5200 + } + ``` + + `enable_power_awareness` requires `environment: "kubernetes"`, a + `total_gpu_power_limit > 0`, and `mode` set to `disagg`, `prefill`, or + `decode` (`agg` is not currently supported). Per-GPU caps are **not** set + here — they live on the worker `podTemplate` annotations only. + +3. Enable the Planner's `pods/list` RBAC permission in the Helm installation. + Power-annotation settlement reads Pod annotations at startup, which requires + this permission. Set it when installing or upgrading the platform chart: + + ```bash + helm dependency build deploy/helm/charts/platform + helm upgrade --install dynamo deploy/helm/charts/platform \ + --set dynamo-operator.planner.powerAwareness.enabled=true + ``` + + Without this flag the Planner's ServiceAccount lacks `pods/list` and the + startup settlement check will fail with a Kubernetes RBAC error. + +## Projection + +```text +projected_watts = + prefill_replicas × prefill_gpus_per_replica × prefill_cap_watts + + decode_replicas × decode_gpus_per_replica × decode_cap_watts +``` + +For the values in this example (2 prefill replicas × 2 GPU × 350 W + 2 decode +replicas × 4 GPU × 300 W) the projection is `1400 + 2400 = 3800 W` against a +`5200 W` budget. A scale-up that would exceed `5200 W` is clamped to fit, and +the `dynamo_planner_power_budget_utilization` gauge reports the ratio. + +## Static-input limitations + +> [!IMPORTANT] +> You cannot patch a power annotation, effective GPU count, or node count in +> place on a power-annotated component. Admission rejects the update; delete and +> recreate the DGD, then start the Planner against the replacement. Restart the +> Planner after changing `total_gpu_power_limit`. + +Power awareness currently assumes a static, uniform GPU count and cap per +component. Mixed GPU generations within one component, dynamic cap retargeting, +and GPU allocation through DRA resource claims are not supported by this +projection. diff --git a/examples/power-aware-budget/dgd.yaml b/examples/power-aware-budget/dgd.yaml new file mode 100644 index 000000000000..76d47e97e071 --- /dev/null +++ b/examples/power-aware-budget/dgd.yaml @@ -0,0 +1,66 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# DGD-owned per-GPU power caps + budget-aware scaling (hand-authored contract). +# +# The per-GPU cap for each worker role is authored on that component's +# podTemplate annotation `dynamo.nvidia.com/gpu-power-limit` (watts). The +# operator stamps it onto every worker Pod at create time (including replicas +# added by a scale-up); the Power Agent DaemonSet reads the live Pod annotation +# and applies the NVML/DCGM cap. The Planner only READS these caps from the DGD +# and combines them with `total_gpu_power_limit` (in the mounted PlannerConfig) +# to project a power budget and clamp scale-up. The Planner never patches Pods. +# +# The annotation, effective main-container nvidia.com/gpu count (limit first, +# request fallback), and multinode.nodeCount are immutable for an annotated +# component. Delete and recreate the DGD to change that tuple. Restart the +# Planner process after changing total_gpu_power_limit. +apiVersion: nvidia.com/v1beta1 +kind: DynamoGraphDeployment +metadata: + name: power-aware-example +spec: + components: + - name: Planner + type: planner + podTemplate: + spec: + containers: + - name: main + args: + - --config + - /workspace/planner_config/planner_config.json + # The mounted PlannerConfig enables power awareness and sets the + # deployment-wide budget (see planner_config.json in this dir): + # enable_power_awareness: true + # total_gpu_power_limit: 5200 + + - name: VllmPrefillWorker + type: prefill + replicas: 2 + podTemplate: + metadata: + annotations: + # 2 GPUs/replica × 350 W = 700 W per prefill replica. + dynamo.nvidia.com/gpu-power-limit: "350" + spec: + containers: + - name: main + resources: + limits: + nvidia.com/gpu: "2" + + - name: VllmDecodeWorker + type: decode + replicas: 2 + podTemplate: + metadata: + annotations: + # 4 GPUs/replica × 300 W = 1200 W per decode replica. + dynamo.nvidia.com/gpu-power-limit: "300" + spec: + containers: + - name: main + resources: + limits: + nvidia.com/gpu: "4" diff --git a/examples/power-aware-budget/planner_config.json b/examples/power-aware-budget/planner_config.json new file mode 100644 index 000000000000..6c536e0eb32c --- /dev/null +++ b/examples/power-aware-budget/planner_config.json @@ -0,0 +1,7 @@ +{ + "environment": "kubernetes", + "backend": "vllm", + "mode": "disagg", + "enable_power_awareness": true, + "total_gpu_power_limit": 5200 +}