advisefeedback

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 13 Imported by: ? modules, 0 packages

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

Documentation

Overview

Package advisefeedback implements canonical, model-agnostic, scorer-attributed profiling advise findings, pre-edit pending outcome tracking, explicit feedback with verifiable evidence gates, Wilson score lower confidence bound ranking with a Bayesian exploration prior, human review queues, and cross-model transfer matrices.

This package is the single canonical owner of ComputeFindingID (using NUL-byte `\x00` field separation to prevent delimiter injection), Verdict, Feedback, WilsonLCB, and RuleStats. Domain-specific rule catalogs and capture analyzers live in consumer packages (such as cudaprof/advise) and register optional rule metadata via WithRules.

Core package logic imports only the Go standard library and communicates with external storage backends (such as nvidia/x/obs/tracedb) through the minimal Sink interface. Passing a nil Sink to NewStore runs purely in memory.

Deterministic Findings and Attribution

ComputeFindingID and ComputeFindingIDForModel produce deterministic 16-hex-character finding identifiers using `\x00` field separators so findings can be referenced across profiling sessions and attempts without separator-injection collisions.

Measured gains use positive fractional speedup: (baseline - candidate) / baseline (for example, +0.062 represents a 6.2% speedup, formatted in UI track records as latency delta "median -6.2%"). Non-finite values (NaN or ±Inf) are rejected as VerdictInvalid by ClassifyVerdict and rejected with ErrInvalidGain by scorer outcome recording methods.

Only trusted external scorer measurements recorded via Store.RecordScorerOutcome or Store.RecordScorerOutcomeWithInput contribute to scored rule statistics and ranking. Self-reported outcomes (ErrSelfReportForbidden), outcomes where scorer_uid matches or omits worker_uid (ErrWorkerUIDForbidden), and outcomes lacking an audit receipt (ErrMissingReceipt) are rejected.

Attempts that declare acts_on before editing may be recorded with VerdictPending via Store.RecordPendingOutcome (enforcing ErrActsOnNotDeclaredBeforeEdit). Pending outcomes are tracked separately in RuleStats.PendingCount and are strictly excluded from RuleStats.ActedOn, RuleStats.Evaluated, WilsonLCB, Store.AdviceThatWorkedForModel, and Store.TransferMatrix until promoted by a trusted external scorer.

Explicit Feedback and Human Review

Store.RecordFeedback records explicit FeedbackCorrection, FeedbackSuggestion, and FeedbackConfusing annotations. Corrections require verifiable evidence (EvidenceQueryHash, EvidenceCapture, or EvidenceCounterExampleAttempt; otherwise ErrEvidenceRequired is returned). Feedback referencing a finding with a mismatched rule_id is rejected with ErrRuleIDMismatch. Feedback never mutates rules automatically; rules exceeding configured hurt or correction thresholds and evidence-backed suggestions are surfaced in Store.ReviewQueue for human review.

Ranking and Cross-Model Transfer

Rule statistics are aggregated per (rule_id, rule_version, model, device, kernel_class). WilsonLCB, RuleStats.HelpRate, and RuleStats.HurtRate use valid evaluated outcomes (n = Helped + NoEffect + Hurt, excluding Invalid and Pending) as the denominator. Findings are ranked by WilsonLCB multiplied by verified expected gain, plus a decaying Bayesian exploration prior for under-sampled rules (Evaluated < StoreConfig.ExplorationMinActed). Store.TransferMatrix compares verified effectiveness across models while preserving rule_version and deterministic ordering.

This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.

Index

Constants

View Source
const (
	TableFindings = "advise_findings"
	TableOutcomes = "advise_outcomes"
	TableFeedback = "advise_feedback"
)

Table names emitted by Store to a configured Sink.

View Source
const (
	// DefaultNoiseThreshold is the default minimum fractional speedup (0.02 = 2%)
	// required to classify an outcome as helped or hurt rather than no_effect.
	DefaultNoiseThreshold      = 0.02
	DefaultMaxHurtRate         = 0.25
	DefaultMinHurtSample       = 3
	DefaultMaxCorrectionRate   = 0.20
	DefaultMinCorrectionSample = 2
	DefaultExplorationMinActed = 3
)

Variables

