File size: 8,516 Bytes
81464dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
from __future__ import annotations

import hashlib
import json
from pathlib import Path
import subprocess

import pytest

from app.services.trading_ml.finrlx import (
    FINRLX_UPSTREAM_REVISION,
    FinRLXArtifactValidator,
    FinRLXQuantEngine,
    InvalidFinRLXArtifact,
)


SCHEMA_HASH = "feature-schema-v1"


def write_artifact(
    root: Path,
    *,
    algorithm: str = "PPO",
    market_family: str = "forex",
    feature_schema_hash: str = SCHEMA_HASH,
    paper_only: bool = True,
) -> Path:
    root.mkdir(parents=True, exist_ok=True)
    artifact = root / "policy.bin"
    artifact.write_bytes(b"verified-finrlx-policy")
    manifest = root / "manifest.json"
    manifest.write_text(
        json.dumps(
            {
                "provider": "finrlx",
                "upstream_repository": "AI4Finance-Foundation/FinRL-Trading",
                "upstream_revision": FINRLX_UPSTREAM_REVISION,
                "algorithm": algorithm,
                "market_family": market_family,
                "feature_schema_hash": feature_schema_hash,
                "action_schema": (
                    "directional_score_v1"
                    if market_family == "forex"
                    else "target_weights_v1"
                ),
                "artifact_path": artifact.name,
                "artifact_sha256": hashlib.sha256(artifact.read_bytes()).hexdigest(),
                "sample_count": 500,
                "paper_only": paper_only,
            }
        ),
        encoding="utf-8",
    )
    return manifest


def write_runner(path: Path) -> Path:
    path.write_text(
        """#!/usr/bin/env python3
import json
import sys

request = json.load(sys.stdin)
if request["operation"] == "propose":
    json.dump({
        "action": "LONG",
        "directional_score": 0.72,
        "confidence": 0.68,
        "uncertainty": 0.21,
        "reason": "validated shadow proposal"
    }, sys.stdout)
elif request["operation"] == "train":
    json.dump({"manifest_path": request["request"]["manifest_path"]}, sys.stdout)
""",
        encoding="utf-8",
    )
    path.chmod(0o755)
    return path


def test_artifact_validator_accepts_pinned_paper_only_manifest(tmp_path):
    manifest_path = write_artifact(tmp_path)

    manifest = FinRLXArtifactValidator(
        root=tmp_path,
        expected_feature_schema_hash=SCHEMA_HASH,
    ).validate(manifest_path, market_family="forex")

    assert manifest.algorithm == "PPO"
    assert manifest.sample_count == 500
    assert manifest.paper_only is True


@pytest.mark.parametrize(
    ("mutation", "expected"),
    [
        ({"algorithm": "UNSUPPORTED"}, "algorithm"),
        ({"market_family": "equity"}, "market"),
        ({"feature_schema_hash": "wrong"}, "schema"),
        ({"paper_only": False}, "paper"),
        ({"upstream_revision": "unpinned"}, "revision"),
    ],
)
def test_artifact_validator_rejects_incompatible_manifest(tmp_path, mutation, expected):
    manifest_path = write_artifact(tmp_path)
    payload = json.loads(manifest_path.read_text(encoding="utf-8"))
    payload.update(mutation)
    manifest_path.write_text(json.dumps(payload), encoding="utf-8")

    with pytest.raises(InvalidFinRLXArtifact, match=expected):
        FinRLXArtifactValidator(
            root=tmp_path,
            expected_feature_schema_hash=SCHEMA_HASH,
        ).validate(manifest_path, market_family="forex")


def test_artifact_validator_rejects_tampered_binary(tmp_path):
    manifest_path = write_artifact(tmp_path)
    (tmp_path / "policy.bin").write_bytes(b"tampered")

    with pytest.raises(InvalidFinRLXArtifact, match="hash"):
        FinRLXArtifactValidator(
            root=tmp_path,
            expected_feature_schema_hash=SCHEMA_HASH,
        ).validate(manifest_path, market_family="forex")


def test_disabled_and_missing_runner_are_non_fatal(tmp_path):
    disabled = FinRLXQuantEngine(
        enabled=False,
        runner_command="",
        artifact_root=tmp_path,
        feature_schema_hash=SCHEMA_HASH,
    )
    unavailable = FinRLXQuantEngine(
        enabled=True,
        runner_command=str(tmp_path / "missing-runner"),
        artifact_root=tmp_path,
        feature_schema_hash=SCHEMA_HASH,
    )

    assert disabled.status()["status"] == "DISABLED"
    assert disabled.propose(market_family="forex", features={}).action == "HOLD"
    assert unavailable.status()["status"] == "UNAVAILABLE"
    assert unavailable.propose(market_family="forex", features={}).status == "UNAVAILABLE"


