docs(req): approve ledger metadata migration requirement

Confirm REQ-057 for BAT-025 while preserving REQ-056/BAT-024 implementation status. Operational DB execution remains separately approved.
This commit is contained in:
Hermes Agent
2026-07-15 10:50:25 +09:00
parent f5636c1ade
commit 7b9c23a377
3 changed files with 160 additions and 1 deletions
@@ -182,6 +182,39 @@
#### Validation Plan
- AC-1~19를 batch verification에서 API/repository/concurrency/regression evidence로 검증한다.
### CHG-20260715-03
- Date: 2026-07-15
- Author: TREX lead (Hermes)
#### Change Summary
- 운영 적용 방식 보완을 REQ-057로 분리 추적한다. REQ-056의 기존 API 계약, AC-1~19, `Implemented` status 및 BAT-024 `release-candidate` 상태는 변경하거나 되돌리지 않는다.
#### Intent
- REQ-056 구현에서 사용된 additive `portfolio_ledger` 컬럼의 운영 DB 적용을 runtime `ensure_schema()` 자동 DDL에만 의존하지 않도록 명시 Alembic migration과 운영 runbook 요구사항으로 후속 관리한다.
#### Acceptance Criteria Delta
- Added: 없음 (REQ-056 AC 변경 없음)
- Updated: 없음
- Removed: 없음
- Follow-on: REQ-057 AC-1~11이 migration, schema/Alembic revision 정합, 운영 preflight/runbook, forward-only recovery, release 결재 게이트를 별도로 정의한다.
#### Impacted Area Delta
- REQ-056 구현 영향 범위는 변경 없음.
- 후속 REQ-057 영향: `migrations/versions/`, runtime `ensure_schema()` 호환성, migration/runbook 및 persistence baseline 문서. 실제 변경은 BAT-025 standard에서 수행한다.
#### Delivery Trace Delta
- Batches: BAT-024는 REQ-056 구현/검증 release-candidate 상태로 유지. BAT-025 standard가 REQ-057 migration implementation/test/QC/runbook을 담당한다.
- Releases: 운영 DB upgrade, 서비스 재시작 및 신규 manual ledger API 활성화는 별도 명시 release 결재 전 실행하지 않는다.
#### Revalidation Impact
- Reverification Needed: no — REQ-056의 기존 implementation/QC evidence는 무효화하지 않는다.
- Existing Implementation Invalidated: no
- Status Recommendation: keep-Implemented
- Follow-up Action: REQ-057 Proposed 검토·승인 후 BAT-025에서 migration compatibility/data preservation/runbook evidence를 확보한다.
#### Validation Plan
- BAT-025에서 fresh DB와 runtime-precreated-schema 환경의 Alembic upgrade, 기존 row/source 보존, `alembic current` 정합, broker/manual ledger regression, runbook preflight 및 service smoke를 검증한다. 운영 DB 실행은 별도 release 결재 범위다.
## Implementation Confirmation
@@ -0,0 +1,124 @@
# REQ-057: portfolio_ledger 수동 장부 메타데이터 명시 Alembic 마이그레이션
- Status: Approved
- Type: Migration
- Priority: High
- Owner: Justin Ko
## Intent
- REQ-056 수동 장부 API가 사용하는 `portfolio_ledger`의 additive 메타데이터 컬럼을 runtime `ensure_schema()` 자동 DDL에만 의존하지 않고, 추적 가능한 명시적 Alembic revision으로 운영 적용 가능하게 한다.
- 운영 DB 스키마와 Alembic revision 상태를 일치시키고, migration 검증 전에는 해당 신규 API 코드를 활성화하지 않는 배포 선행조건을 정의한다.
## Requirement
- `portfolio_ledger`에 아래 네 컬럼을 적용하는 신규 Alembic revision을 작성한다.
| 컬럼 | SQL 타입 | NULL 정책 | 기본값/의미 |
| --- | --- | --- | --- |
| `source` | `TEXT` | `NOT NULL` | `DEFAULT 'broker'`; broker 기존 행과 broker write의 출처 |
| `target_ledger_entry_id` | `BIGINT` | `NULL` 허용 | `REVERSAL` target ledger entry 참조 |
| `confirmation_evidence` | `TEXT` | `NULL` 허용 | daemon-managed manual write의 명시적 확인 근거 |
| `actor_user_id` | `TEXT` | `NULL` 허용 | manual write를 수행한 사용자 추적 값 |
- revision의 `down_revision`은 구현 시점에 repository의 실제 Alembic head를 `alembic heads` 및 migration graph로 사전 확인하여 결정한다. 요구사항 문서에서 특정 revision ID를 하드코드 전제로 단정하지 않는다.
- upgrade는 기존 `portfolio_ledger` 행을 삭제·재작성하지 않고 보존해야 하며, 기존 행과 `source`가 비어 있는 선행 상태의 행은 `source='broker'`를 만족하도록 처리한 뒤 `source NOT NULL DEFAULT 'broker'`를 보장해야 한다.
- runtime `ensure_schema()` 자동 DDL로 위 컬럼이 이미 선행 생성된 DB에서도 migration이 안전하게 완료되어야 한다. 구현은 컬럼/제약 존재 여부, 기존 행의 `source` 값, Alembic version table을 확인해 중복 DDL 오류 없이 revision을 적용 또는 필요한 상태 정합 절차를 수행해야 한다.
- migration 완료 후 `alembic current`가 구현 시 확정한 revision/head와 일치해야 한다. 스키마만 존재하고 Alembic revision이 불일치한 상태는 완료로 간주하지 않는다.
- 이 migration의 검증 완료는 운영 배포에서 REQ-056 신규 manual ledger API 코드를 활성화하기 위한 선행조건이다. 서비스 재시작·신규 코드 활성화는 migration upgrade와 schema/current 검증이 성공한 뒤에만 허용한다.
- 운영 runbook을 작성한다. runbook은 최소한 백업, `alembic current`, 대상 테이블 schema/row count, 활성 쿼리·lock 확인, upgrade, schema/current 재검증, service smoke, 실패 대응을 포함해야 한다.
- rollback은 code rollback + additive schema 유지의 forward-only 정책으로 정의한다. 운영 환경에서 down migration 또는 컬럼 삭제를 자동 rollback 경로로 사용하지 않는다.
- 운영 DB 실행은 이 REQ/BAT 범위에 포함하지 않는다. 실제 upgrade·서비스 활성화는 증적 검토 후 별도 명시 release 결재가 있어야 한다.
- migration implementation, test, 독립 QC 및 batch verification은 표준 배치 `BAT-025`에서 수행한다. 이 REQ 초안에서는 BAT-025 batch artifact 또는 migration/code 파일을 생성하지 않는다.
## Acceptance Criteria
1. Given implementation preflight, When Alembic migration을 생성하기 전 `alembic heads`와 revision graph를 확인하면, Then 실제 단일/유효 head를 근거로 신규 revision의 `down_revision`을 결정하며 REQ 본문에 특정 기존 revision ID를 선결 조건으로 하드코드하지 않는다.
2. Given migration이 적용되지 않은 DB의 `portfolio_ledger`, When 신규 revision을 upgrade하면, Then `source TEXT NOT NULL DEFAULT 'broker'`, `target_ledger_entry_id BIGINT NULL`, `confirmation_evidence TEXT NULL`, `actor_user_id TEXT NULL` 네 컬럼이 모두 존재한다.
3. Given upgrade 전 기존 `portfolio_ledger` 행이 존재하면, When 신규 revision을 upgrade하면, Then 기존 행 수와 기존 business data가 보존되고 모든 기존 행의 `source`는 `'broker'`이다.
4. Given 기존 행 또는 runtime 선행 DDL 상태에서 `source`가 NULL 또는 미설정이면, When migration이 완료되면, Then NULL `source`가 남지 않고 `source`는 `'broker'`로 backfill되며 이후 컬럼은 `NOT NULL DEFAULT 'broker'` 제약을 만족한다.
5. Given runtime `ensure_schema()`가 네 컬럼을 이미 생성한 DB, When Alembic migration을 적용하면, Then 중복 컬럼/제약 오류 없이 안전하게 완료되고 schema와 Alembic version 상태가 revision/head와 일치한다.
6. Given migration upgrade가 완료되면, When `alembic current`와 information schema/row count 검증을 실행하면, Then current revision은 구현 시 확정한 head이고 네 컬럼의 타입·nullable/default 및 row count 보존 결과가 기대값과 일치한다.
7. Given migration 전 preflight, When 운영 runbook을 수행하면, Then DB backup 성공, `alembic current` 기록, `portfolio_ledger` schema/row count 기록, 대상 테이블 활성 쿼리·lock 부재 또는 승인된 maintenance window가 모두 확인되지 않으면 upgrade 전에 중단한다.
8. Given upgrade와 사후 schema/current 검증이 성공하면, When 서비스 smoke를 실행하면, Then DB-enabled health와 REQ-056 manual ledger API의 승인된 non-production/운영 smoke 시나리오가 성공한다. migration 검증 실패 시 신규 API 코드 활성화 또는 서비스 재시작을 진행하지 않는다.
9. Given migration 또는 service smoke 이후 코드 문제가 발생하면, When rollback 판단을 내리면, Then 직전 호환 코드로만 rollback하고 적용된 네 additive 컬럼과 Alembic revision은 유지하는 forward-only 복구 정책을 따른다. 운영 down migration/컬럼 삭제는 자동 조치가 아니다.
10. Given 운영 DB 적용을 요청할 때, When 별도 release 결재가 없으면, Then 실제 DB upgrade, 서비스 재시작, 신규 API 활성화를 실행하지 않는다.
11. Given `BAT-025` delivery, When implementation/test/QC를 완료하면, Then Alembic upgrade 및 runtime-precreated-schema 호환성, data preservation, runbook dry-run/검증, 기존 broker ledger 흐름 회귀를 evidence로 기록하고 독립 QC를 거친다.
## Impacted Area
- Docs:
- `docs/runbooks/` — BAT-025 운영 migration runbook 신규 작성 예정.
- `docs/data-model.md` — `portfolio_ledger` 컬럼과 revision 기록 갱신 예정.
- `docs/releases/` — 운영 적용 시 별도 release 결재와 실행 증적 기록 예정.
- Modules:
- `migrations/versions/` — 네 컬럼을 위한 신규 Alembic revision 예정.
- `app/repositories/postgres.py` 또는 `ensure_schema()` 소유 모듈 — runtime 자동 DDL과 Alembic migration의 idempotent 호환성 검증/보강 예정.
- migration bootstrap/CLI 경로 — `alembic current` 및 upgrade 사전·사후 검증 경로 확인 예정.
- Tests:
- fresh/upgraded DB schema, 기존 행 보존과 `source='broker'` backfill 검증.
- runtime-precreated-schema → Alembic upgrade → current/head 정합 integration 검증.
- 기존 broker ledger write 및 REQ-056 manual ledger smoke/regression 검증.
- runbook preflight/forward-only recovery 절차의 문서 검증.
## Notes
- Source: REQ-056 Implementation Confirmation 및 `docs/srs/index.md` 2026-07-14 release caveat. REQ-056은 이미 Implemented/BAT-024 release-candidate이므로 본 REQ는 REQ-056 AC 또는 status를 되돌리지 않고 운영 적용 방식만 별도 추적한다.
- Repository 기록에는 과거 Alembic head로 보이는 revision이 있으나, 새 migration의 parent는 구현 착수 시점의 실제 head로 재검증해야 한다.
- 기존 runtime `ensure_schema()` 자동 DDL은 선행 스키마 생성 가능성을 만들 수 있으므로, 그 DB에서도 Alembic revision 추적을 회복·일치시키는 것이 핵심이다. 임의 `stamp` 여부와 조건은 BAT-025 design/implementation에서 실제 schema와 migration graph 증거로 결정한다.
- 운영 DB 실행, 배포, 서비스 재시작, commit/push는 이번 요구사항 초안 범위에 포함하지 않는다.
## Change Log
### CHG-20260715-01
- Date: 2026-07-15
- Author: portfolio-hub-dev (Hermes)
#### Change Summary
- 신규 생성 (Proposed) — REQ-056 운영 release caveat에 대한 change requirement. `portfolio_ledger` manual ledger 메타데이터 네 컬럼을 명시 Alembic migration과 운영 runbook으로 관리하는 범위를 정의한다.
#### Intent
- runtime 자동 DDL만으로 생성될 수 있는 additive 컬럼을 Alembic revision 및 운영 증적으로 관리해, 스키마와 version history의 불일치를 방지한다.
#### Acceptance Criteria Delta
- Added:
- AC-1~11 최초 작성
- Updated: 없음
- Removed: 없음
#### Impacted Area Delta
- Docs: BAT-025 runbook, data model/persistence baseline, release evidence 갱신 예정.
- Modules: 신규 Alembic revision, runtime `ensure_schema()` 호환 경로, migration bootstrap/CLI 검증 경로.
- Tests: fresh DB, runtime-precreated schema, data preservation, broker/manual ledger regression, runbook preflight 검증.
#### Delivery Trace Delta
- Batches: BAT-025 standard 예정 — migration implementation/test/QC/runbook 작성.
- Releases: 운영 DB upgrade와 신규 API 활성화는 별도 release 결재 필요.
#### Revalidation Impact
- Reverification Needed: yes — migration 구현 후 AC-1~11 evidence 및 운영 실행 시 별도 실운영 evidence 필요.
- Existing Implementation Invalidated: no — REQ-056 Implemented status와 BAT-024 release-candidate 상태는 유지한다.
- Status Recommendation: keep-proposed
- Follow-up Action: confirm-req → BAT-025 standard batch drafting/planning/design → implementation/QC. 운영 실행은 별도 release approval 후에만 검토한다.
#### Validation Plan
- BAT-025에서 Alembic graph/head preflight, fresh/upgraded DB 및 runtime-precreated-schema integration 검증, data preservation/source backfill, `alembic current` 정합, broker/manual ledger smoke/regression을 실행한다. 운영 runbook은 backup·lock·schema/current·smoke·forward-only recovery 체크리스트로 검토하며, 실 운영 DB 실행은 별도 결재 전 수행하지 않는다.
### CHG-20260715-02
- Date: 2026-07-15
- Author: TREX lead (Hermes)
- confirm-req: `Proposed` → `Approved`.
#### Change Summary
- REQ-056의 이미 검증된 API 계약을 다시 열지 않고, `portfolio_ledger` 운영 스키마 적용을 독립 Migration REQ로 승인한다.
#### Approval Basis
- dcy-012의 `source` 분리·REVERSAL target·daemon-managed confirmation audit 결정과 REQ-056 Implementation Confirmation의 운영 release caveat를 추적했다.
- 실제 `uv run alembic heads` 결과는 단일 head `20260628_0027`이었다. 단, 병렬 revision 가능성을 포함한 구현 시점 graph 재확인을 AC-1의 필수 preflight로 유지한다.
- AC-1~11은 fresh/기존 데이터/runtime-precreated schema, schema-version 정합, rollback 경계, 운영 runbook을 검증 가능하게 정의한다.
#### Revalidation Impact
- Reverification Needed: yes — BAT-025에서 migration 및 runbook evidence를 확보해야 한다.
- Existing Implementation Invalidated: no — REQ-056 `Implemented` 및 BAT-024 `release-candidate`는 유지한다.
- Status Recommendation: proceed-to-batch.
- Follow-up Action: suggest-batch-reqs → BAT-025 standard drafting/planning/design/implementation/verification → independent QC. 운영 DB 실행은 별도 release 결재 후에만 가능하다.
+3 -1
View File
@@ -74,7 +74,7 @@
## Next Requirement ID
- Current: `REQ-057`
- Current: `REQ-058`
- Rule: `Requirement Register`에 있는 가장 큰 REQ 번호보다 정확히 1 커야 한다.
## Requirement Register
@@ -137,9 +137,11 @@
| REQ-054 | 인증정보 관리 보안 격리 — write-only·secret 미반환·로그 미노출 | Non-Functional | Implemented | High | Justin Ko | [req-054](./Non-Functional/req-054_credential-management-security-write-only.md) |
| REQ-055 | GET /v1/portfolios 응답에 전략·시장 메타데이터 노출 (additive) | Interface | Implemented | High | Justin Ko | [req-055](./Interface/req-055_v1-portfolios-strategy-market-meta-exposure.md) |
| REQ-056 | owner-scoped 수동 장부 입력 HTTP API | Interface | Implemented | High | Justin Ko | [req-056](./Interface/req-056_v1-portfolios-manual-ledger-api.md) |
| REQ-057 | portfolio_ledger 수동 장부 메타데이터 명시 Alembic 마이그레이션 | Migration | Approved | High | Justin Ko | [req-057](./Migration/req-057_portfolio-ledger-manual-metadata-alembic-migration.md) |
## Recent Change Log Summary
- 2026-07-15: REQ-057 `Proposed` → `Approved` (confirm-req) — REQ-056/BAT-024의 검증 완료 API 계약은 유지하고, `portfolio_ledger` 네 컬럼의 명시 Alembic migration을 독립 추적한다. 실제 `alembic heads` 단일 head `20260628_0027` 확인, 구현 시점 graph 재확인(AC-1) 유지. BAT-025 standard에서 fresh/기존/runtime-precreated schema 검증, data preservation, runbook, 독립 QC를 수행한다. 운영 DB upgrade·서비스 활성화는 별도 release 결재 전 실행하지 않는다.
- 2026-07-14: REQ-056 `Approved` → `Implemented` (confirm-req-implemented) — BAT-024 local implementation commit `b3447f6`, independent QC PASS (`deleg_f2337a39`). Manual ledger API endpoints added (`POST/GET /v1/portfolios/{portfolio_id}/ledger/manual`, `GET /v1/portfolios/{portfolio_id}/returns/summary`), strict owner-scope without admin bypass, service-token fail-closed, insufficient state 409, daemon-managed confirmation, `total_value_after`, `cumulative_profit_withdrawn`. Verification: full `594 passed`, focused remediation `4 passed`. Release caveat: production DB rollout should address additive `portfolio_ledger` columns with migration/runbook at release gate.
- 2026-07-14: REQ-056 `Proposed` → `Approved` (confirm-req) — dcy-012 confirmed Discovery 근거. 신규 `POST /v1/portfolios/{portfolio_id}/ledger/manual` + action enum(`INVEST`, `BUFFER_OUT`, `BUFFER_IN`, `BUY`, `SELL`, `WITHDRAW`, `PROFIT`, `REVERSAL`) owner-scoped user/session API 계약. 기존 `/ledger/trades`는 daemon/service-token broker write 전용으로 보존. 부족 cash/quantity/buffer 409, daemon-managed confirmation 409 `MANUAL_WRITE_REQUIRES_CONFIRMATION`, after-snapshot/history fields, `cumulative_profit_withdrawn` 및 `PROFIT` 순입금액 미포함 의미 포함. BAT-024 delivery 후보로 진행.
- 2026-07-04: REQ-055 신규 생성 `Implemented` (draft-req) — trex-tvr-v1 dcy-001 confirmed Discovery 근거. `GET /v1/portfolios` 응답에 `active_strategy_id`·`strategy_name`·`strategy_params`·`markets` additive 노출. DB 마이그레이션 불필요(기존 컬럼·테이블 활용), N+1 금지·파싱 에러 격리(500 금지) 포함. BAT-024 delivery 후보로 진행.