0005 가 도메인 스키마를 걷어내고 표 이름을 옮겼는데, 문자열로 표 이름을 들고 있던 자리들이
따라오지 않았다. import 도 타입검사도 pyflakes 도 못 잡는 종류라 전부 **실행되는 순간에만**
터졌고, 그동안 pytest 는 569건이 통째로 죽어 있어 아무것도 못 잡고 있었다.
**init.sql 이 새 DB 를 옛 구조로 세우고 있었다**
64ce467 이 이 파일에 94줄을 더하기만 하고 삭제를 0줄 했다. 그래서 이 파일 한 벌로 세운 DB 는
`place.place_links`·`job.jobs` 를 갖고 ORM 은 `public.place_channels`·`public.jobs` 를 찾는다 —
기동은 정상이고 첫 쿼리에서 죽는다. "init.sql 은 새 DB 를 세우는 전체 DDL 이고 계속 최신을
유지한다"(migrations/README.md)는 계약이 깨져 있었다.
- public 한 벌 · 표 14개로 다시 썼다. 옛 스키마가 있는 DB 에서 다시 돌면 RAISE EXCEPTION 으로
멈춘다 — 그대로 두면 public 에 빈 표가 생기고 0005 가 "relation already exists" 로 실패해
데이터가 옛 스키마에 갇힌다
- 말미에 **마이그레이션 기준선**을 심는다. 없으면 새 DB 에서 migrate.py 가 0001 부터 다시 돌다가
`schema "local" does not exist` 로 죽는다
**운영 버그 둘** — 두 DB(새로 세운 것 · 마이그레이션으로 따라온 것)를 pg_dump 로 찍어 비교해 찾았다
- `upsert_weather` 의 ON CONFLICT 술어에 `kind IS NULL` 이 빠져 **날씨 캐시 저장이 계속 실패**하고
있었다(0007 이 인덱스에 그 조건을 더했다). 캐시라 화면이 안 죽고 로그에만 남았다.
포스트그레스는 술어가 인덱스 술어를 함의하는지 보고 아니면 "no unique or exclusion constraint
matching" 으로 거절한다 — 컬럼도 표도 멀쩡해서 눈으로는 원인이 안 보인다
- ORM 의 `area_contents` 인덱스 정의가 0004·0007·0008 을 하나도 안 따라왔다. 테스트 DB 는 이
모델로 세워지므로 **테스트가 운영과 다른 제약 아래에서 돌고 있었다**
**0009** — 두 DB 비교에서 나온 어긋남 셋(데이터는 안 건드린다)
- `idx_site_contents_site` 가 기존 DB 에만 없었다(0003 이 유니크만 걸었다) — 섹션 조회가 시퀀셜 스캔
- `places.external_place_id` VARCHAR(32) → (64). ORM 은 64 다 — 긴 id 가 잘리면 동일 업소 판정이 틀린다
- RENAME 이 안 따라간 PK 제약 이름 9개(`facts_pkey` → `place_facts_pkey` …)
**테스트를 살린다**
- conftest 의 TRUNCATE 가 표 이름을 **손으로 나열**하고 있었다. 0005 가 이름을 옮기자 전 테스트가
`relation "place_aliases" does not exist` 로 죽었다 — 이제 ORM 메타데이터에서 뽑아 다시 어긋날 수 없다
- `test_schema_ddl` 이 모델 표를 `"None.users"` 로 조회해 **한 표도 비교하지 않고 통과**하고 있었다.
init.sql 이 조용히 어긋난 동안 이 테스트는 초록이었다. 비교한 표 수를 세는 단언을 더한다
- 테스트 SQL 15곳의 옛 표 이름, `_run_worker` 1틱 문제(수집 뒤 따라오는 LOCAL_SYNC 를 집어 가
정작 기다리던 잡이 PENDING 으로 남았다), 지역 캐시 픽스처(읽는 코드가 옳게 거르는데 테스트가 빨개졌다)
**문서**
- `docs/DATA_MODEL.md` 신설 — 표 14개가 무엇을 담고 누가 쓰는지, 값 하나가 DB 에서 페이지까지
가는 길, 두 번 도는 게이트, **DB 에 없는 것**
- `SERVERS.md` DB 절을 마이그레이션 체계로. 배포에 `migrate.py` 를 넣는다 — 코드만 갈면 컨테이너는
정상으로 뜨고 가게 등록·수집·발행만 죽는다
- ARCHITECTURE 2절의 프리렌더 컨테이너가 `solution-frontend` 로 적혀 있었다. 굽는 건
`solution-prerender` 고 전자는 운영에서 뜨지도 않는다 — AGENTS.md 가 함정으로 적어 둔 그 혼동을
문서가 만들고 있었다
- 옛 표 이름 잔재(`place_links`·`local_contents`·`job.jobs`·`company.users`·`fact.facts`·`ai_check_results`)
검증: 빈 컨테이너에 init.sql 로 세운 DB ↔ 마이그레이션으로 따라온 DB 를 `pg_dump --schema-only`
로 비교 — 표·인덱스·제약·컬럼 전부 동일. pytest 583건 중 581 통과(남은 2건은 `.env` 누수·
레이트리밋 카운터로 환경 문제다). 구글 로그인 21건 포함.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
178 lines
8.8 KiB
Python
178 lines
8.8 KiB
Python
"""소개문·FAQ 생성 — ★ LLM 은 사실을 만들지 않는다.
|
|
|
|
이 잡이 절대 하면 안 되는 것:
|
|
- 미검증 fact 를 근거로 문장을 쓰는 것 (그 문장도 미검증이 된다)
|
|
- 근거 없이 생성하는 것 (그게 환각이다)
|
|
- 생성물을 바로 사이트에 노출하는 것 (사람 승인이 있어야 한다)
|
|
- 사람이 확인한 FAQ 를 재생성이 덮어쓰는 것
|
|
"""
|
|
import uuid
|
|
|
|
from sqlalchemy import text
|
|
|
|
from common.enums import ErrorType, FactStatus, JobStatus, SourceType
|
|
from crud.job_crud import JobQueue
|
|
from services.external import gemini_text
|
|
from worker.handlers import build_handler
|
|
from worker.runner import Worker
|
|
|
|
|
|
def _copy(intro="조용한 숙소입니다.", faqs=None, rejected=None):
|
|
return gemini_text.GeneratedCopy(
|
|
intro=intro,
|
|
intro_fact_keys=["check_in_time"],
|
|
meta_description="양양 하조대 펜션",
|
|
faqs=faqs if faqs is not None else [
|
|
gemini_text.GeneratedFaq("체크인은 몇 시인가요?", "15시입니다.", ["check_in_time"]),
|
|
],
|
|
rejected=rejected or [],
|
|
)
|
|
|
|
|
|
def _patch(monkeypatch, copy):
|
|
monkeypatch.setattr(gemini_text, "is_configured", lambda: True)
|
|
|
|
async def _gen(place_name, category, facts, **kw):
|
|
return copy
|
|
|
|
monkeypatch.setattr(gemini_text, "generate_copy", _gen)
|
|
|
|
|
|
async def _place_with_facts(client, h, n_verified=5):
|
|
pid = (await client.post("/v1/place", headers=h, json={"name": "카피펜션", "category": 1})).json()["place"]["place_id"]
|
|
await client.post(f"/v1/place/{pid}/verify", headers=h, json={"source": 2, "road_address": f"주소{uuid.uuid4().hex[:6]}"})
|
|
keys = ["check_in_time", "check_out_time", "cancel_policy", "cooking_allowed", "pet_allowed"][:n_verified]
|
|
for k in keys:
|
|
await client.post(f"/v1/place/{pid}/fact", headers=h, json={"key": k, "value": "15:00"})
|
|
return pid
|
|
|
|
|
|
async def _faq_rows(db_engine, pid):
|
|
async with db_engine.begin() as c:
|
|
return (await c.execute(
|
|
text("SELECT question, answer, source_fact_ids, status FROM place_faqs WHERE place_id = :p ORDER BY sort_order"),
|
|
{"p": uuid.UUID(pid)},
|
|
)).all()
|
|
|
|
|
|
async def test_copy_generates_intro_and_faq_as_candidates(auth_headers, client, db_engine, monkeypatch):
|
|
"""검증: 소개문·FAQ 를 생성한다.
|
|
기대결과: 생성되지만 ★ 전부 미검증 — 사람이 승인해야 사이트에 나간다."""
|
|
_patch(monkeypatch, _copy())
|
|
h = await auth_headers("u1")
|
|
pid = await _place_with_facts(client, h)
|
|
|
|
body = (await client.post(f"/v1/place/{pid}/copy", headers=h, json={})).json()
|
|
assert body["result"]["success"] is True
|
|
assert body["grounded_facts"] == 5
|
|
|
|
await Worker("w", JobQueue(), build_handler(), job_deadline_sec=30).process_one()
|
|
job = (await client.get(f"/v1/job/{body['job_id']}", headers=h)).json()["job"]
|
|
assert job["status"] == JobStatus.DONE.value, job.get("last_error")
|
|
assert job["result"]["intro"] is True
|
|
assert job["result"]["faqs"] == 1
|
|
|
|
rows = await _faq_rows(db_engine, pid)
|
|
assert rows[0][3] == FactStatus.UNVERIFIED.value, "★ 생성된 FAQ 가 바로 노출 상태면 안 된다"
|
|
assert rows[0][2] == ["check_in_time"], "근거 fact 가 기록돼야 한다"
|
|
|
|
# 소개문도 fact 로 들어가되 미검증 후보다
|
|
facts = (await client.get(f"/v1/place/{pid}/fact/list", headers=h)).json()
|
|
intro = [f for f in facts["facts"] if f["key"] == "intro"]
|
|
assert intro and intro[0]["status"] == FactStatus.UNVERIFIED.value
|
|
assert intro[0]["source_type"] == SourceType.LLM.value
|
|
|
|
|
|
async def test_copy_refuses_without_verified_facts(auth_headers, client, monkeypatch):
|
|
"""검증: 확인된 fact 가 하나도 없는 사업장에서 생성을 시도한다.
|
|
기대결과: FAQ_UNGROUNDED — ★ 잡을 만들지 않는다. 근거 없이 쓰면 환각이고 유료 호출만 낭비다."""
|
|
monkeypatch.setattr(gemini_text, "is_configured", lambda: True)
|
|
h = await auth_headers("u1")
|
|
pid = (await client.post("/v1/place", headers=h, json={"name": "빈펜션", "category": 1})).json()["place"]["place_id"]
|
|
await client.post(f"/v1/place/{pid}/verify", headers=h, json={"source": 2, "road_address": "빈주소"})
|
|
|
|
r = await client.post(f"/v1/place/{pid}/copy", headers=h, json={})
|
|
assert r.json()["result"]["code"] == ErrorType.FAQ_UNGROUNDED.value
|
|
|
|
|
|
async def test_unverified_facts_are_not_used_as_grounding(auth_headers, client, monkeypatch):
|
|
"""검증: 크롤링으로 들어온 미검증 fact 만 있는 사업장.
|
|
기대결과: 근거로 안 쳐서 FAQ_UNGROUNDED — 미검증 값으로 쓴 문장도 미검증이다."""
|
|
monkeypatch.setattr(gemini_text, "is_configured", lambda: True)
|
|
h = await auth_headers("u1")
|
|
pid = (await client.post("/v1/place", headers=h, json={"name": "미검증펜션", "category": 1})).json()["place"]["place_id"]
|
|
await client.post(f"/v1/place/{pid}/verify", headers=h, json={"source": 2, "road_address": "미검증주소"})
|
|
await client.post(f"/v1/place/{pid}/fact", headers=h, json={
|
|
"key": "check_in_time", "value": "15:00",
|
|
"source_type": SourceType.CRAWL.value, "source_url": "https://ota.test/1"})
|
|
|
|
r = await client.post(f"/v1/place/{pid}/copy", headers=h, json={})
|
|
assert r.json()["result"]["code"] == ErrorType.FAQ_UNGROUNDED.value
|
|
|
|
|
|
async def test_faq_without_grounding_is_dropped(auth_headers, client, db_engine, monkeypatch):
|
|
"""검증: 근거 fact 가 비어 있는 FAQ 가 생성물에 섞여 온다.
|
|
기대결과: 저장하지 않고 반려 목록에 남는다."""
|
|
_patch(monkeypatch, _copy(faqs=[
|
|
gemini_text.GeneratedFaq("체크인은?", "15시입니다.", ["check_in_time"]),
|
|
gemini_text.GeneratedFaq("수영장 있나요?", "네 있습니다.", []),
|
|
]))
|
|
h = await auth_headers("u1")
|
|
pid = await _place_with_facts(client, h)
|
|
job_id = (await client.post(f"/v1/place/{pid}/copy", headers=h, json={})).json()["job_id"]
|
|
await Worker("w", JobQueue(), build_handler(), job_deadline_sec=30).process_one()
|
|
|
|
job = (await client.get(f"/v1/job/{job_id}", headers=h)).json()["job"]
|
|
assert job["result"]["faqs"] == 1
|
|
assert any("수영장" in str(r) for r in job["result"]["rejected"])
|
|
assert len(await _faq_rows(db_engine, pid)) == 1
|
|
|
|
|
|
async def test_rejected_sentences_are_reported(auth_headers, client, monkeypatch):
|
|
"""검증: 클라이언트가 반려한 문장이 있다.
|
|
기대결과: 잡 result 에 사유와 함께 실린다 — 소개문이 왜 안 나왔는지 알 수 있어야 한다."""
|
|
_patch(monkeypatch, _copy(intro=None, rejected=[("수영장을 갖추고 있습니다", "fact 에 없는 시설 '수영장'")]))
|
|
h = await auth_headers("u1")
|
|
pid = await _place_with_facts(client, h)
|
|
job_id = (await client.post(f"/v1/place/{pid}/copy", headers=h, json={})).json()["job_id"]
|
|
await Worker("w", JobQueue(), build_handler(), job_deadline_sec=30).process_one()
|
|
|
|
job = (await client.get(f"/v1/job/{job_id}", headers=h)).json()["job"]
|
|
assert job["result"]["intro"] is False
|
|
assert any("수영장" in str(r) for r in job["result"]["rejected"])
|
|
|
|
|
|
async def test_regeneration_keeps_human_approved_faq(auth_headers, client, db_engine, monkeypatch):
|
|
"""검증: 사람이 승인한 FAQ 가 있는 상태에서 재생성한다.
|
|
기대결과: ★ 승인된 FAQ 는 남는다 — 재생성이 사람의 판단을 덮어쓰면 안 된다."""
|
|
_patch(monkeypatch, _copy())
|
|
h = await auth_headers("u1")
|
|
pid = await _place_with_facts(client, h)
|
|
await client.post(f"/v1/place/{pid}/copy", headers=h, json={})
|
|
await Worker("w", JobQueue(), build_handler(), job_deadline_sec=30).process_one()
|
|
|
|
# 사람이 승인
|
|
async with db_engine.begin() as c:
|
|
await c.execute(
|
|
text("UPDATE place_faqs SET status = :s WHERE place_id = :p"),
|
|
{"s": FactStatus.VERIFIED.value, "p": uuid.UUID(pid)},
|
|
)
|
|
|
|
_patch(monkeypatch, _copy(faqs=[gemini_text.GeneratedFaq("새 질문?", "새 답변", ["check_in_time"])]))
|
|
await client.post(f"/v1/place/{pid}/copy", headers=h, json={})
|
|
await Worker("w", JobQueue(), build_handler(), job_deadline_sec=30).process_one()
|
|
|
|
rows = await _faq_rows(db_engine, pid)
|
|
approved = [r for r in rows if r[3] == FactStatus.VERIFIED.value]
|
|
assert approved and approved[0][0] == "체크인은 몇 시인가요?", "★ 승인된 FAQ 가 재생성에 밀려났다"
|
|
|
|
|
|
async def test_copy_requires_api_key(auth_headers, client, monkeypatch):
|
|
"""검증: GEMINI_API_KEY 없이 생성을 시도한다.
|
|
기대결과: GENERATOR_NOT_CONFIGURED — 잡을 만들지 않는다."""
|
|
monkeypatch.setattr(gemini_text, "is_configured", lambda: False)
|
|
h = await auth_headers("u1")
|
|
pid = await _place_with_facts(client, h)
|
|
r = await client.post(f"/v1/place/{pid}/copy", headers=h, json={})
|
|
assert r.json()["result"]["code"] == ErrorType.GENERATOR_NOT_CONFIGURED.value
|