Skip to content

fix(exchange): fail loud on over-cap re-quote, empty region, non-positive count - #1082

Merged
cristim merged 2 commits into
feat/multicloud-web-frontendfrom
fix/exchange-fail-loud
Jun 7, 2026
Merged

cristim merged 2 commits into
feat/multicloud-web-frontendfrom
fix/exchange-fail-loud

Conversation

@cristim

@cristim cristim commented Jun 7, 2026

Copy link
Copy Markdown
Member

Summary

Fixes three money-safety / silent-fallback violations in pkg/exchange (all on the RI exchange spend path). RI exchanges are irreversible -- the owner directive is fail-loud, no silent defaults, especially on money paths.

  • M4 (most critical) -- executeWithAPI now performs a second GetReservedInstancesExchangeQuote immediately before AcceptReservedInstancesExchangeQuote to narrow the quote-to-accept window. If the re-quoted payment exceeds MaxPaymentDueUSD, the exchange is aborted with an explicit error surfacing the actual vs cap amounts. Accept is never called when the re-quote is over-cap.

  • M3 -- loadCfg now returns an explicit error when region is empty or whitespace-only. RIs are regional; silently targeting us-east-1 on a spend path was a hardcoded region assumption the owner directive prohibits.

  • L2 -- validateTargets now validates Count >= 1 for both the multi-target and legacy-singleton paths. A zero or negative count is an error, not a silent rewrite to 1. buildTargetConfigs no longer has a count <= 0 => 1 fallback branch.

  • L3 -- Corrected stale comment in pricingGatePasses: NormalizationFactorForSize returns 0 (map miss) for unknown sizes, not 1.0. The actual behavior is fail-closed (alternative excluded), not "no NF adjustment".

Regression tests added in fail_loud_test.go covering all three money-path fixes (M4, M3, L2).

Verification

cd pkg && go build ./...   # Success
cd pkg && go vet ./exchange/...  # No issues
cd pkg && go test -race ./exchange/...  # 94 passed (85 pre-existing + 9 new)
go build ./...  # Success (root module)

Follow-up

L4 (PurchaseHistoryRecord.MonthlyCost should be *float64 -- migration-bearing, out of scope here) is tracked in issue #1081.

Closes #1080.

…tive count

M4: executeWithAPI now re-quotes immediately before AcceptReservedInstancesExchangeQuote
to narrow the quote-to-accept window. If the re-quoted payment exceeds MaxPaymentDueUSD,
the exchange is aborted with an explicit error surfacing actual vs cap amounts rather than
proceeding silently. Accept is never called on an over-cap re-quote.

M3: loadCfg now returns an explicit error when region is empty or whitespace-only,
refusing to default to us-east-1 on the RI exchange path. RIs are regional; an
implicit region default on a spend path violates the fail-loud directive.

L2: validateTargets now accepts legacyCount and validates Count >= 1 for both the
multi-target and legacy-singleton paths. A zero or negative Count is an error, not
a silent rewrite to 1. buildTargetConfigs no longer has a fallback-to-1 branch.

L3: Correct the stale comment in pricingGatePasses: NormalizationFactorForSize
returns 0 (not 1.0) for unknown sizes, causing passesDollarUnitsCheck to reject
the alternative (fail-closed), not to bypass the dollar-units check.

Regression tests added in fail_loud_test.go covering all three money-path fixes.
Closes #1080.
@cristim cristim added triaged Item has been triaged priority/p1 Next up; this sprint severity/high Significant harm urgency/this-sprint Within the current sprint impact/few Limited audience effort/s Hours type/bug Defect labels Jun 7, 2026
@coderabbitai

coderabbitai Bot commented Jun 7, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

@cristim, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 16 minutes and 36 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: ec285080-5126-4bb2-8a5e-1cd14d5584cc

📥 Commits

Reviewing files that changed from the base of the PR and between 5fc0899 and dcee1b4.

📒 Files selected for processing (3)
  • pkg/exchange/exchange.go
  • pkg/exchange/fail_loud_test.go
  • pkg/exchange/reshape.go
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/exchange-fail-loud

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

@cristim

cristim commented Jun 7, 2026

Copy link
Copy Markdown
Member Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jun 7, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

…ic complexity

Extract resolvePaymentDue, checkInitialQuote, and checkReQuote from
executeWithAPI to bring its cyclomatic complexity from 11 to 6, fixing
the gocyclo pre-commit hook failure (limit: 10).