def test_runner_proposal_is_normalized_and_blockers_are_preserved(tmp_path):
    manifest_path = write_artifact(tmp_path)
    runner = write_runner(tmp_path / "runner.py")
    engine = FinRLXQuantEngine(
        enabled=True,
        runner_command=str(runner),
        artifact_root=tmp_path,
        manifest_path=manifest_path,
        feature_schema_hash=SCHEMA_HASH,
        timeout_seconds=5,
    )

    proposal = engine.propose(
        market_family="forex",
        features={"momentum_5": 0.8},
        context={"pair": "EURUSD=X"},
    )
    blocked = engine.propose(
        market_family="forex",
        features={"momentum_5": 0.8},
        deterministic_blockers=["STALE_DATA"],
    )

    assert proposal.status == "SHADOW"
    assert proposal.action == "LONG"
    assert proposal.directional_score == 0.72
    assert blocked.action == "HOLD"
    assert blocked.directional_score == 0.0
    assert "EXISTING_BLOCKER_PRESERVED" in blocked.guardrails


def test_runner_cannot_return_leverage_or_order_authority(tmp_path):
    manifest_path = write_artifact(tmp_path)
    runner = tmp_path / "unsafe-runner.py"
    runner.write_text(
        """#!/usr/bin/env python3
import json
import sys
json.load(sys.stdin)
json.dump({"action": "LONG", "directional_score": 1, "leverage": 30}, sys.stdout)
""",
        encoding="utf-8",
    )
    runner.chmod(0o755)
    engine = FinRLXQuantEngine(
        enabled=True,
        runner_command=str(runner),
        artifact_root=tmp_path,
        manifest_path=manifest_path,
        feature_schema_hash=SCHEMA_HASH,
    )

    proposal = engine.propose(market_family="forex", features={})

    assert proposal.status == "REJECTED"
    assert proposal.action == "HOLD"
    assert "FORBIDDEN_EXECUTION_FIELD" in proposal.guardrails


def test_training_result_is_accepted_only_after_manifest_validation(tmp_path):
    manifest_path = write_artifact(tmp_path)
    runner = write_runner(tmp_path / "runner.py")
    engine = FinRLXQuantEngine(
        enabled=True,
        runner_command=str(runner),
        artifact_root=tmp_path,
        feature_schema_hash=SCHEMA_HASH,
        timeout_seconds=5,
    )

    result = engine.run_training(
        market_family="forex",
        request={"manifest_path": str(manifest_path), "max_rows": 500},
    )

    assert result["status"] == "VALIDATED_SHADOW"
    assert result["manifest"]["algorithm"] == "PPO"
    assert result["manifest"]["paper_only"] is True


def test_equity_target_weights_are_normalized_without_order_authority(tmp_path):
    manifest_path = write_artifact(tmp_path, market_family="equity")
    runner = tmp_path / "equity-runner.py"
    runner.write_text(
        """#!/usr/bin/env python3
import json
import sys
json.load(sys.stdin)
json.dump({"target_weights": {"NVDA": 0.8, "MSFT": 0.8}, "confidence": 0.7}, sys.stdout)
""",
        encoding="utf-8",
    )
    runner.chmod(0o755)
    engine = FinRLXQuantEngine(
        enabled=True,
        runner_command=str(runner),
        artifact_root=tmp_path,
        manifest_path=manifest_path,
        feature_schema_hash=SCHEMA_HASH,
    )

    proposal = engine.propose(market_family="equity", features={})

    assert proposal.action == "TARGET_WEIGHTS"
    assert dict(proposal.target_weights) == {"MSFT": 0.5, "NVDA": 0.5}
    assert proposal.paper_only is True


def test_runner_timeout_returns_hold_without_escaping_cycle(tmp_path, monkeypatch):
    manifest_path = write_artifact(tmp_path)
    runner = write_runner(tmp_path / "runner.py")
    engine = FinRLXQuantEngine(
        enabled=True,
        runner_command=str(runner),
        artifact_root=tmp_path,
        manifest_path=manifest_path,
        feature_schema_hash=SCHEMA_HASH,
    )

    def timeout(*args, **kwargs):
        raise subprocess.TimeoutExpired(cmd="runner", timeout=1)

    monkeypatch.setattr(subprocess, "run", timeout)

    proposal = engine.propose(market_family="forex", features={})

    assert proposal.status == "TIMEOUT"
    assert proposal.action == "HOLD"