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.
@@ -0,0 +1,188 @@
|
||||
from asyncio import current_task
|
||||
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_scoped_session
|
||||
from sqlalchemy.util._collections import immutabledict
|
||||
|
||||
from common.database.model.models import MAIN_BASE
|
||||
from common.enums import DBType, DBWRType, ErrorType
|
||||
from common.logger import LOG
|
||||
from common.singleton import Singleton
|
||||
from config.server_configs import main_db_config
|
||||
|
||||
|
||||
class DBSessionManager(Singleton):
|
||||
"""DB 세션/엔진 관리자 (싱글톤). backend/common/database/db_session_manager.py 와 동일 패턴.
|
||||
|
||||
- DBType(논리 DB) x DBWRType(Read/Write) 조합마다 별도 async 엔진.
|
||||
- 비즈니스 로직(service)은 세션을 직접 열지 않고 "람다"를 넘긴다.
|
||||
execute_lambda : 단일 쿼리 (주로 조회)
|
||||
execute_lambda_run : 동일 DB 의 여러 변경 쿼리를 한 트랜잭션으로 commit
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
if DBSessionManager.is_init():
|
||||
LOG.e_no_callstack("already init DBSessionManager")
|
||||
return
|
||||
DBSessionManager.set_init()
|
||||
|
||||
self.__DB_URL_MAP = {"postgresql": "postgresql+asyncpg"}
|
||||
self.__engines = []
|
||||
self.__db_type_map = {
|
||||
DBType.MAIN.value: main_db_config,
|
||||
}
|
||||
|
||||
self.__write_session = {
|
||||
DBType.MAIN.value: self.create_engine(DBType.MAIN.value, DBWRType.DB_WRITE.value),
|
||||
}
|
||||
self.__read_session = {
|
||||
DBType.MAIN.value: self.create_engine(DBType.MAIN.value, DBWRType.DB_READ.value),
|
||||
}
|
||||
|
||||
def create_engine(self, db_type: int, db_wr_type: int):
|
||||
db_config = self.__db_type_map.get(db_type)
|
||||
if not db_config:
|
||||
raise ValueError("Invalid database type")
|
||||
|
||||
if db_wr_type == DBWRType.DB_READ.value:
|
||||
pw = (":" + db_config.read_pw) if len(db_config.read_pw) > 0 else ""
|
||||
db_url = f"{self.__DB_URL_MAP[db_config.db_type]}://{db_config.read_id}{pw}@{db_config.read_host}:{db_config.read_port}/{db_config.name}"
|
||||
LOG.i(f"Read DB create engine url : {db_url}")
|
||||
else:
|
||||
pw = (":" + db_config.write_pw) if len(db_config.write_pw) > 0 else ""
|
||||
db_url = f"{self.__DB_URL_MAP[db_config.db_type]}://{db_config.write_id}{pw}@{db_config.write_host}:{db_config.write_port}/{db_config.name}"
|
||||
LOG.i(f"Write DB create engine url : {db_url}")
|
||||
|
||||
engine = create_async_engine(
|
||||
db_url,
|
||||
echo=db_config.show_log,
|
||||
pool_size=db_config.pool_size,
|
||||
max_overflow=db_config.max_overflow,
|
||||
pool_pre_ping=True,
|
||||
pool_recycle=600,
|
||||
)
|
||||
self.__engines.append(engine)
|
||||
scoped_session = async_scoped_session(
|
||||
sessionmaker(engine, class_=AsyncSession, expire_on_commit=False, autocommit=False, autoflush=False),
|
||||
scopefunc=current_task,
|
||||
)
|
||||
return scoped_session
|
||||
|
||||
async def dispose_all(self):
|
||||
for engine in self.__engines:
|
||||
await engine.dispose()
|
||||
|
||||
# ---- 세션 lifecycle -------------------------------------------------
|
||||
async def start_session(self, db_type: int, db_wr_type: int) -> AsyncSession:
|
||||
if db_wr_type == DBWRType.DB_WRITE.value:
|
||||
return self.__write_session[db_type]()
|
||||
return self.__read_session[db_type]()
|
||||
|
||||
async def end_session(self, db_type: int, db_wr_type: int):
|
||||
if db_wr_type == DBWRType.DB_WRITE.value:
|
||||
await self.__write_session[db_type].remove()
|
||||
else:
|
||||
await self.__read_session[db_type].remove()
|
||||
|
||||
# ---- 저수준 DB 연산 (crud 에서 호출) --------------------------------
|
||||
async def run(self, db: AsyncSession, err_msg="DB Run Failed", raise_error=True) -> ErrorType:
|
||||
try:
|
||||
await db.commit()
|
||||
return ErrorType.SUCCESS
|
||||
except IntegrityError as ex:
|
||||
await db.rollback()
|
||||
LOG.e_no_callstack(f"duplicated. {ex}")
|
||||
return ErrorType.DB_ALREADY_SAME_KEY
|
||||
except Exception as ex:
|
||||
await db.rollback()
|
||||
err_type = ErrorType.DB_RUN_FAILED
|
||||
LOG.e_no_callstack(f"[{err_type.name}] {err_msg=}, {ex=}")
|
||||
if raise_error:
|
||||
raise RuntimeError(err_type.name, err_msg)
|
||||
return err_type
|
||||
|
||||
async def insert(self, db: AsyncSession, obj, err_msg="DB Failed", raise_error=True) -> ErrorType:
|
||||
try:
|
||||
if isinstance(obj, MAIN_BASE):
|
||||
db.add(obj)
|
||||
elif isinstance(obj, list):
|
||||
db.add_all(obj)
|
||||
else:
|
||||
raise RuntimeError("DO NOT USE QUERY IN DBJOB")
|
||||
return ErrorType.SUCCESS
|
||||
except Exception as ex:
|
||||
await db.rollback()
|
||||
err_type = ErrorType.DB_RUN_FAILED
|
||||
LOG.e_no_callstack(f"[{err_type.name}] {err_msg=}, {ex=}")
|
||||
if raise_error:
|
||||
raise RuntimeError(err_type.name, err_msg)
|
||||
return err_type
|
||||
|
||||
async def add(self, db: AsyncSession, query, err_msg="DB Operation Failed", raise_error=True) -> ErrorType:
|
||||
"""update/delete 등 비-select 쿼리 실행."""
|
||||
try:
|
||||
if hasattr(query, "column_descriptions"):
|
||||
raise RuntimeError("DO NOT USE SELECT QUERY IN DBJOB")
|
||||
await db.execute(query, execution_options=immutabledict({"synchronize_session": "fetch"}))
|
||||
return ErrorType.SUCCESS
|
||||
except IntegrityError as ex:
|
||||
await db.rollback()
|
||||
err_type = ErrorType.DB_ALREADY_SAME_KEY
|
||||
LOG.e_no_callstack(f"[{err_type.name}] {err_msg=}, {ex=}")
|
||||
return err_type
|
||||
except Exception as ex:
|
||||
await db.rollback()
|
||||
err_type = ErrorType.DB_RUN_FAILED
|
||||
LOG.e_no_callstack(f"[{err_type.name}] {err_msg=}, {ex=}")
|
||||
if raise_error:
|
||||
raise RuntimeError(err_type.name, err_msg)
|
||||
return err_type
|
||||
|
||||
async def execute(self, db: AsyncSession, query, err_msg="DB Query Execution Failed", raise_error=True) -> tuple[ErrorType, list]:
|
||||
"""select 쿼리 실행 후 결과 리스트 반환."""
|
||||
try:
|
||||
if not hasattr(query, "column_descriptions"):
|
||||
raise RuntimeError("DO NOT USE NON-SELECT QUERY IN DBJOB")
|
||||
res = await db.execute(query, execution_options=immutabledict({"synchronize_session": "fetch"}))
|
||||
return ErrorType.SUCCESS, res.scalars().fetchall() if 1 == len(query.column_descriptions) else res.all()
|
||||
except Exception as ex:
|
||||
err_type = ErrorType.DB_RUN_FAILED
|
||||
LOG.e_no_callstack(f"[{err_type.name}] {err_msg=}, {ex=}")
|
||||
if raise_error:
|
||||
raise RuntimeError(err_type.name, err_msg)
|
||||
return err_type, []
|
||||
|
||||
# ---- 람다 실행 진입점 (service 에서 호출) ---------------------------
|
||||
async def execute_lambda(self, db_type: int, db_wr_type: int, func):
|
||||
"""단일 쿼리 호출. func(session) 한 개를 실행하고 결과를 그대로 반환."""
|
||||
s = await self.start_session(db_type, db_wr_type)
|
||||
try:
|
||||
return await func(s)
|
||||
finally:
|
||||
await self.end_session(db_type, db_wr_type)
|
||||
|
||||
async def execute_lambda_run(self, db_type_list: list[int], func_list: list):
|
||||
"""동일 DB 의 변경 쿼리 여러 개를 한 트랜잭션으로 실행 후 commit.
|
||||
하나라도 SUCCESS 가 아니면 즉시 중단(rollback)된다.
|
||||
"""
|
||||
temp_list = list(set(db_type_list))
|
||||
if len(temp_list) != 1:
|
||||
return ErrorType.DB_INVALID_TYPE
|
||||
|
||||
db_type = temp_list[0]
|
||||
s = await self.start_session(db_type, DBWRType.DB_WRITE.value)
|
||||
try:
|
||||
for func in func_list:
|
||||
err_type = await func(s)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
return err_type
|
||||
return await self.run(s)
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED
|
||||
finally:
|
||||
await self.end_session(db_type, DBWRType.DB_WRITE.value)
|
||||
|
||||
|
||||
DB_SESSION_MNG = DBSessionManager()
|
||||
Whitespace-only changes.
@@ -0,0 +1,144 @@
|
||||
from sqlalchemy.orm import declarative_base
|
||||
from sqlalchemy import (
|
||||
BigInteger,
|
||||
Boolean,
|
||||
Column,
|
||||
DateTime,
|
||||
Integer,
|
||||
Numeric,
|
||||
SmallInteger,
|
||||
String,
|
||||
Float,
|
||||
)
|
||||
from sqlalchemy.dialects.postgresql import JSONB, UUID
|
||||
from sqlalchemy.sql import text
|
||||
|
||||
from common.enums import DBType
|
||||
|
||||
# 모든 ORM 모델의 베이스. insert 시 isinstance 체크에도 사용된다. (backend 와 동일 패턴)
|
||||
#
|
||||
# agent 는 negosium_db 를 backend 와 공유한다.
|
||||
# - 기존 스키마(company/card/negotiation 등)는 postgres-init/01-schema.sql 이 소유 → 읽기/쓰기만.
|
||||
# - RL 학습 자산은 신설 `learning` 스키마(postgres-init/02-learning-schema.sql)에 둔다.
|
||||
MAIN_BASE = declarative_base()
|
||||
|
||||
LEARNING_SCHEMA = "learning"
|
||||
|
||||
# 공유 베이스 정책의 예약 테넌트 키 (company_id 컬럼에 저장). company uuid 와 혼용되므로 VARCHAR.
|
||||
BASE_COMPANY_ID = "_base"
|
||||
|
||||
|
||||
class _DBTypeMixin:
|
||||
"""모델이 자신이 속한 논리 DB 를 알려준다 (람다 실행 시 DBType 으로 세션 선택)."""
|
||||
|
||||
@staticmethod
|
||||
def DBType():
|
||||
return DBType.MAIN.value
|
||||
|
||||
|
||||
# ============================================================
|
||||
# learning 스키마 ORM (02-learning-schema.sql 과 1:1)
|
||||
# 모든 테이블에 company_id(테넌트 키) — 논리 격리.
|
||||
# ============================================================
|
||||
class QTableVersion(_DBTypeMixin, MAIN_BASE):
|
||||
__tablename__ = "q_table_versions"
|
||||
__table_args__ = {"schema": LEARNING_SCHEMA}
|
||||
|
||||
version_id = Column(UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"))
|
||||
company_id = Column(String(64), nullable=False)
|
||||
version_name = Column(String(50), nullable=False)
|
||||
scope = Column(SmallInteger, nullable=False, default=2) # 1=base, 2=tenant
|
||||
base_version_id = Column(UUID(as_uuid=True), nullable=True)
|
||||
state_space_size = Column(Integer, nullable=False)
|
||||
action_space_size = Column(Integer, nullable=False)
|
||||
learning_rate = Column(Numeric(6, 4), nullable=False, default=0.1)
|
||||
discount_factor = Column(Numeric(6, 4), nullable=False, default=0.95)
|
||||
epochs = Column(Integer, nullable=False, default=0)
|
||||
is_active = Column(Boolean, nullable=False, default=False)
|
||||
created_at = Column(DateTime(timezone=True), server_default=text("now()"))
|
||||
deleted = Column(Boolean, nullable=False, default=False)
|
||||
|
||||
|
||||
class QValue(_DBTypeMixin, MAIN_BASE):
|
||||
__tablename__ = "q_values"
|
||||
__table_args__ = {"schema": LEARNING_SCHEMA}
|
||||
|
||||
id = Column(BigInteger, primary_key=True, autoincrement=True)
|
||||
company_id = Column(String(64), nullable=False)
|
||||
version_id = Column(UUID(as_uuid=True), nullable=False)
|
||||
state_index = Column(Integer, nullable=False)
|
||||
action_id = Column(Integer, nullable=False)
|
||||
q_value = Column(Float, nullable=False, default=0.0)
|
||||
|
||||
|
||||
class VisitCount(_DBTypeMixin, MAIN_BASE):
|
||||
__tablename__ = "visit_counts"
|
||||
__table_args__ = {"schema": LEARNING_SCHEMA}
|
||||
|
||||
id = Column(BigInteger, primary_key=True, autoincrement=True)
|
||||
company_id = Column(String(64), nullable=False)
|
||||
version_id = Column(UUID(as_uuid=True), nullable=False)
|
||||
state_index = Column(Integer, nullable=False)
|
||||
action_id = Column(Integer, nullable=False)
|
||||
count = Column(BigInteger, nullable=False, default=0)
|
||||
|
||||
|
||||
class ExperienceLog(_DBTypeMixin, MAIN_BASE):
|
||||
__tablename__ = "experience_logs"
|
||||
__table_args__ = {"schema": LEARNING_SCHEMA}
|
||||
|
||||
id = Column(BigInteger, primary_key=True, autoincrement=True)
|
||||
company_id = Column(String(64), nullable=False)
|
||||
transition_id = Column(UUID(as_uuid=True), nullable=False, server_default=text("gen_random_uuid()"))
|
||||
session_id = Column(UUID(as_uuid=True), nullable=True)
|
||||
state_index = Column(Integer, nullable=False)
|
||||
action_id = Column(Integer, nullable=False)
|
||||
card_id = Column(String(40), nullable=True)
|
||||
q_value_at_selection = Column(Float, nullable=True)
|
||||
reward = Column(Float, nullable=True)
|
||||
next_state_index = Column(Integer, nullable=True)
|
||||
done = Column(Boolean, nullable=False, default=False)
|
||||
snapshot = Column(JSONB, nullable=True)
|
||||
propensity = Column(Float, nullable=True) # OPE 필수
|
||||
turn = Column(Integer, nullable=True)
|
||||
available_actions = Column(JSONB, nullable=True)
|
||||
settled_price = Column(BigInteger, nullable=True)
|
||||
visit_count_at_selection = Column(BigInteger, nullable=True)
|
||||
total_visits_at_selection = Column(BigInteger, nullable=True)
|
||||
ucb_score_at_selection = Column(Float, nullable=True)
|
||||
is_new_quote = Column(Boolean, nullable=False, default=False)
|
||||
is_invalidated = Column(Boolean, nullable=False, default=False)
|
||||
invalidated_reason = Column(String(255), nullable=True)
|
||||
created_at = Column(DateTime(timezone=True), server_default=text("now()"))
|
||||
|
||||
|
||||
class TenantActionCard(_DBTypeMixin, MAIN_BASE):
|
||||
__tablename__ = "tenant_action_cards"
|
||||
__table_args__ = {"schema": LEARNING_SCHEMA}
|
||||
|
||||
id = Column(BigInteger, primary_key=True, autoincrement=True)
|
||||
company_id = Column(String(64), nullable=False)
|
||||
action_id = Column(Integer, nullable=False)
|
||||
card_id = Column(String(40), nullable=False)
|
||||
created_at = Column(DateTime(timezone=True), server_default=text("now()"))
|
||||
updated_at = Column(DateTime(timezone=True), server_default=text("now()"))
|
||||
deleted = Column(Boolean, nullable=False, default=False)
|
||||
|
||||
|
||||
class ChatSessionRow(_DBTypeMixin, MAIN_BASE):
|
||||
"""/chat 진행 상태 영속화 (P8-A). 채팅 메시지 로그가 아니라 step 머신 상태."""
|
||||
|
||||
__tablename__ = "chat_sessions"
|
||||
__table_args__ = {"schema": LEARNING_SCHEMA}
|
||||
|
||||
session_id = Column(UUID(as_uuid=True), primary_key=True)
|
||||
company_id = Column(String(64), nullable=False)
|
||||
tenant_id = Column(String(64), nullable=False)
|
||||
rq_type = Column(String(10), nullable=False, default="재협상")
|
||||
step = Column(String(40), nullable=False, default="시작")
|
||||
context = Column(JSONB, nullable=False, default=dict)
|
||||
used_action_ids = Column(JSONB, nullable=False, default=list)
|
||||
action_space_size = Column(Integer, nullable=False, default=0)
|
||||
ended = Column(Boolean, nullable=False, default=False)
|
||||
created_at = Column(DateTime(timezone=True), server_default=text("now()"))
|
||||
updated_at = Column(DateTime(timezone=True), server_default=text("now()"))
|
||||
Reference in new issue
Block a user