ladder

package
v0.0.0-...-519451a Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 1, 2026 License: OSL-3.0 Imports: 9 Imported by: 2 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package ladder defines the types, interfaces, and plan rendering for the commitment-laddering engine. This package contains the public contract only; the allocation algorithm and provider implementations live in internal/ and providers/ respectively.

Index

Constants

View Source
const (
	Term1Year             = common.Term1Year
	Term3Year             = common.Term3Year
	PaymentAllUpfront     = common.PaymentAllUpfront
	PaymentPartialUpfront = common.PaymentPartialUpfront
	PaymentNoUpfront      = common.PaymentNoUpfront
)
View Source
const (
	// DefaultTargetCoveragePct is the percentage of on-demand spend to cover
	// with commitments when no explicit target is configured.
	DefaultTargetCoveragePct = 100.0

	// DefaultBufferFraction is the share of the base allocation reserved in
	// short-term or convertible buffer commitments that can be reshaped as
	// usage patterns shift.
	DefaultBufferFraction = 0.10

	// DefaultBaselinePercentile is the usage percentile used to anchor the
	// base commitment layer. A low percentile guards against over-committing
	// on volatile workloads.
	DefaultBaselinePercentile = 5.0

	// DefaultLookbackDays is the historical window (in days) used to compute
	// the usage baseline when none is specified.
	DefaultLookbackDays = 30

	// DefaultBufferUtilizationThresholdPct is the buffer-layer utilization
	// percentage below which the engine emits a reshape recommendation.
	// A value of 90 means reshape when commitments are less than 90% utilized.
	DefaultBufferUtilizationThresholdPct = 90.0
)

Default configuration constants. Every default is named and documented so callers can reference the symbolic name in code rather than bare literals.

Variables

View Source
var (
	ParseTerm          = common.ParseTerm
	ParsePaymentOption = common.ParsePaymentOption
)

Functions

func RequireCap

func RequireCap(name string, capUSD *float64) (float64, error)

RequireCap validates a required money cap and returns it as a float64. nil is rejected: the caller must set an explicit cap, so an omitted field can never mean unlimited spend. Values must be finite and > 0 (a zero cap would block every exchange).

Types

type ActionType

type ActionType string

ActionType describes what a PlannedAction will do.

const (
	ActionPurchase ActionType = "purchase"
	ActionReshape  ActionType = "reshape"
	ActionHold     ActionType = "hold"
)

func ParseActionType

func ParseActionType(s string) (ActionType, error)

ParseActionType converts s into an ActionType, returning a descriptive error when s is not a recognized value.

func (ActionType) Validate

func (a ActionType) Validate() error

Validate returns an error when a is not a recognized ActionType.

type AllocateResult

type AllocateResult struct {
	NetExistingUSDPerHour *big.Rat
	Allocations           []Allocation
	Reshapes              []PlannedAction
	Holds                 []PlannedAction
}

AllocateResult is the output of Allocate.

Allocations may be accompanied by informational Holds (e.g. "buffer utilization unknown; reshape not evaluated", or a sub-minimum split amount that was skipped) and by Reshapes for under-utilized buffer layers. Reshapes are detected independently of the purchase gap, so they can appear alongside an early-exit Hold (baseline unavailable, target met). A run is a no-op if and only if Allocations and Reshapes are both empty (see IsNoOp); in that case Holds carries the explanation (baseline unavailable, gap below the minimum threshold, or every split amount below the minimum).

NetExistingUSDPerHour is the net existing commitment E that Allocate sized the gap against: the sum over layers of ExistingUSDPerHour minus ExpiringUSDPerHour, in the same on-demand-equivalent USD/hr unit as the inputs. It is set on every successful result, including the hold-only early exits, so callers report the figure the engine used instead of recomputing a gross one from the layer states.

func Allocate

func Allocate(in *AllocationInput) (*AllocateResult, error)

Allocate determines how much new commitment to place on each layer for one ladder scope run. All monetary values are computed in exact *big.Rat arithmetic; float64 inputs are converted at the boundary via ratFromFloat.