View Source
var (
	// ErrSelfReportForbidden rejects agent/worker self-reported "this helped" outcomes.
	ErrSelfReportForbidden = errors.New("advise: self-reported outcomes are forbidden; only scorer-measured outcomes count")

	// ErrWorkerUIDForbidden rejects outcomes attributed to or executed under the worker UID.
	ErrWorkerUIDForbidden = errors.New("advise: scorer_uid must be distinct from worker_uid")

	// ErrMissingReceipt rejects outcomes without an auditable receipt link.
	ErrMissingReceipt = errors.New("advise: receipt_id is required to audit scorer outcomes")

	// ErrInvalidGain rejects non-finite (NaN or ±Inf) gain or noise threshold values.
	ErrInvalidGain = errors.New("advise: gain and noise threshold must be finite numbers")

	// ErrFindingNotFound indicates a referenced finding_id does not exist.
	ErrFindingNotFound = errors.New("advise: finding not found")

	// ErrRuleIDMismatch rejects feedback whose explicit rule_id disagrees with
	// the referenced finding's rule_id.
	ErrRuleIDMismatch = errors.New("advise: rule_id does not match referenced finding")

	// ErrInvalidFeedbackKind indicates an unknown advise feedback kind.
	ErrInvalidFeedbackKind = errors.New("advise: invalid feedback kind (must be correction, suggestion, or confusing)")

	// ErrEvidenceRequired rejects correction feedback without verifiable evidence.
	ErrEvidenceRequired = errors.New("advise: correction feedback requires verifiable evidence (query_hash, capture, or counter_example_attempt)")

	// ErrInvalidEvidence indicates malformed evidence kind or empty evidence reference.
	ErrInvalidEvidence = errors.New("advise: invalid evidence kind or empty reference")

	// ErrMissingNote rejects explicit feedback without an explanatory note.
	ErrMissingNote = errors.New("advise: feedback note is required")

	// ErrActsOnNotDeclaredBeforeEdit rejects pending outcomes whose acts_on
	// finding_id was not declared before the attempt's edit was submitted.
	ErrActsOnNotDeclaredBeforeEdit = errors.New("advise: acts_on finding_id must be declared before edit")
)

Functions

func ComputeFindingID

func ComputeFindingID(ruleID, kernel, sourceLoc, captureDigest string) string

ComputeFindingID computes the canonical deterministic 16-hex-char finding identifier using NUL-byte separation to prevent delimiter injection: sha256(rule_id + "\x00" + kernel + "\x00" + source_loc + "\x00" + capture_digest)[:16].

func ComputeFindingIDForModel

func ComputeFindingIDForModel(ruleID, model, kernel, sourceLoc, captureDigest string) string

ComputeFindingIDForModel computes the canonical deterministic 16-hex-char finding identifier keyed by model when model != "":

  • model != "": sha256(rule_id + "\x00" + model + "\x00" + kernel + "\x00" + source_loc + "\x00" + capture_digest)[:16]
  • model == "": ComputeFindingID(rule_id, kernel, source_loc, capture_digest)

func WilsonLCB

func WilsonLCB(successes, total int) float64

WilsonLCB computes the 95% confidence Wilson score lower bound for successes out of total valid evaluated trials. Returns 0 when total <= 0 or successes <= 0.

Types

type Evidence

type Evidence struct {
	Kind EvidenceKind `json:"evidence_kind"`
	Ref  string       `json:"evidence_ref"`
}

Evidence links a feedback record to a verifiable artifact.

func (Evidence) Valid

func (e Evidence) Valid() bool

Valid reports whether e carries a recognized EvidenceKind and non-empty Ref.

type EvidenceKind

type EvidenceKind string

EvidenceKind classifies verifiable evidence attached to explicit feedback.

const (
	EvidenceQueryHash             EvidenceKind = "query_hash"
	EvidenceCapture               EvidenceKind = "capture"
	EvidenceCounterExampleAttempt EvidenceKind = "counter_example_attempt"
)

type Feedback

type Feedback struct {
	FeedbackID   string       `json:"feedback_id"`
	FindingID    string       `json:"finding_id,omitempty"`
	RuleID       string       `json:"rule_id"`
	Kind         FeedbackKind `json:"kind"`
	Note         string       `json:"note"`
	EvidenceKind EvidenceKind `json:"evidence_kind,omitempty"`
	EvidenceRef  string       `json:"evidence_ref,omitempty"`
	Actor        string       `json:"actor"`
	SessionID    string       `json:"session_id"`
	ReceiptID    string       `json:"receipt_id"`
	CreatedAt    time.Time    `json:"created_at"`
}

