Syntrex commited on
Commit
e00a142
·
verified ·
1 Parent(s): d273bac

Update SQL

Browse files
Files changed (1) hide show
  1. SQL +321 -318
SQL CHANGED
@@ -1,318 +1,321 @@
1
- Card Lab — Selector Architecture Repair Pass
2
-
3
- Context
4
-
5
- Three confirmed bugs in the deployed selector system:
6
-
7
- Bug 1: Duplicate pitchers (Paul Skenes × 3)
8
-
9
- pitcher_inning_first_seed_events stores one row per seeded game event (not one row per pitcher). The SQL LEFT JOIN produces N output rows for a pitcher with N
10
- seed events. No deduplication exists in the SQL or the Python loop that builds the options list.
11
-
12
- Root cause: SQL produces non-unique rows when pife has multiple rows per pitcher_id.
13
-
14
- Bug 2: Hitter tab showing pitchers (Freddy Peralta as "hitter")
15
-
16
- get_card_lab_hitters() is returning pitcher names. The dominance filter (batter_count > pitcher_count) is failing. Most likely cause: source_season=2025 data may
17
- include spring training games where pitchers bat, giving them batter_count >= 20. If their pitcher rows are in a different source_season or are sparse for that
18
- year's early data, pitcher_count could be near zero → filter passes incorrectly.
19
-
20
- Root cause: Dominance filter requires batter_count > pitcher_count. If pitcher_count lookup returns 0 for a pitcher who only seeded data in a different
21
- source_season, the filter incorrectly includes them.
22
-
23
- Bug 3: Substring search not working ("Skub" → no results)
24
-
25
- Two causes: (1) Tarik Skubal is an AL pitcher who never bats → batter cross-ref SQL finds no name → still shows as "Pitcher 669923". (2) format_func in
26
- st.selectbox(options, format_func=...) — in Streamlit 1.39, search may operate on the raw option value (the tuple repr "(669923, 'Pitcher 669923')") rather than
27
- the format_func output string. Pre-normalizing to plain strings eliminates this ambiguity entirely.
28
-
29
- ---
30
- Files to Modify
31
-
32
- ┌─────────────────────────────────────┬───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
33
- │ File │ Change │
34
- ├─────────────────────────────────────┼───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤
35
- │ visualization/cards/card_queries.py │ Fix pife aggregation in pitcher SQL; add debug logging in get_card_lab_hitters() for suspicious players │
36
- ├─────────────────────────────────────┼───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤
37
- │ visualization/card_lab_page.py │ Full options pipeline rebuild: pre-normalize names, deduplicate by ID, plain string selectboxes, separate │
38
- │ │ hitter/pitcher variables, improved debug expander │
39
- └─────────────────────────────────────┴───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
40
-
41
- Do NOT touch: poster_renderer.py, player_assets.py, card_data.py, app.py, DB schema.
42
-
43
- ---
44
- Change 1 — card_queries.py
45
-
46
- 1a. Fix pitcher SQL: pre-aggregate pife to guarantee one row per pitcher_id
47
-
48
- Replace the current LEFT JOIN to pitcher_inning_first_seed_events with a subquery that collapses it first:
49
-
50
- -- OLD (produces duplicate rows if pife has multiple rows per pitcher_id):
51
- LEFT JOIN pitcher_inning_first_seed_events pife
52
- ON pife.pitcher_id = sub.pitcher
53
-
54
- -- NEW (safe: one row per pitcher_id):
55
- LEFT JOIN (
56
- SELECT pitcher_id, MAX(pitcher_name) AS pitcher_name
57
- FROM pitcher_inning_first_seed_events
58
- GROUP BY pitcher_id
59
- ) pife ON pife.pitcher_id = sub.pitcher
60
-
61
- Apply this change to BOTH the year and no-year SQL variants inside get_card_lab_pitchers().
62
-
63
- 1b. Replace dominance filter with hard pitcher-exclusion set
64
-
65
- The current batter_count > pitcher_count comparison is unreliable — it fails when pitcher_count returns 0 due to data source season mismatches (e.g., spring
66
- training rows under a different source_season).
67
-
68
- New approach: Build a definitive pitcher exclusion set using a hard pitch-count threshold. Any player ID who threw ≥ 100 pitches as a pitcher is a pitcher and is
69
- unconditionally excluded from the hitter list — regardless of their batter-side appearances.
70
-
71
- Add constant:
72
- _PITCHER_EXCL_THRESHOLD = 100 # threw ≥ 100 pitches → treated as a pitcher; excluded from hitters
73
-
74
- Replace the old Query 2 (which built pitcher_counts: dict[int, int]) with a query that builds a set:
75
-
76
- # Query 2: hard pitcher exclusion set — IDs who threw >= 100 pitches
77
- if year:
78
- excl_rows = conn.execute(
79
- text("""
80
- SELECT pitcher
81
- FROM statcast_event_core
82
- WHERE pitcher IS NOT NULL
83
- AND source_season = :year
84
- GROUP BY pitcher
85
- HAVING COUNT(*) >= :excl_threshold
86
- """),
87
- {"year": int(year), "excl_threshold": _PITCHER_EXCL_THRESHOLD},
88
- ).fetchall()
89
- else:
90
- excl_rows = conn.execute(
91
- text("""
92
- SELECT pitcher
93
- FROM statcast_event_core
94
- WHERE pitcher IS NOT NULL
95
- GROUP BY pitcher
96
- HAVING COUNT(*) >= :excl_threshold
97
- """),
98
- {"excl_threshold": _PITCHER_EXCL_THRESHOLD},
99
- ).fetchall()
100
-
101
- pitcher_exclusion_ids: set[int] = {row[0] for row in excl_rows}
102
-
103
- Replace the eligibility line:
104
- # OLD (unreliable when pitcher_count lookup returns 0):
105
- eligible = batter_count >= _HITTER_MIN_PITCHES and batter_count > pitcher_count
106
-
107
- # NEW (hard exclusion — deterministic):
108
- eligible = batter_count >= _HITTER_MIN_PITCHES and batter_id not in pitcher_exclusion_ids
109
-
110
- Why this works:
111
- - Peralta throws ~3000 pitches/season → pitcher_exclusion_ids always contains him → excluded
112
- - Skubal, Cole, Skenes → same
113
- - True hitters (Judge, Trout, Soto) → 0 pitcher appearances → not in exclusion set → included
114
- - Spring training data issue: even if Peralta batted 30 times in ST with source_season=2025, his pitcher_count ≥ 100 in the same year means he's excluded
115
-
116
- 1c. Diagnostic logging (kept but subordinate to the fix)
117
-
118
- After building pitcher_exclusion_ids, log the status for known pitchers:
119
- for check_name in ["Freddy Peralta", "Tarik Skubal", "Gerrit Cole", "Paul Skenes"]:
120
- matched = [(r[0], r[2]) for r in batter_rows if r[1] and check_name.lower() in str(r[1]).lower()]
121
- for bid, b_count in matched:
122
- in_excl = bid in pitcher_exclusion_ids
123
- logger.info(
124
- "[hitter_filter_diag] name=%s batter_id=%s batter_count=%s "
125
- "in_pitcher_exclusion_set=%s result=%s",
126
- check_name, bid, b_count, in_excl,
127
- "EXCLUDED" if in_excl else "INCLUDED",
128
- )
129
-
130
- logger.info(
131
- "[card_lab_hitter_diag] year=%s raw_candidates=%s excl_set_size=%s "
132
- "final_hitters=%s excluded=%s",
133
- year, len(batter_rows), len(pitcher_exclusion_ids), len(names), excluded,
134
- )
135
-
136
- ---
137
-
138
- ## Change 2 — `card_lab_page.py`: Full options pipeline rebuild
139
-
140
- ### 2a. Pitcher options pipeline (in `render_card_lab`, Pitcher branch)
141
-
142
- Replace the current format_func-based approach with a pre-normalized, deduped, plain-string pipeline:
143
-
144
- ```python
145
- elif card_type == "Pitcher":
146
- pitchers_raw, meta = _cached_pitchers(conn, year=year if mode_key == "season" else None)
147
- if not pitchers_raw:
148
- st.info("No pitchers found in warehouse for selected season.")
149
- return
150
-
151
- # Fill unresolved "Pitcher {id}" entries via MLB Stats API name_map
152
- name_map = _cached_player_name_map(year or 2025)
153
-
154
- # Build deduplicated, normalized options
155
- # Dedup by pitcher_id (in case SQL still returns duplicates)
156
- seen_ids: set[int] = set()
157
- raw_before_dedup = len(pitchers_raw)
158
- pitcher_display_to_id: dict[str, int] = {} # normalized "First Last" → pitcher_id
159
-
160
- for pid, raw_name in pitchers_raw:
161
- if pid in seen_ids:
162
- continue
163
- seen_ids.add(pid)
164
- # Resolve name: SQL result → API fallback → ID fallback
165
- if raw_name.startswith("Pitcher "):
166
- resolved = name_map.get(pid, raw_name)
167
- else:
168
- resolved = raw_name
169
- # Normalize to "First Last"
170
- display = normalize_name(resolved)
171
- # Handle extremely rare display name collision (same display, different ID)
172
- if display in pitcher_display_to_id and pitcher_display_to_id[display] != pid:
173
- display = f"{display} ({pid})"
174
- pitcher_display_to_id[display] = pid
175
-
176
- pitcher_display_names = sorted(pitcher_display_to_id.keys())
177
-
178
- # Update meta counts
179
- n_api_filled = sum(
180
- 1 for pid, raw in pitchers_raw
181
- if raw.startswith("Pitcher ") and name_map.get(pid, raw) != raw
182
- )
183
- n_unknown_final = sum(1 for n in pitcher_display_names if n.startswith("Pitcher "))
184
- meta = {
185
- "total": len(pitcher_display_names),
186
- "raw_before_dedup": raw_before_dedup,
187
- "db": meta["db"],
188
- "api": meta["api"] + n_api_filled,
189
- "unknown": n_unknown_final,
190
- }
191
-
192
- selected_display = st.selectbox(
193
- "Player",
194
- pitcher_display_names, # plain strings — search works natively
195
- key="cl_player_pitcher",
196
- )
197
- pitcher_id = pitcher_display_to_id[selected_display]
198
- player_name = selected_display # normalized "First Last" — safe for display
199
-
200
- 2b. Hitter options pipeline (Hitter branch)
201
-
202
- Replace the current format_func approach with pre-normalized plain strings and a raw-name mapping for queries:
203
-
204
- if card_type == "Hitter":
205
- players_raw = _cached_hitters(conn, year=year if mode_key == "season" else None)
206
- if not players_raw:
207
- st.info("No hitters found in warehouse for selected season.")
208
- return
209
-
210
- # Build normalized display → raw DB name mapping (raw name needed for queries)
211
- hitter_display_to_raw: dict[str, str] = {}
212
- for raw_name in players_raw:
213
- display = normalize_name(raw_name)
214
- hitter_display_to_raw[display] = raw_name # last wins on collision (rare)
215
-
216
- hitter_display_names = sorted(hitter_display_to_raw.keys())
217
- players = hitter_display_names # for debug expander compatibility
218
-
219
- selected_display = st.selectbox(
220
- "Player",
221
- hitter_display_names, # plain normalized strings
222
- key="cl_player_hitter",
223
- )
224
- player_name = hitter_display_to_raw[selected_display] # raw DB name for queries
225
- player_name_display = selected_display # normalized for poster
226
-
227
- Important: In _gen_hitter_bytes(), normalize the payload name for display after building:
228
- def _gen_hitter_bytes(conn, player_name, mode, year, date, start_date, end_date, fmt, player_pil):
229
- ...
230
- payload = build_hitter_card_data(player_name, windowed_df, ...)
231
- payload["player_name"] = normalize_name(payload.get("player_name", player_name))
232
- ...
233
-
234
- Same for _gen_pitcher_bytes() (pitcher names from DB may be in "Last, First" format):
235
- def _gen_pitcher_bytes(...):
236
- ...
237
- payload = build_pitcher_card_data(player_name, windowed_df, ...)
238
- payload["player_name"] = normalize_name(payload.get("player_name", player_name))
239
- ...
240
-
241
- 2c. Debug expander — rebuild with explicit labels and raw counts
242
-
243
- with st.expander("Debug", expanded=False):
244
- st.write(f"**Active card type:** {card_type}")
245
- if card_type == "Pitcher":
246
- st.write("**Source function:** get_card_lab_pitchers()")
247
- st.write(f"**Raw rows (SQL + pife/bnames, before dedup):** {meta['raw_before_dedup']}")
248
- st.write(f"**Final unique pitchers (after dedup):** {meta['total']}")
249
- st.write(f"**DB-resolved (pife/batter cross-ref):** {meta['db']}")
250
- st.write(f"**API-resolved (MLB Stats API):** {meta['api']}")
251
- st.write(f"**Still unresolved ('Pitcher {{id}}'):** {meta['unknown']}")
252
- st.write("**First 20 display names:**", pitcher_display_names[:20])
253
- st.markdown("**Spot checks (must be ✓ for selector to be usable):**")
254
- names_lc = {n.lower() for n in pitcher_display_names}
255
- for check in ["Tarik Skubal", "Sonny Gray", "Liberatore", "Leahy", "Sheehan"]:
256
- found = any(check.lower() in n for n in names_lc)
257
- st.write(f" {'✓' if found else '✗'} {check}")
258
- elif card_type == "Hitter":
259
- st.write("**Source function:** get_card_lab_hitters()")
260
- st.write(f"**Raw names from DB:** {len(players_raw)}")
261
- st.write(f"**Final unique hitters (after normalize+dedup):** {len(hitter_display_names)}")
262
- st.write("**First 20 display names:**", hitter_display_names[:20])
263
- st.markdown("**Pitcher-exclusion spot checks (must be ✗ for filter to be correct):**")
264
- names_lc = {n.lower() for n in hitter_display_names}
265
- for check in ["Freddy Peralta", "Tarik Skubal", "Gerrit Cole", "Paul Skenes"]:
266
- found = any(check.lower() in n for n in names_lc)
267
- st.write(f" {'✗' if not found else '⚠ WRONGLY PRESENT'} {check}")
268
- if card_type in ("Hitter", "Pitcher"):
269
- st.write(f"**MLBAM ID resolved:** {mlbam_id}")
270
- st.write(f"**Image fetched:** {player_pil is not None}")
271
-
272
- 2d. Variable naming cleanup
273
-
274
- Rename to avoid confusion:
275
- - players_raw = raw list from _cached_hitters() (new name, used only in hitter branch)
276
- - pitchers_raw = raw result from _cached_pitchers() (already used)
277
- - players = hitter_display_names (for debug expander backward compat - or just use hitter_display_names everywhere)
278
- - All intermediate pitcher variables (seen_ids, pitcher_display_to_id, pitcher_display_names) are pitcher-only and not reused in hitter branch
279
-
280
- ---
281
- What changes fix what
282
-
283
- ┌─────────────────────────────┬────────────────────────────────────────────────────────────────────┬────────────────────────────────────────────────────────┐
284
- │ Symptom │ Root Cause │ Fix │
285
- ├─────────────────────────────┼────────────────────────────────────────────────────────────────────┼────────────────────────────────────────────────────────┤
286
- │ Paul Skenes × 3 │ pitcher_inning_first_seed_events has one row per game seeded (not │ Pre-aggregate pife with GROUP BY pitcher_id in SQL; │
287
- │ │ per pitcher); LEFT JOIN multiplies output │ Python dedup by seen_ids set as belt-and-suspenders │
288
- ├─────────────────────────────┼────────────────────────────────────────────────────────────────────┼────────────────────────────────────────────────────────┤
289
- │ Freddy Peralta in hitter │ batter_count > pitcher_count fails when pitcher_count returns 0 │ Replace dominance filter with hard exclusion set: any │
290
- │ list │ (spring training / source_season mismatch). Peralta bats in ST → │ pitcher_id with ≥ 100 pitched pitches in the same year │
291
- │ │ passes threshold │ is unconditionally excluded │
292
- ├─────────────────────────────┼────────────────────────────────────────────────────────────────────┼────────────────────────────────────────────────────────┤
293
- │ Peralta/Skenes/Cole in │ Belt-and-suspenders: plain-string normalized hitter options + │ Debug expander shows ⚠ WRONGLY PRESENT for known │
294
- │ hitter list even with fix │ debug checker that flags known pitchers still present │ pitchers — immediately visible if filter still fails │
295
- ├─────────────────────────────┼────────────────────────────────────────────────────────────────────┼────────────────────────────────────────────────────────┤
296
- │ │ format_func in Streamlit 1.39 selectbox may filter on raw option │ Pre-normalize all names to "First Last" plain strings │
297
- │ "Skub" → no results │ value (tuple repr), not format_func output │ before putting in the options list — no format_func │
298
- │ │ │ dependency for search │
299
- └─────────────────────────────┴────────────────────────────────────────────────────────────────────┴────────────────────────────────────────────────────────┘
300
-
301
- ---
302
- Verification
303
-
304
- After deploy:
305
- 1. Open Debug expander in Pitcher mode: Paul Skenes should appear exactly once
306
- 2. Open Debug expander in Hitter mode: "WRONGLY PRESENT" should NOT appear next to Peralta/Skubal/Cole
307
- 3. In Pitcher mode, type "Skub" → "Tarik Skubal" should appear (if MLB API resolved his name)
308
- 4. In Pitcher mode, type "Gray" → "Sonny Gray" should appear
309
- 5. Check HuggingFace logs for [hitter_filter_diag] lines — these will show exact batter/pitcher counts for Peralta and reveal the root cause for any remaining
310
- hitter filter failures
311
- ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌
312
-
313
- Claude has written up a plan and is ready to execute. Would you like to proceed?
314
-
315
- ❯ 1. Yes, clear context (64% used) and auto-accept edits
316
- 2. Yes, auto-accept edits
317
- 3. Yes, manually approve edits
318
- 4. Type here to tell Claude what to change
 
 
 
 
1
+ Rip out the current Card Lab selector logic and replace it with deterministic ID-based selector builders.
2
+
3
+ Do not patch the existing logic.
4
+ Do not preserve batter_count > pitcher_count.
5
+ Do not preserve tuple selectbox options.
6
+ Do not preserve any format_func-based search behavior.
7
+
8
+ Implement the following exact architecture.
9
+
10
+ ==================================================
11
+ 1) REPLACE get_card_lab_pitchers() COMPLETELY
12
+ ==================================================
13
+
14
+ Goal:
15
+ - one row per pitcher ID
16
+ - stable name resolution
17
+ - no duplicates ever
18
+
19
+ Function contract:
20
+ - input: conn, year=None, name_map=None
21
+ - output: list[tuple[int, str]]
22
+ - output format: [(pitcher_id, normalized_display_name), ...]
23
+
24
+ Implementation:
25
+
26
+ def get_card_lab_pitchers(conn, year=None, name_map=None):
27
+ params = {}
28
+ where = "WHERE pitcher IS NOT NULL"
29
+ if year is not None:
30
+ where += " AND source_season = :year"
31
+ params["year"] = int(year)
32
+
33
+ rows = conn.execute(
34
+ text(f"""
35
+ SELECT
36
+ p.pitcher_id,
37
+ COALESCE(seed.pitcher_name, pife.pitcher_name, api_name.player_name) AS raw_name
38
+ FROM (
39
+ SELECT DISTINCT pitcher AS pitcher_id
40
+ FROM statcast_event_core
41
+ {where}
42
+ ) p
43
+ LEFT JOIN (
44
+ SELECT pitcher_id, MAX(pitcher_name) AS pitcher_name
45
+ FROM pitcher_inning_first_seed_events
46
+ GROUP BY pitcher_id
47
+ ) pife
48
+ ON pife.pitcher_id = p.pitcher_id
49
+ LEFT JOIN (
50
+ SELECT pitcher AS pitcher_id, MAX(player_name) AS pitcher_name
51
+ FROM statcast_event_core
52
+ WHERE pitcher IS NOT NULL AND player_name IS NOT NULL
53
+ GROUP BY pitcher
54
+ ) seed
55
+ ON seed.pitcher_id = p.pitcher_id
56
+ LEFT JOIN (
57
+ SELECT batter AS player_id, MAX(player_name) AS player_name
58
+ FROM statcast_event_core
59
+ WHERE batter IS NOT NULL AND player_name IS NOT NULL
60
+ GROUP BY batter
61
+ ) api_name
62
+ ON api_name.player_id = p.pitcher_id
63
+ """),
64
+ params,
65
+ ).fetchall()
66
+
67
+ pitcher_map = {}
68
+
69
+ for pid, raw_name in rows:
70
+ if pid is None:
71
+ continue
72
+ if pid in pitcher_map:
73
+ continue
74
+
75
+ if raw_name and str(raw_name).strip() and not str(raw_name).startswith("Pitcher "):
76
+ resolved = str(raw_name).strip()
77
+ elif name_map and pid in name_map:
78
+ resolved = str(name_map[pid]).strip()
79
+ else:
80
+ resolved = f"Pitcher {pid}"
81
+
82
+ pitcher_map[int(pid)] = normalize_name(resolved)
83
+
84
+ pitchers = [(pid, name) for pid, name in pitcher_map.items()]
85
+ pitchers.sort(key=lambda t: t[1].lower())
86
+ return pitchers
87
+
88
+ Rules:
89
+ - dedupe ONLY by pitcher_id
90
+ - never dedupe by display name first
91
+ - normalize only after resolution
92
+ - if two different pitcher IDs normalize to same display name, append " ({id})" to the later one
93
+
94
+ Add collision handling after pitcher_map is built:
95
+ - build final_display_to_id
96
+ - if normalized name already exists for a different ID, rename second one as "{name} ({id})"
97
+
98
+ ==================================================
99
+ 2) REPLACE get_card_lab_hitters() COMPLETELY
100
+ ==================================================
101
+
102
+ Goal:
103
+ - hitters only
104
+ - no primary pitchers
105
+ - deterministic rule
106
+
107
+ Use a hard pitcher exclusion set.
108
+
109
+ Constants:
110
+ - _HITTER_MIN_PITCHES = keep existing hitter minimum if one already exists
111
+ - _PITCHER_EXCL_THRESHOLD = 100
112
+
113
+ Function contract:
114
+ - input: conn, year=None
115
+ - output: list[str]
116
+ - output format: raw DB names, sorted unique
117
+
118
+ Implementation:
119
+
120
+ def get_card_lab_hitters(conn, year=None):
121
+ params = {}
122
+ hitter_where = "WHERE batter IS NOT NULL AND player_name IS NOT NULL"
123
+ pitcher_where = "WHERE pitcher IS NOT NULL"
124
+
125
+ if year is not None:
126
+ hitter_where += " AND source_season = :year"
127
+ pitcher_where += " AND source_season = :year"
128
+ params["year"] = int(year)
129
+
130
+ excl_rows = conn.execute(
131
+ text(f"""
132
+ SELECT pitcher
133
+ FROM statcast_event_core
134
+ {pitcher_where}
135
+ GROUP BY pitcher
136
+ HAVING COUNT(*) >= :pitcher_excl_threshold
137
+ """),
138
+ {**params, "pitcher_excl_threshold": 100},
139
+ ).fetchall()
140
+
141
+ pitcher_exclusion_ids = {int(row[0]) for row in excl_rows if row[0] is not None}
142
+
143
+ batter_rows = conn.execute(
144
+ text(f"""
145
+ SELECT
146
+ batter,
147
+ MAX(player_name) AS player_name,
148
+ COUNT(*) AS batter_count
149
+ FROM statcast_event_core
150
+ {hitter_where}
151
+ GROUP BY batter
152
+ """),
153
+ params,
154
+ ).fetchall()
155
+
156
+ hitter_map = {}
157
+
158
+ for batter_id, player_name, batter_count in batter_rows:
159
+ if batter_id is None:
160
+ continue
161
+ if batter_count is None or int(batter_count) < _HITTER_MIN_PITCHES:
162
+ continue
163
+ if int(batter_id) in pitcher_exclusion_ids:
164
+ continue
165
+ if not player_name:
166
+ continue
167
+
168
+ hitter_map[int(batter_id)] = str(player_name).strip()
169
+
170
+ names = list(hitter_map.values())
171
+ names = sorted({normalize_name(n) for n in names}, key=str.lower)
172
+ return names
173
+
174
+ Rules:
175
+ - hitter exclusion is ID-based only
176
+ - do not compare batter_count to pitcher_count
177
+ - do not reuse pitcher selector outputs
178
+ - do not allow any ID in pitcher_exclusion_ids into hitter results
179
+
180
+ ==================================================
181
+ 3) DISABLE CACHING TEMPORARILY
182
+ ==================================================
183
+
184
+ Temporarily remove/comment out all @st.cache_data decorators related to:
185
+ - _cached_pitchers
186
+ - _cached_hitters
187
+ - _cached_player_name_map
188
+ - _cached_player_image
189
+
190
+ Do not leave caches on during validation.
191
+
192
+ ==================================================
193
+ 4) REPLACE PAGE SELECTOR LOGIC
194
+ ==================================================
195
+
196
+ Do not use tuple options in Streamlit selectboxes.
197
+ Do not use format_func.
198
+
199
+ Pitcher branch:
200
+
201
+ pitchers = get_card_lab_pitchers(conn, year=year if mode_key == "season" else None, name_map=name_map)
202
+ pitcher_display_to_id = {}
203
+ for pid, display in pitchers:
204
+ final_display = display
205
+ if final_display in pitcher_display_to_id and pitcher_display_to_id[final_display] != pid:
206
+ final_display = f"{display} ({pid})"
207
+ pitcher_display_to_id[final_display] = pid
208
+
209
+ pitcher_display_names = sorted(pitcher_display_to_id.keys(), key=str.lower)
210
+
211
+ selected_pitcher_name = st.selectbox(
212
+ "Player",
213
+ pitcher_display_names,
214
+ key="cl_player_pitcher",
215
+ )
216
+
217
+ pitcher_id = pitcher_display_to_id[selected_pitcher_name]
218
+ player_name = selected_pitcher_name
219
+
220
+ Hitter branch:
221
+
222
+ hitter_names = get_card_lab_hitters(conn, year=year if mode_key == "season" else None)
223
+ hitter_display_names = sorted({normalize_name(n) for n in hitter_names}, key=str.lower)
224
+
225
+ selected_hitter_name = st.selectbox(
226
+ "Player",
227
+ hitter_display_names,
228
+ key="cl_player_hitter",
229
+ )
230
+
231
+ player_name = selected_hitter_name
232
+
233
+ Rules:
234
+ - pitcher tab uses pitcher builder only
235
+ - hitter tab uses hitter builder only
236
+ - do not reuse shared variable names like "players" across branches
237
+ - use separate variables:
238
+ - pitchers
239
+ - pitcher_display_names
240
+ - hitter_names
241
+ - hitter_display_names
242
+
243
+ ==================================================
244
+ 5) ADD HARD VALIDATION
245
+ ==================================================
246
+
247
+ Immediately after building both final lists, validate:
248
+
249
+ pitcher_names_set = {name for _, name in get_card_lab_pitchers(conn, year=year if mode_key == "season" else None, name_map=name_map)}
250
+ hitter_names_set = set(get_card_lab_hitters(conn, year=year if mode_key == "season" else None))
251
+
252
+ overlap = pitcher_names_set & hitter_names_set
253
+ assert len(overlap) == 0, f"CRITICAL: overlap between hitter and pitcher selectors: {list(sorted(overlap))[:10]}"
254
+
255
+ For debug UI:
256
+
257
+ Pitcher mode debug must show:
258
+ - total raw pitcher rows
259
+ - total final unique pitchers
260
+ - first 20 pitcher names
261
+ - whether Tarik Skubal exists
262
+ - whether Sonny Gray exists
263
+ - count of names starting with "Pitcher "
264
+
265
+ Hitter mode debug must show:
266
+ - total raw hitter rows
267
+ - total final unique hitters
268
+ - first 20 hitter names
269
+ - whether Freddy Peralta exists
270
+ - whether Tarik Skubal exists
271
+ - whether Gerrit Cole exists
272
+ - whether Paul Skenes exists
273
+
274
+ ==================================================
275
+ 6) IMAGE SYSTEM
276
+ ==================================================
277
+
278
+ Keep current image hierarchy:
279
+ - local Kasper asset first
280
+ - MLB fallback second
281
+ - silhouette last
282
+
283
+ Do not change renderer layout in this pass.
284
+ Do not add uploader back.
285
+ Do not touch visual styling in this pass.
286
+
287
+ ==================================================
288
+ 7) SUCCESS CRITERIA
289
+ ==================================================
290
+
291
+ This pass is not done until ALL are true:
292
+
293
+ - Tarik Skubal appears in pitcher selector
294
+ - searching "Skub" finds Tarik Skubal
295
+ - Sonny Gray appears in pitcher selector
296
+ - Paul Skenes appears exactly once
297
+ - Aaron Nola appears exactly once
298
+ - Freddy Peralta does not appear in hitter selector
299
+ - Tarik Skubal does not appear in hitter selector
300
+ - Gerrit Cole does not appear in hitter selector
301
+ - Paul Skenes does not appear in hitter selector
302
+ - there is zero overlap between final hitter and pitcher selector names
303
+
304
+ ==================================================
305
+ 8) IMPORTANT CONSTRAINTS
306
+ ==================================================
307
+
308
+ Do NOT:
309
+ - reintroduce batter_count > pitcher_count
310
+ - dedupe by display name before ID
311
+ - use tuple selectbox options
312
+ - use format_func
313
+ - leave cache enabled during validation
314
+ - mix selector repair with visual renderer redesign
315
+
316
+ This is a selector/data repair pass only.
317
+
318
+ At the end, report exactly:
319
+ - what caused duplicate pitchers
320
+ - what caused pitchers in hitter list
321
+ - what was changed to make both impossible