|
| 1 | +"""Paper-only producer for immutable delayed-execution command evidence.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import hashlib |
| 6 | +import json |
| 7 | +from collections.abc import Mapping |
| 8 | +from typing import Any |
| 9 | + |
| 10 | +from quant_platform_kit.common.execution_commands import ( |
| 11 | + ExecutionCommand, |
| 12 | + ExecutionCommandStore, |
| 13 | + build_execution_command_store_from_env as _build_execution_command_store_from_env, |
| 14 | +) |
| 15 | + |
| 16 | + |
| 17 | +PAPER_EXECUTION_INTENT_SCHEMA_VERSION = "longbridge.paper-execution-intent.v1" |
| 18 | + |
| 19 | + |
| 20 | +def _canonical_json(value: Mapping[str, Any]) -> str: |
| 21 | + return json.dumps(dict(value), ensure_ascii=False, separators=(",", ":"), sort_keys=True) |
| 22 | + |
| 23 | + |
| 24 | +def _normalized_symbols(value: object) -> list[str]: |
| 25 | + if not isinstance(value, (list, tuple, set)): |
| 26 | + return [] |
| 27 | + return sorted({str(symbol or "").strip().upper() for symbol in value if str(symbol or "").strip()}) |
| 28 | + |
| 29 | + |
| 30 | +def _normalized_targets(value: object) -> dict[str, float]: |
| 31 | + if not isinstance(value, Mapping): |
| 32 | + return {} |
| 33 | + normalized: dict[str, float] = {} |
| 34 | + for symbol, target in value.items(): |
| 35 | + key = str(symbol or "").strip().upper() |
| 36 | + if not key: |
| 37 | + continue |
| 38 | + try: |
| 39 | + normalized[key] = float(target) |
| 40 | + except (TypeError, ValueError) as exc: |
| 41 | + raise ValueError(f"invalid paper execution target for {key}") from exc |
| 42 | + return {symbol: normalized[symbol] for symbol in sorted(normalized)} |
| 43 | + |
| 44 | + |
| 45 | +def build_paper_execution_command( |
| 46 | + *, |
| 47 | + platform: str, |
| 48 | + account_scope: str, |
| 49 | + strategy_profile: str, |
| 50 | + execution: Mapping[str, Any], |
| 51 | + allocation: Mapping[str, Any], |
| 52 | +) -> ExecutionCommand: |
| 53 | + """Bind one paper-only command to immutable timing and target intent.""" |
| 54 | + execution = dict(execution or {}) |
| 55 | + allocation = dict(allocation or {}) |
| 56 | + intent = { |
| 57 | + "schema_version": PAPER_EXECUTION_INTENT_SCHEMA_VERSION, |
| 58 | + "target_mode": str(allocation.get("target_mode") or "").strip(), |
| 59 | + "targets": _normalized_targets(allocation.get("targets")), |
| 60 | + "strategy_symbols": _normalized_symbols(allocation.get("strategy_symbols")), |
| 61 | + "risk_symbols": _normalized_symbols(allocation.get("risk_symbols")), |
| 62 | + "safe_haven_symbols": _normalized_symbols(allocation.get("safe_haven_symbols")), |
| 63 | + } |
| 64 | + intent_json = _canonical_json(intent) |
| 65 | + return ExecutionCommand.from_decision( |
| 66 | + platform=platform, |
| 67 | + account_scope=account_scope, |
| 68 | + strategy_profile=strategy_profile, |
| 69 | + execution_mode="paper", |
| 70 | + signal_date=execution.get("signal_date"), |
| 71 | + effective_date=execution.get("effective_date"), |
| 72 | + execution_timing_contract=execution.get("execution_timing_contract"), |
| 73 | + decision_digest=hashlib.sha256(intent_json.encode("utf-8")).hexdigest(), |
| 74 | + intent=intent, |
| 75 | + ) |
| 76 | + |
| 77 | + |
| 78 | +def enqueue_paper_execution_command( |
| 79 | + *, |
| 80 | + enabled: bool, |
| 81 | + dry_run_only: bool, |
| 82 | + store: ExecutionCommandStore | None, |
| 83 | + platform: str, |
| 84 | + account_scope: str, |
| 85 | + strategy_profile: str, |
| 86 | + execution: Mapping[str, Any], |
| 87 | + allocation: Mapping[str, Any], |
| 88 | +) -> dict[str, object] | None: |
| 89 | + """Create one command only; this phase never claims or routes it.""" |
| 90 | + if not enabled: |
| 91 | + return None |
| 92 | + if not dry_run_only: |
| 93 | + raise RuntimeError("durable execution command producer is paper-only") |
| 94 | + if store is None or (not store.cloud_prefix_uri and not store.local_dir): |
| 95 | + raise RuntimeError("paper durable execution command store is required") |
| 96 | + command = build_paper_execution_command( |
| 97 | + platform=platform, |
| 98 | + account_scope=account_scope, |
| 99 | + strategy_profile=strategy_profile, |
| 100 | + execution=execution, |
| 101 | + allocation=allocation, |
| 102 | + ) |
| 103 | + created = store.enqueue(command) |
| 104 | + return { |
| 105 | + "schema_version": "longbridge.paper-execution-command-observation.v1", |
| 106 | + "command_id": command.command_id, |
| 107 | + "decision_digest": command.decision_digest, |
| 108 | + "effective_date": command.effective_date, |
| 109 | + "status": "QUEUED" if created else "ALREADY_QUEUED", |
| 110 | + "consumer_authorized": False, |
| 111 | + } |
| 112 | + |
| 113 | + |
| 114 | +def build_execution_command_store_from_env( |
| 115 | + *, |
| 116 | + env_reader, |
| 117 | + gcp_project_id: str | None = None, |
| 118 | +) -> ExecutionCommandStore: |
| 119 | + return _build_execution_command_store_from_env( |
| 120 | + platform_env_prefix="LONGBRIDGE", |
| 121 | + env_reader=env_reader, |
| 122 | + project_id=gcp_project_id, |
| 123 | + ) |
| 124 | + |
| 125 | + |
| 126 | +def resolve_paper_execution_command_producer_enabled(*, env_reader, dry_run_only: bool) -> bool: |
| 127 | + raw_value = str(env_reader("LONGBRIDGE_DURABLE_EXECUTION_COMMAND_PAPER_ENABLED", "") or "").strip().lower() |
| 128 | + enabled = raw_value in {"1", "true", "t", "yes", "y", "on"} |
| 129 | + if enabled and not dry_run_only: |
| 130 | + raise RuntimeError("durable execution command producer is paper-only and cannot be enabled live") |
| 131 | + return enabled |
0 commit comments