Feedback is a stored explicit feedback record.

type FeedbackInput

type FeedbackInput struct {
	FindingID string       `json:"finding_id,omitempty"`
	RuleID    string       `json:"rule_id,omitempty"`
	Kind      FeedbackKind `json:"kind"`
	Note      string       `json:"note"`
	Evidence  *Evidence    `json:"evidence,omitempty"`
	Actor     string       `json:"actor"`
	SessionID string       `json:"session_id"`
	ReceiptID string       `json:"receipt_id"`
}

FeedbackInput is the input to Store.RecordFeedback.

type FeedbackKind

type FeedbackKind string

FeedbackKind classifies explicit agent or human feedback on findings.

const (
	FeedbackCorrection FeedbackKind = "correction"
	FeedbackSuggestion FeedbackKind = "suggestion"
	FeedbackConfusing  FeedbackKind = "confusing"
)

type Finding

type Finding struct {
	FindingID          string             `json:"finding_id"`
	RuleID             string             `json:"rule_id"`
	RuleVersion        string             `json:"rule_version"`
	Model              string             `json:"model"`
	Device             string             `json:"device"`
	Kernel             string             `json:"kernel"`
	KernelClass        string             `json:"kernel_class"`
	SourceLoc          string             `json:"source_loc"`
	CaptureDigest      string             `json:"capture_digest"`
	GenerationID       int64              `json:"generation_id"`
	Severity           string             `json:"severity"`
	Summary            string             `json:"summary"`
	Remedy             string             `json:"remedy,omitempty"`
	Metrics            map[string]float64 `json:"metrics"`
	Thresholds         map[string]float64 `json:"thresholds"`
	SurfacedAt         time.Time          `json:"surfaced_at"`
	LastSeenAt         time.Time          `json:"last_seen_at,omitempty"`
	SurfacedCount      int                `json:"surfaced_count,omitempty"`
	Stats              *RuleStats         `json:"stats,omitempty"`
	TrackRecord        string             `json:"track_record,omitempty"`
	PendingCorrections int                `json:"pending_corrections"`
	RankScore          float64            `json:"rank_score"`
}

Finding represents a surfaced kernel-optimization finding with its evidence and attached per-rule historical track record.

type ModelTransferEntry

type ModelTransferEntry struct {
	RuleID             string  `json:"rule_id,omitempty"`
	RuleVersion        string  `json:"rule_version,omitempty"`
	Model              string  `json:"model"`
	Device             string  `json:"device"`
	KernelClass        string  `json:"kernel_class"`
	Surfaced           int     `json:"surfaced"`
	ActedOn            int     `json:"acted_on"`
	Evaluated          int     `json:"evaluated"`
	PendingCount       int     `json:"pending_count"`
	Helped             int     `json:"helped"`
	NoEffect           int     `json:"no_effect"`
	Hurt               int     `json:"hurt"`
	Invalid            int     `json:"invalid"`
	HelpRate           float64 `json:"help_rate"`
	HurtRate           float64 `json:"hurt_rate"`
	WilsonLCB          float64 `json:"wilson_lcb"`
	MedianVerifiedGain float64 `json:"median_verified_gain"`
}

ModelTransferEntry summarizes scorer-verified rule effectiveness for one (rule_id, rule_version, model, device, kernel_class) slice (or per-model aggregate in TransferMatrixReport.ByModel).

type ModelTransferPair

type ModelTransferPair struct {
	ModelA          string  `json:"model_a"`
	ModelB          string  `json:"model_b"`
	SampleSizeA     int     `json:"sample_size_a"`
	SampleSizeB     int     `json:"sample_size_b"`
	HelpRateA       float64 `json:"help_rate_a"`
	HelpRateB       float64 `json:"help_rate_b"`
	HelpRateDelta   float64 `json:"help_rate_delta"`
	MedianGainA     float64 `json:"median_gain_a"`
	MedianGainB     float64 `json:"median_gain_b"`
	MedianGainDelta float64 `json:"median_gain_delta"`
	Transfers       bool    `json:"transfers"`
}

ModelTransferPair compares verified effectiveness of a rule between two models (for example model_a vs model_b).

type Outcome

