Coverage for execution/field_test.py: 100%

70 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""The field test without a broker (V6.6.5, #351): drive the safety paths of a real `main.py` in Lean's paper brokerage, 

2and judge what the run recorded. 

3 

4A field test needs three keys turned at once: `phase_v2.diagnostics.field_test.enabled: true` in the run's config, the 

5environment variable `AQ_FIELD_TEST=1` in its container, and a runtime mode that can never reach real money (`paper` or 

6`observation`, with `allow_live_orders` false). Then: 

7 

8- **At `order_after_bars`:** it hands `target_weights` to the target-weights path's own `_apply_target_row`, standing in 

9 for the decision a weekday's equity close would bring. 

10- **From `drift_after_bars`:** it adds `drift_weight` of `drift_symbol` to the holdings reconciliation reads. 

11- **From `shock_after_bars`:** it reports a drawdown velocity above the kill switch's limit. 

12 

13Everything else is the real code path: the orders, the paper brokerage's fills, the trip, the flatten, the audit chain, 

14restarts and outages. `main.py` writes `FIELD_TEST ...` lines to the engine log (`field_test_log_line`), and 

15`judge_field_test` turns the run's evidence into pass/fail checks. It proves plumbing, never edge. 

16""" 

17 

18from __future__ import annotations 

19 

20from collections.abc import Mapping, Sequence 

21from dataclasses import dataclass 

22from typing import Any 

23 

24__all__ = [ 

25 "FieldTestPlan", "CHECKS", "LOG_PREFIX", "resolve_field_test_plan", "field_test_allowed", "field_test_target", "inject_metrics", 

26 "inject_reconciliation_drift", "field_test_log_line", "parse_field_test_log", "judge_field_test", 

27] 

28LOG_PREFIX = "FIELD_TEST" 

29 

30CHECKS: tuple[str, ...] = ( 

31 "orders_submitted", "orders_filled", "kill_switch_tripped", "flat_after_trip", "reconciliation_breach_detected", "restart_restored", 

32 "outages_survived", "audit_chain_valid", "accounts_isolated", 

33) 

34 

35 

36@dataclass(frozen=True) 

37class FieldTestPlan: 

38 """When and how hard to push. Bars count from the algorithm's first `on_data`.""" 

39 

40 enabled: bool = False 

41 shock_after_bars: int = 0 

42 drawdown_shock_pct: float = 0.0 

43 drift_after_bars: int = 0 

44 drift_symbol: str = "" 

45 drift_weight: float = 0.0 

46 order_after_bars: int = 0 

47 target_weights: tuple[tuple[str, float], ...] = () 

48 

49 

50def resolve_field_test_plan(raw: Mapping[str, Any] | None) -> FieldTestPlan: 

51 """The plan from `phase_v2.diagnostics.field_test`; absent or malformed means disabled.""" 

52 if not isinstance(raw, Mapping) or not raw.get("enabled"): 

53 return FieldTestPlan() 

54 try: 

55 weights = raw.get("target_weights") or {} 

56 return FieldTestPlan( 

57 enabled=True, shock_after_bars=max(int(raw.get("shock_after_bars", 0)), 0), drawdown_shock_pct=float(raw.get("drawdown_shock_pct", 0.0)), 

58 drift_after_bars=max(int(raw.get("drift_after_bars", 0)), 0), drift_symbol=str(raw.get("drift_symbol", "")), drift_weight=float(raw.get("drift_weight", 0.0)), 

59 order_after_bars=max(int(raw.get("order_after_bars", 0)), 0), 

60 target_weights=tuple(sorted((str(ticker), float(weight)) for ticker, weight in dict(weights).items())), 

61 ) 

62 except (TypeError, ValueError): 

63 return FieldTestPlan() 

64 

65 

66PAPER_BROKERAGE = "lean_paper_brokerage" 

67 

68 

69def field_test_allowed(plan: FieldTestPlan, *, runtime_mode: str, paper_brokerage: str, env_flag: str | None) -> bool: 

70 """True only for an enabled plan, `AQ_FIELD_TEST=1`, and a run that cannot reach real money: observation (no orders at all), 

71 or paper on Lean's own paper brokerage (`phase_v2.paper_trading.brokerage`). Never live, whatever else is set.""" 

72 if not plan.enabled or env_flag != "1": 

73 return False 

74 return runtime_mode == "observation" or (runtime_mode == "paper" and str(paper_brokerage).strip() == PAPER_BROKERAGE) 

75 

76 

77def field_test_target(plan: FieldTestPlan, bar_index: int) -> dict[str, float] | None: 

78 """The target row to apply on exactly bar `order_after_bars`, else None (one decision per run).""" 

79 if not plan.enabled or not plan.target_weights or plan.order_after_bars <= 0 or bar_index != plan.order_after_bars: 

80 return None 

81 return dict(plan.target_weights) 

82 

83 

84def field_test_log_line(event: str, bar_index: int, **fields: object) -> str: 

85 """`FIELD_TEST event=<event> bar=<n> key=value ...`: one engine-log line the report parses.""" 

86 extra = " ".join(f"{key}={value}" for key, value in sorted(fields.items())) 

87 return f"{LOG_PREFIX} event={event} bar={int(bar_index)}" + (f" {extra}" if extra else "") 

88 

89 

90def parse_field_test_log(text: str) -> list[dict[str, str]]: 

91 """Every `FIELD_TEST` line of an engine log as a dict of its fields.""" 

92 events = [] 

93 for line in text.splitlines(): 

94 index = line.find(LOG_PREFIX + " ") 

95 if index < 0: 

96 continue 

97 fields = dict(part.split("=", 1) for part in line[index + len(LOG_PREFIX) + 1:].split() if "=" in part) 

98 if "event" in fields: 

99 events.append(fields) 

100 return events 

101 

102 

103def inject_metrics(runtime_metrics: Mapping[str, Any], plan: FieldTestPlan, bar_index: int) -> dict[str, Any]: 

104 """The kill switch's inputs, with the drawdown shock from `shock_after_bars` on (a copy; the input is not touched).""" 

105 out = dict(runtime_metrics) 

106 if plan.enabled and plan.drawdown_shock_pct > 0.0 and bar_index >= plan.shock_after_bars > 0: 

107 current = out.get("drawdown_velocity_pct_per_bar") 

108 out["drawdown_velocity_pct_per_bar"] = max(float(current) if isinstance(current, (int, float)) else 0.0, float(plan.drawdown_shock_pct)) 

109 out["field_test_injected"] = True 

110 return out 

111 

112 

113def inject_reconciliation_drift(actual_by_symbol: Mapping[str, float], plan: FieldTestPlan, bar_index: int) -> dict[str, float]: 

114 """The holdings reconciliation compares, with the drift from `drift_after_bars` on (a copy).""" 

115 out = {str(key): float(value) for key, value in actual_by_symbol.items()} 

116 if plan.enabled and plan.drift_symbol and plan.drift_weight and bar_index >= plan.drift_after_bars > 0: 

117 out[plan.drift_symbol] = out.get(plan.drift_symbol, 0.0) + float(plan.drift_weight) 

118 return out 

119 

120 

121def _check(passed: bool | None, detail: str) -> dict[str, Any]: 

122 return {"pass": bool(passed) if passed is not None else False, "status": "pass" if passed else ("not_run" if passed is None else "fail"), "detail": detail} 

123 

124 

125def judge_field_test(evidence: Mapping[str, Any]) -> dict[str, Any]: 

126 """Pass/fail per check from a run's evidence (`scripts/lean_smoke/field_test.py` collects it from the engine 

127 logs, the result JSON, the audit chain and the services log). A check without evidence is `not_run`, which fails.""" 

128 runs: Sequence[Mapping[str, Any]] = evidence.get("runs", []) or [] 

129 first = runs[0] if runs else {} 

130 orders = int(first.get("orders_submitted", 0) or 0) 

131 fills = int(first.get("orders_filled", 0) or 0) 

132 trip_bar, shock_bar = first.get("kill_switch_trip_bar"), first.get("shock_bar") 

133 checks = { 

134 "orders_submitted": _check(orders >= 1 if runs else None, f"{orders} orders submitted to the paper brokerage"), 

135 "orders_filled": _check(fills >= 1 if runs else None, f"{fills} fills"), 

136 "kill_switch_tripped": _check( 

137 (trip_bar is not None and shock_bar is not None and 0 <= int(trip_bar) - int(shock_bar) <= 3) if runs else None, 

138 f"shock at bar {shock_bar}, trip at bar {trip_bar}", 

139 ), 

140 "flat_after_trip": _check( 

141 (first.get("gross_after_trip") is not None and float(first["gross_after_trip"]) <= 1e-6) if runs else None, 

142 f"strategy exposure after the trip (the T-bill sweep is cash, as in the lock's liquidation): {first.get('gross_after_trip')}", 

143 ), 

144 "reconciliation_breach_detected": _check( 

145 bool(first.get("reconciliation_breach")) and bool(first.get("reconciliation_audit_event")) if runs else None, 

146 "breach seen in state.json and an audit event written" if first.get("reconciliation_audit_event") else "no breach event", 

147 ), 

148 "restart_restored": _check( 

149 bool(evidence.get("restart", {}).get("started")) and not evidence.get("restart", {}).get("reconciliation_breach_on_start", True) 

150 if evidence.get("restart") else None, 

151 "second run started on the same project and its first reconciliation matched", 

152 ), 

153 "outages_survived": _check( 

154 all(bool(item.get("engine_alive_after")) for item in evidence.get("outages", [])) if evidence.get("outages") else None, 

155 ", ".join(f"{item.get('service')}: {'up' if item.get('engine_alive_after') else 'DOWN'}" for item in evidence.get("outages", [])), 

156 ), 

157 "audit_chain_valid": _check(evidence.get("audit_chain_valid") if "audit_chain_valid" in evidence else None, f"{evidence.get('audit_entries', 0)} entries"), 

158 "accounts_isolated": _check( 

159 (len(set(evidence.get("account_ids_in_audit", []))) >= 2 and bool(evidence.get("state_dirs_distinct"))) if "account_ids_in_audit" in evidence else None, 

160 f"accounts in the audit chain: {sorted(set(evidence.get('account_ids_in_audit', [])))}", 

161 ), 

162 } 

163 passed = [name for name in CHECKS if checks[name]["pass"]] 

164 return {"checks": checks, "passed": len(passed), "total": len(CHECKS), "all_passed": len(passed) == len(CHECKS), 

165 "note": "Plumbing on Lean's paper brokerage with a fake feed. It proves no edge and no real-broker behaviour (#338, #192)."}