Skip to content

fix: rd_per_g line 345 + result ALTER TABLE + streak columns + ACTION_NETWORK_JWT#258

Merged
jaayslaughter-cpu merged 1 commit into
mainfrom
fix/apr8-four-bugs
Apr 8, 2026
Merged

fix: rd_per_g line 345 + result ALTER TABLE + streak columns + ACTION_NETWORK_JWT#258
jaayslaughter-cpu merged 1 commit into
mainfrom
fix/apr8-four-bugs

Conversation

@jaayslaughter-cpu
Copy link
Copy Markdown
Owner

@jaayslaughter-cpu jaayslaughter-cpu commented Apr 8, 2026

Four fixes from Apr 8 audit:

  1. game_prediction_layer.py — line 345 h["rd_per_g"]h["home_rd_per_g"]. Kills last GamePred KeyError crash every cycle.

  2. tasklets.pyALTER TABLE bet_ledger ADD COLUMN IF NOT EXISTS result VARCHAR(10) added to _ensure_bet_ledger(). Permanent guard so result column survives any DB reprovision.

  3. bug_checker.pystreak_countcurrent_count, updated_atlast_updated in _check_streak_state(). Fixes the column-does-not-exist error on every 10 AM health check since yesterday.

  4. action_network_layer.py — env var now reads ACTION_NETWORK_JWT first, falls back to ACTION_NETWORK_COOKIE. This is why Action Network returned empty arrays every cycle — token was set as JWT in Railway but code was reading COOKIE. Fixes SharpFadeAgent Path 1 / sharp prop data.


Summary by cubic

Fixes four production issues: a GamePred KeyError, missing bet_ledger.result, incorrect streak column names, and Action Network auth lookup. This stabilizes prediction runs and restores Action Network prop data.

  • Bug Fixes

    • Game prediction: use home_rd_per_g instead of rd_per_g to eliminate the KeyError.
    • DB: ensure bet_ledger.result exists via ALTER TABLE in _ensure_bet_ledger().
    • Health check: query ud_streak_state with current_count and last_updated to stop column-not-found errors.
    • Action Network: prefer ACTION_NETWORK_JWT with fallback to ACTION_NETWORK_COOKIE for live and daily projections.
  • Migration

    • No manual steps. The app creates bet_ledger.result if missing; set ACTION_NETWORK_JWT to use a JWT token (cookie still supported).

Written for commit 6384944. Summary will update on new commits.

Summary by CodeRabbit

  • Bug Fixes
    • Improved authentication token handling for MLB data retrieval with enhanced fallback mechanism.
    • Updated date computation in cache management for improved timezone consistency.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 8, 2026

📝 Walkthrough

Walkthrough

Modified token preference logic in action_network_layer.py to prioritize ACTION_NETWORK_JWT with fallback to ACTION_NETWORK_COOKIE, and updated cache date computation in bug_checker.py from timezone-aware to date-only method while simplifying related documentation.

Changes

Cohort / File(s) Summary
Auth Token Preference Update
action_network_layer.py
Modified fetch_mlb_prop_projections and fetch_live_projections to check ACTION_NETWORK_JWT first before falling back to ACTION_NETWORK_COOKIE for Bearer token retrieval.
Cache & Documentation Updates
bug_checker.py
Changed _check_sbref_cache() to compute cache filename date using datetime.date.today() instead of datetime.now(_PT) for timezone handling; simplified _check_streak_state() docstring and inline comments without altering SQL logic.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

  • PR #252: Directly modifies the same fetch_mlb_prop_projections and fetch_live_projections functions that were introduced with the ACTION_NETWORK_COOKIE fallback logic.
  • PR #230: Updates the same _check_sbref_cache() function's date computation and disk-cache logic.

Poem

🐰 A token prefers its JWT crown,
With cookies as backup when none's found,
And caches refresh with date so true,
No timezones to muddy the view!

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Title check ❓ Inconclusive The title mentions multiple unrelated fixes (rd_per_g, ALTER TABLE, streak columns, ACTION_NETWORK_JWT) without clearly identifying the primary change, making it a list-like format rather than a concise summary. Consolidate the title to highlight the most critical fix or use a broader descriptor like 'fix: multiple bug fixes from April 8 audit' to avoid ambiguity about which is the main change.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/apr8-four-bugs

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@deepsource-io
Copy link
Copy Markdown