type Outcome struct {
	OutcomeID    string    `json:"outcome_id"`
	FindingID    string    `json:"finding_id"`
	RuleID       string    `json:"rule_id"`
	RuleVersion  string    `json:"rule_version"`
	Model        string    `json:"model"`
	Device       string    `json:"device"`
	KernelClass  string    `json:"kernel_class"`
	SessionID    string    `json:"session_id"`
	AttemptID    string    `json:"attempt_id"`
	GenerationID int64     `json:"generation_id"`
	ReceiptID    string    `json:"receipt_id"`
	Verdict      Verdict   `json:"verdict"`
	Gain         float64   `json:"gain"` // Positive fractional speedup: (baseline - candidate) / baseline.
	ParityPassed bool      `json:"parity_passed"`
	ScorerUID    string    `json:"scorer_uid"`
	RecordedAt   time.Time `json:"recorded_at"`
}

Outcome is a scorer-verified (or pending pre-edit acts_on) verdict attributed to a finding_id and linked to a receipt.

type PendingOutcomeInput

type PendingOutcomeInput struct {
	FindingID          string `json:"finding_id"`
	SessionID          string `json:"session_id"`
	AttemptID          string `json:"attempt_id"`
	GenerationID       int64  `json:"generation_id"`
	ReceiptID          string `json:"receipt_id"`
	Model              string `json:"model"`
	Device             string `json:"device"`
	KernelClass        string `json:"kernel_class"`
	DeclaredBeforeEdit bool   `json:"declared_before_edit"`
}

PendingOutcomeInput records an attempt that declared acts_on before editing, awaiting a verified verdict from an external scorer. Pending verdicts are never inferred and never counted toward scored RuleStats or Wilson LCB.

type ReviewItem

type ReviewItem struct {
	Kind          string     `json:"kind"` // "flagged_rule" or "candidate_rule"
	RuleID        string     `json:"rule_id"`
	RuleVersion   string     `json:"rule_version,omitempty"`
	Model         string     `json:"model,omitempty"`
	Device        string     `json:"device,omitempty"`
	KernelClass   string     `json:"kernel_class,omitempty"`
	Reasons       []string   `json:"reasons,omitempty"`
	Stats         *RuleStats `json:"stats,omitempty"`
	EvidenceCount int        `json:"evidence_count,omitempty"`
	EvidenceRefs  []string   `json:"evidence_refs,omitempty"`
	SampleNotes   []string   `json:"sample_notes,omitempty"`
}

ReviewItem represents an entry in the human review queue: either a rule whose hurt or correction rate crossed threshold, or a candidate rule from suggestion feedback backed by verifiable evidence.

type RuleDefinition

type RuleDefinition struct {
	RuleID          string             `json:"rule_id"`
	Version         string             `json:"rule_version"`
	KernelClass     string             `json:"kernel_class"`
	DefaultSeverity string             `json:"default_severity"`
	Title           string             `json:"title"`
	Remedy          string             `json:"remedy"`
	Thresholds      map[string]float64 `json:"thresholds"`
}

RuleDefinition describes optional versioned rule metadata registered in a Store via WithRules. Rules are never automatically mutated by feedback; rule changes go through reviewed commits.

type RuleStats

type RuleStats struct {
	RuleID             string   `json:"rule_id"`
	RuleVersion        string   `json:"rule_version"`
	Model              string   `json:"model"`
	Device             string   `json:"device"`
	KernelClass        string   `json:"kernel_class"`
	Surfaced           int      `json:"surfaced"`
	ActedOn            int      `json:"acted_on"`  // Helped + NoEffect + Hurt + Invalid (excludes Pending)
	Evaluated          int      `json:"evaluated"` // Helped + NoEffect + Hurt (valid evaluated outcomes; WilsonLCB denominator)
	PendingCount       int      `json:"pending_count"`
	Helped             int      `json:"helped"`
	NoEffect           int      `json:"no_effect"`
	Hurt               int      `json:"hurt"`
	Invalid            int      `json:"invalid"`
	CorrectionCount    int      `json:"correction_count"`
	SuggestionCount    int      `json:"suggestion_count"`
	ConfusingCount     int      `json:"confusing_count"`
	MedianVerifiedGain float64  `json:"median_verified_gain"` // Positive fractional speedup across Helped outcomes.
	HelpRate           float64  `json:"help_rate"`            // Helped / Evaluated when Evaluated > 0.
	HurtRate           float64  `json:"hurt_rate"`            // Hurt / Evaluated when Evaluated > 0.
	CorrectionRate     float64  `json:"correction_rate"`
	WilsonLCB          float64  `json:"wilson_lcb"` // WilsonLCB(Helped, Evaluated).
	ExplorationPrior   float64  `json:"exploration_prior"`
	RankScore          float64  `json:"rank_score"`
	FlaggedForReview   bool     `json:"flagged_for_review"`
	ReviewReasons      []string `json:"review_reasons,omitempty"`
	TrackRecord        string   `json:"track_record"`
}

