feat(anchoring): 앵커링 값 자동 조정 자립 모듈 신설 (v1.2)
schedules/anchoring — backend 를 import 하지 않는 독립 컨테이너 배치 서비스.
회사 × 협력사유형(1유통/2제조/3총판) × 가격구간(3,000원, 33,334칸)별 앵커링
값(정수 천분율)을 격주 토 00:00 KST 에 협상 성공률로 자동 조정한다.
- 판정 = "가격 흔적" 기준: last_offered_price 가 있는 종료 재협상만 표본,
DONE & bid ≤ 박제 앵커만 성공, 나머지(초과 합의·결렬·가격 쓰고 이탈) 실패.
앵커는 비노출(엔진 내부 체결 임계) — agent 무변경
- 저장 = anchoring.rate_adjustments 1개(append-only, consumed_session_ids 박제),
소비 경계 = sessions.anchoring_adjustment_id 마킹(멱등·이월). DDL 은 모듈
소유(schema.sql, sessions 3컬럼 ALTER 포함)
- 안정성: 조정 INSERT+마킹 한 트랜잭션 + rowcount 불일치 전체 롤백,
Redis TTL 7일 + 매주 조정 칸 re-SET, socket timeout 0.3s, DB 폴백,
가격 제시율 0% WARN, --once 수동 캐치업
- 정적 기본 테이블(전 구간 10‰, 상한 정확히 1억·초과분 마지막 인덱스 클램프)
기동 검증 실패 시 기동 중단
- 전체 async(SQLAlchemy+asyncpg, redis.asyncio) — negodata 가 reader 를 그대로
이식 가능(docs/인수인계.md). 최종 문서 docs/{개발용,기획용,워크플로우}.md
- 테스트 15종: 골든 벡터(§11) + DB 통합(멱등·이월·격리·rowcount 롤백)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
0ac37625fc
commit
f29e9723b0
29 files changed
+35833
No files matched your search
@@ -0,0 +1,139 @@
|
||||
"""통합 테스트 픽스처 — 실제 Postgres 필요(로컬 dev DB), 없으면 자동 스킵.
|
||||
|
||||
컨벤션(backend 와 동일): 전용 행을 시드하고 테스트 후 직접 정리한다.
|
||||
Redis 는 초기화하지 않는다 — 클라이언트 None → get None(DB 폴백)/set no-op 로 무Redis 실행.
|
||||
"""
|
||||
import asyncio
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
from sqlalchemy import text
|
||||
|
||||
from anchoring import db as adb
|
||||
from anchoring.config import load_config
|
||||
|
||||
CFG = load_config()
|
||||
_SCHEMA_SQL = Path(__file__).resolve().parents[1] / "schema.sql"
|
||||
|
||||
|
||||
def _db_available() -> bool:
|
||||
import asyncpg
|
||||
|
||||
async def _check():
|
||||
conn = await asyncpg.connect(
|
||||
host=CFG.db.host, port=CFG.db.port, user=CFG.db.user,
|
||||
password=CFG.db.password, database=CFG.db.name, timeout=2,
|
||||
)
|
||||
await conn.close()
|
||||
|
||||
try:
|
||||
asyncio.run(_check())
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
DB_OK = _db_available()
|
||||
requires_db = pytest.mark.skipif(not DB_OK, reason="로컬 Postgres(negosium_db) 미가용 — 통합 테스트 스킵")
|
||||
|
||||
|
||||
def _schema_statements() -> list[str]:
|
||||
"""schema.sql 에서 psql 메타(\\connect)·주석을 제거하고 문장 단위로 분리."""
|
||||
lines = [
|
||||
line for line in _SCHEMA_SQL.read_text().splitlines()
|
||||
if not line.startswith("\\") and not line.strip().startswith("--")
|
||||
]
|
||||
return [s.strip() for s in "\n".join(lines).split(";") if s.strip()]
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def db_ready():
|
||||
"""테스트별 엔진(이벤트 루프 수명 일치) + 스키마 멱등 적용."""
|
||||
adb.init_engine(CFG)
|
||||
async with adb.session_scope() as s:
|
||||
for stmt in _schema_statements():
|
||||
await s.execute(text(stmt))
|
||||
yield
|
||||
await adb.dispose_engine()
|
||||
|
||||
|
||||
class Seeder:
|
||||
"""전용 시드 생성 + 정리. 한 인스턴스 = 한 회사(테넌트)."""
|
||||
|
||||
def __init__(self):
|
||||
self.company_id = uuid.uuid4()
|
||||
self.user_id = uuid.uuid4()
|
||||
self.item_id = uuid.uuid4()
|
||||
self.quotation_ids: list = []
|
||||
self._item_created = False
|
||||
|
||||
async def _ensure_item(self, db):
|
||||
if self._item_created:
|
||||
return
|
||||
await db.execute(text(
|
||||
"INSERT INTO partner.items (item_id, company_id, user_id, name) "
|
||||
"VALUES (:iid, :cid, :uid, 'anchoring-it-test')"
|
||||
), {"iid": self.item_id, "cid": self.company_id, "uid": self.user_id})
|
||||
self._item_created = True
|
||||
|
||||
async def seed_session(
|
||||
self, db, *,
|
||||
supplier_type=1, target_price=30_000, anchor_price=29_700, rate=10,
|
||||
status=3, bid_price=None, last_offered_price=..., qt_type=1,
|
||||
):
|
||||
"""종료 재협상 세션 1건 시드. 반환: session_id.
|
||||
|
||||
last_offered_price 기본값은 bid_price(가격 흔적 = 투찰가). None 을 명시하면 가격 흔적 없는 세션.
|
||||
"""
|
||||
if last_offered_price is ...:
|
||||
last_offered_price = bid_price
|
||||
await self._ensure_item(db)
|
||||
qt_id = uuid.uuid4()
|
||||
self.quotation_ids.append(qt_id)
|
||||
await db.execute(text(
|
||||
"INSERT INTO quotation.quotations "
|
||||
"(qt_id, user_id, qt_setting_id, version_id, name, number, type, round, status, "
|
||||
" start_time, end_time, supplier_type) "
|
||||
"VALUES (:qid, :uid, :sid, :vid, 'anchoring-it-test', :num, :qtype, 1, 3, now(), now(), :stype)"
|
||||
), {
|
||||
"qid": qt_id, "uid": self.user_id, "sid": uuid.uuid4(), "vid": uuid.uuid4(),
|
||||
"num": f"AT{uuid.uuid4().hex[:12]}", "qtype": qt_type, "stype": supplier_type,
|
||||
})
|
||||
session_id = uuid.uuid4()
|
||||
await db.execute(text(
|
||||
"INSERT INTO negotiation.sessions "
|
||||
"(session_id, quotation_id, item_id, supplier_id, qt_number, qt_round, qt_type, "
|
||||
" target_price, target_anchoring_price, anchor_rate_permille, last_offered_price, "
|
||||
" status, bid_price, end_time) "
|
||||
"VALUES (:sid, :qid, :iid, :supid, 'AT-N', 1, :qtype, :tp, :ap, :rate, :lop, :status, :bid, now())"
|
||||
), {
|
||||
"sid": session_id, "qid": qt_id, "iid": self.item_id, "supid": uuid.uuid4(),
|
||||
"qtype": qt_type, "tp": target_price, "ap": anchor_price, "rate": rate,
|
||||
"lop": last_offered_price, "status": status, "bid": bid_price,
|
||||
})
|
||||
return session_id
|
||||
|
||||
async def cleanup(self, db):
|
||||
await db.execute(text(
|
||||
"DELETE FROM anchoring.rate_adjustments WHERE company_id = :cid"
|
||||
), {"cid": self.company_id})
|
||||
if self.quotation_ids:
|
||||
await db.execute(
|
||||
text("DELETE FROM negotiation.sessions WHERE quotation_id = ANY(:qids)"),
|
||||
{"qids": self.quotation_ids},
|
||||
)
|
||||
await db.execute(
|
||||
text("DELETE FROM quotation.quotations WHERE qt_id = ANY(:qids)"),
|
||||
{"qids": self.quotation_ids},
|
||||
)
|
||||
await db.execute(text("DELETE FROM partner.items WHERE item_id = :iid"), {"iid": self.item_id})
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def seeder(db_ready):
|
||||
s = Seeder()
|
||||
yield s
|
||||
async with adb.session_scope() as db:
|
||||
await s.cleanup(db)
|
||||
@@ -0,0 +1,154 @@
|
||||
"""배치 통합 테스트 (스펙 §11.5 — 실제 Postgres, Redis 없음(무Redis 폴백 경로)).
|
||||
|
||||
실행: cd schedules/anchoring && PYTHONPATH=src .venv/bin/python -m pytest tests/test_batch.py -q
|
||||
"""
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import select, text
|
||||
|
||||
from anchoring import db as adb
|
||||
from anchoring.batch import MarkingConflictError, _evaluate_cell, run_evaluation_batch
|
||||
from anchoring.models import RateAdjustment, Session
|
||||
from anchoring.reader import get_anchor_rate
|
||||
from conftest import requires_db
|
||||
|
||||
pytestmark = requires_db
|
||||
|
||||
# 시드 기본값: target 30,000 / rate 10‰ / anchor 29,700 → bracket = 30000//3000 = 10
|
||||
BRACKET = 10
|
||||
SUCCESS_BID = 29_000 # ≤ anchor → BID_SUCCESS
|
||||
FAIL_BID = 29_999 # > anchor → BID_FAIL
|
||||
|
||||
|
||||
async def _adjustments(db, seeder):
|
||||
stmt = (
|
||||
select(RateAdjustment)
|
||||
.where(RateAdjustment.company_id == seeder.company_id)
|
||||
.order_by(RateAdjustment.id)
|
||||
)
|
||||
return (await db.execute(stmt)).scalars().all()
|
||||
|
||||
|
||||
async def _marks(db, session_ids):
|
||||
stmt = select(Session.session_id, Session.anchoring_adjustment_id).where(Session.session_id.in_(session_ids))
|
||||
return dict((await db.execute(stmt)).all())
|
||||
|
||||
|
||||
async def _seed_mixed(db, seeder, success: int, fail: int, **kw):
|
||||
ids = []
|
||||
for _ in range(success):
|
||||
ids.append(await seeder.seed_session(db, bid_price=SUCCESS_BID, **kw))
|
||||
for _ in range(fail):
|
||||
ids.append(await seeder.seed_session(db, bid_price=FAIL_BID, **kw))
|
||||
return ids
|
||||
|
||||
|
||||
# ── §11.5: 13건 전량 평가 + 멱등 (실패 3종 혼합) ──────────
|
||||
async def test_full_cycle_and_idempotency(seeder):
|
||||
async with adb.session_scope() as db:
|
||||
ids = await _seed_mixed(db, seeder, success=8, fail=2) # DONE 인데 앵커 초과(와일드카드 상단 등)
|
||||
for _ in range(2): # 가격 쓰고 결렬(REJECTED) = 실패
|
||||
ids.append(await seeder.seed_session(db, status=5, bid_price=None, last_offered_price=FAIL_BID))
|
||||
# 가격 쓰고 이탈 → 견적 마감 시 일괄 NOT_PARTICIPATED = 실패 (중간 이탈 시나리오)
|
||||
ids.append(await seeder.seed_session(db, status=4, bid_price=None, last_offered_price=FAIL_BID))
|
||||
# 합계 13건, 성공 8 → r≈0.615 → +20
|
||||
|
||||
await run_evaluation_batch(force=True)
|
||||
|
||||
async with adb.session_scope() as db:
|
||||
adjustments = await _adjustments(db, seeder)
|
||||
assert len(adjustments) == 1
|
||||
adj = adjustments[0]
|
||||
assert (adj.nego_count, adj.success_count) == (13, 8)
|
||||
assert (adj.anchor_rate_before, adj.anchor_rate_after) == (10, 30)
|
||||
assert sorted(adj.consumed_session_ids) == sorted(str(i) for i in ids)
|
||||
marks = await _marks(db, ids)
|
||||
assert all(v == adj.id for v in marks.values()) # 13건 모두 소비 마킹
|
||||
|
||||
# 재실행 — 마킹 멱등: 우리 칸 조정은 그대로 1건
|
||||
await run_evaluation_batch(force=True)
|
||||
async with adb.session_scope() as db:
|
||||
assert len(await _adjustments(db, seeder)) == 1
|
||||
|
||||
|
||||
# ── §11.5: 이월(7건 스킵 → 누적 13건 단일 평가) ──────────
|
||||
async def test_carryover(seeder):
|
||||
async with adb.session_scope() as db:
|
||||
first = await _seed_mixed(db, seeder, success=5, fail=2) # 7건 < 10
|
||||
|
||||
await run_evaluation_batch(force=True)
|
||||
async with adb.session_scope() as db:
|
||||
assert await _adjustments(db, seeder) == []
|
||||
marks = await _marks(db, first)
|
||||
assert all(v is None for v in marks.values()) # 마킹 없음 = 이월
|
||||
|
||||
second = await _seed_mixed(db, seeder, success=3, fail=3) # 누적 13건 (8S/5F)
|
||||
|
||||
await run_evaluation_batch(force=True)
|
||||
async with adb.session_scope() as db:
|
||||
adjustments = await _adjustments(db, seeder)
|
||||
assert len(adjustments) == 1
|
||||
assert adjustments[0].nego_count == 13 # 4주치 전량 1회 평가
|
||||
assert adjustments[0].anchor_rate_after == 30
|
||||
marks = await _marks(db, first + second)
|
||||
assert all(v == adjustments[0].id for v in marks.values())
|
||||
|
||||
|
||||
# ── §11.5: 회사 격리 + 현재값 조회(무Redis DB 폴백) + δ 유형 차원 ──
|
||||
async def test_company_isolation_and_reader(seeder):
|
||||
async with adb.session_scope() as db:
|
||||
await _seed_mixed(db, seeder, success=10, fail=0, supplier_type=1) # 유통 → +20
|
||||
await _seed_mixed(db, seeder, success=10, fail=0, supplier_type=2) # 제조 → +10 (δ 스왑 가드)
|
||||
|
||||
await run_evaluation_batch(force=True)
|
||||
|
||||
other_company = uuid.uuid4()
|
||||
async with adb.session_scope() as db:
|
||||
adjustments = await _adjustments(db, seeder)
|
||||
by_type = {a.supplier_type: a.anchor_rate_after for a in adjustments}
|
||||
assert by_type == {1: 30, 2: 20}
|
||||
# 조정된 칸은 새 rate, 타사 같은 (유형,구간) 칸은 정적 테이블 시작값
|
||||
assert await get_anchor_rate(db, seeder.company_id, 1, BRACKET) == 30
|
||||
assert await get_anchor_rate(db, other_company, 1, BRACKET) == 10
|
||||
|
||||
|
||||
# ── §11.5: EXCLUDED 마킹 0 + 유효 n<10 이월 + supplier_type 미지정 ──
|
||||
async def test_excluded_and_unsampleable(seeder):
|
||||
async with adb.session_scope() as db:
|
||||
# 가격 흔적 없는 종료(무가격 결렬·미참여) → EXCLUDED
|
||||
excluded = [await seeder.seed_session(db, status=5, last_offered_price=None) for _ in range(8)]
|
||||
excluded += [await seeder.seed_session(db, status=4, last_offered_price=None) for _ in range(7)]
|
||||
valid = await _seed_mixed(db, seeder, success=5, fail=0) # 유효 5 < 10
|
||||
untyped = [await seeder.seed_session(db, supplier_type=0, bid_price=SUCCESS_BID)] # 칸 구성 불가
|
||||
|
||||
await run_evaluation_batch(force=True)
|
||||
|
||||
async with adb.session_scope() as db:
|
||||
assert await _adjustments(db, seeder) == [] # 유효 5 < 10 → 평가 없음
|
||||
marks = await _marks(db, excluded + untyped)
|
||||
assert all(v == 0 for v in marks.values()) # 제외 확정 마킹(재스캔 방지)
|
||||
marks = await _marks(db, valid)
|
||||
assert all(v is None for v in marks.values()) # 유효 표본은 이월
|
||||
|
||||
|
||||
# ── 개정 1: 마킹 rowcount ≠ n → 조정 INSERT 포함 전체 롤백 ──
|
||||
async def test_marking_conflict_rolls_back(seeder):
|
||||
async with adb.session_scope() as db:
|
||||
ids = await _seed_mixed(db, seeder, success=10, fail=0)
|
||||
# 경합 시뮬레이션: 1건을 다른 실행이 먼저 소비한 상태로 만든다
|
||||
await db.execute(text(
|
||||
"UPDATE negotiation.sessions SET anchoring_adjustment_id = 999999 WHERE session_id = :sid"
|
||||
), {"sid": ids[0]})
|
||||
|
||||
samples = [(sid, 1) for sid in ids] # 10건 전부 BID_SUCCESS 로 평가 시도
|
||||
try:
|
||||
await _evaluate_cell(seeder.company_id, 1, BRACKET, samples)
|
||||
raised = False
|
||||
except MarkingConflictError:
|
||||
raised = True
|
||||
assert raised
|
||||
|
||||
async with adb.session_scope() as db:
|
||||
assert await _adjustments(db, seeder) == [] # 롤백 — 이중 조정 없음
|
||||
marks = await _marks(db, ids[1:])
|
||||
assert all(v is None for v in marks.values()) # 나머지 9건 마킹도 롤백
|
||||
@@ -0,0 +1,118 @@
|
||||
"""순수 로직 골든 테스트 (스펙 §11.1~11.4, 외부 의존성 없음).
|
||||
|
||||
실행: cd schedules/anchoring && PYTHONPATH=src python -m pytest tests/test_core.py -q
|
||||
"""
|
||||
import pytest
|
||||
|
||||
from anchoring.base_table import BaseTableError, _validate, get_base_rate_permille, load_base_table
|
||||
from anchoring.constants import BRACKET_COUNT, AnchoringSampleType
|
||||
from anchoring.service import (
|
||||
calc_anchor_price,
|
||||
calc_bracket_index,
|
||||
evaluate_pending,
|
||||
get_current_rate,
|
||||
judge_sample_type,
|
||||
)
|
||||
|
||||
S = AnchoringSampleType.BID_SUCCESS.value
|
||||
F = AnchoringSampleType.BID_FAIL.value
|
||||
E = AnchoringSampleType.EXCLUDED.value
|
||||
|
||||
|
||||
# ── §11.1 앵커링가 계산 (내림 검증) ──────────────────────
|
||||
def test_calc_anchor_price_floor():
|
||||
assert calc_anchor_price(30_000, 200) == 24_000
|
||||
assert calc_anchor_price(26_706, 10) == 26_438 # 26,438.94 → 내림
|
||||
assert calc_anchor_price(29_999, 15) == 29_549 # 29,549.015 → 내림
|
||||
assert calc_anchor_price(0, 10) == 0
|
||||
|
||||
|
||||
# ── §11.2 구간 인덱스 (상한 클램프 포함) ──────────────────
|
||||
def test_bracket_index():
|
||||
assert calc_bracket_index(0) == 0
|
||||
assert calc_bracket_index(2_999) == 0
|
||||
assert calc_bracket_index(3_000) == 1 # 경계는 상위 구간
|
||||
assert calc_bracket_index(99_999_000) == 33_333 # 마지막 구간 진입
|
||||
assert calc_bracket_index(100_000_000) == 33_333
|
||||
assert calc_bracket_index(150_000_000) == 33_333 # 1억 초과 → 마지막 인덱스 클램프
|
||||
|
||||
|
||||
# ── §2 정적 테이블 로드·검증 ─────────────────────────────
|
||||
def test_base_table_load_and_values():
|
||||
load_base_table()
|
||||
assert get_base_rate_permille(0) == 10
|
||||
assert get_base_rate_permille(33_333) == 10
|
||||
|
||||
|
||||
def _rows(n: int = BRACKET_COUNT):
|
||||
return [
|
||||
{"idx": k, "upper_bound": min(k * 3000, 100_000_000), "anchoring_value": 0.01}
|
||||
for k in range(1, n + 1)
|
||||
]
|
||||
|
||||
|
||||
def test_base_table_validate_ok():
|
||||
rates = _validate(_rows())
|
||||
assert len(rates) == BRACKET_COUNT and set(rates) == {10}
|
||||
|
||||
|
||||
def test_base_table_validate_rejects_bad():
|
||||
with pytest.raises(BaseTableError): # 행 수 부족
|
||||
_validate(_rows()[:-1])
|
||||
rows = _rows()
|
||||
rows[5]["idx"] = 999 # idx 불연속
|
||||
with pytest.raises(BaseTableError):
|
||||
_validate(rows)
|
||||
rows = _rows()
|
||||
rows[-1]["upper_bound"] = 100_002_000 # 마지막 행은 정확히 1억이어야 함
|
||||
with pytest.raises(BaseTableError):
|
||||
_validate(rows)
|
||||
rows = _rows()
|
||||
rows[0]["anchoring_value"] = 0.5 # 값 범위(0.01~0.20) 밖
|
||||
with pytest.raises(BaseTableError):
|
||||
_validate(rows)
|
||||
|
||||
|
||||
# ── §11.3 누적 전량 평가 (유통 코드1, δ=20, before=10) ────
|
||||
def _pending(success: int, fail: int) -> list[int]:
|
||||
return [S] * success + [F] * fail
|
||||
|
||||
|
||||
def test_evaluate_pending_distribution():
|
||||
assert evaluate_pending(10, _pending(8, 5), 1) == 30 # 13건 r≈0.615 → +20
|
||||
assert evaluate_pending(10, _pending(7, 6), 1) == 10 # r≈0.538 → 유지
|
||||
assert evaluate_pending(10, _pending(3, 10), 1) == 10 # r≈0.231 → −20, 하한 clamp
|
||||
assert evaluate_pending(10, _pending(6, 4), 1) == 30 # r=0.60 정확히 → 경계 포함 +20
|
||||
assert evaluate_pending(10, _pending(3, 7), 1) == 10 # r=0.30 정확히 → 유지
|
||||
assert evaluate_pending(10, _pending(9, 0), 1) is None # n=9 → 평가 안 함(이월)
|
||||
|
||||
|
||||
def test_evaluate_pending_delta_swap_guard():
|
||||
"""δ 스왑 가드 (MUST): 코드 2=제조=±10, 3=총판=±15."""
|
||||
all_success = [S] * 10
|
||||
assert evaluate_pending(10, all_success, 2) == 20 # 제조 +10
|
||||
assert evaluate_pending(10, all_success, 3) == 25 # 총판 +15
|
||||
all_fail = [F] * 10
|
||||
assert evaluate_pending(100, all_fail, 2) == 90 # 제조 −10
|
||||
assert evaluate_pending(100, all_fail, 3) == 85 # 총판 −15
|
||||
|
||||
|
||||
def test_evaluate_pending_clamp_upper():
|
||||
assert evaluate_pending(200, _pending(9, 1), 1) == 200 # 상한 clamp — 조정 레코드는 호출측이 INSERT
|
||||
|
||||
|
||||
# ── §11.4 파생 판정 ("가격 흔적" 기준) ────────────────────
|
||||
def test_judge_sample_type():
|
||||
# judge_sample_type(is_done, bid_price, last_offered_price, anchor_price)
|
||||
assert judge_sample_type(True, 24_000, 24_000, 24_000) == S # 같아도 성공
|
||||
assert judge_sample_type(True, 24_001, 24_001, 24_000) == F # 앵커 초과 합의(와일드카드 등)
|
||||
assert judge_sample_type(False, None, 25_000, 24_000) == F # 가격 쓰고 결렬(REJECTED)
|
||||
assert judge_sample_type(False, None, 25_000, 24_000) == F # 가격 쓰고 이탈 → 일괄마감(NOT_PARTICIPATED)
|
||||
assert judge_sample_type(False, None, None, 24_000) == E # 가격 흔적 없음(미참여·무가격 이탈)
|
||||
assert judge_sample_type(True, 24_000, 24_000, None) == E # anchor 박제 없음 → 제외
|
||||
|
||||
|
||||
# ── §4.5 현재 값 조회 ────────────────────────────────────
|
||||
def test_get_current_rate():
|
||||
assert get_current_rate(70, 0) == 70
|
||||
assert get_current_rate(None, 0) == 10 # 이력 없으면 정적 테이블 시작값
|
||||
Reference in new issue
Block a user