Steps (see inline comments):

  1. Validate config, layers (enums + topology), and layer states, then compute net existing commitment (reported on every result as NetExistingUSDPerHour; an inconsistent snapshot is an error even when the baseline is unavailable).
  2. Detect under-utilized buffer layers (reshape, or informational hold when utilization is unknown on a non-empty buffer layer). This runs INDEPENDENTLY of the purchase gap: an over-committed account is exactly when reshaping matters, so the early no-purchase exits below must not mask it. Reshape detection needs only valid layer states.
  3. Nil baseline -> Hold (explainable no-op, not an error), plus any buffer maintenance from step 2.
  4. Compute net existing per layer; derive gap (existing is not subtracted from a residual baseline, which already excludes it; see BaselineBasis).
  5. Gap <= minimum threshold -> Hold with numbers in rationale, plus any buffer maintenance from step 2. A residual baseline with a partial target and existing commitment is held (the gap needs the covered usage the residual excludes).
  6. Split the OD gap across base, flex, and buffer roles, then convert each allocation to commitment dollars with its layer's rate (a layer without a rate is held, never bought 1:1).
  7. Apply per-run spend cap (proportional scaling, in commitment dollars), then drop sub-minimum allocations with an informational hold each (never silently lost).
  8. Truncate to MaxActionsPerRun: sort purchases by GapUSDPerHour descending, keep the largest, emit one ActionHold per dropped action for auditability (reshapes are always retained first; no truncated money action is silently lost).

func (*AllocateResult) IsNoOp

func (r *AllocateResult) IsNoOp() bool

IsNoOp reports whether the result proposes no state-changing actions: no allocations to purchase and no buffer reshapes. Informational Holds do not affect no-op status.

type Allocation

type Allocation struct {
	Layer LayerType
	// Family is the instance family a family-bound commitment is bought for
	// (EC2 Instance Savings Plan). Empty means the allocation is not family
	// bound, which is every layer other than LayerEC2InstanceSP.
	Family        string
	GapUSDPerHour *big.Rat
	// OnDemandEquivalentUSDPerHour is the on-demand-priced usage this
	// commitment covers; the unit of target/existing/gap in plan displays.
	OnDemandEquivalentUSDPerHour *big.Rat
	// Rate is the commitment rate applied (commitment per OD dollar), in (0, 1].
	Rate        *big.Rat
	Rationale   string
	DataSources []string
}

Allocation is a per-layer sizing decision produced by Allocate. GapUSDPerHour is the positive hourly COMMITMENT delta this layer should grow by (what is bought and stored in tranches); it equals OnDemandEquivalentUSDPerHour * Rate, exactly. The purchase boundary must round it DOWN to the provider's commitment precision, never up. Ramp and tranche logic (BuildTranches) converts Allocations into time-indexed purchase tranches.

type AllocationInput

type AllocationInput struct {
	Now             time.Time
	LayerStates     map[LayerType]LayerState
	CommitmentRates map[LayerType]float64
	Layers          []LayerSpec
	DataSources     []string
	InFlight        []InFlightTranche
	Baseline        UsageBaseline
	Config          LadderConfig
}

AllocationInput carries everything Allocate needs. All provider data must be pre-fetched by the caller; Allocate performs no I/O.

Contract on LayerStates: for every LayerSpec in Layers, LayerStates must contain an entry whose ExistingUSDPerHour and ExpiringUSDPerHour are both non-nil. Providers must supply an explicit zero rather than a nil pointer when a field is genuinely zero; a nil pointer is treated as missing data and causes Allocate to return an error (fail loud: incomplete provider data aborts the run).

