ThatAIguyA world of ideas

THE CONSCIOUSNESS ATLAS
Read. Experiment. Follow the evidence.

ConsciousnessLearn · Explore · Joseph Anady

Janady13/missionmatch / internal/platform/magstore/magstore.go

Source identity, revision, and recovered contents.

GitHub sourceSource text recovered

Source identity

FieldRecorded value
Source typeGitHub source
Original recordJanady13/missionmatch / internal/platform/magstore/magstore.go
DateNot specified in source
RepositoryJanady13/missionmatch
Revision720d47fae476b0d38477ae4401697d372b1ea2bc
Branchfeature/opportunity-to-outcome
Path or archive memberinternal/platform/magstore/magstore.go
Original SHA-25673dace376efe82daa45d976fa2c2b51ac60c285e48945583ef33be3fb536817f
Git blob SHA5391ac3e6d00ae9d7f09fdc2c6677c47dbc86ef3
Reading-copy SHA-25673dace376efe82daa45d976fa2c2b51ac60c285e48945583ef33be3fb536817f

Original source ↗

Every recorded occurrence

These 10 records contain identical original source bytes. Their paths and revisions remain part of the archive.

Original recordBranch or archiveRevision / identifierOriginal location
Janady13/missionmatch / internal/platform/magstore/magstore.gofeature/opportunity-to-outcome720d47fae476b0d38477ae4401697d372b1ea2bcOpen original
Janady13/missionmatch / internal/platform/magstore/magstore.gocollision-deconfliction4ee5a09972608ed89f8377c6665542d5f450f0a6Open original
Janady13/missionmatch / internal/platform/magstore/magstore.gomaster1e9249840a4302ec82e123b9c9cb6f75badea3e4Open original
Janady13/missionmatch / internal/platform/magstore/magstore.gomag-substrateb82c7100a492dec67dfd1eda6b3f53def859be35Open original
Janady13/missionmatch / internal/platform/magstore/magstore.gotime-to-fill-survivalb66e1e505863d4f17741a4b9ede73509e45bd6c6Open original
Janady13/missionmatch / internal/platform/magstore/magstore.gopresentation-readinesseb574acaa29d71ce4d0f852572e87c275c79fdb7Open original
Janady13/missionmatch / internal/platform/magstore/magstore.govendor-intelligencefe9796a19c261951d3f2565206c0c1b5ac294465Open original
Janady13/missionmatch / internal/platform/magstore/magstore.gophase2-connectorse038d4c687aec16f8bd9bc4d907eea14d91f8704Open original
Janady13/missionmatch / internal/platform/magstore/magstore.gofeature/aioe-upgrade2178e7298d0e5d9af83afa12402fd587f0ba6ed8Open original
Janady13/missionmatch / internal/platform/magstore/magstore.gocapture-readinessbae6af7cb2997e819174a9e9cfff5e16067a1975Open original

Recovered source transcript

