Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 44 additions & 8 deletions application/rebalance_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,30 @@ def _execution_already_recorded_message(*, config: LongBridgeRebalanceConfig, ma
return message


def _direct_live_routing_requires_durable_command(*, execution: dict, dry_run_only: bool) -> bool:
"""Fail closed when a direct live cycle carries a next-session decision.

The direct cycle has no durable command consumer, so it cannot safely hold
an immutable signal until its effective session. Paper previews remain
available for staged validation, but a live broker path must not route a
decision whose explicit effective date differs from its signal date.
"""
if dry_run_only:
return False
effective_date = str(execution.get("effective_date") or "").strip()
signal_date = str(execution.get("signal_date") or "").strip()
return bool(effective_date) and (not signal_date or effective_date != signal_date)


def _durable_command_required_message(*, execution: dict) -> str:
return (
"Direct live routing blocked because the strategy decision is not effective in the "
"signal session; a durable execution command and reconciliation path is required. "
f"signal_date={execution.get('signal_date') or ''} "
f"effective_date={execution.get('effective_date') or ''}"
)


def _should_record_execution_marker(*, result: ExecutionCycleResult, config: LongBridgeRebalanceConfig) -> bool:
if not getattr(config, "execution_dedup_enabled", False):
return False
Expand Down Expand Up @@ -296,9 +320,16 @@ def fetch_replanned_state():

execution_marker_key = _build_execution_marker_key(config=config, execution=execution)
execution_state_store = getattr(config, "execution_state_store", None)
execution_already_recorded = False
direct_live_routing_blocked = _direct_live_routing_requires_durable_command(
execution=execution,
dry_run_only=bool(getattr(config, "dry_run_only", False)),
)
if direct_live_routing_blocked:
execution["direct_live_routing_blocked"] = True
execution["direct_live_routing_block_reason"] = "durable_execution_command_required"
execution_already_recorded = direct_live_routing_blocked
execution_claim_acquired = False
if execution_marker_key and execution_state_store:
if not direct_live_routing_blocked and execution_marker_key and execution_state_store:
try:
execution_already_recorded = bool(execution_state_store.has_marker(execution_marker_key))
except Exception as exc:
Expand All @@ -325,7 +356,8 @@ def fetch_replanned_state():
)

if (
not execution_already_recorded
not direct_live_routing_blocked
and not execution_already_recorded
and execution_marker_key
and execution_state_store
and bool(getattr(config, "execution_dedup_enabled", False))
Expand All @@ -343,11 +375,15 @@ def fetch_replanned_state():
) from exc

if execution_already_recorded:
message = _execution_already_recorded_message(
config=config,
marker_key=execution_marker_key,
execution=execution,
)
if direct_live_routing_blocked:
message = _durable_command_required_message(execution=execution)
runtime.notify_issue("Next-session execution blocked", message)
else:
message = _execution_already_recorded_message(
config=config,
marker_key=execution_marker_key,
execution=execution,
)
print(config.with_prefix(message), flush=True)
execution_result = ExecutionCycleResult(
plan=plan,
Expand Down
65 changes: 64 additions & 1 deletion tests/test_rebalance_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def _build_plan(
exit_line=0.0,
cash_by_currency=None,
signal_date="2026-04-21",
effective_date="2026-04-22",
effective_date="2026-04-21",
execution_timing_contract="next_trading_day",
):
if dashboard_text is None:
Expand Down Expand Up @@ -1163,6 +1163,69 @@ def test_run_strategy_supports_execution_port_runtime_path(self):
self.assertEqual(len(sent_messages), 1)
self.assertIn("【订单待券商最终确认】", sent_messages[0])

def test_run_strategy_blocks_live_next_session_decision_without_routing(self):
alerts = []
plan = _build_plan(
strategy_symbols=("SOXL",),
risk_symbols=("SOXL",),
targets={"SOXL": 400.0},
market_values={"SOXL": 0.0},
sellable_quantities={"SOXL": 0},
quantities={"SOXL": 0},
current_min_trade=10.0,
trade_threshold_value=10.0,
investable_cash=500.0,
market_status="Risk on",
deploy_ratio_text="70.0%",
income_ratio_text="0.0%",
income_locked_ratio_text="0.0%",
signal_message="SOXL target",
available_cash=500.0,
total_strategy_equity=500.0,
portfolio_rows=(("SOXL",),),
signal_date="2026-07-17",
effective_date="2026-07-20",
)
result = rebalance_service.run_strategy(
runtime=LongBridgeRebalanceRuntime(
bootstrap=lambda: ("quote-context", "trade-context", {"trend": "ok"}),
resolve_rebalance_plan=lambda *, indicators, snapshot=None: plan,
market_data_port_factory=lambda _quote_context: CallableMarketDataPort(
quote_loader=lambda _symbol: (_ for _ in ()).throw(AssertionError("quote should not load"))
),
estimate_max_purchase_quantity=lambda *args, **kwargs: (_ for _ in ()).throw(
AssertionError("buy estimate should not run")
),
notifications=CallableNotificationPort(lambda _message: None),
notify_issue=lambda title, detail: alerts.append((title, detail)),
portfolio_port_factory=lambda _quote_context, _trade_context: CallablePortfolioPort(
lambda: _build_snapshot(plan)
),
execution_port_factory=lambda _trade_context: CallableExecutionPort(
lambda _order_intent: (_ for _ in ()).throw(AssertionError("order should not submit"))
),
),
config=LongBridgeRebalanceConfig(
limit_sell_discount=0.995,
limit_buy_premium=1.005,
separator="━━━━━━━━━━━━━━━━━━",
translator=build_translator("en"),
with_prefix=lambda message: f"[SG/LongBridgeQuant] {message}",
strategy_profile="soxl_soxx_trend_income",
strategy_display_name="SOXL/SOXX Semiconductor Trend Income",
dry_run_only=False,
notify_no_trade_cycles=False,
),
)

self.assertFalse(result.action_done)
self.assertTrue(result.execution["direct_live_routing_blocked"])
self.assertEqual(result.execution["direct_live_routing_block_reason"], "durable_execution_command_required")
self.assertEqual(len(alerts), 1)
self.assertEqual(alerts[0][0], "Next-session execution blocked")
self.assertIn("signal_date=2026-07-17", alerts[0][1])
self.assertIn("effective_date=2026-07-20", alerts[0][1])

def test_run_strategy_skips_when_execution_marker_already_exists(self):
sent_messages = []
checked_keys = []
Expand Down