Units (go#349): Baseline, LayerStates and the gap are on-demand-equivalent (OD) USD/hr. InFlight and everything Allocate returns as GapUSDPerHour are commitment USD/hr (what is actually bought). CommitmentRates bridges them.

InFlight is the commitment already in flight for this config's scope: its scheduled (not-yet-fired) ladder tranches ONLY, each with the rate stored when it was planned. Fired/completed tranches are deliberately excluded because they are executed purchases already reflected in each layer's ExistingUSDPerHour; counting them here as well would double-subtract and under-purchase. Allocate converts each tranche back to OD (commitment / rate) before netting, so an OD figure and a commitment figure are never mixed. It is required non-nil (fail loud): callers must always explicitly account for in-flight commitment; pass an empty non-nil slice for none. Subtracting in-flight from the gap prevents new runs from re-planning commitment that is already scheduled. For a residual baseline InFlight must also cover active commitment not yet reflected in the observed series (see BaselineBasis).

CommitmentRates holds, per layer, the commitment dollars needed per OD dollar covered for a NEW purchase (in (0, 1]). It is required non-nil and may be partial: a layer that would receive an allocation but has no rate is held with an explanation (never bought 1:1, never re-routed to another layer). A present value outside (0, 1] or non-finite is an error.

DataSources lists the data feeds (e.g. "cost-explorer", "cloudwatch") used to derive the inputs. The slice is propagated verbatim to every Allocation and PlannedAction produced by Allocate so that approval emails and audit logs identify the source of each decision.

Now must be set by the caller; Allocate never calls time.Now internally.

type BaselineBasis

type BaselineBasis string

BaselineBasis says what a UsageBaseline series measures (go#282).

A total baseline (BaselineBasisTotal, or the empty legacy value) is all eligible on-demand-equivalent demand, covered or not; Allocate nets the existing commitment out of it: gap = min(target, low_water) - existing.

A residual baseline (BaselineBasisResidual) is only the usage that existing commitments left uncovered, so existing coverage is already excluded. Subtracting existing commitment from it again under-buys and can claim "target already met" while usage is still uncovered. For a residual baseline Allocate sizes:

gap = low_water * target_pct/100 - in_flight

which never exceeds the observed residual. With target_pct = 100 this is the exact remaining gap. Below 100 the true gap is pct*(C+R) - C, where C is the covered usage the residual excludes; it is at most pct*R, but it cannot be sized without C, so when any layer holds existing commitment the run is held rather than guessed (see residualPartialTargetHold). With no existing commitment in any layer the residual and total bases coincide.

Expiring commitment is not added back for a residual baseline: its coverage is still in effect during the observed window, and converting native commitment dollars to the usage it covers needs rates the engine does not have. Usage that becomes uncovered after expiry shows up in later residual observations (a later top-up, never an over-buy).

InFlight contract for a residual baseline: the series only reflects commitments whose coverage was already observed. Callers must include in InFlight every commitment that is active but not yet reflected in the series (for example one bought after the last observed day, given cost-data reporting lag), or Allocate re-plans it.

const (
	// BaselineBasisTotal marks a series of total eligible on-demand-equivalent
	// demand (covered plus uncovered). The empty value means the same.
	BaselineBasisTotal BaselineBasis = "total"
	// BaselineBasisResidual marks a series of usage left uncovered by existing
	// commitments (already net of them).
	BaselineBasisResidual BaselineBasis = "residual"
)

func (BaselineBasis) Validate

func (b BaselineBasis) Validate() error

Validate rejects an unrecognized basis: guessing one would either double-subtract existing commitment or skip netting it.

type BufferReshapeConfig

type BufferReshapeConfig struct {
	// MaxPaymentPerExchangeUSD caps the payment for a single exchange. It is
	// required: nil is an error, never "no cap" (reshape executes exchanges
	// immediately, so an omitted cap must not mean unlimited spend).
	MaxPaymentPerExchangeUSD *float64
	// MaxPaymentDailyUSD caps the total exchange payments for the current day.
	// It is required on the same terms as MaxPaymentPerExchangeUSD.
	MaxPaymentDailyUSD *float64
	// LadderRunID links the exchange records this reshape creates to the ladder
	// run that triggered it, so the exchange layer scopes its pending
	// cancellation to this origin (ladder) instead of the standalone task's
	// pendings (gap G10 / issue #1348). Nil means "no ladder run" (the caller is
	// not a ladder run); the reshape runner then behaves as the standalone
	// origin. The concrete runner (wired in L16) MUST forward this to
	// exchange.RunAutoExchangeParams.LadderRunID — the exchangeRunner seam
	// requires it so a future runner cannot silently drop it and reintroduce the
	// cross-origin cancellation bug.
	LadderRunID *string
	// 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
}

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 CommitmentRateCapability

type CommitmentRateCapability interface {
	GetCommitmentRates(context.Context, Scope, Term, PaymentOption) (map[LayerType]float64, error)
}

CommitmentRateCapability optionally supplies new-purchase commitment dollars per covered on-demand dollar. Missing layers in the partial map are intentional.

type InFlightTranche

type InFlightTranche struct {
	Layer LayerType
	// Family is the instance family of an EC2 Instance SP tranche (Tranche.Family);
	// empty for other layers and for tranches stored before the family dimension.
	Family               string
	CommitmentUSDPerHour float64
	// Rate is the commitment rate stored with the tranche. Required in (0, 1];
	// a tranche without a valid rate is a data error, never treated as 1:1.
	Rate float64
}

InFlightTranche is a scheduled (not-yet-fired) ladder tranche in commitment USD/hr together with the rate that was stored with it when it was planned. Allocate converts it back to OD with that rate (od = commitment / Rate), so a tranche is netted at the rate it was sized with, not at today's.

type LadderCadence

type LadderCadence string

LadderCadence controls how often the ladder engine runs.

const (
	CadenceDaily  LadderCadence = "daily"
	CadenceWeekly LadderCadence = "weekly"
)

func ParseLadderCadence

func ParseLadderCadence(s string) (LadderCadence, error)

ParseLadderCadence converts s into a LadderCadence, returning a descriptive error when s is not a recognized value.

func (LadderCadence) Validate

func (c LadderCadence) Validate() error

Validate returns an error when c is not a recognized LadderCadence.

type LadderCapability

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. A
	// provider whose series counts only usage left uncovered by existing
	// commitments must set Basis to BaselineBasisResidual.
	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.
	//
	// Provider commitment precision (go#354): implementations MUST floor the
	// commitment to the provider's precision before submission, never round
	// it up, and MUST refuse (not submit) an amount outside the provider's
	// accepted range, including one that floors to zero. Callers converting
	// a *big.Rat amount to float64 must not round it up either.
	//   - AWS Savings Plans: the raw amount is range-checked first (outside
	//     [0.001, 1000000] USD/hr, NaN, Inf or <= 0 is refused before any
	//     API call), then truncated to 5 decimal places.
	//   - AWS convertible RIs: purchased as a whole instance count
	//     (rec.Count > 0), so there is no dollar amount to floor.
	//   - Azure, GCP: no LadderCapability implementation yet; each must
	//     document and enforce its precision here when one is added.
	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)
}

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.

