Documentation
¶
Overview ¶
Package core is the Kno engine: the five pipeline stages (Baseline, Value, Select, Validate, Export) and the Ring-0 contracts every adapter implements.
core imports nothing above it. cli, tui, and api are thin shells over identical core calls sharing one event stream — the open-core seam is a directory boundary, not a fork. A change that leaks an upward dependency into core is rejected regardless of quality; an import-boundary test enforces it mechanically.
The Ring-0 interfaces (Agent, Evals, Pool, Goal, Tuner, Capable, and the injectors) land in M0c and carry a stability promise from 1.0.
Index ¶
- Constants
- func ComputeGaps(plan *value.Plan, valuations []*knov1.Valuation) *knov1.Gaps
- func LoadAssetsByID(ctx context.Context, pool Pool) (map[string]*Asset, error)
- func PlanningCostPerCall(o BaselineOptions) int64
- func RenderTuningSetForAssets(p *knov1.Portfolio, assetIDs []string, assets map[string]*Asset) ([]byte, error)
- type Agent
- type AgentRef
- type Asset
- type BaselineOptions
- type BaselineResult
- type Capabilities
- type Capable
- type Case
- type ContextInjector
- type ContextSetInjector
- type Destination
- type Direction
- type Endpoint
- type Estimator
- type Evals
- type ExportOptions
- type ExportResult
- type Goal
- type InjectionMode
- type Interval
- type JobRef
- type JobState
- type Kind
- type KnowledgeInjector
- type Pool
- type Portfolio
- type PortfolioEntry
- type Rejection
- type Report
- type Response
- type Score
- type ScoreDomain
- type ScoreParams
- type ScoreResult
- type SealedEvals
- type SelectOptions
- type SelectResult
- type Split
- type Tuner
- type TuningJob
- type ValidateOptions
- type ValidateQuote
- type ValidateResult
- type Validation
- type ValidationVerdict
- type Valuation
- type ValueOptions
- type ValueResult
Constants ¶
const DefaultMaxAttempts = 3
DefaultMaxAttempts is how many times one Case is tried when the provider rate limits it.
A 429 is the provider asking us to slow down, not the Case failing. Recording it as terminal throws away capacity already paid for, and ordinary throttling would push a run past max_error_rate — marking a perfectly good baseline unusable for no statistical reason.
const DefaultMaxErrorRate = 0.05
DefaultMaxErrorRate is the share of errored Cases above which a Run is no longer a usable reference.
A baseline is what every later delta is measured against. One computed over a run where a third of the Cases never got an answer is not a baseline, it is a partial sample dressed as one — so the Run is marked rather than silently treated as clean by the stages that read it.
const DefaultProgressInterval = time.Second
DefaultProgressInterval is how often to emit StageProgress when progress reporting is on.
One second, against two stated bounds rather than picked: a live view is useful at about 1Hz, and the heartbeat must not dominate durable writes. Every event is one fsync under synchronous=FULL on the same serialized writer as the outcome row that prevents double-spend.
The overhead is 1 / (throughput x writes-per-Case), NOT a function of run length. At two durable writes per Case, staying under ~10% needs about five Cases a second — which concurrency 8 against one-second calls clears and concurrency 1 against a reasoning model does not. Default-off is what actually bounds this; M2-11 owns arguing the rate for a run that turns it on.
const DefaultRetryBackoff = 500 * time.Millisecond
DefaultRetryBackoff is the delay before the first retry. It doubles after each attempt.
const DefaultRetryBudget = 90 * time.Second
DefaultRetryBudget bounds retry by TIME as well as by attempts.
Attempts alone was the wrong bound. Three attempts at 500ms doubling gives a total window of 1.5 seconds, and a real provider's sustained 429 window is minutes — so a rate-limited account marked a perfectly good baseline ErrorRateExceeded and told the user "too many cases errored for this to be a usable baseline", naming nothing about the cause.
Time alone is also wrong, and for the opposite reason: each attempt takes its own reservation and settles its own call, so a long window lets one Case consume dozens of calls against --max-calls. Both bounds apply, whichever binds first.
const MinClusterCases = 5
MinClusterCases is the minimum number of a cluster's failed dev Cases an Asset must have been routed to before its measurement may testify about that cluster. Named, exported, and load-bearing: it is the line between "we looked and found nothing" (GAP) and "we did not really look" (UNKNOWN).
Variables ¶
This section is empty.
Functions ¶
func ComputeGaps ¶ added in v0.1.0
ComputeGaps reduces a source Value run's plan and its recorded Valuations into the per-cluster improvement verdicts the report renders.
The statistic, per the report plan: a cluster is IMPROVED when at least one Asset routed to >= MinClusterCases of its Cases has a delta whose 95% CI excludes zero. It is UNKNOWN when nothing routed reaches the minimum or the covering measurement is underpowered — non-significance is not absence, and the output is a spend recommendation. It is GAP when the cluster is well-covered and no covering measurement is significant.
One reported number per cluster: the BEST covering Asset's delta and interval — the strongest measured effect the cluster actually saw — never a cluster-level threshold game. Deterministic: best is the covering Asset with the largest |delta|, ties broken by Asset ID, clusters in the plan's snapshot order.
func LoadAssetsByID ¶ added in v0.1.7
LoadAssetsByID materializes a Pool into a map keyed by Asset ID.
Exported for the bridge's group-ablation planning (bridge.QuoteGroups), which needs the same map Export already builds internally to render a group's training file — without re-implementing Pool.Assets's borrowing contract (see Evals.Cases's godoc, which Pool.Assets shares) a second time in a package above core. loadAssetsByID itself (core/select.go) stays unexported; this is a thin wrapper.
func PlanningCostPerCall ¶
func PlanningCostPerCall(o BaselineOptions) int64
PlanningCostPerCall exposes the per-Case figure a confirmation would quote.
Exported because the CLI prints that figure for a --yes run, which waives the prompt the number would otherwise appear in. It must be the SAME arithmetic: two places computing "what this will cost" is two numbers that can disagree, and the one the user sees would be the one nothing enforces.
func RenderTuningSetForAssets ¶ added in v0.1.7
func RenderTuningSetForAssets(p *knov1.Portfolio, assetIDs []string, assets map[string]*Asset) ([]byte, error)
RenderTuningSetForAssets renders the tuning-set grammar for an explicit subset of a Portfolio's DESTINATION_TUNING_SET entries — one ablation group's training file, in the bridge's leave-one-group-out design.
BYTE-IDENTICAL to what `kno export --destination tuning_set` writes for the same Portfolio filtered to assetIDs, because both call this exact renderTuningSet function — this IS that function, exported so the bridge can call it without re-implementing the grammar. See the tuner-bridge plan's acceptance criterion 3.
entries are taken from p.Selected in Portfolio order, filtered to assetIDs — the same "selection order" contract destinationEntries documents. An Asset ID in assetIDs that names no entry in p is silently omitted rather than erroring: the caller (bridge.QuoteGroups) computed assetIDs from the same Portfolio's own routing, so a mismatch would be a caller bug this function has no way to diagnose better than its result having fewer lines than expected.
Types ¶
type Agent ¶
type Agent interface {
// Invoke runs the agent on one Case.
//
// c must be non-nil. A failed invocation should be returned as an error;
// the caller records it rather than dropping it, because silently
// discarding failures biases every number downstream.
Invoke(ctx context.Context, c *Case) (*Response, error)
}
Agent is anything invokable on a Case.
This is the narrowest useful contract: given a Case, produce a Response. Everything else an agent might support — context injection, a writable knowledge index, streaming — is a CAPABILITY declared through Capable, not a requirement. The engine degrades per-adapter rather than refusing to run, and the report labels every measurement with the mode actually used.
Implementations must not retain c beyond the call. See the borrowing rule on Evals.Cases.
type BaselineOptions ¶
type BaselineOptions struct {
// RunID identifies this run. Required.
RunID string
// Agent is what gets measured.
Agent Agent
// AgentRef is how the agent was named, for the record.
AgentRef *AgentRef
// Goal scores each Response.
Goal Goal
// GoalName identifies the Goal on the Run.
GoalName string
// Guard authorizes spend. Required: there is no path in this stage that
// calls an Agent without passing through it.
Guard *budget.Guard
// Store persists outcomes and events.
Store store.Store
// Concurrency bounds in-flight work.
Concurrency int
// ProgressInterval is how often a StageProgress heartbeat is emitted.
//
// Zero disables it, which is the default: every event is one fsync under
// synchronous=FULL on the same serialized writer as the outcome row that
// prevents double-spend, so a heartbeat nobody watches is pure write
// contention. The CLI turns it on when there is something rendering.
//
// DefaultProgressInterval is the figure to pass.
ProgressInterval time.Duration
// Resume continues an existing run rather than starting one.
Resume bool
// InputFingerprint identifies the inputs. A resume whose fingerprint
// differs from the recorded one is refused.
InputFingerprint string
// EvalContentHash is the eval source's own hash, so a refusal can name
// which input changed rather than only that something did.
EvalContentHash string
// SplitSeed and HoldoutFrac are recorded for reproducibility.
SplitSeed string
HoldoutFrac float64
// DevCases and HoldoutCases are the counts from ingestion.
//
// DEBT(docs/debt.md#28): the CALLER owns their accuracy. The stage checks
// only that neither is zero — a run with nothing in dev measures nothing,
// and a run with no holdout can never be validated. It does not verify the
// numbers against what the sealed source actually yields, because counting
// would mean consuming the iterator a second time. A caller whose split
// computation is wrong produces a Run and an event stream that misreport
// their own denominator, and nothing here will notice.
DevCases int
HoldoutCases int
// WeakLabelCases is how many Cases in the eval set carry derived
// provenance — weak labels mined from transcripts rather than authored
// expectations.
//
// Recorded on the Run at close so the report can say "weak-label eval" and
// the number travels with the other case counts. The same DEBT(docs/debt.md#28)
// caveat applies: the caller owns this number; the stage records it as
// given. A mined eval set passes the count through its own ingestion pass,
// so for the shipped path the two are the same computation.
WeakLabelCases int
// HoldoutUnderpowered marks a holdout too small for a meaningful interval.
HoldoutUnderpowered bool
// MaxErrorRate overrides DefaultMaxErrorRate. Zero uses the default.
MaxErrorRate float64
// MaxAttempts bounds how many times one Case is tried. Zero means
// DefaultMaxAttempts; 1 disables retry.
MaxAttempts int
// RetryBudget bounds the total WALL-CLOCK time spent retrying one Case.
// Zero means DefaultRetryBudget.
//
// Applies alongside MaxAttempts rather than replacing it. A provider's
// Retry-After can ask for a minute; three attempts of that is three
// minutes on one Case, and a run of a thousand Cases cannot afford it.
RetryBudget time.Duration
// RetryBackoff is the delay before the first retry, doubling thereafter.
// Zero means DefaultRetryBackoff.
RetryBackoff time.Duration
// EstCostPerCallUSDMicros is what one Agent call is expected to cost.
//
// The guard cannot refuse what it was not told about: authorizing with a
// zero cost estimate means the dollar cap is only ever discovered at
// settlement, after the money is spent, and a run can overshoot it by up
// to concurrency calls. An earlier version did exactly that and exceeded a
// $0.10 cap by $0.01.
//
// Deliberately crude — a real pricing model arrives with a real adapter,
// per the M1 plan — but a wrong estimate that is authorized is still
// safer than no estimate at all, because the difference is reconciled at
// settlement.
EstCostPerCallUSDMicros int64
// AcceptUnknownCost lets a run proceed when no per-Case cost can be
// computed.
//
// Explicit rather than a prompt. A confirmation that cannot state a dollar
// figure — "10,000 Cases, per-Case cost unknown" — gives a human no basis
// to decide and is a dialog people click through; a flag someone had to
// type is consent, and it is greppable in a CI config, in shell history,
// and in a code review.
AcceptUnknownCost bool
// Now returns the current time. Nil uses time.Now. Injected so golden
// tests over a Run are stable.
Now func() time.Time
// contains filtered or unexported fields
}
BaselineOptions configures a Baseline run.
type BaselineResult ¶
type BaselineResult struct {
// Run is the persisted record.
Run *knov1.Run
// AggregateScore is the mean over SCORED Cases across the whole run,
// including any part completed by an earlier process before a resume.
//
// Absent for two distinct reasons, and a caller that renders the absence
// must say which — see AggregateUnavailable. Either nothing scored, in
// which case there is no mean and zero would be indistinguishable from a
// real mean of zero; or Cases scored but their numbers cannot be read
// back, in which case a mean exists and we cannot compute it.
AggregateScore *float64
// compute it" from "nothing scored", when AggregateScore is nil.
//
// True when scored Cases can no longer contribute a number: purged before
// scores were stored separately, or holding a Score that failed to
// unmarshal. The counts remain accurate — those Cases really did score —
// so a caller that reports "no cases scored" on a nil aggregate would
// contradict the count it prints beside it.
AggregateUnavailable bool
// Stats is what the executor did.
Stats executor.Stats
// Spent is what the run actually cost, settled.
//
// Carried here rather than on the Run because it is the guard's number,
// not the schema's — and a caller reporting spend should read what the
// guard settled rather than re-deriving it from stored outcomes.
Spent budget.Spend
}
BaselineResult reports what a Baseline run produced.
func Baseline ¶
func Baseline( ctx context.Context, evals *SealedEvals, opts BaselineOptions, ) (result *BaselineResult, err error)
Baseline runs the agent over the dev Cases and scores each Response.
It takes a *SealedEvals, not an Evals. That is a compile-time guarantee that this stage cannot read the holdout: every statistical claim the tool makes downstream depends on the holdout being untouched until Validate, and a requirement enforced by the type cannot be forgotten in a later refactor.
Every Agent call passes through the budget guard. There is no path in this function that spends without an authorized reservation, and every reservation is released or settled on every path.
type Capabilities ¶
type Capabilities = knov1.Capabilities
Capabilities is what an adapter can actually do.
type Capable ¶
type Capable interface {
// Capabilities reports what this adapter supports. It must not return nil.
Capabilities() *Capabilities
}
Capable is implemented by adapters that declare what they support.
Capabilities are checked BEFORE work is scheduled, so an unsupported injection mode is reported as a capability gap at connect time rather than as a run of mysterious failures. An adapter that does not implement Capable is treated as supporting nothing beyond Invoke.
type ContextInjector ¶
type ContextInjector interface {
// WithContext returns an Agent that carries a in its context. The receiver
// is unmodified, so the original Agent remains usable as a control.
WithContext(a *Asset) (Agent, error)
}
ContextInjector is an Agent that can carry an Asset in its prompt.
This is the UPPER-BOUND measurement mode: it bypasses retrieval entirely, so it measures what an Asset could contribute if retrieval were perfect. Results are reported as bounds, never as deployment predictions.
type ContextSetInjector ¶ added in v0.1.4
type ContextSetInjector interface {
// WithContextSet returns an Agent carrying every Asset, in the given
// order. The receiver is unmodified and remains usable as the control arm
// of the same measurement — the same contract, for the same reason, as
// ContextInjector.WithContext.
//
// ORDER IS PART OF THE MEASUREMENT and callers pass it deliberately:
// Validate applies PortfolioEntry.rank. Providers cache on a PREFIX, and a
// portfolio prefix that is byte-identical across every holdout Case is the
// difference between paying for the set's tokens once and paying for them
// on every Case.
//
// An empty or nil slice must be refused rather than answered: an Agent
// carrying no Assets is the control arm, and returning one here would
// measure the control against itself and report the difference as zero,
// with an interval.
WithContextSet(assets []*Asset) (Agent, error)
}
ContextSetInjector is an Agent that can carry a whole Portfolio in its prompt.
A separate capability from ContextInjector rather than a loop over it, and the reason is a refusal that already exists: every ContextInjector in the tree rejects a SECOND Asset, because a per-Asset Valuation silently becoming a two-Asset one is precisely what that refusal prevents. Loosening it to serve Validate would remove a guard from the stage that needs it most, so Validate asks for a different operation instead.
Like ContextInjector this is the UPPER-BOUND mode: the whole set is handed to the model directly rather than reached through a retriever, so the holdout gain it produces is an upper bound on what retrieval would deliver, and every rendering says so.
type Destination ¶
type Destination = knov1.Destination
Destination is where a measured Asset belongs.
type Endpoint ¶ added in v0.1.7
type Endpoint struct {
// ID is the provider-assigned endpoint identifier — what a user would
// look up in the provider's own console if Teardown ever fails.
ID string
// Provider names which Tuner this came from: "together", "fireworks",
// "openai".
Provider string
// Served is the model this endpoint serves, usable as the Ref of an
// AgentRef once Ready is true.
Served string
// Replicas is how many running replicas are billing. Together's per-
// minute rate is per replica; a zero-rate no-op Endpoint (an
// auto-serving provider) may report zero here without implying nothing
// is servable.
Replicas int
// Ready reports whether the endpoint is currently answering requests.
// False while deploying or after teardown.
Ready bool
// ReadyAt is when the endpoint first became ready, zero if it never did.
// The billing clock the per-minute settlement loop reads from.
ReadyAt time.Time
}
Endpoint is a tuned model's live serving location.
A Go struct, not a proto message — deliberately. It is an adapter-lifecycle type with (for now) exactly one implementation, and committing a wire contract to it would repeat the mistake TuningJob.lora_rank nearly made: describing a shape no second adapter has confirmed. The bridge plan's Step 2(f) is explicit about this; TuningEndpointChanged carries the fields a consumer needs on the event stream instead.
type Estimator ¶
type Estimator interface {
// Estimate reports the most one Invoke of c could cost.
//
// It MUST be local: arithmetic over a pricing table the adapter already
// holds. It must not call the provider. This runs BEFORE the budget guard
// authorizes anything, so a network call here spends money outside the
// guard entirely — the one thing prime directive 4 forbids — and a slow one
// blocks a worker while holding no reservation. The engine bounds the call
// with a timeout, but a timeout cannot un-spend a request already sent.
//
// Calls must be exactly 1. One Invoke settles as one provider call, so
// reserving more would reserve N and settle 1, and the call cap would drift
// by (N-1) for every Case. An adapter whose single Invoke really does make
// several provider requests needs the settlement side to carry that too;
// until it does, the engine refuses the Case rather than mis-count it.
//
// An error means the cost is unknown, which is NOT the same as zero: a zero
// estimate makes a dollar cap unenforceable, so the engine treats a
// zero-cost answer under a cost cap exactly as it treats an error. Report
// the error; do not invent a cheap number.
Estimate(ctx context.Context, c *Case) (budget.Estimate, error)
// WorstCase reports the most any single Case could cost, before any Case is
// seen.
//
// Planning needs a number and per-Case estimates need a Case, so without
// this the engine plans against BaselineOptions.EstCostPerCallUSDMicros —
// a scalar an Estimator does not use. Measured with an adapter pricing at
// $0.20 against a scalar of $0.001: the consent prompt quoted $0.06 for a
// run whose real exposure was $12.00, and the feasibility check computed
// enough headroom for 250 in-flight Cases while the run stalled at 0 of 60.
//
// An adapter can answer because the output term dominates and is known up
// front: the output ceiling times the output rate, plus whatever the
// largest plausible prompt costs. It must be an upper bound, for the same
// reason Estimate must be.
WorstCase() budget.Estimate
}
Estimator is an Agent that can say what a Case will cost before it runs.
Named for the value it produces — budget.Estimate — rather than introducing a second word for the same act. The plan called this a Predictor; "predict" and "estimate" would then be two names for one thing, which is the drift the vocabulary rule exists to stop.
Optional, like Capable and the injectors: an adapter that does not implement it falls back to BaselineOptions.EstCostPerCallUSDMicros, so the fake agent and every existing caller are unaffected.
It exists because a cost cap the guard checks only at settlement is a cap discovered after the money is gone — that failure already overshot a $0.10 cap once. And the cost of a Case depends on the Case: its input tokens are the input term of the arithmetic. A single run-scoped scalar cannot express that, which is why this is an interface on the adapter rather than another field on the options.
The estimate must be PESSIMISTIC — the most a call could cost, not the most likely. It bounds a reservation, and a bound that can be too low is not a bound. Under-predicting is how a run walks past its cap; over-predicting only makes the guard refuse early, which is the recoverable direction.
type Evals ¶
type Evals interface {
// Cases returns an iterator over the eval Cases.
//
// The outer error reports a failure to OPEN the source — an unreadable
// file, an unreachable server. Once that succeeds, the contract on the
// iterator is:
//
// - A yielded error is FATAL. The consumer MUST stop ranging. Adapters
// that tolerate malformed records handle them internally and report
// counts via Provenance — never by yielding a skippable error. This is
// one rule rather than two on purpose: if one adapter skipped bad
// records and another halted, the denominator behind every confidence
// interval would silently vary by adapter, and nothing would show it.
//
// - The producer MUST defer resource cleanup INSIDE the iterator
// closure. Early break is legal and expected, and cleanup registered
// outside the closure will not run.
//
// - The producer MUST check ctx.Err() before each yield. iter.Seq2
// carries no cancellation channel of its own.
//
// - Yielded values are BORROWED for one iteration. Consumers clone
// before retaining or mutating; producers may reuse the backing memory
// between yields.
//
// Adapters prove they satisfy this by passing coretest.ConformIterator.
Cases(ctx context.Context) (iter.Seq2[*Case, error], error)
}
Evals supplies the Cases to measure against — the exam.
Deliberately separate from Pool: the exam and the study material are different things with different sources, and conflating them made --pool ambiguous.
type ExportOptions ¶ added in v0.1.0
type ExportOptions struct {
// RunID identifies this Export run.
RunID string
// SelectRunID is the run whose Portfolio is exported.
SelectRunID string
// Store is where the Portfolio and the Run records live.
Store store.Store
// Pool supplies Asset content. Required: the Portfolio carries
// measurements, not content, and the pool is the only place content
// lives — so an Export without one cannot render anything.
Pool Pool
// Destination is the grammar to render into. One of context,
// knowledge_base, or tuning_set; UNSPECIFIED is refused.
Destination knov1.Destination
// Path is where the rendered artifact is written. The manifest is
// written beside it at Path + ".manifest.md".
Path string
// Force replaces an existing file at Path. Refused without it: an
// overwritten export is a silent mutation, and this stage's contract is
// that nothing is silently mutated.
Force bool
}
ExportOptions configure the Export stage.
Export renders the selected Assets of a Select run's Portfolio into the Destination's grammar, at a local path. It never touches the Destination itself — the adapters that write a knowledge base are the v0.2 half the manifest names — and it never mutates the Portfolio or any pool.
func (ExportOptions) Export ¶ added in v0.1.0
func (o ExportOptions) Export(ctx context.Context) (*ExportResult, error)
Export executes the stage: load the Portfolio, render the selected Assets of one Destination into its grammar, and write atomically.
The output is a pure function of the Portfolio and the pool, so a re-export is byte-identical (goldens pin it) and Export can never make a Portfolio lie: the artifact is derived, the record is the source.
type ExportResult ¶ added in v0.1.0
type ExportResult struct {
// RunID identifies the run.
RunID string
// SelectRunID is the Select run whose Portfolio this artifact was
// rendered from — the artifact's provenance link. Reported so a consumer
// holding a tuning set can say which measured Portfolio produced it
// without re-deriving it from the manifest.
SelectRunID string
// Destination rendered.
Destination knov1.Destination
// AssetCount is how many selected entries the artifact holds.
AssetCount int
// BytesWritten is the artifact and manifest bytes on disk.
BytesWritten int64
// Path is where the artifact was written.
Path string
}
ExportResult is what an Export run produced.
type Goal ¶
type Goal interface {
// Score judges one Response against its Case.
Score(ctx context.Context, c *Case, r *Response) (*Score, error)
// Domain reports the set of values Score.value can take.
//
// Declared, never inferred from the scores a run happens to produce.
// Inferring it is method selection from the sample: a confidence level
// would then hold only conditional on a branch that is itself a function
// of the data, one extra observation could flip a measurement between
// branches, and across many measurements some would land in each branch by
// luck while a consumer compared their intervals as if commensurable.
//
// It is on the interface rather than optional so that a new Goal cannot
// land without answering — the interval method for every delta measured
// against it depends on this, and a Goal that stayed silent would get the
// continuous methods, which are valid but wider than they need to be.
Domain() ScoreDomain
// Direction reports which way is better for this Goal.
//
// Without it the sign of every delta is uninterpretable: a -0.03 is an
// improvement for a latency Goal and a regression for an accuracy one.
// Implementations must not return DIRECTION_UNSPECIFIED.
Direction() Direction
}
Goal scores an outcome. Composable and weighted, defined as YAML plus BAML prompt files — extending a Goal is a prompt edit, never a Go plugin.
type InjectionMode ¶
type InjectionMode = knov1.InjectionMode
InjectionMode records how a Valuation was measured.
type Interval ¶ added in v0.1.0
Interval is a confidence interval, deliberately a message so absence is representable.
type KnowledgeInjector ¶
type KnowledgeInjector interface {
// WithKnowledge writes a into the agent's index and returns an Agent that
// can retrieve it, plus a rollback function.
//
// The rollback MUST be called when the caller is done, including on error
// paths — otherwise a valuation run permanently mutates the user's
// production knowledge base. `defer rollback()` is the sanctioned idiom.
WithKnowledge(ctx context.Context, a *Asset) (agent Agent, rollback func() error, err error)
}
KnowledgeInjector is an Agent whose knowledge index Kno can write.
This is the DEPLOYMENT-FAITHFUL mode: the Asset is reached through the agent's own retriever, so the measurement reflects what would actually happen in production. It is also the only mode that preserves the difference between "the data was missing" and "the data was there but retrieval missed it" — context injection collapses the two.
type Pool ¶
type Pool interface {
// Assets returns an iterator over the candidate Assets.
//
// The contract is identical to Evals.Cases: a yielded error is fatal,
// cleanup is deferred inside the closure, ctx is checked before each
// yield, and values are borrowed for one iteration. See Evals.Cases.
Assets(ctx context.Context) (iter.Seq2[*Asset, error], error)
}
Pool supplies the candidate Assets — the study material.
type PortfolioEntry ¶ added in v0.1.0
type PortfolioEntry = knov1.PortfolioEntry
PortfolioEntry is one selected Asset and the measurement that earned it.
type ScoreDomain ¶
type ScoreDomain = knov1.ScoreDomain
ScoreDomain is the set of values a Goal.Score can take. See Goal.Domain.
type ScoreParams ¶ added in v0.1.7
type ScoreParams struct {
// Agent is the deployed model to invoke.
Agent Agent
// AgentRef names the scheme on the provider-call span.
AgentRef *AgentRef
// Goal scores each Response. Its Direction is applied to every score
// this pass returns — see ScoreResult.Scores.
Goal Goal
// Cases is a *SealedEvals, not a bare iter.Seq2. core/seal.go:19-22
// records "convention plus a canary" as a design tried and rejected for
// exactly this reason: a canary test proves only that one call site
// behaved on the day it was written, while a compile-time requirement
// cannot be forgotten in a later refactor. core.Baseline already takes
// the sealed type and calls .Cases(ctx) internally; ScorePass does the
// same.
Cases *SealedEvals
// Guard authorizes and settles every call this pass makes.
Guard *budget.Guard
// AcceptFreeCalls asserts that every Invoke this pass makes is already
// paid for through a channel other than the per-call budget guard.
//
// The bridge is the caller this exists for: a Together dedicated
// endpoint is reserved capacity billed per minute per replica, settled
// forward by its own hosting ticker (bridge/hosting.go); inference on
// it is zero-marginal, already covered by that ticker's dollars, and
// charging a per-call estimate on top would double-count the same
// money. core/ring0.go's Estimator doc states the engine's default
// rule: "a zero estimate makes a dollar cap unenforceable, so the
// engine treats a zero-cost answer under a cost cap exactly as it
// treats an error" — an UNASSERTED zero must not be trusted. This flag
// is the assertion, mirroring cli/baseline.go:346's
// `AcceptUnknownCost: f.acceptUnknownCost || f.costPerCallSet` and its
// own reasoning: "an explicit zero is a claim that the calls are free;
// an absent flag is no claim." When true, ScorePass estimates every
// Case at budget.Estimate{Calls: 1} (zero cost) unconditionally.
AcceptFreeCalls bool
// EstCostPerCallUSDMicros is the fallback per-call estimate when Agent
// does not implement Estimator and AcceptFreeCalls is false. Mirrors
// BaselineOptions.EstCostPerCallUSDMicros.
EstCostPerCallUSDMicros int64
// Concurrency bounds in-flight work. Zero picks a conservative default.
Concurrency int
// MaxAttempts, RetryBudget and RetryBackoff bound retries. Zero means
// the same defaults Baseline and Value use.
MaxAttempts int
RetryBudget, RetryBackoff time.Duration
// Skip reports whether a Case is already scored and should not be
// invoked again. Nil means score everything. This is how a resumed
// bridge group avoids re-paying for Cases a prior process already
// scored and durably recorded through OnScored.
Skip func(caseID string) bool
// OnScored is called once a Case's score is settled — durably, as it
// happens, not batched at the end. An error stops the pass. This is
// what makes ScorePass's resume story work at all: the caller (bridge)
// persists each Case's score the moment it lands, so a process killed
// mid-pass leaves exactly the Cases it paid for recorded, and none
// re-paid for on resume.
OnScored func(ctx context.Context, caseID string, score float64, spend budget.Spend) error
// OnOvershoot and OnRetry mirror invoker's hooks of the same name. Nil
// is allowed and means "do not report". The measurement key they
// receive carries only the Case ID: ScorePass has no Asset or Arm
// concept of its own, and a caller that wants one (bridge: the
// ablation group) enriches the key itself before emitting.
OnOvershoot func(ctx context.Context, key store.MeasurementKey, estimated, settled, overshoot int64)
OnRetry func(ctx context.Context, key store.MeasurementKey, attempt int, reason knov1.RetryReason, wait, remaining time.Duration)
}
ScoreParams configures one ScorePass.
type ScoreResult ¶ added in v0.1.7
type ScoreResult struct {
// Scores maps Case ID to its score, direction-normalised: multiplied by
// -1 when Goal.Direction() is DIRECTION_MINIMIZE, so that a HIGHER
// number always means better regardless of the Goal's natural polarity
// — the same convention core/value_measure.go's pairs applies to
// deltas, applied here to a raw score instead. Raw, never a delta:
// pairing against another pass's scores is the caller's job.
Scores map[string]float64
// Errors maps Case ID to its terminal failure code, for Cases that did
// not score. A Case present in neither Scores nor Errors was never
// reached (Skip returned true, or the pass stopped early).
Errors map[string]string
// Spent is every dimension the guard settled across the whole pass —
// Calls, CostUSDMicros and Tokens. Dropping Tokens has been the same
// bug twice (#170, #172); it is carried here explicitly rather than
// left to a caller that only remembers CostUSDMicros.
Spent budget.Spend
}
ScoreResult is what one ScorePass produced.
func ScorePass ¶ added in v0.1.7
func ScorePass(ctx context.Context, p ScoreParams) (*ScoreResult, error)
ScorePass invokes agent once per Case and scores each answer against goal, under the budget guard, with the same retry and settlement behaviour every other stage gets — core.invoker (core/invoke.go), the six-separately- discovered-defects retry core Baseline, Value and Validate already share. This is the narrow seam the tuner-bridge plan's eval-seam amendment calls for: bridge needs to invoke a deployed model over Cases and score it, and the alternative (re-implementing authorize/call/settle/retry a fourth time) is how a fourth caller comes to disagree with the other three about money.
ScorePass creates no Run and writes no measurement rows. Persistence is the CALLER's job, through OnScored — see ScoreParams.Skip and OnScored's doc for why: the Case is the unit of spend, and a bulk in-memory return with no per-Case checkpoint cannot express "resume must never re-pay for a Case already scored."
The doc this seam originally shipped with said bridge would pair every group's scores "against the all-in baseline model's score for the same Case, which bridge.Run already holds" — that was false (see docs/plans/2026-09-01-bridge-eval-seam.md's Phase 1 review, finding R1), and ScoreResult.Scores is deliberately RAW scores keyed by Case ID, never deltas: pairing belongs to bridge.Run, the component that legitimately holds both a group's scores and the all-in baseline's.
type SealedEvals ¶
type SealedEvals struct {
// contains filtered or unexported fields
}
SealedEvals yields only dev Cases. Holdout Cases are not reachable through it at all.
This is a distinct TYPE rather than a wrapper returning core.Evals, and that is the entire point. A function that requires a *SealedEvals cannot be handed a raw adapter: forgetting to seal is a compile error, not a discipline lapse discovered by review three months from now.
The earlier design returned core.Evals from Seal, which meant any code holding the raw adapter compiled cleanly and read the holdout. A canary test would then have proven only that one call site behaved on the day it was written.
Why the seal lives here and not in the adapter: an Evals adapter reads a file. It has no idea which stage is running, so any restriction it enforced would be advisory, in the ring with the least context and the most implementations. The engine knows the stage; the engine holds the seal.
func Seal ¶
func Seal(e Evals) *SealedEvals
Seal restricts an Evals source to its dev split.
Every stage before Validate takes the result. Validate reads the holdout through a separate path that does not exist yet — deliberately. Designing how a holdout is legitimately opened, and who may do it, belongs with the stage that needs it, not three milestones early against a token nobody can meaningfully gate.
func (*SealedEvals) Cases ¶
Cases yields the dev Cases.
It preserves the Evals.Cases contract and adds one rule: a Case whose Split is anything other than SPLIT_DEV is not yielded.
The seal filters; it does not independently enforce the rest of the contract. Cancellation checks, cleanup-inside-the-closure, and the borrow rule remain the inner producer's obligations, and a non-conformant producer stays non-conformant through the seal. coretest.ConformIterator is what holds adapters to those; this type holds them to the split.
An unassigned Split (SPLIT_UNSPECIFIED) is filtered out too, and that is not an accident. A Case with no split has not been through ingestion, and treating "unknown" as "dev" is exactly how a holdout leaks: silently, one Case at a time, in the direction that inflates the reported gain.
type SelectOptions ¶ added in v0.1.0
type SelectOptions struct {
// RunID identifies this Select run.
RunID string
// ValueRunID is the Value run whose recorded Valuations this builds on.
// The source run's status travels to the Portfolio: a Portfolio built
// from a budget-stopped run is a different statement from one built from
// a completed run.
ValueRunID string
// Store is where Valuations are read and the Portfolio is written.
Store store.Store
// Pool supplies Asset content and destinations. Optional: without it the
// REDUNDANT and WRONG_MECHANISM rules cannot run, and the result names
// which rules were degraded — the budget rules and every measurement-
// based reason still decide.
Pool Pool
// Budget is the constraint set the Portfolio is built under. Every cap
// is honored per selected Asset and checked before the Asset joins.
Budget *knov1.Budget
// AllowPartial accepts a source run that did not complete (BUDGET_STOPPED
// or INTERRUPTED) and builds from its recorded Valuations, carrying the
// source status on the Portfolio. Refused without this flag: a partial
// source would rank an incomplete measurement set as if it were the
// whole answer.
AllowPartial bool
// Level is the confidence level every interval this stage decides with
// is computed at. Zero means the stage default, 0.95.
Level float64
}
SelectOptions configure the Select stage.
The stage reads ONLY the Value run's recorded Valuations — it takes no Evals, so the holdout cannot be reached through it, and every decision below is a pure function of what the store holds.
func (SelectOptions) Select ¶ added in v0.1.0
func (o SelectOptions) Select(ctx context.Context) (*SelectResult, error)
Select executes the stage: rank the recorded Valuations on delta_per_cost, decide each Asset in precedence order, and write the Portfolio.
Greedy on delta_per_cost with per-item feasibility checks — a deliberately simple construction with no approximation guarantee, and the plan says so. Every keep/reject interval is Bonferroni-corrected for the number of Assets screened, and the portfolio-level gain is a single corrected claim combined under the shared-draw covariance discipline (stats/portfolio): never the sum of independent intervals, because routed slices overlap and every delta pairs against the shared baseline draw.
"Include nothing new" is a legal, first-class outcome: an empty selection with a full rejection log is a completed run.
type SelectResult ¶ added in v0.1.0
type SelectResult struct {
// RunID identifies the run.
RunID string
// Portfolio is the constructed Portfolio, source status included.
Portfolio *knov1.Portfolio
// Status is how the run ended.
Status knov1.RunStatus
// DegradedRules names the rejection rules that could not run because no
// Pool was given — REDUNDANT and WRONG_MECHANISM need content and
// destinations. Reported, never silent.
DegradedRules []string
}
SelectResult is what a Select run produced.
type Tuner ¶
type Tuner interface {
// Submit sends a tuning job to the provider.
Submit(ctx context.Context, job *TuningJob) (*JobRef, error)
// Status reports where a submitted job stands.
Status(ctx context.Context, ref *JobRef) (*JobState, error)
// Model returns the tuned model as an agent ref.
//
// This is NOT a promise the model is reachable. Some providers auto-serve
// a finished job; Together does not — reaching a Together fine-tune over
// HTTP requires Deploy first. A caller that needs to invoke the model
// must call Deploy and wait for the returned Endpoint to be ready before
// using this ref against an Agent adapter.
Model(ctx context.Context, ref *JobRef) (*AgentRef, error)
// Deploy brings a finished job's model up behind a servable endpoint.
//
// This is the SECOND spend shape the bridge introduces: unlike Submit, it
// bills incrementally (per minute per replica, idle included) and CAN be
// stopped, so the engine settles it forward per tick through the budget
// guard rather than reserving a pessimistic lump sum at call time — see
// Step 2(f). A Tuner whose provider auto-serves a finished job (no
// separate deploy step) implements this as a no-op returning a
// zero-rate Endpoint, which is how the interface stays honest for a
// provider that is not Together.
//
// The caller is responsible for waiting until the returned Endpoint is
// ready (however this Tuner signals that — a status field, a poll) before
// invoking the model, and for calling Teardown exactly once when done,
// unconditionally, including on every error and cancellation path.
Deploy(ctx context.Context, ref *JobRef) (*Endpoint, error)
// Teardown stops a deployed endpoint and its billing.
//
// MUST be called on every exit path once Deploy has returned successfully
// — success, eval-pass failure, a budget or serve-minute cap, a timeout,
// or cancellation. An error here means the endpoint may still be live and
// billing after the caller has moved on: the caller must treat that as
// loud (see docs — a leaked endpoint is reported, never swallowed), not
// as a retryable nuisance.
Teardown(ctx context.Context, ep *Endpoint) error
// ListJobs lists the provider's fine-tuning jobs whose submitted suffix
// matches suffix exactly, most-recently-submitted first.
//
// This is the tuner-bridge plan's Step 2(d) adopt-by-suffix mechanism,
// used ONLY to recover a row a resume finds still in the write-ahead
// "submitting" state after a crash: the caller does not know whether the
// prior process's Submit request reached the provider before the process
// died, and the answer changes what "resume" means for that group — poll
// an adopted job, or accept the group as abandoned with its estimate
// still settled. Never called to discover work; SubmitGroup is the only
// caller.
//
// This is an ADDITIVE method the tuner-bridge plan's Step 0 did not
// originally scope (it named "exactly two" additions, Deploy and
// Teardown) — Step 2(d)'s own text already described "the adapter lists
// the provider's jobs and adopts one whose model-name suffix matches" as
// the mechanism, so the omission from Step 0's count was the plan's
// error, not a reason to skip building the recovery path Step 2(d)
// requires. See this PR's report.
ListJobs(ctx context.Context, suffix string) ([]*JobRef, error)
// ListEndpoints lists the provider's dedicated endpoints whose served
// model name carries suffix, most-recently-created first.
//
// This is the tuner-bridge plan's Step 2(g) resume-time sweep mechanism
// — used ONLY when a resume finds a durable tuning-job row whose
// EndpointID is unset but whose DeployedAt is set: Deploy may have
// succeeded at the provider before the write recording its EndpointID
// landed, in which case the row alone cannot say whether an endpoint is
// live and billing. When a row's EndpointID IS recorded, the sweep tears
// that endpoint down directly and never calls this.
//
// Additive for the same reason ListJobs is: Step 2(g)'s own text says
// "list the provider's endpoints", and Step 0's "exactly two" count did
// not anticipate that mechanism either.
ListEndpoints(ctx context.Context, suffix string) ([]*Endpoint, error)
}
Tuner submits and tracks fine-tuning jobs on hosted APIs.
Orchestration is HTTP calls — there is no torch in this binary. That constraint is what makes proxy fine-tuning affordable enough to be a measurement rather than an infrastructure commitment.
Every Submit is a spend path, so it must pass the budget guard first. So is Deploy: a Together dedicated endpoint bills per minute per replica, idle included, which is a SECOND spend shape distinct from Submit's one-time commitment — see the bridge plan's Step 2(f). Both must flow through stats/budget before any request leaves.
type ValidateOptions ¶ added in v0.1.4
type ValidateOptions struct {
// RunID identifies this Validate run.
RunID string
// SelectRunID is the Select run whose Portfolio is being validated.
SelectRunID string
// Agent is the CONTROL arm: the agent with nothing injected. It must also
// implement ContextSetInjector, which validate refuses without.
Agent Agent
// AgentRef identifies the agent, for the Run record and the event stream.
AgentRef *AgentRef
// Goal scores every measurement, and its Domain decides the interval
// method for the one delta this run reports.
Goal Goal
// GoalName is the Goal's registered name.
GoalName string
// Guard authorizes every measurement before it is made.
Guard *budget.Guard
// Evals is the eval source, UNSEALED and deliberately so.
//
// A plain Evals, not a *SealedEvals and not a holdout reader: the holdout
// reader is unexported, so cli, tui and api cannot construct one, and
// Validate opens the holdout itself through openHoldout. A caller handing
// over a *SealedEvals is refused with errs.ErrHoldoutSealed rather than
// iterating one and finding no Cases — see openHoldout.
Evals Evals
// Pool supplies the Assets the Portfolio names, so their content can be
// injected and checked against PortfolioEntry.content_hash.
Pool Pool
// Store is where measurements, the holdout-use record and the Validation
// become durable.
Store store.Store
// Concurrency bounds workers within one arm.
Concurrency int
// Trials is how many times each (Case, arm) is measured. Zero means once.
Trials int32
// Resume continues a run whose measurements are already partly recorded.
Resume bool
// ContextOnly validates the DESTINATION_CONTEXT entries of a mixed
// Portfolio, and labels the result a SUBSET everywhere it appears.
//
// Refused by default: a number about the context entries, reported as "the
// Portfolio's holdout gain", is a number about a different set than the one
// the user is about to export.
ContextOnly bool
// AllowRepeatHoldout permits a SECOND, different Portfolio to be measured
// against a holdout that has already been used.
//
// Counted and disclosed, never corrected for: validating N portfolios
// against one holdout re-introduces the multiplicity the holdout existed to
// remove, at rate N. The flag exists because the alternative to a counted
// peek is an uncounted one — the user deletes kno.db or re-splits with
// --split-seed, and the tool has traded an honest number for a comfortable
// rule.
AllowRepeatHoldout bool
// MaxContextTokens refuses a Portfolio whose summed carrying cost exceeds
// it, before any spend. Zero is unset, in which case the Portfolio's own
// recorded Budget.max_context_tokens applies.
MaxContextTokens int64
// MinHoldout is the holdout size below which the number is marked
// underpowered.
//
// Supplied by the caller rather than read from adapters/evals/split, which
// core cannot import (CLAUDE.md prime directive 3). cli passes
// split.MinHoldout, and a test pins that, so changing the constant changes
// this verdict. Zero disables the marking.
MinHoldout int32
// EvalFingerprint identifies the HOLDOUT — the eval source's content hash
// combined with the split configuration that divided it.
//
// It is the key of the one-shot record. Two runs sharing it met the same
// Cases; a run with a different one is looking at a different holdout and
// is not a repeat.
EvalFingerprint string
// InputFingerprint pins the inputs, so a resume cannot silently continue a
// different run.
InputFingerprint string
// EstCostPerCallUSDMicros is the fallback estimate for agents that do not
// implement Estimator, exactly as Baseline and Value use it.
EstCostPerCallUSDMicros int64
// MaxAttempts, RetryBudget and RetryBackoff bound retries per measurement,
// exactly as they do for Baseline and Value.
MaxAttempts int
RetryBudget int64
RetryBackoff int64
}
ValidateOptions configure the Validate stage.
Shaped like ValueOptions where the two stages agree, because they share a Store, a Guard, an executor and an invoker — a field meaning one thing here and another there is how a resume check ends up comparing the wrong pair of values.
func (ValidateOptions) Quote ¶ added in v0.1.4
func (o ValidateOptions) Quote(ctx context.Context) (ValidateQuote, error)
Quote computes what a Validate run would cost, without spending and without consuming the holdout.
It opens the holdout to COUNT it, which is not a peek: no Case is scored, no score is read, and no holdout_uses row is written. The one-shot record is about measurement, and measurement begins in Validate.
func (ValidateOptions) Validate ¶ added in v0.1.4
func (o ValidateOptions) Validate(ctx context.Context) (*ValidateResult, error)
Validate executes the stage: open the holdout, record that it was opened, measure every holdout Case in two arms — one carrying the whole Portfolio, one carrying nothing — and write the paired difference with its interval.
It is the only stage permitted to read SPLIT_HOLDOUT Cases, and the only caller of openHoldout in the module. Every stage before it takes a *SealedEvals; this one takes a plain Evals and opens the holdout itself, because the reader is unexported and cli cannot construct one.
Two arms, both measured in THIS run, and the cost consequence is stated up front because it is the design's main price: 2 x n_holdout x trials agent calls. The alternative — pairing a holdout treatment score against the recorded dev Baseline mean — is half the price and is not an estimator of anything: core.Baseline takes a *SealedEvals, so no baseline run has ever scored a holdout Case, and the difference would carry the portfolio effect plus a random dev/holdout population difference plus provider drift, three terms in one number.
type ValidateQuote ¶ added in v0.1.4
type ValidateQuote struct {
// HoldoutCases is how many Cases the holdout yielded.
HoldoutCases int
// Arms is always validateArms. Carried explicitly so the consent line can
// SHOW the doubling rather than fold it into a total — a quote of
// n x trials would understate the run by exactly this factor.
Arms int
// Trials is the repeat count.
Trials int32
// Calls is HoldoutCases x Arms x Trials: the number the user consents to.
Calls int64
// AssetCount is how many Assets are injected as a set.
AssetCount int
// Underpowered reports a holdout below MinHoldout.
Underpowered bool
// ExcludedAssetIDs are the entries --context-only left out.
ExcludedAssetIDs []string
// NothingToValidate is set when there is no Asset to measure, in which
// case Calls is zero and the run makes no agent call at all.
NothingToValidate bool
}
ValidateQuote is the schedule a Validate run would execute, priced before anything is authorized.
func (ValidateQuote) Derivation ¶ added in v0.1.4
func (q ValidateQuote) Derivation() string
Derivation renders the quote's arithmetic for the consent dialog.
The derivation and not just the total, because prime directive 4 is about disclosure rather than magnitude: two arms is exactly double the naive expectation, and a user reading "40 calls" without "20 holdout Cases x 2 arms x 1 trial" has been told the number but not the shape of the run.
type ValidateResult ¶ added in v0.1.4
type ValidateResult struct {
// RunID identifies the run.
RunID string
// Validation is the finished record. Nil when the run produced none —
// interrupted, budget-stopped, or refused before it started.
Validation *Validation
// Status is how the run ended.
Status knov1.RunStatus
// GoalDirection is which way is better, so the report can un-negate
// MINIMIZE deltas for display.
GoalDirection knov1.Direction
// NothingToValidate is set when the Portfolio selected no Asset this stage
// can measure. A first-class outcome, not a failure: no agent call is
// made, no holdout is consumed, and the exit code is zero.
NothingToValidate bool
// HoldoutCases is how many Cases the holdout yielded.
HoldoutCases int
// HoldoutUseIndex is which portfolio this was for this holdout: 1 for the
// first.
HoldoutUseIndex int32
// AssetCount is how many Assets were injected as a set.
AssetCount int
// Spent is what the run actually cost, settled.
//
// The guard's number, not the schema's, for BaselineResult.Spent's reason,
// and populated on EVERY path returning a non-nil result including the
// error paths: a run that spent real money and then failed for a reason
// with nothing to do with money still owes the caller the figure. On a
// resumed run it is run-lifetime spend, because the run is the unit the
// user authorized.
Spent budget.Spend
}
ValidateResult is what a Validate run produced.
type Validation ¶ added in v0.1.4
type Validation = knov1.Validation
Validation is the holdout slice of a Report: what Validate measured and what it is allowed to claim.
type ValidationVerdict ¶ added in v0.1.4
type ValidationVerdict = knov1.ValidationVerdict
ValidationVerdict is what a Validate run concluded, keyed on the interval.
type ValueOptions ¶ added in v0.0.2
type ValueOptions struct {
// RunID identifies this Value run.
RunID string
// BaselineRunID is the run whose recorded scores this one pairs against.
//
// A separate run, and separate on purpose. The baseline is what the Asset
// is being measured AGAINST, and reading its scores through the Store
// rather than re-running it is what makes the stage affordable — and what
// makes ADR-0005's reasoning about which draw selected which Case
// checkable.
BaselineRunID string
// Agent is the control arm: the agent with no Asset injected. It must also
// implement ContextInjector, which validate refuses without.
Agent Agent
// AgentRef identifies the agent, for the Run record and the event stream.
AgentRef *AgentRef
// Goal scores every measurement, and its Domain decides the interval
// method for every delta this run reports.
Goal Goal
// GoalName is the Goal's registered name.
GoalName string
// Guard authorizes every measurement before it is made.
Guard *budget.Guard
// Evals is the SEALED dev split: SealedEvals never yields a non-dev Case,
// which is the holdout canary's enforcement rather than a scan. The stage
// reads Cases only through it.
Evals *SealedEvals
// EstCostPerCallUSDMicros is the fallback estimate for agents that do not
// implement Estimator, exactly as Baseline uses it.
EstCostPerCallUSDMicros int64
// Store is where measurements and Valuations become durable.
Store store.Store
// Concurrency bounds workers within one arm of one Asset. See the plan's
// note on the loop shape for why the bound is per-arm.
Concurrency int
// Routing configures which Cases measure which Asset.
Routing value.Options
// Resume continues a run whose measurements are already partly recorded.
Resume bool
// UnsafeBaseline accepts a baseline whose resolved models form a blend.
//
// Off by default, and deliberately awkward to reach: pairing against a
// control that mixes models is not an estimator of anything, because each
// Case's control draw came from a different agent. The flag exists for
// operators who know their blend is irrelevant to the Goal — the refusal
// cannot read that from the record.
UnsafeBaseline bool
// InputFingerprint pins the inputs, so a resume cannot silently continue a
// different run.
InputFingerprint string
// MaxAttempts, RetryBudget and RetryBackoff bound retries per measurement,
// exactly as they do for Baseline.
MaxAttempts int
RetryBudget int64
RetryBackoff int64
}
ValueOptions configure the Value stage.
Shaped like BaselineOptions on purpose: the two stages share a Store, a Guard, and an executor, and a field that means one thing here and another there is how a resume check ends up comparing the wrong pair of values.
func (ValueOptions) Quote ¶ added in v0.0.2
Quote computes the routing plan a Value run would execute under, without spending: the figure the user consents to before the first authorize. The run re-computes the plan itself — deterministic under the same seed — and asserts the schedule against it, so the quoted number is a bound on the run by construction rather than by trust.
func (ValueOptions) Value ¶ added in v0.0.2
func (o ValueOptions) Value(ctx context.Context, pool Pool) (*ValueResult, error)
Value executes the stage: route each Asset, measure it with the invoker per arm — the treatment arm carries the Asset, the control arm does not — and write one Valuation per Asset computed from what is DURABLY recorded.
The invoker is shared with Baseline (one budget-and-retry core, not two), and both of its hooks are wired: the money events carry the measurement key, so a retry or an overshoot is attributable to the (Asset, arm, trial) that caused it.
type ValueResult ¶ added in v0.0.2
type ValueResult struct {
// RunID identifies the run.
RunID string
// Valuations is one entry per Asset, including the Assets that routed to
// nothing — an Asset measured against zero Cases is a result, not an
// omission, and it is the one this stage can give away for free.
Valuations []*Valuation
// Plan is the routing decision every number here was produced under.
// Recorded so a reader can re-derive the selection from its seed.
Plan *value.Plan
// Status is how the run ended: COMPLETED, or BUDGET_STOPPED /
// INTERRUPTED with the truncated portfolio marked in the Valuations.
Status knov1.RunStatus
// GoalDirection is which way is better, so the report can un-negate
// MINIMIZE deltas for display: the stored delta is sign-corrected
// (positive is better), and the display wants the goal's own units.
GoalDirection knov1.Direction
// Spent is what the run actually cost, settled.
//
// Carried here rather than on the Run for BaselineResult.Spent's reason:
// it is the guard's number, not the schema's, and a caller reporting
// spend should read what the guard settled rather than re-deriving it
// from stored measurements. On a resumed run it is run-lifetime spend —
// Guard.Restore is additive and openRun seeds it from SettledSpend before
// anything is authorized — because the run, not the session, is the unit
// the user authorized.
//
// Populated on EVERY path that returns a non-nil result, including the
// error paths: a run that spent real money and then failed for a reason
// that has nothing to do with money still owes the caller the figure.
Spent budget.Spend
}
ValueResult is what a Value run produced.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package errs defines Kno's error grammar.
|
Package errs defines Kno's error grammar. |
|
Package value decides which Cases measure which Assets, and what that will cost, before any money is spent.
|
Package value decides which Cases measure which Assets, and what that will cost, before any money is spent. |