-
Notifications
You must be signed in to change notification settings - Fork 174
refactor(BA-5744): migrate kernel live_stat from Valkey to Prometheus #11330
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
seedspirit
wants to merge
3
commits into
main
Choose a base branch
from
refactor/BA-5744
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| Migrate kernel `live_stat` GraphQL resolver from Valkey to Prometheus while preserving the legacy wire shape |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,11 +1,107 @@ | ||
| from typing import Final | ||
| from typing import Final, TypedDict | ||
|
|
||
| UNDEFINED: Final[str] = "undefined" | ||
|
|
||
|
|
||
| class MovingStatValue(TypedDict): | ||
| min: str | ||
| max: str | ||
| sum: str | ||
| avg: str | ||
| diff: str | ||
| rate: str | ||
| version: int | None # for legacy client compatibility | ||
|
|
||
|
|
||
| MetricValue = TypedDict( | ||
| "MetricValue", | ||
| { | ||
| "current": str, | ||
| "capacity": str, | ||
| "pct": str, | ||
| "unit_hint": str, | ||
| "stats.min": str, | ||
| "stats.max": str, | ||
| "stats.sum": str, | ||
| "stats.avg": str, | ||
| "stats.diff": str, | ||
| "stats.rate": str, | ||
| "stats.version": int | None, | ||
| }, | ||
| ) | ||
|
|
||
|
|
||
| def make_default_metric_value(unit_hint: str) -> MetricValue: | ||
| """Return a `MetricValue` populated with neutral defaults. | ||
|
|
||
| All numeric string fields are `"0"` (including `capacity`, matching the | ||
| legacy Valkey shape where every metric carried a string capacity). | ||
| `unit_hint` is supplied by the caller. | ||
| """ | ||
| return MetricValue({ | ||
| "current": "0", | ||
| "capacity": "0", | ||
| "pct": "0", | ||
| "unit_hint": unit_hint, | ||
| "stats.min": "0", | ||
| "stats.max": "0", | ||
| "stats.sum": "0", | ||
| "stats.avg": "0", | ||
| "stats.diff": "0", | ||
| "stats.rate": "0", | ||
| "stats.version": None, | ||
| }) | ||
|
|
||
|
|
||
| UTILIZATION_METRIC_INTERVAL: Final[float] = 5.0 | ||
| UTILIZATION_METRIC_DETENTION: Final[float] = 600.0 # 10 minutes | ||
|
|
||
| CONTAINER_UTILIZATION_METRIC_NAME: Final[str] = "backendai_container_utilization" | ||
| CONTAINER_UTILIZATION_METRIC_LABEL_NAME: Final[str] = "container_metric_name" | ||
| DEVICE_UTILIZATION_METRIC_LABEL_NAME: Final[str] = "device_metric_name" | ||
| PROCESS_UTILIZATION_METRIC_LABEL_NAME: Final[str] = "process_metric_name" | ||
|
|
||
| # Metric-name classification used by the legacy live_stat dict converter. | ||
| # These mirror the semantics that Worker's MovingStatistics produced when | ||
| # kernel stats were stored in Valkey: | ||
| # - RATE_STAT_METRICS: stats.rate is meaningful (rate of change per second). | ||
| # - DIFF_STAT_METRICS: stats.diff is meaningful (delta over the last window). | ||
| RATE_STAT_METRICS: Final[frozenset[str]] = frozenset({"net_rx", "net_tx"}) | ||
| DIFF_STAT_METRICS: Final[frozenset[str]] = frozenset({"cpu_util"}) | ||
|
|
||
| # Per-metric unit hint emitted by the agent (source of truth: src/ai/backend/agent/docker/intrinsic.py). | ||
| METRIC_UNIT_HINTS: Final[dict[str, str]] = { | ||
| "cpu_used": "msec", | ||
| "cpu_util": "percent", | ||
| "mem": "bytes", | ||
| "net_rx": "bps", | ||
| "net_tx": "bps", | ||
| "io_read": "bytes", | ||
| "io_write": "bytes", | ||
| "io_scratch_size": "bytes", | ||
| } | ||
|
|
||
|
|
||
| def resolve_unit_hint(metric_name: str) -> str: | ||
| """Return the unit_hint for a Backend.AI container metric name. | ||
|
|
||
| Prometheus does not carry the agent-side `unit_hint` in its samples, so the | ||
| manager has to recover it from the metric name alone. Lookup order: | ||
|
|
||
| 1. Explicit registration in :data:`METRIC_UNIT_HINTS` (highest priority). | ||
| 2. Naming-convention fallback for plugin metrics that follow Backend.AI | ||
| conventions (e.g., `cuda_util`, `gpu_mem`, `tpu_util`). | ||
| 3. The metric_name itself as a last resort — preserves the sample data | ||
| and surfaces the missing registration to the WebUI via the response. | ||
| """ | ||
| if metric_name in METRIC_UNIT_HINTS: | ||
| return METRIC_UNIT_HINTS[metric_name] | ||
| if metric_name.endswith("_util"): | ||
| return "percent" | ||
| if metric_name == "mem" or metric_name.endswith("_mem"): | ||
| return "bytes" | ||
| if metric_name.startswith("io_"): | ||
| return "bytes" | ||
| if metric_name.startswith("net_"): | ||
| return "bps" | ||
| return metric_name | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -24,6 +24,7 @@ | |
| KernelId, | ||
| SessionId, | ||
| ) | ||
| from ai.backend.manager.api.gql_legacy.stat_converter import LegacyLiveStatConverter | ||
| from ai.backend.manager.data.kernel.types import KernelStatus | ||
| from ai.backend.manager.defs import DEFAULT_ROLE | ||
| from ai.backend.manager.models.group import groups | ||
|
|
@@ -42,6 +43,7 @@ | |
| QueryFilterParser, | ||
| ) | ||
| from ai.backend.manager.models.user import UserRole, users | ||
| from ai.backend.manager.services.metric.actions.live_stat import ContainerLiveStatAction | ||
|
|
||
| from .base import ( | ||
| BigInt, | ||
|
|
@@ -67,6 +69,19 @@ | |
| ) | ||
|
|
||
|
|
||
| async def _batch_load_kernel_live_stat( | ||
|
jopemachine marked this conversation as resolved.
|
||
| ctx: GraphQueryContext, | ||
| kernel_ids: Sequence[KernelId], | ||
| ) -> list[dict[str, Any] | None]: | ||
| if not kernel_ids: | ||
| return [] | ||
| action_result = await ctx.processors.metric.query_container_live_stat.wait_for_complete( | ||
| ContainerLiveStatAction(kernel_ids=list(kernel_ids)) | ||
| ) | ||
| converted = LegacyLiveStatConverter().convert(action_result.stats) | ||
| return [converted.get(kid) for kid in kernel_ids] | ||
|
Comment on lines
+81
to
+82
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why do we have to create a converter every time? |
||
|
|
||
|
|
||
| class KernelNode(graphene.ObjectType): # type: ignore[misc] | ||
| class Meta: | ||
| interfaces = (AsyncNode,) | ||
|
|
@@ -190,17 +205,10 @@ async def resolve_image(self, info: graphene.ResolveInfo) -> ImageNode | None: | |
| async def resolve_live_stat(self, info: graphene.ResolveInfo) -> dict[str, Any] | None: | ||
| graph_ctx: GraphQueryContext = info.context | ||
| loader = graph_ctx.dataloader_manager.get_loader_by_func( | ||
| graph_ctx, self.batch_load_live_stat | ||
| graph_ctx, _batch_load_kernel_live_stat | ||
| ) | ||
| return cast(dict[str, Any] | None, await loader.load(self.row_id)) | ||
|
|
||
| @classmethod | ||
| async def batch_load_live_stat( | ||
| cls, ctx: GraphQueryContext, kernel_ids: Sequence[KernelId] | ||
| ) -> list[dict[str, Any] | None]: | ||
| kernel_ids_str = [str(kid) for kid in kernel_ids] | ||
| return await ctx.valkey_stat.get_session_statistics_batch(kernel_ids_str) | ||
|
|
||
|
|
||
| class KernelConnection(Connection): | ||
| class Meta: | ||
|
|
@@ -313,7 +321,9 @@ def from_row(cls, ctx: GraphQueryContext, row: KernelRow | None) -> ComputeConta | |
| # we can leave last_stat value for legacy support, as an alias to last_stat | ||
| async def resolve_live_stat(self, info: graphene.ResolveInfo) -> Mapping[str, Any] | None: | ||
| graph_ctx: GraphQueryContext = info.context | ||
| loader = graph_ctx.dataloader_manager.get_loader(graph_ctx, "KernelStatistics.by_kernel") | ||
| loader = graph_ctx.dataloader_manager.get_loader_by_func( | ||
| graph_ctx, _batch_load_kernel_live_stat | ||
| ) | ||
| return cast(Mapping[str, Any] | None, await loader.load(self.id)) | ||
|
|
||
| async def resolve_last_stat(self, info: graphene.ResolveInfo) -> Mapping[str, Any] | None: | ||
|
|
@@ -606,7 +616,9 @@ class Meta: | |
| # we can leave last_stat value for legacy support, as an alias to last_stat | ||
| async def resolve_live_stat(self, info: graphene.ResolveInfo) -> Mapping[str, Any] | None: | ||
| graph_ctx: GraphQueryContext = info.context | ||
| loader = graph_ctx.dataloader_manager.get_loader(graph_ctx, "KernelStatistics.by_kernel") | ||
| loader = graph_ctx.dataloader_manager.get_loader_by_func( | ||
| graph_ctx, _batch_load_kernel_live_stat | ||
| ) | ||
| return cast(Mapping[str, Any] | None, await loader.load(self.id)) | ||
|
|
||
| async def resolve_last_stat(self, info: graphene.ResolveInfo) -> Mapping[str, Any] | None: | ||
|
|
@@ -632,7 +644,9 @@ async def _resolve_legacy_metric( | |
| if value is None: | ||
| return convert_type(0) | ||
| return convert_type(value) | ||
| loader = graph_ctx.dataloader_manager.get_loader(graph_ctx, "KernelStatistics.by_kernel") | ||
| loader = graph_ctx.dataloader_manager.get_loader_by_func( | ||
| graph_ctx, _batch_load_kernel_live_stat | ||
| ) | ||
| kstat = await loader.load(self.id) | ||
| if kstat is None: | ||
| return convert_type(0) | ||
|
|
||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
MetricValuenow definescapacityas a requiredstr, but there are still in-repo producers/consumers that treatcapacityas nullable (e.g., alembic stats migration sets"capacity": None, and the CLI formatter checksmetric["capacity"] is not None). This makes the TypedDict inconsistent with real payloads and will either break type-checking or force unsafe casts. Please either keepcapacityasstr | None(like the previous definition) or update all producers to always emit a string (e.g., "0") and remove/adjust theNonehandling accordingly.