fix(505-1 B05): 추천 노선 미리 셈 = 전처리 체인에서만 · 프로젝트 접근은 저장본 읽기만

- B05 열기(GET /route/plan) 미리 셈 예약 걷음 · 체인 쪽(업로드 · B04 재확정 · B01 사용 범위) 그대로
- 추천 창 기본 갈래(기본 다섯 · 저장 제약 · 종단 켬 · 설계 지형) = 저장본만 · 없으면 409 「전처리를 다시 하면 생깁니다」(판 글 · 토스트)
- 사용자가 바꾼 제약 · 비중 · 종단 끔 · 다른 분석 지형 · [재계산] = 그 자리 셈
- 화면이 실은 분석 지형이 설계 지형과 같으면 설계 지형으로 봄
- 저장본 꺼내기 path.touch 걷음 · 초기 종단 지문 노선 파일 칸 걷음(셈이 안 읽음) · 초기 종단 지문 함수 캐시
- B04 _prepare 재투영 · 피클 읽기 · followed_pipes 스레드로
- 시험 test_309_3 새로 · 224_3 · 364_4 · 476_1 새 규칙에 맞춤

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-21 13:14:33 +09:00
co-authored by Claude Opus 5.5
parent 163ab72881
commit d42726030e
12 changed files with 226 additions and 66 deletions
@@ -196,15 +196,16 @@ def wired(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> _Calls:
return calls
def _ask(**fields) -> dict:
def _ask(precompute: bool = True, **fields) -> dict:
"""`precompute` 참 = 전처리 체인 셈 · 거짓 = 화면 요청(기본 갈래는 저장본만 · 505-1)."""
request = replan.RouteInitialRequest(**fields)
return asyncio.run(router.compute_initial(uuid4(), request))
return asyncio.run(router.compute_initial(uuid4(), request, precompute))
def test_second_request_computes_nothing(wired: _Calls) -> None:
first = _ask(mode="earthwork")
assert wired.count == 1 and first["stored"] is False
second = _ask(mode="earthwork")
second = _ask(False, mode="earthwork")
assert wired.count == 1 and second["stored"] is True
assert second["planned"] == first["planned"]
# 덮개 수는 꺼낼 때마다 지금 관으로 · 저장본에는 없음
@@ -226,7 +227,8 @@ def test_same_pool_in_flight_waits(wired: _Calls) -> None:
request = replan.RouteInitialRequest(mode="gentle")
project = uuid4()
return await asyncio.gather(
router.compute_initial(project, request), router.compute_initial(project, request)
router.compute_initial(project, request, True),
router.compute_initial(project, request, True),
)
results = asyncio.run(both())
@@ -245,6 +247,6 @@ def test_precompute_defaults_then_hits(wired: _Calls) -> None:
assert all(item["default"] for item in saved)
# 화면 첫 누름(비중은 화면이 50/25/25 를 채워 보냄 · 다섯 갈래 종단 켬 · 420) — 셈 없이 저장본
assert all(item["request"]["with_profile"] for item in saved)
hit = _ask(mode="weighted", weights={"expected": 50, "earthwork": 25, "grade": 25})
follow = _ask(mode="follow")
hit = _ask(False, mode="weighted", weights={"expected": 50, "earthwork": 25, "grade": 25})
follow = _ask(False, mode="follow")
assert hit["stored"] and follow["stored"] and wired.count == 5
@@ -0,0 +1,141 @@
"""요구 309-3 · 310 · PLAN 505-1 — 추천 노선 미리 셈 = 전처리 체인에서만.
./venv/Scripts/python.exe -m pytest resources/tester/test_309_3_recommend_preprocess_only.py -q
B05 열기(GET /route/plan) · 노선 [저장] · [적용] 뒤 다시 세움 = 미리 셈 0 · 저장본 읽기만(파일
안 건드림) · 미리 셈 갈래가 저장본에 없으면 409 「전처리를 다시 하면 생김」 · 사용자가 바꾼 값 ·
[재계산]은 그 자리 셈 · 체인 셈(`run_precompute`)이 만들면 화면이 꺼냄 · 초기 종단 지문에 노선
파일 없음.
"""
from __future__ import annotations
import asyncio
import json
import os
import re
import sys
from pathlib import Path
from uuid import uuid4
ROOT = Path(__file__).resolve().parents[2]
TESTER = Path(__file__).resolve().parent
for path in (ROOT, TESTER):
if str(path) not in sys.path:
sys.path.insert(0, str(path))
import helper_472_1_paths as P # noqa: E402
from test_224_2_station_snap import _NODES, _patch_replan, _working # noqa: E402
from test_224_3_recommend_store import _ask, wired # noqa: E402, F401 — 가짜 세계 fixture
from test_476_1_recommend_initial import gather # noqa: E402, F401
from B05_Profile import B05_Profile_Engine_InitialProfile as ip # noqa: E402
from B05_Profile import B05_Profile_Router_RouteInitial as router # noqa: E402
from B05_Profile.B05_Profile_Engine_RouteInitial_Store import ( # noqa: E402
DEFAULT_MODES,
read_stored,
store_dir,
write_stored,
)
def test_B05_열기_미리_셈_0(tmp_path: Path, monkeypatch) -> None:
import B03_FileInput.B03_FileInput_Router_Helpers as helpers
scheduled: list[str] = []
monkeypatch.setattr(
helpers,
"_schedule_background_task",
lambda coroutine, task_name: (scheduled.append(task_name), coroutine.close()),
)
replan = _patch_replan(monkeypatch, tmp_path)
replan._write_planned_polyline(_working(tmp_path), _NODES, 30.0, simplify=False)
body = asyncio.run(replan.read_route_plan(uuid4()))
assert body["status"] == "success" and scheduled == []
assert not store_dir(tmp_path).exists()
def test_미리_셈_부르는_곳은_체인만() -> None:
"""노선 [저장] · [적용] · B05 열기 길에는 미리 셈 호출이 없음 — 체인 둘 · B01 사용 범위만."""
callers = set()
for path in ROOT.glob("B0*/*.py"):
text = path.read_text(encoding="utf-8")
if re.search(r"\b(schedule_precompute|run_precompute|refresh_expected_route)\(", text):
callers.add(path.name)
assert callers == {
"B03_FileInput_Service_Chain.py", # 업로드 체인 · B04 재확정 체인
"B01_Dashboard_Router.py", # 사용 범위 바꿈 = 예상노선 다시 씀
"B05_Profile_Router_RouteInitial.py", # 정의
}
def test_화면_기본_갈래_저장본_없으면_409_셈_0(wired) -> None: # noqa: F811
for mode in DEFAULT_MODES:
response = _ask(False, mode=mode)
assert response.status_code == 409
assert "전처리를 다시 하면 생깁니다" in json.loads(response.body)["message"]
assert wired.count == 0 and not list(store_dir(wired.root).glob("*.json"))
def test_체인이_만들면_화면이_꺼냄(wired) -> None: # noqa: F811
asyncio.run(router.run_precompute(uuid4())) # 체인 끝 예약이 도는 한 줄
assert wired.count == 5
for mode in DEFAULT_MODES:
assert _ask(False, mode=mode)["stored"] is True
assert wired.count == 5
def test_화면이_실은_분석_지형이_설계_지형이면_기본_갈래(wired) -> None: # noqa: F811
"""화면은 늘 분석 지형을 실음 — 설계 지형(가짜 세계 = 라이다)과 같으면 저장본만 · 다르면 셈."""
assert _ask(False, mode="gentle", terrain="las").status_code == 409
assert wired.count == 0
assert _ask(False, mode="gentle", terrain="sheet")["stored"] is False
assert wired.count == 1
def test_사용자가_바꾼_값_재계산은_셈(wired) -> None: # noqa: F811
assert _ask(False, mode="earthwork", criteria={"min_radius_m": 15.0})["stored"] is False
assert _ask(False, mode="earthwork", with_profile=False)["stored"] is False
assert wired.count == 2
assert _ask(False, mode="gentle", recompute=True)["stored"] is False
assert wired.count == 3
def test_초기_종단_화면은_저장본만(wired, monkeypatch) -> None: # noqa: F811
import B05_Profile.B05_Profile_Router_RouteInitial_Initial as gatherer
flags: list[bool] = []
async def fake(project_id, root, stored, result, request, selection, key, compute=True):
flags.append(compute)
return {"pvi_count": 3}
monkeypatch.setattr(gatherer, "initial_profile_of", fake)
_ask(True, mode="earthwork") # 체인
_ask(False, mode="earthwork") # 화면 기본 갈래
_ask(False, mode="earthwork", criteria={"min_radius_m": 15.0}) # 사용자가 바꾼 값
assert flags == [True, False, True]
def test_꺼내기는_파일_안_건드림(tmp_path: Path) -> None:
write_stored(tmp_path, "k", "p", {"mode": "gentle"}, {"nodes": []}, True)
path = store_dir(tmp_path) / "k.json"
os.utime(path, ns=(1_000_000_000, 1_000_000_000))
assert read_stored(tmp_path, "k") is not None
assert path.stat().st_mtime_ns == 1_000_000_000
def test_초기_종단_지문에_노선_파일_없음(gather, monkeypatch) -> None: # noqa: F811
first = gather["run"]()
assert "error" not in first, first
assert gather["run"]("k2", False) == {"error": router.NOT_PREPARED} # 저장본 없음 = 셈 안 함
def broken(*args, **kwargs):
raise RuntimeError("다시 셈")
monkeypatch.setattr(ip, "initial_longitudinal", broken)
route = gather["root"] / P.ROUTE
doc = json.loads(route.read_text("utf-8"))
doc["properties"] = {**(doc.get("properties") or {}), "saved": "노선 [저장]"}
route.write_text(json.dumps(doc), "utf-8") # 노선 [저장] = 노선 파일만 바뀜
assert gather["run"]("k1", False) == first
@@ -65,7 +65,8 @@ def test_실패해도_진행_비움(monkeypatch) -> None:
def test_b05_열기_예약_모달_진행_배선() -> None:
replan = (ROOT / "B05_Profile/B05_Profile_Router_Replan.py").read_text(encoding="utf-8")
plan = replan[replan.index("async def read_route_plan") :]
assert "schedule_precompute(project_id)" in plan[: plan.index("\n@router")]
# 505-1 — B05 열기는 미리 셈 안 부름(전처리 체인에서만)
assert "schedule_precompute(" not in plan[: plan.index("\n@router")]
source = (ROOT / "B05_Profile/B05_Profile_Router_RouteInitial.py").read_text(encoding="utf-8")
assert '"/{project_id}/route/initial/progress"' in source
# 체인 · B01 범위도 같은 한 줄(run_precompute)로
@@ -88,7 +89,8 @@ def test_모달이_여는_갈래_먼저(monkeypatch) -> None:
async def paths(_pid):
return (ROOT, None)
async def compute(_pid, request):
async def compute(_pid, request, precompute=False):
assert precompute # 체인 셈 = 저장본 없어도 셈(505-1)
asked.append(request.mode)
assert request.with_profile # 다섯 갈래 모두 종단 켬(420)
return {}
@@ -334,9 +334,11 @@ def gather(tmp_path, monkeypatch):
candidate = _candidate(root)
selection = {"source_filter": "classification", "method": "dtm", "smooth": True}
def run(key: str = "k1") -> dict:
def run(key: str = "k1", compute: bool = True) -> dict:
return asyncio.run(
gatherer.initial_profile_of(uuid4(), root, "p", candidate, request, selection, key)
gatherer.initial_profile_of(
uuid4(), root, "p", candidate, request, selection, key, compute
)
)
return {"run": run, "root": root, "state": state, "pipes": pipes_file}
@@ -392,7 +394,7 @@ def test_추천_응답에_initial_profile(wired, monkeypatch):
seen: list = []
async def fake(project_id, root, stored, result, request, selection, key):
async def fake(project_id, root, stored, result, request, selection, key, compute=True):
seen.append(key)
return {"pvi_count": 3}