|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Build a bounded, no-order lifecycle snapshot for one runtime target. |
| 3 | +
|
| 4 | +This contract intentionally tracks configured target state separately from |
| 5 | +execution evidence. A target disabled by policy is not an unavailable broker, |
| 6 | +and it must not be represented as a paper/live execution result. |
| 7 | +""" |
| 8 | + |
| 9 | +from __future__ import annotations |
| 10 | + |
| 11 | +import argparse |
| 12 | +import json |
| 13 | +import re |
| 14 | +from datetime import UTC, datetime |
| 15 | +from pathlib import Path |
| 16 | +from typing import Any, Mapping |
| 17 | + |
| 18 | + |
| 19 | +SOURCE_SCHEMA_VERSION = "qsl_runtime_target_lifecycle_source_snapshot.v1" |
| 20 | +PLATFORMS = frozenset({"alpaca", "binance", "firstrade", "ibkr", "longbridge", "qmt", "schwab"}) |
| 21 | +CONFIGURED_STATES = frozenset({"enabled", "disabled"}) |
| 22 | +EXECUTION_MODES = frozenset({"dry_run", "paper", "live"}) |
| 23 | +CHECK_STATUSES = frozenset({"pass", "attention", "not_due", "not_applicable", "unavailable"}) |
| 24 | +DISPOSITIONS = frozenset({"continue_enabled_monitoring", "continue_disabled_validation", "parked"}) |
| 25 | +REASON_CODES = frozenset( |
| 26 | + { |
| 27 | + "none", |
| 28 | + "target_intentionally_disabled", |
| 29 | + "runtime_guard_attention", |
| 30 | + "execution_heartbeat_attention", |
| 31 | + "monitoring_unavailable", |
| 32 | + } |
| 33 | +) |
| 34 | +_IDENTIFIER = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._=-]{0,127}$") |
| 35 | +_TIMESTAMP = re.compile(r"^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$") |
| 36 | + |
| 37 | + |
| 38 | +class RuntimeTargetLifecycleError(ValueError): |
| 39 | + """Raised when a lifecycle snapshot would be ambiguous or unsafe.""" |
| 40 | + |
| 41 | + |
| 42 | +def _identifier(value: object, field: str) -> str: |
| 43 | + text = str(value or "").strip() |
| 44 | + if not _IDENTIFIER.fullmatch(text): |
| 45 | + raise RuntimeTargetLifecycleError(f"{field} must be a stable non-sensitive identifier") |
| 46 | + return text |
| 47 | + |
| 48 | + |
| 49 | +def _choice(value: object, choices: frozenset[str], field: str) -> str: |
| 50 | + text = str(value or "").strip() |
| 51 | + if text not in choices: |
| 52 | + raise RuntimeTargetLifecycleError(f"{field} is unsupported") |
| 53 | + return text |
| 54 | + |
| 55 | + |
| 56 | +def _timestamp(value: object | None) -> str: |
| 57 | + if value is None: |
| 58 | + return datetime.now(UTC).replace(microsecond=0).isoformat().replace("+00:00", "Z") |
| 59 | + text = str(value).strip() |
| 60 | + if not _TIMESTAMP.fullmatch(text): |
| 61 | + raise RuntimeTargetLifecycleError("observed_at must be an RFC3339 UTC timestamp") |
| 62 | + try: |
| 63 | + datetime.strptime(text, "%Y-%m-%dT%H:%M:%SZ") |
| 64 | + except ValueError as exc: |
| 65 | + raise RuntimeTargetLifecycleError("observed_at must be a valid calendar timestamp") from exc |
| 66 | + return text |
| 67 | + |
| 68 | + |
| 69 | +def _target_disposition( |
| 70 | + *, |
| 71 | + configured_state: str, |
| 72 | + runtime_guard: str, |
| 73 | + execution_heartbeat: str, |
| 74 | +) -> tuple[str, str]: |
| 75 | + if runtime_guard == "attention": |
| 76 | + return "parked", "runtime_guard_attention" |
| 77 | + if execution_heartbeat == "attention": |
| 78 | + return "parked", "execution_heartbeat_attention" |
| 79 | + if runtime_guard == "unavailable" or execution_heartbeat == "unavailable": |
| 80 | + return "parked", "monitoring_unavailable" |
| 81 | + if configured_state == "disabled": |
| 82 | + if execution_heartbeat != "not_applicable": |
| 83 | + raise RuntimeTargetLifecycleError( |
| 84 | + "disabled targets require a not_applicable execution heartbeat" |
| 85 | + ) |
| 86 | + return "continue_disabled_validation", "target_intentionally_disabled" |
| 87 | + if runtime_guard not in {"pass", "not_due"} or execution_heartbeat not in {"pass", "not_due"}: |
| 88 | + raise RuntimeTargetLifecycleError("enabled target monitoring state is incomplete") |
| 89 | + return "continue_enabled_monitoring", "none" |
| 90 | + |
| 91 | + |
| 92 | +def build_runtime_target_lifecycle_source_snapshot( |
| 93 | + *, |
| 94 | + source_id: object, |
| 95 | + target_id: object, |
| 96 | + platform: object, |
| 97 | + configured_state: object, |
| 98 | + execution_mode: object, |
| 99 | + runtime_guard: object, |
| 100 | + execution_heartbeat: object, |
| 101 | + observed_at: object | None = None, |
| 102 | +) -> dict[str, Any]: |
| 103 | + """Create one sanitized target state record without execution authority.""" |
| 104 | + normalized_source_id = _identifier(source_id, "source_id") |
| 105 | + normalized_target_id = _identifier(target_id, "target_id") |
| 106 | + normalized_platform = _choice(platform, PLATFORMS, "platform") |
| 107 | + normalized_state = _choice(configured_state, CONFIGURED_STATES, "configured_state") |
| 108 | + normalized_mode = _choice(execution_mode, EXECUTION_MODES, "execution_mode") |
| 109 | + normalized_guard = _choice(runtime_guard, CHECK_STATUSES, "runtime_guard") |
| 110 | + normalized_heartbeat = _choice(execution_heartbeat, CHECK_STATUSES, "execution_heartbeat") |
| 111 | + disposition, reason_code = _target_disposition( |
| 112 | + configured_state=normalized_state, |
| 113 | + runtime_guard=normalized_guard, |
| 114 | + execution_heartbeat=normalized_heartbeat, |
| 115 | + ) |
| 116 | + timestamp = _timestamp(observed_at) |
| 117 | + return { |
| 118 | + "schema_version": SOURCE_SCHEMA_VERSION, |
| 119 | + "source_id": normalized_source_id, |
| 120 | + "generated_at": timestamp, |
| 121 | + "computed_at": timestamp, |
| 122 | + "data_status": "ready", |
| 123 | + "targets": [ |
| 124 | + { |
| 125 | + "target_id": normalized_target_id, |
| 126 | + "target": { |
| 127 | + "platform": normalized_platform, |
| 128 | + "configured_state": normalized_state, |
| 129 | + "execution_mode": normalized_mode, |
| 130 | + }, |
| 131 | + "monitoring": { |
| 132 | + "runtime_guard": normalized_guard, |
| 133 | + "execution_heartbeat": normalized_heartbeat, |
| 134 | + }, |
| 135 | + "disposition": {"code": disposition, "reason_code": reason_code}, |
| 136 | + "no_order": True, |
| 137 | + } |
| 138 | + ], |
| 139 | + "errors": [], |
| 140 | + } |
| 141 | + |
| 142 | + |
| 143 | +def _parse_args(argv: list[str] | None = None) -> argparse.Namespace: |
| 144 | + parser = argparse.ArgumentParser(description=__doc__) |
| 145 | + parser.add_argument("--source-id", required=True) |
| 146 | + parser.add_argument("--target-id", required=True) |
| 147 | + parser.add_argument("--platform", required=True) |
| 148 | + parser.add_argument("--configured-state", required=True, choices=sorted(CONFIGURED_STATES)) |
| 149 | + parser.add_argument("--execution-mode", required=True, choices=sorted(EXECUTION_MODES)) |
| 150 | + parser.add_argument("--runtime-guard", required=True, choices=sorted(CHECK_STATUSES)) |
| 151 | + parser.add_argument("--execution-heartbeat", required=True, choices=sorted(CHECK_STATUSES)) |
| 152 | + parser.add_argument("--observed-at") |
| 153 | + parser.add_argument("--output", required=True) |
| 154 | + return parser.parse_args(argv) |
| 155 | + |
| 156 | + |
| 157 | +def main(argv: list[str] | None = None) -> int: |
| 158 | + args = _parse_args(argv) |
| 159 | + snapshot = build_runtime_target_lifecycle_source_snapshot( |
| 160 | + source_id=args.source_id, |
| 161 | + target_id=args.target_id, |
| 162 | + platform=args.platform, |
| 163 | + configured_state=args.configured_state, |
| 164 | + execution_mode=args.execution_mode, |
| 165 | + runtime_guard=args.runtime_guard, |
| 166 | + execution_heartbeat=args.execution_heartbeat, |
| 167 | + observed_at=args.observed_at, |
| 168 | + ) |
| 169 | + output = Path(args.output) |
| 170 | + output.parent.mkdir(parents=True, exist_ok=True) |
| 171 | + output.write_text(json.dumps(snapshot, ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8") |
| 172 | + return 0 |
| 173 | + |
| 174 | + |
| 175 | +if __name__ == "__main__": |
| 176 | + raise SystemExit(main()) |
0 commit comments