RuleStats aggregates surfaced counts, scorer outcomes, pending verdicts, corrections, Wilson LCB, and review status per (rule_id, rule_version, model, device, kernel_class).

type ScorerContext

type ScorerContext struct {
	ScorerUID      string  `json:"scorer_uid"`
	WorkerUID      string  `json:"worker_uid"`
	Actor          string  `json:"actor,omitempty"`
	SelfReported   bool    `json:"self_reported,omitempty"`
	Model          string  `json:"model,omitempty"`
	SessionID      string  `json:"session_id"`
	AttemptID      string  `json:"attempt_id"`
	GenerationID   int64   `json:"generation_id"`
	ReceiptID      string  `json:"receipt_id"`
	ParityPassed   bool    `json:"parity_passed"`
	CompileFailed  bool    `json:"compile_failed,omitempty"`
	Gain           float64 `json:"gain"`                      // Positive fractional speedup: (baseline - candidate) / baseline; positive = speedup (helped), negative = regression (hurt).
	NoiseThreshold float64 `json:"noise_threshold,omitempty"` // Fractional noise threshold; defaults to DefaultNoiseThreshold (0.02).
}

ScorerContext carries trusted scorer-only measurement context for an attempt acting on a finding.

type ScorerOutcomeInput

type ScorerOutcomeInput struct {
	FindingID      string  `json:"finding_id"`
	Model          string  `json:"model"`
	Device         string  `json:"device,omitempty"`
	KernelClass    string  `json:"kernel_class,omitempty"`
	SessionID      string  `json:"session_id"`
	AttemptID      string  `json:"attempt_id"`
	GenerationID   int64   `json:"generation_id"`
	ReceiptID      string  `json:"receipt_id"`
	ParityPassed   bool    `json:"parity_passed"`
	CompileFailed  bool    `json:"compile_failed,omitempty"`
	Gain           float64 `json:"gain"`                      // Positive fractional speedup: (baseline - candidate) / baseline.
	NoiseThreshold float64 `json:"noise_threshold,omitempty"` // Fractional noise threshold; defaults to DefaultNoiseThreshold (0.02).
}

ScorerOutcomeInput carries external-scorer verdict inputs for resolving a pending outcome or recording a new verified outcome for a finding.

type Sink

type Sink interface {
	IngestRows(ctx context.Context, table string, rows []map[string]any) error
}

Sink receives normalized advise rows for external persistence (for example, into nvidia/x/obs/tracedb or another SQL/telemetry backend).

type SinkFunc

type SinkFunc func(ctx context.Context, table string, rows []map[string]any) error

SinkFunc adapts a plain function to the Sink interface.

func (SinkFunc) IngestRows

func (f SinkFunc) IngestRows(ctx context.Context, table string, rows []map[string]any) error

IngestRows calls f(ctx, table, rows).

type Store

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

Store manages advise findings, scorer-only outcomes, explicit feedback, Wilson LCB statistics, and optional synchronization to a Sink.

func NewStore

func NewStore(sink Sink, opts ...StoreOption) *Store

NewStore creates a new generic advise Store optionally synced into sink (TableFindings, TableOutcomes, TableFeedback). Passing sink == nil runs purely in memory. Domain-specific rules are not hardcoded; register optional rule metadata with WithRules.

func (*Store) AdviceThatWorked

func (s *Store) AdviceThatWorked(kernel, device string) []WorkedAdvice

AdviceThatWorked returns verified helped findings for a given kernel (and optional device filter), ordered by median verified speedup (largest positive gain first), then helped count, with linked audit receipt IDs.

func (*Store) AdviceThatWorkedForModel

func (s *Store) AdviceThatWorkedForModel(kernel, model, device string) []WorkedAdvice

