tune

package
v0.25.1 Latest Latest
Warning

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

Go to latest
Published: Sep 24, 2026 License: MIT Imports: 7 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package tune measures search-weight candidates against labelled feedback.

It is deliberately the only place that knows how to turn a set of weights into a number. The holdout half of the labels is never visible here: this package receives a *dataset.HoldoutSet at most as something to call Evaluate on, and the Go compiler prevents it from reading anything inside.

Index

Constants

View Source
const (
	// MinHoldoutQueries is the sample size below which no automatic promotion
	// happens at all. Thirty distinct queries is not a statistically comfortable
	// sample — it is the point below which NDCG differences are visibly
	// dominated by which individual query happened to be labelled.
	MinHoldoutQueries = 30
	// MinNDCGGain is the improvement a candidate must show on the holdout set.
	MinNDCGGain = 0.01
	// MaxFPRegression is how much worse the false-positive penalty may get
	// while still promoting. Surfacing known-bad documents is the failure the
	// user actually notices, so a large NDCG win does not buy the right to it.
	MaxFPRegression = 0.02
)

Promotion thresholds (plan §2.4, §2.5). They are exported so that the batch command can report them, but they are constants: an operator who wants a looser gate has to change this file and re-read the reasoning above it.

View Source
const (
	ReasonEligible         = "ok"
	ReasonHoldoutTooSmall  = "holdout_too_small"
	ReasonNDCGGainTooSmall = "ndcg_gain_below_threshold"
	ReasonFPRegression     = "fp_penalty_regression"
)

Gate reason codes.

These are a closed set on purpose: the code is written to the tune.gate_reason span attribute, which is exported to Langfuse. A free-text reason would eventually carry a fragment of a user's query into an external service by accident. The numbers behind a decision go to Postgres via Describe, not to the trace.

Variables

This section is empty.

Functions

func Describe

func Describe(reason string, in GateInput) string

Describe renders a gate outcome as the sentence stored in search_weights_history.gate_reason. It is the database-side counterpart of the reason code: the code says which rule fired, this says with what numbers, so that "why did the weights not move in August" has an answer that does not require re-running anything.

func Eligible

func Eligible(holdoutQueries int) (bool, string)

Eligible reports whether the holdout sample is large enough for an automatic promotion decision to mean anything.

It is a separate exported function rather than an `if` inside the promotion path because a lone `if` is exactly the kind of thing that acquires an "… || os.Getenv("JUST_THIS_ONCE") != """ six months from now. As its own function with its own tests, weakening it is a visible act.

func Objective

func Objective(m dataset.Metrics) float64

Objective scores a measurement. It delegates to dataset.ObjectiveOf so that the optimiser and the promotion gate cannot end up with different ideas of what an improvement is.

func PassesPromotion

func PassesPromotion(in GateInput) (bool, string)

PassesPromotion applies the three conditions in order and returns the reason code for the first one that fails.

Sample size is checked first so that a spectacular-looking win on twelve queries is reported as "too few queries" rather than as a metric verdict — the metrics are not trustworthy at that size, and recording a metric reason would make the history row read as if the numbers had been believed.

func RunnerFor

func RunnerFor(svc Searcher, w model.SearchWeights) dataset.RunFunc

RunnerFor returns a dataset.RunFunc that searches with exactly the given weights.

Weights travel on the query rather than through search.Service.WithWeights. WithWeights mutates the service and returns it, so evaluating a second candidate through the same instance would leave the first candidate's weights in place for any lane that did not overwrite them — a silent contamination that produces plausible-looking numbers for the wrong configuration. model.SearchQuery.Weights is per-request and takes precedence over the service-level value, which makes each evaluation independent by construction and lets a single service instance be reused safely.

Defaults() is applied so that a candidate can never collapse to the zero value, which search.Service reads as "fall back to whatever this service was configured with".

