File size: 6,811 Bytes
39c4621
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a0c3ef
 
 
 
 
 
 
 
d406c40
a0ccb41
0ea8d95
 
a0ccb41
 
9a0c3ef
 
a0ccb41
0ea8d95
a0ccb41
0ea8d95
a0ccb41
527f69d
a0ccb41
 
 
 
9a0c3ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d406c40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a0c3ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39c4621
 
 
 
 
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
"""Network-free checks for the Finnhub throttle and the VPS HTTPS retry."""

import os
import sys

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

os.environ.setdefault("FINNHUB_API_KEY", "test-key")
os.environ["VPS_API_URL"] = "http://example.test:8080"
os.environ["VPS_API_KEY"] = "test-key"

failures = []


def check(name, cond, detail=""):
    if cond:
        print(f"  PASS  {name}")
    else:
        print(f"  FAIL  {name}  {detail}")
        failures.append(name)


class _Resp:
    def __init__(self, status, payload=None, content=b"", headers=None):
        self.status_code = status
        self._payload = payload if payload is not None else {}
        self.content = content
        self.headers = headers or {}
        self.ok = 200 <= status < 300

    def json(self):
        return self._payload

    def raise_for_status(self):
        if not self.ok:
            raise RuntimeError(f"status {self.status_code}")


print("\n== Finnhub 429 retry and cache ==")

import src.core.finnhub_http as fh

calls = []
sleeps = []


def fake_get(url, params=None, timeout=10):
    calls.append((url, dict(params or {})))
    if len(calls) == 1:
        return _Resp(429, headers={"Retry-After": "1"})
    return _Resp(200, {"data": [{"share": 10}]})


def fake_sleep(seconds):
    sleeps.append(seconds)


fh.requests.get = fake_get
fh.time.sleep = fake_sleep
fh._cache.clear()
fh._next_ok = 0.0

resp = fh.finnhub_get(
    "https://finnhub.io/api/v1/stock/insider-transactions",
    params={"symbol": "SPCE", "token": "secret-token"},
)
check("retries a 429 then returns the body", resp.json() == {"data": [{"share": 10}]})
check("second attempt is the one that succeeds", len(calls) == 2, len(calls))
check("request carries the token as a param", all(c[1].get("token") == "secret-token" for c in calls))
check("honours Retry-After", 1.0 in sleeps, sleeps)

again = fh.finnhub_get(
    "https://finnhub.io/api/v1/stock/insider-transactions",
    params={"symbol": "SPCE", "token": "secret-token"},
)
check("caches a successful response", again.json()["data"][0]["share"] == 10 and len(calls) == 2)

try:
    fh._cache.clear()
    fh.requests.get = lambda *a, **k: _Resp(429, headers={})
    fh.finnhub_get("https://finnhub.io/api/v1/stock/insider-transactions", params={"symbol": "X"})
    check("gives up after repeated 429s", False)
except Exception as exc:
    check("gives up after repeated 429s", "429" in str(exc), str(exc))
    check("error text has no token", "secret-token" not in str(exc), str(exc))

print("\n== VPS http port is really HTTPS ==")

import importlib
import src.core.memory as memory

memory = importlib.reload(memory)

seen = []


def fake_request(method, url, headers=None, timeout=5, verify=True, json=None):
    seen.append((method, url, verify, json))
    if url.startswith("http://"):
        return _Resp(400, content=b"Client sent an HTTP request to an HTTPS server.\n")
    return _Resp(200, {"status": "ok", "ticker": "SPCE"})


memory.requests.request = fake_request
memory.mark_ticker_seen("OPSFIX", "USA")
check("plain HTTP 400 is retried over HTTPS", len(seen) == 2, seen)
check(
    "retry keeps the path and the body",
    seen[1][0] == "POST"
    and seen[1][1].startswith("https://example.test:8080/seen-tickers")
    and seen[1][3]["ticker"] == "OPSFIX",
    seen,
)
local = ""
if os.path.exists("seen_tickers.json"):
    local = open("seen_tickers.json").read()
