gate

package
v2.1.1 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: MIT Imports: 16 Imported by: ? 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 gate implements paired release criteria without model or harness I/O.

Index

Constants

View Source
const (
	// Operational requires a consecutive prefix and immutable stopped variants.
	Operational DecisionMode = "operational"
	// Offline permits an isolated cumulative look for an explicit dry proof.
	Offline DecisionMode = "offline"
	// Complete means scheduling is finished, not that either variant qualified.
	Complete Status = "COMPLETE"
	// CalibrationEligible identifies an offline candidate meeting measured targets.
	CalibrationEligible Status = "CALIBRATION_ELIGIBLE"
	// CalibrationIneligible excludes an unqualified candidate from live scheduling.
	CalibrationIneligible Status = "CALIBRATION_INELIGIBLE"
)
View Source
const FreezeFormat = "loom-mcp.eval.gate.freeze"

FreezeFormat identifies the versioned freeze document.

View Source
const SimulatorVersion = "k19-v2-variant-interval"

SimulatorVersion changes whenever synthetic sampling or reporting changes.

Variables

This section is empty.

Functions

func CalibrationTargets

func CalibrationTargets(cells []CellReport, policy *Policy) ([]string, error)

CalibrationTargets renders explicit v2 candidate and per-variant evidence. Combined PASS is informational and never enters these eligibility comparisons.

func CanGenerateItems

func CanGenerateItems(f *Freeze) error

CanGenerateItems refuses pool regeneration after a freeze exists.

func Digest

func Digest(data []byte) string

Digest returns a lowercase SHA-256 content address.

func LegacyCalibrationTargets

func LegacyCalibrationTargets(cells []CellReport) []string

LegacyCalibrationTargets renders historical v1 measured targets from saved simulation outcomes. Guard attribution is a lower bound: old cells retain criterion marginals at stopping, not joint guard causes. Their union bound safely bounds non-guard failures, including failures at later looks. No simulations are rerun here.

func PercentileIndices

func PercentileIndices(n int, alpha float64) (int, int)

PercentileIndices returns zero-based equal-tail percentile indices.

func Render

func Render(_ Evaluation, d Decision) string

Render reports scheduling separately from qualification, using each variant's own immutable stopping snapshot. Missing keys are an exact rerun manifest.

func ValidateNextLook

func ValidateNextLook(policy *Policy, look int, previous []Decision) error

ValidateNextLook checks the complete operational prefix before scheduling work. It shares the same prefix validator as Decide and never evaluates new rows.

func VerifyCalibrationReport

func VerifyCalibrationReport(report CalibrationReport, cfg CalibrationConfig) error

VerifyCalibrationReport checks population identity and complete measured result consistency without sampling or constructing a provider. Callers must additionally require their planned cells and simulation counts.

func WithCalibrationProgress

func WithCalibrationProgress(ctx context.Context, observe func(CalibrationProgress)) context.Context

WithCalibrationProgress observes calibration work without changing its inputs or results. Calls within each calibration are serialized. The observer must return promptly and must not panic. Counts restart for each calibration call; no callback is retained in configuration or serialized into evidence. A nil observer disables it.

Types

type Bootstrap

type Bootstrap struct {
	Resamples int    `json:"resamples"`
	Seed      uint64 `json:"seed"`
}

Bootstrap records the immutable resample count and seed.

type CalibrationConfig

type CalibrationConfig struct {
	Gate       Config                        `json:"gate"`
	Seed       uint64                        `json:"seed"`
	Workers    int                           `json:"workers"`
	Pilot      map[string]Rates              `json:"pilot"`
	Qualifying map[string]map[string]float64 `json:"qualifying"`
}

CalibrationConfig fixes the bootstrap and outcome seeds independently. Pilot rates are clamped to [.02,.98]; nil uses labelled assumed defaults. Qualifying must give the offline-validated fraction for each variant/scenario.

