Agent 서버 구축: 멀티테넌트 협상 PoC (UCB Q-Table 학습 + /chat + 14 API + 학습검증 하네스), config 단일화(local.toml) + 빌드 경량화
This commit is contained in:
1 parent
212725e5f9
commit
951d6eab84
140 files changed
+6689
-214
No files matched your search
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,339 @@
|
||||
"""LearningRepository — learning.* 테이블 접근 (company_id 스코프, backend CRUD 컨벤션).
|
||||
|
||||
핵심 안전장치(계획서 리스크): company_id 를 **생성자에 박아** 모든 쿼리에 자동 주입한다.
|
||||
삭제/리셋도 ORM core where(company_id=...)로만 수행 → "raw SQL 전체삭제로 타사 데이터 파괴" 불가.
|
||||
메서드는 backend crud 처럼 (session, ...) 을 받고, service 는 DB_SESSION_MNG 람다로 호출한다.
|
||||
"""
|
||||
|
||||
import uuid
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
from sqlalchemy import delete, select, update
|
||||
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import (
|
||||
BASE_COMPANY_ID,
|
||||
ExperienceLog,
|
||||
QTableVersion,
|
||||
QValue,
|
||||
TenantActionCard,
|
||||
VisitCount,
|
||||
)
|
||||
from common.enums import DBType, DBWRType, ErrorType
|
||||
from common.logger import LOG
|
||||
from common.utils.gtime import GTime
|
||||
|
||||
|
||||
class LearningRepository:
|
||||
def __init__(self, company_id: str):
|
||||
if not company_id:
|
||||
raise ValueError("company_id is required (테넌트 스코프 필수)")
|
||||
self.company_id = company_id
|
||||
|
||||
# ---- 버전 ----------------------------------------------------------
|
||||
async def create_version(self, s: AsyncSession, *, version_name: str, scope: int,
|
||||
state_space_size: int, action_space_size: int,
|
||||
learning_rate: float = 0.1, discount_factor: float = 0.95,
|
||||
base_version_id=None, is_active: bool = False) -> ErrorType:
|
||||
obj = QTableVersion(
|
||||
company_id=self.company_id,
|
||||
version_name=version_name,
|
||||
scope=scope,
|
||||
base_version_id=base_version_id,
|
||||
state_space_size=state_space_size,
|
||||
action_space_size=action_space_size,
|
||||
learning_rate=learning_rate,
|
||||
discount_factor=discount_factor,
|
||||
is_active=is_active,
|
||||
)
|
||||
return await DB_SESSION_MNG.insert(s, obj)
|
||||
|
||||
async def get_version_by_name(self, s: AsyncSession, version_name: str) -> Tuple[ErrorType, Optional[QTableVersion]]:
|
||||
q = (
|
||||
select(QTableVersion)
|
||||
.where(QTableVersion.company_id == self.company_id, QTableVersion.version_name == version_name, QTableVersion.deleted == False) # noqa: E712
|
||||
.limit(1)
|
||||
)
|
||||
err, rows = await DB_SESSION_MNG.execute(s, q)
|
||||
if err != ErrorType.SUCCESS:
|
||||
return err, None
|
||||
return ErrorType.SUCCESS, rows[0] if rows else None
|
||||
|
||||
async def list_versions(self, s: AsyncSession) -> Tuple[ErrorType, List[QTableVersion]]:
|
||||
q = (
|
||||
select(QTableVersion)
|
||||
.where(QTableVersion.company_id == self.company_id, QTableVersion.deleted == False) # noqa: E712
|
||||
.order_by(QTableVersion.created_at.asc())
|
||||
)
|
||||
return await DB_SESSION_MNG.execute(s, q)
|
||||
|
||||
async def get_active_version(self, s: AsyncSession) -> Tuple[ErrorType, Optional[QTableVersion]]:
|
||||
q = (
|
||||
select(QTableVersion)
|
||||
.where(QTableVersion.company_id == self.company_id, QTableVersion.is_active == True, QTableVersion.deleted == False) # noqa: E712
|
||||
.limit(1)
|
||||
)
|
||||
err, rows = await DB_SESSION_MNG.execute(s, q)
|
||||
if err != ErrorType.SUCCESS:
|
||||
return err, None
|
||||
return ErrorType.SUCCESS, rows[0] if rows else None
|
||||
|
||||
# ---- 경험 로그 -----------------------------------------------------
|
||||
async def log_transition(self, s: AsyncSession, data: Dict[str, Any]) -> ErrorType:
|
||||
"""data 의 알려진 필드만 채워 ExperienceLog insert. company_id 는 항상 강제 주입."""
|
||||
allowed = {c.name for c in ExperienceLog.__table__.columns}
|
||||
payload = {k: v for k, v in data.items() if k in allowed}
|
||||
payload["company_id"] = self.company_id # 위조 방지: 항상 덮어쓴다
|
||||
return await DB_SESSION_MNG.insert(s, ExperienceLog(**payload))
|
||||
|
||||
async def update_transition_reward(self, s: AsyncSession, transition_id, *, reward: float,
|
||||
next_state_index: Optional[int] = None, done: bool = False,
|
||||
settled_price: Optional[int] = None) -> ErrorType:
|
||||
q = (
|
||||
update(ExperienceLog)
|
||||
.where(ExperienceLog.company_id == self.company_id, ExperienceLog.transition_id == transition_id)
|
||||
.values(reward=reward, next_state_index=next_state_index, done=done, settled_price=settled_price)
|
||||
)
|
||||
return await DB_SESSION_MNG.add(s, q)
|
||||
|
||||
async def count_experience(self, s: AsyncSession) -> Tuple[ErrorType, int]:
|
||||
q = select(ExperienceLog).where(ExperienceLog.company_id == self.company_id)
|
||||
err, rows = await DB_SESSION_MNG.execute(s, q)
|
||||
if err != ErrorType.SUCCESS:
|
||||
return err, 0
|
||||
return ErrorType.SUCCESS, len(rows)
|
||||
|
||||
async def invalidate_by_session(self, s: AsyncSession, session_id, reason: str = "") -> ErrorType:
|
||||
q = (
|
||||
update(ExperienceLog)
|
||||
.where(ExperienceLog.company_id == self.company_id, ExperienceLog.session_id == session_id)
|
||||
.values(is_invalidated=True, invalidated_reason=reason)
|
||||
)
|
||||
return await DB_SESSION_MNG.add(s, q)
|
||||
|
||||
# ---- 리셋 (스코프 강제, 타테넌트 무영향) ---------------------------
|
||||
async def _delete_experience(self, s: AsyncSession) -> ErrorType:
|
||||
# 계획서 리스크: 구 코드의 'DELETE FROM experience_logs' (WHERE 없음)를 대체.
|
||||
return await DB_SESSION_MNG.add(s, delete(ExperienceLog).where(ExperienceLog.company_id == self.company_id))
|
||||
|
||||
async def _delete_learning_rows(self, s: AsyncSession) -> ErrorType:
|
||||
for model in (QValue, VisitCount):
|
||||
err = await DB_SESSION_MNG.add(s, delete(model).where(model.company_id == self.company_id))
|
||||
if err != ErrorType.SUCCESS:
|
||||
return err
|
||||
return ErrorType.SUCCESS
|
||||
|
||||
async def _delete_nonactive_versions(self, s: AsyncSession) -> ErrorType:
|
||||
return await DB_SESSION_MNG.add(
|
||||
s,
|
||||
delete(QTableVersion).where(QTableVersion.company_id == self.company_id, QTableVersion.is_active == False), # noqa: E712
|
||||
)
|
||||
|
||||
async def reset_learning(self) -> ErrorType:
|
||||
"""학습 데이터(q_values/visit_counts/experience)만 초기화. 자사 스코프."""
|
||||
return await DB_SESSION_MNG.execute_lambda_run(
|
||||
[DBType.MAIN.value],
|
||||
[self._delete_learning_rows, self._delete_experience],
|
||||
)
|
||||
|
||||
async def reset_all(self) -> ErrorType:
|
||||
"""완전 초기화: 자사 experience 전체 + q_values/visit + 비활성 버전 삭제. 타테넌트 무영향."""
|
||||
return await DB_SESSION_MNG.execute_lambda_run(
|
||||
[DBType.MAIN.value],
|
||||
[self._delete_experience, self._delete_learning_rows, self._delete_nonactive_versions],
|
||||
)
|
||||
|
||||
# ---- 람다 facade (service/test 용) ---------------------------------
|
||||
async def read(self, func):
|
||||
return await DB_SESSION_MNG.execute_lambda(DBType.MAIN.value, DBWRType.DB_READ.value, func)
|
||||
|
||||
async def write_one(self, func):
|
||||
return await DB_SESSION_MNG.execute_lambda_run([DBType.MAIN.value], [func])
|
||||
|
||||
# ---- 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 스코프)"""
|
||||
err, existing = await DB_SESSION_MNG.execute_lambda(
|
||||
DBType.MAIN.value, DBWRType.DB_READ.value, lambda s: self.get_active_version(s)
|
||||
)
|
||||
if err == ErrorType.SUCCESS and existing is not None:
|
||||
return existing.version_id
|
||||
|
||||
vid = uuid.uuid4()
|
||||
|
||||
async def _create(s: AsyncSession) -> ErrorType:
|
||||
obj = QTableVersion(
|
||||
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,
|
||||
)
|
||||
return await DB_SESSION_MNG.insert(s, obj)
|
||||
|
||||
err = await DB_SESSION_MNG.execute_lambda_run([DBType.MAIN.value], [_create])
|
||||
if err != ErrorType.SUCCESS:
|
||||
# 동시 생성 경합 등 → 다시 읽어 활성 버전 반환
|
||||
err2, existing2 = await DB_SESSION_MNG.execute_lambda(
|
||||
DBType.MAIN.value, DBWRType.DB_READ.value, lambda s: self.get_active_version(s)
|
||||
)
|
||||
return existing2.version_id if existing2 else None
|
||||
return vid
|
||||
|
||||
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]:
|
||||
"""공유 베이스(_base)의 Q값/방문수를 자사로 복제해 활성 버전 생성 (cold-start ①, 계획서 D).
|
||||
|
||||
차원 불일치/베이스 없음 → None (호출자가 휴리스틱 init 폴백). visit 은 감쇠 복제(탐색 여지).
|
||||
"""
|
||||
base_repo = LearningRepository(BASE_COMPANY_ID)
|
||||
err, base_ver = await DB_SESSION_MNG.execute_lambda(
|
||||
DBType.MAIN.value, DBWRType.DB_READ.value, lambda s: base_repo.get_active_version(s))
|
||||
if err != ErrorType.SUCCESS or base_ver is None:
|
||||
return None
|
||||
if base_ver.state_space_size != state_space_size or base_ver.action_space_size != action_space_size:
|
||||
return None # 차원 불일치 → 휴리스틱 폴백
|
||||
|
||||
qcells, vcells = await base_repo.load_cells(base_ver.version_id)
|
||||
vid = uuid.uuid4()
|
||||
|
||||
async def _create(s: AsyncSession) -> ErrorType:
|
||||
ver = QTableVersion(
|
||||
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,
|
||||
)
|
||||
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]
|
||||
vobjs = [VisitCount(company_id=self.company_id, version_id=vid, state_index=st, action_id=a,
|
||||
count=int(c * visit_decay)) for st, a, c in vcells]
|
||||
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):
|
||||
q = select(QValue.state_index, QValue.action_id, QValue.q_value).where(
|
||||
QValue.company_id == self.company_id, QValue.version_id == version_id)
|
||||
return DB_SESSION_MNG.execute(s, q)
|
||||
|
||||
def _v(s):
|
||||
q = select(VisitCount.state_index, VisitCount.action_id, VisitCount.count).where(
|
||||
VisitCount.company_id == self.company_id, VisitCount.version_id == version_id)
|
||||
return DB_SESSION_MNG.execute(s, q)
|
||||
|
||||
err, qrows = await DB_SESSION_MNG.execute_lambda(DBType.MAIN.value, DBWRType.DB_READ.value, _q)
|
||||
err, vrows = await DB_SESSION_MNG.execute_lambda(DBType.MAIN.value, DBWRType.DB_READ.value, _v)
|
||||
return list(qrows), list(vrows)
|
||||
|
||||
# ---- 버전 전환 / 요약 (관리 API) ----------------------------------
|
||||
async def set_active_version(self, version_name: str) -> ErrorType:
|
||||
"""version_name 을 활성으로 전환(나머지 비활성). 자사 스코프."""
|
||||
err, target = await DB_SESSION_MNG.execute_lambda(
|
||||
DBType.MAIN.value, DBWRType.DB_READ.value, lambda s: self.get_version_by_name(s, version_name))
|
||||
if err != ErrorType.SUCCESS or target is None:
|
||||
return ErrorType.DB_INVALID_KEY
|
||||
|
||||
async def _deactivate(s):
|
||||
return await DB_SESSION_MNG.add(s, update(QTableVersion)
|
||||
.where(QTableVersion.company_id == self.company_id).values(is_active=False))
|
||||
|
||||
async def _activate(s):
|
||||
return await DB_SESSION_MNG.add(s, update(QTableVersion)
|
||||
.where(QTableVersion.company_id == self.company_id, QTableVersion.version_name == version_name)
|
||||
.values(is_active=True))
|
||||
|
||||
return await DB_SESSION_MNG.execute_lambda_run([DBType.MAIN.value], [_deactivate, _activate])
|
||||
|
||||
async def qvalue_count(self, version_id) -> int:
|
||||
def _q(s):
|
||||
return DB_SESSION_MNG.execute(s, select(QValue.id).where(
|
||||
QValue.company_id == self.company_id, QValue.version_id == version_id))
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(DBType.MAIN.value, DBWRType.DB_READ.value, _q)
|
||||
return len(rows)
|
||||
|
||||
async def recent_experience(self, limit: int = 50) -> List[dict]:
|
||||
def _q(s):
|
||||
return DB_SESSION_MNG.execute(s, select(
|
||||
ExperienceLog.transition_id, ExperienceLog.session_id, ExperienceLog.state_index,
|
||||
ExperienceLog.action_id, ExperienceLog.card_id, ExperienceLog.reward, ExperienceLog.turn,
|
||||
ExperienceLog.propensity, ExperienceLog.done, ExperienceLog.created_at,
|
||||
).where(ExperienceLog.company_id == self.company_id).order_by(ExperienceLog.id.desc()).limit(limit))
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(DBType.MAIN.value, DBWRType.DB_READ.value, _q)
|
||||
return [dict(state_index=r[2], action_id=r[3], card_id=r[4], reward=r[5], turn=r[6],
|
||||
propensity=r[7], done=r[8], session_id=str(r[1]) if r[1] else None,
|
||||
transition_id=str(r[0]), created_at=str(r[9])) for r in rows]
|
||||
|
||||
async def load_transitions(self) -> List[tuple]:
|
||||
"""학습용 (state_index, action_id, reward, next_state_index, done). reward 있는 row 만."""
|
||||
def _q(s):
|
||||
return DB_SESSION_MNG.execute(s, select(
|
||||
ExperienceLog.state_index, ExperienceLog.action_id, ExperienceLog.reward,
|
||||
ExperienceLog.next_state_index, ExperienceLog.done,
|
||||
).where(ExperienceLog.company_id == self.company_id, ExperienceLog.reward.isnot(None),
|
||||
ExperienceLog.is_invalidated == False)) # noqa: E712
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(DBType.MAIN.value, DBWRType.DB_READ.value, _q)
|
||||
return [(r[0], r[1], r[2], r[3], r[4]) for r in rows]
|
||||
|
||||
# ---- 카드 매핑 (card-update/search) -------------------------------
|
||||
async def upsert_action_card(self, action_id: int, card_id: str) -> ErrorType:
|
||||
async def _do(s):
|
||||
q = select(TenantActionCard).where(
|
||||
TenantActionCard.company_id == self.company_id, TenantActionCard.action_id == action_id,
|
||||
TenantActionCard.deleted == False) # noqa: E712
|
||||
err, rows = await DB_SESSION_MNG.execute(s, q)
|
||||
if rows:
|
||||
return await DB_SESSION_MNG.add(s, update(TenantActionCard)
|
||||
.where(TenantActionCard.company_id == self.company_id, TenantActionCard.action_id == action_id)
|
||||
.values(card_id=card_id, updated_at=GTime.UTC()))
|
||||
return await DB_SESSION_MNG.insert(s, TenantActionCard(
|
||||
company_id=self.company_id, action_id=action_id, card_id=card_id))
|
||||
return await DB_SESSION_MNG.execute_lambda_run([DBType.MAIN.value], [_do])
|
||||
|
||||
async def get_action_cards(self) -> List[dict]:
|
||||
def _q(s):
|
||||
return DB_SESSION_MNG.execute(s, select(TenantActionCard.action_id, TenantActionCard.card_id)
|
||||
.where(TenantActionCard.company_id == self.company_id, TenantActionCard.deleted == False)) # noqa: E712
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(DBType.MAIN.value, DBWRType.DB_READ.value, _q)
|
||||
return [dict(action_id=r[0], card_id=r[1]) for r in rows]
|
||||
|
||||
async def upsert_cell(self, version_id, state_index: int, action_id: int, q_value: float, count: int) -> ErrorType:
|
||||
"""단일 (state, action) 셀 write-through (q_values + visit_counts). company_id 스코프."""
|
||||
def _q(s):
|
||||
stmt = pg_insert(QValue.__table__).values(
|
||||
company_id=self.company_id, version_id=version_id,
|
||||
state_index=state_index, action_id=action_id, q_value=q_value,
|
||||
).on_conflict_do_update(
|
||||
index_elements=[QValue.company_id, QValue.version_id, QValue.state_index, QValue.action_id],
|
||||
set_={"q_value": q_value},
|
||||
)
|
||||
return DB_SESSION_MNG.add(s, stmt)
|
||||
|
||||
def _v(s):
|
||||
stmt = pg_insert(VisitCount.__table__).values(
|
||||
company_id=self.company_id, version_id=version_id,
|
||||
state_index=state_index, action_id=action_id, count=count,
|
||||
).on_conflict_do_update(
|
||||
index_elements=[VisitCount.company_id, VisitCount.version_id, VisitCount.state_index, VisitCount.action_id],
|
||||
set_={"count": count},
|
||||
)
|
||||
return DB_SESSION_MNG.add(s, stmt)
|
||||
|
||||
return await DB_SESSION_MNG.execute_lambda_run([DBType.MAIN.value], [_q, _v])
|
||||
Reference in new issue
Block a user