Claude 리뷰 기반 운영 안정성 보강
This commit is contained in:
1 parent
8b0a7e45ac
commit
725e44e999
15 files changed
+1427
-67
No files matched your search
@@ -0,0 +1,167 @@
|
||||
"""AI 탐지기 학습 데이터 분리 검증 (#F).
|
||||
|
||||
핵심 불변식 두 가지:
|
||||
1) fit=train / threshold=val / report=test 로 역할이 섞이지 않는다.
|
||||
2) 어떤 source_group 도 두 split 에 동시에 나타나지 않는다(누출 금지).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from scripts.build_ai_training_dataset import Record, assign_splits, summarize # noqa: E402
|
||||
|
||||
sklearn = pytest.importorskip("sklearn", reason="scikit-learn 미설치")
|
||||
pytest.importorskip("joblib", reason="joblib 미설치")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 분할 자체의 불변식 (sklearn 불필요 부분)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _records(n_groups_per_label: int = 6, per_group: int = 6) -> list[Record]:
|
||||
out: list[Record] = []
|
||||
for label in (0, 1):
|
||||
origin = "human" if label == 0 else "ai"
|
||||
for g in range(n_groups_per_label):
|
||||
group = f"{origin}:group-{g}"
|
||||
for i in range(per_group):
|
||||
out.append(Record(
|
||||
text=f"{origin} 문단 {g}-{i}", label=label, origin=origin,
|
||||
source_group=group, book=group,
|
||||
))
|
||||
return out
|
||||
|
||||
|
||||
def test_assign_splits_never_shares_a_group():
|
||||
records = _records()
|
||||
assignment = assign_splits(records, (0.7, 0.15, 0.15), seed=7)
|
||||
for rec in records:
|
||||
rec.split = assignment[rec.source_group]
|
||||
|
||||
by_split: dict[str, set[str]] = {}
|
||||
for rec in records:
|
||||
by_split.setdefault(rec.split, set()).add(rec.source_group)
|
||||
splits = list(by_split)
|
||||
for i, a in enumerate(splits):
|
||||
for b in splits[i + 1:]:
|
||||
assert not (by_split[a] & by_split[b]), f"{a}/{b} 그룹 중복 = 누출"
|
||||
|
||||
assert summarize(records)["group_overlap_between_splits"] == []
|
||||
|
||||
|
||||
def test_assign_splits_is_deterministic_for_same_seed():
|
||||
a = assign_splits(_records(), (0.7, 0.15, 0.15), seed=11)
|
||||
b = assign_splits(_records(), (0.7, 0.15, 0.15), seed=11)
|
||||
assert a == b
|
||||
|
||||
|
||||
def test_assign_splits_covers_all_three_splits():
|
||||
assignment = assign_splits(_records(), (0.7, 0.15, 0.15), seed=3)
|
||||
assert set(assignment.values()) == {"train", "val", "test"}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 학습 CLI end-to-end
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _write_dataset(path: Path) -> None:
|
||||
human = "비가 왔다. 나는 그날 학교에 가지 않았고 대신 뒷산에 올라가 온종일 앉아 있었다. 춥지는 않았다. 형이 왔다."
|
||||
ai = "그날의 기억은 오래도록 남아, 지금까지도 선명하게 떠오르는 장면이 되었다. 아침의 공기는 서늘했고, 발걸음은 조용히 이어졌다."
|
||||
rows = []
|
||||
for label, body, origin in ((0, human, "human"), (1, ai, "ai")):
|
||||
for g in range(6):
|
||||
split = "train" if g < 4 else ("val" if g == 4 else "test")
|
||||
for i in range(8):
|
||||
rows.append({
|
||||
"text": (body + f" 변형 {g}-{i}. ") * 3,
|
||||
"label": label, "origin": origin,
|
||||
"source_group": f"{origin}:g{g}", "book": f"{origin}-{g}",
|
||||
"split": split,
|
||||
})
|
||||
path.write_text(
|
||||
"\n".join(json.dumps(r, ensure_ascii=False) for r in rows), encoding="utf-8"
|
||||
)
|
||||
|
||||
|
||||
def _run_trainer(data: Path, out: Path, *extra: str) -> subprocess.CompletedProcess:
|
||||
return subprocess.run(
|
||||
[sys.executable, "scripts/train_ai_detector.py", "--data", str(data),
|
||||
"--out", str(out), *extra],
|
||||
cwd=ROOT, capture_output=True, text=True,
|
||||
)
|
||||
|
||||
|
||||
def test_trainer_uses_train_val_test_roles(tmp_path):
|
||||
data = tmp_path / "ds.jsonl"
|
||||
out = tmp_path / "model.joblib"
|
||||
_write_dataset(data)
|
||||
|
||||
proc = _run_trainer(data, out)
|
||||
assert proc.returncode == 0, proc.stderr[-2000:]
|
||||
|
||||
metrics = json.loads((tmp_path / "model.metrics.json").read_text(encoding="utf-8"))
|
||||
# 세 역할이 모두 기록되어야 한다
|
||||
assert metrics["n_train"] > 0 and metrics["n_val"] > 0 and metrics["n_test"] > 0
|
||||
assert {"train", "validation", "test"} <= set(metrics)
|
||||
# 임계값은 val 에서 뽑혔음이 지표에 남아야 한다
|
||||
assert "validation_low_point" in metrics["cuts"]
|
||||
assert "validation_high_point" in metrics["cuts"]
|
||||
# 학습에 쓰인 표본 수와 보고 표본 수가 서로 다른 집합이어야 한다
|
||||
assert metrics["n_train"] != metrics["n_test"] or metrics["n_val"] != metrics["n_test"]
|
||||
|
||||
|
||||
def test_trainer_rejects_group_overlap_between_splits(tmp_path):
|
||||
data = tmp_path / "leaky.jsonl"
|
||||
out = tmp_path / "model.joblib"
|
||||
_write_dataset(data)
|
||||
|
||||
rows = [json.loads(line) for line in data.read_text(encoding="utf-8").splitlines()]
|
||||
for row in rows:
|
||||
# train 그룹 하나를 test 에도 등장시켜 누출을 주입
|
||||
if row["source_group"] == "human:g0" and row["split"] == "train":
|
||||
row["split"] = "test"
|
||||
break
|
||||
data.write_text(
|
||||
"\n".join(json.dumps(r, ensure_ascii=False) for r in rows), encoding="utf-8"
|
||||
)
|
||||
|
||||
proc = _run_trainer(data, out)
|
||||
assert proc.returncode == 2, "그룹 누출은 학습을 중단시켜야 한다"
|
||||
assert "누출" in proc.stderr or "중복" in proc.stderr
|
||||
|
||||
|
||||
def test_trainer_fails_on_single_class(tmp_path):
|
||||
data = tmp_path / "one.jsonl"
|
||||
_write_dataset(data)
|
||||
rows = [json.loads(line) for line in data.read_text(encoding="utf-8").splitlines()]
|
||||
kept = [r for r in rows if r["label"] == 0]
|
||||
data.write_text(
|
||||
"\n".join(json.dumps(r, ensure_ascii=False) for r in kept), encoding="utf-8"
|
||||
)
|
||||
proc = _run_trainer(data, tmp_path / "m.joblib")
|
||||
assert proc.returncode == 2
|
||||
assert "단일 클래스" in proc.stderr
|
||||
|
||||
|
||||
def test_trainer_fails_when_a_split_is_empty(tmp_path):
|
||||
data = tmp_path / "noval.jsonl"
|
||||
_write_dataset(data)
|
||||
rows = [json.loads(line) for line in data.read_text(encoding="utf-8").splitlines()]
|
||||
for row in rows:
|
||||
if row["split"] == "val":
|
||||
row["split"] = "train"
|
||||
data.write_text(
|
||||
"\n".join(json.dumps(r, ensure_ascii=False) for r in rows), encoding="utf-8"
|
||||
)
|
||||
proc = _run_trainer(data, tmp_path / "m.joblib")
|
||||
assert proc.returncode == 2
|
||||
assert "빈 split" in proc.stderr
|
||||
@@ -56,3 +56,69 @@ def test_batch_flow():
|
||||
job_id = resp.json()["job_id"]
|
||||
status = client.get(f"/v1/plagiarism/batch/{job_id}")
|
||||
assert status.status_code == 200
|
||||
|
||||
|
||||
def test_detect_exposes_score_semantics():
|
||||
"""#9 — 점수/임계값의 의미가 응답에 명시되어야 한다."""
|
||||
with TestClient(app) as client:
|
||||
resp = client.post(
|
||||
"/v1/plagiarism/detect",
|
||||
json={"doc_id": "s-1", "text": "어린왕자는 작은 별에서 온 소년이다."},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
sem = resp.json()["score_semantics"]
|
||||
assert sem["threshold_source"] == "server_default"
|
||||
assert sem["threshold_calibrated"] is False
|
||||
assert sem["provisional"] is True, "캘리브레이션 전에는 잠정값으로 노출"
|
||||
assert 0.0 <= sem["union_coverage"] <= 1.0
|
||||
assert sem["query_chars"] > 0
|
||||
assert "침해 확률이 아닙니다" in sem["note"]
|
||||
|
||||
|
||||
def test_detect_reports_request_threshold_override():
|
||||
with TestClient(app) as client:
|
||||
resp = client.post(
|
||||
"/v1/plagiarism/detect",
|
||||
json={"doc_id": "s-2", "text": "앤 셜리는 초록 지붕 집에 입양된 소녀다.",
|
||||
"options": {"threshold": 0.4}},
|
||||
)
|
||||
sem = resp.json()["score_semantics"]
|
||||
assert sem["threshold_source"] == "request_override"
|
||||
assert sem["threshold_used"] == 0.4
|
||||
|
||||
|
||||
def test_detect_accepts_legal_context():
|
||||
"""#10 — 사람이 확인한 사실을 전달하면 missing_factors 에서 빠진다."""
|
||||
with TestClient(app) as client:
|
||||
base = client.post(
|
||||
"/v1/plagiarism/detect",
|
||||
json={"doc_id": "l-1", "text": "홍길동은 활빈당을 만들어 재물을 나누었다."},
|
||||
).json()["legal_risk"]
|
||||
assert base["access_evidence"] == "not_provided"
|
||||
assert len(base["missing_factors"]) == 3
|
||||
|
||||
supplied = client.post(
|
||||
"/v1/plagiarism/detect",
|
||||
json={
|
||||
"doc_id": "l-2", "text": "홍길동은 활빈당을 만들어 재물을 나누었다.",
|
||||
"legal_context": {
|
||||
"work_type": "literary", "access_evidence": True,
|
||||
"protected_expression_reviewed": True, "rights_verified": True,
|
||||
},
|
||||
},
|
||||
).json()["legal_risk"]
|
||||
assert supplied["access_evidence"] == "provided"
|
||||
assert supplied["protected_expression"] == "reviewed"
|
||||
assert supplied["missing_factors"] == []
|
||||
|
||||
|
||||
def test_matches_carry_match_reasons():
|
||||
with TestClient(app) as client:
|
||||
resp = client.post(
|
||||
"/v1/plagiarism/detect",
|
||||
json={"doc_id": "r-1", "text": "어린왕자는 작은 별에서 온 소년이다. 그는 여우를 만난다.",
|
||||
"options": {"threshold": 0.01}},
|
||||
)
|
||||
for match in resp.json()["matches"]:
|
||||
assert match["match_reasons"], "채택 이유가 비어 있으면 안 된다"
|
||||
assert set(match["match_reasons"]) <= {"score_threshold", "exact_span", "coverage"}
|
||||
@@ -0,0 +1,144 @@
|
||||
"""API 키 인증 미들웨어 (#1).
|
||||
|
||||
앱 전체를 띄우지 않고 순수 함수로 검증한다. 엔진 기동(코퍼스 인덱싱)을 타면
|
||||
테스트가 느려지고 인증 로직과 무관한 이유로 깨진다.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.config import Settings
|
||||
from app.main import (
|
||||
AuthConfigurationError,
|
||||
is_authorized,
|
||||
public_paths,
|
||||
validate_auth_settings,
|
||||
)
|
||||
|
||||
|
||||
def _settings(**overrides) -> Settings:
|
||||
base = {"api_key": "", "require_api_key": False,
|
||||
"public_health": True, "public_docs": True}
|
||||
base.update(overrides)
|
||||
return Settings(**base)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# fail-closed 기동 검증
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_require_api_key_without_key_fails_startup():
|
||||
with pytest.raises(AuthConfigurationError) as exc:
|
||||
validate_auth_settings(_settings(require_api_key=True, api_key=""))
|
||||
assert "REQUIRE_API_KEY" in str(exc.value)
|
||||
|
||||
|
||||
def test_require_api_key_with_whitespace_only_key_fails():
|
||||
with pytest.raises(AuthConfigurationError):
|
||||
validate_auth_settings(_settings(require_api_key=True, api_key=" "))
|
||||
|
||||
|
||||
def test_require_api_key_with_key_starts_fine():
|
||||
validate_auth_settings(_settings(require_api_key=True, api_key="secret"))
|
||||
|
||||
|
||||
def test_default_settings_start_without_key():
|
||||
"""기본값(개발)에서는 기동을 막지 않는다 — 기존 동작 보존."""
|
||||
validate_auth_settings(_settings())
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 기존 기본 동작 보존
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_no_key_configured_allows_everything():
|
||||
s = _settings(api_key="")
|
||||
assert is_authorized(s, "/v1/plagiarism/detect", "") is True
|
||||
assert is_authorized(s, "/v1/corpus", "") is True
|
||||
|
||||
|
||||
def test_key_configured_rejects_missing_and_wrong_key():
|
||||
s = _settings(api_key="secret")
|
||||
assert is_authorized(s, "/v1/plagiarism/detect", "") is False
|
||||
assert is_authorized(s, "/v1/plagiarism/detect", "wrong") is False
|
||||
assert is_authorized(s, "/v1/plagiarism/detect", "secret") is True
|
||||
|
||||
|
||||
def test_corpus_write_paths_are_protected():
|
||||
s = _settings(api_key="secret")
|
||||
for path in ("/v1/corpus", "/v1/corpus/file", "/v1/corpus/doc-1", "/v1/plagiarism/batch"):
|
||||
assert is_authorized(s, path, "") is False, path
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 공개 경로 설정
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_health_public_by_default():
|
||||
s = _settings(api_key="secret")
|
||||
assert "/v1/health" in public_paths(s)
|
||||
assert is_authorized(s, "/v1/health", "") is True
|
||||
|
||||
|
||||
def test_health_can_be_protected():
|
||||
s = _settings(api_key="secret", public_health=False)
|
||||
assert "/v1/health" not in public_paths(s)
|
||||
assert is_authorized(s, "/v1/health", "") is False
|
||||
assert is_authorized(s, "/v1/health", "secret") is True
|
||||
|
||||
|
||||
def test_docs_public_by_default_and_can_be_closed():
|
||||
s = _settings(api_key="secret")
|
||||
assert "/openapi.json" in public_paths(s)
|
||||
closed = _settings(api_key="secret", public_docs=False)
|
||||
assert "/openapi.json" not in public_paths(closed)
|
||||
for path in ("/docs", "/openapi.json", "/redoc"):
|
||||
assert is_authorized(closed, path, "") is False
|
||||
assert is_authorized(closed, path, "secret") is True
|
||||
|
||||
|
||||
def test_root_console_stays_public():
|
||||
s = _settings(api_key="secret")
|
||||
assert is_authorized(s, "/", "") is True
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 회귀: 비ASCII 키가 TypeError 로 500 을 내지 않아야 한다
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_non_ascii_key_does_not_raise():
|
||||
s = _settings(api_key="비밀키-한글🔑")
|
||||
assert is_authorized(s, "/v1/plagiarism/detect", "비밀키-한글🔑") is True
|
||||
assert is_authorized(s, "/v1/plagiarism/detect", "틀린키") is False
|
||||
assert is_authorized(s, "/v1/plagiarism/detect", "") is False
|
||||
|
||||
|
||||
def test_non_ascii_configured_key_returns_401_not_500():
|
||||
"""서버에 한글 키를 설정해도 500 이 아니라 401 이어야 한다.
|
||||
|
||||
HTTP 헤더는 비ASCII 를 전송할 수 없으므로 이런 키는 사실상 인증 불가지만,
|
||||
최소한 서버가 TypeError 로 터지면 안 된다. (운영 키는 ASCII 로 발급할 것)
|
||||
"""
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.main import is_authorized as guard
|
||||
|
||||
settings = _settings(api_key="한글키")
|
||||
app = FastAPI()
|
||||
|
||||
@app.middleware("http")
|
||||
async def auth(request: Request, call_next):
|
||||
if not guard(settings, request.url.path, request.headers.get("x-api-key", "")):
|
||||
return JSONResponse(status_code=401, content={"detail": "Invalid or missing API key"})
|
||||
return await call_next(request)
|
||||
|
||||
@app.get("/v1/thing")
|
||||
async def thing():
|
||||
return {"ok": True}
|
||||
|
||||
with TestClient(app) as client:
|
||||
assert client.get("/v1/thing").status_code == 401
|
||||
assert client.get("/v1/thing", headers={"x-api-key": "ascii-guess"}).status_code == 401
|
||||
@@ -0,0 +1,337 @@
|
||||
"""union coverage (#3), 참조 특징 캐시 (#5), 점수 의미 (#9), 법적 맥락 (#10).
|
||||
|
||||
scipy/sklearn 이 없으면 인덱스 관련 테스트는 skip 된다.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.engine.legal_risk import LegalRiskEngine, Precedent
|
||||
from app.engine.persistent_index import _covered_length, _merge_intervals
|
||||
from app.engine.provenance import CorpusStore, DocumentRecord, SegmentRecord
|
||||
|
||||
scipy = pytest.importorskip("scipy", reason="scipy 미설치")
|
||||
|
||||
from app.engine.persistent_index import PersistentCorpusIndex # noqa: E402
|
||||
|
||||
|
||||
def _segment(segment_id: str, text: str, **kw) -> SegmentRecord:
|
||||
return SegmentRecord(
|
||||
segment_id=segment_id, document_id=kw.pop("document_id", "doc-1"),
|
||||
text=text, ordinal=segment_id, char_start=0, char_end=len(text),
|
||||
source_locator=f"book.json#{segment_id}", **kw,
|
||||
)
|
||||
|
||||
|
||||
def _index_with(tmp_path, segments: list[SegmentRecord], title="원본"):
|
||||
db = tmp_path / "corpus.sqlite3"
|
||||
store = CorpusStore(db)
|
||||
for doc_id in {s.document_id for s in segments}:
|
||||
store.upsert_document(DocumentRecord(document_id=doc_id, title=title))
|
||||
store.add_segments(segments)
|
||||
index = PersistentCorpusIndex(db, tmp_path / "index")
|
||||
index.sync()
|
||||
return store, index
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 구간 병합 (순수 함수)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_merge_intervals_deduplicates_overlap():
|
||||
assert _merge_intervals([(0, 10), (5, 20), (30, 40)]) == [(0, 20), (30, 40)]
|
||||
assert _covered_length([(0, 10), (5, 20)]) == 20
|
||||
assert _covered_length([(0, 10), (0, 10)]) == 10, "중복 구간을 두 번 세면 안 된다"
|
||||
assert _covered_length([]) == 0
|
||||
|
||||
|
||||
def test_merge_intervals_handles_adjacent_and_nested():
|
||||
assert _merge_intervals([(0, 10), (10, 20)]) == [(0, 20)]
|
||||
assert _merge_intervals([(0, 100), (10, 20)]) == [(0, 100)]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# #3 union coverage
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_union_coverage_sums_multiple_segments(tmp_path):
|
||||
"""서로 다른 세그먼트가 질의의 다른 부분과 일치하면 coverage 가 합산된다."""
|
||||
part_a = "바닷가 마을에서 파도 소리를 들으며 자란 기억이 아직도 선명하게 남아 있다. " * 3
|
||||
part_b = "군에 입대하던 날 아버지는 아무 말 없이 내 어깨를 두드려 주셨던 기억이 난다. " * 3
|
||||
_, index = _index_with(tmp_path, [
|
||||
_segment("seg-a", part_a), _segment("seg-b", part_b),
|
||||
])
|
||||
query = part_a + "완전히 무관한 중간 문단입니다. " * 20 + part_b
|
||||
result = index.search(query, top_k=10)
|
||||
|
||||
assert result.union_coverage > 0.4, "두 구간이 모두 반영되어야 한다"
|
||||
assert result.covered_chars >= len(part_a)
|
||||
assert result.query_chars == len(query)
|
||||
# 개별 세그먼트 coverage 는 각자 union 보다 작다
|
||||
per_hit = [h.coverage for h in result.hits if h.reranked]
|
||||
assert max(per_hit) < result.union_coverage
|
||||
|
||||
|
||||
def test_document_coverage_does_not_leak_between_sources(tmp_path):
|
||||
part_a = "바닷가 마을에서 파도 소리를 들으며 자랐다. " * 3
|
||||
part_b = "군에 입대하던 날 아버지가 내 어깨를 두드렸다. " * 3
|
||||
_, index = _index_with(tmp_path, [
|
||||
_segment("seg-a", part_a, document_id="doc-a"),
|
||||
_segment("seg-b", part_b, document_id="doc-b"),
|
||||
])
|
||||
query = part_a + ("서로 무관한 중간 문장입니다. " * 20) + part_b
|
||||
result = index.search(query, top_k=10)
|
||||
|
||||
assert result.union_coverage > result.document_coverage["doc-a"]
|
||||
assert result.union_coverage > result.document_coverage["doc-b"]
|
||||
assert result.document_coverage["doc-a"] < 0.30
|
||||
assert result.document_coverage["doc-b"] < 0.30
|
||||
|
||||
|
||||
def test_union_coverage_low_for_long_unrelated_document(tmp_path):
|
||||
_, index = _index_with(tmp_path, [_segment("seg-1", "바닷가 마을의 파도 소리를 기억한다.")])
|
||||
query = "전혀 다른 주제의 글입니다. 오늘 회의에서 분기 실적을 논의했습니다. " * 100
|
||||
result = index.search(query, top_k=5)
|
||||
assert result.union_coverage < 0.1
|
||||
|
||||
|
||||
def test_short_full_copy_reaches_high_coverage(tmp_path):
|
||||
text = "나는 어린 시절 바닷가 마을에서 살았고 매일 파도 소리를 들으며 잠들었다."
|
||||
_, index = _index_with(tmp_path, [_segment("seg-1", text)])
|
||||
result = index.search(text, top_k=5)
|
||||
assert result.union_coverage > 0.8
|
||||
|
||||
|
||||
def test_long_document_partial_copy_is_not_structurally_zero(tmp_path):
|
||||
"""긴 원고 안의 부분 복사가 coverage 에 실제로 잡히는지 (#3 회귀)."""
|
||||
copied = "바닷가 마을에서 파도 소리를 들으며 자란 기억이 선명하다. " * 10
|
||||
_, index = _index_with(tmp_path, [_segment("seg-1", copied)])
|
||||
filler = "무관한 문장입니다. " * 300
|
||||
query = filler + copied + filler
|
||||
result = index.search(query, top_k=5)
|
||||
assert result.covered_chars >= len(copied) * 0.5
|
||||
assert result.union_coverage > 0.0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# CPU 상한
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_evidence_limit_caps_precise_comparison(tmp_path):
|
||||
segments = [
|
||||
_segment(f"seg-{i}", f"바닷가 마을 이야기 {i}번 문단입니다. 파도 소리를 들었다. " * 3)
|
||||
for i in range(8)
|
||||
]
|
||||
_, index = _index_with(tmp_path, segments)
|
||||
result = index.search("바닷가 마을 이야기 파도 소리를 들었다.", top_k=8, evidence_limit=3)
|
||||
|
||||
reranked = [h for h in result.hits if h.reranked]
|
||||
assert len(reranked) == 3
|
||||
assert result.evidence_truncated is True
|
||||
for hit in result.hits:
|
||||
if not hit.reranked:
|
||||
assert hit.evidence == [] and hit.coverage == 0.0 and hit.longest_span == 0
|
||||
|
||||
|
||||
def test_query_wrapper_still_returns_hits(tmp_path):
|
||||
"""기존 호출부 호환 — query() 는 여전히 list[PersistentHit]."""
|
||||
_, index = _index_with(tmp_path, [_segment("seg-1", "바닷가 마을의 파도 소리.")])
|
||||
hits = index.query("바닷가 마을의 파도 소리.", top_k=1)
|
||||
assert isinstance(hits, list) and hits[0].segment_id == "seg-1"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# #5 참조 특징 캐시 + 마이그레이션
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_v1_database_migrates_without_data_loss(tmp_path):
|
||||
"""lemmas_json/elements_json 없는 기존 DB 도 그대로 열려야 한다."""
|
||||
import sqlite3
|
||||
|
||||
db = tmp_path / "old.sqlite3"
|
||||
con = sqlite3.connect(db)
|
||||
con.executescript(
|
||||
"""
|
||||
CREATE TABLE corpus_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
||||
CREATE TABLE documents (
|
||||
document_id TEXT PRIMARY KEY, title TEXT NOT NULL, source_path TEXT,
|
||||
source_sha256 TEXT, metadata_json TEXT NOT NULL DEFAULT '{}',
|
||||
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT DEFAULT CURRENT_TIMESTAMP);
|
||||
CREATE TABLE segments (
|
||||
segment_id TEXT PRIMARY KEY, document_id TEXT NOT NULL,
|
||||
ordinal TEXT NOT NULL, text TEXT NOT NULL, text_sha256 TEXT NOT NULL,
|
||||
coordinate_scope TEXT NOT NULL, page_number INTEGER,
|
||||
paragraph_number INTEGER, char_start INTEGER, char_end INTEGER,
|
||||
source_locator TEXT, metadata_json TEXT NOT NULL DEFAULT '{}',
|
||||
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE(document_id, text_sha256));
|
||||
INSERT INTO documents(document_id,title) VALUES('doc-1','옛 책');
|
||||
INSERT INTO segments VALUES('seg-1','doc-1','1','옛 본문입니다.','h','episode',
|
||||
NULL,NULL,0,7,NULL,'{}',CURRENT_TIMESTAMP);
|
||||
"""
|
||||
)
|
||||
con.commit()
|
||||
con.close()
|
||||
|
||||
store = CorpusStore(db)
|
||||
store.initialize() # 마이그레이션
|
||||
segments = list(store.iter_segments())
|
||||
assert len(segments) == 1
|
||||
assert segments[0].text == "옛 본문입니다."
|
||||
assert segments[0].lemmas is None
|
||||
assert store.count_missing_features() == 1
|
||||
|
||||
|
||||
def test_feature_roundtrip_and_backfill(tmp_path):
|
||||
store = CorpusStore(tmp_path / "corpus.sqlite3")
|
||||
store.upsert_document(DocumentRecord(document_id="doc-1", title="책"))
|
||||
store.add_segments([_segment("seg-1", "홍길동은 활빈당을 만들었다.")])
|
||||
assert store.count_missing_features() == 1
|
||||
|
||||
store.update_segment_features([("seg-1", ["홍길동", "활빈당"], {"characters": ["홍길동"]})])
|
||||
assert store.count_missing_features() == 0
|
||||
loaded = store.get_segments(["seg-1"])["seg-1"]
|
||||
assert loaded.lemmas == ["홍길동", "활빈당"]
|
||||
assert loaded.elements == {"characters": ["홍길동"]}
|
||||
|
||||
|
||||
def test_precomputed_features_reach_the_hit(tmp_path):
|
||||
store = CorpusStore(tmp_path / "corpus.sqlite3")
|
||||
store.upsert_document(DocumentRecord(document_id="doc-1", title="책"))
|
||||
store.add_segments([_segment(
|
||||
"seg-1", "나는 어린 시절 바닷가 마을에서 살았다.",
|
||||
lemmas=["바닷가", "마을", "살다"],
|
||||
elements={"characters": [], "motifs": [], "genre": None, "keywords": ["바닷가"]},
|
||||
)])
|
||||
index = PersistentCorpusIndex(tmp_path / "corpus.sqlite3", tmp_path / "index")
|
||||
index.sync()
|
||||
hit = index.query("나는 어린 시절 바닷가 마을에서 살았다.", top_k=1)[0]
|
||||
assert hit.reference_lemmas == ["바닷가", "마을", "살다"]
|
||||
assert hit.reference_elements["keywords"] == ["바닷가"]
|
||||
|
||||
|
||||
def test_detector_uses_cache_instead_of_recomputing(monkeypatch, tmp_path):
|
||||
"""캐시가 있으면 형태소 분석을 호출하지 않아야 한다 (#5 호출횟수 테스트)."""
|
||||
from app.api.schemas import ExtractedElements
|
||||
from app.engine import detector as det_module
|
||||
from app.engine.persistent_index import PersistentHit
|
||||
|
||||
calls = {"lemmas": 0, "extract": 0}
|
||||
|
||||
def counting_lemmas(text, *a, **kw):
|
||||
calls["lemmas"] += 1
|
||||
return ["x"]
|
||||
|
||||
monkeypatch.setattr(det_module, "extract_lemmas", counting_lemmas)
|
||||
|
||||
detector = det_module.PlagiarismDetector.__new__(det_module.PlagiarismDetector)
|
||||
detector._feature_cache = {}
|
||||
detector._persistent = None
|
||||
|
||||
class _Extractor:
|
||||
def extract(self, text):
|
||||
calls["extract"] += 1
|
||||
return ExtractedElements()
|
||||
|
||||
detector._extractor = _Extractor()
|
||||
|
||||
cached_hit = PersistentHit(
|
||||
segment_id="seg-1", document_id="doc-1", title="책", score=0.9,
|
||||
evidence=[], coverage=0.0, longest_span=0, source_locator=None,
|
||||
coordinate_scope="episode", page_number=None, paragraph_number=None,
|
||||
source_char_start=None, source_char_end=None, reference_text="본문",
|
||||
reference_lemmas=["미리", "계산"],
|
||||
reference_elements={"characters": [], "motifs": [], "genre": None, "keywords": []},
|
||||
)
|
||||
lemmas, _ = detector.reference_features(cached_hit)
|
||||
assert lemmas == ["미리", "계산"]
|
||||
assert calls == {"lemmas": 0, "extract": 0}, "캐시가 있는데 재계산했다"
|
||||
|
||||
uncached = PersistentHit(
|
||||
segment_id="seg-2", document_id="doc-1", title="책", score=0.9,
|
||||
evidence=[], coverage=0.0, longest_span=0, source_locator=None,
|
||||
coordinate_scope="episode", page_number=None, paragraph_number=None,
|
||||
source_char_start=None, source_char_end=None, reference_text="본문",
|
||||
)
|
||||
detector.reference_features(uncached)
|
||||
assert calls == {"lemmas": 1, "extract": 1}
|
||||
# 두 번째 호출은 프로세스 캐시로 처리
|
||||
detector.reference_features(uncached)
|
||||
assert calls == {"lemmas": 1, "extract": 1}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# #10 법적 맥락 + 판례 랭킹
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _precedents() -> list[Precedent]:
|
||||
return [
|
||||
Precedent("2020다1", "가", "https://x/1", ("literary",),
|
||||
("reproduction",), (), "요지1"),
|
||||
Precedent("2019다2", "나", "https://x/2", ("literary",),
|
||||
("reproduction", "derivative_work"), (), "요지2"),
|
||||
Precedent("2018다3", "다", "https://x/3", ("musical",),
|
||||
("reproduction",), (), "요지3"),
|
||||
]
|
||||
|
||||
|
||||
def test_precedent_ranking_prefers_more_tag_overlap():
|
||||
engine = LegalRiskEngine(_precedents())
|
||||
out = engine.assess(
|
||||
max_similarity=0.9, coverage=0.5, longest_span=200,
|
||||
legal_tags=["reproduction", "derivative_work"], work_type="literary",
|
||||
)
|
||||
assert out.precedent_ids[0] == "2019다2", "태그 교집합이 큰 판례가 먼저"
|
||||
assert "2018다3" not in out.precedent_ids, "work_type 이 다른 판례는 제외"
|
||||
|
||||
|
||||
def test_only_registered_precedents_are_returned():
|
||||
engine = LegalRiskEngine(_precedents())
|
||||
out = engine.assess(
|
||||
max_similarity=0.9, coverage=0.5, longest_span=200,
|
||||
legal_tags=["reproduction"], work_type="literary",
|
||||
)
|
||||
registered = {p.case_id for p in _precedents()}
|
||||
assert set(out.precedent_ids) <= registered
|
||||
|
||||
|
||||
def test_empty_precedent_db_reports_insufficient():
|
||||
out = LegalRiskEngine([]).assess(
|
||||
max_similarity=0.9, coverage=0.9, longest_span=500, legal_tags=["reproduction"],
|
||||
)
|
||||
assert out.status == "insufficient_precedent_data"
|
||||
assert out.risk_level is None
|
||||
assert out.precedent_ids == ()
|
||||
|
||||
|
||||
def test_legal_context_clears_missing_factors():
|
||||
engine = LegalRiskEngine(_precedents())
|
||||
default = engine.assess(max_similarity=0.5, coverage=0.1, longest_span=20,
|
||||
legal_tags=["reproduction"])
|
||||
assert len(default.missing_factors) == 3
|
||||
assert default.access_evidence == "not_provided"
|
||||
|
||||
supplied = engine.assess(
|
||||
max_similarity=0.5, coverage=0.1, longest_span=20, legal_tags=["reproduction"],
|
||||
access_evidence=True, protected_expression_reviewed=True, rights_verified=True,
|
||||
)
|
||||
assert supplied.missing_factors == ()
|
||||
assert supplied.access_evidence == "provided"
|
||||
assert supplied.protected_expression == "reviewed"
|
||||
|
||||
|
||||
def test_legal_context_flows_through_detect_request():
|
||||
from app.api.schemas import DetectRequest, LegalContext
|
||||
|
||||
req = DetectRequest(
|
||||
doc_id="d", text="본문",
|
||||
legal_context=LegalContext(work_type="musical", access_evidence=False,
|
||||
protected_expression_reviewed=True),
|
||||
)
|
||||
assert req.legal_context.work_type == "musical"
|
||||
assert req.legal_context.access_evidence is False
|
||||
assert req.legal_context.rights_verified is False
|
||||
# 미제공이 기본
|
||||
assert DetectRequest(doc_id="d", text="본문").legal_context is None
|
||||
@@ -0,0 +1,144 @@
|
||||
"""이미 반영된 리뷰 항목의 회귀 방지 (#2 #4 #6 #7 #8)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from app.engine.provenance import CorpusStore, DocumentRecord, SegmentRecord
|
||||
|
||||
pytest.importorskip("scipy", reason="scipy 미설치")
|
||||
|
||||
from app.engine.persistent_index import ( # noqa: E402
|
||||
VECTORIZER_CONFIG,
|
||||
PersistentCorpusIndex,
|
||||
)
|
||||
|
||||
|
||||
def _store_with(tmp_path, texts: list[str]) -> CorpusStore:
|
||||
store = CorpusStore(tmp_path / "corpus.sqlite3")
|
||||
store.upsert_document(DocumentRecord(document_id="doc-1", title="책"))
|
||||
store.add_segments([
|
||||
SegmentRecord(segment_id=f"seg-{i}", document_id="doc-1", text=t,
|
||||
ordinal=str(i), char_start=0, char_end=len(t))
|
||||
for i, t in enumerate(texts)
|
||||
])
|
||||
return store
|
||||
|
||||
|
||||
# --- #2 원자적 교체 -------------------------------------------------------
|
||||
|
||||
def test_matrix_file_is_generation_scoped(tmp_path):
|
||||
"""세대별 파일명이라 교체 중 이전 인덱스가 덮어써지지 않는다."""
|
||||
store = _store_with(tmp_path, ["첫 번째 세그먼트 본문입니다."])
|
||||
index = PersistentCorpusIndex(tmp_path / "corpus.sqlite3", tmp_path / "index")
|
||||
index.sync()
|
||||
first = json.loads((tmp_path / "index" / "index.json").read_text())["matrix_file"]
|
||||
|
||||
store.add_segments([SegmentRecord(
|
||||
segment_id="seg-9", document_id="doc-1", text="두 번째 세그먼트 본문입니다.",
|
||||
ordinal="9", char_start=0, char_end=10,
|
||||
)])
|
||||
index.sync()
|
||||
second = json.loads((tmp_path / "index" / "index.json").read_text())["matrix_file"]
|
||||
|
||||
assert first != second, "세대가 바뀌면 파일명도 바뀌어야 한다"
|
||||
assert (tmp_path / "index" / first).exists(), "이전 세대 파일이 살아 있어야 한다"
|
||||
|
||||
|
||||
def test_replaced_index_object_is_self_consistent(tmp_path):
|
||||
"""load() 한 객체는 matrix 행수와 segment_ids 길이가 항상 일치한다."""
|
||||
_store_with(tmp_path, [f"세그먼트 {i} 본문입니다. 파도 소리." for i in range(5)])
|
||||
index = PersistentCorpusIndex(tmp_path / "corpus.sqlite3", tmp_path / "index")
|
||||
index.sync()
|
||||
fresh = PersistentCorpusIndex(tmp_path / "corpus.sqlite3", tmp_path / "index").load()
|
||||
assert fresh._matrix.shape[0] == len(fresh._meta["segment_ids"]) == 5
|
||||
|
||||
|
||||
# --- #8 vectorizer 설정 고정 ---------------------------------------------
|
||||
|
||||
def test_index_with_different_vectorizer_config_is_rejected(tmp_path):
|
||||
_store_with(tmp_path, ["본문입니다. 파도 소리를 들었다."])
|
||||
index = PersistentCorpusIndex(tmp_path / "corpus.sqlite3", tmp_path / "index")
|
||||
index.sync()
|
||||
|
||||
meta_path = tmp_path / "index" / "index.json"
|
||||
meta = json.loads(meta_path.read_text())
|
||||
meta["vectorizer_config"] = {**VECTORIZER_CONFIG, "ngram_range": [2, 6]}
|
||||
meta_path.write_text(json.dumps(meta, ensure_ascii=False), encoding="utf-8")
|
||||
|
||||
with pytest.raises(ValueError, match="재빌드"):
|
||||
PersistentCorpusIndex(tmp_path / "corpus.sqlite3", tmp_path / "index").load()
|
||||
|
||||
|
||||
def test_config_change_forces_rebuild_not_append(tmp_path):
|
||||
_store_with(tmp_path, ["본문입니다. 파도 소리를 들었다."])
|
||||
index_dir = tmp_path / "index"
|
||||
index = PersistentCorpusIndex(tmp_path / "corpus.sqlite3", index_dir)
|
||||
index.sync()
|
||||
# n_features 가 달라지면 append 가 성립하지 않아야 한다
|
||||
result = PersistentCorpusIndex(tmp_path / "corpus.sqlite3", index_dir).sync(n_features=2**16)
|
||||
assert result["mode"] == "rebuild"
|
||||
|
||||
|
||||
# --- #6 document_count 캐시 ----------------------------------------------
|
||||
|
||||
def test_document_count_served_from_meta_without_table_scan(tmp_path, monkeypatch):
|
||||
_store_with(tmp_path, ["본문입니다."])
|
||||
index = PersistentCorpusIndex(tmp_path / "corpus.sqlite3", tmp_path / "index")
|
||||
index.sync()
|
||||
loaded = PersistentCorpusIndex(tmp_path / "corpus.sqlite3", tmp_path / "index").load()
|
||||
|
||||
def explode():
|
||||
raise AssertionError("document_count 가 매 요청 DB 를 스캔하고 있다")
|
||||
|
||||
monkeypatch.setattr(loaded.store, "document_count", explode)
|
||||
assert loaded.document_count == 1
|
||||
|
||||
|
||||
# --- #7 API 업로드 청킹 ---------------------------------------------------
|
||||
|
||||
def test_api_upload_is_chunked_not_single_segment(tmp_path, monkeypatch):
|
||||
from app.core.config import Settings
|
||||
from app.engine.detector import PlagiarismDetector
|
||||
|
||||
settings = Settings(
|
||||
use_persistent_index=True,
|
||||
corpus_db_path=str(tmp_path / "corpus.sqlite3"),
|
||||
persistent_index_dir=str(tmp_path / "index"),
|
||||
precedents_path=str(tmp_path / "none.jsonl"),
|
||||
ai_detector_model_path=str(tmp_path / "none.joblib"),
|
||||
use_clustering=False,
|
||||
use_lsh_filter=False,
|
||||
)
|
||||
_store_with(tmp_path, ["씨앗 세그먼트입니다."])
|
||||
PersistentCorpusIndex(tmp_path / "corpus.sqlite3", tmp_path / "index").sync()
|
||||
|
||||
detector = PlagiarismDetector(settings=settings)
|
||||
assert detector.uses_persistent_index
|
||||
|
||||
long_text = "긴 원고 문장입니다. 계속 이어집니다. " * 200 # 약 4,000자
|
||||
doc_id = detector.add_persistent_document(None, "업로드 원고", long_text)
|
||||
|
||||
segments = [s for s in detector._persistent.store.iter_segments()
|
||||
if s.document_id == doc_id]
|
||||
assert len(segments) > 1, "문서 전체가 세그먼트 1개로 저장되면 부분 표절을 못 잡는다"
|
||||
assert all(len(s.text) <= 1000 for s in segments)
|
||||
# 오프셋이 원문을 정확히 복원해야 한다
|
||||
for seg in segments:
|
||||
assert long_text.strip()[seg.char_start:seg.char_end] == seg.text
|
||||
|
||||
|
||||
# --- #4 detect 가 이벤트 루프를 막지 않는지 -------------------------------
|
||||
|
||||
def test_detect_route_runs_in_threadpool():
|
||||
"""라우트가 동기 detect 를 threadpool 로 넘기는지 (소스 계약 확인)."""
|
||||
import inspect
|
||||
|
||||
from app.api import routes
|
||||
|
||||
source = inspect.getsource(routes.detect)
|
||||
assert "run_in_threadpool" in source
|
||||
for name in ("corpus_upload_json", "corpus_upload_file", "corpus_delete"):
|
||||
assert "run_in_threadpool" in inspect.getsource(getattr(routes, name)), name
|
||||
Reference in new issue
Block a user