check("local ledger is not used when HTTPS succeeds", "OPSFIX" not in local)

print("\n== Debate stays on the free tier ==")

import threading
import src.agents.debate as debate

pitcher = debate.PITCHER_MODEL
skeptic_fb = debate._fallback_for(debate.SKEPTIC_MODEL)
pitcher_fb = debate._fallback_for(debate.PITCHER_MODEL)
skeptic_chain = debate._call_chain(debate.SKEPTIC_MODEL)
check(
    "skeptic starts on Flint",
    debate.SKEPTIC_MODEL == "recursive/flint-v1.0:free",
    debate.SKEPTIC_MODEL,
)
check("skeptic backup is not the pitcher", skeptic_fb != pitcher, skeptic_fb)
check("pitcher backup is not the skeptic", pitcher_fb != debate.SKEPTIC_MODEL, pitcher_fb)
check(
    "skeptic chain is Flint, ERNIE, Super VL",
    skeptic_chain == [
        "recursive/flint-v1.0:free",
        "baidu/ernie-5.5-flash-preview:free",
        "nvidia/nemotron-3.5-super-vl:free",
    ],
    skeptic_chain,
)
check("gemma is not the first skeptic", "gemma" not in skeptic_chain[0], skeptic_chain)

calls = []
sleeps = []


class _Msg:
    def __init__(self, content):
        self.content = content


class _LLM:
    def __init__(self, model):
        self.model = model

    def invoke(self, prompt):
        calls.append(self.model)
        if self.model == debate.SKEPTIC_MODEL:
            raise RuntimeError("429 Too Many Requests")
        return _Msg("bear case")


debate._make_llm = lambda model, max_tokens=2048: _LLM(model)
debate.time.sleep = lambda seconds: sleeps.append(seconds)
text = debate._resilient_llm_call(
    debate.SKEPTIC_MODEL, "prompt", debate._fallback_for(debate.SKEPTIC_MODEL),
)
check("429 switches after one wait", text == "bear case" and calls.count(debate.SKEPTIC_MODEL) == 1, calls)
check("429 does not camp on the same model", calls.count(debate.SKEPTIC_MODEL) < 2)
check("fallback call is the non-pitcher model", calls[-1] == skeptic_fb, calls)

third_calls = []


class _LLMTwoFails:
    def __init__(self, model):
        self.model = model

    def invoke(self, prompt):
        third_calls.append(self.model)
        if self.model != skeptic_chain[-1]:
            raise RuntimeError("429 Too Many Requests")
        return _Msg("third model")


debate._make_llm = lambda model, max_tokens=2048: _LLMTwoFails(model)
third = debate._resilient_llm_call(debate.SKEPTIC_MODEL, "prompt")
check("third model runs after two rate limits", third == "third model" and third_calls == skeptic_chain, third_calls)

overlap = {"n": 0, "max": 0}
gate = threading.Lock()


def _fake_invoke(state):
    with gate:
        overlap["n"] += 1
        overlap["max"] = max(overlap["max"], overlap["n"])
    import time as real_time
    real_time.sleep(0.05)
    with gate:
        overlap["n"] -= 1
    return {"final_verdict": "v", "bull_case": "b", "bear_case": "r", "_structured_result": None}


debate.debate_app.invoke = _fake_invoke
kwargs = dict(
    ticker="T", company_name="C", financial_data_summary="f",
    deep_fundamentals="d", sec_context="s", strategy="GRAHAM CLASSIC",
    price=1.0, eps=0.1, book_value=1.0, ebitda=1.0,
)
threads = [threading.Thread(target=debate.run_debate, kwargs=kwargs) for _ in range(2)]
for t in threads:
    t.start()
for t in threads:
    t.join()
check("debates do not overlap", overlap["max"] == 1, overlap)

print()
if failures:
    print(f"{len(failures)} FAIL")
    sys.exit(1)
print("ALL PASS")