[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:
1 parent
c2760c804f
commit
18020a9e07
25 files changed
+553
-62
No files matched your search
@@ -53,7 +53,7 @@ async def test_4_4_company_id_auto_onboard():
|
||||
eng = await _reg().get_engine(COMPANY_ID)
|
||||
assert eng.tenant_id == COMPANY_ID
|
||||
assert eng.company_id == COMPANY_ID # 학습/세션이 이 company_id 로 격리
|
||||
assert eng.action_space_size == 9 # base 기본 카드(162×9 정합)
|
||||
assert eng.action_space_size == 11 # base 기본 카드(162×11 정합)
|
||||
assert eng.state_space_size == 162
|
||||
|
||||
|
||||
|
||||
@@ -204,6 +204,9 @@ async def test_loader_with_crud_double(db_engine):
|
||||
async def count_item_session_suppliers(self, cdb, item_id):
|
||||
return ErrorType.SUCCESS, 0 # 이력도 없음 → NONE
|
||||
|
||||
async def get_quotation_card_numbers(self, cdb, quotation_id):
|
||||
return ErrorType.SUCCESS, (["NGC-003", "NGC-008"], ["WC-02"]) # 견적 선택 카드
|
||||
|
||||
ctx = await NegotiationContextLoader(crud=_FakeCRUD()).load(str(uuid.uuid4()))
|
||||
assert ctx is not None
|
||||
assert ctx.rq_type == "재견적" # qt_type=2(1:N)
|
||||
@@ -213,6 +216,8 @@ async def test_loader_with_crud_double(db_engine):
|
||||
assert ctx.revenue_amount == 12_000_000.0
|
||||
assert ctx.distribution_code == "B" # supply_type=3(총판) → B
|
||||
assert ctx.partner_type is PartnerType.NONE
|
||||
assert ctx.selected_nego_card_numbers == ["NGC-003", "NGC-008"]
|
||||
assert ctx.selected_wild_card_numbers == ["WC-02"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -49,7 +49,7 @@ def test_platform_neutral_defaults_load():
|
||||
def test_state_space_and_action_space_size():
|
||||
cfg = _loader().load("ktcommerce")
|
||||
assert cfg.state.state_space_size == 162 # 3×3×3×3×2 (차원 구성은 기능적 설계)
|
||||
assert cfg.action_mapping.action_space_size == 9
|
||||
assert cfg.action_mapping.action_space_size == 11
|
||||
# 합성 데모 카드 코드 (우리 스킴)
|
||||
assert cfg.action_mapping.action_to_card["0"] == "NGC-A001"
|
||||
assert cfg.action_mapping.action_to_card["8"] == "NGC-A009"
|
||||
@@ -77,15 +77,15 @@ def test_second_tenant_overrides_merged_on_base():
|
||||
assert cfg.policy.type == "ucb"
|
||||
# 차원은 데모 테넌트 A 와 동일(162) → base warm-start 호환(P5)
|
||||
assert cfg.state.state_space_size == 162
|
||||
assert cfg.action_mapping.action_space_size == 9
|
||||
assert cfg.action_mapping.action_space_size == 11
|
||||
assert cfg.action_mapping.action_to_card["0"] == "NGC-B001"
|
||||
|
||||
|
||||
def test_base_self_does_not_inherit():
|
||||
cfg = _loader().load("_base")
|
||||
assert cfg.tenant_id == "_base"
|
||||
# _base 는 기본 9카드(자동 온보딩 테넌트가 물려받음, base 정책 162×9 정합)
|
||||
assert cfg.action_mapping.action_space_size == 9
|
||||
# _base 는 기본 11카드(자동 온보딩 테넌트가 물려받음, base 정책 162×11 정합)
|
||||
assert cfg.action_mapping.action_space_size == 11
|
||||
|
||||
|
||||
def test_is_registered():
|
||||
|
||||
@@ -129,7 +129,7 @@ def test_reward_deterministic_and_config_driven():
|
||||
def test_action_card_mapper_roundtrip_and_mask():
|
||||
cfg = _cfg("ktcommerce")
|
||||
mapper = ActionCardMapper(cfg.action_mapping)
|
||||
assert mapper.action_space_size == 9
|
||||
assert mapper.action_space_size == 11
|
||||
assert mapper.get_card_id(0) == "NGC-A001"
|
||||
assert mapper.get_action_id("NGC-A001") == 0
|
||||
assert mapper.get_card_id(99) is None
|
||||
@@ -139,7 +139,7 @@ def test_action_card_mapper_roundtrip_and_mask():
|
||||
assert mask.dtype == np.bool_
|
||||
assert mask[0] == False and mask[3] == False
|
||||
assert mask[1] == True
|
||||
assert mask.sum() == 7
|
||||
assert mask.sum() == 9
|
||||
|
||||
# reload 로 다른 테넌트 카드셋 교체
|
||||
mapper.reload(_cfg("imarketkorea").action_mapping)
|
||||
|
||||
@@ -35,7 +35,7 @@ async def test_two_tenants_distinct_engines():
|
||||
assert e1.mapper.get_card_id(0) == "NGC-A001"
|
||||
assert e2.mapper.get_card_id(0) == "NGC-B001"
|
||||
# 차원
|
||||
assert e1.state_space_size == 162 and e1.action_space_size == 9
|
||||
assert e1.state_space_size == 162 and e1.action_space_size == 11
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -69,7 +69,7 @@ async def test_unregistered_company_id_auto_onboards():
|
||||
reg = _registry()
|
||||
# 미등록 company_id(uuid)는 _base 자동 온보딩 → 엔진 생성됨(베이스 9카드, 162 state).
|
||||
eng = await reg.get_engine("00000000-0000-0000-0000-000000000001")
|
||||
assert eng.action_space_size == 9 and eng.state_space_size == 162
|
||||
assert eng.action_space_size == 11 and eng.state_space_size == 162
|
||||
assert eng.company_id == "00000000-0000-0000-0000-000000000001"
|
||||
assert reg.is_registered("ktcommerce") is True
|
||||
# 빈 키만 미등록 → KeyError
|
||||
@@ -97,6 +97,84 @@ def test_episode_state_is_request_scoped():
|
||||
assert not hasattr(TenantEngine, "used_action_ids")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_action_space_from_db_catalog(db_engine):
|
||||
"""action_mapping.type=db(_base) 면 카드 카탈로그(DB)가 action space 를 정의한다 — config 파일이 아님.
|
||||
negodata 에서 카드가 추가/삭제되면 config 수정 없이 action space 가 반영됨을 의미."""
|
||||
from common.enums import ErrorType
|
||||
from negotiation.cards.ports.card_catalog_port import ICardCatalogRepository
|
||||
|
||||
class _FakeCatalog(ICardCatalogRepository):
|
||||
async def get_nego_catalog(self, cdb):
|
||||
return ErrorType.SUCCESS, ["NGC-001", "NGC-002", "NGC-003"] # 3장짜리 카탈로그(파일은 11장)
|
||||
|
||||
reg = TenantEngineRegistry(
|
||||
loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0),
|
||||
catalog_repo=_FakeCatalog(),
|
||||
)
|
||||
eng = await reg.get_engine("_base") # _base = type:db
|
||||
assert eng.action_space_size == 3 # DB 카탈로그(3)가 정의 — 파일 폴백(11) 아님
|
||||
assert eng.mapper.get_card_id(0) == "NGC-001"
|
||||
assert eng.mapper.get_card_id(2) == "NGC-003"
|
||||
assert eng.mapper.get_action_id("NGC-002") == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_action_space_falls_back_to_file_when_catalog_empty(db_engine):
|
||||
"""카탈로그가 비면(신규/미시드 DB) 파일 action_to_card 로 폴백한다."""
|
||||
from common.enums import ErrorType
|
||||
from negotiation.cards.ports.card_catalog_port import ICardCatalogRepository
|
||||
|
||||
class _EmptyCatalog(ICardCatalogRepository):
|
||||
async def get_nego_catalog(self, cdb):
|
||||
return ErrorType.SUCCESS, []
|
||||
|
||||
reg = TenantEngineRegistry(
|
||||
loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0),
|
||||
catalog_repo=_EmptyCatalog(),
|
||||
)
|
||||
eng = await reg.get_engine("_base")
|
||||
assert eng.action_space_size == 11 # 파일 폴백(11장 스냅샷)
|
||||
assert eng.mapper.get_card_id(0) == "NGC-001"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_company_brand_from_db_for_auto_onboard(db_engine):
|
||||
"""자동 온보딩 고객사(company_id=UUID)는 company.companies.name 으로 {company_name} 을 채운다."""
|
||||
import uuid as _uuid
|
||||
from common.enums import ErrorType
|
||||
from tenancy.company_profile_repo import ICompanyProfileRepository
|
||||
|
||||
class _FakeCompany(ICompanyProfileRepository):
|
||||
async def get_company_name(self, cdb, company_id):
|
||||
return ErrorType.SUCCESS, "풀무원"
|
||||
|
||||
reg = TenantEngineRegistry(
|
||||
loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0),
|
||||
company_repo=_FakeCompany(),
|
||||
)
|
||||
eng = await reg.get_engine(str(_uuid.uuid4())) # UUID → 자동 온보딩 + 브랜드 DB
|
||||
assert eng.config.resources.company_name == "풀무원"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_demo_tenant_keeps_file_brand(db_engine):
|
||||
"""데모 테넌트(비-UUID)는 회사명 조회 없이 파일 브랜드 유지."""
|
||||
from common.enums import ErrorType
|
||||
from tenancy.company_profile_repo import ICompanyProfileRepository
|
||||
|
||||
class _FakeCompany(ICompanyProfileRepository):
|
||||
async def get_company_name(self, cdb, company_id):
|
||||
return ErrorType.SUCCESS, "USED-ONLY-IF-QUERIED"
|
||||
|
||||
reg = TenantEngineRegistry(
|
||||
loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0),
|
||||
company_repo=_FakeCompany(),
|
||||
)
|
||||
eng = await reg.get_engine("ktcommerce") # 비-UUID → 조회 안 함
|
||||
assert eng.config.resources.company_name == "데모상사 A"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_middleware_header_missing_unregistered_registered(client):
|
||||
# 헤더 누락 → 400
|
||||
|
||||
@@ -58,7 +58,7 @@ async def test_warm_start_copies_base_with_decayed_visits(db_engine):
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cold_start_creates_warmstart_version(db_engine):
|
||||
await _seed_base()
|
||||
await _seed_base(A=11) # ktcommerce action_space=11 과 차원 일치해야 warm-start
|
||||
eng = await _reg().get_engine("ktcommerce") # 활성 버전 없음 → cold-start
|
||||
policy, version_id, repo = await QTablePolicyStore.load(eng)
|
||||
err, ver = await repo.read(lambda s: repo.get_active_version(s))
|
||||
@@ -67,6 +67,31 @@ async def test_cold_start_creates_warmstart_version(db_engine):
|
||||
assert policy.qtable.q[5, 2] == 0.9
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_catalog_dim_change_migrates_preserving_learning(db_engine):
|
||||
"""카탈로그 카드 수 변경(9→11) 시 학습 보존 마이그레이션 — 겹치는 셀 복사 + 새 카드 fresh."""
|
||||
import uuid as _uuid
|
||||
cid = str(_uuid.uuid4())
|
||||
# 이 회사 활성 버전을 A=9 로 시드 + 셀 (5,2)=0.9
|
||||
repo = LearningRepository(cid)
|
||||
vid = await repo.get_or_create_active_version(
|
||||
state_space_size=162, action_space_size=9, learning_rate=0.1, discount_factor=0.95,
|
||||
scope=2, version_name="old_v9")
|
||||
await repo.upsert_cell(vid, state_index=5, action_id=2, q_value=0.9, count=7)
|
||||
|
||||
# 엔진(_base type:db → 카탈로그 11장) 로드 → 9≠11 감지 → 마이그레이션
|
||||
eng = await _reg().get_engine(cid)
|
||||
assert eng.action_space_size == 11
|
||||
policy, new_vid, _ = await QTablePolicyStore.load(eng)
|
||||
assert str(new_vid) != str(vid) # 새 버전
|
||||
assert policy.qtable.q[5, 2] == 0.9 # 기존 학습 보존
|
||||
assert policy.qtable.q[5, 10] == 0.0 # 새 카드(action 10) fresh
|
||||
assert policy.qtable.visits[5, 2] == 7 # 방문수도 보존
|
||||
# 새 버전이 활성 · 차원 11
|
||||
err, active = await repo.read(lambda s: repo.get_active_version(s))
|
||||
assert str(active.version_id) == str(new_vid) and active.action_space_size == 11
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_dimension_mismatch_falls_back_to_heuristic(db_engine):
|
||||
await _seed_base(S=162, A=9)
|
||||
|
||||
@@ -66,6 +66,26 @@ async def test_card_update_search(client, db_engine):
|
||||
assert any(m["card_id"] == "CUSTOM-X" for m in allm["mapping"])
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_catalog_refresh(client, db_engine):
|
||||
# 카탈로그 발행 후 엔진 재조립 트리거 — 성공 + action_space 반환. 헤더 없으면 400.
|
||||
r = await client.post("/v1/catalog-refresh", headers=H)
|
||||
assert r.status_code == 200
|
||||
body = r.json()
|
||||
assert body["success"] and body["action_space_size"] >= 1
|
||||
r2 = await client.post("/v1/catalog-refresh")
|
||||
assert r2.status_code == 400
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_catalog_refresh_all_no_tenant_header(client, db_engine):
|
||||
# 공용 카탈로그 전역 반영 — 테넌트 헤더 없이도 200(화이트리스트) + 캐시 클리어.
|
||||
await client.post("/v1/catalog-refresh", headers=H) # 엔진 하나 캐시
|
||||
r = await client.post("/v1/catalog-refresh-all") # 헤더 없음
|
||||
assert r.status_code == 200
|
||||
assert r.json()["success"] is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_invalidate_and_reset_scoped(client, db_engine):
|
||||
# 가격협상 카드선택이 일어나는 긴 경로(850→900→990)로 양 테넌트 데이터 생성
|
||||
|
||||
+31
-14
@@ -125,24 +125,41 @@ def test_acceptance_ratio_dynamic_calc():
|
||||
assert calc({"input_price": 9800}) == 0.0 # 기준가 전무(과거 세션 호환)
|
||||
|
||||
|
||||
def test_selected_card_mapping_overrides_tenant_default():
|
||||
"""운영 세션은 견적 version_id 에 묶인 카드 번호를 action_id 순서로 사용한다."""
|
||||
session = ChatSession(
|
||||
session_id="00000000-0000-0000-0000-000000000001",
|
||||
tenant_id="ktcommerce",
|
||||
company_id="ktcommerce",
|
||||
context={"selected_nego_card_numbers": ["2", "7"]},
|
||||
action_space_size=2,
|
||||
)
|
||||
def test_card_id_fixed_mapping_and_selection_mask():
|
||||
"""카드 정리 후: action_id↔카드는 테넌트 매핑으로 고정, 견적 선택은 available_mask 로 걸러진다.
|
||||
(구 인덱스 방식 폐기 — selected[action_id] 인덱싱은 견적마다 action_id 의미가 달라져 Q-table 오염.)"""
|
||||
class _Mapper:
|
||||
def get_card_id(self, action_id):
|
||||
return f"DEFAULT-{action_id}"
|
||||
_m = {i: f"NGC-A{i + 1:03d}" for i in range(11)}
|
||||
def get_card_id(self, a):
|
||||
return self._m.get(a)
|
||||
def get_action_id(self, num):
|
||||
return next((a for a, c in self._m.items() if c == num), None)
|
||||
class _Engine:
|
||||
mapper = _Mapper()
|
||||
action_space_size = 11
|
||||
eng = _Engine()
|
||||
session = ChatSession(
|
||||
session_id="00000000-0000-0000-0000-000000000001", tenant_id="ktcommerce", company_id="ktcommerce",
|
||||
context={"selected_nego_card_numbers": ["NGC-A003", "NGC-A008"]}, action_space_size=11,
|
||||
)
|
||||
|
||||
assert ChatService._card_id_for_action(_Engine(), session, 0) == "2"
|
||||
assert ChatService._card_id_for_action(_Engine(), session, 1) == "7"
|
||||
assert ChatService._card_id_for_action(_Engine(), session, 8) == "DEFAULT-8"
|
||||
# ① card_id 는 고정 매핑 (선택 리스트 인덱싱 아님)
|
||||
assert ChatService._card_id_for_action(eng, session, 0) == "NGC-A001"
|
||||
assert ChatService._card_id_for_action(eng, session, 2) == "NGC-A003"
|
||||
|
||||
# ② 선택은 mask 로 — NGC-A003(action 2), NGC-A008(action 7) 만 pickable
|
||||
mask = ChatService._selection_mask(eng, session)
|
||||
assert mask is not None and mask[2] and mask[7]
|
||||
assert not mask[0] and not mask[5] and mask.sum() == 2
|
||||
|
||||
# ③ 사용한 action 은 mask 에서 제외
|
||||
session.used_action_ids = {2}
|
||||
mask2 = ChatService._selection_mask(eng, session)
|
||||
assert not mask2[2] and mask2[7] and mask2.sum() == 1
|
||||
|
||||
# ④ 선택 없으면 None → 전체 허용(폴백)
|
||||
session.context["selected_nego_card_numbers"] = []
|
||||
assert ChatService._selection_mask(eng, session) is None
|
||||
|
||||
|
||||
def test_default_1pct_wildcard_still_runs_without_selected_wildcard():
|
||||
|
||||
Reference in new issue
Block a user