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
131 changes: 131 additions & 0 deletions application/durable_execution_commands.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
"""Paper-only producer for immutable delayed-execution command evidence."""

from __future__ import annotations

import hashlib
import json
from collections.abc import Mapping
from typing import Any

from quant_platform_kit.common.execution_commands import (
ExecutionCommand,
ExecutionCommandStore,
build_execution_command_store_from_env as _build_execution_command_store_from_env,
)


PAPER_EXECUTION_INTENT_SCHEMA_VERSION = "longbridge.paper-execution-intent.v1"


def _canonical_json(value: Mapping[str, Any]) -> str:
return json.dumps(dict(value), ensure_ascii=False, separators=(",", ":"), sort_keys=True)


def _normalized_symbols(value: object) -> list[str]:
if not isinstance(value, (list, tuple, set)):
return []
return sorted({str(symbol or "").strip().upper() for symbol in value if str(symbol or "").strip()})


def _normalized_targets(value: object) -> dict[str, float]:
if not isinstance(value, Mapping):
return {}
normalized: dict[str, float] = {}
for symbol, target in value.items():
key = str(symbol or "").strip().upper()
if not key:
continue
try:
normalized[key] = float(target)
except (TypeError, ValueError) as exc:
raise ValueError(f"invalid paper execution target for {key}") from exc
return {symbol: normalized[symbol] for symbol in sorted(normalized)}


def build_paper_execution_command(
*,
platform: str,
account_scope: str,
strategy_profile: str,
execution: Mapping[str, Any],
allocation: Mapping[str, Any],
) -> ExecutionCommand:
"""Bind one paper-only command to immutable timing and target intent."""
execution = dict(execution or {})
allocation = dict(allocation or {})
intent = {
"schema_version": PAPER_EXECUTION_INTENT_SCHEMA_VERSION,
"target_mode": str(allocation.get("target_mode") or "").strip(),
"targets": _normalized_targets(allocation.get("targets")),
"strategy_symbols": _normalized_symbols(allocation.get("strategy_symbols")),
"risk_symbols": _normalized_symbols(allocation.get("risk_symbols")),
"safe_haven_symbols": _normalized_symbols(allocation.get("safe_haven_symbols")),
}
intent_json = _canonical_json(intent)
return ExecutionCommand.from_decision(
platform=platform,
account_scope=account_scope,
strategy_profile=strategy_profile,
execution_mode="paper",
signal_date=execution.get("signal_date"),
effective_date=execution.get("effective_date"),
execution_timing_contract=execution.get("execution_timing_contract"),
decision_digest=hashlib.sha256(intent_json.encode("utf-8")).hexdigest(),
intent=intent,
)


def enqueue_paper_execution_command(
*,
enabled: bool,
dry_run_only: bool,
store: ExecutionCommandStore | None,
platform: str,
account_scope: str,
strategy_profile: str,
execution: Mapping[str, Any],
allocation: Mapping[str, Any],
) -> dict[str, object] | None:
"""Create one command only; this phase never claims or routes it."""
if not enabled:
return None
if not dry_run_only:
raise RuntimeError("durable execution command producer is paper-only")
if store is None or (not store.cloud_prefix_uri and not store.local_dir):
raise RuntimeError("paper durable execution command store is required")
command = build_paper_execution_command(
platform=platform,
account_scope=account_scope,
strategy_profile=strategy_profile,
execution=execution,
allocation=allocation,
)
created = store.enqueue(command)
return {
"schema_version": "longbridge.paper-execution-command-observation.v1",
"command_id": command.command_id,
"decision_digest": command.decision_digest,
"effective_date": command.effective_date,
"status": "QUEUED" if created else "ALREADY_QUEUED",
"consumer_authorized": False,
}


def build_execution_command_store_from_env(
*,
env_reader,
gcp_project_id: str | None = None,
) -> ExecutionCommandStore:
return _build_execution_command_store_from_env(
platform_env_prefix="LONGBRIDGE",
env_reader=env_reader,
project_id=gcp_project_id,
)


def resolve_paper_execution_command_producer_enabled(*, env_reader, dry_run_only: bool) -> bool:
raw_value = str(env_reader("LONGBRIDGE_DURABLE_EXECUTION_COMMAND_PAPER_ENABLED", "") or "").strip().lower()
enabled = raw_value in {"1", "true", "t", "yes", "y", "on"}
if enabled and not dry_run_only:
raise RuntimeError("durable execution command producer is paper-only and cannot be enabled live")
return enabled
13 changes: 13 additions & 0 deletions application/rebalance_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

