Repository navigation
feat(ladder): core types and capability interfaces for commitment laddering #1338
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
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
cb11df4
feat(ladder): add core types and capability interfaces for commitment…
cristim 9750262
fix(ladder): enforce action invariants and address review findings
cristim 0754d39
fix(ladder): require FireAfter on tranches
cristim 2c21ea3
fix(ladder): reject NaN in ramp fractions and config bounds
cristim 904f3d1
fix(ladder): align capability contracts, add term/payment enums, hard…
cristim 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,97 @@ | ||
| package ladder | ||
|
|
||
| import ( | ||
| "context" | ||
|
|
||
| "github.com/LeanerCloud/CUDly/pkg/common" | ||
| ) | ||
|
|
||
| // LadderCapability is implemented by each cloud provider to give the ladder | ||
| // engine a uniform interface for querying commitment state and executing | ||
| // purchases. Implementations live in providers/ and are injected into the | ||
| // engine at startup. | ||
| // | ||
| //nolint:revive // Ladder* prefix is the spec-mandated public name (issue #1334); matches pkg/exchange's Exchange* convention. | ||
| type LadderCapability interface { | ||
| // Provider returns the cloud provider identifier (common.ProviderAWS, | ||
| // common.ProviderAzure, or common.ProviderGCP). | ||
| Provider() common.ProviderType | ||
|
|
||
| // SupportedLayers returns the commitment layers this provider can fulfill. | ||
| // Each LayerSpec declares both the layer type and the roles it covers. | ||
| // | ||
| // Role-cardinality contract (enforced by the engine): the returned set | ||
| // must contain exactly one layer carrying RoleFlex, at most one carrying | ||
| // RoleBase, and at most one carrying RoleBuffer. The only permitted | ||
| // multi-role merge is base+buffer on a single layer (e.g. an Azure | ||
| // reservation serving both roles). | ||
| SupportedLayers() []LayerSpec | ||
|
|
||
| // ListCommitments returns all active commitments for the given scope. | ||
| ListCommitments(ctx context.Context, scope Scope) ([]common.Commitment, error) | ||
|
|
||
| // GetLayerStates returns a point-in-time snapshot for each supported layer. | ||
| // Layers with no active commitments carry explicit zeros in | ||
| // ExistingUSDPerHour/ExpiringUSDPerHour; nil is reserved for genuinely | ||
| // unmeasured metrics (e.g. UtilizationPct on an empty layer) and is | ||
| // treated as missing data by the engine. | ||
| GetLayerStates(ctx context.Context, scope Scope) (map[LayerType]LayerState, error) | ||
|
|
||
| // GetUsageBaseline computes a statistical baseline from historical | ||
| // on-demand usage over the given lookback window and percentile. | ||
| GetUsageBaseline(ctx context.Context, scope Scope, lookbackDays int, percentile float64) (UsageBaseline, error) | ||
|
|
||
| // PurchaseLayer buys commitments for the given layer using the provided | ||
| // recommendation. Implementations return an error wrapping | ||
| // common.ErrCommitmentPurchaseNotSupported when the layer cannot be | ||
| // purchased programmatically; callers detect it with | ||
| // errors.Is(err, common.ErrCommitmentPurchaseNotSupported). | ||
| // | ||
| // Precision note: the engine plans amounts as exact *big.Rat values | ||
| // (PlannedAction.AmountUSDPerHour), but this boundary converts them to | ||
| // the float64 cost fields of common.Recommendation. This is a documented | ||
| // precision seam; exact-decimal plumbing through the purchase path is | ||
| // addressed in a later PR. | ||
| PurchaseLayer(ctx context.Context, layer LayerType, rec common.Recommendation, opts common.PurchaseOptions) (common.PurchaseResult, error) | ||
|
|
||
| // ReshapeBuffer exchanges or modifies buffer-layer commitments to improve | ||
| // utilization when it falls below the configured threshold. | ||
| ReshapeBuffer(ctx context.Context, scope Scope, cfg BufferReshapeConfig) (ReshapeSummary, error) | ||
| } | ||
|
|
||
| // BufferReshapeConfig parameterizes a buffer reshape operation. | ||
| // | ||
| // The money caps are config-boundary floats, consistent with | ||
| // LadderConfig.MaxHourlyCommitPerRun (implementations convert to | ||
| // pkg/exchange float64 anyway). Convert via ratFromFloat where exact math | ||
| // is needed; NaN/Inf/non-positive values are rejected wherever these caps | ||
| // are validated. | ||
| type BufferReshapeConfig struct { | ||
| // MaxPaymentPerExchangeUSD caps the payment for a single exchange. nil | ||
| // means no per-exchange cap is applied. | ||
| MaxPaymentPerExchangeUSD *float64 | ||
| // MaxPaymentDailyUSD caps the total exchange payments for the current day. | ||
| // nil means no daily cap is applied. | ||
| MaxPaymentDailyUSD *float64 | ||
| // UtilizationThresholdPct triggers a reshape when commitment utilization | ||
| // drops below this percentage. | ||
| UtilizationThresholdPct float64 | ||
| // LookbackDays is the window used to measure utilization when deciding | ||
| // whether to trigger a reshape. | ||
| LookbackDays int | ||
| // DryRun, when true, simulates the reshape without executing any exchanges. | ||
| DryRun bool | ||
| } | ||
|
|
||
| // ReshapeSummary reports the outcome of a buffer reshape operation. | ||
| type ReshapeSummary struct { | ||
| // Details holds per-commitment outcome descriptions for logging and audit. | ||
| Details []string | ||
| // Analyzed is the total number of commitments inspected. | ||
| Analyzed int | ||
| // Reshaped is the number of commitments exchanged or modified. | ||
| Reshaped int | ||
| // Skipped is the number of commitments that did not meet the utilization | ||
| // threshold or were blocked by a spend cap. | ||
| Skipped int | ||
| } | ||
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,227 @@ | ||
| package ladder | ||
|
|
||
| import ( | ||
| "fmt" | ||
| "math/big" | ||
| "strings" | ||
| "time" | ||
| "unicode" | ||
| ) | ||
|
|
||
| // PlannedAction is a single commitment action proposed by the ladder engine. | ||
| // | ||
| // Every action must carry a non-empty Rationale for audit and approval-email | ||
| // readability -- automated money-path decisions must be explained so the | ||
| // human approver (or the audit log) can understand why each action was chosen. | ||
| type PlannedAction struct { | ||
| Action ActionType | ||
| Layer LayerType | ||
| // AmountUSDPerHour is the hourly commitment delta. It must be non-nil and | ||
| // positive for ActionPurchase, and must be nil for ActionHold and | ||
| // ActionReshape (whose financial impact is implicit in the underlying | ||
| // exchange operation). | ||
| AmountUSDPerHour *big.Rat | ||
| // Term is the commitment term. Must be a valid Term for purchase | ||
| // actions; empty for hold and reshape. | ||
| Term Term | ||
| // PaymentOption is the payment structure. Must be a valid PaymentOption | ||
| // for purchase actions; empty for hold and reshape. | ||
| PaymentOption PaymentOption | ||
| // Rationale is a human-readable explanation of why this action was chosen. | ||
| // Must be non-empty for all action types. | ||
| Rationale string | ||
| // DataSources lists the data feeds (Cost Explorer, CloudWatch, etc.) used | ||
| // to derive this action. Aids auditability. | ||
| DataSources []string | ||
| } | ||
|
|
||
| // Validate checks that the action is self-consistent: | ||
| // - action type and layer type must be recognized | ||
| // - rationale must be non-empty | ||
| // - purchase actions require a positive AmountUSDPerHour and valid Term | ||
| // and PaymentOption enum values (money-shaping fields must be present) | ||
| // - hold and reshape actions require a nil AmountUSDPerHour and empty | ||
| // Term and PaymentOption | ||
| func (a *PlannedAction) Validate() error { | ||
| if err := a.Action.Validate(); err != nil { | ||
| return fmt.Errorf("action: %w", err) | ||
| } | ||
| if err := a.Layer.Validate(); err != nil { | ||
| return fmt.Errorf("layer: %w", err) | ||
| } | ||
| if a.Rationale == "" { | ||
| return fmt.Errorf("rationale is required (money-path auditability)") | ||
| } | ||
| switch a.Action { | ||
| case ActionPurchase: | ||
| return a.validatePurchaseFields() | ||
| case ActionHold, ActionReshape: | ||
| if a.AmountUSDPerHour != nil { | ||
| return fmt.Errorf("%s action requires nil AmountUSDPerHour, got %s", | ||
| a.Action, a.AmountUSDPerHour.RatString()) | ||
| } | ||
| if a.Term != "" || a.PaymentOption != "" { | ||
| return fmt.Errorf("%s action requires empty Term and PaymentOption", a.Action) | ||
| } | ||
| } | ||
| return nil | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| // validatePurchaseFields checks the money-shaping fields required for a | ||
| // purchase action. Split out of Validate to keep each function's cyclomatic | ||
| // complexity within the repo limit. | ||
| func (a *PlannedAction) validatePurchaseFields() error { | ||
| if a.AmountUSDPerHour == nil { | ||
| return fmt.Errorf("purchase action requires a non-nil AmountUSDPerHour") | ||
| } | ||
| if a.AmountUSDPerHour.Sign() <= 0 { | ||
| return fmt.Errorf("purchase action requires a positive AmountUSDPerHour, got %s", | ||
| a.AmountUSDPerHour.RatString()) | ||
| } | ||
| // Term and PaymentOption shape the money committed; a purchase with | ||
| // either missing or unrecognized would silently default at the provider | ||
| // boundary. Validate against the typed enums. | ||
| if err := a.Term.Validate(); err != nil { | ||
| return fmt.Errorf("purchase action term: %w", err) | ||
| } | ||
| if err := a.PaymentOption.Validate(); err != nil { | ||
| return fmt.Errorf("purchase action payment option: %w", err) | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| // LadderPlan is a complete, validated commitment plan for one scope and run. | ||
| // It captures the baseline, the monetary gap, and the ordered list of actions | ||
| // the engine proposes to close that gap. | ||
| // | ||
| //nolint:revive // Ladder* prefix is the spec-mandated public name (issue #1334); matches pkg/exchange's Exchange* convention. | ||
| type LadderPlan struct { | ||
| Scope Scope | ||
| GeneratedAt time.Time | ||
| // TargetUSDPerHour is the hourly commitment target derived from | ||
| // Baseline * TargetCoveragePct. nil means it could not be computed. | ||
| TargetUSDPerHour *big.Rat | ||
| // ExistingUSDPerHour is the sum of hourly amortized costs across all | ||
| // active commitment layers. nil means it could not be measured. | ||
| ExistingUSDPerHour *big.Rat | ||
| // GapUSDPerHour is TargetUSDPerHour - ExistingUSDPerHour. nil when either | ||
| // input is nil. | ||
| GapUSDPerHour *big.Rat | ||
| Actions []PlannedAction | ||
| Baseline UsageBaseline | ||
| } | ||
|
|
||
| // Validate checks that the plan is self-consistent: a valid scope, a set | ||
| // generation timestamp, and all PlannedActions valid. | ||
| func (p *LadderPlan) Validate() error { | ||
| if err := p.Scope.Validate(); err != nil { | ||
| return fmt.Errorf("scope: %w", err) | ||
| } | ||
| // A zero GeneratedAt would corrupt approval-expiry and audit ordering | ||
| // downstream; fail loud like Tranche.FireAfter. | ||
| if p.GeneratedAt.IsZero() { | ||
| return fmt.Errorf("generated_at must be set") | ||
| } | ||
| for i, a := range p.Actions { | ||
| if err := a.Validate(); err != nil { | ||
| return fmt.Errorf("action[%d]: %w", i, err) | ||
| } | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| // sanitizeLine strips control characters (including \n and \r) from a value | ||
| // interpolated into a single Explain line. Without this, a crafted field | ||
| // (e.g. a Rationale containing "\n 2. fake action") could spoof extra lines | ||
| // in the approval email body. | ||
| func sanitizeLine(s string) string { | ||
| return strings.Map(func(r rune) rune { | ||
| if unicode.IsControl(r) { | ||
| return -1 | ||
| } | ||
| return r | ||
| }, s) | ||
| } | ||
|
|
||
| // formatUSDPerHour renders a *big.Rat as a fixed 2-decimal USD/hr string. | ||
| // nil is rendered as "unknown" -- never as "$0.00" -- to unambiguously | ||
| // distinguish absent data from a genuine zero commitment (project rule: | ||
| // absent numbers are nil, not zero). | ||
| // | ||
| // FloatString(2) formats the exact rational with half-away-from-zero | ||
| // rounding, avoiding the float64 conversion step (e.g. 199/200 renders as | ||
| // $1.00/hr, not $0.99/hr). | ||
| func formatUSDPerHour(v *big.Rat) string { | ||
| if v == nil { | ||
| return "unknown" | ||
| } | ||
| return fmt.Sprintf("$%s/hr", v.FloatString(2)) | ||
| } | ||
|
|
||
| // Explain returns a deterministic, human-readable multi-line summary of the | ||
| // plan. The output is suitable for use as an approval email body and is | ||
| // designed to be read by a non-technical budget owner. | ||
| // | ||
| // Layout: | ||
| // 1. Scope header and generation timestamp | ||
| // 2. Baseline parameters (lookback window, percentile) | ||
| // 3. Target / existing / gap hourly rates | ||
| // 4. Numbered action list (or "none") | ||
| // 5. "Data sources:" line aggregating the actions' DataSources (omitted | ||
| // when no action carries any) | ||
| // | ||
| // Every interpolated free-form field is passed through sanitizeLine so a | ||
| // crafted value cannot spoof additional lines in the email body. | ||
| func (p *LadderPlan) Explain() string { | ||
| var b strings.Builder | ||
|
|
||
| fmt.Fprintf(&b, "Scope: provider=%s account=%s\n", p.Scope.Provider, sanitizeLine(p.Scope.AccountID)) | ||
| fmt.Fprintf(&b, "Generated: %s\n", p.GeneratedAt.UTC().Format(time.RFC3339)) | ||
| fmt.Fprintf(&b, "Baseline: lookback=%dd percentile=%g\n", | ||
| p.Baseline.LookbackDays, p.Baseline.Percentile) | ||
| fmt.Fprintf(&b, "Target: %s\n", formatUSDPerHour(p.TargetUSDPerHour)) | ||
| fmt.Fprintf(&b, "Existing: %s\n", formatUSDPerHour(p.ExistingUSDPerHour)) | ||
| fmt.Fprintf(&b, "Gap: %s\n", formatUSDPerHour(p.GapUSDPerHour)) | ||
|
|
||
| if len(p.Actions) == 0 { | ||
| fmt.Fprintf(&b, "Actions: none\n") | ||
| return b.String() | ||
| } | ||
|
|
||
| fmt.Fprintf(&b, "Actions (%d):\n", len(p.Actions)) | ||
| for i, a := range p.Actions { | ||
| switch a.Action { | ||
| case ActionPurchase: | ||
| fmt.Fprintf(&b, " %d. %s %s %s term=%s payment=%s -- %s\n", | ||
| i+1, a.Action, a.Layer, formatUSDPerHour(a.AmountUSDPerHour), | ||
| sanitizeLine(string(a.Term)), sanitizeLine(string(a.PaymentOption)), | ||
| sanitizeLine(a.Rationale)) | ||
| default: | ||
| fmt.Fprintf(&b, " %d. %s %s -- %s\n", | ||
| i+1, a.Action, a.Layer, sanitizeLine(a.Rationale)) | ||
| } | ||
| } | ||
| if sources := collectDataSources(p.Actions); len(sources) > 0 { | ||
| fmt.Fprintf(&b, "Data sources: %s\n", strings.Join(sources, ", ")) | ||
| } | ||
| return b.String() | ||
| } | ||
|
|
||
| // collectDataSources aggregates the DataSources of all actions, sanitized | ||
| // and deduplicated, preserving first-seen stored order so the output stays | ||
| // deterministic for a given plan. | ||
| func collectDataSources(actions []PlannedAction) []string { | ||
| var sources []string | ||
| seen := make(map[string]bool) | ||
| for _, a := range actions { | ||
| for _, s := range a.DataSources { | ||
| s = sanitizeLine(s) | ||
| if seen[s] { | ||
| continue | ||
| } | ||
| seen[s] = true | ||
| sources = append(sources, s) | ||
| } | ||
| } | ||
| return sources | ||
| } | ||
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.
Uh oh!
There was an error while loading. Please reload this page.