// Package magstore is the database glue between the MAG coefficient store (aedt_learned_models, // aedt_model_coefficients, aedt_calibration_bins) plus the bid_outcomes label ledger and the offline trainer // and evaluator (cmd/train-model, cmd/eval-model). It reads the pooled labeled bids, loads and scores a stored // model version, writes a new CHALLENGER (never a champion), and, as a separate call, promotes a version to // champion. The numerical fit itself lives in internal/platform/learn (pure, no DB); this package is only the // DB reads and writes, run under the BYPASSRLS migrator role. // // float64 lives ONLY in the offline solver and this offline scorer (an offline evaluation, never a request // path score); every coefficient WriteChallenger stores is re quantized to shopspring/decimal at the store's // numeric scale, so the SERVED path (internal/modules/ai) stays decimal exact. The served numbers are computed // by the ai package in decimal; this offline float scoring is used only to compare a challenger against the // champion on held out labels, which is a relative metric, not a surfaced number. package magstore import ( "context" "encoding/json" "fmt" "math" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" "github.com/shopspring/decimal" "github.com/missionworkforce/missionmatch/internal/platform/learn" ) // SegmentBaseRateFeature is the one market structure feature the win probability trainer fits and the serving // path gathers: the win rate of a bid's customer agency segment. It is never a protected attribute or a proxy. const SegmentBaseRateFeature = "segment_base_rate" // interceptFeature is the reserved coefficient row carrying the model bias term (the log odds base rate), // matching the serving path's reserved name so a stored model round trips identically. const interceptFeature = "intercept" const ( coefficientScale int32 = 10 // aedt_model_coefficients.coefficient is numeric(20,10) calibrationScale int32 = 8 // aedt_calibration_bins figures are numeric(12,8) ) // Model is a loaded model version: its intercept, its raw feature space coefficients keyed by feature name, and // its monotone calibration bins. Every figure is a float64 for the offline scorer; the stored source is decimal // and is read back exactly, then converted once here. type Model struct { ModelKey string Version int OutputKind string Intercept float64 Coeffs map[string]float64 Bins []Bin } // Bin is one calibration bin: a raw probability range [Lo, Hi] mapping to an EmpiricalRate. type Bin struct { Lo, Hi, EmpiricalRate float64 } // ReadLabeledBids reads every decided bid (win or loss) POOLED across tenants with its segment base rate // feature, the win rate of the bid's customer agency segment over the decided ledger, the SAME market base rate // the serving path gathers. Requirements are joined by the composite key (organization_id, id) so a cross // tenant join can never happen even under the BYPASSRLS migrator role. Ordered deterministically. func ReadLabeledBids(ctx context.Context, pool *pgxpool.Pool) ([]learn.LabeledRow, error) { const q = ` WITH decided AS ( SELECT b.id, b.result, COALESCE(NULLIF(r.customer_agency, ''), '(unspecified)') AS segment FROM bid_outcomes b LEFT JOIN requirements r ON r.organization_id = b.organization_id AND r.id = b.requirement_id WHERE b.result IN ('win', 'loss') ), seg AS ( SELECT segment, (count(*) FILTER (WHERE result = 'win'))::numeric / NULLIF(count(*), 0) AS win_rate FROM decided GROUP BY segment ) SELECT d.result, COALESCE(s.win_rate, 0)::float8 AS segment_base_rate FROM decided d JOIN seg s ON s.segment = d.segment ORDER BY d.id` rows, err := pool.Query(ctx, q) if err != nil { return nil, err } defer rows.Close() var out []learn.LabeledRow for rows.Next() { var result string var rate float64 if err := rows.Scan(&result, &rate); err != nil { return nil, err } out = append(out, learn.LabeledRow{ Result: result, Features: map[string]float64{SegmentBaseRateFeature: rate}, }) } return out, rows.Err() } // ChampionVersion returns the champion version for a model_key, or an error when no champion is resolvable so an // evaluator never silently compares against nothing. func ChampionVersion(ctx context.Context, pool *pgxpool.Pool, modelKey string) (int, error) { var v int err := pool.QueryRow(ctx, `SELECT version FROM aedt_learned_models WHERE model_key = $1 AND champion = true`, modelKey).Scan(&v) if err != nil { if err == pgx.ErrNoRows { return 0, fmt.Errorf("magstore: no champion for %q", modelKey) } return 0, err } return v, nil } // LoadModel loads a specific model version: its output kind, its coefficients (the intercept plus every real // feature), and its calibration bins. It reads the decimal store exactly, then converts each figure to float64 // once for the offline scorer. func LoadModel(ctx context.Context, pool *pgxpool.Pool, modelKey string, version int) (Model, error) { m := Model{ModelKey: modelKey, Version: version, Coeffs: map[string]float64{}} if err := pool.QueryRow(ctx, `SELECT output_kind FROM aedt_learned_models WHERE model_key = $1 AND version = $2`, modelKey, version).Scan(&m.OutputKind); err != nil { if err == pgx.ErrNoRows { return Model{}, fmt.Errorf("magstore: no model %q v%d", modelKey, version) } return Model{}, err } crows, err := pool.Query(ctx, `SELECT feature_name, coefficient FROM aedt_model_coefficients WHERE model_key = $1 AND version = $2`, modelKey, version) if err != nil { return Model{}, err } defer crows.Close() for crows.Next() { var name string var coef decimal.Decimal if err := crows.Scan(&name, &coef); err != nil { return Model{}, err } f, _ := coef.Float64() if name == interceptFeature { m.Intercept = f continue } m.Coeffs[name] = f } if err := crows.Err(); err != nil { return Model{}, err } brows, err := pool.Query(ctx, `SELECT bin_lo, bin_hi, empirical_rate FROM aedt_calibration_bins WHERE model_key = $1 AND version = $2 ORDER BY bin_index`, modelKey, version) if err != nil { return Model{}, err } defer brows.Close() for brows.Next() { var lo, hi, rate decimal.Decimal if err := brows.Scan(&lo, &hi, &rate); err != nil { return Model{}, err } lf, _ := lo.Float64() hf, _ := hi.Float64() rf, _ := rate.Float64() m.Bins = append(m.Bins, Bin{Lo: lf, Hi: hf, EmpiricalRate: rf}) } return m, brows.Err() } // Score computes the offline calibrated probability of a feature vector under a loaded model: raw = // sigmoid(intercept + SUM coef*value), then the monotone calibration remap (an empty bin set is the identity // map). It mirrors the serving path's math for the held out comparison; the served numbers themselves are // computed in decimal by the ai package. func (m Model) Score(features map[string]float64) float64 { eta := m.Intercept for name, v := range features { eta += m.Coeffs[name] * v } raw := 1.0 / (1.0 + math.Exp(-eta)) for _, b := range m.Bins { if raw >= b.Lo && raw <= b.Hi { raw = b.EmpiricalRate break } } if raw < 0 { return 0 } if raw > 1 { return 1 } return raw } // FeatureSpec builds the feature_spec jsonb value recording each feature, the Registry source intent it reads // from, and its TRAINING MEAN, mirroring the v0 seed shape so a challenger is spec compatible with the prior // only champion. The stored mean is what the serve path imputes for a feature with no history (a segment with // no decided bids), so a learned model returns the base rate for a no history segment instead of extrapolating // off a misleading zero. means may be nil (the prior only seed carries none) or aligned to featureNames. func FeatureSpec(featureNames []string, means []float64) map[string]any { feats := make([]map[string]any, 0, len(featureNames)) for i, name := range featureNames { f := map[string]any{"name": name} if name == SegmentBaseRateFeature { f["source_intent"] = "bid_win_rate_by_segment" f["column"] = "win_rate" } if i < len(means) { f["mean"] = quant(means[i], coefficientScale).String() } feats = append(feats, f) } return map[string]any{"features": feats} } // Challenger is a fitted model ready to persist: its raw feature space intercept and coefficients (keyed by // feature name), its calibration bins, and the training summary for the notes column. type Challenger struct { Family string // the model family, e.g. logistic or pairwise_logistic OutputKind string // one of the legal MAG kinds: opportunity_score, display_order, confidence FeatureNames []string Intercept float64 Coeffs []float64 // aligned to FeatureNames Means []float64 // training feature means, aligned to FeatureNames, stored for no history imputation Bins []Bin Notes string } // WriteChallenger writes a new challenger version in ONE migrator transaction: the next version number, its // coefficient rows (decimal), and its calibration bins. It sets champion=false ALWAYS; a champion flip is a // separate governance action (PromoteChampion), never a side effect of a fit. Versions are append only, an // audit trail of every fit. func WriteChallenger(ctx context.Context, pool *pgxpool.Pool, modelKey string, ch Challenger) (int, error) { var version int err := pgx.BeginFunc(ctx, pool, func(tx pgx.Tx) error { if err := tx.QueryRow(ctx, `SELECT COALESCE(MAX(version), 0) + 1 FROM aedt_learned_models WHERE model_key = $1`, modelKey).Scan(&version); err != nil { return err } spec, err := json.Marshal(FeatureSpec(ch.FeatureNames, ch.Means)) if err != nil { return err } family := ch.Family if family == "" { family = "logistic" } outputKind := ch.OutputKind if outputKind == "" { outputKind = "opportunity_score" } if _, err := tx.Exec(ctx, `INSERT INTO aedt_learned_models (model_key, version, family, output_kind, feature_spec, champion, notes) VALUES ($1, $2, $3, $4, $5, false, $6)`, modelKey, version, family, outputKind, spec, ch.Notes); err != nil { return err } if _, err := tx.Exec(ctx, `INSERT INTO aedt_model_coefficients (model_key, version, feature_name, coefficient) VALUES ($1, $2, 'intercept', $3)`, modelKey, version, quant(ch.Intercept, coefficientScale)); err != nil { return err } for j, name := range ch.FeatureNames { if _, err := tx.Exec(ctx, `INSERT INTO aedt_model_coefficients (model_key, version, feature_name, coefficient) VALUES ($1, $2, $3, $4)`, modelKey, version, name, quant(ch.Coeffs[j], coefficientScale)); err != nil { return err } } for i, b := range ch.Bins { if _, err := tx.Exec(ctx, `INSERT INTO aedt_calibration_bins (model_key, version, bin_index, bin_lo, bin_hi, empirical_rate) VALUES ($1, $2, $3, $4, $5, $6)`, modelKey, version, i, quant(b.Lo, calibrationScale), quant(b.Hi, calibrationScale), quant(b.EmpiricalRate, calibrationScale)); err != nil { return err } } return nil }) return version, err } // PromoteChampion flips the champion to a challenger version in ONE migrator transaction: it clears the current // champion flag for the model_key, sets it on the target version, and appends one governance audit row, all // atomically. The partial unique index enforces at most one champion, so the flip is atomic and a second // champion is impossible. It errors if the target version does not exist. This is the ONLY place a champion // changes, and cmd/eval-model calls it only after the held out and fairness gates pass and a human passes the // promote flag. The audit row carries the model_key and the from and to versions, no PII and no org (a global // governance action). It returns the version the promotion replaced (0 when there was no prior champion). func PromoteChampion(ctx context.Context, pool *pgxpool.Pool, modelKey string, version int) (fromVersion int, err error) { err = pgx.BeginFunc(ctx, pool, func(tx pgx.Tx) error { var exists bool if err := tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM aedt_learned_models WHERE model_key = $1 AND version = $2)`, modelKey, version).Scan(&exists); err != nil { return err } if !exists { return fmt.Errorf("magstore: cannot promote missing model %q v%d", modelKey, version) } // The version being replaced (0 when there is no current champion), for the audit trail. if err := tx.QueryRow(ctx, `SELECT COALESCE(MAX(version), 0) FROM aedt_learned_models WHERE model_key = $1 AND champion = true`, modelKey).Scan(&fromVersion); err != nil { return err } if _, err := tx.Exec(ctx, `UPDATE aedt_learned_models SET champion = false WHERE model_key = $1 AND champion = true`, modelKey); err != nil { return err } if _, err := tx.Exec(ctx, `UPDATE aedt_learned_models SET champion = true WHERE model_key = $1 AND version = $2`, modelKey, version); err != nil { return err } newValues, merr := json.Marshal(map[string]any{"from_version": fromVersion, "to_version": version}) if merr != nil { return merr } if _, err := tx.Exec(ctx, `INSERT INTO audit_logs (organization_id, actor_user_id, action, entity_type, entity_id, new_values) VALUES (NULL, NULL, 'aedt.model.promoted', 'aedt_learned_model', $1, $2)`, modelKey, newValues); err != nil { return err } return nil }) return fromVersion, err } // quant re quantizes an offline float64 to a shopspring/decimal at a fixed scale, the boundary where a number // leaves the float solver and becomes the decimal the store holds and the serve path reads. func quant(v float64, scale int32) decimal.Decimal { return decimal.NewFromFloat(v).Round(scale) }

Mathematical records from this source

Search equations, builds, manuscript text, and recovered sources.