Files
themiz/themiz-next/tests/test_next_full.py
T

279 lines
14 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import json
import re
import sys
import time
from decimal import Decimal
from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import core # noqa: E402
import faza_dokument # noqa: E402
from next_helpers import events # noqa: E402
CANARY = "КАНАРЕЙКА-ТЕКСТ-МАТЕРИАЛА"
TAKTIK, DEVIL = "position-council/taktik", "position-council/advokat-dyavola"
SVOD, OBJECTION = "СВОД-ПРЕДСЕДАТЕЛЯ", "ВОЗРАЖЕНИЕ-МАКЛАКОВА"
POSITION = {
"trebovaniya": [
{"obekt": "квартира", "trebovanie": "Признать право на 1/2 доли в квартире", "osnovanie": "п. 1 ст. 39 СК РФ"},
{"obekt": "автомобиль", "trebovanie": "Признать право на 1/3 доли в автомобиле", "osnovanie": "п. 1 ст. 39 СК РФ"},
],
"dovody": [{"tezis": "Имущество нажито в браке", "istochnik": "п. 1 ст. 34 СК РФ"}],
"riski": ["особое мнение: адвокат дьявола — 3 000 000 рублей подтверждены только пояснениями"],
}
def fact(tema, znachenie, status="ок", page=1):
return {"tema": tema, "znachenie": znachenie, "fail": "01.md", "str": page, "status": status}
def make_ctx(run_):
"""Выжимка дела: два вопроса, четыре факта (третий никто не называет), один акт."""
(run_.case / "00_intake" / "01.md").write_text(f"{CANARY}\n", encoding="utf-8")
return {
"texts": {"01.md": str(run_.case / "00_intake" / "01.md")},
"voprosy": [
{"id": "В1", "vopros": "Нажита ли квартира в браке?", "fakty": [0, 1]},
{"id": "В2", "vopros": "Делится ли автомобиль?", "fakty": [1, 3]},
],
"fakty": [
fact("срок брака", "с 10.06.2012 по 10.02.2026"),
fact("цена квартиры", "8 000 000 рублей", "ОСПОРЕНО", 2),
fact("лишний факт", "ЛИШНИЙ-ФАКТ"),
fact("автомобиль", "куплен в 2020 году", page=3),
],
"akty": [{"nomer": "33-7458/2026", "data": "02.03.2026", "sud": "Мосгорсуд", "url": "", "ustanovka": "za",
"tezis": "Режим общего имущества не меняется регистрацией на одного супруга", "vopros": "В1"}],
}
def voice(text, sleep=0):
return {"structured_output": {"tekst": text}, "sleep": sleep}
def areopag_plan(sleep=0):
"""Исходы Ареопага по ролям: у каждого высказывание; Урусов еще свод и итог, Маклаков еще возражение."""
plan = {role: [voice(f"голос {role}", sleep)] for role in faza_dokument.AREOPAG}
plan[TAKTIK] += [voice(SVOD), {"structured_output": POSITION}]
plan[DEVIL] += [voice(OBJECTION)]
return plan
@pytest.fixture
def full(run_):
"""Прогон на треке FULL."""
run_.track = "FULL"
return run_
def positions_md(run_):
return core.context(run_.case) / "positions.md"
def put_stale(run_):
"""Позиция прошлого прогона с маркером совета; возвращает ее текст."""
old = f"# Позиция прошлого прогона\n\n{faza_dokument.FULL_MARKER}\n"
positions_md(run_).parent.mkdir(parents=True, exist_ok=True)
positions_md(run_).write_text(old, encoding="utf-8")
return old
def check_every_question_has_facts(stdin, count):
"""У каждого из count вопросов выжимки есть факт, и каждый названный номер показан строкой факта."""
rows = re.findall(r"(?m)^В\d+\..*\(факты: ([\d, ]*)\)$", stdin)
assert len(rows) == count
for row in rows:
numbers = [n for n in row.split(", ") if n]
assert numbers
assert all(re.search(rf"(?m)^\[{n}\] ", stdin) for n in numbers)
def system_of(call):
return call["argv"][call["argv"].index("--system-prompt") + 1]
def test_areopag_five_parallel(fake, full):
ctx = make_ctx(full)
fake.plan(areopag_plan(sleep=1))
started = time.monotonic()
faza_dokument.pozitsiya(full, ctx)
assert time.monotonic() - started < 2.5 # подряд было бы не меньше 5 с
assert {call["role"] for call in fake.calls()[:5]} == set(faza_dokument.AREOPAG)
spoke = {event["who"] for event in events(full) if event["phase"] == "pozitsiya" and event["state"] == "ok"}
assert set(faza_dokument.AREOPAG) <= spoke # табло ведет роли по фазе и имени роли
def test_areopag_digest_only_cited_facts(fake, full):
ctx = make_ctx(full)
fake.plan(areopag_plan())
faza_dokument.pozitsiya(full, ctx)
for call in fake.calls()[:5]:
stdin = call["stdin"]
assert CANARY not in stdin and "ЛИШНИЙ-ФАКТ" not in stdin
assert "В2. Делится ли автомобиль? (факты: 1, 2)" in stdin # номера в выжимке общие у вопроса и факта
assert "[2] автомобиль: куплен в 2020 году" in stdin and "[1] цена квартиры: 8 000 000 рублей" in stdin
assert "ОСПОРЕНО" in stdin and "33-7458/2026" in stdin
assert "не влезли" not in stdin # ничего не срезано
def test_areopag_input_within_micro_limit(fake, full):
ctx = make_ctx(full)
cited = len(ctx["fakty"])
ctx["fakty"] += [fact(f"тема {n}", "значение " * 30) for n in range(200)]
ctx["voprosy"][0]["fakty"] += range(cited, len(ctx["fakty"]))
fake.plan(areopag_plan())
faza_dokument.pozitsiya(full, ctx)
circle = fake.calls()[:5]
assert {call["role"] for call in circle} == set(faza_dokument.AREOPAG)
for call in circle:
stdin = call["stdin"]
assert len(stdin) <= faza_dokument.MICRO_LIMIT
assert "срок брака" in stdin and "33-7458/2026" in stdin # вопросы, акты и первые факты на месте
assert "тема 0:" in stdin and "тема 199" not in stdin # длинный список вопроса режется с хвоста
assert "автомобиль: куплен в 2020 году" in stdin # единственный факт второго вопроса цел
assert "не влезли в предел выжимки" in stdin
check_every_question_has_facts(stdin, 2)
cut = [int(m[1]) for event in events(full) if (m := re.search(r"срезано фактов (\d+)", event["action"]))]
assert cut and cut[0] > 0 # сколько срезано, видно на табло
def test_areopag_every_question_keeps_a_fact(fake, full):
ctx = make_ctx(full)
ctx["fakty"] = [fact(f"тема {n}", "значение " * 100) for n in range(36)]
ctx["voprosy"] = [{"id": f"В{q}", "vopros": f"Вопрос {q}?", "fakty": list(range(6 * q - 6, 6 * q))} for q in range(1, 7)]
ctx["akty"] = [{**ctx["akty"][0], "nomer": f"33-{n}/2026", "tezis": "тезис " * 160} for n in range(24)]
fake.plan(areopag_plan())
faza_dokument.pozitsiya(full, ctx)
for call in fake.calls()[:5]:
assert len(call["stdin"]) <= faza_dokument.MICRO_LIMIT
assert "не влезли в предел выжимки" in call["stdin"] # факты все-таки срезаны
check_every_question_has_facts(call["stdin"], 6)
def test_areopag_digest_without_room_stops(fake, full):
ctx = make_ctx(full)
ctx["akty"] = [{**ctx["akty"][0], "tezis": "тезис " * 400} for _ in range(30)]
put_stale(full)
with pytest.raises(core.Stop, match="микровыжимк"):
faza_dokument.pozitsiya(full, ctx)
assert fake.calls() == [] and not positions_md(full).exists()
def test_stale_council_marker_does_not_survive_stop(fake, full):
ctx = make_ctx(full)
old = put_stale(full)
plan = areopag_plan()
plan["position-council/processualist"] = [{"code": 2, "stdout": "сбой"}]
fake.plan(plan)
with pytest.raises(core.Stop, match="processualist"):
faza_dokument.pozitsiya(full, ctx)
assert not positions_md(full).exists() # старые ворота не примут прерванный прогон за согласованный
assert (full.dir / "positions.prev.md").read_text(encoding="utf-8") == old # прежняя позиция сохранена
def test_areopag_system_prompts(fake, full):
ctx = make_ctx(full)
fake.plan(areopag_plan())
faza_dokument.pozitsiya(full, ctx)
calls = fake.calls()
for call in calls:
first, angle, *_ = system_of(call).split("\n")
assert first == f"РОЛЬ: {call['role']}" and angle == faza_dokument.ANGLES[call["role"]][1]
assert "по каждому объекту" in system_of(call)
for part in ("`za` — акт в нашу пользу", "`protiv` — акт, на который сошлется оппонент", "`process` — акт о процессе",
"На этапе 4 номера в позицию не переноси: факт называй по теме"):
assert part in system_of(call)
assert [system_of(call).splitlines()[-1] for call in calls] == ["Сейчас этап 1."] * 5 + [f"Сейчас этап {n}." for n in (2, 3, 4)]
def test_chair_then_maklakov_then_final(fake, full):
ctx = make_ctx(full)
fake.plan(areopag_plan())
faza_dokument.pozitsiya(full, ctx)
calls = fake.calls()
assert [call["role"] for call in calls[5:]] == [TAKTIK, DEVIL, TAKTIK]
svod, objection, final = calls[5:]
assert all(f"голос {role}" in svod["stdin"] for role in faza_dokument.AREOPAG)
assert SVOD in objection["stdin"] and OBJECTION not in objection["stdin"]
assert SVOD in final["stdin"] and OBJECTION in final["stdin"]
required = [json.loads(call["argv"][call["argv"].index("--json-schema") + 1])["required"] for call in calls[5:]]
assert required == [["tekst"], ["tekst"], ["trebovaniya", "dovody", "riski"]]
assert ctx["pozitsiya"] == POSITION
def test_full_positions_marker(fake, full):
ctx = make_ctx(full)
fake.plan(areopag_plan())
faza_dokument.pozitsiya(full, ctx)
md = positions_md(full).read_text(encoding="utf-8")
assert faza_dokument.FULL_MARKER in md.splitlines() and "СОГЛАСОВАНО СОВЕТОМ" in faza_dokument.FULL_MARKER
assert faza_dokument.FAST_MARKER not in md
for item in POSITION["trebovaniya"]:
assert f"### {item['obekt']}" in md and item["trebovanie"] in md
assert POSITION["riski"][0] in md
def test_fast_track_has_no_council(fake, run_):
ctx = make_ctx(run_)
fake.plan({TAKTIK: [{"structured_output": POSITION}]})
faza_dokument.pozitsiya(run_, ctx)
assert [call["role"] for call in fake.calls()] == [TAKTIK]
md = positions_md(run_).read_text(encoding="utf-8")
assert faza_dokument.FAST_MARKER in md.splitlines() and "СОГЛАСОВАНО СОВЕТОМ" not in md
def test_failed_role_stops_without_marker(fake, full):
ctx = make_ctx(full)
plan = areopag_plan()
plan["position-council/processualist"] = [{"code": 2, "stdout": "сбой"}]
fake.plan(plan)
with pytest.raises(core.Stop, match="processualist"):
faza_dokument.pozitsiya(full, ctx)
assert len(fake.calls()) == 5 and not positions_md(full).exists()
def test_empty_voice_stops(fake, full):
ctx = make_ctx(full)
plan = areopag_plan()
plan["position-council/prokuror"] = [voice(" ")]
fake.plan(plan)
with pytest.raises(core.Stop, match="prokuror"):
faza_dokument.pozitsiya(full, ctx)
assert len(fake.calls()) == 5 and not positions_md(full).exists()
def test_final_without_requirements_stops(fake, full):
ctx = make_ctx(full)
plan = areopag_plan()
plan[TAKTIK][2] = {"structured_output": {**POSITION, "trebovaniya": []}}
fake.plan(plan)
with pytest.raises(core.Stop, match="без требований"):
faza_dokument.pozitsiya(full, ctx)
assert not positions_md(full).exists() and "pozitsiya" not in ctx
def test_full_final_answer_prices_the_claim(fake, full, monkeypatch):
"""Цена иска идет от итога Ареопага так же, как от ответа Урусова: стоимость из оспоренного факта не годится, доля берется из требования."""
monkeypatch.setitem(core.TOOLS, "gosposhlina", [sys.executable, "-c", "print('К УПЛАТЕ: 44 200 руб.')"])
def decide(flat):
ctx = make_ctx(full)
ctx["fakty"] += [fact("стоимость автомобиля", "оценка 1 000 000 руб."), fact("стоимость участка", "оценка 2 500 000 руб.")]
rows = POSITION["trebovaniya"] # квартира 1/2, автомобиль 1/3
final = {**POSITION, "trebovaniya": [{**rows[0], "stoimost": flat, "dolya": "1/2"},
{**rows[1], "stoimost": "1 000 000 руб.", "dolya": "1/3"}]}
plan = areopag_plan()
plan[TAKTIK][2] = {"structured_output": final}
fake.plan(plan)
faza_dokument.pozitsiya(full, ctx)
return ctx
ctx = decide("8 000 000 руб.") # такая сумма названа только в факте ОСПОРЕНО
assert ctx["nedostaet"] == ["стоимость объекта квартира"] and "cena" not in ctx
ctx = decide("2 500 000 руб.")
assert ctx["nedostaet"] == [] and ctx["cena"] == Decimal("1583333.33") and ctx["poshlina"] == 44200 # 1/2 от 2,5 млн и 1/3 от 1 млн
assert "Цена иска: 1 583 333,33 руб.; госпошлина: 44 200 руб." in positions_md(full).read_text(encoding="utf-8")