release: Евномия, новая версия, линейка юристов
This commit is contained in:
@@ -0,0 +1,123 @@
|
||||
"""Красный тест T449 (12.10.2026): параллельный поиск практики, таймаут агента 300 с x 2, потолок прогона.
|
||||
|
||||
Шаг 8 плана совета № 3 (без faza_karta.py). Дефекты:
|
||||
· faza_praktika искал вопросы подряд по устаревшему запрету: verify_act.py давно пишет через mkstemp;
|
||||
· агент ждал 900 с x 3 попытки (до 45 мин на зависший CLI);
|
||||
· у прогона не было потолка токенов и минут.
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import textwrap
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
NEXT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(NEXT))
|
||||
sys.path.insert(0, str(NEXT / "tests"))
|
||||
|
||||
import core # noqa: E402
|
||||
import faza_praktika # noqa: E402
|
||||
from next_helpers import make_case # noqa: E402
|
||||
|
||||
SCHEMA = {"type": "object", "properties": {"fakty": {"type": "array"}}, "required": ["fakty"]}
|
||||
HANG = {"sleep": 5, "structured_output": {"fakty": []}}
|
||||
|
||||
|
||||
def ask(run, **kw):
|
||||
return core.agent(run, "karta", "docx-reader", "РОЛЬ: docx-reader", "т", SCHEMA, "читает", **kw)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def run_(tmp_path):
|
||||
with core.Run(make_case(tmp_path / "cases" / "c" / "d"), "FAST", "иск") as run:
|
||||
yield run
|
||||
|
||||
|
||||
def test_praktika_searches_questions_in_parallel(tmp_path, monkeypatch):
|
||||
sys.path.insert(0, str(NEXT / "tests"))
|
||||
import test_next_praktika as tp
|
||||
script = tmp_path / "slow_search.py"
|
||||
script.write_text(textwrap.dedent("""
|
||||
import json, sys, time
|
||||
from pathlib import Path
|
||||
q = sys.argv[sys.argv.index("--") + 1]
|
||||
with Path(__file__).with_name("order.log").open("a", encoding="utf-8") as f:
|
||||
f.write(f"start {q}\\n")
|
||||
time.sleep(0.4)
|
||||
with Path(__file__).with_name("order.log").open("a", encoding="utf-8") as f:
|
||||
f.write(f"end {q}\\n")
|
||||
print(json.dumps({"results": []}))
|
||||
"""), encoding="utf-8")
|
||||
for name in ("preflight_search", "verify_act"):
|
||||
stub = tmp_path / f"stub_{name}.py"
|
||||
stub.write_text("import json; print(json.dumps([]))", encoding="utf-8")
|
||||
monkeypatch.setitem(core.TOOLS, name, [sys.executable, str(stub)])
|
||||
monkeypatch.setitem(core.TOOLS, "practice_search", [sys.executable, str(script)])
|
||||
with core.Run(make_case(tmp_path / "cases" / "c" / "d"), "FULL", "иск") as run:
|
||||
ctx = tp.make_ctx(run, [tp.vopros(1), tp.vopros(2), tp.vopros(3)])
|
||||
try:
|
||||
faza_praktika.praktika(run, ctx)
|
||||
except core.Stop:
|
||||
pass # пустая выдача может остановить фазу: порядок поиска уже записан
|
||||
lines = (tmp_path / "order.log").read_text(encoding="utf-8").splitlines()
|
||||
assert [x.split()[0] for x in lines[:3]] == ["start"] * 3 # все три стартовали до первого конца
|
||||
|
||||
|
||||
def test_agent_constants():
|
||||
assert core.AGENT_TIMEOUT == 300 or core.AGENT_TIMEOUT < 300 # 300 с (или меньше ради итога <= 600 с)
|
||||
assert len(core.PAUSES) == 1 # две попытки
|
||||
|
||||
|
||||
def test_hanging_cli_stops_within_600s(fake, run_, monkeypatch):
|
||||
pauses, waited = [], []
|
||||
monkeypatch.setattr(core.time, "sleep", pauses.append)
|
||||
fake.plan({"docx-reader": [HANG, HANG, HANG]})
|
||||
t0 = time.monotonic()
|
||||
with pytest.raises(core.Stop, match="таймаут"):
|
||||
ask(run_, timeout=0.5)
|
||||
assert len(fake.calls()) == 2 # две попытки, не три
|
||||
assert sum(pauses) + 2 * core.AGENT_TIMEOUT <= 600 # бюджет реального времени: таймауты + паузы
|
||||
assert time.monotonic() - t0 < 30
|
||||
|
||||
|
||||
def test_default_timeout_is_agent_timeout(fake, run_, monkeypatch):
|
||||
seen = []
|
||||
real = core._exec
|
||||
monkeypatch.setattr(core, "_exec", lambda argv, cwd, timeout, *a, **k: seen.append(timeout) or real(argv, cwd, timeout, *a, **k))
|
||||
fake.plan({"docx-reader": [{"structured_output": {"fakty": []}}]})
|
||||
ask(run_)
|
||||
assert seen == [core.role_timeout("docx-reader")] # T454: таймаут по роли
|
||||
|
||||
|
||||
def test_token_ceiling_stops_run(fake, run_, monkeypatch):
|
||||
monkeypatch.setattr(core, "MAX_TOKENS", 100)
|
||||
usage = {"input_tokens": 80, "output_tokens": 50}
|
||||
ok = {"structured_output": {"fakty": []}, "usage": usage}
|
||||
fake.plan({"docx-reader": [ok, ok]})
|
||||
ask(run_) # 130 токенов: потолок пробит, но стоп перед СЛЕДУЮЩИМ вызовом
|
||||
with pytest.raises(core.Stop, match="потолок токенов"):
|
||||
ask(run_)
|
||||
assert len(fake.calls()) == 1
|
||||
assert run_.state["tokens_total"] == 130
|
||||
|
||||
|
||||
def test_minutes_ceiling_stops_run(fake, run_, monkeypatch):
|
||||
monkeypatch.setattr(core, "MAX_MIN", 1)
|
||||
run_._t0 -= 61 # прогон идет уже 61 с > 1 мин
|
||||
fake.plan({"docx-reader": [{"structured_output": {"fakty": []}}]})
|
||||
with pytest.raises(core.Stop, match="потолок времени"):
|
||||
ask(run_)
|
||||
assert fake.calls() == []
|
||||
|
||||
|
||||
def test_ceiling_from_env():
|
||||
# отдельный процесс: reload(core) в этом пересоздал бы класс Stop, и pytest.raises(core.Stop) в соседних тестах промахивался
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
env = {**os.environ, "THEMIZ_MAX_TOKENS": "123", "THEMIZ_MAX_MIN": "7"}
|
||||
out = subprocess.run([sys.executable, "-c", "import core; print(core.MAX_TOKENS, core.MAX_MIN)"],
|
||||
cwd=core.ROOT / "themiz-next", env=env, capture_output=True, text=True, check=True).stdout
|
||||
assert out.split() == ["123", "7"]
|
||||
Reference in New Issue
Block a user