[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

@@ -0,0 +1,39 @@
"""CardCatalogDbRepository — card.nego_cards 에서 카탈로그(action space) read-only 조회.
정렬: number 오름차순(zero-padded NGC-001..NGC-011 이라 문자열 정렬로 안정적) → action_id.
스코프: o2o 기본 제공 카드(user_id IS NULL). 회사 전용 카탈로그는 후속(스코프 확장).
스키마 소유권: card 스키마는 backend/negodata 소유 — read-only. 경량 table()/column() 구성.
"""
from typing import List, Tuple
from sqlalchemy import asc, column, select, table
from sqlalchemy.ext.asyncio import AsyncSession
from common.database.db_session_manager import DB_SESSION_MNG
from common.enums import ErrorType
from common.logger import LOG
from negotiation.cards.ports.card_catalog_port import ICardCatalogRepository
_NEGO_CARDS = table(
"nego_cards",
column("number"), column("user_id"), column("deleted"),
schema="card",
)
class CardCatalogDbRepository(ICardCatalogRepository):
async def get_nego_catalog(self, cdb: AsyncSession) -> Tuple[ErrorType, List[str]]:
try:
query = (
select(_NEGO_CARDS.c.number)
.where(_NEGO_CARDS.c.user_id.is_(None), _NEGO_CARDS.c.deleted == False) # noqa: E712
.order_by(asc(_NEGO_CARDS.c.number))
)
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "get_nego_catalog failed.", raise_error=False)
if err_type != ErrorType.SUCCESS or not rows:
return err_type, []
return ErrorType.SUCCESS, [str(r) for r in rows if r]
except Exception as ex:
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, []
@@ -0,0 +1,24 @@
"""ICardCatalogRepository — 협상카드 카탈로그(action space 정의) DB 조회 포트.
카탈로그 = Q-table 의 action 축을 정의하는 "카드 목록". negodata 가 관리하는 card.nego_cards 가
정본이며, agent 는 이를 조회해 action_id(0..N-1) ↔ 카드번호 매핑을 구성한다. tenant.yaml 의
action_to_card 하드코딩을 대체한다(config 결합 제거 — 카탈로그는 DB, config 는 튜닝만).
주의: 카탈로그 크기 = Q-table action 차원. 카드 수가 바뀌면 재차원화(버전 이벤트)가 필요하므로
카탈로그 변경은 드문 이벤트여야 한다.
"""
from abc import ABC, abstractmethod
from typing import List, Tuple
from sqlalchemy.ext.asyncio import AsyncSession
from common.enums import ErrorType
class ICardCatalogRepository(ABC):
@abstractmethod
async def get_nego_catalog(self, cdb: AsyncSession) -> Tuple[ErrorType, List[str]]:
"""action space 를 정의하는 일반 협상카드 번호 목록(정렬됨). action_id = 리스트 인덱스.
비었으면([]) 호출부가 파일 action_to_card 로 폴백한다."""
...
+13 -1
View File
@@ -10,6 +10,7 @@ P5/H 트랙에서 transition_id 기반으로 정교화한다.
import math
from typing import Tuple
from common.logger import LOG
from negotiation.policies.qtable_policy import UCBQTablePolicy
from negotiation.qtable.domain.model.q_table import QTable
from negotiation.qtable.infra.repository.learning_repository import LearningRepository
@@ -31,7 +32,18 @@ class QTablePolicyStore:
# ③ 차원 불일치/base 없음 → 휴리스틱 빈 버전
err, active = await repo.read(lambda s: repo.get_active_version(s))
if active is not None:
version_id = active.version_id
if active.action_space_size != A or active.state_space_size != S:
# 카탈로그 카드 수(또는 상태 차원) 변경 → 학습 보존 마이그레이션.
# 겹치는 셀 복사(append/truncate 안전) + 새 카드 fresh. 실패 시 기존 버전 유지(load 가 reshape).
migrated = await repo.migrate_active_version_dim(
old_version=active, state_space_size=S, action_space_size=A,
learning_rate=lr, discount_factor=gamma, version_name=f"v_migrated_a{A}")
if migrated is not None:
LOG.i(f"[QTablePolicyStore] 차원 변경 마이그레이션 company={engine.company_id} "
f"{active.action_space_size}→{A} action (학습 보존)")
version_id = migrated or active.version_id
else:
version_id = active.version_id
else:
version_id = None
if engine.config.inherits_base:
@@ -227,6 +227,54 @@ class LearningRepository:
err = await DB_SESSION_MNG.execute_lambda_run([DBType.MAIN.value], [_create])
return vid if err == ErrorType.SUCCESS else None
async def migrate_active_version_dim(self, *, old_version, state_space_size: int, action_space_size: int,
learning_rate: float, discount_factor: float,
version_name: str = "v_migrated") -> Optional[uuid.UUID]:
"""활성 Q-table 을 새 차원으로 마이그레이션 (카탈로그 카드 수 변경 = action 차원 변경 시).
겹치는 (state < S, action < A) 셀만 복사한다 → **카탈로그 끝에 카드 추가(append)/삭제(truncate)에
안전**(action_id↔카드 위치 불변). 늘어난 새 action(새 카드)은 fresh(0, UCB 가 우선 탐험).
기존 활성 버전은 비활성화하고 새 버전을 활성화한다. 실패 시 None(호출자가 기존 버전 유지).
⚠️ 한계: 카탈로그 **중간 삽입·삭제**는 action_id 가 밀려 학습이 어긋날 수 있다 — 카드번호 기반
매핑(버전별 카탈로그 스냅샷 저장, tenant_action_cards 활용)이 후속 과제다.
"""
qcells, vcells = await self.load_cells(old_version.version_id)
vid = uuid.uuid4()
S, A = state_space_size, action_space_size
async def _create(s: AsyncSession) -> ErrorType:
# 기존 활성 비활성화 → 새 버전 활성 삽입 (동시 2개 활성 방지).
e = await DB_SESSION_MNG.add(s, update(QTableVersion).where(
QTableVersion.company_id == self.company_id,
QTableVersion.version_id == old_version.version_id).values(is_active=False))
if e != ErrorType.SUCCESS:
return e
ver = QTableVersion(
version_id=vid, company_id=self.company_id, version_name=version_name, scope=2,
base_version_id=old_version.version_id, state_space_size=S, action_space_size=A,
learning_rate=learning_rate, discount_factor=discount_factor, is_active=True,
)
e = await DB_SESSION_MNG.insert(s, ver)
if e != ErrorType.SUCCESS:
return e
qobjs = [QValue(company_id=self.company_id, version_id=vid, state_index=st, action_id=a, q_value=q)
for st, a, q in qcells if st < S and a < A]
vobjs = [VisitCount(company_id=self.company_id, version_id=vid, state_index=st, action_id=a, count=c)
for st, a, c in vcells if st < S and a < A]
if qobjs:
e = await DB_SESSION_MNG.insert(s, qobjs)
if e != ErrorType.SUCCESS:
return e
if vobjs:
e = await DB_SESSION_MNG.insert(s, vobjs)
if e != ErrorType.SUCCESS:
return e
return ErrorType.SUCCESS
err = await DB_SESSION_MNG.execute_lambda_run([DBType.MAIN.value], [_create])
return vid if err == ErrorType.SUCCESS else None
async def load_cells(self, version_id) -> Tuple[List[tuple], List[tuple]]:
"""(q_cells, visit_cells) — q_cells: (state,action,q), visit_cells: (state,action,count). 자사 스코프."""
def _q(s):