type CalibrationProgress

type CalibrationProgress struct {
	CellsCompleted       int
	CellsTotal           int
	SimulationsCompleted int
	SimulationsTotal     int
}

CalibrationProgress reports actual work completed in the current calibration phase. Shared candidate simulations are counted once, not once per candidate.

type CalibrationReport

type CalibrationReport struct {
	Version     string                        `json:"version"`
	RateSource  string                        `json:"rate_source"`
	Seed        uint64                        `json:"seed"`
	Baselines   map[string]Rates              `json:"baselines"`
	Qualifying  map[string]map[string]float64 `json:"qualifying"`
	Cells       []CellReport                  `json:"cells"`
	Sensitivity []CellReport                  `json:"sensitivity"`
	Targets     []string                      `json:"targets"`
}

CalibrationReport retains inputs and all cells in deterministic grid order.

func Calibrate

Calibrate runs the full grid and two central-null copula sensitivity rows. It uses Evaluate and Decide unchanged, including 10,000 frozen-seed resamples. Worker count changes scheduling only; each cell/simulation owns its RNG.

func CalibrateChecks

func CalibrateChecks(ctx context.Context, cfg CalibrationConfig) (CalibrationReport, error)

CalibrateChecks computes the two production-bootstrap, 200-simulation check cells. K19b persists this output and compares its deterministic JSON bytes.

type CandidateReport

type CandidateReport struct {
	Margin float64           `json:"margin"`
	Report CalibrationReport `json:"report"`
}

CandidateReport preserves the complete result for one proposed unsupported margin.

func CalibrateCandidates

func CalibrateCandidates(ctx context.Context, cfg CalibrationConfig) ([]CandidateReport, error)

CalibrateCandidates computes all three fixed margins with production counts and shared identical bootstrap work. Each candidate retains its own stopping path, decision-cell count and complete independently selectable report.

type CandidateSelection

type CandidateSelection struct {
	Variant       string             `json:"variant"`
	Margin        float64            `json:"margin"`
	Status        Status             `json:"status"`
	WorstNull     float64            `json:"worst_null"`
	WorstBoundary map[string]float64 `json:"worst_boundary"`
}

CandidateSelection reports eligibility separately for each variant.

func SelectCandidates

func SelectCandidates(candidates []CandidateReport, variants []string) ([]CandidateSelection, error)

SelectCandidates selects the smallest fully measured eligible candidate per variant. Missing or duplicate decision cells are malformed, not ineligibility.

type CapabilityProfile

type CapabilityProfile struct {
	Version string         `json:"version"`
	Models  []RoleIdentity `json:"models"`
	Parts   []string       `json:"parts"`
}

CapabilityProfile identifies the configured model capabilities without constructing a provider. Empty Parts explicitly means no non-text support.

type Cell

type Cell struct{ DY, DU, DE, Delta, Rho, Recall, Kappa float64 }

Cell identifies one full-factorial synthetic population. DU is bad-oriented; every other difference is good-oriented. Kappa couples measures within a run.

func CalibrationGrid

func CalibrationGrid() []Cell

CalibrationGrid returns all 1620 cells in a stable order.

func (Cell) CandidateDecisionCell

func (c Cell) CandidateDecisionCell(margin float64) bool

CandidateDecisionCell identifies the null or a boundary for this candidate.

func (Cell) DecisionCell

func (c Cell) DecisionCell() bool

DecisionCell identifies the nine null and 36 single-margin cells.

type CellReport

