Phase 0.7 — Acceptance Gate 자동화 + LM Studio 통합 + OntoCast 버그 수정

- platform/ → ont_platform/ rename
  Python 내장 platform 모듈과 이름 충돌. numpy/scipy가 platform.machine() 호출 시
  우리 패키지를 가져와 AttributeError. ont_platform으로 변경하고 pyproject.toml,
  ont_platform/**, tests/** import 경로 모두 업데이트.

- ont_platform/config.py: lenient LLM builder 추가
  LM Studio/vLLM 등 OpenAI-호환 로컬 서버가 임의 모델 식별자(예: deepseek-r1-distill-
  qwen-7b)를 쓸 수 있도록 OntoCast의 OpenAIModel enum validation을 Pydantic
  model_construct로 우회. ToolConfig() 생성 시 충돌을 막기 위해 LLM_MODEL_NAME을
  잠시 비웠다가 lenient 인스턴스로 교체.

- ont_platform/api/deps.py: ToolBox 초기화를 asyncio.to_thread로 격리
  LLMTool.create()가 내부에서 asyncio.run()을 부르는데 lifespan/테스트가 이미
  async 컨텍스트라 이중 loop 충돌. 별도 스레드에서 sync 생성자 실행.

- 테스트 인프라 정비
  * tests/integration/test_api_smoke.py: TestClient 구버전 starlette 호환을 위해
    lifespan='off' 대신 app.router.lifespan_context = noop 패턴 적용.
  * tests/unit/test_convert_document.py, test_select_ontology.py: ontocast.agent
    __init__.py가 re-export한 함수가 서브모듈을 가리는 문제로 sys.modules에서
    실제 모듈 객체 직접 추출.
  * tests/e2e/conftest.py: .env 자동 로드 + provider별 skip 조건 (Ollama는
    LLM_API_KEY 불필요).
  * tests/e2e/test_phase0_full_pipeline.py: provider별 키 분기,
    HDBSCAN 클러스터링이 동작하도록 fixture 페이로드 16문장으로 확장.

- vendored OntoCast 버그 수정 3건 (VENDORED_MODIFICATIONS.md 기록):
  * agent/render_ontology.py: render_ontology_fresh()의 .format() 호출에 누락된
    ontology_prefix 인자 추가 (Bootstrap 단계에서 KeyError: 'ontology_prefix').
  * stategraph/node_factories.py: render_ontology/render_facts 노드의
    state.model_copy(deep=True)로 budget_tracker가 deep-copy되어 root state의
    BudgetTracker가 영원히 0인 채로 남던 버그 수정. 원본 인스턴스 공유로 변경.

- 문서 갱신
  README.md (Phase 0.7 부분완료 + ont_platform 폴더 이름),
  docs/phases/PHASE0_ACCEPTANCE_GATE.md (검증 이력 + Ollama/LM Studio 옵션),
  .env.example (LM Studio/Ollama/OpenAI 세 옵션 명시).

검증
- unit + integration 26/26 통과.
- e2e (LM Studio + Qwen3-8B / DeepSeek-R1-Distill-Qwen-7B): 워크플로우 끝까지
  실행 + 5번 LLM 호출 + LangGraph 전 노드 traceable 확인. 7-8B 로컬 모델은
  strict structured output(Turtle RDF in JSON) 한계로 ontology/facts TTL 자동
  생성 부분 성공. 클라우드 LLM 환경에서 재검증 필요.

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
This commit is contained in:
lasta
2026-05-14 09:05:24 +09:00
parent 9e88f4c7ad
commit ec4f9a64f6
26 changed files with 237 additions and 55 deletions

View File

@@ -28,6 +28,20 @@
- **회귀 테스트**: `tests/unit/test_convert_document.py` (7 케이스 — 단일 PDF / 단일 JSON / 다중 PDF / 다중 JSON first-wins / 미지원 확장자 / 빈 입력 / 혼합 PDF+JSON)
- **근거**: docs/통합설계서.md §5 Phase 0, OntoCast 분석 §13.1 / §21.1 (#4)
### 2026-05-14 — node_factories.py: BudgetTracker가 LLM 호출을 기록하지 못하던 버그 수정
- **파일**: `ontocast/stategraph/node_factories.py`
- **문제**: `make_render_ontology_node`(line 91)와 `make_render_facts_node`(line 256)에서 병렬 unit 처리 시 `base_state = state.model_copy(deep=True)`로 root state를 deep-copy 한 뒤 `budget_tracker=base_state.budget_tracker`를 child state(`UnitOntologyState`/`UnitFactsState`)에 전달했다. 그 결과 LLM이 add_usage()를 호출해도 *복사본* 인스턴스만 갱신되고 root state.budget_tracker는 영원히 0인 채로 남아 BudgetTracker가 LLM 호출 수, chars sent/received를 전혀 기록하지 못했다. e2e 실행 시 LM Studio 로그에 LLM 호출이 분명히 들어왔는데(token count 검증됨) workflow_state["budget_tracker"].calls_count == 0으로 응답되는 증상으로 확인됨.
- **수정**: 두 곳 모두 `base_state.budget_tracker``state.budget_tracker`로 변경. `base_state = state.model_copy(deep=True)` 라인 자체가 budget_tracker 추출에만 쓰였으므로 함께 제거. Python int `+= 1` 연산은 GIL 하에서 원자적이라 병렬 process_unit 간 race condition은 무시 가능한 수준.
- **회귀 테스트**: e2e (`tests/e2e/test_phase0_full_pipeline.py`)에서 `budget.calls_count > 0` 검증.
- **근거**: docs/phases/PHASE0_ACCEPTANCE_GATE.md (Gate #3 통과를 위한 차단 이슈).
### 2026-05-14 — render_ontology.py: Bootstrap KeyError 수정
- **파일**: `ontocast/agent/render_ontology.py`
- **문제**: `vendored/ontocast/ontocast/prompt/render_ontology.py:44``general_ontology_instruction = f"""...{prefix_instruction}..."""`이 f-string이라 모듈 로드 시점에 `prefix_instruction` 변수가 즉시 치환됨. 그 결과 최종 문자열에는 `prefix_instruction` 자체가 가진 `{ontology_prefix}` placeholder만 남는다. `render_ontology_update`는 호출 시 `ontology_prefix=current.prefix`도 함께 넘기지만 `render_ontology_fresh`는 누락 → Bootstrap 단계에서 `KeyError: 'ontology_prefix'`.
- **수정**: `render_ontology_fresh()``.format()` 호출에 `ontology_prefix=""`를 추가. Bootstrap 시점에는 prefix가 아직 LLM에 의해 정의되지 않으므로 빈 문자열이 의미적으로 올바름.
- **회귀 테스트**: e2e (`tests/e2e/test_phase0_full_pipeline.py`)에서 검증.
- **근거**: docs/phases/PHASE0_ACCEPTANCE_GATE.md (Gate #1 통과를 위한 차단 이슈).
### 2026-05-13 — Phase 0.2: select_ontology.py None-index 버그 수정
- **파일**: `ontocast/agent/select_ontology.py`
- **문제**: dynamic Pydantic 모델은 `answer_index ∈ [1, num_ontologies + 1]`을 강제하지만 코드는 `answer_index == 0`을 "None"으로 처리. 0은 Pydantic 검증을 통과할 수 없어 dead code였으며, LLM이 None을 선택할 때마다(`num_ontologies + 1` 반환) defensive branch로 빠져 WARNING 로그가 찍혔다.

View File

@@ -5,6 +5,11 @@ human-readable formats, making the ontological knowledge more accessible and
understandable.
The agent decides between generating bare Turtle for fresh ontologies and SPARQL operations for updates.
# MODIFIED 2026-05-14 (ontology_platform): render_ontology_fresh()의 .format()
# 호출에 ontology_prefix 키가 누락되어 Bootstrap 단계에서 KeyError 발생.
# general_ontology_instruction은 f-string 모듈 로드 시점에 prefix_instruction이
# 치환되며 그 안의 {ontology_prefix} 플레이스홀더만 남는다. Fresh 시점에는
# prefix가 아직 LLM에 의해 정해지지 않으므로 빈 문자열을 전달한다.
"""
import logging
@@ -109,8 +114,13 @@ async def render_ontology_fresh(
output_instruction = output_instruction_ttl
ontology_ttl = ""
improvement_instruction_str = ""
# MODIFIED 2026-05-14 (ontology_platform): Bootstrap에서는 prefix가 아직
# 정해지지 않았으므로 ontology_prefix를 빈 문자열로 채워 KeyError를 피한다.
# prefix_instruction= 인자는 f-string으로 이미 박혔으므로 무시되지만 호환을
# 위해 그대로 둔다.
general_ontology_instruction_str = general_ontology_instruction.format(
prefix_instruction=prefix_instruction_fresh
prefix_instruction=prefix_instruction_fresh,
ontology_prefix="",
)
text_chapter = text_template.format(text=state.content_unit.text)

View File

@@ -1,3 +1,7 @@
# MODIFIED 2026-05-14 (ontology_platform): make_render_ontology_node와
# make_render_facts_node에서 `state.model_copy(deep=True)`로 budget_tracker가
# deep-copy되어 root state의 BudgetTracker가 0인 채로 남던 버그 수정.
# 자세한 내역은 vendored/ontocast/VENDORED_MODIFICATIONS.md 참고.
import asyncio
import logging
@@ -88,12 +92,19 @@ def make_render_ontology_node(tools: ToolBox):
async def process_unit(unit_index: int) -> tuple[int, UnitOntologyState]:
async with semaphore:
base_state = state.model_copy(deep=True)
# MODIFIED 2026-05-14 (ontology_platform): 원래 코드는
# `state.model_copy(deep=True)`로 budget_tracker를 deep-copy해
# child state에 넘겼다. 그 결과 LLM이 add_usage()를 호출해도
# *복사본* 인스턴스만 갱신되고 root state.budget_tracker는
# 영원히 0인 채로 남아 BudgetTracker가 LLM 호출을 기록하지
# 못했다. 원본 인스턴스를 공유해 add_usage가 root state까지
# 직접 반영되도록 수정. (Python int += 1은 GIL 하에서 원자적이라
# 병렬 process_unit 간 race-condition 위험은 무시 가능)
ontology_state = UnitOntologyState(
content_unit=state.content_units[unit_index],
ontology_snapshot=state.current_ontology,
ontology_user_instruction=state.ontology_user_instruction,
budget_tracker=base_state.budget_tracker,
budget_tracker=state.budget_tracker,
max_visits_per_node=tools.config.server.max_visits_per_node,
current_domain=state.current_domain,
ontology_max_triples=tools.config.server.ontology_max_triples,
@@ -253,12 +264,14 @@ def make_render_facts_node(tools: ToolBox):
async def process_unit(unit_index: int) -> tuple[int, UnitFactsState]:
async with semaphore:
base_state = state.model_copy(deep=True)
# MODIFIED 2026-05-14 (ontology_platform): same fix as
# make_render_ontology_node — share the root budget_tracker
# instead of a deep-copied detached instance.
facts_state = UnitFactsState(
content_unit=state.content_units[unit_index],
ontology_snapshot=state.current_ontology,
facts_user_instruction=state.facts_user_instruction,
budget_tracker=base_state.budget_tracker,
budget_tracker=state.budget_tracker,
max_visits_per_node=tools.config.server.max_visits_per_node,
)
result = await facts_loop(facts_state, atomic_tools)