Skip to content

fix: parse milli-quantities in parseUnitsOfBytes - #6817

Open
Pratikdeb07 wants to merge 1 commit into
kubernetes-sigs:mainfrom
Pratikdeb07:fix/parse-milli-quantities
Open

fix: parse milli-quantities in parseUnitsOfBytes#6817
Pratikdeb07 wants to merge 1 commit into
kubernetes-sigs:mainfrom
Pratikdeb07:fix/parse-milli-quantities

Conversation

@Pratikdeb07

@Pratikdeb07 Pratikdeb07 commented Aug 2, 2026

Copy link
Copy Markdown

Summary

This PR fixes an issue where memory usage percentages are displayed approximately 1000× larger than expected when the Metrics API returns memory quantities in milli-units (for example, 2687146666666m).

This occurs with prometheus-adapter, which commonly serves the metrics.k8s.io API in Prometheus-backed Kubernetes clusters that do not use metrics-server.

Related Issue

Fixes #6816

Changes

  • Added support for the Kubernetes m (milli) suffix in parseUnitsOfBytes() (frontend/src/lib/units.ts).
  • Parsed milli-byte values as parseFloat(value) / 1000, matching the existing handling in parseCpu().
  • Added unit tests covering milli-byte quantities, including:
    • 1000m1
    • 2687146666666m2687146666.666
    • 1.5m0.0015

Steps to Test

  1. Set up a cluster where the Metrics API is provided by prometheus-adapter (with resourceRules enabled) instead of metrics-server.
  2. Open Cluster Overview.
    • Verify memory usage displays approximately 32.8% (about 2.5 GiB / 7.63 GiB) instead of 32800%.
  3. Open Workloads → Pods.
    • Verify the CPU/Memory columns and the "Request: X%" tooltips display correct values.
  4. Observe the UI for a few metrics refresh cycles.
    • Memory usage should remain stable even when the metrics provider alternates between Ki and m quantity formats.

Screenshots

Before
Images are present in issue
After
image

Notes for Reviewers

N/A

Summary by CodeRabbit

  • Bug Fixes
    • Improved memory quantity parsing for Kubernetes milli-unit values.
    • Correctly handles whole, large, and fractional milli-quantities by converting them to base units.

@kubernetes-prow

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: Pratikdeb07
Once this PR has been reviewed and has the lgtm label, please assign ashu8912 for approval. For more information see the Code Review Process.

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@kubernetes-prow
kubernetes-prow Bot requested review from kahirokunn and skoeva August 2, 2026 19:22
@linux-foundation-easycla

linux-foundation-easycla Bot commented Aug 2, 2026

Copy link
Copy Markdown

CLA Signed
The committers listed above are authorized under a signed CLA.

  • ✅ login: Pratikdeb07 / name: Pratik Debnath (803320f)

@kubernetes-prow

Copy link
Copy Markdown
Contributor

Welcome @Pratikdeb07!

It looks like this is your first PR to kubernetes-sigs/headlamp 🎉. Please refer to our pull request process documentation to help your PR have a smooth ride to approval.

You will be prompted by a bot to use commands during the review process. Do not be afraid to follow the prompts! It is okay to experiment. Here is the bot commands documentation.

You can also check if kubernetes-sigs/headlamp has its own contribution guidelines.

You may want to refer to our testing guide if you run into trouble with your tests not passing.

If you are having difficulty getting your pull request seen, please follow the recommended escalation practices. Also, for tips and tricks in the contribution process you may want to read the Kubernetes contributor cheat sheet. We want to make sure your contribution gets all the attention it needs!

Thank you, and welcome to Kubernetes. 😃

