Files
vyndr/scripts/verify-grade-range.js
T
builtbykev 1a94ef5fcf Revive the dead probability layer + restore grade range ON MERIT
Folds re-sequenced steps 1+2 into one change (Kev's call): same bug
family — features wired to sources that return null.

THE PROBABILITY LAYER WAS DEAD IN PRODUCTION. p_win/ev_pct/kelly/
model_odds/value were absent on 0/8 live grades because
gameLogService.getGameLogs returns null for MLB by construction and
depends on the offline Python service for NBA/WNBA, so meta.gameLogs was
[] for every sport. This was the S46 bug in a second location — that fix
gave featureCache an MLB branch (why grades still worked) but never the
estimator. featureCache.getStatRows now supplies normalized rows
([{date,[statType]:v}], most-recent-first) for every sport, feeding the
estimator AND consistency AND game_count_in_7d from one fetch.
VERIFIED on real props: p_win 25/25 WNBA, 8/8 MLB (was 0).

GRADE RANGE, ON MERIT — never by rescaling (permanent founder ruling:
minting A's without new information is a relabelled B sold as an A and
corrupts an append-only ledger).
- refreshTeamStats wired into runSnapshot — it had ZERO production
  callers, so opp_rank_stat was permanently null and a +/-1.0 factor
  could never fire. Test-env no-op (opsNotify precedent).
- L20 made SYMMETRIC: both branches were delta +1.0, so the season
  baseline could only ever ADD. No negative path was a structural reason
  D was unreachable. New l20_contradicts_* carries -1.0.
- game_count_in_7d derived from real logged dates (heavy_workload_7d).
- NOT wired, deliberately, with reasons inline: teamId (no team_id
  column; getFeatures reads it top-level; factor also needs a starter-id
  list) and season_type (ESPN 2 = REGULAR season; threading it raw would
  fire veteran_in_playoffs in July). Dead code dressed as a fix is the
  thing we are removing, not adding.

CALIBRATION GUARD (found by verifying, not assuming): consistency CV is
NBA-tuned; for a Poisson-ish stat cv ~ 1/sqrt(mean), so any stat with
mean < 4 auto-classifies boom_bust. First verification run showed 8/8 MLB
props boom_bust — a blanket -1.0 that dropped the board to all-C. Floored
at CONSISTENCY_MIN_MEAN=4 -> 'unknown' below. Absent beats wrong. MLB
low-count stats therefore still get no consistency factor: honest, not
fixed. Scale-free index-of-dispersion classifier is the open follow-up.

CONFIDENCE IS NOT A PROBABILITY: payloads carry confidence_basis:
'grade_band'. Corrected mlb-grade-degradation.md — its "25/25
grade<->confidence agreement" is a TAUTOLOGY (confidence is derived FROM
the letter, so it would report 25/25 even if every grade were wrong), not
a validation. Removed dead mlbGrader.js (referenced only by its own test)
and the stale computeFeatures comment claiming a penalty that never ran.

VERIFICATION (scripts/verify-grade-range.js, real props/logs/engine):
WNBA 25 props B 68%->32%, C 32%->64%, D 0->1 (4%); 11-step spread went
from 2 steps to 5 (C/C+/B-/D). The D is earned: Angel Reese assists o2.5,
p_win 0.365. Nothing flooded — grades got HARDER. A did not emit locally
because opp_rank_stat needs the Redis cache only prod populates (local
ceiling +3.0 vs the +4.5 A needs); reachability is proven arithmetically
and locked in tests. Prod A-emission is the outstanding fingerprint.

MARKETING HOLD: "A-RATED" (AccuracyBadge, TopSignals) is unsupported
until that fingerprint. Confirmed honest fallbacks render today —
/api/ledger/accuracy has B and C buckets only, so the badge shows
"MODEL · 63% HIT" and TopSignals self-hides. Nothing fabricated ships.

Suite 276/3286 green, web build exit 0.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SmNjJAwEnqHPtXbvSZR8kA
2026-07-19 18:54:51 -04:00

110 lines
4.9 KiB
JavaScript