type CellReport struct {
	ExpectedAttempts float64                       `json:"expected_attempts"`
	Variants         map[string]VariantSimulation  `json:"variants"`
	Cell             Cell                          `json:"cell"`
	Simulations      int                           `json:"simulations"`
	Infeasible       string                        `json:"infeasible"`
	Pass             float64                       `json:"pass"`
	NotPassed        float64                       `json:"not_passed"`
	SE               float64                       `json:"se"`
	ExpectedLooks    float64                       `json:"expected_looks"`
	ExpectedItems    float64                       `json:"expected_items"`
	VariantPass      map[string]float64            `json:"variant_pass"`
	LookPass         [3]float64                    `json:"look_pass"`
	LookFail         [3]float64                    `json:"look_fail"`
	TruncatedPass    [2]float64                    `json:"truncated_pass"`
	Final            map[string]map[Status]float64 `json:"final"`
}

CellReport stores probabilities, Monte Carlo uncertainty and stopping cost.

type Config

type Config struct {
	Policy              *Policy
	Baseline            string
	Variants, Scenarios []string
	Items               map[string][]string
	Repeats             int
}

Config identifies the gated populations. Items, when supplied, is the complete cumulative manifest; without it, the union of observed items defines the plan. Policy is required and owns alpha, bootstrap identity and decision margins.

type CriterionResult

type CriterionResult struct {
	Interval
	Status Status
	Reason string
}

CriterionResult records a decision and its precision bounds.

func Criterion

func Criterion(i Interval, margin float64, higher bool) CriterionResult

Criterion uses strict bounds, including the recall margin (Q17).

type Decision

type Decision struct {
	Policy       *Policy
	Variants     []VariantDecision
	Look         int
	Status       Status
	Reason       string
	Rerun        []Key
	Inconclusive []string
}

Decision is the stopping result for a cumulative look.

func Decide

func Decide(e Evaluation, previous []Decision) (Decision, error)

Decide advances a consecutive operational prefix. Completed variants keep their exact terminal evidence; incomplete siblings enforce the same-look barrier.

func DecideMode

func DecideMode(e Evaluation, previous []Decision, mode DecisionMode) (Decision, error)

DecideMode applies a named decision mode. Operational callers use Decide.

type DecisionMode

type DecisionMode string

DecisionMode distinguishes operational prefixes from isolated offline proofs.

type Evaluation

type Evaluation struct {
	Policy        *Policy
	Baseline      string
	Look          int
	Variants      []VariantResult
	Missing       []Key
	GuardFailures []string
}

Evaluation contains one cumulative look's estimates and missing run keys.

func Evaluate

func Evaluate(table Table, cfg Config, look int) (Evaluation, error)

Evaluate computes all measures with one shared stratified item draw per bootstrap resample, across both variants and every paired measure.

type Freeze

type Freeze struct {
	Policy             *Policy                      `json:"policy,omitempty"`
	Selections         []CandidateSelection         `json:"selections,omitempty"`
	Roles              map[string]RoleIdentity      `json:"roles,omitempty"`
	Profiles           map[string]CapabilityProfile `json:"profiles,omitempty"`
	EffectivePolicies  map[string]json.RawMessage   `json:"effective_policies,omitempty"`
	SourceSHA256       string                       `json:"source_sha256,omitempty"`
	SourceBundleSHA256 string                       `json:"source_bundle_sha256,omitempty"`
	ValidationSHA256   string                       `json:"validation_sha256,omitempty"`
	InventorySHA256    string                       `json:"inventory_sha256,omitempty"`

	Format              string                     `json:"format"`
	Version             int                        `json:"version"`
	Configuration       string                     `json:"configuration"`
	Margins             Margins                    `json:"margins"`
	Alpha               float64                    `json:"alpha"`
	Looks               []int                      `json:"looks"`
	Repeats             int                        `json:"repeats"`
	Bootstrap           Bootstrap                  `json:"bootstrap"`
	Guard               float64                    `json:"guard"`
	GatedScenarios      []string                   `json:"gated_scenarios"`
	ReportedScenarios   []string                   `json:"reported_scenarios"`
	ScenarioContexts    map[string]json.RawMessage `json:"scenario_contexts"`
	Policies            map[string]json.RawMessage `json:"policies"`
	Pools               []Pool                     `json:"pools"`
	MaterializerVersion string                     `json:"materializer_version"`
	CalibrationSHA256   string                     `json:"calibration_sha256"`
	SimulatorVersion    string                     `json:"simulator_version"`
	GitRevision         string                     `json:"git_revision"`
	Dirty               bool                       `json:"dirty"`
	Created             time.Time                  `json:"created"`
}

