Wave 1: NBA/WNBA settlement — grades settle vs free ESPN game logs
Unblocks the self-learning loop for basketball. Once an NBA/WNBA grade
exists (Wave 0), it now settles against the FREE ESPN per-game log
(espnStatsAdapter.getPlayerGameLog) — the same {found, last10:[{date,stat}]}
contract MLB settlement already consumes. accuracy:{sport} + by_tier
calibration + the Wave-3 TierRecord light up automatically.
- outcomeService/ledgerService: defaultGetPlayerStats routes nba/wnba to
espnStatsAdapter.getPlayerGameLog; MLB stays on mlbStatsAdapter.
- outcomeService: sport-aware statValue + a SEPARATE NBA_BOX_KEY/NBA_COMBO
map (S11 three-map-split kept — never merged with MLB_LOG_FIELD). Combos
(pts_reb_ast, reb_ast, stl_blk, …) sum components; a missing component
never fabricates a total.
- logRowOnDate: ESPN gamelog rows carry a FULL ISO timestamp (a late tip
rolls past UTC midnight), so basketball date-matches on UTC OR ET date;
MLB keeps exact YYYY-MM-DD compare. Outcome `date` is normalized to the
ET calendar day so the accuracy window filter + idempotency key behave
identically across sports.
- Final-honesty guard: never settle a basketball row whose ET date is
today (an in-progress partial box). MLB is final-only + settles same-day,
so the guard is scoped to basketball. The ledger path is already guarded
(.lt('game_date', today)) for all sports.
- opsWatch: nba/wnba added to SETTLEABLE_SPORTS; zeroSettleAlarm gates them
behind a real-finals probe (finalsBySport) so an offseason/off-day's
stale pendings never false-page "settled 0". snapshotScheduler counts
yesterday's ESPN state==='post' events and feeds the map; MLB unchanged.
- snapshotScheduler: boot announce per settleable sport
([settle:mlb] [settle:nba] [settle:wnba]). Thrown-error paging already
covers the new sports (settleAll* loop every sport).
Tests: tests/unit/nbaSettlement.test.js (16) — WNBA hit/miss/push, combo
pra, idempotent re-run, unplayed/today game does NOT settle, accuracy:wnba
+ byGrade + by_tier populate, ledger WNBA settle. opsWatch (+5) — finals
off-day no page, finals present DOES page. MLB suites unregressed.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -28,7 +28,7 @@
|
||||
*/
|
||||
|
||||
const { nameKey, normalizeName } = require('../utils/playerName');
|
||||
const { settleResult, statValue } = require('./outcomeService');
|
||||
const { settleResult, statValue, logRowOnDate } = require('./outcomeService');
|
||||
|
||||
const CONFLICT = 'user_id,player_key,stat,line,side,game_id';
|
||||
const UPSERT_CHUNK = 200;
|
||||
@@ -330,9 +330,12 @@ async function settleLedger(sport, opts = {}) {
|
||||
let pending = 0;
|
||||
for (const row of rows || []) {
|
||||
const log = logByPlayer[row.player_name] || [];
|
||||
const gameRow = log.find((r) => r && r.date === row.game_date);
|
||||
// Sport-aware date match: MLB rows are YYYY-MM-DD, NBA/WNBA ESPN rows are
|
||||
// ISO timestamps normalized to their ET date. game_date is already < today
|
||||
// (the .lt('game_date', cutoff) fetch), so an unplayed game never settles.
|
||||
const gameRow = log.find((r) => logRowOnDate(r, row.game_date, sp));
|
||||
if (!gameRow) { pending += 1; continue; }
|
||||
const actual = statValue(gameRow.stat, row.stat);
|
||||
const actual = statValue(gameRow.stat, row.stat, sp);
|
||||
if (actual == null) { pending += 1; continue; }
|
||||
const outcome = settleResult(row.side, actual, row.line);
|
||||
if (!outcome) { pending += 1; continue; }
|
||||
@@ -386,10 +389,15 @@ async function settleAllLedgers(opts = {}) {
|
||||
}
|
||||
|
||||
async function defaultGetPlayerStats(name, sport) {
|
||||
if (String(sport).toLowerCase() === 'mlb') {
|
||||
const sp = String(sport || '').toLowerCase();
|
||||
if (sp === 'mlb') {
|
||||
return require('./adapters/mlbStatsAdapter').getPlayerStats(name);
|
||||
}
|
||||
return { found: false }; // no free settled-result feed yet → pending
|
||||
// Wave 1 — NBA/WNBA settle against the FREE ESPN per-game log.
|
||||
if (sp === 'nba' || sp === 'wnba') {
|
||||
return require('./adapters/espnStatsAdapter').getPlayerGameLog(name, sp);
|
||||
}
|
||||
return { found: false }; // soccer — no free settled-result feed yet → pending
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -28,9 +28,16 @@
|
||||
* Everything here is pure or fully injectable — no requires of redis/ntfy.
|
||||
*/
|
||||
|
||||
/** Sports with a real settled-result feed (mlb game logs). Keep in sync with
|
||||
* outcomeService/ledgerService's MLB-only settlement until Phase 4.5. */
|
||||
const SETTLEABLE_SPORTS = ['mlb'];
|
||||
/** Sports with a real settled-result feed. MLB = statsapi game logs; NBA/WNBA =
|
||||
* ESPN per-game logs (Wave 1). Keep in sync with outcomeService/ledgerService's
|
||||
* defaultGetPlayerStats. Soccer stays out until it has a settled-result feed. */
|
||||
const SETTLEABLE_SPORTS = ['mlb', 'nba', 'wnba'];
|
||||
|
||||
/** Sports whose zero-settle alarm requires a real-finals probe before paging:
|
||||
* their slates go dark for months (offseason) and a stale pending row must not
|
||||
* false-page on a genuine off-day. MLB is exempt (proven daily feed in-season;
|
||||
* a dark day fetches 0 rows and never alarms). */
|
||||
const FINALS_GATED_SPORTS = ['nba', 'wnba'];
|
||||
|
||||
const PAGE_THRESHOLD = 3;
|
||||
|
||||
@@ -79,10 +86,28 @@ function morningHourUtc(hoursUtc) {
|
||||
* Evaluate the zero-settle signal from settleAllLedgers results.
|
||||
* alarm === true only when settleable-sport rows EXISTED for settlement
|
||||
* (fetched from Postgres: settled + pending > 0) and none settled.
|
||||
*
|
||||
* Wave 1 — a finals-gated sport (NBA/WNBA) only contributes to the alarm when
|
||||
* yesterday actually had games: `opts.finalsBySport[sport]` truthy (the caller
|
||||
* counts ESPN `state==='post'` events). Without that signal its stale pendings
|
||||
* are excluded, so an offseason/off-day never false-pages "settled 0". MLB is
|
||||
* always counted (a dark MLB day fetches 0 rows → settled 0 / pending 0 → no
|
||||
* alarm on its own).
|
||||
* opts: { settleable, finalsBySport }. A bare array 2nd arg (legacy call:
|
||||
* `zeroSettleAlarm(results, settleableArray)`) is still honored.
|
||||
*/
|
||||
function zeroSettleAlarm(ledgerResults, settleable = SETTLEABLE_SPORTS) {
|
||||
function zeroSettleAlarm(ledgerResults, opts = {}) {
|
||||
const o = Array.isArray(opts) ? { settleable: opts } : (opts || {});
|
||||
const settleable = o.settleable || SETTLEABLE_SPORTS;
|
||||
const finalsBySport = o.finalsBySport || {};
|
||||
const rows = (Array.isArray(ledgerResults) ? ledgerResults : [])
|
||||
.filter((r) => r && settleable.includes(String(r.sport || '').toLowerCase()));
|
||||
.filter((r) => r && settleable.includes(String(r.sport || '').toLowerCase()))
|
||||
.filter((r) => {
|
||||
const sp = String(r.sport || '').toLowerCase();
|
||||
// Finals-gated sports need a "yesterday had games" signal to count.
|
||||
if (FINALS_GATED_SPORTS.includes(sp)) return Boolean(finalsBySport[sp]);
|
||||
return true;
|
||||
});
|
||||
const settled = rows.reduce((n, r) => n + (r.settled || 0), 0);
|
||||
const pending = rows.reduce((n, r) => n + (r.pending || 0), 0);
|
||||
return { alarm: settled === 0 && pending > 0, settled, pending };
|
||||
@@ -177,5 +202,6 @@ module.exports = {
|
||||
buildPulseMessage,
|
||||
dateET,
|
||||
SETTLEABLE_SPORTS,
|
||||
FINALS_GATED_SPORTS,
|
||||
PAGE_THRESHOLD,
|
||||
};
|
||||
|
||||
@@ -45,7 +45,53 @@ const MLB_LOG_FIELD = {
|
||||
doubles: 'doubles', triples: 'triples', outs: 'outs',
|
||||
};
|
||||
|
||||
function statValue(statObj, statType) {
|
||||
// Wave 1 — NBA/WNBA settlement box-field map. A SEPARATE local map from
|
||||
// MLB_LOG_FIELD (the S11 three-map-split rule — settlement, features, and live
|
||||
// tracking each own their own map; never merge). The ESPN gamelog row's `stat`
|
||||
// object (espnStatsAdapter.getPlayerGameLog) is already keyed by VYNDR stat
|
||||
// names, so simple stats map 1:1; combo stat_types (pts_reb_ast, …) sum their
|
||||
// components at read time — mirroring featureCache.statFromGameLog. A stat_type
|
||||
// absent here does NOT settle (absent beats a fabricated outcome); add a new
|
||||
// NBA/WNBA stat here (and to featureCache + liveTrackingService) to unlock it.
|
||||
const NBA_BOX_KEY = {
|
||||
points: 'points', rebounds: 'rebounds', assists: 'assists', threes: 'threes',
|
||||
steals: 'steals', blocks: 'blocks', turnovers: 'turnovers', pra: 'pra',
|
||||
};
|
||||
const NBA_COMBO = {
|
||||
pts_reb_ast: ['points', 'rebounds', 'assists'],
|
||||
pts_reb: ['points', 'rebounds'],
|
||||
pts_ast: ['points', 'assists'],
|
||||
reb_ast: ['rebounds', 'assists'],
|
||||
stl_blk: ['steals', 'blocks'],
|
||||
};
|
||||
|
||||
// Resolve one NBA/WNBA per-game stat value. Combos require EVERY component to
|
||||
// be present (a played game reports 0, not absent) — a partial box never
|
||||
// fabricates a combo total.
|
||||
function nbaStatValue(statObj, statType) {
|
||||
if (!statObj) return null;
|
||||
const st = String(statType || '').toLowerCase();
|
||||
const combo = NBA_COMBO[st];
|
||||
if (combo) {
|
||||
let sum = 0;
|
||||
for (const c of combo) {
|
||||
const n = parseFloat(statObj[c]);
|
||||
if (!Number.isFinite(n)) return null;
|
||||
sum += n;
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
const f = NBA_BOX_KEY[st];
|
||||
if (!f) return null;
|
||||
const n = parseFloat(statObj[f]);
|
||||
return Number.isFinite(n) ? n : null;
|
||||
}
|
||||
|
||||
// Sport-aware actual-value resolver. Default (unspecified/mlb) reads the
|
||||
// statsapi.mlb.com game-log field; nba/wnba read the ESPN gamelog box object.
|
||||
function statValue(statObj, statType, sport) {
|
||||
const sp = String(sport || 'mlb').toLowerCase();
|
||||
if (sp === 'nba' || sp === 'wnba') return nbaStatValue(statObj, statType);
|
||||
const f = MLB_LOG_FIELD[String(statType || '').toLowerCase()];
|
||||
if (!f || !statObj) return null;
|
||||
const n = parseFloat(statObj[f]);
|
||||
@@ -66,6 +112,32 @@ function dateStrings(ts) {
|
||||
return [...new Set([utc, et])];
|
||||
}
|
||||
|
||||
// The America/New_York calendar date (YYYY-MM-DD) of an ISO timestamp.
|
||||
function etDate(ts) {
|
||||
if (!ts) return null;
|
||||
const d = new Date(ts);
|
||||
if (isNaN(d.getTime())) return null;
|
||||
try {
|
||||
return new Intl.DateTimeFormat('en-CA', { timeZone: 'America/New_York' }).format(d);
|
||||
} catch {
|
||||
return d.toISOString().slice(0, 10);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Does a game-log row fall on `targetDate` (YYYY-MM-DD)?
|
||||
* MLB rows are already plain YYYY-MM-DD → exact compare (unchanged behavior).
|
||||
* NBA/WNBA rows carry a FULL ISO timestamp from ESPN (e.g. a late tip is
|
||||
* 00:30Z the next calendar day) → match on either its UTC or ET date so a
|
||||
* game whose UTC date rolled past midnight still matches its ET slate date.
|
||||
*/
|
||||
function logRowOnDate(logRow, targetDate, sport) {
|
||||
if (!logRow || !logRow.date || !targetDate) return false;
|
||||
const sp = String(sport || 'mlb').toLowerCase();
|
||||
if (sp === 'nba' || sp === 'wnba') return dateStrings(logRow.date).includes(targetDate);
|
||||
return logRow.date === targetDate;
|
||||
}
|
||||
|
||||
const sideOver = (side) => {
|
||||
const s = String(side || 'over').toLowerCase();
|
||||
return s === 'over' || s === 'o';
|
||||
@@ -130,6 +202,8 @@ async function settleSnapshot(sport, opts = {}) {
|
||||
} catch { logByPlayer[player] = []; }
|
||||
}
|
||||
|
||||
const todayEt = etDate(nowIso);
|
||||
const isBasketball = sp === 'nba' || sp === 'wnba';
|
||||
const fresh = [];
|
||||
let pending = 0;
|
||||
for (const g of grades) {
|
||||
@@ -140,16 +214,29 @@ async function settleSnapshot(sport, opts = {}) {
|
||||
const gradedTs = (g.gradedAt && g.gradedAt.timestamp) || snap.updated_at || nowIso;
|
||||
const dates = dateStrings(gradedTs);
|
||||
const log = logByPlayer[player] || [];
|
||||
// Find the game played on the graded date.
|
||||
const row = log.find((r) => r && r.date && dates.includes(r.date));
|
||||
// Find the game played on the graded date (sport-aware date normalization).
|
||||
const row = log.find((r) => dates.some((d) => logRowOnDate(r, d, sp)));
|
||||
if (!row) { pending += 1; continue; }
|
||||
const actual = statValue(row.stat, stat);
|
||||
// Detect FINAL honestly: a game-log row is a COMPLETED game, but never
|
||||
// settle a game whose ET date is today (could be an in-progress partial
|
||||
// row for NBA/WNBA). MLB game logs are final-only + settle same-day, so
|
||||
// this guard is scoped to basketball — it must not stall MLB afternoons.
|
||||
if (isBasketball) {
|
||||
const rowEt = etDate(row.date);
|
||||
if (!rowEt || rowEt >= todayEt) { pending += 1; continue; }
|
||||
}
|
||||
const actual = statValue(row.stat, stat, sp);
|
||||
if (actual == null) { pending += 1; continue; }
|
||||
const result = settleResult(side, actual, line);
|
||||
if (!result) { pending += 1; continue; }
|
||||
// Store the game's ET calendar date (YYYY-MM-DD). MLB rows are already in
|
||||
// that form; basketball rows carry a full ISO timestamp → normalize so the
|
||||
// accuracy 30-day window filter + the idempotency key (both key off `date`)
|
||||
// behave identically across sports.
|
||||
const outcomeDate = isBasketball ? (etDate(row.date) || row.date) : row.date;
|
||||
const outcome = {
|
||||
player, stat, line, side: sideOver(side) ? 'O' : 'U',
|
||||
grade: g.grade, actual, result, date: row.date,
|
||||
grade: g.grade, actual, result, date: outcomeDate,
|
||||
gradedAt: gradedTs, settledAt: nowIso,
|
||||
};
|
||||
const key = outcomeKey(outcome);
|
||||
@@ -215,10 +302,16 @@ function normalizeLog(raw) {
|
||||
}
|
||||
|
||||
async function defaultGetPlayerStats(name, sport) {
|
||||
if (String(sport).toLowerCase() === 'mlb') {
|
||||
const sp = String(sport || '').toLowerCase();
|
||||
if (sp === 'mlb') {
|
||||
return require('./adapters/mlbStatsAdapter').getPlayerStats(name);
|
||||
}
|
||||
// NBA/WNBA/soccer: no free settled-result feed here → pending.
|
||||
// Wave 1 — NBA/WNBA settle against the FREE ESPN per-game log (Wave 0's
|
||||
// getPlayerGameLog returns the same { found, last10:[{date, stat}] } shape).
|
||||
if (sp === 'nba' || sp === 'wnba') {
|
||||
return require('./adapters/espnStatsAdapter').getPlayerGameLog(name, sp);
|
||||
}
|
||||
// soccer: no free settled-result feed yet → pending.
|
||||
return { found: false };
|
||||
}
|
||||
|
||||
@@ -293,10 +386,15 @@ module.exports = {
|
||||
computeAccuracy,
|
||||
accuracyBuckets,
|
||||
// Session 58 — settlement primitives shared with ledgerService (single
|
||||
// source of truth for hit/miss/push + MLB log-field resolution).
|
||||
// source of truth for hit/miss/push + log-field resolution). Wave 1 —
|
||||
// logRowOnDate normalizes the ESPN ISO game-log date for NBA/WNBA.
|
||||
settleResult,
|
||||
statValue,
|
||||
logRowOnDate,
|
||||
SPORTS,
|
||||
MIN_SAMPLE,
|
||||
__internals: { settleResult, gradeBucket, dateStrings, statValue, outcomeKey, MLB_LOG_FIELD, TIERS },
|
||||
__internals: {
|
||||
settleResult, gradeBucket, dateStrings, etDate, statValue, nbaStatValue,
|
||||
logRowOnDate, outcomeKey, MLB_LOG_FIELD, NBA_BOX_KEY, NBA_COMBO, TIERS,
|
||||
},
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user