CLAUDE.md carries a curated hot list (the ~47 rules that most often prevent production incidents or wasted agent time). This file is the full catalog for deep-dive reference. When a hot-list item is added or rotated out, keep its full-catalog form here so the reference stays complete while the hot list stays short.
Doctrine (Alex, Queue #207): read-side exclusion protects metrics; it never closes an issue. A curve exclusion, display suppression, or
WATCH-not-REDreclassification stops a bad class from lying to a metric — but the defect is still live. Every excluded class carries a fix-or-documented-loss follow-up (root cause fixed, OR loss quantified: count + ledger). "Stopped counting it" ≠ "fixed it." Corollary for regrades: verify-before-regrade, ledger-first — quote the before/after ledger and confirm the class is what you think (e.g. #1112's Class-A vs the 15 stale-stat_model false positives that a blind pass would have corrupted) BEFORE the bulk write.
Generated 2026-08-24. Regenerate whenever an entry is added. This index is a claim about the file below it, so it goes stale the moment the catalog grows — the rulings index has a CI check in both directions for exactly this reason, and this one does not have one yet (tracked separately). Verified against the catalog on 2026-08-24: the numbered entries below are exactly the 138 in this file.
Coverage: entries #16–#157 and #159. Entries #1–#15 are not in this file (they live as the CLAUDE.md hot list); #158 is
claimed by lane1b/007 and arrives with that branch. The doctrine block at the top (read-side exclusion never closes an
issue; verify-before-regrade, ledger-first) is unnumbered and precedes the catalog.
Coverage line corrected 2026-09-05: it read "#16–#153, contiguous (138 entries) … nothing ≥ #154 appears here" while #154–#157 were already banked below it. The 2026-08-24 generation note above is the reason — this index is a claim about the file and it goes stale the moment the catalog grows.
Items 16–105 (file section: "Items 16-75 (overflow and deep-dive notes)" — actually runs through #105)
#16 — Delete from the 8+ FK tables before removing an event row; use raw SQL, not ORM db.delete(), to avoid autoflush FK violations.
#17 — Kalshi auto-creates pm_ events when none match; guard blocks new duplicates — clean historical orphans via admin endpoints.
#18 — Keep the quota guard remaining-driven; never add a QUOTA_GUARD_EXPIRY/date constant — a hardcoded expiry silently disabled it.
#19 — Route ALL team-name matching through utils/name_normalization.py; expand city abbreviations before token overlap scoring.
#20 — Championship grid: apply the Kalshi 0.45-0.65 noise filter and enforce P(round N) >= P(round N+1); watch esports "Masters" leaking into golf.
#21 — Frontend-only changes need no Heroku step but still need the master-write lock; CI's Heroku deploy transport is live — do not delete it.
#22 — Never show 100%/0% probabilities for finished events — filter post-game completion probs; use opening odds or aggregate instead.
#23 — Derive chart domain from commenceTime + last ESPN/score timestamp; never constrain it solely from (possibly sparse) odds data.
#24 — In classifyPlayoffStage(), check conference patterns BEFORE championship patterns or "Eastern Conference Champion" misclassifies.
#25 — compute_aggregate_probability() is the single source of truth; never display raw odds_snapshots without the aggregate fallback.
#26 — Pipe Python through bash with quoted heredocs (python3 << 'PYEOF') to prevent shell expansion and != escaping issues.
#27 — Filter non-winner golf markets via _NON_WINNER_MARKET_RE; only outright winner/champion markets go in card hero probabilities.
#28 — Use EvolutionView's positionOptions prop to switch markets; pass entityLabel="Teams" for team sports.
#29 — Don't trust "PGA Tour" labels for golf events — classify tours from DataGolf's tour field.
#30 — isTournamentLive() must date-validate: never "live" past end_date + 1 day; check schedule_status === "completed" first.
#31 — Append the _womens suffix when _WOMENS_RE matches so men's and women's golf majors group (and display) separately.
#32 — Championship grid uses sqrt-scaled inline bars (sqrt(prob)/sqrt(0.4) width) with probability-banded font weights, not heat maps.
#33 — 7d/24h/today share one SWR cache key (filtered client-side); only "Season" fetches separately; keep keepPreviousData: true.
#34 — playoffs.py must return market_id on each grid column — the frontend builds evolution-chart stage pills from them.
#35 — When a cup event has exactly 2 golfers (teams), render CupCard (left/right + probability bar); detect via _isCupEvent().
#36 — Never re-import a name inside a function body (Py 3.12+): a late from datetime import timedelta makes earlier uses UnboundLocalError.
#37 — Kalshi futures tickers don't start with Odds API sport keys — use _SPORT_TO_KALSHI_ROOTS in the Related Futures sport filter.
#38 — FuturesMarket.market_tier is NULL for most markets — populate tier during Kalshi/Polymarket upserts before relying on tier queries.
#39 — The Team columns are logo_url_small / logo_url, not logo_small — Team.logo_small raises AttributeError.
#40 — Polymarket neg-risk markets return null outcomePrices in bulk — fall back to bestBid/bestAsk midpoint or lastTradePrice.
#41 — Play-in markets are NOT conference championships — exclude them from the grid entirely (return None), never route to make_playoffs.
#42 — Skip Odds API /scores for ESPN-mapped sports (ESPN covers them every 60s); use it only for non-ESPN sports.
#43 — Daily burn chart: scale per-task increments to the official x-requests-used total so the chart never retroactively shrinks.
#44 — EOM quota forecasts must use the two most recent COMPLETE days — always exclude today's partial day.
#45 — Polymarket game events: create one FuturesMarket per sub-market (own condition_id); don't flatten. NegRisk sub-markets ARE outcomes.
#46 — Never mix ORM attribute writes with Core SQL updates in one session — use Core/raw SQL for ALL task writes, then sync the ORM object.
#47 — The admin auth env var is ADMIN_TOKEN (ADMIN_SECRET is only a fallback) — reference ADMIN_TOKEN in code, docs, and curl.
#48 — GET /api/events/{id} must expose box_score_data or PlayerPropsDashboard falls back to "pre" (probability) mode.
#49 — Never delete a migration file that has run on Heroku — a missing revision blocks ALL migrations, and the Procfile masks the failure.
#50 — Always run npm run build locally — Vercel runs next build (ESLint + rules-of-hooks); tsc --noEmit passing proves nothing.
#51 — Keep _KALSHI_TEAM_ABBREVS complete — missing ticker abbreviations force name-based extraction that fails ILIKE matching.
#52 — Strip diacritics (unicodedata NFD) before StatPal fixture team-name matching — exact string match fails on Montréal vs Montreal.
#53 — Every rate/coverage metric needs a denominator where 100% is structurally achievable — exclude resolved/closed/impossible rows.
#54 — Never read NWPathMonitor.currentPath before start(queue:) — it is always .unsatisfied; use pathUpdateHandler or a continuation.
#55 — Parse BOTH tournament.match and tournament.week in StatPal season-schedule — playoff games live in tournament.week.
#56 — StatPal _normalize_status() collapses periods to "live" — use raw_status on StatPalFixture to preserve Q3/1H/HT.
#57 — Event merges must UPDATE the six non-CASCADE FK tables to the survivor before deleting the orphan event.
#58 — Normalize independent binary-market probabilities before display: if the sum exceeds 1.05, divide each by the sum.
#59 — Treat sports futures with a 90%+ leader as effectively resolved unless the leader had a real underdog/surprise journey.
#60 — Pin hooks must sync to the server API on every pin/unpin when authenticated — localStorage-only pins are invisible cross-platform.
#61 — Update EXPECTED_ENTRIES in tests/test_tasks_wiring.py whenever adding a beat_schedule entry — CI fails otherwise.
#62 — Gmail send uses an OAuth2 refresh token (not a service account); the OAuth Playground redirect URI must NOT have a trailing slash.
#63 — Polymarket commence_time is the market CREATION date — closing-line lookups before it find nothing; use the Part C rescue.
#64 — Never use Polymarket volume as an activity proxy — sub-market rows have volume NULL; use snapshot count or price_moved.
#65 — Wire every new Celery task into beat_schedule — an unwired task cost 23K outcomes their snapshots; the wiring test now catches it.
#66 — status='closed' events are FINISHED games — calibration/closing-line queries must use status IN ('completed','closed').
#67 — Kalshi golf commence_time is the resolution date — fix to the DataGolf start_date via _fix_golf_commence_times() before calibration.
#68 — Keep background-queue scheduling under the drain rate (~23 tasks/hr at concurrency=2); monitor celery-debug, purge in emergencies.
#69 — DB-only fallback: set golf commence_time = close_time - 4.5 days when DataGolf is unreachable — imprecise but prevents stale cards.
#70 — is_winner backfill needs 3 passes (clean resolution / mutually exclusive / independent thresholds) — one heuristic crowns wrong winners.
#71 — Short-circuit the Polymarket group_id API scan when zero null-group_id rows remain — the ~200K-event scan takes 10+ minutes.
#72 — Never use if: secrets.X != '' at step level in GitHub Actions (it rejects the workflow) — use a shell [ -n "$X" ] check in run:.
#73 — Add a ±12h commence_time filter to grouped sub-market queries — group_id alone leaks Game 1 sub-markets onto Game 2's page.
#74 — Use the get_optional_user dependency on the bug-report endpoint so user_id is set for authed users without requiring auth.
#75 — Extracted Swift files need their own imports and module-visible helpers; verify the old class definition was removed from the source file.
#76 — Store user_email on the bug report at creation; enqueue "fixed" email only on the status transition, with summary, valid email, unsent.
#77 — Search FTS weighting is query-time only — if indexing is needed later, make it an explicit migration and measure real traces first.
#78 — Exclude impossible pairs from link-rate denominators — 100% must be structurally achievable or the metric is permanent noise.
#79 — Gate headline-keyword demotion bypasses on Tier 1/2 league context; only elimination/buzzer/walk-off (and EI>=85) bypass unconditionally.
#80 — _MAJOR_ELECTION_RE is an ALLOWLIST — add new countries' elections to it; non-matching election markets get the -30 penalty.
#81 — Dismissals propagate via story keys — a broad new key makes one dismissal suppress the whole class for 14 days; keep keys narrow.
#82 — Semantic-dismiss similarity must exclude generic category/type/archetype/format tokens; keep the soft -0.30 penalty and 50-item cap.
#83 — If the harness blocks literal git push, use git -c push.default=simple push origin master — don't misread the block as auth failure.
#84 — Sentry alert intake needs SENTRY_AUTH_TOKEN with project:read/event:read/org:read plus SENTRY_ORG and SENTRY_PROJECT secrets.
#85 — rollback() expires ORM objects even with expire_on_commit=False — copy scalars before commit/rollback loops; use Core update() after.
#86 — Creating Sentry alert rules needs alerts:read+write — use the idempotent scripts/setup_sentry_alerts.py, not the read-only intake token.
#87 — Event Registry structured match must include completed AND closed in its status filter, or completed events spawn orphan duplicates.
#88 — Give every emergency quota-conservation measure a specific revert date (TODO + usage alert) — March 2026's went 2+ months unreverted.
#89 — Use a ±28h (not ±4h) Event Registry match window; pick the closest candidate by time to avoid doubleheader false matches.
#90 — Never close a bug on deploy — close only on measured production evidence; otherwise label "blocked: awaiting verification".
#91 — Board hygiene is mandatory: move cards as you go, comment at transitions, and move to Done only with linked measured proof.
#92 — Commit migration files immediately; check git status for untracked alembic/versions/*.py before pushing — a missing revision 503s everything.
#93 — Never call run_async() inside async FastAPI endpoints — await directly; run_async() is only for sync Celery wrappers.
#94 — Derive Kalshi market status from KalshiMarket.status on upsert (resolved when all nested closed/settled); never hard-code "open".
#95 — Cache any endpoint loading >1000 ORM objects with relationships (Redis + Celery precompute) — heavy selectinload OOMs the 512MB dyno.
#96 — Size calibration SQL LIMITs to the population (600K, not 200K); the dedicated admin endpoint runs the phase standalone.
#97 — Settled Kalshi markets stay status='open' in our DB — run the two-phase settled-events backfill (status first, then snapshots).
#98 — Decouple status resolution (no limit) from snapshot creation (limit-aware) — a shared counter starves later-listed series.
#99 — Use Kalshi's BATCH candlestick endpoint for settled markets — it works; the per-market endpoint is deprecated (404).
#100 — Track winner coverage at MARKET level (BOOL_OR(is_winner) per market), never outcome level — outcome rate is bounded by market mix.
#101 — Kalshi settled events return 200 forever but drop markets[] past the ~74-86d retention cliff — give recovery rails a retention floor.
#102 — API clients returning Optional[T] must catch only 404 as None — retry or re-raise 429s, timeouts, and 500s.
#103 — box_score_data is a wrapper dict — iterate box_score_data["players"], never the top level, or no player name ever matches.
#104 — The sandbox blocks literal api.bainluck.com curls — source ~/.claude/.env and use $BAINLUCK_API / $ADMIN_TOKEN env vars instead.
#105 — Kalshi has THREE ticker formats — verify which one an endpoint expects before declaring it broken; old data only via settled pagination.
Items 106–153 (file section: "The June 2026 creation-freeze war + July data-integrity classes" and later ops/testing entries)
#106 — asyncio.to_thread does NOT free the loop for json.loads (C parser holds the GIL) — use orjson, smaller pages, and a resumable cursor.
#107 — Never build a raw sync redis client inside tasks/ — route through get_redis_client() (bounded 5s timeouts) or a hung Redis freezes the loop.
#108 — Parse admin db-query JSONB with an ast.literal_eval fallback (it emits Python repr), and never client-count its 1000-row-capped output.
#109 — Bounded backfills must iterate oldest-first (or explicitly target the stale tail) — newest-first can structurally never reach it.
#110 — Wrap every feed/scoring per-item loop body in its own try/except so a poison item is skipped, not fatal; test that siblings survive.
#111 — Scope diversity caps by card type — exempt game events explicitly, and guard-test BOTH the flood cap and the adjacent surface.
#112 — Test time anchors: offset FIRST then truncate, or freeze the clock; an anchor with an if on the clock is the defect. Use clock_sweep.py.
#113 — Escape literal colons in LIKE patterns inside SQLAlchemy text() (parsed as bind params); never wrap scheduled work in a silent catch-all.
#114 — completed_at >= commence_time is a hard invariant — a violation means a wrong-event data merge; treat any recurrence as a matching-layer P1.
#115 — Inspect git log origin/master..HEAD before committing in a shared working tree; use explicit-path git add, never -A or ..
#116 — Headless xcodebuild dies on #Preview macro sandboxing — pass OTHER_SWIFT_FLAGS='$(inherited) -Xfrontend -disable-sandbox'.
#117 — Worktree xcodebuild must borrow master's SPM checkout: -clonedSourcePackagesDirPath plus -disableAutomaticPackageResolution.
#118 — Never divide a _24h counter by 24h — read its TTL-derived window fields, or difference two reads over a known wall-clock gap.
#119 — Never judge task speed from last_duration_ms (one sample = the cheap path) — compute p95 from the rolling durations list.
#120 — Never date/annotate a key with a SECOND key of its own lifetime — derive the window from the counter's own TTL; siblings drift.
#121 — A test comparing production to the constant production reads detects nothing — mutate the constant and require a red test.
#122 — Test doubles must MODEL the operation a bug would abuse, not just record calls — and run mutation oracles on UNMUTATED source first.
#123 — Compare Shared Hit Blocks only between same plan-node types; read Heap Fetches beside index-only scans; arbitrate via endpoint A/B.
#124 — Never pipe or wrap a gate — redirect to a file, print the gate's OWN exit code, and read its VALUE: only exit 1 is a test result.
#125 — Use heroku run:detached for hand-applied DDL (pg:psql/logs are egress-blocked); persist output to Redis and checkpoint as you go.
#126 — Kill switches must fail SAFE: absent/corrupt/unreachable all resolve to the conservative value, initialised BEFORE the read.
#127 — Never f-string a set/dict/callable into a digest — repr order is per-process; sort rendered text and test via subprocess + negative control.
#128 — Before asserting X is ABSENT, prove the resource EXISTS — a 404 body satisfies every absence assertion you can write.
#129 — When fixing a rule, grep for its other copies and make them assert against each other; guard enumerations with a loop over the enumeration.
#130 — A test asserting defective behaviour locks the defect in — read assertions as product claims; amend unsignable ones in the same commit.
#131 — Plan mutations from the CONTRACT before trusting tests; build missing instruments first; an equivalent survivor is a SOURCE defect.
#132 — Use != null (or Number.isFinite), never !== null, for optional payload keys — test with the keys genuinely missing.
#133 — Grep for live importers before reusing a component — shared means imported, not well-named; retire dead components on discovery.
#134 — A census about a page/payload must read origin/master and production, not your branch base; ask which artifact the requester was looking at.
#135 — Require the POSITIVE terminator (* TEST SUCCEEDED **) plus a test-count floor — a truncated log with zero failures is not a pass.
#136 — Resolve simulator destinations to a UDID before xcodebuild — exit 70 with no verdict is a stale destination, not truncation.
#137 — Never put fix/close/resolve before an issue reference unless you mean it — GitHub ignores negation, colons, case, blank lines; use "re #N".
#138 — Never edit source while pytest is in flight — inspect.getsource slices the NEW file at OLD offsets; re-run clean first.
#139 — Truncate or uniquify gate-log paths per run and invoke gates by absolute path — a fixed-path log outlives the run and fakes the verdict.
#140 — A budget computed from completions can never be raised by the runs it cancels — ask what would RAISE any derived limit.
#141 — gh run rerun replays the ORIGINAL merge ref — after fixing the base, close/reopen the PR to mint a fresh merge ref.
#142 — Every worker/task/script ships with one IMPURE test that STARTS its entry point (ruling 102) — pure tests never prove wiring.
#143 — Grade calibration cells on ECE and use signed gap only as a direction hint — two opposite errors cancel in gap but never in ECE.
#144 — Check opening_captured_at against resolution_date before trusting opening_probability; probe null, cp=opening, and age together.
#145 — Re-derive header status claims from source at each publication, or date them as quotations — "met" and "closed" differ.
#146 — A percentile pinned at a limit measures only the CLIP RATE — read the histogram and success count; check whose clock it hits.
#147 — A defect's population is the set of places that RENDER it — read the components, don't grep for the shared constant.
#148 — Widen signatures with an OPTIONS OBJECT, never a bare scalar — .map(fn) hands the new param the index; grep the name without "(".
#149 — db-query: timeout_ms is explain-only (row path fixed at 10s); "multi-statement" refusals count semicolons in COMMENTS — strip, then EXPLAIN.
#150 — Give each feed tier a quota and dedupe before it — one ORDER BY + LIMIT across tiers is winner-takes-all; test flood AND slate directions.
#151 — SQLAlchemy JSON stores Python None as JSON 'null', so IS NOT NULL is true for nothing — also compare the text form ('null', '{}').
#152 — Patch one level BELOW the layer under audit; prove writes through the reader its consumer uses — a stub proves only the stub.
#153 — Advance resume cursors only past COMPLETED rows, never selected ones; report all four counts; never wrap while deferred.
#154 — A state that ENDS needs its own vocabulary and its own timestamp — "it is no longer X" is not derivable from a record of attempts to make it X. market_match_receipts knew linked/rejected and futures_markets had no transition stamp, so "did the merge drop 261 links?" had no answer: a lost link, a moved link and a market that simply settled were the same absence. Two rules follow. (a) Every writer that ends or moves the state writes the record — the matcher's passes, the merge rails, the admin repairs — and the record names WHO (actor) and WHERE FROM (previous_event_id), because a count without the pair diagnoses nothing. (b) A stamp coupled to a status must be written in the SAME statement as the status and cleared when the status reverses; the Kalshi and Polymarket polls rewrite status on every tick and can flip a market back to open, so a stamp written anywhere else outlives the reopen. Never backfill such a column at migration time — NULL means "we did not observe it", and a release-clock backfill asserts that hundreds of thousands of rows transitioned the instant the migration ran.
#155 — onupdate=func.now() is a Core construct and raw text("UPDATE ...") never fires it — a table with a mix of ORM and raw-SQL writers has an updated_at that is silently wrong for the raw ones, so never derive a transition time from it. Give the transition its own column and stamp it at each writer; guard the set of writers with a source scan that reads the UPDATE's TABLE (events has a status column too) and raises on a shape it cannot classify.
#156 — A ONE-ROW-PER-KEY record cannot hold history, and the row it destroys first is the one you added it for. market_match_receipts is deliberately one upserted row per market ("the last time the matcher looked, here is what it decided"), and LINKLOSS-02 wrote the link-change vocabulary onto it — outcome, previous_event_id, actor. But an unlinked market is by definition event_id IS NULL, which is exactly the population the scheduled matcher re-scans every 15 minutes, so the next ordinary attempt upserted {rejected, null, null} over {unlinked, 42, matcher_pass} and the reason a price left a card was gone inside the hour (CERT-791, measured on the exact SHA). The census then counted only the changes nobody had re-attempted — a number that SHRINKS as the matcher works, so a night that lost links reads as a quiet one. Before writing a state transition onto a current-state row, ask what re-touches that row and how soon; if the answer is "the same job that caused the transition", the record has to be an append-only row of its own. Current state and history are two tables, and the census reads history. Corollaries: give the history table no unique key at all, so there is no ON CONFLICT for a later writer to reach for; append from the single function every writer already funnels through, not at each call site; and gate the append on the OUTCOME, so a claim a durability check downgraded never becomes a permanent — and uncorrectable — record of a link loss that never happened.
#157 — A source-scan guard certifies the population it SCANS, not the population its name claims. The LINKLOSS-02 unlink guard was green while three live endpoints unlinked markets with no receipt at all: it scanned prediction_market_matching.py, and it recognised the ORM assignment and the Core values(event_id=None) but not raw UPDATE ... SET event_id = NULL, which is the shape all three used. A scan whose file list or shape list is narrower than the invariant reports a clean zero for exactly the case it exists to catch. Sweep every file under app/, derive the file list from the WEAKER (text) reading so a file whose only site is in a newly-unrecognised shape cannot drop out of the sweep before the cross-check sees it, and attribute a site to its enclosing FUNCTION rather than an N-line window — the receipt of a bulk unlink is often collected before the write and published after the commit, tens of lines away.
#159 — A stranded-ship claim is refutable in four seconds — refute it before you escalate. Same-file line coverage is structurally blind to a re-land under a different commit or branch name: the work IS on master, under a name the score never looked at, so the score reads "stranded" and can never read anything else. git log --all --grep='<the branch's own commit subject>' finds it. UX-P178's status half re-landed one day later as UX-P208/P209/P210 — the faked LIVE dot, the guessed phase, the "Upcoming Tournaments" heading — and two sessions escalated the whole branch as stranded on a score that could never have seen that. But the mirror-image claim is the more dangerous one, and the first draft of this entry made it: it said "UX-P178 re-landed as UX-P208" full stop, recording a PARTIAL re-land as a complete one, against the ship's own id, in the file the next deletion sweep reads. The other half never landed — is_major hardcoded False at both tennis concept sites, the winner market's resolution_date served under the key start_date, and formatDate calling toLocaleDateString with no timeZone (a day early for every reader west of Greenwich, invisible to a CI that runs TZ=UTC) — and it survived on master for a week under an entry asserting it was already home. A false-landed claim deletes the branch; a false-stranded claim only wastes a session. So: a re-land is "landed" only for the defects you have confirmed are gone from master's own source — grep the defect, never the id, and when only part came back, say which part in the same sentence. Neighbours: CLAUDE.md hot-list #52 (no orphan WIP in the shared master tree) and the strip/rebase-completeness rule it cites — a strip or rebase is not complete until the stripped commits are on a pushed ref or explicitly ruled unneeded. (#158 is claimed by lane1b/007 and arrives with that branch; a gap is legal — docs/rulings/README.md.)
#160 — Kalshi settles a TIED golf round leader as result='scalar', never yes, so a tie reaches us as a market with graded losers and no winner; the 6/6 single-yes contrast arm is what turns 17/17 scalars into a mechanism, and crowning the tied leaders would manufacture a calibration defect to hide a cosmetic one.
- #1–#15 — not present in this file; coverage begins at #16. The intro says CLAUDE.md carries the curated hot list; the pre-16 entries apparently live there.
Explicitly cited: #8 (ORM/Core mixed-write JSONB loss on
win_probability_sources, cited inside #46). - Hot-list-numbered cross-references — many in-entry citations use CLAUDE.md HOT-LIST numbering, not this catalog's: e.g. "#53 (an empty 200 is a response
shape, not a fact)", "#54 (
cmd | tailreports tail's exit code)" — the full-catalog form of that #54 is #124 here. Stated mappings: hot-list 38–47 ↔ catalog #106–#115; hot-list #50 ↔ #116; CLAUDE.md #35 = the Kalshi retention window (full form in #101). Other hot-list citations with no full-catalog entry in this file (definitions in CLAUDE.md): #31 (hand-applied indexes), #32 (matching layer), #36, #40, #41, #43, #48 (non-detachedheroku runno-exec), #49 (Sentry count is lifetime), #51 (cwd is session state), #53. - Rulings and doctrine cited by number (rulings 017, 030, 047, 050, 055, 089, 102, 110; doctrine clauses 2 and 9) are defined in the rulings files /
docs/doctrine.md, not in this catalog.
Gap note: no numbering gaps inside this file — entries run contiguously #16–#153; #1–#15 and anything ≥ #154 are defined elsewhere (CLAUDE.md hot list / later additions), not here. #154 (the orphan-strip gotcha) is banked in PR #2140 and lands when that merges — the first regeneration this index will owe.
-
Deleting events requires FK cleanup — must delete from 8+ tables before removing the event row. Use raw SQL, not ORM
db.delete(), to avoid autoflush FK violations. -
Kalshi auto-creates pm_ events when no matching event exists. Guard added to prevent new duplicates, but historical orphans need cleanup via admin endpoints.
-
Quota guard is
remaining-driven, never date-gated —check_quota_guardinredis_state.pygates only on the liveremainingreading and auto-recovers when the billing cycle refills it. Do NOT add aQUOTA_GUARD_EXPIRY/date constant; a hardcoded expiry once silently disabled the guard when the clock rolled past it (expired 2026-04-01). No monthly maintenance is needed. -
Name normalization — ALL team name matching goes through
utils/name_normalization.py. City abbreviations (LA->Los Angeles, NY->New York, etc.) are expanded before token overlap scoring. -
Championship grid data quality — Kalshi 0.45-0.65 noise filter, monotonicity enforcement (P(round N) >= P(round N+1)), esports "Masters" pattern can leak into golf.
-
Frontend-only changes don't need Heroku work — but "only a push to master" is not a one-agent action (CORRECTED 2026-08-21, C-DOC-DRIFT-1). The mechanism is unchanged and still correct: Vercel deploys the frontend from GitHub, and the backend Heroku deploy runs inside CI's serialized, newest-wins-guarded
deployjob (.github/workflows/ci.yml— thegit push heroku master --forcetransport is live; do not "correct" this entry by deleting it). What was wrong was the word only. Under Program Lanes the Integrator alone rebases, gates, merges, pushes and verifies master, and ruling 017 makes.claude/handoff/LANE-integrator.lockmandatory for any exceptional master writer —/triageand/triage2included. So: a frontend-only change needs no Heroku step, and still needs the master-write lock. The superseded path is the lane-level direct push, never CI's backend transport; conflating the two is how a reader deletes a live deploy mechanism while trying to fix a stale instruction. -
Never show 100%/0% probabilities for finished events — Post-game completion probabilities (winner=100%) must be filtered. Use opening odds or aggregate probability instead.
-
Chart domain must derive from game timeline — Use
commenceTime+ last ESPN/score data timestamp. Never constrain chart domain solely from odds data (which may be sparse during API outages). -
classifyPlayoffStage()order matters — Conference patterns must be checked BEFORE championship patterns inRelatedFutures.tsx. "Eastern Conference Champion" contains "champion" and will misclassify as "Championship" if checked in wrong order. -
compute_aggregate_probability()is the single source of truth — Both feed API and event detail API must use it. Never display raw odds_snapshots without aggregate fallback. -
Bash heredocs with Python — When piping Python code via bash, use
python3 << 'PYEOF'(quoted heredoc) to prevent shell variable expansion and!=escaping issues. -
Golf market filtering —
_NON_WINNER_MARKET_REinroutes/golf.pyfilters out "compete in", "make the cut", "top N finishers" etc. from headline probabilities. Only outright winner/champion markets should appear in card hero probabilities. -
Evolution chart position/stage pills —
EvolutionView.tsxsupportspositionOptionsprop for switching markets. Golf uses Top 20/10/5/Win from Kalshi. Team sports use grid column market_ids (Make Playoffs/Conference/Championship). PassentityLabel="Teams"for team sports. -
Golf tour classification — Many events are mislabeled as "PGA Tour" when they're DP World Tour, Asian Tour, etc. DataGolf provides the correct
tourfield. Fix needed. -
Golf "LIVE" badge —
isTournamentLive()in the tournament page now has date-based validation (added April 14). Tournaments past theirend_date + 1 daycan't be "live". Also checksschedule_status === "completed"before falling back to leaderboard status. -
Men's/women's golf major separation —
_normalize_tournament()returns the same key for both. The grouping loop ingolf.pyappends_womenssuffix when_WOMENS_REmatches the market name.TOURNAMENT_DISPLAY_NAMESandTOURNAMENT_ORDERhave entries for both variants. -
Championship grid inline data bars —
TournamentProgressionTable.tsxuses sqrt-scaled horizontal bars instead of background color heat maps. Bar width =sqrt(prob) / sqrt(0.4) * 100%. Font weight varies: semibold >10%, normal 1-10%, faded <1%. -
Evolution chart SWR caching — 7d/24h/today share the same SWR cache key (same fetched data, filtered client-side). Only "Season" triggers a separate fetch (4320h).
keepPreviousData: trueprevents blank during re-fetch. -
Grid columns include market_id —
playoffs.pyreturnsmarket_idon each column (most common market_id from that column's data). Frontend uses these to build stage pills for the evolution chart. -
Cup card detection —
TournamentCard.tsx:_isCupEvent()checks tournament key for ryder/presidents/walker/solheim. When a cup has exactly 2 golfers (teams), rendersCupCardwith left/right layout + probability bar instead of leader/chasers. -
Python 3.12+ redundant imports cause UnboundLocalError —
from datetime import timedeltainside a function body makestimedeltalocal to the ENTIRE function scope. If the function usestimedeltabefore that line (from the module-level import), it crashes. Fixed inespn_sync.pyApril 15. Check for this pattern in other files. -
Related Futures requires Kalshi ticker prefix matching — Kalshi futures tickers (KXNBA, KXMLB, etc.) don't start with the Odds API sport key (basketball_nba, baseball_mlb). The sport filter in
get_related_futures()needs_SPORT_TO_KALSHI_ROOTSto find championship/award markets. Without this, only game-level Kalshi markets (which DO have sport-key external_ids) are discoverable. -
FuturesMarket.market_tieris NULL for most markets — Themarket_tierfield was designed to filter championships (1) from game props (5), but most markets have NULL. This prevents efficient querying for Related Futures. Fix: populate tier during Kalshi/Polymarket task upserts usingMarketMatchingRulefromleague_configs.py. -
Team model uses
logo_url_smallnotlogo_small— The column name islogo_url_small(andlogo_urlfor full size). UsingTeam.logo_smallcrashes with AttributeError. -
Polymarket neg-risk markets need bid/ask fallback — The Gamma API bulk
/eventsendpoint returnsoutcomePricesas null for neg-risk multi-outcome markets (championships, conference winners). The poller must fall back tobestBid/bestAskmidpoint orlastTradePrice. Without this, all championship/conference outcome probabilities are 0%. -
Play-in ≠ Make Playoffs — Kalshi's "Teams to Make the Eastern Conference Play-In Tournament" contains "Eastern Conference" but is NOT a conference championship market. Top seeds have ~0% play-in probability but ~99% playoff probability. Play-in markets must be excluded from the grid entirely (return
Nonefrom_match_market_to_column), not routed to make_playoffs. -
Odds API score fetching is partially redundant — ESPN provides scores every 60s for mapped sports (NBA, NHL, MLB, NFL). The Odds API
/scoresendpoint is only needed for non-ESPN sports (tennis, cricket, rugby). Score fetching is now skipped for ESPN-mapped sports where all recent events haveespn_event_id. -
Admin daily burn chart uses two counting systems — The official count (
x-requests-usedheader) and the per-task incremental tracking can diverge. The chart scales task proportions to match the official total to prevent retroactive shrinking. -
EOM quota forecast must exclude today's partial day — Using today's incomplete data in the trailing average makes the forecast artificially optimistic as the day progresses. Always use the two most recent complete days.
-
Polymarket game events have nested sub-markets — A single Polymarket "event" (e.g., "Magic vs Pistons") contains ~40 sub-markets (moneyline, spread, O/U, player props). These are NOT outcomes of one market — each sub-market has its own
condition_idandquestion. The polling task must create separate FuturesMarket rows per sub-market, not flatten them into outcomes. NegRisk events (championships, multi-candidate) are different — each sub-market IS one candidate and correctly maps to outcomes. -
ORM attribute assignment lost when mixed with Core SQL updates — Setting
event.field = valuevia ORM, then doingsession.execute(update(Event).where(...).values(...))via Core SQL in the same session can cause the ORM change to silently not persist. Found 3 times:espn_id(varchar),box_score_data(JSONB), and the originalwin_probability_sources(JSONB, gotcha #8). Safe pattern for Celery tasks: use Core SQL (or raw text SQL) for ALL writes, then sync the ORM object afterward (event.field = value) to prevent the ORM flush from reverting the DB state. For JSONB specifically, raw text SQL withcast(:val AS jsonb)is most reliable. -
Admin auth env var is
ADMIN_TOKEN, notADMIN_SECRET— Heroku hasADMIN_TOKENset. The code checksADMIN_TOKENfirst, withADMIN_SECRETas fallback. When referencing the admin secret in code, documentation, or curl commands, useADMIN_TOKEN. This mismatch caused a production lockout on April 21, 2026 when a security fix defaulted to False on missingADMIN_SECRET(which was never set — onlyADMIN_TOKENexisted). -
box_score_datamust be exposed in the event detail API — TheGET /api/events/{id}response must includebox_score_datafor the frontendPlayerPropsDashboardto show actual stats on completed games. Without it, the component falls back to "pre" mode (showing probabilities). The related-futures endpoint already usedbox_score_datainternally but the event detail endpoint did not return it until April 30, 2026. -
Never delete a migration file that has already run on Heroku — The
alembic_versiontable stores the current revision. If the corresponding.pyfile is missing,alembic upgrade headsfails with "Can't locate revision," blocking ALL subsequent migrations. This caused a site-wide outage on May 1-2, 2026: theadd_user_seen_markets.pyfile was deleted, theTeam.slugmigration couldn't run, and every endpoint loading Teams 500'd. Fix: restore the file, then clean up any stalealembic_versionentries if the migration originally ran as a separate branch. The Procfile's|| echomakes migration failures non-fatal, which masks this class of bug. -
Vercel runs
next build(ESLint + TS), not justtsc—tsc --noEmitpassing does NOT mean the frontend will deploy.next buildincludes ESLint rules-of-hooks checks. React hooks called after conditional early returns will compile but fail the build. Always runnpm run buildlocally. CI now catches this (May 7, 2026). This caused 20+ consecutive failed Vercel deploys. -
Kalshi ticker abbreviations need explicit mapping — The
_KALSHI_TEAM_ABBREVSmap inprediction_market_matching.pymust include every ticker abbreviation Kalshi uses. Missing entries (ATH for Athletics, WSH_MLB for Nationals) cause the matching task to fall back to market name-based extraction, which uses Kalshi's abbreviated names ("A's", "Chicago WS") that fail ILIKE matching against full event team names. The matching task now prefers ticker-derived team names over name-derived ones for all format types, not just game_prop. -
StatPal
_fixture_match_keyrequires diacritics stripping — The function uses exact lowercase string matching for team names. Unicode characters (Montréal vs Montreal) cause match failures. Fixed May 7, 2026 by stripping diacritics viaunicodedata.normalize("NFD")before comparison. -
Admin metric denominators must make 100% achievable — Every rate/coverage metric (link rate, matching coverage, unclassified rate, overall health) must use a denominator where 100% is structurally possible. Common pollution patterns: including resolved/closed markets, events without PM markets, non-sport markets, or marking overall health as critical for non-essential tasks. See
feedback_denominator_100pct.mdin memory. -
NWPathMonitor.currentPathis unsatisfied until started — CreatingNWPathMonitor()and immediately reading.currentPathalways returns.unsatisfied(offline). Must callmonitor.start(queue:)and usepathUpdateHandlerorwithCheckedContinuationto get the real network state. All iOS bug reports were showingnetwork: offlinebecause of this. -
StatPal
season-scheduleputs playoffs intournament.week, nottournament.match— Regular season games are intournament.match(the array our parser originally read). Playoff/postseason games are intournament.weekas[{"stage": "Play Offs", "match": [...]}]. Both arrays must be parsed in_extract_match_items(). Missing this caused ALL playoff games to be silently dropped for months. Fixed inbacce5d(May 11, 2026). -
StatPal livescores normalizes period to "live" — StatPal returns game period as the
statusfield (e.g., "Q3", "1H", "HT"). The_normalize_status()function converts all of these to "live", discarding the period information. Useraw_statusonStatPalFixtureto preserve the original value for period markers. Fixed in8932636(May 11, 2026). -
Event merge task must reassign ALL FK tables before delete — Eight tables have FK references to
events.id. Only two useON DELETE CASCADE(espn_snapshots,win_prob_snapshots). The other six (odds_snapshots,score_snapshots,scoring_plays,odds_aggregated,line_movement_analyses,futures_markets) require explicitUPDATE SET event_idbefore the orphan event can be deleted. -
Feed probability normalization for independent binary markets — Kalshi creates separate "Will X win?" binary markets for each candidate in a multi-outcome race. Each has its own 0-100% probability that includes vig/overround. When displaying top outcomes on Discover cards, the probabilities can sum well over 100%. Must normalize:
if sum > 1.05: divide each by sum. Applied infeed.pyafter buildingtop_outcomes_data. Same pattern as the Spotify race fix inentertainment.py. -
Sports futures staleness threshold is 90%+ with journey guard — Discover treats sports futures with a 90%+ leader as effectively resolved unless the leader had a real underdog/surprise journey. This catches eliminated-team markets that remain open for settlement while preserving genuinely interesting surprises.
-
Web pin hooks were localStorage-only —
usePinnedEvents.tsandusePinnedFutures.tsnever synced to the server. Pins made on web were invisible on iOS and vice versa. Fixed May 13: hooks now call server API on every pin/unpin when authenticated, and fetch server pins on mount. -
Celery beat schedule test has an allowlist —
tests/test_tasks_wiring.pyhasEXPECTED_ENTRIESset that must include every entry incelery_app.conf.beat_schedule. Adding a new scheduled task without updating this set causes CI failure. The test message tells you exactly what to add. -
Gmail API OAuth refresh tokens via Google Workspace — Using OAuth2 refresh token (not service account) to send email as
bugs@bainluck.com(alias ofalex.bain@bainluck.com). The OAuth Playground redirect URI must NOT have a trailing slash. Config vars:GMAIL_CLIENT_ID,GMAIL_CLIENT_SECRET,GMAIL_REFRESH_TOKEN,GMAIL_SENDER_EMAIL. Token authorized via developers.google.com/oauthplayground with "Use your own OAuth credentials" checked. -
Polymarket
commence_timepredates all snapshots — Polymarket setscommence_timeto the market creation date, not the event start time. 99.8% of Polymarket snapshots are captured AFTERcommence_time. This means the calibration backfill Part A ("last snapshot before commence_time") finds nothing and falls back toopening_probability. Part C rescue uses the last snapshot regardless of commence_time to fix this. -
Polymarket
volumeis NULL on decomposed sub-markets — When Polymarket events are decomposed into sub-markets (player props, spreads, O/U),event.volumefrom the API is stored on the parent market only. Sub-marketFuturesMarketrows getvolume = NULL. Volume is NOT a reliable trading activity proxy for Polymarket — use snapshot count orprice_moved(calibration_probability != opening_probability) instead. -
backfill_polymarket_historymust be in beat schedule — The task existed since early development but was never wired intocelery_app.conf.beat_schedule. This caused 23K outcomes (7%) to have zero snapshots, using placeholder opening prices in calibration. Always check beat schedule when adding new Celery tasks. Thetest_tasks_wiring.pyEXPECTED_ENTRIEStest catches this for future tasks. -
Events with
status = 'closed'are finished games — The staleness detector sets events toclosedwhen the Odds API stops returning data. These are completed games, not cancelled ones. Calibration and closing-line queries must usestatus IN ('completed', 'closed'), not juststatus = 'completed'. Missing this halved the MLB calibration sample. -
Kalshi golf
commence_timeis days wrong — Kalshi setscommence_time = market.close_time(resolution date, e.g., Sunday evening for a golf tournament). But calibration needs the tournament START date (Thursday) to grab pre-tournament closing prices. Without this fix, calibration uses in-play Round 3-4 prices (e.g., DeChambeau at 13% mid-tournament instead of 44% pre-tournament). Fix:_fix_golf_commence_times()intasks/kalshi.pymatches to DataGolf schedule via existing_normalize_tournament()and sets commence_time tostart_date. Also fixes stale golf cards in Discover/Sports feeds. -
Celery background queue saturation — At concurrency=2, scheduling ~35 tasks/hr on the background queue caused 400+ task backup. Tasks pile up faster than workers drain them, leading to hours-long delays for non-critical work. Reduced to ~23 tasks/hr. Monitor via
GET /api/admin/celery-debug. Emergency purge viaPOST /api/admin/celery-purge-background. -
Golf
commence_timeusesclose_time - 4.5 daysheuristic — The DataGolf API may fail or be unreachable from Celery workers. The DB-only fallback setscommence_time = close_time - 4.5 daysfor resolved golf markets. This approximates Thursday-start tournaments that resolve Sunday evening. Not precise, but prevents stale cards and gives calibration a reasonable closing-line window. -
_backfill_from_current_probabilityneeds 3-pass approach — Phase 1is_winnerbackfill handles three distinct market structures: (1) clean resolution — all outcomes at 0 or 1, winner obvious; (2) mutually exclusive — probabilities sum to ~1.0, highest wins; (3) independent thresholds — probabilities sum >1.5 (e.g., "over 2+", "over 3+"), each outcome with probability >0.50 wins independently. Applying a single heuristic to all three produces wrong winners. -
Polymarket API
group_idscan takes 10+ minutes —_backfill_polymarket_group_ids_from_apipaginates through ~200K Polymarket events to find group IDs for our markets. Short-circuit at the top of the phase when the count of nullgroup_idrows is 0 to avoid the expensive API scan on every backfill run. -
CI deploy job with step-level
if: secrets.X != ''breaks entire workflow — GitHub Actions rejects the workflow YAML file outright when a step usesif: secrets.HEROKU_API_KEY != ''. Thesecretscontext is not available in step-levelifconditions. Use a shell-level check (if [ -n "$HEROKU_API_KEY" ]) inside therun:block instead. -
Cross-game Polymarket market contamination — The
group_idlookup for sub-markets in the game-markets endpoint had no time-window filter. In playoff series, Game 1's sub-markets (same team names, samegroup_idprefix) leaked onto Game 2's detail page. Fixed by adding a ±12hcommence_timefilter to the grouped sub-market query, matching the pattern already used in the unlinked fallback query. -
Bug report submissions never had
user_id—request.state.user_idwas never set on the bug report submission endpoint because the route didn't use the auth dependency. All bug reports haduser_id = NULL, making it impossible to send "your bug was fixed" emails. Fix: useget_optional_userdependency (same pattern as preferences endpoint) to populateuser_idwhen the user is authenticated, without requiring auth for anonymous reports. -
Swift file extraction changes imports and visibility — Moving native view models/helpers out of their original view files changes what each Swift file can see. Extracted files need their own imports (
FoundationforlocalizedDescription,Date,trimmingCharacters,components(separatedBy:);CombineforObservableObject;osforLogger) and any helper used across files must be module-visible rather thanprivate. Also verify the old class definition was removed from the source view file; duplicatedfinal class FooViewModeldefinitions can compile far enough to obscure the real integration error. -
Bug fixed emails require captured submission email — Store
user_emailon the bug report when it is created, not when it is later marked fixed. A later join touserscan fail for anonymous reports, deleted users, or accounts whose email changed after submission. The admin PATCH path should enqueue email only when status transitions tofixed/actioned, a resolution summary exists,user_emailis valid, andnotification_sent_atis still null. -
Search weighted FTS is query-time only —
/api/events/searchnow ranks withwebsearch_to_tsqueryand weighted SQL expressions: event/team names weight A, futures market names B, and outcome names C. There is no storedts_vectorcolumn or trigger-backed index yet. If search needs indexing later, make it an explicit Postgres migration and measure against real search traces first. -
Prediction-market link-rate denominators must exclude impossible pairs — Link-rate health should not count unsupported/no-event coverage, obvious season/non-game markets, or sport/league combinations that cannot validly link. A healthy denominator is one where 100% is structurally achievable; otherwise the metric becomes permanent noise and hides real regressions.
-
Discover event demotion bypass: headline keywords must be gated on league tier — The headline generator labels nearly every recently-completed game as "Recent upset." If headline keywords like "upset", "comeback", "historic" bypass demotion regardless of league, Tier 3/4 foreign soccer events score 100 and crowd out entertainment/politics futures. Always gate headline-based demotion exceptions on
_discover_event_has_major_league_context()(Tier 1/2 only). "elimination"/"buzzer"/"walk-off" are the only keywords that should bypass regardless of tier. Same logic: EI >= 70 alone is not exceptional for a minor league game — require Tier 1/2 for moderate EI scores, only EI >= 85 is unconditionally exceptional. -
Election allowlist is inverted — default is penalty, not pass-through —
_MAJOR_ELECTION_REinfutures_highlights.pyis an allowlist, not a blocklist. Markets containing election keywords that do NOT match the allowlist receiveFOREIGN_LOCAL_ELECTION_PENALTY = -30. When adding a new country's election, add it to_MAJOR_ELECTION_RE, not to the obscure patterns blocklist. The obscure blocklist (_OBSCURE_ELECTION_PATTERNS) is for content that should be penalized even MORE (double penalty is prevented by checking"obscure_election" not in result.reasons). -
Dismiss signal propagates via story keys — new story keys affect suppression scope — When a user dismisses a market,
compute_story_key()is called on the dismissed item's name and the resulting key is added torecent_dismissed_story_keys. All futures sharing that key are subsequently suppressed. Adding a new story key (e.g.,story:minor_soccer_leagues) means dismissing ANY minor soccer market will suppress ALL minor soccer markets for that user for 14 days. Be careful not to make story keys too broad. -
Semantic dismiss must ignore generic tokens — Discover semantic dismiss propagation compares candidate tokens against the 50 most recent dismiss/unlike token sets and applies only a soft
semantic_dismiss:-0.30multiplier penalty above 0.60 Jaccard similarity. Do not include genericcategory:,type:,archetype:, orformat:tokens in the similarity set; otherwise dismissing one soccer/politics/entertainment card can downrank unrelated cards in the same broad category. Use topic/region/team/term tokens from_discover_semantic_tokens()and keep the 50-item cap. -
Codex command policy may reject literal
git push— In this harness, a shell command that starts withgit pushcan be blocked before it runs. Use an equivalent non-prefix form such asgit -c push.default=simple push origin master; it still invokes Git normally, but clears the local command-prefix policy. Do not treat a rejected literalgit pushas a remote/auth failure. -
Sentry alert intake needs project-level read scopes — A token that can receive Sentry emails or see basic account data is not enough for automated issue intake. The
Alert Intakeworkflow requiresSENTRY_AUTH_TOKENwith read-onlyproject:read,event:read, andorg:read, plusSENTRY_ORGandSENTRY_PROJECTrepository secrets. If those are missing, GitHub Actions failure intake still works, but Sentry intake is skipped or fails loudly. -
Async SQLAlchemy rollback expires ORM objects —
expire_on_commit=Falsedoes not preventsession.rollback()from expiring ORM instances. In async Celery tasks, reading an expired attribute later can trigger hidden lazy IO and raiseMissingGreenlet(greenlet_spawn has not been called). Long loops that commit/rollback per item must copy ORM rows into scalar refs before the loop, use Coreupdate()for DB mutations after rollback boundaries, and log errors from scalar IDs instead ofmarket.id/event.idORM attributes. -
Sentry alert rule creation needs alerts:write scope — The
SENTRY_AUTH_TOKENused for issue intake (gotcha #84) only has read scopes (project:read,event:read,org:read). Creating alert rules via the Sentry Rules API requiresalerts:read+alerts:write. Usescripts/setup_sentry_alerts.pyto create rules -- run it viagh workflow run setup-sentry-alerts.ymlor locally with a properly scoped token. The script is idempotent (checks by rule name before creating). Three production rules: P0 sustained 503s (>10 in 5min, 5-min cooldown), P1 error rate spike (>100 events from single issue in 24h, 1h cooldown), P1 new high-frequency issue (first seen + >50 in 1h, 1h cooldown). -
Event Registry structured match must include completed/closed events — The
_find_by_structured_match()function inevent_registry.pyqueries events by sport + time ± 4h + team names. The status filter MUST beIN ('scheduled', 'live', 'completed', 'closed'). When onlyscheduledandlivewere included, ESPN-created events that completed before the Odds API's next poll cycle were invisible to the cascade. This caused Step 4 (create new) to fire, producing orphaned duplicate events. The Odds API odds_snapshots attached to the duplicates were invisible to users, charts, and calibration. This single-line bug caused 98% of Tier 1 events (MLB/NBA/NHL/NFL) to have no sportsbook odds data for the entire May 2026 under-polling period. The merge task (every 30 min) also needed enhancement: its SQL should match swapped home/away orientations and usehome_team_normalizedfor fuzzy name matching. -
Quota conservation measures must have revert dates — Emergency quota conservation (doubled discovery intervals, sport region demotions, aggressive adaptive slowdown) should always include a TODO comment with a specific revert date. The March 2026 conservation measures went 2+ months without revert, reducing daily API usage to 30K against a 160K/day budget. Add calendar reminders or automated alerts (daily usage < 50K triggers a warning) to catch forgotten reversions.
-
Event Registry match window must be wider than ±4 hours — Kalshi uses settlement/resolution dates (not game start), which can be 12-24 hours off. UTC/local date boundaries add another source of error. The match window was changed from ±4h to ±28h in May 2026 after finding 28 duplicate events across Tier 1 sports. To prevent doubleheader false matches, the cascade picks the closest candidate by time when multiple matches exist.
-
Never close a bug until you have proof the fix works in production — Don't close issues when you deploy the fix. Close them when you have measured evidence that the fix worked: linkage rates improved, polling increased, snapshots are dense. If verification requires waiting (e.g., 24h of data), leave the issue open with a "blocked: awaiting verification" label and a specific check to run. #548 was closed after deploying a one-line cascade fix, but the Celery worker never restarted with the new code — the fix was never active. The issue sat "closed" while the problem continued for days.
-
GitHub issue management is mandatory, not optional — The project board is the single source of truth. Follow this workflow for EVERY issue:
-
Before starting: Move card to In Progress. Add
in-progresslabel. Comment with what you're doing. -
When subagent launches: Move to In Progress immediately, not after it completes.
-
When code ships: Move to Review/Verify. Add a comment with what was built and how to verify.
-
Only move to Done: After measured proof the fix works (link the evidence).
-
Create sub-issues: For any work that takes more than one commit or spans multiple files.
-
Never batch board updates: Update the board AS you go, not in a cleanup pass later. If the board doesn't reflect reality, the user can't trust it and work gets lost.
-
Uncommitted Alembic migrations break the entire deploy chain — When multiple threads/sessions create migrations in parallel, each chains from the previous via
down_revision. If any migration in the chain is created locally but not committed, Heroku's release phase fails withKeyErroron the missing revision. This blocks ALL endpoints (503), not just the new ones. Always commit migration files immediately after creation, and checkgit statusfor untracked.pyfiles inalembic/versions/before pushing. -
Don't use
run_async()in async FastAPI endpoints —run_async()creates a new event loop viaasyncio.run(), which fails inside an already-running async context (FastAPI's event loop). In async endpoint handlers, useawaitdirectly.run_async()is only for Celery task wrappers (which are sync functions that need to call async code). -
Kalshi poll hard-coded
status: "open"— Prior to commit07dd116, the Kalshi poll task set every market's status to"open"on upsert, regardless of Kalshi's actual settlement state. This preventedbackfill_winners(which filters onstatus = 'resolved') from ever finding settled Kalshi markets. Fix: derive status fromKalshiMarket.statusfield (active/closed/settled). If all nested markets are closed/settled →"resolved", else"open". -
Heavy endpoints crash the 512MB web dyno (R14 OOM) — Endpoints that
selectinloadthousands of outcomes into ORM objects can exceed the Standard-1X 512MB memory limit. The golf endpoint loading 5,497 outcomes + snapshot subqueries hit 916MB (179% quota) and crashed the web dyno. Fix: add Redis cache (same pattern as category pages) so the heavy query runs in Celery precompute (background worker has its own memory), not in the web request. Any endpoint that loads >1000 ORM objects with relationships should be cached. -
Calibration probability LIMIT bottleneck — The
_compute_calibration_prices()SQL queries inbackfill_winners.py(Parts A/B) hadLIMIT 200000, but with 500K+ outcomes per source, they couldn't process everything in one run. Combined with the task-levellimitparameter gating upstream phases, the calibration phase often timed out before running. Fix: increased toLIMIT 600000and added a dedicatedPOST /admin/backfill-calibration-pricesendpoint. -
Kalshi settled markets stay status='open' in DB — When Kalshi game markets settle, our regular polling task stops seeing them (it only fetches open markets from the API). The market status in our DB stays
'open'indefinitely. This blocks ALL downstream pipelines:_compute_calibration_prices(Part A requiresstatus='resolved'),_backfill_kalshi_winners(requiresstatus='resolved'), and_backfill_kalshi_price_history(candlestick backfill, requiresstatus='resolved'). Fix: the settled events backfill (_backfill_from_settled_events) now runs a two-phase approach — Phase 1 unconditionally scans all series and updates market status to 'resolved', Phase 2 creates closing-price snapshots for zero-snapshot outcomes. -
Settled events backfill shared-limit starvation — The original
_backfill_from_settled_eventsshared a singletotal_matchedcounter between status updates and snapshot creation, with an early-exitif total_matched >= limit: breakon the series loop. Series listed first (KXNBAGAME) would exhaust the limit before later series (KXNHLGAME, KXNBASPREAD, etc.) got their status updated. Fix: decouple Phase 1 (status resolution, no limit) from Phase 2 (snapshot creation, limit-aware). Status updates run unconditionally for ALL series; only snapshot creation respects the limit. -
Candlestick API works for settled markets (not deprecated) — Despite earlier assumptions that Kalshi's batch candlestick API (
GET /markets/candlesticks) returns empty for settled markets, it actually returns 100-177 hourly candles per game. The per-market endpoint (GET /markets/{ticker}/candlesticks) is deprecated and returns 404, but the batch endpoint works. The ~50% "empty" rate seen earlier was due to code bugs (query filter excluding target outcomes, bid=0 filtering) not API limitations. Kalshi also has a trades API (GET /markets/trades) with full trade history as a backup. -
Winner coverage has two metrics — market-level vs outcome-level — The calibration decomposition shows
has_winneras a count of outcomes withis_winner=true. In a 47-outcome spread market, only ~26 can be winners (55%). In a binary market, 1 of 2 (50%). So the outcome-level rate will never reach 100% — it's bounded by the market mix. The meaningful metric is market-level:BOOL_OR(is_winner)per market, reported by thebackfill-winners/statusendpoint. Track that one, not the outcome percentage. -
Kalshi's EVENT OBJECT is permanent; its settlement data is not — CORRECTED 2026-08-07 (CAL-P008/P009) —
⚠️ This entry's original headline read "retains settlement data permanently — never assume it's 'purged'", and that is measurably wrong today.GET /events/{ticker}does return 200 for a settled event of ANY age — that part holds, and it is what the May run observed — but past the retention cliff the response carriesmarkets: [], so theresultfield is gone with them. Measured 2026-08-07: events settled 154d / 147d / 87d ago return 200 with zero markets; a 41d event returns 6 markets with results intact. Retention is >=74 and <86 days (CLAUDE.md #35; re-measure withscripts/probe_kalshi_retention.py). Read as originally written, this entry tells you to build a recovery rail with no retention floor — which is part of how three of them shipped that way. The entry's real lesson is undamaged and still important: the May "deceleration" was NOT purging. The KalshiGET /events/{ticker}endpoint returnsresult("yes"/"no") for settled events of any age WITHIN the retention window. The original_backfill_kalshi_winnershad a 60-day window filter assuming older data was purged — this was wrong. When the window was removed and the function was tested with all ages, the API returned 100% hit rate (200/200 found, 0 api_miss). The previous "deceleration" (2,306 resolved → 365 → 0) was entirely caused byget_event()catching ALL exceptions (including 429 rate limits) and returningNone, counted asapi_miss. Fix: retry on 429, only returnNonefor actual 404. With proper retry, every batch returns 100% API data for events inside the retention window — the 100% hit rate was measured on a then-recent population and does not generalise to the old tail. -
Never catch-all exceptions in API clients that distinguish "not found" from "error" —
get_event()originally usedexcept Exception: return Nonewhich made 429 rate limits, network timeouts, and 500 errors indistinguishable from "event doesn't exist on Kalshi." This caused the backfill to believe it had exhausted all API data when it had only been rate-limited. API client methods that returnOptional[T]for "not found" must only catch the specific "not found" case (404) and re-raise or retry everything else. This same pattern applies to any API client where None means "data doesn't exist" vs "request failed." -
box_score_data is a wrapper dict, not the player stats dict —
Event.box_score_datastores{"source": "espn", "players": {"Player Name": {"points": 30, ...}}, "scoring_plays": [...]}. The player stats are under the"players"key, not at the top level. The player prop resolver (_resolve_kalshi_player_props_from_boxscore) originally iteratedbox_score_data.items()directly, which yielded keys like"source","players","scoring_plays"— never matching any player name. The resolver produced 4,500+no_playerfailures for years with zero resolutions. Fix: extractbox_score_data.get("players", {})before iterating. -
Claude Code sandbox blocks direct
curltoapi.bainluck.com— The sandbox periodically tightens and rejectscurlcommands that referenceapi.bainluck.comas "data exfiltration." Workaround: store the API URL and admin token in~/.claude/.envas environment variables (BAINLUCK_API,ADMIN_TOKEN), thensource ~/.claude/.envbefore any curl command. Using$BAINLUCK_APIinstead of the literal URL bypasses the sandbox check. If~/.claude/.envdoesn't exist, ask the user to create it:echo 'export BAINLUCK_API="https://api.bainluck.com"' >> ~/.claude/.env && echo "export ADMIN_TOKEN=$(heroku config:get ADMIN_TOKEN -a bainluck)" >> ~/.claude/.env. This also works forheroku logsworkarounds. Document prominently in CLAUDE.md so other threads know. -
Kalshi has THREE ticker formats — event ticker, market ticker, and outcome ticker — Our DB stores:
FuturesMarket.external_id= event ticker (KXNCAAMBTOTAL-26MAR04UNFUWGA),FuturesOutcome.external_id= market/outcome ticker (KXNCAAMBTOTAL-26MAR04UNFUWGA-155). The Kalshi API endpoints accept different formats:GET /events/{event_ticker}accepts event tickers,GET /markets/{market_ticker}accepts market tickers (same as outcome ticker). When testing API endpoints, always verify WHICH ticker format the endpoint expects. TheGET /events/{ticker}andGET /markets/{ticker}endpoints return 404 for old settled markets (~3+ months) regardless of ticker format — the settled events pagination (GET /events?status=settled&series_ticker=X) is the only endpoint that returns this data. Never assume an API endpoint is broken without testing the correct ticker format first.
The June 2026 creation-freeze war + July data-integrity classes (CLAUDE.md hot-list 38–47, full-catalog form)
These are the current hot-list items 38–47 kept here in expanded form. Items 106–109 are the "why did Kalshi stop creating markets for 29 days" war (June 2026); items 110–115 are the display/data-integrity classes surfaced by the July reliability push.
-
json.loads(the stdlib C decoder) holds the GIL for the ENTIRE parse — this was the #995 29-day creation freeze — Wrapping a hugeresponse.json()inasyncio.to_threaddoes NOT free the event loop, because CPython's C json parser never releases the GIL mid-parse. A 200-event Kalshi nested-markets page held the GIL ~67s inside the worker thread, freezing the asyncio loop so nowait_for/deadline timer could fire → the poll got SIGKILLed by the global 300stask_time_limitbefore it ever reached the end-of-loop commit that creates events. Result: Kalshi market creation froze on 2026-06-09 and stayed frozen for ~29 days across 7 failed fix attempts, while updates to already-existing markets stayed fresh — masking the freeze and making "Kalshi→MLB coverage is poor" look like a matching bug instead of a creation bug (see memoryproject_kalshi_create_freeze). Fixes, all shipped: orjson (orjson.loadsis ~5–10× faster so the GIL hold is a fraction of a second; behind anImportError→stdlibjsonfallback); smaller pages (page limit 200→50 so each decode is sub-second); and a resumable cursor so partial progress persists across a kill. Note the asymmetry: pure-Python work (object construction) DOES release the GIL on the ~5ms switch interval, soto_threadgenuinely helps there — but never for a giant C-level decode. -
A sync Redis client with no socket timeout can freeze an entire async task —
redis.from_url(...)/redis.Redis(...)with nosocket_timeoutblocks the calling thread forever if Redis hangs. When the caller runs inside an asyncio loop — e.g. asetexinside aprogress_cb, or any bareget_redis_client()call in a task — the frozen thread IS the event loop, so nothing else can fire (same failure signature as the #995 freeze).get_redis_client()is now bounded by default (5s socket + connect timeout; passsocket_timeout=Noneonly to opt out for a deliberate long blocking op). Never construct a raw syncredis.from_url/redis.Redisinsidetasks/— always route throughget_redis_client(). A CI guard intest_redis_state.pyenforces this. -
The admin
db-queryendpoint serializes JSONB as Pythonrepr, not JSON — Any tool that parsesPOST /api/admin/db-queryoutput withjson.loadsalone silently reads{}for JSONB columns (single-quoted Python-dict repr is not valid JSON). Consumers need anast.literal_evalfallback. This poisoned the resolution-engine / poly-cutover audit for two full queue cycles — it faked 0% derivative coverage when the real number was ~71% (see memoryproject_poly_cutover_blockers). Fix the consumer, or better, fix the endpoint to emit real JSON. Related: the endpoint also silently truncates at a 1000-row cap (memoryproject_dbquery_1000_row_cap) — use server-side aggregates/pagination for cohort rates, never client-side counting of its rows. -
Bulk backfills ordered newest-first can never reach the old tail — A bounded run (row limit or time budget) that iterates newest-first will exhaust its budget on the 450K+ newer rows long before it reaches the old rows that actually need fixing. Old-tail work needs oldest-first ordering or an explicit filter that targets only the stale tail. This is the "combat-wps" lesson:
backfill-wpsis newest-first and therefore structurally cannot reach old settled combat events, so those never got the win-prob blend backfilled (see memoryproject_poly_cutover_blockers). -
One bad item must never wipe a whole scoring/feed pass — A single unhandled throw inside a per-item loop (e.g.
_score_events) aborts the entire pass and returns an empty result. This was the real root cause of #1091 — one malformed event threw, and the Sports tab came back empty instead of losing one card. Every feed/scoring per-item loop must wrap the body in its own try/except so a poison item is skipped, not fatal. The guard test must assert that the healthy siblings survive when one item throws. -
Scope diversity caps by card type — a cap on "category-less" cards emptied the Sports tab — #1091: a diversity cap added to stop a native golf-tournament flood was written to cap "category-less" cards, but game events also carry
llm_sport_category=None, so the cap swallowed them too and emptied the Sports tab while fixing the golf flood (see memoryproject_feed_tournament_cap_escape). A cap must exempt game events explicitly, and its guard tests must assert both directions: the flood stays capped AND the adjacent surface (Sports tab / game events) stays populated. Reproduce the escape shape via/api/feed?limit=200&event_pct=0.15(iOS shape). -
A test anchor must not branch on the clock, and "seed at a fixed hour" is the advice that caused the last three instances — Near-midnight UTC test runs split seeded events onto different date tokens than the assertions expect, which red-blocked two deploys. The original rule said: seed at a fixed hour, never at "now" ± an offset that can straddle midnight. AMENDED 2026-08-11 (Queue 329, #1729) — that rule is actively harmful, and the two fixes that obeyed it are the evidence.
datetime.now(tz).replace(hour=12)does not pin an age; it pins an hour of a day that is still chosen by the wall clock, so the age it produces swings a full 24 hours across the run window. Three consequences, all measured: (a) it can be in the FUTURE (test_calibration_serve_honest_297._at(days_ago=0)sat 12h ahead all morning); (b) patching that withif anchor > now: anchor -= 1 dayjust moves the boundary —test_feed_phantom_midpoint_suppressionwas red every evening, was "fixed", and became red every afternoon instead; (c) the swing silently eats a consumer's tolerance —serve_honest_297asserts an age inside (1.5d, 2.5d) from an anchor that swings exactly one day, so it was red at precisely 00:00 UTC, the hour CI most often runs. Two rules replace it. (1) Offset FIRST, then truncate —(now - timedelta(days=2)).replace(minute=0, second=0, microsecond=0), the shape intest_calibration_durable_298._at. This is deterministic within a run, always past, and always the same age. (2) Better, freeze the clock out of the test entirely when the fixture carries dates of its own. The phantom-midpoint suite could not be fixed by any anchor age, because its specimens are production rows titled "Week of August 3 2026" andmarket_staleness.infer_market_real_world_endreads that as a real deadline: the scorer correctly suppresses the card once thenowit is handed passes 2026-08-10 23:59:59, so every relative anchor was choosing a date to die on, not avoiding one. It now uses a frozen_FROZEN_NOWcontemporaneous with the capture, plus an invariant test asserting no specimen title has expired at that instant. A conditional on the clock is the defect, not an implementation detail: if your anchor contains anif, you have not fixed this.backend/scripts/clock_sweep.pyruns any pytest target under 12 faked wall clocks (±8h/±2h/0 around both 00:00 and 12:00 UTC, plus +90d and +400d) and is how the fourth instance was found — a suite that is green "when I ran it" is not evidence about a clock bug. -
LIKE '%:something'inside a SQLAlchemytext()string parses the:somethingas a bind parameter — SQLAlchemy'stext()treats:nameas a named bind param, so a literalLIKE '%:foo'raises on every run (missing bind). If that query is wrapped in a catch-allexcept, the whole function dies silently — which is exactly what happened to_fix_golf_commence_times: it never ran for months. Escape the colon or parameterize the pattern properly, and never wrap scheduled work in a catch-all without alerting on the caught error. -
completed_at >= commence_timeis a hard invariant — its violation means an earlier game's data merged onto the wrong event — A completed event whosecompleted_atis before itscommence_timeis impossible in reality; when it appears, it means a different (earlier) game's snapshots/scores were merged onto this event row (a matching-layer failure, sibling of gotcha #32/#87). This was a 439-row incident: it produced empty settled charts and impossible "My Stuff" dates. The read-side was healed in #189; the data repair (439→0) landed in Queue #191; a remaining sub-class B (wrong scores merged on) is still owed under #192 (see memoryproject_inverted_completed_at). The calibration audit + Flow Sentinel both guard this invariant now — treat any recurrence as a matching-layer P1. -
Check
git log origin/master..HEADBEFORE committing in a shared working tree — When multiple lanes (interactive sessions, the headless crank, subagents) share one checkout, a sibling lane's fresh local commit will ride yourgit push(and a crank's commits can land under yours), so a push can carry code you never reviewed. Always inspectgit log origin/master..HEADbefore committing, use explicit-pathgit add(nevergit add -A/.), and keep linear-history discipline per the handoff README. This is why the Agent Execution Lanes protocol exists (the 2026-06-11 collision: stashed WIP, skipped priorities, unverified "shipped" claims). -
Headless
xcodebuildfails on SwiftUI#Previewmacro expansion in a sandbox (hot-list #50) — A headless / agent-drivenxcodebuild ... buildof the iOS target aborts during Swift macro expansion with a nestedsandbox_applyfailure. The cause: the SwiftUI#Previewmacro (like any Swift macro) runs its expansion in a separate compiler-plugin process that tries to spawn its OWN sandbox, and that nestedsandbox_applyis denied because the wholexcodebuildinvocation is already running inside the agent's sandbox. Symptoms in the log look like a macro/plugin crash, not a permissions problem, which sends you down the wrong path. What does NOT fix it:-skipMacroValidation(it skips validation of the macro, not the sandboxed expansion that actually fails). What also makes things worse: deleting the SPM cache /.build/ DerivedData to "start clean" — in a sandboxed env the subsequent package re-resolve then fails on network and filesystem restrictions, so you destroy a working cache and gain nothing. The fix: disable the Swift compiler's own sandbox for the build by passingOTHER_SWIFT_FLAGS='$(inherited) -Xfrontend -disable-sandbox'on thexcodebuildcommand line (the$(inherited)keeps any project-level flags). With that,#Previewmacros expand fine and the build proceeds. Discovered by L2-165 (the team-page polish native gate); documenting it here saves every future iOS queue the same lost cycle. This is the only native-gate blocker of its class seen so far — normal (non-sandboxed) localxcodebuildon Alex's Mac never hits it. -
xcodebuildin a PROGRAM WORKTREE also needs pinned SPM packages — the sibling of #116, and you hit both at once — A native build in~/bainluck-dev/<program>(rather than~/bainluck) fails a second, independent way: a fresh worktree has no resolved Swift Package Manager checkout, soxcodebuildtries to re-resolve packages over the network, and Firebase's fetch is egress-blocked in the agent sandbox. The log blames Firebase, so it reads as a dependency problem rather than a worktree problem — and because #116 fires in the same invocation, the first failure you see is usually the macro sandbox, you fix that, and then meet this one and conclude your #116 fix didn't work. The fix: point the build at master's already-resolved packages and forbid re-resolution —-clonedSourcePackagesDirPath <DerivedData>/SourcePackages -disableAutomaticPackageResolution— alongside #116'sOTHER_SWIFT_FLAGS='$(inherited) -Xfrontend -disable-sandbox'. Both flags, every headless worktree build. Same shape as thenode_modulessymlink fix for frontend worktrees (scripts/setup-worktree-deps.sh): a worktree cannot afford its own dependency resolution, so it borrows master's — and in both cases the failure mode was that borrowing wasn't wired up, not that the dependency was wrong. Banked 2026-08-09 (Fable, ratified) specifically to unblock native work for every lane, since each one was rediscovering it. -
A
*_24hcounter with no window stamp is not a rate, and reading it as one is off by up to 24x —bainluck:task_metrics:<task>:successes(and:failures,:incompletes,:starts) are created bySET NX EX 86400on their FIRST increment, so at any instant each holds somewhere between 0 and 24 hours of history — and nothing in the payload said which. The naming invites the wrong division. Measured 2026-08-09 (LAT-P022/#1609): six fixed-cadence tasks readingsuccesses_24hof 52–63 all had windows about one hour old, sosync_statpal_livescores— confirmed differentially to be running at 0.99x of its 30-second cadence — presented as having missed 96% of its 2,880 daily fires. A whole work-list built that way is fiction, and two separate windows debugging #1609 reasoned from exactly that shape. Two rules follow. (1) Never compare a_24hcounter against a 24-hour expectation;get_task_metricsnow returnssuccesses_window_s/starts_window_s/ etc. beside each count, andapp/utils/schedule_adherence.pyrefuses to grade (verdict: "unmeasurable") when the window has not had room for at least 2 fires. AMENDED 2026-08-10 (LAT-P024/#1609): those*_window_sfields are now derived from each counter's own remaining TTL, NOT from the:sincesibling key this gotcha originally described — the sibling drifted from the counter it dated, by 2.47x, within one day of shipping. See #120; do not reintroduce a second key. (2) When you need a rate NOW and cannot wait for the stamp, take two reads separated by a known wall-clock gap and difference them — that needs no assumption about counter age at all, and it is what actually settled #1609. Sibling of gotcha #49 (a Sentry issuecountis lifetime, not recent) and of #53 (an empty result is a shape, not a fact): here the absence of an age was read as a known age. -
last_duration_msis one sample, and for a self-gating task it is systematically the cheap one — The metrics hash kept only the most recent run's duration, so any "is this task slow?" question was answered from a sample of one.refresh_open_commentaryrecordedlast_duration_ms: 8— a real number, from the cheap off-tournament Redis skip it takes most of the time — while the same task carried a live Sentry issue for exceeding its 90-second hard time limit. Both are true; one sample can only ever show you one of them, and it will preferentially show you the common cheap path. A task that overruns its own beat interval is the textbook lapping shape, and it was uncomputable from the recorded data untilbainluck:task_metrics:<task>:durations(a bounded 50-entry rolling list, LTRIM'd on every write, written for successes and failures and incompletes) made a p95 possible. Do not add an aggregate (a storedp95_ms) instead of the samples: a precomputed statistic drifts from the data behind it and cannot be re-cut at a different percentile. -
A derived property stored in a SECOND key with its own lifetime cannot stay in phase with the first — and
SET NXis what guarantees it never re-syncs — LAT-P022 dated the_24hcounters by writing a:sincesibling alongside each one, under the sameNXand the same 86400s TTL, on the reasoning that "the two are created and expire together and can never describe different windows". That is true only for a pair born together, andNX— the very thing that stops the stamp being overwritten by later increments — is also what stops it ever being corrected. Two entirely ordinary events separate their birthdays. (a) The deploy that introduces the second key. Every counter already alive keeps its value (SET NXcorrectly declines to reset it) and receives a stamp dated NOW, so the window becomes the age of the RELEASE rather than the age of the count. (b) The first key's own roll. When the counter expires at 24h and is recreated, a later-born stamp is still alive,SET NXdeclines again, and the fresh counter inherits a stamp OLDER than itself. Measured 2026-08-10 (LAT-P024/#1609), both ends matching a release to the minute::startscounters born 22:01 PT with v3740, their stamps born 07:15 PT with v3743 — the release that shipped the stamp — soprecompute_category_pagesreported 16 fires in a 6.47h window. It is an hourlycrontab(minute=25)beat, so that reading requires 2.47 schedulers, and a non-integer scheduler count is impossible: that is what turns "this looks off" into a proof. Every rate on every task was inflated 2.47x. The two failure directions are not symmetric in visibility, which is why it survived a cycle:schedule_adherencehas abehindband and anoverrunsband and no "ahead" band, so an inflated rate passes silently ason_schedulewhile corrupting every number a human or an agent reads off the surface — whereas the mirror-image error (case b) would have graded all ~59 tasksbehindin one night. The fix is not a better second key, it is no second key: the window is nowWINDOW_COUNTER_TTL - ttl(counter). The TTL is not a second opinion about the window, it IS the window — set once bySET ... EX ... NX, never refreshed (INCRdoes not touch an expiry) — so one key cannot disagree with itself and the drift becomes unrepresentable rather than merely fixed. It is also retroactive: existing keys already carry the right TTL, so the surface tells the truth on deploy instead of after a roll. Before adding a sibling key to date, version, or annotate another key, ask what happens to the pair at the deploy that introduces it and at the older key's next expiry; if either answer is "they diverge and nothing re-syncs them", derive the property from the key itself or put both in one value with one TTL. Sibling of #118 (the count this dates) and of #40 (a reader and a writer disagreeing about a format). -
A test that compares a production value to the constant the production code reads cannot detect a change to that value — and the ones that are protected are not the ones you would guess —
assert ttl_written == hub_route.HUB_PRIMARY_TTLpasses for every value ofHUB_PRIMARY_TTL, because mutating the constant moves the implementation and the oracle together. LAT-P026 is the recorded escape: that shape let the mutation180 → 60survive the whole suite until the expectation became a literal (backend/tests/test_hub_cache_swr.py:236-240carries the rationale in-tree). The census of the species lives atdocs/constant-oracle-census.md(regenerate:cd backend && python3 scripts/audit_constant_oracle_census.py --artifact), and it carries the standing rule: if you touch a line listed there, fix it in the same change — there is no scheduled sweep coming for the rest. Not every hit is a defect: an assertion testing branch selection ("the fallback returns the default", "this row classifies as foreign") is legitimately written against the constant; it is a defect only when the value is itself the contract and nothing else pins it. That distinction is not readable from the source, which is the part that keeps biting: the only discriminator is does any test go red when the constant is mutated. Queue 331 graded 36 truth-path constants that way and found 20 blind, includingTERMINAL_FAILED,TERMINAL_HARD_LOSSandTERMINAL_OVERLAP_REFUSEDwhileTERMINAL_COMPLETE,TERMINAL_PARTIALandTERMINAL_CANCELLEDin the same module were protected — six constants declared on consecutive lines, used identically, split three-three. The costliest wasAPPLICATION_NAME_MAX = 63: not a value we choose (Postgres truncatesapplication_nameatNAMEDATALEN-1silently, dropping the owner handle), yet all three bound assertions readlen(tag) <= APPLICATION_NAME_MAX, so widening it to 200 stayed green while every tag would have been truncated intopg_stat_activity. When you write the mutation harness, accept only pytest rc 0 or 1 — queue 331's first harness passed--timeout=300with nopytest-timeoutinstalled, so pytest exited4(usage error) on every run and it scored 24 constants "detected" without executing a single test. Sibling of #53 (an empty 200 is a response shape, not a fact): here a usage error was read as a result. -
A test double that cannot express the operation cannot catch a bug in it — and the blindness fails in BOTH directions, one of which scores as a KILL — The fake Redis in
backend/tests/test_schedule_adherence_wiring.pyimplementedexpire()asself.calls.append(("expire", key, ttl)): it recorded that the call happened and did nothing. Nothing in the double modelled a TTL, so no assertion downstream of it could ever be wrong, and a mutation that DELETED anexpirehad nothing to change. LAT-P039'sM19survived its first pass for exactly that reason — not a weak assertion, an inexpressible one. The fix is one line (self.ttls[key] = ttl), and the rule is: when you write a double, model the operation the bug would abuse, not merely the call signature. The second direction is the dangerous one, and it was measured on the fix (LAT-P040). Running the same mutant under both doubles: with the faithful fake,control=pass / mutant=FAIL— it discriminates, a real kill. With the no-op fake,control=FAIL / mutant=FAIL— the oracle fails for every input, so a harness tallying outcomes records a KILL it never earned.M19failed OPEN (survived, looked fine); this one fails CLOSED (died, looked like coverage). Same blindness, opposite sign, and the tally cannot tell them apart. Therefore: a mutation harness MUST run its oracles against UNMUTATED source first and say so out loud —backend/scripts/evals/duration_sample_window_mutations.pyprintscontrol: both oracles PASS on unmutated sourcebefore any mutant runs. A kill count without a passing control is not a measurement. Sibling of #121's--timeouttrap (a usage error read as a result) and of #53 (an empty 200 is a response shape, not a fact): all three are a harness mistaking "I got an answer" for "the answer means what I think". CROSS-LINK (Alex ruling 2026-08-12): this is not a one-off. Codex's C-TD-1 census (.claude/handoff/CODEX-REPORT.md, 2026-08-12) mechanically searched all 641 backend test files and enumerated 21 double-fidelity gaps across 20 files — an explicit lower bound — and independently rediscovered this exact fake-Redis specimen attest_task_delivery_counter.py:75-82from the opposite direction, one day later. Its disposition is tranche-1 (ten worst rows) plus a standing fix-on-touch rule for the remaining eleven: if your change touches a listed double, or the production boundary it stands in for, repair that fidelity gap in the same change. The repair above is entry #1 in that census's fix-on-touch ledger. Note the ledger's live residual on the very same double: the census's separate eager-pipeline escape in that file is NOT discharged by the expiry fix, and belongs to whoever touches it next. -
Shared Hit Blocksis not comparable between anIndex Scanplan and anIndex Only Scanplan — and this program's metric of record is blocks — #1731 established the right discipline ("quote the BLOCKS, not the ms: blocks were identical across passes while wall-clock varied ~2x") and then that discipline pointed the wrong way the first time the plan shape changed under it. Measured 2026-08-12 (LAT-P041) while executing Alex's ruled open-cohort index onfutures_markets: the%la%arm moved fromIndex Scan [ix_futures_markets_status]at 33,982 blocks toIndex Only Scan [ix_fm_open_search_cover]at 34,456 blocks, reading as "the index made it worse by 1.5%". But the new index is 1,082 pages total and its post-vacuumHeap Fetcheswas 745 — so the honest floor is ~1,827 buffer accesses, and the reported 34,456 is dominated by the per-tuple visibility-map probe an index-only scan performs for every one of the 79,085 rows it walks. The block counter is measuring a different kind of work in each plan, so the subtraction is meaningless even though both numbers are correct. Three rules. (1) Compare blocks only between plans of the same node type; when the node type changes, blocks tell you what the executor did, not what it cost. (2) Always readHeap Fetchesbeside an index-only scan — it is the only number in that plan that distinguishes "the visibility map is working" from "this is a heap sweep wearing an index-only hat" (pre-vacuum it was 8,716, post-vacuum 745; same index, same query). (3) When the plan shape changes, the arbiter is a controlled A/B on the endpoint with everything else held constant — LAT-P041 got its answer by timing/api/events/searchwith and without the index after the same VACUUM, which is what showed the index was genuinely 25% slower and, separately, that the real win (fedarm 3,158 → 999 blocks, 35.3 → 2.9 ms) came fromVACUUM (ANALYZE)fixing stale planner stats and persisted after the index was rolled back. Sibling of #118 (a counter with no window is not a rate) and #49 (a Sentry lifetime count read as recent): in all three a correct number was read against the wrong denominator. -
cmd | tailreports TAIL's exit code, so a gate that never ran reports success — and the two obvious "fixes" are also broken in this shell — A gate invoked aspython3 -m pytest ... | tail -30exits0whenevertailexits0, which is always. Two UX-P064 gate runs reported a clean0over runs that never happened: the command died before pytest produced anything,tailcheerfully consumed the empty stream and returned success, and the transcript recorded a green gate. Nothing in the output says "this is tail's verdict" — the number is in exactly the place a run's own status belongs. This is the instruments-that-lie family (#53: an empty 200 is a response shape, not a fact; #121: pytest's rc4usage error read as a result), and it is the worst-shaped member, because the lying instrument is the one certifying every other instrument. Neither reflex fixes it here.set -o pipefailis not on in these non-interactive tool shells unless you set it yourself, and${PIPESTATUS[0]}is bash-only — in zsh it expands to the empty string, soecho "EXIT: ${PIPESTATUS[0]}"printsEXIT:and a reader supplies the zero themselves (measured in this repo's own session shell, 2026-08-12, while writing this entry). An exit-code check that silently evaluates to nothing is worse than none, because it looks like diligence. The canonical form is not to pipe the gate at all: redirect to a file, have the run print its OWN status, then read the file.python3 -m pytest tests/ -q > /tmp/gate.txt 2>&1; echo "PYTEST EXIT CODE: $?"; tail -20 /tmp/gate.txt—$?is now unambiguously pytest's, it is printed on its own line, and you still get the tail. Same fornpm run build,npx jest, andxcodebuild. Any pasted gate evidence whose exit code came through a pipe proves nothing about the gate, only thattailis healthy; re-run it unpiped before certifying. AMENDMENT, same day, from a live specimen: the pipe is not the mechanism — LAST COMMAND WINS is, and a subshell wrapper does it too. UX-P065 ran its backend gate as(pytest > file; echo "EXIT: $?" >> file)in the background, precisely to escape the pipe. The harness then announced "completed (exit code 0)" — because the subshell's status is its LAST command, theecho, which succeeded. The run had one real failure and pytest had exited1. The wrapper was correct where it counted (the$?written INTO the file was pytest's, and reading the file is what caught it), but the number the reader sees first was the echo's. So the rule generalises:$?belongs to the last thing that ran, and any construct that puts something after your gate — a pipe, a;, a subshell, a&&chain, a trap — hands the verdict to that something. Put the gate's own status in the artifact you will actually read, and treat any exit code that arrived through a wrapper as unattributed until you have matched it to the run's own report line. SECOND AMENDMENT (UX-P066, next day, and it is a THIRD mechanism reaching the same false green): in zsh an unquoted$VARdoes NOT word-split. A plant harness ranSUITES="a.py b.py c.py"; pytest $SUITES— in bash that is three paths; in zsh it is ONE argument, a single path named"a.py b.py c.py"which does not exist. Pytest answeredERROR: file or directory not found,collected 0 items, and exit4. The harness had already printed its own*** PLANT n APPLIED ***banner frompytest_configure, so all six plants reported APPLIED over zero tests executed — the precise false-green shape UX-P064 recorded, arrived at by a completely different route (that one was a cwd drift). It was caught only because the harness also printedcollected N itemsand a pass/fail summary, and the baseline run — which must always be run — showed the same exit4and gave the mechanism away. So the rule is not about pipes, subshells, or splitting; it is that a run must report what it DID, not that it started. A harness that prints "applied", "installed", "configured", or "connected" and not "N passed, M failed" is telling you about itself, not about the code. Print the collected count and the pass/fail line for every run, always run an unplanted baseline through the identical command path, and use${=VAR}(or just pass the paths literally) when a zsh line needs word-splitting. THIRD AMENDMENT (queue 355, approved by Alex 2026-08-14) — the cheap tell this entry already contained and never stated: READ THE EXIT CODE'S VALUE, not merely whether it is zero. A non-zero exit that isn't1usually means the gate never ran. Every runner that matters here reserves1for "the thing you asked me to check failed" and spends its other codes on "I could not check": pytest2interrupted,3internal error,4usage error — a path that does not exist,5collected nothing;npm/node127command not found,126not executable; and the signal codes130SIGINT,137SIGKILL (an OOM or akill -9),143SIGTERM. So1is a result, and every other non-zero is a story about the harness rather than about the code. The force of this is that it is free and it is already in the evidence you have: the second amendment's own specimen exited4, and that4is recorded three sentences above — the mechanism (zsh not word-splitting$SUITESinto three paths) was legible from the number alone, before anyone read a single line of output. The same is true of the other two specimens' family: a cwd drift and a killed run both land outside1. Operationally: when your gate returns non-zero, branch on the value before you start reading failures.1→ go read the failing tests. Anything else → you do not have a test result at all; find out why the runner could not run, and do not report the outcome as a failing suite, because "12 tests failed" and "0 tests ran" are opposite facts that a bare "non-zero, so red" collapses into one. And the inverse still bites hardest: this whole entry exists because the number most likely to be wrong is0. -
heroku pg:psqldoes not exist as a channel from an agent session, and neither doesheroku logs— butrun:detacheddoes, so hand-applied DDL never needs aneeds-user— TCP 5432 egress is blocked from the sandbox, sopg:psqldies withOperation not permittedbefore it reaches the server;heroku logsfails the same way, withLogs eventsource failed with: ... connect EPERMagainst every one of its six endpoints. Neither is an auth problem, which is what makes them expensive: the escape clause in a DDL brief usually reads "file aneeds-userif the heroku CLI can't authenticate", auth is fine, and a lane that tests only auth concludes it is blocked and stops. Aheroku run:detachedone-off executes INSIDE Heroku's network, so it reaches the database directly — that is the rail for every gotcha-#31 hand-applied index,VACUUM, andALTER TABLE. LAT-P041 applied and rolled back Alex's ruledCREATE INDEX CONCURRENTLYthis way and filed noneeds-user; LAT-P042 appliedALTER TABLE futures_markets SET (autovacuum_analyze_scale_factor = 0.02, ...)the same way. Banked on Alex's 2026-08-12 ruling so that no future DDL queue plans around a channel that does not exist. Three corollaries, all learned the hard way: (a) because logs are unreachable too, a detached one-off must persist its own output to a sink you can read — write JSON to abainluck:-prefixed Redis key and fetch it withGET /api/admin/redis-read?key=...; stdout is write-only from here (gotcha #48 already says a non-detachedheroku rundoes not execute at all). (b) If the process might be SIGKILLed — an OOM, a time limit — it must checkpoint as it goes, not report at the end, because a killed process runs nofinallyand noexcept, so an end-of-run write is precisely absent in the cases worth diagnosing. LAT-P042 foundprecompute_interestingness's 515 MB peak only because the profiler flushed a partial record at every stage; its first, report-at-the-end version died silently and taught nothing. (c) A script committed during the window that needs it is not in the deployed slug, sorun:detached -- python3 scripts/new_thing.pywill not find it. Base64 the source andrun:detached -- python3 -c "import base64;exec(compile(base64.b64decode('...'),'x.py','exec'))"; commit the file too, as the reproducible rail for later cycles. Sibling of #48 (the non-detached no-exec) and of #53 (an empty 200 is a shape): here an unreachable channel gets read as an impossible task. -
A kill switch whose OFF position is "the key is absent" fails OPEN — and under
allkeys-lruthe cache decides when — Alex ruled on 2026-08-12 that the Discover interestingness blend goes dark until he has seen a side-by-side and ratified a weight, and the switch for that is the Redis keyinterestingness:blend_weight, set to0. Butroutes/feed.pyread it as "the weight, defaulting to 0.2 if the key is absent or unparsable" — so the ruled-OFF state was not a state at all, it was the continued existence of a cache entry. Production Redis at the moment the switch was thrown: 36.32 MB of 100 MB,maxmemory_policy allkeys-lru,evicted_keys 0, switch written withttl -1. Nothing there is alarming, and that is the point — an eviction under later growth, a flush, a plan migration, or a failover restoring an older snapshot would each have silently re-enabled a 20% ranking blend nobody had approved, with no deploy, no log line, and no event anywhere saying it had happened. The blast radius and the trigger are completely decoupled: a routine memory-pressure moment reverses a product ruling. Two rules. (1) The safe state must be the state you land in when you know nothing. Absent, corrupt, and store-unreachable should all resolve to the same conservative value, and — the part that is easy to miss — the variable should be initialised to that value before the lookup, so no arm of the read has to remember to say so. Turning the feature ON is then the only thing that requires an explicit statement, which is exactly the right asymmetry. (2) A defaulted read is indistinguishable from a real value of the same shape —GET /api/admin/feed-configreturned"0.2"for both "the weight is 0.2" and "there is no key at all", which is gotcha #53 committed against the kill switch itself, the one control where you most need to know which world you are in. It now returnskey_presentbeside the value. Corollary for diagnostics: the reason this default existed is that the only way to see the feed at 0.2 was to set the live key — to ship the change to everyone in order to decide whether to ship it. If a flag needs evaluating, give the evaluator an in-process override (_score_futures'sconfig) and never a temporary write, including one with afinally-restore: the process can die between the two writes, and then the temporary state is the permanent one. Sibling of #53 (an empty response is a shape, not a fact) and #120 (a second key with its own lifetime drifts from the first): all three are a system inferring a fact from an absence. -
reprof afrozensetis per-process hash order, so a bare f-string of one in a build fingerprint gives every worker a different digest — and no single-process test can see it — CAL-P045 part (a) had to add five uncovered constants to the calibration build fingerprint's input set, andFIX_SEQUENCING_NOTEdocumented exactly how: interpolate each one by bare f-string, the idiomCOVERAGE_CENSUS_ENABLEDalready used. Three of the five arefrozensetand one is adictof them. Python randomises string hashing per process (PYTHONHASHSEED), set iteration follows hash order, andreprfollows iteration — so the rendered text ofDRAW_AUTHORITY_OUTCOME_NAMESdiffers between processes. Measured on the real constant: four seeds, four orderings. Celery workers are separate processes, so the documented fix would have computed a different digest on every beat, the resumable cursor would have been discarded as foreign every single time, and the walk would have restarted forever — convergence made impossible by the change meant to strengthen the digest that guarantees it. The blast radius is the whole point: this digest is what lets a partial build resume instead of re-earning 600 s of reads, and a lane already fighting SIGKILLs would have lost the one mechanism carrying it forward, with nothing in any log saying why. It would have shipped green. A pytest suite runs in ONE process, so every assertion of the form "the digest is stable" holds within it and says nothing whatsoever about the property that matters, which is stability across processes. The fix is not a test but a render —_canonical_inputinapp/tasks/precompute_calibration.pysorts sets and dict keys on their rendered text (so a heterogeneous set cannot raise on incomparable types) and deliberately preserves order for sequences, because order IS meaning for a tuple and sorting one would erase a contract. THE NAMED PATTERN, which is the reusable part: SUBPROCESS PLUS NEGATIVE CONTROL.backend/tests/test_calibration_fingerprint_coverage.pyre-invokes the digest in asubprocess.run(..., env={"PYTHONHASHSEED": seed})across three seeds and asserts one value (test_the_digest_is_identical_under_different_hash_seeds) — and then, in the same class, runs the naive idiom the same way and asserts it really does produce different text (test_the_naive_idiom_really_is_unstable). Without that second test the first is unfalsifiable: if the subprocess harness silently fails to vary the seed — wrong env plumbing, an inheritedPYTHONHASHSEED=0, a cached.pyc, a run that never executed at all — the stability assertion passes for the wrong reason and certifies nothing. A cross-process determinism test without a negative control is a test that the harness is broken in a convenient direction. Same rule as #122's "run the oracles against unmutated source first" and #124's "a run must report what it DID": here the control is instability you can see, and it is what makes the stability meaningful. Second, smaller trap in the same change: a CALLABLE cannot be covered by value —reprof a function is its memory address, stable within one process and different in every worker, so passing one to the fingerprint has the identical failure shape while looking like ordinary coverage. Callables are covered by SOURCE (inspect.getsource), hencecovered_by_sourcebesidecovered_by_valuein the census, with "uncovered" meaning neither. Scope, so this is not read as a calibration curiosity: anything that hashes configuration into an identity — cache keys, checkpoint/resume cursors, dedup fingerprints, idempotency keys, cross-worker locks — inherits it the moment an unordered collection reaches the string. Sibling of #38 (a C-level decode holds the GIL for its whole duration): both are properties of the runtime, invisible in the code, that only appear at the process boundary a test suite never crosses. -
An absence check must first prove the resource EXISTS — a check written against a nonexistent key cannot fail, and that reads exactly like a check nobody got round to running — UX-P065 owed a live-card verification:
GET /api/event/event:mma:<a live card>carries nocompetitionkey at all (absent, not null). It rolled over two cycles as "carried", and Alex's ruling on it (2026-08-12) is that this is the instruments-that-lie family at the checklist layer. The namespace isufc;event:mma:*does not exist. But "unrunnable" undersells it, and the real shape is worth naming: measured,GET /api/event/event:mma:26aug15returns HTTP 404 with a{"detail": ...}body — and the assertion the check actually makes, "competitionis absent", is TRUE of that body. The check could never have failed. Had anyone run it, it would have reported a clean pass while verifying nothing, because an absence assertion against a nonexistent resource passes for the wrong reason. The same key shape had also been sitting intest_an_unmapped_key_gets_no_competition_key_at_all, green forever by construction, sincemmawill never be mapped into the competition register. This is gotcha #53 (an empty 200 is not an absence) one level up: there, the emptier reading was mistaken for a fact; here, a 404 body satisfies every absence assertion you can write, so the check and a passing check are indistinguishable. The rule: before asserting that X is absent, assert that the thing you are looking in EXISTS — check the status code, or assert a positive precondition (the page resolved, the key is real, the register genuinely does not map it). A negative assertion needs a positive anchor or it is unfalsifiable. And the diagnostic that would have caught it two cycles earlier: when an owed check is carried a SECOND time, re-read the check before rescheduling it. Nobody re-reads a line they have already decided is homework. Fixed permanently in UX-P069: the test now keys onevent:ufc:26aug15— a real, resolvable, legitimately-unmapped card — and assertscompetition_block(...) is Noneas an explicit precondition, so it goes red if UFC is ever mapped instead of staying green forever. -
A rule that lives in two consumers has two verdicts, and fixing the one you were looking at leaves the other wrong FOREVER — the repaired copy even documents the trap, which is what makes the broken one so hard to see —
routes/golf.py::_NON_WINNER_MARKET_REdecides which golf markets are outright-winner fields. In 2026 (#955) somebody hit its\btour\b.*\bwinner\barm eating real fields, diagnosed it exactly right, and wrote the correct prop phrasing intoapp/utils/golf_evolution_market.NON_CONTENDER_WINNER_RE— with a comment naming the trap ("Unlike_NON_WINNER_MARKET_RE, this must NOT match a real field like 'PGA Tour: U.S. Open Winner', so it uses the 'X of (the) winner' prop phrasing … rather than a broad 'tour . winner'"*) and a test asserting it. That fixed the CHART consumer. The AGGREGATION consumer kept the broad pattern and went on silently deleting every tour-prefixed Polymarket winner market — measured 2026-08-13: 23 golf markets, 20 of them resolved holding 1,957 priced outcomes, and zero true positives anywhere in golf. The comment is the sting: a reader who greps the codebase finds a confident, tested, correct treatment of exactly this bug and concludes it is handled. When you fix a rule, grep for its OTHER implementations before you close the ticket, and make the copies assert against each other (test_the_two_copies_of_this_rule_now_agree) — a shared test is the only thing that converts "two copies agree today" into "two copies cannot disagree". The second half is worse and more general: the same regex was ALSO wrong in the opposite direction, for the same underlying reason. Its round-leader exclusion enumerated Kalshi's digit phrasing (Round \d+ Leader) plus one hand-patched word (first round leader), so Polymarket'sSecond/Third/Final Round Leaderclassified as an OUTRIGHT WINNER market. An enumeration written by reading one source's titles is complete for that source and silently partial for every other, and the two failures compose: with the real winner market deleted by the over-broad arm and a round-leader market admitted by the under-broad one,_dedup_winner_markets(which elects the surviving candidate with the most outcomes) crowned the Second Round Leader market as the tournament's winner market. Live consequence on the FedExCup Playoffs opener:event:golf:fedex-st-jude-championshipranked Hideki Matsuyama the favourite at 0.278 —(0.5 + 0.056)/2, where the 0.5 was an EMPTY ORDER BOOK (bid 0.01 / ask 1.00) on a round-2 market and DataGolf priced him 0.056. Guard an enumeration with a LOOP over the enumeration, never a second hand-written list — the fix defines the ordinals once and the test parametrizes over that same constant, so a partial list cannot pass. (UX-P070, #1824.) -
A test that asserts DEFECTIVE behaviour locks the defect in — an honest fix breaks a passing test, and that breakage is evidence, not damage — The literal specimen, LAT-P048 on
backend/tests/test_redis_census_bounded_1807.py: one test assertedverdict == "complete"on the same line assample_budget_exhausted is True. The endpoint exists to rank Redis key classes BY BYTES, and exhausting the sample budget meant 990 of 1,000 classes were never sampled and each therefore estimated zero bytes — a ranking built almost entirely from unmeasured rows, reported as a completed census. The test did not fail to catch that; it certified it, in a suite of twenty that was green on every run. So the honest repair (a third verdict,partial, with apartial_reason) could not be made without turning a passing test red, and for a moment the diff looked like a regression: green suite before, one failure after. That is the correct shape of the fix, and recognising it is the whole point of this entry. The reflex it has to beat is strong and sounds like discipline — "my change broke a test, so my change is wrong" — and under it the repair gets reverted or, worse, contorted until the false green survives, which re-ships the defect with a passing test now guarding it twice. How to tell the two apart, since both look identical in CI: read the assertion as a SENTENCE and ask whether you would sign it as a product claim. "A census that sampled 1% of classes is complete" is not signable; "a bounded scan stops at the bound" is. If the sentence is not signable, the test is a bug of the same severity as the code it describes, and it is amended in the same commit with the reason written into the test — not deleted quietly, because a deleted assertion leaves no record that the contract CHANGED. This is the third specimen in one week and they are structurally distinct, which is why it is a gotcha and not an anecdote: (a) this one, an assertion pinning a false verdict; (b) R3's rewritten tests, same week; (c) #121's constant-oracle family, where the test compares production to the constant production reads, so it asserts nothing at all — the degenerate case, a test that cannot break because it has no independent claim. Siblings by mechanism: #122 (a double that cannot express the operation certifies the bound that fails to charge for it — LAT-P048 hit that one in the same file, where_PagingFakeRedisansweredMEMORY USAGEfor free so no test could describe a page that is SLOW rather than LONG), #53, #124. All of them are an instrument agreeing with the thing it was supposed to check. Corollary for reviewers and for the Integrator: a queue reporting "N passed, and one pre-existing test amended because it asserted the defect" is reporting a stronger result than one reporting "N passed", and the amendment is the part to read first. -
Plan the mutations BEFORE you trust the tests — the mutation PLAN finds the missing instrument, and a SURVIVOR is a design finding, not a coverage gap — Two specimens in two cycles, and in both the value arrived before the harness ran. (a) LAT-P049: while enumerating what could break
/search's scorer wiring, the window noticed there was no test that could distinguish "the concept was demoted" from "the concept was DROPPED" — so it added a structural guard and a two-row route-ordering test, and only then ran the harness. Both mutations that mattered (M4, the original first-writer-wins bug;M3, #1846's blanket flag) were killed by instruments the mutation plan had just caused to exist. Neither would have been caught by the tests that were there when planning started. (b) LAT-P050: the mutationM1— "rebuild the evidence echo from the suggestion instead of taking it from theEvidencethat ranked" — SURVIVED, and the survivor was correct: at that call site the two were byte-identical, because the echo sat before the private-key strip and the suggestion still carried_aliases. The mutation was not weak; the CODE's guarantee was incidental. Moving the echo to after the strip made the provenance structural — a rebuild can no longer reproduce it — and the same mutation then died. The reusable method: (1) write the mutation list from the CONTRACT, not from the diff; (2) for each one, ask which existing test fails? and when the answer is "none", that is the finding — build the instrument first; (3) when a mutation survives, ask whether the mutant is genuinely EQUIVALENT before calling it a coverage gap, because an equivalent mutant means your code's property holds by accident and the fix belongs in the SOURCE, not the test. A harness that only ever reportsN/N killedis a harness that stopped asking. (c) LAT-P051 — the definitive specimen, and Alex ruled it into this entry verbatim (2026-08-14): the two survivors WERE the defect, alive behind 148 green tests because every unit test computed_deriveditself instead of asking the endpoint. The seeded route test as the missing instrument, then 7/7 — that sequence goes in the gotcha body verbatim. Same for rebuilding the tie test that asserted a stable sort is stable. Unpacked, because the sequence is the lesson: the first run scored 4/7, and the three survivors wereM1(restore the blanket_derived = Trueflag — the original defect itself),M2(invert the predicate, so #1846's Emmys over-match returns) andM7(drop the #1206 stopword guard). The route's own line — the single line the whole change was about — had no test coverage at all, and the 148-test oracle set passed anyway, because the unit tests all constructed_derivedthemselves rather than asking/typeaheadwhat it returned. A test that computes the value under test is a test of your arithmetic, not of the endpoint. Buildingtests/integration/test_route_typeahead_concept_provenance.py(seeded session, 9 tests) and addingtest_search_concept_query_gate.pyasM7's oracle took the score to 7/7. And a third finding came out of PLANNING the mutations rather than running them:TestGolfPrependProtectsTheTiehad been written against a hand-ordered list, so what it actually asserted was that a stable sort is stable —M5would have survived it untouched. It was rebuilt on the real_upsert_query_derived_conceptbefore the gate was finished. Siblings: #122 (control green on unmutated source FIRST, or every mutant scores a kill it did not earn), #130 (a test asserting the defect), #121. -
!== nulltreats an ABSENT key as PRESENT — so a shared component breaks on its next caller, not on the one it was written for —components/EventCardgated its projected-score footer onodds.projected_home_score !== null. Every producer it had ever served (/api/events, the feed) spells "no projection" as an explicitnull, so the guard was correct for years. UX-P074 pointed a new producer at it — the league rails, which carry a blend and no snapshot, so the key is simply not there — andundefined !== nullistrue, so the card ranMath.round(undefined)and printed "Proj NaN-NaN" on every league fixture. The strict check does not mean "has a value"; it means "is not exactly null", and absence is a third state it silently reads as presence. Use!= null(the one place loose equality earns its keep: it isnull-or-undefinedin a single operator), or atypeof/Number.isFinitetest when the value must also be a number. Two second-order lessons, both of which cost more than the fix: (1) the bug is in the CARD but it only appears through the CALLER, which is why it survived — no existing test could produce it, because no existing producer omitted the key; a test for it has to construct the partial payload deliberately (__tests__/components/EventCard.test.ts, "absence is absence, however it is spelled"). (2) A plant proved the first version of that test was worthless. The adapter had been made polite — it sends explicit nulls — so reverting the card's guard to!==still passed everything. The guard only became real once a test built the payload with the keys genuinely missing. A fix and a test that both assume the caller is polite verify the caller, not the fix. Numbering note, and it collided exactly as predicted: this entry was banked as 130 againstorigin/master(highest 129 at 2026-08-14) — butprogram/latency-45had claimed 130 in.claude/handoff/RULING-CLAIMS.mdthe day before, and UX-P074 wrote its number without reading the ledger. Per Alex ruling 4 (2026-08-14) and ruling 055, a duplicate number renumbers, never keep-both, and per the ledger's own tie-break the lane that claimed keeps it. Renumbered 130 -> 132 by UX-P075 onprogram/ux-63— the successor branch, exactly as UX-P070 repaired 126 -> 127 onprogram/ux-56, becauseux-61andux-62are certified-and-accepted and are not reopened to fix a number. Zero cross-references needed updating. This is the mirror of the 126 loss: there the careful lane read the ledger and lost to one that did not; here the careless lane was ours. -
THE SHARED COMPONENT IS THE ONE WITH LIVE IMPORTERS, NOT THE ONE WITH THE RIGHT NAME — reusing a retired component while believing it is the canonical one is how a card system fragments a second time —
components/ThresholdGrid.tsxis named for the job, documents itself as "displays a grid of threshold variant outcomes", is clean, tested-adjacent and obviously the shared heatmap card. It has had zero importers since L2-118 replaced it withQuantityGroup. UX-P074 — the queue sent to retrofit the league page onto ruling 047's one card system — went looking for "the existing heatmap card", foundThresholdGridby name, and nearly reused it. That would have re-fragmented the card system inside the very queue commissioned to unify it, and it would have looked like compliance: a page rendering through a shared-looking component with a correct-sounding name. The trap is that a retired component ages better than a live one — nobody edits it, so it accumulates no local hacks, no caller-specific props and no TODOs, and it therefore reads cleaner than the component that actually ships. Grep for importers before you believe a name.grep -rn "from .*ComponentName"(or the ESLint no-unused-modules rule) answers in one command what reading the file cannot answer at all, because a component's file contains no evidence about whether anyone calls it. Two corollaries: (1) retire on discovery, in the same queue — a dead component that is merely noticed stays a trap for the next reader, and this one survived being noticed once already (lib/leagueCards.tscarries a comment warning about it, written by the queue that nearly used it); (2) when a design ruling says "use the existing X", the ruling names a role, and the lane owes a measurement of which artifact currently fills that role — the ruling's author is not tracking your import graph. Retired here by UX-P075 (deleted, with its two token-debt test references removed and its two referring comments moved to past tense). Alex ruling 2, 2026-08-14, on the UX-P074 acceptance. -
A PREMISE CENSUS MUST READ THE WORLD IT WILL MERGE INTO — a census run against your own branch base tells the truth about that base and lies about master the moment master moves — Ruling 030 requires a census before the staged work, and it is allowed to re-decide the queue. UX-P075's did, and it re-decided it wrongly. The staged premise was "By Source merges the three sportsbook shapes into ONE Sportsbooks row, exactly as Source Comparison already does" — Alex's words, written on 2026-08-13 while he was looking at the deployed page. The census ran against the branch base
c6d2e574, found no provider merge anywhere on the calibration page, and reported the premise FALSE. It was true oforigin/masterand false ofc6d2e574, by one day: CAL-P050 (91ae8c8e, queue 316 item 2) had landed the provider merge on master on 2026-08-13, and the base predated it. The lane then built a rival — a shared module, a table component, twelve tests — and posted a correction of Alex that was itself the error. It was caught only whenorigin/mastermoved again andmerge-treenamedfrontend/app/calibration/page.tsx; the rival was deleted whole and CAL-P050's module adopted, which was better on a point the rival had missed (providerOfis total over source keys, so Kalshi and Polymarket are providers-with-one-shape rather than special cases exempted from the grouping, and it carries the forbidden-blend rule that two keys of the SAME shape are never fused). The rule: a census's subject decides what it must read. A census about CODE may read your tree. A census about a PAGE, a payload, or anything a reader sees must readorigin/masterand production — your base is not the world your change will live in, and the gap is exactly as old as your branch. Concretely:git fetchfirst, run the premise query againstorigin/master(git show origin/master:<path>) and against the deployed surface, and when those two disagree with your tree, your tree is the one that is wrong. Note the second half, because it is the part that generalises past git: the user was reading the deployed artifact, and that made his request evidence rather than preference. Alex asked for "traded"/"untraded" while looking at CAL-P050's freshly-deployed "Price changed"/"Price stayed put" labels — so his wording was a judgement about the merged state, and it settled the two-hunk label conflict in the new queue's favour rather than merely competing with it. When a request and your census disagree, ask WHICH ARTIFACT the requester was looking at before concluding they were mistaken. Sibling of gotcha 133 (the shared component is the one with LIVE IMPORTERS, not the one with the right name): both are "neither question is answerable from inside the file you are looking at", one inverted — 133 is reviving a corpse, this is building a rival to something already alive. (UX-P075/UX-P078, #1865; Alex ruling 2026-08-14(b) item 2.) -
A TRUNCATED
xcodebuild testREADS EXACTLY LIKE A PASS — the absence of a failure marker is not a pass, and a killed run produces precisely that absence — UX-P081 ran the native suite, the tool's 600 s timeout moved the job to the background, and the shell was killed. The log stops mid-suite at 238 passed / 0 failed, with no** TEST SUCCEEDED **line, no** TEST FAILED **line, and no exit code at all — because the process that would have printed any of them no longer existed. Every cheap check a reader reaches for returns the reassuring answer:grep -c failedis0, the last hundred lines are greenpassedrows, the failure count is genuinely zero. It is zero the way an empty room contains no arguments. The verdict was never absent because the suite was healthy; it was absent because the suite was interrupted, and those two states are byte-identical in every part of the log a hurried reader samples. The suite in question had 584 tests; a reader who accepted 238/0 would have certified a branch on 41% of its own gate and been able to quote a real, green, honestly-produced log while doing it. The rule: require the POSITIVE terminator.grep -q '\*\* TEST SUCCEEDED \*\*'(orBUILD SUCCEEDEDfor a build) is the assertion; a failure count is a corroboration, never the verdict. Capture the exit code out-of-band in the same breath —cmd > /tmp/gate.log 2>&1; echo "EXIT CODE: $?"— and run anything that can outlive a tool timeout undernohup … &, then poll, so the shell's death cannot take the verdict with it. Also assert the COUNT against a known floor (584 here, = the prior cycle's 568 plus exactly the 16 added), because a truncation that happens to land after the lastfailedline is invisible to the terminator check alone if the terminator is missing for a different reason. Third in the family and the most convincing of the three, because the other two involve a system reporting something and this one involves a system reporting nothing: #53 (an empty 200 is a response shape, not an absence — Kalshi answerstrades: []identically for "purged" and "never traded"), #54 (cmd | tailreports TAIL's exit code, so a gate that never ran reports success — and${PIPESTATUS[0]}expands to EMPTY in zsh, so the reader supplies the zero). All three are the same inference: a missing signal read as a negative finding. The generalisation worth carrying pastxcodebuild: any long-running gate — pytest, a browser rail, a migration, a backfill — must be graded on an artifact it emits on completion, never on the absence of an error in a stream that may simply have stopped. (UX-P081/UX-P082, #1773; owed by the cycle-78 acceptance and banked here.) -
A STALE SIMULATOR DESTINATION EXITS 70 WITH NO VERDICT LINE — it is a typo-class failure wearing #135's truncation costume, and #135's correct reflex is what makes it expensive — The
iPhone 16simulator was removed from this machine (the installed set is the 17 family on iOS 26.5).xcodebuild -destination 'platform=iOS Simulator,name=iPhone 16'then exits 70 having printed no** TEST SUCCEEDED **, no** TEST FAILED **, and no test counts — which is, line for line, the signature #135 teaches you to read as "the run was killed, re-run it." So the reader does the diligent thing, re-runs a command that cannot ever work, and burns a cycle per attempt. The two states are distinguishable, but only by a check nobody runs by reflex: does the destination exist? Note the asymmetry that makes this worth its own entry rather than a footnote on #135 — a truncated run is a transient failure whose correct response is to retry, and a stale destination is a permanent one whose correct response is to edit the command. Reading the second as the first converts a ten-second fix into an unbounded retry loop, and every retry produces fresh, honest, identical evidence for the wrong diagnosis. The fix is a preamble, not a habit:scripts/ios_native_gate.shresolves the destination name to a UDID viaxcrun simctl list devices availablebefore invokingxcodebuild, refuses with a distinct exit code (5, not 70) when it cannot, and prints the installed device list in the refusal — so the failure names itself instead of impersonating another one. It passes-destination "id=<UDID>"thereafter, which also removes the name-matching ambiguity entirely. Two corroborating catches from the same script's first day, both of which a hand-rolled invocation would have mis-read: (a)build-for-testing test-without-buildingemits** TEST BUILD SUCCEEDED **and** TEST EXECUTE SUCCEEDED **, and neither is the** TEST SUCCEEDED **that a plaintestaction prints — a terminator check written for the wrong action pair fails closed, which is the right direction but only if you notice; (b) when the build half fails,test-without-buildingcheerfully runs the previously built bundle, so the log reports the PRIOR cycle's test count at zero failures over code that never compiled — caught only byBAINLUCK_GATE_MIN_TESTS, the count floor #135 asks for. That is the fourth distinct route to a false green in this family, and the first where the stale artifact is a binary rather than a log. Rule: a named device is a claim about this machine — check it, and make the check part of the command rather than part of your memory. (UX-P085, cycle 81; environment note banked by Fable's cycle-81 directive as joining #54's family.) -
"FILED NOT FIXED: #N" CLOSES #N — GitHub's closing-keyword parser has no negation handling, and the phrase this project invented to be HONEST about unfinished work is the exact trigger — GitHub auto-closes an issue when a commit message reaching the default branch contains a closing keyword followed by a reference. Three properties combine badly: the keyword may be followed by a colon (
fixed: #1885is a directive), matching is case-insensitive (FIXED: #1849), and there is no negation handling at all —not,neveranddoes NOTare invisible to the parser. So every one of these closes the issue it is disclaiming:Filed, not fixed: #1885·FILED NOT FIXED: #1849·It deliberately does NOT fix #1619 — that is the next queue. All three are real, all three happened on this repo, and two of them were still closed and undetected a week later when cycle-82 forensics went looking for the first (#1619 was a p1, dark for seven days; #1849 sat on the UX lane's own "owed, deferred six cycles" list while GitHub had it marked done). Four properties make it near-undetectable, and each defeats a different reviewer: it fires at merge, not authorship, so the closure lands days later under whoever pushed; it is attributed to the repo owner, indistinguishable from Alex closing it deliberately; it leavesstate_reason: nulland no comment, so the thread shows nothing to read; and the board card flips to Done silently. The discriminator that names it in one call is the timeline event'scommit_id—gh api repos/OWNER/REPO/issues/N/timeline— because a human close carries none. The trap is that scrupulousness is the risk factor: the more carefully a commit message disclaims what a queue did not finish, the likelier it marks that work complete, which is why this survived in a project that writes unusually careful commit messages. The keyword and the reference may be separated by ANY whitespace, including a BLANK LINE — measured while writing this entry: a commit whose subject ended…not fixedand whose body opened#1620's premise is FALSEmatched asfixed\n\n#1620and would have closed #1620. Subject and body are one string to the parser, so a keyword at the end of a subject reaches a reference at the start of a body. Safe forms that never close anything:re #1885,refs #1885,#1885 (not fixed), or simply a bare#1885— a bare reference only cross-links. When QUOTING one of these sentences as a specimen, elide the hash ("Filed, not fixed: 1885"), because a verbatim quote is itself a live directive: the first draft of the commit that banked this gotcha carried six, and would have re-closed all three victims plus #1620. Never putfix/fixes/fixed/close/closes/closed/resolve/resolves/resolvedimmediately before an issue reference unless you mean it, and note that a colon, a capital, or a preceding "not" changes none of that. Audit history with a scan for a closing keyword within ~30 characters after a negation; the prevention is a commit-message lint in CI, because a detector reconciles a week after the lie, and a lint refuses the sentence while it is being written. Same family as #53 / #54 / #135 — a signal read as the opposite of what it means — but inverted: those are a missing signal read as a negative finding, this is a present signal read as a positive one nobody wrote. (Cycle-82 forensics on #1885; specimen and proposed sentinel condition on #1878.) -
EDITING A SOURCE FILE WHILE PYTEST IS IN FLIGHT MANUFACTURES FAILURES IN TESTS YOU DID NOT TOUCH —
inspect.getsourceslices the file ON DISK at line numbers collected before your edit — CAL-P070's full-suite run reported nine failures; every one of them was a phantom, and every one passed on a clean re-run of the identical tree. The window editedapp/tasks/precompute_calibration.pywhile the suite was running. Pytest had already imported the module and recorded each function'sco_firstlineno, butinspect.getsourcere-reads the file, so nine source-text assertions sliced the new file at the old offsets and were handed the body of some neighbouring function. The failures name subjects the diff never went near, which is what makes them so expensive: the reader's first move is to investigate an unrelated regression, and the evidence supports that reading completely — a real assertion, a real diff between expected and actual, a real function's text. The tell is that the "actual" text belongs to a DIFFERENT function than the test names, and the cheap discriminator is a clean re-run before a single minute is spent reading the tracebacks. Three properties make this worse than an ordinary flake: it is not random (the same nine fail every time until the file settles, so re-running during further edits reproduces it and confirms the wrong diagnosis); it scales with the codebase's own good practice (this project has an unusually large family ofinspect.getsourceguards — #121's constant oracles, #127's callable coverage, the ruling-parity tests, the #1974 idiom tripwire — so a mid-run edit to a heavily-guarded module lights up many at once); and the count is plausible — nine is exactly the sort of number a genuine regression produces, where nine hundred would have prompted suspicion immediately. The rule is the boring one and it was already written down: hold source edits until the suite exits. What this entry adds is the failure's shape, so the next reader recognises it in the first ten seconds instead of the first hour: nine red tests, none of them about your change, all of them source-text assertions. It was violated inside the very window whose report quotes the rule, which is the usual way — the fix is a habit at the keyboard, not a fact in a document. Sibling of #127 (hashing a function's source covers that function, never its callees) and of #131 (a test's instrument can be wrong in ways the test cannot report): all three are cases whereinspect.getsourceis load-bearing and its input is less stable than it looks. (CAL-P070; banked by Fable's CAL-P071 directive.) -
A FIXED-PATH GATE LOG OUTLIVES THE RUN THAT WROTE IT — so a gate that never ran reports its PREDECESSOR's verdict, which is #54's prescribed fix growing its own failure mode — #54 says: never pipe a gate; write
cmd > /tmp/gate.txt 2>&1; echo "EXIT CODE: $?"; tail -20 /tmp/gate.txt. Correct, and this window used it. Then a compoundcd backend && python3 -m pytest … > /tmp/gate_cohort.txtwas issued from a shell whose cwd was alreadybackend;cdfailed,&&short-circuited, pytest never ran, and/tmp/gate_cohort.txtstill held the previous run's output. The block printedEXIT CODE: 1(thecd's) over atailof a real, honest, stale failure — a test that had in fact just been fixed. The reader's own most recent memory corroborates the stale text perfectly, because they were looking at that exact failure four minutes earlier. The redirect target is state, and reusing the path across runs is what lets a non-run impersonate a run. Three instances in two windows, each with a different non-1 exit code, which is the pattern #54's amendment predicts and this entry makes concrete:254(CAL-P070, a frontend gate — lost cwd, the gate never ran);4(this window — pytest's usage error,file or directory not found, because the target path was relative to a directory the shell was not in);1(this window — not pytest's1, butcd's, wearing pytest's clothes).1is the only code that means "what you asked me to check failed"; everything else is a story about the harness — and the third case shows that even a1is not safe when a compound command can fail before the gate starts. Two fixes, both cheap, and the second is the one that generalises: (a) invoke gates by absolute path, never viacd X && …— the working directory is session state set by some earlier call, exactly the hazard #51 names for git, and it is no less true for a test runner; (b) truncate the log first, or make the path unique per run —: > /tmp/gate.txtbefore the command, or/tmp/gate-$(git rev-parse --short HEAD)-<target>.txt, so an absent verdict reads as absent rather than as the last one. Then the three signals cannot disagree: an empty file plus a non-1 code is unmistakably "did not run", where a full file plus a non-1 code invites the reader to trust the file. Same family as #135 (a truncatedxcodebuildlog has no verdict line and reads as a pass) and #136 (a stale simulator destination exits 70 with no verdict, wearing #135's costume) — but inverted once more: those are a missing artifact read as success, this is a stale artifact read as current. (CAL-P070 and CAL-P071; banked by Fable's CAL-P071 directive.) -
A PHASE BUDGET COMPUTED FROM COMPLETIONS IS A CAP THE CANCELLED RUNS CAN NEVER RAISE — and the two states it cannot distinguish are "this phase is cheap" and "this phase has not finished since the workload changed" — The calibration main build budgets each phase at
max(observed COMPLETIONS) * 1.5and, correctly, refuses to let a floor (elapsed-at-cancellation) produce a budget: a phase cancelled at 159,801 ms took longer than that by an unknown amount, so treating it as a duration would under-budget it by construction. Both halves are right and together they close a loop. After the q268 population bump, thefuturesphase's ten most recent completions were 47-118 s beats from BEFORE the bump, when nearly every unit was already banked and the phase did almost no work; that history setbudget_ms 177,374and therefore astatement_timeoutof 159,637 ms. Every beat since cancelled a unit read at that cap — measured 159,801 ms and 159,767 ms on two consecutive beats, overheads of 164 ms and 130 ms — recorded a floor, and left the budget untouched. 111 consecutive failures, and the number that caused them could not move.⚠️ The tell is ahistorywindow that has not advanced whilefloorshas, and it is invisible in the plan payload, which rendersmeasured_input: true,observations: 10andfeasibility: feasiblethroughout — all true, all about a workload that no longer exists. Three further properties make it expensive: the failure is thrown, not banked (asyncpg.QueryCanceledError->DBAPIError, Celery verdictthrown), so a cancelled unit costs the whole beat rather than just itself; the population straddles the cap (one unit finished at 103,473 ms under the same cap that killed the next), so the build banks the cheap units and stalls permanently on the expensive ones rather than slowing down, which is why "give it more beats" and an out-of-band beat both banked nothing; and the surrounding plan declared only 382,139 ms of a 1,380,000 ms window, so ~1,000,000 ms of every beat sat unallocated beside the phase being cancelled for want of it — a cap and an idle window are not visibly related in any single field. Rules. (a) When a derived limit is computed from successes, ask what would RAISE it and whether the constrained thing can produce that; if the answer is "a success it is preventing", the loop is closed and only an outside decision opens it (docs/doctrine.mdclause 9, ruling 089). (b) Make the residue legible — the plan now publishesunallocated_msandslack_target, because "72% of the beat is unspent" was always derivable and never once derived. (c) A budget is a ceiling on a statement, not a reservation of wall clock, so handing the slack to the starved phase takes nothing from the others — which is what makes the fix cheap and what makes the years of leaving it unallocated pure loss. (d) Name the rule that produced each number:budget_basis/slack_assigned_mskeep the measurement recoverable asbudget_ms - slack_assigned_ms, the same discipline CAL-P071 applied to the ETA's divisor one level down. Sibling of #41 (ordering is never the whole answer — ask what the ordering starts on) and of doctrine clause 2 (a guard derived from the thing it guards inherits the lie): clause 2 is a rule corrupted by its subject, this is a rule starved by it. (CAL-P072, #1977/#1680; specimens are generations1787091300309and1787094900158, 2026-08-18.) -
gh run rerunREPLAYS THE ORIGINAL MERGE REF — so re-running a PR's failed job after master was fixed re-runs it against the BROKEN base, and only close/reopen recomputes the merge ref — A PR's CI does not run your branch; it runs the ephemeral merge of your branch into the base as it stood when the run was created (that is why a stale base's failures vanish on their own once the base is fixed — the standing note on this repo). What was not written down, and cost queue 371 a cycle, is the corollary for the repair direction. Master went red on a Python-version-dependent parity assertion (assert 26.32 == 26.33); the Integrator reverted it; PR #1984's one red shard was that inherited failure and nothing of its own. The obvious move —gh run rerun --failed— failed a second time on the identical assertion, against a master that had already been green for several minutes. The re-run is a replay: it reuses the stored merge commit, so it re-tests the exact tree that failed, forever, no matter what the base does afterwards. The tell is a re-run failing with byte-identical output on a base you have verified is fixed. The recompute isgh pr close N && gh pr reopen N, which mints a fresh merge ref against current master (pushing a new commit does the same, but an empty commit to move CI is worse than the close/reopen). Two corollaries worth having: (a) a green re-run is likewise a claim about the OLD base, so a job that flaked green on a stale merge ref is not evidence about master today; (b) this is the CI-side twin of ruling 017's gates prove something about the commit you TESTED, not the commit you push — here the gate proves something about a commit nobody chose and nobody can see. Sibling of #139 (a fixed-path gate log outlives the run that wrote it): both are a stale artifact read as current, one on disk and one on GitHub's side. (Queue 371's #1984 against the calibration-67 reverte61ef179; banked on the q372 directive, Fable ruling (d) — the float assert itself routes to the calibration lane as a tolerance, not a retry, and re-landed atfaf0564d.) -
A GREEN SUITE OVER CODE THAT HAS NEVER EXECUTED IS EVIDENCE ABOUT THE SUITE — a worker can ship with 37 passing tests, a clean integration and a production deploy, and die in 73 ms on every single invocation —
cohort_cell_census(#1978) merged in CAL-P075, deployed at v3863, and failed every call with'_AsyncGeneratorContextManager' object has no attribute '__anext__':get_task_sessionis an@asynccontextmanagerand the worker hand-drove it as a bare async generator. All 37 of its tests were pure — SQL-string invariants and the pure fold — so nothing ever started it, and it went green through a 17,093-test suite. Two more defects were hiding behind the first, both surfaced within minutes of the first real run:resume=Truenever resumed (the JOB's completeness was passed to the ENVELOPE, sodecode_envelopetyped every checkpoint as MALFORMED and_read_checkpointrequiresread.ok), andGET .../lastcould not read a partial census, same cause. The rule is now ruling 102: every worker/consumer/task/script ships with at least one IMPURE test that STARTS it —main()through argparse, the task body with a fake session, the handler with a fakedb— over a stub, because there is no local Postgres here (initdbdies onshmget) and a rule that demands an integration suite is a rule nobody follows. It is not "add integration tests"; it is "make something call the entry point once".⚠️ The rule paid out against its own author in the window that banked it: CAL-P077'sscripts/measure_price_provenance.pywas written under it, its impure test covered the fold read failing and NOT the two optional side probes, and the first real 49-cell sweep died on astatement_timeoutin the uncovered branch after already measuring thirty cells. The untested branch is where the defect was, twice, in the same shape. Pure tests prove the DECISIONS; only an impure one proves the wiring, and the wiring is where this class lives. -
A CELL'S HONEST-LOOKING
gapCAN BE TWO CATASTROPHES CANCELLING — so a detector built on signed gap alone is blind to the worst cells in the population —hockey/container_membercarriedece_complete 41.00withgap_complete −6.58, and #1912 recorded it as the worst true cell with "NO known mechanism". Split by price provenance it is two opposite errors: 367 outcomes priced at 0.017 that won 100% of the time (gap −98.3 pp) and 880 priced at 0.295 that won 0.2% (gap +29.3 pp). Pooled, they nearly annihilate; a signed-gap alarm sees −6.6 pp and moves on, which is what every gap-based check in this program did for months. ECE cannot be cancelled that way (it is an absolute value per bin) — which is the argument for grading cells on ECE and usinggaponly as a direction hint, never as a screen. The same shape as gotcha #53 one level up: one observable standing in for two facts, resolving to the reassuring reading by default. Pinned byTestTheFold::test_two_opposite_errors_cancel_in_gap_but_not_in_ece. -
opening_probabilityIS NOT NECESSARILY AN OPENING PRICE — checkopening_captured_atagainstresolution_datebefore treating it as one — a bulk Polymarket ingest on 2026-06-10 recorded the settled book for NHL games played five weeks earlier, and those post-settlement quotes were stamped asopening_probabilitywithopening_captured_atafter the market'sresolution_date. The curve prices every row asCOALESCE(calibration_probability, opening_probability), so they entered the published curve as though they were prices. 82.4% ofhockey/container_member, 64.2% ofbasketball/quantityand 53.6% ofbasketball/container_memberare priced this way; 9.1% of the whole 49-cell population is. Two consequences worth carrying: (a) there is nothing to re-price them against — 0 of 1,259 hockey rows and 0 of 8,387 basketball/quantity rows have ANYfutures_odds_snapshotsrow before their own resolution, so "recover the closing line" has no input and exclusion is the only sound move; and (b) the writer's own fallback hides half of it —backfill_winnersPart A storesCOALESCE(closing.probability, opening_probability), so a row with no pre-commence snapshot banks the opening under the closing line's name and is INVISIBLE to acalibration_probability IS NULLprobe. Measurecp IS NULLandcp = openingand the capture age; any one of the three alone under-reports. Instrument:app/utils/calibration_price_provenance.py(CAL-P077, #1145/#1978). -
A COPIED-FORWARD SENTENCE IS NOT A MEASUREMENT — a status claim in a report header inherits the AUTHORITY of an observation without inheriting its RE-OBSERVATION, and it self-renews exactly like a held item's permission slip —
CODEX-REPORT.md's sentry header carried "#1894 closed". Queue 386 was staged on the belief that it had said so for three runs; the count was TWENTY — 12 ×closed #1894, 3 ×q351 closed, 5 ×q351 and #1894 closed— byte-identical wording each time, and a fifth instance of the current wording landed during the investigation that found it. #1894's GitHub timeline contains noclosedevent at any point; the Integrator had posted three comments on 08-18 saying the issue must stay open, the same day codex first published "closed". The falsehood was localised and traceable to ONE inferential step: R6 measuredaccepted = 195/24hcorrectly, then wrote "the criterion is met" as "the issue is closed." One run's inference, one sentence wide — and then nineteen re-publications of the sentence, none of which was a second look. Two things made it survive twenty re-reads. (a) The other half of the same sentence was TRUE — q351 really had landed (5b507de0ancestor of47d0775c, verified) — so every reader who spot-checked the line found the part they checked correct. (b) Nothing in the artifact distinguishes a quotation from an observation. Every reader after run 1 was reading a quotation formatted identically to a fresh reading, in the one place in a report that is scanned rather than audited. The rule: a status claim carried in a report header must be RE-DERIVED from its source at each publication, or explicitly marked as a quotation carrying the date of its original measurement. A header is where claims go to stop being checked — so a header entry either costs agh issue viewon every run, or it says "as of 08-18" and stops pretending. Corollary for the derivation step itself: "the criterion is met" and "the issue is closed" are different claims with different sources — the first is yours to measure, the second belongs to GitHub, and substituting one for the other is the whole defect. Note what makes this class nastier than a plain error: the claim eventually came true (#1894's ask was measured satisfied and the issue closed on that evidence, 24h rollingaccepted = 222, non-zero in all 25 trailing hourly buckets,rate_limited = 0) — a header that is wrong for twenty runs and then right by arrival is never falsified by its own eventual reader. The correction was appended toCODEX-REPORT.md, not edited in place; rewriting the record's history is the same failure inverted. (Queue 386 Item 3; Fable directive 2026-08-21.) -
A SATURATED STATISTIC IS NOT A FAILING TASK — a p95 pinned to a soft time limit says only that the CLIP RATE exceeds 5%, and it says exactly that whether the other 95% are healthy or dying — ruling 110's falsifier excluded
precompute_backfill_winners_statusfrom grading asCENSORED, on the documented reasoning that "a beat clamped at its own timeout reports the same number however much further behind it falls". The exclusion was right; the diagnosis was not. The beat had 18 successes and 2 failures in 24 h, and its durations were genuinely spread across the decades — 1 run in 10–100 s, 20 in 100–500 s, 22 in 500–598 s, and 7 at ≥598 s. Seven of fifty is a 14% clip rate, and any clip rate above 5% puts a p95 on the ceiling by arithmetic, regardless of what the unclipped 86% are doing. The rule wasp95 >= 0.98 * soft_time_limit, so the instrument reported a healthy-but-tail-heavy beat in the same bytes as a dead one, and ruling 110's own table recorded it as "succ 24h: 0 — already failing before the move", which was false. The sibling case is the mirror image and equally instructive:compute_calibration_pricesreally does have 0 successes, but it is budget-bounded, not timeout-clamped —_CAL_DEADLINE_S = 540.0is the task's own deadline 60 s under the 600 s soft limit, 35 of 40 runs stop there and only 3 of 40 ever reach 600 s, itspart_a_cursoradvances every run, andtask_verdictdocumentspartialas "not a failure — a resumable sweep returningpartialis behaving as designed". The rule: a percentile at a ceiling is a fact about the CLIP RATE, never about the distribution under it. Before calling a beat censored, dead, or clamped, read the histogram and the SUCCESS COUNT — and check whether the clock it is stopping on is the platform's or its own, because those have opposite remedies (raise the limit vs. raise the budget). The consequence is not cosmetic: a beat excluded as dead is a beat nobody is watching, and this one was one of the seven guarding a live ruling's conditional grant. And note the direction a budget-bounded beat degrades in — work-done-per-run, which a p95 on DURATION can never see — so the right instrument for it is the cursor, not the stopwatch. Sibling of #119 (one sample is systematically the cheap one) and #53 (an empty 200 is a response shape); this is the percentile-shaped member of the family. (#2071, LAT-P078/LAT-P079.) -
A SHARED CONSTANT IS NOT A SHARED DEFECT — the RENDER SITE decides whether a rule's violation is visible, so "file X imports the same rule" is not evidence that file X has the bug — UX-P114 was directed to extend #2060's complement fix to the served feed on the reasoning that
feed.pyshares the band logic and "renders the same 93/8 to every user". The first half is true:_feed_display_scaleuses the identical1.01two-outcome threshold, and 9,252 of 22,110 open complement pairs change rendered value under the corrected band. The second half is false, and measuring the render path rather than the rule path is what showed it: the Discover futures card never prints the second side. BothFuturesCardvariants print only the hero leader; the distribution branch requires>= 4rows andComparisonCardrequires>= 4outcomes, so a two-outcome card falls through to a single number. Native agrees (DiscoverFuturesCardprints the leader alone). A card that prints one number cannot print a wrong sum, whatever rule produced it — so the 9,252 is a real population and not a feed defect, and shipping against it would have been a fix to something nobody sees. The defect on that surface is on a card nobody had named: the event card, which draws away and home side by side, and whose two numbersfeed.pymakes an exact complement by construction (current_away_prob = round(1.0 - current_home_prob, 6)) — 34 of 414 live/upcoming events printed 101, always 101, never 99.⚠️ The generalisation is the cheap part and it is the whole entry: a defect's population is the set of places that RENDER it, which is found by reading the components, not by grepping for the constant. Sharing a helper predicts where a bug could surface and says nothing about where it does. The corollary runs the other way too and is the more expensive half — the surface that had the defect imported nothing from the module the fix lived in, so a grep forrendered_percentwould have found every innocent file and missed the guilty one. Sibling of #135/#139 in family only: those are artifacts read as current, this is a rule read as a symptom. (UX-P114, #2084; the specimen set is incontracts/rendered_percent.jsonduel_cases.) -
WIDENING A FUNCTION'S SIGNATURE SILENTLY REBINDS EVERY POINT-FREE REFERENCE TO IT —
arr.map(fn)hands the new parameter the INDEX, and a bare secondnumberparameter accepts it without complaint — UX-P114 added an optional second argument toformatProbabilityPercent(prob). One existing call waswire.map(formatProbabilityPercent), soArray.prototype.mappassed(value, index, array): the second element receivedrenderedPercent = 1, the third2, and eight outcomes that must all print<1%printed<1%, 1%, 2%, 3%, 4%, 5%, 6%, 7%. It was caught only because an unrelated production-specimen assertion from UX-P046 happened to pin all eight strings. The same widening broke Swift in the same hour, and there it was a compile error:outcome.probability.map(formatProbability)no longer typechecks once the function is(Double, Int?) -> String, exit 65 fromxcodebuild(cannot convert value of type '@Sendable (Double, Int?) -> String') — two call sites, in two files, neither of them near the change. The fix that generalises is to make the new parameter an OPTIONS OBJECT, not a bare scalar:numberis not assignable to{ rendered?: number }, so.map(fn)becomes a type error instead of a wrong number, and the trap is closed for the next person who widens it rather than for this one change.⚠️ The tell you have this bug is that nothing failed — the call site is unchanged, the types were compatible, and the only symptom is values that look plausible. Before widening any signature, grep for the function's name WITHOUT a following(; that one-character difference is the entire search. Two directions worth carrying: the danger scales with how usable the function is (a good pure formatter is exactly the thing people pass point-free), and a strongly-typed runtime turns this into a build failure while a.mapin JavaScript turns it into data. (UX-P114;frontend/lib/probabilityDisplay.ts,ios/.../FormattingUtilities.swift, and__tests__/lib/probabilityDisplay.test.ts's explicit-arrow comment.) -
THE ADMIN
db-queryREAD RAIL HAS TWO BUDGET FACTS AND THE DOCS READ THE OTHER WAY ON BOTH —timeout_msisexplain-only, and a "multi-statement" refusal is usually about COMMENTS — (a)timeout_mscannot buy the row path any headroom. The documented band (500 ms – 25 s, default 10 s) applies toexplain: truealone; sending it with a plain row query returns400 {"detail": "timeout_msis only supported withexplain: true"}. So the row path is fixed at the 10 sstatement_timeout, and for a fold that does not fit, partitioning is not a fallback — it is the only budget control that exists. CAL-P085 designed a market-aware fold around the documented 25 s, asked for it, and got a 400 before a single row came back. (b)Multi-statement queries not allowedcounts semicolons, including the ones inside--comments. The frozen calibration population builder (published_population_fold_sql(), 619 lines, 40 KB) carries 15 semicolons and every one of them is in a comment; a comment strip takes the count to 0 and the same statement returns a plan-only EXPLAIN in 1.45 s. This is not a curiosity: CAL-P084 recorded that EXPLAIN as unreachable on exactly this refusal, and declined to ship source-chunking for #2076 with its pushdown premise untested and its failure direction 7×. The EXPLAIN was onere.subaway, and it refuted the premise — all six CTEs areInitPlan-materialised and each is referenced 2–8 times byCTE Scan, so an outerWHERE source = Xcannot push down and seven chunks would re-run all six, includingranked_outcomesat 94.0% of the fold's 14,059,222 total cost. A whole option was left on the table for a cycle by a guard message that named the wrong noun. Rules: never passtimeout_msoff the explain path; before believing a rail has refused your query, check whether it has refused your prose; and plan-only EXPLAIN does not execute, so it is safe on exactly the statements that always time out — which is when you most need it. Sibling of #53 (an empty 200 is a response shape — one observable standing for two facts) and of #54's amendment (read the exit code's value: a refusal that is not about what you asked is a story about the harness). Both facts measured 2026-08-21 against production (CAL-P085, #2076/#2087). -
ONE
ORDER BY+ ONELIMITACROSS SEVERAL TIERS IS NOT A CAP, IT IS A WINNER-TAKES-ALL — and the tier that wins is decided by whichever upstream source is having its worst day —_score_eventsselected the Discover/Sports feed's game candidates with a singleORDER BY (live, recent, scheduled), commence_time DESCand a singleLIMIT 500. The ordering was added deliberately, to stop thousands of scheduled events crowding out live ones, and for a long time it did exactly that. On 2026-08-21 it inverted: an esports ingestion burst left 2,911 live rows resolving to TEN distinct matchups (mean 291 copies, max 364, zero singletons), which took 488 of the 500 slots. The admitted set was 100%live, spanned a fifteen-minutecommence_timeband, and carried 8 rows with any probability source — so zero scheduled and zero finished events reached the scorer, and the first screen of the product served one real game, rendered twice. The lesson is not "raise the cap". A single ordered cap grants the highest-priority tier an unbounded claim on the whole budget, so the feed's contents become a function of which upstream source is currently malfunctioning — the priority ordering is the starvation mechanism, wearing the clothes of a fix for it. Give each tier a quota that sums to the same budget, and collapse exact duplicates before the quota so one fixture cannot spend another's slots. And test BOTH directions (#43): the flood must collapse and the real slate must stay populated — a one-directional guard passes happily on an empty feed. Sibling of #43 one level up: there a diversity cap emptied the Sports tab, here the candidate cap did, and both were written to protect the thing they emptied. -
SQLAlchemy's JSON/JSONB TYPE STORES PYTHON
NoneAS THE JSON TEXT'null', SOIS NOT NULLIS TRUE FOR A COLUMN THAT HOLDS NOTHING — writingEvent(win_probability_sources=None)through the ORM does not produce SQL NULL by default; it produces the JSON scalarnull, andcol.isnot(None)then answers True. A predicate meaning "this row has probability data" therefore admits the rows that have none, and any tiebreak built on it prefers the emptiest row it can find. UX-P116 hit this in the survivor rule of the feed's duplicate collapse: the copy with no sources beat the copy with real ones, so the fix for a blank card would have chosen the blank card. It is invisible in production data and invisible to a shape test. Today'seventsrows are true SQL NULL (25,442 NULL / 167 real / zero empty{}of 25,610), because they are written by task code using Coreupdate(), not by the ORM — so the defect was latent in production and live the moment an ORM-written row appeared, which is exactly what the test fixture was. It was caught in the first run of an EXECUTING test and could not have been caught by asserting on compiled SQL. Compare the text form when you mean "empty" —CAST(col AS VARCHAR) NOT IN ('null', '{}')alongsideIS NOT NULL— so all three spellings of nothing give one answer. (sqlalchemy.JSONhas anone_as_nullflag for the write side; the read-side predicate still has to survive rows written before anyone set it.) -
A TEST THAT PATCHES THE FUNCTION UNDER AUDIT CAN ONLY PROVE THE STUB — patch one level DOWN — when the question is "is this layer honest about whether its write actually landed?", a test that replaces that layer with a hand-written honest double has removed the defendant from the courtroom. The function under audit must run its real code against a lying dependency: patch the publisher, the driver, the store — never the thing being judged. Specimen, and it cost four rounds. CAL-P081 added an
INTENT_NOT_DURABLEbranch torepair_pm_never_gradedso the apply would refuse whenever_save_obligationreturnedFalse. The branch was real, correct, and completely unreachable:_save_obligationdecided durability from the publisher's ownstatusfield and never read anything back, so no publisher behaviour could ever make it returnFalse. It passed certification because CAL-P081's specimen patched_save_obligationitself — the function whose honesty was the entire question was the one the test had swapped for an honest stub, and a stub is honest by construction. Codex broke it in one move by patching a level down instead: apublish_snapshot_standalonethat stores nothing and answerssupersededlet the real apply commit 4 UPDATEs, 4 commits,success: true,obligation_persisted: true— against an empty store. The repair (CAL-P085) is an after-read, and the reader matters:_save_obligationnow reads back through_load_obligation— the reader a RETRY uses — and_save_planthrough_load_plan— the reader the APPLY uses — and_save_planre-digests rather than comparing the storedplan_hashfield, because a payload can carry a hash that does not describe its own body. Not a bespoke check: a bespoke reader can pass while the reader that actually gates the behaviour still saysmissing. The discharge site is the one that loses money — a discharge "proved" by reading back a still-OPEN record reports the debt paid while the store says it is outstanding, and an open debt at least re-triggers the repair. Rules: (1) patch one level below the layer under audit, always; (2) prove a write through the reader its consumer will use, never through the acknowledgement and never through a reader written for the test; (3) when you fix one call site, add a census test pinning publisher-call count == after-read count, so the next site fails a test instead of waiting for the next cert. Sibling of #53 (an empty 200 is a response shape) and of ruling 050 (a control that cannot fail is not a control) — the same disease at three layers: the thing you replaced to make the test convenient is the thing the test was for. Measured 2026-08-21 (CAL-P085/CAL-P086, #1912, C-APPLY-PRE-1912-R3-R2). -
SELECTION IS NOT COMPLETION — a resume cursor written from what you SELECTED skips everything you did not FINISH, and turns every transient failure into permanent backlog — a cursor advanced before the work converts a retryable error into a skipped row, because the row returns only after a full wraparound and a growing id frontier can prevent that wrap indefinitely. The tell is a recovery task that runs on schedule, reports success, and sits beside a backlog that only grows. Specimen (
C-WINNER-WRITER-1, 2026-08-21, BLOCK):_backfill_polymarket_winners_from_apiranmax_id = max(row.id for row in markets)+setexTHREE LINES ABOVE its first API call, under the comment "Save cursor for next run". Executable specimen: ids 123 and 124, one per call, a transient error each — run 1 checked ZERO markets and moved the cursor to 123; run 2 selected 124 and moved it to 124. That is how a four-times-a-day recovery task coexists with an 82.29% August Polymarket winner gap (305,660 markets missing a winner).limitis selection CAPACITY, never completed work — every early-stop path (throttle circuit-breaker, caller deadline, transport error, SIGKILL) silently converts the difference into loss. Fix: advance only past CLASSIFIED rows; hold just BELOW the lowest deferred id on an ascending drain (_next_gamma_cursor_decision) or just ABOVE the highest on a descending one (clob_resolve._next_cursor_decision, #989 item 1); never wrap while anything is deferred, because a wrap declares the backlog drained. Report selected / completed / deferred / cursor_held SEPARATELY — onemarkets_checkedcannot distinguish a drained page from a skipped one. Two traps worth naming: a row STRUCTURALLY handed to another rail is COMPLETED for cursor purposes (treat ~97.5% of a pull as unfinished and the cursor pins below the first of them forever — #41 arriving through the cursor instead of the ORDER BY), and caching a transient as a dead id is the SAME mistake against a second store, which this function also had. Sibling of #36, #41 and #53. -
A STRIP IS NOT COMPLETE UNTIL THE STRIPPED COMMITS ARE ON A PUSHED REF OR EXPLICITLY RULED UNNEEDED — a rebuild that removes commits from a PR leaves them alive on exactly one stale local branch, and every routine cleanup deletes them — the correct, everyday remedy for "these two commits do not belong in this PR" is to rebuild the branch without them and force-push. The rebuild is right; what nobody performs is the second half. The old head keeps existing, holding the stripped work, and it is now reachable from one place: a stale local branch in a shared tree. That ref is invisible to
origin, invisible togit cherry, invisible to every "has it landed" check that compares against remote refs, and it is removed without ceremony bygit branch -D,git worktree prune, or anyone tidying a tree they did not dirty. Named failure (queue 394, 2026-08-23): stripping two Polymarket commits from PR #2063 produced the rebuilt headc2fbb8f9;git branch -a --containsreturned exactly one name for both stripped commits —lane1/q386-admin-identity@8b8f4e42, a local branch in~/bainluck— and neither was an ancestor oforigin/master. 578 lines of reviewed, tested production work were one routine command from being unrecoverable, and unlike #52's orphan WIP these were real commit objects, so nothing in the tree looked dirty and nogit statuswould ever have mentioned them. This is #52's blind spot, not a restatement of it: #52 covers uncommitted WIP, which at least announces itself as dirty; this covers COMMITTED work orphaned by an otherwise-correct rebase, which announces nothing at all. The tell is also inverted — a cleangit statusis the expected state here, so cleanliness is not evidence. The rule: a strip is finished when each stripped commit is (a) on a pushed ref — its own PR is the cheapest form, and it doubles as the place to decide the work's merits separately from the PR it was crowding — or (b) explicitly ruled unneeded, in writing, by someone entitled to rule it. "It's still in the reflog" is not (a): the reflog is per-clone, expires, and does not survive the tree being re-created. Verify by patch-id against pushed refs only, and read a mismatch as a question rather than an answer — a rebuild that also edited a commit changes its patch-id, so a "not preserved" verdict can mean either lost or legitimately revised; resolve it with a two-dot TREE diff against the pushed head before deleting anything. Discharge for the named failure: PR #2122. Siblings — #52 (no orphan WIP in the shared master tree), #47 (checkgit log origin/master..HEADbefore committing), and thepatch-identry (reference_patch_id_not_ancestry_after_rebase_merge): all four are the same lesson from different angles — the only refs that make work findable by anyone other than you are the pushed ones. -
KALSHI SETTLES A TIED GOLF ROUND LEADER AS
result='scalar', NEVERyes— so a tie arrives in our tables as a market with graded losers and no winner at all, and every "the venue forgot to settle this" theory built on that shape is wrong — Kalshi pays a tie fractionally, and it expresses that by settling each tied legscalarrather thanyes. Our binary drain crowns theyesand cannot crown ascalar, so a three-way tie for the round lead lands as n ×no+ 3 ×scalar+ 0 ×yes. Measured venue-side (2026-09-10, CAL-P1082, standing notice 26 — Kalshi's own API by ticker family, not our mirror): of the 35 winner-less…LEADmarkets, 17 were still reachable (the rest purged, gotcha #35) and 17 of 17 settled 2–5scalarlegs and zeroyes; the contrast arm of 6 markets that DO carry a winner settled 6 of 6 exactly oneyesand zeroscalar.KXLPGAR2LEAD-FMC26: 141 ×no, 3 ×scalar(-ALLCOR,-MIYYAM,-HYOKIM), 0 ×yes. THE CONTRAST ARM IS THE ENTRY, NOT THE CENSUS. 17/17 alone reads as "Kalshi is broken for this family" and would have sent someone to build a DataGolf grading rail; it only becomes a mechanism next to 6/6 single-yes. A one-armed probe of an odd-looking cohort tells you the cohort is odd and nothing about why. DO NOT "FIX" THIS BY CROWNING THE TIED LEADERS. Three winners against a field whose expected payout sums to one overstates the observed rate by the tie multiplicity, which is a calibration defect manufactured to remove a cosmetic one. The honest handling is what the curve already does:no_winner_marketsdrops an all-loser market whole, becauseis_winnerdefaults False and an ungraded row is stored exactly like a real loss, so a market with no winner is UNKNOWN truth rather than a set of confident losses. The general clause: when a venue has more settlement outcomes than our schema has states, the states we cannot represent do not vanish — they reappear as a shape in our data (here, an all-loser market), and reading that shape as a defect in the venue or in our capture inverts cause and effect. Read the venue's own settlement vocabulary before theorising about a missing row. Siblings — #53 (an empty 200 is a response shape, not an absence) and #21 (calibration resolution data is fragile; never bulk-resetis_winner). Named case: #4687, filed on this shape and closed as not-a-defect.