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 PlanningCostPerCall(o BaselineOptions) int64
- type Agent
- type AgentRef
- type Asset
- type BaselineOptions
- type BaselineResult
- type Capabilities
- type Capable
- type Case
- type ContextInjector
- type Destination
- type Direction
- type Estimator
- type Evals
- type Goal
- type InjectionMode
- type JobRef
- type JobState
- type Kind
- type KnowledgeInjector
- type Pool
- type Portfolio
- type Report
- type Response
- type Score
- type ScoreDomain
- type SealedEvals
- type Split
- type Tuner
- type TuningJob
- 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.
Variables ¶
This section is empty.
Functions ¶
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.
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
// 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 Destination ¶
type Destination = knov1.Destination
Destination is where a measured Asset belongs.
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 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 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 ScoreDomain ¶
type ScoreDomain = knov1.ScoreDomain
ScoreDomain is the set of values a Goal.Score can take. See Goal.Domain.
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 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, usable directly for
// post-tune validation against the same untouched holdout.
Model(ctx context.Context, ref *JobRef) (*AgentRef, 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.
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
}
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. |