type LadderConfig

type LadderConfig struct {
	Scope   Scope
	Mode    LadderMode
	Cadence LadderCadence
	// MaxHourlyCommitPerRun caps the total hourly commitment delta a single
	// run may purchase. nil means no cap is applied; when present the cap
	// must be positive (validated by Validate).
	MaxHourlyCommitPerRun *float64
	Ramp                  RampSchedule
	TargetCoveragePct     float64
	BufferFraction        float64
	BaselinePercentile    float64
	LookbackDays          int
	// MaxActionsPerRun limits how many PlannedActions the engine may execute
	// per run. Must be > 0.
	MaxActionsPerRun int
	// BufferUtilizationThresholdPct is the utilization percentage below which a
	// buffer layer is flagged for reshape. Must be in (0, 100]. Use
	// DefaultBufferUtilizationThresholdPct when no threshold is configured.
	BufferUtilizationThresholdPct float64
}

LadderConfig holds the full configuration for a single ladder scope run.

func (*LadderConfig) Validate

func (c *LadderConfig) Validate() error

Validate checks that all configuration fields are within valid ranges and all sub-types are well-formed. It returns a specific, descriptive error on any violation -- callers must not silently default away a validation failure.

type LadderMode

type LadderMode string

LadderMode controls whether ladder runs require human approval before executing purchases.

const (
	ModeEmailApproval LadderMode = "email_approval"
	ModeAutoApprove   LadderMode = "auto_approve"
)

func ParseLadderMode

func ParseLadderMode(s string) (LadderMode, error)

ParseLadderMode converts s into a LadderMode, returning a descriptive error when s is not a recognized value.

func (LadderMode) Validate

func (m LadderMode) Validate() error

Validate returns an error when m is not a recognized LadderMode.

type LadderPlan

type LadderPlan struct {
	Scope       Scope
	GeneratedAt time.Time
	// TargetUSDPerHour is the on-demand-equivalent USD/hr target derived from
	// Baseline * TargetCoveragePct. nil means it could not be computed.
	TargetUSDPerHour *big.Rat
	// ExistingUSDPerHour is the sum of on-demand-equivalent USD/hr 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. All three summary fields are on-demand-equivalent USD/hr.
	GapUSDPerHour *big.Rat
	Actions       []PlannedAction
	Baseline      UsageBaseline
}

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.

func BuildPlan

func BuildPlan(in *PlanInput) (*LadderPlan, error)

BuildPlan assembles the validated LadderPlan for one scope run from the Allocate and BuildTranches outputs.

Each immediate tranche (FireAfter equals Now) becomes one ActionPurchase whose amount is that tranche's own commitment USD/hr step, not the whole Allocation.GapUSDPerHour (the sum over every ramp step). The amount is pre-rounding: the purchase boundary still rounds it down to the provider's precision. Later tranches are scheduled rows persisted by the caller and are not actions. Tranches must be a fresh BuildTranches output: Status is not consulted, so a fired tranche whose FireAfter equals Now would look immediate. An allocation with no immediate tranche yields a hold that states when its first tranche fires, so an approver never reads "nothing" when a purchase is scheduled.

Actions are ordered purchases, reshapes, the Allocate holds, then the delayed-ramp holds, so Explain output is deterministic.

ExistingUSDPerHour is Result.NetExistingUSDPerHour (net of expiring). GapUSDPerHour is Target minus Existing, signed (negative means over target); it is a display figure, not Allocate's purchase sizing rule.

func (*LadderPlan) Explain

func (p *LadderPlan) Explain() string

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 (*LadderPlan) Validate

func (p *LadderPlan) Validate() error

Validate checks that the plan is self-consistent: a valid scope, a set generation timestamp, and all PlannedActions valid.

func (*LadderPlan) ValidateRunCaps

func (p *LadderPlan) ValidateRunCaps(cfg *LadderConfig) error

ValidateRunCaps checks an assembled plan against the per-run caps in cfg. Only the immediate purchases of this run count toward the hourly cap, since later tranches are scheduled rows, not spend. Purchases plus reshapes must not exceed MaxActionsPerRun; holds are audit rows and are not counted, as in truncateToMaxActions. Allocate enforces both caps on its own output, so this check guards plans built or mutated outside that path before they execute.