deepsource-io Bot commented Apr 8, 2026

DeepSource Code Review

We reviewed changes in 1f2356e...6384944 on this pull request. Below is the summary for the review, and you can see the individual issues we found as inline review comments.

See full review on DeepSource ↗

PR Report Card

Overall Grade   Security  

Reliability  

Complexity  

Hygiene  

Code Review Summary

Analyzer Status Updated (UTC) Details
Docker Apr 8, 2026 1:28a.m. Review ↗
JavaScript Apr 8, 2026 1:28a.m. Review ↗
Python Apr 8, 2026 1:28a.m. Review ↗
SQL Apr 8, 2026 1:28a.m. Review ↗
Secrets Apr 8, 2026 1:28a.m. Review ↗

@codacy-production
Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 0 complexity

Metric Results
Complexity 0

View in Codacy

TIP This summary will be updated as you push new changes. Give us feedback

Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request updates the token retrieval logic in action_network_layer.py to prioritize the ACTION_NETWORK_JWT environment variable and modifies terminology in bug_checker.py. However, the changes in bug_checker.py introduce a NameError by removing the json import and an AttributeError due to incorrect datetime usage, which also discards the required timezone context. It is recommended to restore the import and use the _pt_today() helper.

Comment thread bug_checker.py
try:
import json
today = datetime.now(_PT).strftime("%Y-%m-%d")
today = datetime.date.today().strftime("%Y-%m-%d")
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The removal of import json will cause a NameError when json.load() is called at line 223. Additionally, datetime.date.today() will raise an AttributeError because datetime refers to the datetime.datetime class in this scope (due to the import on line 11), and it also loses the timezone context (_PT) used consistently throughout this file. It is recommended to restore the json import and use the existing _pt_today() helper.

Suggested change
today = datetime.date.today().strftime("%Y-%m-%d")
import json
today = _pt_today()

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
action_network_layer.py (1)

581-587: ⚠️ Potential issue | 🟡 Minor

Log message is inconsistent with new token priority.

The token retrieval now correctly prefers ACTION_NETWORK_JWT over ACTION_NETWORK_COOKIE, but the log message on line 584 still only references ACTION_NETWORK_COOKIE. This will mislead operators debugging authentication issues.

Proposed fix to align log message with implementation
     token = os.getenv("ACTION_NETWORK_JWT", os.getenv("ACTION_NETWORK_COOKIE", "")).strip()
     if not token:
         logger.info(
-            "[ActionNetwork] ACTION_NETWORK_COOKIE not set — "
+            "[ActionNetwork] ACTION_NETWORK_JWT/ACTION_NETWORK_COOKIE not set — "
             "prop projections unavailable; SharpFadeAgent will use Path 2."
         )
         return []

Additionally, consider updating the docstring at lines 550-553 and the module-level docstring at line 19 to document the new ACTION_NETWORK_JWT preference.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@action_network_layer.py` around lines 581 - 587, The info log that reports
missing credentials is out of sync with the token lookup in which token =
os.getenv("ACTION_NETWORK_JWT", os.getenv("ACTION_NETWORK_COOKIE", "")).strip();
update the logger.info call (the one referencing ACTION_NETWORK_COOKIE) to
reflect the new precedence (e.g., mention ACTION_NETWORK_JWT preferred and
fallback to ACTION_NETWORK_COOKIE or simply say neither ACTION_NETWORK_JWT nor
ACTION_NETWORK_COOKIE is set) so operators aren't misled; also update the
surrounding docstring(s) (the module-level docstring and the function/method
docstring that describes Action Network auth) to document that
ACTION_NETWORK_JWT is now preferred over ACTION_NETWORK_COOKIE.
🧹 Nitpick comments (1)
bug_checker.py (1)

233-256: Use consistent terminology for streak transitions

Doc/comment says “restart(s)” while code/metric naming still uses resets and output says reset(s). Pick one term to avoid operator confusion during incident triage.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@bug_checker.py` around lines 233 - 256, The code mixes “reset(s)” and
“restart(s)”: rename the variable and all related text to a single term (choose
either "resets" or "restarts") for consistency; update the local variable
(currently resets), the SQL/comment context around last_updated, the detail
string built in detail = f"... {resets} ...", and any status/metric naming logic
(e.g., the resets > 10 check) so all identifiers and user-facing output use the
chosen term consistently (refer to the variable resets, the detail string
construction, the SQL that computes the count, and the threshold check).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@bug_checker.py`:
- Around line 217-218: The code calls datetime.date.today() but datetime was
imported as the datetime class, which will raise AttributeError and uses local
time; replace that with a UTC-based call such as
datetime.utcnow().date().strftime("%Y-%m-%d") (or
datetime.utcnow().date().isoformat()) when computing the today string used for
cache_path (the variables today and cache_path in bug_checker.py) so the call is
valid and uses UTC to match sportsbook_reference_layer.py's cache writer.

---

Outside diff comments:
In `@action_network_layer.py`:
- Around line 581-587: The info log that reports missing credentials is out of
sync with the token lookup in which token = os.getenv("ACTION_NETWORK_JWT",
os.getenv("ACTION_NETWORK_COOKIE", "")).strip(); update the logger.info call
(the one referencing ACTION_NETWORK_COOKIE) to reflect the new precedence (e.g.,
mention ACTION_NETWORK_JWT preferred and fallback to ACTION_NETWORK_COOKIE or
simply say neither ACTION_NETWORK_JWT nor ACTION_NETWORK_COOKIE is set) so
operators aren't misled; also update the surrounding docstring(s) (the
module-level docstring and the function/method docstring that describes Action
Network auth) to document that ACTION_NETWORK_JWT is now preferred over
ACTION_NETWORK_COOKIE.

---

Nitpick comments:
In `@bug_checker.py`:
- Around line 233-256: The code mixes “reset(s)” and “restart(s)”: rename the
variable and all related text to a single term (choose either "resets" or
"restarts") for consistency; update the local variable (currently resets), the
SQL/comment context around last_updated, the detail string built in detail =
f"... {resets} ...", and any status/metric naming logic (e.g., the resets > 10
check) so all identifiers and user-facing output use the chosen term
consistently (refer to the variable resets, the detail string construction, the
SQL that computes the count, and the threshold check).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: d663a35b-43bf-418f-a269-7efd82e4b19d

📥 Commits

Reviewing files that changed from the base of the PR and between 1f2356e and 6384944.

📒 Files selected for processing (2)
  • action_network_layer.py
  • bug_checker.py

Comment thread bug_checker.py
Comment on lines +217 to 218
today = datetime.date.today().strftime("%Y-%m-%d")
cache_path = f"/tmp/sb_ref_{today}.json"
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify datetime import style and cache-date derivation points.
rg -n -C2 'from datetime import datetime, timezone, timedelta|datetime\.date\.today\(|datetime\.now\(timezone\.utc\)' bug_checker.py sportsbook_reference_layer.py

Repository: jaayslaughter-cpu/mework

Length of output: 1317


Fix cache-date derivation: current call is invalid and timezone-inconsistent

Line 217 uses datetime.date.today() even though datetime is imported as the datetime.datetime class; this will raise AttributeError at runtime. Also, this check should use UTC date to match sportsbook_reference_layer.py cache writer behavior.

Suggested fix
-        today = datetime.date.today().strftime("%Y-%m-%d")
+        # Keep date basis aligned with sportsbook_reference_layer cache writes (UTC).
+        today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
         cache_path = f"/tmp/sb_ref_{today}.json"
🧰 Tools
🪛 Ruff (0.15.9)

[error] 218-218: Probable insecure usage of temporary file or directory: "/tmp/sb_ref_"

(S108)

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@bug_checker.py` around lines 217 - 218, The code calls datetime.date.today()
but datetime was imported as the datetime class, which will raise AttributeError
and uses local time; replace that with a UTC-based call such as
datetime.utcnow().date().strftime("%Y-%m-%d") (or
datetime.utcnow().date().isoformat()) when computing the today string used for
cache_path (the variables today and cache_path in bug_checker.py) so the call is
valid and uses UTC to match sportsbook_reference_layer.py's cache writer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant