feat(negodata): 앵커링 v1.2 적용 — 칸 rate 조회·정수 박제·재생성 앵커 상속 폐지
- common/anchoring 이식 패키지 신설: 원본(schedules/anchoring)에서 읽기 경로 발췌 (constants·base_table·service) + reader 이식판(Redis 미사용 — current_rates 뷰 단일 쿼리, 실패·무이력 시 정적 테이블 폴백으로 견적 생성 무중단) - _build_quotation: 목표가 산정과 앵커 산출 분리 — 칸(items.company_id × quotations.supplier_type × 가격구간) rate 로 tp*(1000-rate)//1000 정수 박제, anchor_rate_permille 동시 기록. quotation_settings.anchoring_value 계산 사용 중단 - 재생성(regenerate_next_round): target_price 만 상속, 앵커는 생성 시점 rate 재계산 (인수인계 규칙 1 — 상속 폐지) - sessions 모델 anchor_rate_permille 매핑, crud get_item_companies 신설 - 테스트 6종 신설(스키마 부재 폴백·칸별 조정 반영·유형 미지정·재생성 재계산· bracket 경계 골든 벡터) — 전체 스위트 50 통과 - negodata 담당자 승인 하 직접 적용. 6개월 압축 시뮬레이션(격주 배치 13회, 세션 522건)으로 박제→소비→재박제 루프·클램프·이월·이중소비 방지 검증 완료 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
c98e5fa7bb
commit
b362edf0d7
10 files changed
+529
-28
No files matched your search
@@ -0,0 +1,22 @@
|
||||
"""앵커링 v1.2 읽기 경로 이식 패키지.
|
||||
|
||||
원본: `schedules/anchoring/src/anchoring` (자립 모듈). 견적/세션 생성 시
|
||||
칸(회사 × 협력사유형 × 가격구간) rate 를 조회해 앵커링가를 정수 연산으로 박제하는 데
|
||||
필요한 부분만 이식했다 — 명세: `schedules/anchoring/docs/인수인계.md` §1.
|
||||
|
||||
값 조정(격주 배치)·표본 판정은 이식 대상이 아니다(schedules/anchoring 서비스 담당).
|
||||
상수·계산식을 고칠 일이 생기면 원본 모듈과 반드시 함께 고친다(단독 수정 금지).
|
||||
"""
|
||||
from common.anchoring.base_table import get_base_rate_permille, load_base_table
|
||||
from common.anchoring.constants import SAMPLEABLE_SUPPLIER_TYPES
|
||||
from common.anchoring.reader import fetch_current_rates
|
||||
from common.anchoring.service import calc_anchor_price, calc_bracket_index
|
||||
|
||||
__all__ = [
|
||||
"SAMPLEABLE_SUPPLIER_TYPES",
|
||||
"calc_anchor_price",
|
||||
"calc_bracket_index",
|
||||
"fetch_current_rates",
|
||||
"get_base_rate_permille",
|
||||
"load_base_table",
|
||||
]
|
||||
@@ -0,0 +1,59 @@
|
||||
"""정적 기본 테이블 — 칸 시작값의 유일한 소스. 원본: schedules/anchoring/src/anchoring/base_table.py
|
||||
|
||||
resources/anchoring_base.json(46행 사다리, 불변)을 최초 사용 시 메모리에 로드한다.
|
||||
DB 에 저장하지 않으며 런타임에 절대 수정하지 않는다. 검증 실패 시 예외(견적 생성 차단이 아니라
|
||||
잘못된 리소스 배포를 조기에 드러내기 위함 — 파일은 코드와 함께 배포되므로 정상 배포에선 실패하지 않는다).
|
||||
"""
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from common.anchoring.constants import BRACKET_COUNT, UPPER_BOUNDS
|
||||
|
||||
_RESOURCE = Path(__file__).parent / "resources" / "anchoring_base.json"
|
||||
|
||||
_rates: list[int] | None = None # bracket_index → 시작값(‰)
|
||||
|
||||
|
||||
class BaseTableError(RuntimeError):
|
||||
"""정적 테이블 로드/검증 실패."""
|
||||
|
||||
|
||||
def _validate(rows: list) -> list[int]:
|
||||
"""행 검증 후 천분율 정수 리스트로 변환. 실패 시 BaseTableError.
|
||||
|
||||
규약: 46행 · idx 1..46 연속 · upper_bound == 사다리(UPPER_BOUNDS) · 값 0.01~0.20.
|
||||
"""
|
||||
if not isinstance(rows, list) or len(rows) != BRACKET_COUNT:
|
||||
raise BaseTableError(f"정적 테이블 행 수 불일치: {len(rows) if isinstance(rows, list) else type(rows)} != {BRACKET_COUNT}")
|
||||
rates: list[int] = []
|
||||
for i, row in enumerate(rows):
|
||||
idx = row.get("idx")
|
||||
ub = row.get("upper_bound")
|
||||
av = row.get("anchoring_value")
|
||||
if idx != i + 1:
|
||||
raise BaseTableError(f"idx 불연속: 위치 {i} 의 idx={idx} (기대 {i + 1})")
|
||||
if ub != UPPER_BOUNDS[i]:
|
||||
raise BaseTableError(f"upper_bound 사다리 불일치: idx={idx} upper_bound={ub} (기대 {UPPER_BOUNDS[i]})")
|
||||
if not isinstance(av, (int, float)) or av != av or not (0.01 <= av <= 0.20):
|
||||
raise BaseTableError(f"anchoring_value 범위 밖: idx={idx} value={av}")
|
||||
rates.append(int(round(av * 1000)))
|
||||
return rates
|
||||
|
||||
|
||||
def load_base_table() -> None:
|
||||
"""리소스 파일 로드 + 검증. 최초 1회 호출(멱등)."""
|
||||
global _rates
|
||||
if _rates is not None:
|
||||
return
|
||||
try:
|
||||
rows = json.loads(_RESOURCE.read_text())
|
||||
except Exception as ex:
|
||||
raise BaseTableError(f"정적 테이블 파일 로드 실패: {_RESOURCE}: {ex}") from ex
|
||||
_rates = _validate(rows)
|
||||
|
||||
|
||||
def get_base_rate_permille(bracket_index: int) -> int:
|
||||
"""구간 인덱스 → 시작 앵커링 값(‰)."""
|
||||
if _rates is None:
|
||||
load_base_table()
|
||||
return _rates[bracket_index]
|
||||
@@ -0,0 +1,33 @@
|
||||
"""앵커링 도메인 상수 — 읽기 경로에 필요한 부분만 원본에서 발췌 이식.
|
||||
|
||||
원본: schedules/anchoring/src/anchoring/constants.py (규범: 같은 폴더 docs/개발용.md §3).
|
||||
조정폭(δ)·배치 주기 등 배치 전용 상수는 이식하지 않았다.
|
||||
상수 변경은 정책 재확정 사안 — 코드에서 임의 조정 금지, 변경 시 원본과 동시 반영.
|
||||
"""
|
||||
|
||||
# ── 앵커링 값(정수 천분율 ‰) ──────────────────────────────
|
||||
ANCHOR_RATE_MIN = 10 # 하한 1%
|
||||
ANCHOR_RATE_MAX = 200 # 상한 20%
|
||||
# 시작값은 상수가 아니라 정적 테이블(base_table)에서 로드 — 0.01/10 하드코딩 금지
|
||||
|
||||
# ── 가격구간 (자릿수 계단식 사다리 — 폭 = 구간 상한의 10% = 선행 자릿수 밴드) ──
|
||||
# 예: 1,000~1만 은 1,000원 폭(1천 원대·2천 원대…), 1만~10만 은 1만 폭(1만 원대·2만 원대…).
|
||||
# 최하단(0~1,000원)은 한 칸으로 통일. 1억 초과는 마지막 칸으로 클램프.
|
||||
PRICE_MAX = 100_000_000 # 정적 테이블 상한(1억)
|
||||
_DECADE_STARTS = (1_000, 10_000, 100_000, 1_000_000, 10_000_000)
|
||||
|
||||
|
||||
def _build_upper_bounds() -> tuple:
|
||||
bounds = [1_000] # idx 0: [0, 1,000) 통일 칸
|
||||
for start in _DECADE_STARTS: # 각 자릿수: 폭 = start (상한의 10%)
|
||||
bounds.extend(start + start * i for i in range(1, 10))
|
||||
return tuple(bounds) # 마지막 = 100,000,000
|
||||
|
||||
|
||||
UPPER_BOUNDS = _build_upper_bounds() # 46개 — 구간 = [이전 upper_bound, upper_bound) 좌폐우개
|
||||
BRACKET_COUNT = len(UPPER_BOUNDS) # 46
|
||||
BRACKET_INDEX_MAX = BRACKET_COUNT - 1 # 45
|
||||
|
||||
# 칸을 구성할 수 있는 협력사 유형 코드 — common.enums.SupplierType 의 유통(1)/제조(2)/총판(3).
|
||||
# 이 외(NONE=0/NULL)는 칸 해석 불가 → 정적 테이블 시작값 사용(배치 집계에서도 자동 제외).
|
||||
SAMPLEABLE_SUPPLIER_TYPES = (1, 2, 3)
|
||||
@@ -0,0 +1,55 @@
|
||||
"""현재 앵커링 값 조회(읽기 경로) — negodata 이식판.
|
||||
|
||||
원본 reader(schedules/anchoring)는 Redis 캐시를 먼저 보지만, 이식판은 DB 직조회 한 문장만 쓴다
|
||||
(2026-07-03 단순화 결정 — 조회가 견적 생성 시에만 일어나 캐시가 불필요, Redis 의존 제거).
|
||||
칸별 최신 조정 rate 는 모듈 소유 뷰 `anchoring.current_rates` 가 제공하고,
|
||||
조정 이력이 없는 칸은 결과에 없으므로 호출측이 정적 테이블 시작값으로 폴백한다.
|
||||
|
||||
견적 생성이 앵커 조회 때문에 실패해서는 안 된다(인수인계.md §1 규칙 6) — anchoring 스키마
|
||||
미적용 환경을 포함해 어떤 실패도 밖으로 던지지 않고 빈 결과(전량 정적 폴백) + WARN 으로 처리한다.
|
||||
"""
|
||||
from sqlalchemy import column, select, table
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from common.anchoring.constants import ANCHOR_RATE_MAX, ANCHOR_RATE_MIN, SAMPLEABLE_SUPPLIER_TYPES
|
||||
from common.logger import LOG
|
||||
|
||||
# 모듈 소유 DDL(schedules/anchoring/schema.sql)의 조회용 뷰 — negodata 는 ORM 모델 없이 읽기만 한다.
|
||||
_current_rates = table(
|
||||
"current_rates",
|
||||
column("company_id"),
|
||||
column("price_bracket_index"),
|
||||
column("anchor_rate_permille"),
|
||||
column("supplier_type"),
|
||||
schema="anchoring",
|
||||
)
|
||||
|
||||
|
||||
async def fetch_current_rates(db: AsyncSession, company_ids: list, supplier_type: int) -> dict:
|
||||
"""칸별 현재 앵커링 값 일괄 조회. {(company_id, bracket_index): rate‰} 반환.
|
||||
|
||||
supplier_type 은 견적 단위로 하나뿐이라 키에 넣지 않는다.
|
||||
조정 이력이 없는 칸은 결과에 없다(호출측 정적 폴백). 조회 실패 시 빈 dict."""
|
||||
if not company_ids or supplier_type not in SAMPLEABLE_SUPPLIER_TYPES:
|
||||
return {}
|
||||
try:
|
||||
stmt = select(
|
||||
_current_rates.c.company_id,
|
||||
_current_rates.c.price_bracket_index,
|
||||
_current_rates.c.anchor_rate_permille,
|
||||
).where(
|
||||
_current_rates.c.company_id.in_(company_ids),
|
||||
_current_rates.c.supplier_type == supplier_type,
|
||||
)
|
||||
rows = (await db.execute(stmt)).all()
|
||||
except Exception as ex:
|
||||
LOG.w(f"[앵커링] current_rates 조회 실패 — 전량 정적 테이블 폴백: {ex}")
|
||||
return {}
|
||||
|
||||
out = {}
|
||||
for company_id, bracket_index, rate in rows:
|
||||
if not ANCHOR_RATE_MIN <= rate <= ANCHOR_RATE_MAX: # 범위 밖 값은 오염 방어 — 버리고 정적 폴백
|
||||
LOG.w(f"[앵커링] rate 범위 밖 — 무시(정적 폴백): company={company_id} bracket={bracket_index} rate={rate}")
|
||||
continue
|
||||
out[(company_id, bracket_index)] = rate
|
||||
return out
|
||||
@@ -0,0 +1,48 @@
|
||||
[
|
||||
{ "idx": 1, "upper_bound": 1000, "anchoring_value": 0.01 },
|
||||
{ "idx": 2, "upper_bound": 2000, "anchoring_value": 0.01 },
|
||||
{ "idx": 3, "upper_bound": 3000, "anchoring_value": 0.01 },
|
||||
{ "idx": 4, "upper_bound": 4000, "anchoring_value": 0.01 },
|
||||
{ "idx": 5, "upper_bound": 5000, "anchoring_value": 0.01 },
|
||||
{ "idx": 6, "upper_bound": 6000, "anchoring_value": 0.01 },
|
||||
{ "idx": 7, "upper_bound": 7000, "anchoring_value": 0.01 },
|
||||
{ "idx": 8, "upper_bound": 8000, "anchoring_value": 0.01 },
|
||||
{ "idx": 9, "upper_bound": 9000, "anchoring_value": 0.01 },
|
||||
{ "idx": 10, "upper_bound": 10000, "anchoring_value": 0.01 },
|
||||
{ "idx": 11, "upper_bound": 20000, "anchoring_value": 0.01 },
|
||||
{ "idx": 12, "upper_bound": 30000, "anchoring_value": 0.01 },
|
||||
{ "idx": 13, "upper_bound": 40000, "anchoring_value": 0.01 },
|
||||
{ "idx": 14, "upper_bound": 50000, "anchoring_value": 0.01 },
|
||||
{ "idx": 15, "upper_bound": 60000, "anchoring_value": 0.01 },
|
||||
{ "idx": 16, "upper_bound": 70000, "anchoring_value": 0.01 },
|
||||
{ "idx": 17, "upper_bound": 80000, "anchoring_value": 0.01 },
|
||||
{ "idx": 18, "upper_bound": 90000, "anchoring_value": 0.01 },
|
||||
{ "idx": 19, "upper_bound": 100000, "anchoring_value": 0.01 },
|
||||
{ "idx": 20, "upper_bound": 200000, "anchoring_value": 0.01 },
|
||||
{ "idx": 21, "upper_bound": 300000, "anchoring_value": 0.01 },
|
||||
{ "idx": 22, "upper_bound": 400000, "anchoring_value": 0.01 },
|
||||
{ "idx": 23, "upper_bound": 500000, "anchoring_value": 0.01 },
|
||||
{ "idx": 24, "upper_bound": 600000, "anchoring_value": 0.01 },
|
||||
{ "idx": 25, "upper_bound": 700000, "anchoring_value": 0.01 },
|
||||
{ "idx": 26, "upper_bound": 800000, "anchoring_value": 0.01 },
|
||||
{ "idx": 27, "upper_bound": 900000, "anchoring_value": 0.01 },
|
||||
{ "idx": 28, "upper_bound": 1000000, "anchoring_value": 0.01 },
|
||||
{ "idx": 29, "upper_bound": 2000000, "anchoring_value": 0.01 },
|
||||
{ "idx": 30, "upper_bound": 3000000, "anchoring_value": 0.01 },
|
||||
{ "idx": 31, "upper_bound": 4000000, "anchoring_value": 0.01 },
|
||||
{ "idx": 32, "upper_bound": 5000000, "anchoring_value": 0.01 },
|
||||
{ "idx": 33, "upper_bound": 6000000, "anchoring_value": 0.01 },
|
||||
{ "idx": 34, "upper_bound": 7000000, "anchoring_value": 0.01 },
|
||||
{ "idx": 35, "upper_bound": 8000000, "anchoring_value": 0.01 },
|
||||
{ "idx": 36, "upper_bound": 9000000, "anchoring_value": 0.01 },
|
||||
{ "idx": 37, "upper_bound": 10000000, "anchoring_value": 0.01 },
|
||||
{ "idx": 38, "upper_bound": 20000000, "anchoring_value": 0.01 },
|
||||
{ "idx": 39, "upper_bound": 30000000, "anchoring_value": 0.01 },
|
||||
{ "idx": 40, "upper_bound": 40000000, "anchoring_value": 0.01 },
|
||||
{ "idx": 41, "upper_bound": 50000000, "anchoring_value": 0.01 },
|
||||
{ "idx": 42, "upper_bound": 60000000, "anchoring_value": 0.01 },
|
||||
{ "idx": 43, "upper_bound": 70000000, "anchoring_value": 0.01 },
|
||||
{ "idx": 44, "upper_bound": 80000000, "anchoring_value": 0.01 },
|
||||
{ "idx": 45, "upper_bound": 90000000, "anchoring_value": 0.01 },
|
||||
{ "idx": 46, "upper_bound": 100000000, "anchoring_value": 0.01 }
|
||||
]
|
||||
@@ -0,0 +1,21 @@
|
||||
"""순수 계산 함수 — DB 접근 없음. 원본: schedules/anchoring/src/anchoring/service.py 에서
|
||||
읽기 경로(칸 해석·앵커가 산출) 두 함수만 발췌 이식. 표본 판정·평가 함수는 배치 전용이라 제외.
|
||||
|
||||
모든 산술은 정수(천분율 ‰). float 금지 — 1원 단위 내림의 정확성 보장.
|
||||
"""
|
||||
from bisect import bisect_right
|
||||
|
||||
from common.anchoring.constants import BRACKET_INDEX_MAX, UPPER_BOUNDS
|
||||
|
||||
|
||||
def calc_bracket_index(target_price: int) -> int:
|
||||
"""목표가 → 가격구간 인덱스(0-기반). 자릿수 계단식 사다리.
|
||||
|
||||
좌폐우개 [이전 ub, ub): 가격이 upper_bound 와 정확히 같으면 다음 칸.
|
||||
1억 이상은 마지막 인덱스로 클램프. 정적 테이블 idx = 반환값 + 1"""
|
||||
return min(bisect_right(UPPER_BOUNDS, target_price), BRACKET_INDEX_MAX)
|
||||
|
||||
|
||||
def calc_anchor_price(target_price: int, rate_permille: int) -> int:
|
||||
"""앵커링가 = 목표가 × (1 − A), 1원 단위 내림. (정수 연산만 — float 곱셈 재도입 금지)"""
|
||||
return target_price * (1000 - rate_permille) // 1000
|
||||
@@ -245,7 +245,8 @@ class sessions(MainTableMixin, MAIN_BASE):
|
||||
qt_round = Column(Integer, nullable=False) # 견적 라운드 스냅샷
|
||||
qt_type = Column(SmallInteger, nullable=False) # QuotationType 스냅샷
|
||||
target_price = Column(BigInteger, nullable=False) # 목표가(원)
|
||||
target_anchoring_price = Column(BigInteger, nullable=True)
|
||||
target_anchoring_price = Column(BigInteger, nullable=True) # 앵커링가(원) — 생성 시 박제, 이후 수정 금지(앵커링 배치 판정 기준)
|
||||
anchor_rate_permille = Column(SmallInteger, nullable=True) # 제안 당시 앵커링 값(천분율‰) 박제 — 위와 동일 규칙. 나머지 앵커링 컬럼(last_offered_price 등)은 backend/배치 소유라 매핑 안 함
|
||||
status = Column(SmallInteger, nullable=False) # SessionStatus 코드
|
||||
bid_price = Column(BigInteger, nullable=True) # 입찰가(원)
|
||||
bid_at = Column(DateTime(timezone=True), nullable=True) # 입찰 시각
|
||||
|
||||
Reference in new issue
Block a user