AdviceThatWorkedForModel returns verified helped findings filtered by optional kernel, outcome model, and outcome device. Outcomes are attributed to Outcome.Model and Outcome.Device rather than Finding.Model/Finding.Device so cross-model outcomes are reported accurately. Pending outcomes are excluded.

func (*Store) ExportFeedbackJSONL

func (s *Store) ExportFeedbackJSONL() ([]byte, error)

ExportFeedbackJSONL serializes explicit feedback records as newline-delimited JSON.

func (*Store) GetFinding

func (s *Store) GetFinding(findingID string) (Finding, bool)

GetFinding returns a deep-cloned, stats-enriched copy of the finding with findingID, or (Finding{}, false) if not found.

func (*Store) PendingOutcomes

func (s *Store) PendingOutcomes(ruleID, model string) []Outcome

PendingOutcomes returns a snapshot of unresolved VerdictPending outcomes, optionally filtered by ruleID and/or model.

func (*Store) RankedFindings

func (s *Store) RankedFindings(captureDigest string, generationID int64, device string) []Finding

RankedFindings returns surfaced findings matching the optional captureDigest, generationID (>0), and device filters, enriched with per-rule stats, track record, and pending corrections, ordered by Wilson LCB * expected gain + exploration prior.

func (*Store) RankedFindingsForModel

func (s *Store) RankedFindingsForModel(captureDigest string, generationID int64, model, device string) []Finding

RankedFindingsForModel returns surfaced findings matching the optional captureDigest, generationID (>0), model, and device filters, enriched with per-rule stats, track record, and pending corrections, ordered by Wilson LCB * expected gain + exploration prior.

func (*Store) RecordFeedback

func (s *Store) RecordFeedback(ctx context.Context, in FeedbackInput) (Feedback, error)

RecordFeedback records explicit feedback (correction, suggestion, or confusing).

  • correction MUST reference an existing finding AND carry verifiable evidence (query_hash, capture, or counter_example_attempt).
  • suggestion may reference a finding or propose a new candidate rule.
  • confusing MUST reference an existing finding.
  • if both finding_id and rule_id are provided, they MUST match or ErrRuleIDMismatch is returned.

If syncing to a configured Sink fails, no in-memory state is mutated. Feedback never mutates rules automatically; rules needing attention appear in Store.ReviewQueue.

func (*Store) RecordPendingOutcome

func (s *Store) RecordPendingOutcome(ctx context.Context, in PendingOutcomeInput) (Outcome, error)

RecordPendingOutcome records a pre-edit acts_on outcome with VerdictPending while awaiting a verified verdict from an external scorer. If syncing to a configured Sink fails, no in-memory state is mutated.

Pending outcomes are never inferred and never counted toward Helped, NoEffect, Hurt, Invalid, ActedOn, Evaluated, or Wilson LCB ranking until promoted by Store.RecordScorerOutcome or Store.RecordScorerOutcomeWithInput.

func (*Store) RecordScorerOutcome

func (s *Store) RecordScorerOutcome(ctx context.Context, findingID string, sc ScorerContext) (Outcome, error)

RecordScorerOutcome records a scorer-measured attempt outcome for findingID. Self-reported outcomes, outcomes executed under or attributed to the worker UID, and non-finite (NaN/±Inf) gains or noise thresholds are strictly rejected so only valid trusted scorer measurements feed statistics. If a matching VerdictPending outcome exists for (finding_id, session_id, attempt_id, generation_id), it is resolved in place so PendingCount drops by 1. If syncing to a configured Sink fails, no in-memory state is mutated.

func (*Store) RecordScorerOutcomeWithInput

func (s *Store) RecordScorerOutcomeWithInput(ctx context.Context, sc ScorerContext, in ScorerOutcomeInput) (Outcome, error)

RecordScorerOutcomeWithInput records a scorer-measured outcome using an explicit ScorerOutcomeInput alongside the trusted ScorerContext identity. It enforces the same anti-self-report, worker-UID, and finite-gain checks as Store.RecordScorerOutcome and resolves any matching VerdictPending outcome.

func (*Store) ReviewQueue

func (s *Store) ReviewQueue() []ReviewItem

ReviewQueue returns rules flagged for human review (excess hurt rate or correction rate) plus candidate rules from suggestion feedback that carry verifiable evidence. Feedback never auto-edits rules.

func (*Store) Rules

