Files
AI/ontology_platform/tests/e2e/test_phase0_full_pipeline.py

116 lines
4.8 KiB
Python
Raw Permalink Normal View History

2026-05-13 19:57:34 +09:00
"""Phase 0 end-to-end pipeline test.
Runs the actual OntoCast workflow through the FastAPI ``/process`` endpoint
with a tiny JSON input. Verifies Acceptance Gate 0 evidence:
- /health, /info, /process respond OK
- ontology + facts Turtle are produced
- BudgetTracker reports non-zero LLM call/triple counts
- Filesystem TripleStoreManager writes artifacts under working_directory
Skipped unless ``LLM_API_KEY`` is set (see ``conftest.py``).
"""
from __future__ import annotations
import importlib
import json
import os
import sys
from pathlib import Path
import pytest
from fastapi.testclient import TestClient
REPO_ROOT = Path(__file__).resolve().parents[2]
if str(REPO_ROOT) not in sys.path:
sys.path.insert(0, str(REPO_ROOT))
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>
2026-05-14 09:05:24 +09:00
main_module = importlib.import_module("ont_platform.api.main")
deps_module = importlib.import_module("ont_platform.api.deps")
platform_config = importlib.import_module("ont_platform.config")
2026-05-13 19:57:34 +09:00
@pytest.mark.e2e
@pytest.mark.asyncio
async def test_full_pipeline_writes_ontology_and_facts(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
# Point the working directory at the test's tmp_path so artifacts don't
# leak between runs.
monkeypatch.setenv("ONTOCAST_WORKING_DIRECTORY", str(tmp_path / "work"))
# Honor whatever LLM provider the operator configured.
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>
2026-05-14 09:05:24 +09:00
# OpenAI는 API 키 필수, Ollama는 로컬 데몬만 떠 있으면 됨.
provider = os.environ.get("LLM_PROVIDER", "openai").lower()
if provider == "openai":
assert os.environ.get("LLM_API_KEY"), (
"LLM_API_KEY must be set for e2e with OpenAI provider"
)
2026-05-13 19:57:34 +09:00
# Force a fresh AppContext so the new working_directory wins.
deps_module.reset_app_context_for_testing()
settings = platform_config.load_settings()
await deps_module.initialize_app_context(settings, head_chunks=1)
app = main_module.create_app()
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>
2026-05-14 09:05:24 +09:00
# OntoCast SemanticChunker가 HDBSCAN + UMAP을 쓰므로 최소 문장 수가
# 필요하다. 2문장짜리 toy 입력은 "k must be ≤ training points"로 실패한다.
# Acceptance Gate #1은 "단일 PDF/JSON → TTL 생성"이지 문장 수와 무관하므로,
# ontology-rich한 짧은 단락을 충분한 문장 수로 늘려준다.
2026-05-13 19:57:34 +09:00
payload = {
"text": (
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>
2026-05-14 09:05:24 +09:00
"Alice Carter works at Acme Corporation in Berlin. "
"Acme Corporation is a manufacturing company founded in 1992. "
"Acme manufactures bicycles and electric scooters. "
"Bob Lee is the chief engineer at Acme Corporation. "
"He reports to Alice Carter, who heads the engineering division. "
"Acme's main factory is located in Berlin, Germany. "
"The company also operates a research center in Munich. "
"Carol Schmidt leads research at the Munich center. "
"She previously worked at Globex Industries in Hamburg. "
"Globex Industries is a competitor in the bicycle market. "
"Acme exports bicycles to France, Italy, and Spain. "
"The product line includes road bikes, mountain bikes, and city bikes. "
"Alice Carter graduated from the Technical University of Berlin. "
"Bob Lee holds a doctorate in mechanical engineering. "
"Acme employs around 450 people across its three sites. "
"The company reported annual revenue of 120 million euros last year."
2026-05-13 19:57:34 +09:00
),
"ontology_user_instruction": "Focus on person-organization-location relations.",
"facts_user_instruction": "Extract employment and manufacturing facts.",
}
with TestClient(app) as client:
# /health & /info first as smoke
assert client.get("/health").status_code == 200
assert client.get("/info").status_code == 200
response = client.post(
"/process",
content=json.dumps(payload),
headers={"Content-Type": "application/json"},
)
assert response.status_code == 200, response.text
body = response.json()
assert body["status"] == "success"
assert body["data"]["ontology"], "ontology TTL must not be empty"
assert body["data"]["facts"], "facts TTL must not be empty"
budget = body["metadata"]["budget"]
assert budget["calls_count"] > 0, "BudgetTracker must record at least one LLM call"
assert (
budget["ontology_triples_generated"] > 0
or budget["facts_triples_generated"] > 0
), "BudgetTracker must record triple generation"
# The filesystem manager should have created artifacts somewhere under
# working_directory. We don't assert exact filenames (those depend on
# the document hash) — just that the directory is non-empty.
work_dir = tmp_path / "work"
written = list(work_dir.rglob("*"))
assert any(p.suffix in {".ttl", ".rdf"} for p in written if p.is_file()), (
f"No RDF artifacts produced under {work_dir}"
)