@kubernetes-prow kubernetes-prow Bot added cncf-cla: no Indicates the PR's author has not signed the CNCF CLA. size/S Denotes a PR that changes 10-29 lines, ignoring generated files. cncf-cla: yes Indicates the PR's author has signed the CNCF CLA. and removed cncf-cla: no Indicates the PR's author has not signed the CNCF CLA. labels Aug 2, 2026
@Pratikdeb07
Pratikdeb07 force-pushed the fix/parse-milli-quantities branch from 803320f to 974aefb Compare August 3, 2026 03:17
@skoeva skoeva added the frontend Issues related to the frontend label Aug 3, 2026
@skoeva skoeva added this to the v0.45.0 milestone Aug 3, 2026
@illume illume added kind/bug Categorizes issue or PR as related to a bug. testing labels Aug 5, 2026
@illume
illume requested a lite review from Copilot August 5, 2026 07:44

@illume illume left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the contribution.

Could you take a look at the commit messages in this PR? We follow a Linux kernel style for git commits — see the contributing guide and git log for examples.

Commits that need attention
  • fix: parse milli-quantities in parseUnitsOfBytes — Missing area: description prefix — e.g. frontend: HomeButton: Fix so it navigates to home or backend: config: Add enable-dynamic-clusters flag.
Commit guidelines
  • Use atomic commits focused on a single change.
  • Use the title format <area>: <Description of changes> — description must start with a capital letter.
  • Keep the title under 72 characters (soft requirement).
  • Explain the intention and why the change is needed.
  • Make commit titles meaningful and describe what changed.
  • Do not add code that a later commit rewrites; squash or reorder commits instead.
  • Do not include Fixes #NN in commit messages.

Good examples:

  • frontend: HomeButton: Fix so it navigates to home
  • backend: config: Add enable-dynamic-clusters flag

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR fixes incorrect memory usage/percentage calculations when the Kubernetes Metrics API returns milli-quantities for memory (e.g. values ending in m, as commonly emitted by prometheus-adapter). It updates the shared frontend unit parser so memory values remain consistent across refreshes even when the provider alternates between Ki and m formats.

Changes:

  • Add support for parsing byte quantities with the Kubernetes m (milli) suffix in parseUnitsOfBytes() by dividing by 1000.
  • Add unit tests validating milli-byte parsing behavior for typical and fractional inputs.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.

File Description
frontend/src/lib/units.ts Adds explicit handling for ...m byte quantities to prevent interpreting milli-values as raw bytes.
frontend/src/lib/units.test.ts Adds coverage ensuring milli-byte quantities are parsed correctly and guard against regressions.

@Pratikdeb07
Pratikdeb07 force-pushed the fix/parse-milli-quantities branch from 974aefb to c7e5770 Compare August 5, 2026 17:49
@coderabbitai

coderabbitai Bot commented Aug 5, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: b8a60d01-d7e6-4f5c-9ebe-161d275c85a2

📥 Commits

Reviewing files that changed from the base of the PR and between ce115c8 and deec6d4.

📒 Files selected for processing (2)
  • frontend/src/lib/units.test.ts
  • frontend/src/lib/units.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • frontend/src/lib/units.test.ts
  • frontend/src/lib/units.ts

📝 Walkthrough

Walkthrough

The unit parser recognizes Kubernetes milli-quantity values and divides them by 1000 before existing byte-unit parsing. Tests cover integer, large, and fractional milli-quantity inputs.

Changes

Milli-quantity parsing

Layer / File(s) Summary
Parse and validate milli-quantities
frontend/src/lib/units.ts, frontend/src/lib/units.test.ts
parseUnitsOfBytes converts values ending in m to base units. parseRam tests cover integer, large, and fractional values.

Estimated code review effort: 1 (Trivial) | ~5 minutes

Suggested reviewers: kahirokunn, skoeva, illume

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the primary change: parsing milli-quantities in parseUnitsOfBytes.
Description check ✅ Passed The description includes the summary, issue, changes, testing steps, screenshots, and reviewer notes required by the template.
Linked Issues check ✅ Passed The implementation and tests support issue #6816 by parsing milli-byte quantities and preventing incorrect memory usage percentages.
Out of Scope Changes check ✅ Passed The changes are limited to milli-quantity parsing and related unit tests, which directly match issue #6816.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@Pratikdeb07

