File size: 4,933 Bytes
3d027e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""V8 run records preserve frozen runtime truth and legacy replay files."""

from datetime import datetime, timezone
from pathlib import Path

import pytest

from polyhedra.core.active_routing import build_active_routing_plan
from polyhedra.core.artifacts import JsonArtifactRef
from polyhedra.core.baseline_selector import select_typed_yolo_baseline
from polyhedra.core.dependency_executor import AgentCompletion, DependencyExecutor
from polyhedra.core.quant_contracts import load_quant_contracts
from polyhedra.services.quant_run_record import (
    QuantRunRecord, QuantRunRecordStore, build_quant_run_record,
)

START = datetime(2026, 9, 12, 12, tzinfo=timezone.utc)
END = datetime(2026, 9, 12, 12, 5, tzinfo=timezone.utc)


def completion(agent, *, run="run1", session="session1"):
    permissions = load_quant_contracts().for_agent(agent).permissions.create
    template = next(path for path in permissions if path.endswith(".json"))
    return AgentCompletion(
        result_status="COMPLETE",
        artifact_ref=JsonArtifactRef(
            schema_version="8.0",
            artifact_id=f"{agent}-{run}",
            run_id=run,
            session_id=session,
            producer=agent,
            path=template.replace("{run_id}", run),
        ),
    )


async def completed_record(run="run1"):
    plan = build_active_routing_plan(
        run_id=run, execution_context="YOLO", tickers=["MSFT"],
    )

    async def runner(item):
        return completion(item.agent, run=run)

    execution = await DependencyExecutor(
        plan, session_id="session1", runner=runner,
    ).run()
    snapshots = {
        item.agent: f"quant/runs/{run}/inputs/{item.agent}.json"
        for item in plan.active_agents
    }
    return build_quant_run_record(
        plan=plan,
        execution=execution,
        session_id="session1",
        run_mode="BASELINE",
        baseline_run_id=None,
        started_at=START,
        completed_at=END,
        input_snapshot_paths=snapshots,
    )


@pytest.mark.asyncio
async def test_completed_run_record_is_a_typed_baseline_candidate():
    record = await completed_record()
    assert record.status == "completed"
    assert len(record.artifact_inventory) == len(record.execution.records)
    selection = select_typed_yolo_baseline(
        [record.model_dump(mode="json")],
        session_id="session1",
        current_run_id="current",
        ticker_scope=["MSFT", "QQQ"],
    )
    assert selection.baseline_run_id == "run1"
    assert selection.missing_tickers == ["QQQ"]


@pytest.mark.asyncio
async def test_agent_failure_derives_failed_run_and_cannot_be_baseline():
    plan = build_active_routing_plan(
        run_id="failed", execution_context="YOLO", tickers=["MSFT"],
    )

    async def runner(item):
        if item.agent == "DataFetcher":
            raise RuntimeError("fetch failed")
        return completion(item.agent, run="failed")

    execution = await DependencyExecutor(
        plan, session_id="session1", runner=runner,
    ).run()
    record = build_quant_run_record(
        plan=plan,
        execution=execution,
        session_id="session1",
        run_mode="BASELINE",
        baseline_run_id=None,
        started_at=START,
        completed_at=END,
        input_snapshot_paths={"DataFetcher": "quant/runs/failed/inputs/DataFetcher.json"},
    )
    assert record.status == "failed"
    result = select_typed_yolo_baseline(
        [record.model_dump(mode="json")],
        session_id="session1",
        current_run_id="current",
        ticker_scope=["MSFT"],
    )
    assert result.baseline_run_id is None
    assert result.rejections[0].code == "NOT_COMPLETED"


@pytest.mark.asyncio
async def test_store_is_atomic_immutable_and_preserves_legacy_records(tmp_path: Path):
    record = await completed_record()
    legacy = tmp_path / "yolo_runs" / "legacy.json"
    legacy.parent.mkdir()
    legacy.write_text('{"status":"completed","legacy":true}', encoding="utf-8")
    store = QuantRunRecordStore(tmp_path, session_id="session1")
    path = store.save(record)
    assert path == "yolo_runs/run1.json"
    assert store.load("run1") == record
    assert store.baseline_candidates() == [record.model_dump(mode="json")]
    assert legacy.read_text(encoding="utf-8") == '{"status":"completed","legacy":true}'
    with pytest.raises(FileExistsError):
        store.save(record)


@pytest.mark.asyncio
async def test_record_rejects_missing_completed_output_and_wrong_snapshot_path():
    record = await completed_record()
    data = record.model_dump(mode="json")
    data["artifact_inventory"].pop()
    with pytest.raises(ValueError, match="omits"):
        QuantRunRecord.model_validate(data)
    data = record.model_dump(mode="json")
    data["input_snapshot_paths"]["DataFetcher"] = "quant/runs/other/inputs/DataFetcher.json"
    with pytest.raises(ValueError, match="snapshot path"):
        QuantRunRecord.model_validate(data)