func (s *Store) Rules() []RuleDefinition

Rules returns a sorted snapshot copy of the immutable rule metadata catalog.

func (*Store) Stats

func (s *Store) Stats(ruleID, device string) []RuleStats

Stats computes per-(rule_id, rule_version, model, device, kernel_class) statistics, optionally filtered by ruleID and/or device.

func (*Store) StatsForModel

func (s *Store) StatsForModel(ruleID, model, device, kernelClass string) []RuleStats

StatsForModel computes per-(rule_id, rule_version, model, device, kernel_class) statistics, optionally filtered by ruleID, model, device, and/or kernelClass.

func (*Store) SurfaceFinding

func (s *Store) SurfaceFinding(ctx context.Context, f Finding) (Finding, error)

SurfaceFinding records a finding with its deterministic finding_id, attaches current rule stats and pending corrections, and syncs it to TableFindings when a Sink is configured. On re-surface of an existing finding_id, first-seen metadata is preserved while LastSeenAt is updated and SurfacedCount is incremented. If syncing to the configured Sink fails, no in-memory state is mutated.

func (*Store) TransferMatrix

func (s *Store) TransferMatrix(ruleID string) TransferMatrixReport

TransferMatrix returns cross-model transfer evidence for ruleID, comparing verified help rate, median gain, Wilson LCB, and sample size across models. Entries retain rule_version and are sorted deterministically. Pending and invalid outcomes are excluded from valid evaluated sample sizes and Wilson LCB.

type StoreConfig

type StoreConfig struct {
	NoiseThreshold      float64
	MaxHurtRate         float64
	MinHurtSample       int
	MaxCorrectionRate   float64
	MinCorrectionSample int
	ExplorationMinActed int
}

StoreConfig tunes review thresholds and exploration prior behavior.

type StoreOption

type StoreOption func(*Store)

StoreOption customizes a Store.

func WithConfig

func WithConfig(cfg StoreConfig) StoreOption

WithConfig overrides review and ranking thresholds.

func WithRules

func WithRules(rules ...RuleDefinition) StoreOption

WithRules registers versioned rule metadata in the immutable catalog at Store construction time. Rules cannot be mutated afterward.

type TransferMatrixReport

type TransferMatrixReport struct {
	RuleID  string                        `json:"rule_id"`
	Models  []string                      `json:"models"`
	Entries []ModelTransferEntry          `json:"entries"`
	ByModel map[string]ModelTransferEntry `json:"by_model"`
	Pairs   []ModelTransferPair           `json:"pairs,omitempty"`
}

TransferMatrixReport compares a rule's verified help rate, median gain, and sample size across models. Pending outcomes are excluded from scored metrics.

type Verdict

type Verdict string

Verdict classifies a scorer-measured attempt outcome attributed to a finding.

const (
	VerdictHelped   Verdict = "helped"
	VerdictNoEffect Verdict = "no_effect"
	VerdictHurt     Verdict = "hurt"
	VerdictInvalid  Verdict = "invalid"
	VerdictPending  Verdict = "pending"
)

func ClassifyVerdict

func ClassifyVerdict(parityPassed, compileFailed bool, gain, noiseThreshold float64) Verdict

ClassifyVerdict deterministically maps parity/compile state and measured fractional speedup gain = (baseline - candidate) / baseline against noiseThreshold into a Verdict:

type WorkedAdvice

type WorkedAdvice struct {
	FindingID      string   `json:"finding_id"`
	RuleID         string   `json:"rule_id"`
	RuleVersion    string   `json:"rule_version"`
	Model          string   `json:"model"`
	Device         string   `json:"device"`
	Kernel         string   `json:"kernel"`
	KernelClass    string   `json:"kernel_class"`
	SourceLoc      string   `json:"source_loc"`
	Summary        string   `json:"summary"`
	Remedy         string   `json:"remedy,omitempty"`
	HelpedCount    int      `json:"helped_count"`
	EvaluatedCount int      `json:"evaluated_count"`
	ActedOnCount   int      `json:"acted_on_count"`
	MedianGain     float64  `json:"median_gain"`
	ReceiptIDs     []string `json:"receipt_ids"`
	TrackRecord    string   `json:"track_record"`
}

WorkedAdvice summarizes verified helped advice for a specific kernel, model, and device ("advice that worked" view).

Jump to

Keyboard shortcuts

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