Documentation
¶
Overview ¶
Package policy decides the check's conclusion. It evaluates the built-in Rego pack over one run's rows and the settings that costroid.yml states at the base commit, under a capabilities file that admits no network and no clock.
Index ¶
- Constants
- func ApprovalKeys() []string
- func BaseHead(ctx context.Context, branches Branches, branch string) (string, error)
- func Keys() []string
- func PackSHA256() string
- func WorkflowPath(workflowRef, repository string) (string, error)
- type ApprovalSettings
- type Baseline
- type Branches
- type Commits
- type ConfigFile
- type ConfigState
- type CurrencyUsage
- type Evidence
- type FileReader
- type History
- type LedgerLine
- type LedgerRequest
- type Lifetime
- type Request
- type Result
- type Settings
- type Start
- type Trust
- type Usage
- type Verdict
- type WarnOnly
Constants ¶
const ( PeriodRunning = "in_period" PeriodEnded = "ended" PeriodEnforced = "enforced" PeriodNotOnBase = "not_on_base" PeriodStartUnknown = "start_unknown" )
The reasons the warn-only period is or is not running.
const ( Success = "success" Neutral = "neutral" Failure = "failure" )
The conclusions a check takes.
const ( RuleRunBudget = "run_budget" RuleRunCostThreshold = "run_cost_threshold" RuleRunIncrease = "run_increase" RuleRunIncreasePercent = "run_increase_percent" RulePullRequestBudget = "pr_budget" RuleMonthlyBudget = "monthly_budget" RuleModelAllowlist = "model_allowlist" RuleAttribution = "attribution" )
The rules of the default pack, in the order a verdict lists them.
const ( Pass = "pass" Warn = "warn" Fail = "fail" Unproven = "unproven" )
The outcomes of a rule.
const ( ReasonOverLimit = "over_limit" ReasonWithinLimit = "within_limit" ReasonNoRows = "no_rows" ReasonUnverifiedRows = "unverified_rows" ReasonUnattributedRows = "unattributed_rows" ReasonOtherCurrency = "other_currency" ReasonJoinableRows = "joinable_rows" ReasonOverBaseline = "over_baseline" ReasonNoBaseline = "no_baseline" ReasonNoLifetime = "no_lifetime" ReasonRepeatPossible = "repeat_possible" ReasonNoLedger = "no_ledger" ReasonOutsideAllowlist = "model_outside_allowlist" ReasonUnreadableModel = "unreadable_model" ReasonOnAllowlist = "models_on_allowlist" // ReasonUnmeasuredSpend is a budget or the model allowlist held by // token-verified rows whose spend only the agent's job counted. ReasonUnmeasuredSpend = "unmeasured_spend" // ReasonNoRunRows is a run rule asked of a ledger, whose answer covers the // pull request and not one run. ReasonNoRunRows = "no_run_rows" )
The reasons a rule gives.
const ConfigPath = "costroid.yml"
ConfigPath is where a repository keeps its settings.
const ( // DefaultApprovalDays is how long an approval lasts when expires_days is // not set. DefaultApprovalDays = 7 )
The keys under approval, and the bounds of approval.expires_days.
const MinBaselineRuns = 10
MinBaselineRuns is the fewest earlier runs a baseline is read from before a rule holds a run to it.
const WarnOnlyPeriod = 7 * 24 * time.Hour
WarnOnlyPeriod is how long after the workflow reached the base branch a rule that fails warns instead.
const WarnOnlyPullRequests = 20
WarnOnlyPullRequests is how many pull requests with a measured cost end the warn-only period, if its 7 days have not ended it first.
Variables ¶
This section is empty.
Functions ¶
func ApprovalKeys ¶
func ApprovalKeys() []string
ApprovalKeys are the keys under approval that ParseApproval reads, sorted.
func BaseHead ¶
BaseHead reads the commit at the head of a pull request's base branch, where costroid.yml and the workflow's history are read. GitHub's event names the merge-base as the base commit, and so does GitLab's diff base. It moves only when the pull request updates, so a setting changed on the branch since then would not apply.
func WorkflowPath ¶
WorkflowPath reads the workflow file from GITHUB_WORKFLOW_REF, which names owner/name/path@ref.
Types ¶
type ApprovalSettings ¶
type ApprovalSettings struct {
// AllowAuthor lets a pull request's author approve it.
AllowAuthor bool
// ExpiresDays is how many days a review approves for.
ExpiresDays int
}
ApprovalSettings are the approval keys of costroid.yml.
func ParseApproval ¶
func ParseApproval(data []byte) (ApprovalSettings, error)
ParseApproval reads the approval mapping of costroid.yml. Without it, the author cannot approve and an approval lasts DefaultApprovalDays. Any key or value under it that the schema refuses is an error, so a typo never widens who can approve.
type Baseline ¶
type Baseline struct {
// Runs counts the earlier runs the median was read from.
Runs int
// MedianUSD is the median of their USD totals. It is never negative.
MedianUSD decimal.Decimal
// Trust is who vouches for those runs' rows. Only a token-verified
// baseline can show that a run stayed within it.
Trust Trust
}
Baseline is what this agent's earlier runs on the repository cost, in USD.
type Branches ¶
Branches resolves a branch to the commit at its head. scm.GitHub and scm.GitLab are ones.
type Commits ¶
Commits names what one report is about: a pull request's base and head, or a push's head alone.
type ConfigFile ¶
type ConfigFile struct {
Data []byte
Found bool
// Ref is the commit the file was read at, empty offline.
Ref string
// FromBase says Ref is a pull request's base, not its head.
FromBase bool
// Unread is why the file could not be read, nil when it was.
Unread error
}
ConfigFile is costroid.yml as one commit holds it.
func ConfigFromFile ¶
func ConfigFromFile(path string) ConfigFile
ConfigFromFile reads costroid.yml from a path, as costroid policy does. A missing file is the defaults.
func ReadConfig ¶
func ReadConfig(ctx context.Context, files FileReader, commits Commits) ConfigFile
ReadConfig reads costroid.yml at a pull request's base, never its head, so a pull request cannot change its own verdict. A push has only its head. A failed read is kept in Unread.
type ConfigState ¶
type ConfigState string
ConfigState says what became of costroid.yml.
const ( ConfigFound ConfigState = "found" ConfigAbsent ConfigState = "absent" ConfigInvalid ConfigState = "invalid" ConfigUnread ConfigState = "unread" )
The states of the settings file.
type CurrencyUsage ¶
type CurrencyUsage struct {
Currency string
ListCost decimal.Decimal
Rows int
// UnattributedRows never satisfy a budget rule.
UnattributedRows int
// JoinableRows are unattributed, and name a credential, a pull
// request and a head commit, so a token-verified join would grade them
// exact.
JoinableRows int
// Models counts the rows that name each model in their costroid/model
// tag.
Models map[string]int
// UnreadableModels counts the rows whose costroid/model tag is absent,
// not a string, or not a model id.
UnreadableModels int
}
CurrencyUsage is the rows of one currency. ListCost is their exact sum, and no sum spans two currencies.
type Evidence ¶
type Evidence string
Evidence says what vouches for the spend on rows a ledger checked against a CI token. The token proves which run sent the rows. The token counts on them still come from the agent's job, so they are agent counts until the gateway's own count or a provider's report stands behind them.
const ( // AgentCounts is the counts the agent's job sent, and nothing else. AgentCounts Evidence = "agent_counts" // GatewayMeasured is the gateway's own count for keys attested as minted // for the rows' runs, as costroid gateway close attested it. GatewayMeasured Evidence = "gateway_measured" // Reconciled is a provider's report. Reconciled Evidence = "reconciled" )
The kinds of evidence for a token-verified run's spend.
type FileReader ¶
FileReader reads a file at a commit. A missing file is scm.ErrNotFound.
type LedgerLine ¶
type LedgerLine struct {
Currency string
ListCost decimal.Decimal
Rows int64
// Model is the rows' model, empty when they state none.
Model string
// Verified says the ledger checked the rows' run identity against the
// job's CI token.
Verified bool
// Attributed says the ledger tied the rows to their run, windowed or
// exact.
Attributed bool
}
LedgerLine is a group of one pull request's rows as a ledger holds them.
type LedgerRequest ¶
type LedgerRequest struct {
Lines []LedgerLine
Evidence Evidence
// MeasuredUSD is the gateway's own count for the pull request's keys. It
// is read only with GatewayMeasured, and pr_budget is then held to the
// larger of it and the rows' USD list cost.
MeasuredUSD decimal.Decimal
Config ConfigFile
Start Start
MeasuredPullRequests int
At time.Time
}
LedgerRequest is what costroid serve reads for one pull request. The ledger holds the rows. The caller states what serve cannot read: the settings at the base commit, the warn-only period's start and the count of measured pull requests.
type Lifetime ¶
type Lifetime struct {
// USD is the earlier runs' USD total over every cost basis. It is never
// negative.
USD decimal.Decimal
// OtherCurrency says an earlier run recorded an amount in another
// currency, which USD leaves out.
OtherCurrency bool
// MayRepeat says a report may be counted twice, so USD can read high.
MayRepeat bool
// Trust is who vouches for those runs' rows. Only a token-verified
// lifetime can show that a pull request stayed within its budget.
Trust Trust
}
Lifetime is what the pull request's earlier runs cost, as their reports recorded it. It leaves out the run the check is about.
type Request ¶
type Request struct {
Usage Usage
Trust Trust
Config ConfigFile
Start Start
At time.Time
// Baseline is what earlier runs of the agent cost. Nil, the increase
// rules cannot run.
Baseline *Baseline
// Lifetime is what the pull request's earlier runs cost. Nil, the pull
// request budget cannot run.
Lifetime *Lifetime
// MeasuredPullRequests counts the repository's pull requests with a
// measured cost. At WarnOnlyPullRequests the warn-only period ends. A
// count can only end the period early, so an unverified one is safe.
MeasuredPullRequests int
// Evidence is what stands behind the spend of token-verified rows. Only
// GatewayMeasured and Reconciled let a budget rule or the model allowlist
// pass on them. Anything else reads as AgentCounts.
Evidence Evidence
}
Request is everything one evaluation reads. The pack reads no clock, so At is the time of the check.
type Result ¶
type Result struct {
Rule string `json:"rule"`
Outcome string `json:"outcome"`
Reason string `json:"reason"`
HeldByWarnOnly bool `json:"held_by_warn_only,omitempty"`
LimitUSD string `json:"limit_usd,omitempty"`
// LimitPercent is the increase over the baseline a run may reach, in
// percent.
LimitPercent string `json:"limit_percent,omitempty"`
// CostUSD is the run's USD cost, or the pull request's for pr_budget.
CostUSD string `json:"cost_usd,omitempty"`
// BaselineUSD is the median the increase rules compare the run with.
BaselineUSD string `json:"baseline_usd,omitempty"`
// Models names the models off the allowlist, sorted, at most 10.
Models []string `json:"models,omitempty"`
}
Result is one rule's outcome. LimitUSD, CostUSD and BaselineUSD are amounts, so a comment that withholds amounts drops them.
type Settings ¶
type Settings struct {
// Amounts holds each amount key that is set, by its name in costroid.yml.
Amounts map[string]decimal.Decimal
// Models are the models a run may use: exact ids, or prefixes that end in
// *. Empty when the key is not set.
Models []string
// Enforce ends the warn-only period early.
Enforce bool
}
Settings are the policy keys of costroid.yml. A key that is not set is a rule that does not run.
func ParseSettings ¶
ParseSettings reads the policy mapping of costroid.yml. Any key or value under it that the schema refuses is an error, so a typo never runs a rule on a default. A policy key with no value sets no rule, as an absent one does. Keys outside it are not the policy's to judge.
type Start ¶
type Start struct {
// At is zero when the commit could not be read.
At time.Time
// NotOnBase says the base branch holds no such commit yet, as on the pull
// request that adds the workflow.
NotOnBase bool
}
Start is when the warn-only period began: the time of the oldest commit on the base branch that touched the workflow file.
type Usage ¶
type Usage struct {
Rows int
Currencies []CurrencyUsage
}
Usage is one run's rows, reduced to what the pack reads.
type Verdict ¶
type Verdict struct {
Conclusion string `json:"conclusion"`
Trust Trust `json:"trust"`
PackSHA256 string `json:"pack_sha256"`
// ConfigSHA256 hashes the costroid.yml bytes read. A missing file hashes
// as zero bytes.
ConfigSHA256 string `json:"config_sha256"`
ConfigRef string `json:"config_ref,omitempty"`
Config ConfigState `json:"config"`
// ConfigFromBase says the settings are a pull request's base commit's, so
// a change the pull request makes to them waits for the merge.
ConfigFromBase bool `json:"config_from_base"`
EvaluatedAt string `json:"evaluated_at"`
WarnOnly WarnOnly `json:"warn_only"`
Results []Result `json:"results"`
// JoinableRows counts the rows the attribution rule names.
JoinableRows int `json:"joinable_rows"`
// Evidence is what vouched for the spend of token-verified rows, as a
// ledger states it. A verdict on rows the agent's job wrote states none,
// and so does one from Evaluate.
Evidence Evidence `json:"evidence,omitempty"`
// contains filtered or unexported fields
}
Verdict is the pack's answer and what it was computed from.
func Evaluate ¶
Evaluate runs the default pack. Settings that cannot be read run no rule and conclude neutral, and the verdict says why. On token-verified rows a budget rule or the model allowlist passes only on the evidence the request states. The error is for a pack that could not run.
func EvaluateLedger ¶
func EvaluateLedger(ctx context.Context, request LedgerRequest) (Verdict, error)
EvaluateLedger runs the default pack over a pull request's rows in a ledger. The rows are token-verified only when every line is. Their spend is agent counts unless the request says it was measured or reconciled, and only then can a budget rule or the model allowlist pass. The answer covers the whole pull request, so the rules that read one run's rows conclude unproven.
func (Verdict) ConfigProblem ¶
ConfigProblem says why the settings could not be used, nil when they were.
func (Verdict) WithoutAmounts ¶
WithoutAmounts returns the verdict with every amount dropped.