|
| 1 | +"""Fail-closed, opt-in PAPER admission for Firstrade dry-run requests. |
| 2 | +
|
| 3 | +The shared QPK contract verifies an immutable execution command, its embedded |
| 4 | +deterministic-risk receipt, and the release currently loaded by the runtime. |
| 5 | +This adapter intentionally only turns that pure result into a redacted HTTP |
| 6 | +audit record. It neither creates commands nor reaches a broker, account, |
| 7 | +strategy, deployment, scheduler, or persistence service. |
| 8 | +""" |
| 9 | + |
| 10 | +from __future__ import annotations |
| 11 | + |
| 12 | +import json |
| 13 | +from collections.abc import Mapping |
| 14 | + |
| 15 | +from quant_platform_kit.common.execution_commands import ExecutionCommand |
| 16 | +from quant_platform_kit.common.paper_execution_admission import ( |
| 17 | + PaperExecutionAdmissionDecision, |
| 18 | + evaluate_paper_execution_admission, |
| 19 | +) |
| 20 | + |
| 21 | + |
| 22 | +PAPER_ADMISSION_ENABLED_ENV = "QSL_PAPER_ADMISSION_ENABLED" |
| 23 | +PAPER_EXECUTION_COMMAND_ENV = "QSL_PAPER_EXECUTION_COMMAND_JSON" |
| 24 | +PAPER_EXECUTION_ADMISSION_AUDIT_SCHEMA_VERSION = "firstrade_paper_execution_admission_audit.v1" |
| 25 | + |
| 26 | +_TRUE_VALUES = frozenset({"1", "true", "yes", "on"}) |
| 27 | +_FALSE_VALUES = frozenset({"", "0", "false", "no", "off"}) |
| 28 | +_COMMAND_MISSING = "paper_execution_command_missing" |
| 29 | +_COMMAND_INVALID = "paper_execution_command_invalid" |
| 30 | +_PLATFORM_MISMATCH = "paper_execution_platform_mismatch" |
| 31 | +_ADMISSION_CONFIGURATION_INVALID = "paper_execution_admission_configuration_invalid" |
| 32 | +_ADMISSION_EVALUATION_FAILED = "paper_execution_admission_evaluation_failed" |
| 33 | +_RUNTIME_MODE_INVALID = "paper_runtime_mode_invalid" |
| 34 | + |
| 35 | + |
| 36 | +def paper_dry_run_admission_requested(env: Mapping[str, str | None]) -> bool: |
| 37 | + """Return whether this request should be checked instead of using legacy dry-run. |
| 38 | +
|
| 39 | + The default is disabled. A malformed non-empty enable value is treated as |
| 40 | + requested so the caller receives a fail-closed audit rather than silently |
| 41 | + falling back to the ungated legacy preview path. |
| 42 | + """ |
| 43 | + raw_value = env.get(PAPER_ADMISSION_ENABLED_ENV) |
| 44 | + if raw_value is None: |
| 45 | + return False |
| 46 | + return str(raw_value).strip().lower() not in _FALSE_VALUES |
| 47 | + |
| 48 | + |
| 49 | +def _enabled(env: Mapping[str, str | None]) -> bool: |
| 50 | + return str(env.get(PAPER_ADMISSION_ENABLED_ENV) or "").strip().lower() in _TRUE_VALUES |
| 51 | + |
| 52 | + |
| 53 | +def _audit( |
| 54 | + *, |
| 55 | + disposition: str, |
| 56 | + findings: tuple[str, ...] | list[str], |
| 57 | + command_id: str | None = None, |
| 58 | + receipt_sha256: str | None = None, |
| 59 | +) -> dict[str, object]: |
| 60 | + admitted = disposition == "allow_new_risk" and not findings |
| 61 | + return { |
| 62 | + "schema_version": PAPER_EXECUTION_ADMISSION_AUDIT_SCHEMA_VERSION, |
| 63 | + "admission_enabled": True, |
| 64 | + "audit_color": "green" if admitted else "red", |
| 65 | + "status": "admitted" if admitted else "blocked", |
| 66 | + "command_id": command_id, |
| 67 | + "disposition": disposition, |
| 68 | + "integrity_findings": list(findings), |
| 69 | + "receipt_sha256": receipt_sha256, |
| 70 | + } |
| 71 | + |
| 72 | + |
| 73 | +def _audit_from_decision(decision: PaperExecutionAdmissionDecision) -> dict[str, object]: |
| 74 | + """Return only QPK's stable decision metadata, never raw command intent.""" |
| 75 | + return _audit( |
| 76 | + disposition=decision.disposition.value, |
| 77 | + findings=decision.integrity_findings, |
| 78 | + command_id=decision.command_id, |
| 79 | + receipt_sha256=decision.receipt_sha256, |
| 80 | + ) |
| 81 | + |
| 82 | + |
| 83 | +def evaluate_paper_dry_run_admission( |
| 84 | + *, |
| 85 | + runtime_target: object | None, |
| 86 | + env: Mapping[str, str | None], |
| 87 | +) -> dict[str, object] | None: |
| 88 | + """Evaluate an optional QPK PAPER admission before any preview can start. |
| 89 | +
|
| 90 | + ``None`` preserves the existing dry-run route while the feature is disabled. |
| 91 | + Once requested, every malformed or incomplete input produces a red audit |
| 92 | + record and the caller must avoid invoking the strategy cycle. |
| 93 | + """ |
| 94 | + if not paper_dry_run_admission_requested(env): |
| 95 | + return None |
| 96 | + if not _enabled(env): |
| 97 | + return _audit( |
| 98 | + disposition="halted", |
| 99 | + findings=(_ADMISSION_CONFIGURATION_INVALID,), |
| 100 | + ) |
| 101 | + |
| 102 | + raw_command = env.get(PAPER_EXECUTION_COMMAND_ENV) |
| 103 | + if not raw_command: |
| 104 | + return _audit(disposition="halted", findings=(_COMMAND_MISSING,)) |
| 105 | + try: |
| 106 | + payload = json.loads(raw_command) |
| 107 | + if not isinstance(payload, Mapping): |
| 108 | + raise ValueError("command payload must be an object") |
| 109 | + command = ExecutionCommand.from_dict(payload) |
| 110 | + except (TypeError, ValueError, json.JSONDecodeError): |
| 111 | + return _audit(disposition="halted", findings=(_COMMAND_INVALID,)) |
| 112 | + |
| 113 | + if command.platform != "firstrade": |
| 114 | + return _audit( |
| 115 | + disposition="halted", |
| 116 | + findings=(_PLATFORM_MISMATCH,), |
| 117 | + command_id=command.command_id, |
| 118 | + ) |
| 119 | + if getattr(runtime_target, "dry_run_only", None) is not True: |
| 120 | + return _audit( |
| 121 | + disposition="halted", |
| 122 | + findings=(_RUNTIME_MODE_INVALID,), |
| 123 | + command_id=command.command_id, |
| 124 | + ) |
| 125 | + expected_release = getattr(runtime_target, "strategy_release", None) |
| 126 | + try: |
| 127 | + decision = evaluate_paper_execution_admission( |
| 128 | + command=command, |
| 129 | + expected_strategy_release=expected_release, |
| 130 | + ) |
| 131 | + except (TypeError, ValueError): |
| 132 | + return _audit( |
| 133 | + disposition="halted", |
| 134 | + findings=(_ADMISSION_EVALUATION_FAILED,), |
| 135 | + command_id=command.command_id, |
| 136 | + ) |
| 137 | + return _audit_from_decision(decision) |
| 138 | + |
| 139 | + |
| 140 | +__all__ = [ |
| 141 | + "PAPER_ADMISSION_ENABLED_ENV", |
| 142 | + "PAPER_EXECUTION_ADMISSION_AUDIT_SCHEMA_VERSION", |
| 143 | + "PAPER_EXECUTION_COMMAND_ENV", |
| 144 | + "evaluate_paper_dry_run_admission", |
| 145 | + "paper_dry_run_admission_requested", |
| 146 | +] |
0 commit comments