policy

package
v1.0.0-alpha.39 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2026 License: Apache-2.0 Imports: 32 Imported by: 0 modules, 0 packages

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 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

View Source
const (
	// RuleCustomerPack says why the pack costroid.yml names gave no results.
	RuleCustomerPack = "customer_pack"
	// ReasonPackUnread is a file that is absent or too large, or a host that
	// did not answer.
	ReasonPackUnread = "pack_unread"
	// ReasonPackInvalid is a module that does not compile under
	// capabilities.pack.json, declares another package, or names a result for
	// one of Costroid's rules.
	ReasonPackInvalid = "pack_invalid"
	// ReasonPackBound is an input, a count of steps, a time or a count of
	// results past its bound, or a child that ended without an answer.
	ReasonPackBound = "pack_bound"
	// ReasonPackResult is an answer that is not a list of results in the
	// pack's words.
	ReasonPackResult = "pack_result"
)

The rule of Costroid's own result on a pack that did not run to its end, and its reasons.

View Source
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.

View Source
const (
	Success = "success"
	Neutral = "neutral"
	Failure = "failure"
)

The conclusions a check takes.

View Source
const (
	RuleRunBudget          = "run_budget"
	RuleRunCostThreshold   = "run_cost_threshold"
	RuleRunIncrease        = "run_increase"
	RuleRunIncreasePercent = "run_increase_percent"
	// RuleRunP95 holds a run to a multiple of the P95 of this agent's latest
	// runs on merged pull requests.
	RuleRunP95            = "run_p95"
	RulePullRequestBudget = "pr_budget"
	RuleMonthlyBudget     = "monthly_budget"
	RuleModelAllowlist    = "model_allowlist"
	RuleAttribution       = "attribution"
)

The rules of the default pack, in the order a verdict lists them.

View Source
const (
	Pass     = "pass"
	Warn     = "warn"
	Fail     = "fail"
	Unproven = "unproven"
)

The outcomes of a rule.

View Source
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.

View Source
const (
	TagOrigin              = "costroid/origin"
	OriginDeveloperMachine = "developer_machine"
	OriginRecording        = "recording"
)

TagOrigin says what a row is when it is not a run's own row to send and store. OriginDeveloperMachine marks a row counted on a developer's own machine, whose session counts the developer stated in a receipt. OriginRecording marks a row of the recorded run costroid demo --out writes.

View Source
const BaselineWindow = 20

BaselineWindow is how many of an agent's latest runs with a cost in one currency a baseline reads. Twenty runs put the nearest-rank P95 on the 19th cost of 20, so one outlier does not set it, and the window is the twenty reports that end the warn-only period.

View Source
const ConfigPath = "costroid.yml"

ConfigPath is where a repository keeps its settings.

View Source
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.

View Source
const DemotedByOverrideRate = "override_rate"

DemotedByOverrideRate is why a rule is demoted: reviewers overrode it more than one time in five. The list is closed.

View Source
const DemotionTerm = 30 * 24 * time.Hour

DemotionTerm is how long a demoted rule warns, from the verdict that first crossed the threshold.

View Source
const MinBaselineRuns = 10

MinBaselineRuns is the fewest earlier runs a baseline is read from before a rule holds a run to it. Below it the nearest-rank P95 of 9 runs is their highest cost, and one run moves the P50.

View Source
const MinP95Runs = BaselineWindow

MinP95Runs is the fewest earlier runs whose P95 run_p95 holds a run to. The nearest-rank P95 of n runs is the cost at rank ceil(0.95 n), which for every n below 20 is the highest cost, so one costly run would set the limit. At 20 it is the 19th, and the window holds no more.

View Source
const NextAfterInvalidPack = "Next: costroid policy --rows FILE --pack FILE runs the pack once corrected."

NextAfterInvalidPack is the line under a pack that is not valid. A pull request's check runs the base branch's pack, never the one it changes, so a corrected pack runs first where its author runs it.

View Source
const (
	// PackChildArgument is the one argument a pack's child process starts
	// with. It is no command: costroid's main hands the process to PackChild
	// before it reads any.
	PackChildArgument = "__costroid_pack_child"
)
View Source
const PackKey = "policy_pack"