#!/usr/bin/env node
/**
* Session 63 — GRADE-RANGE VERIFICATION (on merit, not by rescaling).
*
* Replays REAL props from the live board through the REAL engine path that
* Session 63 repaired, and reports the resulting grade distribution.
*
* What is real here:
* - the props (player / stat / line / side) come from the live API board
* - the game logs come from statsapi.mlb.com + ESPN (free, no quota)
* - the consistency factor + L5/L20 features are computed from those logs
* - the grade comes from engine1.gradeProp, unmodified
*
* What is NOT covered (documented, not hidden):
* - `opp_rank_stat` needs `team_stats:{sport}:{abbr}` in Redis, which only
* the production snapshot populates. Locally it stays null, so this run
* UNDERSTATES the restored range — it omits a ±1.0 factor. Any A/D seen
* here is therefore a floor, not a ceiling.
*
* Usage: node scripts/verify-grade-range.js [sport] [limit]
*/
const engine1 = require('../src/services/intelligence/engine1');
const featureCache = require('../src/services/intelligence/featureCache');
const consistencyScore = require('../src/services/intelligence/consistencyScore');
const { estimateProbability } = require('../src/services/intelligence/probabilityEstimator');
const { fourLetterGrade } = require('../src/utils/gradeAdapter').__internals;
const API = process.env.VERIFY_API || 'https://api.vyndr.app';
const SPORT = process.argv[2] || 'mlb';
const LIMIT = Number(process.argv[3] || 40);
async function board(sport) {
const res = await fetch(`${API}/api/snapshot/${sport}`);
const json = await res.json();
const grades = Array.isArray(json.grades) ? json.grades : [];
return grades.map((g) => ({
player: g.player,
stat: g.stat_type,
line: Number(g.line),
direction: String(g.direction || 'over').toLowerCase(),
oldGrade: g.grade,
oldConfidence: g.confidence,
})).filter((p) => p.player && p.stat && Number.isFinite(p.line));
}
async function gradeOne(p, sport) {
const rows = await featureCache.getStatRows(p.player, sport, p.stat);
const features = await featureCache.__internals.gameLogFeatures(p.player, sport, p.stat);
const consistency = await consistencyScore.getConsistency({
playerName: p.player, sport, statType: p.stat, gameLogs: rows,
});
const prop = { line: p.line, direction: p.direction };
const res = engine1.gradeProp({ features, trap: {}, consistency, prop });
const est = estimateProbability({ gameLogs: rows, line: p.line, statType: p.stat, features });
const pWin = Number.isFinite(est.p_over)
? (p.direction === 'under' ? 1 - est.p_over : est.p_over)
: null;
return {
...p,
rows: rows.length,
consistency: consistency.consistency,
newGrade11: res.grade,
newGrade: fourLetterGrade(res.grade),
p_win: pWin == null ? null : Math.round(pWin * 1000) / 1000,
};
}
(async () => {
const props = (await board(SPORT)).slice(0, LIMIT);
if (!props.length) { console.log(`no live props for ${SPORT}`); return; }
console.log(`Replaying ${props.length} REAL ${SPORT.toUpperCase()} props through the repaired engine\n`);
const out = [];
for (const p of props) {
try { out.push(await gradeOne(p, SPORT)); }
catch (e) { console.warn(` ! ${p.player} ${p.stat}: ${e.message}`); }
}
const tally = (arr, key) => arr.reduce((m, r) => { const k = r[key] ?? 'null'; m[k] = (m[k] || 0) + 1; return m; }, {});
const pct = (n) => `${Math.round((n / out.length) * 1000) / 10}%`;
console.log('--- 4-LETTER DISTRIBUTION ---');
console.log('BEFORE (live board):', tally(out, 'oldGrade'));
const after = tally(out, 'newGrade');
console.log('AFTER (repaired) :', after);
for (const g of ['A', 'B', 'C', 'D', 'F']) if (after[g]) console.log(` ${g}: ${after[g]} (${pct(after[g])})`);
console.log('\n--- 11-STEP DISTRIBUTION (pre-collapse) ---');
console.log(tally(out, 'newGrade11'));
console.log('\n--- REVIVED SIGNALS ---');
const withRows = out.filter((r) => r.rows > 0).length;
const withP = out.filter((r) => r.p_win != null).length;
const withCons = out.filter((r) => r.consistency && r.consistency !== 'unknown').length;
console.log(`game-log rows present : ${withRows}/${out.length}`);
console.log(`p_win computed : ${withP}/${out.length} (was 0 in prod)`);
console.log(`consistency known : ${withCons}/${out.length} (was 0 for MLB)`);
console.log('\n--- MOVERS (grade changed) ---');
for (const r of out.filter((r) => r.oldGrade !== r.newGrade).slice(0, 15)) {
console.log(` ${r.oldGrade}${r.newGrade.padEnd(2)} (${r.newGrade11.padEnd(2)}) ${r.player} ${r.stat} ${r.direction} ${r.line} n=${r.rows} cons=${r.consistency} p=${r.p_win}`);
}
// Redis runs in degraded mode locally and keeps a reconnect timer alive, so
// the process would never exit on its own — flush and leave deliberately.
await new Promise((r) => process.stdout.write('', r));
process.exit(0);
})().catch((e) => { console.error('verify failed:', e.message); process.exit(1); });