from application.execution_service import ExecutionCycleResult, execute_rebalance_cycle
from application.execution_state import build_execution_marker_key
from application.durable_execution_commands import enqueue_paper_execution_command
from application.runtime_dependencies import LongBridgeRebalanceConfig, LongBridgeRebalanceRuntime
from quant_platform_kit.longbridge.market_data import fetch_lot_sizes
from application.signal_snapshot import build_signal_snapshot
Expand Down Expand Up @@ -317,6 +318,18 @@ def fetch_replanned_state():
return load_plan(current_snapshot=current_snapshot)

plan, portfolio, execution, allocation = fetch_replanned_state()
paper_command_observation = enqueue_paper_execution_command(
enabled=bool(getattr(config, "durable_execution_command_paper_enabled", False)),
dry_run_only=bool(getattr(config, "dry_run_only", False)),
store=getattr(config, "execution_command_store", None),
platform="longbridge",
account_scope=str(getattr(config, "execution_state_account_scope", "") or "unknown"),
strategy_profile=str(getattr(config, "strategy_profile", "") or "unknown"),
execution=execution,
allocation=allocation,
)
if paper_command_observation is not None:
execution["durable_execution_command"] = paper_command_observation

execution_marker_key = _build_execution_marker_key(config=config, execution=execution)
execution_state_store = getattr(config, "execution_state_store", None)
Expand Down
12 changes: 12 additions & 0 deletions application/runtime_composer.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@
build_execution_marker_store_from_env,
resolve_execution_dedup_enabled,
)
from application.durable_execution_commands import (
build_execution_command_store_from_env,
resolve_paper_execution_command_producer_enabled,
)
from application.runtime_notification_adapters import build_runtime_notification_adapters
from application.runtime_reporting_adapters import build_runtime_reporting_adapters
from quant_platform_kit.common.port_adapters import CallableNotificationPort
Expand Down Expand Up @@ -264,6 +268,14 @@ def build_rebalance_config(
gcp_project_id=self.project_id,
),
execution_state_account_scope=self.account_region,
durable_execution_command_paper_enabled=resolve_paper_execution_command_producer_enabled(
env_reader=self.env_reader,
dry_run_only=self.dry_run_only,
),
execution_command_store=build_execution_command_store_from_env(
env_reader=self.env_reader,
gcp_project_id=self.project_id,
),
)

def load_strategy_plugin_signals(self, raw_mounts):
Expand Down
2 changes: 2 additions & 0 deletions application/runtime_dependencies.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ class LongBridgeRebalanceConfig:
execution_dedup_enabled: bool = False
execution_state_store: Any = None
execution_state_account_scope: str = ""
durable_execution_command_paper_enabled: bool = False
execution_command_store: Any = None


@dataclass(frozen=True)
Expand Down
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ dependencies = [
"google-cloud-storage",
"google-auth",
"longport==3.0.23",
"quant-platform-kit @ git+https://github.com/QuantStrategyLab/QuantPlatformKit.git@68fcad8c68ab48a1109d99715f8315af449de493",
"quant-platform-kit @ git+https://github.com/QuantStrategyLab/QuantPlatformKit.git@0393349dabad79de60fdfed6c3580c8193ed9789",
"us-equity-strategies @ git+https://github.com/QuantStrategyLab/UsEquityStrategies.git@291033051fec86586eab223142e5b5b2532a43b5",
"hk-equity-strategies @ git+https://github.com/QuantStrategyLab/HkEquityStrategies.git@63a3a4e96b1fb2e64b62ef70ff9057496f49ae9c",
]
Expand Down Expand Up @@ -61,5 +61,5 @@ include = [

[tool.uv]
override-dependencies = [
"quant-platform-kit @ git+https://github.com/QuantStrategyLab/QuantPlatformKit.git@68fcad8c68ab48a1109d99715f8315af449de493",
"quant-platform-kit @ git+https://github.com/QuantStrategyLab/QuantPlatformKit.git@0393349dabad79de60fdfed6c3580c8193ed9789",
]
2 changes: 1 addition & 1 deletion qsl.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ upgrade_ring = "ring_d"
allow_legacy = false

[qsl.requires]
quant_platform_kit = "68fcad8c68ab48a1109d99715f8315af449de493"
quant_platform_kit = "0393349dabad79de60fdfed6c3580c8193ed9789"
us_equity_strategies = "291033051fec86586eab223142e5b5b2532a43b5"
hk_equity_strategies = "63a3a4e96b1fb2e64b62ef70ff9057496f49ae9c"

Expand Down
108 changes: 108 additions & 0 deletions tests/test_durable_execution_commands.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
from __future__ import annotations

import sys
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))

from application.durable_execution_commands import ( # noqa: E402
build_paper_execution_command,
enqueue_paper_execution_command,
resolve_paper_execution_command_producer_enabled,
)


def _execution() -> dict[str, object]:
return {
"signal_date": "2026-07-17",
"effective_date": "2026-07-20",
"execution_timing_contract": "next_trading_day",
}