Also deduplicate the ExchangeQuoteRequest literal by factoring it into
a shared quoteReq variable used by both the initial and re-quote calls.

Behavior is identical: all 94 exchange tests pass with -race.
@cristim

cristim commented Jun 7, 2026

Copy link
Copy Markdown
Member Author

refactor: extracted resolvePaymentDue, checkInitialQuote, and checkReQuote helpers from executeWithAPI to bring cyclomatic complexity from 11 to 6 (pre-commit gocyclo limit: 10). All 94 exchange tests pass with -race. CI should now be green.

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jun 7, 2026 •

Copy link
Copy Markdown
Contributor

@cristim Sure! I'll kick off a fresh review of the refactored executeWithAPI and its new helpers. Looks like a clean cyclomatic-complexity reduction — I'll verify the extraction didn't introduce any subtle behavioral changes.


🧠 Learnings used
Learnt from: cristim
Repo: LeanerCloud/CUDly PR: 0
File: :0-0
Timestamp: 2026-05-05T15:44:54.463Z
Learning: In the LeanerCloud/CUDly repository, when a CodeRabbit review flags something as "outside-diff" that was already implemented in an earlier commit of the same PR, it is likely a stale-snapshot artifact where the review diff was generated against a pre-fix view. The inline comment convention `(CR pass on PR #<number> Finding N)` is used by the maintainer (cristim) to mark lines that were changed in direct response to a prior CodeRabbit review pass.

Learnt from: cristim
Repo: LeanerCloud/CUDly PR: 0
File: :0-0
Timestamp: 2026-05-25T21:45:57.471Z
Learning: In this repository (CUDly), `internal/commitmentopts/normalizePayment` is unexported and AWS-spelling-focused (parses "All Upfront"/"ALL_UPFRONT" → canonical AWS tokens). `internal/api/validation.go:purchasePaymentWhitelist` is the purchase-execute boundary. `pkg/common/reservation_name.go:normalizeReservationPayment` produces short-form name segments. These are all distinct concerns from the cross-provider `NormalizePaymentOption` helper in `internal/config/validation.go`.

Learnt from: cristim
Repo: LeanerCloud/CUDly PR: 0
File: :0-0
Timestamp: 2026-06-07T17:38:19.416Z
Learning: In LeanerCloud/CUDly `providers/gcp/services/computeengine/client.go`, `convertGCPRecommendation` must force `paymentOption = "monthly"` unconditionally (logging a WARN when a non-monthly value such as "upfront", "all-upfront", or "partial-upfront" is supplied) because GCP CUDs are monthly-only and any non-monthly value passed through would be a silent misconfiguration. Fixed in PR `#1047` commit c6280c390 (F1). Regression test: `TestConvertGCPRecommendation_NonMonthlyPaymentOptionForcedToMonthly`.

Learnt from: cristim
Repo: LeanerCloud/CUDly PR: 0
File: :0-0
Timestamp: 2026-06-07T17:45:38.040Z
Learning: In LeanerCloud/CUDly `providers/gcp/services/cloudsql/client.go`, `getSQLPricing` had the same per-hour/term-total unit mismatch as memorystore and cloudstorage: `commitmentPrice` (per-hour SKU rate) was passed directly to savings math that expected a term total, producing ~99.99% savings, and `HourlyRate` was set to `per-hour / hoursInTerm` (near-zero). Fixed in PR `#1047` commit 20590c6b4 (issue `#1078` folded in): `commitmentPriceTerm := commitmentPrice * hoursInTerm`; `HourlyRate = commitmentPrice` (raw per-hour). `convertGCPRecommendation` also hardcoded `rec.Term = "1yr"`, ignoring `params.Term`; fixed with same defaulting pattern as memorystore/cloudstorage. Regression tests: `TestGetSQLPricing_CommitmentPriceIsTermTotal` and `TestCloudSQLConvertGCPRecommendation_PropagatesTermFromParams`. PaymentOption was already correct (`if paymentOption == "" { paymentOption = "monthly" }`).
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@cristim
cristim merged commit 278a467 into feat/multicloud-web-frontend Jun 7, 2026
4 checks passed
@cristim
cristim deleted the fix/exchange-fail-loud branch June 7, 2026 19:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

effort/s Hours impact/few Limited audience priority/p1 Next up; this sprint severity/high Significant harm triaged Item has been triaged type/bug Defect urgency/this-sprint Within the current sprint

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant