[feat] agent: 카드번호 기반 Q-table 마이그레이션 + 학습 리셋 스크립트
카탈로그 카드 추가/삭제/재정렬 시 action_id 가 밀려도 학습이 카드를 따라가도록, Q-table 버전에 카탈로그 스냅샷(카드번호)을 저장하고 카드번호로 리맵한다. - q_table_versions.action_cards JSONB 신설(카드번호 목록, index=action_id). models.py + init.sql(DDL·ALTER) + 로컬 DB ALTER. - 버전 생성(get_or_create/warm_start/migrate)이 action_cards 저장. - migrate_active_version_dim: 옛 action_cards ↔ 새 카탈로그를 카드번호로 리맵 (중간 삽입/삭제 보정, 사라진 카드 버림, 새 카드 fresh). 레거시(스냅샷 없음)는 위치 폴백. version_name 은 vid 접미로 유니크. - model_store.load: card_list 계산 → 차원변경 OR 동일차원 내용변경 시 마이그레이션, 레거시 버전 action_cards backfill(set_version_action_cards). - tools/reset_learning.py: learning 스키마만 비우는 리셋(카드·협상 데이터 보존), --company/--yes 옵션. 카탈로그 바꾸고 학습 처음부터 할 때 사용. - 테스트: 중간 카드 삭제 시 카드번호 리맵으로 학습 보존 검증. agent 100/100. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
7b7f606ace
commit
b368a19f79
6 files changed
+154
-25
No files matched your search
@@ -155,8 +155,10 @@ class LearningRepository:
|
||||
# ---- Q-Table 영속화 (H1) -------------------------------------------
|
||||
async def get_or_create_active_version(self, *, state_space_size: int, action_space_size: int,
|
||||
learning_rate: float, discount_factor: float,
|
||||
scope: int = 2, version_name: str = "v000") -> Optional[uuid.UUID]:
|
||||
"""활성 버전 version_id 반환. 없으면 v000 을 활성으로 생성. (company_id 스코프)"""
|
||||
scope: int = 2, version_name: str = "v000",
|
||||
action_cards: Optional[List[str]] = None) -> Optional[uuid.UUID]:
|
||||
"""활성 버전 version_id 반환. 없으면 v000 을 활성으로 생성. (company_id 스코프)
|
||||
action_cards: 카탈로그 스냅샷(카드번호 목록, index=action_id) — 후일 카드번호 기반 마이그레이션용."""
|
||||
err, existing = await DB_SESSION_MNG.execute_lambda(
|
||||
DBType.MAIN.value, DBWRType.DB_READ.value, lambda s: self.get_active_version(s)
|
||||
)
|
||||
@@ -170,6 +172,7 @@ class LearningRepository:
|
||||
version_id=vid, company_id=self.company_id, version_name=version_name, scope=scope,
|
||||
state_space_size=state_space_size, action_space_size=action_space_size,
|
||||
learning_rate=learning_rate, discount_factor=discount_factor, is_active=True,
|
||||
action_cards=action_cards,
|
||||
)
|
||||
return await DB_SESSION_MNG.insert(s, obj)
|
||||
|
||||
@@ -184,7 +187,8 @@ class LearningRepository:
|
||||
|
||||
async def warm_start_from_base(self, *, state_space_size: int, action_space_size: int,
|
||||
learning_rate: float, discount_factor: float, visit_decay: float = 0.5,
|
||||
version_name: str = "v000_warmstart_from_base") -> Optional[uuid.UUID]:
|
||||
version_name: str = "v000_warmstart_from_base",
|
||||
action_cards: Optional[List[str]] = None) -> Optional[uuid.UUID]:
|
||||
"""공유 베이스(_base)의 Q값/방문수를 자사로 복제해 활성 버전 생성 (cold-start ①, 계획서 D).
|
||||
|
||||
차원 불일치/베이스 없음 → None (호출자가 휴리스틱 init 폴백). visit 은 감쇠 복제(탐색 여지).
|
||||
@@ -205,7 +209,7 @@ class LearningRepository:
|
||||
version_id=vid, company_id=self.company_id, version_name=version_name, scope=2,
|
||||
base_version_id=base_ver.version_id, state_space_size=state_space_size,
|
||||
action_space_size=action_space_size, learning_rate=learning_rate,
|
||||
discount_factor=discount_factor, is_active=True,
|
||||
discount_factor=discount_factor, is_active=True, action_cards=action_cards,
|
||||
)
|
||||
e = await DB_SESSION_MNG.insert(s, ver)
|
||||
if e != ErrorType.SUCCESS:
|
||||
@@ -229,20 +233,30 @@ class LearningRepository:
|
||||
|
||||
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 차원 변경 시).
|
||||
version_name: str = "v_migrated",
|
||||
action_cards: Optional[List[str]] = None) -> Optional[uuid.UUID]:
|
||||
"""활성 Q-table 을 새 카탈로그로 마이그레이션 (카드 추가/삭제/재정렬 시).
|
||||
|
||||
겹치는 (state < S, action < A) 셀만 복사한다 → **카탈로그 끝에 카드 추가(append)/삭제(truncate)에
|
||||
안전**(action_id↔카드 위치 불변). 늘어난 새 action(새 카드)은 fresh(0, UCB 가 우선 탐험).
|
||||
기존 활성 버전은 비활성화하고 새 버전을 활성화한다. 실패 시 None(호출자가 기존 버전 유지).
|
||||
|
||||
⚠️ 한계: 카탈로그 **중간 삽입·삭제**는 action_id 가 밀려 학습이 어긋날 수 있다 — 카드번호 기반
|
||||
매핑(버전별 카탈로그 스냅샷 저장, tenant_action_cards 활용)이 후속 과제다.
|
||||
**카드번호 기반 리맵**: 옛 버전의 action_cards(카드번호 스냅샷)와 새 카탈로그(action_cards)를
|
||||
비교해, 같은 **카드번호**의 학습값을 새 action_id 로 옮긴다 → 중간 삽입/삭제로 action_id 가
|
||||
밀려도 학습이 카드에 정확히 따라간다. 새 카드는 fresh, 사라진 카드는 버려진다.
|
||||
옛 버전에 action_cards 가 없으면(레거시) 위치 기반 폴백(끝 추가/삭제만 안전).
|
||||
기존 활성 버전은 비활성화하고 새 버전을 활성화한다. 실패 시 None.
|
||||
"""
|
||||
qcells, vcells = await self.load_cells(old_version.version_id)
|
||||
vid = uuid.uuid4()
|
||||
unique_name = f"{version_name}_{vid.hex[:8]}" # (company_id, version_name) 유니크 충돌 방지
|
||||
S, A = state_space_size, action_space_size
|
||||
|
||||
# 옛 action_id → 새 action_id 리맵 테이블. 카드번호로 매칭(스냅샷 있을 때).
|
||||
old_cards = list(getattr(old_version, "action_cards", None) or [])
|
||||
new_cards = list(action_cards or [])
|
||||
if old_cards and new_cards:
|
||||
new_index = {num: i for i, num in enumerate(new_cards)}
|
||||
remap = {old_a: new_index[num] for old_a, num in enumerate(old_cards) if num in new_index}
|
||||
else:
|
||||
remap = {a: a for a in range(min(old_version.action_space_size, A))} # 위치 기반 폴백
|
||||
|
||||
async def _create(s: AsyncSession) -> ErrorType:
|
||||
# 기존 활성 비활성화 → 새 버전 활성 삽입 (동시 2개 활성 방지).
|
||||
e = await DB_SESSION_MNG.add(s, update(QTableVersion).where(
|
||||
@@ -251,17 +265,18 @@ class LearningRepository:
|
||||
if e != ErrorType.SUCCESS:
|
||||
return e
|
||||
ver = QTableVersion(
|
||||
version_id=vid, company_id=self.company_id, version_name=version_name, scope=2,
|
||||
version_id=vid, company_id=self.company_id, version_name=unique_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,
|
||||
action_cards=new_cards or None,
|
||||
)
|
||||
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]
|
||||
qobjs = [QValue(company_id=self.company_id, version_id=vid, state_index=st, action_id=remap[a], q_value=q)
|
||||
for st, a, q in qcells if st < S and a in remap]
|
||||
vobjs = [VisitCount(company_id=self.company_id, version_id=vid, state_index=st, action_id=remap[a], count=c)
|
||||
for st, a, c in vcells if st < S and a in remap]
|
||||
if qobjs:
|
||||
e = await DB_SESSION_MNG.insert(s, qobjs)
|
||||
if e != ErrorType.SUCCESS:
|
||||
@@ -275,6 +290,14 @@ class LearningRepository:
|
||||
err = await DB_SESSION_MNG.execute_lambda_run([DBType.MAIN.value], [_create])
|
||||
return vid if err == ErrorType.SUCCESS else None
|
||||
|
||||
async def set_version_action_cards(self, version_id, action_cards: List[str]) -> ErrorType:
|
||||
"""버전의 카탈로그 스냅샷(action_cards) 백필 — 레거시 버전이 향후 카탈로그 변경을 감지하게 한다."""
|
||||
async def _do(s: AsyncSession) -> ErrorType:
|
||||
return await DB_SESSION_MNG.add(s, update(QTableVersion).where(
|
||||
QTableVersion.company_id == self.company_id,
|
||||
QTableVersion.version_id == version_id).values(action_cards=action_cards))
|
||||
return await DB_SESSION_MNG.execute_lambda_run([DBType.MAIN.value], [_do])
|
||||
|
||||
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):
|
||||
|
||||
Reference in new issue
Block a user