fix(refractor): mask variant hash to 31 bits to fit Postgres INTEGER #217

Merged
cal merged 1 commits from fix/variant-hash-int32-overflow into main 2026-04-11 18:16:09 +00:00

1 Commits

Author SHA1 Message Date
Cal Corum
ab15228c44 fix(refractor): mask variant hash to 31 bits to fit Postgres INTEGER
compute_variant_hash took the first 8 hex chars of a SHA-256 digest and
cast to int, producing values up to 2^32 - 1. The variant columns on
Card, BattingCard, PitchingCard, and RefractorCardState are Peewee
IntegerField → Postgres INTEGER, which is signed 32-bit (max 2^31 - 1).
Roughly half of all players (~50%) would hash into the range [2^31,
2^32 - 1] and crash tier-up writes with:

  peewee.DataError: integer out of range

Surfaced via /dev refractor-test card_id:64460 (Charles Nagy,
player_id=10795), whose tier-1 hash was 2874960417. The outer
exception handler in refractor.evaluate_game caught the error and
logged a warning, so the tier-up was silently dropped — the test
harness reported "No tier-up detected (evaluated 2 cards)" while
apply_tier_boost was actually failing mid-write.

Fix: mask the hash with & 0x7FFFFFFF, dropping one bit of entropy.
~2.1B distinct values remain — still astronomically collision-safe.

Backwards-compatible: all 9 existing refractor_boost_audit rows and
9 persisted non-zero variants have hashes where the high bit was
already 0 (those tier-ups happened to land in the safe half). Masking
leaves those values unchanged.

Added regression test test_fits_postgres_int32 covering 10,000 player
IDs × 5 tiers = 50,000 combinations, all asserted ≤ 2,147,483,647.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-11 13:11:40 -05:00