PackKey is the top-level key of costroid.yml that names a customer pack.

View Source
const WarnOnlyPeriod = 7 * 24 * time.Hour

WarnOnlyPeriod is how long after the workflow reached the base branch a rule that fails warns instead.

View Source
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

View Source
var ErrMixedRecording = errors.New("the file mixes rows of the demo's recorded run, marked costroid/origin recording, with rows that are not: a recording stands alone in its file")

ErrMixedRecording refuses a rows file that holds a row of the demo's recorded run beside a row that is not one. What reads a recording says that its figures are recorded, and that would be false of the other rows.

View Source
var ErrOriginRow = errors.New("the row states costroid/origin, which marks a row from a developer's machine, and a rows file never carries one")

ErrOriginRow refuses a rows file that holds a row stating costroid/origin. Such a row is counted from a developer's own session file, and a report keeps it in memory alone: no rows file carries one. A job that tagged its own run's rows so would make them vanish from the run's figure and every rule, so the file is refused whole, as for any row that is not valid.

View Source
var ErrRecordedRow = errors.New("the row states costroid/origin recording, which marks the demo's recorded run, no spend of yours: only costroid policy and costroid report --preview read such a file")

ErrRecordedRow refuses a rows file that holds a row of the demo's recorded run wherever rows are sent, written for another tool or reported from a job. A recording is no spend of the person who holds it. A job that tagged its own run's rows so would have them read as no spend of its pull request, so the file is refused whole there, as for any value of costroid/origin.

Functions

func ApprovalKeys

func ApprovalKeys() []string

ApprovalKeys are the keys under approval that ParseApproval reads, sorted.

func BaseHead

func BaseHead(ctx context.Context, branches Branches, branch string) (string, error)

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 Demotable

func Demotable(rule string) bool

Demotable reports whether a rule's record can demote it.

func Keys

func Keys() []string

Keys are the keys under policy that ParseSettings reads, sorted.

func PackChild

func PackChild() (int, bool)

PackChild runs this process as a customer pack's child when it was started as one, and reports whether it was. Every executable that runs a pack calls it first, in main or in TestMain: in any other process it records that the executable hands such a child to the pack, and RunCustomerPack starts no child from an executable that does not. The child limits itself, reads one request on stdin, compiles and evaluates the pack, and writes one answer on stdout. The code is the process's exit code.

func PackSHA256

func PackSHA256() string

PackSHA256 is the SHA-256 of the default pack's source.

func RefuseOriginRows

func RefuseOriginRows(rows []byte) error

RefuseOriginRows holds a rows file a job wrote to the rule a report in a job applies as it reads: it refuses the file at the first row that states costroid/origin, with ErrRecordedRow for a row of the demo's recorded run and ErrOriginRow for any other, before a command sends or writes any of it. A line that is no row is left to the command's own reader, which refuses it in its own words.

func WidenPackTimeForTests

func WidenPackTimeForTests()

WidenPackTimeForTests puts testPackTime on every child this process starts after it. A test binary's TestMain calls it once, before any test runs. No program calls it: make lint-deadcode fails once one does, and no flag, variable of the environment or file reaches it.

func WorkflowPath

func WorkflowPath(workflowRef, repository string) (string, error)

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, their nearest-rank P50.
	// It is never negative.
	MedianUSD decimal.Decimal
	// P95USD is the nearest-rank P95 of their USD totals.
	P95USD 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.

func BaselineOf

func BaselineOf(costs []RunCost, trust Trust) *Baseline

BaselineOf is the USD baseline the increase rules read, nil when no run had a cost in USD. trust is who vouches for the runs' costs.

type Branches

type Branches interface {
	BranchHead(ctx context.Context, branch string) (string, error)
}

Branches resolves a branch to the commit at its head. scm.GitHub and scm.GitLab are ones.

type Commits

type Commits struct {
	Base, Head  string
	PullRequest bool
}

Commits names what one report is about: a pull request's base and head, or a push's head alone.

type Composed

type Composed struct {
	// Verdict is Costroid's verdict. Its results are Costroid's, unchanged,
	// and on a fault one more: its own customer_pack result.
	Verdict Verdict
	// Pack is the pack's results, apart from Costroid's.
	Pack []PackResult
	// contains filtered or unexported fields
}