Freeze is the immutable experiment contract. Hash the serialized value before running variants; keep that trusted hash separate from the mutable input. Scenario weights are equal within GatedScenarios. Policies are exact JSON.

func (Freeze) Hash

func (f Freeze) Hash() (string, error)

Hash returns the deterministic JSON hash of the full freeze contract.

func (Freeze) Label

func (f Freeze) Label(look int) (string, error)

Label returns the required experiment label after hashing the freeze.

func (Freeze) Verify

func (f Freeze) Verify(expected string, in FreezeInputs) error

Verify rejects contract, dataset and materializer drift against a trusted hash.

func (Freeze) VerifyLabel

func (f Freeze) VerifyLabel(label string, look int) error

VerifyLabel rejects experiments that do not belong to this frozen look.

type FreezeInputs

type FreezeInputs struct {
	SourceSHA256       string                       `json:"source_sha256"`
	SourceBundleSHA256 string                       `json:"source_bundle_sha256"`
	ValidationSHA256   string                       `json:"validation_sha256"`
	InventorySHA256    string                       `json:"inventory_sha256"`
	CalibrationSHA256  string                       `json:"calibration_sha256"`
	Roles              map[string]RoleIdentity      `json:"roles"`
	Profiles           map[string]CapabilityProfile `json:"profiles"`
	EffectivePolicies  map[string]json.RawMessage   `json:"effective_policies"`

	Pools               map[string][]byte `json:"pools"`
	Materialized        map[string][]byte `json:"materialized"`
	MaterializerVersion string            `json:"materializer_version"`
}

FreezeInputs supplies current bytes for offline verification before look/report.

type FrozenItem

type FrozenItem struct {
	ID     string `json:"id"`
	SHA256 string `json:"sha256"`
}

FrozenItem binds an item ID to its materialized SHA-256.

type Interval

type Interval struct{ Estimate, Lo, Hi float64 }

Interval is a point estimate and a two-sided confidence interval.

type Key

type Key struct {
	Variant  string `json:"variant"`
	Scenario string `json:"scenario"`
	Item     string `json:"item"`
	Repeat   int    `json:"repeat"`
}

Key identifies one planned run. Repeat is one-based.

type Margins

type Margins struct {
	Success     float64 `json:"success"`
	Unsupported float64 `json:"unsupported"`
	Evidence    float64 `json:"evidence"`
	Recall      float64 `json:"recall"`
}

Margins fixes the four release criteria.

func DefaultMargins

func DefaultMargins() Margins

DefaultMargins returns the binding K19 margins.

type Policy

type Policy struct {
	Version         string             `json:"version"`
	Success         float64            `json:"success"`
	Unsupported     map[string]float64 `json:"unsupported"`
	Evidence        float64            `json:"evidence"`
	Recall          float64            `json:"recall"`
	Guard           float64            `json:"guard"`
	GuardMethod     string             `json:"guard_method"`
	Alpha           float64            `json:"alpha"`
	Looks           []int              `json:"looks"`
	Repeats         int                `json:"repeats"`
	Bootstrap       Bootstrap          `json:"bootstrap"`
	BootstrapMethod string             `json:"bootstrap_method"`
}

Policy is the complete versioned rule consumed by evaluation and stopping. A proposed value authorizes offline computation only; operational work also requires the enclosing verified freeze and consecutive evidence prefix.

func ProposedPolicy

func ProposedPolicy(unsupported map[string]float64, seed uint64) Policy

