[feat] 카드 카탈로그 DB 정본화 — config 결합 제거 + 학습 보존 자동반영

카드 카탈로그(negodata)가 Q-table action space 를 정의하는 정본이 되고, 카드 변경이
config 수정·학습 손실 없이 agent 에 자동 반영되는 고리를 완성.

- action space 정리: 카탈로그 전체(NGC-001~011, 11장) 고정, 견적별 선택은 축소가 아니라
  available_mask(_selection_mask) 로 처리 — action_id↔카드 대응을 견적마다 일정하게 유지해
  Q-table 학습 일관성 보장. 구 인덱스 방식(selected[action_id]) 폐기.
- ① 카탈로그 DB 정본화: action_mapping.type=db 면 registry 가 card.nego_cards(user_id NULL,
  number 순) 조회로 action_to_card 동적 구성(파일은 폴백). port/adapter(card_catalog_*).
  _base=type:db. → negodata 카드 추가/삭제 시 config 수정 불필요.
- ② 차원 변경 학습 보존 마이그레이션: migrate_active_version_dim — 겹치는 셀 복사
  (append/truncate 안전) + 새 카드 fresh. model_store.load 가 차원 불일치 시 호출.
- ③ reload 엔드포인트: /v1/catalog-refresh(테넌트) · /v1/catalog-refresh-all(전역, 화이트리스트).
- ④ 브랜드: company_profile_repo — 자동 온보딩 고객사(company_id UUID)는
  company.companies.name 으로 {company_name} 채움. 데모 테넌트는 파일 유지.
- 크로스서비스: negodata card_service 가 공용 nego 카드 변경 시 agent_notify 로 전역 리로드 알림
  (best-effort, is_test skip). config 에 agent_base_url.
- 하니스 episodes 400→600(action 11 수렴). 테스트 갱신·추가로 agent 98/98.

알려진 갭(후속): per-company 카탈로그 스코프(회사 카드도 action space 포함), 카탈로그 중간
삭제 시 카드번호 기반 마이그레이션.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
HyeongBaeYangandClaude Fable 5 committed 2026-07-08 14:56:28 +09:00
1 parent c2760c804f
commit 18020a9e07
25 files changed
+553 -62

No files matched your search

+31 -4
View File
@@ -7,6 +7,8 @@ ChatEngine(동기 step 전이) + UCB Q-Table(가격협상 카드선택·학습)
import uuid
from typing import Optional
import numpy as np
from common.enums import DBType, ErrorType
from common.database.db_session_manager import DB_SESSION_MNG
from common.logger import LOG
@@ -188,7 +190,11 @@ class ChatService:
LOG.e_no_callstack(f"[ChatService] state error: {ex}")
return
policy, version_id, repo = await QTablePolicyStore.load(engine)
ctx = PolicyContext(state_index=idx, snapshot=snap, action_space_size=session.action_space_size,
# action space 는 카탈로그 전체(engine.action_space_size)로 고정 — action_id↔카드 대응을
# 견적마다 일정하게 유지해 Q-table 학습 일관성을 지킨다. 견적 선택은 축소가 아니라
# available_mask 로 처리한다(선택 카드만 pickable, 사용분 제외).
ctx = PolicyContext(state_index=idx, snapshot=snap, action_space_size=engine.action_space_size,
available_mask=self._selection_mask(engine, session),
episode=EpisodeState(used_action_ids=set(session.used_action_ids)))
decision = policy.select(ctx)
session.used_action_ids.add(decision.action_id)
@@ -244,11 +250,32 @@ class ChatService:
@staticmethod
def _card_id_for_action(engine: TenantEngine, session: ChatSession, action_id: int) -> Optional[str]:
selected = session.context.get("selected_nego_card_numbers") or []
if 0 <= action_id < len(selected):
return str(selected[action_id])
# action_id ↔ 카드는 테넌트 매핑(action_to_card)으로 고정한다. 견적 선택은 available_mask 로
# 걸러지므로 여기서 selected 리스트를 인덱싱하지 않는다 — 인덱싱하면 견적마다 action_id 의미가
# 달라져(같은 action_id 가 다른 카드) Q-table 학습이 오염된다.
return engine.mapper.get_card_id(action_id)
@staticmethod
def _selection_mask(engine: TenantEngine, session: ChatSession) -> Optional[np.ndarray]:
"""견적에서 선택한 카드(selected_nego_card_numbers)만 pickable 로 하는 available_mask.
action space 전체(engine.action_space_size) 크기의 bool 배열. 선택 카드의 action_id 만 True,
이미 사용한 action 은 False. 선택이 없거나(직접호출/데모) 매핑 불가면 None → 전체 허용(폴백).
번호(card.nego_cards.number)와 action_to_card 값이 일치해야 매핑된다.
"""
selected = session.context.get("selected_nego_card_numbers") or []
if not selected:
return None
used = set(session.used_action_ids)
selected_ids = {engine.mapper.get_action_id(str(n)) for n in selected}
selected_ids.discard(None)
if not selected_ids:
return None # 매핑에 없는 번호뿐 → 폴백(전체 허용)
return np.array(
[(a in selected_ids and a not in used) for a in range(engine.action_space_size)],
dtype=bool,
)
async def _log(self, repo: LearningRepository, session, state_index, action_id, card_id, snap, reward, propensity, done):
data = {
"session_id": session.session_id, "state_index": state_index, "action_id": action_id,