Composed is Costroid's verdict with a customer pack's results joined to it.

func RunCustomerPack

func RunCustomerPack(ctx context.Context, source []byte, request Request, verdict Verdict) Composed

RunCustomerPack runs a customer pack in a child process over the request Costroid's verdict was computed from, and joins its results to that verdict. The conclusion it returns is never below the verdict's.

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
	// contains filtered or unexported fields
}

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.

func (ConfigFile) PackPath

func (c ConfigFile) PackPath() string

PackPath is the path of the customer pack the file names, empty when it names none or cannot be read.

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 Demoted

type Demoted struct {
	Reason   string `json:"reason"`
	Approved int    `json:"approved"`
	Failing  int    `json:"failing"`
	Until    string `json:"until"`
}

Demoted is the record that demoted a rule, as a result states it: the pull requests in the window that crossed the threshold, how many of them an approval overrode, and when the demotion ends.

type Demotion

type Demotion struct {
	// Limit is the limit the window counts failures under.
	Limit decimal.Decimal
	// Rearmed is when the window last started empty.
	Rearmed time.Time
	// From is the time of the verdict that first crossed the threshold, and
	// zero while the rule is armed.
	From time.Time
	// Crossed is the record that crossed the threshold at From.
	Crossed Overrides
	// Off says the last verdict that read the rule's demotion read
	// policy.auto_demote: false.
	Off bool
}

Demotion is where a rule's demotion stands in one repository. A rule with no demotion kept yet is Demotion{Limit: its limit}: armed since the record began.

func (Demotion) Demoted

func (d Demotion) Demoted(at time.Time) bool

Demoted reports whether the rule is demoted at a verdict's time: a verified record crossed the threshold, and the term it started has not ended.

func (Demotion) Rearm

func (d Demotion) Rearm(at time.Time, limit decimal.Decimal, on bool) Demotion

Rearm is the demotion at a verdict, before its record is read. It re-arms at once when demotion is turned off or the rule's limit has changed, again when demotion is turned back on, and at the end of a term. A re-armed window starts empty.

func (Demotion) Record

func (d Demotion) Record(at time.Time, overrides Overrides) Demotion

Record is the demotion after a verdict's record is read. The first verdict whose record demotes the rule starts the term and keeps that record, and a later one leaves it as it is, so the state does not flap as the window rolls.

func (Demotion) Until

func (d Demotion) Until() time.Time

Until is when the term of a demotion from From ends.

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

type FileReader interface {
	ReadFile(ctx context.Context, path, ref string) ([]byte, error)
}

FileReader reads a file at a commit. A missing file is scm.ErrNotFound.

type History

type History interface {
	FirstCommit(ctx context.Context, path, ref string) (time.Time, error)
}

History says when a file first reached a branch. scm.GitHub is one.

type Kind

type Kind int

Kind is what a row is to a report.

const (
	// RunRow is a row of the run's own agent.
	RunRow Kind = iota
	// EstimateRow states a cost source and names no agent: an infrastructure
	// estimate the workflow added.
	EstimateRow
	// ReceiptRow carries costroid/origin at any value but recording: a row
	// counted from a developer's own session file.
	ReceiptRow
	// RecordedRow carries costroid/origin recording: a row of the demo's
	// recorded run. It is a run's row, of a run that is not the reader's own.
	// costroid policy and a preview read a file of them as a run's rows and
	// say so, and nothing sends, stores or reports one.
	RecordedRow
)

The kinds of row. Only a run's row reaches a rule, a budget, a total or a figure of the run.

func Classify

func Classify(tags focus.Tags) Kind

Classify says what a row is, by its tags. It is the one place that decides which rows are a run's: every reader that sums or judges a run's rows reads through it. A row that names costroid/origin is never a run's own, whatever else the row says, so a row from a developer's machine can neither raise nor satisfy a budget. Only the value recording, as a string, makes it a RecordedRow. Any other value reads as a ReceiptRow.

func ClassifyRow

func ClassifyRow(row focus.Row) Kind

