feat(765-3): 전처리 체인 = 지형마다 두 벌 — 다른 지형 먼저 짓고 묶음으로 떠 둠 → 설계 지형 → 추천 미리 셈 한 번 · 배수 늘 다시 셈 · 비우기에 묶음 · 죽은 run_redesign_chain 걷음
- run_preprocess_chain: WF1 자동 확정 · 서피스 바꿈 체인이 부름 · 다른 지형 없음 · 실패 = 한 벌 + meta.json 까닭 · 예상노선(공유)은 설계 지형 벌이 씀 - 자동 체인 배수 refresh=True — 저장분이 노선 바뀐 줄 모르던 틈 막음 - purge_output_folders 가 design_sets 도 지움 - run_redesign_chain(앱에서 부르는 곳 0) 걷음 — 시험 정리: test_342_2 의 그 함수 시험 셋 지움(함수 없음) · test_763_3 · test_351_1 은 두 벌 체인으로 · test_74 · test_user_values_survive 의 이월 차례 검사는 살아 있는 자리(B05_Profile_Route_Save)로 옮김 - 시험 test_765_design_sets 에 체인 차례 · 한 벌 · 다른 벌 실패 · 비우기 넷 덧 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -13,12 +13,13 @@ WF1(지표면 분석·자동 확정)이 끝나면 사용자가 화면에 없어
|
||||
사용자는 그 페이지에서 수동으로 이어서 진행할 수 있다.
|
||||
- 라우터 함수를 직접 호출한다(HTTP 재진입 없음). solve/confirm 엔드포인트는 인증
|
||||
의존성이 없는 순수 함수 시그니처라 서버 내부 호출이 가능하다.
|
||||
- **지형마다 한 벌**(765-3): 전처리 체인 = `run_preprocess_chain` — 다른 지형 벌을 먼저 지어
|
||||
`design_sets/` 묶음으로 떠 두고 설계 지형 벌을 지음(`common_util_design_sets`).
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import time
|
||||
from dataclasses import asdict
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from uuid import UUID
|
||||
@@ -311,7 +312,8 @@ async def run_auto_design_chain(
|
||||
|
||||
# 4.5) 배수유역 분석 → 관 지점 확정 → 배관 정착 계획선 재산출.
|
||||
# B06 확정 전에 끝내야 확정 스냅샷에 배관 정착 계획선이 담긴다.
|
||||
await _prepare_drainage_pipes_and_reprofile(project_id, route_id)
|
||||
# 배수는 늘 다시 셈(765-3) — 저장분은 노선이 바뀐 줄 모름(두 벌 · 서피스 바꿈 뒤 묵음).
|
||||
await _prepare_drainage_pipes_and_reprofile(project_id, route_id, refresh=True)
|
||||
|
||||
# 5) B06 횡단 설계 확정 — 미지정 측점을 기본값으로 채워 저장. stage 3은
|
||||
# IN_PROGRESS(스텝바 노란 표시)로 남겨 사용자 검토·확정을 기다린다.
|
||||
@@ -370,11 +372,94 @@ async def run_auto_design_chain(
|
||||
schedule_precompute(project_id)
|
||||
|
||||
|
||||
async def run_preprocess_chain(
|
||||
project_id: UUID, surface_model_id: int | None = None
|
||||
) -> dict[str, Any] | None:
|
||||
"""전처리 체인 = 지형마다 설계 한 벌(765-3 · 요구 605 · 606-1) — 결과 = 설계 지형 요약.
|
||||
|
||||
다른 지형 먼저 자동 설계 → 묶음으로 떠 둠(B05~B09 비움) → 설계 지형 자동 설계 → 추천 미리 셈
|
||||
한 번(실패 길에도). 다른 지형이 없으면(LAS 만 · 수치지형도 못 받음 · 수치지형도만) 한 벌 ·
|
||||
묶음 meta.json 에 까닭. 부르는 곳 = WF1 자동 확정 · 서피스 바꿈 체인(B04 다른 서피스 [확정] ·
|
||||
LAS 나중 올리기 뒤 전처리 다시). 묶음은 처음부터 다시(옛 벌 버림).
|
||||
"""
|
||||
from B03_FileInput.B03_FileInput_Repository import get_project_storage_relative_path
|
||||
from B05_Profile.B05_Profile_Router_RouteInitial import schedule_precompute
|
||||
from common_util import common_util_design_sets as sets
|
||||
from common_util.common_util_initial_snapshot import (
|
||||
clear_designing,
|
||||
mark_designing,
|
||||
read_design_failure,
|
||||
)
|
||||
from common_util.common_util_route_geometry import expected_route_csv_path
|
||||
from common_util.common_util_storage import resolve_stored_project_path
|
||||
from common_util.common_util_surface_confirmation import (
|
||||
design_terrain,
|
||||
get_surface_confirmation_params,
|
||||
)
|
||||
from config.config_db import get_db_pool
|
||||
|
||||
pool = get_db_pool()
|
||||
root: Path | None = None
|
||||
marks = [("시작", time.perf_counter())]
|
||||
try:
|
||||
async with pool.acquire() as connection:
|
||||
stored_path = await get_project_storage_relative_path(connection, project_id)
|
||||
params = await get_surface_confirmation_params(connection, str(project_id))
|
||||
if not stored_path:
|
||||
return None
|
||||
root = Path(resolve_stored_project_path(stored_path))
|
||||
mark_designing(root)
|
||||
sets.discard_sets(root)
|
||||
design = design_terrain(params)
|
||||
other = sets.other_terrain(params, root)
|
||||
if other is None:
|
||||
missing = "sheet" if design == "las" else "las"
|
||||
sets.note_unbuilt(root, missing, f"{missing} 지표면 모델 없음 — 한 벌만")
|
||||
else:
|
||||
# 예상노선(공유)은 설계 지형 벌이 씀 — 다른 지형으로 자른 것이 남지 않게
|
||||
expected = expected_route_csv_path(root)
|
||||
had_expected = expected.is_file()
|
||||
try:
|
||||
async with pool.acquire() as connection:
|
||||
model_id = await sets.switch_terrain(connection, project_id, other)
|
||||
built = await run_auto_design_chain(project_id, model_id, inner=True)
|
||||
async with pool.acquire() as connection:
|
||||
fingerprint = await sets.set_fingerprint(
|
||||
connection, str(project_id), root, other
|
||||
)
|
||||
if built and fingerprint:
|
||||
await sets.park_active_set(connection, root, str(project_id), fingerprint)
|
||||
else:
|
||||
await sets.clear_active_set(connection, root, str(project_id))
|
||||
sets.note_unbuilt(root, other, read_design_failure(root) or "짓기 실패")
|
||||
except Exception as exc: # noqa: BLE001 — 다른 벌 실패가 설계 지형 벌을 막지 않음
|
||||
logger.exception("두 벌 짓기 — %s 벌 실패: project_id=%s", other, project_id)
|
||||
async with pool.acquire() as connection:
|
||||
await sets.clear_active_set(connection, root, str(project_id))
|
||||
sets.note_unbuilt(root, other, f"짓기 오류: {exc}")
|
||||
finally:
|
||||
if not had_expected:
|
||||
expected.unlink(missing_ok=True)
|
||||
async with pool.acquire() as connection:
|
||||
await sets.switch_terrain(connection, project_id, design)
|
||||
marks.append((f"{other} 벌", time.perf_counter()))
|
||||
summary = await run_auto_design_chain(project_id, surface_model_id, inner=True)
|
||||
marks.append((f"{design} 벌", time.perf_counter()))
|
||||
_log_steps("전처리 체인 두 벌", marks)
|
||||
return summary
|
||||
except Exception:
|
||||
logger.exception("전처리 체인 실패: project_id=%s", project_id)
|
||||
return None
|
||||
finally:
|
||||
if root is not None:
|
||||
clear_designing(root)
|
||||
schedule_precompute(project_id) # 추천은 지형 · 예정노선만 씀 — 실패 길에도(763-3)
|
||||
|
||||
|
||||
async def _ensure_initial_polyline(
|
||||
project_id: UUID, project_root: Path, points: list[dict[str, float]]
|
||||
) -> None:
|
||||
"""계획노선 초기 폴리라인을 세운다 — 이미 있으면 그대로 둔다. 실패는 비치명적."""
|
||||
import asyncio
|
||||
|
||||
from B05_Profile.B05_Profile_Router_FollowLand import initial_land
|
||||
from B05_Profile.B05_Profile_Router_Replan import _ensure_planned_initial, _min_plan_radius_m
|
||||
@@ -445,247 +530,3 @@ def redesign_solve_request(
|
||||
start_elevation_offset_m=params.get("start_elevation_offset_m"),
|
||||
end_elevation_offset_m=params.get("end_elevation_offset_m"),
|
||||
)
|
||||
|
||||
|
||||
async def run_redesign_chain(
|
||||
project_id: UUID,
|
||||
surface_model_id: int,
|
||||
selection: dict[str, Any],
|
||||
profile_target: tuple[list[float], list[float]] | None = None,
|
||||
) -> str | None:
|
||||
"""B04 재확정 후 — **사용자 입력을 유지한 채** 새 지표면 기준으로 B05·B06 재계산·저장.
|
||||
|
||||
관리자가 B04에서 다른 지표면 모델로 재확정하면(2026-08-04 사용자 확정) 그 값을
|
||||
기준으로 다음 페이지들도 함께 갱신돼야 한다. 이때 일반 사용자가 이미 쓰던 설정은
|
||||
버리지 않는다:
|
||||
- B05: 저장된 stage 2 params(제어점 BP/EP/CP·회피/금지원·경사 옵션·측점 간격 등)를
|
||||
그대로 쓰고 **지표면(filter/method/smooth/model id)만** 새 확정값으로 바꾼다.
|
||||
- B06: 옛 경로의 측점별 설계(지반유형·단면유형·측구·암 경계)를 chainage 매칭으로
|
||||
새 경로에 이월하고, 표준단면 설정(data.options)도 함께 넘긴다. 나머지 미지정
|
||||
측점은 확정 시 기본값으로 채워진다.
|
||||
|
||||
경로가 아예 없으면 신규 자동 체인(계획노선 정본 기본값)으로 되돌아간다.
|
||||
|
||||
`profile_target`(누가거리 · 계획고)이 오면 1차 종단을 그 계획고로 세운다 — 노선 추천
|
||||
「종단 반영」 켬으로 [적용]한 노선의 균형 종단(PLAN 74-4). 없으면 계획고 = 지반고.
|
||||
"""
|
||||
from B03_FileInput.B03_FileInput_Repository import get_project_storage_relative_path
|
||||
from B05_Profile.B05_Profile_Repository import get_latest_route
|
||||
from B05_Profile.B05_Profile_Router import (
|
||||
_section_options,
|
||||
confirm_latest_route,
|
||||
solve_route_record,
|
||||
)
|
||||
from B06_Section.B06_Section_Repository import (
|
||||
get_cross_section_designs,
|
||||
get_latest_section_options,
|
||||
get_longitudinal_section,
|
||||
)
|
||||
from B06_Section.B06_Section_Repository_Bulk import merge_cross_section_designs
|
||||
from B06_Section.B06_Section_Router import regenerate_route_sections
|
||||
from B06_Section.B06_Section_Router_Confirm import _rowless_station_chainages, confirm_sections
|
||||
from B06_Section.B06_Section_Router_Design import CARRY_INPUT_KEYS, compute_default_designs
|
||||
from B06_Section.B06_Section_Schema import SectionConfirmRequest
|
||||
from common_util.common_util_initial_snapshot import (
|
||||
clear_designing,
|
||||
discard_initial_snapshot,
|
||||
mark_designing,
|
||||
)
|
||||
from common_util.common_util_storage import resolve_stored_project_path
|
||||
from common_util.common_util_workflow_state import get_workflow_state
|
||||
from config.config_db import get_db_pool
|
||||
|
||||
pool = get_db_pool()
|
||||
project_root: Path | None = None
|
||||
marks = [("시작", time.perf_counter())]
|
||||
try:
|
||||
async with pool.acquire() as connection:
|
||||
latest = await get_latest_route(connection, project_id)
|
||||
stored_path = await get_project_storage_relative_path(connection, project_id)
|
||||
if stored_path:
|
||||
project_root = Path(resolve_stored_project_path(stored_path))
|
||||
mark_designing(project_root)
|
||||
# 지표면이 바뀌면 옛 초기값은 다른 지형 기준이라 더는 기준이 아니다. 여기서
|
||||
# 다시 뜨지는 않는다 — 이 체인은 **사용자 입력을 유지한 채** 재계산하므로 그
|
||||
# 결과를 찍으면 편집이 섞인 가짜 초기값이 된다(2026-08-29 사용자 확정).
|
||||
if discard_initial_snapshot(project_root):
|
||||
logger.info("재확정 체인: 초기값 스냅샷 무효화 (project_id=%s)", project_id)
|
||||
if not latest:
|
||||
logger.info(
|
||||
"재확정 체인 → 기존 경로 없음, 신규 자동 체인으로: project_id=%s", project_id
|
||||
)
|
||||
await run_auto_design_chain(project_id, surface_model_id=surface_model_id)
|
||||
return
|
||||
|
||||
# 1) 사용자 입력 회수 — 마지막 경로 계산의 stage 2 params가 정본이다.
|
||||
old_route_id = int(latest["id"])
|
||||
async with pool.acquire() as connection:
|
||||
import aiomysql
|
||||
|
||||
async with connection.cursor(aiomysql.DictCursor) as cursor:
|
||||
state = await get_workflow_state(cursor, str(project_id))
|
||||
old_longitudinal = await get_longitudinal_section(connection, project_id, old_route_id)
|
||||
old_designs = await get_cross_section_designs(connection, old_route_id)
|
||||
old_section_options = await get_latest_section_options(connection, project_id)
|
||||
stage2 = next(
|
||||
(s for s in (state or {}).get("stages", []) if int(s.get("stage_no", -1)) == 2), None
|
||||
)
|
||||
params = (stage2 or {}).get("params") or {}
|
||||
points = params.get("points") or {}
|
||||
if not points.get("bp") or not points.get("ep"):
|
||||
logger.warning(
|
||||
"재확정 체인 중단(stage 2 params에 제어점 없음): project_id=%s", project_id
|
||||
)
|
||||
return "노선 제어점(BP·EP)이 없어 재계산할 수 없습니다."
|
||||
|
||||
marks.append(("준비·사용자입력 회수", time.perf_counter()))
|
||||
|
||||
# 2) B05 재계산 — 지표면 관련 값만 새 확정 선택으로 교체, 나머지는 사용자 저장분.
|
||||
request = redesign_solve_request(params, selection, surface_model_id)
|
||||
# 종횡단은 관을 정한 뒤 한 번만 만든다(342-2) — 여기서 만들면 아래 4c 가 통째로 덮는 헛일.
|
||||
solve_result: Any = await solve_route_record(project_id, request, generate_sections=False)
|
||||
if isinstance(solve_result, JSONResponse):
|
||||
# 사유까지 남긴다 — 상태 코드만으로는 무엇이 막았는지 못 짚는다(2026-09-06
|
||||
# 노선 편집 [확인]이 조용히 400 으로 끊겨 종횡단만 옛 노선에 남았음).
|
||||
try:
|
||||
reason = bytes(solve_result.body).decode("utf-8", "replace")[:300]
|
||||
except Exception: # noqa: BLE001 — 로그용이라 실패해도 흐름을 막지 않는다
|
||||
reason = "(본문 없음)"
|
||||
logger.error(
|
||||
"재확정 체인 중단(B05 재계산 실패): project_id=%s status=%s reason=%s",
|
||||
project_id,
|
||||
solve_result.status_code,
|
||||
reason,
|
||||
)
|
||||
return f"노선 재계산 실패({solve_result.status_code}): {reason}"
|
||||
new_route_id = int(solve_result.route_id)
|
||||
marks.append(("노선 재계산(solve)", time.perf_counter()))
|
||||
logger.info(
|
||||
"재확정 체인 B05 재계산 완료: project_id=%s %s→%s",
|
||||
project_id,
|
||||
old_route_id,
|
||||
new_route_id,
|
||||
)
|
||||
|
||||
# 3) 옛 측점별 사용자 설계 이월은 **측점을 다시 만든 뒤**(아래 5) 한다.
|
||||
# 여기서 하면 `_prepare_drainage_pipes_and_reprofile(refresh=True)` 가 측점을
|
||||
# 새로 만들며 덮어써 값이 사라진다(2026-09-06 실측: 다단 구간값 `extra_spans` 가
|
||||
# 노선 변경 뒤 0건이 됐음). 옛 설계는 `old_designs` 로 이미 손에 있다.
|
||||
carried = 0
|
||||
|
||||
# 4) B05 확정 → B06 확정(옛 표준단면 설정 이월, 미지정 측점 기본값 채움).
|
||||
# 재확정 후에도 stage 2·3은 IN_PROGRESS로 남겨 사용자 재검토를 받는다.
|
||||
confirm_result = await confirm_latest_route(project_id, None, mark_stage_complete=False)
|
||||
if isinstance(confirm_result, JSONResponse):
|
||||
logger.error(
|
||||
"재확정 체인 중단(B05 확정 실패): project_id=%s status=%s",
|
||||
project_id,
|
||||
confirm_result.status_code,
|
||||
)
|
||||
return f"노선 확정 실패({confirm_result.status_code})"
|
||||
marks.append(("B05 확정", time.perf_counter()))
|
||||
# 노선이 바뀌었으므로 배수유역·관 지점도 새 노선 기준으로 다시 만든다 — 옛 관 자리로
|
||||
# 계획선을 앉히면 전부 어긋나고, 저장분은 노선 변경을 스스로 알지 못한다.
|
||||
# 건너뛴 첫 생성이 남겼을 옵션(요청 → 옛 저장 → 기본) — 재생성이 그것을 읽어 결과가 같다.
|
||||
seed = asdict(_section_options(request, old_section_options))
|
||||
seed.pop("extra_stations", None)
|
||||
piped = await _prepare_drainage_pipes_and_reprofile(
|
||||
project_id, new_route_id, refresh=True, stored_options=seed
|
||||
)
|
||||
if not piped:
|
||||
# 관 없이라도 종횡단은 세운다 — 새 노선엔 아직 종횡단이 없다(첫 생성을 건너뜀).
|
||||
await regenerate_route_sections(
|
||||
project_id, new_route_id, float(seed["cross_half_width_m"]), stored_options=seed
|
||||
)
|
||||
|
||||
marks.append(("배수·관·측점 재생성", time.perf_counter()))
|
||||
|
||||
if profile_target is not None:
|
||||
from B05_Profile.B05_Profile_Router_RouteInitial import apply_profile_target
|
||||
|
||||
await apply_profile_target(project_id, new_route_id, profile_target)
|
||||
marks.append(("균형 종단 반영", time.perf_counter()))
|
||||
|
||||
old_options = ((old_longitudinal or {}).get("data") or {}).get("options") or {}
|
||||
standard = old_options.get("standard_cross_section") or None
|
||||
|
||||
# 5) 이제 측점이 새 노선 기준으로 다 섰다 — 옛 사용자 **입력**만 누가거리로 얹고 전 측점을
|
||||
# 새 계획고로 다시 셈한다(PLAN 74-3). 결과 칸(계획고 · 면적 · design_line …)을 통째
|
||||
# 옮기면 옛 노선 단면이 새 노선에 남아 누가토량이 두 배가 됐다(74-1). 새 노선에 없는
|
||||
# 누가거리는 행을 만들지 않는다.
|
||||
try:
|
||||
inputs = {
|
||||
round(float(record["chainage_m"]), 3): {
|
||||
key: record["design"][key]
|
||||
for key in CARRY_INPUT_KEYS
|
||||
if record["design"].get(key) is not None
|
||||
}
|
||||
for record in old_designs
|
||||
if isinstance(record.get("design"), dict)
|
||||
}
|
||||
async with pool.acquire() as connection:
|
||||
new_longitudinal = await get_longitudinal_section(
|
||||
connection, project_id, new_route_id
|
||||
)
|
||||
long_path = str((new_longitudinal or {}).get("longitudinal_file_path") or "")
|
||||
chainages = await asyncio.to_thread(
|
||||
_rowless_station_chainages, project_root, long_path, []
|
||||
)
|
||||
entries = await asyncio.to_thread(
|
||||
compute_default_designs, project_root, long_path, chainages, standard, inputs
|
||||
)
|
||||
async with pool.acquire() as connection:
|
||||
await connection.begin()
|
||||
try:
|
||||
carried = await merge_cross_section_designs(
|
||||
connection,
|
||||
route_id=new_route_id,
|
||||
entries=entries,
|
||||
replace=True,
|
||||
project_id=project_id,
|
||||
)
|
||||
await connection.commit()
|
||||
except Exception:
|
||||
await connection.rollback()
|
||||
raise
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"재확정 체인 — 옛 설계 이월 실패(계속 진행): project_id=%s", project_id
|
||||
)
|
||||
logger.info("재확정 체인 설계 이월: project_id=%s %d건", project_id, carried)
|
||||
|
||||
marks.append(("설계 이월", time.perf_counter()))
|
||||
|
||||
section_request = (
|
||||
SectionConfirmRequest(standard_cross_section=standard) if standard else None
|
||||
)
|
||||
sections_result = await confirm_sections(
|
||||
project_id, new_route_id, section_request, mark_stage_complete=False
|
||||
)
|
||||
if isinstance(sections_result, JSONResponse):
|
||||
logger.error(
|
||||
"재확정 체인 중단(B06 확정 실패): project_id=%s status=%s",
|
||||
project_id,
|
||||
sections_result.status_code,
|
||||
)
|
||||
return f"종횡단 확정 실패({sections_result.status_code})"
|
||||
marks.append(("B06 확정(서버 재계산 포함)", time.perf_counter()))
|
||||
_log_steps("재확정 체인", marks)
|
||||
logger.info(
|
||||
"재확정 체인 완료: project_id=%s route %s→%s (설계 %d건 이월)",
|
||||
project_id,
|
||||
old_route_id,
|
||||
new_route_id,
|
||||
carried,
|
||||
)
|
||||
return None
|
||||
except Exception as exc:
|
||||
logger.exception("재확정 체인 실패: project_id=%s", project_id)
|
||||
return f"재계산 중 오류: {exc}"
|
||||
finally:
|
||||
if project_root is not None:
|
||||
clear_designing(project_root)
|
||||
# 성공 · 실패 · 건너뜀 어느 쪽이든 추천 미리 셈 예약(763-3) — 추천은 지형 · 예정노선만 씀
|
||||
from B05_Profile.B05_Profile_Router_RouteInitial import schedule_precompute
|
||||
|
||||
schedule_precompute(project_id)
|
||||
|
||||
Reference in New Issue
Block a user