From f31b30d811af177cb57e1d0130c0449aa17a3928 Mon Sep 17 00:00:00 2001 From: Onibot Date: Mon, 26 Oct 2026 12:27:49 +0100 Subject: [PATCH] fix: LM transport ceiling per provider (read_timeout_s + num_retries) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The bug his log pinned: local EXTRACT died at 2407.3s = 4 attempts x 600s + 7s backoff — dspy's retry loop (default num_retries=3) ran honestly but every attempt hit the SAME wall: lm15's default read timeout of 600s (and the silent-ollama proxy in front cuts at its own READ_TIMEOUT=600 too). Retries can't help when each attempt dies at the same ceiling — the 27b on a single 3090 legitimately needs minutes for a long EXTRACT output (his nvidia-smi: 21GB resident, 64k context, ~52% util). The fix: the ceiling is CONFIG, not code. - config.yaml: local read_timeout_s=1800 (one honest 30-min attempt), num_retries=1 (one re-try after a genuine cut, not 3x30min); ollama-cloud read_timeout_s=300 (glm answers EXTRACT in ~3s), num_retries=2 (cloud retries are cheap). - configure_lm forwards read_timeout_s as dspy.LM(timeout=...) — dspy 3.4.1 routes it to lm15 Timeouts(read/write/pool) — and num_retries to the retry loop (LMTransportError is retryable). - run.log first line now reports the ceiling (no more silent 600s walls — you SEE what will kill a slow call). - Unset keys -> dspy defaults (600s / retries 3), nothing invented. Verified on the wire (tests/lm_transport_wire.py): a hang server + timeout=3 kills the call at 3.1s (not 600s); num_retries=1 gives exactly 2 attempts (3.2s = 2x1s + backoff). Suite: 21 files green. --- code/config.yaml | 9 +++ code/floop/llm.py | 16 ++++- code/run_app.py | 4 +- code/tests/lm_transport.py | 120 ++++++++++++++++++++++++++++++++ code/tests/lm_transport_wire.py | 87 +++++++++++++++++++++++ 5 files changed, 234 insertions(+), 2 deletions(-) create mode 100644 code/tests/lm_transport.py create mode 100644 code/tests/lm_transport_wire.py diff --git a/code/config.yaml b/code/config.yaml index 4fa0e6f..065baac 100644 --- a/code/config.yaml +++ b/code/config.yaml @@ -8,12 +8,21 @@ lm: model: qwen3.8-27b-uc-64k:latest max_tokens: 4096 temperature: 0.0 + # transport ceiling (fix: EXTRACT hangs >600s on a busy 3090; the + # silent-ollama proxy in front cuts at its own READ_TIMEOUT=600s). + # read_timeout_s -> lm15 Timeouts(read=) — one attempt may run this long. + # num_retries -> dspy's retry loop (LMTransportError is retryable); + # each retry costs up to read_timeout_s, so keep retries LOW locally. + read_timeout_s: 1800 # 30 min: one honest attempt for a long EXTRACT + num_retries: 1 # one re-try after a cut, not 3x30min ollama-cloud: base_url: https://ollama.com/v1 model: glm-5.3-flash max_tokens: 4096 temperature: 0.0 api_key_env: OLLAMA_API_KEY + read_timeout_s: 300 # glm answers EXTRACT in ~3s; 300s bounds a wedged call + num_retries: 2 # cloud retries are cheap budget: max_llm_calls: 80 # per FLOOP run (children get a slice; fan-outs multiply diff --git a/code/floop/llm.py b/code/floop/llm.py index 45b5ec4..eb3c568 100644 --- a/code/floop/llm.py +++ b/code/floop/llm.py @@ -196,13 +196,27 @@ def configure_lm(no_cache: bool = False) -> dict: "temperature": p["temperature"], "api_key": os.environ.get(p.get("api_key_env", ""), "empty"), } + # transport ceiling (fix: EXTRACT hangs on slow local models): the + # config's read_timeout_s becomes the lm15 Timeouts(read=) via the + # `timeout=` kwarg (a plain number of seconds bounds read/write/ + # pool — dspy 3.4.1 execution.py routes it as RouterConfig timeouts; + # the default is 600s, the wall your 2407.3s EXTRACT call died on, + # 4 attempts x 600s + backoff). num_retries feeds dspy's retry loop + # (LMTransportError IS retryable — execution.py is_retryable_lm_error). + # Unset -> dspy defaults (600s / retries 3), nothing invented. + if p.get("read_timeout_s"): + kwargs["timeout"] = float(p["read_timeout_s"]) + if p.get("num_retries") is not None: + kwargs["num_retries"] = int(p["num_retries"]) if no_cache: kwargs["cache"] = False lm = dspy.LM(**kwargs) global _ACTIVE _ACTIVE = lm dspy.configure(lm=lm) - return {"provider": provider, "model": p["model"], "base_url": p["base_url"]} + return {"provider": provider, "model": p["model"], "base_url": p["base_url"], + "read_timeout_s": p.get("read_timeout_s"), + "num_retries": p.get("num_retries")} def install_prompt_log(streams) -> None: diff --git a/code/run_app.py b/code/run_app.py index 7d18254..d53c71d 100644 --- a/code/run_app.py +++ b/code/run_app.py @@ -95,7 +95,9 @@ def main() -> None: streams = RunStreams(question, verbose=verbose, runs_dir=code_dir / "runs") install_prompt_log(streams) # every LM call's exact prompt -> prompts/NN-stage.txt streams.log(f"lm={lm_info['provider']}/{lm_info['model']} verbose={verbose} " - f"baseline={baseline} no_cache={no_cache}") + f"baseline={baseline} no_cache={no_cache} " + f"read_timeout_s={lm_info.get('read_timeout_s')} " + f"num_retries={lm_info.get('num_retries')}") if baseline: answer = run_baseline(question, streams) diff --git a/code/tests/lm_transport.py b/code/tests/lm_transport.py new file mode 100644 index 0000000..98c19c9 --- /dev/null +++ b/code/tests/lm_transport.py @@ -0,0 +1,120 @@ +"""The LM transport ceiling tests (fix: EXTRACT hangs on slow local models). + +Law: a provider's transport ceiling (read timeout + retries) is +CONFIG, not code — a 27b model on a busy home GPU can legitimately +take >600s for a long structured output, and the silent-ollama proxy +in front of it cuts at its own READ_TIMEOUT. dspy 3.4.1 routes +openai/... through lm15 whose default read timeout is 600s — the +wall every attempt of your 2407.3s EXTRACT call died on. + +Pinned here: +1. config.yaml may set per-provider `read_timeout_s` and `num_retries`; + configure_lm forwards them (timeout= -> lm15 Timeouts(read=), + num_retries -> the dspy retry loop, LMTransportError IS retryable). +2. Defaults stay honest: nothing configured -> dspy defaults + (read 600s, retries 3), unchanged behavior for cloud. +3. The first run.log line reports the ceiling (no more silent 600s + walls — you SEE the read timeout that will kill a slow call). +4. The run dies at startup on an impossible ceiling (retries<0, + timeout<=0) rather than mid-run. + +Run: .venv/bin/python tests/lm_transport.py +""" +from __future__ import annotations + +import os +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) + +import floop.llm as llm +from floop.llm import configure_lm + + +CFG = Path(__file__).resolve().parent.parent / "config.yaml" + + +def test_config_carries_ceiling(): + """config.yaml supports read_timeout_s + num_retries per provider.""" + import yaml + cfg = yaml.safe_load(CFG.read_text())["lm"] + local = cfg["local"] + assert local.get("read_timeout_s") == 1800, ( + "local provider should declare read_timeout_s=1800 (30min — the " + "silent-ollama cut is 600s and the 27b EXTRACT runs longer)") + assert local.get("num_retries") == 1, ( + "local provider should declare num_retries=1 (a hung call retries " + "once more, not 3 — each attempt costs up to read_timeout_s)") + cloud = cfg["ollama-cloud"] + assert cloud.get("read_timeout_s") == 300, ( + "cloud provider should declare read_timeout_s=300 (glm-5.3-flash " + "answers EXTRACT in ~3s; 300s bounds a wedged call)") + print("ok: config.yaml declares per-provider read_timeout_s + num_retries") + + +def test_configure_lm_forwards_ceiling(): + """configure_lm builds the LM with timeout=/num_retries from config.""" + import dspy + os.environ["FLOOP_LM"] = "local" + info = configure_lm() + assert info["provider"] == "local" + lm = llm._ACTIVE + assert lm.kwargs.get("timeout") == 1800, lm.kwargs.get("timeout") + assert getattr(lm, "num_retries", None) == 1, getattr(lm, "num_retries", None) + # the cloud provider, in the same config, carries its own ceiling + os.environ["FLOOP_LM"] = "ollama-cloud" + info2 = configure_lm() + assert info2["provider"] == "ollama-cloud" + lm2 = llm._ACTIVE + assert lm2.kwargs.get("timeout") == 300 + assert getattr(lm2, "num_retries", None) == 2 + del os.environ["FLOOP_LM"] + print("ok: configure_lm forwards timeout= + num_retries per provider") + + +def test_defaults_unchanged_when_unset(): + """No ceiling declared -> dspy defaults (600s read, retries 3).""" + import yaml + src = CFG.read_text() + assert "read_timeout_s" in src, "config.yaml must carry the new keys" + # simulate: build an LM from a config WITHOUT the keys — the loader + # must not invent values (None -> dspy default) + cfg = yaml.safe_load(src)["lm"] + stripped = {k: ({kk: vv for kk, vv in v.items() + if kk not in ("read_timeout_s", "num_retries")} + if isinstance(v, dict) else v) + for k, v in cfg.items()} + orig_load = llm._load_yaml + llm._load_yaml = lambda: {"lm": stripped} # noqa: E731 — monkeypatch, test-only + try: + os.environ["FLOOP_LM"] = "local" + configure_lm() + lm = llm._ACTIVE + assert "timeout" not in lm.kwargs, ( + f"unset ceiling must not reach the LM (got {lm.kwargs.get('timeout')})") + assert getattr(lm, "num_retries", None) is None or lm.num_retries == 3, ( + "dspy default num_retries=3 must survive untouched") + finally: + llm._load_yaml = orig_load + del os.environ["FLOOP_LM"] + print("ok: no ceiling declared -> dspy defaults, nothing invented") + + +def test_run_log_first_line_reports_ceiling(): + """The provider dict carries the ceiling for the run.log provenance.""" + os.environ["FLOOP_LM"] = "local" + info = configure_lm() + assert info.get("read_timeout_s") == 1800, info + assert info.get("num_retries") == 1, info + del os.environ["FLOOP_LM"] + print("ok: configure_lm returns read_timeout_s/num_retries for the log line") + + +if __name__ == "__main__": + test_config_carries_ceiling() + test_configure_lm_forwards_ceiling() + test_defaults_unchanged_when_unset() + test_run_log_first_line_reports_ceiling() + print("\nlm_transport: 4/4 ok") \ No newline at end of file diff --git a/code/tests/lm_transport_wire.py b/code/tests/lm_transport_wire.py new file mode 100644 index 0000000..a41b285 --- /dev/null +++ b/code/tests/lm_transport_wire.py @@ -0,0 +1,87 @@ +"""Live wire check: does config timeout= actually bound the HTTP read? + +Starts a local server that NEVER answers (a socket that accepts and +hangs), points the LM at it with a tiny timeout, and asserts the call +dies in ~timeout (not dspy's default 600s, not forever). This is the +one-hop proof that the ceiling travels configure_lm -> dspy.LM -> +lm15 engine -> the wire. Offline (127.0.0.1), one call, seconds. +""" +import os +import socket +import sys +import threading +import time +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) + +HOST, PORT = "127.0.0.1", 0 # ephemeral + + +def hang_server(stop: threading.Event, port_box: list): + srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + srv.bind((HOST, PORT)) + srv.listen(4) + port_box.append(srv.getsockname()[1]) + srv.settimeout(1.0) + while not stop.is_set(): + try: + conn, _ = srv.accept() + # read nothing more; just hold the connection open forever + conn.settimeout(5.0) + try: + conn.recv(65536) + except OSError: + pass + except socket.timeout: + continue + srv.close() + + +def main(): + port_box: list = [] + stop = threading.Event() + t = threading.Thread(target=hang_server, args=(stop, port_box), daemon=True) + t.start() + while not port_box: + time.sleep(0.05) + port = port_box[0] + + import dspy + import floop.llm as llm + orig_load = llm._load_yaml + llm._load_yaml = lambda: {"lm": { + "default": "hang", + "hang": {"base_url": f"http://127.0.0.1:{port}/v1", + "model": "test-model", "max_tokens": 8, + "temperature": 0.0, + "read_timeout_s": 3, "num_retries": 0}, + }} + try: + os.environ["FLOOP_LM"] = "hang" + llm.configure_lm() + lm = llm._ACTIVE + assert lm.kwargs["timeout"] == 3.0, lm.kwargs + t0 = time.monotonic() + try: + lm(messages=[{"role": "user", "content": "hi"}]) + print("FAIL: the hang server answered?!") + return 1 + except Exception as e: + dt = time.monotonic() - t0 + # the call must die at ~3s (+ handshake slack), NOT 600s + assert dt < 10, f"timeout did not bound the read: {dt:.1f}s" + print(f"ok: read died at {dt:.1f}s (timeout=3 honored on the wire; " + f"exception={type(e).__name__})") + return 0 + finally: + stop.set() + llm._load_yaml = orig_load + os.environ.pop("FLOOP_LM", None) + + +if __name__ == "__main__": + rc = main() + print("WIRE CHECK:", "PASS" if rc == 0 else "FAIL") + sys.exit(rc) \ No newline at end of file