ClassifyRow is Classify for a row a writer holds.

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, the
	// counts that stand. pr_budget is held to the larger of it and the rows'
	// USD list cost whatever the evidence: a count still missing can only add,
	// so a sum over the limit fails, and only GatewayMeasured lets a sum
	// within it pass.
	MeasuredUSD decimal.Decimal
	Config      ConfigFile
	// Pack is the customer pack Config names, read by serve itself.
	Pack                 Pack
	Start                Start
	MeasuredPullRequests int
	At                   time.Time
	// Record is the ledger's own override record of the pull request, which
	// serve gives only where it read costroid.yml itself. Each rule that fails
	// is recorded in it, and a rule it demotes warns. Nil records nothing and
	// demotes nothing.
	Record OverrideLedger
}

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 OverrideLedger

type OverrideLedger interface {
	// AddFailure records that rule failed under limit at the verdict's time,
	// on the pull request's head commit.
	AddFailure(ctx context.Context, rule string, limit decimal.Decimal, at time.Time) error
	// Overrides counts the rule's record under limit from rearmed to at.
	Overrides(ctx context.Context, rule string, limit decimal.Decimal, rearmed, at time.Time) (failing, approved, approvers int, err error)
	// Demotion is the rule's demotion as last kept, and false when none is.
	Demotion(ctx context.Context, rule string) (Demotion, bool, error)
	// KeepDemotion keeps the demotion a verdict moved the rule to, and is the
	// one kept: another verdict's when two moved it at once.
	KeepDemotion(ctx context.Context, rule string, demotion Demotion) (Demotion, error)
}

OverrideLedger is a ledger's own record of the failing verdicts serve answered and the approvals it verified, for the one pull request a verdict judges, which it never counts. Only EvaluateLedger reads one, and no field of Request holds one, so a verdict on rows a job wrote, on check runs or on anything a request states never reaches a record.

type Overrides

type Overrides struct {
	Failing   int
	Approved  int
	Approvers int
	// contains filtered or unexported fields
}

Overrides is a rule's record over its window: the pull requests on which it failed, how many of them an approval overrode, and how many accounts gave those approvals.

type Pack

type Pack struct {
	// contains filtered or unexported fields
}

Pack is the customer pack a costroid.yml names, as one commit holds it, or as a file offline. Only ReadPack and PackFromFile make one that holds bytes, and each records the costroid.yml it was read for, so a pack read for one file never runs under another. The zero Pack is a pack not read.

func PackFromFile

func PackFromFile(file string, config ConfigFile) Pack

PackFromFile reads the customer pack config names from a file, as costroid policy does offline: file holds the pack as the base branch holds it at the path config names. A missing file and a file over 64 KiB leave it unread, as they do online.

func ReadPack

func ReadPack(ctx context.Context, files FileReader, config ConfigFile) Pack

ReadPack reads the customer pack config names at the commit ReadConfig read config at, and at no other: no parameter takes a commit. A configuration ReadConfig did not read is refused, and so, on a pull request, is one that is not the base's. A missing file, a file over 64 KiB and a host that did not answer each leave the pack unread.

func (Pack) ChangedAtHead

func (p Pack) ChangedAtHead(ctx context.Context, files FileReader, config ConfigFile, head string) PackChange

ChangedAtHead compares the pack config names with the pull request's head, and reports only what changed. It reads costroid.yml and the pack's path at head when config names a pack, and nothing leaves this function but the answer, so the head's bytes never run. A read the host did not answer is no change, since none is known. Off a pull request there is no head to compare.

func (Pack) Read

func (p Pack) Read() bool

Read reports a pack whose bytes were read whole, which runs when a verdict reads the costroid.yml it was read for.

type PackChange

type PackChange int

PackChange says what a pull request changes of its customer pack. The change applies after the merge, because the verdict reads the base.

const (
	// PackUnchanged is no change, or one that could not be read.
	PackUnchanged PackChange = iota
	// PackKeyChanged is a policy_pack at the head that names another path,
	// or none.
	PackKeyChanged
	// PackFileChanged is a pack file at the head whose bytes differ from the
	// base's.
	PackFileChanged
)

What a pull request changes of its pack.

type PackFault

type PackFault struct {

	// Line is the pack's line the parser or the compiler named, 0 when it
	// named none.
	Line int
	// contains filtered or unexported fields
}