Copy link
Copy Markdown
Author

Thanks for your review @illume ! I have updated the commit message.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated no new comments.

Signed-off-by: Pratik Debnath <pratikdebnath978@gmail.com>
@Pratikdeb07
Pratikdeb07 force-pushed the fix/parse-milli-quantities branch from c7e5770 to deec6d4 Compare August 6, 2026 08:05
@coderabbitai

coderabbitai Bot commented Aug 6, 2026

Copy link
Copy Markdown

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated no new comments.

@unlikelyzero unlikelyzero left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This only handles the 'm' suffix, but Kubernetes decimalSI also has 'u' (micro) and 'n' (nano) on the same family - same bug class, just less common. parseCpu right below in this same file already handles the full n/u/m ladder, and util.ts's normalizeUnit already handles all three for memory too, so the pattern to copy is already sitting in the codebase.

That duplication isn't theoretical either - resourceQuota/Details.tsx renders the same table row using both parsers: the Used/Hard columns go through normalizeUnit, and the Usage bar in that same row goes through parseRam/parseUnitsOfBytes. Before this PR they disagreed 1000x on milli values in that row; after it they agree on 'm' but still disagree on 'u'/'n' and on lowercase 'k' (which is the canonical k8s suffix - the regex here only matches uppercase 'K', so '1k' returns 1 instead of 1000, same 1000x bug in the same function).

A few smaller things inline.

Comment thread frontend/src/lib/units.ts
// Milli-quantity ex. "2687146666666m". Valid Kubernetes quantity syntax
// (e.g. emitted by prometheus-adapter for memory usage), but no unit is
// matched by the regex below, which would misread it as raw bytes.
if (value.endsWith('m')) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would extend this to cover 'u' and 'n' too, mirroring parseCpu a few lines down: /1000 for m, /1e6 for u, /1e9 for n. Same bug, just needs two more branches.

Comment thread frontend/src/lib/units.ts
return parseFloat(value) / 1000;
}

const groups = value.match(/(\d+(?:\.\d+)?)([BKMGTPEe])?(i)?(\d+)?/) || [];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This character class only matches uppercase 'K', but the canonical Kubernetes suffix is lowercase 'k' (unlike M/G/T/P/E which are uppercase) - util.ts's normalizeUnit checks endsWith('k') for exactly this reason. Worth fixing while you're in here, since it's the same 1000x-off bug for the one suffix that happens to be lowercase.

expect(parseRam('0.5G')).toBe(500000000);
});

it('should parse milli quantities (e.g. from prometheus-adapter)', () => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These test parseRam directly, but the actual reported bug is a percentage calculation through divideK8sResources - there's already a describe block for that with a comparable CPU nano/micro case a bit further down that this could extend with a memory-milli one.

@kubernetes-prow kubernetes-prow Bot added the needs-rebase Indicates a PR cannot be merged because it has merge conflicts with HEAD. label Aug 13, 2026
@kubernetes-prow

Copy link
Copy Markdown
Contributor

PR needs rebase.

Details

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.

@illume illume left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for working on this.

Looks like there are git conflicts in this PR. Can you fix them up?

How to resolve conflicts

Rebase or merge the latest main into your branch, resolve the conflicts, and push the updated branch.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cncf-cla: yes Indicates the PR's author has signed the CNCF CLA. frontend Issues related to the frontend kind/bug Categorizes issue or PR as related to a bug. needs-rebase Indicates a PR cannot be merged because it has merge conflicts with HEAD. size/S Denotes a PR that changes 10-29 lines, ignoring generated files. testing

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: usage percentages wrong (~1000x) when metrics API emits milli quantities (e.g. prometheus-adapter)

5 participants