feat(backend): 앵커링 박제값 소비·가격 흔적 기록으로 채팅 경로 전환

- _resolve_anchor_price: quotation_settings.anchoring_value 스칼라 계산(float)
  삭제 → 세션 생성 시 박제된 target_anchoring_price 를 그대로 사용(협상 중
  불변). 박제 없으면 무할인 폴백(anchor=target)+WARN — 미박제라 집계 자동 제외
- 가격 입력 턴마다 sessions.last_offered_price 를 봇 메시지와 같은 트랜잭션으로
  갱신(chat_crud.update_last_offered_price) — 앵커링 표본 판정의 "가격 흔적".
  가격 쓰고 중간 이탈 → 일괄마감된 세션도 실패 표본으로 측정 가능
- sessions 모델에 anchor_rate_permille / last_offered_price /
  anchoring_adjustment_id 3컬럼 추가 (DDL 은 schedules/anchoring/schema.sql 소유)
- e2e 테스트 2종(박제값 소비·제시가 기록 / NULL 폴백) — fake agent 더블

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
민헌andClaude Fable 5 committed 2026-07-02 16:29:46 +09:00
1 parent f29e9723b0
commit fd8a2425c5
4 files changed
+231 -21

No files matched your search

+18 -20
View File
@@ -18,7 +18,7 @@ from fastapi import Depends
from sqlalchemy import func, select
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import chats, items, quotation_settings, quotations, sessions, suppliers
from common.database.model.models import chats, items, quotations, sessions, suppliers
from common.enums import ChatSender, DBWRType, DeliveryType, ErrorType, QuotationStatus, SessionStatus
from common.logger import LOG
from common.models.gmodel import UserInfo
@@ -37,6 +37,7 @@ PRICE_FLOOR_RATIO = 0.3
PRICE_CEIL_RATIO = 1.7
class ChatService:
def __init__(
self,
@@ -365,6 +366,10 @@ class ChatService:
# 봇 메시지 + 종료 시 확정(성공=DONE+입찰가 / 실패=REJECTED+거부사유·제시가). 한 트랜잭션.
bot_msg = self._build_bot_chat(sess, seq=max_seq + 2, turn=turn, bot_chat_type=bot_chat_type, summary=summary)
funcs = [lambda s: self.chat_crud.insert_message(s, bot_msg)]
# 가격 입력 턴 → 마지막 제시가를 봇 메시지 저장과 같은 트랜잭션으로 갱신.
# 앵커링 표본 판정의 "가격 흔적"(가격을 써낸 협상만 집계 — 중간 이탈해도 실패로 측정 가능).
if price is not None:
funcs.append(lambda s: self.chat_crud.update_last_offered_price(s, sess.session_id, price))
new_status = sess.status
if turn.chat_end:
if turn.outcome == "success":
@@ -414,8 +419,7 @@ class ChatService:
LOG.w(f"[chat] tenant_id 해석 실패(item.company_id 없음) session_id={sess.session_id} — agent 400 위험")
rq_type = "재협상" if sess.qt_type == 1 else "재견적"
target_price = int(sess.target_price or 0)
# 앵커가: 견적설정(quotation_settings.anchoring_value) 비율로 계산 → agent NegotiationConfig.anchor_for 와 동일식.
# anchor = round(target * (1 - value)). 설정 조회 실패 시 1% 폴백(항상 양수 보장 — agent state ValueError 방지).
# 앵커가: 세션 생성 시 박제된 값(target_anchoring_price)을 그대로 사용 — 협상 중 불변.
anchor = await self._resolve_anchor_price(sess, target_price)
# 공급사 수: 같은 견적에 속한 세션 수(재협상=1, 재견적=N). agent partner 차원(single/multiple/none) 입력.
partner_count = await self._count_partners(sess)
@@ -430,25 +434,19 @@ class ChatService:
)
async def _resolve_anchor_price(self, sess, target_price: int) -> int:
"""견적설정 anchoring_value(비율) → anchor=round(target*(1-value)). 실패 시 target*0.99 폴백."""
"""세션에 박제된 앵커가(target_anchoring_price — negodata 가 생성 시 기록)를 그대로 사용.
박제값 사용이 정상 경로다: 협상 진행 중 앵커링 배치 조정·재기동이 껴도 앵커가 흔들리지 않는다
("제안 당시 값" 판정의 전제 — schedules/anchoring/docs/개발용.md §9.2). backend 는 앵커를 계산하지 않는다.
박제가 없으면(데이터 이상 — 사실상 발생하지 않음) 무할인 폴백 anchor=target + WARN.
이때 박제하지 않으므로 해당 세션은 앵커링 집계에서 자동 제외(EXCLUDED)된다 — 학습 무오염.
"""
if not target_price:
return 0
fallback = int(round(target_price * 0.99))
def _q(s):
stmt = (
select(quotation_settings.anchoring_value)
.join(quotations, quotations.qt_setting_id == quotation_settings.qt_setting_id)
.where(quotations.qt_id == sess.quotation_id, quotation_settings.deleted == False) # noqa: E712
.limit(1)
)
return DB_SESSION_MNG.execute(s, stmt)
err_type, rows = await DB_SESSION_MNG.execute_lambda(quotation_settings.DBType(), DBWRType.DB_READ.value, _q)
if err_type != ErrorType.SUCCESS or not rows or rows[0] is None:
LOG.w(f"[chat] anchoring_value 조회 실패 session_id={sess.session_id} — anchor=target*0.99 폴백")
return fallback
return int(round(target_price * (1.0 - float(rows[0]))))
if sess.target_anchoring_price is not None:
return int(sess.target_anchoring_price)
LOG.w(f"[chat] 앵커가 박제 없음 session_id={sess.session_id} — 무할인 폴백(anchor=target), 집계 제외")
return target_price
async def _count_partners(self, sess) -> int:
"""같은 견적(quotation_id)에 속한 협상 세션 수 = 참여 공급사 수. 실패 시 1 폴백."""