type LadderStore

type LadderStore interface {
	// SaveRun persists a new run record or updates an existing one (upsert by
	// ID).
	SaveRun(ctx context.Context, run *RunRecord) error

	// LatestRunStartedAt returns the CreatedAt timestamp of the most recent
	// run for the given scope, or nil when no run has been recorded yet.
	LatestRunStartedAt(ctx context.Context, scope Scope) (*time.Time, error)

	// SaveTranches persists a batch of tranches. Every tranche must carry a
	// non-empty RunID (Tranche.RunID is the single source of truth for run
	// linkage); implementations persist tranches exactly as given and must
	// not infer linkage from anything else. Tranches are fully
	// self-describing (Layer, AmountUSDPerHour, Term, PaymentOption):
	// executors must be able to fire a tranche as a purchase without any
	// RunRecord or PlanJSON lookup. Callers may call this multiple times
	// (e.g., once per ramp step) and implementations should upsert by
	// tranche ID.
	SaveTranches(ctx context.Context, tranches []Tranche) error
}

LadderStore is the storage contract for the ladder engine. The concrete implementation lives in internal/ (separate Go module) and is injected into the engine at startup; pkg/ defines only the interface.

type LayerRole

type LayerRole string

LayerRole describes the role a layer plays in the ladder allocation.

const (
	RoleBase   LayerRole = "base"
	RoleFlex   LayerRole = "flex"
	RoleBuffer LayerRole = "buffer"
)

func ParseLayerRole

func ParseLayerRole(s string) (LayerRole, error)

ParseLayerRole converts s into a LayerRole, returning a descriptive error when s is not a recognized value.

func (LayerRole) Validate

func (r LayerRole) Validate() error

Validate returns an error when r is not a recognized LayerRole.

type LayerSpec

type LayerSpec struct {
	Type  LayerType
	Roles []LayerRole
}

LayerSpec describes a layer and the roles it fulfills within the ladder. Azure reservations carry both base and buffer roles simultaneously.

type LayerState

type LayerState struct {
	// ExistingUSDPerHour may be native amortized commitment cost in provider
	// snapshots; callers must normalize it to on-demand-equivalent USD/hr for Allocate.
	ExistingUSDPerHour *float64
	// ExpiringUSDPerHour is the share of ExistingUSDPerHour whose commitments
	// expire within the current run cadence window; normalize to OD USD/hr for Allocate.
	ExpiringUSDPerHour *float64
	// CoveragePct is the percentage of eligible on-demand spend currently
	// covered by commitments in this layer.
	CoveragePct *float64
	// UtilizationPct is the current utilization percentage of commitments in
	// this layer.
	UtilizationPct *float64
	// Layer identifies which commitment layer this snapshot describes.
	Layer LayerType
}

LayerState is a point-in-time snapshot of an existing commitment layer. All monetary and percentage fields are pointers to distinguish "not yet measured" from "measured zero" (project rule: absent numbers are nil).

type LayerType

type LayerType string

LayerType identifies a commitment layer in the ladder hierarchy.

const (
	LayerEC2InstanceSP    LayerType = "ec2-instance-sp"
	LayerComputeSP        LayerType = "compute-sp"
	LayerConvertibleRI    LayerType = "convertible-ri"
	LayerAzureReservation LayerType = "azure-reservation"
	LayerAzureSavingsPlan LayerType = "azure-savings-plan"
)

func ParseLayerType

func ParseLayerType(s string) (LayerType, error)

ParseLayerType converts s into a LayerType, returning a descriptive error when s is not a recognized value. Use it to validate external input at the boundary instead of casting raw strings.

func (LayerType) Validate

func (l LayerType) Validate() error

Validate returns an error when l is not a recognized LayerType.

type ObservedCommitmentRateCapability

type ObservedCommitmentRateCapability interface {
	GetObservedCommitmentRates(context.Context, Scope) (map[LayerType]float64, error)
}

ObservedCommitmentRateCapability optionally supplies commitment dollars per covered on-demand dollar as measured on the account's existing commitments. Keys match CommitmentRateCapability. An absent key means no usable observation; every returned value is finite and in (0,1]. On error the map is nil. Observed rates do not depend on term or payment option.

type PaymentOption

type PaymentOption = common.PaymentOption

Term, PaymentOption and their parsers live in pkg/common; these aliases keep existing ladder callers compiling.

type PlanInput

type PlanInput struct {
	// Target is the on-demand-equivalent USD/hr coverage target. nil means it
	// could not be computed; the plan's gap is then nil too.
	Target *big.Rat
	// Result is the Allocate output the tranches were built from.
	Result *AllocateResult
	// Tranches is the BuildTranches output for Result.Allocations.
	Tranches *TrancheResult
	Scope    Scope
	Now      time.Time
	Baseline UsageBaseline
}