UseRerank and UseHyDE are forced off, not merely left unset:

  • HyDE calls a remote LLM, so the same query would retrieve different candidates on each sweep. A search whose result depends on the weather is not something to tune against, and hundreds of sweeps would bill for it.
  • The reranker is a separate HTTP service that the batch host is not guaranteed to reach (macmini and ubuntu1 cannot address each other's service ports). Baseline and candidate are compared under identical conditions, so the relative comparison stays valid; the absolute numbers are simply pre-rerank numbers, and the weights being tuned act on RRF fusion, which happens before reranking anyway. Record rerank=false alongside any promoted result so this is not mistaken for a live measure.

Types

type GateInput

type GateInput struct {
	BaseNDCG10     float64
	CandNDCG10     float64
	BaseFP10       float64
	CandFP10       float64
	HoldoutQueries int
}

GateInput is everything the promotion decision is allowed to look at: aggregate holdout metrics for the incumbent and the candidate, plus the sample size. No query, no document, no per-query detail.

func (GateInput) FPDelta

func (in GateInput) FPDelta() float64

FPDelta is the change in false-positive penalty. Positive means the candidate surfaces more known-bad documents than the incumbent.

func (GateInput) NDCGGain

func (in GateInput) NDCGGain() float64

NDCGGain is the holdout NDCG@10 improvement of the candidate over the incumbent. Negative means the candidate is worse.

type JudgeResult

type JudgeResult struct {
	Baseline       dataset.Metrics
	Candidate      dataset.Metrics
	HoldoutQueries int
}

JudgeResult is the entire holdout verdict: two sets of aggregate metrics and the sample size behind them.

func Judge

func Judge(ctx context.Context, h *dataset.HoldoutSet, baseline, candidate dataset.RunFunc) (JudgeResult, error)

Judge measures the incumbent and the candidate on the holdout set, in that order, and returns both.

This function exists so that there is exactly one place in the codebase where the holdout set is touched, and it touches it exactly twice. dataset's budget (DefaultHoldoutBudget = 2) makes a third look impossible; keeping the two permitted looks together here makes it obvious that a caller cannot smuggle in a third by evaluating "just the candidate again".

Because a failed evaluation still spends budget by design (an attempt that reached the search path has already observed the holdout set), an error from either run ends the tuning run rather than inviting a retry with different weights — a retry loop would be indistinguishable from tuning on the holdout set.

func (JudgeResult) GateInput

func (r JudgeResult) GateInput() GateInput

GateInput converts the verdict into the promotion gate's input.

type Result

type Result struct {
	// Best is the winning configuration, always a point on the grid.
	Best model.SearchWeights
	// BestObjective is its objective on the TRAINING set. It is not a holdout
	// number and must never be presented as one.
	BestObjective float64
	// StartObjective is the objective of the grid-snapped starting point, so
	// that "how much did searching actually buy" is answerable from the record.
	StartObjective float64
	Sweeps         int
	Evals          int
	// Trace is a human-readable log of accepted moves. It contains weights and
	// objective values only — no query text, no document IDs.
	Trace []string
}

Result is what a search run produces.

func Coordinate

func Coordinate(
	ctx context.Context,
	train *dataset.TrainSet,
	base model.SearchWeights,
	space SearchSpace,
	eval func(context.Context, model.SearchWeights) (dataset.Metrics, error),
) (Result, error)

Coordinate runs coordinate search over the training set.

The signature has no *dataset.HoldoutSet parameter, and that absence is the design: there is no argument position into which a holdout set could be passed by mistake, so no reviewer has to check that this function does not peek. The caller measures the holdout set separately, twice, through Judge.

eval is supplied by the caller rather than built here so that this function stays a pure optimiser over a scored space — it is tested against synthetic objectives with no database in sight.

type SearchSpace

type SearchSpace struct {
	FTS        []float64
	Vec        []float64
	Bigm       []float64
	SummaryVec []float64
	Entity     []float64
	RRFK       []float64
}

SearchSpace is the grid the optimiser is allowed to move on.

The grid is explicit rather than generated by a loop over a range and a step because 0.05 + 0.25 is not 0.30 in float64, and a candidate weight that differs from the recorded one in the sixteenth decimal is a reproducibility problem waiting to be debugged at the worst possible time.

func DefaultSpace

func DefaultSpace() SearchSpace

DefaultSpace is the grid from plan §2.4.

The lower bounds of SummaryVec and Entity are positive, not zero, and that is the load-bearing detail of this whole file. In model.SearchWeights, a zero SummaryVec means "unset — let the coverage gate decide" and a non-positive EntityWeight means "explicitly disabled". Either value would make the search report a configuration whose behaviour it never actually measured. Turning the summary lane off is a separate, explicitly evaluated candidate (DisableSummaryVec), not a point on this grid.

func (SearchSpace) Validate

func (s SearchSpace) Validate() error

Validate rejects a grid the optimiser cannot honestly search.

type Searcher

type Searcher interface {
	Search(ctx context.Context, q model.SearchQuery) ([]*model.SearchResult, error)
}

Searcher is the one capability the harness needs. *search.Service satisfies it.

Jump to

Keyboard shortcuts

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