unlock unlimited code runs for $79, limited time →
NOSSLETTER.techLIVE
back to archive

resource: add Quantity.AsScaledInt64 and AsMilliInt64

Language: Go+623 -187feature
concepts demonstrated
Method receiversMultiple return valuesInteger overflow handlingSaturation arithmetic
The Issue & Context

Kubernetes resource.Quantity methods like Value() silently overflow and wrap on int64 limits, causing incorrect negative values for large resource amounts, impacting components like the kubelet.

Root Cause Analysis

Existing Quantity accessors returned int64 values that wrapped on overflow without indication, leading to invalid negative values when resource amounts exceeded int64 bounds.

Solution Strategy & Architectural Pattern

Introduced AsScaledInt64(scale) and AsMilliInt64() methods that return a boolean indicating success and saturate values to int64 min/max instead of wrapping. Updated existing wrappers to use these saturating methods, and fixed kubelet CPU reservation parsing to avoid negative wraparound.

Key Takeaway for Contributors

APIs returning numeric resource values should signal overflow and saturate to prevent subtle bugs from silent wrapping; callers must still handle bounds explicitly when combining values.