PlanInput carries the engine outputs BuildPlan assembles into a LadderPlan. BuildPlan performs no I/O and never calls time.Now.

Now must be the exact run clock the caller passed to BuildTranches: a tranche is "immediate" when its FireAfter equals Now.

type PlannedAction

type PlannedAction struct {
	Action ActionType
	Layer  LayerType
	// Family is the instance family a purchase is bound to; set only for
	// LayerEC2InstanceSP, empty otherwise.
	Family string
	// AmountUSDPerHour is the hourly commitment delta in commitment USD/hr
	// (not on-demand-equivalent). 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
}

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.

func (*PlannedAction) Validate

func (a *PlannedAction) Validate() error

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

type RampSchedule

type RampSchedule struct {
	Steps []RampStep `json:"steps"`
}

RampSchedule spreads commitment purchases across time-indexed tranches.

This type mirrors the semantic intent of internal/config/types.go RampSchedule (which uses a percent-per-step + interval model) but is defined independently because pkg/ and internal/ are separate Go modules and pkg/ cannot import internal/. See internal/config/types.go for the internal variant.

func (RampSchedule) Validate

func (r RampSchedule) Validate() error

Validate checks that the ramp schedule is well-formed:

  • at least one step
  • AfterDays values are strictly ascending
  • each fraction is in (0, 1]
  • fractions sum to 1.0 within rampSumEpsilon

type RampStep

type RampStep struct {
	// AfterDays is the number of days after the run starts at which this
	// tranche fires. Must be strictly greater than the previous step's
	// AfterDays (ascending order required by RampSchedule.Validate).
	AfterDays int `json:"after_days"`
	// Fraction is the share of the total target allocation committed by this
	// tranche. Must be in (0, 1]; fractions across all steps must sum to 1.0.
	Fraction float64 `json:"fraction"`
}

RampStep is a single tranche within a ramp schedule.

The json tags are load-bearing: the frontend sends and the DB stores this shape as snake_case (`{"after_days":N,"fraction":F}`). Without the tags Go's case-insensitive matching bridges `fraction`->Fraction but NOT `after_days`->AfterDays (the underscore breaks the match), so AfterDays would silently decode to 0 and multi-step ramps would fail RampSchedule.Validate (ascending-AfterDays) or collapse to fire at day 0.

type ReshapeSummary

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
}

ReshapeSummary reports the outcome of a buffer reshape operation.

type RunRecord

type RunRecord struct {
	ID          string
	Scope       Scope
	Status      RunStatus
	CreatedAt   time.Time
	CompletedAt *time.Time
	// PlanJSON holds a serialized LadderPlan for audit. Stored as a string
	// rather than an embedded struct so the store interface stays
	// serialization-format-agnostic.
	PlanJSON string
}

RunRecord is the persistent record of a single ladder engine run. IDs are strings to remain agnostic to the backing store's key scheme (UUID, ULID, etc.).

func (*RunRecord) Validate

func (r *RunRecord) Validate() error

Validate checks that the run record is self-consistent: non-empty ID, a valid scope, a set CreatedAt timestamp, recognized status, and a CompletedAt timestamp only when the status is terminal (a run still in flight cannot have completed).

type RunStatus

type RunStatus string

RunStatus is the lifecycle state of a ladder engine run.

const (
	RunStatusPlanned          RunStatus = "planned"
	RunStatusAwaitingApproval RunStatus = "awaiting_approval"
	RunStatusApproved         RunStatus = "approved"
	RunStatusExecuting        RunStatus = "executing"
	RunStatusCompleted        RunStatus = "completed"
	RunStatusFailed           RunStatus = "failed"
	RunStatusCanceled         RunStatus = "canceled"
	RunStatusExpired          RunStatus = "expired"

	// Deprecated: use RunStatusCanceled. Kept so existing callers compile; it
	// writes the new spelling.
	RunStatusCancelled = RunStatusCanceled
)

func ParseRunStatus

func ParseRunStatus(s string) (RunStatus, error)

ParseRunStatus converts s into a RunStatus, returning a descriptive error when s is not a recognized value. The legacy "cancelled" reads as RunStatusCanceled.

func (RunStatus) IsTerminal

func (s RunStatus) IsTerminal() bool

IsTerminal reports whether s is a terminal run status: RunStatusCompleted, RunStatusFailed, RunStatusCanceled (either spelling), or RunStatusExpired. Terminal runs are the only ones allowed to carry a CompletedAt timestamp (see RunRecord.Validate).

func (RunStatus) Validate

func (s RunStatus) Validate() error