PackFault is why a customer pack gave no results. Its reason alone decides the outcome of Costroid's customer_pack result.

func CheckPackFile

func CheckPackFile(ctx context.Context, file string, config ConfigFile) (bool, *PackFault)

CheckPackFile reads the pack config names from file, and compiles it as a check would before it reads a row: in a child of this executable, under capabilities.pack.json and the same bounds of size and time. It answers false when there is no such file. Otherwise it answers the fault a check would state on any rows, a file over 64 KiB or a pack that is not valid, and nil for a pack that compiles. A fault of a bound is the rows' and the runner's, so it is left to the check.

func (*PackFault) Detail

func (f *PackFault) Detail() string

Detail is the fault's reason, its line when the compiler named one, and its error. A compiler that found more than one thing wrong wrote a line for each, and the detail keeps them a line each under its first.

func (*PackFault) Error

func (f *PackFault) Error() string

Error says what the fault is on its first line. A pack that is not valid has the next step on a line under it.

func (*PackFault) Reason

func (f *PackFault) Reason() string

Reason is the reason Costroid's customer_pack result states.

func (*PackFault) Unwrap

func (f *PackFault) Unwrap() error

type PackOutcome

type PackOutcome string

PackOutcome is what a pack's result says. It has two values: a pack has no word for pass.

const (
	PackWarn PackOutcome = "warn"
	PackFail PackOutcome = "fail"
)

The two outcomes of a pack's result.

type PackResult

type PackResult struct {
	Rule    string      `json:"rule"`
	Outcome PackOutcome `json:"outcome"`
	Reason  string      `json:"reason"`
	// Message holds only the characters a comment prints as a code span, at
	// most 160 bytes. Empty, the pack gave none.
	Message        string `json:"message,omitempty"`
	HeldByWarnOnly bool   `json:"held_by_warn_only,omitempty"`
}

PackResult is one result a customer pack returned.

type PackRun

type PackRun struct {
	// Path is the pack's path as costroid.yml names it.
	Path string `json:"path"`
	// SHA256 hashes the bytes read, and zero bytes when none were.
	SHA256 string `json:"sha256"`
	// Results are the pack's own, empty when it returned none and when
	// Costroid's customer_pack result says why it did not run to its end.
	Results []PackResult `json:"results"`
}

PackRun is the customer pack a verdict ran, as result/0.12 states it.

type Recording

type Recording struct {
	// contains filtered or unexported fields
}

Recording follows the rows of one file as they are read, and says whether the file is the demo's recorded run: every row a RecordedRow.

func (*Recording) Hold

func (r *Recording) Hold(kind Kind) error

Hold takes the kind of the next row. It answers ErrMixedRecording at the first row that makes the file hold a recorded row beside one that is not.

func (Recording) Whole

func (r Recording) Whole() bool

Whole reports whether the file held rows, each one recorded.

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
	// Pack is the customer pack Config names, as ReadPack or PackFromFile
	// read it for Config. A pack read for any other configuration is unread.
	Pack Pack
}

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"`
	// Line is the line of the customer pack the compiler named, beside
	// pack_invalid alone.
	Line     int    `json:"line,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"`
	// P95USD is the P95 of the baseline run_p95 holds the run to, present
	// only beside a baseline of MinP95Runs runs.
	P95USD string `json:"p95_usd,omitempty"`
	// LimitFactor is policy.max_p95_factor: a run may cost up to P95USD times
	// it. The product is not stated, because its scale can pass the twelve
	// fractional digits an amount holds.
	LimitFactor string `json:"limit_factor,omitempty"`
	// BaselineRuns counts the earlier runs run_p95's baseline holds. Nil on
	// every other rule, and on a ledger's answer, which reads no baseline.
	BaselineRuns *int `json:"baseline_runs,omitempty"`
	// Models names the models off the allowlist, sorted, at most 10.
	Models []string `json:"models,omitempty"`
	// Demoted is the record a ledger demoted the rule by, nil unless its
	// failure was lowered to a warning. It holds counts and an instant, so a
	// comment that withholds amounts keeps it.
	Demoted *Demoted `json:"demoted,omitempty"`
}