ProposedPolicy constructs the fixed offline rule with explicitly selected unsupported margins. It does not authorize live execution or qualification.

func (*Policy) Validate

func (p *Policy) Validate(variants []string) error

Validate rejects policy shapes outside the calibrated contract.

type Pool

type Pool struct {
	Scenario    string       `json:"scenario"`
	Partition   string       `json:"partition"`
	DatasetHash string       `json:"dataset_hash"`
	Items       []FrozenItem `json:"items"`
}

Pool binds raw dataset bytes and ordered item identities to a partition.

type Rates

type Rates struct{ Success, Unsupported, Evidence float64 }

Rates are baseline marginal probabilities. Unsupported is bad-oriented.

type RecallResult

type RecallResult struct {
	CriterionResult
	N                     int
	Rho, Deff, EffectiveN float64
}

RecallResult includes the item-cluster design effect used by Wilson.

func Recall

func Recall(rows Table, variant string, scenarios []string, alpha float64) RecallResult

Recall pools qualifying outcomes and adjusts Wilson's effective sample size for agreement between the two qualifying repeats of each item.

type RoleIdentity

type RoleIdentity struct {
	Provider   string `json:"provider"`
	Raw        string `json:"raw"`
	Normalized string `json:"normalized"`
}

RoleIdentity binds the explicit raw provider ID and its normalized model ID.

type Row

type Row struct {
	Key
	Success, Unsupported, Evidence bool
	Qualifying, Recalled           bool
	Infrastructure, RunFailed      bool
}

Row contains binary observations. Infrastructure removes a run from pairing; RunFailed remains an outcome and forces Success false.

type Status

type Status string

Status is a criterion or whole-gate state; inconclusive never implies pass.

const (
	// Pass certifies all required bounds.
	Pass Status = "PASS"
	// Fail identifies a measured regression or guard violation.
	Fail Status = "FAIL"
	// Inconclusive means an interval crosses or touches a margin.
	Inconclusive Status = "INCONCLUSIVE"
	// Continue requests the next held-out partition.
	Continue Status = "CONTINUE"
	// NotPassed means precision prevented certification at the final look.
	NotPassed Status = "NOT_PASSED"
	// Incomplete requires infrastructure reruns before a decision.
	Incomplete Status = "INCOMPLETE"
)

type Table

type Table []Row

Table contains observations; duplicate keys are errors (overlay reruns first).

func FromStored

func FromStored(attempts []eval.StoredAttempt) (Table, error)

FromStored converts persisted reserved measures without reconstructing a harness. Overlay Parent reruns before calling: Evaluate rejects duplicate keys. Missing/nonbinary measures are errors, never implicit quality failures.

type VariantDecision

type VariantDecision struct {
	Variant        string
	Look           int
	Status         Status
	Reason         string
	Rerun          []Key
	Inconclusive   []string
	GuardFailures  []string
	FailedCriteria []string
	Evidence       VariantResult
}

VariantDecision retains each variant's immutable stopping evidence and causes.

type VariantResult

type VariantResult struct {
	Missing                        []Key
	GuardFailures                  []string
	ScenarioIntervals              map[string]Interval
	Variant                        string
	Success, Unsupported, Evidence CriterionResult
	Recall                         RecallResult
	Scenarios                      map[string]float64
}

VariantResult holds all four criteria and scenario success differences.

type VariantSimulation

type VariantSimulation struct {
	Pass          float64            `json:"pass"`
	NotPassed     float64            `json:"not_passed"`
	SE            float64            `json:"se"`
	LookPass      [3]float64         `json:"look_pass"`
	LookFail      [3]float64         `json:"look_fail"`
	GuardStop     float64            `json:"guard_stop"`
	CriterionStop float64            `json:"criterion_stop"`
	FailureMasks  map[string]float64 `json:"failure_masks"`
}

VariantSimulation records a variant's actual terminal outcomes and joint causes.

Jump to

Keyboard shortcuts

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