Validate returns an error when s is not a recognized RunStatus.

type Scope

type Scope struct {
	Provider  common.ProviderType
	AccountID string
}

Scope identifies the ladder scope: a specific provider account or subscription that the ladder engine operates on.

Note: GCP scopes validate here, but no GCP LayerType exists yet, so every GCP run fails loud at layer validation until GCP layers land.

func (Scope) Validate

func (s Scope) Validate() error

Validate checks that the scope names a known provider and a non-empty account identifier. Called first by LadderConfig.Validate so a malformed scope fails loud before any other configuration check.

type Term

type Term = common.Term

Term, PaymentOption and their parsers live in pkg/common; these aliases keep existing ladder callers compiling.

type Tranche

type Tranche struct {
	// FireAfter is the wall-clock time at or after which this tranche fires.
	FireAfter time.Time
	// FiredAt is nil until the tranche actually fires.
	FiredAt *time.Time
	// AmountUSDPerHour is the hourly commitment delta for this tranche step,
	// in commitment USD/hr (the unit of Allocation.GapUSDPerHour, and what the
	// executor buys unchanged). Tranches persisted before go#349 are in the
	// old on-demand-equivalent unit and carry no CommitmentRate.
	// Validation requires any string that big.Rat.SetString parses as a
	// positive rational (e.g. "3/2", "1.5"); producers should emit the
	// canonical big.Rat.RatString() form, which is lossless and round-trips
	// through big.Rat.SetString without floating-point precision loss,
	// making it safe for DB persistence and rehydration.
	AmountUSDPerHour string
	ID               string
	RunID            string
	Status           TrancheStatus
	// Layer identifies the commitment layer this tranche purchases into.
	// Required so a fired tranche is executable without consulting the parent
	// run's plan.
	Layer LayerType
	// Family is the instance family the purchase is bound to; set only for
	// LayerEC2InstanceSP, empty otherwise. The executor must copy it to the
	// provider purchase request (an EC2 Instance Savings Plan is family bound).
	Family string
	// Term is the commitment term for the purchase (Term1Year or Term3Year).
	// Must pass Term.Validate: an unset or unknown term would silently
	// default at the provider boundary (money-shaping field, same rule as
	// PlannedAction.Term).
	Term Term
	// PaymentOption is the payment structure for the purchase (e.g.
	// PaymentNoUpfront). Must pass PaymentOption.Validate, for the same
	// reason as Term.
	PaymentOption PaymentOption
	// CommitmentRate is the commitment rate (commitment per on-demand dollar,
	// in (0, 1]) the amount was sized with, as a big.Rat string. Netting
	// divides AmountUSDPerHour by it to get back to on-demand-equivalent.
	// BuildTranches always sets it; empty only on rows persisted before
	// go#349, which must not be netted or executed. When set it must parse
	// into (0, 1].
	CommitmentRate string
	StepIndex      int
}

Tranche is one ramp step that has been persisted for scheduled firing.

A tranche is fully self-describing: Layer, AmountUSDPerHour, Term, and PaymentOption together specify the exact purchase to execute when the tranche fires. Executors must never need to reconstruct purchase parameters from the parent RunRecord's PlanJSON -- two allocations with equal gaps on different layers must remain distinguishable from the tranche row alone.

func (*Tranche) Validate

func (t *Tranche) Validate() error

Validate checks that the tranche is self-consistent: non-empty ID and RunID (RunID is the single source of run linkage, see LadderStore.SaveTranches), non-negative step index, a set FireAfter timestamp, complete purchase-execution fields (recognized Layer, an AmountUSDPerHour parsing as a positive rational, valid Term and PaymentOption enum values), recognized status, and a FiredAt timestamp only when the status implies the tranche fired.

type TrancheInput

type TrancheInput struct {
	// Config provides the ramp schedule and is re-validated by BuildTranches.
	Config *LadderConfig
	// RunID stamps every produced Tranche row for run linkage. Required.
	RunID string
	// Term is the commitment term (Term1Year or Term3Year) passed to each
	// buy-now purchase action and future tranche. The caller selects the
	// term; v1 uses a single term for all allocations. Must pass
	// Term.Validate.
	Term Term
	// PaymentOption is the payment structure (e.g. PaymentNoUpfront) passed
	// to each buy-now purchase action and future tranche. Must pass
	// PaymentOption.Validate.
	PaymentOption PaymentOption
	// NewID is called once per produced Tranche to assign a unique identifier.
	// Callers may inject a UUID function, a sequential counter, or any other
	// scheme. Must return a non-empty string on every call.
	NewID func() string
	// Now is the wall-clock time of the run. BuildTranches never calls
	// time.Now internally; callers inject the clock for testability and
	// audit-trail accuracy.
	Now time.Time
	// Allocations is the full set of per-layer sizing decisions from Allocate.
	// Each allocation is split across all ramp steps in the schedule.
	Allocations []Allocation
}