Result is one rule's outcome. LimitUSD, CostUSD, BaselineUSD and P95USD are amounts, so a comment that withholds amounts drops them.

type RunCost

type RunCost struct {
	CheckRun int64
	Currency string
	Cost     decimal.Decimal
}

RunCost is what one earlier run of an agent cost in one currency, at list, over every basis, as the run rules read a run. CheckRun orders the runs: the host numbers check runs in the order it creates them.

type Settings

type Settings struct {
	// Amounts holds each key that is set and read as an amount is, by its
	// name in costroid.yml: the amounts, and the P95 limit's factor.
	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
	// DemotionOff is policy.auto_demote: false. A ledger then demotes no
	// rule by its override rate, and every rule is re-armed.
	DemotionOff bool
	// Pack is the path of the customer pack policy_pack names, empty when it
	// names none.
	Pack string
}

Settings are the policy keys of costroid.yml. A key that is not set is a rule that does not run.

func ParseSettings

func ParseSettings(data []byte) (Settings, error)

ParseSettings reads the policy mapping of costroid.yml, and policy_pack. Any key or value under policy that the schema refuses is an error, and so is a policy_pack the schema refuses, so a typo never runs a rule on a default. A policy key with no value sets no rule, as an absent one does. Other keys outside policy 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.

func ReadStart

func ReadStart(ctx context.Context, history History, path, base string) (Start, error)

ReadStart reads when the workflow file reached the base. A base it has not reached is NotOnBase. A start it cannot read comes back zero, with the reason as the error, and the period keeps running.

type Trust

type Trust string

Trust says who vouches for the rows' run identity.

const (
	// Unverified rows were written by the agent's own job, so their tags are
	// claims.
	Unverified Trust = "unverified"
	// TokenVerified rows were checked by a ledger against the job's OIDC token.
	TokenVerified Trust = "token_verified"
)

The two trust paths.

type Usage

type Usage struct {
	Rows       int
	Currencies []CurrencyUsage
	// Recording says the rows are the demo's recorded run, each marked
	// costroid/origin recording: no spend of the person who holds the file.
	Recording bool
}

Usage is one run's rows, reduced to what the pack reads.

func ReadUsage

func ReadUsage(source io.Reader) (Usage, error)

ReadUsage reads FOCUS rows as JSON lines from a file the agent's job wrote. Every row is unattributed whatever its tags claim, because the job could write any tag. One bad row refuses the file: a partial total would read as a smaller cost. Classify says what each row is: an estimate's row is not read, and a row from a developer's machine refuses the file with ErrOriginRow. A file of the demo's recorded run is read as a run's rows, and Usage.Recording says so. A recorded row beside any other refuses the file with ErrMixedRecording.

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"`
	// Pack is the customer pack costroid.yml names and its results, nil when
	// it names none.
	Pack *PackRun `json:"pack,omitempty"`
	// 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"`
	// PackChange says what the pull request changes of the pack, which
	// applies after the merge. The result object does not hold it.
	PackChange PackChange `json:"-"`
	// contains filtered or unexported fields
}

Verdict is the pack's answer and what it was computed from.

func Evaluate

func Evaluate(ctx context.Context, request Request) (Verdict, error)

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. pr_budget is held to the larger of the rows' USD list cost and the gateway's count on any evidence, so a count over the limit fails though the rows are agent counts or none. The answer covers the whole pull request, so the rules that read one run's rows conclude unproven.

func (Verdict) ConfigProblem

func (v Verdict) ConfigProblem() error

ConfigProblem says why the settings could not be used, nil when they were.

func (Verdict) PackProblem

func (v Verdict) PackProblem() error

PackProblem says why the customer pack gave no results, nil when it gave its answer or costroid.yml names none.

func (Verdict) WithoutAmounts

func (v Verdict) WithoutAmounts() Verdict

WithoutAmounts returns the verdict with every amount dropped, and every message of the customer pack's results, which can echo an amount the pack read.

type WarnOnly

type WarnOnly struct {
	Active  bool   `json:"active"`
	Reason  string `json:"reason"`
	Started string `json:"started,omitempty"`
	Ends    string `json:"ends,omitempty"`
}

WarnOnly is the period's state at the time of the check.

Jump to

Keyboard shortcuts

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