def _allocation() -> dict[str, object]:
return {
"target_mode": "value",
"targets": {"SOXL": 350.0, "BOXX": 150.0},
"strategy_symbols": ("SOXL", "BOXX"),
"risk_symbols": ("SOXL",),
"safe_haven_symbols": ("BOXX",),
}


def test_paper_command_is_content_addressed_and_excludes_broker_authority() -> None:
first = build_paper_execution_command(
platform="longbridge",
account_scope="PAPER",
strategy_profile="soxl_soxx_trend_income",
execution=_execution(),
allocation=_allocation(),
)
second = build_paper_execution_command(
platform="longbridge",
account_scope="PAPER",
strategy_profile="soxl_soxx_trend_income",
execution=_execution(),
allocation=_allocation(),
)

assert first.command_id == second.command_id
assert first.execution_mode == "paper"
assert first.effective_date == "2026-07-20"
assert first.intent == {
"schema_version": "longbridge.paper-execution-intent.v1",
"target_mode": "value",
"targets": {"BOXX": 150.0, "SOXL": 350.0},
"strategy_symbols": ["BOXX", "SOXL"],
"risk_symbols": ["SOXL"],
"safe_haven_symbols": ["BOXX"],
}


def test_paper_producer_enqueues_once_and_never_authorizes_consumer() -> None:
observed = []

class Store:
cloud_prefix_uri = "gs://paper/commands"
local_dir = None

def enqueue(self, command):
observed.append(command)
return len(observed) == 1

kwargs = {
"enabled": True,
"dry_run_only": True,
"store": Store(),
"platform": "longbridge",
"account_scope": "PAPER",
"strategy_profile": "soxl_soxx_trend_income",
"execution": _execution(),
"allocation": _allocation(),
}
first = enqueue_paper_execution_command(**kwargs)
second = enqueue_paper_execution_command(**kwargs)

assert first and first["status"] == "QUEUED"
assert second and second["status"] == "ALREADY_QUEUED"
assert first["consumer_authorized"] is False
assert len(observed) == 2


def test_paper_producer_rejects_live_enablement() -> None:
assert resolve_paper_execution_command_producer_enabled(
env_reader=lambda _name, _default="": "true",
dry_run_only=True,
)
try:
resolve_paper_execution_command_producer_enabled(
env_reader=lambda _name, _default="": "true",
dry_run_only=False,
)
except RuntimeError as exc:
assert "paper-only" in str(exc)
else: # pragma: no cover
raise AssertionError("live enablement must fail closed")
17 changes: 16 additions & 1 deletion tests/test_rebalance_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -1380,6 +1380,7 @@ def record_marker(self, *_args, **_kwargs):
def test_run_strategy_records_execution_marker_after_dry_run_order_preview(self):
sent_messages = []
recorded_markers = []
queued_commands = []
plan = _build_plan(
strategy_symbols=("BOXX",),
safe_haven_symbols=("BOXX",),
Expand Down Expand Up @@ -1409,7 +1410,15 @@ def has_marker(self, _marker_key):
def record_marker(self, marker_key, *, metadata=None):
recorded_markers.append((marker_key, dict(metadata or {})))

rebalance_service.run_strategy(
class CommandStore:
cloud_prefix_uri = "gs://paper/commands"
local_dir = None

def enqueue(self, command):
queued_commands.append(command)
return True

result = rebalance_service.run_strategy(
runtime=LongBridgeRebalanceRuntime(
bootstrap=lambda: ("quote-context", "trade-context", {"trend": "ok"}),
resolve_rebalance_plan=lambda *, indicators, snapshot=None, account_state=None: plan,
Expand Down Expand Up @@ -1442,6 +1451,8 @@ def record_marker(self, marker_key, *, metadata=None):
execution_dedup_enabled=True,
execution_state_store=FakeStore(),
execution_state_account_scope="PAPER",
durable_execution_command_paper_enabled=True,
execution_command_store=CommandStore(),
),
)

Expand All @@ -1450,6 +1461,10 @@ def record_marker(self, marker_key, *, metadata=None):
self.assertEqual(len(recorded_markers), 1)
self.assertIn("2026-06-01", recorded_markers[0][0])
self.assertTrue(recorded_markers[0][1]["dry_run_only"])
self.assertEqual(len(queued_commands), 1)
self.assertEqual(queued_commands[0].effective_date, "2026-06-02")
self.assertEqual(result.execution["durable_execution_command"]["status"], "QUEUED")
self.assertFalse(result.execution["durable_execution_command"]["consumer_authorized"])

def test_append_status_lines_localizes_snapshot_guard_text_for_zh(self):
lines = []
Expand Down
6 changes: 3 additions & 3 deletions uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.