TrancheInput carries everything BuildTranches needs to turn a set of Allocations into immediate purchase actions and future ramp tranches. All time and ID generation is injected so BuildTranches is deterministic and free of hidden side effects.

type TrancheResult

type TrancheResult struct {
	// Tranches holds one scheduled row per non-zero ramp step, in step order
	// within each allocation. Each row has status TrancheStatusScheduled and
	// FireAfter = Now + AfterDays.
	Tranches []Tranche
}

TrancheResult is the output of BuildTranches.

Every non-zero ramp step becomes a Tranche, including the immediate (AfterDays == 0) step: its FireAfter equals TrancheInput.Now. Persisting the immediate step as a row is what lets in-flight netting see it; a buy-now amount that lives only in a plan would be neither netted nor executed. A fully-delayed ramp simply has no tranche with FireAfter == Now.

func BuildTranches

func BuildTranches(in *TrancheInput) (*TrancheResult, error)

BuildTranches turns each Allocation into one Tranche row per ramp step, staggered over the ramp schedule so commitment terms expire at different times instead of bunching. The AfterDays == 0 step fires at Now.

Step amounts are computed in exact big.Rat arithmetic. Every step amount is clamped to the remaining unallocated gap and the last step receives the exact leftover, so the total across all produced items reconstructs the gap exactly -- no cent lost, duplicated, or over-allocated -- for every schedule that passes RampSchedule.Validate, despite the binary-float representation of step fractions. Steps whose computed amount is zero (possible when the clamp floors a step after earlier fractions consumed the whole gap) are skipped entirely without affecting total exactness.

BuildTranches performs no I/O and never calls time.Now.

type TrancheStatus

type TrancheStatus string

TrancheStatus is the lifecycle state of a single ramp tranche.

const (
	TrancheStatusScheduled TrancheStatus = "scheduled"
	TrancheStatusFired     TrancheStatus = "fired"
	TrancheStatusCompleted TrancheStatus = "completed"
	TrancheStatusCanceled  TrancheStatus = "canceled"
	TrancheStatusFailed    TrancheStatus = "failed"

	// Deprecated: use TrancheStatusCanceled. Kept so existing callers compile;
	// it writes the new spelling.
	TrancheStatusCancelled = TrancheStatusCanceled
)

func ParseTrancheStatus

func ParseTrancheStatus(s string) (TrancheStatus, error)

ParseTrancheStatus converts s into a TrancheStatus, returning a descriptive error when s is not a recognized value. The legacy "cancelled" reads as TrancheStatusCanceled.

func (TrancheStatus) Validate

func (s TrancheStatus) Validate() error

Validate returns an error when s is not a recognized TrancheStatus.

type UsageBaseline

type UsageBaseline struct {
	// LowWaterUSDPerHour is the usage floor derived from the configured
	// percentile (e.g., the 5th percentile of hourly spend).
	LowWaterUSDPerHour *float64
	// StableUSDPerHour is the estimated stable portion after applying the
	// buffer fraction to LowWaterUSDPerHour. It is nil when the provider cannot
	// estimate it (short or volatile series, or no buffer fraction configured).
	StableUSDPerHour *float64
	// StableUSDPerHourByFamily splits StableUSDPerHour across EC2 instance
	// families (instance family name to absolute USD/hr). Allocate divides the
	// EC2 Instance Savings Plan base gap across these families by headroom (share
	// less that family's in-flight tranches), one family-bound allocation each.
	// Shares must be finite and >= 0 and sum to StableUSDPerHour (within float
	// rounding), which must then be non-nil; otherwise Allocate fails loud. Nil means the
	// base is not family split (the allocation carries no family), which a
	// provider whose base layer is family bound must not rely on.
	StableUSDPerHourByFamily map[string]float64
	// Basis says what the series measures: total demand (the default, empty)
	// or residual uncovered usage already net of existing commitments. See
	// BaselineBasis; Allocate never subtracts existing commitment from a
	// residual baseline a second time (go#282).
	Basis BaselineBasis
	// Series holds the raw hourly values used for computation. It is optional
	// and may be nil when only the summary statistics are needed (e.g., when
	// populating the approval email body).
	Series []float64
	// LookbackDays is the window (in days) over which the baseline was
	// computed.
	LookbackDays int
	// Percentile is the statistical percentile used for LowWaterUSDPerHour.
	Percentile float64
}

UsageBaseline is a statistical summary of recent on-demand usage used to size the base commitment layer. Every monetary field is a pointer to distinguish "absent" from "genuinely zero" (project rule: absent numbers are pointers/nil, never 0).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL