Repository navigation
Monday-open hardening: stale-harvest discard, pre-close blackout, stock-split guard - #43
Conversation
…, stock-split guard Three protections derived from the first full live session's flight recorder (2026-06-12): 1. Stale scans now die at HARVEST. A hunt that straddles the close keeps computing after the bell (worker threads run while the loop idles), then waits overnight/weekend for the next tick; the existing expiry only stamped pending age at harvest time, so Monday 09:30 would have executed Friday-19:55 conviction. The harvest path now discards any finished scan older than pending_scan_expiry_seconds and hunts fresh. Observed live: a 19:55 UTC scan was in flight at today's close and would have fired at Monday's open. 2. Pre-close hunt blackout (daemon.scan_blackout_minutes_before_close, default 15): stop CREATING close-straddling scans in the first place. Stops/take-profits keep running every tick; only new hunts pause. 3. Corporate-action (split) guard in _manage_risk. KLAC's 10:1 split left the stored stop at the pre-split scale (2071) so the post-split quote (239) looked like a -90% crash and falsely stop-sold the book's highest-conviction name; the journal then booked a ~-$80 artifact loss. Discriminator: after a split the broker's avg cost is split-adjusted too, so the stored stop towers over BOTH price and avg cost (>=1.8x each) — re-anchor stop/TP/high-water to the live price instead of selling. A genuine crash keeps avg cost at the stop's scale and still sells (covered by test). 241 tests pass (6 new), ruff clean. https://claude.ai/code/session_01E9KzfCPDyYdFsufQPxURXR
📝 WalkthroughWalkthroughThis PR adds three hardening features to the daemon: (1) a pre-close hunt blackout window to prevent scans from straddling market close, (2) stale scan expiry validation to discard old background scan results, and (3) a corporate-action guard in risk management to re-anchor stops when price scale mismatches are detected instead of triggering false sells. ChangesDaemon Hardening: Scheduling, Scan Lifecycle, and Risk Guards
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/rh_agent/daemon.py (1)
485-514: 📐 Maintainability & Code Quality | 💤 Low valueSilent exception swallow during ATR fetch.
The
try-except-passpattern at lines 496-500 silently discards ATR fetch failures. Whileatr_stop()handlesNoneATR gracefully (falling back to the hard-stop percentage), logging the exception would aid debugging if ATR lookups fail systematically.This is consistent with identical patterns elsewhere in this file (lines 167-172, 566-570), so this is a codebase-wide style. The guard logic itself is correct and the threshold discriminator (stop ≥1.8× both price and avg cost) is well-reasoned for detecting splits vs crashes.
♻️ Optional: log exception at debug level
try: td = self.agent.md.build(tk, deep=False) atr = td.technicals.get("atr") if td else None - except Exception: - pass + except Exception as e: + log.debug("ATR lookup failed for %s split guard: %s", tk, e)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/rh_agent/daemon.py` around lines 485 - 514, The ATR fetch try/except silently swallows errors; update the block around self.agent.md.build(tk, deep=False) (where td and atr are set) to catch Exception as e and log the exception at debug (or warning) level before continuing so failures to obtain ATR are visible; ensure you still leave atr as None so atr_stop(px, atr, atr_mult, hard_pct) behavior is unchanged and retain existing flow that re-anchors stops and records activity.Source: Linters/SAST tools
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@src/rh_agent/daemon.py`:
- Around line 485-514: The ATR fetch try/except silently swallows errors; update
the block around self.agent.md.build(tk, deep=False) (where td and atr are set)
to catch Exception as e and log the exception at debug (or warning) level before
continuing so failures to obtain ATR are visible; ensure you still leave atr as
None so atr_stop(px, atr, atr_mult, hard_pct) behavior is unchanged and retain
existing flow that re-anchors stops and records activity.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 40b78cd8-1dda-4769-8344-4ec1f3921e22
📒 Files selected for processing (5)
config/config.yamlsrc/rh_agent/daemon.pysrc/rh_agent/market_calendar.pytests/test_monday_open_hardening.pytests/test_portfolio_broker.py
There was a problem hiding this comment.
Pull request overview
Note
Copilot was unable to run its full agentic suite in this review.
Hardens the trading daemon against three production issues observed in the first live session: harvesting stale background scans at the next open, starting scans too close to market close, and false stop triggers caused by stock splits.
Changes:
- Discard stale completed scans at harvest time (age measured from scan start) and record
scan_expired at=harvest. - Add pre-close “no new hunts” blackout window plus
minutes_to_close()calendar helper (early-close aware). - Add a stock-split scale-mismatch guard that re-anchors stop/TP/high-water instead of selling.
Reviewed changes
Copilot reviewed 5 out of 5 changed files in this pull request and generated 6 comments.
Show a summary per file
| File | Description |
|---|---|
| tests/test_portfolio_broker.py | Pins minutes_to_close in an existing test to avoid wall-clock dependence from the new blackout behavior. |
| tests/test_monday_open_hardening.py | Adds new tests covering stale-harvest discard, blackout behavior, minutes_to_close, and split-guard behavior. |
| src/rh_agent/market_calendar.py | Introduces minutes_to_close() helper with early-close support. |
| src/rh_agent/daemon.py | Implements stale-harvest discard, pre-close scan blackout, and split-guard risk logic. |
| config/config.yaml | Adds daemon.scan_blackout_minutes_before_close configuration. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| def minutes_to_close(now_utc: datetime | None = None) -> float | None: | ||
| """Minutes until today's closing bell; None when the market is closed.""" | ||
| if not is_market_open(now_utc): | ||
| return None | ||
| et = to_eastern(now_utc) | ||
| close_m = 13 * 60 if et.strftime("%Y-%m-%d") in _EARLY_CLOSE else 16 * 60 | ||
| return close_m - (et.hour * 60 + et.minute + et.second / 60.0) |
| if not is_market_open(now_utc): | ||
| return None | ||
| et = to_eastern(now_utc) |
| if scan_age > self._pending_scan_expiry: | ||
| # The worker finished while the loop was idle (a hunt that | ||
| # straddled the close keeps computing after the bell, then | ||
| # waits overnight/all weekend for the next tick). Trading | ||
| # the next open on that conviction is the classic "mystery | ||
| # trade at 9:30" — discard it; a fresh hunt starts now. | ||
| log.warning("scan finished but is %.0fs old (> expiry %.0fs) — " | ||
| "discarding stale conviction; hunting fresh", | ||
| scan_age, self._pending_scan_expiry) |
| # Pre-close blackout: a hunt kicked now would still be computing at | ||
| # the bell, idle overnight, and beg to fire stale at the next open. | ||
| # The risk loop (stops/TPs) keeps running every tick regardless. | ||
| blackout = float(self.cfg.get("daemon.scan_blackout_minutes_before_close", 15)) |
| if (stop and px and avg > 0 | ||
| and stop / px >= 1.8 and stop / avg >= 1.8): |
| # Pin the pre-close blackout open so this test is deterministic at any wall time. | ||
| monkeypatch.setattr(daemon, "minutes_to_close", lambda now=None: None) |
…nsive blackout config, named split-guard ratio
- minutes_to_close: sample the clock once and clamp at 0.0 (is_market_open
works at minute granularity, so the final sub-minute sliver of the
session could surface as a negative value).
- Blackout config float() coerced defensively — a YAML typo must degrade
to the 15m default, never error every tick.
- Split-guard threshold promoted to a named module constant
(SPLIT_GUARD_RATIO) with the discriminator rationale documented.
- Reworded the blackout-neutralizing test comment (None = market closed,
i.e. blackout not applicable — not 'pinned open').
- Copilot's control-flow finding ('fresh hunt cannot start the same tick
after a stale discard') is incorrect: the kick block is an elif of the
PENDING-execution if, not of the harvest block. Added
test_stale_discard_rekicks_fresh_hunt_same_tick proving the same-tick
re-kick that Monday's open relies on.
242 tests pass, ruff clean.
https://claude.ai/code/session_01E9KzfCPDyYdFsufQPxURXR
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@tests/test_monday_open_hardening.py`:
- Line 100: The _Agent class currently defines a mutable class-level attribute
providers = {}, triggering RUF012; change this to an instance-level attribute
(e.g., set self.providers = {} inside _Agent.__init__) or replace the class
attribute with an immutable mapping (e.g., types.MappingProxyType or a frozen
dict) so tests and other instances don't share mutable state—update the class
definition to remove providers = {} and initialize providers in the constructor
of _Agent (or substitute an immutable mapping) accordingly.
🪄 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: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: d3b8ff4f-493d-49f0-8766-4df356ef422a
📒 Files selected for processing (4)
src/rh_agent/daemon.pysrc/rh_agent/market_calendar.pytests/test_monday_open_hardening.pytests/test_portfolio_broker.py
🚧 Files skipped from review as they are similar to previous changes (3)
- tests/test_portfolio_broker.py
- src/rh_agent/market_calendar.py
- src/rh_agent/daemon.py
| monkeypatch.setattr(daemon, "minutes_to_close", lambda now=None: None) | ||
|
|
||
| class _Agent: | ||
| providers = {} |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
ruff check src tests --select RUF012 -nRepository: nickm538/robinhoodagent
Length of output: 4434
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Show context around the targeted line
nl -ba tests/test_monday_open_hardening.py | sed -n '80,120p'
# Find all references in the file
rg -n "providers" tests/test_monday_open_hardening.pyRepository: nickm538/robinhoodagent
Length of output: 110
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# context around line ~100 using cat -n (nl not available)
cat -n tests/test_monday_open_hardening.py | sed -n '90,115p'
# locate all providers usage in the file
rg -n "providers" tests/test_monday_open_hardening.pyRepository: nickm538/robinhoodagent
Length of output: 1265
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Search for usages of ".providers" that could interact with the test double.
rg -n "\.providers\b" src tests | head -n 200
# Narrow to likely agent access patterns.
rg -n "(agent|self\.agent).*\.providers\b" src | head -n 200
rg -n "\.providers\[" src | head -n 200
rg -n "\.providers\.update\b" src | head -n 200Repository: nickm538/robinhoodagent
Length of output: 7558
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect surrounding areas of each _Agent test double in the file
cat -n tests/test_monday_open_hardening.py | sed -n '40,120p'
echo "-----"
cat -n tests/test_monday_open_hardening.py | sed -n '120,210p'
echo "-----"
cat -n tests/test_monday_open_hardening.py | sed -n '210,320p'
# Search for any mutations/assignments involving agent.providers
rg -n "agent\.providers|d\.agent\.providers|\.providers\s*=" tests/test_monday_open_hardening.pyRepository: nickm538/robinhoodagent
Length of output: 10579
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect daemon providers usage around the earlier reported line
sed -n '560,680p' src/rh_agent/daemon.pyRepository: nickm538/robinhoodagent
Length of output: 3703
🏁 Script executed:
#!/bin/bash
set -euo pipefail
head -n 60 tests/test_monday_open_hardening.py
rg -n "^from types import|^import types|SimpleNamespace" tests/test_monday_open_hardening.pyRepository: nickm538/robinhoodagent
Length of output: 2445
🌐 Web query:
RUF012 mutable default value for class attribute annotating typing.ClassVar fix behavior
💡 Result:
RUF012 is a Ruff lint rule that flags mutable default values in class attributes [1]. This pattern is discouraged because such attributes are shared across all instances of a class, which can lead to unexpected bugs if one instance modifies the shared object [2][1]. To resolve a RUF012 violation, you have several options depending on the intended behavior of your code [1]: 1. Initialize in init: This is the recommended approach if the attribute is intended to be instance-specific [1]. By defining the attribute within the init method, each instance receives its own unique, mutable object [1]. class A: def init(self) -> None: self.variable: list[int] = [] 2. Use typing.ClassVar: If the attribute is explicitly intended to be shared across all instances, you should annotate it with typing.ClassVar [1]. This explicitly signals the intent to developers and tools, causing Ruff to exempt the attribute from the mutable default check [3][4]. from typing import ClassVar class A: variable: ClassVar[list[int]] = [] 3. Use immutable types: Consider using immutable alternatives, such as a tuple instead of a list, or an empty frozenset instead of a set [1]. 4. Use None as a default: Alternatively, set the attribute to None as a placeholder and initialize it later, or provide a default of None [1]. The diagnostic message for RUF012 has been improved in recent versions of Ruff to clarify that annotating with ClassVar is one of several possible solutions, rather than the only one [5][6]. Ruff also supports ClassVar without a subscript (e.g., ClassVar = []) [4].
Citations:
- 1: https://docs.astral.sh/ruff/rules/mutable-class-default/
- 2: https://github.com/astral-sh/ruff/blob/main/crates%2Fruff_linter%2Fsrc%2Frules%2Fruff%2Frules%2Fmutable_class_default.rs
- 3: Expand RUF008 to all classes, but to a new code (RUF012) astral-sh/ruff#4390
- 4: RUF012 should allow plain
ClassVarastral-sh/ruff#6267 - 5: [
ruff] Improve the diagnostic forRUF012astral-sh/ruff#23202 - 6: astral-sh/ruff@3795db1
Fix RUF012: avoid mutable class-level providers in _Agent
tests/test_monday_open_hardening.py sets class _Agent: providers = {} (Line 100), which triggers Ruff’s RUF012 for mutable class attributes. Use an immutable mapping or an instance-level attribute instead.
Suggested fix
-from types import SimpleNamespace
+from types import MappingProxyType, SimpleNamespace
...
- providers = {}
+ providers = MappingProxyType({})🧰 Tools
🪛 Ruff (0.15.15)
[warning] 100-100: Mutable default value for class attribute
(RUF012)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@tests/test_monday_open_hardening.py` at line 100, The _Agent class currently
defines a mutable class-level attribute providers = {}, triggering RUF012;
change this to an instance-level attribute (e.g., set self.providers = {} inside
_Agent.__init__) or replace the class attribute with an immutable mapping (e.g.,
types.MappingProxyType or a frozen dict) so tests and other instances don't
share mutable state—update the class definition to remove providers = {} and
initialize providers in the constructor of _Agent (or substitute an immutable
mapping) accordingly.
Sources: Coding guidelines, Linters/SAST tools
Why — first full live session's flight recorder exposed three real defects
rh-agent whyfrom session 2026-06-12 (the ledger shipped in #41 doing its job):What
pending_scan_expiry_secondsis discarded (scan_expired at=harvestledger event) and a fresh hunt starts immediately. Stale runs no longer pollute cadence stats either.daemon.scan_blackout_minutes_before_close: 15(0 disables): no new hunts within 15 minutes of the bell, so close-straddling scans stop being created. Stops/TPs keep running every tick. Newmarket_calendar.minutes_to_close()helper (regular + early-close aware).split_guardledger event) instead of selling. A genuine −45% gap keeps avg cost at the stop's scale and still sells — covered by a dedicated test.Tests
241 passed (6 new: weekend-stale harvest discard, fresh harvest still executes, blackout skip + mid-session allow,
minutes_to_closemath incl. early close, the live KLAC split case re-anchors, a real crash still fires). Ruff clean. One existing test pinned deterministic against wall-clock blackout timing.Deploy note
Merge + pull + restart before Monday's open — the running daemon currently holds a finished Friday scan that this PR's harvest guard will discard at the first Monday tick.
https://claude.ai/code/session_01E9KzfCPDyYdFsufQPxURXR
Generated by Claude Code
Summary by CodeRabbit
New Features
Tests