Files
trex-core/docs/srs/Data/req-006_postgresql-slot-persistence.md
T
genichinandClaude Opus 4.8 d737467d70 perf(slots): BAT-040 — slots RPC DB-level status 필터 (REQ-002/006/073, issue #25)
REQ-002/006 change-req(CHG-20260612-01)→구현→confirm-req-implemented,
REQ-073 change-req(CHG-20260612-02, 관찰 계약 불변 Implemented 유지) 전체 delivery.

- repository.py/in_memory_repository.py: SlotRepository.list_slots(instance_key,
  status_filter=None) — status 값 집합 필터, None=전체(기존 호출자 불변).
- postgresql.py: list_slots DB-level WHERE status = ANY(%s) (full scan + Python
  필터 제거). 스키마/마이그레이션 변경 없음.
- messaging_handlers.py: _FILTER_STATUS 매핑으로 filter→status 집합 위임,
  watchdog 갱신용 holding 조회를 all/holding fetch 결과에서 재사용(2nd 커넥션 생략).
- 관찰 가능한 RPC 계약(REQ-073 AC-1~6) 불변 — 동작 보존 최적화.
- tests: in-memory status_filter 5종 + PG 게이트 1종. 439 passed (+5), ruff clean.

REQ-002·006 Approved→Implemented, REQ-073 Implemented 유지, BAT-040 release-candidate.
issue #25 close.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-12 19:27:51 +09:00

16 KiB
Raw Blame History

req-006: PostgreSQL SlotRepository 영속화 + 스키마

  • Status: Implemented
  • Type: Data
  • Priority: High
  • Owner: project maintainers

Intent

  • 코어가 daily_slot 을 durable 단일 writer 로 소유하도록 SlotRepository 의 PostgreSQL 구현과 스키마를 추가한다. dcy-001 부록 A 컬럼 계약을 영속화에서 실제로 충족시킨다.

Requirement

  • SlotRepository Protocol 의 psycopg 기반 PostgreSQL 구현을 추가하고, trex-core 소유의 신규 마이그레이션으로 daily_slot(부록 A 16컬럼)·daily_symbol_entries·slot_transition_log·intent_log 테이블을 생성한다. advisory lock 을 실제 pg_advisory_xact_lock 으로 구현한다. EXPECTED_SLOT_FIELDS ↔ daily_slot 실제 컬럼(information_schema) 드리프트 테스트를 동반한다.

Acceptance Criteria

  1. Given PostgreSQL 백엔드, When 마이그레이션 적용, Then daily_slot·daily_symbol_entries·slot_transition_log·intent_log 가 생성되고 daily_slot 컬럼이 부록 A(16컬럼)와 일치한다.
  2. Given PostgreSQL SlotRepository, When SlotService 를 이 repo 로 구동, Then 도메인 단위/통합테스트가 in-memory 와 동일하게 통과한다(전이/재진입+1/race 감지).
  3. Given 드리프트 테스트, When EXPECTED_SLOT_FIELDS ↔ information_schema 대조, Then 일치하고 컬럼 누락 시 실패한다(dcy-001 OQ-2 DB-side 검사 실현).
  4. Given 상태 변경, When transit_slot, Then pg_advisory_xact_lock 하 단일 트랜잭션으로 직렬화되고 lock 보유 중 외부 I/O 가 없다.
  5. (CHG-20260610-02, dcy-023/issue #22) Given 마이그레이션 013(DROP COLUMN IF EXISTS allocated_capital, 멱등) 적용, Then daily_slot 에 allocated_capital 컬럼이 없고 persistence flat 매핑(SELECT/UPDATE/행 복원)에서 해당 컬럼 참조가 제거되며, EXPECTED_SLOT_FIELDS ↔ information_schema 드리프트 테스트가 green 이다. 적용은 코드 배포와 동시(apply_migrations 자동, dcy-023 OQ-2), 비가역 drop 이므로 적용 전 백업 절차를 release 문서에 명시한다.
  6. (CHG-20260612-01, issue #25) Given PostgreSQL list_slots(instance_key, status_filter), When status_filter 가 status 값 집합이면, Then WHERE instance_key = %s AND status = ANY(%s) 로 DB 에서 직접 필터링해 해당 행만 fetch 하고(전 행 fetch + Python 필터 제거), None 이면 기존대로 WHERE instance_key = %s 전체를 반환한다. 반환 결과는 in-memory 구현과 동일하다.

Impacted Area

  • Docs: docs/data-model.md(테이블/계약), dcy-001 부록 A(기준)
  • Modules: trex_core/ 하위 persistence 어댑터(psycopg) + 마이그레이션 SQL; 도메인 패키지는 무의존 유지(NFR-1); (CHG-20260610-02) postgresql.py flat 매핑 allocated_capital 제거 + 013_drop_allocated_capital.sql; (CHG-20260612-01) postgresql.py list_slots DB-level status 필터(status = ANY(%s))
  • Tests: PostgreSQL repo 통합테스트 + 드리프트 테스트

Notes

  • 스키마는 부록 A 단일 기준, orbit-v2 DDL 참조(dcy-002 OQ-4). daily_slot_archive/prune 는 범위 밖.
  • NFR-1(도메인 순수성) 일부 흡수: psycopg 의존은 persistence 어댑터에만, 도메인 import 스윕 0 유지.
  • REQ-005(런타임) 선행 권장, REQ-007/008(API)의 단일 writer 근거.
  • 출처: dcy-002 FR-5.

Change Log

CHG-20260603-01

  • Date: 2026-06-03
  • Author: Justin Ko

Change Summary

  • dcy-002 FR-5 로부터 최초 생성(Proposed). NFR-1 일부 흡수.

Intent

  • PostgreSQL 영속화 + 스키마 + 드리프트 테스트 요구사항을 backlog 로 정규화.

Acceptance Criteria Delta

  • Added:
    • 마이그레이션/컬럼 일치, repo 구동 테스트, 드리프트 테스트, advisory lock 4개 기준
  • Updated:
    • 없음
  • Removed:
    • 없음

Impacted Area Delta

  • Docs:
    • docs/data-model.md, dcy-001 부록 A
  • Modules:
    • persistence 어댑터(psycopg) + 마이그레이션 SQL
  • Tests:
    • PostgreSQL repo 통합테스트 + 드리프트 테스트

Delivery Trace Delta

  • Batches:
    • none
  • Releases:
    • none

Revalidation Impact

  • Reverification Needed: no
  • Existing Implementation Invalidated: no
  • Status Recommendation: keep-current
  • Follow-up Action: confirm-req 후 batch 편성

Validation Plan

  • PostgreSQL 통합테스트(가능 시) + 드리프트 테스트로 검증.

CHG-20260603-02

  • Date: 2026-06-03
  • Author: Justin Ko

Change Summary

  • Status Proposed → Approved (confirm-req).

Intent

  • 승인 게이트(필수 필드·구체 AC·blocker 없음) 충족, source dcy-002(confirmed, handoff 승인)와 모순 없음 확인.

Acceptance Criteria Delta

  • Added:
    • 없음
  • Updated:
    • 없음
  • Removed:
    • 없음

Impacted Area Delta

  • Docs:
    • docs/srs/index.md (Register 상태 Approved)
  • Modules:
    • 없음
  • Tests:
    • 없음

Delivery Trace Delta

  • Batches:
    • none (batch 편성 전)
  • Releases:
    • none

Revalidation Impact

  • Reverification Needed: no
  • Existing Implementation Invalidated: no
  • Status Recommendation: keep-current
  • Follow-up Action: suggest-batch-reqs / draft-batch 로 delivery batch 편성

Validation Plan

  • 승인 후 batch planning 에서 본 REQ 의 Acceptance Criteria 를 검증 기준으로 사용.

CHG-20260603-03

  • Date: 2026-06-03
  • Author: Justin Ko

Change Summary

  • Status Approved → Implemented (confirm-req-implemented, 근거 batch BAT-002 release-candidate).

Intent

  • BAT-002 verification.md 의 acceptance mapping + evidence(pytest 74 pass / PG 통합 / 데몬 E2E)로 모든 AC 충족 → 구현 완료 동기화.

Acceptance Criteria Delta

  • Added:
    • 없음
  • Updated:
    • 없음
  • Removed:
    • 없음

Impacted Area Delta

  • Docs:
    • docs/srs/index.md (Register Implemented)
  • Modules:
    • 없음
  • Tests:
    • 없음

Delivery Trace Delta

  • Batches:
    • BAT-002 (release-candidate)
  • Releases:
    • none

Revalidation Impact

  • Reverification Needed: no
  • Existing Implementation Invalidated: no
  • Status Recommendation: keep-current
  • Follow-up Action: draft-release 로 release 편성

Validation Plan

  • BAT-002 verification evidence 재참조로 충분.

CHG-20260608-01

  • Date: 2026-06-08
  • Author: Justin Ko

Change Summary

  • (change-req, dcy-012) daily_slot.entry_price → limit_price 컬럼 rename 마이그레이션(006_rename_entry_price_to_limit_price.sql, idempotent DO-block) + persistence 매핑(_SLOT_COLUMNS/update_slot/_row_to_slot) 갱신. 순수 rename 으로 기존 행 데이터 보존(S-3). BAT-016 재구현·재검증 완료 → Implemented 유지.

Intent

  • 도메인 필드 rename(REQ-002)을 영속 스키마/매핑에 반영하면서 기존 데이터를 보존.

Acceptance Criteria Delta

  • Updated:
    • daily_slot 컬럼 entry_price → limit_price (마이그레이션 006, 데이터 보존). persistence read/write 매핑 동기화.

Impacted Area Delta

  • Modules: trex_core/adapters/persistence/postgresql.py, trex_core/adapters/persistence/sql/006_rename_entry_price_to_limit_price.sql(신규)
  • Tests: tests/adapters/persistence/test_migration_and_drift.py(컬럼 계약 = limit_price, 마이그레이션 idempotent)

Delivery Trace Delta

  • Batches: BAT-016
  • Releases: none

Revalidation Impact

  • Reverification Needed: yes (BAT-016 에서 완료)
  • Existing Implementation Invalidated: yes (entry_price 컬럼/매핑)
  • Status Recommendation: Implemented (change-req → BAT-016 재검증)
  • Follow-up Action: confirm-req-implemented(BAT-016).

Validation Plan

  • BAT-016: PG 게이트 마이그레이션 round-trip + 컬럼 계약(limit_price) + idempotency.

CHG-20260609-01

  • Date: 2026-06-09
  • Author: Justin Ko

Change Summary

  • (change-req, dcy-019/issue #18) 영속화 레이어에 slot-scoped entry_count 반영: 멱등 마이그레이션 008(ALTER TABLE daily_slot ADD COLUMN IF NOT EXISTS entry_count INTEGER NOT NULL DEFAULT 0), _SLOT_COLUMNS/update_slot/_row_to_slot flat 매핑 +entry_count, 신규 find_allocatable_slot(idle ∪ closed, ORDER BY entry_count ASC, updated_at ASC, slot_id ASC LIMIT 1) selector 추가(in-memory 동등 구현 포함). 동시성은 기존 advisory lock + 재시도 규약 보존(find 쿼리 FOR UPDATE 미사용 — find_idle_slot 와 동일). BAT-025 검증 완료 → Implemented 유지.

Intent

  • buy admission 의 후보 확장(idle∪closed)·공정 정렬을 영속 store 에서 결정적으로 지원하고, slot row 에 진입 횟수를 durable 하게 보존.

Acceptance Criteria Delta

  • Updated:
    • AC-1 컬럼 계약: daily_slot 에 entry_count 컬럼 추가(마이그레이션 008, additive·멱등). EXPECTED_SLOT_FIELDS ↔ information_schema 드리프트 가드가 자동 반영.
  • Added:
    • find_allocatable_slot(trading_date) 가 idle ∪ closed 후보를 entry_count → updated_at → slot_id 정렬로 1건 반환(없으면 None).

Impacted Area Delta

  • Modules: trex_core/adapters/persistence/sql/008_add_slot_entry_count.sql(신규), trex_core/adapters/persistence/postgresql.py(_SLOT_COLUMNS/update_slot/_row_to_slot/find_allocatable_slot), trex_core/domain/slot/repository.py·in_memory_repository.py(selector 포트 + 동등 구현)
  • Tests: tests/adapters/persistence/test_migration_and_drift.py(자동 반영), tests/domain/slot/test_slot_entry_count.py(selector 정렬)

Delivery Trace Delta

  • Batches: BAT-025
  • Releases: none

Revalidation Impact

  • Reverification Needed: yes (BAT-025 에서 완료)
  • Existing Implementation Invalidated: no (additive 컬럼·신규 selector — 기존 find_idle_slot/round-trip 보존)
  • Status Recommendation: Implemented (change-req → BAT-025 재검증)
  • Follow-up Action: confirm-req-implemented(BAT-025).

Validation Plan

  • BAT-025: unit (in-memory selector 정렬·reallocation) green; 마이그레이션 008 round-trip + 드리프트 가드는 test DSN 환경에서 자동 검증(라이브 runtime DSN 미사용 — 파괴적 truncate 회피).

CHG-20260610-01

  • Date: 2026-06-10
  • Author: Justin Ko

Change Summary

  • (change-req, dcy-020) daily_slot persistence 가 영구 슬롯 스키마로 재정의 예정 — REQ-056(portfolio_id 영구키·instance_key·UNIQUE(instance_key, portfolio_id)·trading_date/entry_count 제거·retired_at)·REQ-062(qty 미러)가 대체. find_allocatable_slot 등 풀 모델 쿼리 폐기. 현재 코드 불변이라 Implemented 유지(keep-current), dcy-020 스키마 배치 + cutover(REQ-064)에서 확정.

Intent

  • 영구 슬롯 persistence 전환 추적성 forward-link.

Acceptance Criteria Delta

  • Updated: 없음(dcy-020 delivery 배치에서 스키마 AC 재정의)

Impacted Area Delta

  • Docs: dcy-020, REQ-056/062/064
  • Modules: (예정) adapters/persistence/postgresql.py·sql/ 재설계
  • Tests: (예정) test_migration_and_drift 재작성

Delivery Trace Delta

  • Batches: (예정) dcy-020 스키마/cutover 배치
  • Releases: none

Revalidation Impact

  • Reverification Needed: no (현 시점)
  • Existing Implementation Invalidated: no (코드 불변)
  • Status Recommendation: keep-current
  • Follow-up Action: dcy-020 스키마/cutover 배치에서 재정의 + status 전환.

Validation Plan

  • dcy-020 스키마/cutover 배치 verification 으로 대체.

CHG-20260610-02

  • Date: 2026-06-10
  • Author: Justin Ko

Change Summary

  • (change-req, dcy-023/issue #22) daily_slot.allocated_capital 컬럼 제거 — 신규 마이그레이션 013_drop_allocated_capital.sql(DROP COLUMN IF EXISTS, 멱등) + persistence flat 매핑(SELECT 컬럼 목록/UPDATE 절/행 복원)에서 해당 컬럼 참조 삭제. 코드 배포와 동시 적용(dcy-023 OQ-2 운영자 결정), 비가역 drop — BAT-030 의 011 선례 준용(사전 백업 + 롤백 절차 release 문서 명시). AC-5 추가, Implemented→Approved(재구현 대기).

Intent

  • 소비처 없는 죽은 컬럼을 영속 계약에서 제거해 EXPECTED_SLOT_FIELDS ↔ DB 계약을 실사용 필드로 정렬.

Acceptance Criteria Delta

  • Added:
    • AC-5: 마이그레이션 013 적용 후 allocated_capital 컬럼 부재 + flat 매핑 참조 제거 + 드리프트 테스트 green + 동시 적용·백업 절차.
  • Updated:
    • 없음
  • Removed:
    • 없음

Impacted Area Delta

  • Modules: trex_core/adapters/persistence/postgresql.py(flat 매핑), trex_core/adapters/persistence/sql/013_drop_allocated_capital.sql(신규)
  • Tests: 컬럼 계약 가드(드리프트) + persistence round-trip 테스트 정리

Delivery Trace Delta

  • Batches: (예정) dcy-023 batch
  • Releases: none

Revalidation Impact

  • Reverification Needed: yes (dcy-023 batch 에서 수행 — 테스트 DSN round-trip)
  • Existing Implementation Invalidated: yes (컬럼·매핑 제거 — 기존 컬럼 계약 evidence 무효)
  • Status Recommendation: Approved (Implemented→Approved 되돌림)
  • Follow-up Action: dcy-023 batch 구현·검증 후 confirm-req-implemented. release 시 백업·롤백 절차 명시.

Validation Plan

  • dcy-023 batch: 테스트 DSN 에서 013 멱등 적용 + information_schema 대조 + round-trip + 전체 suite green.

CHG-20260610-IMPL

  • Date: 2026-06-10
  • Author: Justin Ko
  • Type: status
  • Summary: Approved → Implemented (confirm-req-implemented). 근거: BAT-034(release-candidate) verification — allocated_capital 전 경로 제거(도메인/intent/영속/snapshot/CLI), 마이그레이션 013 테스트 DSN 멱등 round-trip + 컬럼 부재 확인, 전체 428 passed + PG 게이트 21 passed + ruff clean, grep 전수 0건. Blocking Issues 없음.

CHG-20260612-01

  • Date: 2026-06-12
  • Author: Justin Ko

Change Summary

  • (change-req, issue #25) PostgreSQL list_slots 에 status_filter 를 받아 WHERE instance_key = %s AND status = ANY(%s) 로 DB 레벨 필터링한다. slots RPC 의 per-request full scan(전 행 fetch + Python 필터)을 제거. status_filter=None 은 기존 전체 fetch. 스키마/마이그레이션 변경 없음(쿼리 한정). 신규 AC-6 → Implemented → Approved 되돌림.

Intent

  • trex.slots.req 가 200-slot 인스턴스에서 매 요청마다 전 슬롯을 읽어오던 비용을 줄인다(issue #25 (1) DB 레벨 status 필터링). REQ-002 포트 확장에 대응하는 PostgreSQL 구현.

Acceptance Criteria Delta

  • Added:
    • AC-6: list_slots(instance_key, status_filter) DB-level status = ANY(%s) 필터 + None 전체. in-memory 와 결과 동일.
  • Updated/Removed: 없음

Impacted Area Delta

  • Docs: 없음
  • Modules: trex_core/adapters/persistence/postgresql.py(list_slots 쿼리)
  • Tests: PG list_slots status 필터 통합 테스트(PG 게이트), in-memory parity

Delivery Trace Delta

  • Batches: BAT-040 (예정, issue #25)
  • Releases: none

Revalidation Impact

  • Reverification Needed: yes (BAT-040 에서 AC-6 + 기존 AC 회귀)
  • Existing Implementation Invalidated: no (쿼리 확장, default None 기존 동작 보존). 신규 AC-6 미구현으로 Implemented 유지 불가 → Approved.
  • Status Recommendation: Implemented → Approved
  • Follow-up Action: confirm-req → BAT-040 구현·검증 → confirm-req-implemented

Validation Plan

  • BAT-040: PG list_slots status 필터 통합(PG 게이트, DSN 가용 시) + in-memory parity 단위 + 전체 suite + ruff clean. 스키마 드리프트 테스트 회귀(컬럼 불변).

CHG-20260612-IMPL

  • Date: 2026-06-12
  • Author: Justin Ko
  • Type: status
  • Summary: Approved → Implemented (confirm-req-implemented). 근거: BAT-040(release-candidate) verification — AC-6 PG list_slots status = ANY(%s) 게이트 테스트(test_list_slots_status_filter_pg, DSN 가용 시 실행; 현재 skip) + in-memory parity(REQ-002 AC-6)로 동작 계약 보증, 스키마 변경 없음(쿼리 한정), 전체 439 passed + ruff clean. Blocking Issues 없음.