Files
vyndr/tests/unit/computeFeatures.test.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

201 lines
8.2 KiB
JavaScript

// Fix 1 (Session 7f) — computeFeaturesForProp must never throw, and
// must return the engine1 input shape (features/trap/consistency/prop)
// even when every upstream is missing.
const mockSupabaseState = {
rosterRow: null,
error: null,
};
jest.mock('../../src/utils/supabase', () => ({
getSupabaseServiceClient: () => ({
from() {
const proxy = {
select() { return proxy; },
eq() { return proxy; },
limit() { return proxy; },
maybeSingle: () => Promise.resolve({ data: mockSupabaseState.rosterRow, error: mockSupabaseState.error }),
};
return proxy;
},
}),
}));
const mockAxiosGet = jest.fn();
jest.mock('axios', () => ({ get: (...args) => mockAxiosGet(...args) }));
const mockFeatures = { current: {}, throws: false };
jest.mock('../../src/services/intelligence/featureCache', () => ({
getFeatures: async () => {
if (mockFeatures.throws) throw new Error('feature-fetch boom');
return { features: mockFeatures.current, meta: {} };
},
// Session 63 — computeFeatures now sources normalized per-game rows here
// (feeds consistency + the probability estimator + game_count_in_7d).
// Routed through the SAME mockLogs fixture the old gameLogService mock used,
// so "logs available → consistency computed" keeps its original meaning.
getStatRows: async () => mockLogs.current || [],
gameCountInWindow: () => null,
}));
const mockTrap = { current: null, throws: false };
jest.mock('../../src/services/intelligence/trapDetection', () => ({
getTrapScore: async () => {
if (mockTrap.throws) throw new Error('trap boom');
return mockTrap.current;
},
normalizeName: (n) => n,
}));
const mockLogs = { current: null };
const mockConsistency = { current: null };
jest.mock('../../src/services/intelligence/gameLogService', () => ({
getGameLogs: async () => mockLogs.current,
getCareerPlayoffGames: async () => null,
getWithWithoutStats: async () => null,
}));
jest.mock('../../src/services/intelligence/consistencyScore', () => ({
getConsistency: async () => mockConsistency.current || { consistency: 'reliable', cv: 0.2, score: 0.7, games: 20 },
}));
const { computeFeaturesForProp } = require('../../src/services/intelligence/computeFeatures');
beforeEach(() => {
mockSupabaseState.rosterRow = null;
mockSupabaseState.error = null;
mockAxiosGet.mockReset();
mockFeatures.current = {};
mockFeatures.throws = false;
mockTrap.current = null;
mockTrap.throws = false;
mockLogs.current = null;
mockConsistency.current = null;
});
function nbaScoreboard(events) {
return { status: 200, data: { events } };
}
function game(id, homeAbbr, awayAbbr) {
return {
id,
competitions: [{
competitors: [
{ homeAway: 'home', team: { abbreviation: homeAbbr } },
{ homeAway: 'away', team: { abbreviation: awayAbbr } },
],
}],
};
}
describe('computeFeaturesForProp — happy path', () => {
test('resolves player + game + features + trap + consistency', async () => {
mockSupabaseState.rosterRow = {
display_name: 'Jalen Brunson', normalized_name: 'jalen brunson',
espn_id: '3934672', team_abbr: 'NYK', sport: 'nba',
};
mockAxiosGet.mockResolvedValue(nbaScoreboard([game('ev-1', 'NYK', 'BOS')]));
mockFeatures.current = { l5_avg: 28.4, l20_avg: 26.1, home_away: 1.0, opp_rank_stat: 0.82 };
mockTrap.current = { composite: 0.12, signals: {}, active_count: 1, recommendation: 'proceed' };
mockLogs.current = [{ points: 28 }, { points: 26 }];
const out = await computeFeaturesForProp({
player: 'Jalen Brunson', stat_type: 'points', line: 25.5, direction: 'over', sport: 'nba',
});
expect(out.features.l5_avg).toBe(28.4);
expect(out.features.home_away).toBe(1.0);
expect(out.trap.composite).toBe(0.12);
expect(out.consistency.consistency).toBe('reliable');
expect(out.prop).toEqual({ line: 25.5, direction: 'over' });
expect(out.meta.teamAbbr).toBe('NYK');
expect(out.meta.opponentAbbr).toBe('BOS');
expect(out.meta.gameId).toBe('ev-1');
expect(out.meta.isHome).toBe(true);
expect(out.meta.errors).toHaveLength(0);
});
});
describe('computeFeaturesForProp — graceful degradation', () => {
test('player not in player_id_map → errors logged, partial result returned', async () => {
mockSupabaseState.rosterRow = null;
const out = await computeFeaturesForProp({
player: 'Unknown Person', stat_type: 'points', line: 20, direction: 'over', sport: 'nba',
});
expect(out.meta.errors).toContain('player_not_found_in_id_map');
expect(out.meta.errors).toContain('no_game_scheduled_today');
expect(out.meta.teamAbbr).toBeNull();
expect(out.meta.gameId).toBeNull();
expect(out.features).toEqual({});
expect(out.prop.line).toBe(20);
});
test('player found but no game today → still returns features attempt', async () => {
mockSupabaseState.rosterRow = { team_abbr: 'NYK', espn_id: '1', sport: 'nba' };
mockAxiosGet.mockResolvedValue(nbaScoreboard([])); // empty slate
const out = await computeFeaturesForProp({
player: 'Some Player', stat_type: 'points', line: 22, direction: 'over', sport: 'nba',
});
expect(out.meta.errors).toContain('no_game_scheduled_today');
expect(out.meta.teamAbbr).toBe('NYK');
expect(out.meta.gameId).toBeNull();
});
test('feature fetch throws → ESPN fields empty, but static-context augmentation still surfaces (Session 15)', async () => {
mockSupabaseState.rosterRow = { team_abbr: 'NYK', espn_id: '1', sport: 'nba' };
mockAxiosGet.mockResolvedValue(nbaScoreboard([game('e2', 'NYK', 'BOS')]));
mockFeatures.throws = true;
const out = await computeFeaturesForProp({
player: 'Brunson', stat_type: 'points', line: 25, direction: 'over', sport: 'nba',
});
expect(out.meta.errors).toContain('no_features_computed');
// Session 15 — static lookups (pace factor, park factor) populate
// regardless of ESPN fetch state. The contract used to be
// "features is empty when ESPN fails"; the contract is now
// "features may contain static context even when ESPN fails."
// ESPN-derived fields (l5_avg, opp_rank_stat, ...) ARE absent.
expect(out.features.l5_avg).toBeUndefined();
expect(out.features.opp_rank_stat).toBeUndefined();
// Pace factor lookup is static and stable for known team codes.
expect(out.features.pace_factor).toBe(95); // NYK pace
expect(out.features.opp_pace_factor).toBe(99); // BOS pace
expect(out.trap).toBeDefined();
});
test('trap detection throws → defaults to no signals', async () => {
mockSupabaseState.rosterRow = { team_abbr: 'NYK', espn_id: '1', sport: 'nba' };
mockAxiosGet.mockResolvedValue(nbaScoreboard([game('e3', 'NYK', 'BOS')]));
mockFeatures.current = { l5_avg: 25 };
mockTrap.throws = true;
const out = await computeFeaturesForProp({
player: 'Brunson', stat_type: 'points', line: 25, direction: 'over', sport: 'nba',
});
expect(out.trap).toMatchObject({ composite: 0, recommendation: 'proceed' });
});
test('missing required fields surfaces in errors but still returns shape', async () => {
const out = await computeFeaturesForProp({});
expect(out.meta.errors[0]).toMatch(/missing required fields/);
expect(out.features).toBeDefined();
expect(out.trap).toBeDefined();
expect(out.consistency).toBeDefined();
expect(out.prop).toBeDefined();
});
test('scoreboard fetch throws → no game noted, no crash', async () => {
mockSupabaseState.rosterRow = { team_abbr: 'NYK', espn_id: '1', sport: 'nba' };
mockAxiosGet.mockRejectedValue(new Error('espn down'));
const out = await computeFeaturesForProp({
player: 'B', stat_type: 'points', line: 25, direction: 'over', sport: 'nba',
});
expect(out.meta.gameId).toBeNull();
expect(out.meta.errors).toContain('no_game_scheduled_today');
});
test('does not import from legacy path (no propAnalyzer/grader/UnifiedOddsProvider)', () => {
const fs = require('fs');
const src = fs.readFileSync(require.resolve('../../src/services/intelligence/computeFeatures.js'), 'utf8');
expect(src).not.toMatch(/propAnalyzer/);
expect(src).not.toMatch(/require.*['"]\.\.\/grader/);
expect(src).not.toMatch(/UnifiedOddsProvider/);
});
});